(function(){"use strict";function YI(n,t){for(var e=0;e<t.length;e++){const s=t[e];if(typeof s!="string"&&!Array.isArray(s)){for(const o in s)if(o!=="default"&&!(o in n)){const r=Object.getOwnPropertyDescriptor(s,o);r&&Object.defineProperty(n,o,r.get?r:{enumerable:!0,get:()=>s[o]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const QI=1e-7,JI=1e-4;class lf{constructor(t,e){this.backend=t,this.dataMover=e,this.data=new WeakMap,this.dataIdsCount=0}get(t){return this.data.has(t)||this.dataMover.moveData(this.backend,t),this.data.get(t)}set(t,e){this.dataIdsCount++,this.data.set(t,e)}has(t){return this.data.has(t)}delete(t){return this.dataIdsCount--,this.data.delete(t)}numDataIds(){return this.dataIdsCount}}class Zl{refCount(t){return Ze("refCount")}incRef(t){return Ze("incRef")}timerAvailable(){return!0}time(t){return Ze("time")}read(t){return Ze("read")}readSync(t){return Ze("readSync")}readToGPU(t,e){return Ze("readToGPU")}numDataIds(){return Ze("numDataIds")}disposeData(t,e){return Ze("disposeData")}write(t,e,s){return Ze("write")}move(t,e,s,o,r){return Ze("move")}createTensorFromGPUData(t,e,s){return Ze("createTensorFromGPUData")}memory(){return Ze("memory")}floatPrecision(){return Ze("floatPrecision")}epsilon(){return this.floatPrecision()===32?QI:JI}dispose(){return Ze("dispose")}}function Ze(n){throw new Error(`'${n}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function jI(n){let t=n.length,e=0;for(;t>0;)e=Math.random()*t|0,t--,Eo(n,t,e)}function Ks(n,t,e){return Math.max(n,Math.min(t,e))}function Bl(n){return n%2===0?n:n+1}function Eo(n,t,e){const s=n[t];n[t]=n[e],n[e]=s}function qI(n){let t=0;for(let e=0;e<n.length;e++)t+=n[e];return t}function v(n,t){if(!n)throw new Error(typeof t=="string"?t:t())}function Hl(n,t,e=""){v(Rt(n,t),()=>e+` Shapes ${n} and ${t} must match`)}function _l(n){v(n!=null,()=>"The input to the tensor constructor must be a non-null value.")}function Z(n){if(n.length===0)return 1;let t=n[0];for(let e=1;e<n.length;e++)t*=n[e];return t}function Rt(n,t){if(n===t)return!0;if(n==null||t==null||n.length!==t.length)return!1;for(let e=0;e<n.length;e++)if(n[e]!==t[e])return!1;return!0}function Do(n){return n%1===0}function Ul(n){const t=Math.ceil(Math.sqrt(n));return[t,Math.ceil(n/t)]}function Wo(n,t){return t<=n.length?n:n+" ".repeat(t-n.length)}function uf(n,t=o=>0,e,s){return new Promise((o,r)=>{let i=0;const a=()=>{if(n()){o();return}i++;const c=t(i);if(e!=null&&i>=e){r();return}s!=null?s(a,c):setTimeout(a,c)};a()})}function df(n,t){let e=1,s=-1;for(let r=0;r<n.length;++r)if(n[r]>=0)e*=n[r];else if(n[r]===-1){if(s!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${s} and dim ${r}`);s=r}else if(n[r]<0)throw Error(`Shapes can not be < 0. Found ${n[r]} at dim ${r}`);if(s===-1){if(t>0&&t!==e)throw Error(`Size(${t}) must match the product of shape ${n}`);return n}if(e===0)throw Error(`Cannot infer the missing size in [${n}] when there are 0 elements`);if(t%e!==0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${e}`);const o=n.slice();return o[s]=t/e,o}function It(n,t){const e=t.length;return n=n==null?t.map((s,o)=>o):[].concat(n),v(n.every(s=>s>=-e&&s<e),()=>`All values in axis param must be in range [-${e}, ${e}) but got axis ${n}`),v(n.every(s=>Do(s)),()=>`All values in axis param must be integers but got axis ${n}`),n.map(s=>s<0?e+s:s)}function fs(n,t){const e=[],s=[],o=t!=null&&Array.isArray(t)&&t.length===0,r=t==null||o?null:It(t,n).sort();let i=0;for(let a=0;a<n.length;++a){if(r!=null){if(r[i]===a&&n[a]!==1)throw new Error(`Can't squeeze axis ${a} since its dim '${n[a]}' is not 1`);(r[i]==null||r[i]>a)&&n[a]===1&&(e.push(n[a]),s.push(a)),r[i]<=a&&i++}n[a]!==1&&(e.push(n[a]),s.push(a))}return{newShape:e,keptDims:s}}function Se(n,t){return qt(n,t)}function qt(n,t){let e=null;if(n==null||n==="float32")e=new Float32Array(t);else if(n==="int32")e=new Int32Array(t);else if(n==="bool")e=new Uint8Array(t);else if(n==="string")e=new Array(t);else throw new Error(`Unknown data type ${n}`);return e}function tw(n,t){for(let e=0;e<n.length;e++){const s=n[e];if(isNaN(s)||!isFinite(s))throw Error(`A tensor of type ${t} being uploaded contains ${s}.`)}}function ew(n){return n==="bool"||n==="complex64"||n==="float32"||n==="int32"||n==="string"}function hf(n,t){return!(t==="complex64"||t==="float32"&&n!=="complex64"||t==="int32"&&n!=="float32"&&n!=="complex64"||t==="bool"&&n==="bool")}function xa(n){if(n==="float32"||n==="int32")return 4;if(n==="complex64")return 8;if(n==="bool")return 1;throw new Error(`Unknown dtype ${n}`)}function nw(n){if(n==null)return 0;let t=0;return n.forEach(e=>t+=e.length),t}function Cr(n){return typeof n=="string"||n instanceof String}function sw(n){return typeof n=="boolean"}function Yl(n){return typeof n=="number"}function Mo(n){return Array.isArray(n)?Mo(n[0]):n instanceof Float32Array?"float32":n instanceof Int32Array||n instanceof Uint8Array||n instanceof Uint8ClampedArray?"int32":Yl(n)?"float32":Cr(n)?"string":sw(n)?"bool":"float32"}function Ql(n){return!!(n&&n.constructor&&n.call&&n.apply)}function Jl(n,t){for(let e=t;e<n;++e)if(n%e===0)return e;return n}function ct(n){const t=n.length;if(t<2)return[];const e=new Array(t-1);e[t-2]=n[t-1];for(let s=t-3;s>=0;--s)e[s]=e[s+1]*n[s+1];return e}function pf(n,t,e,s=!1){const o=new Array;if(t.length===1){const r=t[0]*(s?2:1);for(let i=0;i<r;i++)o[i]=e[n+i]}else{const r=t[0],i=t.slice(1),a=i.reduce((c,l)=>c*l)*(s?2:1);for(let c=0;c<r;c++)o[c]=pf(n+c*a,i,e,s)}return o}function vn(n,t,e=!1){if(n.length===0)return t[0];const s=n.reduce((o,r)=>o*r)*(e?2:1);if(s===0)return[];if(s!==t.length)throw new Error(`[${n}] does not match the input size ${t.length}${e?" for a complex tensor":""}.`);return pf(0,n,t,e)}function ow(n,t){if(Array.isArray(n))return n;if(t==="float32")return n instanceof Float32Array?n:new Float32Array(n);if(t==="int32")return n instanceof Int32Array?n:new Int32Array(n);if(t==="bool"||t==="string")return Uint8Array.from(new Int32Array(n));throw new Error(`Unknown dtype ${t}`)}function jl(n,t){const e=ke(n,t);for(let s=0;s<e.length;s++)e[s]=1;return e}function ke(n,t){if(t==null||t==="float32"||t==="complex64")return new Float32Array(n);if(t==="int32")return new Int32Array(n);if(t==="bool")return new Uint8Array(n);throw new Error(`Unknown data type ${t}`)}function ff(n,t){const e=n.reduce((s,o)=>s*o,1);if(t==null||t==="float32")return vn(n,new Float32Array(e));if(t==="int32")return vn(n,new Int32Array(e));if(t==="bool")return vn(n,new Uint8Array(e));throw new Error(`Unknown data type ${t}`)}function es(n){n.forEach(t=>{v(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${n}].`)})}function Fn(n,t,e){if(t===0)return 0;if(t===1)return n[0];let s=n[n.length-1];for(let o=0;o<n.length-1;++o)s+=e[o]*n[o];return s}function Vo(n,t,e){if(t===0)return[];if(t===1)return[n];const s=new Array(t);for(let o=0;o<s.length-1;++o)s[o]=Math.floor(n/e[o]),n-=s[o]*e[o];return s[s.length-1]=n,s}function ql(n){return n&&n.then&&typeof n.then=="function"}/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const mf="tfjsflags";class rw{constructor(t){this.global=t,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=iw,this.populateURLFlags()}setPlatform(t,e){this.platform!=null&&(z().getBool("IS_TEST")||z().getBool("PROD")||console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${t}.`)),this.platformName=t,this.platform=e}registerFlag(t,e,s){if(this.flagRegistry[t]={evaluationFn:e,setHook:s},this.urlFlags[t]!=null){const o=this.urlFlags[t];z().getBool("IS_TEST")||z().getBool("PROD")||console.warn(`Setting feature override from URL ${t}: ${o}.`),this.set(t,o)}}async getAsync(t){return t in this.flags?this.flags[t]:(this.flags[t]=await this.evaluateFlag(t),this.flags[t])}get(t){if(t in this.flags)return this.flags[t];const e=this.evaluateFlag(t);if(ql(e))throw new Error(`Flag ${t} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[t]=e,this.flags[t]}getNumber(t){return this.get(t)}getBool(t){return this.get(t)}getString(t){return this.get(t)}getFlags(){return this.flags}get features(){return this.flags}set(t,e){if(this.flagRegistry[t]==null)throw new Error(`Cannot set flag ${t} as it has not been registered.`);this.flags[t]=e,this.flagRegistry[t].setHook!=null&&this.flagRegistry[t].setHook(e)}evaluateFlag(t){if(this.flagRegistry[t]==null)throw new Error(`Cannot evaluate flag '${t}': no evaluation function found.`);return this.flagRegistry[t].evaluationFn()}setFlags(t){this.flags=Object.assign({},t)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(typeof this.global>"u"||typeof this.global.location>"u"||typeof this.global.location.search>"u")return;const t=this.getQueryParams(this.global.location.search);mf in t&&t[mf].split(",").forEach(s=>{const[o,r]=s.split(":");this.urlFlags[o]=cw(o,r)})}}function iw(n){const t={};return n.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(e,...s)=>(aw(t,s[0],s[1]),s.join("="))),t}function aw(n,t,e){n[decodeURIComponent(t)]=decodeURIComponent(e||"")}function cw(n,t){const e=t.toLowerCase();return e==="true"||e==="false"?e==="true":`${+e}`===e?+e:t}function z(){return gf}let gf=null;function lw(n){gf=n}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */let tu;function bf(){if(tu==null){let n;if(typeof window<"u")n=window;else if(typeof global<"u")n=global;else if(typeof process<"u")n=process;else if(typeof self<"u")n=self;else throw new Error("Could not find a global object");tu=n}return tu}function uw(){const n=bf();return n._tfGlobals==null&&(n._tfGlobals=new Map),n._tfGlobals}function eu(n,t){const e=uw();if(e.has(n))return e.get(n);{const s=t();return e.set(n,s),e.get(n)}}const ya="Abs",vr="Acos",Sr="Acosh",Fo="Add",nu="AddN",su="All",ou="Any",Ia="ArgMax",wa="ArgMin",kr="Asin",Tr="Asinh",Nr="Atan",Rr="Atanh",$r="Atan2",Ca="AvgPool",ru="AvgPoolGrad",va="AvgPool3D",iu="AvgPool3DGrad",Sa="BatchMatMul",ka="BatchToSpaceND",au="Bincount",cu="BitwiseAnd",dw="BroadcastTo",xf="BroadcastArgs",Gr="Cast",Lr="Ceil",Er="ClipByValue",lu="Complex",Ta="ComplexAbs",Na="Concat",Ra="Conv2D",uu="Conv2DBackpropFilter",$a="Conv2DBackpropInput",Ga="Conv3D",du="Conv3DBackpropFilterV2",hu="Conv3DBackpropInputV2",Dr="Cos",Wr="Cosh",pu="Cumprod",La="Cumsum",fu="CropAndResize",mu="DenseBincount",gu="DepthToSpace",Ea="DepthwiseConv2dNative",bu="DepthwiseConv2dNativeBackpropFilter",xu="DepthwiseConv2dNativeBackpropInput",yf="Diag",Da="Dilation2D",yu="Dilation2DBackpropInput",Iu="Dilation2DBackpropFilter",hw="Draw",Mr="RealDiv",wu="Einsum",Vr="Elu",Cu="EluGrad",Fr="Erf",Wa="Equal",zr="Exp",Ma="ExpandDims",Xr="Expm1",vu="FFT",Su="Fill",ku="FlipLeftRight",Ar="Floor",Pr="FloorDiv",Va="FusedBatchNorm",Fa="GatherV2",If="GatherNd",za="Greater",Or="GreaterEqual",Kr="Identity",Tu="IFFT",Nu="Imag",Zr="IsFinite",Br="IsInf",Hr="IsNan",Xa="LeakyRelu",Aa="Less",Pa="LessEqual",wf="LinSpace",_r="Log",Ur="Log1p",Oa="LogicalAnd",Ka="LogicalNot",Za="LogicalOr",pw="LogSoftmax",Ba="LRN",Ru="LRNGrad",Ha="Max",Yr="Maximum",_a="MaxPool",$u="MaxPoolGrad",Ua="MaxPool3D",Gu="MaxPool3DGrad",Cf="MaxPoolWithArgmax",Ya="Mean",Qa="Min",Qr="Minimum",Ja="MirrorPad",Jr="Mod",vf="Multinomial",jr="Multiply",ja="Neg",qa="NotEqual",Lu="NonMaxSuppressionV3",Eu="NonMaxSuppressionV4",Du="NonMaxSuppressionV5",tc="OnesLike",ec="OneHot",nc="Pack",sc="PadV2",qr="Pow",oc="Prelu",rc="Prod",Sf="RaggedGather",kf="RaggedRange",Tf="RaggedTensorToTensor",Wu="Range",Mu="Real",ti="Reciprocal",ei="Relu",ic="Reshape",ac="ResizeNearestNeighbor",Vu="ResizeNearestNeighborGrad",cc="ResizeBilinear",Fu="ResizeBilinearGrad",ni="Relu6",lc="Reverse",si="Round",oi="Rsqrt",Nf="ScatterNd",Rf="TensorScatterUpdate",$f="SearchSorted",uc="Select",ri="Selu",dc="Slice",ii="Sin",ai="Sinh",ci="Sign",li="Sigmoid",ui="Softplus",di="Sqrt",hc="Sum",pc="SpaceToBatchND",fc="SplitV",mc="Softmax",Gf="SparseFillEmptyRows",Lf="SparseReshape",Ef="SparseSegmentMean",Df="SparseSegmentSum",Wf="SparseToDense",hi="SquaredDifference",zu="Square",Xu="StaticRegexReplace",Au="StridedSlice",Mf="StringNGrams",Vf="StringSplit",Ff="StringToHashBucketFast",pi="Sub",fi="Tan",mi="Tanh",gi="Tile",Pu="TopK",Ou="Transform",zo="Transpose",Ku="Unique",gc="Unpack",bc="UnsortedSegmentSum",xc="ZerosLike",bi="Step",Zu="FromPixels",Bu="RotateWithOffset",yc="_FusedMatMul",Ic="FusedConv2D",zf="FusedDepthwiseConv2D";/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function je(...n){z().getBool("IS_TEST")||z().getBool("PROD")||console.warn(...n)}function fw(...n){z().getBool("IS_TEST")||z().getBool("PROD")||console.log(...n)}/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const wc=eu("kernelRegistry",()=>new Map),Hu=eu("gradRegistry",()=>new Map);function _u(n,t){const e=Pf(n,t);return wc.get(e)}function Xf(n){return Hu.get(n)}function Af(n){const t=wc.entries(),e=[];for(;;){const{done:s,value:o}=t.next();if(s)break;const[r,i]=o,[a]=r.split("_");a===n&&e.push(i)}return e}function qe(n){const{kernelName:t,backendName:e}=n,s=Pf(t,e);wc.has(s)&&je(`The kernel '${t}' for backend '${e}' is already registered`),wc.set(s,n)}function mw(n){const{kernelName:t}=n;Hu.has(t)&&z().getBool("DEBUG")&&je(`Overriding the gradient for '${t}'`),Hu.set(t,n)}function Pf(n,t){return`${t}_${n}`}/**
 * @license
 * Copyright 2023 Google LLC.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Of(n){return n instanceof Float32Array||n instanceof Int32Array||n instanceof Uint8Array||n instanceof Uint8ClampedArray}var Zs=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function gw(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function bw(n){if(n.__esModule)return n;var t=n.default;if(typeof t=="function"){var e=function s(){return this instanceof s?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};e.prototype=t.prototype}else e={};return Object.defineProperty(e,"__esModule",{value:!0}),Object.keys(n).forEach(function(s){var o=Object.getOwnPropertyDescriptor(n,s);Object.defineProperty(e,s,o.get?o:{enumerable:!0,get:function(){return n[s]}})}),e}var Kf=Kt,ln=null;try{ln=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{}function Kt(n,t,e){this.low=n|0,this.high=t|0,this.unsigned=!!e}Kt.prototype.__isLong__,Object.defineProperty(Kt.prototype,"__isLong__",{value:!0});function Be(n){return(n&&n.__isLong__)===!0}Kt.isLong=Be;var Zf={},Bf={};function Bs(n,t){var e,s,o;return t?(n>>>=0,(o=0<=n&&n<256)&&(s=Bf[n],s)?s:(e=Zt(n,(n|0)<0?-1:0,!0),o&&(Bf[n]=e),e)):(n|=0,(o=-128<=n&&n<128)&&(s=Zf[n],s)?s:(e=Zt(n,n<0?-1:0,!1),o&&(Zf[n]=e),e))}Kt.fromInt=Bs;function un(n,t){if(isNaN(n))return t?Hs:dn;if(t){if(n<0)return Hs;if(n>=_f)return jf}else{if(n<=-Uf)return He;if(n+1>=Uf)return Jf}return n<0?un(-n,t).neg():Zt(n%Xo|0,n/Xo|0,t)}Kt.fromNumber=un;function Zt(n,t,e){return new Kt(n,t,e)}Kt.fromBits=Zt;var Cc=Math.pow;function Uu(n,t,e){if(n.length===0)throw Error("empty string");if(n==="NaN"||n==="Infinity"||n==="+Infinity"||n==="-Infinity")return dn;if(typeof t=="number"?(e=t,t=!1):t=!!t,e=e||10,e<2||36<e)throw RangeError("radix");var s;if((s=n.indexOf("-"))>0)throw Error("interior hyphen");if(s===0)return Uu(n.substring(1),t,e).neg();for(var o=un(Cc(e,8)),r=dn,i=0;i<n.length;i+=8){var a=Math.min(8,n.length-i),c=parseInt(n.substring(i,i+a),e);if(a<8){var l=un(Cc(e,a));r=r.mul(l).add(un(c))}else r=r.mul(o),r=r.add(un(c))}return r.unsigned=t,r}Kt.fromString=Uu;function Sn(n,t){return typeof n=="number"?un(n,t):typeof n=="string"?Uu(n,t):Zt(n.low,n.high,typeof t=="boolean"?t:n.unsigned)}Kt.fromValue=Sn;var Hf=65536,xw=1<<24,Xo=Hf*Hf,_f=Xo*Xo,Uf=_f/2,Yf=Bs(xw),dn=Bs(0);Kt.ZERO=dn;var Hs=Bs(0,!0);Kt.UZERO=Hs;var Ao=Bs(1);Kt.ONE=Ao;var Qf=Bs(1,!0);Kt.UONE=Qf;var Yu=Bs(-1);Kt.NEG_ONE=Yu;var Jf=Zt(-1,2147483647,!1);Kt.MAX_VALUE=Jf;var jf=Zt(-1,-1,!0);Kt.MAX_UNSIGNED_VALUE=jf;var He=Zt(0,-2147483648,!1);Kt.MIN_VALUE=He;var et=Kt.prototype;et.toInt=function(){return this.unsigned?this.low>>>0:this.low},et.toNumber=function(){return this.unsigned?(this.high>>>0)*Xo+(this.low>>>0):this.high*Xo+(this.low>>>0)},et.toString=function(t){if(t=t||10,t<2||36<t)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(He)){var e=un(t),s=this.div(e),o=s.mul(e).sub(this);return s.toString(t)+o.toInt().toString(t)}else return"-"+this.neg().toString(t);for(var r=un(Cc(t,6),this.unsigned),i=this,a="";;){var c=i.div(r),l=i.sub(c.mul(r)).toInt()>>>0,u=l.toString(t);if(i=c,i.isZero())return u+a;for(;u.length<6;)u="0"+u;a=""+u+a}},et.getHighBits=function(){return this.high},et.getHighBitsUnsigned=function(){return this.high>>>0},et.getLowBits=function(){return this.low},et.getLowBitsUnsigned=function(){return this.low>>>0},et.getNumBitsAbs=function(){if(this.isNegative())return this.eq(He)?64:this.neg().getNumBitsAbs();for(var t=this.high!=0?this.high:this.low,e=31;e>0&&!(t&1<<e);e--);return this.high!=0?e+33:e+1},et.isZero=function(){return this.high===0&&this.low===0},et.eqz=et.isZero,et.isNegative=function(){return!this.unsigned&&this.high<0},et.isPositive=function(){return this.unsigned||this.high>=0},et.isOdd=function(){return(this.low&1)===1},et.isEven=function(){return(this.low&1)===0},et.equals=function(t){return Be(t)||(t=Sn(t)),this.unsigned!==t.unsigned&&this.high>>>31===1&&t.high>>>31===1?!1:this.high===t.high&&this.low===t.low},et.eq=et.equals,et.notEquals=function(t){return!this.eq(t)},et.neq=et.notEquals,et.ne=et.notEquals,et.lessThan=function(t){return this.comp(t)<0},et.lt=et.lessThan,et.lessThanOrEqual=function(t){return this.comp(t)<=0},et.lte=et.lessThanOrEqual,et.le=et.lessThanOrEqual,et.greaterThan=function(t){return this.comp(t)>0},et.gt=et.greaterThan,et.greaterThanOrEqual=function(t){return this.comp(t)>=0},et.gte=et.greaterThanOrEqual,et.ge=et.greaterThanOrEqual,et.compare=function(t){if(Be(t)||(t=Sn(t)),this.eq(t))return 0;var e=this.isNegative(),s=t.isNegative();return e&&!s?-1:!e&&s?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1},et.comp=et.compare,et.negate=function(){return!this.unsigned&&this.eq(He)?He:this.not().add(Ao)},et.neg=et.negate,et.add=function(t){Be(t)||(t=Sn(t));var e=this.high>>>16,s=this.high&65535,o=this.low>>>16,r=this.low&65535,i=t.high>>>16,a=t.high&65535,c=t.low>>>16,l=t.low&65535,u=0,d=0,h=0,p=0;return p+=r+l,h+=p>>>16,p&=65535,h+=o+c,d+=h>>>16,h&=65535,d+=s+a,u+=d>>>16,d&=65535,u+=e+i,u&=65535,Zt(h<<16|p,u<<16|d,this.unsigned)},et.subtract=function(t){return Be(t)||(t=Sn(t)),this.add(t.neg())},et.sub=et.subtract,et.multiply=function(t){if(this.isZero())return dn;if(Be(t)||(t=Sn(t)),ln){var e=ln.mul(this.low,this.high,t.low,t.high);return Zt(e,ln.get_high(),this.unsigned)}if(t.isZero())return dn;if(this.eq(He))return t.isOdd()?He:dn;if(t.eq(He))return this.isOdd()?He:dn;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(Yf)&&t.lt(Yf))return un(this.toNumber()*t.toNumber(),this.unsigned);var s=this.high>>>16,o=this.high&65535,r=this.low>>>16,i=this.low&65535,a=t.high>>>16,c=t.high&65535,l=t.low>>>16,u=t.low&65535,d=0,h=0,p=0,f=0;return f+=i*u,p+=f>>>16,f&=65535,p+=r*u,h+=p>>>16,p&=65535,p+=i*l,h+=p>>>16,p&=65535,h+=o*u,d+=h>>>16,h&=65535,h+=r*l,d+=h>>>16,h&=65535,h+=i*c,d+=h>>>16,h&=65535,d+=s*u+o*l+r*c+i*a,d&=65535,Zt(p<<16|f,d<<16|h,this.unsigned)},et.mul=et.multiply,et.divide=function(t){if(Be(t)||(t=Sn(t)),t.isZero())throw Error("division by zero");if(ln){if(!this.unsigned&&this.high===-2147483648&&t.low===-1&&t.high===-1)return this;var e=(this.unsigned?ln.div_u:ln.div_s)(this.low,this.high,t.low,t.high);return Zt(e,ln.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Hs:dn;var s,o,r;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return Hs;if(t.gt(this.shru(1)))return Qf;r=Hs}else{if(this.eq(He)){if(t.eq(Ao)||t.eq(Yu))return He;if(t.eq(He))return Ao;var i=this.shr(1);return s=i.div(t).shl(1),s.eq(dn)?t.isNegative()?Ao:Yu:(o=this.sub(t.mul(s)),r=s.add(o.div(t)),r)}else if(t.eq(He))return this.unsigned?Hs:dn;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();r=dn}for(o=this;o.gte(t);){s=Math.max(1,Math.floor(o.toNumber()/t.toNumber()));for(var a=Math.ceil(Math.log(s)/Math.LN2),c=a<=48?1:Cc(2,a-48),l=un(s),u=l.mul(t);u.isNegative()||u.gt(o);)s-=c,l=un(s,this.unsigned),u=l.mul(t);l.isZero()&&(l=Ao),r=r.add(l),o=o.sub(u)}return r},et.div=et.divide,et.modulo=function(t){if(Be(t)||(t=Sn(t)),ln){var e=(this.unsigned?ln.rem_u:ln.rem_s)(this.low,this.high,t.low,t.high);return Zt(e,ln.get_high(),this.unsigned)}return this.sub(this.div(t).mul(t))},et.mod=et.modulo,et.rem=et.modulo,et.not=function(){return Zt(~this.low,~this.high,this.unsigned)},et.and=function(t){return Be(t)||(t=Sn(t)),Zt(this.low&t.low,this.high&t.high,this.unsigned)},et.or=function(t){return Be(t)||(t=Sn(t)),Zt(this.low|t.low,this.high|t.high,this.unsigned)},et.xor=function(t){return Be(t)||(t=Sn(t)),Zt(this.low^t.low,this.high^t.high,this.unsigned)},et.shiftLeft=function(t){return Be(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?Zt(this.low<<t,this.high<<t|this.low>>>32-t,this.unsigned):Zt(0,this.low<<t-32,this.unsigned)},et.shl=et.shiftLeft,et.shiftRight=function(t){return Be(t)&&(t=t.toInt()),(t&=63)===0?this:t<32?Zt(this.low>>>t|this.high<<32-t,this.high>>t,this.unsigned):Zt(this.high>>t-32,this.high>=0?0:-1,this.unsigned)},et.shr=et.shiftRight,et.shiftRightUnsigned=function(t){if(Be(t)&&(t=t.toInt()),t&=63,t===0)return this;var e=this.high;if(t<32){var s=this.low;return Zt(s>>>t|e<<32-t,e>>>t,this.unsigned)}else return t===32?Zt(e,0,this.unsigned):Zt(e>>>t-32,0,this.unsigned)},et.shru=et.shiftRightUnsigned,et.shr_u=et.shiftRightUnsigned,et.toSigned=function(){return this.unsigned?Zt(this.low,this.high,!1):this},et.toUnsigned=function(){return this.unsigned?this:Zt(this.low,this.high,!0)},et.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()},et.toBytesLE=function(){var t=this.high,e=this.low;return[e&255,e>>>8&255,e>>>16&255,e>>>24,t&255,t>>>8&255,t>>>16&255,t>>>24]},et.toBytesBE=function(){var t=this.high,e=this.low;return[t>>>24,t>>>16&255,t>>>8&255,t&255,e>>>24,e>>>16&255,e>>>8&255,e&255]},Kt.fromBytes=function(t,e,s){return s?Kt.fromBytesLE(t,e):Kt.fromBytesBE(t,e)},Kt.fromBytesLE=function(t,e){return new Kt(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)},Kt.fromBytesBE=function(t,e){return new Kt(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)};const qf=gw(Kf),yw=YI({__proto__:null,default:qf},[Kf]);/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const _s=qf||yw;function vc(n){return _s.fromString(n,!0,16)}const tm=vc("c3a5c85c97cb3127"),Us=vc("b492b66fbe98f273"),Re=vc("9ae16a3b2f90404f");function Qu(n){return n.xor(n.shru(47))}function em(n,t,e){const s=n.slice(t,t+e);return _s.fromBytes(Array.from(s),!0,!0)}function Ft(n,t){return em(n,t,8)}function nm(n,t){return em(n,t,4)}function fe(n,t){return t===0?n:n.shru(t).or(n.shl(64-t))}function ms(n,t,e=vc("9ddfea08eb382d69")){let s=n.xor(t).mul(e);s=s.xor(s.shru(47));let o=t.xor(s).mul(e);return o=o.xor(o.shru(47)),o=o.mul(e),o}function Iw(n,t,e,s,o,r){o=o.add(n),r=fe(r.add(o).add(s),21);const i=o;return o=o.add(t),o=o.add(e),r=r.add(fe(o,44)),[o.add(s),r.add(i)]}function Sc(n,t,e,s){return Iw(Ft(n,t),Ft(n,t+8),Ft(n,t+16),Ft(n,t+24),e,s)}function ww(n,t=n.length){if(t>=8){const e=Re.add(t*2),s=Ft(n,0).add(Re),o=Ft(n,t-8),r=fe(o,37).mul(e).add(s),i=fe(s,25).add(o).mul(e);return ms(r,i,e)}if(t>=4){const e=Re.add(t*2),s=nm(n,0);return ms(s.shl(3).add(t),nm(n,t-4),e)}if(t>0){const e=n[0],s=n[t>>1],o=n[t-1],r=e+(s<<8),i=t+(o<<2);return Qu(Re.mul(r).xor(tm.mul(i))).mul(Re)}return Re}function Cw(n,t=n.length){const e=Re.add(t*2),s=Ft(n,0).mul(Us),o=Ft(n,8),r=Ft(n,t-8).mul(e),i=Ft(n,t-16).mul(Re);return ms(fe(s.add(o),43).add(fe(r,30)).add(i),s.add(fe(o.add(Re),18)).add(r),e)}function vw(n,t=n.length){const e=Re.add(t*2),s=Ft(n,0).mul(Re),o=Ft(n,8),r=Ft(n,t-8).mul(e),i=Ft(n,t-16).mul(Re),a=fe(s.add(o),43).add(fe(r,30)).add(i),c=ms(a,s.add(fe(o.add(Re),18)).add(r),e),l=Ft(n,16).mul(e),u=Ft(n,24),d=a.add(Ft(n,t-32)).mul(e),h=c.add(Ft(n,t-24)).mul(e);return ms(fe(l.add(u),43).add(fe(d,30)).add(h),l.add(fe(u.add(s),18)).add(d),e)}function Sw(n,t=n.length){const e=_s.fromNumber(81,!0);if(t<=32)return t<=16?ww(n,t):Cw(n,t);if(t<=64)return vw(n,t);let s=e,o=e.mul(Us).add(113),r=Qu(o.mul(Re).add(113)).mul(Re),i=[_s.UZERO,_s.UZERO],a=[_s.UZERO,_s.UZERO];s=s.mul(Re).add(Ft(n,0));let c=0;const l=(t-1>>6)*64,u=l+(t-1&63)-63;do s=fe(s.add(o).add(i[0]).add(Ft(n,c+8)),37).mul(Us),o=fe(o.add(i[1]).add(Ft(n,c+48)),42).mul(Us),s=s.xor(a[1]),o=o.add(i[0]).add(Ft(n,c+40)),r=fe(r.add(a[0]),33).mul(Us),i=Sc(n,c,i[1].mul(Us),s.add(a[0])),a=Sc(n,c+32,r.add(a[1]),o.add(Ft(n,c+16))),[r,s]=[s,r],c+=64;while(c!==l);const d=Us.add(r.and(255).shl(1));return c=u,a[0]=a[0].add(t-1&63),i[0]=i[0].add(a[0]),a[0]=a[0].add(i[0]),s=fe(s.add(o).add(i[0]).add(Ft(n,c+8)),37).mul(d),o=fe(o.add(i[1]).add(Ft(n,c+48)),42).mul(d),s=s.xor(a[1].mul(9)),o=o.add(i[0].mul(9).add(Ft(n,c+40))),r=fe(r.add(a[0]),33).mul(d),i=Sc(n,c,i[1].mul(d),s.add(a[0])),a=Sc(n,c+32,r.add(a[1]),o.add(Ft(n,c+16))),[r,s]=[s,r],ms(ms(i[0],a[0],d).add(Qu(o).mul(tm)).add(r),ms(i[1],a[1],d).add(s),d)}/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function gs(n,t){return t==="string"?bs(n):Ys([n],t)}function kw(n,t){return n instanceof Float32Array&&t==="float32"||n instanceof Int32Array&&t==="int32"||n instanceof Uint8Array&&t==="bool"}function Ys(n,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(n)&&(n=Qs(n)),z().getBool("DEBUG")&&tw(n,t),kw(n,t))return n;if(t==null||t==="float32"||t==="complex64")return new Float32Array(n);if(t==="int32")return new Int32Array(n);if(t==="bool"){const e=new Uint8Array(n.length);for(let s=0;s<e.length;++s)Math.round(n[s])!==0&&(e[s]=1);return e}else throw new Error(`Unknown data type ${t}`)}function Ve(){return z().platform.now()}function bs(n,t="utf-8"){return t=t||"utf-8",z().platform.encode(n,t)}function xs(n,t="utf-8"){return t=t||"utf-8",z().platform.decode(n,t)}function hn(n){return z().platform.isTypedArray!=null?z().platform.isTypedArray(n):Of(n)}function Qs(n,t=[],e=!1){if(t==null&&(t=[]),typeof n=="boolean"||typeof n=="number"||typeof n=="string"||ql(n)||n==null||hn(n)&&e)t.push(n);else if(Array.isArray(n)||hn(n))for(let s=0;s<n.length;++s)Qs(n[s],t,e);else{let s=-1;for(const o of Object.keys(n))/^([1-9]+[0-9]*|0)$/.test(o)&&(s=Math.max(s,Number(o)));for(let o=0;o<=s;o++)Qs(n[o],t,e)}return t}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class Tw{constructor(t,e){this.backendTimer=t,this.logger=e,e==null&&(this.logger=new Rw)}profileKernel(t,e,s){let o;const r=()=>{o=s()};let i;const a=Ve();if(this.backendTimer.timerAvailable())i=this.backendTimer.time(r);else{r();for(const l of o)l.dataSync();i=Promise.resolve({kernelMs:Ve()-a})}if(z().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let l=0;l<o.length;l++){const u=o[l];u.data().then(d=>{Nw(d,u.dtype,t)})}return{kernelName:t,outputs:o,inputs:e,timeMs:i.then(l=>l.kernelMs),extraInfo:i.then(l=>l.getExtraProfileInfo!=null?l.getExtraProfileInfo():"")}}logKernelProfile(t){const{kernelName:e,outputs:s,timeMs:o,inputs:r,extraInfo:i}=t;s.forEach(a=>{Promise.all([a.data(),o,i]).then(c=>{this.logger.logKernelProfile(e,a,c[0],c[1],r,c[2])})})}}function Nw(n,t,e){if(t!=="float32")return!1;for(let s=0;s<n.length;s++){const o=n[s];if(isNaN(o)||!isFinite(o))return console.warn(`Found ${o} in the result of '${e}'`),!0}return!1}class Rw{logKernelProfile(t,e,s,o,r,i){const a=typeof o=="number"?Wo(`${o}ms`,9):o.error,c=Wo(t,25),l=e.rank,u=e.size,d=Wo(e.shape.toString(),14);let h="";for(const p in r){const f=r[p];if(f!=null){const m=f.shape||e.shape,g=m.length;h+=`${p}: ${g}D ${g>0?m:""} `}}console.log(`%c${c}	%c${a}	%c${l}D ${d}	%c${u}	%c${h}	%c${i}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function $w(n,t,e){const s={},o={};for(let c=0;c<t.length;c++)s[t[c].id]=!0;for(let c=0;c<n.length;c++){const l=n[c],u=l.inputs;for(const d in u){const h=u[d];let p=!1;for(let f=0;f<t.length;f++)if(s[h.id]){l.outputs.forEach(m=>s[m.id]=!0),p=!0,o[l.id]=!0;break}if(p)break}}const r={};r[e.id]=!0;const i={};for(let c=n.length-1;c>=0;c--){const l=n[c],u=l.inputs;for(let d=0;d<l.outputs.length;d++)if(r[l.outputs[d].id]){for(const h in u)r[u[h].id]=!0,i[l.id]=!0;break}}const a=[];for(let c=0;c<n.length;c++){const l=n[c];if(o[l.id]&&i[l.id]){const u={};for(const h in l.inputs){const p=l.inputs[h];s[p.id]&&(u[h]=p)}const d=Object.assign({},l);d.inputs=u,d.outputs=l.outputs,a.push(d)}}return a}function Gw(n,t,e,s){for(let o=t.length-1;o>=0;o--){const r=t[o],i=[];if(r.outputs.forEach(c=>{const l=n[c.id];l!=null?i.push(l):i.push(null)}),r.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${r.kernelName}.`);const a=r.gradient(i);for(const c in r.inputs){if(!(c in a))throw new Error(`Cannot backprop through input ${c}. Available gradients found: ${Object.keys(a)}.`);const l=e(()=>a[c]());if(l.dtype!=="float32")throw new Error(`Error in gradient for op ${r.kernelName}. The gradient of input ${c} must have 'float32' dtype, but has '${l.dtype}'`);const u=r.inputs[c];if(!Rt(l.shape,u.shape))throw new Error(`Error in gradient for op ${r.kernelName}. The gradient of input '${c}' has shape '${l.shape}', which does not match the shape of the input '${u.shape}'`);if(n[u.id]==null)n[u.id]=l;else{const d=n[u.id];n[u.id]=s(d,l),d.dispose()}}}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const sm=20,xi=3,Ju=7;function Lw(n,t,e,s){const o=ct(t),r=Ew(n,t,e,o),i=t.length,a=kc(n,t,e,o,r),c=["Tensor"];return s&&(c.push(`  dtype: ${e}`),c.push(`  rank: ${i}`),c.push(`  shape: [${t}]`),c.push("  values:")),c.push(a.map(l=>"    "+l).join(`
`)),c.join(`
`)}function Ew(n,t,e,s){const o=Z(t),r=s[s.length-1],i=new Array(r).fill(0),a=t.length,c=e==="complex64"?Ii(n):n;if(a>1)for(let l=0;l<o/r;l++){const u=l*r;for(let d=0;d<r;d++)i[d]=Math.max(i[d],yi(c[u+d],0,e).length)}return i}function yi(n,t,e){let s;return Array.isArray(n)?s=`${parseFloat(n[0].toFixed(Ju))} + ${parseFloat(n[1].toFixed(Ju))}j`:Cr(n)?s=`'${n}'`:e==="bool"?s=om(n):s=parseFloat(n.toFixed(Ju)).toString(),Wo(s,t)}function om(n){return n===0?"false":"true"}function kc(n,t,e,s,o,r=!0){const i=e==="complex64"?2:1,a=t[0],c=t.length;if(c===0){if(e==="complex64"){const m=Ii(n);return[yi(m[0],0,e)]}return e==="bool"?[om(n[0])]:[n[0].toString()]}if(c===1){if(a>sm){const g=xi*i;let b=Array.from(n.slice(0,g)),x=Array.from(n.slice((a-xi)*i,a*i));return e==="complex64"&&(b=Ii(b),x=Ii(x)),["["+b.map((I,y)=>yi(I,o[y],e)).join(", ")+", ..., "+x.map((I,y)=>yi(I,o[a-xi+y],e)).join(", ")+"]"]}return["["+(e==="complex64"?Ii(n):Array.from(n)).map((g,b)=>yi(g,o[b],e)).join(", ")+"]"]}const l=t.slice(1),u=s.slice(1),d=s[0]*i,h=[];if(a>sm){for(let m=0;m<xi;m++){const g=m*d,b=g+d;h.push(...kc(n.slice(g,b),l,e,u,o,!1))}h.push("...");for(let m=a-xi;m<a;m++){const g=m*d,b=g+d;h.push(...kc(n.slice(g,b),l,e,u,o,m===a-1))}}else for(let m=0;m<a;m++){const g=m*d,b=g+d;h.push(...kc(n.slice(g,b),l,e,u,o,m===a-1))}const p=c===2?",":"";h[0]="["+(a>0?h[0]+p:"");for(let m=1;m<h.length-1;m++)h[m]=" "+h[m]+p;let f=`,
`;for(let m=2;m<c;m++)f+=`
`;return h[h.length-1]=" "+h[h.length-1]+"]"+(r?"":f),h}function Ii(n){const t=[];for(let e=0;e<n.length;e+=2)t.push([n[e],n[e+1]]);return t}/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class xe{constructor(t,e,s){if(this.dtype=e,this.shape=t.slice(),this.size=Z(t),s!=null){const o=s.length;v(o===this.size,()=>`Length of values '${o}' does not match the size inferred by the shape '${this.size}'.`)}if(e==="complex64")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=s||qt(e,this.size),this.strides=ct(t)}set(t,...e){e.length===0&&(e=[0]),v(e.length===this.rank,()=>`The number of provided coordinates (${e.length}) must match the rank (${this.rank})`);const s=this.locToIndex(e);this.values[s]=t}get(...t){t.length===0&&(t=[0]);let e=0;for(const o of t){if(o<0||o>=this.shape[e]){const r=`Requested out of range element at ${t}.   Buffer shape=${this.shape}`;throw new Error(r)}e++}let s=t[t.length-1];for(let o=0;o<t.length-1;++o)s+=this.strides[o]*t[o];return this.values[s]}locToIndex(t){if(this.rank===0)return 0;if(this.rank===1)return t[0];let e=t[t.length-1];for(let s=0;s<t.length-1;++s)e+=this.strides[s]*t[s];return e}indexToLoc(t){if(this.rank===0)return[];if(this.rank===1)return[t];const e=new Array(this.shape.length);for(let s=0;s<e.length-1;++s)e[s]=Math.floor(t/this.strides[s]),t-=e[s]*this.strides[s];return e[e.length-1]=t,e}get rank(){return this.shape.length}toTensor(){return kn().makeTensor(this.values,this.shape,this.dtype)}}let kn=null,Po=null;function Dw(n){kn=n}function Ww(n){Po=n}class ae{constructor(t,e,s,o){this.kept=!1,this.isDisposedInternal=!1,this.shape=t.slice(),this.dtype=e||"float32",this.size=Z(t),this.strides=ct(t),this.dataId=s,this.id=o,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const t=await this.data();return Po.buffer(this.shape,this.dtype,t)}bufferSync(){return Po.buffer(this.shape,this.dtype,this.dataSync())}async array(){const t=await this.data();return vn(this.shape,t,this.dtype==="complex64")}arraySync(){return vn(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();const t=kn().read(this.dataId);if(this.dtype==="string"){const e=await t;try{return e.map(s=>xs(s))}catch{throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return t}dataToGPU(t){return this.throwIfDisposed(),kn().readToGPU(this.dataId,t)}dataSync(){this.throwIfDisposed();const t=kn().readSync(this.dataId);if(this.dtype==="string")try{return t.map(e=>xs(e))}catch{throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return t}async bytes(){this.throwIfDisposed();const t=await kn().read(this.dataId);return this.dtype==="string"?t:new Uint8Array(t.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),kn().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(t=!1){return Po.print(this,t)}clone(){return this.throwIfDisposed(),Po.clone(this)}toString(t=!1){const e=this.dataSync();return Lw(e,this.shape,this.dtype,t)}cast(t){return this.throwIfDisposed(),Po.cast(this,t)}variable(t=!0,e,s){return this.throwIfDisposed(),kn().makeVariable(this,t,e,s)}}Object.defineProperty(ae,Symbol.hasInstance,{value:n=>!!n&&n.data!=null&&n.dataSync!=null&&n.throwIfDisposed!=null});function O(){return eu("Tensor",()=>ae)}O();class Tc extends ae{constructor(t,e,s,o){super(t.shape,t.dtype,t.dataId,o),this.trainable=e,this.name=s}assign(t){if(t.dtype!==this.dtype)throw new Error(`dtype of the new value (${t.dtype}) and previous value (${this.dtype}) must match`);if(!Rt(t.shape,this.shape))throw new Error(`shape of the new value (${t.shape}) and previous value (${this.shape}) must match`);kn().disposeTensor(this),this.dataId=t.dataId,kn().incRef(this,null)}dispose(){kn().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(Tc,Symbol.hasInstance,{value:n=>n instanceof ae&&n.assign!=null&&n.assign instanceof Function});/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */var rm;(function(n){n.R0="R0",n.R1="R1",n.R2="R2",n.R3="R3",n.R4="R4",n.R5="R5",n.R6="R6"})(rm||(rm={}));var ju;(function(n){n.float32="float32",n.int32="int32",n.bool="int32",n.complex64="complex64"})(ju||(ju={}));var qu;(function(n){n.float32="float32",n.int32="int32",n.bool="bool",n.complex64="complex64"})(qu||(qu={}));var td;(function(n){n.float32="float32",n.int32="float32",n.bool="float32",n.complex64="complex64"})(td||(td={}));var ed;(function(n){n.float32="complex64",n.int32="complex64",n.bool="complex64",n.complex64="complex64"})(ed||(ed={}));const Mw={float32:td,int32:ju,bool:qu,complex64:ed};function _e(n,t){if(n==="string"||t==="string"){if(n==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${n} with ${t}`)}return Mw[n][t]}function nd(n){return _e(n,"int32")}function im(n){return n!=null&&typeof n=="object"&&"texture"in n&&n.texture instanceof WebGLTexture}function am(n){return typeof GPUBuffer<"u"&&n!=null&&typeof n=="object"&&"buffer"in n&&n.buffer instanceof GPUBuffer}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function te(n,t){if(n.dtype===t.dtype)return[n,t];const e=_e(n.dtype,t.dtype);return[n.cast(e),t.cast(e)]}function cm(n){const t=[];return lm(n,t,new Set),t}function lm(n,t,e){if(n==null)return;if(n instanceof ae){t.push(n);return}if(!Vw(n))return;const s=n;for(const o in s){const r=s[o];e.has(r)||(e.add(r),lm(r,t,e))}}function Vw(n){return Array.isArray(n)||typeof n=="object"}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function sd(n){return n.kernelName!=null}class um{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null,get kernelNames(){return Array.from(new Set(this.kernels.map(t=>t.name)))}}}dispose(){for(const t in this.registeredVariables)this.registeredVariables[t].dispose()}}class Oo{constructor(t){this.ENV=t,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new um}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;const t=this.getSortedBackends();for(let e=0;e<t.length;e++){const s=t[e];if(await this.initializeBackend(s).success){await this.setBackend(s);return}}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(this.pendingBackendInit!=null)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(this.backendInstance==null){const{name:t,asyncInit:e}=this.initializeBackendsAndReturnBest();if(e)throw new Error(`The highest priority backend '${t}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(t)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(t){if(!(t in this.registry))if(t in this.registryFactory){const{asyncInit:e}=this.initializeBackend(t);if(e)return null}else return null;return this.registry[t]}findBackendFactory(t){return t in this.registryFactory?this.registryFactory[t].factory:null}registerBackend(t,e,s=1){return t in this.registryFactory?(je(`${t} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[t]={factory:e,priority:s},!0)}async setBackend(t){if(this.registryFactory[t]==null)throw new Error(`Backend name '${t}' not found in registry`);if(this.backendName=t,this.registry[t]==null){this.backendInstance=null;const{success:e,asyncInit:s}=this.initializeBackend(t);if(!(s?await e:e))return!1}return this.backendInstance=this.registry[t],this.setupRegisteredKernels(),this.profiler=new Tw(this.backendInstance),!0}setupRegisteredKernels(){Af(this.backendName).forEach(e=>{e.setupFunc!=null&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(t){Af(t).forEach(s=>{s.disposeFunc!=null&&s.disposeFunc(this.registry[t])})}initializeBackend(t){const e=this.registryFactory[t];if(e==null)throw new Error(`Cannot initialize backend ${t}, no registration found.`);try{const s=e.factory();if(s&&!(s instanceof Zl)&&typeof s.then=="function"){const o=++this.pendingBackendInitId,r=s.then(i=>o<this.pendingBackendInitId?!1:(this.registry[t]=i,this.pendingBackendInit=null,!0)).catch(i=>(o<this.pendingBackendInitId||(this.pendingBackendInit=null,je(`Initialization of backend ${t} failed`),je(i.stack||i.message)),!1));return this.pendingBackendInit=r,{success:r,asyncInit:!0}}else return this.registry[t]=s,{success:!0,asyncInit:!1}}catch(s){return je(`Initialization of backend ${t} failed`),je(s.stack||s.message),{success:!1,asyncInit:!1}}}removeBackend(t){if(!(t in this.registryFactory))throw new Error(`${t} backend not found in registry`);this.backendName===t&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,t in this.registry&&(this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t]),delete this.registryFactory[t],this.backendName===t&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(Object.keys(this.registryFactory).length===0)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((t,e)=>this.registryFactory[e].priority-this.registryFactory[t].priority)}initializeBackendsAndReturnBest(){const t=this.getSortedBackends();for(let e=0;e<t.length;e++){const s=t[e],{success:o,asyncInit:r}=this.initializeBackend(s);if(r||o)return{name:s,asyncInit:r}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(t,e){const s=this.state.tensorInfo.get(e),o=s.backend,r=this.readSync(e),i=o.refCount(e);o.disposeData(e,!0),s.backend=t,t.move(e,r,s.shape,s.dtype,i),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(t,e){let s=null;if(e==null){if(typeof t!="function")throw new Error("Please provide a function to tidy()");e=t}else{if(typeof t!="string"&&!(t instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof e!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");s=t}let o;return this.scopedRun(()=>this.startScope(s),()=>this.endScope(o),()=>(o=e(),o instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),o))}scopedRun(t,e,s){t();try{const o=s();return e(),o}catch(o){throw e(),o}}nextTensorId(){return Oo.nextTensorId++}nextVariableId(){return Oo.nextVariableId++}clone(t){const e=G.runKernel(Kr,{x:t}),s={x:t},o=i=>({x:()=>{const a="float32",c={x:i},l={dtype:a};return G.runKernel(Gr,c,l)}}),r=[];return this.addTapeNode(this.state.activeScope.name,s,[e],o,r,{}),e}runKernel(t,e,s){if(this.backendName==null&&this.backend,!(_u(t,this.backendName)!=null))throw new Error(`Kernel '${t}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:t,inputs:e,attrs:s})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(t,e,s){const o=this.backend.numDataIds();let r=0;s.forEach(c=>{r+=c.dtype==="complex64"?3:1});const i=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],a=o-e-r-i;if(a>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${a} data ids) after running '${t}'`)}runKernelFunc(t){let e,s=[];const o=this.isTapeOn(),r=this.state.numBytes,i=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let a;this.backendName==null&&this.backend;let c;const l=sd(t)?t.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(sd(t)){const{kernelName:f,inputs:m,attrs:g}=t;this.backendName==null&&this.backend;const b=_u(f,this.backendName);v(b!=null,()=>`Cannot find registered kernel '${f}' for backend '${this.backendName}'`),a=()=>{const x=this.backend.numDataIds();c=b.kernelFunc({inputs:m,attrs:g,backend:this.backend});const I=Array.isArray(c)?c:[c];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(f,x,I);const y=I.map(w=>w.rank!=null?w:this.makeTensorFromTensorInfo(w));if(o){const w=this.getTensorsForGradient(f,m,y);s=this.saveTensorsForBackwardMode(w)}return y}}else{const{forwardFunc:f}=t,m=g=>{o&&(s=g.map(b=>this.keep(this.clone(b))))};a=()=>{const g=this.backend.numDataIds();c=this.tidy(()=>f(this.backend,m));const b=Array.isArray(c)?c:[c];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,g,b),b}}const{inputs:u,attrs:d}=t,h=sd(t)?null:t.backwardsFunc;let p;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?e=a():(p=this.profiler.profileKernel(l,u,()=>a()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),e=p.outputs)}),o&&this.addTapeNode(l,u,e,h,s,d),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-r,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-i,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(u).map(f=>u[f]!=null?u[f].shape:null),outputShapes:e.map(f=>f.shape),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(c)?e:e[0]}saveTensorsForBackwardMode(t){return t.map(s=>this.keep(this.clone(s)))}getTensorsForGradient(t,e,s){const o=Xf(t);if(o!=null){const r=o.inputsToSave||[],i=o.outputsToSave||[];let a;o.saveAllInputs?(v(Array.isArray(e),()=>"saveAllInputs is true, expected inputs to be an array."),a=Object.keys(e).map(l=>e[l])):a=r.map(l=>e[l]);const c=s.filter((l,u)=>i[u]);return a.concat(c)}return[]}makeTensor(t,e,s,o){if(t==null)throw new Error("Values passed to engine.makeTensor() are null");s=s||"float32",o=o||this.backend;let r=t;s==="string"&&Cr(t[0])&&(r=t.map(c=>bs(c)));const i=o.write(r,e,s),a=new ae(e,s,i,this.nextTensorId());if(this.trackTensor(a,o),s==="string"){const c=this.state.tensorInfo.get(i),l=nw(r);this.state.numBytes+=l-c.bytes,c.bytes=l}return a}makeTensorFromDataId(t,e,s,o){s=s||"float32";const r={dataId:t,shape:e,dtype:s};return this.makeTensorFromTensorInfo(r,o)}makeTensorFromTensorInfo(t,e){const{dataId:s,shape:o,dtype:r}=t,i=new ae(o,r,s,this.nextTensorId());return this.trackTensor(i,e),i}makeVariable(t,e=!0,s,o){s=s||this.nextVariableId().toString(),o!=null&&o!==t.dtype&&(t=t.cast(o));const r=new Tc(t,e,s,this.nextTensorId());if(this.state.registeredVariables[r.name]!=null)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(t,e){this.state.numTensors++,t.dtype==="string"&&this.state.numStringTensors++;let s=0;t.dtype!=="complex64"&&t.dtype!=="string"&&(s=t.size*xa(t.dtype)),this.state.numBytes+=s,this.state.tensorInfo.has(t.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(t.dataId,{backend:e||this.backend,dtype:t.dtype,shape:t.shape,bytes:s})),t instanceof Tc||this.track(t)}incRef(t,e){this.trackTensor(t,e),this.backend.incRef(t.dataId)}removeDataId(t,e){this.state.tensorInfo.has(t)&&this.state.tensorInfo.get(t).backend===e&&(this.state.tensorInfo.delete(t),this.state.numDataBuffers--)}disposeTensor(t){if(!this.state.tensorInfo.has(t.dataId))return;const e=this.state.tensorInfo.get(t.dataId);if(this.state.numTensors--,t.dtype==="string"&&(this.state.numStringTensors--,this.state.numBytes-=e.bytes),t.dtype!=="complex64"&&t.dtype!=="string"){const s=t.size*xa(t.dtype);this.state.numBytes-=s}e.backend.disposeData(t.dataId)&&this.removeDataId(t.dataId,e.backend)}disposeVariables(){for(const t in this.state.registeredVariables){const e=this.state.registeredVariables[t];this.disposeVariable(e)}}disposeVariable(t){this.disposeTensor(t),this.state.registeredVariables[t.name]!=null&&delete this.state.registeredVariables[t.name]}memory(){const t=this.backend.memory();return t.numTensors=this.state.numTensors,t.numDataBuffers=this.state.numDataBuffers,t.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(t.unreliable=!0,t.reasons==null&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t}async profile(t){this.state.profiling=!0;const e=this.state.numBytes,s=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await t(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(o=>o.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-e,this.state.activeProfile.newTensors=this.state.numTensors-s;for(const o of this.state.activeProfile.kernels)o.kernelTimeMs=await o.kernelTimeMs,o.extraInfo=await o.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(t,e,s,o,r,i){const a={id:this.state.nextTapeNodeId++,kernelName:t,inputs:e,outputs:s,saved:r},c=Xf(t);c!=null&&(o=c.gradFunc),o!=null&&(a.gradient=l=>(l=l.map((u,d)=>{if(u==null){const h=s[d],p=ke(h.size,h.dtype);return this.makeTensor(p,h.shape,h.dtype)}return u}),o(l.length>1?l:l[0],r,i))),this.state.activeTape.push(a)}keep(t){return t.kept=!0,t}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(t){const e={track:[],name:"unnamed scope",id:this.state.nextScopeId++};t&&(e.name=t),this.state.scopeStack.push(e),this.state.activeScope=e}endScope(t){const e=cm(t),s=new Set(e.map(r=>r.id));for(let r=0;r<this.state.activeScope.track.length;r++){const i=this.state.activeScope.track[r];!i.kept&&!s.has(i.id)&&i.dispose()}const o=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],e.forEach(r=>{!r.kept&&r.scopeId===o.id&&this.track(r)})}gradients(t,e,s,o=!1){if(v(e.length>0,()=>"gradients() received an empty list of xs."),s!=null&&s.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${s.dtype}'`);const r=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",t));v(r instanceof ae,()=>"The result y returned by f() must be a tensor.");const i=$w(this.state.activeTape,e,r);if(!o&&i.length===0&&e.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",()=>{const a={};a[r.id]=s??Fw(r.shape),Gw(a,i,l=>this.tidy(l),zw);const c=e.map(l=>a[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(const u of l.saved)u.dispose()}),this.state.activeTape=null),{value:r,grads:c}})}customGrad(t){return v(Ql(t),()=>"The f passed in customGrad(f) must be a function."),(...e)=>{v(e.every(a=>a instanceof ae),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let s;const o={};e.forEach((a,c)=>{o[c]=a});const r=(a,c)=>(s=t(...e,c),v(s.value instanceof ae,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),v(Ql(s.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),s.value),i=(a,c)=>{const l=s.gradFunc(a,c),u=Array.isArray(l)?l:[l];v(u.length===e.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),v(u.every(h=>h instanceof ae),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");const d={};return u.forEach((h,p)=>{d[p]=()=>h}),d};return this.runKernelFunc({forwardFunc:r,backwardsFunc:i,inputs:o})}}readSync(t){return this.state.tensorInfo.get(t).backend.readSync(t)}read(t){return this.state.tensorInfo.get(t).backend.read(t)}readToGPU(t,e){return this.state.tensorInfo.get(t).backend.readToGPU(t,e)}async time(t){const e=Ve(),s=await this.backend.time(t);return s.wallMs=Ve()-e,s}track(t){return this.state.activeScope!=null&&(t.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(t)),t}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new um;for(const t in this.registry)this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}Oo.nextTensorId=0,Oo.nextVariableId=0;function Fw(n){const t=jl(Z(n),"float32");return G.makeTensor(t,n,"float32")}function dm(){const n=bf();if(n._tfengine==null){const t=new rw(n);n._tfengine=new Oo(t)}return lw(n._tfengine.ENV),Dw(()=>n._tfengine),n._tfengine}const G=dm();function zw(n,t){const e={a:n,b:t};return G.runKernel(Fo,e)}/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Xw(){return typeof navigator<"u"&&navigator!=null}function hm(n){if(n||Xw()){if(n||(n=navigator),n.product==="ReactNative")return!0;const t=n.userAgent||n.vendor||(typeof window<"u"?window.opera:"");if(!t){const e=n;return e.userAgentData&&e.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 pm(){return typeof window<"u"&&window.document!=null||typeof WorkerGlobalScope<"u"}/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const Fe=z();Fe.registerFlag("DEBUG",()=>!1,n=>{n&&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.")}),Fe.registerFlag("IS_BROWSER",()=>pm()),Fe.registerFlag("IS_NODE",()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"),Fe.registerFlag("IS_CHROME",()=>typeof navigator<"u"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)),Fe.registerFlag("IS_SAFARI",()=>typeof navigator<"u"&&navigator!=null&&navigator.userAgent!=null&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor)),Fe.registerFlag("PROD",()=>!1),Fe.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Fe.getBool("DEBUG")),Fe.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0),Fe.registerFlag("IS_TEST",()=>!1),Fe.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>Fe.getBool("DEBUG")),Fe.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1),Fe.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",()=>!1),Fe.registerFlag("USE_SETTIMEOUTCUSTOM",()=>!1);/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function wi(n,t){let e=n;if(hn(n))return t==="string"?[]:[n.length];if(im(n)){const o=n.channels||"RGBA";return[n.height,n.width*o.length]}else if(am(n))return[n.buffer.size/(t==null?4:xa(t))];if(!Array.isArray(n))return[];const s=[];for(;Array.isArray(e)||hn(e)&&t!=="string";)s.push(e.length),e=e[0];return Array.isArray(n)&&z().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&fm(n,s,[]),s}function fm(n,t,e){if(e=e||[],!Array.isArray(n)&&!hn(n)){v(t.length===0,()=>`Element arr[${e.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}v(t.length>0,()=>`Element arr[${e.join("][")}] should be a primitive, but is an array of ${n.length} elements`),v(n.length===t[0],()=>`Element arr[${e.join("][")}] should have ${t[0]} elements, but has ${n.length} elements`);const s=t.slice(1);for(let o=0;o<n.length;++o)fm(n[o],s,e.concat(o))}function mm(n,t,e,s){if(n!=="string_or_numeric"){if(n==null)throw new Error("Expected dtype cannot be null.");if(n!=="numeric"&&n!==t||n==="numeric"&&t==="string")throw new Error(`Argument '${e}' passed to '${s}' must be ${n} tensor, but got ${t} tensor`)}}function N(n,t,e,s="numeric"){if(n instanceof O())return mm(s,n.dtype,t,e),n;let o=Mo(n);if(o!=="string"&&["bool","int32","float32"].indexOf(s)>=0&&(o=s),mm(s,o,t,e),n==null||!hn(n)&&!Array.isArray(n)&&typeof n!="number"&&typeof n!="boolean"&&typeof n!="string"){const c=n==null?"null":n.constructor.name;throw new Error(`Argument '${t}' passed to '${e}' must be a Tensor or TensorLike, but got '${c}'`)}const r=wi(n,o);!hn(n)&&!Array.isArray(n)&&(n=[n]);const a=o!=="string"?Ys(n,o):Qs(n,[],!0);return G.makeTensor(a,r,o)}function gm(n,t,e,s="numeric"){if(!Array.isArray(n))throw new Error(`Argument ${t} passed to ${e} must be a \`Tensor[]\` or \`TensorLike[]\``);return n.map((r,i)=>N(r,`${t}[${i}]`,e,s))}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const Aw="__op";function D(n){const t=Object.keys(n);if(t.length!==1)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 e=t[0];const s=n[e];e.endsWith("_")&&(e=e.substring(0,e.length-1)),e=e+Aw;const o=(...r)=>{G.startScope(e);try{const i=s(...r);return ql(i)&&console.error("Cannot return a Promise inside of tidy."),G.endScope(i),i}catch(i){throw G.endScope(null),i}};return Object.defineProperty(o,"name",{value:e,configurable:!0}),o}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Pw(n,t){const e=N(n,"real","complex"),s=N(t,"imag","complex");Hl(e.shape,s.shape,`real and imag shapes, ${e.shape} and ${s.shape}, must match in call to tf.complex().`);const o={real:e,imag:s};return G.runKernel(lu,o)}const Ko=D({complex_:Pw});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Ci(n,t,e,s){if(s==null)s=Mo(n);else if(s==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(am(n)||im(n)){if(s!=="float32"&&s!=="int32")throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${s}.`);return G.backend.createTensorFromGPUData(n,t||e,s)}if(!hn(n)&&!Array.isArray(n)&&typeof n!="number"&&typeof n!="boolean"&&typeof n!="string")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(t!=null){es(t);const o=Z(t),r=Z(e);v(o===r,()=>`Based on the provided shape, [${t}], the tensor should have ${o} values but has ${r}`);for(let i=0;i<e.length;++i){const a=e[i],c=i===e.length-1?a!==Z(t.slice(i)):!0;v(e[i]===t[i]||!c,()=>`Error creating a new Tensor. Inferred shape (${e}) does not match the provided shape (${t}). `)}}return!hn(n)&&!Array.isArray(n)&&(n=[n]),t=t||e,n=s!=="string"?Ys(n,s):Qs(n,[],!0),G.makeTensor(n,t,s)}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function tn(n,t,e){const s=wi(n,e);return Ci(n,t,s,e)}class Zo{static join(t){return new Zo(t).slice()}constructor(t){if(this.shards=[],this.previousShardIndex=0,t==null||(t instanceof Array||(t=[t]),t=t.map(s=>hn(s)?s.buffer:s),t.length===0))return;this.bufferUniformSize=t[0].byteLength;let e=0;for(let s=0;s<t.length;s++){const o=t[s];s!==t.length-1&&o.byteLength!==this.bufferUniformSize&&(this.bufferUniformSize=void 0);const r=e+o.byteLength;this.shards.push({buffer:o,start:e,end:r}),e=r}this.shards.length===0&&(this.byteLength=0),this.byteLength=this.shards[this.shards.length-1].end}slice(t=0,e=this.byteLength){if(this.shards.length===0)return new ArrayBuffer(0);if(t=isNaN(Number(t))?0:t,e=isNaN(Number(e))?0:e,t=Math.max(0,t),e=Math.min(this.byteLength,e),e<=t)return new ArrayBuffer(0);const s=this.findShardForByte(t);if(s===-1)throw new Error(`Could not find start shard for byte ${t}`);const o=e-t,r=new ArrayBuffer(o),i=new Uint8Array(r);let a=0;for(let c=s;c<this.shards.length;c++){const l=this.shards[c],d=t+a-l.start,h=a,f=Math.min(e,l.end)-l.start,m=new Uint8Array(l.buffer,d,f-d);if(i.set(m,h),a+=m.length,e<l.end)break}return r}findShardForByte(t){if(this.shards.length===0||t<0||t>=this.byteLength)return-1;if(this.bufferUniformSize!=null)return this.previousShardIndex=Math.floor(t/this.bufferUniformSize),this.previousShardIndex;function e(o){return t<o.start?-1:t>=o.end?1:0}if(e(this.shards[this.previousShardIndex])===0)return this.previousShardIndex;const s=Ow(this.shards,e);return s===-1?-1:(this.previousShardIndex=s,this.previousShardIndex)}}function Ow(n,t){let e=0,s=n.length;for(;e<=s;){const o=Math.floor((s-e)/2)+e,r=t(n[o]);if(r===0)return o;r<0?s=o:e=o+1}return-1}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function zt(){return G}function Nc(){return G.memory()}function M(n,t){return G.tidy(n,t)}function vt(n){cm(n).forEach(e=>e.dispose())}function en(n){return G.keep(n)}function bm(n,t,e=1){return G.registerBackend(n,t,e)}function ys(){return G.backend}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const xm=4;async function ym(n,t){const e=[],s=[],o=Array.isArray(n)?n.map(i=>i.name):Object.keys(n);for(let i=0;i<o.length;++i){const a=o[i],c=Array.isArray(n)?n[i].tensor:n[a];if(c.dtype!=="float32"&&c.dtype!=="int32"&&c.dtype!=="bool"&&c.dtype!=="string"&&c.dtype!=="complex64")throw new Error(`Unsupported dtype in weight '${a}': ${c.dtype}`);const l={name:a,shape:c.shape,dtype:c.dtype};if(c.dtype==="string"){const u=new Promise(async d=>{const h=await c.bytes(),p=h.reduce((g,b)=>g+b.length,0)+xm*h.length,f=new Uint8Array(p);let m=0;for(let g=0;g<h.length;g++){const b=h[g],x=new Uint8Array(new Uint32Array([b.length]).buffer);f.set(x,m),m+=xm,f.set(b,m),m+=b.length}d(f)});s.push(u)}else s.push(c.data());t!=null&&(l.group=t),e.push(l)}const r=await Promise.all(s);return{data:Kw(r),specs:e}}function Kw(n){if(n===null)throw new Error(`Invalid input value: ${JSON.stringify(n)}`);let t=0;const e=[];n.forEach(r=>{if(t+=r.byteLength,e.push(r.byteLength===r.buffer.byteLength?r:new r.constructor(r)),!(r instanceof Float32Array||r instanceof Int32Array||r instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${r.constructor.name}`)});const s=new Uint8Array(t);let o=0;return e.forEach(r=>{s.set(new Uint8Array(r.buffer),o),o+=r.byteLength}),s.buffer}const od=typeof Buffer<"u"&&(typeof Blob>"u"||typeof atob>"u"||typeof btoa>"u");function Im(n){return od?Buffer.byteLength(n,"utf8"):new Blob([n]).size}function Zw(n){if(od)return Buffer.from(n).toString("base64");const t=new Uint8Array(n);let e="";for(let s=0,o=t.length;s<o;s++)e+=String.fromCharCode(t[s]);return btoa(e)}function Bw(n){if(od){const s=Buffer.from(n,"base64");return s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)}const t=atob(n),e=new Uint8Array(t.length);for(let s=0;s<t.length;++s)e.set([t.charCodeAt(s)],s);return e.buffer}function Hw(n){return Zo.join(n)}function wm(n){if(n.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:n.modelTopology==null?0:Im(JSON.stringify(n.modelTopology)),weightSpecsBytes:n.weightSpecs==null?0:Im(JSON.stringify(n.weightSpecs)),weightDataBytes:n.weightData==null?0:new Zo(n.weightData).byteLength}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class $e{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return $e.instance==null&&($e.instance=new $e),$e.instance}static registerSaveRouter(t){$e.getInstance().saveRouters.push(t)}static registerLoadRouter(t){$e.getInstance().loadRouters.push(t)}static getSaveHandlers(t){return $e.getHandlers(t,"save")}static getLoadHandlers(t,e){return $e.getHandlers(t,"load",e)}static getHandlers(t,e,s){const o=[];return(e==="load"?$e.getInstance().loadRouters:$e.getInstance().saveRouters).forEach(i=>{const a=i(t,s);a!==null&&o.push(a)}),o}}const _w=n=>$e.getSaveHandlers(n);/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const rd="tensorflowjs",id=1,Js="models_store",Is="model_info_store";function Cm(){if(!z().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const n=typeof window>"u"?self:window,t=n.indexedDB||n.mozIndexedDB||n.webkitIndexedDB||n.msIndexedDB||n.shimIndexedDB;if(t==null)throw new Error("The current browser does not appear to support IndexedDB.");return t}function ad(n){const t=n.result;t.createObjectStore(Js,{keyPath:"modelPath"}),t.createObjectStore(Is,{keyPath:"modelPath"})}class js{constructor(t){if(this.indexedDB=Cm(),t==null||!t)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=t}async save(t){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,t)}async load(){return this.databaseAction(this.modelPath)}databaseAction(t,e){return new Promise((s,o)=>{const r=this.indexedDB.open(rd,id);r.onupgradeneeded=()=>ad(r),r.onsuccess=()=>{const i=r.result;if(e==null){const a=i.transaction(Js,"readonly"),l=a.objectStore(Js).get(this.modelPath);l.onsuccess=()=>{if(l.result==null)return i.close(),o(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));s(l.result.modelArtifacts)},l.onerror=u=>(i.close(),o(l.error)),a.oncomplete=()=>i.close()}else{e.weightData=Zo.join(e.weightData);const a=wm(e),c=i.transaction(Is,"readwrite");let l=c.objectStore(Is),u;try{u=l.put({modelPath:this.modelPath,modelArtifactsInfo:a})}catch(h){return o(h)}let d;u.onsuccess=()=>{d=i.transaction(Js,"readwrite");const h=d.objectStore(Js);let p;try{p=h.put({modelPath:this.modelPath,modelArtifacts:e,modelArtifactsInfo:a})}catch(f){return o(f)}p.onsuccess=()=>s({modelArtifactsInfo:a}),p.onerror=f=>{l=c.objectStore(Is);const m=l.delete(this.modelPath);m.onsuccess=()=>(i.close(),o(p.error)),m.onerror=g=>(i.close(),o(p.error))}},u.onerror=h=>(i.close(),o(u.error)),c.oncomplete=()=>{d==null?i.close():d.oncomplete=()=>i.close()}}},r.onerror=i=>o(r.error)})}}js.URL_SCHEME="indexeddb://";const vm=n=>z().getBool("IS_BROWSER")&&!Array.isArray(n)&&n.startsWith(js.URL_SCHEME)?Uw(n.slice(js.URL_SCHEME.length)):null;$e.registerSaveRouter(vm),$e.registerLoadRouter(vm);function Uw(n){return new js(n)}function Yw(n){return n.startsWith(js.URL_SCHEME)?n.slice(js.URL_SCHEME.length):n}class Qw{constructor(){this.indexedDB=Cm()}async listModels(){return new Promise((t,e)=>{const s=this.indexedDB.open(rd,id);s.onupgradeneeded=()=>ad(s),s.onsuccess=()=>{const o=s.result,r=o.transaction(Is,"readonly"),a=r.objectStore(Is).getAll();a.onsuccess=()=>{const c={};for(const l of a.result)c[l.modelPath]=l.modelArtifactsInfo;t(c)},a.onerror=c=>(o.close(),e(a.error)),r.oncomplete=()=>o.close()},s.onerror=o=>e(s.error)})}async removeModel(t){return t=Yw(t),new Promise((e,s)=>{const o=this.indexedDB.open(rd,id);o.onupgradeneeded=()=>ad(o),o.onsuccess=()=>{const r=o.result,i=r.transaction(Is,"readwrite"),a=i.objectStore(Is),c=a.get(t);let l;c.onsuccess=()=>{if(c.result==null)return r.close(),s(new Error(`Cannot find model with path '${t}' in IndexedDB.`));{const u=a.delete(t),d=()=>{l=r.transaction(Js,"readwrite");const p=l.objectStore(Js).delete(t);p.onsuccess=()=>e(c.result.modelArtifactsInfo),p.onerror=f=>s(c.error)};u.onsuccess=d,u.onerror=h=>(d(),r.close(),s(c.error))}},c.onerror=u=>(r.close(),s(c.error)),i.oncomplete=()=>{l==null?r.close():l.oncomplete=()=>r.close()}},o.onerror=r=>s(o.error)})}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const ns="/",Bo="tensorflowjs_models",Sm="info",Jw="model_topology",jw="weight_specs",qw="weight_data",tC="model_metadata";function km(n){return{info:[Bo,n,Sm].join(ns),topology:[Bo,n,Jw].join(ns),weightSpecs:[Bo,n,jw].join(ns),weightData:[Bo,n,qw].join(ns),modelMetadata:[Bo,n,tC].join(ns)}}function Tm(n){for(const t of Object.values(n))window.localStorage.removeItem(t)}function eC(n){const t=n.split(ns);if(t.length<3)throw new Error(`Invalid key format: ${n}`);return t.slice(1,t.length-1).join(ns)}function nC(n){return n.startsWith(qs.URL_SCHEME)?n.slice(qs.URL_SCHEME.length):n}class qs{constructor(t){if(!z().getBool("IS_BROWSER")||typeof window>"u"||typeof window.localStorage>"u")throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,t==null||!t)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=t,this.keys=km(this.modelPath)}async save(t){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{const e=JSON.stringify(t.modelTopology),s=JSON.stringify(t.weightSpecs),o=wm(t),r=Zo.join(t.weightData);try{this.LS.setItem(this.keys.info,JSON.stringify(o)),this.LS.setItem(this.keys.topology,e),this.LS.setItem(this.keys.weightSpecs,s),this.LS.setItem(this.keys.weightData,Zw(r));const i={format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,signature:t.signature!=null?t.signature:void 0,userDefinedMetadata:t.userDefinedMetadata!=null?t.userDefinedMetadata:void 0,modelInitializer:t.modelInitializer!=null?t.modelInitializer:void 0,initializerSignature:t.initializerSignature!=null?t.initializerSignature:void 0,trainingConfig:t.trainingConfig!=null?t.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(i)),{modelArtifactsInfo:o}}catch{throw Tm(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=${o.modelTopologyBytes}, weightSpecsBytes=${o.weightSpecsBytes}, weightDataBytes=${o.weightDataBytes}.`)}}}async load(){const t=JSON.parse(this.LS.getItem(this.keys.info));if(t==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(t.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");const e={},s=JSON.parse(this.LS.getItem(this.keys.topology));if(s==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);e.modelTopology=s;const o=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(o==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);e.weightSpecs=o;const r=this.LS.getItem(this.keys.modelMetadata);if(r!=null){const a=JSON.parse(r);e.format=a.format,e.generatedBy=a.generatedBy,e.convertedBy=a.convertedBy,a.signature!=null&&(e.signature=a.signature),a.userDefinedMetadata!=null&&(e.userDefinedMetadata=a.userDefinedMetadata),a.modelInitializer!=null&&(e.modelInitializer=a.modelInitializer),a.initializerSignature!=null&&(e.initializerSignature=a.initializerSignature),a.trainingConfig!=null&&(e.trainingConfig=a.trainingConfig)}const i=this.LS.getItem(this.keys.weightData);if(i==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return e.weightData=Bw(i),e}}qs.URL_SCHEME="localstorage://";const Nm=n=>z().getBool("IS_BROWSER")&&!Array.isArray(n)&&n.startsWith(qs.URL_SCHEME)?sC(n.slice(qs.URL_SCHEME.length)):null;$e.registerSaveRouter(Nm),$e.registerLoadRouter(Nm);function sC(n){return new qs(n)}class oC{constructor(){v(z().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),v(typeof window>"u"||typeof window.localStorage<"u",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){const t={},e=Bo+ns,s=ns+Sm;for(let o=0;o<this.LS.length;++o){const r=this.LS.key(o);if(r.startsWith(e)&&r.endsWith(s)){const i=eC(r);t[i]=JSON.parse(this.LS.getItem(r))}}return t}async removeModel(t){t=nC(t);const e=km(t);if(this.LS.getItem(e.info)==null)throw new Error(`Cannot find model at path '${t}'`);const s=JSON.parse(this.LS.getItem(e.info));return Tm(e),s}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const Rm="://";class zn{constructor(){this.managers={}}static getInstance(){return zn.instance==null&&(zn.instance=new zn),zn.instance}static registerManager(t,e){v(t!=null,()=>"scheme must not be undefined or null."),t.endsWith(Rm)&&(t=t.slice(0,t.indexOf(Rm))),v(t.length>0,()=>"scheme must not be an empty string.");const s=zn.getInstance();v(s.managers[t]==null,()=>`A model store manager is already registered for scheme '${t}'.`),s.managers[t]=e}static getManager(t){const e=zn.getInstance().managers[t];if(e==null)throw new Error(`Cannot find model manager for scheme '${t}'`);return e}static getSchemes(){return Object.keys(zn.getInstance().managers)}}/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class rC{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}fetch(t,e){return fetch(t,e)}now(){return performance.now()}encode(t,e){if(e!=="utf-8"&&e!=="utf8")throw new Error(`Browser's encoder only supports utf-8, but got ${e}`);return this.textEncoder==null&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(t)}decode(t,e){return new TextDecoder(e).decode(t)}setTimeoutCustom(t,e){if(typeof window>"u"||!z().getBool("USE_SETTIMEOUTCUSTOM")){setTimeout(t,e);return}this.functionRefs.push(t),setTimeout(()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")},e),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",s=>{if(s.source===window&&s.data.name===this.messageName){s.stopPropagation();const o=this.functionRefs[s.data.index];o(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0)}},!0))}isTypedArray(t){return Of(t)}}if(z().get("IS_BROWSER")){z().setPlatform("browser",new rC);try{zn.registerManager(qs.URL_SCHEME,new oC)}catch{}try{zn.registerManager(js.URL_SCHEME,new Qw)}catch{}}/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const iC={importFetch:()=>require("node-fetch")};let cd;class aC{constructor(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}fetch(t,e){return z().global.fetch!=null?z().global.fetch(t,e):(cd==null&&(cd=iC.importFetch()),cd(t,e))}now(){const t=process.hrtime();return t[0]*1e3+t[1]/1e6}encode(t,e){if(e!=="utf-8"&&e!=="utf8")throw new Error(`Node built-in encoder only supports utf-8, but got ${e}`);return this.textEncoder.encode(t)}decode(t,e){return t.length===0?"":new this.util.TextDecoder(e).decode(t)}isTypedArray(t){return this.util.types.isFloat32Array(t)||this.util.types.isInt32Array(t)||this.util.types.isUint8Array(t)||this.util.types.isUint8ClampedArray(t)}}z().get("IS_NODE")&&!z().get("IS_BROWSER")&&z().setPlatform("node",new aC);/**
 * @license
 * Copyright 2020 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function wt(n,t="float32",e){return t=t||"float32",es(n),new xe(n,t,e)}/**
 * @license
 * Copyright 2020 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function cC(n,t){const e=N(n,"x","cast");if(!ew(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&e.dtype!=="string"||t!=="string"&&e.dtype==="string")throw new Error("Only strings can be casted to strings");const s={x:e},o={dtype:t};return G.runKernel(Gr,s,o)}const st=D({cast_:cC});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function lC(n){const e={x:N(n,"x","clone","string_or_numeric")};return G.runKernel(Kr,e)}const to=D({clone_:lC});/**
 * @license
 * Copyright 2020 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function uC(n,t=!1){console.log(n.toString(t))}/**
 * @license
 * Copyright 2020 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */dm(),Ww({buffer:wt,cast:st,clone:to,print:uC});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function dC(n,t){let e=N(n,"a","add"),s=N(t,"b","add");[e,s]=te(e,s);const o={a:e,b:s};return G.runKernel(Fo,o)}const Q=D({add_:dC});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function hC(n,t){let e=N(n,"a","floorDiv"),s=N(t,"b","floorDiv");[e,s]=te(e,s);const o={a:e,b:s};return G.runKernel(Pr,o)}const $m=D({floorDiv_:hC});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function pC(n,t){let e=N(n,"a","div"),s=N(t,"b","div");if([e,s]=te(e,s),e.dtype==="int32"&&s.dtype==="int32")return $m(e,s);const o={a:e,b:s},r={};return G.runKernel(Mr,o,r)}const dt=D({div_:pC});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function fC(n,t){let e=N(n,"a","mul"),s=N(t,"b","mul");[e,s]=te(e,s);const o={a:e,b:s};return G.runKernel(jr,o)}const E=D({mul_:fC});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function mC(n){const t=N(n,"x","abs");if(t.dtype==="complex64"){const e={x:t};return G.runKernel(Ta,e)}else{const e={x:t};return G.runKernel(ya,e)}}const Ge=D({abs_:mC});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function gC(n){const e={x:N(n,"x","acos")};return G.runKernel(vr,e)}const bC=D({acos_:gC});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function xC(n){const e={x:N(n,"x","acosh")};return G.runKernel(Sr,e)}const yC=D({acosh_:xC});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function IC(n,t=null,e=!1){const o={x:N(n,"x","all","bool")},r={axis:t,keepDims:e};return G.runKernel(su,o,r)}const Gm=D({all_:IC});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function wC(n,t=null,e=!1){const o={x:N(n,"x","any","bool")},r={axis:t,keepDims:e};return G.runKernel(ou,o,r)}const ld=D({any_:wC});/**
 * @license
 * Copyright 2020 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function CC(n,t=0){const s={x:N(n,"x","argMax")},o={axis:t};return G.runKernel(Ia,s,o)}const vi=D({argMax_:CC});/**
 * @license
 * Copyright 2020 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function vC(n,t=0){const s={x:N(n,"x","argMin")},o={axis:t};return G.runKernel(wa,s,o)}const SC=D({argMin_:vC});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function kC(n){const e={x:N(n,"x","asin")};return G.runKernel(kr,e)}const TC=D({asin_:kC});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function NC(n){const e={x:N(n,"x","asinh")};return G.runKernel(Tr,e)}const RC=D({asinh_:NC});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function $C(n){const e={x:N(n,"x","atan")};return G.runKernel(Nr,e)}const GC=D({atan_:$C});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function LC(n,t){let e=N(n,"a","atan2"),s=N(t,"b","atan2");[e,s]=te(e,s);const o={a:e,b:s};return G.runKernel($r,o)}const EC=D({atan2_:LC});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function DC(n){const e={x:N(n,"x","atanh")};return G.runKernel(Rr,e)}const WC=D({atanh_:DC});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Si(n,t,e,s,o="NHWC",r){const i=n[3],a=[...t,i],c=os(o);return ye(n,a,e,r,s,null,null,c)}function pn(n,t,e,s,o,r,i="channelsLast"){const[a,c]=ki(t);let l;if(i==="channelsLast")l=[a,c,n[3],n[3]];else if(i==="channelsFirst")l=[a,c,n[1],n[1]];else throw new Error(`Unknown dataFormat ${i}`);return ye(n,l,e,s,o,r,!1,i)}function ss(n,t,e,s,o,r,i="NDHWC"){const[a,c,l]=dd(t);let u,d;if(i==="NDHWC")d="channelsLast",u=[a,c,l,n[4],n[4]];else if(i==="NCDHW")d="channelsFirst",u=[a,c,l,n[1],n[1]];else throw new Error(`Unknown dataFormat ${i}`);return ws(n,u,e,s,o,!1,d,r)}function ye(n,t,e,s,o,r,i=!1,a="channelsLast"){let[c,l,u,d]=[-1,-1,-1,-1];if(a==="channelsLast")[c,l,u,d]=n;else if(a==="channelsFirst")[c,d,l,u]=n;else throw new Error(`Unknown dataFormat ${a}`);const[h,p,,f]=t,[m,g]=ki(e),[b,x]=ki(s),I=Ho(h,b),y=Ho(p,x),{padInfo:w,outHeight:C,outWidth:k}=FC(o,l,u,m,g,I,y,r,a),S=i?f*d:f;let T;return a==="channelsFirst"?T=[c,S,C,k]:a==="channelsLast"&&(T=[c,C,k,S]),{batchSize:c,dataFormat:a,inHeight:l,inWidth:u,inChannels:d,outHeight:C,outWidth:k,outChannels:S,padInfo:w,strideHeight:m,strideWidth:g,filterHeight:h,filterWidth:p,effectiveFilterHeight:I,effectiveFilterWidth:y,dilationHeight:b,dilationWidth:x,inShape:n,outShape:T,filterShape:t}}function ws(n,t,e,s,o,r=!1,i="channelsLast",a){let[c,l,u,d,h]=[-1,-1,-1,-1,-1];if(i==="channelsLast")[c,l,u,d,h]=n;else if(i==="channelsFirst")[c,h,l,u,d]=n;else throw new Error(`Unknown dataFormat ${i}`);const[p,f,m,,g]=t,[b,x,I]=dd(e),[y,w,C]=dd(s),k=Ho(p,y),S=Ho(f,w),T=Ho(m,C),{padInfo:R,outDepth:L,outHeight:V,outWidth:F}=zC(o,l,u,d,b,x,I,k,S,T,a),X=r?g*h:g;let A;return i==="channelsFirst"?A=[c,X,L,V,F]:i==="channelsLast"&&(A=[c,L,V,F,X]),{batchSize:c,dataFormat:i,inDepth:l,inHeight:u,inWidth:d,inChannels:h,outDepth:L,outHeight:V,outWidth:F,outChannels:X,padInfo:R,strideDepth:b,strideHeight:x,strideWidth:I,filterDepth:p,filterHeight:f,filterWidth:m,effectiveFilterDepth:k,effectiveFilterHeight:S,effectiveFilterWidth:T,dilationDepth:y,dilationHeight:w,dilationWidth:C,inShape:n,outShape:A,filterShape:t}}function MC(n,t,e,s,o){s==null&&(s=ud(n,t,e));const r=n[0],i=n[1],a=Ti((r-t+2*s)/e+1,o),c=Ti((i-t+2*s)/e+1,o);return[a,c]}function VC(n,t,e,s,o,r){o==null&&(o=ud(n,t[0],s[0]));const i=[0,0,0,e];for(let a=0;a<3;a++)n[a]+2*o>=t[a]&&(i[a]=Ti((n[a]-t[a]+2*o)/s[a]+1,r));return i}function ud(n,t,e,s=1){const o=Ho(t,s);return Math.floor((n[0]*(e-1)-e+o)/2)}function ki(n){return typeof n=="number"?[n,n,n]:n.length===2?[n[0],n[1],1]:n}function dd(n){return typeof n=="number"?[n,n,n]:n}function Ho(n,t){return t<=1?n:n+(n-1)*(t-1)}function FC(n,t,e,s,o,r,i,a,c){let l,u,d;if(typeof n=="number"){l={top:n,bottom:n,left:n,right:n,type:n===0?"VALID":"NUMBER"};const p=MC([t,e],r,s,n,a);u=p[0],d=p[1]}else if(n==="same"){u=Math.ceil(t/s),d=Math.ceil(e/o);const h=Math.max(0,(u-1)*s+r-t),p=Math.max(0,(d-1)*o+i-e),f=Math.floor(h/2),m=h-f,g=Math.floor(p/2),b=p-g;l={top:f,bottom:m,left:g,right:b,type:"SAME"}}else if(n==="valid")l={top:0,bottom:0,left:0,right:0,type:"VALID"},u=Math.ceil((t-r+1)/s),d=Math.ceil((e-i+1)/o);else if(typeof n=="object"){const h=c==="channelsLast"?n[1][0]:n[2][0],p=c==="channelsLast"?n[1][1]:n[2][1],f=c==="channelsLast"?n[2][0]:n[3][0],m=c==="channelsLast"?n[2][1]:n[3][1];l={top:h,bottom:p,left:f,right:m,type:h===0&&p===0&&f===0&&m===0?"VALID":"EXPLICIT"},u=Ti((t-r+h+p)/s+1,a),d=Ti((e-i+f+m)/o+1,a)}else throw Error(`Unknown padding parameter: ${n}`);return{padInfo:l,outHeight:u,outWidth:d}}function zC(n,t,e,s,o,r,i,a,c,l,u){let d,h,p,f;if(n==="valid"&&(n=0),typeof n=="number"){d={top:n,bottom:n,left:n,right:n,front:n,back:n,type:n===0?"VALID":"NUMBER"};const g=VC([t,e,s,1],[a,c,l],1,[o,r,i],n,u);h=g[0],p=g[1],f=g[2]}else if(n==="same"){h=Math.ceil(t/o),p=Math.ceil(e/r),f=Math.ceil(s/i);const m=(h-1)*o+a-t,g=(p-1)*r+c-e,b=(f-1)*i+l-s,x=Math.floor(m/2),I=m-x,y=Math.floor(g/2),w=g-y,C=Math.floor(b/2),k=b-C;d={top:y,bottom:w,left:C,right:k,front:x,back:I,type:"SAME"}}else throw Error(`Unknown padding parameter: ${n}`);return{padInfo:d,outDepth:h,outHeight:p,outWidth:f}}function Ti(n,t){if(!t)return Math.trunc(n);switch(t){case"round":return Math.round(n);case"ceil":return Math.ceil(n);case"floor":return Math.floor(n);default:throw new Error(`Unknown roundingMode ${t}`)}}function eo(n){const[t,e,s]=ki(n);return t===1&&e===1&&s===1}function Te(n,t){return eo(n)||eo(t)}function no(n){return ki(n).every(t=>t>0)}function os(n){if(n==="NHWC")return"channelsLast";if(n==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${n}`)}function ze(n,t,e){if(e!=null){if(typeof t=="string")throw Error(`Error in ${n}: pad must be an integer when using dimRoundingMode ${e} but got pad ${t}.`);if(typeof t=="number")v(Do(t),()=>`Error in ${n}: pad must be an integer when using dimRoundingMode ${e} but got pad ${t}.`);else if(typeof t=="object")t.forEach(s=>{s.forEach(o=>{v(Do(o),()=>`Error in ${n}: pad must be an integer when using dimRoundingMode ${e} but got pad ${o}.`)})});else throw Error(`Error in ${n}: Unknown padding parameter: ${t}`)}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function XC(n,t){const s={x:N(n,"x","reshape","string_or_numeric")},o={shape:t};return G.runKernel(ic,s,o)}const W=D({reshape_:XC});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function AC(n,t,e,s,o){const r=N(n,"x","avgPool","float32"),i=1;v(Te(e,i),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${e} and dilations '${i}'`);let a=r,c=!1;r.rank===3&&(c=!0,a=W(r,[1,r.shape[0],r.shape[1],r.shape[2]])),v(a.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${a.rank}.`),ze("avgPool",s,o);const l={x:a},u={filterSize:t,strides:e,pad:s,dimRoundingMode:o};let d=G.runKernel(Ca,l,u);return d=st(d,r.dtype),c?W(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const hd=D({avgPool_:AC});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function PC(n,t,e,s,o,r="NDHWC"){const i=N(n,"x","avgPool3d","float32");let a=i,c=!1;i.rank===4&&(c=!0,a=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),v(a.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${a.rank}.`),v(r==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${r}`),v(typeof e=="number"&&e>0||Array.isArray(e)&&e[0]>0&&e[1]>0&&e[2]>0,()=>`Error in avgPool3d: Stride must be > 0, but got '${e}'`),ze("avgPool3d",s,o);const l={x:a},u={filterSize:t,strides:e,pad:s,dimRoundingMode:o,dataFormat:r};let d=G.runKernel(va,l,u);return d=st(d,a.dtype),c?W(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}const OC=D({avgPool3d_:PC});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function KC(n,t=0){v(n.length>=1,()=>"Pass at least one tensor to concat");const e=gm(n,"tensors","concat","string_or_numeric");if(e[0].dtype==="complex64"&&e.forEach(r=>{if(r.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
          with dtype ${r.dtype}. `)}),e.length===1)return to(e[0]);const s=e,o={axis:t};return G.runKernel(Na,s,o)}const Xe=D({concat_:KC});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function ZC(n,t,e=!1,s=!1){let o=N(n,"a","matMul"),r=N(t,"b","matMul");[o,r]=te(o,r);const i={a:o,b:r},a={transposeA:e,transposeB:s};return G.runKernel(Sa,i,a)}const $t=D({matMul_:ZC});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function BC(n){const e={x:N(n,"x","sigmoid","float32")};return G.runKernel(li,e)}const _o=D({sigmoid_:BC});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function HC(n,t,e){const s=N(n,"x","slice","string_or_numeric");if(s.rank===0)throw new Error("Slicing scalar is not possible");const o={x:s},r={begin:t,size:e};return G.runKernel(dc,o,r)}const Xt=D({slice_:HC});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function _C(n){const e={x:N(n,"x","tanh","float32")};return G.runKernel(mi,e)}const pd=D({tanh_:_C});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function UC(n,t,e){const s=N(n,"x","batchToSpaceND"),o=t.reduce((a,c)=>a*c);v(s.rank>=1+t.length,()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`),v(e.length===t.length,()=>`crops.length is ${e.length} but should be equal to blockShape.length  ${t.length}`),v(s.shape[0]%o===0,()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${o}`);const r={x:s},i={blockShape:t,crops:e};return G.runKernel(ka,r,i)}const fd=D({batchToSpaceND_:UC});function YC(n){let t;return n.rank===0||n.rank===1?t=W(n,[1,1,1,n.size]):n.rank===2?t=W(n,[1,1,n.shape[0],n.shape[1]]):n.rank===3?t=W(n,[1,n.shape[0],n.shape[1],n.shape[2]]):t=n,t}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function QC(n,t,e,s,o,r){r==null&&(r=.001);const i=N(n,"x","batchNorm"),a=N(t,"mean","batchNorm"),c=N(e,"variance","batchNorm");let l;o!=null&&(l=N(o,"scale","batchNorm"));let u;s!=null&&(u=N(s,"offset","batchNorm")),v(a.rank===c.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),v(u==null||a.rank===u.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),v(l==null||a.rank===l.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const h={x:YC(i),scale:l,offset:u,mean:a,variance:c},p={varianceEpsilon:r},f=G.runKernel(Va,h,p);return W(f,i.shape)}const Rc=D({batchNorm_:QC});function JC(n,t,e,s,o,r){const i=N(n,"x","batchNorm"),a=N(t,"mean","batchNorm"),c=N(e,"variance","batchNorm");let l;o!=null&&(l=N(o,"scale","batchNorm"));let u;return s!=null&&(u=N(s,"offset","batchNorm")),v(i.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`),v(a.rank===2||a.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${a.rank}.`),v(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${c.rank}.`),l!=null&&v(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&v(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${u.rank}.`),Rc(i,a,c,u,l,r)}const jC=D({batchNorm2d_:JC});function qC(n,t,e,s,o,r){const i=N(n,"x","batchNorm"),a=N(t,"mean","batchNorm"),c=N(e,"variance","batchNorm");let l;o!=null&&(l=N(o,"scale","batchNorm"));let u;return s!=null&&(u=N(s,"offset","batchNorm")),v(i.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`),v(a.rank===3||a.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${a.rank}.`),v(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${c.rank}.`),l!=null&&v(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&v(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${u.rank}.`),Rc(i,a,c,u,l,r)}const t2=D({batchNorm3d_:qC});function e2(n,t,e,s,o,r){const i=N(n,"x","batchNorm"),a=N(t,"mean","batchNorm"),c=N(e,"variance","batchNorm");let l;o!=null&&(l=N(o,"scale","batchNorm"));let u;return s!=null&&(u=N(s,"offset","batchNorm")),v(i.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`),v(a.rank===4||a.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${a.rank}.`),v(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${c.rank}.`),l!=null&&v(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${l.rank}.`),u!=null&&v(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${u.rank}.`),Rc(i,a,c,u,l,r)}const n2=D({batchNorm4d_:e2});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function s2(n,t,e){const s=N(n,"x","bincount"),o=N(t,"weights","bincount");v(s.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${s.dtype}`),v(e>=0,()=>`size must be non-negative, but got ${e}.`),v(o.size===s.size||o.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${s.shape}, weights shape: ${o.shape}.`);const r={x:s,weights:o},i={size:e};return G.runKernel(au,r,i)}const o2=D({bincount_:s2});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function r2(n,t){let e=N(n,"broadcastTo","x");const s=e.shape;if(es(t),t.length<e.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${e.rank}.`);if(t.length>e.rank){const l=e.shape.slice();for(;l.length<t.length;)l.unshift(1);e=W(e,l)}const o=e.shape,r=Array.from(t);for(let l=t.length-1;l>=0;l--)if(o[l]===t[l])r[l]=1;else if(e.shape[l]!==1)throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${t}].`);if(r.map((l,u)=>l>1?u:-1).filter(l=>l>=0).length===0)return to(e);const a={x:e},c={reps:r};return G.runKernel(gi,a,c)}const Ni=D({broadcastTo_:r2});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function i2(n){const e={x:N(n,"x","ceil","float32")};return G.runKernel(Lr,e)}const a2=D({ceil_:i2});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function $c(n,t,e){es(n),e=e||Mo(t);const s={shape:n,value:t,dtype:e};return G.runKernel(Su,{},s)}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function c2(n,t,e){const s=N(n,"x","clipByValue");if(v(t<=e,()=>`Error in clip: min (${t}) must be less than or equal to max (${e}).`),t===e)return $c(s.shape,t,s.dtype);const o={x:s},r={clipValueMin:t,clipValueMax:e};return G.runKernel(Er,o,r)}const nn=D({clipByValue_:c2});function l2(n){return Xe(n,0)}const u2=D({concat1d_:l2});function d2(n,t){return Xe(n,t)}const h2=D({concat2d_:d2});function p2(n,t){return Xe(n,t)}const f2=D({concat3d_:p2});function m2(n,t){return Xe(n,t)}const g2=D({concat4d_:m2});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function b2(n,t,e,s,o="NHWC",r=[1,1],i){const a=N(n,"x","conv2d","float32"),c=N(t,"filter","conv2d","float32");let l=a,u=!1;a.rank===3&&(u=!0,l=W(a,[1,a.shape[0],a.shape[1],a.shape[2]])),v(l.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${l.rank}.`),v(c.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${c.rank}.`),ze("conv2d",s,i);const d=o==="NHWC"?l.shape[3]:l.shape[1];v(d===c.shape[2],()=>`Error in conv2d: depth of input (${d}) must match input depth for filter ${c.shape[2]}.`),v(Te(e,r),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${e} and dilations '${r}'`),v(no(r),()=>"Error in conv2D: Dilated rates should be larger than 0."),v(no(e),()=>"Error in conv2D: Strides should be larger than 0.");const h={x:l,filter:c},p={strides:e,pad:s,dataFormat:o,dilations:r,dimRoundingMode:i},f=G.runKernel(Ra,h,p);return u?W(f,[f.shape[1],f.shape[2],f.shape[3]]):f}const so=D({conv2d_:b2});function x2(n,t,e,s,o="NWC",r=1,i){const a=N(n,"x","conv1d"),c=N(t,"filter","conv1d");let l=a,u=!1;a.rank===2&&(u=!0,l=W(a,[1,a.shape[0],a.shape[1]])),v(l.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${l.rank}.`),v(c.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${c.rank}.`),ze("conv1d",s,i),v(l.shape[2]===c.shape[1],()=>`Error in conv1d: depth of input (${l.shape[2]}) must match input depth for filter ${c.shape[1]}.`),v(Te(e,r),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${e} and dilation '${r}'`),v(no(r),()=>"Error in conv1D: Dilated rates should be larger than 0."),v(no(e),()=>"Error in conv1D: Stride should be larger than 0."),v(o==="NWC",()=>`Error in conv1d: got dataFormat of ${o} but only NWC is currently supported.`);const d=W(c,[1,c.shape[0],c.shape[1],c.shape[2]]),h=W(l,[l.shape[0],1,l.shape[1],l.shape[2]]),g=so(h,d,[1,e],s,"NHWC",[1,r],i);return u?W(g,[g.shape[2],g.shape[3]]):W(g,[g.shape[0],g.shape[2],g.shape[3]])}const Lm=D({conv1d_:x2});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function y2(n,t,e,s,o,r="NHWC",i){v(n.length===t.rank,()=>`Length of inShape (${n.length}) and rank of dy (${t.rank}) must match`);let a=n,c=t,l=!1;t.rank===3&&(l=!0,c=W(t,[1,t.shape[0],t.shape[1],t.shape[2]]),a=[1,n[0],n[1],n[2]]),v(a.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${a.length}.`),v(c.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${c.rank}`),v(e.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${e.rank}`);const u=r==="NHWC"?a[3]:a[1],d=r==="NHWC"?c.shape[3]:c.shape[1];v(u===e.shape[2],()=>`Error in conv2dDerInput: depth of input (${u}) must match input depth for filter ${e.shape[2]}.`),v(d===e.shape[3],()=>`Error in conv2dDerInput: depth of output (${d}) must match output depth for filter ${e.shape[3]}.`),ze("conv2dDerInput",o,i);const h={dy:c,filter:e},p={strides:s,pad:o,dataFormat:r,dimRoundingMode:i,inputShape:a},f=G.runKernel($a,h,p);return l?W(f,[f.shape[1],f.shape[2],f.shape[3]]):f}const md=D({conv2DBackpropInput_:y2});function I2(n,t,e,s,o,r){const i=N(n,"x","conv2dTranspose"),a=N(t,"filter","conv2dTranspose");return md(e,i,a,s,o,"NHWC",r)}const Em=D({conv2dTranspose_:I2});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function w2(n,t,e,s,o="NDHWC",r=[1,1,1]){const i=N(n,"x","conv3d"),a=N(t,"filter","conv3d");let c=i,l=!1;i.rank===4&&(l=!0,c=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),v(c.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${c.rank}.`),v(a.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${a.rank}.`),v(c.shape[4]===a.shape[3],()=>`Error in conv3d: depth of input (${c.shape[4]}) must match input depth for filter ${a.shape[3]}.`),v(Te(e,r),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${e} and dilations '${r}'`),v(o==="NDHWC",()=>`Error in conv3d: got dataFormat of ${o} but only NDHWC is currently supported.`),v(no(r),()=>"Error in conv3D: Dilated rates should be larger than 0."),v(no(e),()=>"Error in conv3D: Strides should be larger than 0.");const u={x:c,filter:a},d={strides:e,pad:s,dataFormat:o,dilations:r},h=G.runKernel(Ga,u,d);return l?W(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}const C2=D({conv3d_:w2});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function v2(n,t,e,s,o){v(n.length===t.rank,()=>`Length of inShape (${n.length}) and rank of dy (${t.rank}) must match`);let r=n,i=t,a=!1;t.rank===4&&(a=!0,i=W(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),r=[1,n[0],n[1],n[2],n[3]]);const c=r[4],l=i.shape[4];v(r.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${r.length}.`),v(i.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`),v(e.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${e.rank}`),v(c===e.shape[3],()=>`Error in conv3dDerInput: depth of input (${c}) must match input depth for filter ${e.shape[3]}.`),v(l===e.shape[4],()=>`Error in conv3dDerInput: depth of output (${l}) must match output depth for filter ${e.shape[4]}.`);const u={dy:i,filter:e},d={pad:o,strides:s,inputShape:r},h=G.runKernel(hu,u,d);return a?W(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}const Dm=D({conv3DBackpropInput_:v2});function S2(n,t,e,s,o){const r=N(n,"x","conv3dTranspose"),i=N(t,"filter","conv3dTranspose");return Dm(e,r,i,s,o)}const k2=D({conv3dTranspose_:S2});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function T2(n){const e={x:N(n,"x","cos","float32")};return G.runKernel(Dr,e)}const gd=D({cos_:T2});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function N2(n){const e={x:N(n,"x","cosh","float32")};return G.runKernel(Wr,e)}const Wm=D({cosh_:N2});/**
 * @license
 * Copyright 2022 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function R2(n,t=0,e=!1,s=!1){const r={x:N(n,"x","cumprod")},i={axis:t,exclusive:e,reverse:s};return G.runKernel(pu,r,i)}const bd=D({cumprod_:R2});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function $2(n,t=0,e=!1,s=!1){const r={x:N(n,"x","cumsum")},i={axis:t,exclusive:e,reverse:s};return G.runKernel(La,r,i)}const Mm=D({cumsum_:$2});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function G2(n,t,e,s=!1){const o=N(n,"x","denseBincount"),r=N(t,"weights","denseBincount");v(o.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${o.dtype}`),v(o.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${o.rank}.`),v(e>=0,()=>`size must be non-negative, but got ${e}.`),v(r.size===o.size||r.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${o.shape}, weights shape: ${r.shape}.`);const i={x:o,weights:r},a={size:e,binaryOutput:s};return G.runKernel(mu,i,a)}const Vm=D({denseBincount_:G2});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function L2(n,t,e="NHWC"){const s=N(n,"x","depthToSpace","float32"),o=e==="NHWC"?s.shape[1]:s.shape[2],r=e==="NHWC"?s.shape[2]:s.shape[3],i=e==="NHWC"?s.shape[3]:s.shape[1];v(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`),v(o*t>=0,()=>`Negative dimension size caused by overflow when multiplying
    ${o} and ${t}  for depthToSpace with input shape
    ${s.shape}`),v(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying
    ${r} and ${t} for depthToSpace with input shape
        ${s.shape}`),v(i%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${i} for depthToSpace with input shape ${s.shape}`);const a={x:s},c={blockSize:t,dataFormat:e};return G.runKernel(gu,a,c)}const E2=D({depthToSpace_:L2});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function D2(n,t,e,s,o="NHWC",r=[1,1],i){const a=N(n,"x","depthwiseConv2d","float32"),c=N(t,"filter","depthwiseConv2d","float32");let l=a,u=!1;a.rank===3&&(u=!0,l=W(a,[1,a.shape[0],a.shape[1],a.shape[2]])),v(l.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${l.rank}.`),v(c.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${c.rank}.`);const d=o==="NHWC"?l.shape[3]:l.shape[1];v(d===c.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${d}) must match the inChannels dimension in filter ${c.shape[2]}.`),ze("depthwiseConv2d",s,i);const h={x:l,filter:c},p={strides:e,pad:s,dataFormat:o,dilations:r,dimRoundingMode:i},f=G.runKernel(Ea,h,p);return u?W(f,[f.shape[1],f.shape[2],f.shape[3]]):f}const xd=D({depthwiseConv2d_:D2});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function W2(n,t,e,s,o=[1,1],r="NHWC"){const i=N(n,"x","dilation2d"),a=N(t,"filter","dilation2d");v(i.rank===3||i.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`),v(a.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${a.rank}.`),v(r==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${r}`);let c=i,l=!1;i.rank===3&&(c=W(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=!0),v(c.shape[3]===a.shape[2],()=>`Error in dilation2d:  input and filter must have the same depth: ${c.shape[3]} vs ${a.shape[2]}`);const u={x:c,filter:a},d={strides:e,pad:s,dilations:o},h=G.runKernel(Da,u,d);return l?W(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const M2=D({dilation2d_:W2});/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Uo(n,t){const e=n.length,s=[];for(let o=0;o<e;o++){const r=e-1-o,i=n[r]||1;(t[t.length-1-o]||1)>1&&i===1&&s.unshift(r)}return s}function ce(n,t){const e=[];for(let s=0;s<t.length;s++){const o=n[n.length-s-1],r=t.length-s-1,i=t[r];(o==null||o===1&&i>1)&&e.unshift(r)}return e}function gt(n,t){const e=Math.max(n.length,t.length),s=new Array(e);for(let o=0;o<e;o++){let r=n[n.length-o-1];r==null&&(r=1);let i=t[t.length-o-1];if(i==null&&(i=1),r===1)s[e-o-1]=i;else if(i===1)s[e-o-1]=r;else if(r!==i){const a=`Operands could not be broadcast together with shapes ${n} and ${t}.`;throw Error(a)}else s[e-o-1]=r}return s}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function V2(n,t){let e=N(n,"a","equal","string_or_numeric"),s=N(t,"b","equal","string_or_numeric");[e,s]=te(e,s),gt(e.shape,s.shape);const o={a:e,b:s};return G.runKernel(Wa,o)}const Xn=D({equal_:V2});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function F2(n,t,e){const s=N(t,"a","where"),o=N(e,"b","where"),r=N(n,"condition","where","bool"),i=gt(gt(r.shape,s.shape),o.shape),a=Ni(r,i),c=Ni(s,i),l=Ni(o,i),u={condition:a,t:c,e:l};return G.runKernel(uc,u)}const Le=D({where_:F2});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function z2(n){const e={x:N(n,"x","zerosLike")};return G.runKernel(xc,e)}const St=D({zerosLike_:z2});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function X2(n,t){let e=N(n,"a","div"),s=N(t,"b","div");[e,s]=te(e,s);const o=dt(e,s),r=St(o),i=Xn(s,r);return Le(i,r,o)}const A2=D({divNoNan_:X2});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function P2(n,t){const e=N(n,"t1","dot"),s=N(t,"t2","dot");v((e.rank===1||e.rank===2)&&(s.rank===1||s.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${e.rank} and ${s.rank}.`);const o=e.rank===1?e.size:e.shape[1],r=s.rank===1?s.size:s.shape[0];if(v(o===r,()=>`Error in dot: inner dimensions of inputs must match, but got ${o} and ${r}.`),e.rank===1&&s.rank===1){const i=W(e,[1,-1]),a=W(s,[-1,1]),c=$t(i,a);return W(c,[])}else if(e.rank===1&&s.rank===2){const i=W(e,[1,-1]),a=W(s,[s.shape[0],s.shape[1]]),c=$t(i,a);return W(c,[c.size])}else if(e.rank===2&&s.rank===1){const i=W(s,[-1,1]),a=$t(e,i);return W(a,[a.size])}else{const i=W(s,[s.shape[0],s.shape[1]]);return $t(e,i)}}const O2=D({dot_:P2});/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function K2(n,...t){const e=t.map((o,r)=>N(o,`tensors${r}`,"einsum")),s={equation:n};return G.runKernel(wu,e,s)}const Ri=D({einsum_:K2});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Z2(n){const e={x:N(n,"x","elu","float32")};return G.runKernel(Vr,e)}const Gc=D({elu_:Z2});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function B2(n){let t=N(n,"x","erf");v(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=st(t,"float32"));const e={x:t};return G.runKernel(Fr,e)}const H2=D({erf_:B2});/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function yd(n,t){for(let e=0;e<n.length;++e)if(n[n.length-e-1]!==t-1-e)return!1;return!0}function Fm(n,t,e){const s=n.length+t.length,o=[];let r=0,i=0;for(let a=0;a<s;a++)e.indexOf(a)===-1?o.push(n[r++]):o.push(t[i++]);return o}function me(n,t){const e=[],s=n.length;for(let r=0;r<s;r++)t.indexOf(r)===-1&&e.push(n[r]);const o=t.map(r=>n[r]);return[e,o]}function re(n,t){const e=t.map(s=>1);return Fm(n,e,t)}function Ie(n,t,e){v(yd(t,e),()=>`${n} supports only inner-most axes for now. Got axes ${t} and rank-${e} input.`)}function Yt(n,t){if(yd(n,t))return null;const e=[];for(let s=0;s<t;++s)n.indexOf(s)===-1&&e.push(s);return n.forEach(s=>e.push(s)),e}function Cs(n){return n.map((t,e)=>[e,t]).sort((t,e)=>t[1]-e[1]).map(t=>t[0])}function ee(n,t){const e=[];for(let s=t-n;s<t;++s)e.push(s);return e}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function _2(n,t=null,e=!1){const o={x:N(n,"x","max")},r={reductionIndices:t,keepDims:e};return G.runKernel(Ha,o,r)}const Tn=D({max_:_2});/**
 * @license
 * Copyright 2020 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function U2(n,t=null,e=!1){const o={x:N(n,"x","min")},r={axis:t,keepDims:e};return G.runKernel(Qa,o,r)}const Lc=D({min_:U2});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Y2(n,t){let e=N(n,"base","pow"),s=N(t,"exp","pow");[e,s]=te(e,s);const o={a:e,b:s};return G.runKernel(qr,o)}const Yo=D({pow_:Y2});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Gt(n,t){if((hn(n)&&t!=="string"||Array.isArray(n))&&t!=="complex64")throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if(t==="string"&&hn(n)&&!(n instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Ci(n,[],[],t)}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Q2(n){const e={x:N(n,"x","sqrt","float32")};return G.runKernel(di,e)}const Ee=D({sqrt_:Q2});/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function J2(n){const t=N(n,"x","square"),e={};return G.runKernel("Square",{x:t},e)}const Bt=D({square_:J2});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function j2(n,t=null,e=!1){let s=N(n,"x","sum");s.dtype==="bool"&&(s=st(s,"int32"));const o={x:s},r={axis:t,keepDims:e};return G.runKernel(hc,o,r)}const ut=D({sum_:j2});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function q2(n,t="euclidean",e=null,s=!1){n=N(n,"x","norm");const o=zm(n,t,e);let r=o.shape;if(s){const i=It(e,n.shape);r=re(o.shape,i)}return W(o,r)}function zm(n,t,e=null){if(n.rank===0)return Ge(n);if(n.rank!==1&&e===null)return zm(W(n,[-1]),t,e);if(n.rank===1||typeof e=="number"||Array.isArray(e)&&e.length===1){if(t===1)return ut(Ge(n),e);if(t===1/0)return Tn(Ge(n),e);if(t===-1/0)return Lc(Ge(n),e);if(t==="euclidean"||t===2)return Ee(ut(Yo(Ge(n),Gt(2,"int32")),e));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(e)&&e.length===2){if(t===1)return Tn(ut(Ge(n),e[0]),e[1]-1);if(t===1/0)return Tn(ut(Ge(n),e[1]),e[0]);if(t===-1/0)return Lc(ut(Ge(n),e[1]),e[0]);if(t==="fro"||t==="euclidean")return Ee(ut(Bt(n),e));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${e}`)}const Ec=D({norm_:q2});/**
 * @license
 * Copyright 2022 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function tv(n,t=null,e=!1){return Ec(n,"euclidean",t,e)}const ev=D({euclideanNorm_:tv});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function nv(n){const e={x:N(n,"x","exp")};return G.runKernel(zr,e)}const An=D({exp_:nv});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function sv(n,t=0){const e=N(n,"x","expandDims","string_or_numeric");v(t<=e.rank,()=>"Axis must be <= rank of the tensor");const s={input:e},o={dim:t};return G.runKernel(Ma,s,o)}const Ae=D({expandDims_:sv});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function ov(n){const e={x:N(n,"x","expm1")};return G.runKernel(Xr,e)}const rv=D({expm1_:ov});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function iv(n,t){const e=N(n,"x","tile","string_or_numeric");v(e.rank===t.length,()=>`Error in transpose: rank of input ${e.rank} must match length of reps ${t}.`);const s={x:e},o={reps:t};return G.runKernel(gi,s,o)}const Nn=D({tile_:iv});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function av(n,t,e,s="float32"){t==null&&(t=n);const o=wt([n,t],s),r=n<=t?n:t;for(let a=0;a<r;++a)o.set(1,a,a);const i=W(o.toTensor(),[n,t]);if(e==null)return i;if(e.length===1)return Nn(Ae(i,0),[e[0],1,1]);if(e.length===2)return Nn(Ae(Ae(i,0),0),[e[0],e[1],1,1]);if(e.length===3)return Nn(Ae(Ae(Ae(i,0),0),0),[e[0],e[1],e[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${e.length}D.`)}const Xm=D({eye_:av});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function cv(n){const e={x:N(n,"x","floor","float32")};return G.runKernel(Ar,e)}const Dc=D({floor_:cv});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function lv(n,t,e=0,s=0){const o=N(n,"x","gather"),r=N(t,"indices","gather","int32"),i={x:o,indices:r},a={axis:e,batchDims:s};return G.runKernel(Fa,i,a)}const Id=D({gather_:lv});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function uv(n,t){let e=N(n,"a","greater","string_or_numeric"),s=N(t,"b","greater","string_or_numeric");[e,s]=te(e,s),gt(e.shape,s.shape);const o={a:e,b:s};return G.runKernel(za,o)}const sn=D({greater_:uv});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function dv(n,t){let e=N(n,"a","greaterEqual","string_or_numeric"),s=N(t,"b","greaterEqual","string_or_numeric");[e,s]=te(e,s),gt(e.shape,s.shape);const o={a:e,b:s};return G.runKernel(Or,o)}const oo=D({greaterEqual_:dv});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function hv(n){const e={input:N(n,"input","imag")};return G.runKernel(Nu,e)}const wd=D({imag_:hv});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function pv(n){const e={x:N(n,"x","isFinite")};return G.runKernel(Zr,e)}const fv=D({isFinite_:pv});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function mv(n){const e={x:N(n,"x","isInf")};return G.runKernel(Br,e)}const gv=D({isInf_:mv});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function bv(n){const e={x:N(n,"x","isNaN")};return G.runKernel(Hr,e)}const xv=D({isNaN_:bv});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function yv(n,t=.2){const s={x:N(n,"x","leakyRelu")},o={alpha:t};return G.runKernel(Xa,s,o)}const Cd=D({leakyRelu_:yv});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Iv(n,t){let e=N(n,"a","less","string_or_numeric"),s=N(t,"b","less","string_or_numeric");[e,s]=te(e,s),gt(e.shape,s.shape);const o={a:e,b:s};return G.runKernel(Aa,o)}const Wc=D({less_:Iv});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function wv(n,t){let e=N(n,"a","lessEqual","string_or_numeric"),s=N(t,"b","lessEqual","string_or_numeric");[e,s]=te(e,s),gt(e.shape,s.shape);const o={a:e,b:s};return G.runKernel(Pa,o)}const Qo=D({lessEqual_:wv});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Cv(n,t=5,e=1,s=1,o=.5){const r=N(n,"x","localResponseNormalization");v(r.rank===4||r.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
               rank ${r.rank}.`),v(Do(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let i=r,a=!1;r.rank===3&&(a=!0,i=W(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const c={x:i},l={depthRadius:t,bias:e,alpha:s,beta:o},u=G.runKernel(Ba,c,l);return a?W(u,[u.shape[1],u.shape[2],u.shape[3]]):u}const vv=D({localResponseNormalization_:Cv});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Sv(n){const e={x:N(n,"x","log","float32")};return G.runKernel(_r,e)}const Pn=D({log_:Sv});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function kv(n){const e={x:N(n,"x","log1p")};return G.runKernel(Ur,e)}const Am=D({log1p_:kv});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Tv(n,t){v(Ql(n),()=>"The f passed in variableGrads(f) must be a function"),v(t==null||Array.isArray(t)&&t.every(l=>l instanceof Tc),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const e=t!=null;if(!e){t=[];for(const l in G.registeredVariables)t.push(G.registeredVariables[l])}const s=e?t.filter(l=>!l.trainable):null,o=t.length;t=t.filter(l=>l.trainable),v(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${o} variables is trainable.`);const r=!0,{value:i,grads:a}=G.gradients(n,t,null,r);v(a.some(l=>l!=null),()=>"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()."),v(i.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${i.rank} tensor`);const c={};return t.forEach((l,u)=>{a[u]!=null&&(c[l.name]=a[u])}),s!=null&&s.forEach(l=>c[l.name]=null),{value:i,grads:c}}function Jo(n){return G.customGrad(n)}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Nv(n){const e={x:N(n,"x","neg")};return G.runKernel(ja,e)}const ne=D({neg_:Nv});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Rv(n){const e={x:N(n,"x","softplus")};return G.runKernel(ui,e)}const $i=D({softplus_:Rv});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function $v(n){const t=N(n,"x","logSigmoid");return Jo(s=>({value:ne($i(ne(s))),gradFunc:i=>E(i,_o(ne(s)))}))(t)}const Gv=D({logSigmoid_:$v});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Lv(n,t){let e=N(n,"a","sub"),s=N(t,"b","sub");[e,s]=te(e,s);const o={a:e,b:s};return G.runKernel(pi,o)}const pt=D({sub_:Lv});/**
 * @license
 * Copyright 2020 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Ev(n,t=-1){const e=N(n,"logits","logSoftmax");if(t===-1&&(t=e.rank-1),t!==e.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${e.rank} and axis was ${t}`);return Jo((o,r)=>{const a=Tn(o,t,!0),c=pt(o,a),l=pt(st(c,"float32"),Pn(ut(An(c),t,!0)));return r([l]),{value:l,gradFunc:(d,h)=>{const[p]=h,f=!0,m=An(p);return pt(d,E(ut(d,t,f),m))}}})(e)}const Pm=D({logSoftmax_:Ev});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Dv(n,t=null,e=!1){const s=N(n,"x","logSumExp"),o=It(t,s.shape),r=Tn(s,o,!0),i=pt(s,r),a=An(i),c=ut(a,o),l=Pn(c),u=Q(W(r,l.shape),l);if(e){const d=re(u.shape,o);return W(u,d)}return u}const Om=D({logSumExp_:Dv});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Wv(n,t){const e=N(n,"a","logicalAnd","bool"),s=N(t,"b","logicalAnd","bool");gt(e.shape,s.shape);const o={a:e,b:s};return G.runKernel(Oa,o)}const rs=D({logicalAnd_:Wv});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Mv(n){const e={x:N(n,"x","logicalNot","bool")};return G.runKernel(Ka,e)}const vd=D({logicalNot_:Mv});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Vv(n,t){const e=N(n,"a","logicalOr","bool"),s=N(t,"b","logicalOr","bool");gt(e.shape,s.shape);const o={a:e,b:s};return G.runKernel(Za,o)}const Km=D({logicalOr_:Vv});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Fv(n,t){const e=N(n,"a","logicalXor","bool"),s=N(t,"b","logicalXor","bool");return gt(e.shape,s.shape),rs(Km(n,t),vd(rs(n,t)))}const zv=D({logicalXor_:Fv});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Xv(n,t,e,s,o){const r=N(n,"x","maxPool"),i=1;let a=r,c=!1;r.rank===3&&(c=!0,a=W(r,[1,r.shape[0],r.shape[1],r.shape[2]])),v(a.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${a.rank}.`),v(Te(e,i),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${e} and dilations '${i}'`),ze("maxPool",s,o);const l={x:a},u={filterSize:t,strides:e,pad:s,dimRoundingMode:o},d=G.runKernel(_a,l,u);return c?W(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const Sd=D({maxPool_:Xv});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Av(n,t=[1,1,1],e,s,o,r="NDHWC"){const i=N(n,"x","maxPool3d");let a=i,c=!1;i.rank===4&&(c=!0,a=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),v(a.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${a.rank}.`),v(r==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${r}`),ze("maxPool3d",s,o);const l={x:a},u={filterSize:t,strides:e,pad:s,dimRoundingMode:o,dataFormat:r},d=G.runKernel(Ua,l,u);return c?W(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}const Pv=D({maxPool3d_:Av});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Ov(n,t){let e=N(n,"a","maximum"),s=N(t,"b","maximum");[e,s]=te(e,s),e.dtype==="bool"&&(e=st(e,"int32"),s=st(s,"int32")),gt(e.shape,s.shape);const o={a:e,b:s};return G.runKernel(Yr,o)}const vs=D({maximum_:Ov});/**
 * @license
 * Copyright 2020 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Kv(n,t=null,e=!1){const o={x:N(n,"x","mean")},r={axis:t,keepDims:e};return G.runKernel(Ya,o,r)}const ie=D({mean_:Kv});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function ge(n,t="float32"){if(es(n),t==="complex64"){const s=ge(n,"float32"),o=ge(n,"float32");return Ko(s,o)}const e=ke(Z(n),t);return G.makeTensor(e,n,t)}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Ss(n,t="float32"){if(es(n),t==="complex64"){const s=Ss(n,"float32"),o=ge(n,"float32");return Ko(s,o)}const e=jl(Z(n),t);return G.makeTensor(e,n,t)}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Zv(n,t){let e=N(n,"a","minimum"),s=N(t,"b","minimum");[e,s]=te(e,s),e.dtype==="bool"&&(e=st(e,"int32"),s=st(s,"int32")),gt(e.shape,s.shape);const o={a:e,b:s};return G.runKernel(Qr,o)}const Gi=D({minimum_:Zv});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Bv(n,t,e){v(e==="reflect"||e==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${e}.`);const s=N(n,"x","mirrorPad");if(s.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");v(t.length===s.rank,()=>`Padding doesn't match input. Must be ${s.rank}. Got ${t.length}.`);const o=e==="reflect"?1:0;for(let a=0;a<s.rank;a++)v(t[a].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),v(t[a][0]>=0&&t[a][0]<=s.shape[a]-o&&t[a][1]>=0&&t[a][1]<=s.shape[a]-o,()=>`Padding in dimension ${a} cannot be greater than or equal to ${s.shape[a]-o} or less than 0 for input of shape ${s.shape}`);const r={paddings:t,mode:e},i={x:s};return G.runKernel(Ja,i,r)}const Hv=D({mirrorPad_:Bv});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function _v(n,t){let e=N(n,"a","mod"),s=N(t,"b","mod");[e,s]=te(e,s);const o={a:e,b:s};return G.runKernel(Jr,o)}const Uv=D({mod_:_v});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Yv(n,t=null,e=!1){n=N(n,"x","moments");const s=It(t,n.shape),o=ie(n,s,e);let r=o.shape;e||(r=re(o.shape,s));const i=Bt(pt(st(n,"float32"),W(o,r))),a=ie(i,s,e);return{mean:o,variance:a}}const kd=D({moments_:Yv});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Qv(n,t){let e=N(n,"a","notEqual","string_or_numeric"),s=N(t,"b","notEqual","string_or_numeric");[e,s]=te(e,s),gt(e.shape,s.shape);const o={a:e,b:s};return G.runKernel(qa,o)}const Mc=D({notEqual_:Qv});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Jv(n,t,e=1,s=0,o="int32"){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const i={indices:N(n,"indices","oneHot","int32")},a={dtype:o,depth:t,onValue:e,offValue:s};return G.runKernel(ec,i,a)}const Zm=D({oneHot_:Jv});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function jv(n){const e={x:N(n,"x","onesLike")};return G.runKernel(tc,e)}const fn=D({onesLike_:jv});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function qv(n,t,e=0){const s=N(n,"x","pad");if(s.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const o={paddings:t,constantValue:e},r={x:s};return G.runKernel(sc,r,o)}const Td=D({pad_:qv});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function tS(n,t,e){const s=N(n,"x","spaceToBatchND");v(s.rank>=1+t.length,()=>`input rank ${s.rank} should be > than [blockShape] ${t.length}`),v(e.length===t.length,()=>`paddings.shape[0] ${e.length} must be equal to [blockShape] ${t.length}`),v(s.shape.reduce((i,a,c)=>c>0&&c<=t.length?i&&(a+e[c-1][0]+e[c-1][1])%t[c-1]===0:i,!0),()=>`input spatial dimensions ${s.shape.slice(1)} with paddings ${e.toString()} must be divisible by blockShapes ${t.toString()}`);const o={x:s},r={blockShape:t,paddings:e};return G.runKernel(pc,o,r)}const Nd=D({spaceToBatchND_:tS});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function eS(n,t,e,s,o,r,i){o==null&&(o=[1,1]),r==null&&(r=1),s===0&&(s="valid");const a=N(n,"x","maxPool");let c=a,l=!1;a.rank===3&&(l=!0,c=W(a,[1,a.shape[0],a.shape[1],a.shape[2]])),v(Te(r,o),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${r} and dilations '${o}'`);const u=pn(c.shape,t,r,o,s),d=[u.dilationHeight,u.dilationWidth];let h;s==="same"?h=sS([u.filterHeight,u.filterWidth],d):h=[[0,0],[0,0]];const p=d[0]===1&&d[1]===1,[f,m]=nS([u.inHeight,u.inWidth],d,h),g=p?s:"valid",b=p?c:Nd(c,d,f),I=(e==="avg"?()=>hd(b,t,r,g,i):()=>Sd(b,t,r,g,i))(),y=p?I:fd(I,d,m);return l?W(y,[y.shape[1],y.shape[2],y.shape[3]]):y}function nS(n,t,e){const s=e.map(u=>u[0]),o=e.map(u=>u[1]),r=n.concat(s,o),i=t.map((u,d)=>(u-r[d]%u)%u),a=o.map((u,d)=>u+i[d]),c=t.map((u,d)=>[s[d],a[d]]),l=t.map((u,d)=>[0,i[d]]);return[c,l]}function sS(n,t){const s=n.map((i,a)=>i+(i-1)*(t[a]-1)).map(i=>i-1),o=s.map(i=>Math.floor(i/2)),r=s.map((i,a)=>i-o[a]);return s.map((i,a)=>[o[a],r[a]])}const oS=D({pool_:eS});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function rS(n,t){const e=N(n,"x","prelu"),s=N(t,"alpha","prelu"),o={x:e,alpha:s};return G.runKernel(oc,o)}const Rd=D({prelu_:rS});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function iS(n,t=null,e=!1){let s=N(n,"x","prod");s.dtype==="bool"&&(s=st(s,"int32"));const o={x:s},r={axis:t,keepDims:e};return G.runKernel(rc,o,r)}const aS=D({prod_:iS});var $d={exports:{}};$d.exports,function(n){(function(t,e,s){function o(c){var l=this,u=a();l.next=function(){var d=2091639*l.s0+l.c*23283064365386963e-26;return l.s0=l.s1,l.s1=l.s2,l.s2=d-(l.c=d|0)},l.c=1,l.s0=u(" "),l.s1=u(" "),l.s2=u(" "),l.s0-=u(c),l.s0<0&&(l.s0+=1),l.s1-=u(c),l.s1<0&&(l.s1+=1),l.s2-=u(c),l.s2<0&&(l.s2+=1),u=null}function r(c,l){return l.c=c.c,l.s0=c.s0,l.s1=c.s1,l.s2=c.s2,l}function i(c,l){var u=new o(c),d=l&&l.state,h=u.next;return h.int32=function(){return u.next()*4294967296|0},h.double=function(){return h()+(h()*2097152|0)*11102230246251565e-32},h.quick=h,d&&(typeof d=="object"&&r(d,u),h.state=function(){return r(u,{})}),h}function a(){var c=4022871197,l=function(u){u=String(u);for(var d=0;d<u.length;d++){c+=u.charCodeAt(d);var h=.02519603282416938*c;c=h>>>0,h-=c,h*=c,c=h>>>0,h-=c,c+=h*4294967296}return(c>>>0)*23283064365386963e-26};return l}e&&e.exports?e.exports=i:s&&s.amd?s(function(){return i}):this.alea=i})(Zs,n,!1)}($d);var cS=$d.exports,Gd={exports:{}};Gd.exports,function(n){(function(t,e,s){function o(a){var c=this,l="";c.x=0,c.y=0,c.z=0,c.w=0,c.next=function(){var d=c.x^c.x<<11;return c.x=c.y,c.y=c.z,c.z=c.w,c.w^=c.w>>>19^d^d>>>8},a===(a|0)?c.x=a:l+=a;for(var u=0;u<l.length+64;u++)c.x^=l.charCodeAt(u)|0,c.next()}function r(a,c){return c.x=a.x,c.y=a.y,c.z=a.z,c.w=a.w,c}function i(a,c){var l=new o(a),u=c&&c.state,d=function(){return(l.next()>>>0)/4294967296};return d.double=function(){do var h=l.next()>>>11,p=(l.next()>>>0)/4294967296,f=(h+p)/(1<<21);while(f===0);return f},d.int32=l.next,d.quick=d,u&&(typeof u=="object"&&r(u,l),d.state=function(){return r(l,{})}),d}e&&e.exports?e.exports=i:s&&s.amd?s(function(){return i}):this.xor128=i})(Zs,n,!1)}(Gd);var lS=Gd.exports,Ld={exports:{}};Ld.exports,function(n){(function(t,e,s){function o(a){var c=this,l="";c.next=function(){var d=c.x^c.x>>>2;return c.x=c.y,c.y=c.z,c.z=c.w,c.w=c.v,(c.d=c.d+362437|0)+(c.v=c.v^c.v<<4^(d^d<<1))|0},c.x=0,c.y=0,c.z=0,c.w=0,c.v=0,a===(a|0)?c.x=a:l+=a;for(var u=0;u<l.length+64;u++)c.x^=l.charCodeAt(u)|0,u==l.length&&(c.d=c.x<<10^c.x>>>4),c.next()}function r(a,c){return c.x=a.x,c.y=a.y,c.z=a.z,c.w=a.w,c.v=a.v,c.d=a.d,c}function i(a,c){var l=new o(a),u=c&&c.state,d=function(){return(l.next()>>>0)/4294967296};return d.double=function(){do var h=l.next()>>>11,p=(l.next()>>>0)/4294967296,f=(h+p)/(1<<21);while(f===0);return f},d.int32=l.next,d.quick=d,u&&(typeof u=="object"&&r(u,l),d.state=function(){return r(l,{})}),d}e&&e.exports?e.exports=i:s&&s.amd?s(function(){return i}):this.xorwow=i})(Zs,n,!1)}(Ld);var uS=Ld.exports,Ed={exports:{}};Ed.exports,function(n){(function(t,e,s){function o(a){var c=this;c.next=function(){var u=c.x,d=c.i,h,p;return h=u[d],h^=h>>>7,p=h^h<<24,h=u[d+1&7],p^=h^h>>>10,h=u[d+3&7],p^=h^h>>>3,h=u[d+4&7],p^=h^h<<7,h=u[d+7&7],h=h^h<<13,p^=h^h<<9,u[d]=p,c.i=d+1&7,p};function l(u,d){var h,p=[];if(d===(d|0))p[0]=d;else for(d=""+d,h=0;h<d.length;++h)p[h&7]=p[h&7]<<15^d.charCodeAt(h)+p[h+1&7]<<13;for(;p.length<8;)p.push(0);for(h=0;h<8&&p[h]===0;++h);for(h==8?p[7]=-1:p[h],u.x=p,u.i=0,h=256;h>0;--h)u.next()}l(c,a)}function r(a,c){return c.x=a.x.slice(),c.i=a.i,c}function i(a,c){a==null&&(a=+new Date);var l=new o(a),u=c&&c.state,d=function(){return(l.next()>>>0)/4294967296};return d.double=function(){do var h=l.next()>>>11,p=(l.next()>>>0)/4294967296,f=(h+p)/(1<<21);while(f===0);return f},d.int32=l.next,d.quick=d,u&&(u.x&&r(u,l),d.state=function(){return r(l,{})}),d}e&&e.exports?e.exports=i:s&&s.amd?s(function(){return i}):this.xorshift7=i})(Zs,n,!1)}(Ed);var dS=Ed.exports,Dd={exports:{}};Dd.exports,function(n){(function(t,e,s){function o(a){var c=this;c.next=function(){var u=c.w,d=c.X,h=c.i,p,f;return c.w=u=u+1640531527|0,f=d[h+34&127],p=d[h=h+1&127],f^=f<<13,p^=p<<17,f^=f>>>15,p^=p>>>12,f=d[h]=f^p,c.i=h,f+(u^u>>>16)|0};function l(u,d){var h,p,f,m,g,b=[],x=128;for(d===(d|0)?(p=d,d=null):(d=d+"\0",p=0,x=Math.max(x,d.length)),f=0,m=-32;m<x;++m)d&&(p^=d.charCodeAt((m+32)%d.length)),m===0&&(g=p),p^=p<<10,p^=p>>>15,p^=p<<4,p^=p>>>13,m>=0&&(g=g+1640531527|0,h=b[m&127]^=p+g,f=h==0?f+1:0);for(f>=128&&(b[(d&&d.length||0)&127]=-1),f=127,m=4*128;m>0;--m)p=b[f+34&127],h=b[f=f+1&127],p^=p<<13,h^=h<<17,p^=p>>>15,h^=h>>>12,b[f]=p^h;u.w=g,u.X=b,u.i=f}l(c,a)}function r(a,c){return c.i=a.i,c.w=a.w,c.X=a.X.slice(),c}function i(a,c){a==null&&(a=+new Date);var l=new o(a),u=c&&c.state,d=function(){return(l.next()>>>0)/4294967296};return d.double=function(){do var h=l.next()>>>11,p=(l.next()>>>0)/4294967296,f=(h+p)/(1<<21);while(f===0);return f},d.int32=l.next,d.quick=d,u&&(u.X&&r(u,l),d.state=function(){return r(l,{})}),d}e&&e.exports?e.exports=i:s&&s.amd?s(function(){return i}):this.xor4096=i})(Zs,n,!1)}(Dd);var hS=Dd.exports,Wd={exports:{}};Wd.exports,function(n){(function(t,e,s){function o(a){var c=this,l="";c.next=function(){var d=c.b,h=c.c,p=c.d,f=c.a;return d=d<<25^d>>>7^h,h=h-p|0,p=p<<24^p>>>8^f,f=f-d|0,c.b=d=d<<20^d>>>12^h,c.c=h=h-p|0,c.d=p<<16^h>>>16^f,c.a=f-d|0},c.a=0,c.b=0,c.c=-1640531527,c.d=1367130551,a===Math.floor(a)?(c.a=a/4294967296|0,c.b=a|0):l+=a;for(var u=0;u<l.length+20;u++)c.b^=l.charCodeAt(u)|0,c.next()}function r(a,c){return c.a=a.a,c.b=a.b,c.c=a.c,c.d=a.d,c}function i(a,c){var l=new o(a),u=c&&c.state,d=function(){return(l.next()>>>0)/4294967296};return d.double=function(){do var h=l.next()>>>11,p=(l.next()>>>0)/4294967296,f=(h+p)/(1<<21);while(f===0);return f},d.int32=l.next,d.quick=d,u&&(typeof u=="object"&&r(u,l),d.state=function(){return r(l,{})}),d}e&&e.exports?e.exports=i:s&&s.amd?s(function(){return i}):this.tychei=i})(Zs,n,!1)}(Wd);var pS=Wd.exports,Bm={exports:{}};const fS=bw(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));(function(n){(function(t,e,s){var o=256,r=6,i=52,a="random",c=s.pow(o,r),l=s.pow(2,i),u=l*2,d=o-1,h;function p(y,w,C){var k=[];w=w==!0?{entropy:!0}:w||{};var S=b(g(w.entropy?[y,I(e)]:y??x(),3),k),T=new f(k),R=function(){for(var L=T.g(r),V=c,F=0;L<l;)L=(L+F)*o,V*=o,F=T.g(1);for(;L>=u;)L/=2,V/=2,F>>>=1;return(L+F)/V};return R.int32=function(){return T.g(4)|0},R.quick=function(){return T.g(4)/4294967296},R.double=R,b(I(T.S),e),(w.pass||C||function(L,V,F,X){return X&&(X.S&&m(X,T),L.state=function(){return m(T,{})}),F?(s[a]=L,V):L})(R,S,"global"in w?w.global:this==s,w.state)}function f(y){var w,C=y.length,k=this,S=0,T=k.i=k.j=0,R=k.S=[];for(C||(y=[C++]);S<o;)R[S]=S++;for(S=0;S<o;S++)R[S]=R[T=d&T+y[S%C]+(w=R[S])],R[T]=w;(k.g=function(L){for(var V,F=0,X=k.i,A=k.j,P=k.S;L--;)V=P[X=d&X+1],F=F*o+P[d&(P[X]=P[A=d&A+V])+(P[A]=V)];return k.i=X,k.j=A,F})(o)}function m(y,w){return w.i=y.i,w.j=y.j,w.S=y.S.slice(),w}function g(y,w){var C=[],k=typeof y,S;if(w&&k=="object")for(S in y)try{C.push(g(y[S],w-1))}catch{}return C.length?C:k=="string"?y:y+"\0"}function b(y,w){for(var C=y+"",k,S=0;S<C.length;)w[d&S]=d&(k^=w[d&S]*19)+C.charCodeAt(S++);return I(w)}function x(){try{var y;return h&&(y=h.randomBytes)?y=y(o):(y=new Uint8Array(o),(t.crypto||t.msCrypto).getRandomValues(y)),I(y)}catch{var w=t.navigator,C=w&&w.plugins;return[+new Date,t,C,t.screen,I(e)]}}function I(y){return String.fromCharCode.apply(0,y)}if(b(s.random(),e),n.exports){n.exports=p;try{h=fS}catch{}}else s["seed"+a]=p})(typeof self<"u"?self:Zs,[],Math)})(Bm);var mS=Bm.exports,gS=cS,bS=lS,xS=uS,yS=dS,IS=hS,wS=pS,ro=mS;ro.alea=gS,ro.xor128=bS,ro.xorwow=xS,ro.xorshift7=yS,ro.xor4096=IS,ro.tychei=wS;var Md=ro;/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class Hm{constructor(t,e,s,o,r){this.mean=t,this.stdDev=e,this.dtype=s,this.nextVal=NaN,this.truncated=o,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);const i=r||Math.random();this.random=Md.alea(i.toString())}nextValue(){if(!isNaN(this.nextVal)){const o=this.nextVal;return this.nextVal=NaN,o}let t,e,s=!1;for(;!s;){let o,r,i;do o=2*this.random()-1,r=2*this.random()-1,i=o*o+r*r;while(i>=1||i===0);const a=Math.sqrt(-2*Math.log(i)/i);t=this.mean+this.stdDev*o*a,e=this.mean+this.stdDev*r*a,(!this.truncated||this.isValidTruncated(t))&&(s=!0)}return(!this.truncated||this.isValidTruncated(e))&&(this.nextVal=this.convertValue(e)),this.convertValue(t)}convertValue(t){return this.dtype==null||this.dtype==="float32"?t:Math.round(t)}isValidTruncated(t){return t<=this.upper&&t>=this.lower}}class CS{constructor(t=0,e=1,s,o){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=t,this.range=e-t,this.dtype=s,o==null&&(o=Math.random()),typeof o=="number"&&(o=o.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${t} - ${e} <= 1 and dtype is not float`);this.random=Md.alea(o)}convertValue(t){return this.canReturnFloat()?t:Math.round(t)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function vS(n,t=0,e=1,s,o){if(es(n),s!=null&&s==="bool")throw new Error(`Unsupported data type ${s}`);const r=new Hm(t,e,s,!1,o),i=wt(n,s);for(let a=0;a<i.values.length;a++)i.values[a]=r.nextValue();return i.toTensor()}const SS=D({randomNormal_:vS});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function kS(n,t=0,e=1,s="float32",o){es(n);const r=wt(n,s),i=new CS(t,e,null,o);for(let a=0;a<r.values.length;a++)r.values[a]=i.nextValue();return r.toTensor()}const Li=D({randomUniform_:kS});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Ei(n,t,e=1,s="float32"){if(e===0)throw new Error("Cannot have a step of zero");const o={start:n,stop:t,step:e,dtype:s};return G.runKernel(Wu,{},o)}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function TS(n){const e={input:N(n,"input","real")};return G.runKernel(Mu,e)}const Vc=D({real_:TS});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function NS(n){const e={x:N(n,"x","reciprocal")};return G.runKernel(ti,e)}const RS=D({reciprocal_:NS});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function $S(n){const e={x:N(n,"x","relu")};return G.runKernel(ei,e)}const io=D({relu_:$S});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function GS(n){const e={x:N(n,"x","relu6")};return G.runKernel(ni,e)}const _m=D({relu6_:GS});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function LS(n,t){const s={x:N(n,"x","reverse")},o={dims:t};return G.runKernel(lc,s,o)}const ao=D({reverse_:LS});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function ES(n){const e={x:N(n,"x","round")};return G.runKernel(si,e)}const Um=D({round_:ES});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function DS(n){const e={x:N(n,"x","rsqrt","float32")};return G.runKernel(oi,e)}const Ym=D({rsqrt_:DS});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function WS(n){const e={x:N(n,"x","selu")};return G.runKernel(ri,e)}const Qm=D({selu_:WS});function MS(n,t,e,s,o,r=[1,1],i="NHWC"){const a=N(n,"x","separableConv2d"),c=N(t,"depthwiseFilter","separableConv2d"),l=N(e,"pointwiseFilter","separableConv2d");let u=a,d=!1;if(a.rank===3&&(d=!0,u=W(a,[1,a.shape[0],a.shape[1],a.shape[2]])),i==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");v(u.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${u.rank}.`),v(c.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${c.rank}.`),v(l.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${c.rank}.`),v(l.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter  must be 1, but got ${l.shape[0]}.`),v(l.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${l.shape[1]}.`);const h=c.shape[2],p=c.shape[3];v(l.shape[2]===h*p,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${h*p}, but got ${l.shape[2]}.`);const f=xd(u,c,s,o,i,r),g=so(f,l,1,"valid",i);return d?W(g,[g.shape[1],g.shape[2],g.shape[3]]):g}const Jm=D({separableConv2d_:MS});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function VS(n){const e={x:N(n,"x","sign")};return G.runKernel(ci,e)}const FS=D({sign_:VS});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function zS(n){const e={x:N(n,"x","sin","float32")};return G.runKernel(ii,e)}const jm=D({sin_:zS});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function XS(n){const e={x:N(n,"x","sinh")};return G.runKernel(ai,e)}const qm=D({sinh_:XS});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function AS(n,t,e){const s=N(n,"x","slice1d");return v(s.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`),Xt(s,[t],[e])}const Vd=D({slice1d_:AS});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function PS(n,t,e){const s=N(n,"x","slice2d");return v(s.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`),Xt(s,t,e)}const tg=D({slice2d_:PS});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function OS(n,t,e){const s=N(n,"x","slice3d");return v(s.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`),Xt(s,t,e)}const Fd=D({slice3d_:OS});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function KS(n,t,e){const s=N(n,"x","slice4d");return v(s.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`),Xt(s,t,e)}const Fc=D({slice4d_:KS});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function ZS(n,t=-1){const e=N(n,"logits","softmax","float32");if(t===-1&&(t=e.rank-1),t!==e.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${e.rank} and dim was ${t}`);const s={logits:e},o={dim:t};return G.runKernel(mc,s,o)}const zd=D({softmax_:ZS});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function BS(n){v(n.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${n.dtype}.`);const t={input:n};return G.runKernel(vu,t)}const eg=D({fft_:BS});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function HS(n){v(n.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${n.dtype}.`);const t={input:n};return G.runKernel(Tu,t)}const Xd=D({ifft_:HS});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function _S(n){const t=n.shape[n.shape.length-1],e=n.size/t;let s;if(t<=2){const o=W(n,[e,t]);s=Xd(o)}else{const o=[e,2*(t-1)],r=W(Vc(n),[e,t]),i=W(wd(n),[e,t]),a=ao(Xt(r,[0,1],[e,t-2]),1),c=E(ao(Xt(i,[0,1],[e,t-2]),1),Gt(-1)),l=Xe([r,a],1),u=Xe([i,c],1),d=W(Ko(l,u),[o[0],o[1]]);s=Xd(d)}if(s=Vc(s),n.rank===3&&n.shape[0]!==0){const o=s,r=n.shape[0];s=W(s,[r,s.shape[0]/r,s.shape[1]]),o.dispose()}return s}const US=D({irfft_:_S});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function YS(n,t,e=0){const o={x:N(n,"x","split")},r={numOrSizeSplits:t,axis:e};return G.runKernel(fc,o,r)}const on=D({split_:YS});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function QS(n,t){v(n.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${n.dtype}`);let e=n.shape[n.shape.length-1];const s=n.size/e;let o;if(t!=null&&t<e){const f=n.shape.map(g=>0),m=n.shape.map(g=>g);m[n.shape.length-1]=t,o=Xt(n,f,m),e=t}else if(t!=null&&t>e){const f=n.shape.map(m=>m);f[n.shape.length-1]=t-e,o=Xe([n,ge(f)],n.shape.length-1),e=t}else o=n;const r=St(o),i=W(Ko(o,r),[s,e]),a=eg(i),c=Math.floor(e/2)+1,l=Vc(a),u=wd(a),d=on(l,[c,e-c],l.shape.length-1),h=on(u,[c,e-c],u.shape.length-1),p=o.shape.slice();return p[o.shape.length-1]=c,W(Ko(d[0],h[0]),p)}const JS=D({rfft_:QS});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function jS(n,t){let e=N(n,"a","squaredDifference"),s=N(t,"b","squaredDifference");[e,s]=te(e,s),gt(e.shape,s.shape);const o={a:e,b:s},r={};return G.runKernel(hi,o,r)}const qS=D({squaredDifference_:jS});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function tk(n,t){const e=N(n,"x","squeeze","string_or_numeric");return W(e,fs(e.shape,t).newShape)}const Di=D({squeeze_:tk});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function ek(n,t=0){const e=gm(n,"tensors","stack","string_or_numeric");v(e.length>=1,()=>"Pass at least one tensor to tf.stack"),e.length>0&&v(t<=e[0].rank,()=>"Axis must be <= rank of the tensor");const s=e,o={axis:t};return G.runKernel(nc,s,o)}const On=D({stack_:ek});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function nk(n,t=0){const s={x:N(n,"x","step")},o={alpha:t};return G.runKernel(bi,s,o)}const Wi=D({step_:nk});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function sk(n,t,e,s,o=0,r=0,i=0,a=0,c=0){const u={x:N(n,"x","stridedSlice","string_or_numeric")},d={begin:t,end:e,strides:s,beginMask:o,endMask:r,ellipsisMask:i,newAxisMask:a,shrinkAxisMask:c};return G.runKernel(Au,u,d)}const ok=D({stridedSlice_:sk});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function rk(n){const e={x:N(n,"x","tan","float32")};return G.runKernel(fi,e)}const ik=D({tan_:rk});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Ue(n,t){_l(n);const e=wi(n,t);if(e.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Ci(n,null,e,t)}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Ad(n,t,e){if(_l(n),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");const s=wi(n,e);if(s.length!==2&&s.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Ci(n,t,s,e)}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function ak(n,t,e){if(_l(n),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");const s=wi(n,e);if(s.length!==3&&s.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Ci(n,t,s,e)}function ng(n,t,e){const s=t.rank>1?t.shape[t.rank-1]:1,o=t.rank>1?t.rank-1:1,r=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${e.shape}, indices.shape: ${t.shape}, shape: ${n}, sliceDim: ${s}, and batchDim: ${o}.`;if(e.rank<o)throw new Error(r+` update.rank < ${o}. `);if(n.length<s+(e.rank-o))throw new Error(r+` Output shape length < ${s+(e.rank-o)}`);if(e.rank!==o+n.length-s)throw new Error(r+` update.rank != ${o+n.length-s}`);for(let i=0;i<o;++i)if(e.shape[i]!==t.shape[i])throw new Error(r+` updates.shape[${i}] (${e.shape[i]}) != indices.shape[${i}] (${t.shape[i]}).`);for(let i=0;i<e.rank-o;++i)if(e.shape[i+o]!==n[i+s])throw new Error(r+` updates.shape[${i+o}] (${e.shape[i+o]}) != shape[${i+o}] (${n[i+o]})`)}function ck(n,t,e){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(n.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${n.rank}.`);if(t.dtype!=="int32")throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${t.dtype}`);if(e.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${e}`);if(e.length===0){if(t.size===0)throw new Error(`Indices specified for empty output. indices shape: ${t.shape}`);if(n.size===0)throw new Error(`Updates specified for empty output. updates shape: ${n.shape}`)}ng(e,t,n)}function co(n,t,e){const s=t.shape.length,o=s>1?t.shape[s-1]:1,r=e.length;let i=1;for(let d=o;d<r;++d)i*=e[d];const a=o<1?1:o,c=Z(t.shape)/a,l=[...ct(e.slice(0,o)),1],u=Z(e);return{sliceRank:o,numUpdates:c,sliceSize:i,strides:l,outputSize:u}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function lk(n,t=1,e=!0){const s=N(n,"x","topk");if(s.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");const o=s.shape[s.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>o)throw new Error(`'k' passed to topk() must be <= the last dimension (${o}) but got ${t}`);const r={x:s},i={k:t,sorted:e},[a,c]=G.runKernel(Pu,r,i);return{values:a,indices:c}}const uk=D({topk_:lk});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function dk(n,t=0,e=1,s,o){if(es(n),s!=null&&s==="bool")throw new Error("Unsupported data type $ { dtype }");const r=new Hm(t,e,s,!0,o),i=wt(n,s);for(let a=0;a<i.values.length;a++)i.values[a]=r.nextValue();return i.toTensor()}const sg=D({truncatedNormal_:dk});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function hk(n,t=0){const e=N(n,"x","unique","string_or_numeric");v(e.rank>0,()=>"The input tensor must be at least 1D");const s={x:e},o={axis:t},[r,i]=G.runKernel(Ku,s,o);return{values:r,indices:i}}const pk=D({unique_:hk});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function fk(n,t,e){const s=N(n,"x","unsortedSegmentSum"),o=N(t,"segmentIds","unsortedSegmentSum","int32");v(Do(e),()=>"numSegments must be of dtype int");const r={x:s,segmentIds:o},i={numSegments:e};return G.runKernel(bc,r,i)}const og=D({unsortedSegmentSum_:fk});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function mk(n,t=0){const e=N(n,"x","unstack","string_or_numeric");v(t>=-e.shape.length&&t<e.shape.length,()=>`Axis = ${t} is not in [-${e.shape.length}, ${e.shape.length})`);const s={value:e},o={axis:t};return G.runKernel(gc,s,o)}const lo=D({unstack_:mk});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function gk(n,t=!0,e,s){return G.makeVariable(n,t,e,s)}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function rg(n,t){const e=[];for(let r=0;r<t.length;r++)t[r]&&e.push(r);const s=wt(n,"int32"),o=wt([e.length,n.length],"int32");for(let r=0;r<e.length;r++){const i=s.indexToLoc(e[r]),a=r*n.length;o.values.set(i,a)}return o.toTensor()}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function bk(n,t,e){const s=N(n,"x","transpose");if(t==null&&(t=s.shape.map((i,a)=>a).reverse()),v(s.rank===t.length,()=>`Error in transpose: rank of input ${s.rank} must match length of perm ${t}.`),t.forEach(i=>{v(i>=0&&i<s.rank,()=>`All entries in 'perm' must be between 0 and ${s.rank-1} but got ${t}`)}),s.rank<=1)return s.clone();const o={x:s},r={perm:t};return s.dtype==="complex64"?M(()=>{let i=Vc(s),a=wd(s);return i=G.runKernel(zo,{x:i},r),a=G.runKernel(zo,{x:a},r),e&&(a=ne(a)),Ko(i,a)}):G.runKernel(zo,o,r)}const kt=D({transpose_:bk});/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function xk(n,t){if(t==null)return n.shape.slice();if(Rt(n.shape,t))return t;if(n.shape.length===t.length){const e=[];for(let s=0;s<n.shape.length;s++)t[s]==null&&n.shape[s]!=null?e.push(n.shape[s]):e.push(t[s]);return e}return t}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function yk(n,t,e,s){const o=N(n,"x","dropout");if(v(o.dtype==="float32",()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${o.dtype} tensor instead.`),v(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return n instanceof ae?o.clone():o;const r=xk(o,e),i=1-t,a=dt(Dc(Q(Li(r,0,1,"float32",s),i)),i);return E(o,a)}const Ik=D({dropout_:yk});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function wk(n,t,e,s,o,r="NHWC",i){let a=n;n.rank===3&&(a=W(n,[1,n.shape[0],n.shape[1],n.shape[2]]));let c=t;c.rank===3&&(c=W(t,[1,t.shape[0],t.shape[1],t.shape[2]])),v(a.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${a.shape}.`),v(c.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${c.shape}.`),v(e.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${e}.`);const l=r==="NHWC"?a.shape[3]:a.shape[1],u=r==="NHWC"?c.shape[3]:c.shape[1];v(l===e[2],()=>`Error in conv2dDerFilter: depth of input ${l}) must match input depth in filter (${e[2]}.`),v(u===e[3],()=>`Error in conv2dDerFilter: depth of dy (${u}) must match output depth for filter (${e[3]}).`),ze("conv2dDerFilter",o,i);const d={x:a,dy:c},h={strides:s,pad:o,dataFormat:r,dimRoundingMode:i,filterShape:e};return G.runKernel(uu,d,h)}const Pd=D({conv2DBackpropFilter_:wk});/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Od(n,t,e){if(e==null||e==="linear")return n;if(e==="relu")return E(n,Wi(t));throw new Error(`Cannot compute gradient for fused activation ${e}.`)}function Kd(n,t){let e=t;const s=ce(n.shape,t.shape);return s.length>0&&(e=ut(e,s)),W(e,n.shape)}function Zd(n,t,e,s){if(t==="linear")return n;if(t==="relu")return io(n);if(t==="elu")return Gc(n);if(t==="relu6")return _m(n);if(t==="prelu")return Rd(n,e);if(t==="leakyrelu")return Cd(n,s);if(t==="sigmoid")return _o(n);throw new Error(`Unknown fused activation ${t}.`)}const Bd=(n,t)=>!(n>0)||t==="linear";/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Ck({x:n,filter:t,strides:e,pad:s,dataFormat:o="NHWC",dilations:r=[1,1],dimRoundingMode:i,bias:a,activation:c="linear",preluActivationWeights:l,leakyreluAlpha:u}){if(c=c||"linear",Bd(G.state.gradientDepth,c)===!1){v(o==="NHWC",()=>`Error in fused conv2d: got dataFormat of ${o} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`);let C=so(n,t,e,s,o,r,i);return a!=null&&(C=Q(C,a)),Zd(C,c,l,u)}const d=N(n,"x","conv2d","float32"),h=N(t,"filter","conv2d","float32");let p=d,f=!1;d.rank===3&&(f=!0,p=W(d,[1,d.shape[0],d.shape[1],d.shape[2]])),v(p.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${p.rank}.`),v(h.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${h.rank}.`),ze("fused conv2d",s,i);const m=o==="NHWC"?p.shape[3]:p.shape[1];v(h.shape[2]===m,()=>`Error in conv2d: depth of input (${m}) must match input depth for filter ${h.shape[2]}.`),v(Te(e,r),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${e} and dilations '${r}'`);const g=ye(p.shape,h.shape,e,r,s,i);let b;a!=null&&(b=N(a,"bias","fused conv2d"),[b]=te(b,d),o==="NHWC"?gt(g.outShape,b.shape):(v(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}.`),v(b.shape.length===0||b.shape[0]===g.outChannels||b.shape[0]===1,()=>`Error in fused conv2d: bias shape (${b.shape}) is not compatible with the number of output channels (${g.outChannels})`)));let x;if(l!=null){const C=l.shape;if(v(C.length<=1||C.length===3,()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${C.length}.`),C.length===1)v(C[0]===1||C[0]===g.outChannels,()=>`Error in fused conv2d: PReLU activation weights (${C}) is not compatible with the number of output channels (${g.outChannels}).`);else if(C.length===3)try{gt(C,g.outShape)}catch{const S=`Error in fused conv2d: PReLU activation weights (${C}) is not compatible with the output shape of the conv2d (${g.outShape}).`;throw Error(S)}x=N(l,"prelu weights","fused conv2d")}const I=(C,k)=>{v(o==="NHWC",()=>`Error in gradient of fused conv2D: got dataFormat of ${o} but only NHWC is currently supported.`);const[S,T,R,L]=k,V=Od(C,R,c);v(eo(r),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`);const F=md(T.shape,V,S,e,s),X=Pd(T,V,S.shape,e,s),A=[F,X];if(L!=null){const P=Kd(L,V);A.push(P)}return A},y={x:p,filter:h,bias:b,preluActivationWeights:x},w={strides:e,pad:s,dataFormat:o,dilations:r,dimRoundingMode:i,activation:c,leakyreluAlpha:u};return a==null?Jo((k,S,T)=>{let R=G.runKernel(Ic,y,w);return T([S,k,R]),f&&(R=W(R,[R.shape[1],R.shape[2],R.shape[3]])),{value:R,gradFunc:I}})(p,h):Jo((k,S,T,R)=>{let L=G.runKernel(Ic,y,w);return R([S,k,L,T]),f&&(L=W(L,[L.shape[1],L.shape[2],L.shape[3]])),{value:L,gradFunc:I}})(p,h,b)}const vk=D({fusedConv2d_:Ck});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Sk(n,t,e,s,o,r=[1,1],i){let a=n;n.rank===3&&(a=W(n,[1,n.shape[0],n.shape[1],n.shape[2]]));let c=t;c.rank===3&&(c=W(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const l={x:a,dy:c},u={strides:s,pad:o,dimRoundingMode:i,dilations:r,filterShape:e};return G.runKernel(bu,l,u)}const kk=D({depthwiseConv2dNativeBackpropFilter_:Sk});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Tk(n,t,e,s,o,r=[1,1],i){let a=t,c=!1;t.rank===3&&(c=!0,a=W(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const l={dy:a,filter:e},u={strides:s,pad:o,dimRoundingMode:i,dilations:r,inputShape:n},d=G.runKernel(xu,l,u);return c?W(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const Nk=D({depthwiseConv2dNativeBackpropInput_:Tk});/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Rk({a:n,b:t,transposeA:e=!1,transposeB:s=!1,bias:o,activation:r="linear",preluActivationWeights:i,leakyreluAlpha:a=.2}){if(Bd(G.state.gradientDepth,r)===!1){let L=$t(n,t,e,s);return o!=null&&(L=Q(L,o)),Zd(L,r,i,a)}let c=N(n,"a","fused matMul"),l=N(t,"b","fused matMul");[c,l]=te(c,l);const u=e?c.shape[c.rank-2]:c.shape[c.rank-1],d=s?l.shape[l.rank-1]:l.shape[l.rank-2],h=e?c.shape[c.rank-1]:c.shape[c.rank-2],p=s?l.shape[l.rank-2]:l.shape[l.rank-1],f=c.shape.slice(0,-2),m=l.shape.slice(0,-2),g=Z(f),b=Z(m);v(u===d,()=>`Error in fused matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${c.shape} and ${l.shape} and transposeA=${e} and transposeB=${s} must match.`);const I=gt(c.shape.slice(0,-2),l.shape.slice(0,-2)).concat([h,p]),y=e?W(c,[g,u,h]):W(c,[g,h,u]),w=s?W(l,[b,p,d]):W(l,[b,d,p]);let C;o!=null&&(C=N(o,"bias","fused matMul"),[C]=te(C,c),gt(I,C.shape));let k;i!=null&&(k=N(i,"prelu weights","fused matMul"));const S=(L,V)=>{const[F,X,A,P]=V,B=Od(W(L,A.shape),A,r);let K,H;if(!e&&!s?(K=$t(B,X,!1,!0),H=$t(F,B,!0,!1)):!e&&s?(K=$t(B,X,!1,!1),H=$t(B,F,!0,!1)):e&&!s?(K=$t(X,B,!1,!0),H=$t(F,B,!1,!1)):(K=$t(X,B,!0,!0),H=$t(B,F,!0,!0)),o!=null){const U=Kd(P,B);return[K,H,U]}else return[K,H]},T={a:y,b:w,bias:C,preluActivationWeights:k},R={transposeA:e,transposeB:s,activation:r,leakyreluAlpha:a};return o==null?Jo((V,F,X)=>{const A=G.runKernel(yc,T,R);return X([V,F,A]),{value:W(A,I),gradFunc:S}})(y,w):Jo((V,F,X,A)=>{const P=G.runKernel(yc,T,R);return A([V,F,P,X]),{value:W(P,I),gradFunc:S}})(y,w,C)}const ig=D({fusedMatMul_:Rk});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function $k(n,t,e,s,o="bilinear",r=0){const i=N(n,"image","cropAndResize"),a=N(t,"boxes","cropAndResize","float32"),c=N(e,"boxInd","cropAndResize","int32"),l=a.shape[0];v(i.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`),v(a.rank===2&&a.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${l},4] but had shape ${a.shape}.`),v(c.rank===1&&c.shape[0]===l,()=>`Error in cropAndResize: boxInd must be have size [${l}] but had shape ${a.shape}.`),v(s.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`),v(s[0]>=1&&s[1]>=1,()=>`cropSize must be atleast [1,1], but was ${s}`),v(o==="bilinear"||o==="nearest",()=>`method must be bilinear or nearest, but was ${o}`);const u={image:i,boxes:a,boxInd:c},d={method:o,extrapolationValue:r,cropSize:s};return G.runKernel(fu,u,d)}const Gk=D({cropAndResize_:$k});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Lk(n){const t=N(n,"image","flipLeftRight","float32");v(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);const e={image:t};return G.runKernel(ku,e,{})}const Ek=D({flipLeftRight_:Lk});/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Dk(n){const t=N(n,"image","grayscaleToRGB"),e=t.rank-1,s=t.shape[e];v(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),v(s===1,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${s}.`);const o=new Array(t.rank);return o.fill(1,0,e),o[e]=3,Nn(t,o)}const Wk=D({grayscaleToRGB_:Dk});/**
 * @license
 * Copyright 2023 Google LLC.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Mk(n){const t=N(n,"image","RGBToGrayscale"),e=t.rank-1,s=t.shape[e];v(t.rank>=2,()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${t.rank}.`),v(s===3,()=>`Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${s}.`);const o=t.dtype,r=st(t,"float32"),i=Ue([.2989,.587,.114]);let a;switch(t.rank){case 2:a=Ri("ij,j->i",r,i);break;case 3:a=Ri("ijk,k->ij",r,i);break;case 4:a=Ri("ijkl,l->ijk",r,i);break;case 5:a=Ri("ijklm,m->ijkl",r,i);break;case 6:a=Ri("ijklmn,n->ijklm",r,i);break;default:throw new Error("Not a valid tensor rank.")}return a=Ae(a,-1),st(a,o)}const Vk=D({rgbToGrayscale_:Mk});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Fk(n,t,e=0,s=.5){const o=N(n,"image","rotateWithOffset","float32");v(o.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${o.rank}.`);const r={image:o},i={radians:t,fillValue:e,center:s};return G.runKernel(Bu,r,i)}const zk=D({rotateWithOffset_:Fk});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function jo(n,t,e,s,o,r){s==null&&(s=.5),o==null&&(o=Number.NEGATIVE_INFINITY),r==null&&(r=0);const i=n.shape[0];return e=Math.min(e,i),v(0<=s&&s<=1,()=>`iouThreshold must be in [0, 1], but was '${s}'`),v(n.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${n.rank}'`),v(n.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${n.shape[1]}`),v(t.rank===1,()=>"scores must be a 1D tensor"),v(t.shape[0]===i,()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`),v(0<=r&&r<=1,()=>`softNmsSigma must be in [0, 1], but was '${r}'`),{maxOutputSize:e,iouThreshold:s,scoreThreshold:o,softNmsSigma:r}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Xk(n,t,e,s=.5,o=Number.NEGATIVE_INFINITY){const r=N(n,"boxes","nonMaxSuppression","float32"),i=N(t,"scores","nonMaxSuppression","float32"),a=jo(r,i,e,s,o);e=a.maxOutputSize,s=a.iouThreshold,o=a.scoreThreshold;const c={maxOutputSize:e,iouThreshold:s,scoreThreshold:o};return G.runKernel(Lu,{boxes:r,scores:i},c)}const Ak=D({nonMaxSuppression_:Xk});/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Pk(n,t,e){const s=Ok(n,t,e),o=s<0?-(s+1):s;n.splice(o,0,t)}function Ok(n,t,e){return Zk(n,t,e||Kk)}function Kk(n,t){return n>t?1:n<t?-1:0}function Zk(n,t,e){let s=0,o=n.length,r=0,i=!1;for(;s<o;){r=s+(o-s>>>1);const a=e(t,n[r]);a>0?s=r+1:(o=r,i=!a)}return i?s:-s-1}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Hd(n,t,e,s,o){return Yd(n,t,e,s,o,0)}function _d(n,t,e,s,o,r){return Yd(n,t,e,s,o,0,!1,r,!0)}function Ud(n,t,e,s,o,r){return Yd(n,t,e,s,o,r,!0)}function Yd(n,t,e,s,o,r,i=!1,a=!1,c=!1){const l=[];for(let g=0;g<t.length;g++)t[g]>o&&l.push({score:t[g],boxIndex:g,suppressBeginIndex:0});l.sort(ag);const u=r>0?-.5/r:0,d=[],h=[];for(;d.length<e&&l.length>0;){const g=l.pop(),{score:b,boxIndex:x,suppressBeginIndex:I}=g;if(b<o)break;let y=!1;for(let w=d.length-1;w>=I;--w){const C=Bk(n,x,d[w]);if(C>=s){y=!0;break}if(g.score=g.score*Hk(s,u,C),g.score<=o)break}g.suppressBeginIndex=d.length,y||(g.score===b?(d.push(x),h.push(g.score)):g.score>o&&Pk(l,g,ag))}const p=d.length,f=e-p;a&&f>0&&(d.push(...new Array(f).fill(0)),h.push(...new Array(f).fill(0)));const m={selectedIndices:d};return i&&(m.selectedScores=h),c&&(m.validOutputs=p),m}function Bk(n,t,e){const s=n.subarray(t*4,t*4+4),o=n.subarray(e*4,e*4+4),r=Math.min(s[0],s[2]),i=Math.min(s[1],s[3]),a=Math.max(s[0],s[2]),c=Math.max(s[1],s[3]),l=Math.min(o[0],o[2]),u=Math.min(o[1],o[3]),d=Math.max(o[0],o[2]),h=Math.max(o[1],o[3]),p=(a-r)*(c-i),f=(d-l)*(h-u);if(p<=0||f<=0)return 0;const m=Math.max(r,l),g=Math.max(i,u),b=Math.min(a,d),x=Math.min(c,h),I=Math.max(b-m,0)*Math.max(x-g,0);return I/(p+f-I)}function Hk(n,t,e){const s=Math.exp(t*e*e);return e<=n?s:0}function ag(n,t){return n.score-t.score||n.score===t.score&&t.boxIndex-n.boxIndex}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */async function _k(n,t,e,s=.5,o=Number.NEGATIVE_INFINITY){const r=N(n,"boxes","nonMaxSuppressionAsync"),i=N(t,"scores","nonMaxSuppressionAsync"),a=jo(r,i,e,s,o);e=a.maxOutputSize,s=a.iouThreshold,o=a.scoreThreshold;const c=await Promise.all([r.data(),i.data()]),l=c[0],u=c[1],{selectedIndices:d}=Hd(l,u,e,s,o);return r!==n&&r.dispose(),i!==t&&i.dispose(),Ue(d,"int32")}const Uk=_k;/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Yk(n,t,e,s=.5,o=Number.NEGATIVE_INFINITY,r=0){const i=N(n,"boxes","nonMaxSuppression"),a=N(t,"scores","nonMaxSuppression"),c=jo(i,a,e,s,o,r);e=c.maxOutputSize,s=c.iouThreshold,o=c.scoreThreshold,r=c.softNmsSigma;const l={boxes:i,scores:a},u={maxOutputSize:e,iouThreshold:s,scoreThreshold:o,softNmsSigma:r},d=G.runKernel(Du,l,u);return{selectedIndices:d[0],selectedScores:d[1]}}const Qk=D({nonMaxSuppressionWithScore_:Yk});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */async function Jk(n,t,e,s=.5,o=Number.NEGATIVE_INFINITY,r=0){const i=N(n,"boxes","nonMaxSuppressionAsync"),a=N(t,"scores","nonMaxSuppressionAsync"),c=jo(i,a,e,s,o,r);e=c.maxOutputSize,s=c.iouThreshold,o=c.scoreThreshold,r=c.softNmsSigma;const l=await Promise.all([i.data(),a.data()]),u=l[0],d=l[1],{selectedIndices:h,selectedScores:p}=Ud(u,d,e,s,o,r);return i!==n&&i.dispose(),a!==t&&a.dispose(),{selectedIndices:Ue(h,"int32"),selectedScores:Ue(p)}}const jk=Jk;/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function qk(n,t,e,s=.5,o=Number.NEGATIVE_INFINITY,r=!1){const i=N(n,"boxes","nonMaxSuppression"),a=N(t,"scores","nonMaxSuppression"),c=jo(i,a,e,s,o,null),l=c.maxOutputSize,u=c.iouThreshold,d=c.scoreThreshold,h={boxes:i,scores:a},p={maxOutputSize:l,iouThreshold:u,scoreThreshold:d,padToMaxOutputSize:r},f=G.runKernel(Eu,h,p);return{selectedIndices:f[0],validOutputs:f[1]}}const tT=D({nonMaxSuppressionPadded_:qk});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */async function eT(n,t,e,s=.5,o=Number.NEGATIVE_INFINITY,r=!1){const i=N(n,"boxes","nonMaxSuppressionAsync"),a=N(t,"scores","nonMaxSuppressionAsync"),c=jo(i,a,e,s,o,null),l=c.maxOutputSize,u=c.iouThreshold,d=c.scoreThreshold,[h,p]=await Promise.all([i.data(),a.data()]),{selectedIndices:f,validOutputs:m}=_d(h,p,l,u,d,r);return i!==n&&i.dispose(),a!==t&&a.dispose(),{selectedIndices:Ue(f,"int32"),validOutputs:Gt(m,"int32")}}const nT=eT;/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function sT(n,t,e=!1,s=!1){const o=N(n,"images","resizeBilinear");v(o.rank===3||o.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${o.rank}.`),v(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),v(s===!1||e===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let r=o,i=!1;o.rank===3&&(i=!0,r=W(o,[1,o.shape[0],o.shape[1],o.shape[2]]));const a={images:r},c={alignCorners:e,halfPixelCenters:s,size:t},l=G.runKernel(cc,a,c);return i?W(l,[l.shape[1],l.shape[2],l.shape[3]]):l}const cg=D({resizeBilinear_:sT});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function oT(n,t,e=!1,s=!1){const o=N(n,"images","resizeNearestNeighbor");v(o.rank===3||o.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${o.rank}.`),v(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),v(o.dtype==="float32"||o.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),v(s===!1||e===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let r=o,i=!1;o.rank===3&&(i=!0,r=W(o,[1,o.shape[0],o.shape[1],o.shape[2]]));const a={images:r},c={alignCorners:e,halfPixelCenters:s,size:t},l=G.runKernel(ac,a,c);return i?W(l,[l.shape[1],l.shape[2],l.shape[3]]):l}const lg=D({resizeNearestNeighbor_:oT});/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function rT(n,t="binary",e=!1,s=.5){const o=N(n,"image","threshold"),r=.2989,i=.587,a=.114,c=o.shape[0]*o.shape[1];let l=E(Ue([s]),255),u,d,h,p;if(v(o.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${o.rank}.`),v(o.shape[2]===3||o.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${o.shape[2]}.`),v(o.dtype==="int32"||o.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${o.dtype}.`),v(t==="otsu"||t==="binary",()=>`Method must be binary or otsu, but was ${t}`),o.shape[2]===3){[u,d,h]=on(o,[1,1,1],-1);const g=E(u,r),b=E(d,i),x=E(h,a);p=Q(Q(g,b),x)}else p=n;if(t==="otsu"){const g=o2(st(Um(p),"int32"),tn([]),256);l=iT(g,c)}const f=e?Qo(p,l):sn(p,l);return st(E(f,255),"int32")}function iT(n,t){let e=Ue([-1]),s=Ue([0]),o=Ue([0]),r,i,a,c,l,u;for(let d=0;d<n.size-1;d++){r=Xt(n,0,d+1),i=Xt(n,d+1),l=dt(ut(r),t),u=dt(ut(i),t);const h=ut(E(r,Ei(0,r.size)));a=dt(h,ut(r));const p=$c(i.shape,r.size),f=Q(Ei(0,i.size),p),m=E(i,f);c=dt(ut(m),ut(i));const g=pt(a,c),b=pt(a,c),x=E(l,u);o=E(E(x,g),b);const I=sn(o,s);s=Le(I,o,s),e=Le(I,Ue([d]),e)}return e}const aT=D({threshold_:rT});/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function cT(n,t,e="nearest",s="constant",o=0,r){const i=N(n,"image","transform","float32"),a=N(t,"transforms","transform","float32");v(i.rank===4,()=>`Error in transform: image must be rank 4,but got rank ${i.rank}.`),v(a.rank===2&&(a.shape[0]===i.shape[0]||a.shape[0]===1)&&a.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),v(r==null||r.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${r}.`);const c={image:i,transforms:a},l={interpolation:e,fillMode:s,fillValue:o,outputShape:r};return G.runKernel(Ou,c,l)}const lT=D({transform_:cT});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function uT(n,t,e){const s=N(n,"a","bandPart");v(s.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${s.rank}.`);const o=s.shape,[r,i]=s.shape.slice(-2);let a,c;typeof t=="number"?(v(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),v(t<=r,()=>`bandPart(): numLower (${t}) must not be greater than the number of rows (${r}).`),a=N(t<0?r:t,"numLower","bandPart")):(v(t.dtype==="int32",()=>"bandPart(): numLower's dtype must be an int32."),a=Le(Wc(t,0),r,Gi(t,r))),typeof e=="number"?(v(e%1===0,()=>`bandPart(): numUpper must be an integer, got ${e}.`),v(e<=i,()=>`bandPart(): numUpper (${e}) must not be greater than the number of columns (${i}).`),c=N(e<0?i:e,"numUpper","bandPart")):(v(e.dtype==="int32",()=>"bandPart(): numUpper's dtype must be an int32."),c=Le(Wc(e,0),i,Gi(e,i)));const l=W(Ei(0,r,1,"int32"),[-1,1]),u=Ei(0,i,1,"int32"),d=pt(l,u),h=rs(Qo(d,a),oo(d,ne(c))),p=ge([r,i],s.dtype);return W(On(lo(W(s,[-1,r,i])).map(f=>Le(h,f,p))),o)}const dT=D({bandPart_:uT});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function hT(n){let t;if(Array.isArray(n)){t=!1,v(n!=null&&n.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");const o=n[0].shape[0];for(let r=1;r<n.length;++r)v(n[r].shape[0]===o,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${n[r].shape[0]} vs. ${o})`)}else t=!0,n=on(n,n.shape[0],0).map(o=>Di(o,[0]));v(n.length<=n[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${n.length}) exceeds number of dimensions (${n[0].shape[0]}).`);const e=[],s=n;for(let o=0;o<n.length;++o)e.push(G.tidy(()=>{let r=s[o];if(o>0)for(let i=0;i<o;++i){const a=E(ut(E(e[i],r)),e[i]);r=pt(r,a)}return dt(r,Ec(r,"euclidean"))}));return t?On(e,0):e}const pT=D({gramSchmidt_:hT});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function fT(n,t=!1){if(v(n.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${n.rank}`),n.rank===2)return ug(n,t);{const e=n.shape.slice(0,n.shape.length-2).reduce((c,l)=>c*l),s=lo(W(n,[e,n.shape[n.shape.length-2],n.shape[n.shape.length-1]]),0),o=[],r=[];s.forEach(c=>{const[l,u]=ug(c,t);o.push(l),r.push(u)});const i=W(On(o,0),n.shape),a=W(On(r,0),n.shape);return[i,a]}}function ug(n,t=!1){return G.tidy(()=>{v(n.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${n.shape.length}D Tensor.`);const e=n.shape[0],s=n.shape[1];let o=Xm(e),r=to(n);const i=Ad([[1]],[1,1]);let a=to(i);const c=e>=s?s:e;for(let l=0;l<c;++l){const u=r,d=a,h=o;[a,r,o]=G.tidy(()=>{const p=Xt(r,[l,l],[e-l,1]),f=Ec(p),m=Xt(r,[l,l],[1,1]),g=Le(sn(m,0),Ad([[-1]]),Ad([[1]])),b=pt(m,E(g,f)),x=dt(p,b);x.shape[0]===1?a=to(i):a=Xe([i,Xt(x,[1,0],[x.shape[0]-1,x.shape[1]])],0);const I=ne(dt($t(g,b),f)),y=Xt(r,[l,0],[e-l,s]),w=E(I,a),C=kt(a);if(l===0)r=pt(y,$t(w,$t(C,y)));else{const T=pt(y,$t(w,$t(C,y)));r=Xe([Xt(r,[0,0],[l,s]),T],0)}const k=kt(w),S=Xt(o,[0,l],[e,o.shape[1]-l]);if(l===0)o=pt(S,$t($t(S,a),k));else{const T=pt(S,$t($t(S,a),k));o=Xe([Xt(o,[0,0],[e,l]),T],1)}return[a,r,o]}),vt([u,d,h])}return!t&&e>s&&(o=Xt(o,[0,0],[e,s]),r=Xt(r,[0,0],[s,s])),[o,r]})}const mT=D({qr_:fT});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const is={flipLeftRight:Ek,grayscaleToRGB:Wk,resizeNearestNeighbor:lg,resizeBilinear:cg,rgbToGrayscale:Vk,rotateWithOffset:zk,cropAndResize:Gk,nonMaxSuppression:Ak,nonMaxSuppressionAsync:Uk,nonMaxSuppressionWithScore:Qk,nonMaxSuppressionWithScoreAsync:jk,nonMaxSuppressionPadded:tT,nonMaxSuppressionPaddedAsync:nT,threshold:aT,transform:lT},gT={bandPart:dT,gramSchmidt:pT,qr:mT};/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const bT=new Map,xT=new Map;class qo{getClassName(){return this.constructor.className}static fromConfig(t,e){return new t(e)}}class mn{constructor(){this.classNameMap={}}static getMap(){return mn.instance==null&&(mn.instance=new mn),mn.instance}static register(t){mn.getMap().classNameMap[t.className]=[t,t.fromConfig]}}function _(n,t,e){v(n.className!=null,()=>"Class being registered does not have the static className property defined."),v(typeof n.className=="string",()=>"className is required to be a string, but got type "+typeof n.className),v(n.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),typeof t>"u"&&(t="Custom"),typeof e>"u"&&(e=n.className);const s=e,o=t+">"+s;return mn.register(n),bT.set(o,n),xT.set(n,o),n}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class ks extends qo{minimize(t,e=!1,s){const{value:o,grads:r}=this.computeGradients(t,s);if(s!=null){const i=s.map(a=>({name:a.name,tensor:r[a.name]}));this.applyGradients(i)}else this.applyGradients(r);return vt(r),e?o:(o.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(t,e){return Tv(t,e)}dispose(){this.iterations_!=null&&vt(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Gt(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(t){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(t){return this.iterations_=(await t[0].tensor.data())[0],t.slice(1)}}Object.defineProperty(ks,Symbol.hasInstance,{value:n=>n.minimize!=null&&n.computeGradients!=null&&n.applyGradients!=null});/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class dg extends ks{static get className(){return"Adadelta"}constructor(t,e,s=null){super(),this.learningRate=t,this.rho=e,this.epsilon=s,this.accumulatedGrads=[],this.accumulatedUpdates=[],s==null&&(this.epsilon=G.backend.epsilon())}applyGradients(t){(Array.isArray(t)?t.map(s=>s.name):Object.keys(t)).forEach((s,o)=>{const r=G.registeredVariables[s],i=!1;this.accumulatedGrads[o]==null&&(this.accumulatedGrads[o]={originalName:`${s}/accum_grad`,variable:M(()=>St(r).variable(i))}),this.accumulatedUpdates[o]==null&&(this.accumulatedUpdates[o]={originalName:`${s}/accum_var`,variable:M(()=>St(r).variable(i))});const a=Array.isArray(t)?t[o].tensor:t[s];if(a==null)return;const c=this.accumulatedGrads[o].variable,l=this.accumulatedUpdates[o].variable;M(()=>{const u=Q(E(c,this.rho),E(Bt(a),1-this.rho)),d=E(dt(Ee(Q(l,this.epsilon)),Ee(Q(c,this.epsilon))),a),h=Q(E(l,this.rho),E(Bt(d),1-this.rho));c.assign(u),l.assign(h);const p=Q(E(d,-this.learningRate),r);r.assign(p)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(vt(this.accumulatedGrads.map(t=>t.variable)),vt(this.accumulatedUpdates.map(t=>t.variable)))}async getWeights(){const t=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(t.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(t){t=await this.extractIterations(t);const e=t.length/2,s=!1;this.accumulatedGrads=t.slice(0,e).map(o=>({originalName:o.name,variable:o.tensor.variable(s)})),this.accumulatedUpdates=t.slice(e,e*2).map(o=>({originalName:o.name,variable:o.tensor.variable(s)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(t,e){return new t(e.learningRate,e.rho,e.epsilon)}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class hg extends ks{static get className(){return"Adagrad"}constructor(t,e=.1){super(),this.learningRate=t,this.initialAccumulatorValue=e,this.accumulatedGrads=[]}applyGradients(t){(Array.isArray(t)?t.map(s=>s.name):Object.keys(t)).forEach((s,o)=>{const r=G.registeredVariables[s];this.accumulatedGrads[o]==null&&(this.accumulatedGrads[o]={originalName:`${s}/accumulator`,variable:M(()=>$c(r.shape,this.initialAccumulatorValue).variable(!1))});const i=Array.isArray(t)?t[o].tensor:t[s];if(i==null)return;const a=this.accumulatedGrads[o].variable;M(()=>{const c=Q(a,Bt(i));a.assign(c);const l=Q(E(dt(i,Ee(Q(c,G.backend.epsilon()))),-this.learningRate),r);r.assign(l)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&vt(this.accumulatedGrads.map(t=>t.variable))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(t){t=await this.extractIterations(t);const e=!1;this.accumulatedGrads=t.map(s=>({originalName:s.name,variable:s.tensor.variable(e)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(t,e){return new t(e.learningRate,e.initialAccumulatorValue)}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class pg extends ks{static get className(){return"Adam"}constructor(t,e,s,o=null){super(),this.learningRate=t,this.beta1=e,this.beta2=s,this.epsilon=o,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],M(()=>{this.accBeta1=Gt(e).variable(),this.accBeta2=Gt(s).variable()}),o==null&&(this.epsilon=G.backend.epsilon())}applyGradients(t){const e=Array.isArray(t)?t.map(s=>s.name):Object.keys(t);M(()=>{const s=pt(1,this.accBeta1),o=pt(1,this.accBeta2);e.forEach((r,i)=>{const a=G.registeredVariables[r],c=!1;this.accumulatedFirstMoment[i]==null&&(this.accumulatedFirstMoment[i]={originalName:`${r}/m`,variable:M(()=>St(a).variable(c))}),this.accumulatedSecondMoment[i]==null&&(this.accumulatedSecondMoment[i]={originalName:`${r}/v`,variable:M(()=>St(a).variable(c))});const l=Array.isArray(t)?t[i].tensor:t[r];if(l==null)return;const u=this.accumulatedFirstMoment[i].variable,d=this.accumulatedSecondMoment[i].variable,h=Q(E(u,this.beta1),E(l,1-this.beta1)),p=Q(E(d,this.beta2),E(Bt(l),1-this.beta2)),f=dt(h,s),m=dt(p,o);u.assign(h),d.assign(p);const g=Q(E(dt(f,Q(Ee(m),this.epsilon)),-this.learningRate),a);a.assign(g)}),this.accBeta1.assign(E(this.accBeta1,this.beta1)),this.accBeta2.assign(E(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&vt(this.accumulatedFirstMoment.map(t=>t.variable)),this.accumulatedSecondMoment!=null&&vt(this.accumulatedSecondMoment.map(t=>t.variable))}async getWeights(){const t=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(t.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(t){t=await this.extractIterations(t),M(()=>{this.accBeta1.assign(Yo(this.beta1,this.iterations_+1)),this.accBeta2.assign(Yo(this.beta2,this.iterations_+1))});const e=t.length/2,s=!1;this.accumulatedFirstMoment=t.slice(0,e).map(o=>({originalName:o.name,variable:o.tensor.variable(s)})),this.accumulatedSecondMoment=t.slice(e,e*2).map(o=>({originalName:o.name,variable:o.tensor.variable(s)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon)}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class fg extends ks{static get className(){return"Adamax"}constructor(t,e,s,o=null,r=0){super(),this.learningRate=t,this.beta1=e,this.beta2=s,this.epsilon=o,this.decay=r,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],M(()=>{this.iteration=Gt(0).variable(),this.accBeta1=Gt(e).variable()}),o==null&&(this.epsilon=G.backend.epsilon())}applyGradients(t){const e=Array.isArray(t)?t.map(s=>s.name):Object.keys(t);M(()=>{const s=pt(1,this.accBeta1),o=dt(-this.learningRate,Q(E(this.iteration,this.decay),1));e.forEach((r,i)=>{const a=G.registeredVariables[r],c=!1;this.accumulatedFirstMoment[i]==null&&(this.accumulatedFirstMoment[i]={originalName:`${r}/m`,variable:St(a).variable(c)}),this.accumulatedWeightedInfNorm[i]==null&&(this.accumulatedWeightedInfNorm[i]={originalName:`${r}/v`,variable:St(a).variable(c)});const l=Array.isArray(t)?t[i].tensor:t[r];if(l==null)return;const u=this.accumulatedFirstMoment[i].variable,d=this.accumulatedWeightedInfNorm[i].variable,h=Q(E(u,this.beta1),E(l,1-this.beta1)),p=E(d,this.beta2),f=Ge(l),m=vs(p,f);u.assign(h),d.assign(m);const g=Q(E(dt(o,s),dt(h,Q(m,this.epsilon))),a);a.assign(g)}),this.iteration.assign(Q(this.iteration,1)),this.accBeta1.assign(E(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&vt(this.accumulatedFirstMoment.map(t=>t.variable)),this.accumulatedWeightedInfNorm!=null&&vt(this.accumulatedWeightedInfNorm.map(t=>t.variable))}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(t){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(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon,e.decay)}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class Qd extends ks{static get className(){return"SGD"}constructor(t){super(),this.learningRate=t,this.setLearningRate(t)}applyGradients(t){(Array.isArray(t)?t.map(s=>s.name):Object.keys(t)).forEach((s,o)=>{const r=Array.isArray(t)?t[o].tensor:t[s];if(r==null)return;const i=G.registeredVariables[s];M(()=>{const a=Q(E(this.c,r),i);i.assign(a)})}),this.incrementIterations()}setLearningRate(t){this.learningRate=t,this.c!=null&&this.c.dispose(),this.c=en(Gt(-t))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(t){if(t=await this.extractIterations(t),t.length!==0)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(t,e){return new t(e.learningRate)}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class mg extends Qd{static get className(){return"Momentum"}constructor(t,e,s=!1){super(t),this.learningRate=t,this.momentum=e,this.useNesterov=s,this.accumulations=[],this.m=Gt(this.momentum)}applyGradients(t){(Array.isArray(t)?t.map(s=>s.name):Object.keys(t)).forEach((s,o)=>{const r=G.registeredVariables[s];this.accumulations[o]==null&&(this.accumulations[o]={originalName:`${s}/momentum`,variable:M(()=>St(r).variable(!1))});const i=this.accumulations[o].variable,a=Array.isArray(t)?t[o].tensor:t[s];a!=null&&M(()=>{let c;const l=Q(E(this.m,i),a);this.useNesterov?c=Q(E(this.c,Q(a,E(l,this.m))),r):c=Q(E(this.c,l),r),i.assign(l),r.assign(c)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&vt(this.accumulations.map(t=>t.variable))}setMomentum(t){this.momentum=t}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(t){t=await this.extractIterations(t);const e=!1;this.accumulations=t.map(s=>({originalName:s.name,variable:s.tensor.variable(e)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(t,e){return new t(e.learningRate,e.momentum,e.useNesterov)}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class gg extends ks{static get className(){return"RMSProp"}constructor(t,e=.9,s=0,o=null,r=!1){if(super(),this.learningRate=t,this.decay=e,this.momentum=s,this.epsilon=o,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=r,o==null&&(this.epsilon=G.backend.epsilon()),t==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(t){(Array.isArray(t)?t.map(s=>s.name):Object.keys(t)).forEach((s,o)=>{const r=G.registeredVariables[s],i=!1;this.accumulatedMeanSquares[o]==null&&(this.accumulatedMeanSquares[o]={originalName:`${s}/rms`,variable:M(()=>St(r).variable(i))}),this.accumulatedMoments[o]==null&&(this.accumulatedMoments[o]={originalName:`${s}/momentum`,variable:M(()=>St(r).variable(i))}),this.accumulatedMeanGrads[o]==null&&this.centered&&(this.accumulatedMeanGrads[o]={originalName:`${s}/mg`,variable:M(()=>St(r).variable(i))});const a=Array.isArray(t)?t[o].tensor:t[s];if(a==null)return;const c=this.accumulatedMeanSquares[o].variable,l=this.accumulatedMoments[o].variable;M(()=>{const u=Q(E(c,this.decay),E(Bt(a),1-this.decay));if(this.centered){const d=this.accumulatedMeanGrads[o].variable,h=Q(E(d,this.decay),E(a,1-this.decay)),p=dt(E(a,this.learningRate),Ee(pt(u,Q(Bt(h),this.epsilon)))),f=Q(E(l,this.momentum),p);c.assign(u),d.assign(h),l.assign(f);const m=pt(r,f);r.assign(m)}else{const d=Q(E(c,this.decay),E(Bt(a),1-this.decay)),h=Q(E(l,this.momentum),dt(E(a,this.learningRate),Ee(Q(d,this.epsilon))));c.assign(d),l.assign(h);const p=pt(r,h);r.assign(p)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&vt(this.accumulatedMeanSquares.map(t=>t.variable)),this.accumulatedMeanGrads!=null&&this.centered&&vt(this.accumulatedMeanGrads.map(t=>t.variable)),this.accumulatedMoments!=null&&vt(this.accumulatedMoments.map(t=>t.variable))}async getWeights(){const t=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&t.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(t.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(t){t=await this.extractIterations(t);const e=this.centered?t.length/3:t.length/2,s=!1;this.accumulatedMeanSquares=t.slice(0,e).map(o=>({originalName:o.name,variable:o.tensor.variable(s)})),this.accumulatedMoments=t.slice(e,e*2).map(o=>({originalName:o.name,variable:o.tensor.variable(s)})),this.centered&&(this.accumulatedMeanGrads=t.slice(e*2,e*3).map(o=>({originalName:o.name,variable:o.tensor.variable(s)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(t,e){return new t(e.learningRate,e.decay,e.momentum,e.epsilon,e.centered)}}/**
 * @license
 * Copyright 2022 Google LLC.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const yT=[dg,hg,pg,fg,mg,gg,Qd];function IT(){for(const n of yT)_(n)}/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */let uo;function wT(n,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(n==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let e=!1,s=!1,o=!1,r=!1,i=!1,a=!1;if(n.data instanceof Uint8Array)e=!0;else if(typeof ImageData<"u"&&n instanceof ImageData)s=!0;else if(typeof HTMLVideoElement<"u"&&n instanceof HTMLVideoElement)o=!0;else if(typeof HTMLImageElement<"u"&&n instanceof HTMLImageElement)r=!0;else if(n.getContext!=null)i=!0;else if(typeof ImageBitmap<"u"&&n instanceof ImageBitmap)a=!0;else 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 ${n.constructor.name}`);if(_u(Zu,G.backendName)!=null){const f={pixels:n},m={numChannels:t};return G.runKernel(Zu,f,m)}const[l,u]=o?[n.videoWidth,n.videoHeight]:[n.width,n.height];let d;if(i)d=n.getContext("2d").getImageData(0,0,l,u).data;else if(s||e)d=n.data;else if(r||o||a){if(uo==null)if(typeof document>"u")if(typeof OffscreenCanvas<"u"&&typeof OffscreenCanvasRenderingContext2D<"u")uo=new OffscreenCanvas(1,1).getContext("2d");else throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");else uo=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});uo.canvas.width=l,uo.canvas.height=u,uo.drawImage(n,0,0,l,u),d=uo.getImageData(0,0,l,u).data}let h;if(t===4)h=new Int32Array(d);else{const f=l*u;h=new Int32Array(f*t);for(let m=0;m<f;m++)for(let g=0;g<t;++g)h[m*t+g]=d[m*4+g]}return ak(h,[u,l,t],"int32")}const CT=D({fromPixels_:wT});function Jd(n,t){const e=n.shape.length,s=t.shape.length;if(e<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${e}.`);if(s<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${s}.`);if(t.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[s-1]>e)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[s-1]} vs. ${e}`);if(Z(n.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${n.shape}.`);const o=t.shape,r=o[o.length-1];let i=1;for(let d=0;d<o.length-1;++d)i*=o[d];const a=n.shape,c=o.slice();c.pop();let l=1;for(let d=r;d<e;++d)l*=a[d],c.push(a[d]);const u=[...ct(n.shape).map(d=>d/l),1].slice(0,r);return[c,i,l,u]}/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const jd=-2,vT=-1;function qd(n,t,e){const s=n.shape.length;v(s===t.length,()=>`Error in slice${s}D: Length of begin ${t} must match the rank of the array (${s}).`),v(s===e.length,()=>`Error in slice${s}D: Length of size ${e} must match the rank of the array (${s}).`);for(let o=0;o<s;++o)v(t[o]+e[o]<=n.shape[o],()=>`Error in slice${s}D: begin[${o}] + size[${o}] (${t[o]+e[o]}) would overflow input.shape[${o}] (${n.shape[o]})`)}function ST(n){const t=[];let e=0;for(;n>0;)n&1&&t.push(e),n/=2,e++;return t}function th(n,t,e){const s=[];for(let o=0;o<n.length;o++)s[o]=Math.ceil((t[o]-n[o])/e[o]);return s}function bg(n,t,e,s){const o=[...n];for(let r=o.length;r<s.length;r++)o.push(1);for(let r=0;r<e;r++)r===0?o[t]=1:(o.splice(t,0,1),o.pop());return o}function xg(n,t,e){return e<=n?e:e-(t-1)}function yg(n,t){const e=[];for(let s=0;s<n;s++)e.push(t+s);return e}function kT(n,t,e,s,o,r,i,a,c){const l=n.length;let u=new Array(l),d=new Array(l),h=new Array(l);if(t.length&&e>0){const p=t[0],f=e+1;u=Ig(i,p,f,s,n),d=wg(a,p,f,o,n),h=bg(r,p,f,n)}else for(let p=0;p<l;p++)u[p]=vg(i,s,r,n,p,c),d[p]=Sg(a,o,r,n,p,c),h[p]=Cg(r,p,c);return{begin:u,end:d,strides:h}}function Ig(n,t,e,s,o){const r=[...o],i=yg(e,t);for(let a=0;a<r.length;a++)if(i.indexOf(a)>-1)r[a]=0;else{const c=xg(t,e,a);let l=s[c];n&1<<c&&(l=0),r[a]=l}return r}function wg(n,t,e,s,o){const r=[...o],i=yg(e,t);for(let a=0;a<r.length;a++)if(i.indexOf(a)>-1)r[a]=Number.MAX_SAFE_INTEGER;else{const c=xg(t,e,a);let l=s[c];n&1<<c&&(l=Number.MAX_SAFE_INTEGER),r[a]=l}for(let a=0;a<r.length;a++){const c=o[a];r[a]<0&&(r[a]+=c),r[a]=Ks(0,r[a],o[a])}return r}function Cg(n,t,e){let s=n[t];return(e&1<<t||s==null)&&(s=1),s}function vg(n,t,e,s,o,r){let i=t[o];const a=e[o]||1;(n&1<<o||r&1<<o||i==null)&&(a>0?i=Number.MIN_SAFE_INTEGER:i=Number.MAX_SAFE_INTEGER);const c=s[o];return i<0&&(i+=c),i=Ks(0,i,c-1),i}function Sg(n,t,e,s,o,r){let i=t[o];const a=e[o]||1;(n&1<<o||r&1<<o||i==null)&&(a>0?i=Number.MAX_SAFE_INTEGER:i=Number.MIN_SAFE_INTEGER);const c=s[o];return i<0&&(i+=c),a>0?i=Ks(0,i,c):i=Ks(-1,i,c-1),i}function eh(n,t,e){let s=e.length;for(let o=0;o<e.length;o++)if(e[o]>1){s=o;break}for(let o=s+1;o<e.length;o++)if(t[o]>0||e[o]!==n[o])return!1;return!0}function nh(n,t){let e=n.length>0?n[n.length-1]:1;for(let s=0;s<n.length-1;s++)e+=n[s]*t[s];return e}function zc(n,t,e){let s;const o=n.shape.length;typeof t=="number"?s=[t,...new Array(o-1).fill(0)]:t.length<o?s=t.concat(new Array(o-t.length).fill(0)):s=t.slice(),s.forEach(i=>{v(i!==-1,()=>"slice() does not support negative begin indexing.")});let r;return e==null?r=new Array(o).fill(-1):typeof e=="number"?r=[e,...new Array(o-1).fill(-1)]:e.length<o?r=e.concat(new Array(o-e.length).fill(-1)):r=e,r=r.map((i,a)=>i>=0?i:(v(i===-1,()=>`Negative size values should be exactly -1 but got ${i} for the slice() size at index ${a}.`),n.shape[a]-s[a])),[s,r]}function sh(n,t,e,s,o,r,i,a,c){let l;if(s==null?(l=new Array(t.length),l.fill(1)):l=s,i!=null&&i&i-1)throw new Error("Multiple ellipses in slice is not allowed.");let u=!1;const d={dims:l.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:e.slice(),strides:l.slice(),beginMask:o,endMask:r,ellipsisMask:i,newAxisMask:a,shrinkAxisMask:c};for(let I=0;I<d.dims;I++)u&&1<<I&a&&d.numAddAxisAfterEllipsis++,1<<I&i&&(u=!0);u||(d.ellipsisMask|=1<<d.dims,d.dims++);const h={dims:n.length,beginMask:0,endMask:0,beginValid:!1,endValid:!1};TT(d,h);let p=!0,f=!0,m=!0;const g=[],b=[];for(let I=0;I<n.length;++I){if(h.strides[I]===0)throw Error(`strides[${I}] must be non-zero`);const y=!!(h.shrinkAxisMask&1<<I),w=n[I];if(w===-1){g.push(y?1:-1);continue}const C=[h.beginMask&1<<I,h.endMask&1<<I],k=[h.strides[I]>0?0:-1,h.strides[I]>0?w:w-1];if(y&&h.strides[I]<=0)throw Error("only stride 1 allowed on non-range indexing.");m=m&&h.strides[I]===1;const S=!!(h.beginMask&1<<I&&h.endMask&1<<I);if(h.beginValid&&h.endValid){if(y){const V=h.begin[I]<0?w+h.begin[I]:h.begin[I];if(h.begin[I]=V,h.end[I]=h.begin[I]+1,V<0||V>=w)throw Error(`slice index ${h.begin[I]} of dimension ${I} out of bounds.`)}else h.begin[I]=kg(h.begin[I],0,h.strides[I],w,C,k),h.end[I]=kg(h.end[I],1,h.strides[I],w,C,k);const L=h.strides[I]===1&&h.begin[I]===0&&h.end[I]===w;p=p&&L,f=f&&(I===0&&h.strides[I]===1||L)}else p=p&&h.strides[I]===1&&S,f=f&&(I===0&&h.strides[I]===1||S);let T,R=!1;if(h.beginValid&&h.endValid?(T=h.end[I]-h.begin[I],R=!0):y?(T=1,R=!0):S&&w>=0&&(h.strides[I]<0?T=-w:T=w,R=!0),R){let L;T===0||T<0!=h.strides[I]<0?L=0:L=Math.trunc(T/h.strides[I])+(T%h.strides[I]!==0?1:0),g.push(L)}else g.push(-1)}for(let I=0;I<h.finalShapeGatherIndices.length;++I){const y=h.finalShapeGatherIndices[I];y>=0?b.push(g[y]):y===jd&&b.push(1)}return{finalShapeSparse:b.filter((I,y)=>h.finalShapeGatherIndices[y]!==jd),finalShape:b,isIdentity:p,sliceDim0:f,isSimpleSlice:m,begin:h.begin,end:h.end,strides:h.strides}}function TT(n,t){t.beginMask=0,t.endMask=0,t.shrinkAxisMask=0;let e=0;t.beginValid=n.begin!=null,t.endValid=n.end!=null,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<n.dims;s++)if(1<<s&n.ellipsisMask){const o=Math.min(t.dims-(n.dims-s)+1+n.numAddAxisAfterEllipsis,t.dims);for(;e<o;e++)t.begin[e]=0,t.end[e]=0,t.strides[e]=1,t.beginMask|=1<<e,t.endMask|=1<<e,t.finalShapeGatherIndices.push(e),t.finalShapeGatherIndicesSparse.push(-1),t.inputShapeGatherIndicesSparse[e]=s}else if(1<<s&n.newAxisMask)t.finalShapeGatherIndices.push(jd),t.finalShapeGatherIndicesSparse.push(-1);else{if(e===t.begin.length)throw Error(`Index out of range using input dim ${e}; input has only ${t.dims} dims, ${t.begin.length}.`);n.begin!=null&&(t.begin[e]=n.begin[s]),n.end!=null&&(t.end[e]=n.end[s]),t.strides[e]=n.strides[s],n.beginMask&1<<s&&(t.beginMask|=1<<e),n.endMask&1<<s&&(t.endMask|=1<<e),n.shrinkAxisMask&1<<s?(t.finalShapeGatherIndices.push(vT),t.finalShapeGatherIndicesSparse.push(-1),t.shrinkAxisMask|=1<<e):(t.finalShapeGatherIndices.push(e),t.finalShapeGatherIndicesSparse.push(s)),t.inputShapeGatherIndicesSparse[e]=s,e++}}function kg(n,t,e,s,o,r){if(o[t])return e>0?r[t]:r[t+1&1];{const i=n<0?s+n:n;return i<r[0]?r[0]:i>r[1]?r[1]:i}}const NT=Object.freeze(Object.defineProperty({__proto__:null,assertParamsValid:qd,computeFlatOffset:nh,computeOutShape:th,getNormalizedAxes:kT,isSliceContinous:eh,maskToAxes:ST,parseSliceParams:zc,sliceInfo:sh,startForAxis:vg,startIndicesWithElidedDims:Ig,stopForAxis:Sg,stopIndicesWithElidedDims:wg,stridesForAxis:Cg,stridesWithElidedDims:bg},Symbol.toStringTag,{value:"Module"}));/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class RT{static sgd(t){return new Qd(t)}static momentum(t,e,s=!1){return new mg(t,e,s)}static rmsprop(t,e=.9,s=0,o=null,r=!1){return new gg(t,e,s,o,r)}static adam(t=.001,e=.9,s=.999,o=null){return new pg(t,e,s,o)}static adadelta(t=.001,e=.95,s=null){return new dg(t,e,s)}static adamax(t=.002,e=.9,s=.999,o=null,r=0){return new fg(t,e,s,o,r)}static adagrad(t,e=.1){return new hg(t,e)}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const tr=RT;/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const $T=typeof requestAnimationFrame<"u"?requestAnimationFrame:typeof setImmediate<"u"?setImmediate:n=>n();function Xc(){return new Promise(n=>$T(()=>n()))}/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function oh(n,t){const e=n[0].length;n.forEach((o,r)=>{v(o.length===e,()=>`Error in concat${e}D: rank of tensors[${r}] must be the same as the rank of the rest (${e})`)}),v(t>=0&&t<e,()=>`Error in concat${e}D: axis must be between 0 and ${e-1}.`);const s=n[0];n.forEach((o,r)=>{for(let i=0;i<e;i++)v(i===t||o[i]===s[i],()=>`Error in concat${e}D: Shape of tensors[${r}] (${o}) does not match the shape of the rest (${s}) along the non-concatenated axis ${r}.`)})}function Kn(n,t){const e=n[0].slice();for(let s=1;s<n.length;s++)e[t]+=n[s][t];return e}/**
 * @license
 * Copyright 2022 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */var Rn;(function(n){n[n.FIRST_DIM_SIZE=0]="FIRST_DIM_SIZE",n[n.VALUE_ROWIDS=1]="VALUE_ROWIDS",n[n.ROW_LENGTHS=2]="ROW_LENGTHS",n[n.ROW_SPLITS=3]="ROW_SPLITS",n[n.ROW_LIMITS=4]="ROW_LIMITS",n[n.ROW_STARTS=5]="ROW_STARTS"})(Rn||(Rn={}));function Tg(n,t,e){let s=new Array;if(e==null&&t==null)return s;if(t==null)for(;s.length<n+e.length;)s.push(-1);else s=t.slice();if(e==null)return s;if(n+e.length!==s.length)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.rank = ${n+e.length}, but shape.rank = ${s.length}`);for(let o=1;o<e.length;++o){const r=e[o],i=s[s.length-e.length+o],a=s[i];if(r>=0)if(a>=0){if(a!==r)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.shape[${o+n}] = ${r} but shape[${o+n}] = ${a}`)}else s[i]=r}return s}function Ng(n){const t={FIRST_DIM_SIZE:Rn.FIRST_DIM_SIZE,VALUE_ROWIDS:Rn.VALUE_ROWIDS,ROW_LENGTHS:Rn.ROW_LENGTHS,ROW_SPLITS:Rn.ROW_SPLITS,ROW_LIMITS:Rn.ROW_LIMITS,ROW_STARTS:Rn.ROW_STARTS},e=[];for(const s of n)if(s in t)e.push(t[s]);else break;return e}function Rg(n){return n.length===0?0:n[0]===Rn.FIRST_DIM_SIZE?n.length-1:n.length}function $g(n,t){if(n==null||t==null)return;const e=n.length,s=t.length;if(e>=s)throw new Error(`defaultValue.shape=${n} and ragged tensor flatValues.shape=${t}, are incompatible: defaultValue.rank = ${e} must be less than ragged tensor input flatValues.rank = ${s})`);for(let o=0;o<Math.min(e,s-1);++o){const r=n[o],i=t[o+1];if(r>=0&&i>=0&&r!==1&&r!==i)throw new Error(`defaultValue.shape=${n}, and ragged tensor input flatValues.shape=${t} are incompatible: defaultValue.shape[${o-n.length}] = ${r} but ragged tensor input.flatValues.shape[${o-n.length}] = ${i}`)}}/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const rh=30;function Ac(n){return n<=rh?n:Jl(n,Math.floor(Math.sqrt(n)))}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function ih(n,t,e){const s=e*(typeof n=="number"?n:n[0]),o=t*(typeof n=="number"?n:n[1]);return[s,o]}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Mi(n,t,e,s=!0){let o=[];if(s)o=o.concat(t.slice(0)),o.push(n[0]/e),o=o.concat(n.slice(1));else{o=o.concat(n[0]);const r=t.length;for(let i=0;i<r;++i)o=o.concat([n[i+1]/t[i],t[i]]);o=o.concat(n.slice(r+1))}return o}function Vi(n,t,e=!0){const s=[];if(e){s.push(t);for(let o=t+1;o<n;++o)o<=2*t?(s.push(o),s.push(o-(t+1))):s.push(o)}else{const o=[],r=[];for(let i=1;i<n;++i)i>=t*2+1||i%2===1?r.push(i):o.push(i);s.push(...o),s.push(0),s.push(...r)}return s}function Fi(n,t,e,s=!0){const o=[];s?o.push(n[0]/e):o.push(n[0]*e);for(let r=1;r<n.length;++r)r<=t.length?s?o.push(t[r-1]*n[r]):o.push(n[r]/t[r-1]):o.push(n[r]);return o}function ah(n,t){const e=[0];for(let s=0;s<t;++s)e.push(n[s][0]);return e}function ch(n,t,e){const s=n.slice(0,1);for(let o=0;o<e;++o)s.push(n[o+1]-t[o][0]-t[o][1]);return s}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const Pc=1.7580993408473768,Oc=1.0507009873554805;/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const lh=.3275911,uh=.254829592,dh=-.284496736,hh=1.421413741,ph=-1.453152027,fh=1.061405429;/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function as(n,t){if(n.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${n.length}, imag: ${t.length}.`);const e=new Float32Array(n.length*2);for(let s=0;s<e.length;s+=2)e[s]=n[s/2],e[s+1]=t[s/2];return e}function Gg(n){const t=new Float32Array(n.length/2),e=new Float32Array(n.length/2);for(let s=0;s<n.length;s+=2)t[s/2]=n[s],e[s/2]=n[s+1];return{real:t,imag:e}}function Lg(n){const t=Math.ceil(n.length/4),e=new Float32Array(t),s=new Float32Array(t);for(let o=0;o<n.length;o+=4)e[Math.floor(o/4)]=n[o],s[Math.floor(o/4)]=n[o+1];return{real:e,imag:s}}function Eg(n){const t=Math.floor(n.length/4),e=new Float32Array(t),s=new Float32Array(t);for(let o=2;o<n.length;o+=4)e[Math.floor(o/4)]=n[o],s[Math.floor(o/4)]=n[o+1];return{real:e,imag:s}}function mh(n,t){const e=n[t*2],s=n[t*2+1];return{real:e,imag:s}}function Dg(n,t,e,s){n[s*2]=t,n[s*2+1]=e}function Wg(n,t){const e=new Float32Array(n/2),s=new Float32Array(n/2);for(let o=0;o<Math.ceil(n/2);o++){const r=(t?2:-2)*Math.PI*(o/n);e[o]=Math.cos(r),s[o]=Math.sin(r)}return{real:e,imag:s}}function Mg(n,t,e){const s=(e?2:-2)*Math.PI*(n/t),o=Math.cos(s),r=Math.sin(s);return{real:o,imag:r}}/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const gh="->",GT=/->/g,Vg=",",Fg="...";function bh(n,t){n=n.replace(/\s/g,"");const e=(n.length-n.replace(GT,"").length)/gh.length;if(e<1)throw new Error("Equations without an arrow are not supported.");if(e>1)throw new Error(`Equation must contain exactly one arrow ("${gh}").`);const[s,o]=n.split(gh);v(s.indexOf(Fg)===-1,()=>`The ellipsis notation ("${Fg}") is not supported yet.`);const r=s.split(Vg),i=r.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 a=[];for(let h=0;h<o.length;++h){const p=o[h];if(!r.some(f=>f.indexOf(p)!==-1))throw new Error(`Output subscripts contain the label ${p} not present in the input subscripts.`);a.indexOf(p)===-1&&a.push(p)}for(let h=0;h<s.length;++h){const p=s[h];a.indexOf(p)===-1&&p!==Vg&&a.push(p)}const c=new Array(r.length);for(let h=0;h<i;++h){if(new Set(r[h].split("")).size!==r[h].length)throw new Error(`Found duplicate axes in input component ${r[h]}. Support for duplicate axes in input is not implemented yet.`);c[h]=[];for(let p=0;p<r[h].length;++p)c[h].push(a.indexOf(r[h][p]))}const l=a.length,u=o.length,d=[];for(let h=u;h<l;++h)d.push(h);return{allDims:a,summedDims:d,idDims:c}}function xh(n,t){let e=new Array(n);e.fill(-1);for(let o=0;o<t.length;++o)e[t[o]]=o;const s=[];for(let o=0;o<n;++o)e[o]===-1&&s.push(o);return e=e.filter(o=>o!==-1),{permutationIndices:e,expandDims:s}}function yh(n,t,e){const s=new Array(n);for(let o=0;o<e.length;++o){const r=e[o].shape;for(let i=0;i<t[o].length;++i)s[t[o][i]]===void 0?s[t[o][i]]=r[i]:v(s[t[o][i]]===r[i],()=>`Expected dimension ${s[t[o][i]]} at axis ${i} of input shaped ${JSON.stringify(r)}, but got dimension ${r[i]}`)}}function Ih(n,t){const e=n,s=[];let o=0;n.length===0&&e.push(-1),o=n.length+1;for(let i=0;i<o;++i)s.push([]);const r=[];for(let i=0;i<e.length;++i){const a=e[i],c=LT(t,a);for(const l of c)r.indexOf(l)===-1&&(s[i].push(l),r.push(l))}return{path:e,steps:s}}function wh(n){return n.every((t,e)=>t===e)}function LT(n,t){const e=[];for(let s=0;s<n.length;++s)(n[s].length===0||n[s].indexOf(t)!==-1||t===-1)&&e.push(s);return e}function Ch(n,t,e=0){let s=[];if(typeof t=="number")v(n.shape[e]%t===0,()=>"Number of splits must evenly divide the axis."),s=new Array(t).fill(n.shape[e]/t);else{const o=t.reduce((i,a)=>(a===-1&&(i+=1),i),0);v(o<=1,()=>"There should be only one negative value in split array.");const r=t.indexOf(-1);if(r!==-1){const i=t.reduce((a,c)=>c>0?a+c:a);t[r]=n.shape[e]-i}v(n.shape[e]===t.reduce((i,a)=>i+a),()=>"The sum of sizes must match the size of the axis dimension."),s=t}return s}/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function zg(n){return`Received SparseTensor with denseShape[0] = 0 but
  indices.shape[0] = ${n}`}function Xg(n,t){return`indices(${n}, 0) is invalid: ${t} < 0`}function Ag(n,t,e){return`indices(${n}, 0) is invalid: ${t} >= ${e}`}/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Pg(n,t){return`only one output dimension may be -1, not both ${n} and ${t}`}function Og(n,t){return`size ${n} must be non-negative, not ${t}`}function Kg(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function Zg(n,t){const e=Z(n),s=Z(t);return`Input to reshape is a SparseTensor with ${e}
  dense values, but the requested shape requires a multiple of ${s}. inputShape=${n} outputShape= ${t}`}function Bg(n,t){const e=Z(n),s=Z(t);return`Input to reshape is a tensor with ${e} dense values, but the requested shape has ${s}. inputShape=${n} outputShape=${t}`}/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function vh(){return"segment ids must be >= 0"}function Hg(){return"segment ids are not increasing"}function _g(n,t){return`Segment id ${n} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function Ug(n,t,e){return`Bad: indices[${n}] == ${t} out of range [0, ${e})`}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Yg(n,t){let e=!1,s;for(n<=rh?(s=n,e=!0):s=Jl(n,Math.floor(Math.sqrt(n)));!e;)s>t||s===n?e=!0:s=Jl(n,s+1);return s}function Qg(n,t,e){const s=[],o=n.length;for(let r=0;r<o;r++)r!==t?s.push(n[r]):s.push(e);return s}function Sh(n,t,e,s){const o=t.shape.length,r=n.shape.length;if(s!==0&&(s<-o||s>o))throw new Error(`Expect batchDims in the range of [-${o}, ${o}], but got ${s}`);if(s<0&&(s+=o),s>r)throw new Error(`batchDims (${s}) must be less than rank(x) (
    ${r}).`);if(e<s)throw new Error(`batchDims (${s}) must be less than or equal to axis (${e}).`);for(let d=0;d<s;++d)if(n.shape[d]!==t.shape[d])throw new Error(`x.shape[${d}]: ${n.shape[d]} should be equal to indices.shape[${d}]: ${t.shape[d]}.`);const i=n.shape[e],a=[];let c=1,l=1,u=1;for(let d=0;d<s;++d)a.push(n.shape[d]),c*=n.shape[d];for(let d=s;d<e;d++)a.push(n.shape[d]),l*=n.shape[d];for(let d=s;d<o;d++)a.push(t.shape[d]);for(let d=e+1;d<r;d++)a.push(n.shape[d]),u*=n.shape[d];return{batchSize:c,sliceSize:u,outerSize:l,dimSize:i,outputShape:a}}const ET=Object.freeze(Object.defineProperty({__proto__:null,collectGatherOpShapeInfo:Sh,computeOutShape:Qg,segOpComputeOptimalWindowSize:Yg},Symbol.toStringTag,{value:"Module"}));/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function cs(n){try{return n.map(t=>xs(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function Jg(n){return n.map(t=>bs(t))}const DT=Object.freeze(Object.defineProperty({__proto__:null,ERF_A1:uh,ERF_A2:dh,ERF_A3:hh,ERF_A4:ph,ERF_A5:fh,ERF_P:lh,PARALLELIZE_THRESHOLD:rh,get RowPartitionType(){return Rn},SELU_SCALE:Oc,SELU_SCALEALPHA:Pc,applyActivation:Zd,assertAndGetBroadcastShape:gt,assertAxesAreInnerMostDims:Ie,assertParamsConsistent:oh,assignToTypedArray:Dg,axesAreInnerMostDims:yd,calculateShapes:co,checkEinsumDimSizes:yh,checkPadOnDimRoundingMode:ze,combineLocations:Fm,combineRaggedTensorToTensorShapes:Tg,complexWithEvenIndex:Lg,complexWithOddIndex:Eg,computeConv2DInfo:ye,computeConv3DInfo:ws,computeDefaultPad:ud,computeDilation2DInfo:Si,computeOptimalWindowSize:Ac,computeOutAndReduceShapes:me,computeOutShape:Kn,computePool2DInfo:pn,computePool3DInfo:ss,convertConv2DDataFormat:os,decodeEinsumEquation:bh,eitherStridesOrDilationsAreOne:Te,expandShapeToKeepDim:re,exponent:Mg,exponents:Wg,fromStringArrayToUint8:Jg,fromUint8ToStringArray:cs,getAxesPermutation:Yt,getBroadcastDims:Uo,getComplexWithIndex:mh,getEinsumComputePath:Ih,getEinsumPermutation:xh,getFusedBiasGradient:Kd,getFusedDyActivation:Od,getImageCenter:ih,getInnerMostAxes:ee,getPermuted:Vi,getRaggedRank:Rg,getReductionAxes:ce,getReshaped:Mi,getReshapedPermuted:Fi,getRowPartitionTypesHelper:Ng,getSliceBeginCoords:ah,getSliceSize:ch,getSparseFillEmptyRowsIndicesDenseShapeMismatch:zg,getSparseFillEmptyRowsNegativeIndexErrorMessage:Xg,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:Ag,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:Kg,getSparseReshapeInputOutputMismatchErrorMessage:Bg,getSparseReshapeInputOutputMultipleErrorMessage:Zg,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:Pg,getSparseReshapeNegativeOutputDimErrorMessage:Og,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:Ug,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:vh,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:Hg,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:_g,getUndoAxesPermutation:Cs,isIdentityPermutation:wh,log:fw,mergeRealAndImagArrays:as,prepareAndValidate:Jd,prepareSplitSize:Ch,segment_util:ET,shouldFuse:Bd,slice_util:NT,splitRealAndImagArrays:Gg,stridesOrDilationsArePositive:no,tupleValuesAreOne:eo,upcastType:_e,validateDefaultValueShape:$g,validateInput:ck,validateUpdateShape:ng,warn:je},Symbol.toStringTag,{value:"Module"}));/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */IT();/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const jg={kernelName:ya,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(n,Wi(st(e,"float32"),-1))}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const WT={kernelName:vr,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>{const s=Bt(st(e,"float32")),o=Ee(pt(Gt(1),s));return ne(dt(n,o))}}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const MT={kernelName:Sr,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>{const s=Ee(pt(Bt(st(e,"float32")),1));return dt(n,s)}}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const VT={kernelName:Fo,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,o=gt(e.shape,s.shape);return{a:()=>{let a=n;const c=ce(e.shape,o);return c.length>0&&(a=ut(a,c)),W(a,e.shape)},b:()=>{let a=n;const c=ce(s.shape,o);return c.length>0&&(a=ut(a,c)),W(a,s.shape)}}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const FT={kernelName:nu,saveAllInputs:!0,gradFunc:(n,t)=>{const e={};return t.forEach((s,o)=>{e[o]=()=>n.clone()}),e}};/**
 * @license
 * Copyright 2020 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const zT={kernelName:Ia,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>St(e)}}};/**
 * @license
 * Copyright 2020 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const XT={kernelName:wa,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>St(e)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const AT={kernelName:kr,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>dt(n,Ee(pt(Gt(1),Bt(st(e,"float32")))))}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const PT={kernelName:Tr,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>{const s=Ee(Q(Gt(1),Bt(st(e,"float32"))));return dt(n,s)}}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const OT={kernelName:$r,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,o=gt(e.shape,s.shape);return{a:()=>{const a=Q(Bt(e),Bt(s));let c=E(n,dt(s,a));const l=ce(e.shape,o);return l.length>0&&(c=ut(c,l)),W(c,e.shape)},b:()=>{const a=Q(Bt(e),Bt(s));let c=ne(E(n,dt(e,a)));const l=ce(s.shape,o);return l.length>0&&(c=ut(c,l)),W(c,s.shape)}}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const KT={kernelName:Nr,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>dt(n,Q(Bt(st(e,"float32")),1))}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const ZT={kernelName:Rr,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>dt(n,pt(Gt(1),Bt(st(e,"float32"))))}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function BT(n,t,e,s,o,r){const i=N(n,"dy","avgPool3dGrad"),a=N(t,"input","avgPool3dGrad");let c=i,l=a,u=!1;a.rank===4&&(u=!0,c=W(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),l=W(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),v(c.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`),v(l.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${l.rank}.`),ze("avgPool3dGrad",o,r);const d={dy:c,input:l},h={filterSize:e,strides:s,pad:o,dimRoundingMode:r},p=G.runKernel(iu,d,h);return u?W(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}const HT=D({avgPool3dGrad_:BT});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const _T={kernelName:va,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{filterSize:o,strides:r,pad:i,dimRoundingMode:a}=e;return{x:()=>HT(n,s,o,r,i,a)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function UT(n,t,e,s,o){const r=N(n,"dy","avgPoolGrad"),i=N(t,"input","avgPoolGrad");v(i.rank===r.rank,()=>`Rank of input (${i.rank}) does not match rank of dy (${r.rank})`);let a=i,c=r,l=!1;i.rank===3&&(l=!0,a=W(i,[1,i.shape[0],i.shape[1],i.shape[2]]),c=W(r,[1,r.shape[0],r.shape[1],r.shape[2]])),v(c.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${c.rank}.`),v(a.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${a.rank}.`);const u={dy:c,input:a},d={filterSize:e,strides:s,pad:o},h=G.runKernel(ru,u,d);return l?W(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const YT=D({avgPoolGrad_:UT});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const QT={kernelName:Ca,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{filterSize:o,strides:r,pad:i}=e;return{x:()=>YT(n,s,o,r,i)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const JT={kernelName:Sa,inputsToSave:["a","b"],gradFunc:(n,t,e)=>{const[s,o]=t,{transposeA:r,transposeB:i}=e;return!r&&!i?{a:()=>$t(n,o,!1,!0),b:()=>$t(s,n,!0,!1)}:!r&&i?{a:()=>$t(n,o,!1,!1),b:()=>$t(n,s,!0,!1)}:r&&!i?{a:()=>$t(o,n,!1,!0),b:()=>$t(s,n,!1,!1)}:{a:()=>$t(o,n,!0,!0),b:()=>$t(n,s,!0,!0)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const jT={kernelName:ka,gradFunc:(n,t,e)=>{const{blockShape:s,crops:o}=e;return{x:()=>Nd(n,s,o)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const qT={kernelName:dw,gradFunc:(n,t,e)=>{const s=e,o=s.inputShape,r=s.shape,i=Array.from(r);for(let c=o.length-1;c>=0;c--)if(o[c]===r[c])i[c]=1;else if(o[c]!==1)throw new Error(`broadcastTo(): [${o}] cannot be broadcast to [${r}].`);const a=[];for(let c=0;c<i.length;c++)i[c]>1&&a.push(c);return{x:()=>ut(n,a,!0)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const tN={kernelName:Gr,gradFunc:n=>({x:()=>n.clone()})};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const eN={kernelName:Lr,gradFunc:n=>({x:()=>St(n)})};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const nN={kernelName:Er,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{clipValueMin:o,clipValueMax:r}=e;return{x:()=>Le(rs(oo(s,o),Qo(s,r)),n,St(n))}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const sN={kernelName:Ta,inputsToSave:["x"],gradFunc:jg.gradFunc};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const oN={kernelName:Na,saveAllInputs:!0,gradFunc:(n,t,e)=>{const s=t.map(c=>c.shape),{axis:o}=e,r=It(o,t[0].shape)[0],i=s.map(c=>c[r]);return on(n,i,r).map(c=>()=>c)}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const rN={kernelName:Ra,inputsToSave:["x","filter"],gradFunc:(n,t,e)=>{const[s,o]=t,{dilations:r,strides:i,pad:a,dataFormat:c}=e;return v(eo(r),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`),{x:()=>md(s.shape,n,o,i,a,c),filter:()=>Pd(s,n,o.shape,i,a,c)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const iN={kernelName:$a,inputsToSave:["dy","filter"],gradFunc:(n,t,e)=>{const[s,o]=t,{strides:r,pad:i,dataFormat:a,dimRoundingMode:c}=e;return{dy:()=>so(n,o,r,i,a,1,c),filter:()=>Pd(n,s,o.shape,r,i,a,c)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function aN(n,t,e,s,o){let r=n;n.rank===4&&(r=W(n,[1,n.shape[0],n.shape[1],n.shape[2],n.shape[3]]));let i=t;i.rank===4&&(i=W(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),v(r.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${r.shape}.`),v(i.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`),v(e.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${e}.`),v(r.shape[4]===e[3],()=>`Error in conv3dDerFilter: depth of input ${r.shape[4]}) must match input depth in filter (${e[3]}.`),v(i.shape[4]===e[4],()=>`Error in conv3dDerFilter: depth of dy (${i.shape[4]}) must match output depth for filter (${e[4]}).`);const a={x:r,dy:i},c={strides:s,pad:o,filterShape:e};return G.runKernel(du,a,c)}const cN=D({conv3DBackpropFilter_:aN});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const lN={kernelName:Ga,inputsToSave:["x","filter"],gradFunc:(n,t,e)=>{const{dilations:s,strides:o,pad:r}=e;v(eo(s),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);const[i,a]=t;return{x:()=>Dm(i.shape,n,a,o,r),filter:()=>cN(i,n,a.shape,o,r)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const uN={kernelName:Dr,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(ne(jm(st(e,"float32"))),n)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const dN={kernelName:Wr,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(qm(st(e,"float32")),n)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const hN={kernelName:La,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{axis:o,exclusive:r,reverse:i}=e;return{x:()=>{const a=Yt([o],s.rank);let c=Mm(n,o,r,!i);return a!=null&&(c=kt(c,a)),c}}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const pN={kernelName:Ea,inputsToSave:["x","filter"],gradFunc:(n,t,e)=>{const{dilations:s,strides:o,pad:r,dimRoundingMode:i}=e,a=s??[1,1];v(eo(a),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);const[c,l]=t;return v(c.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${c.rank}.`),v(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${l.rank}.`),v(c.shape[3]===l.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),v(Te(o,a),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be  1. Got strides ${o} and dilations '${a}'.`),ze("depthwiseConv2d",r,i),{x:()=>Nk(c.shape,n,l,o,r,a,i),filter:()=>kk(c,n,l.shape,o,r,a,i)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const fN={kernelName:Da,inputsToSave:["x","filter"],gradFunc:(n,t,e)=>{const[s,o]=t,r={x:s,filter:o,dy:n},i={x:s,filter:o,dy:n};return{x:()=>G.runKernel(yu,r,e),filter:()=>G.runKernel(Iu,i,e)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const mN={kernelName:Vr,outputsToSave:[!0],gradFunc:(n,t)=>{const[e]=t,s={dy:n,y:e};return{x:()=>G.runKernel(Cu,s)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const gN={kernelName:Fr,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t,s=E(An(ne(Bt(e))),2/Math.sqrt(Math.PI));return{x:()=>E(n,s)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const bN={kernelName:zr,outputsToSave:[!0],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(n,e)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const xN={kernelName:Ma,inputsToSave:["input"],gradFunc:(n,t)=>{const[e]=t;return{input:()=>W(n,e.shape)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const yN={kernelName:Xr,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(n,An(e))}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const IN={kernelName:Ar,gradFunc:n=>({x:()=>St(n)})};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const wN={kernelName:Pr,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,o=gt(e.shape,s.shape);return{a:()=>{const a=dt(n,st(s,"float32")),c=ce(e.shape,o);return c.length>0?W(ut(a,c),e.shape):a},b:()=>{let a=E(n,st(e,"float32"));const c=ce(s.shape,o);c.length>0&&(a=W(ut(a,c),s.shape));const l=Bt(s);return ne(dt(a,st(l,"float32")))}}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const CN={kernelName:Va,inputsToSave:["x","mean","variance","scale"],gradFunc:(n,t,e)=>{const{varianceEpsilon:s}=e,[o,r,i,a]=t,c=a??Gt(1),l=ce(r.shape,o.shape),u=[];if(r.rank===1){for(let y=0;y<o.shape.length-1;++y)u.push(o.shape[y]);u.push(1)}const d=pt(o,r),h=E(n,c),p=Ym(Q(i,Gt(s))),f=E(E(E(p,p),p),Gt(-.5));return{x:()=>r.rank===1?W(E(E(n,Nn(W(p,[1,1,1,r.shape[0]]),u)),c),o.shape):W(E(E(n,p),c),o.shape),mean:()=>{let y=E(E(p,Gt(-1)),h);return r.rank===1&&(y=ut(y,l)),W(y,r.shape)},variance:()=>{let y=E(E(f,d),h);return r.rank===1&&(y=ut(y,l)),W(y,r.shape)},scale:()=>{const y=E(d,p);let w=E(n,y);return r.rank===1&&(w=ut(w,l)),W(w,r.shape)},offset:()=>{let y=n;return r.rank===1&&(y=ut(y,l)),W(y,r.shape)}}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const vN={kernelName:Fa,inputsToSave:["x","indices"],gradFunc:(n,t,e)=>{const[s,o]=t,{axis:r,batchDims:i}=e,a=It(r,s.shape)[0],c=(l,u,d)=>()=>{const h=l.shape,p=u.size,f=h.slice(0,a),m=f.length,g=h.slice(r,h.length).slice(1),b=g.length,x=qg(0,m),I=qg(m+1,m+1+b),y=t0([f,[p],g]),w=W(d,y),C=W(u,[p]),k=t0([[m],x,I]),S=kt(w,k);let T=og(S,C,l.shape[a]);const R=Cs(k);return T=kt(T,R),T};if(i===1){const l=s.shape[0],u=s.split(l,0);return{x:()=>On(u.map((p,f)=>c(p,o.slice(f,1),n.slice(f,1))())).reshape(s.shape),indices:()=>o}}else return{x:c(s,o,n),indices:()=>o}}};function qg(n,t){const e=[];for(let s=n;s<t;++s)e.push(s);return e}function t0(n){const t=[];for(let e=0;e<n.length;++e)for(let s=0;s<n[e].length;++s)t.push(n[e][s]);return t}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const SN={kernelName:Or,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t;return{a:()=>St(e),b:()=>St(s)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const kN={kernelName:Kr,gradFunc:n=>({x:()=>st(n,"float32")})};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const TN={kernelName:Zr,gradFunc:n=>({x:()=>St(n)})};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const NN={kernelName:Br,gradFunc:n=>({x:()=>St(n)})};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const RN={kernelName:Hr,gradFunc:n=>({x:()=>St(n)})};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const $N={kernelName:Xa,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{alpha:o}=e,r=sn(s,0);return{x:()=>Le(r,n,E(n,o))}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const GN={kernelName:Ur,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>dt(n,Q(e,1))}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const LN={kernelName:_r,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>dt(n,st(e,"float32"))}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const EN={kernelName:pw,inputsToSave:[],outputsToSave:[!0],gradFunc:(n,t,e)=>{const[s]=t,{axis:o}=e;return{logits:()=>{const i=An(s);return pt(n,E(ut(n,o,!0),i))}}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function DN(n,t,e,s=5,o=1,r=1,i=.5){const a={x:n,y:t,dy:e},c={depthRadius:s,bias:o,alpha:r,beta:i};return G.runKernel(Ru,a,c)}const WN=D({localResponseNormalizationBackprop_:DN});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const MN={kernelName:Ba,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,t,e)=>{const[s,o]=t,{depthRadius:r,bias:i,alpha:a,beta:c}=e;return{x:()=>WN(s,o,n,r,i,a,c)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function e0(n,t,e,s){return t.rank<e.rank&&(t=W(t,re(t.shape,s))),n.rank<e.rank&&(n=W(n,re(n.shape,s))),{x:()=>E(n,st(Xn(e,t),n.dtype))}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const n0={kernelName:Ha,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,t,e)=>{const s=e,{reductionIndices:o}=s,r=t[0],i=t[1],a=It(o,r.shape),c=e0(n,i,r,a);return{x:()=>c.x()}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const VN={kernelName:Yr,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t;return{a:()=>E(n,st(oo(e,s),"float32")),b:()=>E(n,st(Wc(e,s),"float32"))}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function FN(n,t,e,s,o,r,i){const a=N(n,"dy","maxPool3dGrad"),c=N(t,"input","maxPool3dGrad"),l=N(e,"output","maxPool3dGrad");let u=a,d=c,h=l,p=!1;c.rank===4&&(p=!0,u=W(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]]),d=W(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]]),h=W(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]])),v(u.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${u.rank}.`),v(d.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${d.rank}.`),v(h.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${h.rank}.`),ze("maxPool3dGrad",r,i);const f={dy:u,input:d,output:h},m={filterSize:s,strides:o,pad:r,dimRoundingMode:i},g=G.runKernel(Gu,f,m);return p?W(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}const zN=D({maxPool3dGrad_:FN});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const XN={kernelName:Ua,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,t,e)=>{const[s,o]=t,{filterSize:r,strides:i,pad:a,dimRoundingMode:c}=e;return{x:()=>zN(n,s,o,r,i,a,c)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function AN(n,t,e,s,o,r,i){const a=N(n,"dy","maxPoolGrad"),c=N(t,"input","maxPoolGrad"),l=N(e,"output","maxPoolGrad");v(c.rank===a.rank,()=>`Rank of input (${c.rank}) does not match rank of dy (${a.rank})`),v(a.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${a.rank}.`),v(c.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${c.rank}.`),ze("maxPoolGrad",r,i);const u={dy:a,input:c,output:l},d={filterSize:s,strides:o,pad:r,dimRoundingMode:i};return G.runKernel($u,u,d)}const PN=D({maxPoolGrad_:AN});/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const ON={kernelName:_a,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,t,e)=>{const[s,o]=t,{filterSize:r,strides:i,pad:a}=e;return{x:()=>PN(n,s,o,r,i,a)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const KN={kernelName:Ya,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{axis:o}=e,r=It(o,s.shape),a=me(s.shape,r)[1],c=Z(a);return{x:()=>{const u=s.shape.slice();r.forEach(p=>{u[p]=1});const d=W(n,u);return dt(E(d,Ss(s.shape,"float32")),c)}}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const ZN={kernelName:Qa,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(n,t,e)=>{const s=e,{axis:o}=s,[r,i]=t,a=It(o,r.shape),c=e0(n,i,r,a);return{x:()=>c.x()}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const BN={kernelName:Qr,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t;return{a:()=>E(n,st(Qo(e,s),"float32")),b:()=>E(n,st(sn(e,s),"float32"))}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const HN={kernelName:Ja,inputsToSave:["x"],gradFunc:(n,t,e)=>{const s=t[0],{paddings:o}=e,r=o.map(i=>i[0]);return{x:()=>Xt(n,r,s.shape)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const _N={kernelName:Jr,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,o=gt(e.shape,s.shape);return{a:()=>{const a=ce(e.shape,o);return a.length>0?W(ut(n,a),e.shape):n},b:()=>{const a=E(n,ne(Dc(dt(e,s)))),c=ce(s.shape,o);return c.length>0?W(ut(a,c),s.shape):a}}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const UN={kernelName:jr,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,o=gt(e.shape,s.shape);return{a:()=>{const a=E(n,st(s,"float32")),c=ce(e.shape,o);return c.length>0?W(ut(a,c),e.shape):a},b:()=>{const a=E(n,st(e,"float32")),c=ce(s.shape,o);return c.length>0?W(ut(a,c),s.shape):a}}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const YN={kernelName:ja,gradFunc:n=>({x:()=>ne(n)})};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const QN={kernelName:ec,inputsToSave:["indices"],gradFunc:(n,t)=>{const e=t[0];return{indices:()=>ge(e.shape,"float32")}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const JN={kernelName:tc,gradFunc:n=>({x:()=>St(n)})};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const jN={kernelName:nc,saveAllInputs:!0,gradFunc:(n,t,e)=>{const{axis:s}=e;return lo(n,s).map(r=>()=>r)}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const s0={kernelName:sc,inputsToSave:["x"],gradFunc:(n,t,e)=>{const s=t[0],{paddings:o}=e,r=o.map(i=>i[0]);return{x:()=>Xt(n,r,s.shape)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const qN={kernelName:qr,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(n,t)=>{const[e,s,o]=t,r=e,i=s,a=gt(r.shape,i.shape);return{a:()=>{const u=st(i,"float32");let d=E(n,E(u,Yo(r,pt(u,Gt(1)))));const h=ce(r.shape,a);return h.length>0&&(d=ut(d,h)),W(d,r.shape)},b:()=>{const u=sn(r,0),d=Le(u,Pn(r),St(r));let h=E(n,E(o,d));const p=ce(i.shape,a);return p.length>0&&(h=ut(h,p)),W(h,i.shape)}}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const tR={kernelName:oc,inputsToSave:["x","alpha"],gradFunc:(n,t)=>{const[e,s]=t,o=sn(e,0);return{x:()=>Le(o,n,E(n,s)),alpha:()=>{let r=Le(o,St(n),E(n,e));const i=ce(s.shape,n.shape);return i.length>0&&(r=ut(r,i)),W(r,s.shape)}}}};/**
 * @license
 * Copyright 2022 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function eR(n,t,e){const s=n.shape.slice();s[e]=1;const o=W(t,s),r=bd(n,e,!0,!1),i=bd(n,e,!0,!0),a=E(r,i);return E(o,a)}function nR(n,t,e){const s=n.shape.length,o=s-e.length,r=Yt(e,s);let i=n;r!=null&&(i=kt(n,r));const a=i.shape.slice(),l=a.splice(s-e.length,e.length).reduce((h,p)=>h*p,1);a.push(l);const u=i.reshape(a);let d=eR(u,t,o);if(d=d.reshape(i.shape),r!=null){const h=Cs(r);d=kt(d,h)}return d}const sR={kernelName:rc,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{axis:o}=e;let r=[];return o==null?r=s.shape.map((i,a)=>a):typeof o=="number"?r=[o]:r=o,{x:()=>nR(s,n,r)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const oR={kernelName:Mr,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,o=gt(e.shape,s.shape);return{a:()=>{const a=dt(n,st(s,"float32")),c=ce(e.shape,o);return c.length>0?W(ut(a,c),e.shape):a},b:()=>{let a=E(n,st(e,"float32"));const c=ce(s.shape,o);c.length>0&&(a=W(ut(a,c),s.shape));const l=Bt(s);return ne(dt(a,st(l,"float32")))}}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const rR={kernelName:ti,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>dt(n,ne(Bt(e)))}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const iR={kernelName:ni,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t,s=E(Qo(e,6),Wi(e));return{x:()=>E(n,st(s,"float32"))}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const aR={kernelName:ei,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(n,st(Wi(e),"float32"))}}};/**
 * @license
 * Copyright 2020 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const cR={kernelName:ic,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>W(n,e.shape)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const lR={kernelName:cc,inputsToSave:["images"],gradFunc:(n,t,e)=>{const[s]=t,o={dy:n,images:s};return{images:()=>G.runKernel(Fu,o,e)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const uR={kernelName:ac,inputsToSave:["images"],gradFunc:(n,t,e)=>{const[s]=t,o={dy:n,images:s};return{images:()=>G.runKernel(Vu,o,e)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const dR={kernelName:lc,gradFunc:(n,t,e)=>{const{dims:s}=e,o=It(s,n.shape);return{x:()=>ao(n,o)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const hR={kernelName:si,gradFunc:n=>({x:()=>St(n)})};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const pR={kernelName:oi,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>ne(dt(n,E(Yo(e,1.5),2)))}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const fR={kernelName:uc,inputsToSave:["condition"],gradFunc:(n,t)=>{const[e]=t;return{condition:()=>st(St(e),"float32"),t:()=>E(n,st(e,n.dtype)),e:()=>E(n,st(vd(e),n.dtype))}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const mR={kernelName:ri,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>{const s=sn(e,Gt(0)),o=Gt(Pc),r=Gt(Oc),i=E(n,r),a=E(E(n,o),An(st(e,"float32")));return Le(s,i,a)}}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const gR={kernelName:li,outputsToSave:[!0],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(n,E(e,pt(Gt(1),e)))}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const bR={kernelName:ci,gradFunc:n=>({x:()=>St(n)})};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const xR={kernelName:ii,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(gd(st(e,"float32")),n)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const yR={kernelName:ai,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(Wm(st(e,"float32")),n)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const IR={kernelName:dc,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{begin:o,size:r}=e,i=s.shape,[a,c]=zc(s,o,r),l=[];for(let u=0;u<n.rank;u++)l.push([a[u],i[u]-a[u]-c[u]]);return{x:()=>Td(n,l)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const wR={kernelName:mc,outputsToSave:[!0],gradFunc:(n,t,e)=>{const[s]=t,{dim:o}=e,r=!0,i=E(n,s);return{logits:()=>pt(i,E(ut(i,[o],r),s))}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const CR={kernelName:ui,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(n,_o(e))}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const o0={kernelName:pc,gradFunc:(n,t,e)=>{const{blockShape:s,paddings:o}=e;return{x:()=>fd(n,s,o)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const r0={kernelName:fc,gradFunc:(n,t,e)=>{const{axis:s}=e;return{x:()=>Xe(n,s)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const vR={kernelName:di,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>dt(n,E(Ee(st(e,"float32")),2))}}};/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const SR={kernelName:zu,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(n,E(st(e,"float32"),2))}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const kR={kernelName:hi,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,o=Gt(2);return{a:()=>E(n,E(o,pt(e,s))),b:()=>E(n,E(o,pt(s,e)))}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const TR={kernelName:bi,gradFunc:n=>({x:()=>St(n)})};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const NR={kernelName:pi,inputsToSave:["a","b"],gradFunc:(n,t)=>{const[e,s]=t,o=gt(e.shape,s.shape);return{a:()=>{let a=n;const c=ce(e.shape,o);return c.length>0&&(a=ut(a,c)),W(a,e.shape)},b:()=>{let a=n;const c=ce(s.shape,o);return c.length>0&&(a=ut(a,c)),W(ne(a),s.shape)}}}};/**
 * @license
 * Copyright 2020 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const RR={kernelName:hc,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,o=s.shape.slice(),{axis:r}=e;It(r,s.shape).forEach(l=>{o[l]=1});const a=W(n,o),c=E(a,Ss(s.shape,"float32"));return{x:()=>c}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const $R={kernelName:fi,inputsToSave:["x"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>dt(n,Bt(gd(e)))}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const GR={kernelName:mi,outputsToSave:[!0],gradFunc:(n,t)=>{const[e]=t;return{x:()=>E(pt(Gt(1),Bt(e)),n)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const LR={kernelName:gi,inputsToSave:["x"],gradFunc:(n,t,e)=>{const[s]=t,{reps:o}=e;return{x:()=>{let i=St(s);if(s.rank===1)for(let a=0;a<o[0];++a)i=Q(i,Xt(n,[a*s.shape[0]],[s.shape[0]]));else if(s.rank===2)for(let a=0;a<o[0];++a)for(let c=0;c<o[1];++c)i=Q(i,Xt(n,[a*s.shape[0],c*s.shape[1]],[s.shape[0],s.shape[1]]));else if(s.rank===3)for(let a=0;a<o[0];++a)for(let c=0;c<o[1];++c)for(let l=0;l<o[2];++l)i=Q(i,Xt(n,[a*s.shape[0],c*s.shape[1],l*s.shape[2]],[s.shape[0],s.shape[1],s.shape[2]]));else if(s.rank===4)for(let a=0;a<o[0];++a)for(let c=0;c<o[1];++c)for(let l=0;l<o[2];++l)for(let u=0;u<o[3];++u)i=Q(i,Xt(n,[a*s.shape[0],c*s.shape[1],l*s.shape[2],u*s.shape[3]],[s.shape[0],s.shape[1],s.shape[2],s.shape[3]]));else throw new Error(`Gradient for tile operation is not implemented for rank-${s.rank} tensors yet.`);return i}}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const ER={kernelName:zo,gradFunc:(n,t,e)=>{const s=e,{perm:o}=s,r=Cs(o);return{x:()=>kt(n,r)}}};/**
 * @license
 * Copyright 2020 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const DR={kernelName:gc,gradFunc:(n,t,e)=>{const s=e,{axis:o}=s;return{value:()=>On(n,o)}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const WR={kernelName:bc,inputsToSave:["segmentIds"],gradFunc:(n,t)=>{const[e]=t;return{x:()=>MR(n,e)}}};function MR(n,t){const e=vs(t,St(t)),s=Id(n,e);let o=oo(t,Gt(0,"int32"));const r=s.rank-o.rank;for(let a=0;a<r;++a)o=Ae(o,a+1);o=rs(o,Ss(s.shape,"bool"));const i=St(s);return Le(o,s,i)}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const VR={kernelName:xc,gradFunc:n=>({x:()=>St(n)})};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const FR=[jg,WT,MT,VT,FT,zT,XT,AT,PT,OT,KT,ZT,_T,QT,JT,jT,qT,tN,eN,nN,sN,oN,iN,rN,lN,uN,dN,hN,pN,fN,oR,mN,gN,bN,xN,yN,wN,IN,CN,vN,SN,kN,TN,NN,RN,$N,GN,LN,EN,MN,n0,n0,VN,XN,ON,KN,ZN,BN,HN,_N,UN,YN,QN,JN,jN,s0,s0,qN,tR,sR,rR,iR,aR,cR,lR,uR,dR,hR,pR,fR,mR,gR,bR,xR,yR,IR,wR,CR,o0,o0,r0,r0,vR,kR,SR,TR,NR,RR,$R,GR,LR,ER,DR,WR,VR];for(const n of FR)mw(n);/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.abs=function(){return this.throwIfDisposed(),Ge(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.acos=function(){return this.throwIfDisposed(),bC(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.acosh=function(){return this.throwIfDisposed(),yC(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.add=function(n){return this.throwIfDisposed(),Q(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.all=function(n,t){return this.throwIfDisposed(),Gm(this,n,t)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.any=function(n,t){return this.throwIfDisposed(),ld(this,n,t)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.argMax=function(n){return this.throwIfDisposed(),vi(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.argMin=function(n){return this.throwIfDisposed(),SC(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.asScalar=function(){return this.throwIfDisposed(),v(this.size===1,()=>"The array must have only 1 element."),W(this,[])};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.asType=function(n){return this.throwIfDisposed(),st(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.as1D=function(){return this.throwIfDisposed(),W(this,[this.size])};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.as2D=function(n,t){return this.throwIfDisposed(),W(this,[n,t])};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.as3D=function(n,t,e){return this.throwIfDisposed(),W(this,[n,t,e])};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.as4D=function(n,t,e,s){return this.throwIfDisposed(),W(this,[n,t,e,s])};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.as5D=function(n,t,e,s,o){return this.throwIfDisposed(),W(this,[n,t,e,s,o])};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.asin=function(){return this.throwIfDisposed(),TC(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.asinh=function(){return this.throwIfDisposed(),RC(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.atan=function(){return this.throwIfDisposed(),GC(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.atan2=function(n){return this.throwIfDisposed(),EC(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.atanh=function(){return this.throwIfDisposed(),WC(this)},O().prototype.avgPool=function(n,t,e,s){return this.throwIfDisposed(),hd(this,n,t,e,s)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.batchToSpaceND=function(n,t){return this.throwIfDisposed(),fd(this,n,t)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.batchNorm=function(n,t,e,s,o){return this.throwIfDisposed(),Rc(this,n,t,e,s,o)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.broadcastTo=function(n){return this.throwIfDisposed(),Ni(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.cast=function(n){return this.throwIfDisposed(),st(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.ceil=function(){return this.throwIfDisposed(),a2(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.clipByValue=function(n,t){return this.throwIfDisposed(),nn(this,n,t)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.concat=function(n,t){return this.throwIfDisposed(),n instanceof ae&&(n=[n]),Xe([this,...n],t)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.conv1d=function(n,t,e,s,o,r){return this.throwIfDisposed(),Lm(this,n,t,e,s,o,r)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.conv2dTranspose=function(n,t,e,s,o){return this.throwIfDisposed(),Em(this,n,t,e,s,o)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.conv2d=function(n,t,e,s,o,r){return this.throwIfDisposed(),so(this,n,t,e,s,o,r)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.cos=function(){return this.throwIfDisposed(),gd(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.cosh=function(){return this.throwIfDisposed(),Wm(this)};/**
 * @license
 * Copyright 2022 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.cumprod=function(n,t,e){return this.throwIfDisposed(),bd(this,n,t,e)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.cumsum=function(n,t,e){return this.throwIfDisposed(),Mm(this,n,t,e)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.depthToSpace=function(n,t){return this.throwIfDisposed(),E2(this,n,t)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.depthwiseConv2d=function(n,t,e,s,o,r){return this.throwIfDisposed(),xd(this,n,t,e,s,o,r)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.dilation2d=function(n,t,e,s,o){return this.throwIfDisposed(),M2(this,n,t,e,s,o)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.divNoNan=function(n){return this.throwIfDisposed(),A2(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.div=function(n){return this.throwIfDisposed(),dt(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.dot=function(n){return this.throwIfDisposed(),O2(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.elu=function(){return this.throwIfDisposed(),Gc(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.equal=function(n){return this.throwIfDisposed(),Xn(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.erf=function(){return this.throwIfDisposed(),H2(this)};/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.euclideanNorm=function(n,t){return this.throwIfDisposed(),ev(this,n,t)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.exp=function(){return this.throwIfDisposed(),An(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.expandDims=function(n){return this.throwIfDisposed(),Ae(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.expm1=function(){return this.throwIfDisposed(),rv(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.fft=function(){return this.throwIfDisposed(),eg(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.flatten=function(){return this.throwIfDisposed(),W(this,[this.size])};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.floor=function(){return this.throwIfDisposed(),Dc(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.floorDiv=function(n){return this.throwIfDisposed(),$m(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.gather=function(n,t,e){return this.throwIfDisposed(),Id(this,n,t,e)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.greaterEqual=function(n){return this.throwIfDisposed(),oo(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.greater=function(n){return this.throwIfDisposed(),sn(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.ifft=function(){return this.throwIfDisposed(),Xd(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.irfft=function(){return this.throwIfDisposed(),US(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.isFinite=function(){return this.throwIfDisposed(),fv(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.isInf=function(){return this.throwIfDisposed(),gv(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.isNaN=function(){return this.throwIfDisposed(),xv(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.leakyRelu=function(n){return this.throwIfDisposed(),Cd(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.lessEqual=function(n){return this.throwIfDisposed(),Qo(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.less=function(n){return this.throwIfDisposed(),Wc(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.localResponseNormalization=function(n,t,e,s){return this.throwIfDisposed(),vv(this,n,t,e,s)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.logSigmoid=function(){return this.throwIfDisposed(),Gv(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.logSoftmax=function(n){return this.throwIfDisposed(),Pm(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.logSumExp=function(n,t){return this.throwIfDisposed(),Om(this,n,t)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.log=function(){return this.throwIfDisposed(),Pn(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.log1p=function(){return this.throwIfDisposed(),Am(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.logicalAnd=function(n){return this.throwIfDisposed(),rs(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.logicalNot=function(){return this.throwIfDisposed(),vd(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.logicalOr=function(n){return this.throwIfDisposed(),Km(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.logicalXor=function(n){return this.throwIfDisposed(),zv(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.matMul=function(n,t,e){return this.throwIfDisposed(),$t(this,n,t,e)},O().prototype.maxPool=function(n,t,e,s){return this.throwIfDisposed(),Sd(this,n,t,e,s)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.max=function(n,t){return this.throwIfDisposed(),Tn(this,n,t)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.maximum=function(n){return this.throwIfDisposed(),vs(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.mean=function(n,t){return this.throwIfDisposed(),ie(this,n,t)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.min=function(n,t){return this.throwIfDisposed(),Lc(this,n,t)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.minimum=function(n){return this.throwIfDisposed(),Gi(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.mirrorPad=function(n,t){return this.throwIfDisposed(),Hv(this,n,t)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.mod=function(n){return this.throwIfDisposed(),Uv(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.mul=function(n){return this.throwIfDisposed(),E(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.neg=function(){return this.throwIfDisposed(),ne(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.norm=function(n,t,e){return this.throwIfDisposed(),Ec(this,n,t,e)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.notEqual=function(n){return this.throwIfDisposed(),Mc(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.oneHot=function(n,t=1,e=0){return this.throwIfDisposed(),Zm(this,n,t,e)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.onesLike=function(){return this.throwIfDisposed(),fn(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.pad=function(n,t){return this.throwIfDisposed(),Td(this,n,t)},O().prototype.pool=function(n,t,e,s,o,r){return this.throwIfDisposed(),oS(this,n,t,e,s,o,r)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.pow=function(n){return this.throwIfDisposed(),Yo(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.prelu=function(n){return this.throwIfDisposed(),Rd(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.prod=function(n,t){return this.throwIfDisposed(),aS(this,n,t)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.reciprocal=function(){return this.throwIfDisposed(),RS(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.relu=function(){return this.throwIfDisposed(),io(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.relu6=function(){return this.throwIfDisposed(),_m(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.reshapeAs=function(n){return this.throwIfDisposed(),W(this,n.shape)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.reshape=function(n){return this.throwIfDisposed(),W(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.resizeBilinear=function(n,t,e){return this.throwIfDisposed(),cg(this,n,t,e)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.resizeNearestNeighbor=function(n,t,e){return this.throwIfDisposed(),lg(this,n,t,e)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.reverse=function(n){return this.throwIfDisposed(),ao(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.rfft=function(){return this.throwIfDisposed(),JS(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.round=function(){return this.throwIfDisposed(),Um(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.rsqrt=function(){return this.throwIfDisposed(),Ym(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.selu=function(){return this.throwIfDisposed(),Qm(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.separableConv2d=function(n,t,e,s,o,r){return this.throwIfDisposed(),Jm(this,n,t,e,s,o,r)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.sigmoid=function(){return this.throwIfDisposed(),_o(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.sign=function(){return this.throwIfDisposed(),FS(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.sin=function(){return this.throwIfDisposed(),jm(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.sinh=function(){return this.throwIfDisposed(),qm(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.slice=function(n,t){return this.throwIfDisposed(),Xt(this,n,t)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.softmax=function(n){return this.throwIfDisposed(),zd(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.softplus=function(){return this.throwIfDisposed(),$i(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.spaceToBatchND=function(n,t){return this.throwIfDisposed(),Nd(this,n,t)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.split=function(n,t){return this.throwIfDisposed(),on(this,n,t)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.sqrt=function(){return this.throwIfDisposed(),Ee(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.square=function(){return this.throwIfDisposed(),Bt(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.squaredDifference=function(n){return this.throwIfDisposed(),qS(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.squeeze=function(n){return this.throwIfDisposed(),Di(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.stack=function(n,t){this.throwIfDisposed();const e=n instanceof ae?[this,n]:[this,...n];return On(e,t)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.step=function(n){return this.throwIfDisposed(),Wi(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.stridedSlice=function(n,t,e,s,o,r,i,a){return this.throwIfDisposed(),ok(this,n,t,e,s,o,r,i,a)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.sub=function(n){return this.throwIfDisposed(),pt(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.sum=function(n,t){return this.throwIfDisposed(),ut(this,n,t)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.tan=function(){return this.throwIfDisposed(),ik(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.tanh=function(){return this.throwIfDisposed(),pd(this)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.tile=function(n){return this.throwIfDisposed(),Nn(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.toBool=function(){return this.throwIfDisposed(),st(this,"bool")};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.toFloat=function(){return this.throwIfDisposed(),st(this,"float32")};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.toInt=function(){return this.throwIfDisposed(),st(this,"int32")};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.topk=function(n,t){return this.throwIfDisposed(),uk(this,n,t)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.transpose=function(n){return this.throwIfDisposed(),kt(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.unique=function(n){return this.throwIfDisposed(),pk(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.unsortedSegmentSum=function(n,t){return this.throwIfDisposed(),og(this,n,t)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.unstack=function(n){return this.throwIfDisposed(),lo(this,n)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.where=function(n,t){return this.throwIfDisposed(),Le(n,this,t)};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */O().prototype.zerosLike=function(){return this.throwIfDisposed(),St(this)};/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */class Zn extends Error{constructor(t){super(t),Object.setPrototypeOf(this,Zn.prototype)}}class gn extends Error{constructor(t){super(t),Object.setPrototypeOf(this,gn.prototype)}}class $ extends Error{constructor(t){super(t),Object.setPrototypeOf(this,$.prototype)}}class bt extends Error{constructor(t){super(t),Object.setPrototypeOf(this,bt.prototype)}}class kh extends Error{constructor(t){super(t),Object.setPrototypeOf(this,kh.prototype)}}/**
 * @license
 * Copyright 2022 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */class i0{constructor(t){this.maxEntries=t||100,this.cache=new Map}get(t){let e;return this.cache.has(t)&&(e=this.cache.get(t),this.cache.delete(t),this.cache.set(t,e)),e}put(t,e){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.maxEntries){const s=this.cache.keys().next().value;this.cache.delete(s)}this.cache.set(t,e)}getMaxEntries(){return this.maxEntries}setMaxEntries(t){if(t<0)throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${t}.`);if(this.maxEntries>t)for(let e=0;e<this.maxEntries-t;e++){const s=this.cache.keys().next().value;this.cache.delete(s)}this.maxEntries=t}}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function ho(n,t){if(Array.isArray(n)){let e=[];for(let s=0;s<t;s++)e=e.concat(n);return e}else{const e=new Array(t);return e.fill(n),e}}function Bn(n,t){if(!n)throw new kh(t)}function a0(n,t){let e=0;for(const s of n)s===t&&e++;return e}function Pe(n){return n.length===1?n[0]:n}function Lt(n){return Array.isArray(n)?n:[n]}function ls(n){const e=n.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return e[0]!=="_"?e:"private"+e}function po(n){return n.length<=1||n.indexOf("_")===-1?n:n.replace(/[_]+(\w|$)/g,(t,e)=>e.toUpperCase())}let bn={};function Th(n){if(n==null)return null;const t={};return t.className=n.getClassName(),t.config=n.getConfig(),t}function Nh(n){if(!(n==null||typeof n!="object"))if(Array.isArray(n))n.forEach(t=>Nh(t));else{const t=Object.keys(n);for(const e of t){const s=n[e];s!=null&&typeof s=="object"&&(!Array.isArray(s)&&s.type==="ndarray"&&typeof s.value=="number"?n[e]=s.value:Nh(s))}}}function zi(n,t={},e={},s="object",o=!1){if(typeof n=="string"){const r=n;let i;if(r in e)i=e[r];else if(r in bn)i=bn[r];else if(i=t[r],i==null)throw new $(`Unknown ${s}: ${n}. This may be due to one of the following reasons:
1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return i}else{const r=n;if(r.className==null||r.config==null)throw new $(`${s}: Improper config format: ${JSON.stringify(r)}.
'className' and 'config' must set.`);const i=r.className;let a,c;if(i in e?[a,c]=e[i]:i in bn?[a,c]=bn.className:i in t&&([a,c]=t[i]),a==null)throw new $(`Unknown ${s}: ${i}. This may be due to one of the following reasons:
1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(c!=null){const l={};for(const p of Object.keys(bn))l[p]=bn[p];for(const p of Object.keys(e))l[p]=e[p];const u=r.config;u.customObjects=l;const d=Object.assign({},bn);for(const p of Object.keys(e))bn[p]=e[p];Nh(r.config);const h=c(a,r.config,e,o);return bn=Object.assign({},d),h}else{const l=Object.assign({},bn);for(const d of Object.keys(e))bn[d]=e[d];const u=new a(r.config);return bn=Object.assign({},l),u}}}function zR(n,t){return n<t?-1:n>t?1:0}function Kc(n,t){return-1*zR(n,t)}function Ts(n){if(n==null)return n;const t=[];for(const e of n)t.indexOf(e)===-1&&t.push(e);return t}function XR(n){if(n==null)throw new $(`Invalid value in obj: ${JSON.stringify(n)}`);for(const t in n)if(n.hasOwnProperty(t))return!1;return!0}function fo(n,t,e){if(e!=null&&n.indexOf(e)<0)throw new $(`${e} is not a valid ${t}.  Valid values are ${n} or null/undefined.`)}function Rh(n,t,e=0,s=1/0){return Bn(e>=0),Bn(s>=e),Array.isArray(n)&&n.length>=e&&n.length<=s&&n.every(o=>typeof o===t)}function be(n,t){Array.isArray(n)?(v(n.length>0,()=>`${t} is unexpectedly an empty array.`),n.forEach((e,s)=>be(e,`element ${s+1} of ${t}`))):v(Number.isInteger(n)&&n>0,()=>`Expected ${t} to be a positive integer, but got ${c0(n)}.`)}function c0(n){return n===null?"null":Array.isArray(n)?"["+n.map(t=>c0(t)).join(",")+"]":typeof n=="string"?`"${n}"`:`${n}`}function AR(n,t,e){let s=e!=null?e():Ve(),o;return(...i)=>{const a=e!=null?e():Ve();return a-s<t||(s=a,o=n(...i)),o}}function l0(n){return n==="relu"?"relu":n==="linear"?"linear":n==="elu"?"elu":null}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */let PR=0;function u0(){return PR++}const Zc={};function Bc(n=""){return n in Zc||(Zc[n]=0),Zc[n]+=1,n+Zc[n].toString()}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */const OR=["channelsFirst","channelsLast"],KR=["nearest","bilinear"],ZR=["valid","same","causal"],BR=["max","avg"],HR=["sum","mul","concat","ave"];/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */const er=new Map;function se(n){fo(OR,"DataFormat",n)}function _R(n){fo(KR,"InterpolationFormat",n)}function rn(n){fo(ZR,"PaddingMode",n)}function d0(n){fo(BR,"PoolMode",n)}const Xi=[],h0="/";function mo(n,t){Xi.push(n);try{const e=t();return Xi.pop(),e}catch(e){throw Xi.pop(),e}}function UR(){return Xi.length===0?"":Xi.join(h0)+h0}function p0(n){if(!m0(n))throw new Error("Not a valid tensor name: '"+n+"'");return UR()+n}function f0(n){if(!m0(n))throw new Error("Not a valid tensor name: '"+n+"'");er.has(n)||er.set(n,0);const t=er.get(n);if(er.set(n,er.get(n)+1),t>0){const e=`${n}_${t}`;return er.set(e,1),e}else return n}const YR=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function m0(n){return!!n.match(YR)}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function QR(n){return n===parseInt(n.toString(),10)}function Ns(n,t,e){t==null&&(t=0),e==null&&(e=n.length);let s=1;for(let o=t;o<e;++o)s*=n[o];return s}function nr(n){if(n.length===0)return Number.NaN;let t=Number.POSITIVE_INFINITY;for(let e=0;e<n.length;e++){const s=n[e];s<t&&(t=s)}return t}function Rs(n){if(n.length===0)return Number.NaN;let t=Number.NEGATIVE_INFINITY;for(let e=0;e<n.length;e++){const s=n[e];s>t&&(t=s)}return t}function $n(n,t){if(t<n)throw new $(`end (${t}) < begin (${n}) is forbidden.`);const e=[];for(let s=n;s<t;++s)e.push(s);return e}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */let $h;function le(){return $h==null&&($h=ys().epsilon()),$h}function Gn(){return"channelsLast"}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function Hn(n,t){return st(n,t)}function Ai(n,t=-1){const e=n.shape.slice();return t<0&&(t=e.length+t+1),e.splice(t,0,1),W(n,e)}function JR(n,t){return M(()=>{if(n.shape.length!==2)throw new $(`repeat() expects a rank-2 tensor, but received a rank-${n.shape.length} tensor.`);const e=Ai(n,1);return Eh(e,[1,t,1])})}function jR(n){const t=[Ns(n.shape)];return W(n,t)}function qR(n){if(n.rank<=1)throw new $(`batchFlatten requires a minimum rank of 2. Got rank: ${n.rank}.`);const t=[n.shape[0],Ns(n.shape,1)];return W(n,t)}function go(n,t,e){return M(()=>{switch(n.rank){case 1:return Vd(n,t,e);case 2:return tg(n,[t,0],[e,n.shape[1]]);case 3:return Fd(n,[t,0,0],[e,n.shape[1],n.shape[2]]);case 4:return Fc(n,[t,0,0,0],[e,n.shape[1],n.shape[2],n.shape[3]]);case 5:return Xt(n,[t,0,0,0,0],[e,n.shape[1],n.shape[2],n.shape[3],n.shape[4]]);case 6:return Xt(n,[t,0,0,0,0,0],[e,n.shape[1],n.shape[2],n.shape[3],n.shape[4],n.shape[5]]);default:throw new $(`sliceAlongFirstAxis() received an unsupported tensor rank: ${n.rank}`)}})}function Gh(n,t,e){return M(()=>{switch(n.rank){case 1:return Vd(n,t,e);case 2:return tg(n,[0,t],[n.shape[0],e]);case 3:return Fd(n,[0,0,t],[n.shape[0],n.shape[1],e]);case 4:return Fc(n,[0,0,0,t],[n.shape[0],n.shape[1],n.shape[2],e]);default:throw new $(`sliceAlongLastAxis() received an unsupported tensor rank: ${n.rank}`)}})}function Hc(n,t,e,s){return M(()=>{switch(n.rank){case 1:return Vd(n,t,e);case 2:switch(s){case 1:return go(n,t,e);case 2:return Gh(n,t,e);default:throw new $(`The axis is not within the rank of the tensor ${s}`)}case 3:switch(s){case 1:return go(n,t,e);case 2:return Fd(n,[0,t,0],[n.shape[0],e,n.shape[2]]);case 3:return Gh(n,t,e);default:throw new $(`The axis is not within the rank of the tensor ${s}`)}case 4:switch(s){case 1:return go(n,t,e);case 2:return Fc(n,[0,t,0,0],[n.shape[0],e,n.shape[2],n.shape[3]]);case 3:return Fc(n,[0,0,t,0],[n.shape[0],n.shape[1],e,n.shape[3]]);case 4:return Gh(n,t,e);default:throw new $(`The axis is not within the rank of the tensor ${s}`)}default:throw new $(`sliceAlongLastAxis() received an unsupported tensor rank: ${n.rank}`)}})}function Lh(n,t=-1){let e;return t<0&&(e=n[0].rank,e!==0?t=e:t=0),t===n[0].rank&&(t=-1),Xe(n,t)}function g0(n,t){switch(n.rank){case 1:return u2([n,t]);case 2:return h2([n,t],0);case 3:return f2([n,t],0);case 4:return g2([n,t],0);default:throw new $(`concatAlongFirstAxis() received an unsupported tensor rank: ${n.rank}`)}}function Eh(n,t){if(Array.isArray(t)||(t=[t]),n.rank!==t.length)throw new $(`The length of input n (${t.length}) does not match the number of dimensions in input x (${n.rank})`);return Nn(n,t)}function _c(n,t=0,e=1,s,o){return SS(n,t,e,s,o)}function _n(n,t,e,s){if(n.rank<2||t.rank<2)throw new bt(`dot requires both inputs to be rank >= 2 but got x shape = ${n.shape} and y shape = ${t.shape}`);if(t.rank>=3){const o=n.shape.slice(-1)[0],r=t.shape.slice(-2)[0];if(o!==r)throw new bt(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${n.shape} and  y shape = ${t.shape}`)}if(n.rank===2&&t.rank===2)return ig({a:n,b:t,transposeA:!1,transposeB:!1,bias:s?Dh(n.rank,s,Gn()):null,activation:e});{const o=n.shape.slice(),r=o.pop();n=W(n,[-1,r]);const i=t.shape.slice(),a=i.pop(),c=i.pop(),l=[...i,a],u=Array.from({length:t.rank},(f,m)=>m===0?t.rank-2:m<=t.rank-2?m-1:m);t=W(kt(t,u),[c,-1]);const d=[...o,...l];return W(ig({a:n,b:t,transposeA:!1,transposeB:!1,bias:s?Dh(n.rank,s,Gn()):null,activation:e}),d)}}function b0(n,t,e){return M(()=>(Array.isArray(t)?t=Ue(t,"int32"):t=st(t,"int32"),Id(n,t,e)))}function Pi(n){return E(n,n)}function Dh(n,t,e){const s=t.shape;if(t.rank!==1&&t.rank!==n)throw new $(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${n}`);if(n===5){if(e==="channelsFirst")return s.length===1?W(t,[1,s[0],1,1,1]):W(t,[1,s[3],s[0],s[1],s[2]]);if(e==="channelsLast")return s.length===1?W(t,[1,1,1,1,s[0]]):W(t,[1].concat(s))}else if(n===4){if(e==="channelsFirst")return s.length===1?W(t,[1,s[0],1,1]):W(t,[1,s[2],s[0],s[1]]);if(e==="channelsLast")return s.length===1?W(t,[1,1,1,s[0]]):W(t,[1].concat(s))}else if(n===3){if(e==="channelsFirst")return s.length===1?W(t,[1,s[0],1]):W(t,[1,s[1],s[0]]);if(e==="channelsLast")return s.length===1?W(t,[1,1,s[0]]):W(t,[1].concat(s))}else if(n<3)return t;throw new $(`Unsupported input rank by biasAdd: ${t.rank}`)}function Ln(n,t,e){return M(()=>(e==null&&(e=Gn()),se(e),Q(n,Dh(n.rank,t,e))))}function t$(n,t=1){if(t!==1)throw new bt(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return Gc(n)}function e$(n){return M(()=>dt(n,Q(Ge(n),1)))}function x0(n,t,e,s){return M(()=>Ik(n,t,e,s))}function n$(n){return M(()=>{const t=Q(.5,E(.2,n));return nn(t,0,1)})}function Oi(n,t,e=!1){return e?n():t()}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */const s$=["fanIn","fanOut","fanAvg"],o$=["normal","uniform","truncatedNormal"];/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function r$(n){fo(s$,"FanMode",n)}function i$(n){fo(o$,"Distribution",n)}class xn extends qo{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class y0 extends xn{apply(t,e){return ge(t,e)}}y0.className="Zeros",_(y0);class Wh extends xn{apply(t,e){return Ss(t,e)}}Wh.className="Ones",_(Wh);class I0 extends xn{constructor(t){if(super(),typeof t!="object")throw new $(`Expected argument of type ConstantConfig but got ${t}`);if(t.value===void 0)throw new $(`config must have value set but got ${t}`);this.value=t.value}apply(t,e){return M(()=>E(Gt(this.value),Ss(t,e)))}getConfig(){return{value:this.value}}}I0.className="Constant",_(I0);class w0 extends xn{constructor(t){super(),this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=t.minval||this.DEFAULT_MINVAL,this.maxval=t.maxval||this.DEFAULT_MAXVAL,this.seed=t.seed}apply(t,e){return Li(t,this.minval,this.maxval,e,this.seed)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}w0.className="RandomUniform",_(w0);class C0 extends xn{constructor(t){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=t.mean||this.DEFAULT_MEAN,this.stddev=t.stddev||this.DEFAULT_STDDEV,this.seed=t.seed}apply(t,e){if(e=e||"float32",e!=="float32"&&e!=="int32")throw new bt(`randomNormal does not support dType ${e}.`);return _c(t,this.mean,this.stddev,e,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}C0.className="RandomNormal",_(C0);class v0 extends xn{constructor(t){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=t.mean||this.DEFAULT_MEAN,this.stddev=t.stddev||this.DEFAULT_STDDEV,this.seed=t.seed}apply(t,e){if(e=e||"float32",e!=="float32"&&e!=="int32")throw new bt(`truncatedNormal does not support dType ${e}.`);return sg(t,this.mean,this.stddev,e,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}v0.className="TruncatedNormal",_(v0);class S0 extends xn{constructor(t){super(),this.gain=t.gain!=null?t.gain:1}apply(t,e){return M(()=>{if(t.length!==2||t[0]!==t[1])throw new $("Identity matrix initializer can only be used for 2D square matrices.");return E(this.gain,Xm(t[0]))})}getConfig(){return{gain:this.gain}}}S0.className="Identity",_(S0);function a$(n,t="channelsLast"){let e,s;if(se(t),n.length===2)e=n[0],s=n[1];else if([3,4,5].indexOf(n.length)!==-1){if(t==="channelsFirst"){const o=Ns(n,2);e=n[1]*o,s=n[0]*o}else if(t==="channelsLast"){const o=Ns(n,0,n.length-2);e=n[n.length-2]*o,s=n[n.length-1]*o}}else{const o=Ns(n);e=Math.sqrt(o),s=Math.sqrt(o)}return[e,s]}class Ye extends xn{constructor(t){if(super(),t.scale<0)throw new $(`scale must be a positive float. Got: ${t.scale}`);this.scale=t.scale==null?1:t.scale,this.mode=t.mode==null?"fanIn":t.mode,r$(this.mode),this.distribution=t.distribution==null?"normal":t.distribution,i$(this.distribution),this.seed=t.seed}apply(t,e){const s=a$(t),o=s[0],r=s[1];let i=this.scale;if(this.mode==="fanIn"?i/=Math.max(1,o):this.mode==="fanOut"?i/=Math.max(1,r):i/=Math.max(1,(o+r)/2),this.distribution==="normal"){const a=Math.sqrt(i);if(e=e||"float32",e!=="float32"&&e!=="int32")throw new bt(`${this.getClassName()} does not support dType ${e}.`);return sg(t,0,a,e,this.seed)}else{const a=Math.sqrt(3*i);return Li(t,-a,a,e,this.seed)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}Ye.className="VarianceScaling",_(Ye);class Mh extends Ye{constructor(t){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:t==null?null:t.seed})}getClassName(){return Ye.className}}Mh.className="GlorotUniform",_(Mh);class Vh extends Ye{constructor(t){super({scale:1,mode:"fanAvg",distribution:"normal",seed:t==null?null:t.seed})}getClassName(){return Ye.className}}Vh.className="GlorotNormal",_(Vh);class Fh extends Ye{constructor(t){super({scale:2,mode:"fanIn",distribution:"normal",seed:t==null?null:t.seed})}getClassName(){return Ye.className}}Fh.className="HeNormal",_(Fh);class zh extends Ye{constructor(t){super({scale:2,mode:"fanIn",distribution:"uniform",seed:t==null?null:t.seed})}getClassName(){return Ye.className}}zh.className="HeUniform",_(zh);class Xh extends Ye{constructor(t){super({scale:1,mode:"fanIn",distribution:"normal",seed:t==null?null:t.seed})}getClassName(){return Ye.className}}Xh.className="LeCunNormal",_(Xh);class Ah extends Ye{constructor(t){super({scale:1,mode:"fanIn",distribution:"uniform",seed:t==null?null:t.seed})}getClassName(){return Ye.className}}Ah.className="LeCunUniform",_(Ah);class k0 extends xn{constructor(t){super(),this.DEFAULT_GAIN=1,this.ELEMENTS_WARN_SLOW=2e3,this.gain=t.gain==null?this.DEFAULT_GAIN:t.gain,this.seed=t.seed}apply(t,e){return M(()=>{if(t.length<2)throw new bt("Shape must be at least 2D.");if(e!=="int32"&&e!=="float32"&&e!==void 0)throw new TypeError(`Unsupported data type ${e}.`);e=e;const s=Z(t.slice(0,-1)),o=t[t.length-1],r=s*o;r>this.ELEMENTS_WARN_SLOW&&console.warn(`Orthogonal initializer is being called on a matrix with more than ${this.ELEMENTS_WARN_SLOW} (${r}) elements: Slowness may result.`);const i=[Math.max(o,s),Math.min(o,s)],a=_c(i,0,1,e,this.seed),c=gT.qr(a,!1);let l=c[0];const d=c[1].flatten().stridedSlice([0],[Math.min(o,s)*Math.min(o,s)],[Math.min(o,s)+1]);return l=E(l,d.sign()),s<o&&(l=l.transpose()),E(Gt(this.gain),l.reshape(t))})}getConfig(){return{gain:this.gain,seed:this.seed}}}k0.className="Orthogonal",_(k0);const T0={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 N0(n,t={}){return zi(n,mn.getMap().classNameMap,t,"initializer")}function Qt(n){return Th(n)}function Ht(n){if(typeof n=="string"){const t=n in T0?T0[n]:n;if(t==="GlorotNormal")return new Vh;if(t==="GlorotUniform")return new Mh;if(t==="HeNormal")return new Fh;if(t==="HeUniform")return new zh;if(t==="LeCunNormal")return new Xh;if(t==="LeCunUniform")return new Ah;{const e={};return e.className=t,e.config={},N0(e)}}else return n instanceof xn?n:N0(n)}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function Ph(n){return Array.isArray(n)&&Array.isArray(n[0])}function Uc(n){return n.length===0?[]:Array.isArray(n[0])?n:[n]}function mt(n){let t;if(Array.isArray(n)){if(n.length!==1)throw new $(`Expected Tensor length to be 1; got ${n.length}`);t=n[0]}else t=n;return t}function Nt(n){if(Array.isArray(n)&&Array.isArray(n[0])){if(n.length===1)return n=n,n[0];throw new $(`Expected exactly 1 Shape; got ${n.length}`)}else return n}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function Yc(n){let t=0;for(const e of n)e.shape.length===0?t+=1:t+=e.shape.reduce((s,o)=>s*o);return t}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */const R0="Variable";class c${constructor(t,e="float32",s=R0,o=!0,r=null){this.dtype=e??"float32",this.shape=t.shape,this.id=u0(),s=s??R0,this.originalName=p0(s),this.name=f0(this.originalName),this.trainable_=o,this.constraint=r,this.val=gk(t,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(t){return this.assertNotDisposed(),l$(this.val,t),this.val.id!==t.id&&(this.val.assign(t),this.constraint!=null&&this.val.assign(this.constraint.apply(this.val))),this}dispose(){this.assertNotDisposed(),this.val.dispose()}assertNotDisposed(){if(this.val.isDisposed)throw new Error(`LayersVariable ${this.name} is already disposed.`)}get trainable(){return this.trainable_}set trainable(t){this.trainable_=t,this.val.trainable=t}}function l$(n,t){if(n.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(n.shape)+" vs. "+JSON.stringify(t.shape))}function Oh(n){return n.map(t=>t.read())}function Kh(n){n.forEach(t=>{t[0].write(t[1])})}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */class ue{constructor(t){this.dtype=t.dtype,this.shape=t.shape,t.shape!=null?this.ndim=t.shape.length:this.ndim=t.ndim,this.maxNDim=t.maxNDim,this.minNDim=t.minNDim,this.axes=t.axes||{}}}class Un{constructor(t,e,s,o,r,i,a){this.dtype=t,this.shape=e,this.sourceLayer=s,this.inputs=o,this.callArgs=r,this.outputTensorIndex=a,this.id=u0(),i!=null&&(this.originalName=p0(i),this.name=f0(this.originalName)),this.rank=e.length}}let u$=0;class Qc{constructor(t,e){this.callArgs=e,this.id=u$++,this.outboundLayer=t.outboundLayer,this.inboundLayers=t.inboundLayers,this.nodeIndices=t.nodeIndices,this.tensorIndices=t.tensorIndices,this.inputTensors=t.inputTensors,this.outputTensors=t.outputTensors,this.inputMasks=t.inputMasks,this.outputMasks=t.outputMasks,this.inputShapes=t.inputShapes,this.outputShapes=t.outputShapes;for(const s of t.inboundLayers)s!=null&&s.outboundNodes.push(this);t.outboundLayer.inboundNodes.push(this)}getConfig(){const t=[];for(const e of this.inboundLayers)e!=null?t.push(e.name):t.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:t,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}}let d$=0;class Ct extends qo{constructor(t={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=d$++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let e=t.name;if(!e){const s=this.getClassName();e=ls(s)+"_"+Bc(s)}if(this.name=e,this.trainable_=t.trainable==null?!0:t.trainable,t.inputShape!=null||t.batchInputShape!=null){let s;if(t.batchInputShape!=null)s=t.batchInputShape;else if(t.inputShape!=null){let r=null;t.batchSize!=null&&(r=t.batchSize),s=[r].concat(t.inputShape)}this.batchInputShape=s;let o=t.dtype;o==null&&(o=t.inputDType),o==null&&(o="float32"),this.dtype=o}t.weights!=null?this.initialWeights=t.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(t,e){return t.name+"_ib-"+e.toString()}getNodeAtIndex(t,e){if(this.inboundNodes.length===0)throw new gn(`The layer has never been called and thus has no defined ${e}.`);if(this.inboundNodes.length<=t)throw new $(`Asked to get ${e} at node ${t}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[t]}getInputAt(t){return Pe(this.getNodeAtIndex(t,"input").inputTensors)}getOutputAt(t){return Pe(this.getNodeAtIndex(t,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new Zn(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(this.inboundNodes.length===0)throw new Zn(`Layer ${this.name} is not connected, no input to return.`);return Pe(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new Zn(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new Zn(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return Pe(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map(t=>t())}get updates(){return this._updates}get built(){return this._built}set built(t){this._built=t}get trainable(){return this.trainable_}set trainable(t){this._trainableWeights.forEach(e=>e.trainable=t),this.trainable_=t}get trainableWeights(){return this.trainable_?this._trainableWeights.filter(t=>t.trainable):[]}set trainableWeights(t){this._trainableWeights=t}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter(t=>!t.trainable).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(t){this._nonTrainableWeights=t}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(t){const e=Lt(t);if(this.inputSpec==null||this.inputSpec.length===0)return;const s=Lt(this.inputSpec);if(e.length!==s.length)throw new $(`Layer ${this.name} expects ${s.length} inputs, but it received ${e.length} input tensors. Input received: ${t}`);for(let o=0;o<e.length;o++){const r=e[o],i=s[o];if(i==null)continue;const a=r.rank;if(i.ndim!=null&&a!==i.ndim)throw new $(`Input ${o} is incompatible with layer ${this.name}: expected ndim=${i.ndim}, found ndim=${a}`);if(i.maxNDim!=null&&a>i.maxNDim)throw new $(`Input ${o} is incompatible with layer ${this.name}: expected max_ndim=${i.maxNDim}, found ndim=${a}`);if(i.minNDim!=null&&a<i.minNDim)throw new $(`Input ${o} is incompatible with layer ${this.name}: expected min_ndim=${i.minNDim}, found ndim=${a}.`);if(i.dtype!=null&&r.dtype!==i.dtype)throw new $(`Input ${o} is incompatible with layer ${this.name} : expected dtype=${i.dtype}, found dtype=${r.dtype}.`);if(i.axes){const c=r.shape;for(const l in i.axes){const u=Number(l),d=i.axes[l],h=u>=0?c[u]:c[c.length+u];if(d!=null&&[d,null].indexOf(h)===-1)throw new $(`Input ${o} is incompatible with layer ${this.name}: expected axis ${u} of input shape to have value ${d} but got shape ${c}.`)}}if(i.shape!=null)for(let c=0;c<i.shape.length;++c){const l=i.shape[c],u=r.shape[c];if(l!=null&&u!=null&&l!==u)throw new $(`Input ${o} is incompatible with layer ${this.name}: expected shape=${i.shape}, found shape=${r.shape}.`)}}}call(t,e){return t}invokeCallHook(t,e){this._callHook!=null&&this._callHook(t,e)}setCallHook(t){this._callHook=t}clearCallHook(){this._callHook=null}apply(t,e){e=e||{},this.assertNotDisposed();const s=Lt(t),o=f$(t),r=m$(t);if(o===r)throw new $("Arguments to apply() must be all SymbolicTensors or all Tensors");return mo(this.name,()=>{if(!this.built){this.assertInputCompatibility(t);const i=[];for(const a of Lt(t))i.push(a.shape);this.build(Pe(i)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&r&&(this._refCount=1)}if(this.assertInputCompatibility(t),r){let i=this.call(t,e);this.supportsMasking&&this.setMaskMetadata(t,i);const a=Lt(i),c=[];for(let l of a)s.indexOf(l)!==-1&&(l=l.clone()),c.push(l);if(i=Pe(c),this.activityRegularizer!=null)throw new bt("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return i}else{const i=h$(t),a=this.computeOutputShape(i);let c;const l=p$(t);if(this.warnOnIncompatibleInputShape(Array.isArray(t)?i[0]:i),a!=null&&a.length>0&&Array.isArray(a[0])?c=a.map((u,d)=>new Un(l,u,this,Lt(t),e,this.name,d)):c=new Un(l,a,this,Lt(t),e,this.name),this.addInboundNode(t,c,null,null,i,a,e),this._refCount++,this.activityRegularizer!=null)throw new bt("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return c}})}warnOnIncompatibleInputShape(t){if(this.batchInputShape!=null)if(t.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(t)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let e=!1;this.batchInputShape.forEach((s,o)=>{s!=null&&t[o]!=null&&t[o]!==s&&(e=!0)}),e&&console.warn(`The shape of the input tensor (${JSON.stringify(t)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(this.inboundNodes==null||this.inboundNodes.length===0)throw new Zn(`The layer ${this.name} has never been called and thus has no defined output shape.`);const t=[];for(const e of this.inboundNodes){const s=JSON.stringify(e.outputShapes);t.indexOf(s)===-1&&t.push(s)}if(t.length===1){const e=this.inboundNodes[0].outputShapes;return Array.isArray(e)&&Array.isArray(e[0])&&e.length===1?e[0]:e}else throw new Zn(`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 gn(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Yc(this.weights)}build(t){this.built=!0}getWeights(t=!1){return Oh(t?this.trainableWeights:this.weights)}setWeights(t){M(()=>{const e=this.weights;if(e.length!==t.length)throw new $(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${t.length}, but the layer was expecting ${e.length} weights. Provided weights: ${t}...`);if(e.length===0)return;const s=[],o=Oh(e);for(let r=0;r<o.length;++r){const i=o[r],a=e[r],c=t[r];if(!Rt(i.shape,c.shape))throw new $(`Layer weight shape ${i.shape} not compatible with provided weight shape ${c.shape}`);s.push([a,c])}Kh(s)})}addWeight(t,e,s,o,r,i,a,c){if(this._addedWeightNames.indexOf(t)!==-1)throw new $(`Duplicate weight name ${t} for layer ${this.name}`);this._addedWeightNames.push(t),s==null&&(s="float32"),this.fastWeightInitDuringBuild&&(o=c!=null?c():Ht("zeros"));const l=o.apply(e,s),u=new c$(l,s,t,i,a);return l.dispose(),r!=null&&this.addLoss(()=>r.apply(u.read())),i==null&&(i=!0),i?this._trainableWeights.push(u):this._nonTrainableWeights.push(u),u}setFastWeightInitDuringBuild(t){this.fastWeightInitDuringBuild=t}addLoss(t){t==null||Array.isArray(t)&&t.length===0||(t=Lt(t),this._losses!==void 0&&this._losses!==null&&this.losses.push(...t))}computeOutputShape(t){return t}computeMask(t,e){if(!this.supportsMasking){if(e!=null)if(Array.isArray(e))e.forEach(s=>{if(s!=null)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)});else throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);return null}return e}setMaskMetadata(t,e,s){if(!this.supportsMasking)return;const o=this.computeMask(t,s),r=Lt(e),i=Lt(o);if(r.length!==i.length)throw new Error(`${this.name} outputs ${r.length} tensors but ${r.length} masks for those tensors`);for(let a=0;a<r.length;a++)r[a].kerasMask=i[a]}addInboundNode(t,e,s,o,r,i,a=null){const c=Lt(t);e=Lt(e),s=Lt(s),o=Lt(o),r=Uc(r),i=Uc(i);const l=[],u=[],d=[];for(const h of c)l.push(h.sourceLayer),u.push(h.nodeIndex),d.push(h.tensorIndex);new Qc({outboundLayer:this,inboundLayers:l,nodeIndices:u,tensorIndices:d,inputTensors:c,outputTensors:e,inputMasks:s,outputMasks:o,inputShapes:r,outputShapes:i},a);for(let h=0;h<e.length;h++)e[h].sourceLayer=this,e[h].nodeIndex=this.inboundNodes.length-1,e[h].tensorIndex=h}getConfig(){const t={name:this.name,trainable:this.trainable};return this.batchInputShape!=null&&(t.batchInputShape=this.batchInputShape),this.dtype!=null&&(t.dtype=this.dtype),t}disposeWeights(){return this.weights.forEach(t=>t.dispose()),this.weights.length}assertNotDisposed(){if(this._refCount===0)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(this._refCount===null)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let t=0;return--this._refCount===0&&(t=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:t}}}function h$(n){n=Lt(n);const t=[];for(const e of n)t.push(e.shape);return Pe(t)}function p$(n){return"float32"}function $0(n,t,e){if((t==null||e!=null&&e>0)&&(t=n.sourceLayer,e=n.nodeIndex),t.inboundNodes.length===0)return[n];{const s=t.inboundNodes[e];if(s.inboundLayers.length===0)return s.inputTensors;{const o=[];for(let r=0;r<s.inboundLayers.length;r++){const i=s.inputTensors[r],a=s.inboundLayers[r],c=s.nodeIndices[r],l=$0(i,a,c);for(const u of l)o.indexOf(u)===-1&&o.push(u)}return o}}}function f$(n){let t=!0;for(const e of Lt(n))if(!(e instanceof Un)){t=!1;break}return t}function m$(n){let t=!0;for(const e of Lt(n))if(e instanceof Un){t=!1;break}return t}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */class Ki extends Ct{constructor(t){if(super({dtype:t.dtype,name:t.name!=null?t.name:Bc("input").toString()}),t.batchSize==null&&(t.batchSize=null),t.sparse==null&&(t.sparse=!1),this.trainable=!1,this.built=!0,this.sparse=t.sparse,t.inputShape!=null&&t.batchInputShape!=null)throw new $("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");let e=t.batchInputShape;if(e==null){if(t.inputShape==null)throw new $("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");e=[t.batchSize].concat(t.inputShape)}else if(t.batchSize!=null)throw new $("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");const s=t.dtype||"float32";this.batchInputShape=e,this.dtype=s,this.inputSpec=[{shape:e}];const o=new Un(this.dtype,this.batchInputShape,this,[],{},this.name);o.nodeIndex=0,o.tensorIndex=0,new Qc({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[o],outputTensors:[o],inputMasks:[null],outputMasks:[null],inputShapes:[e],outputShapes:[e]})}apply(t,e){throw new $(`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}}}Ki.className="InputLayer",_(Ki);function g$(n){if(n.batchShape==null&&n.shape==null)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(n.batchShape!=null&&n.shape!=null)throw new $("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let t=n.batchShape;n.shape!=null&&t==null&&(t=[null].concat(n.shape));let e=n.dtype;return e==null&&(e="float32"),new Ki({batchInputShape:t,name:n.name,dtype:e,sparse:n.sparse}).inboundNodes[0].outputTensors[0]}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function b$(n,t){if(n.dtype==null||n.dtype===t.dtype)return t;try{return st(t,n.dtype)}catch{throw new $(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${n.name}' (${n.dtype}).`)}}class $s{constructor(t){if(this.id2Value={},this.id2Mask={},this.name2Id={},t instanceof $s)for(const e in t.id2Value)this.id2Value[e]=t.id2Value[e],e in t.id2Mask&&(this.id2Mask[e]=t.id2Mask[e]);else{if(t==null)return;for(const e of t)this.add(e.key,e.value)}}add(t,e,s){if(this.id2Value[t.id]==null)this.id2Value[t.id]=b$(t,e),this.name2Id[t.name]=t.id,s!=null&&(this.id2Mask[t.id]=s);else throw new $(`Duplicate key: name=${t.name}, id=${t.id}`);return this}addFeed(t){this.add(t.key,t.value)}hasKey(t){return this.id2Value[t.id]!=null}names(){return Object.keys(this.name2Id)}getValue(t){if(t instanceof Un){if(this.id2Value[t.id]==null)throw new $(`Nonexistent key: ${t.name}`);return this.id2Value[t.id]}else{const e=this.name2Id[t];if(e==null)throw new $(`Feed dict has no SymbolicTensor name: ${t}`);return this.id2Value[e]}}getMask(t){if(t instanceof Un){if(this.id2Value[t.id]==null)throw new $(`Nonexistent key: ${t.name}`);return this.id2Mask[t.id]}else{const e=this.name2Id[t];if(e==null)throw new $(`Feed dict has no SymbolicTensor name: ${t}`);return this.id2Mask[e]}}disposeMasks(){this.id2Mask!=null&&vt(this.id2Mask)}}const Jc=new i0,jc=new i0;function x$(n){Jc!=null&&Jc.setMaxEntries(n),jc!=null&&jc.setMaxEntries(n)}function Zi(n,t,e,s){const o=e==null?!1:e.training,r=Array.isArray(n),i=r?n:[n],a=i.map(f=>f.name),c=[],l=t.names();for(const f of a)l.indexOf(f)!==-1?c.push(t.getValue(f)):c.push(null);s!=null&&(s.maxNumTensors=-1/0,s.minNumTensors=1/0);const u=a.join(",")+"|"+t.names().sort().join(",");let d=Jc.get(u),h;if(d==null){const f=y$(i,t);d=f.sorted,h=f.recipientCounts,Jc.put(u,d),jc.put(u,h)}h={},o||Object.assign(h,jc.get(u));const p=new $s(t);for(let f=0;f<d.length;++f){if(s!=null){const T=Nc().numTensors;T>s.maxNumTensors&&(s.maxNumTensors=T),T<s.minNumTensors&&(s.minNumTensors=T)}const m=d[f],g=m.sourceLayer;if(g instanceof Ki)continue;const b=[],x=[],I=[];let y=!1;for(const T of m.inputs){const R=p.getValue(T),L=p.getMask(T);b.push(R),x.push(L),L!=null&&(y=!0),o||(h[T.name]--,h[T.name]===0&&!t.hasKey(T)&&a.indexOf(T.name)===-1&&!R.isDisposed&&T.sourceLayer.stateful!==!0&&I.push(R))}y&&(e=e||{},e.mask=x[0]);const w=Lt(g.apply(b,e));let C=null;g.supportsMasking&&(C=g.computeMask(b,x));const k=w$(m),S=Array.isArray(k)?k:[k];for(let T=0;T<S.length;++T){p.hasKey(S[T])||p.add(S[T],w[T],Array.isArray(C)?C[0]:C);const R=a.indexOf(S[T].name);R!==-1&&(c[R]=w[T])}o||vt(I)}return p.disposeMasks(),r?c:c[0]}function y$(n,t){v(n!=null&&n.length>0,()=>"Expected at least one fetch, got none");let e=[],s={};if(n.length===1){const o=G0(n[0],t);e=o.sorted,s=o.recipientMap}else{const o=new Set;for(const r of n){const{sorted:i,recipientMap:a}=G0(r,t);for(const c of i)o.has(c.name)||(e.push(c),o.add(c.name));for(const c in a)s[c]==null&&(s[c]=new Set),a[c].forEach(l=>s[c].add(l))}}return{sorted:e,recipientCounts:I$(s)}}function I$(n){const t={};for(const e in n)t[e]=n[e].size;return t}function G0(n,t){const e=new Set,s=[],o={};for(const a of t.names())e.add(a);const r=[],i=[];for(r.push(n);r.length>0;){const a=r[r.length-1];if(e.has(a.name)){r.pop();continue}const c=i[i.length-1]===r.length-1;if(a.inputs.length===0||c)r.pop(),s.push(a),e.add(a.name),c&&i.pop();else{i.push(r.length-1);for(const l of a.inputs)o[l.name]==null&&(o[l.name]=new Set),o[l.name].add(a.name),!e.has(l.name)&&r.push(l)}}return{sorted:s,recipientMap:o}}function w$(n){let t;if(n.sourceLayer.inboundNodes.length===1)t=n.sourceLayer.output;else{let e=null;for(let s=0;s<n.sourceLayer.inboundNodes.length;++s)for(const o of n.sourceLayer.inboundNodes[s].outputTensors)if(o.id===n.id){e=s;break}t=n.sourceLayer.getOutputAt(e)}return t}/**
 * @license
 * Copyright 2022 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */z().registerFlag("TOPOLOGICAL_SORT_CACHE_MAX_ENTRIES",()=>100,x$);/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function Zh(n,t){return M(()=>Ee(ut(E(n,n),t,!0)))}class Bi extends qo{getConfig(){return{}}}class L0 extends Bi{constructor(t){super(),this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=t.maxValue!=null?t.maxValue:this.defaultMaxValue,this.axis=t.axis!=null?t.axis:this.defaultAxis}apply(t){return M(()=>{const e=Zh(t,this.axis),s=nn(e,0,this.maxValue);return E(t,dt(s,Q(le(),e)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}L0.className="MaxNorm",_(L0);class E0 extends Bi{constructor(t){super(),this.defaultAxis=0,this.axis=t.axis!=null?t.axis:this.defaultAxis}apply(t){return M(()=>dt(t,Q(le(),Zh(t,this.axis))))}getConfig(){return{axis:this.axis}}}E0.className="UnitNorm",_(E0);class D0 extends Bi{apply(t){return io(t)}}D0.className="NonNeg",_(D0);class W0 extends Bi{constructor(t){super(),this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=t.minValue!=null?t.minValue:this.defaultMinValue,this.maxValue=t.maxValue!=null?t.maxValue:this.defaultMaxValue,this.rate=t.rate!=null?t.rate:this.defaultRate,this.axis=t.axis!=null?t.axis:this.defaultAxis}apply(t){return M(()=>{const e=Zh(t,this.axis),s=Q(E(this.rate,nn(e,this.minValue,this.maxValue)),E(1-this.rate,e));return E(t,dt(s,Q(le(),e)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}W0.className="MinMaxNorm",_(W0);const M0={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function de(n){return Th(n)}function V0(n,t={}){return zi(n,mn.getMap().classNameMap,t,"constraint")}function he(n){if(n==null)return null;if(typeof n=="string"){const e={className:n in M0?M0[n]:n,config:{}};return V0(e)}else return n instanceof Bi?n:V0(n)}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */async function bo(n){if(n==null)return;const t=[],e=[],s=[];for(const o in n){const r=n[o];if(typeof r!="number"){const i=r;t.push(i.data()),e.push(o),s.push(i)}}if(t.length>0){const o=await Promise.all(t);for(let r=0;r<o.length;++r)n[e[r]]=o[r][0];vt(s)}}function F0(n){if(n!=null)for(const t in n){const e=n[t];typeof e!="number"&&e.dispose()}}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */var z0;(function(n){n[n.SILENT=0]="SILENT",n[n.VERBOSE=1]="VERBOSE"})(z0||(z0={}));const C$=125;class Hi{constructor(){this.validationData=null}setParams(t){this.params=t}async onEpochBegin(t,e){}async onEpochEnd(t,e){}async onBatchBegin(t,e){}async onBatchEnd(t,e){}async onTrainBegin(t){}async onTrainEnd(t){}setModel(t){}}class v${constructor(t,e=10){t==null&&(t=[]),this.callbacks=t,this.queueLength=e}append(t){this.callbacks.push(t)}setParams(t){for(const e of this.callbacks)e.setParams(t)}setModel(t){for(const e of this.callbacks)e.setModel(t)}async onEpochBegin(t,e){e==null&&(e={});for(const s of this.callbacks)await s.onEpochBegin(t,e)}async onEpochEnd(t,e){e==null&&(e={});for(const s of this.callbacks)await s.onEpochEnd(t,e)}async onBatchBegin(t,e){e==null&&(e={});for(const s of this.callbacks)await s.onBatchBegin(t,e)}async onBatchEnd(t,e){e==null&&(e={});for(const s of this.callbacks)await s.onBatchEnd(t,e)}async onTrainBegin(t){t==null&&(t={});for(const e of this.callbacks)await e.onTrainBegin(t)}async onTrainEnd(t){t==null&&(t={});for(const e of this.callbacks)await e.onTrainEnd(t)}}class S$ extends Hi{constructor(){super()}async onEpochBegin(t){this.seen=0,this.totals={}}async onBatchEnd(t,e){e==null&&(e={});const s=e.size==null?0:e.size;this.seen+=s;for(const o in e){const r=e[o];if(typeof r=="number")this.totals.hasOwnProperty(o)||(this.totals[o]=0),this.totals[o]=this.totals[o]+r*s;else{let i;o in this.totals?i=this.totals[o]:this.totals[o]=0;const a=M(()=>Q(this.totals[o],E(r,s)));this.totals[o]=a,i!=null&&i.dispose()}}}async onEpochEnd(t,e){if(e!=null)for(const s of this.params.metrics)this.totals[s]!=null&&(typeof this.totals[s]=="number"?e[s]=this.totals[s]/this.seen:M(()=>{const o=E(dt(1,this.seen),this.totals[s]);e[s]=o,this.totals[s].dispose(),en(e[s])}))}}class k$ extends Hi{async onTrainBegin(t){this.epoch=[],this.history={}}async onEpochEnd(t,e){e==null&&(e={}),this.epoch.push(t);for(const s in e)this.history[s]==null&&(this.history[s]=[]),this.history[s].push(e[s])}async syncData(){const t=[],e=[],s=[];for(const r in this.history){const i=this.history[r];for(let a=0;a<i.length;++a)if(typeof i[a]!="number"){const c=i[a];t.push(c.data()),e.push(r),s.push(a)}}const o=await Promise.all(t);for(let r=0;r<o.length;++r)this.history[e[r]][s[r]].dispose(),this.history[e[r]][s[r]]=o[r][0]}}class T$ extends Hi{constructor(t,e){if(super(),this.currentEpoch=0,this.nowFunc=t.nowFunc,this.nextFrameFunc=t.nextFrameFunc||Xc,this.yieldEvery=e||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=C$),this.yieldEvery==="never"&&t.onYield!=null)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");Yl(this.yieldEvery)&&(this.maybeWait=AR(this.maybeWait.bind(this),this.yieldEvery,this.nowFunc)),this.trainBegin=t.onTrainBegin,this.trainEnd=t.onTrainEnd,this.epochBegin=t.onEpochBegin,this.epochEnd=t.onEpochEnd,this.batchBegin=t.onBatchBegin,this.batchEnd=t.onBatchEnd,this.yield=t.onYield}async maybeWait(t,e,s){const o=[];this.yield!=null&&(await bo(s),o.push(this.yield(t,e,s))),o.push(this.nextFrameFunc()),await Promise.all(o)}async onEpochBegin(t,e){this.currentEpoch=t,this.epochBegin!=null&&(await bo(e),await this.epochBegin(t,e))}async onEpochEnd(t,e){const s=[];this.epochEnd!=null&&(await bo(e),s.push(this.epochEnd(t,e))),this.yieldEvery==="epoch"&&s.push(this.nextFrameFunc()),await Promise.all(s)}async onBatchBegin(t,e){this.batchBegin!=null&&(await bo(e),await this.batchBegin(t,e))}async onBatchEnd(t,e){const s=[];this.batchEnd!=null&&(await bo(e),s.push(this.batchEnd(t,e))),this.yieldEvery==="batch"?s.push(this.nextFrameFunc()):Yl(this.yieldEvery)&&s.push(this.maybeWait(this.currentEpoch,t,e)),await Promise.all(s)}async onTrainBegin(t){this.trainBegin!=null&&(await bo(t),await this.trainBegin(t))}async onTrainEnd(t){this.trainEnd!=null&&(await bo(t),await this.trainEnd(t))}}function X0(n,t){return n==null&&(n={}),n instanceof Hi?[n]:Array.isArray(n)&&n[0]instanceof Hi?n:Lt(n).map(s=>new T$(s,t))}class yn{constructor(){}static registerCallbackConstructor(t,e){v(t>=0&&Number.isInteger(t),()=>`Verbosity level is expected to be an integer >= 0, but got ${t}`),yn.checkForDuplicate(e),yn.constructors[t]==null&&(yn.constructors[t]=[]),yn.constructors[t].push(e)}static checkForDuplicate(t){for(const e in yn.constructors)yn.constructors[+e].forEach(o=>{if(o===t)throw new $("Duplicate callback constructor.")})}static clear(){yn.constructors={}}static createCallbacks(t){const e=[];for(const s in yn.constructors){const o=+s;t>=o&&e.push(...yn.constructors[o])}return e.map(s=>new s)}}yn.constructors={};function A0(n,t,e,s,o,r,i,a,c){const l=new k$,u=[new S$,...yn.createCallbacks(t)];n!=null&&u.push(...n),u.push(l);const d=new v$(u);return d.setParams({epochs:e,initialEpoch:s,samples:o,steps:r,batchSize:i,verbose:t,doValidation:a,metrics:c}),{callbackList:d,history:l}}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function us(n,t={},e=!1){return zi(n,mn.getMap().classNameMap,t,"layer",e)}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function qc(n,t){return M(()=>{n.dtype!=="float32"&&(n=st(n,"float32"));const e=ut(Pi(n),t,!0),s=$c(e.shape,le()),o=Ee(vs(e,s));return dt(n,o)})}function tl(n,t){return M(()=>ie(Pi(pt(t,n)),-1))}function Bh(n,t){return M(()=>ie(Ge(pt(t,n)),-1))}function Hh(n,t){return M(()=>{const e=pt(n,t),s=nn(Ge(n),le(),Number.MAX_VALUE),o=Ge(dt(e,s));return E(100,ie(o,-1))})}function N$(n,t){return M(()=>{const e=nn(t,le(),Number.MAX_VALUE),s=Pn(Q(1,e)),o=nn(n,le(),Number.MAX_VALUE),r=Pn(Q(1,o));return ie(Pi(pt(s,r)),-1)})}function R$(n,t){return M(()=>{const e=vs(0,pt(1,E(n,t)));return ie(Pi(e),-1)})}function $$(n,t){return M(()=>{const e=vs(0,pt(1,E(n,t)));return ie(e,-1)})}function G$(n,t){return M(()=>{const e=ut(E(n,t),-1),s=Tn(E(pt(1,n),t),-1);return vs(0,Q(1,pt(s,e)))})}function L$(n,t){return M(()=>{const e=Math.log(2),s=pt(t,n),o=pt(Q(s,$i(E(-2,s))),e);return ie(o,-1)})}function _i(n,t,e=!1){return M(()=>{if(e)t=zd(t);else{const s=ut(t,t.shape.length-1,!0);t=dt(t,s)}return t=nn(t,le(),1-le()),ne(ut(E(st(n,"float32"),Pn(t)),t.shape.length-1))})}function el(n,t,e=!1){return M(()=>{const s=st(Dc(jR(n)),"int32");t=nn(t,le(),1-le());const o=t.shape,r=W(Zm(s,o[o.length-1]),o);return _i(r,t,e)})}function E$(n,t){if(!Rt(n.shape,t.shape))throw new $(`logits and labels must have the same shape, but got shapes ${JSON.stringify(n.shape)} and ${JSON.stringify(t.shape)}`);return M(()=>{const e=io(t),s=ne(Ge(t));return Q(pt(e,E(t,n)),Am(An(s)))})}function nl(n,t){return M(()=>{let e;return e=nn(t,le(),1-le()),e=Pn(dt(e,pt(1,e))),ie(E$(n,e),-1)})}function D$(n,t){return M(()=>{const e=nn(n,le(),1),s=nn(t,le(),1);return ut(E(n,Pn(dt(e,s))),-1)})}function W$(n,t){return M(()=>{const e=Pn(Q(le(),t));return ie(pt(t,E(n,e)),-1)})}function P0(n,t){return M(()=>{const e=qc(n,-1),s=qc(t,-1),o=E(e,s);return ne(ut(o,-1))})}const sl={meanSquaredError:tl,meanAbsoluteError:Bh,meanAbsolutePercentageError:Hh,meanSquaredLogarithmicError:N$,squaredHinge:R$,hinge:$$,categoricalHinge:G$,logcosh:L$,categoricalCrossentropy:_i,sparseCategoricalCrossentropy:el,binaryCrossentropy:nl,kullbackLeiblerDivergence:D$,poisson:W$,cosineProximity:P0};function _h(n){if(typeof n=="string"){if(n in sl)return sl[n];let t=`Unknown loss ${n}`;throw n.toLowerCase().includes("softmaxcrossentropy")&&(t=`Unknown loss ${n}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new $(t)}else return n}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function O0(n,t){return M(()=>{const e=E(.5,fn(t)),s=Hn(sn(t,e),n.dtype);return ie(Xn(n,s),-1)})}function K0(n,t){return M(()=>Hn(Xn(vi(n,-1),vi(t,-1)),"float32"))}function M$(n,t){return M(()=>st(ut(rs(Xn(n,1),Xn(t,1))),"float32"))}function V$(n,t){return M(()=>st(ut(rs(Xn(n,0),Xn(t,1))),"float32"))}function F$(n,t){return M(()=>{const e=M$(n,t),s=V$(n,t),o=Q(e,s);return st(Le(sn(o,0),dt(e,o),0),"float32")})}function z$(n,t){return nl(n,t)}function X$(n,t){return n.rank===t.rank&&(n=Di(n,[n.rank-1])),t=vi(t,-1),t.dtype!==n.dtype&&(t=st(t,n.dtype)),st(Xn(n,t),"float32")}const A$=tl,P$=tl,O$=Bh,K$=Bh,Z$=Hh,B$=Hh,Z0=_i,H$=P0,B0=el,ol={binaryAccuracy:O0,categoricalAccuracy:K0,precision:F$,categoricalCrossentropy:Z0,sparseCategoricalCrossentropy:B0,mse:A$,MSE:P$,mae:O$,MAE:K$,mape:Z$,MAPE:B$,cosine:H$};function _$(n){if(typeof n=="string"&&n in ol)return ol[n];if(typeof n!="string"&&n!=null)return n;throw new $(`Unknown metric ${n}`)}function rl(n){if(Bn(n!==null,`Unknown LossOrMetricFn ${n}`),typeof n=="string")return n;{let t;for(const e of Object.keys(sl))if(sl[e]===n){t=e;break}if(t!==void 0)return t;for(const e of Object.keys(ol))if(ol[e]===n){t=e;break}return t!==void 0?t:n.name}}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function U$(n){const t={Adagrad:()=>tr.adagrad(.01),Adadelta:()=>tr.adadelta(1,.95,le()),Adam:()=>tr.adam(.001,.9,.999,le()),Adamax:()=>tr.adamax(.002,.9,.999,le(),0),RMSProp:()=>tr.rmsprop(.001,.9,0,le()),SGD:()=>tr.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,n in t)return t[n]();throw new $(`Unknown Optimizer ${n}`)}/**
 * @license
 * Copyright 2019 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */const H0=1*1024*1024;function _0(n,t,e=!1){if(n==null||typeof n!="object"||Object.getPrototypeOf(n)!==Object.prototype||!Uh(n))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(e){const s=JSON.stringify(n);s.length>H0&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${s.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= ${H0}.`)}}function Uh(n){if(n===null)return!0;if(typeof n=="object")if(Object.getPrototypeOf(n)===Object.prototype){const t=Object.keys(n);for(const e of t)if(typeof e!="string"||!Uh(n[e]))return!1;return!0}else if(Array.isArray(n)){for(const t of n)if(!Uh(t))return!1;return!0}else return!1;else{const t=typeof n;return t==="string"||t==="number"||t==="boolean"}}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function Y$(n,t,e,s=console.log){const o=J$(n),r=["Layer (type)","Input Shape","Output shape","Param #"];o?(t=t||90,e=e||[.32,.61,.89,1]):(t=t||115,e=e||[.24,.48,.7,.8,1]),e[e.length-1]<=1&&(e=e.map(u=>Math.floor(t*u)));let i;if(!o){r.push("Receives inputs"),i=[];for(const u in n.nodesByDepth)i.push(...n.nodesByDepth[u])}s("_".repeat(t)),il(r,e,s),s("=".repeat(t));const a=n.layers;for(let u=0;u<a.length;++u)o?j$(a[u],e,s):q$(a[u],e,i,s),s((u===a.length-1?"=":"_").repeat(t));n.checkTrainableWeightsConsistency();const c=Q$(n),l=Yc(n.nonTrainableWeights);s(`Total params: ${c+l}`),s(`Trainable params: ${c}`),s(`Non-trainable params: ${l}`),s("_".repeat(t))}function Q$(n){let t;return n.collectedTrainableWeights!=null?t=Yc(n.collectedTrainableWeights):t=Yc(n.trainableWeights),t}function J$(n){let t=!0;const e=[],s=[];for(const o in n.nodesByDepth)e.push(n.nodesByDepth[o]);for(const o of e){if(o.length>1||o.length===1&&o[0].inboundLayers.length>1){t=!1;break}s.push(...o)}if(t)for(const o of n.layers){let r=!1;for(const i of o.inboundNodes)if(s.indexOf(i)!==-1)if(r){t=!1;break}else r=!0;if(!t)break}return t}function il(n,t,e=console.log){let s="";for(let o=0;o<n.length;++o)o>0&&(s=s.slice(0,s.length-1)+" "),s+=n[o],s=s.slice(0,t[o]),s+=" ".repeat(t[o]-s.length);e(s)}function j$(n,t,e){let s,o;try{o=n.inboundNodes.map(c=>JSON.stringify(c.inputShapes)).join(",")}catch{o="multiple"}try{s=JSON.stringify(n.outputShape)}catch{s="multiple"}const r=n.name,i=n.getClassName(),a=[`${r} (${i})`,o,s,n.countParams().toString()];il(a,t,e)}function q$(n,t,e,s){let o,r;try{r=n.inboundNodes.map(d=>JSON.stringify(d.inputShapes)).join(",")}catch{r="multiple"}try{o=JSON.stringify(n.outputShape)}catch{o="multiple"}const i=[];for(const d of n.inboundNodes)if(!(e!=null&&e.length>0&&e.indexOf(d)===-1))for(let h=0;h<d.inboundLayers.length;++h){const p=d.inboundLayers[h].name,f=d.nodeIndices[h],m=d.tensorIndices[h];i.push(`${p}[${f}][${m}]`)}const a=n.name,c=n.getClassName(),l=i.length===0?"":i[0],u=[`${a} (${c})`,r,o,n.countParams().toString(),l];il(u,t,s);for(let d=1;d<i.length;++d)il(["","","","",i[d]],t,s)}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function U0(n,t,e){return(n==="inboundNodes"||n==="outputLayers"||n==="inputLayers")&&t===0&&typeof e=="string"}function Yh(n,t){if(n===null)return null;if(typeof n=="string")return po(n);if(typeof n=="number"||typeof n=="boolean")return n;if(n instanceof Array){const e=[],s=n.length;for(let o=0;o<s;++o){const r=n[o];U0(t,o,r)?e.push(r):e.push(Yh(r,t))}return e}else{const e={};for(const s of Object.keys(n)){const o=n[s];if(s==="name"&&typeof o=="string")e[s]=o;else{const r=po(s);e[r]=Yh(o,r)}}return e}}function Qh(n,t){if(n==null)return null;if(typeof n=="string")return ls(n);if(typeof n=="number"||typeof n=="boolean")return n;if(n instanceof Array){const e=[],s=n.length;for(let o=0;o<s;++o){const r=n[o];U0(t,o,r)?e.push(r):e.push(Qh(r,t))}return e}else{const e={};for(const s of Object.keys(n)){const o=n[s],r=ls(s);(s==="name"||s==="className")&&typeof o=="string"?e[r]=o:e[r]=Qh(o,s)}return e}}/** @license See the LICENSE file. */const Y0="4.16.0";/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */const tG=n=>{const t=Object.keys(n);if(t.length===0)return!1;const e=t[0].split("/");return!isNaN(parseInt(e[e.length-1],10))};class En extends Ct{constructor(t){if(super({}),this.containerNodes=new Set,this.name=t.name,this.name==null){const x=this.getClassName().toLowerCase();this.name=Bc(x)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(t.inputs)?this.inputs=t.inputs.slice():this.inputs=[t.inputs],Array.isArray(t.outputs)?this.outputs=t.outputs.slice():this.outputs=[t.outputs],Ts(this.inputs).length!==this.inputs.length)throw new $(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(x=>x.name)}`);Ts(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(x=>x.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(const x of this.outputs){const I=x.sourceLayer,y=x.nodeIndex,w=x.tensorIndex;this.outputLayers.push(I),this.outputLayersNodeIndices.push(y),this.outputLayersTensorIndices.push(w)}for(const x of this.inputs){const I=x.sourceLayer,y=x.nodeIndex,w=x.tensorIndex;Bn(y===0,"input layer has >1 nodes"),Bn(w===0,"input layer has >1 tensors"),this.inputLayers.push(I),this.inputLayersNodeIndices.push(y),this.inputLayersTensorIndices.push(w)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let x=0;x<this.inputLayers.length;x++){const I=this.inputLayers[x];if(!(I instanceof Ki))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${t.inputs}. Input ${x} (0-based) originates from layer type ${I.getClassName()}.`);this.inputNames.push(I.name),this.feedInputShapes.push(I.batchInputShape),this.feedInputNames.push(I.name)}for(const x of this.outputLayers)this.outputNames.push(x.name);this.internalInputShapes=this.inputs.map(x=>x.shape),this.internalOutputShapes=this.outputs.map(x=>x.shape);const e={},s={},o={},r={},i={},a=[],c=(x,I,y,w,C,k)=>{(w==null||C==null||k==null)&&(w=x.sourceLayer,C=x.nodeIndex,k=x.tensorIndex);const S=w.inboundNodes[C];if(y.indexOf(S)!==-1)throw new gn(`The tensor ${x.name} at layer "${w.name}" is part of a cycle.`);if(I.indexOf(S)!==-1)return;this.containerNodes.add(En.nodeKey(w,C)),w.id in i||(i[w.id]=Object.keys(i).length),y.indexOf(S)===-1&&y.push(S);const T=S.inboundLayers.length;for(let R=0;R<T;R++){const L=S.inputTensors[R],V=S.inboundLayers[R],F=S.nodeIndices[R],X=S.tensorIndices[R];c(L,I,y,V,F,X)}for(I.push(S);y.indexOf(S)>=0;)y.splice(y.indexOf(S),1);a.push(S)},l=[],u=[];for(const x of this.outputs)c(x,l,u);const d=a.slice().reverse();for(const x of d){s[x.id]=x,x.id in e||(e[x.id]=0);let I=e[x.id];const y=o[x.outboundLayer.id]==null?0:o[x.outboundLayer.id];I=Math.max(I,y),o[x.outboundLayer.id]=I,r[x.outboundLayer.id]=x.outboundLayer,e[x.id]=I;for(let w=0;w<x.inboundLayers.length;w++){const C=x.inboundLayers[w],k=x.nodeIndices[w],S=C.inboundNodes[k],T=e[S.id]==null?0:e[S.id];e[S.id]=Math.max(I+1,T),s[S.id]=S}}const h={};for(const x in e){const I=e[x];I in h||(h[I]=[]),h[I].push(s[x])}const p={};for(const x in o){const I=o[x];I in p||(p[I]=[]),p[I].push(r[x])}let f=Object.keys(p).map(x=>parseInt(x,10)).sort(Kc);this.layers=[];for(const x of f){const I=p[x];I.sort((y,w)=>{const C=i[y.id],k=i[w.id];return C<k?-1:C>k?1:0});for(const y of I)y instanceof En&&this.internalContainerRefs.push(y),this.layers.push(y)}this.layersByDepth=p,f=Object.keys(h).map(x=>parseInt(x,10)).sort(Kc);const m=this.inputs.slice(),g=[];for(const x of f)for(const I of h[x]){const y=I.outboundLayer;if(y!=null){for(const w of I.inputTensors)if(m.indexOf(w)===-1)throw new gn(`Graph disconnected: cannot obtain value for tensor ${w} at layer "${y.name}". The following previous layers were accessed without issue: ${g}`);for(const w of I.outputTensors)m.push(w);g.push(y.name)}}this.nodesByDepth=h;const b=this.layers.map(x=>x.name);for(const x of b){const I=b.filter(y=>y===x).length;if(I!==1)throw new gn(`The name "${x}" is used ${I} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(b))}this.outboundNodes=[],this.inboundNodes=[],new Qc({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(x=>null),outputMasks:this.outputs.map(x=>null),inputShapes:this.inputs.map(x=>x.shape),outputShapes:this.outputs.map(x=>x.shape)}),this.built=!0,this._refCount=1}assertNotDisposed(){if(this._refCount===0)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();const t={refCountAfterDispose:null,numDisposedVariables:0};if(--this._refCount===0){for(const e of this.layers)t.numDisposedVariables+=e.dispose().numDisposedVariables;for(const e of this.internalContainerRefs)t.numDisposedVariables+=e.dispose().numDisposedVariables}return t.refCountAfterDispose=this._refCount,t}get trainable(){return this.trainable_}set trainable(t){this.layers.forEach(e=>{e._trainableWeights.forEach(s=>s.trainable=t)}),this.trainable_=t}get trainableWeights(){if(this._trainableWeights.length>0)throw new $("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let t=[];for(const e of this.layers)t=t.concat(e.trainableWeights);return t}get nonTrainableWeights(){const t=[];for(const e of this.layers)t.push(...e.nonTrainableWeights);if(!this.trainable){const e=[];for(const s of this.layers)e.push(...s.trainableWeights);return e.concat(t)}return t}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(t,e=!0){const s={};let o=0;const r=tG(t);r&&this.parseWeights(t);for(const a of this.layers)for(const[c,l]of a.weights.entries()){const u=r?`${l.name.split("/").slice(0,-1).join("/")+"/"}${c}`:l.originalName;if(s[u]!=null)throw new $(`Duplicate weight name: ${u}`);s[u]=l,o++}const i=[];for(const a in t){let c=a;if(s[a]==null){const l=a.split("/");c=l.slice(0,-2).concat([l[l.length-1]]).join("/")}if(s[c]!=null)i.push([s[c],t[a]]);else if(e)throw new $(`Provided weight data has no target variable: ${a}`);delete s[c]}if(e){const a=[];for(const c in s)a.push(c);if(a.length>0)throw new $(`${a.length} of ${o} weights are not set: ${a}`)}Kh(i)}parseWeights(t){for(const e in Object.keys(t)){const s=e.split("/"),o=["vars","layer_checkpoint_dependencies"],r=s.map(i=>i.startsWith("_")?i.slice(1):i).filter(i=>!o.includes(i)).join("/");r!==e&&(t[r]=t[e],delete t[e])}}updatedConfig(){const t=this.getConfig(),e={};return e.className=this.getClassName(),e.config=t,e.kerasVersion=`tfjs-layers ${Y0}`,e.backend="TensorFlow.js",e}toJSON(t,e=!0){const s=Qh(this.updatedConfig());return e?JSON.stringify(s):s}call(t,e){return M(()=>{t=Lt(t);const s=new $s;for(let o=0;o<this.inputs.length;++o)s.add(this.inputs[o],t[o]);return Zi(this.outputs,s,e)})}computeMask(t,e){return M(()=>{t=Lt(t);let s;return e==null?s=ho(null,t.length):s=Lt(e),this.runInternalGraph(t,s)[1]})}computeOutputShape(t){const e=Uc(t);if(e.length!==this.inputLayers.length)throw new $(`Invalid inputShape argument ${t}: model has ${this.inputLayers.length} tensor inputs.`);const s={};for(let a=0;a<e.length;a++){const c=this.inputLayers[a],l=e[a],u=c.name+"_0_0";s[u]=l}const o=Object.keys(this.nodesByDepth).map(a=>parseInt(a,10)).sort(Kc);if(o.length>1)for(const a of o){const c=this.nodesByDepth[a];for(const l of c){const u=l.outboundLayer;if(this.inputLayers.map(m=>m.id).indexOf(u.id)!==-1)continue;const d=[];for(let m=0;m<l.inboundLayers.length;m++){const g=l.inboundLayers[m],b=l.nodeIndices[m],x=l.tensorIndices[m],I=`${g.name}_${b}_${x}`,y=s[I];d.push(y)}const h=u.computeOutputShape(Pe(d)),p=Uc(h),f=u.inboundNodes.indexOf(l);for(let m=0;m<p.length;m++){const g=`${u.name}_${f}_${m}`;s[g]=p[m]}}}const r=[],i=[];for(let a=0;a<this.outputLayers.length;a++){const c=this.outputLayers[a],l=this.outputLayersNodeIndices[a],u=this.outputLayersTensorIndices[a],d=`${c.name}_${l}_${u}`;i.push(d)}for(let a=0;a<i.length;a++){const c=i[a];Bn(c in s),r.push(s[c])}return Pe(r)}runInternalGraph(t,e){e==null&&(e=ho(null,t.length));const s={};for(let c=0;c<this.inputs.length;++c){const l=this.inputs[c],u=t[c],d=e[c];s[l.id]=[u,d]}const o=Object.keys(this.nodesByDepth).map(c=>parseInt(c,10)).sort(Kc);for(const c of o){const l=this.nodesByDepth[c];for(const u of l){const d=u.outboundLayer,h=u.inputTensors,p=u.outputTensors,f=new Array;for(const m of h)m.id in s&&f.push(s[m.id]);if(f.length===h.length){let m={},g,b,x,I;if(u.callArgs!=null&&(m=u.callArgs),f.length===1){const[y,w]=f[0];m.mask==null&&(m.mask=w),x=Lt(d.call(y,m)),I=Lt(d.computeMask(y,w)),g=[y],b=[w]}else g=f.map(y=>y[0]),b=f.map(y=>y[1]),m.mask==null&&(m.mask=b),x=Lt(d.call(g,m)),I=Lt(d.computeMask(g,b));if(d.activityRegularizer)throw new bt("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let y=0;y<p.length;++y){const w=p[y],C=x[y],k=I[y];s[w.id]=[C,k]}}}}const r=[],i=[],a=[];for(const c of this.outputs){Bn(c.id in s,`Could not compute output ${c.name} : ${c.id}`);const[l,u]=s[c.id];a.push(l.shape),r.push(l),i.push(u)}return[r,i,a]}buildNodeConversionMap(t){const e={};let s;for(const o of this.layers){s=o instanceof En?1:0;for(let r=0;r<o.inboundNodes.length;r++){const i=En.nodeKey(o,r);this.containerNodes.has(i)&&(e[i]=s,s+=1)}}return e}getLayer(t,e){if(e!=null)return this.findLayer(e);if(t==null)throw new $("Provide either a layer name or layer index");if(typeof t=="number")return this.findLayer(t);for(const s of this.layers)if(s.name===t)return s;throw new $(`No such layer: ${t}`)}findLayer(t){if(this.layers.length<=t)throw new $(`Was asked to retrieve layer at index ${t}, but model only has ${this.layers.length} layer(s).`);return this.layers[t]}calculateLosses(){return M(()=>{const t=[];for(const e of this.layers)for(let s=0;s<e.inboundNodes.length;++s){const o=En.nodeKey(e,s);this.containerNodes.has(o)&&t.push(...e.calculateLosses())}return t})}getConfig(){const t={name:this.name},e=this.buildNodeConversionMap(this.layers),s=[];for(const i of this.layers){const a=i.getClassName(),c=i.getConfig(),l=[];for(let d=0;d<i.inboundNodes.length;d++){const h=i.inboundNodes[d],p=En.nodeKey(i,d);let f={};if(this.containerNodes.has(p)){if(h.callArgs)try{JSON.stringify(h.callArgs),f=h.callArgs}catch{console.warn(`Layer ${i.name} was passed non-serializable keyword arguments: ${h.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),f={}}if(h.inboundLayers.length>0){const m=[];for(let g=0;g<h.inboundLayers.length;g++){const b=h.inboundLayers[g],x=h.nodeIndices[g],I=h.tensorIndices[g],y=En.nodeKey(b,x);let w=e[y];w==null&&(w=0),m.push([b.name,w,I,f])}l.push(m)}}}const u={};u.name=i.name,u.className=a,u.config=c,u.inboundNodes=l,s.push(u)}t.layers=s;const o=[];for(let i=0;i<this.inputLayers.length;i++){const a=this.inputLayers[i],c=this.inputLayersNodeIndices[i],l=En.nodeKey(a,c);if(!this.containerNodes.has(l))continue;let u=e[l];u==null&&(u=0);const d=this.inputLayersTensorIndices[i];o.push([a.name,u,d])}t.inputLayers=o;const r=[];for(let i=0;i<this.outputLayers.length;i++){const a=this.outputLayers[i],c=this.outputLayersNodeIndices[i],l=En.nodeKey(a,c);if(!this.containerNodes.has(l))continue;let u=e[l];u==null&&(u=0);const d=this.outputLayersTensorIndices[i];r.push([a.name,u,d])}return t.outputLayers=r,t}static fromConfig(t,e,s={},o=!1){const r={},i={};function a(g,b){g.name in i?i[g.name].push(b):i[g.name]=[b]}function c(g,b){const x=[];let I;for(const y of b){const w=y[0],C=y[1],k=y[2];if(I=y[3]==null?{}:y[3],!(w in r)){a(g,b);return}const S=r[w];if(S.inboundNodes.length<=C){a(g,b);return}const T=S.inboundNodes[C];x.push(T.outputTensors[k])}x.length>0&&g.apply(Pe(x),I)}function l(g){const b=g.name,x=us(g,e.customObjects!=null?e.customObjects:{});x.setFastWeightInitDuringBuild(o),r[b]=x,g.inboundNodes.forEach(y=>{if(!(y instanceof Array))throw new $(`Corrupted configuration, expected array for nodeData: ${y}`);a(x,y)})}const u=e.name,d=e.layers;for(const g of d)l(g);for(;!XR(i);)for(const g of d){const b=r[g.name];if(b.name in i){const x=i[b.name];delete i[b.name];for(const I of x)c(b,I)}}const h=[],p=[],f=e.inputLayers;for(const g of f){const b=g[0],x=g[1],I=g[2];Bn(b in r);const w=r[b].inboundNodes[x].outputTensors;h.push(w[I])}const m=e.outputLayers;for(const g of m){const b=g[0],x=g[1],I=g[2];Bn(b in r);const w=r[b].inboundNodes[x].outputTensors;p.push(w[I])}return new t({inputs:h,outputs:p,name:u})}get stateful(){if(this._stateful)throw new $("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(const t of this.layers)if(t.stateful)return!0;return!1}resetStates(){M(()=>{this.layers.forEach(t=>{t.stateful&&t.resetStates()})})}}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function eG(n,t,e){const s=t.length;if(n==null||Array.isArray(n)&&n.length===0)return t.map(o=>null);if(s===1)return Array.isArray(n)&&n.length===1?n:typeof n=="object"&&t[0]in n?[n[t[0]]]:[n];if(Array.isArray(n)){if(n.length!==s)throw new Error(`Provided ${e} is an array of ${n.length} element(s), but the model has ${s} outputs. Make sure a set of weights is provided for each model output.`);return n}else if(typeof n=="object"&&Object.keys(n).length>0&&typeof n[Object.keys(n)[0]]=="object"){const o=[];return t.forEach(r=>{r in n?o.push(n[r]):o.push(null)}),o}else throw new Error(`The model has multiple (${s}) outputs, so ${e} must be either an array with ${s} elements or an object with ${t} keys. Provided ${e} not understood: ${JSON.stringify(n)}`)}function Q0(n,t){return eG(n,t,"classWeight")}async function J0(n,t,e,s){if(t!=null||s!=null)throw new Error("Support sampleWeight is not implemented yet");if(e!=null){const o=M(()=>{if(n.shape.length===1)return to(n);if(n.shape.length===2){if(n.shape[1]>1)return vi(n,1);if(n.shape[1]===1)return W(n,[n.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${n.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}else throw new Error(`Unexpected rank of target (y) tensor (${n.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)}),r=Array.from(await o.data());vt(o);const i=[];return r.forEach(a=>{if(e[a]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${a} exists in the data but not in classWeight`);i.push(e[a])}),Ue(i,"float32")}else return null}function nG(n,t){return E(n,t)}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */const sG=32;function j0(n,t){let e,s;const o=t;e=o.xs,s=o.ys,v(e!=null&&s!=null,()=>`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 r=q0("input",n.inputNames,e),i=q0("output",n.outputNames,s),a=r[0].shape[0];v(r.length===n.inputs.length,()=>`LayersModel has ${n.inputs.length} inputs, but the dataset provides ${r.length} inputs.  (Expected input keys: ${JSON.stringify(n.inputNames)})`),v(i.length===n.outputs.length,()=>`LayersModel has ${n.outputs.length} outputs, but the dataset provides ${i.length} outputs.  (Expected output keys: ${JSON.stringify(n.outputNames)})`);for(let c=0;c<r.length;c++)v(r[c].shape[0]===a,()=>`Batch size mismatch: input ${n.inputNames[c]} has ${r[c].shape[0]}; expected  ${a} based on input ${n.inputNames[0]}.`);for(let c=0;c<i.length;c++)v(i[c].shape[0]===a,()=>`Batch size mismatch: output ${n.outputNames[c]} has ${i[c].shape[0]}; expected  ${a} based on input ${n.inputNames[0]}.`);return{xs:r,ys:i}}function q0(n,t,e){if(e instanceof ae)return[e];if(Array.isArray(e))return v(e.length===t.length,()=>`Received an array of ${e.length} Tensors, but expected ${t.length} to match the ${n} keys ${t}.`),e;{const s=[];for(const o of t){if(e[o]==null)throw new $(`The feature data generated by the dataset lacks the required ${n} key '${o}'.`);s.push(e[o])}return s}}function oG(n){if(n.length===3)throw new bt("Validation with sample weights is not implemented yet.");return{xs:n[0],ys:n[1]}}async function rG(n,t,e){const s=e.batchesPerEpoch!=null;if(v(n.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),v(e!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),v(e.epochs!=null&&e.epochs>0&&Number.isInteger(e.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${e.epochs}`),v(!s||e.batchesPerEpoch>0&&Number.isInteger(e.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${e.batchesPerEpoch}`),v(e.validationSplit==null,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),n.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");n.isTraining=!0;try{const o=e.validationData!=null;let r,i;if(o)if(tb(e.validationData))v(e.validationBatches==null||e.validationBatches>0&&Number.isInteger(e.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${e.validationBatches}`);else{const g=oG(e.validationData);r=g.xs,i=g.ys}const a=n.makeTrainFunction(),c=n.getDedupedMetricsNames();let l;o?l=c.slice().concat(c.map(g=>"val_"+g)):l=c.slice();const u=X0(e.callbacks,e.yieldEvery),d=e.verbose==null?1:e.verbose,{callbackList:h,history:p}=A0(u,d,e.epochs,null,null,iG(t,e),null,o,l);h.setModel(n),n.history=p,await h.onTrainBegin(),n.stopTraining_=!1;let f=e.initialEpoch==null?0:e.initialEpoch,m=await t.iterator();for(;f<e.epochs;){const g={};await h.onEpochBegin(f);let b=0,x=0;for(s||(m=await t.iterator());!s||b<e.batchesPerEpoch;){const I=await m.next();if(s&&I.done){console.warn(`You provided \`batchesPerEpoch\` as ${e.batchesPerEpoch}, but your dataset iterator ran out of data after ${b} batches; interrupting training. Make sure that your dataset can generate at least \`batchesPerEpoch * epochs\` batches (in this case, ${e.batchesPerEpoch*e.epochs} batches). You may need to use the repeat() function when building your dataset.`);break}if(I.value!=null){const{xs:y,ys:w}=j0(n,I.value),C={};C.batch=x,C.size=y[0].shape[0],await h.onBatchBegin(x,C);const k=[];if(e.classWeight!=null){const R=Q0(e.classWeight,n.outputNames);for(let L=0;L<R.length;++L)k.push(await J0(w[L],null,R[L]))}const S=y.concat(w).concat(k),T=a(S);vt(S);for(let R=0;R<c.length;++R){const L=c[R],V=T[R];C[L]=V,en(V)}await h.onBatchEnd(x,C),F0(C),x++,b++}if(s?b>=e.batchesPerEpoch:I.done){if(o){let y;tb(e.validationData)?y=Lt(await n.evaluateDataset(e.validationData,{batches:e.validationBatches})):y=Lt(n.evaluate(r,i,{batchSize:e.validationBatchSize==null?sG:e.validationBatchSize,verbose:0}));for(let w=0;w<n.metricsNames.length;++w)g[`val_${n.metricsNames[w]}`]=y[w]}break}if(n.stopTraining_)break}if(await h.onEpochEnd(f,g),f++,n.stopTraining_)break}return await h.onTrainEnd(),await n.history.syncData(),n.history}finally{n.isTraining=!1}}function iG(n,t){let e=null;return t.batchesPerEpoch!=null?e=t.batchesPerEpoch:Number.isFinite(n.size)&&(e=n.size),e}function tb(n){return typeof n.iterator=="function"}function aG(n){return typeof n.next=="function"}async function cG(n,t,e){e=e||{};const s=e.batches!=null,o=n.testFunction;let r=[];if(e.verbose>0)throw new bt("Verbose mode is not implemented yet.");v(!s||e.batches>0&&Number.isInteger(e.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(e.batches)}`);const i=aG(t)?t:await t.iterator();let a=0,c=0;for(;!s||c<e.batches;){const l=await i.next();if(r=M(()=>{if(l.value){const{xs:u,ys:d}=j0(n,l.value),h=u.concat(d),p=M(()=>o(h));if(vt(h),c===0)for(let m=0;m<p.length;++m)r.push(Gt(0));const f=h[0].shape[0];for(let m=0;m<p.length;++m){const g=p[m],b=r[m];r[m]=M(()=>Q(r[m],E(f,g))),c>0&&vt(b)}vt(p),a+=f,++c}return r}),l.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, ${e.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let l=0;l<r.length;++l){const u=r[l];r[l]=dt(r[l],a),vt(u)}return Pe(r)}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function Jh(n){v(n>0&&Number.isInteger(n),()=>`batchSize is required to be a positive integer, but got ${n}`)}function Ui(n,t,e){return n==null?[null]:Array.isArray(n)?n.map(s=>go(s,t,e-t)):go(n,t,e-t)}function jh(n,t){return M(()=>n==null?null:Array.isArray(n)?n.map(e=>jh(e,t)):b0(n,t.dtype==="int32"?t:st(t,"int32")))}function qh(n,t){const e=[];let s=0,o=null;for(;s<n;)o=s+t,o>=n&&(o=n),e.push([s,o]),s=o;return e}function eb(n){const t=[];n instanceof ae&&(n=[n]);for(let e=0;e<n.length;++e){const s=n[e];if(s.rank===1)t.push(Ai(s,1));else{if(s.rank===0)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(s)}}return t}function Dn(n,t){if(n==null)return;const e=[];if(t instanceof ae)e.push(t.id);else if(Array.isArray(t))t.forEach(o=>e.push(o.id));else if(t!=null)for(const o in t){const r=t[o];e.push(r.id)}const s=[];if(n instanceof ae)e.indexOf(n.id)===-1&&s.push(n);else if(Array.isArray(n))n.forEach(o=>{e.indexOf(o.id)===-1&&s.push(o)});else if(n!=null)for(const o in n){const r=n[o];e.indexOf(r.id)===-1&&s.push(r)}s.forEach(o=>{o.isDisposed||o.dispose()})}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function lG(n){return n instanceof ae}function tp(n){return Array.isArray(n)}function nb(n){return!lG(n)&&!tp(n)}function sb(n,t,e,s=!0,o=""){if(t==null||t.length===0){if(n!=null){let i=!1;if(tp(n)&&n.length>0)i=!0;else if(nb(n)){for(const a in n)if(n.hasOwnProperty(a)){i=!0;break}}else i=!0;if(i)throw new $(`Error when checking model ${o} expected no data, but got ${n}`)}return[]}if(n==null)return t.map(i=>null);let r;if(nb(n)){n=n,r=[];for(const i of t){if(n[i]==null)throw new $(`No data provided for "${i}". Need data for each key in: ${t}`);r.push(n[i])}}else if(tp(n)){if(n=n,n.length!==t.length)throw new $(`Error when checking model ${o}: 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): ${n}`);r=n}else{if(n=n,t.length>1)throw new $(`The model ${o} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${n.shape}`);r=[n]}if(r=eb(r),e!=null)for(let i=0;i<t.length;++i){if(e[i]==null)continue;const a=r[i];if(a.shape.length!==e[i].length)throw new $(`Error when checking ${o}: expected ${t[i]} to have ${e[i].length} dimension(s). but got array with shape ${a.shape}`);for(let c=0;c<e[i].length;++c){if(c===0&&!s)continue;const l=a.shape[c],u=e[i][c];if(u!=null&&u>=0&&l!==u)throw new $(`${o} expected a batch of elements where each example has shape [${e[i].slice(1,e[i].length)}] (i.e.,tensor shape [*,${e[i].slice(1,e[i].length)}]) but the ${o} received an input with ${a.shape[0]} examples, each with shape [${a.shape.slice(1,a.shape.length)}] (tensor shape [${a.shape}])`)}}return r}function uG(n,t,e){const s=Ts(n.map(r=>r.shape[0]));s.sort();const o=Ts(t.map(r=>r.shape[0]));if(o.sort(),s.length>1)throw new $(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(n.map(r=>r.shape))}`);if(o.length>1)throw new $(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(r=>r.shape))}`);if(s.length>0&&o.length>0&&!Rt(s,o))throw new $(`Input Tensors should have the same number of samples as target Tensors. Found ${s[0]} input sample(s) and ${o[0]} target sample(s).`)}function dG(n,t,e){const s=[tl,nl,_i];for(let o=0;o<n.length;++o){const r=n[o],i=t[o],a=e[o];if(i!=null){if(i===_i&&r.shape[r.shape.length-1]===1)throw new $(`You are passing a target array of shape ${r.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(s.indexOf(i)!==-1){const c=r.shape.slice(1),l=a.slice(1);for(let u=0;u<c.length;++u){const d=c[u],h=l[u];if(h!=null&&d!==h)throw new $(`A target Tensor with shape ${r.shape} was passed for an output of shape ${a}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}function ob(n,t,e,s=!0,o=""){let r;if(Array.isArray(n)){if(n.length!==t.length)throw new $(`Error when checking model ${o}: 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 ${n.length} Tensors(s).`);r=n}else{if(t.length>1)throw new $(`The model expects ${t.length} ${o} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(n.shape)}.`);r=[n]}if(e!=null)for(let i=0;i<t.length;++i){if(e[i]==null)continue;const a=r[i];if(a.shape.length!==e[i].length)throw new $(`Error when checking ${o}: expected ${t[i]} to have ${e[i].length} dimension(s), but got array with shape ${JSON.stringify(a.shape)}`);for(let c=0;c<e[i].length;++c){if(c===0&&!s)continue;const l=a.shape[c],u=e[i][c];if(u!=null&&u!==l)throw new $(`Error when checking ${o}: expected ${t[i]} to have shape ${JSON.stringify(e[i])} but got array with shape ${JSON.stringify(a.shape)}.`)}}}function hG(n,t){if(n==null||Array.isArray(n)&&n.length===0)return t.map(s=>[]);let e;if(typeof n=="string"||typeof n=="function")e=[n];else if(Array.isArray(n)||typeof n=="object")e=n;else throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${n}`);if(Array.isArray(e))return t.map(s=>e);{const s=[];for(const o of t){let r=e.hasOwnProperty(o)?e[o]:[];Array.isArray(r)||(r=[r]),s.push(r)}return s}}const pG="layers-model";class sr extends En{constructor(t){super(t),this.isTraining=!1}summary(t,e,s=console.log){if(!this.built)throw new $("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).");Y$(this,t,e,s)}compile(t){if(t.loss==null&&(t.loss=[]),this.loss=t.loss,typeof t.optimizer=="string")this.optimizer_=U$(t.optimizer),this.isOptimizerOwned=!0;else{if(!(t.optimizer instanceof ks))throw new $("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=t.optimizer,this.isOptimizerOwned=!1}let e=[];if(!Array.isArray(t.loss)&&typeof t.loss!="string"&&typeof t.loss!="function"){t.loss=t.loss;for(const i in t.loss)if(this.outputNames.indexOf(i)===-1)throw new $(`Unknown entry in loss dictionary: "${i}". Only expected the following keys: ${this.outputNames}`);for(const i of this.outputNames)t.loss[i]==null&&console.warn(`Output "${i}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${i} during training`),e.push(_h(t.loss[i]))}else if(Array.isArray(t.loss)){if(t.loss.length!==this.outputs.length)throw new $(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${t.loss}.`);e=t.loss.map(a=>_h(a))}else{const i=_h(t.loss);this.outputs.forEach(a=>{e.push(i)})}this.lossFunctions=e,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let i=0;i<this.outputs.length;++i){const a=this.internalOutputShapes[i],c=this.outputNames[i];this.feedOutputNames.push(c),this.feedOutputShapes.push(a),this.feedLossFns.push(this.lossFunctions[i])}const s=[];this.metrics=t.metrics,this.metricsNames=["loss"],this.metricsTensors=[],mo("loss",()=>{for(let i=0;i<this.outputs.length;++i){if(s.indexOf(i)!==-1)continue;const a=this.lossFunctions[i];this.outputs.length>1&&(this.metricsTensors.push([a,i]),this.metricsNames.push(this.outputNames[i]+"_loss"))}});const o=hG(t.metrics,this.outputNames),r=(i,a,c)=>{this.outputNames.length>1&&(a=this.outputNames[i]+"_"+a),this.metricsNames.push(a),this.metricsTensors.push([c,i])};mo("metric",()=>{for(let i=0;i<this.outputs.length;++i){if(s.indexOf(i)!==-1)continue;const a=o[i];(l=>{const u="";let d,h,p;for(const f of l){if(typeof f=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(f)!==-1){const g=this.internalOutputShapes[i];g[g.length-1]===1||this.lossFunctions[i]===nl?["accuracy","acc"].indexOf(f)!==-1?h=O0:["crossentropy","ce"].indexOf(f)!==-1&&(h=z$):this.lossFunctions[i]===el?["accuracy","acc"].indexOf(f)!==-1?h=X$:["crossentropy","ce"].indexOf(f)!==-1&&(h=B0):["accuracy","acc"].indexOf(f)!==-1?h=K0:["crossentropy","ce"].indexOf(f)!==-1&&(h=Z0);let b;["accuracy","acc"].indexOf(f)!==-1?b="acc":["crossentropy","ce"].indexOf(f)!==-1&&(b="ce"),p=h,d=u+b}else p=_$(f),d=u+rl(f);let m;mo(d,()=>{m=p}),r(i,d,m)}})(a)}}),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){this.collectedTrainableWeights!=null&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(t,e,s={}){const o=s.batchSize==null?32:s.batchSize;Jh(o);const i=this.standardizeUserDataXY(t,e,!0,o);try{const a=i[0].concat(i[1]);this.makeTestFunction();const c=this.testFunction,l=this.testLoop(c,a,o,s.verbose,s.steps);return Pe(l)}finally{Dn(i[0],t),Dn(i[1],e)}}async evaluateDataset(t,e){return this.makeTestFunction(),cG(this,t,e)}checkNumSamples(t,e,s,o="steps"){let r;if(s!=null){if(r=null,e!=null)throw new $(`If ${o} is set, batchSize must be null or undefined.Got batchSize = ${e}`)}else if(t!=null)Array.isArray(t)?r=t[0].shape[0]:r=t.shape[0];else throw new $(`Either the input data should have a defined shape, or ${o} shoud be specified.`);return r}execute(t,e){if(Array.isArray(e)&&e.length===0)throw new $("`outputs` is an empty Array, which is not allowed.");const s=Array.isArray(e),o=s?e:[e],r=this.retrieveSymbolicTensors(o),i=new $s;if(t instanceof ae&&(t=[t]),Array.isArray(t)){if(t.length!==this.inputs.length)throw new $(`The number of inputs provided (${t.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let c=0;c<this.inputs.length;++c)i.add(this.inputs[c],t[c])}else for(const c of this.inputs){const l=t[c.name];if(l==null)throw new $(`No value is provided for the model's input ${c.name}`);i.add(c,l)}const a=Zi(r,i);return s?a:a[0]}retrieveSymbolicTensors(t){const e=ho(null,t.length);let s=t.length;for(const o of this.layers){const r=Array.isArray(o.output)?o.output:[o.output],i=r.map(a=>a.name);for(let a=0;a<t.length;++a){const c=i.indexOf(t[a]);if(c!==-1&&(e[a]=r[c],s--),s===0)break}if(s===0)break}if(s>0){const o=[];throw e.forEach((r,i)=>{r==null&&o.push(t[i])}),new $(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(o)}`)}return e}predictLoop(t,e=32,s=!1){return M(()=>{const o=this.checkNumSamples(t);if(s)throw new bt("Verbose predictLoop() is not implemented yet.");const r=qh(o,e),i=this.outputs.map(a=>[]);for(let a=0;a<r.length;++a)M(()=>{const l=r[a][0],u=r[a][1],d=Ui(t,l,u),h=[];if(Array.isArray(d))for(let f=0;f<d.length;++f)h.push({key:this.inputs[f],value:d[f]});else h.push({key:this.inputs[0],value:d});const p=new $s(h);return Zi(this.outputs,p)}).forEach((l,u)=>i[u].push(l));return Pe(i.map(a=>Xe(a,0)))})}predict(t,e={}){const s=eb(t);ob(s,this.inputNames,this.feedInputShapes,!1);try{const o=e.batchSize==null?32:e.batchSize;return Jh(o),this.predictLoop(s,o)}finally{Dn(s,t)}}predictOnBatch(t){ob(t,this.inputNames,this.feedInputShapes,!0);const e=(Array.isArray(t)?t[0]:t).shape[0];return this.predictLoop(t,e)}standardizeUserDataXY(t,e,s=!0,o){if(this.optimizer_==null)throw new gn("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");const r=[];for(let i=0;i<this.feedOutputShapes.length;++i){const a=this.feedOutputShapes[i];this.feedLossFns[i]===el?r.push(a.slice(0,a.length-1).concat([1])):r.push(a)}if(t=sb(t,this.feedInputNames,this.feedInputShapes,!1,"input"),e=sb(e,this.feedOutputNames,r,!1,"target"),uG(t,e),dG(e,this.feedLossFns,this.feedOutputShapes),this.stateful&&o!=null&&o>0&&t[0].shape[0]%o!==0)throw new $(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${o}. Found: ${t[0].shape[0]} sample(s).`);return[t,e]}async standardizeUserData(t,e,s,o,r=!0,i){const[a,c]=this.standardizeUserDataXY(t,e,r,i);if(s!=null)throw new Error("sample weight is not supported yet.");let l=null;if(o!=null){const u=Q0(o,this.outputNames);l=[];for(let d=0;d<u.length;++d)l.push(await J0(c[d],null,u[d]))}return[a,c,l]}testLoop(t,e,s,o=0,r){return M(()=>{const i=this.checkNumSamples(e,s,r,"steps"),a=[];if(o>0)throw new bt("Verbose mode is not implemented yet.");if(r!=null)throw new bt("steps mode in testLoop() is not implemented yet");{const c=qh(i,s),l=Ue($n(0,i));for(let u=0;u<c.length;++u){const d=c[u][0],h=c[u][1],p=go(l,d,h-d),f=jh(e,p),m=t(f);if(u===0)for(let g=0;g<m.length;++g)a.push(Gt(0));for(let g=0;g<m.length;++g){const b=m[g];a[g]=Q(a[g],E(h-d,b))}}for(let u=0;u<a.length;++u)a[u]=dt(a[u],i)}return a})}getDedupedMetricsNames(){const t=this.metricsNames,e=[];for(let s=0;s<t.length;++s){const o=t[s];let r=o;if(a0(t,o)>1){const i=a0(t.slice(0,s),o);r+=`_${i}`}e.push(r)}return e}makeTrainFunction(){return t=>{const e=[],s=t.slice(0,this.inputs.length),o=t.slice(this.inputs.length,this.inputs.length+this.outputs.length),r=t.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),i=[],a=()=>{const d=[];for(let m=0;m<this.inputs.length;++m)d.push({key:this.inputs[m],value:s[m]});const h=new $s(d),p=Zi(this.outputs,h,{training:!0});let f;for(let m=0;m<this.lossFunctions.length;++m){const g=this.lossFunctions[m];let b=g(o[m],p[m]);r[m]!=null&&(b=nG(b,r[m]));const x=ie(b);e.push(x),m===0?f=b:f=Q(f,b)}for(let m=0;m<this.metricsTensors.length;++m){let g;if(this.outputs.length>1&&m<this.outputs.length)g=e[m];else{const b=this.metricsTensors[m][0],x=this.metricsTensors[m][1];g=ie(b(o[x],p[x]))}en(g),i.push(g)}return f=ie(f),this.calculateLosses().forEach(m=>{f=Q(f,m)}),f},c=this.collectedTrainableWeights.map(d=>d.read());return[this.optimizer_.minimize(a,!0,c)].concat(i)}}makeTestFunction(){this.testFunction=t=>M(()=>{const e=[];let s;const o=t.slice(0,this.inputs.length),r=t.slice(this.inputs.length,this.inputs.length+this.outputs.length),i=[];for(let l=0;l<this.inputs.length;++l)i.push({key:this.inputs[l],value:o[l]});const a=new $s(i),c=Zi(this.outputs,a);for(let l=0;l<this.lossFunctions.length;++l){const u=this.lossFunctions[l],d=ie(u(r[l],c[l]));l===0?s=d:s=Q(s,d),e.push(s)}for(let l=0;l<this.metricsTensors.length;++l){const u=this.metricsTensors[l][0],d=this.metricsTensors[l][1],h=ie(u(r[d],c[d]));e.push(h)}return e})}async fit(t,e,s={}){if(this.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");this.isTraining=!0;let o,r,i,a,c,l,u,d,h;try{const p=s.batchSize==null?32:s.batchSize;Jh(p);const m=await this.standardizeUserData(t,e,s.sampleWeight,s.classWeight,!1,p);o=m[0],r=m[1],h=m[2];let g=!1,b;if(s.validationData!=null&&s.validationData.length>0){if(g=!0,s.validationData.length===2)c=s.validationData[0],l=s.validationData[1];else throw s.validationData.length===3?new bt("validationData including sample weights is not supported yet."):new $(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${s.validationData} is invalid.`);const R=await this.standardizeUserData(c,l,null,null,!0,p);u=R[0],d=R[1],b=u.concat(d)}else if(s.validationSplit!=null&&s.validationSplit>0&&s.validationSplit<1){g=!0;const T=Math.floor(o[0].shape[0]*(1-s.validationSplit)),R=o[0].shape[0];u=Ui(o,T,R),i=o,o=Ui(o,0,T),d=Ui(r,T,R),a=r,r=Ui(r,0,T),b=u.concat(d)}else s.validationSteps!=null&&(g=!0);const x=o.concat(r).concat(h);this.checkTrainableWeightsConsistency();const I=this.makeTrainFunction(),y=this.getDedupedMetricsNames();let w,C;g?(this.makeTestFunction(),w=this.testFunction,C=y.slice().concat(y.map(T=>"val_"+T))):(w=null,b=[],C=y.slice());const k=X0(s.callbacks,s.yieldEvery);return await this.fitLoop(I,x,y,p,s.epochs,s.verbose,k,w,b,s.shuffle,C,s.initialEpoch,null,null)}finally{this.isTraining=!1,Dn(o,t),Dn(r,e),Dn(i,t),Dn(a,e),Dn(u,c),Dn(d,l),h!=null&&vt(h)}}async fitLoop(t,e,s,o,r,i,a,c,l,u,d,h,p,f){o==null&&(o=32),r==null&&(r=1),u==null&&(u=!0),h==null&&(h=0);let m=!1;if(c!=null&&l!=null&&(m=!0),f!=null&&(m=!0,p==null))throw new $("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");const g=this.checkNumSamples(e,o,p,"steps_per_epoch");let b;g!=null&&(b=$n(0,g)),i==null&&(i=1);const{callbackList:x,history:I}=A0(a,i,r,h,g,p,o,m,d);x.setModel(this),this.history=I,await x.onTrainBegin(),this.stopTraining_=!1;for(let y=h;y<r;++y){await x.onEpochBegin(y);const w={};if(p!=null)throw new bt("stepsPerEpoch mode is not implemented yet.");{if(u==="batch")throw new bt("batch shuffling is not implemneted yet");u&&jI(b);const C=Ue(b),k=qh(g,o);for(let S=0;S<k.length;++S){const T={};if(await x.onBatchBegin(S,T),M(()=>{const R=k[S][0],L=k[S][1],V=go(C,R,L-R);T.batch=S,T.size=L-R;const F=jh(e,V),X=t(F);for(let A=0;A<s.length;++A){const P=s[A],B=X[A];T[P]=B,en(B)}if(S===k.length-1&&m){const A=this.testLoop(c,l,o);for(let P=0;P<s.length;++P){const B=s[P],K=A[P];en(K),w["val_"+B]=K}}}),await x.onBatchEnd(S,T),F0(T),this.stopTraining_)break}C.dispose()}if(await x.onEpochEnd(y,w),this.stopTraining_)break}return await x.onTrainEnd(),await this.history.syncData(),this.history}async fitDataset(t,e){return rG(this,t,e)}async trainOnBatch(t,e){const s=await this.standardizeUserData(t,e),o=s[0],r=s[1],a=this.makeTrainFunction()(o.concat(r)),c=[];for(const l of a){const u=await l.data();c.push(u[0])}return vt(a),Dn(s[0],t),Dn(s[1],e),Pe(c)}getNamedWeights(t){const e=[],s=t!=null&&t.trainableOnly,o=s?this.trainableWeights:this.weights,r=this.getWeights(s);for(let i=0;i<o.length;++i)s&&!o[i].trainable||e.push({name:o[i].originalName,tensor:r[i]});return e}set stopTraining(t){this.stopTraining_=t}get stopTraining(){return this.stopTraining_}get optimizer(){return this.optimizer_}set optimizer(t){this.optimizer_!==t&&(this.optimizer_=t,this.isOptimizerOwned=!1)}dispose(){const t=super.dispose();if(t.refCountAfterDispose===0&&this.optimizer!=null&&this.isOptimizerOwned){const e=Nc().numTensors;this.optimizer_.dispose(),t.numDisposedVariables+=e-Nc().numTensors}return t}getLossIdentifiers(){let t;if(typeof this.loss=="string")t=ls(this.loss);else if(Array.isArray(this.loss)){for(const e of this.loss)if(typeof e!="string")throw new Error("Serialization of non-string loss is not supported.");t=this.loss.map(e=>ls(e))}else{const e=Object.keys(this.loss);t={};const s=this.loss;for(const o of e)if(typeof s[o]=="string")t[o]=ls(s[o]);else throw new Error("Serialization of non-string loss is not supported.")}return t}getMetricIdentifiers(){if(typeof this.metrics=="string"||typeof this.metrics=="function")return[ls(rl(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(t=>ls(rl(t)));{const t={};for(const e in this.metrics)t[e]=ls(rl(this.metrics[e]));return t}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(t){if(t.weighted_metrics!=null)throw new Error("Loading weight_metrics is not supported yet.");if(t.loss_weights!=null)throw new Error("Loading loss_weights is not supported yet.");if(t.sample_weight_mode!=null)throw new Error("Loading sample_weight_mode is not supported yet.");const e=Yh(t.optimizer_config),s=us(e);let o;if(typeof t.loss=="string")o=po(t.loss);else if(Array.isArray(t.loss))o=t.loss.map(i=>po(i));else if(t.loss!=null){o={};for(const i in t.loss)o[i]=po(t.loss[i])}let r;if(Array.isArray(t.metrics))r=t.metrics.map(i=>po(i));else if(t.metrics!=null){r={};for(const i in t.metrics)r[i]=po(t.metrics[i])}this.compile({loss:o,metrics:r,optimizer:s})}async save(t,e){if(typeof t=="string"){const l=_w(t);if(l.length===0)throw new $(`Cannot find any save handlers for URL '${t}'`);if(l.length>1)throw new $(`Found more than one (${l.length}) save handlers for URL '${t}'`);t=l[0]}if(t.save==null)throw new $("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const s=await ym(this.getNamedWeights(e)),a={modelTopology:this.toJSON(null,!1),format:pG,generatedBy:`TensorFlow.js tfjs-layers v${Y0}`,convertedBy:null};if((e==null?!1:e.includeOptimizer)&&this.optimizer!=null){a.trainingConfig=this.getTrainingConfig();const l="optimizer",{data:u,specs:d}=await ym(await this.optimizer.getWeights(),l);s.specs.push(...d),s.data=Hw([s.data,u])}return this.userDefinedMetadata!=null&&(_0(this.userDefinedMetadata,this.name,!0),a.userDefinedMetadata=this.userDefinedMetadata),a.weightData=s.data,a.weightSpecs=s.specs,t.save(a)}setUserDefinedMetadata(t){_0(t,this.name),this.userDefinedMetadata=t}getUserDefinedMetadata(){return this.userDefinedMetadata}}sr.className="Model",_(sr);class rb extends sr{}rb.className="Functional",_(rb);/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */class Yi extends sr{constructor(t){if(super({inputs:[],outputs:[]}),t=t||{},this.trainable=!0,this.built=!1,this.name=t.name!=null?t.name:Bc("sequential_"),t.layers!=null)for(const e of t.layers)this.add(e)}checkShape(t){if(t.inboundNodes[0].outputTensors[0].shape.some(s=>s<0))throw new $(`Negative dimension size caused by adding layer ${t.name} with input shape [${t.inboundNodes[0].inputTensors[0].shape}]`)}add(t){const e=t instanceof Yi||t instanceof sr;let s;if(e){if(s=t,s.outputs.length!==1)throw new $("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(s.inputs.length!==1)throw new $("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(this.outputs.length===0){if(t.inboundNodes.length===0){if(t.batchInputShape==null)throw new $("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const o=g$({batchShape:t.batchInputShape,dtype:t.dtype,name:t.name+"_input"});t.apply(o)}if(e)this.outputs=s.outputs,this.inputs=s.inputs;else{if(t.inboundNodes.length!==1)throw new $(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${t.name} which has ${t.inboundNodes.length} pre-existing inbound connections.`);if(t.inboundNodes[0].outputTensors.length!==1)throw new $("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(t),this.outputs=[t.inboundNodes[0].outputTensors[0]],this.inputs=$0(this.outputs[0])}this.inboundNodes=[],new Qc({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:ho(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(o=>o.shape),outputShapes:this.outputs[0].shape})}else{const o=t.apply(this.outputs[0]);if(Array.isArray(o))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(t),this.outputs=[o],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(t),this.built=!1}pop(){if(this.layers.length===0)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),this.layers.length===0)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{const t=this.layers.length-1;this.layers[t].outboundNodes=[],this.outputs=[this.layers[t].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(t,e){return this.model==null&&this.build(),this.model.call(t,e)}build(t){if(Nt(t),this.inputs.length===0||this.outputs.length===0)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new sr({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(t,e,s=console.log){this.built||this.build(),super.summary(t,e,s)}setWeights(t){this.model==null&&this.build(),this.model.setWeights(t)}evaluate(t,e,s={}){if(!this.built)throw new gn("The model needs to be compiled before being used.");return this.model.evaluate(t,e,s)}async evaluateDataset(t,e){if(!this.built)throw new gn("The model needs to be compiled before being used.");return this.model.evaluateDataset(t,e)}predict(t,e={}){return this.model==null&&this.build(),this.model.predict(t,e)}predictOnBatch(t){return this.model==null&&this.build(),this.model.predictOnBatch(t)}compile(t){this.build(),this.model.compile(t),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return this.model==null?void 0:this.model.optimizer}set optimizer(t){this.model.optimizer=t}async fit(t,e,s={}){if(!this.built)throw new gn("The model needs to be compiled before being used.");return this.model.fit(t,e,s)}async fitDataset(t,e){if(!this.built)throw new gn("The model needs to be compiled before being used.");return this.model.fitDataset(t,e)}async trainOnBatch(t,e){return this.model.trainOnBatch(t,e)}static fromConfig(t,e,s={},o=!1){let r,i={};if(e instanceof Array){if(e[0].className==null||e[0].className==="Merge")throw new $("Legacy serialization format not supported yet.");r=e}else v(e.layers!=null,()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."),r=e.layers,delete e.layers,i=e;const a=new t(i);if(!(a instanceof Yi))throw new bt(`Sequential.fromConfig called on non-Sequential input: ${a}`);for(const c of r){const u=us(c,void 0,o);o&&u.setFastWeightInitDuringBuild(!0),a.add(u)}return a}set stopTraining(t){if(this.model==null)throw new $("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=t}get stopTraining(){if(this.model==null)throw new $("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){const t=[];for(const e of this.layers){const s={};s.className=e.getClassName(),s.config=e.getConfig(),t.push(s)}return{name:this.name,layers:t}}}Yi.className="Sequential",_(Yi);/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */let Oe=class extends qo{getConfig(){return{}}};class ib extends Oe{apply(t,e=1){return t$(t,e)}}ib.className="elu",_(ib);class ab extends Oe{apply(t){return Qm(t)}}ab.className="selu",_(ab);class cb extends Oe{apply(t){return io(t)}}cb.className="relu",_(cb);class lb extends Oe{apply(t){return M(()=>Gi(6,io(t)))}}lb.className="relu6",_(lb);class ub extends Oe{apply(t){return t}}ub.className="linear",_(ub);class db extends Oe{apply(t){return _o(t)}}db.className="sigmoid",_(db);class hb extends Oe{apply(t){return n$(t)}}hb.className="hardSigmoid",_(hb);class pb extends Oe{apply(t){return $i(t)}}pb.className="softplus",_(pb);class fb extends Oe{apply(t){return e$(t)}}fb.className="softsign",_(fb);class mb extends Oe{apply(t){return pd(t)}}mb.className="tanh",_(mb);let ep=class extends Oe{apply(t,e=-1){return zd(t,e)}};ep.className="softmax",_(ep);class gb extends Oe{apply(t,e=-1){return Pm(t,e)}}gb.className="logSoftmax",_(gb);class bb extends Oe{apply(t,e=1){return M(()=>E(_o(E(t,e)),t))}}bb.className="swish",_(bb);class xb extends Oe{apply(t){return M(()=>E(t,pd($i(t))))}}xb.className="mish",_(xb);function Gs(n){return n.getClassName()}function np(n,t={}){return zi(n,mn.getMap().classNameMap,t,"activation")}function Ls(n){if(n==null){const t={};return t.className="linear",t.config={},np(t)}if(typeof n=="string"){const t={};return t.className=n,t.config={},np(t)}else return n instanceof Oe?n:np(n)}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function fG(n){if(n!=null&&typeof n!="object")throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${n}`)}class yb extends qo{}class Ib extends yb{constructor(t){super(),fG(t),this.l1=t==null||t.l1==null?.01:t.l1,this.l2=t==null||t.l2==null?.01:t.l2,this.hasL1=this.l1!==0,this.hasL2=this.l2!==0}apply(t){return M(()=>{let e=ge([1]);return this.hasL1&&(e=Q(e,ut(E(this.l1,Ge(t))))),this.hasL2&&(e=Q(e,ut(E(this.l2,Pi(t))))),W(e,[])})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(t,e){return new t({l1:e.l1,l2:e.l2})}}Ib.className="L1L2",_(Ib);const wb={l1l2:"L1L2"};function Vt(n){return Th(n)}function Cb(n,t={}){return zi(n,mn.getMap().classNameMap,t,"regularizer")}function _t(n){if(n==null)return null;if(typeof n=="string"){const e={className:n in wb?wb[n]:n,config:{}};return Cb(e)}else return n instanceof yb?n:Cb(n)}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */class vb extends Ct{constructor(t){super(t??{}),this.supportsMasking=!0,t!=null&&(this.maxValue=t.maxValue)}call(t,e){t=mt(t);let s=io(t);return this.maxValue!=null&&(s=nn(s,0,this.maxValue)),s}computeOutputShape(t){return t}getConfig(){const t={maxValue:this.maxValue},e=super.getConfig();return Object.assign(t,e),t}}vb.className="ReLU",_(vb);class Sb extends Ct{constructor(t){super(t??{}),this.DEFAULT_ALPHA=.3,t==null&&(t={}),this.alpha=t.alpha==null?this.DEFAULT_ALPHA:t.alpha}call(t,e){const s=mt(t);return Cd(s,this.alpha)}computeOutputShape(t){return t}getConfig(){const t={alpha:this.alpha},e=super.getConfig();return Object.assign(t,e),t}}Sb.className="LeakyReLU",_(Sb);class kb extends Ct{constructor(t){if(super(t??{}),this.DEFAULT_ALPHA_INITIALIZER="zeros",t==null&&(t={}),this.supportsMasking=!0,this.alphaInitializer=Ht(t.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=_t(t.alphaRegularizer),this.alphaConstraint=he(t.alphaConstraint),t.sharedAxes==null)this.sharedAxes=null;else if(Array.isArray(t.sharedAxes))this.sharedAxes=t.sharedAxes;else if(typeof t.sharedAxes=="number")this.sharedAxes=[t.sharedAxes];else throw new $(`Expected sharedAxes to be a number or an array of numbers, but got ${t.sharedAxes}`)}build(t){t=Nt(t);const e=t.slice(1);if(this.sharedAxes!=null)for(const o of this.sharedAxes)e[o-1]=1;this.alpha=this.addWeight("alpha",e,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);const s={};if(this.sharedAxes!=null)for(let o=1;o<t.length;++o)s[o]=t[o];this.inputSpec=[new ue({ndim:t.length,axes:s})],this.built=!0}call(t,e){return t=mt(t),Rd(t,this.alpha.read())}getConfig(){const t={alphaInitializer:Qt(this.alphaInitializer),alphaRegularizer:Vt(this.alphaRegularizer),alphaConstraint:de(this.alphaConstraint),sharedAxes:this.sharedAxes},e=super.getConfig();return Object.assign(t,e),t}}kb.className="PReLU",_(kb);let Tb=class extends Ct{constructor(t){if(super(t??{}),this.DEFAULT_ALPHA=1,t==null&&(t={}),t.alpha!=null&&t.alpha!==this.DEFAULT_ALPHA)throw new bt(`Non-default alpha value (${t.alpha}) is not supported by the ELU layer yet.`);this.alpha=t.alpha==null?this.DEFAULT_ALPHA:t.alpha}call(t,e){const s=mt(t);return Gc(s)}computeOutputShape(t){return t}getConfig(){const t={alpha:this.alpha},e=super.getConfig();return Object.assign(t,e),t}};Tb.className="ELU",_(Tb);class Nb extends Ct{constructor(t){super(t??{}),this.DEFAULT_THETA=1,t==null&&(t={}),this.theta=t.theta==null?this.DEFAULT_THETA:t.theta}call(t,e){const s=mt(t);return E(s,st(sn(s,this.theta),"float32"))}computeOutputShape(t){return t}getConfig(){const t={theta:this.theta},e=super.getConfig();return Object.assign(t,e),t}}Nb.className="ThresholdedReLU",_(Nb);class Rb extends Ct{constructor(t){super(t??{}),this.DEFAULT_AXIS=1,t==null&&(t={}),this.softmax=new ep().apply,this.axis=t.axis==null?this.DEFAULT_AXIS:t.axis}call(t,e){return M(()=>{let s=mt(t);const o=e.mask;if(o!=null){const r=E(pt(Ss(s.shape),st(o,s.dtype)),Gt(-1e9));s=Q(s,r)}return this.axis instanceof Array?this.axis.length>1?An(pt(s,Om(s,this.axis,!0))):this.softmax(s,this.axis[0]):this.softmax(s,this.axis)})}computeOutputShape(t){return t}getConfig(){const t={axis:this.axis},e=super.getConfig();return Object.assign(t,e),t}}Rb.className="Softmax",_(Rb);/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function or(n,t,e){if(typeof n=="number")return ho(n,t);if(n.length!==t)throw new $(`The ${e} argument must be an integer or tuple of ${t} integers. Received: ${n.length} elements.`);for(let s=0;s<t;++s){const o=n[s];if(!QR(o))throw new $(`The ${e} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(n)} including a non-integer number ${o}`)}return n}function Wn(n,t,e,s,o=1){if(n==null)return n;const r=t+(t-1)*(o-1);let i;return e==="same"?i=n:i=n-r+1,Math.floor((i+s-1)/s)}function Yn(n,t,e,s){if(n==null)return null;if(s==="valid")n=n*t+Rs([e-t,0]);else if(s==="same")n=n*t;else throw new $(`Unsupport padding mode: ${s}.`);return n}/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function sp(n,t){return M(()=>(se(t),t==="channelsFirst"?kt(n,[0,2,3,1]):n))}function $b(n,t){return M(()=>(se(t),t==="channelsFirst"?kt(n,[0,2,3,4,1]):n))}function mG(n,t,e,s=1,o="valid",r,i=1){return M(()=>{if(r==null&&(r=Gn()),se(r),n.shape.length!==3)throw new $(`The input of a conv1dWithBias operation should be 3, but is ${n.shape.length} instead.`);if(t.shape.length!==3)throw new $(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(e!=null&&e.shape.length!==1)throw new $(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(r==="channelsFirst"&&(n=kt(n,[0,2,1])),o==="causal")throw new bt("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let a=Lm(n,t,s,o==="same"?"same":"valid","NWC",i);return e!=null&&(a=Ln(a,e)),a})}function Gb(n,t,e,s=[1,1],o="valid",r,i,a=null){return M(()=>{if(r==null&&(r=Gn()),se(r),n.rank!==3&&n.rank!==4)throw new $(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${n.rank}.`);if(t.rank!==3&&t.rank!==4)throw new $(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${n.rank}.`);let c=sp(n,r);if(o==="causal")throw new bt("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return c=vk({x:c,filter:t,strides:s,pad:o==="same"?"same":"valid",dilations:i,dataFormat:"NHWC",bias:e,activation:a}),r==="channelsFirst"&&(c=kt(c,[0,3,1,2])),c})}function gG(n,t,e,s=[1,1,1],o="valid",r,i){return M(()=>{if(r==null&&(r=Gn()),se(r),n.rank!==4&&n.rank!==5)throw new $(`conv3dWithBias expects input to be of rank 4 or 5, but received ${n.rank}.`);if(t.rank!==4&&t.rank!==5)throw new $(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${n.rank}.`);let a=$b(n,r);if(o==="causal")throw new bt("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return a=C2(a,t,s,o==="same"?"same":"valid","NDHWC",i),e!=null&&(a=Ln(a,e)),r==="channelsFirst"&&(a=kt(a,[0,4,1,2,3])),a})}class al extends Ct{constructor(t,e){if(super(e),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",al.verifyArgs(e),this.rank=t,be(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new bt(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=or(e.kernelSize,t,"kernelSize"),this.strides=or(e.strides==null?1:e.strides,t,"strides"),this.padding=e.padding==null?"valid":e.padding,rn(this.padding),this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,se(this.dataFormat),this.activation=Ls(e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.biasInitializer=Ht(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=he(e.biasConstraint),this.biasRegularizer=_t(e.biasRegularizer),this.activityRegularizer=_t(e.activityRegularizer),this.dilationRate=or(e.dilationRate==null?1:e.dilationRate,t,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new $(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(this.rank===2){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==2)throw new $(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(this.rank===3){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==3)throw new $(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(t){if(Bn("kernelSize"in t,"required key 'kernelSize' not in config"),typeof t.kernelSize!="number"&&!Rh(t.kernelSize,"number",1,3))throw new $(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(t.kernelSize)}.`)}getConfig(){const t={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:Gs(this.activation),useBias:this.useBias,biasInitializer:Qt(this.biasInitializer),biasRegularizer:Vt(this.biasRegularizer),activityRegularizer:Vt(this.activityRegularizer),biasConstraint:de(this.biasConstraint)},e=super.getConfig();return Object.assign(t,e),t}}class rr extends al{constructor(t,e){super(t,e),this.kernel=null,rr.verifyArgs(e),this.filters=e.filters,be(this.filters,"filters"),this.kernelInitializer=Ht(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=he(e.kernelConstraint),this.kernelRegularizer=_t(e.kernelRegularizer)}build(t){t=Nt(t);const e=this.dataFormat==="channelsFirst"?1:t.length-1;if(t[e]==null)throw new $(`The channel dimension of the input should be defined. Found ${t[e]}`);const s=t[e],o=this.kernelSize.concat([s,this.filters]);this.kernel=this.addWeight("kernel",o,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[e]:s}}],this.built=!0}call(t,e){return M(()=>{t=mt(t);let s;const o=this.bias==null?null:this.bias.read(),r=l0(this.activation.getClassName());if(r!=null&&this.rank===2)s=Gb(t,this.kernel.read(),o,this.strides,this.padding,this.dataFormat,this.dilationRate,r);else{if(this.rank===1)s=mG(t,this.kernel.read(),o,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)s=Gb(t,this.kernel.read(),o,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)s=gG(t,this.kernel.read(),o,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new bt("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(s=this.activation.apply(s))}return s})}computeOutputShape(t){t=Nt(t);const e=[],s=this.dataFormat==="channelsLast"?t.slice(1,t.length-1):t.slice(2);for(let r=0;r<s.length;++r){const i=Wn(s[r],this.kernelSize[r],this.padding,this.strides[r],typeof this.dilationRate=="number"?this.dilationRate:this.dilationRate[r]);e.push(i)}let o=[t[0]];return this.dataFormat==="channelsLast"?(o=o.concat(e),o.push(this.filters)):(o.push(this.filters),o=o.concat(e)),o}getConfig(){const t={filters:this.filters,kernelInitializer:Qt(this.kernelInitializer),kernelRegularizer:Vt(this.kernelRegularizer),kernelConstraint:de(this.kernelConstraint)},e=super.getConfig();return Object.assign(t,e),t}static verifyArgs(t){if(!("filters"in t)||typeof t.filters!="number"||t.filters<1)throw new $(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(t.filters)}`)}}class Qi extends rr{constructor(t){super(2,t),Qi.verifyArgs(t)}getConfig(){const t=super.getConfig();return delete t.rank,t}static verifyArgs(t){if(typeof t.kernelSize!="number"&&!Rh(t.kernelSize,"number",1,2))throw new $(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(t.kernelSize)}.`)}}Qi.className="Conv2D",_(Qi);class Ji extends rr{constructor(t){super(3,t),Ji.verifyArgs(t)}getConfig(){const t=super.getConfig();return delete t.rank,t}static verifyArgs(t){if(typeof t.kernelSize!="number"&&!(Array.isArray(t.kernelSize)&&(t.kernelSize.length===1||t.kernelSize.length===3)))throw new $(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(t.kernelSize)}.`)}}Ji.className="Conv3D",_(Ji);class Lb extends Qi{constructor(t){if(super(t),this.inputSpec=[new ue({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new $(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(t){if(t=Nt(t),t.length!==4)throw new $("Input should have rank 4; Received input shape: "+JSON.stringify(t));const e=this.dataFormat==="channelsFirst"?1:t.length-1;if(t[e]==null)throw new $("The channel dimension of the inputs should be defined. Found `None`.");const s=t[e],o=this.kernelSize.concat([this.filters,s]);this.kernel=this.addWeight("kernel",o,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new ue({ndim:4,axes:{[e]:s}})],this.built=!0}call(t,e){return M(()=>{let s=mt(t);if(s.shape.length!==4)throw new $(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${s.shape.length}`);const o=s.shape,r=o[0];let i,a;this.dataFormat==="channelsFirst"?(i=2,a=3):(i=1,a=2);const c=o[i],l=o[a],u=this.kernelSize[0],d=this.kernelSize[1],h=this.strides[0],p=this.strides[1],f=Yn(c,h,u,this.padding),m=Yn(l,p,d,this.padding),g=[r,f,m,this.filters];this.dataFormat!=="channelsLast"&&(s=kt(s,[0,2,3,1]));let b=Em(s,this.kernel.read(),g,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(b=kt(b,[0,3,1,2])),this.bias!=null&&(b=Ln(b,this.bias.read(),this.dataFormat)),this.activation!=null&&(b=this.activation.apply(b)),b})}computeOutputShape(t){t=Nt(t);const e=t.slice();let s,o,r;this.dataFormat==="channelsFirst"?(s=1,o=2,r=3):(s=3,o=1,r=2);const i=this.kernelSize[0],a=this.kernelSize[1],c=this.strides[0],l=this.strides[1];return e[s]=this.filters,e[o]=Yn(e[o],c,i,this.padding),e[r]=Yn(e[r],l,a,this.padding),e}getConfig(){const t=super.getConfig();return delete t.dilationRate,t}}Lb.className="Conv2DTranspose",_(Lb);class Eb extends Ji{constructor(t){if(super(t),this.inputSpec=[new ue({ndim:5})],this.padding!=="same"&&this.padding!=="valid")throw new $(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(t){if(t=Nt(t),t.length!==5)throw new $("Input should have rank 5; Received input shape: "+JSON.stringify(t));const e=this.dataFormat==="channelsFirst"?1:t.length-1;if(t[e]==null)throw new $("The channel dimension of the inputs should be defined. Found `None`.");const s=t[e],o=this.kernelSize.concat([this.filters,s]);this.kernel=this.addWeight("kernel",o,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new ue({ndim:5,axes:{[e]:s}})],this.built=!0}call(t,e){return M(()=>{let s=mt(t);if(s.shape.length!==5)throw new $(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${s.shape.length}`);const o=s.shape,r=o[0];let i,a,c;this.dataFormat==="channelsFirst"?(c=2,i=3,a=4):(c=1,i=2,a=3);const l=o[c],u=o[i],d=o[a],h=this.kernelSize[0],p=this.kernelSize[1],f=this.kernelSize[2],m=this.strides[0],g=this.strides[1],b=this.strides[2],x=Yn(l,m,h,this.padding),I=Yn(u,g,p,this.padding),y=Yn(d,b,f,this.padding),w=[r,x,I,y,this.filters];this.dataFormat!=="channelsLast"&&(s=kt(s,[0,2,3,4,1]));let C=k2(s,this.kernel.read(),w,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(C=kt(C,[0,4,1,2,3])),this.bias!==null&&(C=Ln(C,this.bias.read(),this.dataFormat)),this.activation!==null&&(C=this.activation.apply(C)),C})}computeOutputShape(t){t=Nt(t);const e=t.slice();let s,o,r,i;this.dataFormat==="channelsFirst"?(s=1,o=2,r=3,i=4):(s=4,o=1,r=2,i=3);const a=this.kernelSize[0],c=this.kernelSize[1],l=this.kernelSize[2],u=this.strides[0],d=this.strides[1],h=this.strides[2];return e[s]=this.filters,e[o]=Yn(e[o],u,a,this.padding),e[r]=Yn(e[r],d,c,this.padding),e[i]=Yn(e[i],h,l,this.padding),e}getConfig(){const t=super.getConfig();return delete t.dilationRate,t}}Eb.className="Conv3DTranspose",_(Eb);class Db extends rr{constructor(t,e){if(super(t,e),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,e.filters==null)throw new $("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(e.kernelInitializer!=null||e.kernelRegularizer!=null||e.kernelConstraint!=null)throw new $("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(e.padding!=null&&e.padding!=="same"&&e.padding!=="valid")throw new $(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(e.padding)}`);this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=Ht(e.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=_t(e.depthwiseRegularizer),this.depthwiseConstraint=he(e.depthwiseConstraint),this.pointwiseInitializer=Ht(e.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=_t(e.pointwiseRegularizer),this.pointwiseConstraint=he(e.pointwiseConstraint)}build(t){if(t=Nt(t),t.length<this.rank+2)throw new $(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank+2}, but received input shape: ${JSON.stringify(t)}`);const e=this.dataFormat==="channelsFirst"?1:t.length-1;if(t[e]==null||t[e]<0)throw new $(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(t[e])}`);const s=t[e],o=this.kernelSize.concat([s,this.depthMultiplier]),r=[];for(let a=0;a<this.rank;++a)r.push(1);r.push(s*this.depthMultiplier,this.filters);const i=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",o,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,i,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",r,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,i,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,i,this.biasConstraint):this.bias=null,this.inputSpec=[new ue({ndim:this.rank+2,axes:{[e]:s}})],this.built=!0}call(t,e){return M(()=>{t=mt(t);let s;if(this.rank===1)throw new bt("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(t=kt(t,[0,2,3,1])),s=Jm(t,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(s=Ln(s,this.bias.read(),this.dataFormat)),this.activation!=null&&(s=this.activation.apply(s)),this.dataFormat==="channelsFirst"&&(s=kt(s,[0,3,1,2])),s})}getConfig(){const t=super.getConfig();return delete t.rank,delete t.kernelInitializer,delete t.kernelRegularizer,delete t.kernelConstraint,t.depthwiseInitializer=Qt(this.depthwiseInitializer),t.pointwiseInitializer=Qt(this.pointwiseInitializer),t.depthwiseRegularizer=Vt(this.depthwiseRegularizer),t.pointwiseRegularizer=Vt(this.pointwiseRegularizer),t.depthwiseConstraint=de(this.depthwiseConstraint),t.pointwiseConstraint=de(this.pointwiseConstraint),t}}Db.className="SeparableConv";class Wb extends Db{constructor(t){super(2,t)}}Wb.className="SeparableConv2D",_(Wb);class cl extends rr{constructor(t){super(1,t),cl.verifyArgs(t),this.inputSpec=[{ndim:3}]}getConfig(){const t=super.getConfig();return delete t.rank,delete t.dataFormat,t}static verifyArgs(t){if(typeof t.kernelSize!="number"&&!Rh(t.kernelSize,"number",1,1))throw new $(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(t.kernelSize)}.`)}}cl.className="Conv1D",_(cl);class Mb extends Ct{constructor(t){super(t),typeof t.cropping=="number"?this.cropping=[[t.cropping,t.cropping],[t.cropping,t.cropping]]:typeof t.cropping[0]=="number"?this.cropping=[[t.cropping[0],t.cropping[0]],[t.cropping[1],t.cropping[1]]]:this.cropping=t.cropping,this.dataFormat=t.dataFormat===void 0?"channelsLast":t.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(t){return this.dataFormat==="channelsFirst"?[t[0],t[1],t[2]-this.cropping[0][0]-this.cropping[0][1],t[3]-this.cropping[1][0]-this.cropping[1][1]]:[t[0],t[1]-this.cropping[0][0]-this.cropping[0][1],t[2]-this.cropping[1][0]-this.cropping[1][1],t[3]]}call(t,e){return M(()=>{if(t=mt(t),this.dataFormat==="channelsLast"){const s=Hc(t,this.cropping[0][0],t.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Hc(s,this.cropping[1][0],t.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{const s=Hc(t,this.cropping[0][0],t.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Hc(s,this.cropping[1][0],t.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}})}getConfig(){const t={cropping:this.cropping,dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}}Mb.className="Cropping2D",_(Mb);class Vb extends Ct{constructor(t){super(t),this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=t.size==null?this.DEFAULT_SIZE:t.size,this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,se(this.dataFormat),this.interpolation=t.interpolation==null?"nearest":t.interpolation,_R(this.interpolation)}computeOutputShape(t){if(this.dataFormat==="channelsFirst"){const e=t[2]==null?null:this.size[0]*t[2],s=t[3]==null?null:this.size[1]*t[3];return[t[0],t[1],e,s]}else{const e=t[1]==null?null:this.size[0]*t[1],s=t[2]==null?null:this.size[1]*t[2];return[t[0],e,s,t[3]]}}call(t,e){return M(()=>{let s=mt(t);const o=s.shape;if(this.dataFormat==="channelsFirst"){s=kt(s,[0,2,3,1]);const r=this.size[0]*o[2],i=this.size[1]*o[3],a=this.interpolation==="nearest"?is.resizeNearestNeighbor(s,[r,i]):is.resizeBilinear(s,[r,i]);return kt(a,[0,3,1,2])}else{const r=this.size[0]*o[1],i=this.size[1]*o[2];return this.interpolation==="nearest"?is.resizeNearestNeighbor(s,[r,i]):is.resizeBilinear(s,[r,i])}})}getConfig(){const t={size:this.size,dataFormat:this.dataFormat,interpolation:this.interpolation},e=super.getConfig();return Object.assign(t,e),t}}Vb.className="UpSampling2D",_(Vb);/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function bG(n,t,e=[1,1],s="valid",o,r){return M(()=>{o==null&&(o=Gn()),se(o);let i=sp(n,o);if(n.rank!==4)throw new $(`Input for depthwiseConv2d is required to be 4-D, but is instead ${n.rank}-D`);if(t.rank!==4)throw new $(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return i=xd(i,t,e,s==="same"?"same":"valid","NHWC",r),o==="channelsFirst"&&(i=kt(i,[0,3,1,2])),i})}class Fb extends al{constructor(t){super(2,t),this.depthwiseKernel=null,this.depthMultiplier=t.depthMultiplier==null?1:t.depthMultiplier,this.depthwiseInitializer=Ht(t.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=he(t.depthwiseConstraint),this.depthwiseRegularizer=_t(t.depthwiseRegularizer)}build(t){if(t=Nt(t),t.length<4)throw new $(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(t)}.`);const e=this.dataFormat==="channelsFirst"?1:3;if(t[e]==null||t[e]<0)throw new $(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${t[e]}).`);const s=t[e],o=[this.kernelSize[0],this.kernelSize[1],s,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",o,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[s*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(t,e){return M(()=>{t=mt(t);let s=bG(t,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(s=Ln(s,this.bias.read(),this.dataFormat)),this.activation!=null&&(s=this.activation.apply(s)),s})}computeOutputShape(t){t=Nt(t);const e=this.dataFormat==="channelsFirst"?t[2]:t[1],s=this.dataFormat==="channelsFirst"?t[3]:t[2],o=this.dataFormat==="channelsFirst"?t[1]*this.depthMultiplier:t[3]*this.depthMultiplier,r=Wn(e,this.kernelSize[0],this.padding,this.strides[0]),i=Wn(s,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[t[0],o,r,i]:[t[0],r,i,o]}getConfig(){const t=super.getConfig();return t.depthMultiplier=this.depthMultiplier,t.depthwiseInitializer=Qt(this.depthwiseInitializer),t.depthwiseRegularizer=Vt(this.depthwiseRegularizer),t.depthwiseConstraint=de(this.depthwiseRegularizer),t}}Fb.className="DepthwiseConv2D",_(Fb);/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function zb(n,t,e,s){if(Array.isArray(n)){if(t!=null||e!=null)throw new $("When inputs is an array, neither initialState or constants should be provided");s!=null&&(e=n.slice(n.length-s,n.length),n=n.slice(0,n.length-s)),n.length>1&&(t=n.slice(1,n.length)),n=n[0]}function o(r){return r==null||Array.isArray(r)?r:[r]}return t=o(t),e=o(e),{inputs:n,initialState:t,constants:e}}function Xb(n,t,e,s=!1,o,r,i=!1,a=!1){return M(()=>{const c=t.shape.length;if(c<3)throw new $(`Input should be at least 3D, but is ${c}D.`);const l=[1,0].concat($n(2,c));if(t=kt(t,l),r!=null)throw new bt("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."),o!=null&&(o=st(st(o,"bool"),"float32"),o.rank===c-1&&(o=Ae(o,-1)),o=kt(o,l)),s&&(t=ao(t,0),o!=null&&(o=ao(o,0)));const u=[];let d,h=e;const p=t.shape[0],f=lo(t);let m;o!=null&&(m=lo(o));for(let b=0;b<p;++b){const x=f[b],I=M(()=>n(x,h));if(o==null)d=I[0],h=I[1];else{const y=M(()=>{const w=m[b],C=pt(fn(w),w),k=Q(E(I[0],w),E(h[0],C)),S=h.map((T,R)=>Q(E(I[1][R],w),E(T,C)));return{output:k,newStates:S}});d=y.output,h=y.newStates}a&&u.push(d)}let g;return a&&(g=On(u,1)),[d,g,h]})}class Es extends Ct{constructor(t){super(t);let e;if(t.cell==null)throw new $("cell property is missing for the constructor of RNN.");if(Array.isArray(t.cell)?e=new ip({cells:t.cell}):e=t.cell,e.stateSize==null)throw new $("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=e,this.returnSequences=t.returnSequences==null?!1:t.returnSequences,this.returnState=t.returnState==null?!1:t.returnState,this.goBackwards=t.goBackwards==null?!1:t.goBackwards,this._stateful=t.stateful==null?!1:t.stateful,this.unroll=t.unroll==null?!1:t.unroll,this.supportsMasking=!0,this.inputSpec=[new ue({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(this.states_==null){const t=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;return $n(0,t).map(e=>null)}else return this.states_}setStates(t){this.states_=t}computeOutputShape(t){Ph(t)&&(t=t[0]),t=t;let e=this.cell.stateSize;Array.isArray(e)||(e=[e]);const s=e[0];let o;if(this.returnSequences?o=[t[0],t[1],s]:o=[t[0],s],this.returnState){const r=[];for(const i of e)r.push([t[0],i]);return[o].concat(r)}else return o}computeMask(t,e){return M(()=>{Array.isArray(e)&&(e=e[0]);const s=this.returnSequences?e:null;if(this.returnState){const o=this.states.map(r=>null);return[s].concat(o)}else return s})}get states(){if(this.states_==null){const t=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,e=[];for(let s=0;s<t;++s)e.push(null);return e}else return this.states_}set states(t){this.states_=t}build(t){if(this.numConstants!=null)throw new bt("Constants support is not implemented in RNN yet.");Ph(t)&&(t=t[0]),t=t;const e=this.stateful?t[0]:null,s=t.slice(2);this.inputSpec[0]=new ue({shape:[e,null,...s]});const o=[t[0]].concat(t.slice(2));this.cell.build(o);let r;if(Array.isArray(this.cell.stateSize)?r=this.cell.stateSize:r=[this.cell.stateSize],this.stateSpec!=null){if(!Rt(this.stateSpec.map(i=>i.shape[i.shape.length-1]),r))throw new $(`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(i=>new ue({shape:[null,i]}));this.stateful&&this.resetStates()}resetStates(t,e=!1){M(()=>{if(!this.stateful)throw new Zn("Cannot call resetStates() on an RNN Layer that is not stateful.");const s=this.inputSpec[0].shape[0];if(s==null)throw new $("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(this.states_==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(o=>ge([s,o])):this.states_=[ge([s,this.cell.stateSize])];else if(t==null)vt(this.states_),this.keptStates!=null&&(vt(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(o=>ge([s,o])):this.states_[0]=ge([s,this.cell.stateSize]);else{if(Array.isArray(t)||(t=[t]),t.length!==this.states_.length)throw new $(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${t.length} state value(s). Input received: ${t}`);e===!0?this.keptStates.push(this.states_.slice()):vt(this.states_);for(let o=0;o<this.states_.length;++o){const r=t[o],i=Array.isArray(this.cell.stateSize)?this.cell.stateSize[o]:this.cell.stateSize,a=[s,i];if(!Rt(r.shape,a))throw new $(`State ${o} is incompatible with layer ${this.name}: expected shape=${a}, received shape=${r.shape}`);this.states_[o]=r}}this.states_=this.states_.map(o=>en(o.clone()))})}apply(t,e){let s=e==null?null:e.initialState,o=e==null?null:e.constants;e==null&&(e={});const r=zb(t,s,o,this.numConstants);t=r.inputs,s=r.initialState,o=r.constants;let i=[],a=[];if(s!=null){e.initialState=s,i=i.concat(s),this.stateSpec=[];for(const l of s)this.stateSpec.push(new ue({shape:l.shape}));a=a.concat(this.stateSpec)}if(o!=null&&(e.constants=o,i=i.concat(o),this.numConstants=o.length),i[0]instanceof Un){const l=[t].concat(i),u=this.inputSpec.concat(a),d=this.inputSpec;this.inputSpec=u;const h=super.apply(l,e);return this.inputSpec=d,h}else return super.apply(t,e)}call(t,e){return M(()=>{const s=e==null?null:e.mask,o=e==null?null:e.training;let r=e==null?null:e.initialState;t=mt(t),r==null&&(this.stateful?r=this.states_:r=this.getInitialState(t));const i=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(r.length!==i)throw new $(`RNN Layer has ${i} 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 a={training:o},l=Xb((f,m)=>{const g=this.cell.call([f].concat(m),a);return[g[0],g.slice(1)]},t,r,this.goBackwards,s,null,this.unroll,this.returnSequences),u=l[0],d=l[1],h=l[2];this.stateful&&this.resetStates(h,o);const p=this.returnSequences?d:u;return this.returnState?[p].concat(h):p})}getInitialState(t){return M(()=>{let e=ge(t.shape);return e=ut(e,[1,2]),e=Ai(e),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(s=>s>1?Eh(e,[1,s]):e):this.cell.stateSize>1?[Eh(e,[1,this.cell.stateSize])]:[e]})}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(t){super.setFastWeightInitDuringBuild(t),this.cell!=null&&this.cell.setFastWeightInitDuringBuild(t)}getConfig(){const t=super.getConfig(),e={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};this.numConstants!=null&&(e.numConstants=this.numConstants);const s=this.cell.getConfig();return this.getClassName()===Es.className&&(e.cell={className:this.cell.getClassName(),config:s}),Object.assign(Object.assign(Object.assign({},s),t),e)}static fromConfig(t,e,s={}){const o=e.cell,r=us(o,s);return new t(Object.assign(e,{cell:r}))}}Es.className="RNN",_(Es);class ll extends Ct{}class op extends ll{constructor(t){super(t),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=t.units,be(this.units,"units"),this.activation=Ls(t.activation==null?this.DEFAULT_ACTIVATION:t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.kernelInitializer=Ht(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ht(t.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ht(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=_t(t.kernelRegularizer),this.recurrentRegularizer=_t(t.recurrentRegularizer),this.biasRegularizer=_t(t.biasRegularizer),this.kernelConstraint=he(t.kernelConstraint),this.recurrentConstraint=he(t.recurrentConstraint),this.biasConstraint=he(t.biasConstraint),this.dropout=nr([1,Rs([0,t.dropout==null?0:t.dropout])]),this.recurrentDropout=nr([1,Rs([0,t.recurrentDropout==null?0:t.recurrentDropout])]),this.dropoutFunc=t.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(t){t=Nt(t),this.kernel=this.addWeight("kernel",[t[t.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(t,e){return M(()=>{if(t=t,t.length!==2)throw new $(`SimpleRNNCell expects 2 input Tensors, got ${t.length}.`);let s=t[1];t=t[0];const o=e.training==null?!1:e.training;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Ds({ones:()=>fn(t),rate:this.dropout,training:o,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Ds({ones:()=>fn(s),rate:this.recurrentDropout,training:o,dropoutFunc:this.dropoutFunc}));let r;const i=this.dropoutMask,a=this.recurrentDropoutMask;i!=null?r=_n(E(t,i),this.kernel.read()):r=_n(t,this.kernel.read()),this.bias!=null&&(r=Ln(r,this.bias.read())),a!=null&&(s=E(s,a));let c=Q(r,_n(s,this.recurrentKernel.read()));return this.activation!=null&&(c=this.activation.apply(c)),[c,c]})}getConfig(){const t=super.getConfig(),e={units:this.units,activation:Gs(this.activation),useBias:this.useBias,kernelInitializer:Qt(this.kernelInitializer),recurrentInitializer:Qt(this.recurrentInitializer),biasInitializer:Qt(this.biasInitializer),kernelRegularizer:Vt(this.kernelRegularizer),recurrentRegularizer:Vt(this.recurrentRegularizer),biasRegularizer:Vt(this.biasRegularizer),activityRegularizer:Vt(this.activityRegularizer),kernelConstraint:de(this.kernelConstraint),recurrentConstraint:de(this.recurrentConstraint),biasConstraint:de(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign(Object.assign({},t),e)}}op.className="SimpleRNNCell",_(op);class Ab extends Es{constructor(t){t.cell=new op(t),super(t)}call(t,e){return M(()=>{this.cell.dropoutMask!=null&&(vt(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(vt(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const s=e==null?null:e.mask,o=e==null?null:e.training,r=e==null?null:e.initialState;return super.call(t,{mask:s,training:o,initialState:r})})}static fromConfig(t,e){return new t(e)}}Ab.className="SimpleRNN",_(Ab);class rp extends ll{constructor(t){if(super(t),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",t.resetAfter)throw new $("GRUCell does not support reset_after parameter set to true.");this.units=t.units,be(this.units,"units"),this.activation=Ls(t.activation===void 0?this.DEFAULT_ACTIVATION:t.activation),this.recurrentActivation=Ls(t.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:t.recurrentActivation),this.useBias=t.useBias==null?!0:t.useBias,this.kernelInitializer=Ht(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ht(t.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ht(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=_t(t.kernelRegularizer),this.recurrentRegularizer=_t(t.recurrentRegularizer),this.biasRegularizer=_t(t.biasRegularizer),this.kernelConstraint=he(t.kernelConstraint),this.recurrentConstraint=he(t.recurrentConstraint),this.biasConstraint=he(t.biasConstraint),this.dropout=nr([1,Rs([0,t.dropout==null?0:t.dropout])]),this.recurrentDropout=nr([1,Rs([0,t.recurrentDropout==null?0:t.recurrentDropout])]),this.dropoutFunc=t.dropoutFunc,this.implementation=t.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(t){t=Nt(t);const e=t[t.length-1];this.kernel=this.addWeight("kernel",[e,this.units*3],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*3],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units*3],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(t,e){return M(()=>{if(t=t,t.length!==2)throw new $(`GRUCell expects 2 input Tensors (inputs, h, c), got ${t.length}.`);const s=e.training==null?!1:e.training;let o=t[1];t=t[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Ds({ones:()=>fn(t),rate:this.dropout,training:s,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Ds({ones:()=>fn(o),rate:this.recurrentDropout,training:s,count:3,dropoutFunc:this.dropoutFunc}));const r=this.dropoutMask,i=this.recurrentDropoutMask;let a,c,l;0<this.dropout&&this.dropout<1&&(t=E(t,r[0]));let u=_n(t,this.kernel.read());this.useBias&&(u=Ln(u,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(o=E(o,i[0]));const d=this.recurrentKernel.read(),[h,p]=on(d,[2*this.units,this.units],d.rank-1),f=_n(o,h),[m,g,b]=on(u,3,u.rank-1),[x,I]=on(f,2,f.rank-1);a=this.recurrentActivation.apply(Q(m,x)),c=this.recurrentActivation.apply(Q(g,I));const y=_n(E(c,o),p);l=this.activation.apply(Q(b,y));const w=Q(E(a,o),E(Q(1,ne(a)),l));return[w,w]})}getConfig(){const t=super.getConfig(),e={units:this.units,activation:Gs(this.activation),recurrentActivation:Gs(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Qt(this.kernelInitializer),recurrentInitializer:Qt(this.recurrentInitializer),biasInitializer:Qt(this.biasInitializer),kernelRegularizer:Vt(this.kernelRegularizer),recurrentRegularizer:Vt(this.recurrentRegularizer),biasRegularizer:Vt(this.biasRegularizer),activityRegularizer:Vt(this.activityRegularizer),kernelConstraint:de(this.kernelConstraint),recurrentConstraint:de(this.recurrentConstraint),biasConstraint:de(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign(Object.assign({},t),e)}}rp.className="GRUCell",_(rp);class Pb extends Es{constructor(t){t.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),t.cell=new rp(t),super(t)}call(t,e){return M(()=>{this.cell.dropoutMask!=null&&(vt(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(vt(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const s=e==null?null:e.mask,o=e==null?null:e.training,r=e==null?null:e.initialState;return super.call(t,{mask:s,training:o,initialState:r})})}static fromConfig(t,e){return e.implmentation===0&&(e.implementation=1),new t(e)}}Pb.className="GRU",_(Pb);class ul extends ll{constructor(t){super(t),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=t.units,be(this.units,"units"),this.activation=Ls(t.activation===void 0?this.DEFAULT_ACTIVATION:t.activation),this.recurrentActivation=Ls(t.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:t.recurrentActivation),this.useBias=t.useBias==null?!0:t.useBias,this.kernelInitializer=Ht(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ht(t.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ht(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=t.unitForgetBias,this.kernelRegularizer=_t(t.kernelRegularizer),this.recurrentRegularizer=_t(t.recurrentRegularizer),this.biasRegularizer=_t(t.biasRegularizer),this.kernelConstraint=he(t.kernelConstraint),this.recurrentConstraint=he(t.recurrentConstraint),this.biasConstraint=he(t.biasConstraint),this.dropout=nr([1,Rs([0,t.dropout==null?0:t.dropout])]),this.recurrentDropout=nr([1,Rs([0,t.recurrentDropout==null?0:t.recurrentDropout])]),this.dropoutFunc=t.dropoutFunc,this.implementation=t.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(t){var e;t=Nt(t);const s=t[t.length-1];this.kernel=this.addWeight("kernel",[s,this.units*4],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*4],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint);let o;if(this.useBias){if(this.unitForgetBias){const r=this.biasInitializer,i=this.units;o=new(e=class extends xn{apply(c,l){const u=r.apply([i]),d=new Wh().apply([i]),h=r.apply([i*2]);return g0(g0(u,d),h)}},e.className="CustomInit",e)}else o=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,o,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(t,e){return M(()=>{const s=e.training==null?!1:e.training;if(t=t,t.length!==3)throw new $(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${t.length}.`);let o=t[1];const r=t[2];t=t[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Ds({ones:()=>fn(t),rate:this.dropout,training:s,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Ds({ones:()=>fn(o),rate:this.recurrentDropout,training:s,count:4,dropoutFunc:this.dropoutFunc}));const i=this.dropoutMask,a=this.recurrentDropoutMask;let c,l,u,d;0<this.dropout&&this.dropout<1&&(t=E(t,i[0]));let h=_n(t,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(o=E(o,a[0])),h=Q(h,_n(o,this.recurrentKernel.read())),this.useBias&&(h=Ln(h,this.bias.read()));const[p,f,m,g]=on(h,4,h.rank-1);c=this.recurrentActivation.apply(p),l=this.recurrentActivation.apply(f),u=Q(E(l,r),E(c,this.activation.apply(m))),d=this.recurrentActivation.apply(g);const b=E(d,this.activation.apply(u));return[b,b,u]})}getConfig(){const t=super.getConfig(),e={units:this.units,activation:Gs(this.activation),recurrentActivation:Gs(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Qt(this.kernelInitializer),recurrentInitializer:Qt(this.recurrentInitializer),biasInitializer:Qt(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Vt(this.kernelRegularizer),recurrentRegularizer:Vt(this.recurrentRegularizer),biasRegularizer:Vt(this.biasRegularizer),activityRegularizer:Vt(this.activityRegularizer),kernelConstraint:de(this.kernelConstraint),recurrentConstraint:de(this.recurrentConstraint),biasConstraint:de(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign(Object.assign({},t),e)}}ul.className="LSTMCell",_(ul);class Ob extends Es{constructor(t){t.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),t.cell=new ul(t),super(t)}call(t,e){return M(()=>{this.cell.dropoutMask!=null&&(vt(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(vt(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const s=e==null?null:e.mask,o=e==null?null:e.training,r=e==null?null:e.initialState;return super.call(t,{mask:s,training:o,initialState:r})})}static fromConfig(t,e){return e.implmentation===0&&(e.implementation=1),new t(e)}}Ob.className="LSTM",_(Ob);class ip extends ll{constructor(t){super(t),this.cells=t.cells}get stateSize(){const t=[];for(const e of this.cells.slice().reverse())Array.isArray(e.stateSize)?t.push(...e.stateSize):t.push(e.stateSize);return t}call(t,e){return M(()=>{t=t;let s=t.slice(1);const o=[];for(const a of this.cells.slice().reverse())Array.isArray(a.stateSize)?o.push(s.splice(0,a.stateSize.length)):o.push(s.splice(0,1));o.reverse();const r=[];let i;for(let a=0;a<this.cells.length;++a){const c=this.cells[a];s=o[a],a===0?i=[t[0]].concat(s):i=[i[0]].concat(s),i=c.call(i,e),r.push(i.slice(1))}s=[];for(const a of r.slice().reverse())s.push(...a);return[i[0]].concat(s)})}build(t){Ph(t)&&(t=t[0]),t=t;let e;this.cells.forEach((s,o)=>{mo(`RNNCell_${o}`,()=>{s.build(t),Array.isArray(s.stateSize)?e=s.stateSize[0]:e=s.stateSize,t=[t[0],e]})}),this.built=!0}getConfig(){const t=super.getConfig(),e=r=>({className:r.getClassName(),config:r.getConfig()}),o={cells:this.cells.map(e)};return Object.assign(Object.assign({},t),o)}static fromConfig(t,e,s={}){const o=[];for(const r of e.cells)o.push(us(r,s));return new t({cells:o})}get trainableWeights(){if(!this.trainable)return[];const t=[];for(const e of this.cells)t.push(...e.trainableWeights);return t}get nonTrainableWeights(){const t=[];for(const e of this.cells)t.push(...e.nonTrainableWeights);if(!this.trainable){const e=[];for(const s of this.cells)e.push(...s.trainableWeights);return e.concat(t)}return t}getWeights(){const t=[];for(const e of this.cells)t.push(...e.weights);return Oh(t)}setWeights(t){const e=[];for(const s of this.cells){const o=s.weights.length,r=t.splice(o);for(let i=0;i<s.weights.length;++i)e.push([s.weights[i],r[i]])}Kh(e)}}ip.className="StackedRNNCells",_(ip);function Ds(n){const{ones:t,rate:e,training:s=!1,count:o=1,dropoutFunc:r}=n,i=()=>r!=null?r(t(),e):x0(t(),e),a=()=>Oi(i,t,s);return!o||o<=1?en(a().clone()):Array(o).fill(void 0).map(a).map(l=>en(l.clone()))}/**
 * @license
 * Copyright 2020 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */var xG=function(n,t){var e={};for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&t.indexOf(s)<0&&(e[s]=n[s]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,s=Object.getOwnPropertySymbols(n);o<s.length;o++)t.indexOf(s[o])<0&&Object.prototype.propertyIsEnumerable.call(n,s[o])&&(e[s[o]]=n[s[o]]);return e};class Kb extends Es{constructor(t){if(t.unroll)throw new bt("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(t.cell))throw new bt("It is not possible at the moment to stack convolutional cells.");super(t),this.inputSpec=[new ue({ndim:5})]}call(t,e){return M(()=>{if(this.cell.dropoutMask!=null&&(vt(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(vt(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),e&&e.constants)throw new $("ConvRNN2D cell does not support constants");const s=e==null?null:e.mask,o=e==null?null:e.training,r=e==null?null:e.initialState;return super.call(t,{mask:s,training:o,initialState:r})})}computeOutputShape(t){let e=this.computeSingleOutputShape(t);return this.returnSequences||(e=[e[0],...e.slice(2)]),this.returnState&&(e=[e,...Array(2).fill([t[0],...e.slice(-3)])]),e}getInitialState(t){return M(()=>{const{stateSize:e}=this.cell,s=t.shape,o=this.computeSingleOutputShape(s),r=[o[0],...o.slice(2)],i=ge(r);return Array.isArray(e)?Array(e.length).fill(i):[i]})}resetStates(t,e=!1){M(()=>{if(!this.stateful)throw new Zn("Cannot call resetStates() on an RNN Layer that is not stateful.");const s=this.inputSpec[0].shape,o=this.computeSingleOutputShape(s),r=[o[0],...o.slice(2)];if(s[0]==null)throw new $("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(this.getStates()==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>ge(r)):this.states_=[ge(r)];else if(t==null)vt(this.states_),this.keptStates!=null&&(vt(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>ge(r)):this.states_[0]=ge(r);else{if(Array.isArray(t)||(t=[t]),t.length!==this.states_.length)throw new $(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${t.length} state value(s). Input received: ${t}`);e?this.keptStates.push(this.states_.slice()):vt(this.states_);for(let a=0;a<this.states_.length;++a){const c=t[a],l=r;if(!Rt(c.shape,l))throw new $(`State ${a} is incompatible with layer ${this.name}: expected shape=${l}, received shape=${c.shape}`);this.states_[a]=c}}this.states_=this.states_.map(a=>en(a.clone()))})}computeSingleOutputShape(t){const{dataFormat:e,filters:s,kernelSize:o,padding:r,strides:i,dilationRate:a}=this.cell,c=e==="channelsFirst",l=t[c?3:2],u=t[c?4:3],d=Wn(l,o[0],r,i[0],a[0]),h=Wn(u,o[1],r,i[1],a[1]);return[...t.slice(0,2),...c?[s,d,h]:[d,h,s]]}}Kb.className="ConvRNN2D";class ap extends ul{constructor(t){const{filters:e,kernelSize:s,strides:o,padding:r,dataFormat:i,dilationRate:a}=t;super(Object.assign(Object.assign({},t),{units:e})),this.filters=e,be(this.filters,"filters"),this.kernelSize=or(s,2,"kernelSize"),this.kernelSize.forEach(c=>be(c,"kernelSize")),this.strides=or(o||1,2,"strides"),this.strides.forEach(c=>be(c,"strides")),this.padding=r||"valid",rn(this.padding),this.dataFormat=i||"channelsLast",se(this.dataFormat),this.dilationRate=or(a||1,2,"dilationRate"),this.dilationRate.forEach(c=>be(c,"dilationRate"))}build(t){var e;t=Nt(t);const s=this.dataFormat==="channelsFirst"?1:t.length-1;if(t[s]==null)throw new $(`The channel dimension of the input should be defined. Found ${t[s]}`);const o=t[s],r=4,i=this.kernelSize.concat([o,this.filters*r]);this.kernel=this.addWeight("kernel",i,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);const a=this.kernelSize.concat([this.filters,this.filters*r]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",a,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let c;if(this.unitForgetBias){const l=this.biasInitializer,u=this.filters;c=new(e=class extends xn{apply(h,p){const f=l.apply([u]),m=Ss([u]),g=l.apply([u*2]);return Lh([f,m,g])}},e.className="CustomInit",e)}else c=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*r],null,c,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(t,e){return M(()=>{if(t.length!==3)throw new $(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${t.length}.`);const s=e.training||!1,o=t[0],r=t[1],i=t[2],a=4;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Ds({ones:()=>fn(o),rate:this.dropout,training:s,count:a,dropoutFunc:this.dropoutFunc}));const c=this.dropoutMask,l=(U,Y,j)=>!Y||!Y[j]?U:E(Y[j],U);let u=l(o,c,0),d=l(o,c,1),h=l(o,c,2),p=l(o,c,3);0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Ds({ones:()=>fn(r),rate:this.recurrentDropout,training:s,count:a,dropoutFunc:this.dropoutFunc}));const f=this.recurrentDropoutMask;let m=l(r,f,0),g=l(r,f,1),b=l(r,f,2),x=l(r,f,3);const I=3,[y,w,C,k]=on(this.kernel.read(),a,I),[S,T,R,L]=this.useBias?on(this.bias.read(),a):[null,null,null,null];u=this.inputConv(u,y,S,this.padding),d=this.inputConv(d,w,T,this.padding),h=this.inputConv(h,C,R,this.padding),p=this.inputConv(p,k,L,this.padding);const[V,F,X,A]=on(this.recurrentKernel.read(),a,I);m=this.recurrentConv(m,V),g=this.recurrentConv(g,F),b=this.recurrentConv(b,X),x=this.recurrentConv(x,A);const P=this.recurrentActivation.apply(Q(u,m)),B=this.recurrentActivation.apply(Q(d,g)),K=Q(E(B,i),E(P,this.activation.apply(Q(h,b)))),H=E(this.recurrentActivation.apply(Q(p,x)),this.activation.apply(K));return[H,H,K]})}getConfig(){const t=super.getConfig(),e=xG(t,["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({},e),s)}inputConv(t,e,s,o){const r=so(t,e,this.strides,o||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return s?Ln(r,s,this.dataFormat):r}recurrentConv(t,e){return so(t,e,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}}ap.className="ConvLSTM2DCell",_(ap);class Zb extends Kb{constructor(t){const e=new ap(t);super(Object.assign(Object.assign({},t),{cell:e}))}static fromConfig(t,e){return new t(e)}}Zb.className="ConvLSTM2D",_(Zb);/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */class cp extends Ct{constructor(t){super(t),this.rate=Math.max(Math.min(t.rate,1),0),this.noiseShape=t.noiseShape,this.seed=t.seed,this.supportsMasking=!0}getNoiseShape(t){if(this.noiseShape==null)return this.noiseShape;const e=t.shape,s=[];for(let o=0;o<this.noiseShape.length;++o)s.push(this.noiseShape[o]==null?e[o]:this.noiseShape[o]);return s}call(t,e){return M(()=>{this.invokeCallHook(t,e);const s=mt(t);if(0<this.rate&&this.rate<1){const o=e.training==null?!1:e.training,r=this.getNoiseShape(s);return Oi(()=>x0(s,this.rate,r,this.seed),()=>s,o)}return t})}getConfig(){const t={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},e=super.getConfig();return Object.assign(t,e),t}dispose(){return super.dispose()}}cp.className="Dropout",_(cp);class Bb extends cp{constructor(t){super(t),this.inputSpec=[{ndim:3}]}getNoiseShape(t){const e=t.shape;return[e[0],1,e[2]]}}Bb.className="SpatialDropout1D",_(Bb);class Hb extends Ct{constructor(t){if(super(t),this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",t.batchInputShape==null&&t.inputShape==null&&t.inputDim!=null){let e=null;t.batchSize!=null&&(e=t.batchSize),this.batchInputShape=[e,t.inputDim]}this.units=t.units,be(this.units,"units"),this.activation=Ls(t.activation),t.useBias!=null&&(this.useBias=t.useBias),this.kernelInitializer=Ht(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=Ht(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=he(t.kernelConstraint),this.biasConstraint=he(t.biasConstraint),this.kernelRegularizer=_t(t.kernelRegularizer),this.biasRegularizer=_t(t.biasRegularizer),this.activityRegularizer=_t(t.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(t){t=Nt(t);const e=t[t.length-1];this.kernel==null&&(this.kernel=this.addWeight("kernel",[e,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:e}}],this.built=!0}computeOutputShape(t){t=Nt(t);const e=t.slice();return e[e.length-1]=this.units,e}call(t,e){return M(()=>{this.invokeCallHook(t,e);const s=mt(t),o=l0(this.activation.getClassName());let r;return o!=null?r=_n(s,this.kernel.read(),o,this.bias?this.bias.read():null):(r=_n(s,this.kernel.read()),this.bias!=null&&(r=Ln(r,this.bias.read())),this.activation!=null&&(r=this.activation.apply(r))),r})}getConfig(){const t={units:this.units,activation:Gs(this.activation),useBias:this.useBias,kernelInitializer:Qt(this.kernelInitializer),biasInitializer:Qt(this.biasInitializer),kernelRegularizer:Vt(this.kernelRegularizer),biasRegularizer:Vt(this.biasRegularizer),activityRegularizer:Vt(this.activityRegularizer),kernelConstraint:de(this.kernelConstraint),biasConstraint:de(this.biasConstraint)},e=super.getConfig();return Object.assign(t,e),t}}Hb.className="Dense",_(Hb);class _b extends Ct{constructor(t){t=t||{},super(t),this.inputSpec=[{minNDim:3}],this.dataFormat=t.dataFormat}computeOutputShape(t){t=Nt(t);for(const e of t.slice(1))if(e==null)throw new $(`The shape of the input to "Flatten" is not fully defined (got ${t.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[t[0],Ns(t,1)]}call(t,e){return M(()=>{this.invokeCallHook(t,e);let s=mt(t);if(this.dataFormat==="channelsFirst"&&s.rank>1){const o=[0];for(let r=2;r<s.rank;++r)o.push(r);o.push(1),s=kt(s,o)}return qR(s)})}getConfig(){const t={};this.dataFormat!=null&&(t.dataFormat=this.dataFormat);const e=super.getConfig();return Object.assign(t,e),t}}_b.className="Flatten",_(_b);class Ub extends Ct{constructor(t){super(t),this.supportsMasking=!0,this.activation=Ls(t.activation)}call(t,e){return M(()=>{this.invokeCallHook(t,e);const s=mt(t);return this.activation.apply(s)})}getConfig(){const t={activation:Gs(this.activation)},e=super.getConfig();return Object.assign(t,e),t}}Ub.className="Activation",_(Ub);class Yb extends Ct{constructor(t){super(t),this.n=t.n,this.inputSpec=[{ndim:2}]}computeOutputShape(t){return[t[0],this.n,t[1]]}call(t,e){return M(()=>(t=mt(t),JR(t,this.n)))}getConfig(){const t={n:this.n},e=super.getConfig();return Object.assign(t,e),t}}Yb.className="RepeatVector",_(Yb);class Qb extends Ct{constructor(t){super(t),this.targetShape=t.targetShape;for(let e=0;e<this.targetShape.length;++e)this.isUnknown(this.targetShape[e])&&(this.targetShape[e]=null)}isUnknown(t){return t<0||t==null}fixUnknownDimension(t,e){const s="Total size of new array must be unchanged.",o=e.slice();let r=1,i=null;for(let c=0;c<o.length;++c){const l=o[c];if(this.isUnknown(l))if(i===null)i=c;else throw new $("Can only specifiy one unknown dimension.");else r*=l}const a=Ns(t);if(i!==null){if(r===0||a%r!==0)throw new $(s);o[i]=a/r}else if(a!==r)throw new $(s);return o}computeOutputShape(t){let e=!1;for(let s=0;s<t.length;++s)if(this.isUnknown(t[s])){e=!0;break}return e?t.slice(0,1).concat(this.targetShape):t.slice(0,1).concat(this.fixUnknownDimension(t.slice(1),this.targetShape))}call(t,e){return M(()=>{this.invokeCallHook(t,e);const s=mt(t),o=s.shape,r=o.slice(0,1).concat(this.fixUnknownDimension(o.slice(1),this.targetShape));return W(s,r)})}getConfig(){const t={targetShape:this.targetShape},e=super.getConfig();return Object.assign(t,e),t}}Qb.className="Reshape",_(Qb);class Jb extends Ct{constructor(t){if(super(t),t.dims==null)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(t.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${t.dims} instead.`);const e=$n(1,t.dims.length+1);if(!Rt(t.dims.slice().sort(),e))throw new Error("Invalid permutation `dims`: "+JSON.stringify(t.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=t.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new ue({ndim:this.dims.length+1})]}computeOutputShape(t){t=Nt(t);const e=t.slice();return this.dims.forEach((s,o)=>{e[o+1]=t[s]}),e}call(t,e){return kt(mt(t),this.dimsIncludingBatch)}getConfig(){const t={dims:this.dims},e=super.getConfig();return Object.assign(t,e),t}}Jb.className="Permute",_(Jb);class jb extends Ct{constructor(t){super(t??{}),this.supportsMasking=!0,t!=null?this.maskValue=t.maskValue==null?0:t.maskValue:this.maskValue=0}computeOutputShape(t){return t}getConfig(){const t=super.getConfig(),e={maskValue:this.maskValue};return Object.assign(e,t),e}computeMask(t,e){const s=mt(t);return ld(Mc(s,this.maskValue),-1)}call(t,e){return M(()=>{this.invokeCallHook(t,e);const s=mt(t),i=ld(Mc(s,this.maskValue),-1,!0);return E(s,st(i,s.dtype))})}}jb.className="Masking",_(jb);/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */class qb extends Ct{constructor(t){if(super(t),this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",t.batchInputShape==null&&t.inputShape==null){let e=null;t.batchSize!=null&&(e=t.batchSize),t.inputLength==null?this.batchInputShape=[e,null]:this.batchInputShape=[e].concat(Lt(t.inputLength))}this.inputDim=t.inputDim,be(this.inputDim,"inputDim"),this.outputDim=t.outputDim,be(this.outputDim,"outputDim"),this.embeddingsInitializer=Ht(t.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=_t(t.embeddingsRegularizer),this.activityRegularizer=_t(t.activityRegularizer),this.embeddingsConstraint=he(t.embeddingsConstraint),this.maskZero=t.maskZero,this.supportsMasking=t.maskZero,this.inputLength=t.inputLength}build(t){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0}warnOnIncompatibleInputShape(t){}computeMask(t,e){return M(()=>this.maskZero?(t=mt(t),Mc(t,St(t))):null)}computeOutputShape(t){if(t=Nt(t),this.inputLength==null)return[...t,this.outputDim];const e=Lt(this.inputLength);if(e.length!==t.length-1)throw new $(`"inputLength" is ${this.inputLength}, but received input shape has shape ${t}`);{let s=0;for(let o=0;o<e.length;++o){const r=e[o],i=t[o+1];if(r!=null&&i!=null&&r!==i)throw new $(`"inputLength" is ${this.inputLength}, but received input shape has shape ${t}`);r==null&&(e[s]=i),s++}}return[t[0],...e,this.outputDim]}call(t,e){return M(()=>{this.invokeCallHook(t,e);let s=mt(t);s.dtype!=="int32"&&(s=Hn(s,"int32"));const o=b0(this.embeddings.read(),W(s,[s.size]));return W(o,Nt(this.computeOutputShape(s.shape)))})}getConfig(){const t={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Qt(this.embeddingsInitializer),embeddingsRegularizer:Vt(this.embeddingsRegularizer),activityRegularizer:Vt(this.activityRegularizer),embeddingsConstraint:de(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},e=super.getConfig();return Object.assign(t,e),t}}qb.className="Embedding",_(qb);/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */class xo extends Ct{constructor(t){super(t||{}),this.supportsMasking=!0}mergeFunction(t){throw new bt}computeElementwiseOpOutputShape(t,e){if(t==null||e==null)return null;if(t.length<e.length)return this.computeElementwiseOpOutputShape(e,t);if(e.length===0)return t;const s=t.slice(0,t.length-e.length);for(let o=0;o<e.length;++o){const r=t[t.length-e.length+o],i=e[o];if(r==null||i==null||r<0||i<0)s.push(null);else if(r===1)s.push(i);else if(i===1)s.push(r);else{if(r!==i)throw new $("Operands could not be broadcast together with shapes "+JSON.stringify(t)+" "+JSON.stringify(e));s.push(r)}}return s}build(t){if(Array.isArray(t)&&!Array.isArray(t[0])&&(t=[Nt(t)]),t=t,t.length<2)throw new $(`A merge layer should be called on an Array of at least 2 inputs. Got ${t.length} input(s).`);let e=[];for(const r of t)r!=null&&r[0]!==null&&e.push(r[0]);if(e=Ts(e),e.length>1)throw new $(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(t)}.`);let s=t[0]==null?null:t[0].slice(1);for(let r=1;r<t.length;++r){const i=t[r]==null?null:t[r].slice(1);s=this.computeElementwiseOpOutputShape(s,i)}const o=t.map(r=>r.length);t.indexOf(null)===-1&&Ts(o).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(t,e){return M(()=>{if(t=t,this.reshapeRequired){const s=[],o=t.map(r=>r.rank);if(o.indexOf(null)===-1){const r=Rs(o);for(let i of t){const a=i.rank;for(let c=0;c<r-a;++c)i=Ai(i,1);s.push(i)}return this.mergeFunction(s)}else{let r=!1;for(const c of t){const l=c.rank;if(l==null){const u=c.shape,d=u[0],h=u.slice(1).concat([d]);let p=W(c,[d].concat(Ns(u.slice(1))));p=kt(p,[1,0]),p=W(p,h),s.push(p),r=!0}else if(l>1){const u=$n(1,l).concat([0]);s.push(kt(c,u)),r=!0}else s.push(c)}let i=this.mergeFunction(s);const a=i.rank;if(r){if(a==null){const c=i.shape,l=c.length,u=c[l-1],d=[u].concat(c.slice(0,c.length-1));i=W(kt(W(i,[-1,u]),[1,0]),d)}else if(a>1){const c=[a-1].concat($n(0,a-1));i=kt(i,c)}}return i}}else return this.mergeFunction(t)})}computeOutputShape(t){t=t;let e;t[0]==null?e=null:e=t[0].slice(1);for(let o=1;o<t.length;++o){const r=t[o]==null?null:t[o].slice(1);e=this.computeElementwiseOpOutputShape(e,r)}let s=[];for(const o of t)o!=null&&o[0]!==null&&s.push(o[0]);return s=Ts(s),s.length===1?e=s.concat(e):e=[null].concat(e),e}computeMask(t,e){return M(()=>{if(e==null)return null;if(!Array.isArray(e))throw new $("`mask` should be an Array");if(!Array.isArray(t))throw new $("`inputs` should be an Array");if(e.length!==t.length)throw new $(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${t.length} vs ${e.length})`);if(e.every(o=>o==null))return null;e=e.map(o=>o==null?o:Ae(o,0));let s=e[0];for(let o=1;o<e.length-1;++o)s=rs(s,e[o]);return s})}}class tx extends xo{constructor(t){super(t)}mergeFunction(t){return M(()=>{let e=t[0].clone();for(let s=1;s<t.length;++s)e=Q(e,t[s]);return e})}}tx.className="Add",_(tx);class ex extends xo{constructor(t){super(t)}mergeFunction(t){return M(()=>{let e=t[0].clone();for(let s=1;s<t.length;++s)e=E(e,t[s]);return e})}}ex.className="Multiply",_(ex);class nx extends xo{constructor(t){super(t)}mergeFunction(t){return M(()=>{let e=t[0].clone();for(let s=1;s<t.length;++s)e=Q(e,t[s]);return E(1/t.length,e)})}}nx.className="Average",_(nx);class sx extends xo{constructor(t){super(t)}mergeFunction(t){return M(()=>{let e=t[0];for(let s=1;s<t.length;++s)e=vs(e,t[s]);return e})}}sx.className="Maximum",_(sx);class ox extends xo{constructor(t){super(t)}mergeFunction(t){return M(()=>{let e=t[0];for(let s=1;s<t.length;++s)e=Gi(e,t[s]);return e})}}ox.className="Minimum",_(ox);class rx extends xo{constructor(t){super(t),this.DEFAULT_AXIS=-1,t==null&&(t={}),this.axis=t.axis==null?this.DEFAULT_AXIS:t.axis,this.supportsMasking=!0,this.reshapeRequired=!1}build(t){if(!(Array.isArray(t)&&Array.isArray(t[0]))||t.length===1)throw new $("A `Concatenate` layer should be called on a list of at least 2 inputs");t=t;let e=!0;for(const o of t)if(o!=null){e=!1;break}if(e)return;const s=[];for(let o=0;o<t.length;++o){const r=t[o].slice();r.splice(this.axis,1);let i=!1;for(const a of s)if(Rt(a,r)){i=!0;break}i||s.push(r)}if(s.length>1)throw new $("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(t))}mergeFunction(t){return M(()=>Lh(t,this.axis))}computeOutputShape(t){if(!(Array.isArray(t)&&Array.isArray(t[0])))throw new $("A `Concatenate` layer should be called on a list of inputs.");const e=t,s=e[0].slice(),o=this.axis<0?s.length+this.axis:this.axis;for(const r of e.slice(1)){if(s[o]==null||r[o]==null){s[o]=null;break}s[o]+=r[o]}return s}computeMask(t,e){if(e==null)return null;if(!Array.isArray(e))throw new $("`mask` should be an array for Concatenate");if(!Array.isArray(t))throw new $("`inputs` should be an array for Concatenate");if(e.length!==t.length)throw new $(`Mismatch in the length of mask (${e.length}) and the legnth of inputs (${t.length})`);return M(()=>{let s=!0;if(e.forEach(i=>{if(i!=null){s=!1;return}}),s)return null;const o=[];for(let i=0;i<t.length;++i)e[i]==null?o.push(st(fn(t[i]),"bool")):e[i].rank<t[i].rank?o.push(Ae(e[i],-1)):o.push(e[i]);const r=Xe(o,this.axis);return Gm(r,-1,!1)})}getConfig(){const t={axis:this.axis},e=super.getConfig();return Object.assign(t,e),t}}rx.className="Concatenate",_(rx);function ji(n,t){for(;n<0;)n+=t;return n}function yG(n,t,e){if(n.shape.length>3||t.shape.length>3)throw new bt("batchDot is not implemented for tensors of 4D or higher rank yet");if(v(n.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${n.shape.length}`),v(n.shape.length>=2,()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`),typeof e=="number"&&(e=[e,e]),n.dtype==="complex64"||t.dtype==="complex64")throw new bt("batchDot is not implemented for complex64-type Tensors yet.");const s=n.shape.length,o=t.shape.length;e==null&&(e=[s-1,o-2]);const r=e;return M(()=>{let i;if(s>o){i=s-o;const c=[];for(let l=0;l<i;++l)c.push(1);t=W(t,t.shape.concat(c))}else if(o>s){i=o-s;const c=[];for(let l=0;l<i;++l)c.push(1);n=W(n,n.shape.concat(c))}else i=0;let a;if(n.shape.length===2&&t.shape.length===2)r[0]===r[1]?a=ut(E(n,t),r[0]):a=ut(E(kt(n,[1,0]),t),r[1]);else{const c=r[0]!==n.shape.length-1,l=r[1]===t.shape.length-1;a=$t(n,t,c,l)}if(i>0){let c;s>o?c=s+o-3:c=s-1;const l=[];for(let u=c;u<c+i;++u)l.push(u);a=Di(a,l)}return a.shape.length===1&&(a=Ae(a,1)),a})}class ix extends xo{constructor(t){super(t),this.axes=t.axes,this.normalize=t.normalize==null?!1:t.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(t){v(Array.isArray(t)&&t.length===2&&Array.isArray(t[0])&&Array.isArray(t[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");const e=t[0],s=t[1];if(e.length>3||s.length>3)throw new bt("Dot layer does not support tensors of 4D or higher rank yet.");const o=this.interpretAxes(e,s);if(e[o[0]]!==s[o[1]])throw new $(`Dimension incompatibility: ${e[o[0]]} !== ${s[o[1]]}`)}mergeFunction(t){if(t.length!==2)throw new $(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${t.length} input(s).`);let e=t[0],s=t[1],o;return Array.isArray(this.axes)?o=this.axes.map((r,i)=>ji(r,t[i].shape.length)):o=[ji(this.axes,e.shape.length),ji(this.axes,s.shape.length)],this.normalize&&(e=qc(e,o[0]),s=qc(s,o[1])),yG(e,s,o)}interpretAxes(t,e){let s;return Array.isArray(this.axes)?s=this.axes:s=[ji(this.axes,t.length),ji(this.axes,e.length)],s}computeOutputShape(t){v(Array.isArray(t)&&t.length===2&&Array.isArray(t[0])&&Array.isArray(t[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");const e=t[0].slice(),s=t[1].slice();if(e.length>3||s.length>3)throw new bt("Dot layer does not support tensors of 4D or higher rank yet.");const o=this.interpretAxes(e,s);e.splice(o[0],1),s.splice(o[1],1),s.splice(0,1);const r=e.concat(s);return r.length===1&&r.push(1),r}computeMask(t,e){return null}getConfig(){const t={axes:this.axes,normalize:this.normalize},e=super.getConfig();return Object.assign(t,e),t}}ix.className="Dot",_(ix);/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */class ax extends Ct{constructor(t){super(t),this.supportsMasking=!0,this.stddev=t.stddev}computeOutputShape(t){return t}getConfig(){const t=super.getConfig(),e={stddev:this.stddev};return Object.assign(e,t),e}call(t,e){return M(()=>{this.invokeCallHook(t,e);const s=mt(t);return Oi(()=>Q(_c(s.shape,0,this.stddev),s),()=>s,e.training||!1)})}}ax.className="GaussianNoise",_(ax);class cx extends Ct{constructor(t){super(t),this.supportsMasking=!0,this.rate=t.rate}computeOutputShape(t){return t}getConfig(){const t=super.getConfig(),e={rate:this.rate};return Object.assign(e,t),e}call(t,e){return M(()=>{this.invokeCallHook(t,e);const s=mt(t);return this.rate>0&&this.rate<1?Oi(()=>{const r=Math.sqrt(this.rate/(1-this.rate));return E(s,_c(s.shape,1,r))},()=>s,e.training||!1):s})}}cx.className="GaussianDropout",_(cx);class lx extends Ct{constructor(t){super(t),this.supportsMasking=!0,this.rate=t.rate,this.noiseShape=t.noiseShape}_getNoiseShape(t){return this.noiseShape||mt(t).shape}computeOutputShape(t){return t}getConfig(){const t=super.getConfig(),e={rate:this.rate};return Object.assign(e,t),e}call(t,e){return M(()=>{if(this.rate<1&&this.rate>0){const s=this._getNoiseShape(t);return Oi(()=>{const r=mt(t),c=-1.6732632423543772*1.0507009873554805;let l=oo(Li(s),this.rate);l=Hn(l,"float32");const u=((1-this.rate)*(1+this.rate*c**2))**-.5,d=-u*c*this.rate,h=Q(E(r,l),E(Q(l,-1),c));return Q(E(h,u),d)},()=>mt(t),e.training||!1)}return t})}}lx.className="AlphaDropout",_(lx);/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function qi(n,t,e,s,o,r=.001){let i;if(n.rank===2)i=jC(n,t,e,s,o,r);else if(n.rank===3)i=t2(n,t,e,s,o,r);else if(n.rank===4)i=n2(n,t,e,s,o,r);else throw new bt(`batchNormalization is not implemented for array of rank ${n.rank} yet`);return i}function IG(n,t,e,s,o=.001){return M(()=>{const r=kd(n,s),i=r.mean,a=r.variance;return[qi(n,i,a,e,t,o),i,a]})}function wG(n,t,e,s,o=.001){return M(()=>{const r=kd(n,s),i=r.mean,a=r.variance,c=[];for(const f of $n(0,n.rank))s.indexOf(f)!==-1?c.push(1):c.push(n.shape[f]);const l=W(i,c),u=W(a,c),d=t==null?null:W(t,c),h=e==null?null:W(e,c);return[qi(n,l,u,h,d,o),i,a]})}function CG(n,t,e,s,o=.001){return Rt(s.slice().sort(),$n(0,n.rank-1))?IG(n,t,e,s,o):wG(n,t,e,s,o)}class ux extends Ct{constructor(t){t==null&&(t={}),super(t),this.supportsMasking=!0,this.axis=t.axis==null?-1:t.axis,this.momentum=t.momentum==null?.99:t.momentum,this.epsilon=t.epsilon==null?.001:t.epsilon,this.center=t.center==null?!0:t.center,this.scale=t.scale==null?!0:t.scale,this.betaInitializer=Ht(t.betaInitializer||"zeros"),this.gammaInitializer=Ht(t.gammaInitializer||"ones"),this.movingMeanInitializer=Ht(t.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=Ht(t.movingVarianceInitializer||"ones"),this.betaConstraint=he(t.betaConstraint),this.gammaConstraint=he(t.gammaConstraint),this.betaRegularizer=_t(t.betaRegularizer),this.gammaRegularizer=_t(t.gammaRegularizer)}build(t){t=Nt(t);const e=this.axis>=0?this.axis:this.axis+t.length,s=t[e];if(s==null)throw new $(`Axis ${e} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(t)}.`);this.inputSpec=[new ue({ndim:t.length,axes:{[e]:s}})];const o=[s];this.scale&&(this.gamma=this.addWeight("gamma",o,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",o,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",o,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",o,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(t,e){return M(()=>{const s=e.training==null?!1:e.training,o=mt(t),r=o.shape,i=r.length,a=$n(0,i),c=this.axis>=0?this.axis:this.axis+i;a.splice(c,1);const l=ho(1,i);l[c]=r[c];const u=a.slice();u.sort();const d=!Rt(u,$n(0,i).slice(0,i-1)),h=()=>{if(d){const x=W(this.movingMean.read(),l),I=W(this.movingVariance.read(),l),y=this.center?W(this.beta.read(),l):null,w=this.scale?W(this.gamma.read(),l):null;return qi(o,x,I,y,w,this.epsilon)}else return qi(o,this.movingMean.read(),this.movingVariance.read(),this.beta==null?null:this.beta.read(),this.gamma==null?null:this.gamma.read(),this.epsilon)};if(!s)return h();const[p,f,m]=CG(o,this.gamma.read(),this.beta.read(),a,this.epsilon),g=(x,I,y)=>{M(()=>{const w=1-y,C=x.read(),k=E(pt(C,I),w);x.write(pt(C,k))})};return(()=>{g(this.movingMean,f,this.momentum),g(this.movingVariance,m,this.momentum)})(),p})}getConfig(){const t={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Qt(this.betaInitializer),gammaInitializer:Qt(this.gammaInitializer),movingMeanInitializer:Qt(this.movingMeanInitializer),movingVarianceInitializer:Qt(this.movingVarianceInitializer),betaRegularizer:Vt(this.betaRegularizer),gammaRegularizer:Vt(this.gammaRegularizer),betaConstraint:de(this.betaConstraint),gammaConstraint:de(this.gammaConstraint)},e=super.getConfig();return Object.assign(t,e),t}}ux.className="BatchNormalization",_(ux);class dx extends Ct{constructor(t){if(t==null&&(t={}),super(t),this.axis=t.axis==null?-1:t.axis,typeof this.axis=="number"){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else if(Array.isArray(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)}`)}else throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);this.epsilon=t.epsilon==null?.001:t.epsilon,this.center=t.center==null?!0:t.center,this.scale=t.scale==null?!0:t.scale,this.betaInitializer=Ht(t.betaInitializer||"zeros"),this.gammaInitializer=Ht(t.gammaInitializer||"ones"),this.betaRegularizer=_t(t.betaRegularizer),this.gammaRegularizer=_t(t.gammaRegularizer),this.supportsMasking=!0}build(t){t=Nt(t);const e=t.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let r=0;r<this.axis.length;++r)this.axis[r]<0&&(this.axis[r]+=e);for(const r of this.axis)if(r<0||r>=e)throw new Error(`Invalid axis: ${r}`);if(this.axis.length!==Ts(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);const s=this.axis.map(r=>t[r]),o=!0;this.scale?this.gamma=this.addWeight("gamma",s,"float32",this.gammaInitializer,this.gammaRegularizer,o):this.gamma=null,this.center?this.beta=this.addWeight("beta",s,"float32",this.betaInitializer,this.betaRegularizer,o):this.beta=null,this.built=!0}call(t,e){const s=mt(t),o=s.shape,r=o.length;return M(()=>{let{mean:a,variance:c}=kd(s,this.axis,!0);const l=ho(1,r);for(const m of this.axis)l[m]=o[m];const u=m=>m!=null&&m.shape.length!==r?W(m,l):m;let d=this.scale?u(this.gamma.read()):null,h=this.center?u(this.beta.read()):null;const p=[],f=[];for(let m=0;m<r;++m)this.axis.indexOf(m)!==-1?(p.push(o[m]),f.push(1)):(p.push(1),f.push(o[m]));return a=Nn(a,p),c=Nn(c,p),d!=null&&(d=Nn(d,f)),h!=null&&(h=Nn(h,f)),qi(s,a,c,h,d,this.epsilon)})}getConfig(){const t={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Qt(this.betaInitializer),gammaInitializer:Qt(this.gammaInitializer),betaRegularizer:Vt(this.betaRegularizer),gammaRegularizer:Vt(this.gammaRegularizer)},e=super.getConfig();return Object.assign(t,e),t}}dx.className="LayerNormalization",_(dx);/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function vG(n,t,e){return M(()=>{if(n.rank!==4)throw new $(`temporalPadding expects input tensor to be 4-D, but received a ${n.rank}-D tensor.`);if(t==null&&(t=[[1,1],[1,1]]),t.length!==2||t[0].length!==2||t[1].length!==2)throw new $("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(e==null&&(e=Gn()),e!=="channelsLast"&&e!=="channelsFirst")throw new $(`Unknown data format: ${e}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let s;return e==="channelsFirst"?s=[[0,0],[0,0],t[0],t[1]]:s=[[0,0],t[0],t[1],[0,0]],Td(n,s)})}class hx extends Ct{constructor(t){if(t==null&&(t={}),super(t),this.dataFormat=t.dataFormat==null?Gn():t.dataFormat,t.padding==null)this.padding=[[1,1],[1,1]];else if(typeof t.padding=="number")this.padding=[[t.padding,t.padding],[t.padding,t.padding]];else{if(t.padding=t.padding,t.padding.length!==2)throw new $(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${t.padding.length} array.`);let e,s;if(typeof t.padding[0]=="number")e=[t.padding[0],t.padding[0]],s=[t.padding[1],t.padding[1]];else{if(t.padding=t.padding,t.padding[0].length!==2)throw new $(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${t.padding[0].length} array.`);if(e=t.padding[0],t.padding[1].length!==2)throw new $(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${t.padding[1].length} array.`);s=t.padding[1]}this.padding=[e,s]}this.inputSpec=[new ue({ndim:4})]}computeOutputShape(t){t=Nt(t);let e,s;return this.dataFormat==="channelsFirst"?(t[2]!=null&&t[2]>=0?e=t[2]+this.padding[0][0]+this.padding[0][1]:e=null,t[3]!=null&&t[3]>=0?s=t[3]+this.padding[1][0]+this.padding[1][1]:s=null,[t[0],t[1],e,s]):(t[1]!=null&&t[1]>=0?e=t[1]+this.padding[0][0]+this.padding[0][1]:e=null,t[2]!=null&&t[2]>=0?s=t[2]+this.padding[1][0]+this.padding[1][1]:s=null,[t[0],e,s,t[3]])}call(t,e){return M(()=>vG(mt(t),this.padding,this.dataFormat))}getConfig(){const t={padding:this.padding,dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}}hx.className="ZeroPadding2D",_(hx);/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function dl(n,t,e,s,o,r){return M(()=>{se(o),d0(r),rn(s),e==null&&(e=[1,1]),s==null&&(s="valid"),o==null&&(o=Gn()),r==null&&(r="max"),n=sp(n,o);let i;const a=s==="same"?"same":"valid";return r==="max"?i=Sd(n,t,e,a):i=hd(n,t,e,a),o==="channelsFirst"&&(i=kt(i,[0,3,1,2])),i})}function px(n,t,e,s,o,r){return M(()=>{se(o),d0(r),rn(s),e==null&&(e=[1,1,1]),s==null&&(s="valid"),o==null&&(o=Gn()),r==null&&(r="max"),n=$b(n,o);let i;const a=s==="same"?"same":"valid";return r==="max"?i=Pv(n,t,e,a):i=OC(n,t,e,a),o==="channelsFirst"&&(i=kt(i,[0,4,1,2,3])),i})}class fx extends Ct{constructor(t){if(t.poolSize==null&&(t.poolSize=2),super(t),typeof t.poolSize=="number")this.poolSize=[t.poolSize];else if(Array.isArray(t.poolSize)&&t.poolSize.length===1&&typeof t.poolSize[0]=="number")this.poolSize=t.poolSize;else throw new $(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(t.poolSize)}`);if(be(this.poolSize,"poolSize"),t.strides==null)this.strides=this.poolSize;else if(typeof t.strides=="number")this.strides=[t.strides];else if(Array.isArray(t.strides)&&t.strides.length===1&&typeof t.strides[0]=="number")this.strides=t.strides;else throw new $(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(t.strides)}`);be(this.strides,"strides"),this.padding=t.padding==null?"valid":t.padding,rn(this.padding),this.inputSpec=[new ue({ndim:3})]}computeOutputShape(t){t=Nt(t);const e=Wn(t[1],this.poolSize[0],this.padding,this.strides[0]);return[t[0],e,t[2]]}call(t,e){return M(()=>{this.invokeCallHook(t,e),t=Ai(mt(t),2);const s=this.poolingFunction(mt(t),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Di(s,[2])})}getConfig(){const t={poolSize:this.poolSize,padding:this.padding,strides:this.strides},e=super.getConfig();return Object.assign(t,e),t}}class mx extends fx{constructor(t){super(t)}poolingFunction(t,e,s,o,r){return se(r),rn(o),dl(t,e,s,o,r,"max")}}mx.className="MaxPooling1D",_(mx);class gx extends fx{constructor(t){super(t)}poolingFunction(t,e,s,o,r){return se(r),rn(o),dl(t,e,s,o,r,"avg")}}gx.className="AveragePooling1D",_(gx);class bx extends Ct{constructor(t){if(t.poolSize==null&&(t.poolSize=[2,2]),super(t),this.poolSize=Array.isArray(t.poolSize)?t.poolSize:[t.poolSize,t.poolSize],t.strides==null)this.strides=this.poolSize;else if(Array.isArray(t.strides)){if(t.strides.length!==2)throw new $(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${t.strides.length}.`);this.strides=t.strides}else this.strides=[t.strides,t.strides];be(this.poolSize,"poolSize"),be(this.strides,"strides"),this.padding=t.padding==null?"valid":t.padding,this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,se(this.dataFormat),rn(this.padding),this.inputSpec=[new ue({ndim:4})]}computeOutputShape(t){t=Nt(t);let e=this.dataFormat==="channelsFirst"?t[2]:t[1],s=this.dataFormat==="channelsFirst"?t[3]:t[2];return e=Wn(e,this.poolSize[0],this.padding,this.strides[0]),s=Wn(s,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[t[0],t[1],e,s]:[t[0],e,s,t[3]]}call(t,e){return M(()=>(this.invokeCallHook(t,e),this.poolingFunction(mt(t),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){const t={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}}class xx extends bx{constructor(t){super(t)}poolingFunction(t,e,s,o,r){return se(r),rn(o),dl(t,e,s,o,r,"max")}}xx.className="MaxPooling2D",_(xx);class yx extends bx{constructor(t){super(t)}poolingFunction(t,e,s,o,r){return se(r),rn(o),dl(t,e,s,o,r,"avg")}}yx.className="AveragePooling2D",_(yx);class Ix extends Ct{constructor(t){if(t.poolSize==null&&(t.poolSize=[2,2,2]),super(t),this.poolSize=Array.isArray(t.poolSize)?t.poolSize:[t.poolSize,t.poolSize,t.poolSize],t.strides==null)this.strides=this.poolSize;else if(Array.isArray(t.strides)){if(t.strides.length!==3)throw new $(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${t.strides.length}.`);this.strides=t.strides}else this.strides=[t.strides,t.strides,t.strides];be(this.poolSize,"poolSize"),be(this.strides,"strides"),this.padding=t.padding==null?"valid":t.padding,this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,se(this.dataFormat),rn(this.padding),this.inputSpec=[new ue({ndim:5})]}computeOutputShape(t){t=Nt(t);let e=this.dataFormat==="channelsFirst"?t[2]:t[1],s=this.dataFormat==="channelsFirst"?t[3]:t[2],o=this.dataFormat==="channelsFirst"?t[4]:t[3];return e=Wn(e,this.poolSize[0],this.padding,this.strides[0]),s=Wn(s,this.poolSize[1],this.padding,this.strides[1]),o=Wn(o,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[t[0],t[1],e,s,o]:[t[0],e,s,o,t[4]]}call(t,e){return M(()=>(this.invokeCallHook(t,e),this.poolingFunction(mt(t),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){const t={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}}class wx extends Ix{constructor(t){super(t)}poolingFunction(t,e,s,o,r){return se(r),rn(o),px(t,e,s,o,r,"max")}}wx.className="MaxPooling3D",_(wx);class Cx extends Ix{constructor(t){super(t)}poolingFunction(t,e,s,o,r){return se(r),rn(o),px(t,e,s,o,r,"avg")}}Cx.className="AveragePooling3D",_(Cx);class vx extends Ct{constructor(t){super(t),this.inputSpec=[new ue({ndim:3})]}computeOutputShape(t){return[t[0],t[2]]}call(t,e){throw new bt}}class Sx extends vx{constructor(t){super(t||{})}call(t,e){return M(()=>{const s=mt(t);return ie(s,1)})}}Sx.className="GlobalAveragePooling1D",_(Sx);class kx extends vx{constructor(t){super(t||{})}call(t,e){return M(()=>{const s=mt(t);return Tn(s,1)})}}kx.className="GlobalMaxPooling1D",_(kx);class Tx extends Ct{constructor(t){super(t),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,se(this.dataFormat),this.inputSpec=[new ue({ndim:4})]}computeOutputShape(t){return t=t,this.dataFormat==="channelsLast"?[t[0],t[3]]:[t[0],t[1]]}call(t,e){throw new bt}getConfig(){const t={dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}}class Nx extends Tx{call(t,e){return M(()=>{const s=mt(t);return this.dataFormat==="channelsLast"?ie(s,[1,2]):ie(s,[2,3])})}}Nx.className="GlobalAveragePooling2D",_(Nx);class Rx extends Tx{call(t,e){return M(()=>{const s=mt(t);return this.dataFormat==="channelsLast"?Tn(s,[1,2]):Tn(s,[2,3])})}}Rx.className="GlobalMaxPooling2D",_(Rx);/**
 * @license
 * Copyright 2018 Google LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */class $x extends Ct{constructor(t){super(t),this.layer=t.layer}build(t){this.built=!0}get trainable(){return this.layer!=null?this.layer.trainable:!1}set trainable(t){this.layer!=null&&(this.layer.trainable=t)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(t){this.layer.setWeights(t)}getConfig(){const t={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},e=super.getConfig();return Object.assign(t,e),t}setFastWeightInitDuringBuild(t){super.setFastWeightInitDuringBuild(t),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(t)}static fromConfig(t,e,s={}){const o=e.layer,r=us(o,s);delete e.layer;const i={layer:r};return Object.assign(i,e),new t(i)}}class Gx extends $x{constructor(t){super(t),this.supportsMasking=!0}build(t){if(t=Nt(t),t.length<3)throw new $(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(t)}`);this.inputSpec=[{shape:t}];const e=[t[0]].concat(t.slice(2));this.layer.built||(this.layer.build(e),this.layer.built=!0),super.build(t)}computeOutputShape(t){t=Nt(t);const e=[t[0]].concat(t.slice(2)),s=this.layer.computeOutputShape(e),o=t[1];return[s[0],o].concat(s.slice(1))}call(t,e){return M(()=>(t=mt(t),Xb((i,a)=>[mt(this.layer.call(i,e)),[]],t,[],!1,null,null,!1,!0)[1]))}}Gx.className="TimeDistributed",_(Gx);function SG(n){fo(HR,"BidirectionalMergeMode",n)}const kG="concat";class Lx extends $x{constructor(t){super(t);const e=t.layer.getConfig(),s={};s.className=t.layer.getClassName(),s.config=e,this.forwardLayer=us(s),e.goBackwards=e.goBackwards!==!0;const o={};if(o.className=t.layer.getClassName(),o.config=e,this.backwardLayer=us(o),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=t.mergeMode===void 0?kG:t.mergeMode,SG(this.mergeMode),t.weights)throw new bt("weights support is not implemented for Bidirectional layer yet.");this._stateful=t.layer.stateful,this.returnSequences=t.layer.returnSequences,this.returnState=t.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=t.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(t){this._trainable=t,this.forwardLayer!=null&&(this.forwardLayer.trainable=t),this.backwardLayer!=null&&(this.backwardLayer.trainable=t)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(t){const e=t.length,s=Math.floor(e/2);this.forwardLayer.setWeights(t.slice(0,s)),this.backwardLayer.setWeights(t.slice(s))}computeOutputShape(t){let e=this.forwardLayer.computeOutputShape(t);Array.isArray(e)&&Array.isArray(e[0])||(e=[e]),e=e;let s,o,r;return this.returnState&&(r=e.slice(1)),s=e[0],s=s,this.mergeMode==="concat"?(s[s.length-1]*=2,o=[s]):this.mergeMode==null?o=[s,s.slice()]:o=[s],this.returnState?this.mergeMode==null?o.concat(r).concat(r.slice()):[s].concat(r).concat(r.slice()):Pe(o)}apply(t,e){let s=e==null?null:e.initialState,o=e==null?null:e.constants;e==null&&(e={});const r=zb(t,s,o,this.numConstants);if(t=r.inputs,s=r.initialState,o=r.constants,Array.isArray(t)&&(s=t.slice(1),t=t[0]),(s==null||s.length===0)&&o==null)return super.apply(t,e);const i=[],a=[];if(s!=null){const l=s.length;if(l%2>0)throw new $("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");e.initialState=s,i.push(...s);const u=s.map(d=>new ue({shape:d.shape}));this.forwardLayer.stateSpec=u.slice(0,l/2),this.backwardLayer.stateSpec=u.slice(l/2),a.push(...u)}if(o!=null)throw new bt("Support for constants in Bidirectional layers is not implemented yet.");const c=i[0]instanceof Un;for(const l of i)if(l instanceof Un!==c)throw new $("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(c){const l=[t].concat(i),u=this.inputSpec.concat(a),d=this.inputSpec;this.inputSpec=u;const h=super.apply(l,e);return this.inputSpec=d,h}else return super.apply(t,e)}call(t,e){return M(()=>{const s=e.initialState;let o,r;if(s==null)o=this.forwardLayer.call(t,e),r=this.backwardLayer.call(t,e);else{const c=s.slice(0,s.length/2),l=s.slice(s.length/2);o=this.forwardLayer.call(t,Object.assign(e,{initialState:c})),r=this.backwardLayer.call(t,Object.assign(e,{initialState:l}))}let i;this.returnState&&(Array.isArray(o)&&(i=o.slice(1).concat(r.slice(1))),o=o[0],r=r[0]),this.returnSequences&&(r=ao(r,1));let a;return this.mergeMode==="concat"?a=Lh([o,r]):this.mergeMode==="sum"?a=Q(o,r):this.mergeMode==="ave"?a=E(.5,Q(o,r)):this.mergeMode==="mul"?a=E(o,r):this.mergeMode==null&&(a=[o,r]),this.returnState?this.mergeMode==null?a.concat(i):[a].concat(i):a})}resetStates(t){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(t){mo(this.forwardLayer.name,()=>{this.forwardLayer.build(t)}),mo(this.backwardLayer.name,()=>{this.backwardLayer.build(t)}),this.built=!0}computeMask(t,e){Array.isArray(e)&&(e=e[0]);let s;if(this.returnSequences?this.mergeMode==null?s=[e,e]:s=e:this.mergeMode==null?s=[null,null]:s=null,this.returnState){const r=this.forwardLayer.states.map(i=>null);return Array.isArray(s)?s.concat(r).concat(r):[s].concat(r).concat(r)}else return s}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(t){super.setFastWeightInitDuringBuild(t),this.forwardLayer!=null&&this.forwardLayer.setFastWeightInitDuringBuild(t),this.backwardLayer!=null&&this.backwardLayer.setFastWeightInitDuringBuild(t)}getConfig(){const t={mergeMode:this.mergeMode},e=super.getConfig();return Object.assign(t,e),t}static fromConfig(t,e){const s=us(e.layer);if(delete e.layer,e.numConstants!=null)throw new bt("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const o=e;return o.layer=s,new t(o)}}Lx.className="Bidirectional",_(Lx);/**
 * @license
 * Copyright 2022 CodeSmith LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */class Ex extends Ct{constructor(t){super(t),this.scale=t.scale,t.offset?this.offset=t.offset:this.offset=0}getConfig(){const t={scale:this.scale,offset:this.offset},e=super.getConfig();return Object.assign(t,e),t}call(t,e){return M(()=>(t=mt(t),t.dtype!=="float32"&&(t=Hn(t,"float32")),Q(E(t,this.scale),this.offset)))}}Ex.className="Rescaling",_(Ex);/**
 * @license
 * Copyright 2022 CodeSmith LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */const{resizeBilinear:TG,cropAndResize:NG}=is;class Dx extends Ct{constructor(t){super(t),this.height=t.height,this.width=t.width}centerCrop(t,e,s,o,r,i,a,c){return M(()=>{let l,u=!1;const d=e/i,h=s/a,p=(o+e)/i,f=(r+s)/a,m=[d,h,p,f],g=[];t.rank===3?(u=!0,l=On([t])):l=t;for(let w=0;w<l.shape[0];w++)g.push(m);const b=tn(g,[g.length,4]),x=Ei(0,g.length,1,"int32"),y=NG(l,b,x,[o,r],"nearest");return Hn(u?mt(lo(y)):y,c)})}upsize(t,e,s,o){return M(()=>{const r=TG(t,[e,s]);return Hn(r,o)})}call(t,e){return M(()=>{const s=mt(t),o=s.dtype,r=s.shape,i=r[r.length-3],a=r[r.length-2];let c=0;i!==this.height&&(c=Math.floor((i-this.height)/2));let l=0;return a!==this.width&&(l=Math.floor((a-this.width)/2),l===0&&(l=1)),c>=0&&l>=0?this.centerCrop(s,c,l,this.height,this.width,i,a,o):this.upsize(t,this.height,this.width,o)})}getConfig(){const t={height:this.height,width:this.width},e=super.getConfig();return Object.assign(t,e),t}computeOutputShape(t){t=Nt(t);const e=t.length-3,s=t.length-2;return t[e]=this.height,t[s]=this.width,t}}Dx.className="CenterCrop",_(Dx);/**
 * @license
 * Copyright 2022 CodeSmith LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */function RG(n,t,e,s){let o=mt(n);if(o.dtype!=="int32"&&(o=Hn(o,"int32")),t==="int")return o;const r=o.shape;if(o.rank===0&&(o=Ae(o,-1)),t==="oneHot"&&o.shape[o.shape.length-1]!==1&&(o=Ae(o,-1)),o.rank>2)throw new $(`When outputMode is not int, maximum output rank is 2 Received outputMode ${t} and input shape ${r} which would result in output rank ${o.rank}.`);const i=["multiHot","oneHot"].includes(t),a=o;let c;if(typeof s<"u"&&t==="count"?c=Vm(a,s,e,i):c=Vm(a,[],e,i),t!=="tfIdf")return c;if(s)return E(c,s);throw new $("When outputMode is 'tfIdf', weights must be provided.")}/**
 * @license
 * Copyright 2022 CodeSmith LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */class Wx extends Ct{constructor(t){super(t),this.numTokens=t.numTokens,t.outputMode?this.outputMode=t.outputMode:this.outputMode="multiHot"}getConfig(){const t={numTokens:this.numTokens,outputMode:this.outputMode},e=super.getConfig();return Object.assign(t,e),t}computeOutputShape(t){return t=Nt(t),t==null?[this.numTokens]:this.outputMode==="oneHot"&&t[t.length-1]!==1?(t.push(this.numTokens),t):(t[t.length-1]=this.numTokens,t)}call(t,e){return M(()=>{t=mt(t),t.dtype!=="int32"&&(t=Hn(t,"int32"));let s;if(typeof e.countWeights<"u"){if(this.outputMode!=="count")throw new $(`countWeights is not used when outputMode !== count.
              Received countWeights=${e.countWeights}`);s=mt(e.countWeights)}const o=Tn(t),r=Lc(t),i=sn(this.numTokens,o).bufferSync().get(0),a=oo(r,0).bufferSync().get(0);if(!(i&&a))throw new $(`Input values must be between 0 < values <= numTokens with numTokens=${this.numTokens}`);return RG(t,this.outputMode,this.numTokens,s)})}}Wx.className="CategoryEncoding",_(Wx);/**
 * @license
 * Copyright 2022 CodeSmith LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */const $G=["bilinear","nearest"],Mx=new Set($G);class Vx extends Ct{constructor(t){if(super(t),this.height=t.height,this.width=t.width,t.interpolation)if(Mx.has(t.interpolation))this.interpolation=t.interpolation;else throw new $(`Invalid interpolation parameter: ${t.interpolation} is not implemented`);else this.interpolation="bilinear";this.cropToAspectRatio=!!t.cropToAspectRatio}computeOutputShape(t){t=Nt(t);const e=t[2];return[this.height,this.width,e]}getConfig(){const t={height:this.height,width:this.width,interpolation:this.interpolation,cropToAspectRatio:this.cropToAspectRatio},e=super.getConfig();return Object.assign(t,e),t}call(t,e){return M(()=>{const s=[this.height,this.width];if(this.interpolation==="bilinear")return is.resizeBilinear(t,s,!this.cropToAspectRatio);if(this.interpolation==="nearest")return is.resizeNearestNeighbor(t,s,!this.cropToAspectRatio);throw new Error(`Interpolation is ${this.interpolation} but only ${[...Mx]} are supported`)})}}Vx.className="Resizing",_(Vx);/**
 * @license
 * Copyright 2023 CodeSmith LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */class Fx{constructor(t){this.seed=t}next(){if(this.seed!==void 0)return this.seed++}}Fx.className="RandomSeed";/**
 * @license
 * Copyright 2023 CodeSmith LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */class zx extends Ct{constructor(t){super(t),this.randomGenerator=new Fx(t.seed)}getConfig(){const t={seed:this.randomGenerator.seed},e=super.getConfig();return Object.assign(t,e),t}}zx.className="BaseRandomLayer";/**
 * @license
 * Copyright 2023 CodeSmith LLC
 *
 * Use of this source code is governed by an MIT-style
 * license that can be found in the LICENSE file or at
 * https://opensource.org/licenses/MIT.
 * =============================================================================
 */const GG=["bilinear","nearest"],Xx=new Set(GG);class Ax extends zx{constructor(t){super(t);const{factor:e,interpolation:s="bilinear"}=t;if(this.factor=e,Array.isArray(this.factor)&&this.factor.length===2)this.widthLower=this.factor[0],this.widthUpper=this.factor[1];else if(!Array.isArray(this.factor)&&this.factor>0)this.widthLower=-this.factor,this.widthUpper=this.factor;else throw new $(`Invalid factor: ${this.factor}. Must be positive number or tuple of 2 numbers`);if(this.widthLower<-1||this.widthUpper<-1)throw new $(`factor must have values larger than -1. Got: ${this.factor}`);if(this.widthUpper<this.widthLower)throw new $(`factor cannot have upper bound less than lower bound.
        Got upper bound: ${this.widthUpper}.
        Got lower bound: ${this.widthLower}
      `);if(s)if(Xx.has(s))this.interpolation=s;else throw new $(`Invalid interpolation parameter: ${s} is not implemented`)}getConfig(){const t={factor:this.factor,interpolation:this.interpolation},e=super.getConfig();return Object.assign(t,e),t}computeOutputShape(t){t=Nt(t);const e=t[2];return[this.imgHeight,-1,e]}call(t,e){return M(()=>{const s=mt(t);this.imgHeight=s.shape[s.shape.length-3];const o=s.shape[s.shape.length-2];this.widthFactor=Li([1],1+this.widthLower,1+this.widthUpper,"float32",this.randomGenerator.next());let r=this.widthFactor.dataSync()[0]*o;r=Math.round(r);const i=[this.imgHeight,r];switch(this.interpolation){case"bilinear":return is.resizeBilinear(t,i);case"nearest":return is.resizeNearestNeighbor(t,i);default:throw new Error(`Interpolation is ${this.interpolation}
          but only ${[...Xx]} are supported`)}})}}Ax.className="RandomWidth",_(Ax);/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */z().registerFlag("KEEP_INTERMEDIATE_TENSORS",()=>!1,n=>{n&&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.")});/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * =============================================================================
 */var Px;(function(n){n[n.DT_INVALID=0]="DT_INVALID",n[n.DT_FLOAT=1]="DT_FLOAT",n[n.DT_DOUBLE=2]="DT_DOUBLE",n[n.DT_INT32=3]="DT_INT32",n[n.DT_UINT8=4]="DT_UINT8",n[n.DT_INT16=5]="DT_INT16",n[n.DT_INT8=6]="DT_INT8",n[n.DT_STRING=7]="DT_STRING",n[n.DT_COMPLEX64=8]="DT_COMPLEX64",n[n.DT_INT64=9]="DT_INT64",n[n.DT_BOOL=10]="DT_BOOL",n[n.DT_QINT8=11]="DT_QINT8",n[n.DT_QUINT8=12]="DT_QUINT8",n[n.DT_QINT32=13]="DT_QINT32",n[n.DT_BFLOAT16=14]="DT_BFLOAT16",n[n.DT_QINT16=15]="DT_QINT16",n[n.DT_QUINT16=16]="DT_QUINT16",n[n.DT_UINT16=17]="DT_UINT16",n[n.DT_COMPLEX128=18]="DT_COMPLEX128",n[n.DT_HALF=19]="DT_HALF",n[n.DT_RESOURCE=20]="DT_RESOURCE",n[n.DT_VARIANT=21]="DT_VARIANT",n[n.DT_UINT32=22]="DT_UINT32",n[n.DT_UINT64=23]="DT_UINT64",n[n.DT_FLOAT_REF=101]="DT_FLOAT_REF",n[n.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",n[n.DT_INT32_REF=103]="DT_INT32_REF",n[n.DT_UINT8_REF=104]="DT_UINT8_REF",n[n.DT_INT16_REF=105]="DT_INT16_REF",n[n.DT_INT8_REF=106]="DT_INT8_REF",n[n.DT_STRING_REF=107]="DT_STRING_REF",n[n.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",n[n.DT_INT64_REF=109]="DT_INT64_REF",n[n.DT_BOOL_REF=110]="DT_BOOL_REF",n[n.DT_QINT8_REF=111]="DT_QINT8_REF",n[n.DT_QUINT8_REF=112]="DT_QUINT8_REF",n[n.DT_QINT32_REF=113]="DT_QINT32_REF",n[n.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF",n[n.DT_QINT16_REF=115]="DT_QINT16_REF",n[n.DT_QUINT16_REF=116]="DT_QUINT16_REF",n[n.DT_UINT16_REF=117]="DT_UINT16_REF",n[n.DT_COMPLEX128_REF=118]="DT_COMPLEX128_REF",n[n.DT_HALF_REF=119]="DT_HALF_REF",n[n.DT_RESOURCE_REF=120]="DT_RESOURCE_REF",n[n.DT_VARIANT_REF=121]="DT_VARIANT_REF",n[n.DT_UINT32_REF=122]="DT_UINT32_REF",n[n.DT_UINT64_REF=123]="DT_UINT64_REF"})(Px||(Px={}));var Ox;(function(n){(function(t){t[t.LEGACY=0]="LEGACY",t[t.V1=1]="V1",t[t.V2=2]="V2"})(n.CheckpointFormatVersion||(n.CheckpointFormatVersion={}))})(Ox||(Ox={}));/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * =============================================================================
 */var Kx;(function(n){n[n.FAIL=0]="FAIL",n[n.SHORTEST=1]="SHORTEST",n[n.LONGEST=2]="LONGEST"})(Kx||(Kx={}));/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function it(n,t){Array.isArray(n)||(n=[n]),n.forEach(e=>{e!=null&&v(e.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const LG=rg;class hl extends Zl{nextDataId(){return hl.nextDataId++}constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new lf(this,zt())}write(t,e,s){this.firstUse&&(this.firstUse=!1,z().get("IS_NODE")&&je(`
============================
Hi, 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. 
============================`));const o={id:this.nextDataId()};return this.data.set(o,{values:t,dtype:s,refCount:1}),o}makeTensorInfo(t,e,s){let o;if(e==="string"&&s!=null&&s.length>0&&Cr(s[0])){const r=s.map(i=>bs(i));o=this.write(r,t,e)}else o=this.write(s,t,e);return{dataId:o,shape:t,dtype:e}}refCount(t){return this.data.has(t)?this.data.get(t).refCount:0}incRef(t){const e=this.data.get(t);e.refCount++}decRef(t){if(this.data.has(t)){const e=this.data.get(t);e.refCount--}}move(t,e,s,o,r){this.data.set(t,{values:e,dtype:o,refCount:r})}numDataIds(){return this.data.numDataIds()}async read(t){return this.readSync(t)}readSync(t){const{dtype:e,complexTensorInfos:s}=this.data.get(t);if(e==="complex64"){const o=this.readSync(s.real.dataId),r=this.readSync(s.imag.dataId);return as(o,r)}return ow(this.data.get(t).values,e)}bufferSync(t){const e=this.readSync(t.dataId);if(t.dtype==="string")try{const s=e.map(o=>xs(o));return wt(t.shape,t.dtype,s)}catch{throw new Error("Failed to decode encoded string bytes into utf-8")}return wt(t.shape,t.dtype,e)}makeOutput(t,e,s){return zt().makeTensorFromTensorInfo(this.makeTensorInfo(e,s,t),this)}disposeData(t,e=!1){if(this.data.has(t)){if(this.data.get(t).refCount--,!e&&this.data.get(t).refCount>0)return!1;const{complexTensorInfos:s}=this.data.get(t);s!=null&&(this.disposeData(s.real.dataId,!0),this.disposeData(s.imag.dataId,!0)),this.data.delete(t)}return!0}disposeIntermediateTensorInfo(t){this.disposeData(t.dataId)}async time(t){const e=Ve();return t(),{kernelMs:Ve()-e}}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(t){it([t],"where");const e=this.readSync(t.dataId);return LG(t.shape,e)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}hl.nextDataId=0;/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Zx(n){const t=new Float32Array(n.length);for(let e=0;e<n.length;++e)t[e]=Math.abs(n[e]);return t}const EG={kernelName:ya,backendName:"cpu",kernelFunc:n=>{const{x:t}=n.inputs,e=n.backend;it(t,"abs");let s=new Float32Array(Z(t.shape));const o=e.data.get(t.dataId).values;return s=Zx(o),e.makeOutput(s,t.shape,t.dtype)}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function oe(n){return(t,e,s,o,r)=>{const i=gt(t,e),a=i.length,c=ct(i),l=Z(i),u=Se(r,l),d=t.length,h=e.length,p=ct(t),f=ct(e),m=Uo(t,i),g=Uo(e,i);if(m.length+g.length===0)for(let b=0;b<u.length;++b)u[b]=n(s[b%s.length],o[b%o.length]);else for(let b=0;b<u.length;++b){const x=Vo(b,a,c),I=x.slice(-d);m.forEach(k=>I[k]=0);const y=Fn(I,d,p),w=x.slice(-h);g.forEach(k=>w[k]=0);const C=Fn(w,h,f);u[b]=n(s[y],o[C])}return[u,i]}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Qe(n){const{inputs:t,backend:e}=n,{real:s,imag:o}=t,r=e.data.get(s.dataId).values,i=e.data.get(o.dataId).values,a=e.makeTensorInfo(s.shape,"complex64"),c=e.data.get(a.dataId);return c.complexTensorInfos={real:e.makeTensorInfo(s.shape,"float32",r),imag:e.makeTensorInfo(o.shape,"float32",i)},a}const DG={kernelName:lu,backendName:"cpu",kernelFunc:Qe};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function pl(n,t,e="float32"){if(e==="complex64"){const o=pl(n,t,"float32"),r=pl(n,t,"float32");return Qe({inputs:{real:o,imag:r},backend:n})}const s=ke(Z(t),e);return n.makeTensorInfo(t,e,s)}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Qn(n){const{inputs:t,backend:e}=n,{x:s}=t;return e.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const WG={kernelName:Kr,backendName:"cpu",kernelFunc:Qn};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function yo(n){const{inputs:t,backend:e}=n,{input:s}=t,o=e.data.get(s.dataId).complexTensorInfos.real,r=e.data.get(o.dataId).values;return e.makeTensorInfo(o.shape,o.dtype,r)}const MG={kernelName:Mu,backendName:"cpu",kernelFunc:yo};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Bx(n,t,e,s){if(s==="int32"){const o=Int32Array.from(n);return[t,"int32",o]}if(s==="bool"){const o=Ys([0],e),[r,i]=oe((a,c)=>a!==c?1:0)(t,[],n,o,"bool");return[i,"bool",r]}throw new Error(`Error in Cast: failed to cast ${e} to ${s}`)}function Ws(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{dtype:r}=s;if(r==="complex64"){if(o.dtype==="complex64")return Qn({inputs:{x:o},backend:e});const u=pl(e,o.shape,o.dtype),d=Ws({inputs:{x:o},backend:e,attrs:{dtype:"float32"}}),h=Qe({inputs:{real:d,imag:u},backend:e});return e.disposeIntermediateTensorInfo(u),e.disposeIntermediateTensorInfo(d),h}if(o.dtype==="complex64"){const u=yo({inputs:{input:o},backend:e}),d=Ws({inputs:{x:u},backend:e,attrs:{dtype:r}});return e.disposeIntermediateTensorInfo(u),d}if(!hf(o.dtype,r)){const u=Qn({inputs:{x:o},backend:e});return{dataId:u.dataId,shape:u.shape,dtype:r}}const i=e.data.get(o.dataId).values,[a,c,l]=Bx(i,o.shape,o.dtype,r);return e.makeTensorInfo(a,c,l)}const VG={kernelName:Gr,backendName:"cpu",kernelFunc:Ws};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function pe(n,t,e,s){return e==null?({inputs:o,backend:r})=>{const{a:i,b:a}=o,c=r;it([i,a],n);const l=c.data.get(i.dataId).values,u=c.data.get(a.dataId).values,d=i.dtype==="string"?cs(l):l,h=i.dtype==="string"?cs(u):u,p=s||i.dtype,[f,m]=t(i.shape,a.shape,d,h,p);return c.makeTensorInfo(m,p,f)}:({inputs:o,backend:r})=>{const{a:i,b:a}=o,c=r;if(i.dtype==="complex64"||a.dtype==="complex64"){const l=Ws({inputs:{x:i},backend:c,attrs:{dtype:"complex64"}}),u=c.data.get(l.dataId),d=u.complexTensorInfos.real,h=u.complexTensorInfos.imag,p=c.data.get(d.dataId).values,f=c.data.get(h.dataId).values,m=Ws({inputs:{x:a},backend:c,attrs:{dtype:"complex64"}}),g=c.data.get(m.dataId),b=g.complexTensorInfos.real,x=g.complexTensorInfos.imag,I=c.data.get(b.dataId).values,y=c.data.get(x.dataId).values,[w,C,k]=e(i.shape,a.shape,p,f,I,y),S=c.makeTensorInfo(k,"float32",w),T=c.makeTensorInfo(k,"float32",C),R=Qe({inputs:{real:S,imag:T},backend:c});return c.disposeIntermediateTensorInfo(l),c.disposeIntermediateTensorInfo(m),c.disposeIntermediateTensorInfo(S),c.disposeIntermediateTensorInfo(T),R}else{const l=c.data.get(i.dataId).values,u=c.data.get(a.dataId).values,d=s||i.dtype,[h,p]=t(i.shape,a.shape,l,u,d);return c.makeTensorInfo(p,d,h)}}}function lp(n){return(t,e,s,o,r,i)=>{const a=gt(t,e),c=Z(a),l=a.length,u=ct(a),d=Se("float32",c),h=Se("float32",c),p=Uo(t,a),f=Uo(e,a),m=as(s,o),g=as(r,i),b=t.length,x=ct(t),I=e.length,y=ct(e);if(p.length+f.length===0)for(let w=0;w<d.length;w++){const C=w%m.length,k=w%g.length,S=n(m[C*2],m[C*2+1],g[k*2],g[k*2+1]);d[w]=S.real,h[w]=S.imag}else for(let w=0;w<d.length;w++){const C=Vo(w,l,u),k=C.slice(-b);p.forEach(V=>k[V]=0);const S=Fn(k,b,x),T=C.slice(-I);f.forEach(V=>T[V]=0);const R=Fn(T,I,y),L=n(m[S*2],m[S*2+1],g[R*2],g[R*2+1]);d[w]=L.real,h[w]=L.imag}return[d,h,a]}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const Hx=oe((n,t)=>n+t),FG=lp((n,t,e,s)=>({real:n+e,imag:t+s})),ir=pe(Fo,Hx,FG),zG={kernelName:Fo,backendName:"cpu",kernelFunc:ir};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function up(n,t,e,s,o){const r=Z(s),i=ke(o,e);for(let a=0;a<n.length;a++){const c=n[a];if(c<0)throw new Error("Input x must be non-negative!");c>=o||(r>0?i[c]+=t[a]:i[c]+=1)}return i}function _x(n,t,e,s=!1){const o=n.shape[0],r=n.shape[1],i=wt([o,e],t.dtype);for(let a=0;a<o;a++)for(let c=0;c<r;c++){const l=n.get(a,c);if(l<0)throw new Error("Input x must be non-negative!");l>=e||(s?i.set(1,a,l):t.size>0?i.set(i.get(a,l)+t.get(a,c),a,l):i.set(i.get(a,l)+1,a,l))}return i}/**
 * @license
 * Copyright 2023 Google LLC.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const Ux=oe((n,t)=>n&t),XG=pe(cu,Ux),AG={kernelName:cu,backendName:"cpu",kernelFunc:XG};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Jn(n){return(t,e,s)=>{const o=qt(e,t.length);for(let r=0;r<t.length;++r)o[r]=n(t[r],s);return o}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Et(n,t,e){const s=Jn(t);return Ms(n,s,e)}function Ms(n,t,e){return({inputs:s,attrs:o,backend:r})=>{const{x:i}=s;it(i,n);const a=r,c=a.data.get(i.dataId).values;let l;if(i.dtype==="string"){if(!Array.isArray(c))throw new Error("String tensor's value was not an instance of Array");l=cs(c)}else l=c;const u=e||i.dtype,d=t(l,u,o);return a.makeTensorInfo(i.shape,u,d)}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const Yx=Jn(n=>Math.ceil(n)),PG=Ms(Lr,Yx),OG={kernelName:Lr,backendName:"cpu",kernelFunc:PG};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Qx(n,t,e,s){const o=qt(e,Z(t));if(s&&e!=="string"){let r=0;n.forEach(i=>{const a=Z(i.shape);o.set(i.vals,r),r+=a})}else{let r=0;n.forEach(i=>{const a=e==="string"?cs(i.vals):i.vals;let c=0;for(let l=0;l<i.shape[0];++l){const u=l*t[1]+r;for(let d=0;d<i.shape[1];++d)o[u+d]=a[c++]}r+=i.shape[1]})}return o}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const Jx=oe((n,t)=>n===t?1:0),jx=pe(Wa,Jx,null,"bool"),KG={kernelName:Wa,backendName:"cpu",kernelFunc:jx};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const qx=Jn(n=>Math.exp(n)),ty=Ms(zr,qx,"float32"),ZG={kernelName:zr,backendName:"cpu",kernelFunc:ty};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const ey=Jn(n=>Math.expm1(n)),BG=Ms(Xr,ey),HG={kernelName:Xr,backendName:"cpu",kernelFunc:BG};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const ny=Jn(n=>Math.floor(n)),_G=Ms(Ar,ny),UG={kernelName:Ar,backendName:"cpu",kernelFunc:_G};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const sy=oe((n,t)=>Math.floor(n/t)),YG=pe(Pr,sy,null,"int32"),QG={kernelName:Pr,backendName:"cpu",kernelFunc:YG};/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function oy(n,t,e,s,o,r,i,a,c){const l=wt([s,r],e);for(let u=0;u<s;u++){const d=[];let h=0;for(let p=0;p<o;p++){const f=n[u*o+p];h+=f*i[p],d.push(f)}if(h<0||h>=c/r)throw new Error(`Invalid indices: ${d} does not index into ${a}`);for(let p=0;p<r;p++)l.values[u*r+p]=t.get(...t.indexToLoc(h*r+p))}return l}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function ry(n,t,e){const s=wt(e,n.dtype);for(let o=0;o<s.size;++o){const i=s.indexToLoc(o).slice(),a=i[0],c=i[2],l=t.locToIndex([a,c]);i[2]=t.values[l];const u=n.locToIndex(i);0<=u&&u<n.values.length&&(s.values[o]=n.values[u])}return s}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const iy=oe((n,t)=>n>t?1:0),JG=pe(za,iy,null,"bool"),jG={kernelName:za,backendName:"cpu",kernelFunc:JG};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const ay=oe((n,t)=>n>=t?1:0),qG=pe(Or,ay,null,"bool"),tL={kernelName:Or,backendName:"cpu",kernelFunc:qG};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const cy=oe((n,t)=>n<t?1:0),eL=pe(Aa,cy,null,"bool"),nL={kernelName:Aa,backendName:"cpu",kernelFunc:eL};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const ly=oe((n,t)=>n<=t?1:0),sL=pe(Pa,ly,null,"bool"),oL={kernelName:Pa,backendName:"cpu",kernelFunc:sL};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function uy(n,t,e){const s=(t-n)/(e-1),o=ke(e,"float32");o[0]=n;for(let r=1;r<o.length;r++)o[r]=o[r-1]+s;return o}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const dy=Jn(n=>Math.log(n)),rL=Ms(_r,dy),iL={kernelName:_r,backendName:"cpu",kernelFunc:rL};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function hy(n,t,e,s){const o=Se(s,Z(e));for(let r=0;r<o.length;++r){const i=r*t;let a=n[i];for(let c=0;c<t;++c){const l=n[i+c];(Number.isNaN(l)||l>a)&&(a=l)}o[r]=a}return o}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const py=oe((n,t)=>Math.max(n,t)),aL=pe(Yr,py),cL={kernelName:Yr,backendName:"cpu",kernelFunc:aL};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const fy=oe((n,t)=>Math.min(n,t)),lL=pe(Qr,fy),uL={kernelName:Qr,backendName:"cpu",kernelFunc:lL};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const dp=oe((n,t)=>n*t),dL=lp((n,t,e,s)=>({real:n*e-t*s,imag:n*s+t*e})),fl=pe(jr,dp,dL),hL={kernelName:jr,backendName:"cpu",kernelFunc:fl};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function my(n,t,e){const s=gs(-1,e);return dp([],t,s,n,e)}function pL(n){const{inputs:t,backend:e}=n,{x:s}=t;it(s,"neg");const o=e.data.get(s.dataId).values,[r,i]=my(o,s.shape,s.dtype);return e.makeTensorInfo(i,s.dtype,r)}const fL={kernelName:ja,backendName:"cpu",kernelFunc:pL};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const gy=oe((n,t)=>n!==t?1:0),mL=pe(qa,gy,null,"bool"),gL={kernelName:qa,backendName:"cpu",kernelFunc:mL};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function hp(n,t,e,s,o){const r=t.length,i=Z(t),a=ct(t),c=ct(o),l=Se(e,Z(o));for(let u=0;u<i;++u){const d=Vo(u,r,a),h=new Array(d.length);for(let f=0;f<h.length;f++)h[f]=d[s[f]];const p=Fn(h,r,c);l[p]=n[u]}return l}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Ke(n){const{inputs:t,attrs:e,backend:s}=n,{x:o}=t,{perm:r}=e;it(o,"transpose");const i=o.shape.length,a=new Array(i);for(let d=0;d<a.length;d++)a[d]=o.shape[r[d]];const c=s.data.get(o.dataId).values,l=hp(c,o.shape,o.dtype,r,a);return{dataId:s.write(l,a,o.dtype),shape:a,dtype:o.dtype}}const bL={kernelName:zo,backendName:"cpu",kernelFunc:Ke};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function by(n,t,e,s){const[o,r]=me(n,s),i=_e(t,"int32"),a=ke(Z(o),i),c=Z(r);for(let l=0;l<a.length;++l){const u=l*c;let d=1;for(let h=0;h<c;++h)d*=e[u+h];a[l]=d}return{outVals:a,outShape:o,outDtype:i}}function xL(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r,keepDims:i}=s;it(o,"prod");const a=o.shape.length,c=It(r,o.shape),l=Yt(c,a);let u=c,d=o;const h=[];l!=null&&(d=Ke({inputs:{x:o},backend:e,attrs:{perm:l}}),h.push(d),u=ee(u.length,a));const p=e.data.get(d.dataId).values,{outVals:f,outShape:m,outDtype:g}=by(d.shape,d.dtype,p,u);let b=m;return i&&(b=re(m,c)),h.forEach(x=>e.disposeIntermediateTensorInfo(x)),e.makeTensorInfo(b,g,f)}const yL={kernelName:rc,backendName:"cpu",kernelFunc:xL};/**
 * @license
 * Copyright 2022 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function IL(n,t,e){n.forEach((s,o)=>{if(s<0||s>=e){const r=Vo(o,t.length,ct(t)).join(",");throw new Error(`indices[${r}] = ${s} is not in [0, ${e})`)}})}function wL(n,t){for(let e=0;e<n.length;++e){const s=n[e],o=e===n.length-1?t:n[e+1].length;if(s.length===0)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]>o)throw new Error("Ragged splits must not point past values");for(let r=1;r<s.length;++r)if(s[r-1]>s[r])throw new Error("Ragged splits must be sorted in ascending order")}}function CL(n,t,e,s){const o=[];let r=0;const i=t.length-1+e.length,a=new Array(i).fill(null).map(()=>[0]);wL(e,s);let c=1;for(let l=0;l<t.length-1;++l){c*=t[l];const u=t[l+1];for(let d=1;d<c+1;++d)a[l].push(d*u)}for(let l=0;l<n.length;++l){let u=n[l],d=n[l]+1;for(let h=0;h<e.length;++h){const p=e[h],f=h+t.length-1;if(f>=0){const m=a[f],g=m[m.length-1]-p[u];for(let b=u;b<d;++b)a[f].push(p[b+1]+g)}u=p[u],d=p[d]}d!==u&&(o.push([u,d]),r+=d-u)}return{outSplits:a,valueSlices:o,numValues:r}}function vL(n){const t=[];for(let e=0;e<n.length;++e){const s=n[e].length,o=qt("int32",s);t.push(o),n[e].forEach((r,i)=>o[i]=r)}return t}function xy(n,t){const e=n.slice(0,t);for(;e.length<t;)e.push(1);for(let s=t;s<n.length;s++)e[t-1]*=n[s];return e}function SL(n,t,e,s,o,r){const i=xy(t,2)[1],a=xy(r,2)[1];let c=0;for(const l of e)for(let u=l[0];u<l[1];++u){for(let d=0;d<s;++d)o[c*a+d]=n[u*i+d];++c}}function kL(n,t,e,s,o){const r=t.slice();r[0]=o;const i=qt(e,Z(r)),a=n.length,c=a===0?0:a/t[0];return SL(n,t,s,c,i,r),[i,r]}function yy(n,t,e,s,o,r,i,a){if(n.length===0)throw new Error("paramsNestedSplits must be non empty");if(t[0].length===0)throw new Error("Split tensors must not be scalars");const c=t[0][0]-1;if(IL(r,i,c),s.length===0)throw new Error("params.rank must be nonzero");const l=s[0],{outSplits:u,valueSlices:d,numValues:h}=CL(r,i,n,l),p=vL(u),f=kL(e,s,o,d,h);return[p,f[0],f[1]]}/**
 * @license
 * Copyright 2022 Google LLC.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const Iy=2147483647;function wy(n,t,e,s,o,r,i){if(t.length>1)throw new Error("starts must be a scalar or vector");if(o.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 a=t.length===0,c=o.length===0,l=i.length===0,u=[];a||u.push(t[0]),c||u.push(o[0]),l||u.push(i[0]);for(let g=1;g<u.length;++g)if(u[g]!==u[g-1])throw new Error("starts, limits, and deltas must have the same shape");const d=u.length===0?1:u[0],h=qt("int32",d+1);h[0]=0;for(let g=0;g<d;++g){const b=a?n[0]:n[g],x=c?s[0]:s[g],I=l?r[0]:r[g];if(I===0)throw new Error("Requires delta != 0");let y;if(I>0&&x<b||I<0&&x>b)y=0;else if(y=Math.ceil(Math.abs((x-b)/I)),y>Iy)throw new Error(`Requires ((limit - start) / delta) <= ${Iy}`);h[g+1]=h[g]+y}const p=h[d],f=qt(e,p);let m=0;for(let g=0;g<d;++g){const b=h[g+1]-h[g];let x=a?n[0]:n[g];const I=l?r[0]:r[g];for(let y=0;y<b;++y)f[m++]=x,x+=I}return[h,f]}/**
 * @license
 * Copyright 2022 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */var In=Rn;class ml{constructor(t,e,s,o,r,i,a,c,l,u){this.shape=t,this.shapeShape=e,this.values=s,this.valuesShape=o,this.valuesDType=r,this.defaultValue=i,this.defaultValueShape=a,this.rowPartitionValues=c,this.rowPartitionValuesShapes=l,this.rowPartitionTypes=Ng(u),this.raggedRank=Rg(this.rowPartitionTypes)}getRowPartitionTypeByDimension(t){return this.rowPartitionTypes[0]===In.FIRST_DIM_SIZE?this.rowPartitionTypes[t+1]:this.rowPartitionTypes[t]}getRowPartitionTensor(t){return this.rowPartitionTypes[0]===In.FIRST_DIM_SIZE?this.rowPartitionValues[t+1]:this.rowPartitionValues[t]}getMaxWidth(t){const e=this.getRowPartitionTensor(t-1);switch(this.getRowPartitionTypeByDimension(t-1)){case In.VALUE_ROWIDS:return ml.getMaxWidthValueRowID(e);case In.ROW_SPLITS:return ml.getMaxWidthRowSplit(e);default:throw new Error(`Cannot handle partition type ${In[this.getRowPartitionTypeByDimension(t-1)]}`)}}static getMaxWidthRowSplit(t){const e=t.length;if(e===0||e===1)return 0;let s=0;for(let o=0;o<e-1;++o){const r=t[o+1]-t[o];r>s&&(s=r)}return s}static getMaxWidthValueRowID(t){const e=t.length;if(e===0)return 0;let s=0,o=t[0],r=0;for(let i=1;i<e;++i){const a=t[i];a!==o&&(o=a,r=Math.max(i-s,r),s=i)}return Math.max(e-s,r)}tensorShapeFromTensor(t,e,s=!0){if(e.length===0){if(t[0]===-1)return[];throw new Error("The only valid scalar shape tensor is the fully unknown shape specified as -1.")}return vy(t,s)}calculateOutputSize(t){const e=this.valuesShape,s=this.defaultValueShape;$g(s,e);const o=this.tensorShapeFromTensor(this.shape,this.shapeShape),i=Tg(this.raggedRank,o,e);i[0]<0&&(i[0]=t);for(let a=1;a<=this.raggedRank;++a)i[a]<0&&(i[a]=this.getMaxWidth(a));return i}calculateFirstParentOutputIndex(t,e,s){const o=Math.min(t,s),r=[];let i=0;for(let a=0;a<o;++a,i+=e)r.push(i);for(let a=o;a<t;++a)r.push(-1);return v(r.length===t,()=>"Final length of result must be equal to firstDimension."),r}calculateOutputIndexRowSplit(t,e,s,o){const r=t.length,i=[];for(let a=0;a<r-1;++a){const c=t[a+1]-t[a];let l=Math.min(o,c),u=e[a];u===-1&&(l=0);for(let d=0;d<l;++d)i.push(u),u+=s;for(let d=0;d<c-l;++d)i.push(-1)}if(r>0&&i.length!==t[r-1])throw new Error("Invalid row split size.");return i}calculateOutputIndexValueRowID(t,e,s,o){const r=t.length,i=[];if(r===0)return[];let a=0,c=t[0];if(c>=e.length)throw new Error(`Got currentValueRowId=${c}, which is not less than ${e.length}`);let l=e[c];i.push(l);for(let u=1;u<r;++u){const d=t[u];if(d===c)l>=0&&(++a,a<o?l+=s:l=-1);else{if(a=0,c=d,d>=e.length)throw new Error(`Got nextValueRowId=${d} which is not less than ${e.length}`);l=e[d]}i.push(l)}if(i.length!==t.length)throw new Error("Invalid row ids.");return i}calculateOutputIndex(t,e,s,o){const r=this.getRowPartitionTensor(t),i=this.getRowPartitionTypeByDimension(t);switch(i){case In.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(r,e,s,o);case In.ROW_SPLITS:if(r.length-1>e.length)throw new Error(`Row partition size is greater than output size: ${r.length-1} > ${e.length}`);return this.calculateOutputIndexRowSplit(r,e,s,o);default:throw new Error(`Unsupported partition type: ${In[i]}`)}}getFirstDimensionSize(){const t=this.rowPartitionValues[0];if(this.rowPartitionTypes.length===0)throw new Error("No row_partition_types given.");const e=this.rowPartitionTypes[0];switch(e){case In.FIRST_DIM_SIZE:return t[0];case In.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case In.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${In[e]}`)}}compute(){if(this.rowPartitionValues[0].length<=0)throw new Error("Invalid first partition input. Tensor requires at least one element.");const e=this.getFirstDimensionSize(),s=this.calculateOutputSize(e),o=new Array(this.raggedRank+1);o[o.length-1]=1;for(let c=o.length-2;c>=0;--c)o[c]=o[c+1]*s[c+1];const r=vy(s,!1),i=qt(this.valuesDType,Z(r));if(o[0]*s[0]>0){let c=this.calculateFirstParentOutputIndex(e,o[0],s[0]);for(let l=1;l<=this.raggedRank;++l)c=this.calculateOutputIndex(l-1,c,o[l],s[l]);this.setOutput(this.raggedRank,c,i,r)}return[r,i]}setOutput(t,e,s,o){if(s.length===0)return;const r=this.values,i=s;let a=o.slice();a=a.slice(t+1);const c=Z(a),l=e.length;let u=this.defaultValue;if(u.length!==c&&u.length!==1){const f=this.defaultValueShape;M(()=>{const m=W(u,f);u=Ni(m,a).dataSync()})}let d=0,h=0,p=0;for(let f=0;f<=l;++f){let m=f<l?e[f]:-1;if(m===p){++p;continue}if(h<p){const g=r.subarray(d*c),b=i.subarray(h*c),x=(p-h)*c;Cy(b,g,x)}if(f>=l){const g=s.length;m=Math.floor(g/c)}if(m>p)if(this.defaultValue.length===1)i.subarray(p*c,m*c).fill(this.defaultValue[0]),p=m;else for(;m>p;){const g=i.slice(p*c);Cy(g,u,c),++p}m<0?(d=f+1,h=p):(d=f,h=p,p=h+1)}}}function Cy(n,t,e){for(let s=0;s<e;s++)n[s]=t[s]}function vy(n,t){const e=[];for(let s of n){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}e.push(s)}return e}function Sy(n,t,e,s,o,r,i,a,c,l){return new ml(n,t,e,s,o,r,i,a,c,l).compute()}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function ky(n,t,e,s){const o=n===t,r=n<t&&e<0,i=t<n&&e>1;if(o||r||i)return ke(0,s);const a=Math.abs(Math.ceil((t-n)/e)),c=ke(a,s);t<n&&e===1&&(e=-1),c[0]=n;for(let l=1;l<c.length;l++)c[l]=c[l-1]+e;return c}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const Ty=Jn(n=>1/Math.sqrt(n)),TL=Ms(oi,Ty),NL={kernelName:oi,backendName:"cpu",kernelFunc:TL};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Io(n,t,e,s,o,r,i,a,c,l){const u=[s/o,o],d=n.values,h=t.values;if(s===0)return wt(e,t.dtype);const p=c instanceof xe?c:wt(u,t.dtype);typeof c=="string"||typeof c=="number"?p.values.fill(c):typeof c=="boolean"&&p.values.fill(+c);for(let f=0;f<r;f++){const m=[];let g=0;for(let b=0;b<i;b++){const x=d[f*i+b];m.push(x),g+=x*a[b]}if(g<0||g>=s/o)throw new Error(`Invalid indices: ${m} does not index into ${e}`);for(let b=0;b<o;b++)l?p.values[g*o+b]+=h[f*o+b]:p.values[g*o+b]=t.rank===0?h[0]:h[f*o+b]}return p}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const RL=Jn(n=>1/(1+Math.exp(-n))),Ny=Et(li,n=>1/(1+Math.exp(-n))),$L={kernelName:li,backendName:"cpu",kernelFunc:Ny};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Ry(n,t,e,s,o){const r=eh(s,t,e),i=Z(e),a=ct(s);if(r){const d=nh(t,a);return o==="string"?n.slice(d,d+i):n.subarray(d,d+i)}const c=o==="string"?cs(n):n,l=wt(s,o,c),u=wt(e,o);for(let d=0;d<u.size;++d){const h=u.indexToLoc(d),p=h.map((f,m)=>f+t[m]);u.set(l.get(...p),...h)}return o==="string"?Jg(u.values):u.values}function wo(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{begin:r,size:i}=s;it(o,"slice");const[a,c]=zc(o,r,i);qd(o,a,c);const l=e.data.get(o.dataId).values,u=Ry(l,a,c,o.shape,o.dtype);return e.makeTensorInfo(c,o.dtype,u)}const GL={kernelName:dc,backendName:"cpu",kernelFunc:wo};/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function $y(n,t,e,s,o,r,i){const a=t[0],c=r[0],l=new Array(c),u=new Array(a),d=t[1];if(c===0){if(a!==0)throw new Error(zg(a));const g=qt(e,0),b=qt(o,0);return[g,[0,d],b,l,u]}let h=!0,p=0;const f=new Array(c).fill(0);for(let g=0;g<a;++g){const b=n[g*d];if(b<0)throw new Error(Xg(g,b));if(b>=c)throw new Error(Ag(g,b,c));++f[b],h=h&&b>=p,p=b}let m=!0;for(let g=0;g<c;++g){const b=f[g]===0;l[g]=b,m=m&&!b,f[g]=Math.max(f[g],1),g>0&&(f[g]+=f[g-1])}if(m&&h){const g=n,b=s;for(let x=0;x<a;++x)u[x]=x;return[g,[a,d],b,l,u]}else{const g=f[c-1],b=qt(e,g*d),x=qt(o,g),I=new Array(c).fill(0);for(let y=0;y<a;++y){const w=n[y*d],C=I[w],k=(w===0?0:f[w-1])+C;I[w]++;for(let S=0;S<d;++S)b[k*d+S]=n[y*d+S];x[k]=s[y],u[y]=k}for(let y=0;y<c;++y)if(I[y]===0){const C=y===0?0:f[y-1];b[C*d+0]=y;for(let k=1;k<d;++k)b[C*d+k]=0;x[C]=i}return[b,[g,d],x,l,u]}}/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Gy(n,t,e,s,o){const r=Z(s),i=t[0],a=o.length,c=[];let l=1,u=-1;for(let g=0;g<a;++g){const b=o[g];if(b===-1){if(u!==-1)throw new Error(Pg(u,g));u=g,c.push(1)}else{if(b<0)throw new Error(Og(g,b));l*=b,c.push(b)}}if(u!==-1){if(l<=0)throw new Error(Kg());const g=Math.trunc(r/l);if(l*g!==r)throw new Error(Zg(s,c));c[u]=g}if(Z(c)!==r)throw new Error(Bg(s,c));const h=s.length,p=[];if(h>0){p[h-1]=1;for(let g=h-2;g>=0;--g)p[g]=p[g+1]*s[g+1]}const f=[];if(a>0){f[a-1]=1;for(let g=a-2;g>=0;--g)f[g]=f[g+1]*c[g+1]}const m=qt(e,i*a);for(let g=0;g<i;++g){let b=0;for(let x=0;x<h;++x)b+=n[g*h+x]*p[x];for(let x=0;x<a;++x)m[g*a+x]=Math.trunc(b/f[x]),b%=f[x]}return[m,[i,a],c]}/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function pp(n,t,e,s,o,r=!1,i=0){const a=s.length,c=[t[0],n.length/t[0]],l=c[1],d=a>0?o[a-1]+1:0;if(d<0)throw new Error(vh());const h=t.slice();h[0]=d;const p=h.reduce((I,y)=>I*y,1),f=qt(e,p);if(a===0)return d>0&&f.fill(i),[f,h];if(d<=0)throw new Error(vh());let m=0,g=1,b=0,x=o[m];for(;;){let I=0;if(g<a){if(I=o[g],x===I){++g;continue}if(x>=I)throw new Error(Hg())}if(x<0||x>=d)throw new Error(_g(x,d));x>b&&f.fill(i,b*l,x*l);for(let y=m;y<g;++y){const w=s[y];if(w<0||w>=c[0])throw new Error(Ug(y,s[y],c[0]));for(let C=0;C<l;C++)f[x*l+C]+=n[w*l+C]}if(r)for(let y=0;y<l;y++)f[x*l+y]/=g-m;if(m=g,++g,b=x+1,x=I,g>a)break}return b<d&&f.fill(i,b*l,d*l),[f,h]}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const LL=Jn(n=>Math.sqrt(n)),EL=Et(di,n=>Math.sqrt(n)),DL={kernelName:di,backendName:"cpu",kernelFunc:EL};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const Ly=oe((n,t)=>{const e=n-t;return e*e}),WL=pe(hi,Ly),ML={kernelName:hi,backendName:"cpu",kernelFunc:WL};/**
 * @license
 * Copyright 2023 Google LLC.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const Ey=Jn((n,t)=>{const{pattern:e,replaceGlobal:s,rewrite:o}=t;return n.replace(new RegExp(e,s?"g":""),o)}),VL=Ms(Xu,Ey),FL={kernelName:Xu,backendName:"cpu",kernelFunc:VL};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Dy(n,t,e,s){const o=wt(n,t.dtype);for(let r=0;r<o.size;r++){const i=o.indexToLoc(r),a=new Array(i.length);for(let c=0;c<a.length;c++)a[c]=i[c]*e[c]+s[c];o.set(t.get(...a),...i)}return o}/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class zL{constructor(t,e,s,o,r,i){this.separator=bs(t),this.nGramWidths=e,this.leftPad=bs(s),this.rightPad=bs(o),this.padWidth=r,this.preserveShort=i}getPadWidth(t){return Math.min(this.padWidth<0?t-1:this.padWidth,t-1)}getNumNGrams(t,e){const s=this.getPadWidth(e);return Math.max(0,t+2*s-e+1)}createNGrams(t,e,s,o,r,i){for(let a=0;a<r;++a){const c=this.getPadWidth(i),l=Math.max(0,c-a),u=Math.max(0,c-(r-(a+1))),d=i-(l+u),h=e+(l>0?0:a-c);let p=0;p+=l*this.leftPad.length;for(let x=0;x<d;++x)p+=t[h+x].length;p+=u*this.rightPad.length;const f=l+u+d-1;p+=f*this.separator.length,s[o+a]=new Uint8Array(p);const m=s[o+a];let g=0;const b=x=>x.forEach(I=>m[g++]=I);for(let x=0;x<l;++x)b(this.leftPad),b(this.separator);for(let x=0;x<d-1;++x)b(t[h+x]),b(this.separator);if(d>0){b(t[h+d-1]);for(let x=0;x<u;++x)b(this.separator),b(this.rightPad)}else{for(let x=0;x<u-1;++x)b(this.rightPad),b(this.separator);b(this.rightPad)}}}compute(t,e){const s=t.length,o=e.length;if(o>0){let c=e[0];if(c!==0)throw new Error(`First split value must be 0, got ${c}`);for(let l=1;l<o;++l){let u=e[l]>=c;if(u=u&&e[l]<=s,!u)throw new Error(`Invalid split value ${e[l]}, must be in [${c}, ${s}]`);c=e[l]}if(c!==s)throw new Error(`Last split value must be data size. Expected ${s}, got ${c}`)}const r=o-1,i=qt("int32",o);if(s===0||o===0){const c=new Array(s);for(let l=0;l<=r;++l)i[l]=0;return[c,i]}i[0]=0;for(let c=1;c<=r;++c){const l=e[c]-e[c-1];let u=0;this.nGramWidths.forEach(d=>{u+=this.getNumNGrams(l,d)}),this.preserveShort&&l>0&&u===0&&(u=1),i[c]=i[c-1]+u}const a=new Array(i[r]);for(let c=0;c<r;++c){const l=e[c];let u=i[c];if(this.nGramWidths.forEach(d=>{const h=e[c+1]-e[c],p=this.getNumNGrams(h,d);this.createNGrams(t,l,a,u,p,d),u+=p}),this.preserveShort&&u===i[c]){const d=e[c+1]-e[c];if(d===0)continue;const h=d+2*this.padWidth;this.createNGrams(t,l,a,u,1,h)}}return[a,i]}}function Wy(n,t,e,s,o,r,i,a){return new zL(e,s,o,r,i,a).compute(n,t)}/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function XL(n,t,e,s){if(!n.length)return;if(t.length===0){for(let r=0;r<n.length;++r)s.push(n.subarray(r,r+1));return}if(t.length===1){const r=t[0];let i=n.indexOf(r);for(;i!==-1;){const a=n.subarray(0,i);(!e||a.length!==0)&&s.push(a),n=n.subarray(i+1),i=n.indexOf(r)}(!e||n.length!==0)&&s.push(n);return}let o=0;for(let r=0;r<n.length+1;r++)if(r===n.length||t.indexOf(n[r])!==-1){const i=n.subarray(o,r);(!e||i.length!==0)&&s.push(i),o=r+1}}function My(n,t,e){const s=n.length,o=[];let r=0,i=0;const a=new Array(s);for(let h=0;h<s;++h){const p=o.length;XL(n[h],t,e,o);const f=o.length-p;a[h]=f,r+=f,i=Math.max(i,f)}const c=qt("int32",r*2),l=new Array(r),u=[s,i];let d=0;for(let h=0;h<s;++h)for(let p=0;p<a[h];++p)c[d*2]=h,c[d*2+1]=p,l[d]=o[d],++d;return[c,l,u]}/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Vy(n,t){const e=qt("int32",n.length);for(let s=0;s<n.length;++s)e[s]=Sw(n[s]).modulo(t).getLowBitsUnsigned();return e}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const Fy=oe((n,t)=>n-t),AL=lp((n,t,e,s)=>({real:n-e,imag:t-s})),fp=pe(pi,Fy,AL),PL={kernelName:pi,backendName:"cpu",kernelFunc:fp};/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function zy(n,t){const e=new Array(n.rank);for(let o=0;o<e.length;o++)e[o]=n.shape[o]*t[o];const s=wt(e,n.dtype);for(let o=0;o<s.values.length;++o){const r=s.indexToLoc(o),i=new Array(n.rank);for(let c=0;c<i.length;c++)i[c]=r[c]%n.shape[c];const a=n.locToIndex(i);s.values[o]=n.values[a]}return s}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const ta=(n,t)=>{const e=t.value-n.value;return e===0?n.index-t.index:e};function Xy(n,t,e=0,s=n.length-1){for(;s>e;){if(s-e>600){const a=s-e+1,c=t-e+1,l=Math.log(a),u=.5*Math.exp(2*l/3),d=.5*Math.sqrt(l*u*(a-u)/a)*Math.sign(c-a/2),h=Math.max(e,Math.floor(t-c*u/a+d)),p=Math.min(s,Math.floor(t+(a-c)*u/a+d));Xy(n,t,h,p)}const o=n[t];let r=e,i=s;for(Eo(n,e,t),ta(n[s],o)>0&&Eo(n,e,s);r<i;){for(Eo(n,r,i),r++,i--;ta(n[r],o)<0;)r=r+1;for(;ta(n[i],o)>0;)i=i-1}ta(n[e],o)===0?Eo(n,e,i):(i=i+1,Eo(n,i,s)),i<=t&&(e=i+1),t<=i&&(s=i-1)}}function Ay(n,t,e,s,o){const r=t[t.length-1],[i,a]=[n.length/r,r],c=Se(e,i*s),l=Se("int32",i*s);for(let d=0;d<i;d++){const h=d*a,p=n.subarray(h,h+a);let f=new Array(p.length);p.forEach((x,I)=>f[I]={value:x,index:I}),s<f.length&&(Xy(f,s),f=f.slice(0,s)),o&&f.sort(ta);const m=d*s,g=c.subarray(m,m+s),b=l.subarray(m,m+s);for(let x=0;x<s;x++)g[x]=f[x].value,b[x]=f[x].index}const u=t.slice();return u[u.length-1]=s,[wt(u,e,c),wt(u,"int32",l)]}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Py(n,t,e,s){const o=It(t,e)[0],r=[1,e[0],1];for(let f=0;f<o;f++)r[0]*=e[f];r[1]=e[o];for(let f=o+1;f<e.length;f++)r[2]*=e[f];const i=new Map,a=new Int32Array(e[o]),c=new xe(r,s,n),l=[],u=r[0]===1&&r[2]===1;for(let f=0;f<e[o];f++){let m;if(u)m=n[f].toString();else{const b=[];for(let x=0;x<r[0];x++)for(let I=0;I<r[2];I++)b.push(c.get(x,f,I));m=b.join(",")}const g=i.get(m);if(g!=null)a[f]=g;else{const b=i.size;i.set(m,b),a[f]=b,l.push(f)}}const d=r.slice();d[1]=i.size;const h=new xe(d,s);l.forEach((f,m)=>{for(let g=0;g<r[0];g++)for(let b=0;b<r[2];b++)h.set(c.get(g,f,b),g,m,b)});const p=e.slice();return p[o]=d[1],{outputValues:h.values,outputShape:p,indices:a}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const OL=Object.freeze(Object.defineProperty({__proto__:null,addImpl:Hx,bincountImpl:up,bincountReduceImpl:_x,bitwiseAndImpl:Ux,castImpl:Bx,ceilImpl:Yx,concatImpl:Qx,equalImpl:Jx,expImpl:qx,expm1Impl:ey,floorDivImpl:sy,floorImpl:ny,gatherNdImpl:oy,gatherV2Impl:ry,greaterEqualImpl:ay,greaterImpl:iy,lessEqualImpl:ly,lessImpl:cy,linSpaceImpl:uy,logImpl:dy,maxImpl:hy,maximumImpl:py,minimumImpl:fy,multiplyImpl:dp,negImpl:my,notEqualImpl:gy,prodImpl:by,raggedGatherImpl:yy,raggedRangeImpl:wy,raggedTensorToTensorImpl:Sy,rangeImpl:ky,rsqrtImpl:Ty,scatterImpl:Io,sigmoidImpl:RL,simpleAbsImpl:Zx,sliceImpl:Ry,sparseFillEmptyRowsImpl:$y,sparseReshapeImpl:Gy,sparseSegmentReductionImpl:pp,sqrtImpl:LL,squaredDifferenceImpl:Ly,staticRegexReplaceImpl:Ey,stridedSliceImpl:Dy,stringNGramsImpl:Wy,stringSplitImpl:My,stringToHashBucketFastImpl:Vy,subImpl:Fy,tileImpl:zy,topKImpl:Ay,transposeImpl:hp,uniqueImpl:Py},Symbol.toStringTag,{value:"Module"}));/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */bm("cpu",()=>new hl,1);/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const Oy=Et(Vr,n=>n>=0?n:Math.exp(n)-1),KL={kernelName:Vr,backendName:"cpu",kernelFunc:Oy};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Ky(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{alpha:r}=s;it([o],"leakyRelu");const i=Z(o.shape),a=e.data.get(o.dataId).values,c=Se("float32",i);for(let l=0;l<a.length;l++)c[l]=a[l]<0?r*a[l]:a[l];return e.makeTensorInfo(o.shape,"float32",c)}const ZL={kernelName:Xa,backendName:"cpu",kernelFunc:Ky};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const BL=oe((n,t)=>n<0?t*n:n);function Zy(n){const{inputs:t,backend:e}=n,{x:s,alpha:o}=t;it([s,o],"prelu");const r=e.data.get(s.dataId).values,i=e.data.get(o.dataId).values,[a,c]=BL(s.shape,o.shape,r,i,"float32");return e.makeTensorInfo(c,"float32",a)}const HL={kernelName:oc,backendName:"cpu",kernelFunc:Zy};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const By=Et(ei,n=>Math.max(0,n)),_L={kernelName:ei,backendName:"cpu",kernelFunc:By};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const Hy=Et(ni,n=>Math.min(Math.max(0,n),6)),UL={kernelName:ni,backendName:"cpu",kernelFunc:Hy};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function gl(n,t,e,s,o){if(e==="linear")return Qn({inputs:{x:t},backend:n});if(e==="relu")return By({inputs:{x:t},backend:n});if(e==="elu")return Oy({inputs:{x:t},backend:n});if(e==="relu6")return Hy({inputs:{x:t},backend:n});if(e==="prelu")return Zy({inputs:{x:t,alpha:s},backend:n});if(e==="leakyrelu")return Ky({inputs:{x:t},backend:n,attrs:{alpha:o}});if(e==="sigmoid")return Ny({inputs:{x:t},backend:n});throw new Error(`Activation ${e} has not been implemented for the CPU backend.`)}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function At(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{shape:r}=s,i=Z(o.shape),a=df(r,i),c=Z(a);v(i===c,()=>`The new shape (${a}) has ${c} elements and the old shape (${o.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`),e.incRef(o.dataId);const l=e.data.get(o.dataId);if(l.complexTensorInfos!=null){const u=l.complexTensorInfos.real,d=l.complexTensorInfos.imag;u.shape=a,d.shape=a}return{dataId:o.dataId,shape:a,dtype:o.dtype}}const YL={kernelName:ic,backendName:"cpu",kernelFunc:At};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function _y(n){const{inputs:t,backend:e,attrs:s}=n,{a:o,b:r}=t,{transposeA:i,transposeB:a}=s;it([o,r],"matMul");const c=o.shape.length,l=r.shape.length,u=i?o.shape[c-2]:o.shape[c-1],d=a?r.shape[l-1]:r.shape[l-2],h=i?o.shape[c-1]:o.shape[c-2],p=a?r.shape[l-2]:r.shape[l-1],f=o.shape.slice(0,-2),m=r.shape.slice(0,-2),g=Z(f),b=Z(m),I=gt(o.shape.slice(0,-2),r.shape.slice(0,-2)).concat([h,p]);v(u===d,()=>`Error in matMul: inner shapes (${u}) and (${d}) of Tensors with shapes ${o.shape} and ${r.shape} and transposeA=${i} and transposeB=${a} must match.`);const y=i?[g,u,h]:[g,h,u],w=a?[b,p,d]:[b,d,p],C=At({inputs:{x:o},backend:e,attrs:{shape:y}}),k=At({inputs:{x:r},backend:e,attrs:{shape:w}}),S=i?C.shape[1]:C.shape[2],T=i?C.shape[2]:C.shape[1],R=a?k.shape[1]:k.shape[2],L=Math.max(g,b),V=e.data.get(C.dataId).values,F=e.data.get(k.dataId).values,X=ct(C.shape),A=ct(k.shape),[P,B,K]=i?[X[0],1,X[1]]:[X[0],X[1],1],[H,U,Y]=a?[1,A[1],A[0]]:[A[1],1,A[0]],j=T*R,J=wt([L,T,R],C.dtype),nt=J.values,q=e.blockSize;for(let rt=0;rt<L;rt++){const lt=rt%g,ft=rt%b;for(let ht=0;ht<T;ht+=q){const xt=Math.min(ht+q,T);for(let yt=0;yt<R;yt+=q){const Dt=Math.min(yt+q,R);for(let Pt=0;Pt<S;Pt+=q){const jt=Math.min(Pt+q,S);for(let Ot=ht;Ot<xt;Ot++)for(let Mt=yt;Mt<Dt;Mt++){let Jt=0;for(let Ut=Pt;Ut<jt;Ut++){const hs=V[lt*P+Ot*B+Ut*K],ve=F[Ut*H+Mt*U+ft*Y];Jt+=hs*ve}nt[rt*j+(Ot*R+Mt)]+=Jt}}}}}return e.disposeIntermediateTensorInfo(C),e.disposeIntermediateTensorInfo(k),e.makeTensorInfo(I,J.dtype,J.values)}const QL={kernelName:Sa,backendName:"cpu",kernelFunc:_y};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function JL(n){const{inputs:t,backend:e,attrs:s}=n,{a:o,b:r,bias:i,preluActivationWeights:a}=t,{transposeA:c,transposeB:l,activation:u,leakyreluAlpha:d}=s;let h,p,f;const m=[];h=_y({inputs:{a:o,b:r},attrs:{transposeA:c,transposeB:l},backend:e}),i&&(p=ir({inputs:{a:h,b:i},backend:e}),m.push(h),h=p),u&&(f=gl(e,h,u,a,d),m.push(h),h=f);for(const b of m)e.disposeIntermediateTensorInfo(b);return h}const jL={kernelName:yc,backendName:"cpu",kernelFunc:JL};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const qL=Et(vr,n=>Math.acos(n)),tE={kernelName:vr,backendName:"cpu",kernelFunc:qL};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const eE=Et(Sr,n=>Math.acosh(n)),nE={kernelName:Sr,backendName:"cpu",kernelFunc:eE};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function sE(n){const{inputs:t,backend:e}=n,s=t;it(t,"addN");const o=s.map(a=>e.data.get(a.dataId).values),r=wt(s[0].shape,s[0].dtype),i=r.values;for(let a=0;a<s.length;a++){const c=o[a];for(let l=0;l<i.length;l++)i[l]+=c[l]}return e.makeTensorInfo(r.shape,r.dtype,r.values)}const oE={kernelName:nu,backendName:"cpu",kernelFunc:sE};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function rE(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r,keepDims:i}=s;it(o,"all");const a=It(r,o.shape);let c=a;const l=Yt(c,o.shape.length);let u=o;l!=null&&(u=Ke({inputs:{x:o},backend:e,attrs:{perm:l}}),c=ee(c.length,o.shape.length)),Ie("all",c,u.shape.length);const[d,h]=me(u.shape,c),p=Z(h),f=ke(Z(d),u.dtype),m=e.data.get(u.dataId).values;for(let b=0;b<f.length;++b){const x=b*p;let I=m[x];for(let y=0;y<p;++y){const w=m[x+y];I=I&&w}f[b]=I}l!=null&&e.disposeIntermediateTensorInfo(u);const g=e.makeTensorInfo(d,u.dtype,f);if(i){const b=re(d,a),x=At({inputs:{x:g},backend:e,attrs:{shape:b}});return e.disposeIntermediateTensorInfo(g),x}return g}const iE={kernelName:su,backendName:"cpu",kernelFunc:rE};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function aE(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r,keepDims:i}=s;it(o,"any");const a=It(r,o.shape);let c=a;const l=Yt(c,o.shape.length);let u=o;l!=null&&(u=Ke({inputs:{x:o},backend:e,attrs:{perm:l}}),c=ee(c.length,o.shape.length)),Ie("any",c,u.shape.length);const[d,h]=me(u.shape,c),p=Z(h),f=ke(Z(d),u.dtype),m=e.data.get(u.dataId).values;for(let b=0;b<f.length;++b){const x=b*p;let I=m[x];for(let y=0;y<p;++y){const w=m[x+y];I=I||w}f[b]=I}l!=null&&e.disposeIntermediateTensorInfo(u);const g=e.makeTensorInfo(d,u.dtype,f);if(i){const b=re(d,a),x=At({inputs:{x:g},backend:e,attrs:{shape:b}});return e.disposeIntermediateTensorInfo(g),x}return g}const cE={kernelName:ou,backendName:"cpu",kernelFunc:aE};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function lE(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r}=s;it(o,"argMax");let i=It(r,o.shape);const a=Yt(i,o.shape.length);let c=o;const l=[];a!=null&&(c=Ke({inputs:{x:o},backend:e,attrs:{perm:a}}),l.push(c),i=ee(i.length,c.shape.length)),i=[i[0]],Ie("argMax",i,c.shape.length);const[u,d]=me(c.shape,i),h=Z(u),p=ke(h,"int32"),f=Z(d),m=e.data.get(c.dataId).values;for(let g=0;g<p.length;++g){const b=g*f;let x=m[b],I=0;for(let y=0;y<f;++y){const w=m[b+y];w>x&&(x=w,I=y)}p[g]=I}return l.forEach(g=>e.disposeIntermediateTensorInfo(g)),e.makeTensorInfo(u,"int32",p)}const uE={kernelName:Ia,backendName:"cpu",kernelFunc:lE};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function dE(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r}=s;it(o,"argMin");let i=It(r,o.shape);const a=Yt(i,o.shape.length);let c=o;const l=[];a!=null&&(c=Ke({inputs:{x:o},backend:e,attrs:{perm:a}}),l.push(c),i=ee(i.length,c.shape.length)),i=[i[0]],Ie("argMin",i,c.shape.length);const[u,d]=me(c.shape,i),h=Z(u),p=ke(h,"int32"),f=Z(d),m=e.data.get(c.dataId).values;for(let g=0;g<p.length;++g){const b=g*f;let x=m[b],I=0;for(let y=0;y<f;++y){const w=m[b+y];w<x&&(x=w,I=y)}p[g]=I}return l.forEach(g=>e.disposeIntermediateTensorInfo(g)),e.makeTensorInfo(u,"int32",p)}const hE={kernelName:wa,backendName:"cpu",kernelFunc:dE};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const pE=Et(kr,n=>Math.asin(n)),fE={kernelName:kr,backendName:"cpu",kernelFunc:pE};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const mE=Et(Tr,n=>Math.asinh(n)),gE={kernelName:Tr,backendName:"cpu",kernelFunc:mE};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const bE=Et(Nr,n=>Math.atan(n)),xE={kernelName:Nr,backendName:"cpu",kernelFunc:bE};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const yE=oe((n,t)=>Math.atan2(n,t)),IE=pe($r,yE),wE={kernelName:$r,backendName:"cpu",kernelFunc:IE};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const CE=Et(Rr,n=>Math.atanh(n)),vE={kernelName:Rr,backendName:"cpu",kernelFunc:CE};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function mp(n,t,e,s,o,r){const i=o.strideHeight,a=o.strideWidth,c=o.dilationHeight,l=o.dilationWidth,u=o.effectiveFilterHeight,d=o.effectiveFilterWidth,h=o.padInfo.top,p=o.padInfo.left,f=r==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=wt(o.outShape,e),g=m.values,b=o.outShape[1]*o.outShape[2]*o.outShape[3],x=o.outShape[2]*o.outShape[3],I=o.outShape[3];for(let y=0;y<o.batchSize;++y){const w=y*b,C=y*s[0];for(let k=0;k<o.inChannels;++k)for(let S=0;S<o.outHeight;++S){const T=S*i-h,R=Math.max(0,T),L=Math.min(o.inHeight,u+T),V=w+S*x;for(let F=0;F<o.outWidth;++F){const X=F*a-p,A=Math.max(0,X),P=Math.min(o.inWidth,d+X);let B=f,K=0,H=0;for(let Y=R;Y<L;Y+=c){const j=C+Y*s[1];for(let J=A;J<P;J+=l){const nt=j+J*s[2],q=n[nt+k];r==="max"&&q>B?B=q:r==="avg"&&(K+=q,H++)}if(isNaN(B))break}const U=V+F*I+k;g[U]=r==="avg"?K/H:B}}}return m}function Uy(n,t,e,s,o=!1,r=!1){const i=wt(s.outShape,"int32"),a=s.strideHeight,c=s.strideWidth,l=s.dilationHeight,u=s.dilationWidth,d=s.effectiveFilterHeight,h=s.effectiveFilterWidth,p=s.padInfo.top,f=s.padInfo.left,m=wt(t,e,n);for(let g=0;g<s.batchSize;++g)for(let b=0;b<s.inChannels;++b)for(let x=0;x<s.outHeight;++x){const I=x*a-p;let y=I;for(;y<0;)y+=l;const w=Math.min(s.inHeight,d+I);for(let C=0;C<s.outWidth;++C){const k=C*c-f;let S=k;for(;S<0;)S+=u;const T=Math.min(s.inWidth,h+k);let R=Number.NEGATIVE_INFINITY,L=-1;for(let V=y;V<w;V+=l){const F=V-I;for(let X=S;X<T;X+=u){const A=X-k,P=m.get(g,V,X,b);P>R&&(R=P,o?L=r?((g*s.inHeight+V)*s.inWidth+X)*s.inChannels+b:(V*s.inWidth+X)*s.inChannels+b:L=F*h+A)}}i.set(L,g,x,C,b)}}return i}function Yy(n,t,e,s,o,r){const i=o.strideDepth,a=o.strideHeight,c=o.strideWidth,l=o.dilationDepth,u=o.dilationHeight,d=o.dilationWidth,h=o.effectiveFilterDepth,p=o.effectiveFilterHeight,f=o.effectiveFilterWidth,m=o.padInfo.front,g=o.padInfo.top,b=o.padInfo.left,x=r==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,I=wt(o.outShape,e),y=I.values,w=o.outShape[1]*o.outShape[2]*o.outShape[3]*o.outShape[4],C=o.outShape[2]*o.outShape[3]*o.outShape[4],k=o.outShape[3]*o.outShape[4],S=o.outShape[4];for(let T=0;T<o.batchSize;++T){const R=T*w,L=T*s[0];for(let V=0;V<o.inChannels;++V)for(let F=0;F<o.outDepth;++F){const X=F*i-m;let A=X;for(;A<0;)A+=l;const P=Math.min(o.inDepth,h+X),B=R+F*C;for(let K=0;K<o.outHeight;++K){const H=K*a-g;let U=H;for(;U<0;)U+=u;const Y=Math.min(o.inHeight,p+H),j=B+K*k;for(let J=0;J<o.outWidth;++J){const nt=J*c-b;let q=nt;for(;q<0;)q+=d;const rt=Math.min(o.inWidth,f+nt),lt=j+J*S;let ft=x,ht=0,xt=0;for(let Dt=A;Dt<P;Dt+=l){const Pt=L+Dt*s[1];for(let jt=U;jt<Y;jt+=u){const Ot=Pt+jt*s[2];for(let Mt=q;Mt<rt;Mt+=d){const Jt=Ot+Mt*s[3],Ut=n[Jt+V];if(r==="max"&&Ut>ft?ft=Ut:r==="avg"&&(ht+=Ut,xt++),isNaN(ft))break}if(isNaN(ft))break}if(isNaN(ft))break}const yt=lt+V;y[yt]=r==="avg"?ht/Math.max(xt,1):ft}}}}return I}function SE(n,t){const e=wt(t.outShape,"int32"),s=t.strideDepth,o=t.strideHeight,r=t.strideWidth,i=t.dilationDepth,a=t.dilationHeight,c=t.dilationWidth,l=t.effectiveFilterDepth,u=t.effectiveFilterHeight,d=t.effectiveFilterWidth,h=t.padInfo.front,p=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 b=0;b<t.outDepth;++b){const x=b*s-h;let I=x;for(;I<0;)I+=i;const y=Math.min(t.inDepth,l+x);for(let w=0;w<t.outHeight;++w){const C=w*o-p;let k=C;for(;k<0;)k+=a;const S=Math.min(t.inHeight,u+C);for(let T=0;T<t.outWidth;++T){const R=T*r-f;let L=R;for(;L<0;)L+=c;const V=Math.min(t.inWidth,d+R);let F=Number.NEGATIVE_INFINITY,X=-1;for(let A=I;A<y;A+=i){const P=A-x;for(let B=k;B<S;B+=a){const K=B-C;for(let H=L;H<V;H+=c){const U=H-R,Y=n.get(m,A,B,H,g);Y>=F&&(F=Y,X=P*u*d+K*u+U)}}}e.set(X,m,b,w,T,g)}}}return e}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function kE(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t;it(o,"avgPool");const{filterSize:r,strides:i,pad:a,dimRoundingMode:c}=s,l=1;v(Te(i,l),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${l}'`);const u=pn(o.shape,r,i,l,a,c);let d;if(u.filterWidth===1&&u.filterHeight===1&&Rt(u.inShape,u.outShape))d=Qn({inputs:{x:o},backend:e});else{const h=e.data.get(o.dataId).values,p=ct(o.shape),f=mp(h,o.shape,o.dtype,p,u,"avg");d=e.makeTensorInfo(u.outShape,o.dtype,f.values)}return d}const TE={kernelName:Ca,backendName:"cpu",kernelFunc:kE};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function NE(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{filterSize:r,strides:i,pad:a,dimRoundingMode:c,dataFormat:l}=s;it(o,"avgPool3d");const u=ss(o.shape,r,i,1,a,c,l),d=e.data.get(o.dataId).values,h=Yy(d,o.shape,o.dtype,ct(o.shape),u,"avg");return e.makeTensorInfo(h.shape,"float32",h.values)}const RE={kernelName:va,backendName:"cpu",kernelFunc:NE};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function $E(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,input:r}=t,{filterSize:i,strides:a,pad:c,dimRoundingMode:l}=s;it([o,r],"avgPool3DGrad");const u=ss(r.shape,i,a,1,c,l),d=u.strideDepth,h=u.strideHeight,p=u.strideWidth,f=u.filterDepth,m=u.filterHeight,g=u.filterWidth,b=u.dilationDepth,x=u.dilationHeight,I=u.dilationWidth,y=u.effectiveFilterDepth,w=u.effectiveFilterHeight,C=u.effectiveFilterWidth,k=y-1-u.padInfo.front,S=C-1-u.padInfo.left,T=w-1-u.padInfo.top,R=wt(r.shape,"float32"),L=1/(f*m*g),V=e.bufferSync(o);for(let F=0;F<u.batchSize;++F)for(let X=0;X<u.inChannels;++X)for(let A=0;A<u.inDepth;++A)for(let P=0;P<u.inHeight;++P)for(let B=0;B<u.inWidth;++B){const K=A-k,H=P-T,U=B-S;let Y=0;for(let j=0;j<y;j+=b){const J=(K+j)/d;if(!(J<0||J>=u.outDepth||Math.floor(J)!==J))for(let nt=0;nt<w;nt+=x){const q=(H+nt)/h;if(!(q<0||q>=u.outHeight||Math.floor(q)!==q))for(let rt=0;rt<C;rt+=I){const lt=(U+rt)/p;if(lt<0||lt>=u.outWidth||Math.floor(lt)!==lt)continue;const ft=V.get(F,J,q,lt,X);Y+=ft}}}R.set(Y*L,F,A,P,B,X)}return e.makeTensorInfo(R.shape,R.dtype,R.values)}const GE={kernelName:iu,backendName:"cpu",kernelFunc:$E};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function LE(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,input:r}=t,i=r;it([o,r],"avgPoolGrad");const{filterSize:a,strides:c,pad:l}=s,u=pn(i.shape,a,c,1,l),d=u.strideHeight,h=u.strideWidth,p=u.filterHeight,f=u.filterWidth,m=u.dilationHeight,g=u.dilationWidth,b=u.effectiveFilterHeight,x=u.effectiveFilterWidth,I=x-1-u.padInfo.left,y=b-1-u.padInfo.top,w=wt(i.shape,"float32"),C=1/(p*f),k=e.data.get(o.dataId).values,S=wt(o.shape,"float32",k);for(let T=0;T<u.batchSize;++T)for(let R=0;R<u.inChannels;++R)for(let L=0;L<u.inHeight;++L)for(let V=0;V<u.inWidth;++V){const F=L-y,X=V-I;let A=0;for(let P=0;P<b;P+=m){const B=(F+P)/d;if(!(B<0||B>=u.outHeight||Math.floor(B)!==B))for(let K=0;K<x;K+=g){const H=(X+K)/h;if(H<0||H>=u.outWidth||Math.floor(H)!==H)continue;const U=S.get(T,B,H,R);A+=U}}w.set(A*C,T,L,V,R)}return e.makeTensorInfo(w.shape,w.dtype,w.values)}const EE={kernelName:ru,backendName:"cpu",kernelFunc:LE};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function DE(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,scale:r,offset:i,mean:a,variance:c}=t;v(a.shape.length===c.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),v(i==null||a.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),v(r==null||a.shape.length===r.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),it([o,a,c,r,i],"batchNorm");let{varianceEpsilon:l}=s;l==null&&(l=.001);const u=e.data.get(o.dataId).values,d=e.data.get(a.dataId).values,h=e.data.get(c.dataId).values,p=r?e.data.get(r.dataId).values:new Float32Array([1]),f=i?e.data.get(i.dataId).values:new Float32Array([0]),m=new Float32Array(u.length),g=f.length,b=p.length,x=h.length,I=d.length;let y=0,w=0,C=0,k=0;for(let S=0;S<u.length;++S)m[S]=f[y++]+(u[S]-d[w++])*p[C++]/Math.sqrt(h[k++]+l),y>=g&&(y=0),w>=I&&(w=0),C>=b&&(C=0),k>=x&&(k=0);return e.makeTensorInfo(o.shape,o.dtype,m)}const WE={kernelName:Va,backendName:"cpu",kernelFunc:DE};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function ME(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{blockShape:r,crops:i}=s;it([o],"batchToSpaceND");const a=r.reduce((b,x)=>b*x),c=Mi(o.shape,r,a),l=Vi(c.length,r.length),u=Fi(o.shape,r,a),d=ah(i,r.length),h=ch(u,i,r.length),p=At({inputs:{x:o},backend:e,attrs:{shape:c}}),f=Ke({inputs:{x:p},backend:e,attrs:{perm:l}}),m=At({inputs:{x:f},backend:e,attrs:{shape:u}}),g=wo({inputs:{x:m},backend:e,attrs:{begin:d,size:h}});return e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(m),g}const VE={kernelName:ka,backendName:"cpu",kernelFunc:ME};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function FE(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,weights:r}=t,{size:i}=s,a=e.data.get(o.dataId).values,c=e.data.get(r.dataId).values,l=up(a,c,r.dtype,r.shape,i);return e.makeTensorInfo([i],r.dtype,l)}const zE={kernelName:au,backendName:"cpu",kernelFunc:FE};/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function XE(n){const{inputs:t,backend:e}=n,{s0:s,s1:o}=t,r=e.data.get(s.dataId).values,i=e.data.get(o.dataId).values,a=gt(Array.from(r),Array.from(i));return e.makeTensorInfo([a.length],"int32",Int32Array.from(a))}const AE={kernelName:xf,backendName:"cpu",kernelFunc:XE};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const PE=Et(Er,(n,t)=>{const e=t;return n>e.clipValueMax?e.clipValueMax:n<e.clipValueMin?e.clipValueMin:n}),OE={kernelName:Er,backendName:"cpu",kernelFunc:PE};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const KE={kernelName:Ta,backendName:"cpu",kernelFunc:n=>{const{x:t}=n.inputs,e=n.backend,s=new Float32Array(Z(t.shape)),o=e.data.get(t.dataId),r=o.complexTensorInfos.real,i=o.complexTensorInfos.imag,a=e.data.get(r.dataId).values,c=e.data.get(i.dataId).values;for(let l=0;l<a.length;l++){const u=a[l],d=c[l];s[l]=Math.hypot(u,d)}return e.makeOutput(s,t.shape,"float32")}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function ar(n){const{inputs:t,backend:e}=n,{input:s}=t,o=e.data.get(s.dataId).complexTensorInfos.imag,r=e.data.get(o.dataId).values;return e.makeTensorInfo(o.shape,o.dtype,r)}const ZE={kernelName:Nu,backendName:"cpu",kernelFunc:ar};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function cr(n){const{inputs:t,backend:e,attrs:s}=n,{axis:o}=s,r=It(o,t[0].shape)[0],i=t.map(m=>m.shape);oh(i,r);let a=Kn(t.map(m=>m.shape),r);if(Z(a)===0)return e.makeTensorInfo(a,t[0].dtype,[]);const c=t.filter(m=>Z(m.shape)>0);if(c.length===1)return Qn({inputs:{x:c[0]},backend:e});if(c[0].dtype==="complex64"){const m=c.map(y=>yo({inputs:{input:y},backend:e})),g=c.map(y=>ar({inputs:{input:y},backend:e})),b=cr({inputs:m,backend:e,attrs:{axis:r}}),x=cr({inputs:g,backend:e,attrs:{axis:r}}),I=Qe({inputs:{real:b,imag:x},backend:e});return m.forEach(y=>e.disposeIntermediateTensorInfo(y)),g.forEach(y=>e.disposeIntermediateTensorInfo(y)),e.disposeIntermediateTensorInfo(b),e.disposeIntermediateTensorInfo(x),I}const l=c.map(m=>{const b=[-1,Z(m.shape.slice(r))];return At({inputs:{x:m},backend:e,attrs:{shape:b}})}),u=l.map(m=>({vals:e.data.get(m.dataId).values,shape:m.shape}));a=Kn(l.map(m=>m.shape),1);const d=l[0].shape[0]===1,h=Qx(u,a,t[0].dtype,d),p=Kn(c.map(m=>m.shape),r),f=e.makeTensorInfo(p,t[0].dtype,h);return l.forEach(m=>e.disposeIntermediateTensorInfo(m)),f}const BE={kernelName:Na,backendName:"cpu",kernelFunc:cr};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Qy(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,filter:r}=t,{strides:i,pad:a,dataFormat:c,dilations:l,dimRoundingMode:u}=s;it([o,r],"conv2d");const d=os(c),h=ye(o.shape,r.shape,i,l,a,u,!1,d),p=h.filterHeight,f=h.filterWidth,m=h.dilationHeight,g=h.dilationWidth,b=h.padInfo.left,x=h.padInfo.top,I=h.dataFormat==="channelsLast",y=new xe(h.outShape,o.dtype),w=ct(o.shape),C=ct(r.shape),k=w[0],S=I?w[1]:w[2],T=I?w[2]:1,R=I?1:w[1],L=y.strides[0],V=I?y.strides[1]:y.strides[2],F=I?y.strides[2]:1,X=I?1:y.strides[1],A=e.data.get(o.dataId).values,P=e.data.get(r.dataId).values,B=y.values;for(let K=0;K<h.batchSize;++K){const H=K*k,U=K*L;for(let Y=0;Y<h.outHeight;++Y){const j=U+Y*V,J=Y*h.strideHeight-x;for(let nt=0;nt<p;++nt){const q=J+nt*m;if(q<0||q>=h.inHeight)continue;const rt=nt*C[0],lt=H+q*S;for(let ft=0;ft<h.outWidth;++ft){const ht=j+ft*F,xt=ft*h.strideWidth-b;for(let yt=0;yt<f;++yt){const Dt=xt+yt*g;if(Dt<0||Dt>=h.inWidth)continue;const Pt=rt+yt*C[1],jt=lt+Dt*T;let Ot=Pt;for(let Mt=0;Mt<h.inChannels;++Mt){const Jt=A[jt+Mt*R];for(let Ut=0;Ut<h.outChannels;++Ut)B[ht+Ut*X]+=Jt*P[Ot+Ut];Ot+=h.outChannels}}}}}}return e.makeTensorInfo(y.shape,y.dtype,B)}const HE={kernelName:Ra,backendName:"cpu",kernelFunc:Qy};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function _E(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,dy:r}=t,{strides:i,pad:a,dataFormat:c,dimRoundingMode:l,filterShape:u}=s;it([o,r],"conv2dBackpropFilter");const d=os(c),h=ye(o.shape,u,i,1,a,l,!1,d),{strideHeight:p,strideWidth:f,filterHeight:m,filterWidth:g}=h,b=h.dataFormat==="channelsLast",x=new xe(h.filterShape,"float32"),I=h.padInfo.left,y=h.padInfo.top,w=e.data.get(o.dataId).values,C=e.data.get(r.dataId).values,k=new xe(o.shape,o.dtype,w),S=new xe(r.shape,r.dtype,C);for(let T=0;T<m;++T){const R=Math.max(0,Math.ceil((y-T)/p)),L=Math.min(h.outHeight,(h.inHeight+y-T)/p);for(let V=0;V<g;++V){const F=Math.max(0,Math.ceil((I-V)/f)),X=Math.min(h.outWidth,(h.inWidth+I-V)/f);for(let A=0;A<h.inChannels;++A)for(let P=0;P<h.outChannels;++P){let B=0;for(let K=0;K<h.batchSize;++K)for(let H=R;H<L;++H){const U=T+H*p-y;for(let Y=F;Y<X;++Y){const j=V+Y*f-I;b?B+=k.get(K,U,j,A)*S.get(K,H,Y,P):B+=k.get(K,A,U,j)*S.get(K,P,H,Y)}}x.set(B,T,V,A,P)}}}return e.makeTensorInfo(x.shape,x.dtype,x.values)}const UE={kernelName:uu,backendName:"cpu",kernelFunc:_E};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function YE(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,filter:r}=t,{inputShape:i,strides:a,pad:c,dataFormat:l,dimRoundingMode:u}=s;it([o,r],"conv2dBackpropInput");const d=ct(r.shape),h=ct(o.shape);let p=os(l);const f=ye(i,r.shape,a,1,c,u,!1,p),m=new xe(f.inShape,"float32"),g=m.values,b=e.data.get(o.dataId).values,x=e.data.get(r.dataId).values,[I,y,w]=d,{batchSize:C,filterHeight:k,filterWidth:S,inChannels:T,inHeight:R,inWidth:L,outChannels:V,outHeight:F,outWidth:X,strideHeight:A,strideWidth:P}=f;p=f.dataFormat;const B=k-1-f.padInfo.top,K=S-1-f.padInfo.left,H=p==="channelsLast",U=m.strides[0],Y=H?m.strides[1]:m.strides[2],j=H?m.strides[2]:1,J=H?1:m.strides[1],nt=h[0],q=H?h[1]:h[2],rt=H?h[2]:1,lt=H?1:h[1];for(let ft=0;ft<C;++ft)for(let ht=0;ht<T;++ht)for(let xt=0;xt<R;++xt){const yt=xt-B,Dt=Math.max(0,Math.ceil(yt/A)),Pt=Math.min(F,(k+yt)/A);for(let jt=0;jt<L;++jt){const Ot=jt-K,Mt=Math.max(0,Math.ceil(Ot/P)),Jt=Math.min(X,(S+Ot)/P);let Ut=0;for(let ve=Dt;ve<Pt;++ve){const Xs=ve*A-yt;for(let cn=Mt;cn<Jt;++cn){const Lo=cn*P-Ot,Vn=nt*ft+q*ve+rt*cn,ps=I*(k-1-Xs)+y*(S-1-Lo)+w*ht;for(let As=0;As<V;++As){const Ps=b[Vn+lt*As],Os=x[ps+As];Ut+=Ps*Os}}}const hs=U*ft+Y*xt+j*jt+J*ht;g[hs]=Ut}}return e.makeTensorInfo(m.shape,m.dtype,m.values)}const QE={kernelName:$a,backendName:"cpu",kernelFunc:YE};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function JE(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,filter:r}=t,{strides:i,pad:a,dilations:c}=s;it([o,r],"conv3d");const l=ws(o.shape,r.shape,i,c,a),{filterDepth:u,filterHeight:d,filterWidth:h,dilationDepth:p,dilationHeight:f,dilationWidth:m,padInfo:g}=l,b=g.front,x=g.left,I=g.top,y=new xe(l.outShape,o.dtype),w=e.data.get(o.dataId).values,C=e.data.get(r.dataId).values,k=y.values,S=ct(o.shape),T=ct(r.shape);for(let R=0;R<l.batchSize;++R){const L=R*S[0],V=R*y.strides[0];for(let F=0;F<l.outDepth;++F){const X=V+F*y.strides[1],A=F*l.strideDepth-b;for(let P=0;P<u;++P){const B=A+P*p;if(B<0||B>=l.inDepth)continue;const K=P*T[0],H=L+B*S[1];for(let U=0;U<l.outHeight;++U){const Y=X+U*y.strides[2],j=U*l.strideHeight-I;for(let J=0;J<d;++J){const nt=j+J*f;if(nt<0||nt>=l.inHeight)continue;const q=K+J*T[1],rt=H+nt*S[2];for(let lt=0;lt<l.outWidth;++lt){const ft=Y+lt*l.outChannels,ht=lt*l.strideWidth-x;for(let xt=0;xt<h;++xt){const yt=ht+xt*m;if(yt<0||yt>=l.inWidth)continue;const Dt=q+xt*T[2],Pt=rt+yt*l.inChannels;let jt=Dt;for(let Ot=0;Ot<l.inChannels;++Ot){const Mt=w[Pt+Ot];for(let Jt=0;Jt<l.outChannels;++Jt)k[ft+Jt]+=Mt*C[jt+Jt];jt+=l.outChannels}}}}}}}}return e.makeTensorInfo(y.shape,y.dtype,y.values)}const jE={kernelName:Ga,backendName:"cpu",kernelFunc:JE};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function qE(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,dy:r}=t,{strides:i,pad:a,filterShape:c}=s;it([o,r],"conv3dBackpropFilterV2");const l=ct(o.shape),u=ct(r.shape),d=ws(o.shape,c,i,1,a),h=d.strideDepth,p=d.strideHeight,f=d.strideWidth,m=d.filterDepth,g=d.filterHeight,b=d.filterWidth,x=new xe(d.filterShape,"float32"),I=x.values,[y,w,C,k]=x.strides,S=e.data.get(r.dataId).values,[T,R,L,V]=u,F=e.data.get(o.dataId).values,[X,A,P,B]=l,K=d.padInfo.front,H=d.padInfo.left,U=d.padInfo.top;for(let Y=0;Y<m;++Y){const j=Math.max(0,Math.ceil((K-Y)/h)),J=Math.min(d.outDepth,(d.inDepth+K-Y)/h),nt=Y*y;for(let q=0;q<g;++q){const rt=Math.max(0,Math.ceil((U-q)/p)),lt=Math.min(d.outHeight,(d.inHeight+U-q)/p),ft=q*w+nt;for(let ht=0;ht<b;++ht){const xt=Math.max(0,Math.ceil((H-ht)/f)),yt=Math.min(d.outWidth,(d.inWidth+H-ht)/f),Dt=ht*C+ft;for(let Pt=0;Pt<d.inChannels;++Pt){const jt=Pt*k+Dt;for(let Ot=0;Ot<d.outChannels;++Ot){let Mt=0;for(let Jt=0;Jt<d.batchSize;++Jt){const Ut=Jt*X,hs=Jt*T;for(let ve=j;ve<J;++ve){const cn=(Y+ve*h-K)*A+Ut,Lo=ve*R+hs;for(let Vn=rt;Vn<lt;++Vn){const As=(q+Vn*p-U)*P+cn,Ps=Vn*L+Lo;for(let Os=xt;Os<yt;++Os){const af=(ht+Os*f-H)*B+As,cf=Os*V+Ps;Mt+=F[af+Pt]*S[cf+Ot]}}}}I[jt+Ot]=Mt}}}}}return e.makeTensorInfo(x.shape,x.dtype,x.values)}const t3={kernelName:du,backendName:"cpu",kernelFunc:qE};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function e3(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,filter:r}=t,{pad:i,strides:a,inputShape:c}=s;it([o],"conv3dBackpropInputV2");const l=ct(o.shape),u=ct(r.shape),d=ws(c,r.shape,a,1,i),h=new xe(d.inShape,"float32"),p=h.values,[f,m,g,b]=h.strides,x=e.data.get(o.dataId).values,[I,y,w,C]=l,k=e.data.get(r.dataId).values,[S,T,R,L]=u,{batchSize:V,filterDepth:F,filterHeight:X,filterWidth:A,inChannels:P,inDepth:B,inHeight:K,inWidth:H,outChannels:U,outDepth:Y,outHeight:j,outWidth:J,strideDepth:nt,strideHeight:q,strideWidth:rt}=d,lt=F-1-d.padInfo.front,ft=X-1-d.padInfo.top,ht=A-1-d.padInfo.left;for(let xt=0;xt<V;++xt)for(let yt=0;yt<P;++yt)for(let Dt=0;Dt<B;++Dt){const Pt=Dt-lt,jt=Math.max(0,Math.ceil(Pt/nt)),Ot=Math.min(Y,(F+Pt)/nt);for(let Mt=0;Mt<K;++Mt){const Jt=Mt-ft,Ut=Math.max(0,Math.ceil(Jt/q)),hs=Math.min(j,(X+Jt)/q);for(let ve=0;ve<H;++ve){const Xs=ve-ht,cn=Math.max(0,Math.ceil(Xs/rt)),Lo=Math.min(J,(A+Xs)/rt);let Vn=0;for(let ps=jt;ps<Ot;++ps){const As=ps*nt-Pt;for(let Ps=Ut;Ps<hs;++Ps){const Os=Ps*q-Jt;for(let ba=cn;ba<Lo;++ba){const af=ba*rt-Xs,cf=I*xt+y*ps+w*Ps+C*ba,B_=S*(F-1-As)+T*(X-1-Os)+R*(A-1-af)+L*yt;for(let Kl=0;Kl<U;++Kl){const H_=x[cf+Kl],__=k[B_+Kl];Vn+=H_*__}}}}p[f*xt+m*Dt+g*Mt+b*ve+yt]=Vn}}}return e.makeTensorInfo(h.shape,h.dtype,h.values)}const n3={kernelName:hu,backendName:"cpu",kernelFunc:e3};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const s3=Et(Dr,n=>Math.cos(n)),o3={kernelName:Dr,backendName:"cpu",kernelFunc:s3};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const r3=Et(Wr,n=>Math.cosh(n)),i3={kernelName:Wr,backendName:"cpu",kernelFunc:r3};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function a3(n){const{inputs:t,backend:e,attrs:s}=n,{image:o,boxes:r,boxInd:i}=t,{cropSize:a,method:c,extrapolationValue:l}=s,[u,d,h,p]=o.shape,f=r.shape[0],[m,g]=a,b=wt([f,m,g,p],"float32"),x=e.data.get(r.dataId).values,I=e.data.get(i.dataId).values,y=e.data.get(o.dataId).values,w=ct(o.shape),C=ct(b.shape);for(let k=0;k<f;k++){const S=k*4,T=x[S],R=x[S+1],L=x[S+2],V=x[S+3],F=I[k];if(F>=u)continue;const X=m>1?(L-T)*(d-1)/(m-1):0,A=g>1?(V-R)*(h-1)/(g-1):0;for(let P=0;P<m;P++){const B=m>1?T*(d-1)+P*X:.5*(T+L)*(d-1);if(B<0||B>d-1){for(let K=0;K<g;K++)for(let H=0;H<p;H++){const U=H+K*C[2]+P*C[1]+k*C[0];b.values[U]=l}continue}if(c==="bilinear"){const K=Math.floor(B),H=Math.ceil(B),U=B-K;for(let Y=0;Y<g;Y++){const j=g>1?R*(h-1)+Y*A:.5*(R+V)*(h-1);if(j<0||j>h-1){for(let rt=0;rt<p;rt++){const lt=rt+Y*C[2]+P*C[1]+k*C[0];b.values[lt]=l}continue}const J=Math.floor(j),nt=Math.ceil(j),q=j-J;for(let rt=0;rt<p;rt++){let lt=rt+J*w[2]+K*w[1]+F*w[0];const ft=y[lt];lt=rt+nt*w[2]+K*w[1]+F*w[0];const ht=y[lt];lt=rt+J*w[2]+H*w[1]+F*w[0];const xt=y[lt];lt=rt+nt*w[2]+H*w[1]+F*w[0];const yt=y[lt],Dt=ft+(ht-ft)*q,Pt=xt+(yt-xt)*q;lt=rt+Y*C[2]+P*C[1]+k*C[0],b.values[lt]=Dt+(Pt-Dt)*U}}}else for(let K=0;K<g;++K){const H=g>1?R*(h-1)+K*A:.5*(R+V)*(h-1);if(H<0||H>h-1){for(let j=0;j<p;j++){const J=j+K*C[2]+P*C[1]+k*C[0];b.values[J]=l}continue}const U=Math.round(H),Y=Math.round(B);for(let j=0;j<p;j++){const J=j+U*w[2]+Y*w[1]+F*w[0],nt=j+K*C[2]+P*C[1]+k*C[0];b.values[nt]=y[J]}}}}return e.makeTensorInfo(b.shape,b.dtype,b.values)}const c3={kernelName:fu,backendName:"cpu",kernelFunc:a3};/**
 * @license
 * Copyright 2022 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function l3(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r,exclusive:i,reverse:a}=s;it(o,"cumprod");const c=Yt([r],o.shape.length);let l=o;c!=null&&(l=Ke({inputs:{x:o},backend:e,attrs:{perm:c}}));const u=ee(1,o.shape.length)[0];if(u!==l.shape.length-1)throw new Error(`backend.cumprod in CPU expects an inner-most axis=${l.shape.length-1} but got axis=${u}`);const d=_e(l.dtype,"int32"),h=jl(Z(l.shape),d),p=e.data.get(l.dataId).values,f=l.shape[l.shape.length-1],m=a?(b,x)=>b+f-x-1:(b,x)=>b+x;for(let b=0;b<p.length;b+=f)for(let x=0;x<f;x++){const I=m(b,x);if(x===0)h[I]=i?1:p[I];else{const y=m(b,x-1);h[I]=i?p[y]*h[y]:p[I]*h[y]}}const g=e.makeTensorInfo(l.shape,d,h);if(c!=null){const b=Cs(c),x=Ke({inputs:{x:g},backend:e,attrs:{perm:b}});return e.disposeIntermediateTensorInfo(g),e.disposeIntermediateTensorInfo(l),x}return g}const u3={kernelName:pu,backendName:"cpu",kernelFunc:l3};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function d3(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r,exclusive:i,reverse:a}=s;it(o,"cumsum");const c=Yt([r],o.shape.length);let l=o;c!=null&&(l=Ke({inputs:{x:o},backend:e,attrs:{perm:c}}));const u=ee(1,o.shape.length)[0];if(u!==l.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${l.shape.length-1} but got axis=${u}`);const d=_e(l.dtype,"int32"),h=ke(Z(l.shape),d),p=e.data.get(l.dataId).values,f=l.shape[l.shape.length-1],m=a?(b,x)=>b+f-x-1:(b,x)=>b+x;for(let b=0;b<p.length;b+=f)for(let x=0;x<f;x++){const I=m(b,x);if(x===0)h[I]=i?0:p[I];else{const y=m(b,x-1);h[I]=i?p[y]+h[y]:p[I]+h[y]}}const g=e.makeTensorInfo(l.shape,d,h);if(c!=null){const b=Cs(c),x=Ke({inputs:{x:g},backend:e,attrs:{perm:b}});return e.disposeIntermediateTensorInfo(g),e.disposeIntermediateTensorInfo(l),x}return g}const h3={kernelName:La,backendName:"cpu",kernelFunc:d3};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function p3(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,weights:r}=t,{size:i,binaryOutput:a}=s;if(o.shape.length===1){const c=e.data.get(o.dataId).values,l=e.data.get(r.dataId).values,u=up(c,l,r.dtype,r.shape,i);return e.makeTensorInfo([i],r.dtype,u)}else if(o.shape.length===2){const c=e.bufferSync(o),l=e.bufferSync(r),u=_x(c,l,i,a);return e.makeTensorInfo(u.shape,r.dtype,u.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${o.shape.length}.`)}const f3={kernelName:mu,backendName:"cpu",kernelFunc:p3};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function m3(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{blockSize:r,dataFormat:i}=s;v(i==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`);const a=o.shape[0],c=o.shape[1],l=o.shape[2],u=o.shape[3],d=c*r,h=l*r,p=u/(r*r),f=e.data.get(o.dataId).values,m=new Float32Array(a*d*h*p);let g=0;for(let b=0;b<a;++b)for(let x=0;x<d;++x){const I=Math.floor(x/r),y=x%r;for(let w=0;w<h;++w){const C=Math.floor(w/r),k=w%r,S=(y*r+k)*p;for(let T=0;T<p;++T){const L=T+S+u*(C+l*(I+c*b));m[g++]=f[L]}}}return e.makeTensorInfo([a,d,h,p],o.dtype,m)}const g3={kernelName:gu,backendName:"cpu",kernelFunc:m3};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Jy(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,filter:r}=t,{strides:i,pad:a,dilations:c,dimRoundingMode:l}=s;it([o,r],"depthwiseConv2DNative");const u=ct(o.shape),d=ct(r.shape);let h=c;h==null&&(h=[1,1]),v(Te(i,h),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${h}'`);const p=ye(o.shape,r.shape,i,h,a,l,!0),{filterHeight:f,filterWidth:m,dilationHeight:g,dilationWidth:b,padInfo:x}=p,I=x.left,y=x.top,w=p.outChannels/p.inChannels,C=new xe(p.outShape,o.dtype),k=e.data.get(o.dataId).values,S=e.data.get(r.dataId).values,T=C.values;for(let R=0;R<p.batchSize;++R){const L=R*u[0],V=R*C.strides[0];for(let F=0;F<p.outHeight;++F){const X=V+F*C.strides[1],A=F*p.strideHeight-y;for(let P=0;P<f;++P){const B=A+P*g;if(B<0||B>=p.inHeight)continue;const K=P*d[0],H=L+B*u[1];for(let U=0;U<p.outWidth;++U){const Y=X+U*C.strides[2],j=U*p.strideWidth-I;for(let J=0;J<m;++J){const nt=j+J*b;if(nt<0||nt>=p.inWidth)continue;const q=K+J*d[1],rt=H+nt*p.inChannels;let lt=Y,ft=q;for(let ht=0;ht<p.inChannels;++ht){const xt=k[rt+ht];for(let yt=0;yt<w;++yt)T[lt+yt]+=xt*S[ft+yt];lt+=w,ft+=w}}}}}}return e.makeTensorInfo(C.shape,C.dtype,C.values)}const b3={kernelName:Ea,backendName:"cpu",kernelFunc:Jy};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function x3(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,dy:r}=t,{strides:i,dilations:a,pad:c,dimRoundingMode:l,filterShape:u}=s;it([o,r],"depthwiseConv2dNativeBackpropFilter");const d=ye(o.shape,u,i,a,c,l,!0),{strideHeight:h,strideWidth:p,filterHeight:f,filterWidth:m}=d,g=new xe(d.filterShape,"float32"),b=d.padInfo.left,x=d.padInfo.top,I=d.outChannels/d.inChannels,y=e.data.get(o.dataId).values,w=new xe(o.shape,o.dtype,y),C=e.data.get(r.dataId).values,k=new xe(r.shape,r.dtype,C);for(let S=0;S<f;++S){const T=Math.max(0,Math.ceil((x-S)/h)),R=Math.min(d.outHeight,(d.inHeight+x-S)/h);for(let L=0;L<m;++L){const V=Math.max(0,Math.ceil((b-L)/p)),F=Math.min(d.outWidth,(d.inWidth+b-L)/p);for(let X=0;X<d.outChannels;++X){const A=Math.trunc(X/I),P=X%I;let B=0;for(let K=0;K<d.batchSize;++K)for(let H=T;H<R;++H){const U=S+H*h-x;for(let Y=V;Y<F;++Y){const j=L+Y*p-b;B+=w.get(K,U,j,A)*k.get(K,H,Y,X)}}g.set(B,S,L,A,P)}}}return e.makeTensorInfo(g.shape,g.dtype,g.values)}const y3={kernelName:bu,backendName:"cpu",kernelFunc:x3};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function I3(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,filter:r}=t,{strides:i,dilations:a,pad:c,dimRoundingMode:l,inputShape:u}=s;it([o,r],"depthwiseConv2DNativeBackpropInput");const d=ct(o.shape),h=ct(r.shape),p=ye(u,r.shape,i,a,c,l,!0),f=new xe(p.inShape,"float32"),m=f.values,[g,b,x]=f.strides,I=e.data.get(o.dataId).values,[y,w,C]=d,k=e.data.get(r.dataId).values,[S,T,R]=h,{batchSize:L,filterHeight:V,filterWidth:F,inChannels:X,inHeight:A,inWidth:P,outChannels:B,outHeight:K,outWidth:H,strideHeight:U,strideWidth:Y}=p,j=V-1-p.padInfo.top,J=F-1-p.padInfo.left,nt=B/X;for(let q=0;q<L;++q)for(let rt=0;rt<X;++rt)for(let lt=0;lt<A;++lt){const ft=lt-j,ht=Math.max(0,Math.ceil(ft/U)),xt=Math.min(K,(V+ft)/U);for(let yt=0;yt<P;++yt){const Dt=yt-J,Pt=Math.max(0,Math.ceil(Dt/Y)),jt=Math.min(H,(F+Dt)/Y);let Ot=0;for(let Mt=ht;Mt<xt;++Mt){const Jt=Mt*U-ft;for(let Ut=Pt;Ut<jt;++Ut){const hs=Ut*Y-Dt,ve=y*q+w*Mt+C*Ut,Xs=S*(V-1-Jt)+T*(F-1-hs)+R*rt;for(let cn=0;cn<nt;++cn){const Lo=rt*nt+cn,Vn=I[ve+Lo],ps=k[Xs+cn];Ot+=Vn*ps}}}m[g*q+b*lt+x*yt+rt]=Ot}}return e.makeTensorInfo(f.shape,f.dtype,f.values)}const w3={kernelName:xu,backendName:"cpu",kernelFunc:I3};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function C3(n){const{inputs:t,backend:e}=n,{x:s}=t,o=Z(s.shape),r=e.data.get(s.dataId).values,i=wt([o,o],s.dtype),a=i.values;for(let l=0;l<r.length;l++)a[l*o+l]=r[l];const c=[...s.shape,...s.shape];return e.makeTensorInfo(c,i.dtype,i.values)}const v3={kernelName:yf,backendName:"cpu",kernelFunc:C3};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const S3={kernelName:Da,backendName:"cpu",kernelFunc:({inputs:n,backend:t,attrs:e})=>{const{x:s,filter:o}=n,{strides:r,pad:i,dilations:a}=e,c=t,l=c.data.get(s.dataId).values,u=s.shape.length,d=c.data.get(o.dataId).values,h=o.shape.length,{batchSize:p,inHeight:f,inWidth:m,inChannels:g,outHeight:b,outWidth:x,padInfo:I,strideHeight:y,strideWidth:w,filterHeight:C,filterWidth:k,dilationHeight:S,dilationWidth:T,outShape:R}=Si(s.shape,o.shape,r,i,"NHWC",a),L=Z(R),V=R.length,F=qt(s.dtype,L);for(let A=0;A<p;++A)for(let P=0;P<b;++P){const B=P*y-I.top;for(let K=0;K<x;++K){const H=K*w-I.left;for(let U=0;U<g;++U){let Y=Number.MIN_SAFE_INTEGER;for(let J=0;J<C;++J){const nt=B+J*S;if(nt>=0&&nt<f)for(let q=0;q<k;++q){const rt=H+q*T;if(rt>=0&&rt<m){const lt=Fn([A,nt,rt,U],u,ct(s.shape)),ft=Fn([J,q,U],h,ct(o.shape)),ht=l[lt]+d[ft];ht>Y&&(Y=ht)}}}const j=Fn([A,P,K,U],V,ct(R));F[j]=Y}}}return{dataId:c.write(Ys(F,s.dtype),R,s.dtype),shape:R,dtype:s.dtype}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const k3={kernelName:Iu,backendName:"cpu",kernelFunc:({inputs:n,backend:t,attrs:e})=>{const{x:s,filter:o,dy:r}=n,{strides:i,pad:a,dilations:c}=e,l=t,u=vn(s.shape,l.data.get(s.dataId).values),d=vn(o.shape,l.data.get(o.dataId).values),{batchSize:h,inHeight:p,inWidth:f,inChannels:m,outHeight:g,outWidth:b,padInfo:x,strideHeight:I,strideWidth:y,filterHeight:w,filterWidth:C,dilationHeight:k,dilationWidth:S,outShape:T}=Si(s.shape,o.shape,i,a,"NHWC",c);v(r.rank===T.length,()=>`Error in ${Iu}, dy must have the same rank as output ${T.length}, but got ${r.rank}`);const R=vn(T,l.data.get(r.dataId).values),L=ff(o.shape,o.dtype);for(let F=0;F<h;++F)for(let X=0;X<g;++X){const A=X*I-x.top;for(let P=0;P<b;++P){const B=P*y-x.left;for(let K=0;K<m;++K){let H=Number.MIN_SAFE_INTEGER,U=0,Y=0;for(let j=0;j<w;++j){const J=A+j*k;if(J>=0&&J<p)for(let nt=0;nt<C;++nt){const q=B+nt*S;if(q>=0&&q<f){const rt=u[F][J][q][K]+d[j][nt][K];rt>H&&(H=rt,U=j,Y=nt)}}}L[U][Y][K]+=R[F][X][P][K]}}}return{dataId:l.write(Ys(L,s.dtype),o.shape,o.dtype),shape:o.shape,dtype:o.dtype}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const T3={kernelName:yu,backendName:"cpu",kernelFunc:({inputs:n,backend:t,attrs:e})=>{const{x:s,filter:o,dy:r}=n,{strides:i,pad:a,dilations:c}=e,l=t,u=vn(s.shape,l.data.get(s.dataId).values),d=vn(o.shape,l.data.get(o.dataId).values),{batchSize:h,inHeight:p,inWidth:f,inChannels:m,outHeight:g,outWidth:b,padInfo:x,strideHeight:I,strideWidth:y,filterHeight:w,filterWidth:C,dilationHeight:k,dilationWidth:S,outShape:T}=Si(s.shape,o.shape,i,a,"NHWC",c);v(r.rank===T.length,()=>`Error in ${yu}, dy must have the same rank as output ${T.length}, but got ${r.rank}`);const R=vn(T,l.data.get(r.dataId).values),L=ff(s.shape,s.dtype);for(let F=0;F<h;++F)for(let X=0;X<g;++X){const A=X*I-x.top;for(let P=0;P<b;++P){const B=P*y-x.left;for(let K=0;K<m;++K){let H=Number.MIN_SAFE_INTEGER,U=A<0?0:A,Y=B<0?0:B;for(let j=0;j<w;++j){const J=A+j*k;if(J>=0&&J<p)for(let nt=0;nt<C;++nt){const q=B+nt*S;if(q>=0&&q<f){const rt=u[F][J][q][K]+d[j][nt][K];rt>H&&(H=rt,U=J,Y=q)}}}L[F][U][Y][K]+=R[F][X][P][K]}}}return{dataId:l.write(Ys(L,s.dtype),s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}};/**
 * @license
 * Copyright 2023 Google LLC.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function N3(n){const{inputs:t,backend:e,attrs:s}=n,{image:o}=t,{canvas:r,options:i}=s,{contextOptions:a,imageOptions:c}=i||{},l=(c==null?void 0:c.alpha)||1,u=(a==null?void 0:a.contextType)||"2d";if(u!=="2d")throw new Error(`Context type ${a.contextType} is not supported by the CPU backend.`);const d=r.getContext(u,(a==null?void 0:a.contextAttributes)||{});if(d==null)throw new Error(`Could not get the context with ${u} type.`);const[h,p]=o.shape.slice(0,2),f=o.shape.length===2?1:o.shape[2],m=e.data.get(o.dataId).values,g=o.dtype==="float32"?255:1,b=new Uint8ClampedArray(p*h*4);for(let I=0;I<h*p;++I){const y=[0,0,0,255*l];for(let C=0;C<f;C++){const k=m[I*f+C];if(o.dtype==="float32"){if(k<0||k>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${k}.`)}else if(o.dtype==="int32"&&(k<0||k>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${k}.`);f===1?(y[0]=k*g,y[1]=k*g,y[2]=k*g):y[C]=k*g}const w=I*4;b[w+0]=Math.round(y[0]),b[w+1]=Math.round(y[1]),b[w+2]=Math.round(y[2]),b[w+3]=Math.round(y[3])}r.width=p,r.height=h;const x=new ImageData(b,p,h);return d.putImageData(x,0,0),o}const R3={kernelName:hw,backendName:"cpu",kernelFunc:N3};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function ea(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r,keepDims:i}=s;it(o,"sum");let a;o.dtype==="bool"?a=Ws({inputs:{x:o},backend:e,attrs:{dtype:"int32"}}):a=Qn({inputs:{x:o},backend:e});const c=a.shape.length,l=It(r,a.shape),u=Yt(l,c);let d=l,h=a;u!=null&&(h=Ke({inputs:{x:a},backend:e,attrs:{perm:u}}),d=ee(d.length,c)),Ie("sum",d,h.shape.length);const[p,f]=me(h.shape,d),m=_e(h.dtype,"int32");let g=pl(e,p,m);const b=Z(f),x=e.data.get(g.dataId).values,I=e.data.get(h.dataId).values;for(let y=0;y<x.length;++y){const w=y*b;let C=0;for(let k=0;k<b;++k)C+=I[w+k];x[y]=C}if(i){const y=re(g.shape,l),w=g;g=At({inputs:{x:g},backend:e,attrs:{shape:y}}),e.disposeIntermediateTensorInfo(w)}return e.disposeIntermediateTensorInfo(a),u!=null&&e.disposeIntermediateTensorInfo(h),g}const $3={kernelName:hc,backendName:"cpu",kernelFunc:ea};/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function G3(n){const{inputs:t,backend:e,attrs:s}=n,{equation:o}=s,r=t,{allDims:i,summedDims:a,idDims:c}=bh(o,r.length);yh(i.length,c,r);const{path:l,steps:u}=Ih(a,c),d=u.length;let h=null,p=i.length;const f=[];for(let m=0;m<d;++m){for(const g of u[m]){const{permutationIndices:b,expandDims:x}=xh(p,c[g]);let I;wh(b)?I=r[g]:(I=Ke({inputs:{x:r[g]},backend:e,attrs:{perm:b}}),f.push(I));const y=I.shape.slice();for(let w=0;w<x.length;++w)y.splice(x[w],0,1);Rt(I.shape,y)||(I=At({inputs:{x:I},backend:e,attrs:{shape:y}}),f.push(I)),h===null?h=I:(h=fl({inputs:{a:I,b:h},backend:e}),f.push(h))}m<d-1&&(l[m]>=0&&(h=ea({inputs:{x:h},backend:e,attrs:{axis:l[m]-(i.length-p),keepDims:!1}}),f.push(h)),p--)}for(const m of f)m!==h&&e.disposeIntermediateTensorInfo(m);return h}const L3={kernelName:wu,backendName:"cpu",kernelFunc:G3};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function E3(n){const{inputs:t,backend:e}=n,{dy:s,y:o}=t;it([s,o],"eluGrad");const r=new Float32Array(Z(o.shape)),i=e.data.get(o.dataId).values,a=e.data.get(s.dataId).values;for(let c=0;c<i.length;++c){const l=i[c];l>=0?r[c]=a[c]:r[c]=a[c]*(l+1)}return e.makeTensorInfo(o.shape,"float32",r)}const D3={kernelName:Cu,backendName:"cpu",kernelFunc:E3};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const W3=lh,M3=uh,V3=dh,F3=hh,z3=ph,X3=fh,A3=Et(Fr,n=>{const t=Math.sign(n),e=Math.abs(n),s=1/(1+W3*e);return t*(1-((((X3*s+z3)*s+F3)*s+V3)*s+M3)*s*Math.exp(-e*e))}),P3={kernelName:Fr,backendName:"cpu",kernelFunc:A3};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function bl(n){const{inputs:t,backend:e,attrs:s}=n,{input:o}=t,{dim:r}=s,i=o.shape.length,a=o.shape.slice();let c=r;return r<0&&(v(-(i+1)<=r,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),c=i+r+1),a.splice(c,0,1),At({inputs:{x:o},backend:e,attrs:{shape:a}})}const O3={kernelName:Ma,backendName:"cpu",kernelFunc:bl};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const K3=oe((n,t)=>n/t),gp=pe(Mr,K3),bp={kernelName:Mr,backendName:"cpu",kernelFunc:gp};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function jy(n,t,e){const s=n.shape,o=s[0],r=s[1],i=e.data.get(n.dataId),a=i.complexTensorInfos.real,c=i.complexTensorInfos.imag,l=[o,r],u=Z(l),d=Se("float32",u),h=Se("float32",u);for(let g=0;g<o;g++){const b=wo({inputs:{x:a},backend:e,attrs:{begin:[g,0],size:[1,r]}}),x=wo({inputs:{x:c},backend:e,attrs:{begin:[g,0],size:[1,r]}}),I=Qe({inputs:{real:b,imag:x},backend:e}),{real:y,imag:w}=Z3(I,t,e),C=as(y,w);for(let k=0;k<r;k++){const S=mh(C,k);d[g*r+k]=S.real,h[g*r+k]=S.imag}e.disposeIntermediateTensorInfo(b),e.disposeIntermediateTensorInfo(x),e.disposeIntermediateTensorInfo(I)}const p=e.makeTensorInfo(l,"float32",d),f=e.makeTensorInfo(l,"float32",h),m=Qe({inputs:{real:p,imag:f},backend:e});return e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(f),m}function Z3(n,t,e){const s=Z(n.shape),o=e.data.get(n.dataId),r=e.data.get(o.complexTensorInfos.real.dataId).values,i=e.data.get(o.complexTensorInfos.imag.dataId).values;if(B3(s)){const a=xp(r,i,s,t,e),c=[n.shape[0],n.shape[1]];if(t){const l=e.makeTensorInfo(c,"float32",a.real),u=e.makeTensorInfo(c,"float32",a.imag),d=e.makeTensorInfo([],"float32",gs(s,"float32")),h=Qn({inputs:{x:d},backend:e}),p=bp.kernelFunc({inputs:{a:l,b:d},backend:e}),f=bp.kernelFunc({inputs:{a:u,b:h},backend:e}),m=e.data.get(p.dataId).values,g=e.data.get(f.dataId).values;return e.disposeIntermediateTensorInfo(l),e.disposeIntermediateTensorInfo(u),e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(f),{real:m,imag:g}}return a}else{const a=as(r,i),c=H3(a,s,t);return Gg(c)}}function B3(n){return(n&n-1)===0}function xp(n,t,e,s,o){if(e===1)return{real:n,imag:t};const r=as(n,t),i=e/2,a=Lg(r),c=a.real,l=a.imag,u=[c.length],d=o.makeTensorInfo(u,"float32",c),h=o.makeTensorInfo(u,"float32",l),p=Qe({inputs:{real:d,imag:h},backend:o}),f=Eg(r),m=f.real,g=f.imag,b=[m.length],x=o.makeTensorInfo(b,"float32",m),I=o.makeTensorInfo(b,"float32",g),y=Qe({inputs:{real:x,imag:I},backend:o}),w=xp(c,l,i,s,o),C=w.real,k=w.imag,S=[C.length],T=o.makeTensorInfo(S,"float32",C),R=o.makeTensorInfo(S,"float32",k),L=Qe({inputs:{real:T,imag:R},backend:o}),V=xp(m,g,i,s,o),F=V.real,X=V.imag,A=[F.length],P=o.makeTensorInfo(A,"float32",F),B=o.makeTensorInfo(A,"float32",X),K=Qe({inputs:{real:P,imag:B},backend:o}),H=Wg(e,s),U=[H.real.length],Y=o.makeTensorInfo(U,"float32",H.real),j=o.makeTensorInfo(U,"float32",H.imag),J=Qe({inputs:{real:Y,imag:j},backend:o}),nt=fl({inputs:{a:J,b:K},backend:o}),q=ir({inputs:{a:L,b:nt},backend:o}),rt=fp({inputs:{a:L,b:nt},backend:o}),lt=yo({inputs:{input:q},backend:o}),ft=yo({inputs:{input:rt},backend:o}),ht=ar({inputs:{input:q},backend:o}),xt=ar({inputs:{input:rt},backend:o}),yt=cr({inputs:[lt,ft],backend:o,attrs:{axis:0}}),Dt=cr({inputs:[ht,xt],backend:o,attrs:{axis:0}}),Pt=o.data.get(yt.dataId).values,jt=o.data.get(Dt.dataId).values;return o.disposeIntermediateTensorInfo(d),o.disposeIntermediateTensorInfo(h),o.disposeIntermediateTensorInfo(p),o.disposeIntermediateTensorInfo(x),o.disposeIntermediateTensorInfo(I),o.disposeIntermediateTensorInfo(y),o.disposeIntermediateTensorInfo(T),o.disposeIntermediateTensorInfo(R),o.disposeIntermediateTensorInfo(L),o.disposeIntermediateTensorInfo(P),o.disposeIntermediateTensorInfo(B),o.disposeIntermediateTensorInfo(K),o.disposeIntermediateTensorInfo(Y),o.disposeIntermediateTensorInfo(j),o.disposeIntermediateTensorInfo(J),o.disposeIntermediateTensorInfo(nt),o.disposeIntermediateTensorInfo(q),o.disposeIntermediateTensorInfo(rt),o.disposeIntermediateTensorInfo(lt),o.disposeIntermediateTensorInfo(ht),o.disposeIntermediateTensorInfo(ft),o.disposeIntermediateTensorInfo(xt),o.disposeIntermediateTensorInfo(yt),o.disposeIntermediateTensorInfo(Dt),{real:Pt,imag:jt}}function H3(n,t,e){const s=new Float32Array(t*2);for(let o=0;o<t;o++){let r=0,i=0;for(let a=0;a<t;a++){const c=Mg(o*a,t,e),l=mh(n,a);r+=l.real*c.real-l.imag*c.imag,i+=l.real*c.imag+l.imag*c.real}e&&(r/=t,i/=t),Dg(s,r,i,o)}return s}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function _3(n){const{inputs:t,backend:e}=n,{input:s}=t,o=Z(s.shape),r=s.shape[s.shape.length-1],i=o/r,a=At({inputs:{x:s},backend:e,attrs:{shape:[i,r]}}),c=jy(a,!1,e),l=At({inputs:{x:c},backend:e,attrs:{shape:s.shape}});return e.disposeIntermediateTensorInfo(a),e.disposeIntermediateTensorInfo(c),l}const U3={kernelName:vu,backendName:"cpu",kernelFunc:_3};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function yp(n){const{backend:t,attrs:e}=n,{shape:s,value:o,dtype:r}=e,i=r||Mo(o),a=qt(i,Z(s));return Q3(a,o,i),t.makeTensorInfo(s,i,a)}const Y3={kernelName:Su,backendName:"cpu",kernelFunc:yp};function Q3(n,t,e){n.fill(t)}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const J3={kernelName:ku,backendName:"cpu",kernelFunc:({inputs:n,attrs:t,backend:e})=>{const{image:s}=n,o=e,r=Se(s.dtype,Z(s.shape)),[i,a,c,l]=s.shape,u=o.data.get(s.dataId).values;for(let h=0;h<i;h++){const p=h*c*a*l;for(let f=0;f<a;f++){const m=f*(c*l);for(let g=0;g<c;g++){const b=g*l;for(let x=0;x<l;x++){const I=Math.round(c-g-1),y=p+m+b+x;let w=u[y];if(I>=0&&I<c){const C=I*l,k=p+m+C+x;w=u[k]}r[y]=w}}}}return{dataId:o.write(r,s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function j3(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,filter:r,bias:i,preluActivationWeights:a}=t,{strides:c,pad:l,dataFormat:u,dilations:d,dimRoundingMode:h,activation:p,leakyreluAlpha:f}=s;let m=Qy({inputs:{x:o,filter:r},backend:e,attrs:{strides:c,pad:l,dataFormat:u,dilations:d,dimRoundingMode:h}});if(i){const g=m;if(u==="NCHW"&&i.shape.length===1&&i.shape[0]!==1){const b=At({inputs:{x:i},backend:e,attrs:{shape:[i.shape[0],1,1]}});m=ir({inputs:{a:m,b},backend:e}),e.disposeIntermediateTensorInfo(b)}else m=ir({inputs:{a:m,b:i},backend:e});e.disposeIntermediateTensorInfo(g)}if(p){const g=m;if(u==="NCHW"&&p==="prelu"&&a.shape.length===1&&a.shape[0]!==1){const b=At({inputs:{x:a},backend:e,attrs:{shape:[a.shape[0],1,1]}});m=gl(e,m,p,b,f),e.disposeIntermediateTensorInfo(b)}else m=gl(e,m,p,a,f);e.disposeIntermediateTensorInfo(g)}return m}const q3={kernelName:Ic,backendName:"cpu",kernelFunc:j3};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function tD(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,filter:r,bias:i,preluActivationWeights:a}=t,{strides:c,pad:l,dataFormat:u,dilations:d,dimRoundingMode:h,activation:p,leakyreluAlpha:f}=s;let m=Jy({inputs:{x:o,filter:r},backend:e,attrs:{strides:c,pad:l,dataFormat:u,dilations:d,dimRoundingMode:h}});if(i){const g=m;m=ir({inputs:{a:m,b:i},backend:e}),e.disposeIntermediateTensorInfo(g)}if(p){const g=m;m=gl(e,m,p,a,f),e.disposeIntermediateTensorInfo(g)}return m}const eD={kernelName:zf,backendName:"cpu",kernelFunc:tD};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function nD(n){const{inputs:t,backend:e}=n,{params:s,indices:o}=t,r=Z(s.shape),i=o.shape,a=i[i.length-1],[c,l,u,d]=Jd(s,o);if(l===0)return e.makeTensorInfo(c,s.dtype,[]);const h=e.data.get(o.dataId).values,p=e.bufferSync(s),f=oy(h,p,s.dtype,l,a,u,d,s.shape,r);return e.makeTensorInfo(c,s.dtype,f.values)}const sD={kernelName:If,backendName:"cpu",kernelFunc:nD};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function oD(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,indices:r}=t,{axis:i,batchDims:a}=s;it([o,r],"gatherV2");const c=It(i,o.shape)[0],l=e.data.get(r.dataId).values,u=o.shape[c];for(let y=0;y<l.length;++y){const w=l[y];v(w<=u-1&&w>=0,()=>`GatherV2: the index value ${w} is not in [0, ${u-1}]`)}let d=a;a==null&&(d=0);const h=Z(r.shape),p=Sh(o,r,c,d),f=At({inputs:{x:o},backend:e,attrs:{shape:[p.batchSize,p.outerSize,p.dimSize,p.sliceSize]}}),m=At({inputs:{x:r},backend:e,attrs:{shape:[p.batchSize,h/p.batchSize]}}),g=[p.batchSize,p.outerSize,h/p.batchSize,p.sliceSize],b=e.bufferSync(m),x=e.bufferSync(f),I=ry(x,b,g);return e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(m),e.makeTensorInfo(p.outputShape,I.dtype,I.values)}const rD={kernelName:Fa,backendName:"cpu",kernelFunc:oD};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function iD(n){const{inputs:t,backend:e}=n,{input:s}=t,o=Z(s.shape),r=s.shape[s.shape.length-1],i=o/r,a=At({inputs:{x:s},backend:e,attrs:{shape:[i,r]}}),c=jy(a,!0,e),l=At({inputs:{x:c},backend:e,attrs:{shape:s.shape}});return e.disposeIntermediateTensorInfo(a),e.disposeIntermediateTensorInfo(c),l}const aD={kernelName:Tu,backendName:"cpu",kernelFunc:iD};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const cD=Et(Zr,n=>Number.isFinite(n)?1:0,"bool"),lD={kernelName:Zr,backendName:"cpu",kernelFunc:cD};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const uD=Et(Br,n=>Math.abs(n)===1/0?1:0,"bool"),dD={kernelName:Br,backendName:"cpu",kernelFunc:uD};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const hD=Et(Hr,n=>Number.isNaN(n)?1:0,"bool"),pD={kernelName:Hr,backendName:"cpu",kernelFunc:hD};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function fD(n){const{backend:t,attrs:e}=n,{start:s,stop:o,num:r}=e,i=uy(s,o,r);return t.makeTensorInfo([i.length],"float32",i)}const mD={kernelName:wf,backendName:"cpu",kernelFunc:fD};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const gD=Et(Ur,n=>Math.log1p(n)),bD={kernelName:Ur,backendName:"cpu",kernelFunc:gD};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const xD=oe((n,t)=>n&&t),yD=pe(Oa,xD,null,"bool"),ID={kernelName:Oa,backendName:"cpu",kernelFunc:yD};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const wD=Et(Ka,n=>n?0:1,"bool"),CD={kernelName:Ka,backendName:"cpu",kernelFunc:wD};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const vD=oe((n,t)=>n||t),SD=pe(Za,vD,null,"bool"),kD={kernelName:Za,backendName:"cpu",kernelFunc:SD};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function TD(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{depthRadius:r,bias:i,alpha:a,beta:c}=s;it(o,"LRN");const l=o.shape[3],u=l-1,d=e.data.get(o.dataId).values,h=Z(o.shape),p=new Float32Array(h);function f(m){const g=m%l;let b=m-g+Math.max(0,g-r);const x=m-g+Math.min(g+r,u);let I=0;for(;b<=x;b++){const y=d[b];I+=y*y}return I}for(let m=0;m<h;m++){const g=f(m),b=d[m]*Math.pow(i+a*g,-c);p[m]=b}return e.makeTensorInfo(o.shape,o.dtype,p)}const ND={kernelName:Ba,backendName:"cpu",kernelFunc:TD};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function RD(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,y:r,dy:i}=t,{depthRadius:a,bias:c,alpha:l,beta:u}=s;it(i,"LRNGrad");const d=Z(i.shape),h=i.shape[3],p=e.data.get(i.dataId).values,f=e.data.get(o.dataId).values,m=e.data.get(r.dataId).values,g=new Float32Array(d),b=d;for(let x=0;x<b;x++){const I=x%h,y=x-I+Math.max(0,I-a),w=x-I+Math.min(h,I+a+1);let C=0;for(let k=y;k<w;k++)C+=Math.pow(f[k],2);C=l*C+c;for(let k=y;k<w;k++){let S=-2*l*u*f[k]*m[x]/C;x===k&&(S+=Math.pow(C,-u)),S*=p[x],g[k]+=S}}return e.makeTensorInfo(i.shape,o.dtype,g)}const $D={kernelName:Ru,backendName:"cpu",kernelFunc:RD};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function qy(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{reductionIndices:r,keepDims:i}=s,a=e;let c=o.shape;const l=c.length,u=It(r,c);let d=u;const h=Yt(d,l);let p=a.data.get(o.dataId).values;if(h!=null){const y=new Array(l);for(let w=0;w<y.length;w++)y[w]=c[h[w]];p=hp(p,c,o.dtype,h,y),d=ee(d.length,l),c=y}it(o,"max"),Ie("max",d,l);const[f,m]=me(c,d),g=Z(m),b=hy(p,g,f,o.dtype),x=a.write(b,f,o.dtype);let I=f;return i&&(I=re(f,u)),{dataId:x,shape:I,dtype:o.dtype}}const GD={kernelName:Ha,backendName:"cpu",kernelFunc:qy};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function LD(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t;it(o,"maxPool");const{filterSize:r,strides:i,pad:a,dimRoundingMode:c}=s,l=1;v(Te(i,l),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${l}'`);const u=pn(o.shape,r,i,l,a,c);let d;if(u.filterWidth===1&&u.filterHeight===1&&Rt(u.inShape,u.outShape))d=Qn({inputs:{x:o},backend:e});else{const h=e.data.get(o.dataId).values,p=ct(o.shape),f=mp(h,o.shape,o.dtype,p,u,"max");d=e.makeTensorInfo(u.outShape,o.dtype,f.values)}return d}const ED={kernelName:_a,backendName:"cpu",kernelFunc:LD};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function DD(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{filterSize:r,strides:i,pad:a,dimRoundingMode:c,dataFormat:l}=s;it(o,"maxPool3d");const u=ss(o.shape,r,i,1,a,c,l),d=e.data.get(o.dataId).values,h=Yy(d,o.shape,o.dtype,ct(o.shape),u,"max");return e.makeTensorInfo(h.shape,"float32",h.values)}const WD={kernelName:Ua,backendName:"cpu",kernelFunc:DD};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function MD(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,input:r}=t,{filterSize:i,strides:a,pad:c,dimRoundingMode:l}=s;it([o,r],"maxPool3DGrad");const u=ss(r.shape,i,a,1,c,l),d=e.bufferSync(r),h=SE(d,u),p=u.strideDepth,f=u.strideHeight,m=u.strideWidth,g=u.dilationDepth,b=u.dilationHeight,x=u.dilationWidth,I=u.effectiveFilterDepth,y=u.effectiveFilterHeight,w=u.effectiveFilterWidth,C=I-1-u.padInfo.front,k=w-1-u.padInfo.left,S=y-1-u.padInfo.top,T=wt(r.shape,"float32"),R=e.bufferSync(o);for(let L=0;L<u.batchSize;++L)for(let V=0;V<u.inChannels;++V)for(let F=0;F<u.inDepth;++F)for(let X=0;X<u.inHeight;++X)for(let A=0;A<u.inWidth;++A){const P=F-C,B=X-S,K=A-k;let H=0;for(let U=0;U<I;U+=g){const Y=(P+U)/p;if(!(Y<0||Y>=u.outDepth||Math.floor(Y)!==Y))for(let j=0;j<y;j+=b){const J=(B+j)/f;if(!(J<0||J>=u.outHeight||Math.floor(J)!==J))for(let nt=0;nt<w;nt+=x){const q=(K+nt)/m;if(q<0||q>=u.outWidth||Math.floor(q)!==q)continue;const rt=I*y*w-1-h.get(L,Y,J,q,V),lt=U*y*w+j*w+nt,ft=rt===lt?1:0;if(ft===0)continue;const ht=R.get(L,Y,J,q,V);H+=ht*ft}}}T.set(H,L,F,X,A,V)}return e.makeTensorInfo(T.shape,T.dtype,T.values)}const VD={kernelName:Gu,backendName:"cpu",kernelFunc:MD};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function FD(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,input:r,output:i}=t,a=r;it([r,i],"maxPoolGrad");const{filterSize:c,strides:l,pad:u,dimRoundingMode:d}=s,h=pn(a.shape,c,l,1,u,d),p=e.data.get(a.dataId).values,f=wt(h.outShape,a.dtype,Uy(p,a.shape,a.dtype,h).values),m=h.strideHeight,g=h.strideWidth,b=h.dilationHeight,x=h.dilationWidth,I=h.effectiveFilterHeight,y=h.effectiveFilterWidth,w=y-1-h.padInfo.left,C=I-1-h.padInfo.top,k=wt(a.shape,"float32"),S=e.data.get(o.dataId).values,T=wt(o.shape,"float32",S);for(let R=0;R<h.batchSize;++R)for(let L=0;L<h.inChannels;++L)for(let V=0;V<h.inHeight;++V)for(let F=0;F<h.inWidth;++F){const X=V-C,A=F-w;let P=0;for(let B=0;B<I;B+=b){const K=(X+B)/m;if(!(K<0||K>=h.outHeight||Math.floor(K)!==K))for(let H=0;H<y;H+=x){const U=(A+H)/g;if(U<0||U>=h.outWidth||Math.floor(U)!==U)continue;const Y=I*y-1-f.get(R,K,U,L),j=B*y+H,J=Y===j?1:0;if(J===0)continue;const nt=T.get(R,K,U,L);P+=nt*J}}k.set(P,R,V,F,L)}return e.makeTensorInfo(k.shape,k.dtype,k.values)}const zD={kernelName:$u,backendName:"cpu",kernelFunc:FD};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function XD(n,t,e,s,o){const r=ct(t),i=mp(n,t,e,r,o,"max"),a=Uy(n,t,e,o,!0,s);return[i.values,a.values]}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const AD={kernelName:Cf,backendName:"cpu",kernelFunc:({inputs:n,attrs:t,backend:e})=>{const{x:s}=n,{filterSize:o,strides:r,pad:i,includeBatchInIndex:a}=t,c=e;it(s,"MaxPoolWithArgmax");const l=c.data.get(s.dataId).values,u=pn(s.shape,o,r,[1,1],i),[d,h]=XD(l,s.shape,s.dtype,a,u),p=c.write(d,u.outShape,s.dtype),f=c.write(h,u.outShape,s.dtype);return[{dataId:p,shape:u.outShape,dtype:s.dtype},{dataId:f,shape:u.outShape,dtype:"int32"}]}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function PD(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r,keepDims:i}=s,a=It(r,o.shape),l=me(o.shape,a)[1],u=Z(l),d=[],h=e.makeTensorInfo([],"float32",new Float32Array([u]));d.push(h);const p=Ws({inputs:{x:o},backend:e,attrs:{dtype:"float32"}});d.push(p);const f=gp({inputs:{a:p,b:h},backend:e});d.push(f);const m=ea({inputs:{x:f},backend:e,attrs:{axis:r,keepDims:i}});return d.forEach(g=>e.disposeIntermediateTensorInfo(g)),m}const OD={kernelName:Ya,backendName:"cpu",kernelFunc:PD};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function KD(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r,keepDims:i}=s;it(o,"min");const a=It(r,o.shape);let c=a;const l=Yt(c,o.shape.length);let u=o;l!=null&&(u=Ke({inputs:{x:o},backend:e,attrs:{perm:l}}),c=ee(c.length,o.shape.length)),Ie("min",c,u.shape.length);const[d,h]=me(u.shape,c),p=Z(h),f=ke(Z(d),u.dtype),m=e.data.get(u.dataId).values;for(let b=0;b<f.length;++b){const x=b*p;let I=m[x];for(let y=0;y<p;++y){const w=m[x+y];(Number.isNaN(w)||w<I)&&(I=w)}f[b]=I}l!=null&&e.disposeIntermediateTensorInfo(u);const g=e.makeTensorInfo(d,u.dtype,f);if(i){const b=re(d,a),x=At({inputs:{x:g},backend:e,attrs:{shape:b}});return e.disposeIntermediateTensorInfo(g),x}return g}const ZD={kernelName:Qa,backendName:"cpu",kernelFunc:KD};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function BD(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{paddings:r,mode:i}=s;it(o,"mirrorPad");const a=r.map((I,y)=>I[0]+o.shape[y]+I[1]),c=r.map(I=>I[0]),l=r.map((I,y)=>I[0]+o.shape[y]),u=i==="reflect"?0:1,d=e.data.get(o.dataId).values,h=o.shape.length,p=ct(o.shape),f=Z(a),m=a.length,g=ct(a),b=Se(o.dtype,f);for(let I=0;I<f;I++){let y=Vo(I,m,g);for(let C=0;C<m;C++)y[C]<c[C]?y[C]=c[C]*2-y[C]-u:y[C]>=l[C]&&(y[C]=(l[C]-1)*2-y[C]+u);y=y.map((C,k)=>C-c[k]);const w=Fn(y,h,p);b[I]=d[w]}return{dataId:e.write(b,a,o.dtype),shape:a,dtype:o.dtype}}const HD={kernelName:Ja,backendName:"cpu",kernelFunc:BD};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const _D=oe((n,t)=>{const e=n%t;return n<0&&t<0||n>=0&&t>=0?e:(e+t)%t}),UD=pe(Jr,_D),YD={kernelName:Jr,backendName:"cpu",kernelFunc:UD};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function t1(n){const{inputs:t,backend:e,attrs:s}=n,{logits:o}=t,{dim:r}=s,i=o.shape.length;let a=r;if(a===-1&&(a=i-1),a!==i-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${i} and dim was ${a}`);const c=It([a],o.shape),l=qy({inputs:{x:o},backend:e,attrs:{reductionIndices:c,keepDims:!1}}),u=re(l.shape,c),d=At({inputs:{x:l},backend:e,attrs:{shape:u}}),h=fp({inputs:{a:o,b:d},backend:e}),p=ty({inputs:{x:h},backend:e}),f=ea({inputs:{x:p},backend:e,attrs:{axis:c,keepDims:!1}}),m=At({inputs:{x:f},backend:e,attrs:{shape:u}}),g=gp({inputs:{a:p,b:m},backend:e});return e.disposeIntermediateTensorInfo(l),e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(m),g}const QD={kernelName:mc,backendName:"cpu",kernelFunc:t1};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function JD(n){const{inputs:t,backend:e,attrs:s}=n,{logits:o}=t,{numSamples:r,seed:i,normalized:a}=s;it(o,"multinomial");const c=a?o:t1({inputs:{logits:o},backend:e,attrs:{dim:-1}}),l=c.shape[0],u=c.shape[1],d=e.data.get(c.dataId).values,h=[l,r],p=ke(Z(h),"int32");for(let f=0;f<l;++f){const m=f*u,g=new Float32Array(u-1);g[0]=d[m];for(let I=1;I<g.length;++I)g[I]=g[I-1]+d[m+I];const b=Md.alea(i.toString()),x=f*r;for(let I=0;I<r;++I){const y=b();p[x+I]=g.length;for(let w=0;w<g.length;w++)if(y<g[w]){p[x+I]=w;break}}}return a||e.disposeIntermediateTensorInfo(c),e.makeTensorInfo(h,"int32",p)}const jD={kernelName:vf,backendName:"cpu",kernelFunc:JD};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const qD=Hd;function tW(n){const{inputs:t,backend:e,attrs:s}=n,{boxes:o,scores:r}=t,{maxOutputSize:i,iouThreshold:a,scoreThreshold:c}=s;it(o,"NonMaxSuppression");const l=e.data.get(o.dataId).values,u=e.data.get(r.dataId).values,{selectedIndices:d}=qD(l,u,i,a,c);return e.makeTensorInfo([d.length],"int32",new Int32Array(d))}const eW={kernelName:Lu,backendName:"cpu",kernelFunc:tW};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const nW=_d;function sW(n){const{inputs:t,backend:e,attrs:s}=n,{boxes:o,scores:r}=t,{maxOutputSize:i,iouThreshold:a,scoreThreshold:c,padToMaxOutputSize:l}=s;it(o,"NonMaxSuppressionPadded");const u=e.data.get(o.dataId).values,d=e.data.get(r.dataId).values,{selectedIndices:h,validOutputs:p}=nW(u,d,i,a,c,l);return[e.makeTensorInfo([h.length],"int32",new Int32Array(h)),e.makeTensorInfo([],"int32",new Int32Array([p]))]}const oW={kernelName:Eu,backendName:"cpu",kernelFunc:sW};/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const rW=Ud;function iW(n){const{inputs:t,backend:e,attrs:s}=n,{boxes:o,scores:r}=t,{maxOutputSize:i,iouThreshold:a,scoreThreshold:c,softNmsSigma:l}=s;it(o,"NonMaxSuppressionWithScore");const u=e.data.get(o.dataId).values,d=e.data.get(r.dataId).values,h=i,p=a,f=c,m=l,{selectedIndices:g,selectedScores:b}=rW(u,d,h,p,f,m);return[e.makeTensorInfo([g.length],"int32",new Int32Array(g)),e.makeTensorInfo([b.length],"float32",new Float32Array(b))]}const aW={kernelName:Du,backendName:"cpu",kernelFunc:iW};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function cW(n){const{inputs:t,backend:e,attrs:s}=n,{indices:o}=t,{dtype:r,depth:i,onValue:a,offValue:c}=s;it(o,"oneHot");const l=Z(o.shape),u=new Float32Array(l*i);u.fill(c);const d=e.data.get(o.dataId).values;for(let h=0;h<l;++h)d[h]>=0&&d[h]<i&&(u[h*i+d[h]]=a);return e.makeTensorInfo([...o.shape,i],r,u)}const lW={kernelName:ec,backendName:"cpu",kernelFunc:cW};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function xl(n){const{inputs:t,backend:e}=n,{x:s}=t;if(s.dtype==="string")throw new Error("zerosLike is not supported for string tensors");if(s.dtype==="complex64"){const o=yo({inputs:{input:s},backend:e}),r=xl({inputs:{x:o},backend:e}),i=ar({inputs:{input:s},backend:e}),a=xl({inputs:{x:i},backend:e}),c=Qe({inputs:{real:r,imag:a},backend:e});return e.disposeIntermediateTensorInfo(o),e.disposeIntermediateTensorInfo(r),e.disposeIntermediateTensorInfo(i),e.disposeIntermediateTensorInfo(a),c}else return yp({backend:e,attrs:{shape:s.shape,value:0,dtype:s.dtype}})}const uW={kernelName:xc,backendName:"cpu",kernelFunc:xl};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function e1(n){const{inputs:t,backend:e}=n,{x:s}=t;if(s.dtype==="string")throw new Error("onesLike is not supported for string tensors");if(s.dtype==="complex64"){const o=yo({inputs:{input:s},backend:e}),r=e1({inputs:{x:o},backend:e}),i=ar({inputs:{input:s},backend:e}),a=xl({inputs:{x:i},backend:e}),c=Qe({inputs:{real:r,imag:a},backend:e});return e.disposeIntermediateTensorInfo(o),e.disposeIntermediateTensorInfo(r),e.disposeIntermediateTensorInfo(i),e.disposeIntermediateTensorInfo(a),c}else return yp({backend:e,attrs:{shape:s.shape,value:1,dtype:s.dtype}})}const dW={kernelName:tc,backendName:"cpu",kernelFunc:e1};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function n1(n){const{inputs:t,backend:e,attrs:s}=n,{axis:o}=s;if(t.length===1)return bl({inputs:{input:t[0]},backend:e,attrs:{dim:o}});const r=t[0].shape,i=t[0].dtype;t.forEach(u=>{Hl(r,u.shape,"All tensors passed to stack must have matching shapes"),v(i===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});const a=[],c=t.map(u=>{const d=bl({inputs:{input:u},backend:e,attrs:{dim:o}});return a.push(d),d}),l=cr({inputs:c,backend:e,attrs:{axis:o}});return a.forEach(u=>e.disposeIntermediateTensorInfo(u)),l}const hW={kernelName:nc,backendName:"cpu",kernelFunc:n1};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function pW(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{paddings:r,constantValue:i}=s;it(o,"pad");const a=r.map((x,I)=>x[0]+o.shape[I]+x[1]),c=r.map(x=>x[0]),l=e.data.get(o.dataId).values,u=Z(o.shape),d=o.shape.length,h=ct(o.shape),p=Z(a),f=a.length,m=ct(a),g=Se(o.dtype,p);i!==0&&g.fill(i);for(let x=0;x<u;x++){const y=Vo(x,d,h).map((C,k)=>C+c[k]),w=Fn(y,f,m);g[w]=l[x]}return{dataId:e.write(g,a,o.dtype),shape:a,dtype:o.dtype}}const s1={kernelName:sc,backendName:"cpu",kernelFunc:pW};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const fW=oe((n,t)=>Math.pow(n,t)),mW=pe(qr,fW),gW={kernelName:qr,backendName:"cpu",kernelFunc:mW};/**
 * @license
 * Copyright 2022 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function bW(n){const{inputs:t,backend:e,attrs:s}=n,{paramsNestedSplits:o,paramsDenseValues:r,indices:i}=t,a=o.map(g=>e.data.get(g.dataId).values),c=o.map(g=>g.shape),l=e.data.get(r.dataId).values,u=e.data.get(i.dataId).values,[d,h,p]=yy(a,c,l,r.shape,r.dtype,u,i.shape),f=d.map(g=>e.makeTensorInfo([g.length],"int32",g)),m=e.makeTensorInfo(p,r.dtype,h);return f.concat([m])}const xW={kernelName:Sf,backendName:"cpu",kernelFunc:bW};/**
 * @license
 * Copyright 2022 Google LLC.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function yW(n){const{inputs:t,backend:e}=n,{starts:s,limits:o,deltas:r}=t,i=e.data.get(s.dataId).values,a=e.data.get(o.dataId).values,c=e.data.get(r.dataId).values,[l,u]=wy(i,s.shape,s.dtype,a,o.shape,c,r.shape),d=e.makeTensorInfo([l.length],"int32",l),h=e.makeTensorInfo([u.length],s.dtype,u);return[d,h]}const IW={kernelName:kf,backendName:"cpu",kernelFunc:yW};/**
 * @license
 * Copyright 2022 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function wW(n){const{inputs:t,backend:e,attrs:s}=n,{shape:o,values:r,defaultValue:i,rowPartitionTensors:a}=t,{rowPartitionTypes:c}=s,l=e.data.get(o.dataId).values,u=e.data.get(r.dataId).values,d=e.data.get(i.dataId).values,h=a.map(g=>e.data.get(g.dataId).values),p=a.map(g=>g.shape),[f,m]=Sy(l,o.shape,u,r.shape,r.dtype,d,i.shape,h,p,c);return e.makeTensorInfo(f,r.dtype,m)}const CW={kernelName:Tf,backendName:"cpu",kernelFunc:wW};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function vW(n){const{backend:t,attrs:e}=n,{start:s,stop:o,dtype:r,step:i}=e,a=ky(s,o,i,r);return t.makeTensorInfo([a.length],r,a)}const SW={kernelName:Wu,backendName:"cpu",kernelFunc:vW};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const kW=Et(ti,n=>1/n),TW={kernelName:ti,backendName:"cpu",kernelFunc:kW};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function NW(n){const{inputs:t,backend:e,attrs:s}=n,{images:o}=t,{alignCorners:r,halfPixelCenters:i,size:a}=s;it(o,"resizeBilinear");const c=ct(o.shape),[l,u]=a,[d,h,p,f]=o.shape,m=e.data.get(o.dataId).values,g=new Float32Array(Z([d,l,u,f])),b=[r&&l>1?h-1:h,r&&u>1?p-1:p],x=[r&&l>1?l-1:l,r&&u>1?u-1:u];let I=0;const y=b[0]/x[0],w=b[1]/x[1];for(let C=0;C<d;C++)for(let k=0;k<l;k++){let S;i?S=y*(k+.5)-.5:S=y*k;const T=Math.max(0,Math.floor(S)),R=S-T,L=Math.min(h-1,Math.ceil(S)),V=C*c[0]+T*c[1],F=C*c[0]+L*c[1];for(let X=0;X<u;X++){let A;i?A=w*(X+.5)-.5:A=w*X;const P=Math.max(0,Math.floor(A)),B=A-P,K=Math.min(p-1,Math.ceil(A)),H=V+P*c[2],U=F+P*c[2],Y=V+K*c[2],j=F+K*c[2];for(let J=0;J<f;J++){const nt=m[H+J],q=m[U+J],rt=m[Y+J],lt=m[j+J],ft=nt+(rt-nt)*B,ht=q+(lt-q)*B,xt=ft+(ht-ft)*R;g[I++]=xt}}}return e.makeTensorInfo([d,l,u,f],"float32",g)}const RW={kernelName:cc,backendName:"cpu",kernelFunc:NW};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function $W(n){const{inputs:t,backend:e,attrs:s}=n,{images:o,dy:r}=t,{alignCorners:i}=s;it([r,o],"resizeBilinearGrad");const a=ct(o.shape),[c,l,u,d]=o.shape,[,h,p]=r.shape,f=new Float32Array(c*l*u*d),m=[i&&h>1?l-1:l,i&&p>1?u-1:u],g=[i&&h>1?h-1:h,i&&p>1?p-1:p],b=m[0]/g[0],x=m[1]/g[1],I=e.data.get(r.dataId).values;let y=0;for(let w=0;w<c;w++){const C=w*a[0];for(let k=0;k<h;k++){const S=k*b,T=Math.floor(S),R=Math.min(Math.ceil(S),l-1),L=C+T*a[1],V=C+R*a[1],F=S-T,X=1-F;for(let A=0;A<p;A++){const P=A*x,B=Math.floor(P),K=Math.min(Math.ceil(P),u-1),H=P-B,U=1-H,Y=L+B*a[2],j=L+K*a[2],J=V+B*a[2],nt=V+K*a[2],q=X*U,rt=X*H,lt=F*U,ft=F*H;for(let ht=0;ht<d;ht++){const xt=I[y++];f[Y+ht]+=xt*q,f[j+ht]+=xt*rt,f[J+ht]+=xt*lt,f[nt+ht]+=xt*ft}}}}return e.makeTensorInfo([c,u,l,d],"float32",f)}const GW={kernelName:Fu,backendName:"cpu",kernelFunc:$W};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function LW(n){const{inputs:t,backend:e,attrs:s}=n,{images:o}=t,{alignCorners:r,halfPixelCenters:i,size:a}=s;it(o,"resizeNearestNeighbor");const c=ct(o.shape),[l,u]=a,[d,h,p,f]=o.shape,m=e.data.get(o.dataId).values,g=new Float32Array(d*l*u*f),b=[r&&l>1?h-1:h,r&&u>1?p-1:p],x=[r&&l>1?l-1:l,r&&u>1?u-1:u],I=b[0]/x[0],y=b[1]/x[1];let w=0;for(let C=0;C<d;C++){const k=C*c[0];for(let S=0;S<l;S++){const T=i?I*(S+.5):I*S;let R=Math.min(h-1,r?Math.round(T):Math.floor(T));i&&(R=Math.max(0,R));const L=k+R*c[1];for(let V=0;V<u;V++){const F=i?y*(V+.5):y*V;let X=Math.min(p-1,r?Math.round(F):Math.floor(F));i&&(X=Math.max(0,X));const A=L+X*c[2];for(let P=0;P<f;P++){const B=m[A+P];g[w++]=B}}}}return e.makeTensorInfo([d,l,u,f],o.dtype,g)}const EW={kernelName:ac,backendName:"cpu",kernelFunc:LW};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function DW(n){const{inputs:t,backend:e,attrs:s}=n,{images:o,dy:r}=t,{alignCorners:i}=s;it([r,o],"resizeNearestNeighborGrad");const a=ct(o.shape),c=ct(r.shape),[l,u,d,h]=o.shape,[,p,f]=r.shape,m=new Float32Array(l*u*d*h),g=e.data.get(r.dataId).values,b=[i&&p>1?u-1:u,i&&f>1?d-1:d],x=[i&&p>1?p-1:p,i&&f>1?f-1:f],I=b[0]/x[0],y=b[1]/x[1],w=1/I,C=1/y,k=Math.ceil(w)*2+2,S=Math.ceil(C)*2+2;for(let T=0;T<l;T++){const R=T*a[0];for(let L=0;L<u;L++){const V=R+L*a[1],F=Math.floor(L*w),X=Math.floor(F-k/2);for(let A=0;A<d;A++){const P=V+A*a[2],B=Math.floor(A*C),K=Math.floor(B-S/2);for(let H=0;H<h;H++){let U=0;for(let Y=0;Y<k;Y++){const j=Y+X;if(j<0||j>=p)continue;const J=R+j*c[1],nt=j*I,q=Math.min(u-1,i?Math.round(nt):Math.floor(nt));if(L===q)for(let rt=0;rt<S;rt++){const lt=rt+K;if(lt<0||lt>=f)continue;const ft=J+lt*c[2],ht=lt*y,xt=Math.min(d-1,i?Math.round(ht):Math.floor(ht));A===xt&&(U+=g[ft+H])}}m[P+H]=U}}}}return e.makeTensorInfo(o.shape,o.dtype,m)}const WW={kernelName:Vu,backendName:"cpu",kernelFunc:DW};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function MW(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{dims:r}=s;it(o,"reverse");const i=o.shape.length,a=It(r,o.shape);if(i===0)return Qn({inputs:{x:o},backend:e});const c=new xe(o.shape,o.dtype),l=e.bufferSync(o);for(let u=0;u<c.size;u++){const d=c.indexToLoc(u),h=d.slice();a.forEach(p=>h[p]=o.shape[p]-1-h[p]),c.set(l.get(...h),...d)}return e.makeTensorInfo(c.shape,c.dtype,c.values)}const VW={kernelName:lc,backendName:"cpu",kernelFunc:MW};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const FW={kernelName:Bu,backendName:"cpu",kernelFunc:({inputs:n,attrs:t,backend:e})=>{const{image:s}=n,{radians:o,fillValue:r,center:i}=t,a=e,c=Se(s.dtype,Z(s.shape)),[l,u,d,h]=s.shape,[p,f]=ih(i,u,d),m=255,g=Math.sin(o),b=Math.cos(o),x=a.data.get(s.dataId).values;for(let y=0;y<l;y++){const w=y*d*u*h;for(let C=0;C<u;C++){const k=C*(d*h);for(let S=0;S<d;S++){const T=S*h;for(let R=0;R<h;R++){const L=[l,C,S,R],V=L[2],F=L[1];let X=(V-p)*b-(F-f)*g,A=(V-p)*g+(F-f)*b;X=Math.round(X+p),A=Math.round(A+f);let P=r;if(typeof r!="number"&&(R===3?P=m:P=r[R]),X>=0&&X<d&&A>=0&&A<u){const K=A*(d*h),H=X*h,U=w+K+H+R;P=x[U]}const B=w+k+T+R;c[B]=P}}}}return{dataId:a.write(c,s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const zW=Et(si,n=>{const t=Math.floor(n);return n-t<.5?Math.floor(n):n-t>.5?Math.ceil(n):t%2===0?t:t+1}),XW={kernelName:si,backendName:"cpu",kernelFunc:zW};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function AW(n){const{inputs:t,backend:e,attrs:s}=n,{indices:o,updates:r}=t,{shape:i}=s,{sliceRank:a,numUpdates:c,sliceSize:l,strides:u,outputSize:d}=co(r,o,i),h=!0,p=e.bufferSync(o),f=e.bufferSync(r),m=Io(p,f,i,d,l,c,a,u,0,h);return e.makeTensorInfo(i,m.dtype,m.values)}const PW={kernelName:Nf,backendName:"cpu",kernelFunc:AW};/**
 * @license
 * Copyright 2022 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function OW(n,t){let e=0,s=n.length,o=0;for(;e<s;)o=Math.floor((e+s)/2),n[o]<t?e=o+1:s=o;return s}function KW(n,t){let e=0,s=n.length,o=0;for(;e<s;)o=Math.floor((e+s)/2),n[o]<=t?e=o+1:s=o;return s}function ZW(n,t,e,s,o,r){const i=qt("int32",e*o);for(let a=0;a<e;++a){const c=n.slice(a*s,(a+1)*s),l=a*o;for(let u=0;u<o;++u)i[l+u]=r==="left"?OW(c,t[u+l]):KW(c,t[u+l])}return i}/**
 * @license
 * Copyright 2022 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function BW(n){const{inputs:t,backend:e,attrs:s}=n,{sortedSequence:o,values:r}=t,{side:i}=s,a=e.data.get(o.dataId).values,c=e.data.get(r.dataId).values,l=ZW(a,c,o.shape[0],o.shape[1],r.shape[1],i);return e.makeTensorInfo(r.shape,"int32",l)}const HW={kernelName:$f,backendName:"cpu",kernelFunc:BW};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function _W(n){const{inputs:t,backend:e}=n,{condition:s,t:o,e:r}=t;it([s,o,r],"select");const i=s.shape.length,a=e.data.get(s.dataId).values,c=e.data.get(o.dataId).values,l=e.data.get(r.dataId).values,u=_e(o.dtype,r.dtype),d=ke(Z(o.shape),u);let h=0;const p=i===0||i>1||o.shape.length===1?1:Z(o.shape.slice(1));for(let f=0;f<a.length;f++)for(let m=0;m<p;m++)a[f]===1?d[h++]=c[f]:d[h++]=l[f];return e.makeTensorInfo(o.shape,u,d)}const UW={kernelName:uc,backendName:"cpu",kernelFunc:_W};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const YW=Pc,QW=Oc,JW=Et(ri,n=>n>=0?QW*n:YW*(Math.exp(n)-1)),jW={kernelName:ri,backendName:"cpu",kernelFunc:JW};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const qW=Et(ci,n=>n<0?-1:n>0?1:0),tM={kernelName:ci,backendName:"cpu",kernelFunc:qW};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const eM=Et(ii,n=>Math.sin(n)),nM={kernelName:ii,backendName:"cpu",kernelFunc:eM};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const sM=Et(ai,n=>Math.sinh(n)),oM={kernelName:ai,backendName:"cpu",kernelFunc:sM};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const o1=Math.log(11920928955078125e-23)+2,rM=Et(ui,n=>{const t=n>-o1,e=n<o1,s=Math.exp(n);let o;return e?o=s:t?o=n:o=Math.log(1+s),o}),iM={kernelName:ui,backendName:"cpu",kernelFunc:rM};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function aM(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{blockShape:r,paddings:i}=s;it([o],"spaceToBatchND");const a=Z(r),c=[[0,0]];c.push(...i);for(let C=1+r.length;C<o.shape.length;++C)c.push([0,0]);const l=s1.kernelFunc({inputs:{x:o},backend:e,attrs:{paddings:c,constantValue:0}}),u=Mi(l.shape,r,a,!1),d=Vi(u.length,r.length,!1),h=Fi(l.shape,r,a,!1),m=At({inputs:{x:l},backend:e,attrs:{shape:u}}),x=Ke({inputs:{x:m},backend:e,attrs:{perm:d}}),w=At({inputs:{x},backend:e,attrs:{shape:h}});return e.disposeIntermediateTensorInfo(l),e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(x),w}const cM={kernelName:pc,backendName:"cpu",kernelFunc:aM};/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function lM(n){const{inputs:t,backend:e}=n,{indices:s,values:o,denseShape:r,defaultValue:i}=t;if(r.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
        ${r.shape}`);if(s.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
        ${s.shape}`);if(o.shape.length!==1)throw new Error(`Values must be a vector, saw:
        ${o.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
        ${i.shape}`);const a=e.data.get(s.dataId).values,c=e.data.get(o.dataId).values,l=e.data.get(r.dataId).values,u=e.data.get(i.dataId).values[0],[d,h,p,f,m]=$y(a,s.shape,s.dtype,c,o.dtype,l,u);return[e.makeTensorInfo(h,s.dtype,d),e.makeTensorInfo([h[0]],o.dtype,p),e.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),e.makeTensorInfo([m.length],s.dtype,new Int32Array(m))]}const uM={kernelName:Gf,backendName:"cpu",kernelFunc:lM};/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function dM(n){const{inputs:t,backend:e}=n,{inputIndices:s,inputShape:o,newShape:r}=t;if(s.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
        ${s.shape}`);if(o.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
        ${o.shape}`);if(r.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${r.shape}`);const i=Array.from(e.data.get(o.dataId).values),a=e.data.get(s.dataId).values,c=Array.from(e.data.get(r.dataId).values),[l,u,d]=Gy(a,s.shape,s.dtype,i,c);return[e.makeTensorInfo(u,s.dtype,l),e.makeTensorInfo([d.length],r.dtype,new Int32Array(d))]}const hM={kernelName:Lf,backendName:"cpu",kernelFunc:dM};/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function pM(n){const{inputs:t,backend:e}=n,{data:s,indices:o,segmentIds:r}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.shape.length!==1)throw new Error(`Indices should be a vector but received shape
          ${o.shape}`);if(r.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
          ${r.shape}`);if(o.shape[0]!==r.shape[0])throw new Error("segmentIds and indices should have same size.");const i=e.data.get(s.dataId).values,a=e.data.get(o.dataId).values,c=e.data.get(r.dataId).values,[l,u]=pp(i,s.shape,s.dtype,a,c,!0);return e.makeTensorInfo(u,s.dtype,l)}const fM={kernelName:Ef,backendName:"cpu",kernelFunc:pM};/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function mM(n){const{inputs:t,backend:e}=n,{data:s,indices:o,segmentIds:r}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.shape.length!==1)throw new Error(`Indices should be a vector but received shape
         ${o.shape}`);if(r.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
         ${r.shape}`);if(o.shape[0]!==r.shape[0])throw new Error("segmentIds and indices should have same size.");const i=e.data.get(s.dataId).values,a=e.data.get(o.dataId).values,c=e.data.get(r.dataId).values,[l,u]=pp(i,s.shape,s.dtype,a,c);return e.makeTensorInfo(u,s.dtype,l)}const gM={kernelName:Df,backendName:"cpu",kernelFunc:mM};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function bM(n){const{inputs:t,backend:e,attrs:s}=n,{sparseIndices:o,sparseValues:r,defaultValue:i}=t,{outputShape:a}=s,{sliceRank:c,numUpdates:l,sliceSize:u,strides:d,outputSize:h}=co(r,o,a),p=!1,f=e.bufferSync(o);let m;switch(r.dtype){case"bool":{const g=e.bufferSync(r),b=!!e.data.get(i.dataId).values[0];m=Io(f,g,a,h,u,l,c,d,b,p);break}case"float32":{const g=e.bufferSync(r),b=e.data.get(i.dataId).values[0];m=Io(f,g,a,h,u,l,c,d,b,p);break}case"int32":{const g=e.bufferSync(r),b=e.data.get(i.dataId).values[0];m=Io(f,g,a,h,u,l,c,d,b,p);break}case"string":{const g=e.bufferSync(r),b=xs(e.data.get(i.dataId).values[0]);m=Io(f,g,a,h,u,l,c,d,b,p);break}default:throw new Error(`Unsupported type ${r.dtype}`)}return e.makeTensorInfo(a,m.dtype,m.values)}const xM={kernelName:Wf,backendName:"cpu",kernelFunc:bM};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function yM(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{numOrSizeSplits:r,axis:i}=s,a=It(i,o.shape)[0],c=Ch(o,r,a),l=new Array(o.shape.length).fill(0),u=o.shape.slice();return c.map(d=>{const h=[...u];h[a]=d;const p=wo({inputs:{x:o},backend:e,attrs:{begin:l,size:h}});return l[a]+=d,p})}const IM={kernelName:fc,backendName:"cpu",kernelFunc:yM};/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const wM={kernelName:zu,backendName:"cpu",kernelFunc:({inputs:n,backend:t})=>{const{x:e}=n,s=t;it(e,"square");const o=s.data.get(e.dataId).values,r=new Float32Array(o.length);for(let a=0;a<o.length;++a){const c=o[a];r[a]=c*c}return{dataId:s.write(r,e.shape,e.dtype),shape:e.shape,dtype:e.dtype}}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const CM=Et(bi,(n,t)=>{const e=t;return isNaN(n)?NaN:n>0?1:e.alpha}),vM={kernelName:bi,backendName:"cpu",kernelFunc:CM};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function SM(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{begin:r,end:i,strides:a,beginMask:c,endMask:l,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:h}=s;it(o,"stridedSlice");const{finalShapeSparse:p,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:b,begin:x,end:I,strides:y}=sh(o.shape,r,i,a,c,l,u,d,h);let w;if(m)w=At({inputs:{x:o},backend:e,attrs:{shape:f}});else if(g||b){v(o.shape.length>=1,()=>`Input must have rank at least 1, got: ${o.shape.length}`);const C=th(x,I,y),k=wo({inputs:{x:o},backend:e,attrs:{begin:x,size:C}});w=At({inputs:{x:k},backend:e,attrs:{shape:f}}),e.disposeIntermediateTensorInfo(k)}else{const C=e.bufferSync(o),k=Dy(p,C,y,x);w=e.makeTensorInfo(f,k.dtype,k.values)}return w}const kM={kernelName:Au,backendName:"cpu",kernelFunc:SM};/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function TM(n){const{inputs:t,backend:e,attrs:s}=n,{separator:o,nGramWidths:r,leftPad:i,rightPad:a,padWidth:c,preserveShortSequences:l}=s,{data:u,dataSplits:d}=t,h=e.data.get(u.dataId).values,p=e.data.get(d.dataId).values,[f,m]=Wy(h,p,o,r,i,a,c,l);return[e.makeTensorInfo([f.length],"string",f),e.makeTensorInfo(d.shape,"int32",m)]}const NM={kernelName:Mf,backendName:"cpu",kernelFunc:TM};/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function RM(n){const{inputs:t,backend:e,attrs:s}=n,{skipEmpty:o}=s,{input:r,delimiter:i}=t;if(r.dtype!=="string")throw new Error("Input must be of datatype string");if(r.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${r.shape}`);if(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);const a=e.data.get(r.dataId).values,c=e.data.get(i.dataId).values[0],[l,u,d]=My(a,c,o),h=u.length;return[e.makeTensorInfo([h,2],"int32",l),e.makeTensorInfo([h],"string",u),e.makeTensorInfo([2],"int32",new Int32Array(d))]}const $M={kernelName:Vf,backendName:"cpu",kernelFunc:RM};/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function GM(n){const{inputs:t,backend:e,attrs:s}=n,{numBuckets:o}=s,{input:r}=t;if(r.dtype!=="string")throw new Error("Input must be of datatype string");if(o<=0)throw new Error("Number of buckets must be at least 1");const i=e.data.get(r.dataId).values,a=Vy(i,o);return e.makeTensorInfo(r.shape,"int32",a)}const LM={kernelName:Ff,backendName:"cpu",kernelFunc:GM};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const EM=Et(fi,n=>Math.tan(n)),DM={kernelName:fi,backendName:"cpu",kernelFunc:EM};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const WM=Et(mi,n=>Math.tanh(n)),MM={kernelName:mi,backendName:"cpu",kernelFunc:WM};/**
 * @license
 * Copyright 2022 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function VM(n){const{inputs:t,backend:e}=n,{tensor:s,indices:o,updates:r}=t,{sliceRank:i,numUpdates:a,sliceSize:c,strides:l,outputSize:u}=co(r,o,s.shape),d=!1,h=e.bufferSync(o),p=e.bufferSync(r),f=e.bufferSync(s),m=Io(h,p,s.shape,u,c,a,i,l,f,d);return e.makeTensorInfo(s.shape,m.dtype,m.values)}const FM={kernelName:Rf,backendName:"cpu",kernelFunc:VM};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function zM(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{reps:r}=s;it(o,"tile");const i=zy(e.bufferSync(o),r);return e.makeTensorInfo(i.shape,i.dtype,i.values)}const XM={kernelName:gi,backendName:"cpu",kernelFunc:zM};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function AM(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{k:r,sorted:i}=s;it(o,"topk");const a=e.data.get(o.dataId).values,[c,l]=Ay(a,o.shape,o.dtype,r,i);return[e.makeTensorInfo(c.shape,c.dtype,c.values),e.makeTensorInfo(l.shape,l.dtype,l.values)]}const PM={kernelName:Pu,backendName:"cpu",kernelFunc:AM};/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function OM(n){const{inputs:t,attrs:e,backend:s}=n,{image:o,transforms:r}=t,{interpolation:i,fillMode:a,fillValue:c,outputShape:l}=e,[u,d,h,p]=o.shape,[f,m]=l??[d,h],g=[u,f,m,p],b=ct(o.shape),x=b[0],I=b[1],y=b[2],w=ct(g),C=w[0],k=w[1],S=w[2],T=Se(o.dtype,Z(g));T.fill(c);const R=s.data.get(o.dataId).values,L=s.data.get(r.dataId).values;for(let F=0;F<u;++F){const X=r.shape[0]===1?L:L.subarray(F*8,F*8+8);for(let A=0;A<f;++A)for(let P=0;P<m;++P)for(let B=0;B<p;++B){let K;const H=X[6]*P+X[7]*A+1;if(H===0)continue;const U=(X[0]*P+X[1]*A+X[2])/H,Y=(X[3]*P+X[4]*A+X[5])/H,j=r1(U,h,a),J=r1(Y,d,a);switch(i){case"nearest":K=UM(R,d,h,x,I,y,F,J,j,B,c);break;case"bilinear":K=YM(R,d,h,x,I,y,F,J,j,B,c);break;default:throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${i}`)}const nt=F*C+A*k+P*S+B;T[nt]=K}return s.makeTensorInfo(g,o.dtype,T)}return{dataId:s.write(T,g,o.dtype),shape:o.shape,dtype:o.dtype}}const KM={kernelName:Ou,backendName:"cpu",kernelFunc:OM};function r1(n,t,e){switch(e){case"reflect":return ZM(n,t);case"wrap":return BM(n,t);case"nearest":return _M(n,t);case"constant":default:return HM(n)}}function ZM(n,t){let e=n;if(e<0)if(t<=1)e=0;else{const s=2*t;e<s&&(e=s*Math.trunc(-e/s)+e),e=e<-t?e+s:-e-1}else if(e>t-1)if(t<=1)e=0;else{const s=2*t;e-=s*Math.trunc(e/s),e>=t&&(e=s-e-1)}return Ks(0,e,t-1)}function BM(n,t){let e=n;if(e<0)if(t<=1)e=0;else{const s=t-1;e+=t*(Math.trunc(-e/s)+1)}else if(e>t-1)if(t<=1)e=0;else{const s=t-1;e-=t*Math.trunc(e/s)}return Ks(0,e,t-1)}function HM(n,t){return n}function _M(n,t){return Ks(0,n,t-1)}function na(n,t,e,s,o,r,i,a,c,l,u){const d=i*s+a*o+c*r+l;return 0<=a&&a<t&&0<=c&&c<e?n[d]:u}function UM(n,t,e,s,o,r,i,a,c,l,u){const d=Math.round(a),h=Math.round(c);return na(n,t,e,s,o,r,i,d,h,l,u)}function YM(n,t,e,s,o,r,i,a,c,l,u){const d=Math.floor(a),h=Math.floor(c),p=d+1,f=h+1,m=(f-c)*na(n,t,e,s,o,r,i,d,h,l,u)+(c-h)*na(n,t,e,s,o,r,i,d,f,l,u),g=(f-c)*na(n,t,e,s,o,r,i,p,h,l,u)+(c-h)*na(n,t,e,s,o,r,i,p,f,l,u);return(p-a)*m+(a-d)*g}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function QM(n){const{inputs:t,attrs:e,backend:s}=n,{axis:o}=e,{x:r}=t;it(r,"unique");const i=s.data.get(r.dataId).values,{outputValues:a,outputShape:c,indices:l}=Py(i,o,r.shape,r.dtype);return[s.makeTensorInfo(c,r.dtype,a),s.makeTensorInfo([l.length],"int32",l)]}const JM={kernelName:Ku,backendName:"cpu",kernelFunc:QM};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function jM(n){const{inputs:t,backend:e,attrs:s}=n,{value:o}=t;let{axis:r}=s;r<0&&(r+=o.shape.length);const i=o.shape.length,a=o.shape[r],c=new Array(i-1);let l=0;for(let p=0;p<i;p++)p!==r&&(c[l++]=o.shape[p]);const u=new Array(i).fill(0),d=o.shape.slice();d[r]=1;const h=new Array(a);for(let p=0;p<h.length;p++){u[r]=p;const f=wo({inputs:{x:o},backend:e,attrs:{begin:u,size:d}});h[p]=At({inputs:{x:f},backend:e,attrs:{shape:c}}),e.disposeIntermediateTensorInfo(f)}return h}const qM={kernelName:gc,backendName:"cpu",kernelFunc:jM};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function tV(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,segmentIds:r}=t,{numSegments:i}=s;it(o,"unsortedSegmentSum");const a=o.shape.length,c=r.shape.length,l=[],u=[],d=a-c;let h=r;for(let f=0;f<d;++f){const m=bl({inputs:{input:h},backend:e,attrs:{dim:f+1}});h=m,u.push(m)}for(let f=0;f<i;++f){const m=gs(f,"int32"),g=e.makeTensorInfo([],"int32",m),b=jx({inputs:{a:g,b:h},backend:e}),x=Ws({inputs:{x:b},backend:e,attrs:{dtype:"float32"}}),I=fl({inputs:{a:x,b:o},backend:e}),y=ea({inputs:{x:I},backend:e,attrs:{axis:0,keepDims:!1}});l.push(y),u.push(g),u.push(b),u.push(x),u.push(I),u.push(y)}const p=n1({inputs:l,backend:e,attrs:{axis:0}});return u.forEach(f=>e.disposeIntermediateTensorInfo(f)),p}const eV={kernelName:bc,backendName:"cpu",kernelFunc:tV};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const nV=[jL,EG,tE,nE,zG,oE,iE,cE,uE,hE,fE,gE,xE,wE,vE,TE,RE,GE,EE,QL,WE,VE,zE,AG,AE,VG,OG,OE,DG,KE,BE,HE,UE,QE,jE,t3,n3,o3,i3,c3,u3,h3,f3,g3,b3,y3,w3,v3,S3,k3,T3,R3,L3,KL,D3,KG,P3,ZG,O3,HG,U3,Y3,J3,UG,QG,q3,eD,sD,rD,jG,tL,WG,aD,ZE,lD,dD,pD,ZL,nL,oL,mD,iL,bD,ID,CD,kD,ND,$D,GD,cL,ED,WD,VD,zD,AD,OD,ZD,uL,HD,YD,jD,hL,fL,eW,oW,aW,gL,lW,dW,hW,s1,gW,HL,yL,xW,IW,CW,SW,MG,bp,TW,_L,UL,YL,RW,GW,EW,WW,VW,FW,XW,NL,PW,HW,UW,jW,$L,tM,nM,oM,GL,QD,iM,cM,uM,hM,fM,gM,xM,IM,DL,wM,ML,FL,vM,kM,NM,$M,LM,PL,$3,DM,MM,FM,XM,PM,KM,bL,JM,qM,eV,uW];for(const n of nV)qe(n);/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const Co={},yl={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function sV(n,t){Co[n]=t}function Mn(n,t){if(!(n in Co)||t!=null){const s=rV(n,t);if(s!==null)Co[n]=s;else return console.log("Could not get context for WebGL version",n),null}const e=Co[n];return e==null||e.isContextLost()?(delete Co[n],Mn(n)):(e.disable(e.DEPTH_TEST),e.disable(e.STENCIL_TEST),e.disable(e.BLEND),e.disable(e.DITHER),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SAMPLE_COVERAGE),e.enable(e.SCISSOR_TEST),e.enable(e.CULL_FACE),e.cullFace(e.BACK),Co[n])}function oV(n){if(!z().getBool("IS_SAFARI")&&typeof OffscreenCanvas<"u"&&n===2)return new OffscreenCanvas(300,150);if(typeof document<"u")return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}function rV(n,t){if(n!==1&&n!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");const e=t??oV(n);return e.addEventListener("webglcontextlost",s=>{s.preventDefault(),delete Co[n]},!1),z().getBool("SOFTWARE_WEBGL_ENABLED")&&(yl.failIfMajorPerformanceCaveat=!1),n===1?e.getContext("webgl",yl)||e.getContext("experimental-webgl",yl):e.getContext("webgl2",yl)}/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */var sa;(function(n){n[n.DENSE=0]="DENSE",n[n.SHARED_BATCH=1]="SHARED_BATCH"})(sa||(sa={}));var an;(function(n){n[n.RENDER=0]="RENDER",n[n.UPLOAD=1]="UPLOAD",n[n.PIXELS=2]="PIXELS",n[n.DOWNLOAD=3]="DOWNLOAD"})(an||(an={}));var we;(function(n){n[n.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",n[n.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",n[n.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",n[n.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",n[n.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"})(we||(we={}));function oa(n,t){return[t,n]}function iV(n,t){return n*t}function Il(n){const t=Z(n),e=Math.ceil(t/4);return Ul(e)}function lr(n,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(n/2))]}function aV(n,t){const[e,s]=lr(n,t);return e*s*4}function Ip(n,t){const e=n;let s,o,r,i,a,c,l,u,d,h;return z().getNumber("WEBGL_VERSION")===2?(s=e.R32F,o=e.R16F,r=e.RGBA16F,i=e.RGBA32F,a=e.RED,l=4,u=1,d=e.HALF_FLOAT,h=e.FLOAT,c=e.RGBA8):(s=n.RGBA,o=n.RGBA,r=n.RGBA,i=e.RGBA,a=n.RGBA,l=4,u=4,d=t!=null?t.HALF_FLOAT_OES:null,h=n.FLOAT,c=n.RGBA),{internalFormatFloat:s,internalFormatHalfFloat:o,internalFormatPackedHalfFloat:r,internalFormatPackedFloat:i,textureFormatFloat:a,downloadTextureFormat:c,downloadUnpackNumChannels:l,defaultNumChannels:u,textureTypeHalfFloat:d,textureTypeFloat:h}}/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function ot(n,t){const e=t();return z().getBool("DEBUG")&&cV(n),e}function cV(n){const t=n.getError();if(t!==n.NO_ERROR)throw new Error("WebGL Error: "+hV(n,t))}const lV=596e-10,uV=65504;function dV(n){return!!(z().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||n===0||lV<Math.abs(n)&&Math.abs(n)<uV)}function hV(n,t){switch(t){case n.NO_ERROR:return"NO_ERROR";case n.INVALID_ENUM:return"INVALID_ENUM";case n.INVALID_VALUE:return"INVALID_VALUE";case n.INVALID_OPERATION:return"INVALID_OPERATION";case n.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case n.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case n.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return`Unknown error code ${t}`}}function wl(n,t){return ds(n,()=>n.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function pV(n,t){const e=ds(n,()=>n.createShader(n.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(ot(n,()=>n.shaderSource(e,t)),ot(n,()=>n.compileShader(e)),n.getShaderParameter(e,n.COMPILE_STATUS)===!1)throw console.log(n.getShaderInfoLog(e)),new Error("Failed to compile vertex shader.");return e}function fV(n,t){const e=ds(n,()=>n.createShader(n.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(ot(n,()=>n.shaderSource(e,t)),ot(n,()=>n.compileShader(e)),z().get("ENGINE_COMPILE_ONLY"))return e;if(n.getShaderParameter(e,n.COMPILE_STATUS)===!1)throw i1(t,n.getShaderInfoLog(e)),new Error("Failed to compile fragment shader.");return e}const mV=/ERROR: [0-9]+:([0-9]+):/g;function i1(n,t){const e=mV.exec(t);if(e==null){console.log(`Couldn't parse line number in error: ${t}`),console.log(n);return}const s=+e[1],o=n.split(`
`),r=o.length.toString().length+2,i=o.map((d,h)=>Wo((h+1).toString(),r)+d);let a=0;for(let d=0;d<i.length;d++)a=Math.max(i[d].length,a);const c=i.slice(0,s-1),l=i.slice(s-1,s),u=i.slice(s);console.log(c.join(`
`)),console.log(t.split(`
`)[0]),console.log(`%c ${Wo(l[0],a)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(u.join(`
`))}function gV(n){return ds(n,()=>n.createProgram(),"Unable to create WebGLProgram.")}function bV(n,t){if(ot(n,()=>n.linkProgram(t)),!z().get("ENGINE_COMPILE_ONLY")&&n.getProgramParameter(t,n.LINK_STATUS)===!1)throw console.log(n.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function wp(n,t){if(ot(n,()=>n.validateProgram(t)),n.getProgramParameter(t,n.VALIDATE_STATUS)===!1)throw console.log(n.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function xV(n,t){const e=ds(n,()=>n.createBuffer(),"Unable to create WebGLBuffer");return ot(n,()=>n.bindBuffer(n.ARRAY_BUFFER,e)),ot(n,()=>n.bufferData(n.ARRAY_BUFFER,t,n.STATIC_DRAW)),e}function yV(n,t){const e=ds(n,()=>n.createBuffer(),"Unable to create WebGLBuffer");return ot(n,()=>n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,e)),ot(n,()=>n.bufferData(n.ELEMENT_ARRAY_BUFFER,t,n.STATIC_DRAW)),e}function IV(n){return ds(n,()=>n.createTexture(),"Unable to create WebGLTexture.")}function wV(n,t){const e=z().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(n<=0||t<=0){const s=`[${n}x${t}]`;throw new Error("Requested texture size "+s+" is invalid.")}if(n>e||t>e){const s=`[${n}x${t}]`,o=`[${e}x${e}]`;throw new Error("Requested texture size "+s+" greater than WebGL maximum on this browser / GPU "+o+".")}}function CV(n){return ds(n,()=>n.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function a1(n,t,e,s,o,r,i){const a=n.getAttribLocation(t,e);return a===-1?!1:(ot(n,()=>n.bindBuffer(n.ARRAY_BUFFER,s)),ot(n,()=>n.vertexAttribPointer(a,o,n.FLOAT,!1,r,i)),ot(n,()=>n.enableVertexAttribArray(a)),!0)}function vV(n,t,e){RV(n,e),ot(n,()=>n.activeTexture(n.TEXTURE0+e)),ot(n,()=>n.bindTexture(n.TEXTURE_2D,t))}function SV(n,t,e){return ds(n,()=>n.getUniformLocation(t,e),'uniform "'+e+'" not present in program.')}function kV(n,t,e){return n.getUniformLocation(t,e)}function TV(n,t,e,s){ot(n,()=>vV(n,t,s)),ot(n,()=>n.uniform1i(e,s))}function Cp(n,t,e){ot(n,()=>n.bindFramebuffer(n.FRAMEBUFFER,e)),ot(n,()=>n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,t,0))}function c1(n,t){ot(n,()=>n.bindFramebuffer(n.FRAMEBUFFER,t)),ot(n,()=>n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,null,0))}function Cl(n){const t=n.checkFramebufferStatus(n.FRAMEBUFFER);if(t!==n.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+NV(n,t))}function NV(n,t){switch(t){case n.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case n.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case n.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}function ds(n,t,e){const s=ot(n,()=>t());if(s==null)throw new Error(e);return s}function RV(n,t){const e=n.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,s=t+n.TEXTURE0;if(s<n.TEXTURE0||s>e){const o=`[gl.TEXTURE0, gl.TEXTURE${e}]`;throw new Error(`textureUnit must be in ${o}.`)}}function ur(n,t=2){return Z(n.slice(0,n.length-t))}function dr(n){if(n.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[n.length>1?n[n.length-2]:1,n[n.length-1]]}function vl(n){let t=[1,1,1];return n.length===0||n.length===1&&n[0]===1||(t=[ur(n),...dr(n)]),t}function $V(n,t=!1){let e=z().getNumber("WEBGL_MAX_TEXTURE_SIZE"),s=z().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");s===1/0&&z().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")&&(s=e/2),t&&(e=e*2,s=s*2,n=n.map((a,c)=>c>=n.length-2?Bl(n[c]):n[c]),n.length===1&&(n=[2,n[0]])),n.length!==2&&(n=fs(n).newShape);let o=Z(n),r=null;n.length<=1&&o<=e?r=[1,o]:n.length===2&&n[0]<=e&&n[1]<=e?r=n:n.length===3&&n[0]*n[1]<=e&&n[2]<=e?r=[n[0]*n[1],n[2]]:n.length===3&&n[0]<=e&&n[1]*n[2]<=e?r=[n[0],n[1]*n[2]]:n.length===4&&n[0]*n[1]*n[2]<=e&&n[3]<=e?r=[n[0]*n[1]*n[2],n[3]]:n.length===4&&n[0]<=e&&n[1]*n[2]*n[3]<=e&&(r=[n[0],n[1]*n[2]*n[3]]);const i=r!=null&&Math.max(...r)>s&&Math.min(...r)<=(t?2:1)&&Math.min(...r)>0;if(r==null||i)if(t){const a=ur(n);let c=2,l=2;n.length&&([c,l]=dr(n)),o=a*(c/2)*(l/2),r=Ul(o).map(u=>u*2)}else r=Ul(o);return r}function Sl(n){return n%2===0}function kl(n,t){if(n=n.slice(-2),t=t.slice(-2),Rt(n,t)||!n.length||!t.length||n[0]===0||n[1]===0||t[0]===0||t[1]===0)return!0;if(n.length!==t.length){const e=n[n.length-1],s=t[t.length-1];if(e===s||Sl(e)&&Sl(s)&&(n[0]===1||t[0]===1))return!0}return n[1]===t[1]&&Sl(n[0])&&Sl(t[0])}let vp,Sp;function GV(n){if(vp==null){const t=Mn(n);vp=t.getParameter(t.MAX_TEXTURE_SIZE)}return vp}function LV(n){if(Sp==null){const t=Mn(n);Sp=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Sp)}function EV(n){if(n===0)return 0;let t;const e=Mn(n);return wn(e,"EXT_disjoint_timer_query_webgl2")&&n===2?t=2:wn(e,"EXT_disjoint_timer_query")?t=1:t=0,t}function wn(n,t){return n.getExtension(t)!=null}function l1(n){try{if(Mn(n)!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function DV(n){if(n===0)return!1;const t=Mn(n);if(n===1){if(!wn(t,"OES_texture_float"))return!1}else if(!wn(t,"EXT_color_buffer_float"))return!1;return kp(t)}function WV(n){if(n===0)return!1;const t=Mn(n);if(n===1){if(!wn(t,"OES_texture_float")||!wn(t,"WEBGL_color_buffer_float"))return!1}else{if(wn(t,"EXT_color_buffer_float"))return kp(t);const s="EXT_color_buffer_half_float";if(wn(t,s)){const o=t.getExtension(s);return MV(t,o)}return!1}return kp(t)}function kp(n){const t=Ip(n),e=n.createTexture();n.bindTexture(n.TEXTURE_2D,e),n.texImage2D(n.TEXTURE_2D,0,t.internalFormatFloat,1,1,0,t.textureFormatFloat,t.textureTypeFloat,null);const r=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,r),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,e,0);const i=n.checkFramebufferStatus(n.FRAMEBUFFER)===n.FRAMEBUFFER_COMPLETE;return n.bindTexture(n.TEXTURE_2D,null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(e),n.deleteFramebuffer(r),i}function MV(n,t){const e=Ip(n,t),s=n.createTexture();n.bindTexture(n.TEXTURE_2D,s),n.texImage2D(n.TEXTURE_2D,0,e.internalFormatHalfFloat,1,1,0,e.textureFormatFloat,e.textureTypeHalfFloat,null);const i=n.createFramebuffer();n.bindFramebuffer(n.FRAMEBUFFER,i),n.framebufferTexture2D(n.FRAMEBUFFER,n.COLOR_ATTACHMENT0,n.TEXTURE_2D,s,0);const a=n.checkFramebufferStatus(n.FRAMEBUFFER)===n.FRAMEBUFFER_COMPLETE;return n.bindTexture(n.TEXTURE_2D,null),n.bindFramebuffer(n.FRAMEBUFFER,null),n.deleteTexture(s),n.deleteFramebuffer(i),a}function VV(n){return n!==2?!1:Mn(n).fenceSync!=null}function ra(n,t){Array.isArray(n)||(n=[n]),n.forEach(e=>{e!=null&&v(e.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the WebGL backend.`)})}/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const at=z();at.registerFlag("HAS_WEBGL",()=>at.getNumber("WEBGL_VERSION")>0),at.registerFlag("WEBGL_VERSION",()=>l1(2)?2:l1(1)?1:0),at.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1),at.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>at.get("WEBGL_VERSION")===2),at.registerFlag("WEBGL_CPU_FORWARD",()=>!0),at.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1),at.registerFlag("WEBGL_PACK",()=>at.getBool("HAS_WEBGL")),at.registerFlag("WEBGL_PACK_NORMALIZATION",()=>at.getBool("WEBGL_PACK")),at.registerFlag("WEBGL_PACK_CLIP",()=>at.getBool("WEBGL_PACK")),at.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>at.getBool("WEBGL_PACK")),at.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>at.getBool("WEBGL_PACK")),at.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>at.getBool("WEBGL_PACK")),at.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>at.getBool("WEBGL_PACK")),at.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>at.getBool("WEBGL_PACK")),at.registerFlag("WEBGL_PACK_REDUCE",()=>at.getBool("WEBGL_PACK")),at.registerFlag("WEBGL_LAZILY_UNPACK",()=>at.getBool("WEBGL_PACK")),at.registerFlag("WEBGL_CONV_IM2COL",()=>at.getBool("WEBGL_PACK")),at.registerFlag("WEBGL_PACK_CONV2DTRANSPOSE",()=>at.getBool("WEBGL_PACK")),at.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>GV(at.getNumber("WEBGL_VERSION"))),at.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>LV(at.getNumber("WEBGL_VERSION"))),at.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{const n=at.getNumber("WEBGL_VERSION");return n===0?0:EV(n)}),at.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>at.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!hm()),at.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>DV(at.getNumber("WEBGL_VERSION"))),at.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>at.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:at.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")),at.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>WV(at.getNumber("WEBGL_VERSION"))),at.registerFlag("WEBGL_FENCE_API_ENABLED",()=>VV(at.getNumber("WEBGL_VERSION"))),at.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>at.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0),at.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",()=>-1,n=>{if(typeof n!="number")throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be a number but got ${n}.`);if(n<0&&n!==-1)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${n}.`)}),at.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>hm()?1:-1,n=>{if(typeof n!="number")throw new Error(`WEBGL_FLUSH_THRESHOLD must be a number but got ${n}.`);if(n<0&&n!==-1)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${n}.`)}),at.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128),at.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",()=>!1),at.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e5),at.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",()=>128),at.registerFlag("WEBGL_EXP_CONV",()=>!1),at.registerFlag("SOFTWARE_WEBGL_ENABLED",()=>at.getBool("IS_TEST")),at.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",()=>1/0),at.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",()=>!1),at.registerFlag("WEBGL2_ISNAN_CUSTOM",()=>!1),at.registerFlag("ENGINE_COMPILE_ONLY",()=>!1);/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function De(){let n,t,e,s,o,r,i,a,c,l;return z().getNumber("WEBGL_VERSION")===2?(n="#version 300 es",t="in",e="out",s="in",o="texture",r="outputColor",i="out vec4 outputColor;",a=z().getBool("WEBGL2_ISNAN_CUSTOM")?`
      bool isnan_custom(float val) {
        uint floatToUint = floatBitsToUint(val);
        return (floatToUint & 0x7fffffffu) > 0x7f800000u;
      }

      bvec4 isnan_custom(vec4 val) {
        return bvec4(isnan_custom(val.x),
          isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
      }

      #define isnan(value) isnan_custom(value)
    `:"",c="",l=`
      #define round(value) newRound(value)
      int newRound(float value) {
        return int(floor(value + 0.5));
      }

      ivec4 newRound(vec4 value) {
        return ivec4(floor(value + vec4(0.5)));
      }
    `):(n="",t="attribute",e="varying",s="varying",o="texture2D",r="gl_FragColor",i="",a=`
      #define isnan(value) isnan_custom(value)
      bool isnan_custom(float val) {
        return (val > 0. || val < 1. || val == 0.) ? false : true;
      }
      bvec4 isnan_custom(vec4 val) {
        return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
      }
    `,c=`
      uniform float INFINITY;

      bool isinf(float val) {
        return abs(val) == INFINITY;
      }
      bvec4 isinf(vec4 val) {
        return equal(abs(val), vec4(INFINITY));
      }
    `,l=`
      int round(float value) {
        return int(floor(value + 0.5));
      }

      ivec4 round(vec4 value) {
        return ivec4(floor(value + vec4(0.5)));
      }
    `),{version:n,attribute:t,varyingVs:e,varyingFs:s,texture2D:o,output:r,defineOutput:i,defineSpecialNaN:a,defineSpecialInf:c,defineRound:l}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function vo(n,t,e="index"){const s=ct(t);return s.map((o,r)=>{const i=`int ${n[r]} = ${e} / ${o}`,a=r===s.length-1?`int ${n[r+1]} = ${e} - ${n[r]} * ${o}`:`index -= ${n[r]} * ${o}`;return`${i}; ${a};`}).join("")}function Tl(n,t,e="index"){const s=ct(t);return s.map((o,r)=>{const i=`int ${n[r]} = ${e} / outShapeStrides[${r}]`,a=r===s.length-1?`int ${n[r+1]} = ${e} - ${n[r]} * outShapeStrides[${r}]`:`index -= ${n[r]} * outShapeStrides[${r}]`;return`${i}; ${a};`}).join("")}function FV(n,t){const e=n.length,s=n.map(r=>`${t}[${r}]`),o=new Array(e-1);o[e-2]=s[e-1];for(let r=e-3;r>=0;--r)o[r]=`(${o[r+1]} * ${s[r+1]})`;return o}function zV(n,t,e="index"){const s=n.map((r,i)=>i),o=FV(s,t);return o.map((r,i)=>{const a=`int ${n[i]} = ${e} / ${o[i]}`,c=i===o.length-1?`int ${n[i+1]} = ${e} - ${n[i]} * ${o[i]}`:`index -= ${n[i]} * ${o[i]}`;return`${a}; ${c};`}).join("")}function Tp(n){const t=ct(n).map(e=>e.toString());return`
  int getFlatIndex(ivec3 coords) {
    return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
  }
`}function Np(){return`
  int getFlatIndex(ivec3 coords) {
    return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
  }
`}const u1=`
  const float FLOAT_MAX = 1.70141184e38;
  const float FLOAT_MIN = 1.17549435e-38;

  lowp vec4 encode_float(highp float v) {
    if (isnan(v)) {
      return vec4(255, 255, 255, 255);
    }

    highp float av = abs(v);

    if(av < FLOAT_MIN) {
      return vec4(0.0, 0.0, 0.0, 0.0);
    } else if(v > FLOAT_MAX) {
      return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
    } else if(v < -FLOAT_MAX) {
      return vec4(0.0, 0.0,  128.0, 255.0) / 255.0;
    }

    highp vec4 c = vec4(0,0,0,0);

    highp float e = floor(log2(av));
    highp float m = exp2(fract(log2(av))) - 1.0;

    c[2] = floor(128.0 * m);
    m -= c[2] / 128.0;
    c[1] = floor(32768.0 * m);
    m -= c[1] / 32768.0;
    c[0] = floor(8388608.0 * m);

    highp float ebias = e + 127.0;
    c[3] = floor(ebias / 2.0);
    ebias -= c[3] * 2.0;
    c[2] += floor(ebias) * 128.0;

    c[3] += 128.0 * step(0.0, -v);

    return c / 255.0;
  }
`;/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const{getBroadcastDims:d1}=DT;function XV(n,t,e){const s=[];if(n.forEach(p=>{const f=Z(p.shapeInfo.logicalShape);if(p.shapeInfo.isUniform?s.push(`uniform float ${p.name}${f>1?`[${f}]`:""};`):(s.push(`uniform sampler2D ${p.name};`),s.push(`uniform int offset${p.name};`)),e.enableShapeUniforms){const{uniformShape:m}=Rp(e.packedInputs,p.shapeInfo.logicalShape,p.shapeInfo.texShape);switch(m.length){case 1:s.push(`uniform int ${p.name}Shape;`);break;case 2:s.push(`uniform ivec2 ${p.name}Shape;`);break;case 3:s.push(`uniform ivec3 ${p.name}Shape;`);break;case 4:s.push(`uniform ivec4 ${p.name}Shape;`);break}s.push(`uniform ivec2 ${p.name}TexShape;`)}}),e.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;");break}s.push("uniform ivec2 outTexShape;")}e.customUniforms&&e.customUniforms.forEach(p=>{s.push(`uniform ${p.type} ${p.name}${p.arrayIndex?`[${p.arrayIndex}]`:""};`)});const o=s.join(`
`),r=n.map(p=>AV(p,t,e.packedInputs,e.enableShapeUniforms)).join(`
`),i=t.texShape,a=De(),c=KV(a);let l,u,d=HV(a);return t.isPacked?(l=PV(t.logicalShape,i,e.enableShapeUniforms),u=BV(a)):(l=OV(t.logicalShape,i,e.enableShapeUniforms),u=ZV(a)),e.packedInputs&&(d+=QV),[d,c,u,o,l,r,e.userCode].join(`
`)}function hr(n,t=!1){const e=n.shapeInfo.logicalShape;switch(e.length){case 0:return cF(n,t);case 1:return uF(n,t);case 2:return hF(n,t);case 3:return fF(n,t);case 4:return gF(n,t);case 5:return bF(n);case 6:return xF(n);default:throw new Error(`${e.length}-D input sampling is not yet supported`)}}function h1(n,t){switch(n.shapeInfo.logicalShape.length){case 0:return aF(n);case 1:return lF(n,t);case 2:return dF(n,t);case 3:return pF(n,t);default:return mF(n,t)}}function AV(n,t,e=!1,s){let o="";e?o+=h1(n,s):o+=hr(n,s);const r=n.shapeInfo.logicalShape,i=t.logicalShape;return r.length<=i.length&&(e?o+=yF(n,t):o+=IF(n,t)),o}function PV(n,t,e){switch(n.length){case 0:return p1();case 1:return JV(n,t,e);case 2:return rF(n,t,e);case 3:return qV(n,t,e);default:return eF(n,t,e)}}function OV(n,t,e){switch(n.length){case 0:return p1();case 1:return jV(n,t,e);case 2:return iF(n,t,e);case 3:return tF(n,t,e);case 4:return nF(n,t,e);case 5:return sF(n,t);case 6:return oF(n,t);default:throw new Error(`${n.length}-D output sampling is not yet supported`)}}function KV(n){return`
    float sampleTexture(sampler2D textureSampler, vec2 uv) {
      return ${n.texture2D}(textureSampler, uv).r;
    }
  `}function ZV(n){return`
    void setOutput(float val) {
      ${n.output} = vec4(val, 0, 0, 0);
    }
  `}function BV(n){return`
    void setOutput(vec4 val) {
      ${n.output} = val;
    }
  `}function HV(n){return`${n.version}
    precision highp float;
    precision highp int;
    precision highp sampler2D;
    ${n.varyingFs} vec2 resultUV;
    ${n.defineOutput}
    const vec2 halfCR = vec2(0.5, 0.5);

    struct ivec5
    {
      int x;
      int y;
      int z;
      int w;
      int u;
    };

    struct ivec6
    {
      int x;
      int y;
      int z;
      int w;
      int u;
      int v;
    };

    uniform float NAN;
    ${n.defineSpecialNaN}
    ${n.defineSpecialInf}
    ${n.defineRound}

    int imod(int x, int y) {
      return x - y * (x / y);
    }

    int idiv(int a, int b, float sign) {
      int res = a / b;
      int mod = imod(a, b);
      if (sign < 0. && mod != 0) {
        res -= 1;
      }
      return res;
    }

    //Based on the work of Dave Hoskins
    //https://www.shadertoy.com/view/4djSRW
    #define HASHSCALE1 443.8975
    float random(float seed){
      vec2 p = resultUV * seed;
      vec3 p3  = fract(vec3(p.xyx) * HASHSCALE1);
      p3 += dot(p3, p3.yzx + 19.19);
      return fract((p3.x + p3.y) * p3.z);
    }

    ${_V}
    ${UV}
    ${YV}
  `}const _V=`
vec2 uvFromFlat(int texNumR, int texNumC, int index) {
  int texR = index / texNumC;
  int texC = index - texR * texNumC;
  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
  int texelIndex = index / 2;
  int texR = texelIndex / texNumC;
  int texC = texelIndex - texR * texNumC;
  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`,UV=`
vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,
  int texNumC, int row, int col) {
  int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
  int texR = texelIndex / texNumC;
  int texC = texelIndex - texR * texNumC;
  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`,YV=`
vec2 packedUVfrom3D(int texNumR, int texNumC,
    int texelsInBatch, int texelsInLogicalRow, int b,
    int row, int col) {
  int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);
  int texR = index / texNumC;
  int texC = index - texR * texNumC;
  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`,QV=`
  float getChannel(vec4 frag, vec2 innerDims) {
    vec2 modCoord = mod(innerDims, 2.);
    return modCoord.x == 0. ?
      (modCoord.y == 0. ? frag.r : frag.g) :
      (modCoord.y == 0. ? frag.b : frag.a);
  }
  float getChannel(vec4 frag, int dim) {
    float modCoord = mod(float(dim), 2.);
    return modCoord == 0. ? frag.r : frag.g;
  }
`;function p1(){return`
    int getOutputCoords() {
      return 0;
    }
  `}function JV(n,t,e){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return s[0]===1?e?`
      int getOutputCoords() {
        return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));
      }
    `:`
      int getOutputCoords() {
        return 2 * int(resultUV.x * ${s[1]}.0);
      }
    `:s[1]===1?e?`
      int getOutputCoords() {
        return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));
      }
    `:`
      int getOutputCoords() {
        return 2 * int(resultUV.y * ${s[0]}.0);
      }
    `:e?`
    int getOutputCoords() {
      ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
      ivec2 resTexRC = ivec2(resultUV.yx *
                             vec2(packedTexShape[0], packedTexShape[1]));
      return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y);
    }
  `:`
    int getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
                             vec2(${s[0]}, ${s[1]}));
      return 2 * (resTexRC.x * ${s[1]} + resTexRC.y);
    }
  `}function jV(n,t,e){return t[0]===1?e?`
      int getOutputCoords() {
        return int(resultUV.x * float(outTexShape[1]));
      }
    `:`
      int getOutputCoords() {
        return int(resultUV.x * ${t[1]}.0);
      }
    `:t[1]===1?e?`
      int getOutputCoords() {
        return int(resultUV.y * float(outTexShape[0]));
      }
    `:`
      int getOutputCoords() {
        return int(resultUV.y * ${t[0]}.0);
      }
    `:e?`
    int getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
                             vec2(outTexShape[0], outTexShape[1]));
      return resTexRC.x * outTexShape[1] + resTexRC.y;
    }
  `:`
    int getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
                             vec2(${t[0]}, ${t[1]}));
      return resTexRC.x * ${t[1]} + resTexRC.y;
    }
  `}function qV(n,t,e){if(e)return`
    ivec3 getOutputCoords() {
      ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
      int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));
      int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));
      ivec2 resTexRC = ivec2(resultUV.yx *
                             vec2(packedTexShape[0], packedTexShape[1]));
      int index = resTexRC.x * packedTexShape[1] + resTexRC.y;

      int b = index / texelsInBatch;
      index -= b * texelsInBatch;

      int r = 2 * (index / texelsInLogicalRow);
      int c = imod(index, texelsInLogicalRow) * 2;

      return ivec3(b, r, c);
    }
  `;const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],o=Math.ceil(n[2]/2),r=o*Math.ceil(n[1]/2);return`
    ivec3 getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
                             vec2(${s[0]}, ${s[1]}));
      int index = resTexRC.x * ${s[1]} + resTexRC.y;

      int b = index / ${r};
      index -= b * ${r};

      int r = 2 * (index / ${o});
      int c = imod(index, ${o}) * 2;

      return ivec3(b, r, c);
    }
  `}function tF(n,t,e){if(e)return`
  ivec3 getOutputCoords() {
    ivec2 resTexRC = ivec2(resultUV.yx *
                           vec2(outTexShape[0], outTexShape[1]));
    int index = resTexRC.x * outTexShape[1] + resTexRC.y;
    ${Tl(["r","c","d"],n)}
    return ivec3(r, c, d);
  }
`;const s=vo(["r","c","d"],n);return`
    ivec3 getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
                             vec2(${t[0]}, ${t[1]}));
      int index = resTexRC.x * ${t[1]} + resTexRC.y;
      ${s}
      return ivec3(r, c, d);
    }
  `}function eF(n,t,e){if(e)return`
    ivec4 getOutputCoords() {
      ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
      ivec2 resTexRC = ivec2(resultUV.yx *
                             vec2(packedTexShape[0], packedTexShape[1]));
      int index = resTexRC.x * packedTexShape[1] + resTexRC.y;

      int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));
      int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));
      int texelsInBatchN = texelsInBatch * outShape[1];

      int b2 = index / texelsInBatchN;
      index -= b2 * texelsInBatchN;

      int b = index / texelsInBatch;
      index -= b * texelsInBatch;

      int r = 2 * (index / texelsInLogicalRow);
      int c = imod(index, texelsInLogicalRow) * 2;

      return ivec4(b2, b, r, c);
    }
  `;const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],o=Math.ceil(n[n.length-1]/2),r=o*Math.ceil(n[n.length-2]/2);let i=r,a="",c="b, r, c";for(let l=2;l<n.length-1;l++)i*=n[n.length-l-1],a=`
      int b${l} = index / ${i};
      index -= b${l} * ${i};
    `+a,c=`b${l}, `+c;return`
    ivec${n.length} getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
                             vec2(${s[0]}, ${s[1]}));
      int index = resTexRC.x * ${s[1]} + resTexRC.y;

      ${a}

      int b = index / ${r};
      index -= b * ${r};

      int r = 2 * (index / ${o});
      int c = imod(index, ${o}) * 2;

      return ivec${n.length}(${c});
    }
  `}function nF(n,t,e){if(e)return`
    ivec4 getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
        vec2(outTexShape[0], outTexShape[1]));
      int index = resTexRC.x * outTexShape[1] + resTexRC.y;
      ${Tl(["r","c","d","d2"],n)}
      return ivec4(r, c, d, d2);
    }
  `;const s=vo(["r","c","d","d2"],n);return`
    ivec4 getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
        vec2(${t[0]}, ${t[1]}));
      int index = resTexRC.x * ${t[1]} + resTexRC.y;
      ${s}
      return ivec4(r, c, d, d2);
    }
  `}function sF(n,t){const e=vo(["r","c","d","d2","d3"],n);return`
    ivec5 getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},
                             ${t[1]}));

      int index = resTexRC.x * ${t[1]} + resTexRC.y;

      ${e}

      ivec5 outShape = ivec5(r, c, d, d2, d3);
      return outShape;
    }
  `}function oF(n,t){const e=vo(["r","c","d","d2","d3","d4"],n);return`
    ivec6 getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
        vec2(${t[0]}, ${t[1]}));
      int index = resTexRC.x * ${t[1]} + resTexRC.y;

      ${e}

      ivec6 result = ivec6(r, c, d, d2, d3, d4);
      return result;
    }
  `}function rF(n,t,e){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(Rt(n,t))return e?`
      ivec2 getOutputCoords() {
        ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
        return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));
      }
    `:`
      ivec2 getOutputCoords() {
        return 2 * ivec2(resultUV.yx * vec2(${s[0]}, ${s[1]}));
      }
    `;const o=Math.ceil(n[1]/2);return e?`
    ivec2 getOutputCoords() {
      ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
      int texelsInLogicalRow = int(ceil(float(outShape[1]) / 2.0));
      ivec2 resTexRC = ivec2(resultUV.yx *
                             vec2(packedTexShape[0], packedTexShape[1]));

      int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
      int r = 2 * (index / texelsInLogicalRow);
      int c = imod(index, texelsInLogicalRow) * 2;

      return ivec2(r, c);
    }
  `:`
    ivec2 getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
                             vec2(${s[0]}, ${s[1]}));

      int index = resTexRC.x * ${s[1]} + resTexRC.y;
      int r = 2 * (index / ${o});
      int c = imod(index, ${o}) * 2;

      return ivec2(r, c);
    }
  `}function iF(n,t,e){return Rt(n,t)?e?`
      ivec2 getOutputCoords() {
        return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));
      }
    `:`
      ivec2 getOutputCoords() {
        return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
      }
    `:n[1]===1?e?`
      ivec2 getOutputCoords() {
        ivec2 resTexRC = ivec2(resultUV.yx *
                               vec2(outTexShape[0], outTexShape[1]));
        int index = resTexRC.x * outTexShape[1] + resTexRC.y;
        return ivec2(index, 0);
      }
    `:`
      ivec2 getOutputCoords() {
        ivec2 resTexRC = ivec2(resultUV.yx *
                               vec2(${t[0]}, ${t[1]}));
        int index = resTexRC.x * ${t[1]} + resTexRC.y;
        return ivec2(index, 0);
      }
    `:n[0]===1?e?`
      ivec2 getOutputCoords() {
        ivec2 resTexRC = ivec2(resultUV.yx *
                               vec2(outTexShape[0], outTexShape[1]));
        int index = resTexRC.x * outTexShape[1] + resTexRC.y;
        return ivec2(0, index);
      }
    `:`
      ivec2 getOutputCoords() {
        ivec2 resTexRC = ivec2(resultUV.yx *
                               vec2(${t[0]}, ${t[1]}));
        int index = resTexRC.x * ${t[1]} + resTexRC.y;
        return ivec2(0, index);
      }
    `:e?`
    ivec2 getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
                             vec2(outTexShape[0], outTexShape[1]));
      int index = resTexRC.x * outTexShape[1] + resTexRC.y;
      int r = index / outShape[1];
      int c = index - r * outShape[1];
      return ivec2(r, c);
    }
  `:`
    ivec2 getOutputCoords() {
      ivec2 resTexRC = ivec2(resultUV.yx *
                             vec2(${t[0]}, ${t[1]}));
      int index = resTexRC.x * ${t[1]} + resTexRC.y;
      int r = index / ${n[1]};
      int c = index - r * ${n[1]};
      return ivec2(r, c);
    }
  `}function So(n){return`offset${n}`}function aF(n){const t=n.name,e="get"+t.charAt(0).toUpperCase()+t.slice(1),s=De();return`
    vec4 ${e}() {
      return ${s.texture2D}(${t}, halfCR);
    }
  `}function cF(n,t){const e=n.name,s="get"+e.charAt(0).toUpperCase()+e.slice(1);if(n.shapeInfo.isUniform)return`float ${s}() {return ${e};}`;const[o,r]=n.shapeInfo.texShape;if(o===1&&r===1)return`
      float ${s}() {
        return sampleTexture(${e}, halfCR);
      }
    `;const i=So(e);if(t)return`
    float ${s}() {
      vec2 uv = uvFromFlat(${e}TexShape[0], ${e}TexShape[1], ${i});
      return sampleTexture(${e}, uv);
    }
  `;const[a,c]=n.shapeInfo.texShape;return`
    float ${s}() {
      vec2 uv = uvFromFlat(${a}, ${c}, ${i});
      return sampleTexture(${e}, uv);
    }
  `}function lF(n,t){const e=n.name,s="get"+e.charAt(0).toUpperCase()+e.slice(1),o=n.shapeInfo.texShape,r=De();if(t)return`
    vec4 ${s}(int index) {
      ivec2 packedTexShape = ivec2(ceil(float(${e}TexShape[0]) / 2.0), ceil(float(${e}TexShape[1]) / 2.0));
      vec2 uv = packedUVfrom1D(
        packedTexShape[0], packedTexShape[1], index);
      return ${r.texture2D}(${e}, uv);
    }
  `;const i=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)];return`
    vec4 ${s}(int index) {
      vec2 uv = packedUVfrom1D(
        ${i[0]}, ${i[1]}, index);
      return ${r.texture2D}(${e}, uv);
    }
  `}function uF(n,t){const e=n.name,s="get"+e.charAt(0).toUpperCase()+e.slice(1);if(n.shapeInfo.isUniform)return`
      float ${s}(int index) {
        ${pr(n)}
      }
    `;const o=n.shapeInfo.texShape,r=o[0],i=o[1];if(i===1&&r===1)return`
      float ${s}(int index) {
        return sampleTexture(${e}, halfCR);
      }
    `;const a=So(e);return i===1?t?`
      float ${s}(int index) {
        vec2 uv = vec2(0.5, (float(index + ${a}) + 0.5) / float(${e}TexShape[0]));
        return sampleTexture(${e}, uv);
      }
    `:`
      float ${s}(int index) {
        vec2 uv = vec2(0.5, (float(index + ${a}) + 0.5) / ${r}.0);
        return sampleTexture(${e}, uv);
      }
    `:r===1?t?`
      float ${s}(int index) {
        vec2 uv = vec2((float(index + ${a}) + 0.5) / float(${e}TexShape[1]), 0.5);
        return sampleTexture(${e}, uv);
      }
    `:`
      float ${s}(int index) {
        vec2 uv = vec2((float(index + ${a}) + 0.5) / ${i}.0, 0.5);
        return sampleTexture(${e}, uv);
      }
    `:t?`
    float ${s}(int index) {
      vec2 uv = uvFromFlat(${e}TexShape[0], ${e}TexShape[1], index + ${a});
      return sampleTexture(${e}, uv);
    }
  `:`
    float ${s}(int index) {
      vec2 uv = uvFromFlat(${r}, ${i}, index + ${a});
      return sampleTexture(${e}, uv);
    }
  `}function dF(n,t){const e=n.shapeInfo.logicalShape,s=n.name,o="get"+s.charAt(0).toUpperCase()+s.slice(1),r=n.shapeInfo.texShape,i=r[0],a=r[1],c=De();if(r!=null&&Rt(e,r))return t?`
      vec4 ${o}(int row, int col) {
        vec2 uv = (vec2(col, row) + halfCR) / vec2(${s}TexShape[1], ${s}TexShape[0]);

        return ${c.texture2D}(${s}, uv);
      }
    `:`
      vec4 ${o}(int row, int col) {
        vec2 uv = (vec2(col, row) + halfCR) / vec2(${a}.0, ${i}.0);

        return ${c.texture2D}(${s}, uv);
      }
    `;if(t)return`
    vec4 ${o}(int row, int col) {
      ivec2 packedTexShape = ivec2(ceil(float(${s}TexShape[0]) / 2.0), ceil(float(${s}TexShape[1]) / 2.0));
      int valuesPerRow = int(ceil(float(${s}Shape[1]) / 2.0));
      vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);
      return ${c.texture2D}(${s}, uv);
    }
  `;const l=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],u=Math.ceil(e[1]/2);return`
    vec4 ${o}(int row, int col) {
      vec2 uv = packedUVfrom2D(${u}, ${l[0]}, ${l[1]}, row, col);
      return ${c.texture2D}(${s}, uv);
    }
  `}function hF(n,t){const e=n.shapeInfo.logicalShape,s=n.name,o="get"+s.charAt(0).toUpperCase()+s.slice(1),r=n.shapeInfo.texShape;if(r!=null&&Rt(e,r)){if(t)return`
      float ${o}(int row, int col) {
        vec2 uv = (vec2(col, row) + halfCR) / vec2(${s}TexShape[1], ${s}TexShape[0]);
        return sampleTexture(${s}, uv);
      }
    `;const h=r[0],p=r[1];return`
    float ${o}(int row, int col) {
      vec2 uv = (vec2(col, row) + halfCR) / vec2(${p}.0, ${h}.0);
      return sampleTexture(${s}, uv);
    }
  `}const{newShape:i,keptDims:a}=fs(e),c=i;if(c.length<e.length){const h=fr(n,c),p=["row","col"];return`
      ${hr(h,t)}
      float ${o}(int row, int col) {
        return ${o}(${mr(p,a)});
      }
    `}if(n.shapeInfo.isUniform)return`
      float ${o}(int row, int col) {
        int index = round(dot(vec2(row, col), vec2(${e[1]}, 1)));
        ${pr(n)}
      }
    `;const l=r[0],u=r[1],d=So(s);return u===1?t?`
      float ${o}(int row, int col) {
        float index = dot(vec3(row, col, ${d}), vec3(${s}Shape[1], 1, 1));
        vec2 uv = vec2(0.5, (index + 0.5) / float(${s}TexShape[0]));
        return sampleTexture(${s}, uv);
      }
    `:`
    float ${o}(int row, int col) {
      float index = dot(vec3(row, col, ${d}), vec3(${e[1]}, 1, 1));
      vec2 uv = vec2(0.5, (index + 0.5) / ${l}.0);
      return sampleTexture(${s}, uv);
    }
  `:l===1?t?`
      float ${o}(int row, int col) {
        float index = dot(vec3(row, col, ${d}), vec3(${s}Shape[1], 1, 1));
        vec2 uv = vec2((index + 0.5) / float(${s}TexShape[1]), 0.5);
        return sampleTexture(${s}, uv);
      }
    `:`
    float ${o}(int row, int col) {
      float index = dot(vec3(row, col, ${d}), vec3(${e[1]}, 1, 1));
      vec2 uv = vec2((index + 0.5) / ${u}.0, 0.5);
      return sampleTexture(${s}, uv);
    }
  `:t?`
      float ${o}(int row, int col) {
        // Explicitly use integer operations as dot() only works on floats.
        int index = row * ${s}Shape[1] + col + ${d};
        vec2 uv = uvFromFlat(${s}TexShape[0], ${s}TexShape[1], index);
        return sampleTexture(${s}, uv);
      }
    `:`
  float ${o}(int row, int col) {
    // Explicitly use integer operations as dot() only works on floats.
    int index = row * ${e[1]} + col + ${d};
    vec2 uv = uvFromFlat(${l}, ${u}, index);
    return sampleTexture(${s}, uv);
  }
`}function pF(n,t){const e=n.shapeInfo.logicalShape,s=n.name,o="get"+s.charAt(0).toUpperCase()+s.slice(1),r=n.shapeInfo.texShape,i=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)];if(e[0]===1){const h=e.slice(1),p=[1,2],f=fr(n,h),m=["b","row","col"];return`
        ${h1(f,t)}
        vec4 ${o}(int b, int row, int col) {
          return ${o}(${mr(m,p)});
        }
      `}const a=De();if(t)return`
    vec4 ${o}(int b, int row, int col) {
      ivec2 packedTexShape = ivec2(ceil(float(${s}TexShape[0]) / 2.0), ceil(float(${s}TexShape[1]) / 2.0));
      int valuesPerRow = int(ceil(float(${s}Shape[2]) / 2.0));
      int texelsInBatch = valuesPerRow * int(ceil(float(${s}Shape[1]) / 2.0));
      vec2 uv = packedUVfrom3D(
        packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);
      return ${a.texture2D}(${s}, uv);
    }
  `;const c=i[0],l=i[1],u=Math.ceil(e[2]/2),d=u*Math.ceil(e[1]/2);return`
    vec4 ${o}(int b, int row, int col) {
      vec2 uv = packedUVfrom3D(
        ${c}, ${l}, ${d}, ${u}, b, row, col);
      return ${a.texture2D}(${s}, uv);
    }
  `}function fF(n,t){const e=n.shapeInfo.logicalShape,s=n.name,o="get"+s.charAt(0).toUpperCase()+s.slice(1),r=e[1]*e[2],i=e[2],{newShape:a,keptDims:c}=fs(e),l=a;if(l.length<e.length){const m=fr(n,l),g=["row","col","depth"];return`
        ${hr(m,t)}
        float ${o}(int row, int col, int depth) {
          return ${o}(${mr(g,c)});
        }
      `}if(n.shapeInfo.isUniform)return`
      float ${o}(int row, int col, int depth) {
        int index = round(dot(vec3(row, col, depth),
                          vec3(${r}, ${i}, 1)));
        ${pr(n)}
      }
    `;const u=n.shapeInfo.texShape,d=u[0],h=u[1],p=n.shapeInfo.flatOffset;if(h===r&&p==null)return t?`
      float ${o}(int row, int col, int depth) {
        int stride1 = ${s}Shape[2];
        float texR = float(row);
        float texC = dot(vec2(col, depth), vec2(stride1, 1));
        vec2 uv = (vec2(texC, texR) + halfCR) /
                   vec2(${s}TexShape[1], ${s}TexShape[0]);
        return sampleTexture(${s}, uv);
      }
    `:`
        float ${o}(int row, int col, int depth) {
          float texR = float(row);
          float texC = dot(vec2(col, depth), vec2(${i}, 1));
          vec2 uv = (vec2(texC, texR) + halfCR) /
                     vec2(${h}.0, ${d}.0);
          return sampleTexture(${s}, uv);
        }
      `;if(h===i&&p==null)return t?`
      float ${o}(int row, int col, int depth) {
        float texR = dot(vec2(row, col), vec2(${s}Shape[1], 1));
        float texC = float(depth);
        vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${s}TexShape[1], ${s}TexShape[0]);
        return sampleTexture(${s}, uv);
      }
    `:`
    float ${o}(int row, int col, int depth) {
      float texR = dot(vec2(row, col), vec2(${e[1]}, 1));
      float texC = float(depth);
      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${h}.0, ${d}.0);
      return sampleTexture(${s}, uv);
    }
  `;const f=So(s);return t?`
    float ${o}(int row, int col, int depth) {
      // Explicitly use integer operations as dot() only works on floats.
      int stride0 = ${s}Shape[1] * ${s}Shape[2];
      int stride1 = ${s}Shape[2];
      int index = row * stride0 + col * stride1 + depth + ${f};
      vec2 uv = uvFromFlat(${s}TexShape[0], ${s}TexShape[1], index);
      return sampleTexture(${s}, uv);
    }
    `:`
      float ${o}(int row, int col, int depth) {
        // Explicitly use integer operations as dot() only works on floats.
        int index = row * ${r} + col * ${i} + depth + ${f};
        vec2 uv = uvFromFlat(${d}, ${h}, index);
        return sampleTexture(${s}, uv);
      }
  `}function mF(n,t){const e=n.name,s="get"+e.charAt(0).toUpperCase()+e.slice(1),o=De();if(t)return`
    vec4 ${s}(int b2, int b, int row, int col) {
      int valuesPerRow = int(ceil(float(${e}Shape[3]) / 2.0));
      int texelsInBatch = valuesPerRow * int(ceil(float(${e}Shape[2]) / 2.0));
      int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);
      texelsInBatch *= ${e}Shape[1];
      index = b2 * texelsInBatch + index;
      ivec2 packedTexShape = ivec2(ceil(float(${e}TexShape[0]) / 2.0), ceil(float(${e}TexShape[1]) / 2.0));
      int texR = index / packedTexShape[1];
      int texC = index - texR * packedTexShape[1];
      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${o.texture2D}(${e}, uv);
    }
  `;const r=n.shapeInfo.logicalShape,i=r.length,a=n.shapeInfo.texShape,c=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],l=c[0],u=c[1],d=Math.ceil(r[i-1]/2);let h=d*Math.ceil(r[i-2]/2),p="int b, int row, int col",f=`b * ${h} + (row / 2) * ${d} + (col / 2)`;for(let m=2;m<i-1;m++)p=`int b${m}, `+p,h*=r[i-m-1],f=`b${m} * ${h} + `+f;return`
    vec4 ${s}(${p}) {
      int index = ${f};
      int texR = index / ${u};
      int texC = index - texR * ${u};
      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${u}, ${l});
      return ${o.texture2D}(${e}, uv);
    }
  `}function gF(n,t){const e=n.shapeInfo.logicalShape,s=n.name,o="get"+s.charAt(0).toUpperCase()+s.slice(1),r=e[3],i=e[2]*r,a=e[1]*i,{newShape:c,keptDims:l}=fs(e);if(c.length<e.length){const x=fr(n,c),I=["row","col","depth","depth2"];return`
      ${hr(x,t)}
      float ${o}(int row, int col, int depth, int depth2) {
        return ${o}(${mr(I,l)});
      }
    `}if(n.shapeInfo.isUniform)return`
      float ${o}(int row, int col, int depth, int depth2) {
        int index = round(dot(vec4(row, col, depth, depth2),
                          vec4(${a}, ${i}, ${r}, 1)));
        ${pr(n)}
      }
    `;const u=n.shapeInfo.flatOffset,d=n.shapeInfo.texShape,h=d[0],p=d[1],f=`int stride2 = ${s}Shape[3];`,m=`int stride1 = ${s}Shape[2] * stride2;`,g=`int stride0 = ${s}Shape[1] * stride1;`;if(p===a&&u==null)return t?`
      float ${o}(int row, int col, int depth, int depth2) {
        ${f}
        ${m}
        float texR = float(row);
        float texC =
            dot(vec3(col, depth, depth2),
                vec3(stride1, stride2, 1));
        vec2 uv = (vec2(texC, texR) + halfCR) /
                   vec2(${s}TexShape[1], ${s}TexShape[0]);
        return sampleTexture(${s}, uv);
      }
    `:`
      float ${o}(int row, int col, int depth, int depth2) {
        float texR = float(row);
        float texC =
            dot(vec3(col, depth, depth2),
                vec3(${i}, ${r}, 1));
        vec2 uv = (vec2(texC, texR) + halfCR) /
                   vec2(${p}.0, ${h}.0);
        return sampleTexture(${s}, uv);
      }
    `;if(p===r&&u==null)return t?`
      float ${o}(int row, int col, int depth, int depth2) {
        float texR = dot(vec3(row, col, depth),
                         vec3(${s}Shape[1] * ${s}Shape[2], ${s}Shape[2], 1));
        float texC = float(depth2);
        vec2 uv = (vec2(texC, texR) + halfCR) /
                  vec2(${s}TexShape[1], ${s}TexShape[0]);
        return sampleTexture(${s}, uv);
      }
    `:`
      float ${o}(int row, int col, int depth, int depth2) {
        float texR = dot(vec3(row, col, depth),
                         vec3(${e[1]*e[2]}, ${e[2]}, 1));
        float texC = float(depth2);
        vec2 uv = (vec2(texC, texR) + halfCR) /
                  vec2(${p}.0, ${h}.0);
        return sampleTexture(${s}, uv);
      }
    `;const b=So(s);return t?`
    float ${o}(int row, int col, int depth, int depth2) {
      // Explicitly use integer operations as dot() only works on floats.
      ${f}
      ${m}
      ${g}
      int index = row * stride0 + col * stride1 +
          depth * stride2 + depth2;
      vec2 uv = uvFromFlat(${s}TexShape[0], ${s}TexShape[1], index + ${b});
      return sampleTexture(${s}, uv);
    }
  `:`
    float ${o}(int row, int col, int depth, int depth2) {
      // Explicitly use integer operations as dot() only works on floats.
      int index = row * ${a} + col * ${i} +
          depth * ${r} + depth2;
      vec2 uv = uvFromFlat(${h}, ${p}, index + ${b});
      return sampleTexture(${s}, uv);
    }
  `}function bF(n){const t=n.shapeInfo.logicalShape,e=n.name,s="get"+e.charAt(0).toUpperCase()+e.slice(1),o=t[4],r=t[3]*o,i=t[2]*r,a=t[1]*i,{newShape:c,keptDims:l}=fs(t);if(c.length<t.length){const m=fr(n,c),g=["row","col","depth","depth2","depth3"];return`
      ${hr(m)}
      float ${s}(int row, int col, int depth, int depth2, int depth3) {
        return ${s}(${mr(g,l)});
      }
    `}if(n.shapeInfo.isUniform)return`
      float ${s}(int row, int col, int depth, int depth2, int depth3) {
        float index = dot(
          vec4(row, col, depth, depth2),
          vec4(${a}, ${i}, ${r}, ${o})) +
          depth3;
        ${pr(n)}
      }
    `;const u=n.shapeInfo.flatOffset,d=n.shapeInfo.texShape,h=d[0],p=d[1];if(p===a&&u==null)return`
      float ${s}(int row, int col, int depth, int depth2, int depth3) {
        int texR = row;
        float texC = dot(vec4(col, depth, depth2, depth3),
                         vec4(${i}, ${r}, ${o}, 1));
        vec2 uv = (vec2(texC, texR) + halfCR) /
                   vec2(${p}.0, ${h}.0);
        return sampleTexture(${e}, uv);
      }
    `;if(p===o&&u==null)return`
      float ${s}(int row, int col, int depth, int depth2, int depth3) {
        float texR = dot(
          vec4(row, col, depth, depth2),
          vec4(${t[1]*t[2]*t[3]},
               ${t[2]*t[3]}, ${t[3]}, 1));
        int texC = depth3;
        vec2 uv = (vec2(texC, texR) + halfCR) /
                  vec2(${p}.0, ${h}.0);
        return sampleTexture(${e}, uv);
      }
    `;const f=So(e);return`
    float ${s}(int row, int col, int depth, int depth2, int depth3) {
      // Explicitly use integer operations as dot() only works on floats.
      int index = row * ${a} + col * ${i} + depth * ${r} +
          depth2 * ${o} + depth3 + ${f};
      vec2 uv = uvFromFlat(${h}, ${p}, index);
      return sampleTexture(${e}, uv);
    }
  `}function xF(n){const t=n.shapeInfo.logicalShape,e=n.name,s="get"+e.charAt(0).toUpperCase()+e.slice(1),{newShape:o,keptDims:r}=fs(t);if(o.length<t.length){const g=fr(n,o),b=["row","col","depth","depth2","depth3","depth4"];return`
      ${hr(g)}
      float ${s}(int row, int col, int depth,
                    int depth2, int depth3, int depth4) {
        return ${s}(${mr(b,r)});
      }
    `}const i=t[5],a=t[4]*i,c=t[3]*a,l=t[2]*c,u=t[1]*l;if(n.shapeInfo.isUniform)return`
      float ${s}(int row, int col, int depth,
                  int depth2, int depth3, int depth4) {
        int index = round(dot(
          vec4(row, col, depth, depth2),
          vec4(${u}, ${l}, ${c}, ${a})) +
          dot(
            vec2(depth3, depth4),
            vec2(${i}, 1)));
        ${pr(n)}
      }
    `;const d=n.shapeInfo.flatOffset,h=n.shapeInfo.texShape,p=h[0],f=h[1];if(f===u&&d==null)return`
      float ${s}(int row, int col, int depth,
                    int depth2, int depth3, int depth4) {
        int texR = row;
        float texC = dot(vec4(col, depth, depth2, depth3),
          vec4(${l}, ${c}, ${a}, ${i})) +
               float(depth4);
        vec2 uv = (vec2(texC, texR) + halfCR) /
                   vec2(${f}.0, ${p}.0);
        return sampleTexture(${e}, uv);
      }
    `;if(f===i&&d==null)return`
      float ${s}(int row, int col, int depth,
                    int depth2, int depth3, int depth4) {
        float texR = dot(vec4(row, col, depth, depth2),
          vec4(${t[1]*t[2]*t[3]*t[4]},
               ${t[2]*t[3]*t[4]},
               ${t[3]*t[4]},
               ${t[4]})) + float(depth3);
        int texC = depth4;
        vec2 uv = (vec2(texC, texR) + halfCR) /
                  vec2(${f}.0, ${p}.0);
        return sampleTexture(${e}, uv);
      }
    `;const m=So(e);return`
    float ${s}(int row, int col, int depth,
                  int depth2, int depth3, int depth4) {
      // Explicitly use integer operations as dot() only works on floats.
      int index = row * ${u} + col * ${l} + depth * ${c} +
          depth2 * ${a} + depth3 * ${i} + depth4 + ${m};
      vec2 uv = uvFromFlat(${p}, ${f}, index);
      return sampleTexture(${e}, uv);
    }
  `}function pr(n){const t=n.name,e=Z(n.shapeInfo.logicalShape);return e<2?`return ${t};`:`
    for (int i = 0; i < ${e}; i++) {
      if (i == index) {
        return ${t}[i];
      }
    }
  `}function yF(n,t){const e=n.name,s=e.charAt(0).toUpperCase()+e.slice(1),o="get"+s+"AtOutCoords",r=n.shapeInfo.logicalShape.length,i=t.logicalShape.length,a=d1(n.shapeInfo.logicalShape,t.logicalShape),c=Wt(i),l=i-r;let u;const d=["x","y","z","w","u","v"];r===0?u="":i<2&&a.length>=1?u="coords = 0;":u=a.map(x=>`coords.${d[x+l]} = 0;`).join(`
`);let h="";i<2&&r>0?h="coords":h=n.shapeInfo.logicalShape.map((x,I)=>`coords.${d[I+l]}`).join(", ");let p="return outputValue;";const m=Z(n.shapeInfo.logicalShape)===1,b=Z(t.logicalShape)===1;if(r===1&&!m&&!b)p=`
      return vec4(outputValue.xy, outputValue.xy);
    `;else if(m&&!b)i===1?p=`
        return vec4(outputValue.x, outputValue.x, 0., 0.);
      `:p=`
        return vec4(outputValue.x);
      `;else if(a.length){const x=r-2,I=r-1;a.indexOf(x)>-1&&a.indexOf(I)>-1?p="return vec4(outputValue.x);":a.indexOf(x)>-1?p="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":a.indexOf(I)>-1&&(p="return vec4(outputValue.xx, outputValue.zz);")}return`
    vec4 ${o}() {
      ${c} coords = getOutputCoords();
      ${u}
      vec4 outputValue = get${s}(${h});
      ${p}
    }
  `}function IF(n,t){const e=n.name,s=e.charAt(0).toUpperCase()+e.slice(1),o="get"+s+"AtOutCoords",r=t.texShape,i=n.shapeInfo.texShape,a=n.shapeInfo.logicalShape.length,c=t.logicalShape.length;if(!n.shapeInfo.isUniform&&a===c&&n.shapeInfo.flatOffset==null&&Rt(i,r))return`
      float ${o}() {
        return sampleTexture(${e}, resultUV);
      }
    `;const l=Wt(c),u=d1(n.shapeInfo.logicalShape,t.logicalShape),d=c-a;let h;const p=["x","y","z","w","u","v"];a===0?h="":c<2&&u.length>=1?h="coords = 0;":h=u.map(m=>`coords.${p[m+d]} = 0;`).join(`
`);let f="";return c<2&&a>0?f="coords":f=n.shapeInfo.logicalShape.map((m,g)=>`coords.${p[g+d]}`).join(", "),`
    float ${o}() {
      ${l} coords = getOutputCoords();
      ${h}
      return get${s}(${f});
    }
  `}function Wt(n){if(n<=1)return"int";if(n===2)return"ivec2";if(n===3)return"ivec3";if(n===4)return"ivec4";if(n===5)return"ivec5";if(n===6)return"ivec6";throw Error(`GPU for rank ${n} is not yet supported`)}function Rp(n,t,e){const{newShape:s,keptDims:o}=fs(t),r=t.length,i=n&&r===3&&t[0]===1,a=i?t.slice(1):s,c=!n&&r>1&&!Rt(t,e)&&s.length<r||i;return{useSqueezeShape:c,uniformShape:c?a:t,keptDims:o}}function fr(n,t){const e=JSON.parse(JSON.stringify(n));return e.shapeInfo.logicalShape=t,e}function mr(n,t){return t.map(e=>n[e]).join(", ")}/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function wF(n,t,e,s){const o=e.map((u,d)=>{const h={logicalShape:u.shape,texShape:u.isUniform?null:u.texData.texShape,isUniform:u.isUniform,isPacked:u.isUniform?!1:u.texData.isPacked,flatOffset:null};return u.texData!=null&&u.texData.slice!=null&&u.texData.slice.flatOffset>0&&(h.flatOffset=u.texData.slice.flatOffset),{name:t.variableNames[d],shapeInfo:h}}),r=o.map(u=>u.shapeInfo),i={logicalShape:s.shape,texShape:s.texData.texShape,isUniform:!1,isPacked:s.texData.isPacked,flatOffset:null},a=XV(o,i,t),c=fV(n.gl,a),l=n.createProgram(c);return z().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:c,source:a,webGLProgram:l,inShapeInfos:r,outShapeInfo:i,variablesLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:(n.buildVao(l),Object.assign({program:t,fragmentShader:c,source:a,webGLProgram:l,inShapeInfos:r,outShapeInfo:i},f1(n,t,l)))}function f1(n,t,e){const s=[],o=[];let r,i,a,c=null,l=null;l=n.getUniformLocation(e,"NAN",!1),z().getNumber("WEBGL_VERSION")===1&&(c=n.getUniformLocation(e,"INFINITY",!1));const u=!1;for(const d of t.variableNames){const h={name:d,uniform:n.getUniformLocation(e,d,u),offset:n.getUniformLocation(e,`offset${d}`,u)};t.enableShapeUniforms&&(h.shape=n.getUniformLocation(e,`${d}Shape`,u),h.texShape=n.getUniformLocation(e,`${d}TexShape`,u)),s.push(h)}if(t.enableShapeUniforms&&(r=n.getUniformLocation(e,"outShape",u),a=n.getUniformLocation(e,"outShapeStrides",u),i=n.getUniformLocation(e,"outTexShape",u)),t.customUniforms)for(const d of t.customUniforms)o.push(n.getUniformLocation(e,d.name,u));return{variablesLocations:s,customUniformLocations:o,infLoc:c,nanLoc:l,outShapeLocation:r,outShapeStridesLocation:a,outTexShapeLocation:i}}function m1(n,t){if(n.length!==t.length)throw Error(`Binary was compiled with ${n.length} inputs, but was executed with ${t.length} inputs`);n.forEach((e,s)=>{const o=e.logicalShape,r=t[s],i=r.shape;if(!Rt(o,i))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${o} and ${i} must match`);if(e.isUniform&&r.isUniform)return;const a=e.texShape,c=r.isUniform?null:r.texData.texShape;if(!Rt(a,c))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${a} and ${c} must match`)})}function CF(n,t,e,s,o){t.program.enableShapeUniforms||(m1(t.inShapeInfos,e),m1([t.outShapeInfo],[s]));const r=s.texData.texture,i=s.texData.texShape;s.texData.isPacked?n.setOutputPackedMatrixTexture(r.texture,i[0],i[1]):n.setOutputMatrixTexture(r.texture,i[0],i[1]),n.setProgram(t.webGLProgram),n.bindVertexArray(t.webGLProgram.vao),z().getNumber("WEBGL_VERSION")===1&&t.infLoc!==null&&n.gl.uniform1f(t.infLoc,1/0),t.nanLoc!==null&&n.gl.uniform1f(t.nanLoc,NaN);for(let c=0;c<e.length;++c){const l=e[c],{uniform:u,offset:d,shape:h,texShape:p}=t.variablesLocations[c];if(h){const{uniformShape:f}=Rp(t.program.packedInputs,l.shape,l.texData.texShape);switch(f.length){case 1:n.gl.uniform1iv(h,new Int32Array(f));break;case 2:n.gl.uniform2iv(h,new Int32Array(f));break;case 3:n.gl.uniform3iv(h,new Int32Array(f));break;case 4:n.gl.uniform4iv(h,new Int32Array(f));break}}if(p&&n.gl.uniform2i(p,l.texData.texShape[0],l.texData.texShape[1]),u!=null){if(l.isUniform){if(Z(l.shape)<2)n.gl.uniform1f(u,l.uniformValues[0]);else{let f=l.uniformValues;f instanceof Float32Array||(f=new Float32Array(f)),n.gl.uniform1fv(u,f)}continue}l.texData.slice!=null&&d!=null&&n.gl.uniform1i(d,l.texData.slice.flatOffset),n.setInputMatrixTexture(l.texData.texture.texture,u,c)}}const a=t.outShapeLocation;if(a)switch(s.shape.length){case 1:n.gl.uniform1iv(a,new Int32Array(s.shape));break;case 2:n.gl.uniform2iv(a,new Int32Array(s.shape));break;case 3:n.gl.uniform3iv(a,new Int32Array(s.shape));break;case 4:n.gl.uniform4iv(a,new Int32Array(s.shape));break}if(t.outShapeStridesLocation){const c=ct(s.shape);switch(s.shape.length){case 2:n.gl.uniform1iv(t.outShapeStridesLocation,new Int32Array(c));break;case 3:n.gl.uniform2iv(t.outShapeStridesLocation,new Int32Array(c));break;case 4:n.gl.uniform3iv(t.outShapeStridesLocation,new Int32Array(c));break}}if(t.outTexShapeLocation&&n.gl.uniform2i(t.outTexShapeLocation,s.texData.texShape[0],s.texData.texShape[1]),t.program.customUniforms&&o)for(let c=0;c<t.program.customUniforms.length;++c){const l=t.program.customUniforms[c],u=t.customUniformLocations[c],d=o[c];if(l.type==="float")n.gl.uniform1fv(u,d);else if(l.type==="vec2")n.gl.uniform2fv(u,d);else if(l.type==="vec3")n.gl.uniform3fv(u,d);else if(l.type==="vec4")n.gl.uniform4fv(u,d);else if(l.type==="int")n.gl.uniform1iv(u,d);else if(l.type==="ivec2")n.gl.uniform2iv(u,d);else if(l.type==="ivec3")n.gl.uniform3iv(u,d);else if(l.type==="ivec4")n.gl.uniform4iv(u,d);else throw Error(`uniform type ${l.type} is not supported yet.`)}n.executeProgram()}function vF(n,t,e){let s="";t.concat(e).forEach(i=>{const a=i.texData!=null&&i.texData.slice!=null&&i.texData.slice.flatOffset>0;if(n.enableShapeUniforms&&!i.isUniform){const c=i.texData.texShape,{useSqueezeShape:l,uniformShape:u,keptDims:d}=Rp(n.packedInputs,i.shape,c);let h="",p="",f="";if(u.length===1&&n.packedInputs){const w=[Math.ceil(c[0]/2),Math.ceil(c[1]/2)];h=`${w[0]>1}_${w[1]>1}`}else if(u.length===2&&!n.packedInputs)p=`${u[0]>1}_${u[1]>1}`;else if(u.length>2&&!n.packedInputs){const w=ct(u);f=`${w[0]===c[1]}_${w[w.length-1]===c[1]}`}const m=i.shape.length,g=u.length===2&&Rt(i.shape,c),b=Z(i.shape)===1,x=Uo(i.shape,e.shape),I=!n.packedInputs&&m===e.shape.length&&Rt(c,e.texData.texShape),y=n.packedInputs||u.length>2?"":`${c[0]>1}_${c[1]>1}`;s+=`${m}_${I}_${l?d:""}_${u.length}_${b}_${x}_${g}_${h}_${p}_${f}_${y}_${a}`}else{const c=i.isUniform?"uniform":i.texData.texShape;s+=`${i.shape}_${c}_${a}`}});const o=n.userCode;let r=n.constructor.name;return r+="_"+s+"_"+o+`${z().getNumber("WEBGL_VERSION")}`,r}function Ne(n){return z().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&n<=4}/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class SF{constructor(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=sa.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const e=De();this.outputShape=t,this.enableShapeUniforms=Ne(this.outputShape.length),this.userCode=`
      ivec3 outCoordsFromFlatIndex(int index) {
        ${this.enableShapeUniforms?Tl(["r","c","d"],t):vo(["r","c","d"],t)}
        return ivec3(r, c, d);
      }

      void main() {
        ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
        int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);

        vec4 result = vec4(0.);

        for (int i=0; i<4; i++) {
          int flatIndex = index + i;
          ivec3 rc = outCoordsFromFlatIndex(flatIndex);
          result[i] = getA(rc.x, rc.y, rc.z);
        }

        ${e.output} = result;
      }
    `}}/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class kF{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=sa.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const e=De();this.outputShape=t,this.enableShapeUniforms=Ne(this.outputShape.length),this.userCode=`
      ivec3 outCoordsFromFlatIndex(int index) {
        ${this.enableShapeUniforms?Tl(["r","c","d"],t):vo(["r","c","d"],t)}
        return ivec3(r, c, d);
      }

      void main() {
        ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
        int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);

        vec4 result = vec4(0.);

        for (int i=0; i<4; i++) {
          int flatIndex = index + i;
          ivec3 rc = outCoordsFromFlatIndex(flatIndex);
          result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));
        }

        ${e.output} = result;
      }
    `}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class TF{constructor(t){this.variableNames=["A"],this.outTexUsage=an.DOWNLOAD;const e=De();this.outputShape=t,this.userCode=`
      ${u1}

      void main() {
        float x = getAAtOutCoords();
        ${e.output} = encode_float(x);
      }
    `}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class NF{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=an.DOWNLOAD;const e=De();this.outputShape=t,this.userCode=`
      ${u1}

      void main() {
        ivec3 coords = getOutputCoords();
        float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
        ${e.output} = encode_float(x);
      }
    `}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const RF={R:0,G:1,B:2,A:3};class g1{constructor(t,e=!1,s="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];const o=De();this.outputShape=t,this.enableShapeUniforms=Ne(this.outputShape.length);let r="result";e&&(r="floor(result * 255. + 0.5)");let i="";for(let a=0;a<s.length;a++){const c=s[a];i+=`
          if(offset == ${a}) {
            result = values[${RF[c]}];
          }`}this.userCode=`
      ${this.enableShapeUniforms?Np():Tp(t)}

      void main() {
        ivec3 coords = getOutputCoords();
        int flatIndex = getFlatIndex(coords);
        float result = 0.;
        int offset = imod(flatIndex, ${s.length});

        flatIndex = idiv(flatIndex, ${s.length}, 1.);

        int r = flatIndex / texShape[1];
        if (r < texShape[0]) {
          int c = imod(flatIndex, texShape[1]);
          vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
          vec4 values = ${o.texture2D}(A, uv);
          ${i}
        }
        ${o.output} = vec4(${r}, 0., 0., 0.);
      }
    `}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class $F{constructor(t,e=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];const s=De();this.outputShape=t,this.enableShapeUniforms=Ne(this.outputShape.length);let o="",r="result";e&&(r="floor(result * 255. + 0.5)");for(let i=0;i<=1;i++)for(let a=0;a<=1;a++){const c=i*2+a;o+=`
          localCoords = coords;
          if(localCoords[2] + ${a} < ${this.enableShapeUniforms?"outShape[2]":`${t[2]}`}) {
          localCoords[2] += ${a};
          if (localCoords[1] + ${i} < ${this.enableShapeUniforms?"outShape[1]":`${t[1]}`}) {
            localCoords[1] += ${i};

            flatIndex = getFlatIndex(localCoords);
            offset = imod(flatIndex, 4);

            flatIndex = idiv(flatIndex, 4, 1.);

            int r = flatIndex / texShape[1];
            int c = imod(flatIndex, texShape[1]);
            vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
            values = ${s.texture2D}(A, uv);

            if (offset == 0) {
              result[${c}] = values[0];
            } else if (offset == 1) {
              result[${c}] = values[1];
            } else if (offset == 2) {
              result[${c}] = values[2];
            } else {
              result[${c}] = values[3];
            }
          }
        }
        `}this.userCode=`
        ${this.enableShapeUniforms?Np():Tp(t)}

        void main() {
          ivec3 coords = getOutputCoords();

          vec4 result = vec4(0.);
          int flatIndex, r, c, offset;
          ivec3 localCoords;
          vec2 uv;
          vec4 values;

          ${o}

          ${s.output} = ${r};
        }
    `}}/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function GF(n){const t=De(),e=`${t.version}
    precision highp float;
    ${t.attribute} vec3 clipSpacePos;
    ${t.attribute} vec2 uv;
    ${t.varyingVs} vec2 resultUV;

    void main() {
      gl_Position = vec4(clipSpacePos, 1);
      resultUV = uv;
    }`;return pV(n,e)}function LF(n){const t=new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]);return xV(n,t)}function EF(n){const t=new Uint16Array([0,1,2,2,1,3]);return yV(n,t)}function ia(n,t,e,s,o,r){wV(t,e);const i=IV(n),a=n.TEXTURE_2D;return ot(n,()=>n.bindTexture(a,i)),ot(n,()=>n.texParameteri(a,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE)),ot(n,()=>n.texParameteri(a,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE)),ot(n,()=>n.texParameteri(a,n.TEXTURE_MIN_FILTER,n.NEAREST)),ot(n,()=>n.texParameteri(a,n.TEXTURE_MAG_FILTER,n.NEAREST)),z().getNumber("WEBGL_VERSION")===1?ot(n,()=>n.texImage2D(a,0,s,t,e,0,o,r,null)):ot(n,()=>n.texStorage2D(a,1,s,t,e)),ot(n,()=>n.bindTexture(n.TEXTURE_2D,null)),{texture:i,texShape:[e,t]}}function b1(n){return n.internalFormatFloat}function DF(n,t,e,s){const[o,r]=oa(t,e);return ia(n,o,r,b1(s),s.textureFormatFloat,n.FLOAT)}function x1(n){return n.internalFormatHalfFloat}function WF(n,t,e,s){const[o,r]=oa(t,e);return ia(n,o,r,x1(s),s.textureFormatFloat,s.textureTypeHalfFloat)}function y1(n){return n.downloadTextureFormat}function MF(n,t,e,s){const[o,r]=oa(t,e);return ia(n,o,r,y1(s),n.RGBA,n.UNSIGNED_BYTE)}function I1(n){return n.internalFormatPackedFloat}function VF(n,t,e,s){const[o,r]=lr(t,e);return ia(n,o,r,I1(s),n.RGBA,n.FLOAT)}function w1(n){return n.internalFormatPackedHalfFloat}function FF(n,t,e,s){const[o,r]=lr(t,e);return ia(n,o,r,w1(s),n.RGBA,s.textureTypeHalfFloat)}function zF(n,t,e){return ot(n,()=>n.bindBuffer(n.ARRAY_BUFFER,e)),a1(n,t,"clipSpacePos",e,3,20,0)&&a1(n,t,"uv",e,2,20,12)}function XF(n,t,e,s,o,r){ot(n,()=>n.bindTexture(n.TEXTURE_2D,t));let i,a,c;o instanceof Uint8Array?(i=new Uint8Array(e*s*4),a=n.UNSIGNED_BYTE,c=n.RGBA):(i=new Float32Array(e*s*4),a=n.FLOAT,c=r.internalFormatPackedFloat),i.set(o),z().getNumber("WEBGL_VERSION")===2?ot(n,()=>n.texSubImage2D(n.TEXTURE_2D,0,0,0,e,s,n.RGBA,a,i)):ot(n,()=>n.texImage2D(n.TEXTURE_2D,0,c,e,s,0,n.RGBA,a,i)),ot(n,()=>n.bindTexture(n.TEXTURE_2D,null))}function AF(n,t,e){ot(n,()=>n.bindTexture(n.TEXTURE_2D,t)),e.data instanceof Uint8Array?z().getNumber("WEBGL_VERSION")===2?ot(n,()=>n.texSubImage2D(n.TEXTURE_2D,0,0,0,e.width,e.height,n.RGBA,n.UNSIGNED_BYTE,e.data)):ot(n,()=>n.texImage2D(n.TEXTURE_2D,0,n.RGBA,e.width,e.height,0,n.RGBA,n.UNSIGNED_BYTE,e.data)):z().getNumber("WEBGL_VERSION")===2?ot(n,()=>n.texSubImage2D(n.TEXTURE_2D,0,0,0,n.RGBA,n.UNSIGNED_BYTE,e)):ot(n,()=>n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,e)),ot(n,()=>n.bindTexture(n.TEXTURE_2D,null))}function PF(n,t,e,s){const o=n.createBuffer();ot(n,()=>n.bindBuffer(n.PIXEL_PACK_BUFFER,o));const a=4*4*t*e;return ot(n,()=>n.bufferData(n.PIXEL_PACK_BUFFER,a,n.STREAM_READ)),ot(n,()=>n.readPixels(0,0,e,t,n.RGBA,n.FLOAT,0)),ot(n,()=>n.bindBuffer(n.PIXEL_PACK_BUFFER,null)),o}function OF(n,t,e){const s=n,o=new Float32Array(e);return s.bindBuffer(s.PIXEL_PACK_BUFFER,t),s.getBufferSubData(s.PIXEL_PACK_BUFFER,0,o),s.bindBuffer(s.PIXEL_PACK_BUFFER,null),o}function KF(n,t,e,s){const[o,r]=oa(t,e),i=4,a=new Uint8Array(iV(t*e,i));return ot(n,()=>n.readPixels(0,0,o,r,s.downloadTextureFormat,n.UNSIGNED_BYTE,a)),new Float32Array(a.buffer)}function ZF(n,t,e,s,o,r,i,a){const c=n,l=new Float32Array(aV(r,i));return c.bindBuffer(c.PIXEL_PACK_BUFFER,t),c.getBufferSubData(c.PIXEL_PACK_BUFFER,0,l),c.bindBuffer(c.PIXEL_PACK_BUFFER,null),l}function BF(n,t,e){const s=new Float32Array(t*e*4);return ot(n,()=>n.readPixels(0,0,e,t,n.RGBA,n.FLOAT,s)),s}/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class $p{constructor(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];const e=z().getNumber("WEBGL_VERSION");if(t!=null?(this.gl=t,sV(e,t)):this.gl=Mn(e),t=this.gl,z().getNumber("WEBGL_VERSION")===2){const r=t;this.createVertexArray=()=>ot(r,()=>r.createVertexArray()),this.bindVertexArray=i=>ot(r,()=>r.bindVertexArray(i)),this.deleteVertexArray=i=>ot(r,()=>r.deleteVertexArray(i)),this.getVertexArray=()=>ot(r,()=>r.getParameter(r.VERTEX_ARRAY_BINDING))}else if(t!=null){const r=t.getExtension("OES_vertex_array_object");if(r==null)throw new Error("All WebGL1 implementations are expected to offer OES_vertex_array_object.");this.createVertexArray=()=>ot(t,()=>r.createVertexArrayOES()),this.bindVertexArray=i=>ot(t,()=>r.bindVertexArrayOES(i)),this.deleteVertexArray=i=>ot(t,()=>r.deleteVertexArrayOES(i)),this.getVertexArray=()=>ot(t,()=>t.getParameter(r.VERTEX_ARRAY_BINDING_OES))}let s="WEBGL_color_buffer_float";const o="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),z().getNumber("WEBGL_VERSION")===1){const r="OES_texture_float",i="OES_texture_half_float";if(this.textureFloatExtension=wl(this.gl,r),wn(this.gl,i))this.textureHalfFloatExtension=wl(this.gl,i);else if(z().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(s),wn(this.gl,o))this.colorBufferHalfFloatExtension=wl(this.gl,o);else if(z().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(s="EXT_color_buffer_float",wn(this.gl,s))this.colorBufferFloatExtension=this.gl.getExtension(s);else if(wn(this.gl,o))this.colorBufferHalfFloatExtension=this.gl.getExtension(o);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=LF(this.gl),this.indexBuffer=EF(this.gl),this.framebuffer=CV(this.gl),this.textureConfig=Ip(this.gl,this.textureHalfFloatExtension)}get debug(){return z().getBool("DEBUG")}dispose(){if(this.disposed)return;this.program!=null&&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."),this.outputTexture!=null&&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 t=this.gl;ot(t,()=>t.finish()),ot(t,()=>t.bindFramebuffer(t.FRAMEBUFFER,null)),ot(t,()=>t.deleteFramebuffer(this.framebuffer)),ot(t,()=>t.bindBuffer(t.ARRAY_BUFFER,null)),ot(t,()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null)),ot(t,()=>t.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(t,e){return this.throwIfDisposed(),DF(this.gl,t,e,this.textureConfig)}createFloat16MatrixTexture(t,e){return this.throwIfDisposed(),WF(this.gl,t,e,this.textureConfig)}createUnsignedBytesMatrixTexture(t,e){return this.throwIfDisposed(),MF(this.gl,t,e,this.textureConfig)}uploadPixelDataToTexture(t,e){this.throwIfDisposed(),AF(this.gl,t,e)}uploadDenseMatrixToTexture(t,e,s,o){this.throwIfDisposed(),XF(this.gl,t,e,s,o,this.textureConfig)}createFloat16PackedMatrixTexture(t,e){return this.throwIfDisposed(),FF(this.gl,t,e,this.textureConfig)}createPackedMatrixTexture(t,e){return this.throwIfDisposed(),VF(this.gl,t,e,this.textureConfig)}deleteMatrixTexture(t){this.throwIfDisposed(),this.outputTexture===t&&(c1(this.gl,this.framebuffer),this.outputTexture=null),ot(this.gl,()=>this.gl.deleteTexture(t))}downloadByteEncodedFloatMatrixFromOutputTexture(t,e,s){return this.downloadMatrixDriver(t,()=>KF(this.gl,e,s,this.textureConfig))}downloadPackedMatrixFromBuffer(t,e,s,o,r,i){return ZF(this.gl,t,e,s,o,r,i,this.textureConfig)}downloadFloat32MatrixFromBuffer(t,e){return OF(this.gl,t,e)}createBufferFromTexture(t,e,s){this.bindTextureToFrameBuffer(t);const o=PF(this.gl,e,s,this.textureConfig);return this.unbindTextureToFrameBuffer(),o}createAndWaitForFence(){const t=this.createFence(this.gl);return this.pollFence(t)}createFence(t){let e,s;if(z().getBool("WEBGL_FENCE_API_ENABLED")){const o=t,r=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),s=()=>{const i=o.clientWaitSync(r,0,0);return i===o.ALREADY_SIGNALED||i===o.CONDITION_SATISFIED},e=r}else z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),s=()=>this.isQueryAvailable(e,z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):s=()=>!0;return{query:e,isFencePassed:s}}downloadMatrixFromPackedTexture(t,e,s){return this.downloadMatrixDriver(t,()=>BF(this.gl,e,s))}createProgram(t){this.throwIfDisposed();const e=this.gl;this.vertexShader==null&&(this.vertexShader=GF(e));const s=gV(e);ot(e,()=>e.attachShader(s,this.vertexShader)),ot(e,()=>e.attachShader(s,t)),bV(e,s);const o=Object.assign(s,{vao:this.createVertexArray()});return this.debug&&wp(e,o),o}buildVao(t){this.setProgram(t),this.bindVertexArray(t.vao);const e=this.gl;ot(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,this.indexBuffer)),zF(e,t,this.vertexBuffer)}deleteProgram(t){this.throwIfDisposed(),t===this.program&&(this.program=null),t!=null&&(ot(this.gl,()=>this.gl.deleteProgram(t)),this.deleteVertexArray(t.vao))}setProgram(t){this.throwIfDisposed(),this.program=t,this.program!=null&&this.debug&&wp(this.gl,this.program),ot(this.gl,()=>this.gl.useProgram(t))}getUniformLocation(t,e,s=!0){return this.throwIfDisposed(),s?SV(this.gl,t,e):kV(this.gl,t,e)}getAttributeLocation(t,e){return this.throwIfDisposed(),ot(this.gl,()=>this.gl.getAttribLocation(t,e))}getUniformLocationNoThrow(t,e){return this.throwIfDisposed(),this.gl.getUniformLocation(t,e)}setInputMatrixTexture(t,e,s){this.throwIfDisposed(),this.throwIfNoProgram(),TV(this.gl,t,e,s)}setOutputMatrixTexture(t,e,s){this.setOutputMatrixTextureDriver(t,s,e)}setOutputPackedMatrixTexture(t,e,s){this.throwIfDisposed();const[o,r]=lr(e,s);this.setOutputMatrixTextureDriver(t,o,r)}setOutputMatrixWriteRegion(t,e,s,o){this.setOutputMatrixWriteRegionDriver(s,t,o,e)}setOutputPackedMatrixWriteRegion(t,e,s,o){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&wp(this.gl,this.program),Cl(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const t=this.gl;if(this.debug){const e=this.getVertexArray();console.assert(e===this.program.vao,"VAO changed between setProgram and executeProgram!"),this.debugValidate()}ot(t,()=>t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),ot(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=wl(this.gl,z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){const s=this.gl,o=this.getQueryTimerExtensionWebGL2(),r=s.createQuery();return s.beginQuery(o.TIME_ELAPSED_EXT,r),r}const t=this.getQueryTimerExtensionWebGL1(),e=t.createQueryEXT();return t.beginQueryEXT(t.TIME_ELAPSED_EXT,e),e}endQuery(){if(z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){const e=this.gl,s=this.getQueryTimerExtensionWebGL2();e.endQuery(s.TIME_ELAPSED_EXT);return}const t=this.getQueryTimerExtensionWebGL1();t.endQueryEXT(t.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(t){return await uf(()=>this.disposed||this.isQueryAvailable(t,z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(t,z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(t,e){if(e===0)return null;if(e===2){const s=this.gl;return s.getQueryParameter(t,s.QUERY_RESULT)/1e6}else{const s=this.getQueryTimerExtensionWebGL1();return s.getQueryObjectEXT(t,s.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(t,e){if(e===0)return!0;if(e===2){const s=this.gl,o=this.getQueryTimerExtensionWebGL2(),r=s.getQueryParameter(t,s.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(o.GPU_DISJOINT_EXT)),r&&!this.disjoint}else{const s=this.getQueryTimerExtensionWebGL1(),o=s.getQueryObjectEXT(t,s.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(s.GPU_DISJOINT_EXT)),o&&!this.disjoint}}pollFence(t){return new Promise(e=>{this.addItemToPoll(()=>t.isFencePassed(),()=>e())})}pollItems(){const t=HF(this.itemsToPoll.map(e=>e.isDoneFn));for(let e=0;e<=t;++e){const{resolveFn:s}=this.itemsToPoll[e];s()}this.itemsToPoll=this.itemsToPoll.slice(t+1)}addItemToPoll(t,e){if(this.itemsToPoll.push({isDoneFn:t,resolveFn:e}),this.itemsToPoll.length>1)return;let s;"setTimeoutCustom"in z().platform&&(s=z().platform.setTimeoutCustom.bind(z().platform)),uf(()=>(this.pollItems(),this.itemsToPoll.length===0),()=>0,null,s)}bindTextureToFrameBuffer(t){this.throwIfDisposed(),Cp(this.gl,t,this.framebuffer),this.debug&&Cl(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(Cp(this.gl,this.outputTexture,this.framebuffer),this.debug&&Cl(this.gl)):c1(this.gl,this.framebuffer)}downloadMatrixDriver(t,e){this.bindTextureToFrameBuffer(t);const s=e();return this.unbindTextureToFrameBuffer(),s}setOutputMatrixTextureDriver(t,e,s){this.throwIfDisposed();const o=this.gl;Cp(o,t,this.framebuffer),this.debug&&Cl(o),this.outputTexture=t,ot(o,()=>o.viewport(0,0,e,s)),ot(o,()=>o.scissor(0,0,e,s))}setOutputMatrixWriteRegionDriver(t,e,s,o){this.throwIfDisposed(),ot(this.gl,()=>this.gl.scissor(t,e,s,o))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(this.program==null)throw new Error("No GPU program is currently set.")}}function HF(n){let t=0;for(;t<n.length&&n[t]();++t);return t-1}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const{addImpl:_F,bincountImpl:C1,bincountReduceImpl:UF,bitwiseAndImpl:YF,castImpl:QF,ceilImpl:JF,concatImpl:jF,equalImpl:qF,expImpl:tz,expm1Impl:ez,floorImpl:nz,gatherNdImpl:sz,gatherV2Impl:oz,greaterImpl:rz,greaterEqualImpl:iz,lessImpl:az,lessEqualImpl:cz,linSpaceImpl:lz,logImpl:uz,maxImpl:dz,maximumImpl:hz,minimumImpl:pz,multiplyImpl:fz,negImpl:mz,notEqualImpl:gz,prodImpl:bz,raggedGatherImpl:xz,raggedRangeImpl:yz,raggedTensorToTensorImpl:Iz,rangeImpl:wz,rsqrtImpl:Cz,scatterImpl:vz,sigmoidImpl:Sz,simpleAbsImpl:v1,sliceImpl:kz,sparseFillEmptyRowsImpl:Tz,sparseReshapeImpl:Nz,sparseSegmentReductionImpl:S1,sqrtImpl:Rz,staticRegexReplaceImpl:$z,stridedSliceImpl:Gz,stringNGramsImpl:Lz,stringSplitImpl:Ez,stringToHashBucketFastImpl:Dz,subImpl:Wz,tileImpl:Mz,topKImpl:Vz,transposeImpl:Gp,uniqueImpl:Fz}=OL;/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function k1(n,t){return["x","y","z","w","u","v"].slice(0,t).map(e=>`${n}.${e}`)}function We(n,t){return t===1?[n]:k1(n,t)}function zz(n,t){if(n===1)return"rc";let e="";for(let s=0;s<n;s++)e+=t[s],s<n-1&&(e+=",");return e}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class Xz{constructor(t){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=t,this.rank=t.length,this.enableShapeUniforms=Ne(this.outputShape.length),this.rank===0)this.userCode=`
        void main() {
          setOutput(vec4(getA(), 0., 0., 0.));
        }
      `;else{const e=We("rc",this.rank),s=Wt(this.rank),o=this.getOutOfBoundsCondition(e),r=this.getSetup(e),i=this.getOutput(e);this.userCode=`
        void main() {
          ${s} rc = getOutputCoords();

          if(${o}) {
            setOutput(vec4(0));
          } else {
            ${r}

            setOutput(vec4(${i}));
          }
        }
      `}}getSourceCoordsArr(t){const e=[];for(let s=0;s<=1;s++)for(let o=0;o<=1;o++){let r=`${s===0?"r":"rp1"}, ${o===0?"c":"cp1"}`;for(let i=2;i<this.rank;i++)r=`${t[t.length-1-i]},`+r;e.push(r)}return e}getOutOfBoundsCondition(t){if(this.rank===1)return`rc > ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let e="";for(let s=this.rank-2;s<this.rank;s++)e+=`${t[s]} >= ${this.enableShapeUniforms?`outShape[${s}]`:this.outputShape[s]}`,s<this.rank-1&&(e+="||");return e}getSetup(t){if(this.rank===1)return"";const e=t.slice(-2),s=this.enableShapeUniforms?`outShape[${this.rank} - 1]`:this.outputShape[this.rank-1],o=this.enableShapeUniforms?`outShape[${this.rank} - 2]`:this.outputShape[this.rank-2];return`
      int r = ${e[0]};
      int c = ${e[1]};
      int rp1 = r + 1;
      int cp1 = c + 1;

      bool cEdge = cp1 >= ${s};
      bool rEdge = rp1 >= ${o};
    `}getOutput(t){const e=this.getSourceCoordsArr(t);return this.rank===1?`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`:`getA(${e[0]}),
            cEdge ? 0. : getA(${e[1]}),
            rEdge ? 0. : getA(${e[2]}),
            rEdge || cEdge ? 0. : getA(${e[3]})`}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class T1{constructor(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=t,this.enableShapeUniforms=Ne(this.outputShape.length);let s="";for(let o=0;o<4;o++){let r="thisRC = rc;";o%2===1&&(r+="thisRC.z += 1;"),o>1&&(r+="thisRC.y += 1;"),s+=`
        ${r}
        ${o>0?"if(thisRC.y < rows && thisRC.z < cols){":""}
          int flatIndex = getFlatIndex(thisRC);

          ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
          vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));

          result[${o}] =
            getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
        ${o>0?"}":""}
      `}this.userCode=`
      ${Az(e,this.enableShapeUniforms)}
      ${this.enableShapeUniforms?Np():Tp(t)}

      void main() {
        ivec3 rc = getOutputCoords();

        vec4 result = vec4(0.);

        ivec3 thisRC;
        int rows = ${this.enableShapeUniforms?"outShape[1]":t[1]};
        int cols = ${this.enableShapeUniforms?"outShape[2]":t[2]};

        ${s}

        setOutput(result);
      }
    `}}function Az(n,t){return`
    ivec3 inputCoordsFromReshapedOutCoords(int index) {
      ${t?zV(["r","c","d"],"inputShape"):vo(["r","c","d"],n)}
      return ivec3(r, c, d);
    }
  `}/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class Pz{constructor(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.usedTextures={},this.logEnabled=!1}acquireTexture(t,e,s){const o=R1(e,s),r=$1(t,o,s);r in this.freeTextures||(this.freeTextures[r]=[]),r in this.usedTextures||(this.usedTextures[r]=[]);const i=N1(t,o,this.gpgpu.gl,this.gpgpu.textureConfig,s);if(this.freeTextures[r].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=i,this.log();const c=this.freeTextures[r].pop();return this.usedTextures[r].push(c),c}let a;return o===we.PACKED_2X2_FLOAT32?a=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):o===we.PACKED_2X2_FLOAT16?a=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):o===we.UNPACKED_FLOAT32?a=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):o===we.UNPACKED_FLOAT16?a=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):o===we.PACKED_4X1_UNSIGNED_BYTE&&(a=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[r].push(a),this.numUsedTextures++,this._numBytesAllocated+=i,this.log(),a}releaseTexture(t,e,s,o){if(this.freeTextures==null)return;const r=R1(s,o),i=$1(e,r,o);i in this.freeTextures||(this.freeTextures[i]=[]);const a=N1(e,r,this.gpgpu.gl,this.gpgpu.textureConfig,o),c=z().getNumber("WEBGL_DELETE_TEXTURE_THRESHOLD");c!==-1&&this._numBytesAllocated>c?(this.gpgpu.deleteMatrixTexture(t.texture),this._numBytesAllocated-=a):(this.freeTextures[i].push(t),this.numFreeTextures++,this._numBytesFree+=a),this.numUsedTextures--;const l=this.usedTextures[i],u=l&&l.indexOf(t);if(u==null||u<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l[u]=l[l.length-1],l.pop(),this.log()}log(){if(!this.logEnabled)return;const t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${t})`);const e=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*e)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures!=null){for(const t in this.freeTextures)this.freeTextures[t].forEach(e=>{this.gpgpu.deleteMatrixTexture(e.texture)});for(const t in this.usedTextures)this.usedTextures[t].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 Oz(n,t){const e=n;if(t===e.R32F)return 4;if(t===e.R16F)return 2;if(t===e.RGBA32F)return 16;if(t===n.RGBA)return 16;if(t===e.RGBA16F)return 8;if(t===e.RGBA8)return 4;throw new Error(`Unknown internal format ${t}`)}function N1(n,t,e,s,o){const r=Kz(t,s);let i;if(o){const[c,l]=lr(n[0],n[1]);i=c*l}else{const[c,l]=oa(n[0],n[1]);i=c*l}const a=Oz(e,r);return i*a}function Kz(n,t){switch(n){case we.PACKED_2X2_FLOAT32:return I1(t);case we.PACKED_2X2_FLOAT16:return w1(t);case we.UNPACKED_FLOAT32:return b1(t);case we.UNPACKED_FLOAT16:return x1(t);case we.PACKED_4X1_UNSIGNED_BYTE:return y1(t);default:throw new Error(`Unknown physical texture type ${n}`)}}function Zz(n){return z().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?n?we.PACKED_2X2_FLOAT32:we.UNPACKED_FLOAT32:n?we.PACKED_2X2_FLOAT16:we.UNPACKED_FLOAT16}function R1(n,t){if(n===an.UPLOAD)return we.PACKED_2X2_FLOAT32;if(n===an.RENDER||n==null)return Zz(t);if(n===an.DOWNLOAD||n===an.PIXELS)return we.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${n}`)}function $1(n,t,e){return`${n[0]}_${n[1]}_${t}_${e}`}/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class jn{constructor(t,e){this.variableNames=["A"],this.outputShape=t,this.enableShapeUniforms=Ne(this.outputShape.length),this.userCode=`
      float unaryOperation(float x) {
        ${e}
      }

      void main() {
        float x = getAAtOutCoords();
        float y = unaryOperation(x);

        setOutput(y);
      }
    `}}const Cn="if (isnan(x)) return x;",Bz="return x;",G1="return abs(x);",Hz="return (x >= 0.0) ? x : (exp(x) - 1.0);",_z=Cn+`
  return (x < 0.0) ? 0.0 : x;
`,Uz=Cn+`
  return (x < 0.0) ? 0.0 : min(6.0, x);
`,Vs="return x;",Yz="return 1.0 / (1.0 + exp(-1.0 * x));";/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const Qz="return x;",Jz=`
  vec4 result;

  result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
  result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
  result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
  result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);

  return result;
`,jz=`
  vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
  bvec4 isNaN = isnan(x);

  result.r = isNaN.r ? x.r : result.r;
  result.g = isNaN.g ? x.g : result.g;
  result.b = isNaN.b ? x.b : result.b;
  result.a = isNaN.a ? x.a : result.a;

  return result;
`,qz=`
  vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
  bvec4 isNaN = isnan(x);

  result.r = isNaN.r ? x.r : result.r;
  result.g = isNaN.g ? x.g : result.g;
  result.b = isNaN.b ? x.b : result.b;
  result.a = isNaN.a ? x.a : result.a;

  return result;
`,tX="return 1.0 / (1.0 + exp(-1.0 * x));";class Fs{constructor(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.enableShapeUniforms=Ne(this.outputShape.length),this.userCode=`
      vec4 unaryOperation(vec4 x) {
        ${e}
      }

      void main() {
        vec4 x = getAAtOutCoords();
        vec4 y = unaryOperation(x);

        setOutput(y);
      }
    `}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class eX{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=t,this.enableShapeUniforms=Ne(this.outputShape.length);const e=t.length,s=We("rc",e),o=Wt(e),r=zz(e,s),i=s.slice(-2),a=e<=1?"rc":`vec2(${i.join(",")})`;this.userCode=`
      void main() {
        ${o} rc = getOutputCoords();
        vec4 packedInput = getA(${r});

        setOutput(getChannel(packedInput, ${a}));
      }
    `}}/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const nX=rg,sX=1e-7,oX=1e-4,Nl={};function rX(n){return n in Nl||(Nl[n]={}),Nl[n]}const iX=z().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),aX=600;function cX(){return z().global.screen==null?1024:z().global.screen.height*z().global.screen.width*window.devicePixelRatio*aX/1024/1024}class Rl extends Zl{nextDataId(){return Rl.nextDataId++}constructor(t){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,!z().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let e;if(t!=null){if(t instanceof $p)e=t;else{const s=Mn(z().getNumber("WEBGL_VERSION"),t);e=new $p(s)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{const s=Mn(z().getNumber("WEBGL_VERSION"));e=new $p(s),this.binaryCache=rX(z().getNumber("WEBGL_VERSION")),this.gpgpuCreatedLocally=!0}this.gpgpu=e,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new Pz(this.gpgpu),this.numMBBeforeWarning=cX(),this.texData=new lf(this,zt())}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}writeTexture(t,e,s,o,r,i){const a=this.makeTensorInfo(e,s),c=this.texData.get(a.dataId);c.isPacked=!1,c.texture={texture:t,texShape:[o,r]},c.texShape=[o,r];const l=vl(e),u=new g1(l,!1,i),d=this.runWebGLProgram(u,[a],s,[[o,r]]);return d.shape=e,c.texture=null,this.disposeIntermediateTensorInfo(a),d.dataId}write(t,e,s){if((z().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||z().getBool("DEBUG"))&&this.checkNumericalProblems(t),s==="complex64"&&t!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const o={id:this.nextDataId()};return this.texData.set(o,{shape:e,dtype:s,values:t,usage:an.UPLOAD,refCount:1}),o}refCount(t){return this.texData.has(t)?this.texData.get(t).refCount:0}incRef(t){const e=this.texData.get(t);e.refCount++}decRef(t){if(this.texData.has(t)){const e=this.texData.get(t);e.refCount--}}move(t,e,s,o,r){if(z().getBool("DEBUG")&&this.checkNumericalProblems(e),o==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(t,{shape:s,dtype:o,values:e,usage:an.UPLOAD,refCount:r})}disposeIntermediateTensorInfo(t){this.disposeData(t.dataId)}readSync(t){const e=this.texData.get(t),{values:s,dtype:o,complexTensorInfos:r,slice:i,shape:a,isPacked:c}=e;if(i!=null){let h;c?h=new Fs(a,Vs):h=new jn(a,Vs);const p=this.runWebGLProgram(h,[{dataId:t,shape:a,dtype:o}],o),f=this.readSync(p.dataId);return this.disposeIntermediateTensorInfo(p),f}if(s!=null)return this.convertAndCacheOnCPU(t);if(o==="string")return s;const l=this.activeTimers!=null;let u;l&&(u=Ve());let d;if(o==="complex64"){const h=this.readSync(r.real.dataId),p=this.readSync(r.imag.dataId);d=as(h,p)}else d=this.getValuesFromTexture(t);return l&&(this.downloadWaitMs+=Ve()-u),this.convertAndCacheOnCPU(t,d)}async read(t){if(this.pendingRead.has(t)){const f=this.pendingRead.get(t);return new Promise(m=>f.push(m))}const e=this.texData.get(t),{values:s,shape:o,slice:r,dtype:i,complexTensorInfos:a,isPacked:c}=e;if(r!=null){let f;c?f=new Fs(o,Vs):f=new jn(o,Vs);const m=this.runWebGLProgram(f,[{dataId:t,shape:o,dtype:i}],i),g=this.read(m.dataId);return this.disposeIntermediateTensorInfo(m),g}if(s!=null)return this.convertAndCacheOnCPU(t);if(z().getBool("DEBUG")&&!z().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&z().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let l=null,u;if(i!=="complex64"&&z().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(t);const f=this.texData.get(u.dataId);l=this.gpgpu.createBufferFromTexture(f.texture.texture,...Il(o))}this.pendingRead.set(t,[]),i!=="complex64"&&await this.gpgpu.createAndWaitForFence();let d;if(i==="complex64"){const f=await Promise.all([this.read(a.real.dataId),this.read(a.imag.dataId)]),m=f[0],g=f[1];d=as(m,g)}else if(l==null)d=this.getValuesFromTexture(t);else{const f=Z(o);d=this.gpgpu.downloadFloat32MatrixFromBuffer(l,f)}if(u!=null&&this.disposeIntermediateTensorInfo(u),l!=null){const f=this.gpgpu.gl;ot(f,()=>f.deleteBuffer(l))}const h=this.convertAndCacheOnCPU(t,d),p=this.pendingRead.get(t);return this.pendingRead.delete(t),p.forEach(f=>f(h)),this.pendingDisposal.has(t)&&(this.pendingDisposal.delete(t),this.disposeData(t)&&zt().removeDataId(t,this),this.pendingDeletes--),h}readToGPU(t,e={}){const s=this.texData.get(t),{values:o,shape:r,slice:i,dtype:a,isPacked:c,texture:l}=s;if(a==="complex64")throw new Error("Does not support reading texture for complex64 dtype.");if(i!=null){let p;c?p=new Fs(r,Vs):p=new jn(r,Vs);const f=this.runWebGLProgram(p,[{dataId:t,shape:r,dtype:a}],a),m=this.readToGPU(f,e);return this.disposeIntermediateTensorInfo(f),m}if(l==null)throw o!=null?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");const u=this.decode(t,e.customTexShape),d=zt().makeTensorFromTensorInfo(u),h=this.texData.get(u.dataId);return Object.assign({tensorRef:d},h.texture)}bufferSync(t){const e=this.readSync(t.dataId);if(t.dtype==="string")try{const s=e.map(o=>xs(o));return wt(t.shape,t.dtype,s)}catch{throw new Error("Failed to decode encoded string bytes into utf-8")}return wt(t.shape,t.dtype,e)}checkNumericalProblems(t){if(t!=null)for(let e=0;e<t.length;e++){const s=t[e];if(!dV(s))throw z().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")?Error(`The value ${s} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`):Error(`The value ${s} cannot be represented on this device.`)}}getValuesFromTexture(t){const{shape:e,dtype:s,isPacked:o}=this.texData.get(t),r=Z(e);if(z().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){const h=this.decode(t),p=this.texData.get(h.dataId),f=this.gpgpu.downloadMatrixFromPackedTexture(p.texture.texture,...Il(e)).subarray(0,r);return this.disposeIntermediateTensorInfo(h),f}const i=z().getBool("WEBGL_PACK")&&o===!0,a=i?vl(e):e,c=i?new NF(a):new TF(a),l=this.runWebGLProgram(c,[{shape:a,dtype:s,dataId:t}],"float32"),u=this.texData.get(l.dataId),d=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(u.texture.texture,u.texShape[0],u.texShape[1]).subarray(0,r);return this.disposeIntermediateTensorInfo(l),d}timerAvailable(){return z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}time(t){const e=this.activeTimers,s=[];let o=!1;this.programTimersStack==null?(this.programTimersStack=s,o=!0):this.activeTimers.push(s),this.activeTimers=s,t();const r=Qs(this.activeTimers.map(c=>c.query)).filter(c=>c!=null),i=Qs(this.activeTimers.map(c=>c.name)).filter(c=>c!=null);this.activeTimers=e,o&&(this.programTimersStack=null);const a={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const c=await Promise.all(r);a.kernelMs=qI(c),a.getExtraProfileInfo=()=>c.map((l,u)=>({name:i[u],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", ")}else a.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,a})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:Ve(),endMs:null}}endTimer(t){return z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),t):(t.endMs=Ve(),t)}async getQueryTime(t){if(z().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(t);const e=t;return e.endMs-e.startMs}disposeData(t,e=!1){if(this.pendingDisposal.has(t))return!1;if(!this.texData.has(t))return!0;if(e?this.texData.get(t).refCount=0:this.texData.get(t).refCount--,!e&&this.texData.get(t).refCount>0)return!1;if(this.pendingRead.has(t))return this.pendingDisposal.add(t),this.pendingDeletes++,!1;this.releaseGPUData(t);const{complexTensorInfos:s}=this.texData.get(t);return s!=null&&(this.disposeData(s.real.dataId,e),this.disposeData(s.imag.dataId,e)),this.texData.delete(t),!0}releaseGPUData(t){const{texture:e,dtype:s,texShape:o,usage:r,isPacked:i,slice:a}=this.texData.get(t),c=a&&a.origDataId||t,l=this.dataRefCount.get(c);l>1?this.dataRefCount.set(c,l-1):(this.dataRefCount.delete(c),e!=null&&(this.numBytesInGPU-=this.computeBytes(o,s),this.textureManager.releaseTexture(e,o,r,i)));const u=this.texData.get(t);u.texture=null,u.texShape=null,u.isPacked=!1,u.slice=null}getTexture(t){return this.uploadToGPU(t),this.texData.get(t).texture.texture}getDataInfo(t){return this.texData.get(t)}shouldExecuteOnCPU(t,e=iX){return z().getBool("WEBGL_CPU_FORWARD")&&t.every(s=>this.texData.get(s.dataId).texture==null&&Z(s.shape)<e)}getGPGPUContext(){return this.gpgpu}where(t){je("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");const e=t.dataSync();return nX(t.shape,e)}packedUnaryOp(t,e,s){const o=new Fs(t.shape,e),r=this.compileAndRun(o,[t],s);return zt().makeTensorFromTensorInfo(r)}abs(t){if(this.shouldExecuteOnCPU([t])&&t.dtype!=="complex64"){const o=v1(this.texData.get(t.dataId).values);return this.makeOutput(t.shape,t.dtype,o)}if(z().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,G1,t.dtype);const e=new jn(t.shape,G1),s=this.compileAndRun(e,[t]);return zt().makeTensorFromTensorInfo(s)}makeTensorInfo(t,e,s){let o;if(e==="string"&&s!=null&&s.length>0&&Cr(s[0])){const r=s.map(i=>bs(i));o=this.write(r,t,e)}else o=this.write(s,t,e);return this.texData.get(o).usage=null,{dataId:o,shape:t,dtype:e}}makeOutput(t,e,s){return zt().makeTensorFromTensorInfo(this.makeTensorInfo(t,e,s),this)}unpackTensor(t){const e=new eX(t.shape);return this.runWebGLProgram(e,[t],t.dtype)}packTensor(t){const e=new Xz(t.shape);return this.runWebGLProgram(e,[t],t.dtype,null,!0)}packedReshape(t,e){const s=[ur(t.shape),...dr(t.shape)],o={dtype:t.dtype,shape:s,dataId:t.dataId},r=[ur(e),...dr(e)],i=new T1(r,s),a=!0,c=[s],l=this.runWebGLProgram(i,[o],t.dtype,c,a);return{dataId:l.dataId,shape:e,dtype:l.dtype}}decode(t,e){const s=this.texData.get(t),{isPacked:o,shape:r,dtype:i}=s;if(e!=null){const h=Z(r),p=e[0]*e[1]*4;v(h<=p,()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.")}const a=vl(r);let c;o?c=new kF(a):c=new SF(a);const l=!0,u=[e??Il(a)],d=this.runWebGLProgram(c,[{shape:a,dtype:i,dataId:t}],i,u,l,e);return{dtype:i,shape:r,dataId:d.dataId}}runWebGLProgram(t,e,s,o,r=!1,i){const a=this.makeTensorInfo(t.outputShape,s),c=this.texData.get(a.dataId);if(t.packedOutput&&(c.isPacked=!0),t.outPackingScheme===sa.DENSE){const b=i??Il(t.outputShape);c.texShape=b.map(x=>x*2)}if(t.outTexUsage!=null&&(c.usage=t.outTexUsage),Z(a.shape)===0)return c.values=Se(a.dtype,0),a;const l=[],u=e.map(b=>{if(b.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let x=this.texData.get(b.dataId);if(x.texture==null){if(!t.packedInputs&&Z(b.shape)<=z().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:b.shape,texData:null,isUniform:!0,uniformValues:x.values};t.packedInputs&&(x.isPacked=!0,x.shape=b.shape)}if(this.uploadToGPU(b.dataId),!!x.isPacked!=!!t.packedInputs)b=x.isPacked?this.unpackTensor(b):this.packTensor(b),l.push(b),x=this.texData.get(b.dataId);else if(x.isPacked&&!kl(x.shape,b.shape)){const I=b,y=b.shape;b.shape=x.shape,b=this.packedReshape(b,y),l.push(b),x=this.texData.get(b.dataId),I.shape=y}return{shape:b.shape,texData:x,isUniform:!1}});this.uploadToGPU(a.dataId);const d={shape:a.shape,texData:c,isUniform:!1},h=vF(t,u,d),p=this.getAndSaveBinary(h,()=>wF(this.gpgpu,t,u,d)),f=this.activeTimers!=null;let m;f&&(m=this.startTimer()),z().get("ENGINE_COMPILE_ONLY")||CF(this.gpgpu,p,u,d,o),l.forEach(b=>this.disposeIntermediateTensorInfo(b)),f&&(m=this.endTimer(m),this.activeTimers.push({name:t.constructor.name,query:this.getQueryTime(m)}));const g=z().getNumber("WEBGL_FLUSH_THRESHOLD");if(g>0){const b=Ve();b-this.lastGlFlushTime>g&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=b)}if(!z().getBool("WEBGL_LAZILY_UNPACK")&&c.isPacked&&r===!1){const b=this.unpackTensor(a);return this.disposeIntermediateTensorInfo(a),b}return a}compileAndRun(t,e,s,o,r=!1){return s=s||e[0].dtype,this.runWebGLProgram(t,e,s,o,r)}getAndSaveBinary(t,e){return t in this.binaryCache||(this.binaryCache[t]=e()),this.binaryCache[t]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(z().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach(e=>{this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram),delete this.binaryCache[e]}),this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement<"u"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return this.floatPrecisionValue==null&&(this.floatPrecisionValue=M(()=>{if(!z().get("WEBGL_RENDER_FLOAT32_ENABLED")){const t=z().getBool("DEBUG");z().set("DEBUG",!1);const e=this.abs(Gt(1e-8)).dataSync()[0];if(z().set("DEBUG",t),e>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?sX:oX}uploadToGPU(t){const e=this.texData.get(t),{shape:s,dtype:o,values:r,texture:i,usage:a,isPacked:c}=e;if(i!=null)return;const l=this.activeTimers!=null;let u;l&&(u=Ve());let d=e.texShape;if(d==null&&(d=$V(s,c),e.texShape=d),r!=null){const h=vl(s);let p,f=d[1],m=d[0];const g=r instanceof Uint8Array||r instanceof Uint8ClampedArray;(c||!g)&&([f,m]=lr(d[0],d[1])),c?p=new $F(h,g):p=new g1(h,g);const b=g?[m,f]:d,x=this.makeTensorInfo(b,o),I=this.texData.get(x.dataId);g?I.usage=an.PIXELS:I.usage=an.UPLOAD,I.texShape=b,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(x.dataId),f,m,r);const y=[[m,f]],C=this.runWebGLProgram(p,[x],o,y,!0),k=this.texData.get(C.dataId);e.texShape=k.texShape,e.isPacked=k.isPacked,e.usage=k.usage,z().get("ENGINE_COMPILE_ONLY")?this.disposeData(C.dataId):(e.texture=k.texture,e.values=null,this.texData.delete(C.dataId)),this.disposeIntermediateTensorInfo(x),l&&(this.uploadWaitMs+=Ve()-u)}else{const h=this.acquireTexture(d,a,o,c);e.texture=h}}convertAndCacheOnCPU(t,e){const s=this.texData.get(t),{dtype:o}=s;return e!=null&&(s.values=lX(e,o)),s.values}acquireTexture(t,e,s,o){if(this.numBytesInGPU+=this.computeBytes(t,s),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){const r=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${r} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(t,e,o)}computeBytes(t,e){return t[0]*t[1]*xa(e)}checkCompileCompletion(){for(const[,t]of Object.entries(this.binaryCache))this.checkCompletion_(t)}async checkCompileCompletionAsync(){const t=[];if(this.gpgpu.parallelCompilationExtension){for(const[,e]of Object.entries(this.binaryCache))t.push(this.checkCompletionAsync_(e));return Promise.all(t)}else{for(const[,e]of Object.entries(this.binaryCache)){const s=new Promise(o=>{try{this.checkCompletion_(e),o(!0)}catch(r){throw r}});t.push(s)}return Promise.all(t)}}async checkCompletionAsync_(t){return this.gpgpu.gl.getProgramParameter(t.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?this.checkCompletion_(t):(await Xc(),this.checkCompletionAsync_(t))}checkCompletion_(t){if(this.gpgpu.gl.getProgramParameter(t.webGLProgram,this.gpgpu.gl.LINK_STATUS)===!1)throw console.log(this.gpgpu.gl.getProgramInfoLog(t.webGLProgram)),this.gpgpu.gl.getShaderParameter(t.fragmentShader,this.gpgpu.gl.COMPILE_STATUS)===!1?(i1(t.source,this.gpgpu.gl.getShaderInfoLog(t.fragmentShader)),new Error("Failed to compile fragment shader.")):new Error("Failed to link vertex and fragment shaders.");return!0}getUniformLocations(){for(const t of Object.values(this.binaryCache)){this.gpgpu.buildVao(t.webGLProgram);const{variablesLocations:e,customUniformLocations:s,infLoc:o,nanLoc:r,outShapeLocation:i,outShapeStridesLocation:a,outTexShapeLocation:c}=f1(this.gpgpu,t.program,t.webGLProgram);t.variablesLocations=e,t.customUniformLocations=s,t.infLoc=o,t.nanLoc=r,t.outShapeLocation=i,t.outShapeStridesLocation=a,t.outTexShapeLocation=c}}createTensorFromGPUData(t,e,s){t.channels=t.channels||"RGBA";const{texture:o,height:r,width:i,channels:a}=t,c=zt().backend;if(!c.gpgpu.gl.isTexture(o))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=c.writeTexture(o,e,s,r,i,a);return zt().makeTensorFromDataId(l,e,s,c)}}Rl.nextDataId=0;function lX(n,t){if(t==="float32"||t==="complex64")return n;if(t==="int32"||t==="bool"){const e=t==="int32"?new Int32Array(n.length):new Uint8Array(n.length);for(let s=0;s<e.length;++s)e[s]=Math.round(n[s]);return e}else throw new Error(`Unknown dtype ${t}`)}/**
 * @license
 * Copyright 2020 Google Inc. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */pm()&&bm("webgl",()=>new Rl,2);/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const Lp=`
  if (isnan(a)) return a;
  if (isnan(b)) return b;
`;class ko{constructor(t,e,s){this.variableNames=["A","B"],this.outputShape=gt(e,s),this.enableShapeUniforms=Ne(this.outputShape.length),this.userCode=`
      float binaryOperation(float a, float b) {
        ${t}
      }

      void main() {
        float a = getAAtOutCoords();
        float b = getBAtOutCoords();
        setOutput(binaryOperation(a, b));
      }
    `}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const To=`
  result.r = isNaN.r ? NAN : result.r;
  result.g = isNaN.g ? NAN : result.g;
  result.b = isNaN.b ? NAN : result.b;
  result.a = isNaN.a ? NAN : result.a;
`;class gr{constructor(t,e,s,o=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=gt(e,s);const r=this.outputShape.length;this.enableShapeUniforms=Ne(r);let i="";if(o)if(r===0||Z(this.outputShape)===1)i=`
          result.y = 0.;
          result.z = 0.;
          result.w = 0.;
        `;else if(i=`
          ${Wt(r)} coords = getOutputCoords();
        `,r===1)this.enableShapeUniforms?i+=`
            result.y = (coords + 1) >= outShape ? 0. : result.y;
            result.z = 0.;
            result.w = 0.;
          `:i+=`
            result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
            result.z = 0.;
            result.w = 0.;
          `;else{const c=We("coords",r);this.enableShapeUniforms?i+=`
            bool nextRowOutOfBounds =
              (${c[r-2]} + 1) >= outShape[${r} - 2];
            bool nextColOutOfBounds =
              (${c[r-1]} + 1) >= outShape[${r} - 1];
            result.y = nextColOutOfBounds ? 0. : result.y;
            result.z = nextRowOutOfBounds ? 0. : result.z;
            result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
          `:i+=`
            bool nextRowOutOfBounds =
              (${c[r-2]} + 1) >= ${this.outputShape[r-2]};
            bool nextColOutOfBounds =
              (${c[r-1]} + 1) >= ${this.outputShape[r-1]};
            result.y = nextColOutOfBounds ? 0. : result.y;
            result.z = nextRowOutOfBounds ? 0. : result.z;
            result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
          `}this.userCode=`
      vec4 binaryOperation(vec4 a, vec4 b) {
        ${t}
      }

      void main() {
        vec4 a = getAAtOutCoords();
        vec4 b = getBAtOutCoords();

        vec4 result = binaryOperation(a, b);
        ${i}

        setOutput(result);
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Je(n){const{inputs:t,backend:e}=n,{x:s}=t;return e.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const uX={kernelName:Kr,backendName:"webgl",kernelFunc:Je};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function zs(n){const{inputs:t,backend:e}=n,{real:s,imag:o}=t,r=e.makeTensorInfo(s.shape,"complex64"),i=e.texData.get(r.dataId),a=Je({inputs:{x:s},backend:e}),c=Je({inputs:{x:o},backend:e});return i.complexTensorInfos={real:a,imag:c},r}const dX={kernelName:lu,backendName:"webgl",kernelFunc:zs};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const L1="return (a < 0.) ? b * a : a;",E1=`
  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`;function hX(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{alpha:r}=s,i=e.makeTensorInfo([],"float32",gs(r,"float32")),a=z().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new gr(E1,o.shape,i.shape):new ko(L1,o.shape,i.shape),c=e.runWebGLProgram(a,[o,i],"float32");return e.disposeIntermediateTensorInfo(i),c}const pX={kernelName:Xa,backendName:"webgl",kernelFunc:hX};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const D1="return (a < 0.) ? b * a : a;",W1=`
  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`;function fX(n){const{inputs:t,backend:e}=n,{x:s,alpha:o}=t,r=z().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new gr(W1,s.shape,o.shape):new ko(D1,s.shape,o.shape);return e.runWebGLProgram(r,[s,o],"float32")}const mX={kernelName:oc,backendName:"webgl",kernelFunc:fX};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const br="if (isnan(x)) return x;";function Tt({opSnippet:n,packedOpSnippet:t,cpuKernelImpl:e,dtype:s}){return({inputs:o,backend:r})=>{const{x:i}=o,a=r,c=s||i.dtype;if(a.shouldExecuteOnCPU([i])&&e!=null){const d=a.texData.get(i.dataId),h=e(d.values,c);return a.makeTensorInfo(i.shape,c,h)}const l=z().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null;let u;return l?u=new Fs(i.shape,t):u=new jn(i.shape,n),a.runWebGLProgram(u,[i],c)}}function Ce({opSnippet:n,packedOpSnippet:t,checkOutOfBounds:e=!1,supportsComplex:s=!1,cpuKernelImpl:o,dtype:r}){return({inputs:i,backend:a})=>{const{a:c,b:l}=i,u=a;if(s&&c.dtype==="complex64"){const f=u.texData.get(c.dataId),m=u.texData.get(l.dataId),[g,b]=[[f.complexTensorInfos.real,m.complexTensorInfos.real],[f.complexTensorInfos.imag,m.complexTensorInfos.imag]].map(I=>{const[y,w]=I,C={dataId:y.dataId,dtype:y.dtype,shape:c.shape},k={dataId:w.dataId,dtype:w.dtype,shape:l.shape},S=new ko(n,c.shape,l.shape);return u.runWebGLProgram(S,[C,k],_e(y.dtype,w.dtype))}),x=zs({inputs:{real:g,imag:b},backend:u});return u.disposeIntermediateTensorInfo(g),u.disposeIntermediateTensorInfo(b),x}const d=r||_e(c.dtype,l.dtype);if((c.dtype==="string"||l.dtype==="string"||u.shouldExecuteOnCPU([c,l]))&&o!=null){const f=u.texData.get(c.dataId).values,m=u.texData.get(l.dataId).values,g=c.dtype==="string"?cs(f):f,b=c.dtype==="string"?cs(m):m,[x,I]=o(c.shape,l.shape,g,b,d),y=u.makeTensorInfo(I,d),w=u.texData.get(y.dataId);return w.values=x,y}const h=z().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null;let p;return h?p=new gr(t,c.shape,l.shape,e):p=new ko(n,c.shape,l.shape),u.runWebGLProgram(p,[c,l],d)}}function aa(n,t=!1){if(n==="linear")return t?Qz:Bz;if(n==="relu")return t?jz:_z;if(n==="elu")return t?Jz:Hz;if(n==="relu6")return t?qz:Uz;if(n==="prelu")return t?W1:D1;if(n==="leakyrelu")return t?E1:L1;if(n==="sigmoid")return t?tX:Yz;throw new Error(`Activation ${n} has not been implemented for the WebGL backend.`)}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class M1{constructor(t,e,s,o=!1,r=!1,i=!1,a=null,c=!1,l=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=s,this.enableShapeUniforms=Ne(this.outputShape.length);const u=o?t[1]:t[2],d=Math.ceil(u/2),h=o?"i * 2, rc.y":"rc.y, i * 2",p=r?"rc.z, i * 2":"i * 2, rc.z",f=o?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],m=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let g="",b="";a&&(c?g=`vec4 activation(vec4 a) {
          vec4 b = getPreluActivationWeightsAtOutCoords();
          ${a}
        }`:l?g=`vec4 activation(vec4 a) {
          vec4 b = getLeakyreluAlphaAtOutCoords();
          ${a}
        }`:g=`vec4 activation(vec4 x) {
          ${a}
        }`,b="result = activation(result);");const x=i?"result += getBiasAtOutCoords();":"";i&&this.variableNames.push("bias"),c&&this.variableNames.push("preluActivationWeights"),l&&this.variableNames.push("leakyreluAlpha");let I="rc.x",y="rc.x";t[0]<e[0]?I=`imod(rc.x, ${t[0]})`:e[0]<t[0]&&(y=`imod(rc.x, ${e[0]})`),this.userCode=`
      ${g}
      // Don't use uniform for sharedDimensionPacked for performance.
      const float sharedDimension = ${d}.0;

      vec4 dot2x2ARowBCol(ivec3 rc) {
        vec4 result = vec4(0);
        int batchA = ${I};
        int batchB = ${y};
        for (int i = 0; i < ${d}; i++) {
          vec4 a = getMatrixA(batchA, ${h});
          vec4 b = getMatrixB(batchB, ${p});

          // These swizzled products need to be separately added.
          // See: https://github.com/tensorflow/tfjs/issues/1735
          result += (${f[0]} * ${m[0]});
          result += (${f[1]} * ${m[1]});
        }
        return result;
      }

      void main() {
        ivec3 rc = getOutputCoords();
        vec4 result = dot2x2ARowBCol(rc);

        ${x}

        ${b}

        setOutput(result);
      }
    `}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const V1={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"};class F1{constructor(t,e,s){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=gt(e,s),this.userCode=`
      float binaryOpComplex(
          float areal, float aimag, float breal, float bimag) {
        ${t}
      }

      void main() {
        float areal = getARealAtOutCoords();
        float aimag = getAImagAtOutCoords();
        float breal = getBRealAtOutCoords();
        float bimag = getBImagAtOutCoords();
        setOutput(binaryOpComplex(areal, aimag, breal, bimag));
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const z1="return a * b;";function Ep(n){const{inputs:t,backend:e}=n,{a:s,b:o}=t,r=_e(s.dtype,o.dtype);if(s.dtype==="complex64"){const a=e.texData.get(s.dataId),c=e.texData.get(o.dataId),l=new F1(V1.REAL,s.shape,o.shape),u=new F1(V1.IMAG,s.shape,o.shape),d=[{dataId:a.complexTensorInfos.real.dataId,dtype:a.complexTensorInfos.real.dtype,shape:s.shape},{dataId:a.complexTensorInfos.imag.dataId,dtype:a.complexTensorInfos.imag.dtype,shape:s.shape},{dataId:c.complexTensorInfos.real.dataId,dtype:c.complexTensorInfos.real.dtype,shape:o.shape},{dataId:c.complexTensorInfos.imag.dataId,dtype:c.complexTensorInfos.imag.dtype,shape:o.shape}],h=e.runWebGLProgram(l,d,"float32"),p=e.runWebGLProgram(u,d,"float32"),f=zs({inputs:{real:h,imag:p},backend:e});return e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(p),f}if(e.shouldExecuteOnCPU([s,o])){const a=e.texData.get(s.dataId),c=e.texData.get(o.dataId),[l,u]=fz(s.shape,o.shape,a.values,c.values,r),d=e.makeTensorInfo(u,r),h=e.texData.get(d.dataId);return h.values=l,d}let i;return z().getBool("WEBGL_PACK_BINARY_OPERATIONS")?i=new gr(z1,s.shape,o.shape):i=new ko(z1,s.shape,o.shape),e.runWebGLProgram(i,[s,o],r)}const gX={kernelName:jr,backendName:"webgl",kernelFunc:Ep};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function bX(n,t,e){const s=[ur(n.shape),...dr(n.shape)],o={dtype:n.dtype,shape:s,dataId:n.dataId},r=[ur(t),...dr(t)],i=new T1(r,s),a=!0,c=[s],l=e.runWebGLProgram(i,[o],n.dtype,c,a);return{dataId:l.dataId,shape:t,dtype:l.dtype}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function tt(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{shape:r}=s,i=e,a=Z(o.shape),c=df(r,a),l=Z(c);v(a===l,()=>`The new shape (${c}) has ${l} elements and the old shape (${o.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`);const u=i.texData.get(o.dataId);return u.isPacked&&!kl(o.shape,c)&&!(u.texture!==null&&kl(u.shape,c))?bX(o,c,i):(i.incRef(o.dataId),{dataId:o.dataId,shape:c,dtype:o.dtype})}const xX={kernelName:ic,backendName:"webgl",kernelFunc:tt};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class X1{constructor(t,e){this.variableNames=["x"];const{windowSize:s,batchSize:o,inSize:r,outSize:i}=t;this.outputShape=[o,i];const a=Math.floor(s/4)*4,c=s%4;let l="sumValue += dot(values, ones);";if(e!=null){const d=1/e;l=`sumValue += dot(values * ${Do(d)?d.toPrecision(2):d}, ones);`}let u="";r%s>0&&(u=`
        if (inIdx < 0 || inIdx >= ${r}) {
          return 0.0;
        }
      `),this.userCode=`
      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);

      float getValue(int batch, int inIdx) {
        ${u}
        return getX(batch, inIdx);
      }

      void main() {
        ivec2 coords = getOutputCoords();
        int batch = coords[0];
        int outIdx = coords[1];
        int inOffset = outIdx * ${s};

        float sumValue = 0.0;

        for (int i = 0; i < ${a}; i += 4) {
          int inIdx = inOffset + i;
          vec4 values = vec4(
            getValue(batch, inIdx),
            getValue(batch, inIdx + 1),
            getValue(batch, inIdx + 2),
            getValue(batch, inIdx + 3)
          );

          ${l}
        }

        int inIdx = inOffset + ${a};
        if (${c===1}) {
          vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);

          ${l}
        } else if (${c===2}) {
          vec4 values = vec4(
            getValue(batch, inIdx),
            getValue(batch, inIdx + 1), 0.0, 0.0);

          ${l}
        } else if (${c===3}) {
          vec4 values = vec4(
            getValue(batch, inIdx),
            getValue(batch, inIdx + 1),
            getValue(batch, inIdx + 2), 0.0);

          ${l}
        }
        setOutput(sumValue);
      }
    `}}/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class yX{constructor(t,e){this.variableNames=["x"];const{windowSize:s,batchSize:o,inSize:r,outSize:i}=t;this.outputShape=[o,i];let a="0.0",c="";e==="prod"?a="1.0":e==="min"?(a="1.0 / 1e-20",c="min"):e==="max"&&(a="-1.0 / 1e-20",c="max");let l=`${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;e==="sum"?l="sumValue":e==="prod"?l="prodValue":e==="all"?l="allValue":e==="any"&&(l="anyValue");const u=Math.floor(s/4)*4,d=s%4;let h=`
      if (${e==="sum"}) {
        sumValue += dot(values, ones);
      } else if (${e==="prod"}) {
        vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
        prodValue *= tmp[0] * tmp[1];
      } else {
        minMaxValue = ${c}(values, minMaxValue);
        if (${e==="min"} || ${e==="max"}) {
          minMaxValue = ${c}(values, minMaxValue);
          bvec4 isNaN = isnan(values);
          if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {
            minMaxValue = vec4(NAN);
          }
        }
      }
    `,p="vec4";e==="all"?(a="1.0",h=`
        bool reducedAllValue = all(values);
        float floatedReducedAllValue = float(reducedAllValue);
        allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
      `,p="bvec4"):e==="any"&&(a="0.0",h=`
        bool reducedAnyValue = any(values);
        float floatedReducedAnyValue = float(reducedAnyValue);
        anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
      `,p="bvec4");let f="";r%s>0&&(f=`
        if (inIdx < 0 || inIdx >= ${r}) {
          return initializationValue;
        }
      `),this.userCode=`
      const float initializationValue = ${a};
      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);

      float getValue(int batch, int inIdx) {
        ${f}
        return getX(batch, inIdx);
      }

      void main() {
        ivec2 coords = getOutputCoords();
        int batch = coords[0];
        int outIdx = coords[1];
        int inOffset = outIdx * ${s};

        vec4 minMaxValue = vec4(${a});
        float prodValue = 1.0;
        float sumValue = 0.0;
        float allValue = 1.0;
        float anyValue = 0.0;

        for (int i = 0; i < ${u}; i += 4) {
          int inIdx = inOffset + i;
          ${p} values = ${p}(
            getValue(batch, inIdx),
            getValue(batch, inIdx + 1),
            getValue(batch, inIdx + 2),
            getValue(batch, inIdx + 3)
          );

          ${h}
        }

        int inIdx = inOffset + ${u};
        if (${d===1}) {
          ${p} values = ${p}(
            getValue(batch, inIdx),
            initializationValue,
            initializationValue,
            initializationValue
          );

          ${h}
        } else if (${d===2}) {
          ${p} values = ${p}(
            getValue(batch, inIdx),
            getValue(batch, inIdx + 1),
            initializationValue,
            initializationValue
          );

          ${h}
        } else if (${d===3}) {
          ${p} values = ${p}(
            getValue(batch, inIdx),
            getValue(batch, inIdx + 1),
            getValue(batch, inIdx + 2),
            initializationValue
          );

          ${h}
        }
        setOutput(${l});
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function IX(n){const t=[];for(;t.length===0||t[t.length-1].outSize!==1;){const e=t.length?t[t.length-1].outSize:n[1],s=Ac(e);t.push({inSize:e,windowSize:s,outSize:Math.ceil(e/s)})}return t}function No(n,t,e,s){const o=IX(n.shape);let r=n;for(let i=0;i<o.length;i++){const{inSize:a,windowSize:c,outSize:l}=o[i];let u,d;e==="mean"?u=i===0?new X1({windowSize:c,inSize:a,batchSize:n.shape[0],outSize:l},a):new X1({windowSize:c,inSize:a,batchSize:n.shape[0],outSize:l}):u=new yX({windowSize:c,inSize:a,batchSize:n.shape[0],outSize:l},e),d=r,r=s.runWebGLProgram(u,[r],t),d.dataId!==n.dataId&&s.disposeIntermediateTensorInfo(d)}return r}/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class wX{constructor(t,e){this.variableNames=["A"];const s=new Array(t.length);for(let i=0;i<s.length;i++)s[i]=t[e[i]];this.outputShape=s,this.rank=s.length;const o=Wt(this.rank),r=CX(e);this.userCode=`
    void main() {
      ${o} resRC = getOutputCoords();
      setOutput(getA(${r}));
    }
    `}}function CX(n){const t=n.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);const e=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],s=new Array(t);for(let o=0;o<n.length;o++)s[n[o]]=e[o];return s.join()}/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class vX{constructor(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;const s=new Array(t.length);for(let u=0;u<s.length;u++)s[u]=t[e[u]];if(this.outputShape=s,this.rank=s.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const o=Wt(this.rank),r=k1("rc",this.rank),i=new Array(this.rank);for(let u=0;u<e.length;u++)i[e[u]]=r[u];const a=`vec2(${i.slice(-2).join()})`,c=`++${r[this.rank-1]} < ${s[this.rank-1]}`,l=`getChannel(getA(${i.join()}), ${a})`;this.userCode=`
    void main() {
      ${o} rc = getOutputCoords();
      vec4 result = vec4(0.);
      result[0] = ${l};
      if(${c}) {
        result[1] = ${l};
      }
      --${r[this.rank-1]};
      if(++${r[this.rank-2]} < ${s[this.rank-2]}) {
        result[2] = ${l};
        if(${c}) {
          result[3] = ${l};
        }
      }
      setOutput(result);
    }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function $l(n,t,e){const s=z().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new vX(n.shape,t):new wX(n.shape,t);return e.runWebGLProgram(s,[n],n.dtype)}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function SX(n,t,e,s){const o=t,r=n.shape.length,i=It(o,n.shape);let a=i;const c=Yt(a,r),l=c!=null;let u=n;l&&(u=$l(n,c,s),a=ee(a.length,r)),Ie("sum",a,r);const[d,h]=me(u.shape,a);let p=d;e&&(p=re(d,i));const f=Z(h),g=Z(n.shape)/f,b=tt({inputs:{x:u},attrs:{shape:[g,f]},backend:s}),x=nd(n.dtype),I=No(b,x,"sum",s),y=tt({inputs:{x:I},attrs:{shape:p},backend:s});return s.disposeIntermediateTensorInfo(b),s.disposeIntermediateTensorInfo(I),l&&s.disposeIntermediateTensorInfo(u),y}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Gl(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r,keepDims:i}=s;return SX(o,r,i,e)}const kX={kernelName:hc,backendName:"webgl",kernelFunc:Gl};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Me(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{perm:r}=s,i=e,a=o.shape.length,c=new Array(a);for(let u=0;u<c.length;u++)c[u]=o.shape[r[u]];let l;if(i.shouldExecuteOnCPU([o])){const d=i.texData.get(o.dataId).values,h=Gp(d,o.shape,o.dtype,r,c);l=i.makeTensorInfo(c,o.dtype);const p=i.texData.get(l.dataId);p.values=h}else l=$l(o,r,i);return l}const TX={kernelName:zo,backendName:"webgl",kernelFunc:Me};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const A1=1e3;function Ll({a:n,b:t,transposeA:e,transposeB:s,backend:o,bias:r=null,preluActivationWeights:i=null,leakyreluAlpha:a=0,activation:c=null}){const l=n.shape.length,u=t.shape.length,d=e?n.shape[l-2]:n.shape[l-1],h=s?t.shape[u-1]:t.shape[u-2],p=e?n.shape[l-1]:n.shape[l-2],f=s?t.shape[u-2]:t.shape[u-1],m=n.shape.slice(0,-2),g=t.shape.slice(0,-2),b=Z(m),x=Z(g),y=gt(n.shape.slice(0,-2),t.shape.slice(0,-2)).concat([p,f]);v(d===h,()=>`Error in matMul: inner shapes (${d}) and (${h}) of Tensors with shapes ${n.shape} and ${t.shape} and transposeA=${e} and transposeB=${s} must match.`);const w=e?[b,d,p]:[b,p,d],C=s?[x,f,h]:[x,h,f],k=tt({inputs:{x:n},backend:o,attrs:{shape:w}}),S=tt({inputs:{x:t},backend:o,attrs:{shape:C}}),T=[k,S],R=Math.max(b,x),L=e?k.shape[1]:k.shape[2],V=r!=null,F=i!=null,X=c==="leakyrelu",A=c!=null?aa(c,!0):null,P=V||F||X||A!=null;let B;if((p===1||f===1)&&L>A1&&P===!1){let H=k,U=S;e&&(H=Me({inputs:{x:k},backend:o,attrs:{perm:[0,2,1]}}),T.push(H)),s&&(U=Me({inputs:{x:S},backend:o,attrs:{perm:[0,2,1]}}),T.push(U));const Y=f!==1,j=f===1;let J=H;Y&&(J=tt({inputs:{x:H},backend:o,attrs:{shape:[R,L,1]}}),T.push(J));const nt=f===1?2:1;let q=U;j&&(q=tt({inputs:{x:U},backend:o,attrs:{shape:[R,1,L]}}),T.push(q));const rt=Ep({inputs:{a:J,b:q},backend:o});B=Gl({inputs:{x:rt},backend:o,attrs:{axis:nt,keepDims:!0}}),T.push(rt)}else{const H=_e(n.dtype,t.dtype),U=new M1(w,C,[R,p,f],e,s,V,A,F,X),Y=[k,S];if(r!=null&&Y.push(r),F&&Y.push(i),X){const j=o.makeTensorInfo([],"float32",gs(a,"float32"));Y.push(j),T.push(j)}B=o.runWebGLProgram(U,Y,H)}const K=tt({inputs:{x:B},backend:o,attrs:{shape:y}});T.push(B);for(const H of T)o.disposeIntermediateTensorInfo(H);return K}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function NX(n){const{inputs:t,backend:e,attrs:s}=n,{a:o,b:r,bias:i,preluActivationWeights:a}=t,{transposeA:c,transposeB:l,activation:u,leakyreluAlpha:d}=s;return Ll({a:o,b:r,transposeA:c,transposeB:l,backend:e,bias:i,preluActivationWeights:a,leakyreluAlpha:d,activation:u})}const RX={kernelName:yc,backendName:"webgl",kernelFunc:NX};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const P1="return abs(x);";function $X(n){const{inputs:t,backend:e}=n,{x:s}=t;if(e.shouldExecuteOnCPU([s])&&s.dtype!=="complex64"){const r=e.texData.get(s.dataId),i=v1(r.values);return e.makeTensorInfo(s.shape,s.dtype,i)}let o;return z().getBool("WEBGL_PACK_UNARY_OPERATIONS")?o=new Fs(s.shape,P1):o=new jn(s.shape,P1),e.runWebGLProgram(o,[s],s.dtype)}const GX={kernelName:ya,backendName:"webgl",kernelFunc:$X};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const LX=Cn+`
  if (abs(x) > 1.) {
    return NAN;
  }
  return acos(x);
`,EX=Tt({opSnippet:LX}),DX={kernelName:vr,backendName:"webgl",kernelFunc:EX};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const WX=Cn+`
  if (x < 1.0) return NAN;
return log(x + sqrt(x * x - 1.0));`,MX=Tt({opSnippet:WX}),VX={kernelName:Sr,backendName:"webgl",kernelFunc:MX};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const O1="return a + b;",FX=Ce({opSnippet:O1,packedOpSnippet:O1,supportsComplex:!0,cpuKernelImpl:_F}),zX={kernelName:Fo,backendName:"webgl",kernelFunc:FX};/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class XX{constructor(t,e){this.outputShape=[],this.outputShape=t,this.variableNames=e.map((r,i)=>`T${i}`);const s=[];this.variableNames.forEach(r=>{s.push(`float v${r} = get${r}AtOutCoords();`)});const o=this.variableNames.map(r=>`v${r}`).join(" + ");this.userCode=`
      void main() {
        ${s.join(`
        `)}

        float result = ${o};
        setOutput(result);
      }
    `}}/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class AX{constructor(t,e){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.variableNames=e.map((r,i)=>`T${i}`);const s=[];this.variableNames.forEach(r=>{s.push(`vec4 v${r} = get${r}AtOutCoords();`)});const o=this.variableNames.map(r=>`v${r}`).join(" + ");this.userCode=`
      void main() {
        ${s.join(`
        `)}

        vec4 result = ${o};
        setOutput(result);
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function El(n){const{inputs:t,backend:e}=n,s=t;if(s.length===1)return Je({inputs:{x:s[0]},backend:e});if(s.length>z().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const c=Math.floor(s.length/2),l=El({inputs:s.slice(0,c),backend:e}),u=El({inputs:s.slice(c),backend:e});return El({inputs:[l,u],backend:e})}const o=s.map(c=>c.dtype).reduce((c,l)=>_e(c,l)),r=s.map(c=>c.shape),a=z().getBool("WEBGL_PACK")?new AX(s[0].shape,r):new XX(s[0].shape,r);return e.runWebGLProgram(a,s,o)}const PX={kernelName:nu,backendName:"webgl",kernelFunc:El};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function OX(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r,keepDims:i}=s,a=o.shape.length,c=It(r,o.shape);let l=c;const u=Yt(l,a);let d=o;u!=null&&(d=Me({inputs:{x:o},backend:e,attrs:{perm:u}}),l=ee(l.length,a)),Ie("all",l,a);const[h,p]=me(d.shape,l),f=Z(p),m=tt({inputs:{x:d},backend:e,attrs:{shape:[-1,f]}}),g=No(m,m.dtype,"all",e);let b;if(i){const x=re(h,c);b=tt({inputs:{x:g},backend:e,attrs:{shape:x}})}else b=tt({inputs:{x:g},backend:e,attrs:{shape:h}});return e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(g),u!=null&&e.disposeIntermediateTensorInfo(d),b}const KX={kernelName:su,backendName:"webgl",kernelFunc:OX};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function ZX(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r,keepDims:i}=s,a=o.shape.length,c=It(r,o.shape);let l=c;const u=Yt(l,a);let d=o;u!=null&&(d=Me({inputs:{x:o},backend:e,attrs:{perm:u}}),l=ee(l.length,a)),Ie("any",l,a);const[h,p]=me(d.shape,l),f=Z(p),m=tt({inputs:{x:d},backend:e,attrs:{shape:[-1,f]}}),g=No(m,m.dtype,"any",e);let b;if(i){const x=re(h,c);b=tt({inputs:{x:g},backend:e,attrs:{shape:x}})}else b=tt({inputs:{x:g},backend:e,attrs:{shape:h}});return e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(g),u!=null&&e.disposeIntermediateTensorInfo(d),b}const BX={kernelName:ou,backendName:"webgl",kernelFunc:ZX};/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class HX{constructor(t,e,s){this.variableNames=["A"];const{windowSize:o,batchSize:r,outSize:i}=t;s||this.variableNames.push("bestIndicesA"),this.outputShape=[r,i];const a=e==="max"?">":"<",c=s?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
      void main() {
        ivec2 coords = getOutputCoords();
        int batch = coords[0];
        int outIdx = coords[1];
        int inOffset = outIdx * ${o};

        int bestIndex = inOffset;
        float bestValue = getA(batch, bestIndex);

        for (int i = 0; i < ${o}; i++) {
          int inIdx = ${c};
          float candidate = getA(batch, inIdx);
          if (candidate ${a} bestValue) {
            bestValue = candidate;
            bestIndex = inIdx;
          }
        }
        setOutput(float(bestIndex));
      }
    `}}/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class _X{constructor(t,e,s,o){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,v(t.length>2,()=>`Packed arg${s.charAt(0).toUpperCase()+s.slice(1)} supports only inputs with rank above 2.`);const r=t[t.length-1],i=Math.ceil(r/e);this.outputShape=t.slice(0,-1),i>1&&this.outputShape.push(i),o||this.variableNames.push("bestIndicesA");const a=this.outputShape,c=a.length,l=Wt(c),u=We("coords",c);let d,h;if(i===1){h=c+1;const S=Wt(h);d=`
        ${S} sourceLocR = ${S}(${u.join()}, 0);
        ++${u[c-1]};
        ${S} sourceLocG = ${S}(${u.join()}, 0);
        ++${u[c-2]};
        ${S} sourceLocA = ${S}(${u.join()}, 0);
        --${u[c-1]};
        ${S} sourceLocB = ${S}(${u.join()}, 0);
        --${u[c-2]};`}else h=c,d=`
        ${l} sourceLocR = coords;
        ++${u[c-1]};
        ${l} sourceLocG = coords;
        ++${u[c-2]};
        ${l} sourceLocA = coords;
        --${u[c-1]};
        ${l} sourceLocB = coords;
        --${u[c-2]};`;const p=["x","y","z","w","u","v"].slice(0,h),f="."+p[h-1],m=p.map(S=>"int "+S),g=We("sourceLocR",h-1).concat("inIdx.r"),b=We("sourceLocG",h-1).concat("inIdx.g"),x=We("sourceLocB",h-1).concat("inIdx.b"),I=We("sourceLocA",h-1).concat("inIdx.a"),y=s==="max"?"greaterThan":"lessThan",w=o?"":`
          inIdx = round(vec4(getBestIndicesAChannel(${g.join()}),
                             getBestIndicesAChannel(${b.join()}),
                             getBestIndicesAChannel(${x.join()}),
                             getBestIndicesAChannel(${I.join()})));`,C=`vec4(
            getAChannel(${g.join()}),
            hasNextCol ? getAChannel(${b.join()}) : 0.,
            hasNextRow ? getAChannel(${x.join()}) : 0.,
            hasNextRow && hasNextCol ? getAChannel(${I.join()}) : 0.)`,k=o?"":`
      float getBestIndicesAChannel(${m.join()}) {
        return getChannel(getBestIndicesA(${p.join()}),
                                          vec2(${p.slice(-2).join()}));
      }`;this.userCode=`
      float getAChannel(${m.join()}) {
        return getChannel(getA(${p.join()}),
                               vec2(${p.slice(-2).join()}));
      }
      ${k}
      void main() {
        ${l} coords = getOutputCoords();
        bool hasNextCol = ${u[c-1]} < ${a[c-1]-1};
        bool hasNextRow = ${u[c-2]} < ${a[c-2]-1};
        ${d}
        ivec4 srcIdx = ivec4(sourceLocR${f}, sourceLocG${f},
          sourceLocB${f}, sourceLocA${f}) * ${e};
        ivec4 inIdx = srcIdx;
        vec4 bestIndex = vec4(inIdx);
        vec4 bestValue = ${C};

        for (int i = 0; i < ${e}; i++) {
          inIdx = srcIdx;
          ${w}
          vec4 candidate = ${C};
          bvec4 nan = isnan(candidate);
          bvec4 replace = bvec4(
            vec4(${y}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));

          bestValue = vec4(replace.x  ? candidate.x : bestValue.x,
                           replace.y  ? candidate.y : bestValue.y,
                           replace.z  ? candidate.z : bestValue.z,
                           replace.w  ? candidate.w : bestValue.w);
          bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
          srcIdx++;
        }
        setOutput(bestIndex);
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function K1(n,t,e,s=null){let o=t.shape[0],r=t.shape[1];s!=null&&(o=s.shape[0],r=s.shape[1]);const i=Ac(r),a={windowSize:i,inSize:r,batchSize:o,outSize:Math.ceil(r/i)},c=new HX(a,e,s==null),l=[t];s!=null&&l.push(s);const u=n.runWebGLProgram(c,l,"int32");if(u.shape[1]===1)return u;const d=K1(n,t,e,u);return n.disposeIntermediateTensorInfo(u),d}function Z1(n,t,e,s=null){const o=s!=null?s.shape:t.shape,r=o[o.length-1],i=Ac(r),a=new _X(o,i,e,s==null),c=s==null?[t]:[t,s],l=n.runWebGLProgram(a,c,"int32");if(l.shape.length===t.shape.length){const u=Z1(n,t,e,l);return n.disposeIntermediateTensorInfo(l),u}return l}function B1(n,t,e,s){const o=[e];if(Ie("arg"+s.charAt(0).toUpperCase()+s.slice(1),o,t.shape.length),!z().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){const r=[],i=n.texData.get(t.dataId),a=i!==null&&i.isPacked;let c=t;a&&(c=n.unpackTensor(t),r.push(c));const[l,u]=me(c.shape,o),d=Z(u),h=tt({inputs:{x:c},backend:n,attrs:{shape:[-1,d]}});r.push(h);const p=K1(n,h,s);r.push(p);const f=tt({inputs:{x:p},backend:n,attrs:{shape:l}});return r.forEach(m=>n.disposeIntermediateTensorInfo(m)),f}return Z1(n,t,s)}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function UX(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r}=s;let i=It(r,o.shape);const a=Yt(i,o.shape.length);let c=o;const l=[];a!=null&&(c=Me({inputs:{x:o},backend:e,attrs:{perm:a}}),l.push(c),i=ee(i.length,c.shape.length)),Ie("argMax",[i[0]],c.shape.length);const u=B1(e,c,i[0],"max");return l.forEach(d=>e.disposeIntermediateTensorInfo(d)),u}const YX={kernelName:Ia,backendName:"webgl",kernelFunc:UX};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function QX(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r}=s;let i=It(r,o.shape);const a=Yt(i,o.shape.length);let c=o;const l=[];a!=null&&(c=Me({inputs:{x:o},backend:e,attrs:{perm:a}}),l.push(c),i=ee(i.length,c.shape.length)),Ie("argMin",[i[0]],c.shape.length);const u=B1(e,c,i[0],"min");return l.forEach(d=>e.disposeIntermediateTensorInfo(d)),u}const JX={kernelName:wa,backendName:"webgl",kernelFunc:QX};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const jX=Cn+`
  if (abs(x) > 1.) {
    return NAN;
  }
  return asin(x);
`,qX=Tt({opSnippet:jX}),tA={kernelName:kr,backendName:"webgl",kernelFunc:qX};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const eA=Cn+"return log(x + sqrt(x * x + 1.0));",nA=Tt({opSnippet:eA}),sA={kernelName:Tr,backendName:"webgl",kernelFunc:nA};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const oA=Cn+`
  return atan(x);
`,rA=Tt({opSnippet:oA}),iA={kernelName:Nr,backendName:"webgl",kernelFunc:rA};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const aA=Lp+`
  return atan(a, b);
`,cA=`
  vec4 result = atan(a, b);
  bvec4 isNaNA = isnan(a);
  bvec4 isNaNB = isnan(b);
  bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
  `+To+`
  return result;
`,lA=Ce({opSnippet:aA,packedOpSnippet:cA}),uA={kernelName:$r,backendName:"webgl",kernelFunc:lA};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const dA=Cn+`
  if ((x < -1.0) || (x > 1.0)) return NAN;
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,hA=Tt({opSnippet:dA}),pA={kernelName:Rr,backendName:"webgl",kernelFunc:hA};/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class ca{constructor(t,e,s,o=!1,r=!1){if(this.variableNames=["x"],e==="avg"&&s)throw new Error("Cannot compute positions for average pool.");const i=t.filterWidth,a=t.strideHeight,c=t.strideWidth,l=t.dilationHeight,u=t.dilationWidth,d=t.effectiveFilterHeight,h=t.effectiveFilterWidth,p=t.padInfo.top,f=t.padInfo.left;this.outputShape=t.outShape;const m=e==="avg",g=`((batch  * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + d`,b=`(xR * ${t.inWidth} + xC) * ${t.inChannels} + d`;let x="0.0";if(m||(x="-1.0 / 1e-20"),s){const S=">=";this.userCode=`
        const ivec2 strides = ivec2(${a}, ${c});
        const ivec2 pads = ivec2(${p}, ${f});

        void main() {
          ivec4 coords = getOutputCoords();
          int batch = coords[0];
          int d = coords[3];

          ivec2 xRCCorner = coords.yz * strides - pads;
          int xRCorner = xRCCorner.x;
          int xCCorner = xRCCorner.y;

          // max/min x(?, ?, d) to get y(yR, yC, d).
          // ? = to be determined
          float minMaxValue = 0.0;
          float minMaxValueFound = 0.0;
          int minMaxPosition = 0;
          float avgValue = 0.0;

          for (int wR = 0; wR < ${d};
              wR += ${l}) {
            int xR = xRCorner + wR;

            if (xR < 0 || xR >= ${t.inHeight}) {
              continue;
            }

            for (int wC = 0; wC < ${h};
                wC += ${u}) {
              int xC = xCCorner + wC;

              if (xC < 0 || xC >= ${t.inWidth}) {
                continue;
              }

              float value = getX(batch, xR, xC, d);

              // If a min / max value has already been found, use it. If not,
              // use the current value.
              float currMinMaxValue = mix(
                  value, minMaxValue, minMaxValueFound);
              if (value ${S} currMinMaxValue) {
                minMaxValue = value;
                minMaxValueFound = 1.0;
                minMaxPosition = ${o?r?g:b:`wR * ${h} + wC`};
              }
            }
          }
          setOutput(float(minMaxPosition));
        }
      `;return}const I="max";let y=`${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;e==="avg"&&(y="avgValue / max(count, 1.0)");const w=Math.floor(i/4)*4,C=i%4,k=`
      if (${m}) {
        avgValue += dot(values, ones);
      } else {
        minMaxValue = ${I}(values, minMaxValue);
      }
    `;this.userCode=`
      const ivec2 strides = ivec2(${a}, ${c});
      const ivec2 pads = ivec2(${p}, ${f});
      const float initializationValue = ${x};
      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);

      float count = 0.0;

      float getValue(int batch, int xR, int xC, int d) {
        if (xC < 0 || xC >= ${t.inWidth}) {
          return initializationValue;
        }
        count += 1.0;
        return getX(batch, xR, xC, d);
      }

      void main() {
        ivec4 coords = getOutputCoords();
        int batch = coords[0];
        int d = coords[3];

        ivec2 xRCCorner = coords.yz * strides - pads;
        int xRCorner = xRCCorner.x;
        int xCCorner = xRCCorner.y;

        // max/min x(?, ?, d) to get y(yR, yC, d).
        // ? = to be determined
        vec4 minMaxValue = vec4(${x});
        float avgValue = 0.0;
        count = 0.0;

        for (int wR = 0; wR < ${d};
            wR += ${l}) {
          int xR = xRCorner + wR;

          if (xR < 0 || xR >= ${t.inHeight}) {
            continue;
          }

          for (int wC = 0; wC < ${w}; wC += 4) {
            int xC = xCCorner + wC * ${u};

            vec4 values = vec4(
              getValue(batch, xR, xC, d),
              getValue(batch, xR, xC + ${u}, d),
              getValue(batch, xR, xC + 2 * ${u}, d),
              getValue(batch, xR, xC + 3 * ${u}, d)
            );

            ${k}
          }

          int xC = xCCorner + ${w};
          if (${C===1}) {
            vec4 values = vec4(
              getValue(batch, xR, xC, d),
              initializationValue,
              initializationValue,
              initializationValue
            );

            ${k}
          } else if (${C===2}) {
            vec4 values = vec4(
              getValue(batch, xR, xC, d),
              getValue(batch, xR, xC + ${u}, d),
              initializationValue,
              initializationValue
            );

            ${k}
          } else if (${C===3}) {
            vec4 values = vec4(
              getValue(batch, xR, xC, d),
              getValue(batch, xR, xC + ${u}, d),
              getValue(batch, xR, xC + 2 * ${u}, d),
              initializationValue
            );

            ${k}
          }
        }
        setOutput(${y});
      }
    `}}class Dp{constructor(t,e,s,o=!1,r=!1){if(this.variableNames=["x"],e==="avg"&&s)throw new Error("Cannot compute positions for average pool.");const i=t.filterWidth,a=t.strideDepth,c=t.strideHeight,l=t.strideWidth,u=t.dilationDepth,d=t.dilationHeight,h=t.dilationWidth,p=t.effectiveFilterDepth,f=t.effectiveFilterHeight,m=t.effectiveFilterWidth,g=t.padInfo.front,b=t.padInfo.top,x=t.padInfo.left;this.outputShape=t.outShape;const I=e==="avg";let y="0.0";if(I||(y="-1.0 / 1e-20"),s){const R=">=";this.userCode=`
        const ivec3 strides =
            ivec3(${a}, ${c}, ${l});
        const ivec3 pads = ivec3(${g}, ${b}, ${x});

        void main() {
          ivec5 coords = getOutputCoords();
          int batch = coords.x;
          int ch = coords.u;

          ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
          int xDCorner = xCorner.x;
          int xRCorner = xCorner.y;
          int xCCorner = xCorner.z;

          // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
          // ? = to be determined
          float minMaxValue = 0.0;
          float minMaxValueFound = 0.0;
          int minMaxPosition = 0;

          for (int wD = 0; wD < ${p};
              wD += ${u}) {
            int xD = xDCorner + wD;

            if (xD < 0 || xD >= ${t.inDepth}) {
              continue;
            }

            for (int wR = 0; wR < ${f};
                wR += ${d}) {
              int xR = xRCorner + wR;

              if (xR < 0 || xR >= ${t.inHeight}) {
                continue;
              }

              for (int wC = 0; wC < ${m};
                  wC += ${h}) {
                int xC = xCCorner + wC;

                if (xC < 0 || xC >= ${t.inWidth}) {
                  continue;
                }

                float value = getX(batch, xD, xR, xC, ch);

                // If a min / max value has already been found, use it. If not,
                // use the current value.
                float currMinMaxValue = mix(
                    value, minMaxValue, minMaxValueFound);
                if (value ${R} currMinMaxValue) {
                  minMaxValue = value;
                  minMaxValueFound = 1.0;
                  minMaxPosition = ${o?r?`(((batch * ${t.inDepth} + xD) * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + ch`:`((xD * ${t.inHeight} + xR) * ${t.inWidth} + xC) * ${t.inChannels} + ch`:`wD * ${f} * ${m} +
                      wR * ${m} + wC`};
                }
              }
            }
          }
          setOutput(float(minMaxPosition));
        }
      `;return}const w="max";let C=`${e}(${e}(${e}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;e==="avg"&&(C="avgValue / max(count, 1.0)");const k=Math.floor(i/4)*4,S=i%4,T=`
      if (${I}) {
        avgValue += dot(values, ones);
      } else {
        minMaxValue = ${w}(values, minMaxValue);
      }
    `;this.userCode=`
      const ivec3 strides =
        ivec3(${a}, ${c}, ${l});
      const ivec3 pads = ivec3(${g}, ${b}, ${x});
      const float initializationValue = ${y};
      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);

      float count = 0.0;

      float getValue(int batch, int xD, int xR, int xC, int ch) {
        if (xC < 0 || xC >= ${t.inWidth}) {
          return initializationValue;
        }
        count += 1.0;
        return getX(batch, xD, xR, xC, ch);
      }

      void main() {
        ivec5 coords = getOutputCoords();
        int batch = coords.x;
        int ch = coords.u;

        ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
        int xDCorner = xCorner.x;
        int xRCorner = xCorner.y;
        int xCCorner = xCorner.z;

        // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
        // ? = to be determined
        vec4 minMaxValue = vec4(${y});
        float avgValue = 0.0;
        count = 0.0;

        for (int wD = 0; wD < ${p};
            wD += ${u}) {
          int xD = xDCorner + wD;

          if (xD < 0 || xD >= ${t.inDepth}) {
            continue;
          }

          for (int wR = 0; wR < ${f};
            wR += ${d}) {
            int xR = xRCorner + wR;

            if (xR < 0 || xR >= ${t.inHeight}) {
              continue;
            }

            for (int wC = 0; wC < ${k}; wC += 4) {
              int xC = xCCorner + wC * ${h};

              vec4 values = vec4(
                getValue(batch, xD, xR, xC, ch),
                getValue(batch, xD, xR, xC + ${h}, ch),
                getValue(batch, xD, xR, xC + 2 * ${h}, ch),
                getValue(batch, xD, xR, xC + 3 * ${h}, ch)
              );

              ${T}
            }

            int xC = xCCorner + ${k};
            if (${S===1}) {
              vec4 values = vec4(
                getValue(batch, xD, xR, xC, ch),
                initializationValue,
                initializationValue,
                initializationValue
              );

              ${T}
            } else if (${S===2}) {
              vec4 values = vec4(
                getValue(batch, xD, xR, xC, ch),
                getValue(batch, xD, xR, xC + ${h}, ch),
                initializationValue,
                initializationValue
              );

              ${T}
            } else if (${S===3}) {
              vec4 values = vec4(
                getValue(batch, xD, xR, xC, ch),
                getValue(batch, xD, xR, xC + ${h}, ch),
                getValue(batch, xD, xR, xC + 2 * ${h}, ch),
                initializationValue
              );

              ${T}
            }
          }
        }
        setOutput(${C});
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function fA(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t;ra(o,"avgPool");const{filterSize:r,strides:i,pad:a,dimRoundingMode:c}=s,l=1;v(Te(i,l),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${l}'`);const u=pn(o.shape,r,i,l,a,c);if(u.filterWidth===1&&u.filterHeight===1&&Rt(u.inShape,u.outShape))return Je({inputs:{x:o},backend:e});const d=new ca(u,"avg",!1);return e.runWebGLProgram(d,[o],"float32")}const mA={kernelName:Ca,backendName:"webgl",kernelFunc:fA};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function gA(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{filterSize:r,strides:i,pad:a,dimRoundingMode:c,dataFormat:l}=s,u=[1,1,1],d=ss(o.shape,r,i,u,a,c,l),h=new Dp(d,"avg",!1);return e.runWebGLProgram(h,[o],"float32")}const bA={kernelName:va,backendName:"webgl",kernelFunc:gA};/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class xA{constructor(t){this.variableNames=["dy"],this.outputShape=t.inShape;const e=t.filterHeight,s=t.filterWidth,o=t.strideHeight,r=t.strideWidth,i=t.dilationHeight,a=t.dilationWidth,c=t.effectiveFilterHeight,l=t.effectiveFilterWidth,u=c-1-t.padInfo.top,d=l-1-t.padInfo.left,h=1/(e*s);this.userCode=`
      const ivec2 pads = ivec2(${u}, ${d});
      const float avgMultiplier = float(${h});

      void main() {
        ivec4 coords = getOutputCoords();
        int b = coords[0];
        int d = coords[3];

        ivec2 dyRCCorner = coords.yz - pads;
        int dyRCorner = dyRCCorner.x;
        int dyCCorner = dyRCCorner.y;

        // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
        // ? = to be determined. : = across all values in that axis.
        float dotProd = 0.0;
        for (int wR = 0; wR < ${c};
            wR += ${i}) {
          float dyR = float(dyRCorner + wR) / ${o}.0;

          if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {
            continue;
          }
          int idyR = int(dyR);

          for (int wC = 0; wC < ${l};
            wC+= ${a}) {
            float dyC = float(dyCCorner + wC) / ${r}.0;

            if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
                fract(dyC) > 0.0) {
              continue;
            }
            int idyC = int(dyC);

            float dyValue = getDy(b, idyR, idyC, d);

            dotProd += dyValue * avgMultiplier;
          }
        }
        setOutput(dotProd);
      }
    `}}class yA{constructor(t){this.variableNames=["dy"],this.outputShape=t.inShape;const e=t.filterDepth,s=t.filterHeight,o=t.filterWidth,r=t.strideDepth,i=t.strideHeight,a=t.strideWidth,c=t.dilationDepth,l=t.dilationHeight,u=t.dilationWidth,d=t.effectiveFilterDepth,h=t.effectiveFilterHeight,p=t.effectiveFilterWidth,f=d-1-t.padInfo.front,m=h-1-t.padInfo.top,g=p-1-t.padInfo.left,b=1/(e*s*o);this.userCode=`
      const ivec3 pads = ivec3(${f}, ${m}, ${g});
      const float avgMultiplier = float(${b});

      void main() {
        ivec5 coords = getOutputCoords();
        int batch = coords.x;
        int ch = coords.u;

        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
        int dyDCorner = dyCorner.x;
        int dyRCorner = dyCorner.y;
        int dyCCorner = dyCorner.z;

        // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
        // dx(xD, xR, xC, ch).
        // ? = to be determined. : = across all values in that axis.
        float dotProd = 0.0;

        for (int wD = 0; wD < ${d};
            wD += ${c}) {
          float dyD = float(dyDCorner + wD) / ${r}.0;

          if (dyD < 0.0 || dyD >= ${t.outDepth}.0 || fract(dyD) > 0.0) {
            continue;
          }
          int idyD = int(dyD);

          for (int wR = 0; wR < ${h};
              wR += ${l}) {
            float dyR = float(dyRCorner + wR) / ${i}.0;

            if (dyR < 0.0 || dyR >= ${t.outHeight}.0 ||
                fract(dyR) > 0.0) {
              continue;
            }
            int idyR = int(dyR);

            for (int wC = 0; wC < ${p};
                wC += ${u}) {
              float dyC = float(dyCCorner + wC) / ${a}.0;

              if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
                  fract(dyC) > 0.0) {
                continue;
              }
              int idyC = int(dyC);

              float dyValue = getDy(batch, idyD, idyR, idyC, ch);

              dotProd += dyValue * avgMultiplier;
            }
          }
        }
        setOutput(dotProd);
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function IA(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,input:r}=t,i=r,{filterSize:a,strides:c,pad:l,dimRoundingMode:u}=s,d=[1,1,1],h=ss(i.shape,a,c,d,l,u),p=new yA(h);return e.runWebGLProgram(p,[o],i.dtype)}const wA={kernelName:iu,backendName:"webgl",kernelFunc:IA};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function CA(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,input:r}=t,i=r;ra([o,r],"avgPoolGrad");const{filterSize:a,strides:c,pad:l}=s,u=pn(i.shape,a,c,1,l),d=new xA(u);return e.runWebGLProgram(d,[o],i.dtype)}const vA={kernelName:ru,backendName:"webgl",kernelFunc:CA};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function SA(n){const{inputs:t,backend:e,attrs:s}=n,{a:o,b:r}=t,{transposeA:i,transposeB:a}=s;return Ll({a:o,b:r,transposeA:i,transposeB:a,backend:e})}const kA={kernelName:Sa,backendName:"webgl",kernelFunc:SA};/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class TA{constructor(t,e,s,o,r,i){this.outputShape=[],this.variableNames=["x","mean","variance"],gt(t,e),gt(t,s);let a="0.0";o!=null&&(gt(t,o),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let c="1.0";r!=null&&(gt(t,r),this.variableNames.push("scale"),c="getScaleAtOutCoords()"),this.outputShape=t,this.userCode=`
      void main() {
        float x = getXAtOutCoords();
        float mean = getMeanAtOutCoords();
        float variance = getVarianceAtOutCoords();
        float offset = ${a};
        float scale = ${c};
        float inv = scale * inversesqrt(variance + float(${i}));
        setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
      }
    `}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class NA{constructor(t,e,s,o,r,i){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],gt(t,e),gt(t,s);let a="vec4(0.0)";o!=null&&(gt(t,o),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let c="vec4(1.0)";r!=null&&(gt(t,r),this.variableNames.push("scale"),c="getScaleAtOutCoords()"),this.outputShape=t,this.userCode=`
      void main() {
        vec4 offset = ${a};
        vec4 scale = ${c};

        vec4 x = getXAtOutCoords();
        vec4 mean = getMeanAtOutCoords();
        vec4 variance = getVarianceAtOutCoords();

        vec4 inv = scale * inversesqrt(variance + vec4(${i}));

        setOutput((x - mean) * inv + offset);
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const RA={kernelName:Va,backendName:"webgl",kernelFunc:({inputs:n,backend:t,attrs:e})=>{const{x:s,mean:o,variance:r,offset:i,scale:a}=n;v(o.shape.length===r.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),v(i==null||o.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),v(a==null||o.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:c}=e;c==null&&(c=.001);const l=[s,o,r];let u=null;i!=null&&(u=i.shape,l.push(i));let d=null;a!=null&&(d=a.shape,l.push(a));const h=z().getBool("WEBGL_PACK_NORMALIZATION")?new NA(s.shape,o.shape,r.shape,u,d,c):new TA(s.shape,o.shape,r.shape,u,d,c);return t.runWebGLProgram(h,l,l[0].dtype)}};/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class $A{constructor(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;const e=Wt(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const s=GA(this.rank);let o;const r=t.map((i,a)=>`sourceLoc.${Wp[a]} = start[${a}] + coords.${Wp[a]};`);o=`
        ${e} sourceLoc;
        ${e} coords = getOutputCoords();
        ${r.join(`
`)}
      `,this.userCode=`
      void main() {
        ${o}
        setOutput(getSource(${s}));
      }
    `}}const Wp=["x","y","z","w","u","v"];function GA(n){if(n===1)return"sourceLoc";if(n<=6)return Wp.slice(0,n).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${n} is not yet supported`)}/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class LA{constructor(t){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.rank=t.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const e=Wt(this.rank),s=We("coords",this.rank),o=We("sourceLoc",this.rank),r=this.rank===1?"sourceLoc":`vec2(${o.slice(-2).join()})`,i=`getChannel(getSource(${o.join()}), ${r})`,a=`
      result.x = ${i};
      if (++${s[this.rank-1]} < ${t[this.rank-1]}) {
        ++${o[this.rank-1]};
        result.y = ${i};
        --${o[this.rank-1]};
      }
    `,c=this.rank===1?"":`
      --${s[this.rank-1]};
      if (++${s[this.rank-2]} < ${t[this.rank-2]}) {
        ++${o[this.rank-2]};
        result.z = ${i};
        if (++${s[this.rank-1]} < ${t[this.rank-1]}) {
          ++${o[this.rank-1]};
          result.w = ${i};
        }
      }
    `,l=this.rank<=4?`sourceLoc = coords +
            ${e}(${t.map((u,d)=>`start[${d}]`).join()});`:t.map((u,d)=>`${o[d]} = ${s[d]} + start[${d}];`).join(`
`);this.userCode=`
      void main() {
        ${e} coords = getOutputCoords();
        ${e} sourceLoc;
        ${l}
        vec4 result = vec4(0.);
        ${a}
        ${c}
        setOutput(result);
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function EA(n,t,e,s){const o=s.texData.get(n.dataId),r=s.makeTensorInfo(e,n.dtype),i=s.texData.get(r.dataId);Object.assign(i,o),i.refCount=1,i.shape=e,i.dtype=n.dtype;let a=nh(t,ct(n.shape));o.slice&&(a+=o.slice.flatOffset),i.slice={flatOffset:a,origDataId:o.slice&&o.slice.origDataId||n.dataId};const c=s.dataRefCount.get(i.slice.origDataId)||1;return s.dataRefCount.set(i.slice.origDataId,c+1),r}function xr(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{begin:r,size:i}=s,[a,c]=zc(o,r,i);if(qd(o,a,c),Z(c)===0)return e.makeTensorInfo(c,o.dtype,[]);if(e.shouldExecuteOnCPU([o])||o.dtype==="string"){const d=e.texData.get(o.dataId),h=kz(d.values,a,c,o.shape,o.dtype);return e.makeTensorInfo(c,o.dtype,h)}const{isPacked:l}=e.texData.get(o.dataId),u=eh(o.shape,a,c);if(l||!u){const d=z().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new LA(c):new $A(c),h=[a];return e.runWebGLProgram(d,[o],o.dtype,h)}return e.uploadToGPU(o.dataId),EA(o,a,c,e)}const DA={kernelName:dc,backendName:"webgl",kernelFunc:xr};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const WA={kernelName:ka,backendName:"webgl",kernelFunc:n=>{const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{blockShape:r,crops:i}=s;v(o.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");const a=r.reduce((x,I)=>x*I),c=Mi(o.shape,r,a),l=Vi(c.length,r.length),u=Fi(o.shape,r,a),d=ah(i,r.length),h=ch(u,i,r.length),p=[],f=tt({inputs:{x:o},backend:e,attrs:{shape:c}}),m=Me({inputs:{x:f},backend:e,attrs:{perm:l}}),g=tt({inputs:{x:m},backend:e,attrs:{shape:u}}),b=xr({inputs:{x:g},backend:e,attrs:{begin:d,size:h}});return p.push(f),p.push(m),p.push(g),p.forEach(x=>e.disposeIntermediateTensorInfo(x)),b}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function MA(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,weights:r}=t,{size:i}=s,a=e.readSync(o.dataId),c=e.readSync(r.dataId),l=C1(a,c,r.dtype,r.shape,i);return e.makeTensorInfo([i],r.dtype,l)}const VA={kernelName:au,backendName:"webgl",kernelFunc:MA};/**
 * @license
 * Copyright 2023 Google LLC.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const FA=`
  int r = int(a.r) & int(b.r);
  int g = int(a.g) & int(b.g);
  int rb = int(a.b) & int(b.b);
  int ra = int(a.a) & int(b.a);
  return vec4(r, g, rb, ra);
`,zA=`
  return float(int(a.r) & int(b.r));
`;function XA(n){const{inputs:t,backend:e}=n,{a:s,b:o}=t,r=z().getBool("WEBGL_PACK_BINARY_OPERATIONS"),i=z().getNumber("WEBGL_VERSION");if(e.shouldExecuteOnCPU([s,o])||i===1){const c=e.texData.get(s.dataId).values,l=e.texData.get(o.dataId).values,[u,d]=YF(s.shape,o.shape,c,l,s.dtype),h=e.makeTensorInfo(d,s.dtype),p=e.texData.get(h.dataId);return p.values=u,h}let a;return r?a=new gr(FA,s.shape,o.shape,!1):a=new ko(zA,s.shape,o.shape),e.runWebGLProgram(a,[s,o],s.dtype)}const AA={kernelName:cu,backendName:"webgl",kernelFunc:XA};/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function PA(n){const{inputs:t,backend:e}=n,{s0:s,s1:o}=t,r=e.readSync(s.dataId),i=e.readSync(o.dataId),a=gt(Array.from(r),Array.from(i));return e.makeTensorInfo([a.length],"int32",Int32Array.from(a))}const OA={kernelName:xf,backendName:"webgl",kernelFunc:PA};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const H1=Ce({opSnippet:"return float(a != b);",cpuKernelImpl:gz,dtype:"bool"}),KA={kernelName:qa,backendName:"webgl",kernelFunc:H1};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function la(n){const{inputs:t,backend:e}=n,{input:s}=t,o=e.texData.get(s.dataId);return Je({inputs:{x:o.complexTensorInfos.real},backend:e})}const ZA={kernelName:Mu,backendName:"webgl",kernelFunc:la};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const BA="return float(int(x));";function HA(n,t){const e=new jn(n.shape,BA),s=t.runWebGLProgram(e,[n],"int32");return{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Mp(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{dtype:r}=s;if(r==="complex64"){if(o.dtype==="complex64")return Je({inputs:{x:o},backend:e});const i=ge(o.shape),a=Mp({inputs:{x:o},backend:e,attrs:{dtype:"float32"}}),c=zs({inputs:{real:a,imag:i},backend:e});return i.dispose(),e.disposeIntermediateTensorInfo(a),c}if(o.dtype==="complex64"){const i=la({inputs:{input:o},backend:e}),a=Mp({inputs:{x:i},backend:e,attrs:{dtype:r}});return e.disposeIntermediateTensorInfo(i),a}if(!hf(o.dtype,r)){const i=Je({inputs:{x:o},backend:e});return{dataId:i.dataId,shape:i.shape,dtype:r}}if(e.shouldExecuteOnCPU([o])){const i=e.texData.get(o.dataId).values,[a,c,l]=QF(i,o.shape,o.dtype,r);return e.makeTensorInfo(a,c,l)}if(r==="int32")return HA(o,e);if(r==="bool"){const i=e.makeTensorInfo([],"bool",Se("bool",1)),c=H1({inputs:{a:o,b:i},backend:e});return e.disposeIntermediateTensorInfo(i),c}throw new Error(`Error in Cast: failed to cast ${o.dtype} to ${r}`)}const _A={kernelName:Gr,backendName:"webgl",kernelFunc:Mp};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const _1="return ceil(x);",UA=Tt({opSnippet:_1,packedOpSnippet:_1,cpuKernelImpl:JF}),YA={kernelName:Lr,backendName:"webgl",kernelFunc:UA};/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class QA{constructor(t){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=t,this.userCode=`

      void main() {
        float value = getAAtOutCoords();
        if (isnan(value)) {
          setOutput(value);
          return;
        }

        setOutput(clamp(value, minVal, maxVal));
      }
    `}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class JA{constructor(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=t,this.userCode=`
      void main() {
        vec4 value = getAAtOutCoords();

        if (any(isnan(value))) {
          setOutput(value);
          return;
        }

        setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function jA(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{clipValueMin:r,clipValueMax:i}=s;let a;z().getBool("WEBGL_PACK_CLIP")?a=new JA(o.shape):a=new QA(o.shape);const c=[[r],[i]];return e.runWebGLProgram(a,[o],o.dtype,c)}const qA={kernelName:Er,backendName:"webgl",kernelFunc:jA};/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class tP{constructor(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode=`
      void main() {
        float re = abs(getRealAtOutCoords());
        float im = abs(getImagAtOutCoords());
        float mx = max(re, im);

        // sadly the length function in glsl is not underflow-safe
        // (at least not on Intel GPUs). So the safe solution is
        // to ensure underflow-safety in all cases.
        setOutput(
          mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))
        );
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function U1(n,t){return{dataId:t.dataId,dtype:t.dtype,shape:n.shape}}function eP(n){const{inputs:t,backend:e}=n,{x:s}=t,o=e.texData.get(s.dataId),r=new tP(s.shape),i=[U1(s,o.complexTensorInfos.real),U1(s,o.complexTensorInfos.imag)];return e.runWebGLProgram(r,i,i[0].dtype)}const nP={kernelName:Ta,backendName:"webgl",kernelFunc:eP};/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class sP{constructor(t){this.outputShape=[],this.outputShape=Kn(t,1),this.variableNames=t.map((i,a)=>`T${a}`);const e=new Array(t.length-1);e[0]=t[0][1];for(let i=1;i<e.length;i++)e[i]=e[i-1]+t[i][1];const s=[`if (yC < ${e[0]}) setOutput(getT0(yR, yC));`];for(let i=1;i<e.length;i++){const a=e[i-1];s.push(`else if (yC < ${e[i]}) setOutput(getT${i}(yR, yC-${a}));`)}const o=e.length,r=e[e.length-1];s.push(`else setOutput(getT${o}(yR, yC-${r}));`),this.userCode=`
      void main() {
        ivec2 coords = getOutputCoords();
        int yR = coords.x;
        int yC = coords.y;

        ${s.join(`
        `)}
      }
    `}}/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class oP{constructor(t,e){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=Kn(t,e);const s=this.outputShape,o=s.length,r=Wt(o),i=We("coords",o),a=["x","y","z","w","u","v"].slice(0,o);this.variableNames=t.map((m,g)=>`T${g}`);const c=new Array(t.length-1);c[0]=t[0][e];for(let m=1;m<c.length;m++)c[m]=c[m-1]+t[m][e];const l=a[e],u=a.slice(-2),d=a.join();let h=`if (${l} < ${c[0]}) {
        return getChannel(
            getT0(${d}), vec2(${u.join()}));
        }`;for(let m=1;m<c.length;m++){const g=c[m-1];h+=`
        if (${l} < ${c[m]}  && ${l} >= ${c[m-1]}) {
          return getChannel(
            getT${m}(${Dl(a,l,g)}),
            vec2(${Dl(u,l,g)}));
        }`}const p=c.length,f=c[c.length-1];h+=`
        return getChannel(
          getT${p}(${Dl(a,l,f)}),
          vec2(${Dl(u,l,f)}));`,this.userCode=`
      float getValue(${a.map(m=>"int "+m)}) {
        ${h}
      }

      void main() {
        ${r} coords = getOutputCoords();
        vec4 result = vec4(getValue(${i}), 0., 0., 0.);

        ${i[o-1]} = ${i[o-1]} + 1;
        if (${i[o-1]} < ${s[o-1]}) {
          result.g = getValue(${i});
        }

        ${i[o-2]} = ${i[o-2]} + 1;
        if (${i[o-2]} < ${s[o-2]}) {
          result.a = getValue(${i});
        }

        ${i[o-1]} = ${i[o-1]} - 1;
        if (${i[o-2]} < ${s[o-2]} &&
            ${i[o-1]} < ${s[o-1]}) {
          result.b = getValue(${i});
        }
        setOutput(result);
      }
    `}}function Dl(n,t,e){const s=n.indexOf(t);return n.map((r,i)=>i===s?`${r} - ${e}`:r).join()}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Wl(n){const{inputs:t,backend:e}=n,{input:s}=t,o=e.texData.get(s.dataId);return Je({inputs:{x:o.complexTensorInfos.imag},backend:e})}const rP={kernelName:Nu,backendName:"webgl",kernelFunc:Wl};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function ua(n,t,e){const s=n[0].dtype;if(s==="complex64"){const p=n.map(x=>la({inputs:{input:x},backend:e})),f=n.map(x=>Wl({inputs:{input:x},backend:e})),m=ua(p,t,e),g=ua(f,t,e),b=zs({inputs:{real:m,imag:g},backend:e});return p.forEach(x=>e.disposeIntermediateTensorInfo(x)),f.forEach(x=>e.disposeIntermediateTensorInfo(x)),e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(g),b}let o=e.shouldExecuteOnCPU(n);if(s==="string"&&(o=!0),o){const p=n.map(y=>{const C=[-1,Z(y.shape.slice(t))];return tt({inputs:{x:y},backend:e,attrs:{shape:C}})}),f=p.map(y=>({vals:e.readSync(y.dataId),shape:y.shape})),m=Kn(p.map(y=>y.shape),1),g=p[0].shape[0]===1,b=jF(f,m,s,g),x=Kn(n.map(y=>y.shape),t),I=e.makeTensorInfo(x,s,b);return p.forEach(y=>e.disposeIntermediateTensorInfo(y)),I}const r=n.filter(p=>Z(p.shape)>0),i=z().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&r[0].shape.length>1;if(r.length===1){const p=i?new jn(n[0].shape,Vs):new Fs(n[0].shape,Vs);return e.runWebGLProgram(p,n,s)}const a=z().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(r.length>a){const p=[];for(let m=0;m<r.length;m+=a){const g=r.slice(m,m+a);p.push(ua(g,t,e))}const f=ua(p,t,e);for(const m of p)e.disposeIntermediateTensorInfo(m);return f}if(i){const p=new oP(r.map(f=>f.shape),t);return e.runWebGLProgram(p,r,s)}const{tensors2D:c,outShape:l}=iP(r,t,e),u=new sP(c.map(p=>p.shape)),d=e.runWebGLProgram(u,c,s);c.forEach(p=>e.disposeIntermediateTensorInfo(p));const h=tt({inputs:{x:d},attrs:{shape:l},backend:e});return e.disposeIntermediateTensorInfo(d),h}function iP(n,t,e){const s=Kn(n.map(r=>r.shape),t);return{tensors2D:n.map(r=>tt({inputs:{x:r},attrs:{shape:[-1,Z(r.shape.slice(t))]},backend:e})),outShape:s}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Y1(n){const{inputs:t,backend:e,attrs:s}=n,{axis:o}=s,r=It(o,t[0].shape)[0],i=t.map(l=>l.shape);oh(i,r);const a=Kn(t.map(l=>l.shape),r);if(Z(a)===0)return e.makeTensorInfo(a,t[0].dtype,[]);const c=t.filter(l=>Z(l.shape)>0);return c.length===1?Je({inputs:{x:c[0]},backend:e}):ua(c,r,e)}const aP={kernelName:Na,backendName:"webgl",kernelFunc:Y1};/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class Q1{constructor(t,e=!1,s=null,o=!1,r=!1){this.variableNames=["x","W"],this.outputShape=t.outShape;const i=t.padInfo.top,a=t.padInfo.left,c=t.strideHeight,l=t.strideWidth,u=t.dilationHeight,d=t.dilationWidth,h=t.filterHeight,p=t.filterWidth,f=Math.floor(t.inChannels/4)*4,m=t.inChannels%4,g=t.dataFormat==="channelsLast",b=g?1:2,x=g?2:3,I=g?3:1;let y="",w="";s&&(o?y=`float activation(float a) {
          float b = getPreluActivationWeightsAtOutCoords();
          ${s}
        }`:r?y=`float activation(float a) {
          float b = getLeakyreluAlphaAtOutCoords();
          ${s}
        }`:y=`
          float activation(float x) {
            ${s}
          }
        `,w="result = activation(result);");const C=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
      ${y}

      const ivec2 strides = ivec2(${c}, ${l});
      const ivec2 pads = ivec2(${i}, ${a});

      void main() {
        ivec4 coords = getOutputCoords();
        int batch = coords[0];
        int d2 = coords[${I}];

        ivec2 xRCCorner =
            ivec2(coords[${b}], coords[${x}]) * strides - pads;
        int xRCorner = xRCCorner.x;
        int xCCorner = xRCCorner.y;

        // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
        // ? = to be determined. : = across all values in that axis.
        float dotProd = 0.0;
        for (int wR = 0; wR < ${h}; wR++) {
          int xR = xRCorner + wR * ${u};

          if (xR < 0 || xR >= ${t.inHeight}) {
            continue;
          }

          for (int wC = 0; wC < ${p}; wC++) {
            int xC = xCCorner + wC * ${d};

            if (xC < 0 || xC >= ${t.inWidth}) {
              continue;
            }

            for (int d1 = 0; d1 < ${f}; d1 += 4) {
              vec4 wValues = vec4(
                getW(wR, wC, d1, d2),
                getW(wR, wC, d1 + 1, d2),
                getW(wR, wC, d1 + 2, d2),
                getW(wR, wC, d1 + 3, d2)
              );

              if (${g}) {
                vec4 xValues = vec4(
                  getX(batch, xR, xC, d1),
                  getX(batch, xR, xC, d1 + 1),
                  getX(batch, xR, xC, d1 + 2),
                  getX(batch, xR, xC, d1 + 3)
                );
                dotProd += dot(xValues, wValues);
              } else {
                vec4 xValues = vec4(
                  getX(batch, d1, xR, xC),
                  getX(batch, d1 + 1, xR, xC),
                  getX(batch, d1 + 2, xR, xC),
                  getX(batch, d1 + 3, xR, xC)
                );
                dotProd += dot(xValues, wValues);
              }
            }

            if (${m===1}) {

              if (${g}) {
                dotProd +=
                    getX(batch, xR, xC, ${f}) *
                    getW(wR, wC, ${f}, d2);
              } else {
                dotProd +=
                    getX(batch, ${f}, xR, xC) *
                    getW(wR, wC, ${f}, d2);
              }

            } else if (${m===2}) {
              vec2 wValues = vec2(
                getW(wR, wC, ${f}, d2),
                getW(wR, wC, ${f} + 1, d2)
              );

              if (${g}) {
                vec2 xValues = vec2(
                  getX(batch, xR, xC, ${f}),
                  getX(batch, xR, xC, ${f} + 1)
                );
                dotProd += dot(xValues, wValues);
              } else {
                vec2 xValues = vec2(
                  getX(batch, ${f}, xR, xC),
                  getX(batch, ${f} + 1, xR, xC)
                );
                dotProd += dot(xValues, wValues);
              }

            } else if (${m===3}) {
              vec3 wValues = vec3(
                getW(wR, wC, ${f}, d2),
                getW(wR, wC, ${f} + 1, d2),
                getW(wR, wC, ${f} + 2, d2)
              );

              if (${g}) {
                vec3 xValues = vec3(
                  getX(batch, xR, xC, ${f}),
                  getX(batch, xR, xC, ${f} + 1),
                  getX(batch, xR, xC, ${f} + 2)
                );
                dotProd += dot(xValues, wValues);
              } else {
                vec3 xValues = vec3(
                  getX(batch, ${f}, xR, xC),
                  getX(batch, ${f} + 1, xR, xC),
                  getX(batch, ${f} + 2, xR, xC)
                );
                dotProd += dot(xValues, wValues);
              }

            }
          }
        }

        float result = dotProd;
        ${C}
        ${w}
        setOutput(result);
      }
    `}}class cP{constructor(t){this.variableNames=["x","W"],this.outputShape=t.outShape;const e=t.padInfo.front,s=t.padInfo.top,o=t.padInfo.left,r=t.strideDepth,i=t.strideHeight,a=t.strideWidth,c=t.dilationDepth,l=t.dilationHeight,u=t.dilationWidth,d=t.filterDepth,h=t.filterHeight,p=t.filterWidth,f=Math.floor(t.inChannels/4)*4,m=t.inChannels%4;this.userCode=`
      const ivec3 strides = ivec3(${r}, ${i}, ${a});
      const ivec3 pads = ivec3(${e}, ${s}, ${o});

      void main() {
        ivec5 coords = getOutputCoords();
        int batch = coords.x;
        int d2 = coords.u;

        ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
        int xFCorner = xFRCCorner.x;
        int xRCorner = xFRCCorner.y;
        int xCCorner = xFRCCorner.z;

        // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
        // y(yF, yR, yC, d2). ? = to be determined. : = across all
        // values in that axis.
        float dotProd = 0.0;
        for (int wF = 0; wF < ${d}; wF++) {
          int xF = xFCorner + wF * ${c};

          if (xF < 0 || xF >= ${t.inDepth}) {
            continue;
          }

          for (int wR = 0; wR < ${h}; wR++) {
            int xR = xRCorner + wR * ${l};

            if (xR < 0 || xR >= ${t.inHeight}) {
              continue;
            }

            for (int wC = 0; wC < ${p}; wC++) {
              int xC = xCCorner + wC * ${u};

              if (xC < 0 || xC >= ${t.inWidth}) {
                continue;
              }

              for (int d1 = 0; d1 < ${f}; d1 += 4) {
                vec4 xValues = vec4(
                  getX(batch, xF, xR, xC, d1),
                  getX(batch, xF, xR, xC, d1 + 1),
                  getX(batch, xF, xR, xC, d1 + 2),
                  getX(batch, xF, xR, xC, d1 + 3)
                );
                vec4 wValues = vec4(
                  getW(wF, wR, wC, d1, d2),
                  getW(wF, wR, wC, d1 + 1, d2),
                  getW(wF, wR, wC, d1 + 2, d2),
                  getW(wF, wR, wC, d1 + 3, d2)
                );

                dotProd += dot(xValues, wValues);
              }

              if (${m===1}) {
                dotProd +=
                  getX(batch, xF, xR, xC, ${f}) *
                  getW(wF, wR, wC, ${f}, d2);
              } else if (${m===2}) {
                vec2 xValues = vec2(
                  getX(batch, xF, xR, xC, ${f}),
                  getX(batch, xF, xR, xC, ${f} + 1)
                );
                vec2 wValues = vec2(
                  getW(wF, wR, wC, ${f}, d2),
                  getW(wF, wR, wC, ${f} + 1, d2)
                );
                dotProd += dot(xValues, wValues);
              } else if (${m===3}) {
                vec3 xValues = vec3(
                  getX(batch, xF, xR, xC, ${f}),
                  getX(batch, xF, xR, xC, ${f} + 1),
                  getX(batch, xF, xR, xC, ${f} + 2)
                );
                vec3 wValues = vec3(
                  getW(wF, wR, wC, ${f}, d2),
                  getW(wF, wR, wC, ${f} + 1, d2),
                  getW(wF, wR, wC, ${f} + 2, d2)
                );
                dotProd += dot(xValues, wValues);
              }
            }
          }
        }
        setOutput(dotProd);
      }
    `}}/**
 * @license
 * Copyright 2022 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class J1{constructor(t,e=!1,s=null,o=!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=t.outShape,this.enableShapeUniforms=Ne(this.outputShape.length);const i=t.padInfo.left,a=t.strideWidth,c=t.dilationWidth,l=t.filterHeight,u=t.filterWidth,d=u;let h=`
       int xR; int xC; int xCOffset;
       vec4 wTexel; vec4 previous; vec4 final;`;for(let g=0;g<u;g++)h+=`
           vec4 xTexelC${g*2};
           int xTexelC${g*2}Ready;
           vec4 xTexelC${g*2+1};
           int xTexelC${g*2+1}Ready;
           vec4 xC${g};`;h+=`
     for (int r = 0; r < ${l}; r++) {
      for (int d1 = 0; d1 < ${t.inChannels}; d1 += 2) {
       `;for(let g=0;g<u;g++)h+=`
           xTexelC${g*2} = vec4(0.0);
           xTexelC${g*2}Ready = 0;
           xTexelC${g*2+1} = vec4(0.0);
           xTexelC${g*2+1}Ready = 0;
           xC${g} = vec4(0.0);`;h+=`
         xR = xRCorner + r * dilations[0];
         if (xR >=0 && xR < inDims[0]) {
       `;for(let g=0;g<(d+1)/2;g++){const b=g*2;if(h+=`
           xC = xCCorner + ${b*c};
           `,a===1){if(b<u&&(i%2===1?(h+=`
                 xCOffset = xC + 1;
                 if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
                   xTexelC${b} = getX(batch, xR, xCOffset, d1);

                   // Need to manually clear unused channels in case
                   // we're reading from recycled texture.
                   if (xCOffset + 1 >= inDims[1]) {
                     xTexelC${b}.zw = vec2(0.0);
                   }
                   xTexelC${b}Ready = 1;
                 }
               `,c===1&&b>0?h+=`
                 xC${b} = vec4(xTexelC${b-2}.zw, xTexelC${b}.xy);
                 `:h+=`
                   xCOffset = xC + 1 - 2;

                   if (xCOffset >= 0 && xCOffset < inDims[1]) {
                     previous = getX(batch, xR, xCOffset, d1);

                     // Need to manually clear unused channels in case
                     // we're reading from recycled texture.
                     if (xCOffset + 1 >= inDims[1]) {
                       previous.zw = vec2(0.0);
                     }

                     xC${b} = vec4(previous.zw, xTexelC${b}.xy);
                   } else {
                     xC${b} = vec4(0.0, 0.0, xTexelC${b}.xy);
                   }
                   `):h+=`
                 if (xC >= 0 && xC < inDims[1] && xTexelC${b}Ready == 0) {
                   xTexelC${b} = getX(batch, xR, xC, d1);
                   if (xC + 1 >= inDims[1]) {
                     xTexelC${b}.zw = vec2(0.0);
                   }
                   xTexelC${b}Ready = 1;
                 }

                 xC${b} = xTexelC${b};
                 `,b+1<u)){const x=i%2===0?Bl(c):c;c%2===0&&i%2===1||c%2!==0&&i%2!==1?(h+=`
                   xCOffset = xC + imod(pads[1], 2) + ${x};

                   if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) {
                     xTexelC${b+1} = getX(batch, xR, xCOffset, d1);

                     // Need to manually clear unused channels in case
                     // we're reading from recycled texture.
                     if (xCOffset + 1 >= inDims[1]) {
                       xTexelC${b+1}.zw = vec2(0.0);
                     }
                     xTexelC${b+1}Ready = 1;
                   }
                   `,c>1?h+=`
                     xCOffset -= 2;
                     if (xCOffset >= 0 && xCOffset < inDims[1]) {
                      previous = getX(batch, xR, xCOffset, d1);
                      xC${b+1} = vec4(previous.zw, xTexelC${b+1}.xy);
                     } else {
                      xC${b+1} = vec4(0.0, 0.0, xTexelC${b+1}.xy);
                     }
                     `:h+=`
                     xC${b+1} = vec4(xTexelC${b}.zw, xTexelC${b+1}.xy);
                     `):x===1?h+=`
                     xC${b+1} = xTexelC${b};
                     `:h+=`
                     xCOffset = xC + ${x};

                     if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) {
                       xTexelC${b+1} = getX(batch, xR, xCOffset, d1);
                       if (xCOffset + 1 >= inDims[1]) {
                         xTexelC${b+1}.zw = vec2(0.0);
                       }
                       xTexelC${b+1}Ready = 1;
                     }

                     xC${b+1} = xTexelC${b+1};
                     `}}else b<u&&(i%2===1?(h+=`
                 xCOffset = xC + 1 - strides[1];
                 if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b}Ready == 0) {
                   xTexelC${b} = getX(batch, xR, xCOffset, d1);
                   // Need to manually clear unused channels in case
                   // we're reading from recycled texture.
                   if (xCOffset + 1 >= inDims[1]) {
                     xTexelC${b}.zw = vec2(0.0);
                   }
                   xTexelC${b}Ready = 1;
                 }

                 if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${b+1}Ready == 0) {
                   xTexelC${b+1} = getX(batch, xR, xC + 1, d1);
                   // Need to manually clear unused channels in case
                   // we're reading from recycled texture.
                   if (xC + 2 >= inDims[1]) {
                     xTexelC${b+1}.zw = vec2(0.0);
                   }
                   xTexelC${b+1}Ready = 1;
                 }

                 xC${b} = vec4(xTexelC${b}.zw, xTexelC${b+1}.zw);
               `,b+1<u&&(h+=`
                   final = vec4(0.0);
                   xCOffset = xC + 1 + strides[1];
                   if(xCOffset >= 0 && xCOffset < inDims[1]) {
                     final = getX(batch, xR, xCOffset, d1);
                   }
                   xC${b+1} = vec4(xTexelC${b+1}.xy, final.xy);
                 `)):(h+=`
                 if(xC >= 0 && xC < inDims[1] && xTexelC${b}Ready == 0) {
                   xTexelC${b} = getX(batch, xR, xC, d1);
                   if (xC + 1 >= inDims[1]) {
                     xTexelC${b}.zw = vec2(0.0);
                   }
                   xTexelC${b}Ready = 1;
                 }

                 xCOffset = xC + strides[1];
                 if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${b+1}Ready == 0) {
                   xTexelC${b+1} = getX(batch, xR, xCOffset, d1);
                   if (xCOffset + 1 >= inDims[1]) {
                     xTexelC${b+1}.zw = vec2(0.);
                   }
                   xTexelC${b+1}Ready = 1;
                 }

                 xC${b} = vec4(
                   xTexelC${b}.xy, xTexelC${b+1}.xy);
               `,b+1<u&&(h+=`
                   xC${b+1} = vec4(xTexelC${b}.zw, xTexelC${b+1}.zw);
                 `)));b<u&&(h+=`
             wTexel = getW(r, ${b}, d1, d2);
             dotProd += xC${b}.xxzz * vec4(wTexel.xy, wTexel.xy);
             if(d1 + 1 < ${t.inChannels}) {
               dotProd += xC${b}.yyww * vec4(wTexel.zw, wTexel.zw);
             }
           `,b+1<u&&(h+=`
               wTexel = getW(r, ${b+1}, d1, d2);
               dotProd += xC${b+1}.xxzz * vec4(wTexel.xy, wTexel.xy);
               if(d1 + 1 < ${t.inChannels}) {
                 dotProd += xC${b+1}.yyww * vec4(wTexel.zw, wTexel.zw);
               }
             `))}h+=`
     }
   `,h+=`
     }
   `,h+=`
     }
   `;let p="",f="";s&&(o?p=`vec4 activation(vec4 a) {
           vec4 b = getPreluActivationWeightsAtOutCoords();
           ${s}
         }`:r?p=`vec4 activation(vec4 a) {
           vec4 b = getLeakyreluAlphaAtOutCoords();
           ${s}
         }`:p=`vec4 activation(vec4 x) {
           ${s}
         }`,f="result = activation(result);");const m=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
       ${p}

       void main() {
         ivec4 coords = getOutputCoords();
         int batch = coords.x;
         ivec2 xRCCorner = coords.yz * strides - pads;
         int d2 = coords.w;
         int xRCorner = xRCCorner.x;
         int xCCorner = xRCCorner.y;

         //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
         vec4 dotProd = vec4(0.000000000000001);

         ${h}

         vec4 result = dotProd - vec4(0.000000000000001);
         ${m}
         ${f}
         setOutput(result);
       }
     `}}/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class lP{constructor(t,e){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=t,this.enableShapeUniforms=Ne(this.outputShape.length);const{dataFormat:s}=e,o=De(),r=s==="channelsLast",i=r?1:2,a=r?2:3,c=this.enableShapeUniforms?"if(blockIndex < outShape[2] && pos < outShape[1]) {":`if(blockIndex < ${t[2]} && pos < ${t[1]}) {`;let l="";for(let u=0;u<=1;u++)for(let d=0;d<=1;d++)l+=`
          blockIndex = rc.z + ${d};
          pos = rc.y + ${u};

          ${c}
            offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];
            d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);

            if(d0 < inputShape[${i}] && d0 >= 0) {
              // Use custom imod instead mod. On Intel GPU, mod may generate
              // unexpected value.
              // https://github.com/tensorflow/tfjs/issues/5447
              offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];
              d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /
                  inChannels);

              if(d1 < inputShape[${a}] && d1 >= 0) {

                ch = imod(pos, inChannels);

                if (${r}) {
                  innerDims = vec2(d1, ch);
                  result[${u*2+d}] = getChannel(
                    getA(rc.x, d0, int(innerDims.x),
                    int(innerDims.y)), innerDims);
                } else {
                  innerDims = vec2(d0, d1);
                  result[${u*2+d}] = getChannel(
                    getA(rc.x, ch, int(innerDims.x),
                    int(innerDims.y)), innerDims);
                }
              }
            }
          }
        `;this.userCode=`
      void main() {
        ivec3 rc = getOutputCoords();

        vec4 result = vec4(0);

        int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
        vec2 innerDims;

        ${l}

        ${o.output} = result;
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Ml(n,t){const e=n.length;return e>=3?t?[...n.slice(0,-3),n[e-3]*n[e-2],n[e-1]]:[...n.slice(0,-3),n[e-3],n[e-2]*n[e-1]]:!t&&e===1&&n[0]>1?[n[0],1]:null}function j1({x:n,filter:t,convInfo:e,backend:s,bias:o=null,preluActivationWeights:r=null,leakyreluAlpha:i=0,activation:a=null}){const c=n.shape,l=s.texData.get(n.dataId),u=e.inChannels,d=c[0]*c[1]*c[2],h=e.outChannels,p=e.dataFormat==="channelsLast",f=!1,m=!1;let g;const b=[];if(r!=null){const y=Ml(r.shape,p);y!=null&&(r=tt({inputs:{x:r},backend:s,attrs:{shape:y}}),b.push(r))}if(o!=null){const y=Ml(o.shape,p);y!=null&&(o=tt({inputs:{x:o},backend:s,attrs:{shape:y}}),b.push(o))}if(!((d===1||h===1)&&u>A1)&&l.isPacked&&p&&l.texture!=null&&c[2]%2!==0&&Rt(l.shape.slice(-3),c.slice(-3))){const y=c[0]*c[1]*(c[2]+1),w={dataId:n.dataId,shape:[1,y,e.inChannels],dtype:n.dtype},C=l.shape;l.shape=l.shape.slice(),l.shape[l.shape.length-2]++,v(kl(l.shape,w.shape),()=>`packed reshape ${l.shape} to ${w.shape} isn't free`);const k=tt({inputs:{x:t},backend:s,attrs:{shape:[1,e.inChannels,e.outChannels]}});b.push(k);const S=Ll({a:w,b:k,backend:s,transposeA:f,transposeB:m,bias:o,activation:a,preluActivationWeights:r,leakyreluAlpha:i}),T=s.texData.get(S.dataId);v(T.isPacked,()=>"batchMatMul result is expected to be packed"),l.shape=C,T.shape=e.outShape,g=Je({inputs:{x:S},backend:s}),g.shape=e.outShape,b.push(S)}else{const y=e.outHeight*e.outWidth,w=tt({inputs:{x:n},backend:s,attrs:{shape:p?[e.batchSize,y,e.inChannels]:[e.batchSize,e.inChannels,y]}}),C=tt({inputs:{x:t},backend:s,attrs:{shape:[1,e.inChannels,e.outChannels]}}),k=Ll({a:p?w:C,b:p?C:w,transposeA:!p,transposeB:m,backend:s,bias:o,activation:a,preluActivationWeights:r,leakyreluAlpha:i});g=tt({inputs:{x:k},backend:s,attrs:{shape:e.outShape}}),b.push(w),b.push(C),b.push(k)}for(const y of b)s.disposeIntermediateTensorInfo(y);return g}function q1({x:n,filter:t,convInfo:e,backend:s,bias:o=null,preluActivationWeights:r=null,leakyreluAlpha:i=0,activation:a=null}){const{filterWidth:c,filterHeight:l,inChannels:u,outWidth:d,outHeight:h,dataFormat:p}=e,f=p==="channelsLast",m=c*l*u,g=h*d,b=[e.batchSize,m,g],x=!0,I=!1,y=[];if(r!=null){const K=Ml(r.shape,f);K!=null&&(r=tt({inputs:{x:r},backend:s,attrs:{shape:K}}),y.push(r))}if(o!=null){const K=Ml(o.shape,f);K!=null&&(o=tt({inputs:{x:o},backend:s,attrs:{shape:K}}),y.push(o))}const w=tt({inputs:{x:t},backend:s,attrs:{shape:[1,m,Z(t.shape)/m]}});y.push(w);const C=new lP(b,e),k=[n.shape,[e.padInfo.top,e.padInfo.left],[e.strideHeight,e.strideWidth],[e.dilationHeight,e.dilationWidth],[e.inChannels],[e.filterWidth*e.inChannels],[e.outWidth]],S=s.runWebGLProgram(C,[n],"float32",k),T=tt({inputs:{x:S},backend:s,attrs:{shape:b}});y.push(S),y.push(T);const R=o!=null,L=r!=null,V=a==="leakyrelu",F=a?aa(a,!0):null,X=new M1(f?T.shape:w.shape,f?w.shape:T.shape,f?[e.batchSize,g,e.outChannels]:[e.batchSize,e.outChannels,g],x,I,R,F,L,V),A=f?[T,w]:[w,T];if(o&&A.push(o),L&&A.push(r),V){const K=s.makeTensorInfo([],"float32",gs(i,"float32"));A.push(K),y.push(K)}const P=s.runWebGLProgram(X,A,"float32"),B=tt({inputs:{x:P},backend:s,attrs:{shape:e.outShape}});y.push(P);for(const K of y)s.disposeIntermediateTensorInfo(K);return B}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function uP(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,filter:r}=t,{strides:i,pad:a,dataFormat:c,dilations:l,dimRoundingMode:u}=s,d=os(c),h=ye(o.shape,r.shape,i,l,a,u,!1,d);let p;if(h.filterHeight===1&&h.filterWidth===1&&h.dilationHeight===1&&h.dilationWidth===1&&h.strideHeight===1&&h.strideWidth===1&&(h.padInfo.type==="SAME"||h.padInfo.type==="VALID"))p=j1({x:o,filter:r,convInfo:h,backend:e});else if(h.strideWidth<=2&&d==="channelsLast"&&z().getBool("WEBGL_EXP_CONV")){const m=new J1(h),g=[[h.padInfo.top,h.padInfo.left],[h.strideHeight,h.strideWidth],[h.dilationHeight,h.dilationWidth],[h.inHeight,h.inWidth]];p=e.runWebGLProgram(m,[o,r],"float32",g)}else if(z().getBool("WEBGL_CONV_IM2COL"))p=q1({x:o,filter:r,convInfo:h,backend:e});else{const m=new Q1(h);p=e.runWebGLProgram(m,[o,r],"float32")}const f=tt({inputs:{x:p},backend:e,attrs:{shape:h.outShape}});return e.disposeIntermediateTensorInfo(p),f}const dP={kernelName:Ra,backendName:"webgl",kernelFunc:uP};/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class hP{constructor(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;const e=t.strideHeight,s=t.strideWidth,o=t.padInfo.top,r=t.padInfo.left,i=t.dataFormat==="channelsLast";this.userCode=`
      void main() {
        ivec4 coords = getOutputCoords();
        int wR = coords.x;
        int wC = coords.y;
        int d1 = coords.z;
        int d2 = coords.w;

        // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
        // ? = to be determined. : = across all values in that axis.
        float dotProd = 0.0;

        for (int b = 0; b < ${t.batchSize}; b++) {
          for (int yR = 0; yR < ${t.outHeight}; yR++) {
            int xR = wR + yR * ${e} - ${o};

            if (xR < 0 || xR >= ${t.inHeight}) {
              continue;
            }

            for (int yC = 0; yC < ${t.outWidth}; yC++) {
              int xC = wC + yC * ${s} - ${r};

              if (xC < 0 || xC >= ${t.inWidth}) {
                continue;
              }

              ${i?`float dyValue = getDy(b, yR, yC, d2);
              float xValue = getX(b, xR, xC, d1);
              dotProd += (xValue * dyValue);`:`float dyValue = getDy(b, d2, yR, yC);
              float xValue = getX(b, d1, xR, xC);
              dotProd += (xValue * dyValue);`}
            }
          }
        }
        setOutput(dotProd);
      }
    `}}class pP{constructor(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;const e=t.filterHeight,s=t.filterWidth,o=t.strideHeight,r=t.strideWidth,i=t.dataFormat==="channelsLast",a=e-1-t.padInfo.top,c=s-1-t.padInfo.left,l=i?1:2,u=i?2:3,d=i?3:1;this.userCode=`
      const ivec2 pads = ivec2(${a}, ${c});

      void main() {
        ivec4 coords = getOutputCoords();
        int batch = coords[0];
        int d1 = coords[${d}];

        ivec2 dyCorner = ivec2(coords[${l}], coords[${u}]) - pads;
        int dyRCorner = dyCorner.x;
        int dyCCorner = dyCorner.y;

        // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
        // ? = to be determined. : = across all values in that axis.
        float dotProd = 0.0;
        for (int wR = 0; wR < ${e}; wR++) {
          float dyR = float(dyRCorner + wR) / ${o}.0;

          if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {
            continue;
          }
          int idyR = int(dyR);

          int wRPerm = ${e} - 1 - wR;

          for (int wC = 0; wC < ${s}; wC++) {
            float dyC = float(dyCCorner + wC) / ${r}.0;

            if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
                fract(dyC) > 0.0) {
              continue;
            }
            int idyC = int(dyC);

            int wCPerm = ${s} - 1 - wC;

            for (int d2 = 0; d2 < ${t.outChannels}; d2++) {

              if (${i}) {
                float xValue = getDy(batch, idyR, idyC, d2);
                float wValue = getW(wRPerm, wCPerm, d1, d2);
                dotProd += xValue * wValue;
              } else {
                float xValue = getDy(batch, d2, idyR, idyC);
                float wValue = getW(wRPerm, wCPerm, d1, d2);
                dotProd += xValue * wValue;
              }

            }
          }
        }
        setOutput(dotProd);
      }
    `}}class fP{constructor(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;const e=t.strideDepth,s=t.strideHeight,o=t.strideWidth,r=t.padInfo.front,i=t.padInfo.top,a=t.padInfo.left;this.userCode=`
      void main() {
        ivec5 coords = getOutputCoords();
        int wF = coords.x;
        int wR = coords.y;
        int wC = coords.z;
        int d1 = coords.w;
        int d2 = coords.u;

        float dotProd = 0.0;

        for (int b = 0; b < ${t.batchSize}; b++) {
          for (int yF = 0; yF < ${t.outDepth}; yF++) {
            int xF = wF + yF * ${e} - ${r};

            if (xF < 0 || xF >= ${t.inDepth}) {
              continue;
            }

            for (int yR = 0; yR < ${t.outHeight}; yR++) {
              int xR = wR + yR * ${s} - ${i};

              if (xR < 0 || xR >= ${t.inHeight}) {
                continue;
              }

              for (int yC = 0; yC < ${t.outWidth}; yC++) {
                int xC = wC + yC * ${o} - ${a};

                if (xC < 0 || xC >= ${t.inWidth}) {
                  continue;
                }

                float dyValue = getDy(b, yF, yR, yC, d2);
                float xValue = getX(b, xF, xR, xC, d1);
                dotProd += (xValue * dyValue);
              }
            }
          }
        }
        setOutput(dotProd);
      }
    `}}class mP{constructor(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;const e=t.filterDepth,s=t.filterHeight,o=t.filterWidth,r=t.strideDepth,i=t.strideHeight,a=t.strideWidth,c=e-1-t.padInfo.front,l=s-1-t.padInfo.top,u=o-1-t.padInfo.left;this.userCode=`
      const ivec3 pads = ivec3(${c}, ${l}, ${u});

      void main() {
        ivec5 coords = getOutputCoords();
        int batch = coords.x;
        int d1 = coords.u;


        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
        int dyFCorner = dyCorner.x;
        int dyRCorner = dyCorner.y;
        int dyCCorner = dyCorner.z;

        float dotProd = 0.0;
        for (int wF = 0; wF < ${e}; wF++) {
          float dyF = float(dyFCorner + wF) / ${r}.0;

          if (dyF < 0.0 || dyF >= ${t.outDepth}.0 || fract(dyF) > 0.0) {
            continue;
          }
          int idyF = int(dyF);

          int wFPerm = ${e} - 1 - wF;

          for (int wR = 0; wR < ${s}; wR++) {
            float dyR = float(dyRCorner + wR) / ${i}.0;

            if (dyR < 0.0 || dyR >= ${t.outHeight}.0 ||
              fract(dyR) > 0.0) {
              continue;
            }
            int idyR = int(dyR);

            int wRPerm = ${s} - 1 - wR;

            for (int wC = 0; wC < ${o}; wC++) {
              float dyC = float(dyCCorner + wC) / ${a}.0;

              if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
                  fract(dyC) > 0.0) {
                continue;
              }
              int idyC = int(dyC);

              int wCPerm = ${o} - 1 - wC;

              for (int d2 = 0; d2 < ${t.outChannels}; d2++) {
                float xValue = getDy(batch, idyF, idyR, idyC, d2);
                float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
                dotProd += xValue * wValue;
              }
            }
          }
        }
        setOutput(dotProd);
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function gP(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,dy:r}=t,{strides:i,pad:a,dataFormat:c,dimRoundingMode:l,filterShape:u}=s,d=os(c),h=ye(o.shape,u,i,1,a,l,!1,d),p=new hP(h);return e.runWebGLProgram(p,[o,r],"float32")}const bP={kernelName:uu,backendName:"webgl",kernelFunc:gP};/**
 * @license
 * Copyright 2023 Google LLC.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class xP{constructor(t){this.variableNames=["dy","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"strides",type:"vec2"}],this.outputShape=t.inShape,this.enableShapeUniforms=Ne(this.outputShape.length);const e=t.filterHeight,s=t.filterWidth,o=e-1-t.padInfo.top,r=s-1-t.padInfo.left;this.userCode=`
      const ivec2 pads = ivec2(${o}, ${r});

      void main() {
        ivec4 coords = getOutputCoords();
        int batch = coords[0];
        int d1 = coords[3];

        ivec2 dyCorner = ivec2(coords[1], coords[2]) - pads;
        int dyRCorner = dyCorner.x;
        int dyCCorner = dyCorner.y;

        vec4 result = vec4(0.);
        for (int wR = 0; wR < ${e}; wR++) {
          float dyR = float(dyRCorner + wR) / strides[0];
          if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {
            continue;
          }
          int idyR = int(dyR);
          int wRPerm = ${e} - 1 - wR;

          for (int wC = 0; wC < ${s}; wC++) {
            int wCPerm = ${s} - 1 - wC;

            float dyC = float(dyCCorner + wC) / strides[1];
            bool idyCVal = (dyC >= 0.0) && (dyC < ${t.outWidth}.0)
              && (fract(dyC) == 0.0);
            int idyC = int(dyC);

            float dyC2 = float(dyCCorner + wC + 1) / strides[1];
            bool idyCVal2 = (dyC2 >= 0.0) && (dyC2 < ${t.outWidth}.0)
              && (fract(dyC2) == 0.0);
            int idyC2 = int(dyC2);

            if (idyCVal && idyCVal2) {
              for (int d2 = 0; d2 < ${t.outChannels}; d2 += 2) {
                vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
                vec4 dySample = getDy(batch, idyR, idyC, d2);
                vec4 dySample2 = (idyC / 2 == idyC2 / 2) ?
                  dySample : getDy(batch, idyR, idyC2, d2);

                vec2 dyValue = mod(float(idyC), 2.) == 0. ?
                  dySample.xy : dySample.zw;
                result.xy += vec2(dot(dyValue, wValue.xy),
                  dot(dyValue, wValue.zw));

                dyValue = mod(float(idyC2), 2.) == 0. ?
                  dySample2.xy : dySample2.zw;
                result.zw += vec2(dot(dyValue, wValue.xy),
                  dot(dyValue, wValue.zw));
              }
            } else if (idyCVal) {
              for (int d2 = 0; d2 < ${t.outChannels}; d2 += 2) {
                vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
                vec4 dySample = getDy(batch, idyR, idyC, d2);
                vec2 dyValue = mod(float(idyC), 2.) == 0. ?
                  dySample.xy : dySample.zw;
                result.xy += vec2(dot(dyValue, wValue.xy),
                  dot(dyValue, wValue.zw));
              }
            } else if (idyCVal2) {
              for (int d2 = 0; d2 < ${t.outChannels}; d2 += 2) {
                vec4 wValue = getW(wRPerm, wCPerm, d1, d2);
                vec4 dySample = getDy(batch, idyR, idyC2, d2);
                vec2 dyValue = mod(float(idyC2), 2.) == 0. ?
                  dySample.xy : dySample.zw;
                result.zw += vec2(dot(dyValue, wValue.xy),
                  dot(dyValue, wValue.zw));
              }
            }
          }
        }
        setOutput(result);
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function yP(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,filter:r}=t,{inputShape:i,strides:a,pad:c,dataFormat:l,dimRoundingMode:u}=s,d=os(l),h=ye(i,r.shape,a,1,c,u,!1,d);if(z().getBool("WEBGL_PACK_CONV2DTRANSPOSE")&&d==="channelsLast"){const p=[[h.strideHeight,h.strideWidth]],f=new xP(h);return e.runWebGLProgram(f,[o,r],"float32",p)}else{const p=new pP(h);return e.runWebGLProgram(p,[o,r],"float32")}}const IP={kernelName:$a,backendName:"webgl",kernelFunc:yP};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function wP(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,filter:r}=t,{strides:i,pad:a,dilations:c}=s,l=ws(o.shape,r.shape,i,c,a),u=new cP(l);return e.runWebGLProgram(u,[o,r],"float32")}const CP={kernelName:Ga,backendName:"webgl",kernelFunc:wP};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function vP(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,dy:r}=t,{strides:i,pad:a,filterShape:c}=s,l=ws(o.shape,c,i,1,a),u=new fP(l);return e.runWebGLProgram(u,[o,r],"float32")}const SP={kernelName:du,backendName:"webgl",kernelFunc:vP};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function kP(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,filter:r}=t,{pad:i,strides:a,inputShape:c}=s,l=ws(c,r.shape,a,1,i),u=new mP(l);return e.runWebGLProgram(u,[o,r],"float32")}const TP={kernelName:hu,backendName:"webgl",kernelFunc:kP};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const NP=br+`
  return cos(x);
`,RP=`
  vec4 result = cos(x);
  bvec4 isNaN = isnan(x);
  ${To}
  return result;
`,$P=Tt({opSnippet:NP,packedOpSnippet:RP}),GP={kernelName:Dr,backendName:"webgl",kernelFunc:$P};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const LP=Tt({opSnippet:`
  float e2x = exp(-x);
  return (e2x + 1.0 / e2x) / 2.0;
`}),EP={kernelName:Wr,backendName:"webgl",kernelFunc:LP};/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class DP{constructor(t,e,s,o,r){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[i,a,c,l]=t,[u]=e,[d,h]=s;this.outputShape=[u,d,h,l];const p=o==="bilinear"?1:0,[f,m]=[`${a-1}.0`,`${c-1}.0`],[g,b,x]=d>1?[`${(a-1)/(d-1)}`,"(y2-y1) * height_ratio",`y1*${f} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${f}`],[I,y,w]=h>1?[`${(c-1)/(h-1)}`,"(x2-x1) * width_ratio",`x1*${m} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${m}`];this.userCode=`
      const float height_ratio = float(${g});
      const float width_ratio = float(${I});
      void main() {
        ivec4 coords = getOutputCoords();
        int b = coords[0];
        int y = coords[1];
        int x = coords[2];
        int d = coords[3];

        // get box vals
        float y1 = getBoxes(b,0);
        float x1 = getBoxes(b,1);
        float y2 = getBoxes(b,2);
        float x2 = getBoxes(b,3);

        // get image in batch index
        int bInd = round(getBoxInd(b));
        if(bInd < 0 || bInd >= ${i}) {
          return;
        }

        float height_scale = ${b};
        float width_scale = ${y};

        float in_y = ${x};
        if( in_y < 0.0 || in_y > ${f} ) {
          setOutput(float(${r}));
          return;
        }
        float in_x = ${w};
        if( in_x < 0.0 || in_x > ${m} ) {
          setOutput(float(${r}));
          return;
        }

        vec2 sourceFracIndexCR = vec2(in_x,in_y);
        if(${p} == 1) {
          // Compute the four integer indices.
          ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
          ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));

          float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
          float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
          float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
          float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);

          vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);

          float top = topLeft + (topRight - topLeft) * fracCR.x;
          float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
          float newValue = top + (bottom - top) * fracCR.y;
          setOutput(newValue);
        } else {
          // Compute the coordinators of nearest neighbor point.
          ivec2 sourceNearestCR = ivec2(floor(
            sourceFracIndexCR + vec2(0.5,0.5)));
          float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
          setOutput(newValue);
        }
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const WP={kernelName:fu,backendName:"webgl",kernelFunc:n=>{const{inputs:t,backend:e,attrs:s}=n,{image:o,boxes:r,boxInd:i}=t,{cropSize:a,method:c,extrapolationValue:l}=s,u=new DP(o.shape,r.shape,a,c,l);return e.runWebGLProgram(u,[o,r,i],"float32")}};var da;(function(n){n.Prod="*",n.Sum="+"})(da||(da={}));class tI{constructor(t,e,s,o){this.op=t,this.outputShape=e,this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}];const r=this.outputShape.length,i=this.op===da.Prod?"1.0":"0.0",a=s?i:`getX(${eI(r,"coords",this.op)})`,c=this.outputShape[this.outputShape.length-1];let l="",u="";s?(l=o?`end != ${c-1}`:"end != 0",u=o?"end + 1":"end - 1"):(l=o?`end + pow2 < ${c}`:"end >= pow2",u=o?"end + pow2":"end - pow2"),this.userCode=`
      void main() {
        ${Wt(r)} coords = getOutputCoords();
        int end = ${nI(r,"coords",this.op)};
        float val = ${a};
        int pow2 = int(pow(2.0, index));
        if (${l}) {
          int idx = ${u};
          ${nI(r,"coords",this.op)} = idx;
          val ${this.op}= getX(${eI(r,"coords",this.op)});
        }
        setOutput(val);
      }
    `}}function eI(n,t,e){if(n===1)return`${t}`;if(n===2)return`${t}.x, ${t}.y`;if(n===3)return`${t}.x, ${t}.y, ${t}.z`;if(n===4)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw new Error(`Cumulative ${e} for rank ${n} is not yet supported`)}function nI(n,t,e){if(n===1)return`${t}`;if(n===2)return`${t}.y`;if(n===3)return`${t}.z`;if(n===4)return`${t}.w`;throw new Error(`Cumulative ${e} for rank ${n} is not yet supported`)}/**
 * @license
 * Copyright 2022 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function sI(n,t,e,s,o,r){const i=t.shape.length,a=Yt([s],i);let c=t;a!=null&&(c=Me({inputs:{x:t},backend:e,attrs:{perm:a}}));const l=ee(1,i)[0];if(l!==i-1)throw new Error(`WebGL cumprod shader expects an inner-most axis=${t.shape.length-1} but got axis=${s}`);const u=c.shape[l];let d=Je({inputs:{x:c},backend:e});for(let h=0;h<=Math.ceil(Math.log2(u))-1;h++){const p=new tI(n,c.shape,!1,r),f=[[h]],m=d;d=e.runWebGLProgram(p,[d],d.dtype,f),e.disposeIntermediateTensorInfo(m)}if(o){const h=new tI(n,c.shape,o,r),p=d;d=e.runWebGLProgram(h,[d],d.dtype),e.disposeIntermediateTensorInfo(p)}if(a!=null){const h=Cs(a),p=Me({inputs:{x:d},backend:e,attrs:{perm:h}});return e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(c),p}return d}/**
 * @license
 * Copyright 2022 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function MP(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r,exclusive:i,reverse:a}=s;return sI(da.Prod,o,e,r,i,a)}const VP={kernelName:pu,backendName:"webgl",kernelFunc:MP};/**
 * @license
 * Copyright 2022 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function FP(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r,exclusive:i,reverse:a}=s;return sI(da.Sum,o,e,r,i,a)}const zP={kernelName:La,backendName:"webgl",kernelFunc:FP};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function XP(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,weights:r}=t,{size:i,binaryOutput:a}=s;if(o.shape.length===1){const c=e.readSync(o.dataId),l=e.readSync(r.dataId),u=C1(c,l,r.dtype,r.shape,i);return e.makeTensorInfo([i],r.dtype,u)}else if(o.shape.length===2){const c=e.bufferSync(o),l=e.bufferSync(r),u=UF(c,l,i,a);return e.makeTensorInfo(u.shape,r.dtype,u.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${o.shape.length}.`)}const AP={kernelName:mu,backendName:"webgl",kernelFunc:XP};/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class PP{constructor(t,e,s){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=s,this.userCode=`
    void main() {
      ivec4 coords = getOutputCoords();
      int b = coords[0];
      int h = ${this.getHeightCoordString()};
      int w = ${this.getWidthCoordString()};
      int d = ${this.getDepthCoordString()};

      int in_h = h / ${e};
      int offset_h = imod(h, ${e});
      int in_w = w / ${e};
      int offset_w = imod(w, ${e});
      int offset_d = (offset_h * ${e} + offset_w) *
        ${this.getOutputDepthSize()};
      int in_d = d + offset_d;

      float result = ${this.getInputSamplingString()};
      setOutput(result);
    }
  `}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function OP(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{blockSize:r,dataFormat:i}=s,a=o.shape[0],c=i==="NHWC"?o.shape[1]:o.shape[2],l=i==="NHWC"?o.shape[2]:o.shape[3],u=i==="NHWC"?o.shape[3]:o.shape[1],d=c*r,h=l*r,p=u/(r*r),f=i==="NHWC"?[a,d,h,p]:[a,p,d,h],m=new PP(f,r,i);return e.runWebGLProgram(m,[o],o.dtype)}const KP={kernelName:gu,backendName:"webgl",kernelFunc:OP};/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class oI{constructor(t,e=!1,s=null,o=!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=t.outShape,this.enableShapeUniforms=Ne(this.outputShape.length);const i=t.filterHeight,a=t.filterWidth,c=t.outChannels/t.inChannels;let l="",u="";s&&(o?l=`float activation(float a) {
          float b = getPreluActivationWeightsAtOutCoords();
          ${s}
        }`:r?l=`float activation(float a) {
          float b = getLeakyreluAlphaAtOutCoords();
          ${s}
        }`:l=`
          float activation(float x) {
            ${s}
          }
        `,u="result = activation(result);");const d=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
      ${l}

      void main() {
        ivec4 coords = getOutputCoords();
        int batch = coords.x;
        ivec2 xRCCorner = coords.yz * strides - pads;
        int d2 = coords.w;
        int d1 = d2 / ${c};
        int q = d2 - d1 * ${c};

        int xRCorner = xRCCorner.x;
        int xCCorner = xRCCorner.y;

        // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
        // ? = to be determined. : = across all values in that axis.
        float dotProd = 0.0;
        // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
        for (int wR = 0; wR < ${i}; wR++) {
          int xR = xRCorner + wR * dilations[0];

          if (xR < 0 || xR >= inDims[0]) {
            continue;
          }

          for (int wC = 0; wC < ${a}; wC++) {
            int xC = xCCorner + wC * dilations[1];

            if (xC < 0 || xC >= inDims[1]) {
              continue;
            }

            float xVal = getX(batch, xR, xC, d1);
            float wVal = getW(wR, wC, d1, q);
            dotProd += xVal * wVal;
          }
        }

        float result = dotProd;
        ${d}
        ${u}
        setOutput(result);
      }
    `}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class rI{constructor(t,e=!1,s=null,o=!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=t.outShape,this.enableShapeUniforms=Ne(this.outputShape.length);const i=t.outChannels/t.inChannels,a=t.padInfo.left,c=t.strideWidth,l=t.dilationWidth,u=t.filterHeight,d=t.filterWidth,h=d;let p=`
      int xR; int xC; int xCOffset;
      vec4 wTexel; vec4 previous; vec4 final;`;for(let b=0;b<d;b++)p+=`
          vec4 xTexelC${b*2};
          int xTexelC${b*2}Ready;
          vec4 xTexelC${b*2+1};
          int xTexelC${b*2+1}Ready;
          vec4 xC${b};`;p+=`
    for (int r = 0; r < ${u}; r++) {
      `;for(let b=0;b<d;b++)p+=`
          xTexelC${b*2} = vec4(0.0);
          xTexelC${b*2}Ready = 0;
          xTexelC${b*2+1} = vec4(0.0);
          xTexelC${b*2+1}Ready = 0;
          xC${b} = vec4(0.0);`;p+=`
        xR = xRCorner + r * dilations[0];
        if (xR >=0 && xR < inDims[0]) {
      `;for(let b=0;b<(h+1)/2;b++){const x=b*2;if(p+=`
          xC = xCCorner + ${x*l};
          `,c===1){if(x<d&&(a%2===1?(p+=`
                xCOffset = xC + 1;
                if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x}Ready == 0) {
                  xTexelC${x} = getX(batch, xR, xCOffset, d1);

                  // Need to manually clear unused channels in case
                  // we're reading from recycled texture.
                  if (xCOffset + 1 >= inDims[1]) {
                    xTexelC${x}.zw = vec2(0.0);
                  }
                  xTexelC${x}Ready = 1;
                }
              `,l===1&&x>0?p+=`
                xC${x} = vec4(xTexelC${x-2}.zw, xTexelC${x}.xy);
                `:p+=`
                  xCOffset = xC + 1 - 2;

                  if (xCOffset >= 0 && xCOffset < inDims[1]) {
                    previous = getX(batch, xR, xCOffset, d1);

                    // Need to manually clear unused channels in case
                    // we're reading from recycled texture.
                    if (xCOffset + 1 >= inDims[1]) {
                      previous.zw = vec2(0.0);
                    }

                    xC${x} = vec4(previous.zw, xTexelC${x}.xy);
                  } else {
                    xC${x} = vec4(0.0, 0.0, xTexelC${x}.xy);
                  }
                  `):p+=`
                if (xC >= 0 && xC < inDims[1] && xTexelC${x}Ready == 0) {
                  xTexelC${x} = getX(batch, xR, xC, d1);
                  if (xC + 1 >= inDims[1]) {
                    xTexelC${x}.zw = vec2(0.0);
                  }
                  xTexelC${x}Ready = 1;
                }

                xC${x} = xTexelC${x};
                `,x+1<d)){const I=a%2===0?Bl(l):l;l%2===0&&a%2===1||l%2!==0&&a%2!==1?(p+=`
                  xCOffset = xC + imod(pads[1], 2) + ${I};

                  if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x+1}Ready == 0) {
                    xTexelC${x+1} = getX(batch, xR, xCOffset, d1);

                    // Need to manually clear unused channels in case
                    // we're reading from recycled texture.
                    if (xCOffset + 1 >= inDims[1]) {
                      xTexelC${x+1}.zw = vec2(0.0);
                    }
                    xTexelC${x+1}Ready = 1;
                  }
                  `,l>1?p+=`
                    xCOffset -= 2;
                    if (xCOffset >= 0 && xCOffset < inDims[1]) {
                     previous = getX(batch, xR, xCOffset, d1);
                     xC${x+1} = vec4(previous.zw, xTexelC${x+1}.xy);
                    } else {
                     xC${x+1} = vec4(0.0, 0.0, xTexelC${x+1}.xy);
                    }
                    `:p+=`
                    xC${x+1} = vec4(xTexelC${x}.zw, xTexelC${x+1}.xy);
                    `):I===1?p+=`
                    xC${x+1} = xTexelC${x};
                    `:p+=`
                    xCOffset = xC + ${I};

                    if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x+1}Ready == 0) {
                      xTexelC${x+1} = getX(batch, xR, xCOffset, d1);
                      if (xCOffset + 1 >= inDims[1]) {
                        xTexelC${x+1}.zw = vec2(0.0);
                      }
                      xTexelC${x+1}Ready = 1;
                    }

                    xC${x+1} = xTexelC${x+1};
                    `}}else x<d&&(a%2===1?(p+=`
                xCOffset = xC + 1 - strides[1];
                if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x}Ready == 0) {
                  xTexelC${x} = getX(batch, xR, xCOffset, d1);
                  // Need to manually clear unused channels in case
                  // we're reading from recycled texture.
                  if (xCOffset + 1 >= inDims[1]) {
                    xTexelC${x}.zw = vec2(0.0);
                  }
                  xTexelC${x}Ready = 1;
                }

                if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${x+1}Ready == 0) {
                  xTexelC${x+1} = getX(batch, xR, xC + 1, d1);
                  // Need to manually clear unused channels in case
                  // we're reading from recycled texture.
                  if (xC + 2 >= inDims[1]) {
                    xTexelC${x+1}.zw = vec2(0.0);
                  }
                  xTexelC${x+1}Ready = 1;
                }

                xC${x} = vec4(xTexelC${x}.zw, xTexelC${x+1}.zw);
              `,x+1<d&&(p+=`
                  final = vec4(0.0);
                  xCOffset = xC + 1 + strides[1];
                  if(xCOffset >= 0 && xCOffset < inDims[1]) {
                    final = getX(batch, xR, xCOffset, d1);
                  }
                  xC${x+1} = vec4(xTexelC${x+1}.xy, final.xy);
                `)):(p+=`
                if(xC >= 0 && xC < inDims[1] && xTexelC${x}Ready == 0) {
                  xTexelC${x} = getX(batch, xR, xC, d1);
                  if (xC + 1 >= inDims[1]) {
                    xTexelC${x}.zw = vec2(0.0);
                  }
                  xTexelC${x}Ready = 1;
                }

                xCOffset = xC + strides[1];
                if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${x+1}Ready == 0) {
                  xTexelC${x+1} = getX(batch, xR, xCOffset, d1);
                  if (xCOffset + 1 >= inDims[1]) {
                    xTexelC${x+1}.zw = vec2(0.);
                  }
                  xTexelC${x+1}Ready = 1;
                }

                xC${x} = vec4(
                  xTexelC${x}.xy, xTexelC${x+1}.xy);
              `,x+1<d&&(p+=`
                  xC${x+1} = vec4(xTexelC${x}.zw, xTexelC${x+1}.zw);
                `)));x<d&&(p+=`
            wTexel = getW(r, ${x}, d1, q);
            dotProd += xC${x} * vec4(wTexel.xz, wTexel.xz);
          `,x+1<d&&(p+=`
              wTexel = getW(r, ${x+1}, d1, q);
              dotProd += xC${x+1} * vec4(wTexel.xz, wTexel.xz);
            `))}p+=`
    }
  `,p+=`
      }
    `;let f="",m="";s&&(o?f=`vec4 activation(vec4 a) {
          vec4 b = getPreluActivationWeightsAtOutCoords();
          ${s}
        }`:r?f=`vec4 activation(vec4 a) {
          vec4 b = getLeakyreluAlphaAtOutCoords();
          ${s}
        }`:f=`vec4 activation(vec4 x) {
          ${s}
        }`,m="result = activation(result);");const g=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
      ${f}

      void main() {
        ivec4 coords = getOutputCoords();
        int batch = coords.x;
        ivec2 xRCCorner = coords.yz * strides - pads;
        int d2 = coords.w;
        int d1 = d2 / ${i};
        int q = d2 - d1 * ${i};
        int xRCorner = xRCCorner.x;
        int xCCorner = xRCCorner.y;

        //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
        vec4 dotProd = vec4(0.000000000000001);

        ${p}

        vec4 result = dotProd - vec4(0.000000000000001);
        ${g}
        ${m}
        setOutput(result);
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function ZP(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,filter:r}=t,{strides:i,pad:a,dilations:c,dimRoundingMode:l}=s;let u=c;u==null&&(u=[1,1]),v(Te(i,u),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);const d=ye(o.shape,r.shape,i,u,a,l,!0);let h;z().getBool("WEBGL_PACK_DEPTHWISECONV")&&d.strideWidth<=2&&d.outChannels/d.inChannels===1?h=new rI(d):h=new oI(d);const p=[[d.padInfo.top,d.padInfo.left],[d.strideHeight,d.strideWidth],[d.dilationHeight,d.dilationWidth],[d.inHeight,d.inWidth]];return e.runWebGLProgram(h,[o,r],"float32",p)}const BP={kernelName:Ea,backendName:"webgl",kernelFunc:ZP};/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class HP{constructor(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;const e=t.strideHeight,s=t.strideWidth,o=t.padInfo.top,r=t.padInfo.left,i=t.outChannels/t.inChannels;this.userCode=`
      void main() {
        ivec4 coords = getOutputCoords();
        int wR = coords.x;
        int wC = coords.y;
        int d1 = coords.z;
        int dm = coords.w;
        int d2 = d1 * ${i} + dm;

        float dotProd = 0.0;

        // TO DO: Vec4 over the batch size
        for (int b = 0; b < ${t.batchSize}; b++) {
          for (int yR = 0; yR < ${t.outHeight}; yR++) {
            int xR = wR + yR * ${e} - ${o};

            if (xR < 0 || xR >= ${t.inHeight}) {
              continue;
            }

            for (int yC = 0; yC < ${t.outWidth}; yC++) {
              int xC = wC + yC * ${s} - ${r};

              if (xC < 0 || xC >= ${t.inWidth}) {
                continue;
              }

              float dyValue = getDy(b, yR, yC, d2);
              float xValue = getX(b, xR, xC, d1);
              dotProd += (xValue * dyValue);
            }
          }
        }
        setOutput(dotProd);
      }
    `}}class _P{constructor(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;const e=t.filterHeight,s=t.filterWidth,o=t.strideHeight,r=t.strideWidth,i=e-1-t.padInfo.top,a=s-1-t.padInfo.left,c=t.outChannels/t.inChannels;this.userCode=`
      const ivec2 pads = ivec2(${i}, ${a});

      void main() {
        ivec4 coords = getOutputCoords();
        int batch = coords[0];
        int d1 = coords[3];
        ivec2 dyCorner = coords.yz - pads;
        int dyRCorner = dyCorner.x;
        int dyCCorner = dyCorner.y;

        float dotProd = 0.0;

        for (int wR = 0; wR < ${e}; wR++) {
          float dyR = float(dyRCorner + wR) / ${o}.0;

          if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {
            continue;
          }
          int idyR = int(dyR);

          int wRPerm = ${e} - 1 - wR;

          for (int wC = 0; wC < ${s}; wC++) {
            float dyC = float(dyCCorner + wC) / ${r}.0;

            if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
                fract(dyC) > 0.0) {
              continue;
            }
            int idyC = int(dyC);

            int wCPerm = ${s} - 1 - wC;

            // TO DO: Vec4 over the channelMul
            for (int dm = 0; dm < ${c}; dm++) {
              int d2 = d1 * ${c} + dm;
              float xValue = getDy(batch, idyR, idyC, d2);
              float wValue = getW(wRPerm, wCPerm, d1, dm);
              dotProd += xValue * wValue;
            }
          }
        }
        setOutput(dotProd);
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function UP(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,dy:r}=t,{strides:i,dilations:a,pad:c,dimRoundingMode:l,filterShape:u}=s,d=ye(o.shape,u,i,a,c,l,!0),h=new HP(d);return e.runWebGLProgram(h,[o,r],"float32")}const YP={kernelName:bu,backendName:"webgl",kernelFunc:UP};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function QP(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,filter:r}=t,{strides:i,dilations:a,pad:c,dimRoundingMode:l,inputShape:u}=s,d=ye(u,r.shape,i,a,c,l,!0),h=new _P(d);return e.runWebGLProgram(h,[o,r],"float32")}const JP={kernelName:xu,backendName:"webgl",kernelFunc:QP};/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class jP{constructor(t){this.variableNames=["X"],this.outputShape=[t,t],this.userCode=`
      void main() {
          ivec2 coords = getOutputCoords();
          float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
          setOutput(val);
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function qP(n){const{inputs:t,backend:e}=n,{x:s}=t,o=[...s.shape,...s.shape],r=Z(s.shape),i=tt({inputs:{x:s},backend:e,attrs:{shape:[r]}}),a=new jP(r),c=e.runWebGLProgram(a,[i],i.dtype),l=tt({inputs:{x:c},backend:e,attrs:{shape:o}});return e.disposeIntermediateTensorInfo(i),e.disposeIntermediateTensorInfo(c),l}const tO={kernelName:yf,backendName:"webgl",kernelFunc:qP};/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class eO{constructor(t){this.variableNames=["x","W"],this.outputShape=t.outShape;const{inHeight:e,inWidth:s,padInfo:o,strideHeight:r,strideWidth:i,filterHeight:a,filterWidth:c,dilationHeight:l,dilationWidth:u}=t,{top:d,left:h}=o;this.userCode=`
      const ivec2 strides = ivec2(${r}, ${i});
      const ivec2 pads = ivec2(${d}, ${h});
      const float neg_infinity = -3.4e38;

      void main() {
        ivec4 coords = getOutputCoords();
        int batch = coords.x;
        int d1 = coords.w;
        ivec2 outTopLeftCorner =
            coords.yz * strides - pads;
        int hBeg = outTopLeftCorner.x;
        int wBeg = outTopLeftCorner.y;

        float curVal = neg_infinity;
        for (int h = 0; h < ${a}; h++) {
          int hIn = hBeg + h * ${l};

          if (hIn >= 0 && hIn < ${e}) {
            for (int w = 0; w < ${c}; w++) {
              int wIn = wBeg + w * ${u};

              if (wIn >= 0 && wIn < ${s}) {
                float xVal = getX(batch, hIn, wIn, d1);
                float wVal = getW(h, w, d1);

                float val = xVal + wVal;
                if (val > curVal) {
                  curVal = val;
                }
              }
            }
          }
        }

        float result = curVal;
        setOutput(result);
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function nO(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,filter:r}=t,{strides:i,pad:a,dilations:c}=s,l=Si(o.shape,r.shape,i,a,"NHWC",c);let u;const d=new eO(l);u=e.runWebGLProgram(d,[o,r],"float32");const h=tt({inputs:{x:u},backend:e,attrs:{shape:l.outShape}});return e.disposeIntermediateTensorInfo(u),h}const sO={kernelName:Da,backendName:"webgl",kernelFunc:nO};/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function oO(n){const{inputs:t,backend:e,attrs:s}=n,{equation:o}=s,r=t,{allDims:i,summedDims:a,idDims:c}=bh(o,r.length);yh(i.length,c,r);const{path:l,steps:u}=Ih(a,c),d=u.length;let h=null,p=i.length;const f=[];for(let m=0;m<d;++m){for(const g of u[m]){const{permutationIndices:b,expandDims:x}=xh(p,c[g]);let I;wh(b)?I=r[g]:(I=Me({inputs:{x:r[g]},backend:e,attrs:{perm:b}}),f.push(I));const y=I.shape.slice();for(let w=0;w<x.length;++w)y.splice(x[w],0,1);Rt(I.shape,y)||(I=tt({inputs:{x:I},backend:e,attrs:{shape:y}}),f.push(I)),h===null?h=I:(h=Ep({inputs:{a:I,b:h},backend:e}),f.push(h))}m<d-1&&(l[m]>=0&&(h=Gl({inputs:{x:h},backend:e,attrs:{axis:l[m]-(i.length-p),keepDims:!1}}),f.push(h)),p--)}for(const m of f)m!==h&&e.disposeIntermediateTensorInfo(m);return h}const rO={kernelName:wu,backendName:"webgl",kernelFunc:oO};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const iO=Tt({opSnippet:"return (x >= 0.0) ? x : (exp(x) - 1.0);",packedOpSnippet:`
  vec4 result;

  result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
  result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
  result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
  result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);

  return result;
`}),aO={kernelName:Vr,backendName:"webgl",kernelFunc:iO};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const cO="return (b >= 0.0) ? a : a * (b + 1.0);",lO=`
  vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
  return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
`,uO={kernelName:Cu,backendName:"webgl",kernelFunc:n=>{const{inputs:t,backend:e}=n,{dy:s,y:o}=t,r=z().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new gr(lO,s.shape,o.shape):new ko(cO,s.shape,o.shape);return e.runWebGLProgram(r,[s,o],s.dtype)}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const dO=Ce({opSnippet:"return float(a == b);",packedOpSnippet:`
  return vec4(equal(a, b));
`,dtype:"bool",cpuKernelImpl:qF}),hO={kernelName:Wa,backendName:"webgl",kernelFunc:dO};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const pO=`
  // Error function is calculated approximately with elementary function.
  // See "Handbook of Mathematical Functions with Formulas,
  // Graphs, and Mathematical Tables", Abramowitz and Stegun.
  float p = ${lh};
  float a1 = ${uh};
  float a2 = ${dh};
  float a3 = ${hh};
  float a4 = ${ph};
  float a5 = ${fh};

  float sign = sign(x);
  x = abs(x);
  float t = 1.0 / (1.0 + p * x);
  return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));
`,fO=Tt({opSnippet:pO}),mO={kernelName:Fr,backendName:"webgl",kernelFunc:fO};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const gO=br+`
  return exp(x);
`,iI=Tt({opSnippet:gO,packedOpSnippet:`
  vec4 result = exp(x);
  bvec4 isNaN = isnan(x);
  result.r = isNaN.r ? x.r : result.r;
  result.g = isNaN.g ? x.g : result.g;
  result.b = isNaN.b ? x.b : result.b;
  result.a = isNaN.a ? x.a : result.a;

  return result;
`,cpuKernelImpl:tz,dtype:"float32"}),bO={kernelName:zr,backendName:"webgl",kernelFunc:iI};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Vp(n){const{inputs:t,attrs:e,backend:s}=n,{dim:o}=e,{input:r}=t,i=r.shape.length,a=r.shape.slice();let c=o;return o<0&&(v(-(i+1)<=o,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),c=i+o+1),a.splice(c,0,1),tt({inputs:{x:r},backend:s,attrs:{shape:a}})}const xO={kernelName:Ma,backendName:"webgl",kernelFunc:Vp};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const aI="return exp(x) - 1.0;",yO=Tt({opSnippet:aI,packedOpSnippet:aI,cpuKernelImpl:ez}),IO={kernelName:Xr,backendName:"webgl",kernelFunc:yO};/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class cI{constructor(t,e,s){this.variableNames=["real","imag"];const o=e[1];this.outputShape=e;const r=s?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,i=s?`${o}.0`:"1.0";let a;if(t==="real")a="return real * expR - imag * expI;";else if(t==="imag")a="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${t}.`);this.userCode=`
      const float exponentMultiplier = ${r};

      float unaryOpComplex(float real, float expR, float imag, float expI) {
        ${a}
      }

      float mulMatDFT(int batch, int index) {
        float indexRatio = float(index) / float(${o});
        float exponentMultiplierTimesIndexRatio =
            exponentMultiplier * indexRatio;

        float result = 0.0;

        for (int i = 0; i < ${o}; i++) {
          // x = (-2|2 * PI / N) * index * i;
          float x = exponentMultiplierTimesIndexRatio * float(i);
          float expR = cos(x);
          float expI = sin(x);
          float real = getReal(batch, i);
          float imag = getImag(batch, i);

          result +=
              unaryOpComplex(real, expR, imag, expI) / ${i};
        }

        return result;
      }

      void main() {
        ivec2 coords = getOutputCoords();
        setOutput(mulMatDFT(coords[0], coords[1]));
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function lI(n,t,e){const s=e.texData.get(n.dataId),o=Z(n.shape),r=n.shape[n.shape.length-1],i=o/r,a=tt({inputs:{x:n},backend:e,attrs:{shape:[i,r]}}),c=a.shape,l=new cI("real",c,t),u=new cI("imag",c,t),d=[{dataId:s.complexTensorInfos.real.dataId,dtype:s.complexTensorInfos.real.dtype,shape:c},{dataId:s.complexTensorInfos.imag.dataId,dtype:s.complexTensorInfos.imag.dtype,shape:c}],h=e.runWebGLProgram(l,d,"float32"),p=e.runWebGLProgram(u,d,"float32"),f=zs({inputs:{real:h,imag:p},backend:e});e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(p);const m=tt({inputs:{x:f},backend:e,attrs:{shape:n.shape}});return e.disposeIntermediateTensorInfo(a),e.disposeIntermediateTensorInfo(f),m}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function wO(n){const{inputs:t,backend:e}=n,{input:s}=t;return lI(s,!1,e)}const CO={kernelName:vu,backendName:"webgl",kernelFunc:wO};/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class vO{constructor(t,e){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=t,this.userCode=`
      void main() {
        // Input can be obtained from uniform value.
        setOutput(value);
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function ha(n){const{backend:t,attrs:e}=n,{shape:s,value:o}=e;let{dtype:r}=e;if(r=r||Mo(o),r==="string"){const i=qt(r,Z(s));return i.fill(o),t.makeTensorInfo(s,r,i)}else{const i=new vO(s,o),a=[[o]];return t.runWebGLProgram(i,[],r,a)}}const SO={kernelName:Su,backendName:"webgl",kernelFunc:ha};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class kO{constructor(t){this.variableNames=["Image"],this.outputShape=[];const e=t[2];this.outputShape=t,this.userCode=`
        void main() {
          ivec4 coords = getOutputCoords();
          int x = coords[2];

          int coordX = ${e} - x - 1;
          float outputValue;
          if(coordX >= 0 && coordX < ${e}) {
            outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
          } else {
            outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
          }
          setOutput(outputValue);
        }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const TO={kernelName:ku,backendName:"webgl",kernelFunc:({inputs:n,backend:t})=>{const{image:e}=n,s=t,o=new kO(e.shape);return s.runWebGLProgram(o,[e],e.dtype)}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const uI="return floor(x);",NO=Tt({opSnippet:uI,packedOpSnippet:uI,cpuKernelImpl:nz}),RO={kernelName:Ar,backendName:"webgl",kernelFunc:NO};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const $O=Ce({opSnippet:`
  float s = sign(a) * sign(b);
  int ia = round(a);
  int ib = round(b);
  if (ib != 0) {
    // Windows (D3D) wants guaranteed non-zero int division at compile-time.
    return float(idiv(ia, ib, s));
  } else {
    return NAN;
  }
`,packedOpSnippet:`
  ivec4 ia = round(a);
  ivec4 ib = round(b);
  bvec4 cond = notEqual(ib, ivec4(0));
  ivec4 result = ivec4(0);
  vec4 s = sign(a) * sign(b);

  // Windows (D3D) wants guaranteed non-zero int division at compile-time.
  if (cond[0]) {
    result[0] = idiv(ia[0], ib[0], s[0]);
  }
  if (cond[1]) {
    result[1] = idiv(ia[1], ib[1], s[1]);
  }
  if (cond[2]) {
    result[2] = idiv(ia[2], ib[2], s[2]);
  }
  if (cond[3]) {
    result[3] = idiv(ia[3], ib[3], s[3]);
  }
  return vec4(result);
`,dtype:"int32"}),GO={kernelName:Pr,backendName:"webgl",kernelFunc:$O};/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class LO{constructor(t){this.variableNames=["A"];const e=De(),[s,o]=t;this.outputShape=t,this.userCode=`
      void main() {
        ivec3 coords = getOutputCoords();
        int texR = coords[0];
        int texC = coords[1];
        int depth = coords[2];
        vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${o}.0, ${s}.0);

        vec4 values = ${e.texture2D}(A, uv);
        float value;
        if (depth == 0) {
          value = values.r;
        } else if (depth == 1) {
          value = values.g;
        } else if (depth == 2) {
          value = values.b;
        } else if (depth == 3) {
          value = values.a;
        }

        setOutput(floor(value * 255.0 + 0.5));
      }
    `}}/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class EO{constructor(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const e=De(),[s,o]=t;this.outputShape=t,this.userCode=`
      void main() {
        ivec3 coords = getOutputCoords();
        int texR = coords[0];
        int texC = coords[1];
        int depth = coords[2];

        vec4 result = vec4(0.);

        for(int row=0; row<=1; row++) {
          for(int col=0; col<=1; col++) {
            texC = coords[1] + row;
            depth = coords[2] + col;

            vec2 uv = (vec2(texC, texR) + halfCR) /
                       vec2(${o}.0, ${s}.0);
            vec4 values = ${e.texture2D}(A, uv);
            float value;
            if (depth == 0) {
              value = values.r;
            } else if (depth == 1) {
              value = values.g;
            } else if (depth == 2) {
              value = values.b;
            } else if (depth == 3) {
              value = values.a;
            }

            result[row * 2 + col] = floor(value * 255.0 + 0.5);
          }
        }

        ${e.output} = result;
      }
    `}}/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const DO={kernelName:Zu,backendName:"webgl",kernelFunc:WO};let yr,Fp=z().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");function WO(n){const{inputs:t,backend:e,attrs:s}=n;let{pixels:o}=t;const{numChannels:r}=s,i=typeof HTMLVideoElement<"u"&&o instanceof HTMLVideoElement,a=typeof HTMLImageElement<"u"&&o instanceof HTMLImageElement,[c,l]=i?[o.videoWidth,o.videoHeight]:[o.width,o.height],u=[l,c],d=[l,c,r];if(a||i){const m=z().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");(yr==null||m!==Fp)&&(Fp=m,yr=document.createElement("canvas").getContext("2d",{willReadFrequently:Fp})),yr.canvas.width=c,yr.canvas.height=l,yr.drawImage(o,0,0,c,l),o=yr.canvas}const h=e.makeTensorInfo(u,"int32");e.texData.get(h.dataId).usage=an.PIXELS,e.gpgpu.uploadPixelDataToTexture(e.getTexture(h.dataId),o);const p=z().getBool("WEBGL_PACK")?new EO(d):new LO(d),f=e.runWebGLProgram(p,[h],"int32");return e.disposeData(h.dataId),f}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function MO(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,filter:r,bias:i,preluActivationWeights:a}=t,{strides:c,pad:l,dataFormat:u,dilations:d,dimRoundingMode:h,activation:p,leakyreluAlpha:f}=s,m=os(u),g=ye(o.shape,r.shape,c,d,l,h,!1,m);let b;const x=[],I=i!=null,y=a!=null,w=p==="leakyrelu",C=()=>{const S=[o,r],T=(R,L)=>{if(L==="NCHW"&&R.shape.length===1&&R.shape[0]!==1){const V=tt({inputs:{x:R},backend:e,attrs:{shape:[R.shape[0],1,1]}});return x.push(V),V}return R};if(I&&S.push(T(i,u)),y&&S.push(T(a,u)),w){const R=e.makeTensorInfo([],"float32",gs(f,"float32"));S.push(R),x.push(R)}return S};if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))b=j1({x:o,filter:r,convInfo:g,backend:e,bias:i,activation:p,preluActivationWeights:a,leakyreluAlpha:f});else if(g.strideWidth<=2&&m==="channelsLast"&&z().getBool("WEBGL_EXP_CONV")){const S=p?aa(p,!0):null,T=new J1(g,I,S,y,w),R=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],L=C();b=e.runWebGLProgram(T,L,"float32",R)}else if(z().getBool("WEBGL_CONV_IM2COL"))b=q1({x:o,filter:r,convInfo:g,backend:e,bias:i,activation:p,preluActivationWeights:a,leakyreluAlpha:f});else{const S=p?aa(p,!1):null,T=new Q1(g,I,S,y,w),R=C();b=e.runWebGLProgram(T,R,"float32")}const k=tt({inputs:{x:b},backend:e,attrs:{shape:g.outShape}});return x.push(b),x.forEach(S=>e.disposeIntermediateTensorInfo(S)),k}const VO={kernelName:Ic,backendName:"webgl",kernelFunc:MO};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function FO(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,filter:r,bias:i,preluActivationWeights:a}=t,{strides:c,pad:l,dilations:u,dimRoundingMode:d,activation:h,leakyreluAlpha:p}=s,f=[];let m=u;m==null&&(m=[1,1]),v(Te(c,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${c} and dilations '${m}'`);const g=ye(o.shape,r.shape,c,m,l,d,!0),b=z().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels===1,x=h?aa(h,b):null,I=[o,r],y=i!=null,w=a!=null,C=h==="leakyrelu";if(y&&I.push(i),w&&I.push(a),C){const R=e.makeTensorInfo([],"float32",gs(p,"float32"));I.push(R),f.push(R)}let k;b?k=new rI(g,y,x,w,C):k=new oI(g,y,x,w,C);const S=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],T=e.runWebGLProgram(k,I,"float32",S);return f.forEach(R=>e.disposeIntermediateTensorInfo(R)),T}const zO={kernelName:zf,backendName:"webgl",kernelFunc:FO};class XO{constructor(t,e,s,o){this.sliceDim=t,this.strides=e,this.paramsShape=o,this.variableNames=["x","indices"],this.outputShape=s;const r=Wt(s.length);let i=`
    int index;`;for(let a=0;a<this.sliceDim;a++)i+=`
          index = round(getIndices(coords[0], ${a}));
          out_of_bounds = out_of_bounds || index < 0;
          out_of_bounds = out_of_bounds || index >= ${this.paramsShape[a]};
          flattenIndex += index * ${this.strides[a]};`;this.userCode=`
         void main() {
          ${r} coords = getOutputCoords();
          int flattenIndex = 0;
          bool out_of_bounds = false;

          ${i}

          setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1]));
        }
      `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function AO(n){const{inputs:t,backend:e}=n,{params:s,indices:o}=t,r=o.shape,i=r[r.length-1],a=Z(s.shape),[c,l,u,d]=Jd(s,o),h=tt({inputs:{x:o},backend:e,attrs:{shape:[l,i]}}),p=tt({inputs:{x:s},backend:e,attrs:{shape:[Z(s.shape)/u,u]}});if(e.shouldExecuteOnCPU([s,o])||s.dtype==="string"){const b=e.readSync(o.dataId),x=e.bufferSync(s),I=sz(b,x,s.dtype,l,i,u,d,s.shape,a);return e.makeTensorInfo(c,s.dtype,I.values)}const f=new XO(i,d,[l,u],s.shape),m=e.runWebGLProgram(f,[p,h],p.dtype),g=tt({inputs:{x:m},backend:e,attrs:{shape:c}});return e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(m),g}const PO={kernelName:If,backendName:"webgl",kernelFunc:AO};/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class OO{constructor(t,e){this.variableNames=["A","indices"],this.outputShape=e,this.rank=e.length;const s=Wt(this.rank),o=KO(t);this.userCode=`
      void main() {
        ${s} resRC = getOutputCoords();
        int index = int(getIndices(resRC.x, resRC.z));
        float inBounds = (index >= 0) && (index < ${t[2]}) ? 1.0 : 0.0;
        setOutput(inBounds * getA(${o}));
      }
    `}}function KO(n,t){const e=["resRC.x","resRC.y","resRC.z","resRC.w"],s=[];for(let o=0;o<n.length;o++)o===2?s.push("index"):s.push(`${e[o]}`);return s.join()}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function dI(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,indices:r}=t,{axis:i,batchDims:a}=s,c=It(i,o.shape)[0];if(z().get("DEBUG")){const x=e.readSync(r.dataId),I=o.shape[c];for(let y=0;y<x.length;++y){const w=x[y];v(w<=I-1&&w>=0,()=>`GatherV2: the index value ${w} is not in [0, ${I-1}]`)}}const l=Sh(o,r,c,a),u=Z(r.shape),d=[],h=tt({inputs:{x:o},backend:e,attrs:{shape:[l.batchSize,l.outerSize,l.dimSize,l.sliceSize]}}),p=tt({inputs:{x:r},backend:e,attrs:{shape:[l.batchSize,u/l.batchSize]}});d.push(h),d.push(p);const f=[l.batchSize,l.outerSize,u/l.batchSize,l.sliceSize];if(e.shouldExecuteOnCPU([o,r])||o.dtype==="string"){const x=e.bufferSync(p),I=e.bufferSync(h),y=oz(I,x,f);return d.forEach(w=>e.disposeIntermediateTensorInfo(w)),e.makeTensorInfo(l.outputShape,y.dtype,y.values)}const m=new OO(h.shape,f),g=e.runWebGLProgram(m,[h,p],h.dtype);d.push(g);const b=tt({inputs:{x:g},backend:e,attrs:{shape:l.outputShape}});return d.forEach(x=>e.disposeIntermediateTensorInfo(x)),b}const ZO={kernelName:Fa,backendName:"webgl",kernelFunc:dI};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const BO=Ce({opSnippet:"return float(a > b);",packedOpSnippet:`
  return vec4(greaterThan(a, b));
`,cpuKernelImpl:rz,dtype:"bool"}),HO={kernelName:za,backendName:"webgl",kernelFunc:BO};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const _O=Ce({opSnippet:"return float(a >= b);",packedOpSnippet:`
  return vec4(greaterThanEqual(a, b));
`,dtype:"bool",cpuKernelImpl:iz}),UO={kernelName:Or,backendName:"webgl",kernelFunc:_O};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function YO(n){const{inputs:t,backend:e}=n,{input:s}=t;return lI(s,!0,e)}const QO={kernelName:Tu,backendName:"webgl",kernelFunc:YO};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const JO=Tt({opSnippet:"return float(!isnan(x) && !isinf(x));",dtype:"bool"}),jO={kernelName:Zr,backendName:"webgl",kernelFunc:JO};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const qO=Tt({opSnippet:"return float(isinf(x));",dtype:"bool"}),tK={kernelName:Br,backendName:"webgl",kernelFunc:qO};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const eK=Tt({opSnippet:"return float(isnan(x));",dtype:"bool"}),nK={kernelName:Hr,backendName:"webgl",kernelFunc:eK};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const sK=Ce({opSnippet:"return float(a < b);",packedOpSnippet:`
  return vec4(lessThan(a, b));
`,cpuKernelImpl:az,dtype:"bool"}),oK={kernelName:Aa,backendName:"webgl",kernelFunc:sK};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const rK=Ce({opSnippet:"return float(a <= b);",packedOpSnippet:`
  return vec4(lessThanEqual(a, b));
`,cpuKernelImpl:cz,dtype:"bool"}),iK={kernelName:Pa,backendName:"webgl",kernelFunc:rK};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function aK(n){const{backend:t,attrs:e}=n,{start:s,stop:o,num:r}=e,i=lz(s,o,r);return t.makeTensorInfo([i.length],"float32",i)}const cK={kernelName:wf,backendName:"webgl",kernelFunc:aK};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const lK=br+`
  return x < 0.0 ? 0./0. : log(x);
`,uK=Tt({opSnippet:lK,packedOpSnippet:`
  vec4 result = log(x);
  bvec4 isNaN = isnan(x);
  result.r = isNaN.r ? x.r : (x.r < 0.0 ? 0./0. : result.r);
  result.g = isNaN.g ? x.g : (x.g < 0.0 ? 0./0. : result.g);
  result.b = isNaN.b ? x.b : (x.b < 0.0 ? 0./0. : result.b);
  result.a = isNaN.a ? x.a : (x.a < 0.0 ? 0./0. : result.a);
  return result;
`,cpuKernelImpl:uz}),dK={kernelName:_r,backendName:"webgl",kernelFunc:uK};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const hK=br+`
  return log(1.0 + x);
`,pK=Tt({opSnippet:hK}),fK={kernelName:Ur,backendName:"webgl",kernelFunc:pK};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const mK=Ce({opSnippet:"return float(a >= 1.0 && b >= 1.0);",packedOpSnippet:`
  return vec4(
    vec4(greaterThanEqual(a, vec4(1.0))) *
    vec4(greaterThanEqual(b, vec4(1.0))));
`,dtype:"bool"}),gK={kernelName:Oa,backendName:"webgl",kernelFunc:mK};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const bK=Tt({opSnippet:"return float(!(x >= 1.0));"}),xK={kernelName:Ka,backendName:"webgl",kernelFunc:bK};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const yK=Ce({opSnippet:"return float(a >= 1.0 || b >= 1.0);",packedOpSnippet:`
  return min(
    vec4(greaterThanEqual(a, vec4(1.0))) +
    vec4(greaterThanEqual(b, vec4(1.0))),
    vec4(1.0));
`,dtype:"bool"}),IK={kernelName:Za,backendName:"webgl",kernelFunc:yK};/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class wK{constructor(t,e,s,o,r){this.variableNames=["x"],this.outputShape=[];const i=e,a=t[3]-1;this.outputShape=t;let c;const l=`float(${s}) + float(${o}) * sum`;r===.5?c=`inversesqrt(${l})`:r===1?c=`1.0/(${l})`:c=`exp(log(${l}) * float(-${r}));`,this.userCode=`
      void main() {
        ivec4 coords = getOutputCoords();
        int b = coords[0];
        int r = coords[1];
        int c = coords[2];
        int d = coords[3];
        float x = getX(b, r, c, d);
        float sum = 0.0;
        for (int j = -${i}; j <= ${i}; j++) {
          int idx = d + j;
          if (idx >= 0 && idx <=  ${a}) {
            float z = getX(b, r, c, idx);
            sum += z * z;
          }
        }
        float val = x * ${c};
        setOutput(val);
      }
    `}}/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class CK{constructor(t,e,s,o,r){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;const i=e,a=t[3]-1;this.outputShape=t;let c;const l=`float(${s}) + float(${o}) * sum`;r===.5?c=`inversesqrt(${l})`:r===1?c=`1.0/(${l})`:c=`exp(log(${l}) * float(-${r}));`,this.userCode=`
      void main() {
        ivec4 coords = getOutputCoords();
        int b = coords.x;
        int r = coords.y;
        int c = coords.z;
        int d = coords.w;

        bool hasNextCol = d < ${this.outputShape[3]};
        bool hasNextRow = c < ${this.outputShape[2]};

        vec4 sum = vec4(0.);
        vec4 xFragAtOutputCoords = getX(b, r, c, d);

        vec4 xAtOutputCoords = vec4(
          getChannel(xFragAtOutputCoords, vec2(c, d)),
          hasNextCol ?
            getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
          hasNextRow ?
            getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
          (hasNextRow && hasNextCol) ?
            getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
        );

        int firstChannel = d - ${i};
        vec2 cache = vec2(0.);
        if(firstChannel >= 0){
          vec4 firstChannelFrag = getX(b, r, c, firstChannel);
          cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));
            if(hasNextRow){
              cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));
            }
        }

        ivec2 depth = ivec2(d, d + 1);
        for (int j = - ${i}; j <= ${i}; j++) {
          ivec2 idx = depth + j;
          bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
          bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${a}));

          bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
          bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;

          if(depthInRange || depthPlusOneInRange){
            vec4 z = vec4(0.);
            vec4 xFragAtCurrentDepth;
            z.xz = cache.xy;
            if(depthPlusOneInRange && hasNextCol){
              xFragAtCurrentDepth = idx.y != d ?
                getX(b, r, c, idx.y) : xFragAtOutputCoords;
              z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
              if(hasNextRow){
                z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
              }
            }
            cache.xy = z.yw;
            sum += z * z;
          }
        }
        vec4 result = xAtOutputCoords * ${c};
        setOutput(result);
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const vK={kernelName:Ba,backendName:"webgl",kernelFunc:n=>{const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{depthRadius:r,bias:i,alpha:a,beta:c}=s,l=z().getBool("WEBGL_PACK_NORMALIZATION")?new CK(o.shape,r,i,a,c):new wK(o.shape,r,i,a,c);return e.runWebGLProgram(l,[o],o.dtype)}};/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class SK{constructor(t,e,s,o,r){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=s,this.alpha=o,this.beta=r,this.userCode=`
      void main() {
        ivec4 coords = getOutputCoords();
        int b = coords[0];
        int r = coords[1];
        int c = coords[2];

        float result = 0.0;
        for (int d = 0; d < ${this.depth}; ++d) {
          int depthBegin = int(max(0.0, float(d - ${e})));
          int depthEnd = int(min(float(${this.depth}),
              float(d + ${e} + 1)));

          const int MIN_DEPTH_BEGIN = 0;
          const int MAX_DEPTH_END = ${this.depth};

          float norm = 0.0;
          for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {
            if (k < depthBegin){
              continue;
            }
            else if (k >= depthBegin && k < depthEnd) {
              norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
            }
            else {
              break;
            }
          }

          norm = float(${o}) * norm + float(${s});

          for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
            if (k < depthBegin){
              continue;
            }
            else if (k >= depthBegin && k < depthEnd){
              float dyi = -2.0 * float(${o})
                * float(${r})
                * getInputImage(b, r, c, k) * getOutputImage(b, r, c, d)
                / norm;
              if (k == d) {
                dyi += pow(norm, -1.0 * ${r});
              }
              if (k == coords[3]) {
                dyi *= getDy(b, r, c, d);
                result += dyi;
              }
            }
            else {
              break;
            }
          }
      }
      setOutput(result);
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const kK={kernelName:Ru,backendName:"webgl",kernelFunc:n=>{const{inputs:t,backend:e,attrs:s}=n,{x:o,y:r,dy:i}=t,{depthRadius:a,bias:c,alpha:l,beta:u}=s,d=new SK(o.shape,a,c,l,u);return e.runWebGLProgram(d,[o,r,i],o.dtype)}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function TK(n,t,e,s){const o=Z(t),i=Z(n.shape)/o,a=tt({inputs:{x:n},attrs:{shape:[i,o]},backend:s}),c=No(a,n.dtype,"max",s),l=tt({inputs:{x:c},attrs:{shape:e},backend:s});return s.disposeIntermediateTensorInfo(a),s.disposeIntermediateTensorInfo(c),l}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function hI(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{reductionIndices:r,keepDims:i}=s,a=o.shape.length,c=It(r,o.shape);let l=c;const u=Yt(l,a),d=u!=null,h=e.shouldExecuteOnCPU([o]);let p=o;if(d){if(h){const I=e.texData.get(p.dataId).values,y=new Array(a);for(let k=0;k<y.length;k++)y[k]=o.shape[u[k]];const w=Gp(I,o.shape,o.dtype,u,y);p=e.makeTensorInfo(y,o.dtype);const C=e.texData.get(p.dataId);C.values=w}else p=$l(o,u,e);l=ee(l.length,a)}Ie("max",l,a);const[f,m]=me(p.shape,l);let g=f;i&&(g=re(f,c));let b;if(h){const I=e.texData.get(p.dataId).values,y=dz(I,Z(m),g,o.dtype);b=e.makeTensorInfo(g,o.dtype);const w=e.texData.get(b.dataId);w.values=y}else b=TK(p,m,g,e);return d&&e.disposeIntermediateTensorInfo(p),b}const NK={kernelName:Ha,backendName:"webgl",kernelFunc:hI};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const RK=Lp+`
  return max(a, b);
`,$K=`
  vec4 result = vec4(max(a, b));
  bvec4 isNaNA = isnan(a);
  bvec4 isNaNB = isnan(b);
  bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
  `+To+`
  return result;
`,GK=Ce({opSnippet:RK,packedOpSnippet:$K,cpuKernelImpl:hz}),LK={kernelName:Yr,backendName:"webgl",kernelFunc:GK};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function EK(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t;ra(o,"maxPool");const{filterSize:r,strides:i,pad:a,dimRoundingMode:c}=s,l=1;v(Te(i,l),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${l}'`);const u=pn(o.shape,r,i,l,a,c);if(u.filterWidth===1&&u.filterHeight===1&&Rt(u.inShape,u.outShape))return Je({inputs:{x:o},backend:e});const d=new ca(u,"max",!1);return e.runWebGLProgram(d,[o],o.dtype)}const DK={kernelName:_a,backendName:"webgl",kernelFunc:EK};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function WK(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{filterSize:r,strides:i,pad:a,dataFormat:c,dimRoundingMode:l}=s,u=[1,1,1],d=ss(o.shape,r,i,u,a,l,c),h=new Dp(d,"max",!1);return e.runWebGLProgram(h,[o],o.dtype)}const MK={kernelName:Ua,backendName:"webgl",kernelFunc:WK};/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class VK{constructor(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;const e=t.strideHeight,s=t.strideWidth,o=t.dilationHeight,r=t.effectiveFilterHeight,i=t.effectiveFilterWidth,a=r-1-t.padInfo.top,c=i-1-t.padInfo.left,l=r*i-1;this.userCode=`
      const ivec2 pads = ivec2(${a}, ${c});

      void main() {
        ivec4 coords = getOutputCoords();
        int b = coords[0];
        int d = coords[3];

        ivec2 dyRCCorner = coords.yz - pads;
        int dyRCorner = dyRCCorner.x;
        int dyCCorner = dyRCCorner.y;

        // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
        // ? = to be determined. : = across all values in that axis.
        float dotProd = 0.0;
        for (int wR = 0; wR < ${r};
          wR += ${o}) {
          float dyR = float(dyRCorner + wR) / ${e}.0;

          if (dyR < 0.0 || dyR >= ${t.outHeight}.0 || fract(dyR) > 0.0) {
            continue;
          }
          int idyR = int(dyR);

          for (int wC = 0; wC < ${i}; wC++) {
            float dyC = float(dyCCorner + wC) / ${s}.0;

            if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
                fract(dyC) > 0.0) {
              continue;
            }
            int idyC = int(dyC);

            float dyValue = getDy(b, idyR, idyC, d);
            int maxPosValue = ${l} - int(getMaxPos(b, idyR, idyC, d));

            // Get the current value, check it against the value from the
            // position matrix.
            int curPosValue = wR * ${i} + wC;
            float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);

            dotProd += dyValue * mask;
          }
        }
        setOutput(dotProd);
      }
    `}}class FK{constructor(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;const e=t.strideDepth,s=t.strideHeight,o=t.strideWidth,r=t.dilationDepth,i=t.dilationHeight,a=t.dilationWidth,c=t.effectiveFilterDepth,l=t.effectiveFilterHeight,u=t.effectiveFilterWidth,d=c-1-t.padInfo.front,h=l-1-t.padInfo.top,p=u-1-t.padInfo.left,f=c*l*u-1;this.userCode=`
      const ivec3 pads = ivec3(${d}, ${h}, ${p});

      void main() {
        ivec5 coords = getOutputCoords();
        int batch = coords.x;
        int ch = coords.u;

        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
        int dyDCorner = dyCorner.x;
        int dyRCorner = dyCorner.y;
        int dyCCorner = dyCorner.z;

        // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
        // dx(xD, xR, xC, ch).
        // ? = to be determined. : = across all values in that axis.
        float dotProd = 0.0;

        for (int wD = 0; wD < ${c};
           wD += ${r}) {
          float dyD = float(dyDCorner + wD) / ${e}.0;

          if (dyD < 0.0 || dyD >= ${t.outDepth}.0 || fract(dyD) > 0.0) {
            continue;
          }
          int idyD = int(dyD);

          for (int wR = 0; wR < ${l};
              wR += ${i}) {
            float dyR = float(dyRCorner + wR) / ${s}.0;

            if (dyR < 0.0 || dyR >= ${t.outHeight}.0 ||
                fract(dyR) > 0.0) {
              continue;
            }
            int idyR = int(dyR);

            for (int wC = 0; wC < ${u};
                wC += ${a}) {
              float dyC = float(dyCCorner + wC) / ${o}.0;

              if (dyC < 0.0 || dyC >= ${t.outWidth}.0 ||
                  fract(dyC) > 0.0) {
                continue;
              }
              int idyC = int(dyC);

              float dyValue = getDy(batch, idyD, idyR, idyC, ch);
              int maxPosValue = ${f} -
                  int(getMaxPos(batch, idyD, idyR, idyC, ch));

              // Get the current value, check it against the value from the
              // position matrix.
              int curPosValue =
                  wD * ${l} * ${u} +
                  wR * ${u} + wC;
              float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);

              dotProd += dyValue * mask;
            }
          }
        }
        setOutput(dotProd);
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function zK(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,input:r}=t,i=r,{filterSize:a,strides:c,pad:l,dimRoundingMode:u}=s,d=[1,1,1],h=ss(i.shape,a,c,d,l,u),p=new Dp(h,"max",!0),f=e.runWebGLProgram(p,[i],i.dtype),m=new FK(h),g=e.runWebGLProgram(m,[o,f],i.dtype);return e.disposeIntermediateTensorInfo(f),g}const XK={kernelName:Gu,backendName:"webgl",kernelFunc:zK};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function AK(n){const{inputs:t,backend:e,attrs:s}=n,{dy:o,input:r,output:i}=t,a=r;ra([r,i],"maxPoolGrad");const{filterSize:c,strides:l,pad:u,dimRoundingMode:d}=s,h=pn(a.shape,c,l,1,u,d),p=!0,f=new ca(h,"max",p),m=e.runWebGLProgram(f,[a],a.dtype),g=new VK(h),b=e.runWebGLProgram(g,[o,m],a.dtype);return e.disposeIntermediateTensorInfo(m),b}const PK={kernelName:$u,backendName:"webgl",kernelFunc:AK};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function OK(n,t,e,s){let o=new ca(e,"max",!1);const r=s.runWebGLProgram(o,[n],"float32");o=new ca(e,"max",!0,!0,t);const i=s.runWebGLProgram(o,[n],"float32");return[r,i]}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const KK={kernelName:Cf,backendName:"webgl",kernelFunc:({inputs:n,attrs:t,backend:e})=>{const{x:s}=n,{filterSize:o,strides:r,pad:i,includeBatchInIndex:a}=t,c=e;v(s.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${s.shape.length}.`);const l=[1,1];v(Te(r,l),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${r} and dilations '${l}'`);const u=pn(s.shape,o,r,l,i),[d,h]=OK(s,a,u,c);return[d,h]}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function ZK(n,t,e,s){const o=Z(t),i=Z(n.shape)/o,a=tt({inputs:{x:n},attrs:{shape:[i,o]},backend:s}),c=No(a,"float32","mean",s),l=tt({inputs:{x:c},attrs:{shape:e},backend:s});return s.disposeIntermediateTensorInfo(a),s.disposeIntermediateTensorInfo(c),l}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const BK={kernelName:Ya,backendName:"webgl",kernelFunc:({inputs:n,attrs:t,backend:e})=>{const{x:s}=n,{keepDims:o,axis:r}=t,i=e,a=s.shape.length,c=It(r,s.shape);let l=c;const u=Yt(l,a),d=u!=null,h=i.shouldExecuteOnCPU([s]),p=[];let f=s;if(d){if(h){const y=i.texData.get(f.dataId).values,w=new Array(a);for(let S=0;S<w.length;S++)w[S]=s.shape[u[S]];const C=Gp(y,s.shape,s.dtype,u,w);f=i.makeTensorInfo(w,s.dtype);const k=i.texData.get(f.dataId);k.values=C}else f=$l(s,u,i);p.push(f),l=ee(l.length,a)}Ie("sum",l,a);const[m,g]=me(f.shape,l);let b=m;o&&(b=re(m,c));const x=ZK(f,g,b,i);for(const I of p)i.disposeIntermediateTensorInfo(I);return x}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function HK(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r,keepDims:i}=s,a=o.shape.length,c=It(r,o.shape);let l=c;const u=Yt(l,a);let d=o;u!=null&&(d=Me({inputs:{x:o},backend:e,attrs:{perm:u}}),l=ee(l.length,o.shape.length)),Ie("min",l,a);const[h,p]=me(d.shape,l),f=Z(p),m=tt({inputs:{x:d},backend:e,attrs:{shape:[-1,f]}}),g=No(m,m.dtype,"min",e);let b;if(i){const x=re(h,c);b=tt({inputs:{x:g},backend:e,attrs:{shape:x}})}else b=tt({inputs:{x:g},backend:e,attrs:{shape:h}});return e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(g),u!=null&&e.disposeIntermediateTensorInfo(d),b}const _K={kernelName:Qa,backendName:"webgl",kernelFunc:HK};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const UK=Lp+`
  return min(a, b);
`,YK=`
  vec4 result = vec4(min(a, b));
  bvec4 isNaNA = isnan(a);
  bvec4 isNaNB = isnan(b);
  bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);
  `+To+`
  return result;
`,QK=Ce({opSnippet:UK,packedOpSnippet:YK,cpuKernelImpl:pz}),JK={kernelName:Qr,backendName:"webgl",kernelFunc:QK};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class jK{constructor(t,e,s){this.variableNames=["x"],this.outputShape=e.map((u,d)=>u[0]+t[d]+u[1]);const o=t.length,r=Wt(o),i=e.map(u=>u[0]).join(","),a=e.map((u,d)=>u[0]+t[d]).join(","),c=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,o),l=s==="reflect"?0:1;if(o===1){this.userCode=`
        int start = ${i};
        int end = ${a};

        void main() {
          int outC = getOutputCoords();
          if (outC < start) {
            outC = start * 2 - outC - ${l};
          } else if(outC >= end) {
            outC = (end - 1) * 2 - outC + ${l};
          }
          setOutput(getX(outC - start));
        }
      `;return}this.userCode=`
      ${r} start = ${r}(${i});
      ${r} end = ${r}(${a});

      void main() {
        ${r} outC = getOutputCoords();
        for (int i = 0; i < ${o}; i++) {
          if (outC[i] < start[i]) {
            outC[i] = start[i] * 2 - outC[i] - ${l};
          } else if(outC[i] >= end[i]) {
            outC[i] = (end[i] - 1) * 2 - outC[i] + ${l};
          }
        }
        ${r} coords = outC - start;
        setOutput(getX(${c}));
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class qK{constructor(t,e,s){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.map((f,m)=>f[0]+t[m]+f[1]);const o=t.length,r=Wt(o),i=e.map(f=>f[0]).join(","),a=e.map((f,m)=>f[0]+t[m]).join(","),c=We("rc",o),l=We("source",o),u=`${c[o-1]} < ${this.outputShape[o-1]}`,d=o===1?"source":`vec2(${l.slice(-2).join()})`,h=s==="reflect"?0:1;let p="";if(o===1){const f=`
        ${r} source = rc;
        if (source < start) {
          source = start * 2 - source - ${h};
        } else if (source >= end) {
          source = (end - 1) * 2 - source + ${h};
        }
        source -= start;
      `;p=`
        ${r} rc = outputLoc;
        ${f}
        result[0] = getChannel(getX(${l.join()}), ${d});
        ${c[o-1]} += 1;
        if(${u}) {
          ${f}
          result[1] = getChannel(getX(${l.join()}), ${d});
        }
      `}else{const f=`
        ${r} source = rc;
        ${r} lt = ${r}(lessThan(source, start));
        ${r} gte = ${r}(greaterThanEqual(source, end));
        ${r} orig = 1 - (lt + gte);
        source = orig * source +
                lt * (start * 2 - source - ${h}) +
                gte * ((end - 1) * 2 - source + ${h});
        source -= start;
      `;p=`
        ${r} rc = outputLoc;
        ${f}
        result[0] = getChannel(getX(${l.join()}), ${d});
        ${c[o-1]} += 1;
        if(${u}) {
          ${f}
          result[1] = getChannel(getX(${l.join()}), ${d});
        }
        rc = outputLoc;
        ${c[o-2]} += 1;
        if(${c[o-2]} < ${this.outputShape[o-2]}) {
          ${f}
          result[2] = getChannel(getX(${l.join()}), ${d});
          ${c[o-1]} += 1;
          if(${u}) {
            ${f}
            result[3] = getChannel(getX(${l.join()}), ${d});
          }
        }
      `}this.userCode=`
      const ${r} start = ${r}(${i});
      const ${r} end = ${r}(${a});

      void main() {
        ${r} outputLoc = getOutputCoords();
        vec4 result = vec4(0.);
        ${p}
        setOutput(result);
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const tZ={kernelName:Ja,backendName:"webgl",kernelFunc:({inputs:n,backend:t,attrs:e})=>{const{x:s}=n,{paddings:o,mode:r}=e,i=z().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new qK(s.shape,o,r):new jK(s.shape,o,r);return t.runWebGLProgram(i,[s],s.dtype)}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const eZ=`if (b == 0.0) return NAN;
  return mod(a, b);`,nZ=`
  vec4 result = mod(a, b);
  bvec4 isNaN = equal(b, vec4(0.0));
  `+To+`
  return result;
`,sZ=Ce({opSnippet:eZ,packedOpSnippet:nZ}),oZ={kernelName:Jr,backendName:"webgl",kernelFunc:sZ};/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class rZ{constructor(t,e,s){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[t,s],this.userCode=`
      void main() {
        ivec2 coords = getOutputCoords();
        int batch = coords[0];

        float r = random(seed);
        float cdf = 0.0;

        for (int i = 0; i < ${e-1}; i++) {
          cdf += getProbs(batch, i);

          if (r < cdf) {
            setOutput(float(i));
            return;
          }
        }

        // If no other event happened, last event happened.
        setOutput(float(${e-1}));
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const pI=Ce({opSnippet:`
if (a == b) {
  return 1.0;
};
return a / b;`,packedOpSnippet:`
  // vec4 one = vec4(equal(a, b));
  // return one + (vec4(1.0) - one) * a / b;
  vec4 result = a / b;
  if(a.x == b.x) {
    result.x = 1.;
  }
  if(a.y == b.y) {
    result.y = 1.;
  }
  if(a.z == b.z) {
    result.z = 1.;
  }
  if(a.w == b.w) {
    result.w = 1.;
  }

  return result;
`,checkOutOfBounds:!0}),iZ={kernelName:Mr,backendName:"webgl",kernelFunc:pI};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const fI="return a - b;",mI=Ce({opSnippet:fI,packedOpSnippet:fI,supportsComplex:!0,cpuKernelImpl:Wz}),aZ={kernelName:pi,backendName:"webgl",kernelFunc:mI};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function gI(n){const{inputs:t,backend:e,attrs:s}=n,{logits:o}=t,{dim:r}=s,i=It([r],o.shape),a=hI({inputs:{x:o},backend:e,attrs:{reductionIndices:i,keepDims:!1}}),c=re(a.shape,i),l=tt({inputs:{x:a},backend:e,attrs:{shape:c}}),u=mI({inputs:{a:o,b:l},backend:e}),d=iI({inputs:{x:u},backend:e}),h=Gl({inputs:{x:d},backend:e,attrs:{axis:i,keepDims:!1}}),p=tt({inputs:{x:h},backend:e,attrs:{shape:c}}),f=pI({inputs:{a:d,b:p},backend:e});return e.disposeIntermediateTensorInfo(a),e.disposeIntermediateTensorInfo(l),e.disposeIntermediateTensorInfo(u),e.disposeIntermediateTensorInfo(d),e.disposeIntermediateTensorInfo(h),e.disposeIntermediateTensorInfo(p),f}const cZ={kernelName:mc,backendName:"webgl",kernelFunc:gI};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function lZ(n){const{inputs:t,backend:e,attrs:s}=n,{logits:o}=t,{numSamples:r,seed:i,normalized:a}=s,c=a?o:gI({inputs:{logits:o},backend:e,attrs:{dim:o.shape.length-1}}),l=c.shape[0],u=c.shape[1],d=new rZ(l,u,r),h=[[i]],p=e.runWebGLProgram(d,[c],"int32",h);return a||e.disposeIntermediateTensorInfo(c),p}const uZ={kernelName:vf,backendName:"webgl",kernelFunc:lZ};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const dZ=Cn+`
  return -x;
`,hZ=`
  vec4 result = -x;
  bvec4 isNaN = isnan(x);

  result.r = isNaN.r ? x.r : result.r;
  result.g = isNaN.g ? x.g : result.g;
  result.b = isNaN.b ? x.b : result.b;
  result.a = isNaN.a ? x.a : result.a;

  return result;
`;function pZ(n){const{inputs:t,backend:e}=n,{x:s}=t;if(e.shouldExecuteOnCPU([s])){const r=e.texData.get(s.dataId),[i,a]=mz(r.values,s.shape,s.dtype);return e.makeTensorInfo(a,s.dtype,i)}let o;return z().getBool("WEBGL_PACK_UNARY_OPERATIONS")?o=new Fs(s.shape,hZ):o=new jn(s.shape,dZ),e.runWebGLProgram(o,[s],s.dtype)}const fZ={kernelName:ja,backendName:"webgl",kernelFunc:pZ};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const mZ=Hd;function gZ(n){je("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:e,attrs:s}=n,{boxes:o,scores:r}=t,{maxOutputSize:i,iouThreshold:a,scoreThreshold:c}=s,l=e.readSync(o.dataId),u=e.readSync(r.dataId),{selectedIndices:d}=mZ(l,u,i,a,c);return e.makeTensorInfo([d.length],"int32",new Int32Array(d))}const bZ={kernelName:Lu,backendName:"webgl",kernelFunc:gZ};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const xZ=_d;function yZ(n){je("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:e,attrs:s}=n,{boxes:o,scores:r}=t,{maxOutputSize:i,iouThreshold:a,scoreThreshold:c,padToMaxOutputSize:l}=s,u=e.readSync(o.dataId),d=e.readSync(r.dataId),{selectedIndices:h,validOutputs:p}=xZ(u,d,i,a,c,l);return[e.makeTensorInfo([h.length],"int32",new Int32Array(h)),e.makeTensorInfo([],"int32",new Int32Array([p]))]}const IZ={kernelName:Eu,backendName:"webgl",kernelFunc:yZ};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const wZ=Ud;function CZ(n){je("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:e,attrs:s}=n,{boxes:o,scores:r}=t,{maxOutputSize:i,iouThreshold:a,scoreThreshold:c,softNmsSigma:l}=s,u=e.readSync(o.dataId),d=e.readSync(r.dataId),h=i,p=a,f=c,m=l,{selectedIndices:g,selectedScores:b}=wZ(u,d,h,p,f,m);return[e.makeTensorInfo([g.length],"int32",new Int32Array(g)),e.makeTensorInfo([b.length],"float32",new Float32Array(b))]}const vZ={kernelName:Du,backendName:"webgl",kernelFunc:CZ};/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class SZ{constructor(t,e,s,o){this.variableNames=["indices"],this.outputShape=[t,e],this.userCode=`
      void main() {
        ivec2 coords = getOutputCoords();
        int index = round(getIndices(coords.x));
        setOutput(mix(float(${o}), float(${s}),
                      float(index == coords.y)));
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const kZ={kernelName:ec,backendName:"webgl",kernelFunc:n=>{const{inputs:t,backend:e,attrs:s}=n,{indices:o}=t,{dtype:r,depth:i,onValue:a,offValue:c}=s,l=Z(o.shape),u=new SZ(l,i,a,c),d=tt({inputs:{x:o},backend:e,attrs:{shape:[l]}}),h=e.runWebGLProgram(u,[d],r);e.disposeIntermediateTensorInfo(d);const p=[...o.shape,i],f=tt({inputs:{x:h},backend:e,attrs:{shape:p}});return e.disposeIntermediateTensorInfo(h),f}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Vl(n){const{inputs:t,backend:e}=n,{x:s}=t;if(s.dtype==="complex64"){const o=la({inputs:{input:s},backend:e}),r=Vl({inputs:{x:o},backend:e}),i=Wl({inputs:{input:s},backend:e}),a=Vl({inputs:{x:i},backend:e}),c=zs({inputs:{real:r,imag:a},backend:e});return e.disposeIntermediateTensorInfo(o),e.disposeIntermediateTensorInfo(r),e.disposeIntermediateTensorInfo(i),e.disposeIntermediateTensorInfo(a),c}else return ha({attrs:{shape:s.shape,dtype:s.dtype,value:s.dtype==="string"?"":0},backend:e})}const TZ={kernelName:xc,backendName:"webgl",kernelFunc:Vl};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function bI(n){const{inputs:t,backend:e}=n,{x:s}=t;if(s.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(s.dtype==="complex64"){const o=la({inputs:{input:s},backend:e}),r=bI({inputs:{x:o},backend:e}),i=Wl({inputs:{input:s},backend:e}),a=Vl({inputs:{x:i},backend:e}),c=zs({inputs:{real:r,imag:a},backend:e});return e.disposeIntermediateTensorInfo(o),e.disposeIntermediateTensorInfo(r),e.disposeIntermediateTensorInfo(i),e.disposeIntermediateTensorInfo(a),c}else return ha({attrs:{shape:s.shape,dtype:s.dtype,value:1},backend:e})}const NZ={kernelName:tc,backendName:"webgl",kernelFunc:bI};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function RZ(n){const{inputs:t,backend:e,attrs:s}=n,{axis:o}=s;if(t.length===1)return Vp({inputs:{input:t[0]},backend:e,attrs:{dim:o}});const r=t[0].shape,i=t[0].dtype;t.forEach(u=>{Hl(r,u.shape,"All tensors passed to stack must have matching shapes"),v(i===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});const a=[],c=t.map(u=>{const d=Vp({inputs:{input:u},backend:e,attrs:{dim:o}});return a.push(d),d}),l=Y1({inputs:c,backend:e,attrs:{axis:o}});return a.forEach(u=>e.disposeIntermediateTensorInfo(u)),l}const $Z={kernelName:nc,backendName:"webgl",kernelFunc:RZ};/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class GZ{constructor(t,e,s){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=e.map((l,u)=>l[0]+t[u]+l[1]);const o=t.length,r=Wt(o),i=e.map(l=>l[0]).join(","),a=e.map((l,u)=>l[0]+t[u]).join(","),c=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,o);if(o===1){this.userCode=`
        int start = ${i};
        int end = ${a};

        void main() {
          int outC = getOutputCoords();
          if (outC < start || outC >= end) {
            setOutput(value);
          } else {
            setOutput(getX(outC - start));
          }
        }
      `;return}this.userCode=`
      ${r} start = ${r}(${i});
      ${r} end = ${r}(${a});

      void main() {
        ${r} outC = getOutputCoords();
        if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
          setOutput(value);
        } else {
          ${r} coords = outC - start;
          setOutput(getX(${c}));
        }
      }
    `}}/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class LZ{constructor(t,e,s){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=e.map((m,g)=>m[0]+t[g]+m[1]);const o=t.length,r=Wt(o),i=e.map(m=>m[0]).join(","),a=e.map((m,g)=>m[0]+t[g]).join(","),c=We("rc",o),l=We("source",o),u=`${c[o-1]} < ${this.outputShape[o-1]}`,d=o===1?"source":`vec2(${l.slice(-2).join()})`,h=[`${r} rc = outputLoc;`,`${c[o-1]} += 1;
       if(${u}) {
      `,o===1?"":`}
       rc = outputLoc;
       ${c[o-2]} += 1;
       if(${c[o-2]} < ${this.outputShape[o-2]}) {`,o===1?"":`  ${c[o-1]} += 1;
         if(${u}) {`],p=o===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let f="";for(let m=0,g=o===1?2:4;m<g;m++)f+=`
        ${h[m]}
        if (${p}) {
          result[${m}] = float(value);
        } else {
          ${r} source = rc - start;
          result[${m}] = getChannel(getX(${l.join()}), ${d});
        }
      `;f+=o===1?"} ":"}}",this.userCode=`
      const ${r} start = ${r}(${i});
      const ${r} end = ${r}(${a});

      void main() {
        ${r} outputLoc = getOutputCoords();
        vec4 result = vec4(0.);
        ${f}
        setOutput(result);
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const xI=n=>{const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{paddings:r,constantValue:i}=s;if(Z(o.shape)===0){const l=r.map((u,d)=>u[0]+o.shape[d]+u[1]);return ha({backend:e,attrs:{shape:l,value:i,dtype:o.dtype}})}const a=z().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new LZ(o.shape,r,i):new GZ(o.shape,r,i),c=[[i]];return e.runWebGLProgram(a,[o],o.dtype,c)},EZ={kernelName:sc,backendName:"webgl",kernelFunc:xI};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const DZ=`
  if(a < 0.0 && floor(b) < b){
    return NAN;
  }
  if (b == 0.0) {
    return 1.0;
  }
  return (round(mod(b, 2.0)) != 1) ?
      pow(abs(a), b) : sign(a) * pow(abs(a), b);
`,WZ=`
  // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
  vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));
  vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);
  vec4 result = multiplier * pow(abs(a), b);

  // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
  bvec4 isExpZero = equal(b, vec4(0.0));
  result.r = isExpZero.r ? 1.0 : result.r;
  result.g = isExpZero.g ? 1.0 : result.g;
  result.b = isExpZero.b ? 1.0 : result.b;
  result.a = isExpZero.a ? 1.0 : result.a;

  bvec4 isNaN1 = lessThan(a, vec4(0.0));
  bvec4 isNaN2 = lessThan(floor(b), b);
  bvec4 isNaN = bvec4(isNaN1.x && isNaN2.x, isNaN1.y && isNaN2.y, isNaN1.z && isNaN2.z, isNaN1.w && isNaN2.w);
  `+To+`
  return result;
`,MZ=Ce({opSnippet:DZ,packedOpSnippet:WZ}),VZ={kernelName:qr,backendName:"webgl",kernelFunc:MZ};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function FZ(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{axis:r,keepDims:i}=s,a=o.shape.length,c=[],l=It(r,o.shape);let u=l;const d=Yt(u,a);let h=o;d!=null&&(h=Me({inputs:{x:o},backend:e,attrs:{perm:d}}),u=ee(u.length,a),c.push(h)),Ie("prod",u,a);let p;if(e.shouldExecuteOnCPU([h])){const f=e.texData.get(h.dataId).values,{outVals:m,outShape:g,outDtype:b}=bz(h.shape,h.dtype,f,u);p=e.makeTensorInfo(g,b,m)}else{const[f,m]=me(h.shape,u),g=Z(m),b=tt({inputs:{x:h},backend:e,attrs:{shape:[-1,g]}}),x=nd(o.dtype),I=No(b,x,"prod",e);p=tt({inputs:{x:I},backend:e,attrs:{shape:f}}),c.push(b),c.push(I)}if(i){c.push(p);const f=re(p.shape,l);p=tt({inputs:{x:p},backend:e,attrs:{shape:f}})}return c.forEach(f=>e.disposeIntermediateTensorInfo(f)),p}const zZ={kernelName:rc,backendName:"webgl",kernelFunc:FZ};/**
 * @license
 * Copyright 2022 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function XZ(n){const{inputs:t,backend:e,attrs:s}=n,{paramsNestedSplits:o,paramsDenseValues:r,indices:i}=t,{outputRaggedRank:a}=s,c=o.map(b=>e.readSync(b.dataId)),l=o.map(b=>b.shape),u=e.readSync(r.dataId),d=e.readSync(i.dataId),[h,p,f]=xz(c,l,u,r.shape,r.dtype,d,i.shape,a),m=h.map(b=>e.makeTensorInfo([b.length],"int32",b)),g=e.makeTensorInfo(f,r.dtype,p);return m.concat([g])}const AZ={kernelName:Sf,backendName:"webgl",kernelFunc:XZ};/**
 * @license
 * Copyright 2022 Google LLC.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function PZ(n){const{inputs:t,backend:e}=n,{starts:s,limits:o,deltas:r}=t,i=e.readSync(s.dataId),a=e.readSync(o.dataId),c=e.readSync(r.dataId),[l,u]=yz(i,s.shape,s.dtype,a,o.shape,c,r.shape),d=e.makeTensorInfo([l.length],"int32",l),h=e.makeTensorInfo([u.length],s.dtype,u);return[d,h]}const OZ={kernelName:kf,backendName:"webgl",kernelFunc:PZ};/**
 * @license
 * Copyright 2022 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function KZ(n){const{inputs:t,backend:e,attrs:s}=n,{shape:o,values:r,defaultValue:i,rowPartitionTensors:a}=t,{rowPartitionTypes:c}=s,l=e.readSync(o.dataId),u=e.readSync(r.dataId),d=e.readSync(i.dataId),h=a.map(g=>e.readSync(g.dataId)),p=a.map(g=>g.shape),[f,m]=Iz(l,o.shape,u,r.shape,r.dtype,d,i.shape,h,p,c);return e.makeTensorInfo(f,r.dtype,m)}const ZZ={kernelName:Tf,backendName:"webgl",kernelFunc:KZ};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const yI=n=>{const{backend:t,attrs:e}=n,{start:s,stop:o,step:r,dtype:i}=e,a=wz(s,o,r,i);return t.makeTensorInfo([a.length],i,a)},BZ={kernelName:Wu,backendName:"webgl",kernelFunc:yI};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const HZ=Tt({opSnippet:"return 1.0 / x;"}),_Z={kernelName:ti,backendName:"webgl",kernelFunc:HZ};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const UZ=Cn+`
  return (x < 0.0) ? 0.0 : x;
`,YZ=Tt({opSnippet:UZ,packedOpSnippet:`
  vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
  bvec4 isNaN = isnan(x);

  result.r = isNaN.r ? x.r : result.r;
  result.g = isNaN.g ? x.g : result.g;
  result.b = isNaN.b ? x.b : result.b;
  result.a = isNaN.a ? x.a : result.a;

  return result;
`}),QZ={kernelName:ei,backendName:"webgl",kernelFunc:YZ};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const JZ=Cn+`
  return (x < 0.0) ? 0.0 : min(6.0, x);
`,jZ=Tt({opSnippet:JZ,packedOpSnippet:`
  vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
  bvec4 isNaN = isnan(x);

  result.r = isNaN.r ? x.r : result.r;
  result.g = isNaN.g ? x.g : result.g;
  result.b = isNaN.b ? x.b : result.b;
  result.a = isNaN.a ? x.a : result.a;

  return result;
`}),qZ={kernelName:ni,backendName:"webgl",kernelFunc:jZ};/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class tB{constructor(t,e,s,o,r){this.variableNames=["A"],this.outputShape=[];const[i,a,c,l]=t;this.outputShape=[i,e,s,l];const u=[o&&e>1?a-1:a,o&&s>1?c-1:c],d=[o&&e>1?e-1:e,o&&s>1?s-1:s];let h;r?h="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":h="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
      const vec2 effectiveInputOverOutputRatioRC = vec2(
          ${u[0]/d[0]},
          ${u[1]/d[1]});
      const vec2 inputShapeRC = vec2(${a}.0, ${c}.0);

      void main() {
        ivec4 coords = getOutputCoords();
        int b = coords[0];
        int d = coords[3];
        ivec2 yRC = coords.yz;

        // Fractional source index.
        vec2 sourceFracIndexRC = ${h};

        // Compute the four integer indices.
        ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));
        ivec2 sourceCeilRC = ivec2(
          min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));

        float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);
        float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);
        float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);
        float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);

        vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);

        float top = topLeft + (topRight - topLeft) * fracRC.y;
        float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
        float newValue = top + (bottom - top) * fracRC.x;

        setOutput(newValue);
      }
    `}}/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class eB{constructor(t,e,s,o,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[i,a,c,l]=t;this.outputShape=[i,e,s,l];const u=[o&&e>1?a-1:a,o&&s>1?c-1:c],d=[o&&e>1?e-1:e,o&&s>1?s-1:s];let h;r?h="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":h="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
      const vec3 effectiveInputOverOutputRatioRC = vec3(
          ${u[0]/d[0]},
          ${u[1]/d[1]},
          ${u[1]/d[1]});
      const vec3 inputShapeRC = vec3(${a}.0, ${c}.0,
                                     ${c}.0);

      float getAValue(int b, int r, int c, int d) {
        return getChannel(getA(b, r, c, d), vec2(c, d));
      }

      void main() {
        ivec4 coords = getOutputCoords();
        int b = coords[0];
        int d = coords[3];
        // Calculate values for next column in yRC.z.
        ivec3 yRC = coords.yzz + ivec3(0, 0, 1);

        // Fractional source index.
        vec3 sourceFracIndexRC = ${h};

        // Compute the four integer indices.
        ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));
        ivec3 sourceCeilRC = ivec3(
          min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));

        // Should we calculate next column and row elements in 2x2 packed cell.
        bool hasNextCol = d < ${l-1};
        bool hasNextRow = coords.z < ${s-1};

        // In parallel, construct four corners for all four components in
        // packed 2x2 cell.
        vec4 topLeft = vec4(
          getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),
          hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)
                     : 0.0,
          hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)
                     : 0.0,
          (hasNextRow && hasNextCol) ?
            getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);

        vec4 bottomLeft = vec4(
          getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),
          hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)
                     : 0.0,
          hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)
                     : 0.0,
          (hasNextRow && hasNextCol) ?
            getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);

        vec4 topRight = vec4(
          getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),
          hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)
                     : 0.0,
          hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)
                     : 0.0,
          (hasNextRow && hasNextCol) ?
            getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);

        vec4 bottomRight = vec4(
          getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),
          hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)
                     : 0.0,
          hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)
                     : 0.0,
          (hasNextRow && hasNextCol) ?
            getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);

        vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);

        vec4 top = mix(topLeft, topRight, fracRC.yyzz);
        vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
        vec4 newValue = mix(top, bottom, fracRC.x);

        setOutput(newValue);
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function nB(n){const{inputs:t,backend:e,attrs:s}=n,{images:o}=t,{alignCorners:r,halfPixelCenters:i,size:a}=s,[c,l]=a,u=z().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new eB(o.shape,c,l,r,i):new tB(o.shape,c,l,r,i);return e.runWebGLProgram(u,[o],"float32")}const sB={kernelName:cc,backendName:"webgl",kernelFunc:nB};/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class oB{constructor(t,e,s){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e;const[,o,r]=e,[,i,a]=t,c=[s&&i>1?o-1:o,s&&a>1?r-1:r],l=[s&&i>1?i-1:i,s&&a>1?a-1:a],u=c[0]/l[0],d=c[1]/l[1],h=1/u,p=1/d,f=Math.ceil(h)*2+2,m=Math.ceil(p)*2+2;this.userCode=`
      void main() {
        ivec4 coords = getOutputCoords();
        int b = coords[0];
        int d = coords[3];
        int r = coords[1];
        int c = coords[2];

        float accumulator = 0.0;

        const float heightScale = float(${u});
        const float widthScale = float(${d});

        const float invHeightScale = float(${h});
        const float invWidthScale = float(${p});

        const int winHeight = int(${f});
        const int winWidth = int(${m});

        // Compute bounds for where in dy we will look
        float startRLerp = floor(float(r) * invHeightScale);
        int startDyR = int(startRLerp - float(winHeight / 2));

        float startCLerp = floor(float(c) * invWidthScale);
        int startDyC = int(startCLerp - float(winWidth / 2));

        // Loop over dy
        for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
          int dyR = dyROffset + startDyR;

          // Guard against the window exceeding the bounds of dy
          if (dyR < 0 || dyR >= ${i}) {
            continue;
          }

          for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
            int dyC = dyCOffset + startDyC;

            // Guard against the window exceeding the bounds of dy
            if (dyC < 0 || dyC >= ${a}) {
              continue;
            }

            float dxR = float(dyR) * heightScale;
            int topDxRIndex = int(floor(dxR));
            int bottomDxRIndex = int(min(ceil(dxR), ${o-1}.0));
            float dxRLerp = dxR - float(topDxRIndex);
            float inverseDxRLerp = 1.0 - dxRLerp;

            float dxC = float(dyC) * widthScale;
            int leftDxCIndex = int(floor(dxC));
            int rightDxCIndex = int(min(ceil(dxC), ${r-1}.0));
            float dxCLerp = dxC - float(leftDxCIndex);
            float inverseDxCLerp = 1.0 - dxCLerp;

            if (r == topDxRIndex && c == leftDxCIndex) {
              // topLeft
              accumulator +=
                getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;
            }

            if (r == topDxRIndex && c == rightDxCIndex) {
              // topRight
              accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;
            }

            if (r == bottomDxRIndex && c == leftDxCIndex) {
              // bottomLeft
              accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;
            }

            if (r == bottomDxRIndex && c == rightDxCIndex) {
              // bottomRight
              accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;
            }
          }
        }
        // End loop over dy

        setOutput(accumulator);
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function rB(n){const{inputs:t,backend:e,attrs:s}=n,{images:o,dy:r}=t,{alignCorners:i}=s,a=new oB(r.shape,o.shape,i);return e.runWebGLProgram(a,[r],r.dtype)}const iB={kernelName:Fu,backendName:"webgl",kernelFunc:rB};/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class aB{constructor(t,e,s,o,r){this.variableNames=["A"],this.outputShape=[];const[i,a,c,l]=t;this.outputShape=[i,e,s,l];const u=[o&&e>1?a-1:a,o&&s>1?c-1:c],d=[o&&e>1?e-1:e,o&&s>1?s-1:s],h=o?"0.5":"0.0";let p;r?p="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":p="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
      const vec2 effectiveInputOverOutputRatioRC = vec2(
          ${u[0]/d[0]},
          ${u[1]/d[1]});
      const vec2 inputShapeRC = vec2(${a}.0, ${c}.0);

      void main() {
        ivec4 coords = getOutputCoords();
        int b = coords[0];
        int d = coords[3];
        ivec2 yRC = coords.yz;

        // Fractional source index.
        vec2 sourceFracIndexRC = ${p};

        // Compute the coordinators of nearest neighbor point.
        ivec2 sourceNearestRC = ivec2(
          min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${h})));
        float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);

        setOutput(newValue);
      }
    `}}/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class cB{constructor(t,e,s,o,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[i,a,c,l]=t;this.outputShape=[i,e,s,l];const u=[o&&e>1?a-1:a,o&&s>1?c-1:c],d=[o&&e>1?e-1:e,o&&s>1?s-1:s],h=o?"0.5":"0.0";let p;r?p="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":p="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
      const vec3 effectiveInputOverOutputRatioRC = vec3(
          ${u[0]/d[0]},
          ${u[1]/d[1]},
          ${u[1]/d[1]});
      const vec3 inputShapeRC = vec3(${a}.0, ${c}.0,
                                     ${c}.0);

      float getAValue(int b, int r, int c, int d) {
        return getChannel(getA(b, r, c, d), vec2(c, d));
      }

      void main() {
        ivec4 coords = getOutputCoords();
        int b = coords[0];
        int d = coords[3];
        // Calculate values for next column in yRC.z.
        ivec3 yRC = coords.yzz + ivec3(0, 0, 1);

        // Fractional source index.
        vec3 sourceFracIndexRC = ${p};

        // Compute the coordinators of nearest neighbor point.
        ivec3 sourceNearestRC = ivec3(
          min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${h})));

        // Should we calculate next column and row elements in 2x2 packed cell.
        bool hasNextCol = d < ${l-1};
        bool hasNextRow = coords.z < ${s-1};

        vec4 newValue = vec4(
          getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),
          hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)
                     : 0.0,
          hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)
                     : 0.0,
          (hasNextRow && hasNextCol) ?
            getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);

        setOutput(newValue);
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function lB(n){const{inputs:t,backend:e,attrs:s}=n,{images:o}=t,{alignCorners:r,halfPixelCenters:i,size:a}=s,[c,l]=a,u=z().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new cB(o.shape,c,l,r,i):new aB(o.shape,c,l,r,i);return e.runWebGLProgram(u,[o],o.dtype)}const uB={kernelName:ac,backendName:"webgl",kernelFunc:lB};/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class dB{constructor(t,e,s){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e;const[,o,r]=e,[,i,a]=t,c=[s&&i>1?o-1:o,s&&a>1?r-1:r],l=[s&&i>1?i-1:i,s&&a>1?a-1:a],u=c[0]/l[0],d=c[1]/l[1],h=1/u,p=1/d,f=Math.ceil(h)*2+2,m=Math.ceil(p)*2+2;this.userCode=`
      void main() {
        ivec4 coords = getOutputCoords();
        int b = coords[0];
        int d = coords[3];
        int r = coords[1];
        int c = coords[2];

        float accumulator = 0.0;

        const float heightScale = float(${u});
        const float widthScale = float(${d});

        const float invHeightScale = float(${h});
        const float invWidthScale = float(${p});

        const int winHeight = int(${f});
        const int winWidth = int(${m});

        // Compute bounds for where in dy we will look
        float startRLerp = floor(float(r) * invHeightScale);
        int startDyR = int(floor(startRLerp - float(winHeight / 2)));

        float startCLerp = floor(float(c) * invWidthScale);
        int startDyC = int(floor(startCLerp - float(winWidth / 2)));

        // Loop over dy
        for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
          int dyR = dyROffset + startDyR;

          // Guard against the window exceeding the bounds of dy
          if (dyR < 0 || dyR >= ${i}) {
            continue;
          }

          for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
            int dyC = dyCOffset + startDyC;

            // Guard against the window exceeding the bounds of dy
            if (dyC < 0 || dyC >= ${a}) {
              continue;
            }

            float sourceFracRow =
              float(${c[0]}) *
                (float(dyR) / float(${l[0]}));

            float sourceFracCol =
                float(${c[1]}) *
                  (float(dyC) / float(${l[1]}));

            int sourceNearestRow = int(min(
                float(int(${o}) - 1),
                ${s} ? float(round(sourceFracRow)) :
                                  float(floor(sourceFracRow))));

            int sourceNearestCol = int(min(
                float(int(${r}) - 1),
                ${s} ? float(round(sourceFracCol)) :
                                  float(floor(sourceFracCol))));

            if (r == sourceNearestRow && c == sourceNearestCol) {
              accumulator += getDy(b, dyR, dyC, d);
            }
          }
        }
        // End loop over dy

        setOutput(accumulator);
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function hB(n){const{inputs:t,backend:e,attrs:s}=n,{images:o,dy:r}=t,{alignCorners:i}=s,a=new dB(r.shape,o.shape,i);return e.runWebGLProgram(a,[r],r.dtype)}const pB={kernelName:Vu,backendName:"webgl",kernelFunc:hB};/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class fB{constructor(t,e){this.variableNames=["x"];const s=t.length;if(s>4)throw new Error(`WebGL backend: Reverse of rank-${s} tensor is not yet supported`);if(this.outputShape=t,s===1){this.userCode=`
        void main() {
          int coord = getOutputCoords();
          setOutput(getX(${t[0]} - coord - 1));
        }
      `;return}const o=a=>e.indexOf(a)!==-1&&t[a]!==1?`${t[a]} - coords[${a}] - 1`:`coords[${a}]`,r=t.map((a,c)=>o(c)).join(","),i=Wt(s);this.userCode=`
      void main() {
        ${i} coords = getOutputCoords();
        setOutput(getX(${r}));
      }
    `}}/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class mB{constructor(t,e){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const s=t.length;if(s>4)throw new Error(`WebGL backend: Reverse of rank-${s} tensor is not yet supported`);this.outputShape=t;const o=We("rc",s),r=`${o[s-1]} + 1 < ${this.outputShape[s-1]}`,i=`${o[s-2]} + 1 < ${this.outputShape[s-2]}`,a=Wt(s);s===1?this.userCode=`
        void main(){
          int rc = getOutputCoords();
          vec4 result = vec4(0.);
          result.r = getChannel(getX(${t[0]} - rc - 1),
            ${t[0]} - rc - 1);
          if(${r}){
              result.g = getChannel(getX(${t[0]} - (rc  + 1) - 1),
                ${t[0]} - (rc  + 1) - 1);
          }
          setOutput(result);
        }
      `:this.userCode=`
        void main() {
          ${a} rc = getOutputCoords();
          vec4 result = vec4(0.);
          result.r = ${c(o.slice())};
          if(${r}){
            result.g = ${l(o.slice())};
          }
          if(${i}) {
            result.b = ${u(o.slice())};
            if(${r}) {
              result.a = ${d(o.slice())};
            }
          }
          setOutput(result);
        }
    `;function c(f){return h(f)}function l(f){return f[s-1]="("+f[s-1]+" + 1)",h(f)}function u(f){return f[s-2]="("+f[s-2]+" + 1)",h(f)}function d(f){return f[s-1]="("+f[s-1]+" + 1)",f[s-2]="("+f[s-2]+" + 1)",h(f)}function h(f){const m=t.map((x,I)=>p(I,f)),g=m.join(","),b=m.slice(-2).join(",");return`getChannel(getX(${g}), vec2(${b}))`}function p(f,m){return e.indexOf(f)!==-1&&t[f]!==1?`${t[f]} - ${m[f]} - 1`:`${m[f]}`}}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function gB(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{dims:r}=s,i=o.shape.length,a=It(r,o.shape);if(i===0)return Je({inputs:{x:o},backend:e});const c=z().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new mB(o.shape,a):new fB(o.shape,a);return e.runWebGLProgram(c,[o],o.dtype)}const bB={kernelName:lc,backendName:"webgl",kernelFunc:gB};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class xB{constructor(t,e){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];const s=t[1],o=t[2];this.outputShape=t;let r="";typeof e=="number"?r=`float outputValue = ${e.toFixed(2)};`:r=`
        vec3 fill = vec3(${e.join(",")});
        float outputValue = fill[coords[3]];`,this.userCode=`
        void main() {
          ivec4 coords = getOutputCoords();
          int x = coords[2];
          int y = coords[1];
          float coordXFloat = (float(x) - params[0]) * params[3] -
            (float(y) - params[1]) * params[2];
          float coordYFloat = (float(x) - params[0]) * params[2] +
            (float(y) - params[1]) * params[3];
          int coordX = int(round(coordXFloat + params[0]));
          int coordY = int(round(coordYFloat + params[1]));
          ${r}
          if(coordX >= 0 && coordX < ${o} && coordY >= 0 && coordY < ${s}) {
            outputValue = getImage(coords[0], coordY, coordX, coords[3]);
          }
          setOutput(outputValue);
        }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const yB={kernelName:Bu,backendName:"webgl",kernelFunc:({inputs:n,attrs:t,backend:e})=>{const{image:s}=n,{radians:o,fillValue:r,center:i}=t,a=e,c=new xB(s.shape,r),[l,u]=ih(i,s.shape[1],s.shape[2]),d=[[l,u,Math.sin(o),Math.cos(o)]];return a.runWebGLProgram(c,[s],s.dtype,d)}};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const IB=Tt({opSnippet:`
  // OpenGL ES does not support round function.
  // The algorithm is based on banker's rounding.
  float base = floor(x);
  if ((x - base) < 0.5) {
    return floor(x);
  } else if ((x - base) > 0.5) {
    return ceil(x);
  } else {
    if (mod(base, 2.0) == 0.0) {
      return base;
    } else {
      return base + 1.0;
    }
  }
`}),wB={kernelName:si,backendName:"webgl",kernelFunc:IB};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const CB=Tt({opSnippet:"return inversesqrt(x);",cpuKernelImpl:Cz}),vB={kernelName:oi,backendName:"webgl",kernelFunc:CB};/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class zp{constructor(t,e,s,o,r,i,a=!0,c=!1){this.variableNames=["updates","indices","defaultValue"],this.outputShape=i;const l=Wt(r.length),u=Wt(i.length);let d="";s===1?d="i":s===2&&(d="i, j");const h=`getIndices(${d})`;let p="";o===1?p="i":o===2&&(p="i, coords[1]");const f=`getUpdates(${p})`;let m="";c&&(m="coords[0], coords[1]");const g=`getDefaultValue(${m})`,b=e>1?"strides[j]":"strides";this.userCode=`
        ${l} strides = ${l}(${r});

        void main() {
          ${u} coords = getOutputCoords();
          float sum = 0.0;
          bool found = false;
          for (int i = 0; i < ${t}; i++) {
            int flattenedIndex = 0;
            for (int j = 0; j < ${e}; j++) {
              int index = round(${h});
              flattenedIndex += index * ${b};
            }
            if (flattenedIndex == coords[0]) {
              sum += ${f};
              found = true;
            }
          }
          setOutput(mix(${g}, sum, float(found)));
        }
      `}}/**
 * @license
 * Copyright 2023 Google LLC.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class SB{constructor(t,e,s,o,r,i,a=!0,c=!1){this.variableNames=["updates","indices","defaultValue"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=i;const l=Wt(r.length),u=Wt(i.length);let d="";s===1?d="i":s===2&&(d="i, j");const h=`getIndices(${d})`;let p="";o===1?p="i":o===2&&(p="i, coords[1]");const f=`getUpdates(${p})`;let m="";c&&(m="coords[0], coords[1]");const g=`getDefaultValue(${m})`,b=e>1?"strides[j]":"strides",x=e>1?"strides[j + 1]":"strides";this.userCode=`
        ${l} strides = ${l}(${r});

        void main() {
          ${u} coords = getOutputCoords();
          vec4 sum = vec4(0.);
          vec4 found = vec4(0.);
          for (int i = 0; i < ${t}; i+=2) {
            ivec2 flattenedIndex = ivec2(0);
            for (int j = 0; j < ${e}; j+=2) {
              ivec4 index = round(${h});
              flattenedIndex += index.xz * ${b};
              if (j + 1 < ${e}) {
                flattenedIndex += index.yw * ${x};
              }
            }
            if (flattenedIndex[0] == coords[0] || flattenedIndex[1] == coords[0] ||
                flattenedIndex[0] == coords[0] + 1 || flattenedIndex[1] == coords[0] + 1) {
              vec4 updVals = ${f};
              if (flattenedIndex[0] == coords[0]) {
                sum.xy += updVals.xy;
                found.xy = vec2(1.);
              } else if (flattenedIndex[0] == coords[0] + 1) {
                sum.zw += updVals.xy;
                found.zw = vec2(1.);
              }
              if (flattenedIndex[1] == coords[0]) {
                sum.xy += updVals.zw;
                found.xy = vec2(1.);
              } else if (flattenedIndex[1] == coords[0] + 1) {
                sum.zw += updVals.zw;
                found.zw = vec2(1.);
              }
            }
          }
          setOutput(mix(${g}, sum, found));
        }
      `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function kB(n){const{inputs:t,backend:e,attrs:s}=n,{indices:o,updates:r}=t,{shape:i}=s,{sliceRank:a,numUpdates:c,sliceSize:l,strides:u,outputSize:d}=co(r,o,i),h=[d/l,l];if(d===0)return e.makeTensorInfo(i,o.dtype);const p=tt({inputs:{x:o},backend:e,attrs:{shape:[c,a]}}),f=tt({inputs:{x:r},backend:e,attrs:{shape:[c,l]}}),m=e.makeTensorInfo([],"float32",new Float32Array([0]));let g;z().getBool("WEBGL_PACK")?g=new SB(c,a,p.shape.length,f.shape.length,u,h):g=new zp(c,a,p.shape.length,f.shape.length,u,h);const b=e.runWebGLProgram(g,[f,p,m],f.dtype),x=tt({inputs:{x:b},backend:e,attrs:{shape:i}});return e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(b),e.disposeIntermediateTensorInfo(m),x}const TB={kernelName:Nf,backendName:"webgl",kernelFunc:kB};/**
 * @license
 * Copyright 2022 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class NB{constructor(t,e,s,o){this.variableNames=["sortedSequence","values"],this.customUniforms=[{name:"numInputs",type:"int"}],this.outputShape=[t,s];const r="while (left < right) {",i=`for (int i = 0; i < ${Math.ceil(Math.log2(e+1))}; ++i) { if (left >= right) break;`,a=z().getNumber("WEBGL_VERSION")===2?r:i,c=o==="left"?"<":"<=";this.userCode=`
       int findBound(int batch, float value) {
         int left = 0;
         int right = numInputs;
         int mid;
         ${a}
           mid = (left + right) / 2;
           if (getSortedSequence(batch, mid) ${c} value) {
             left = mid + 1;
           } else {
             right = mid;
           }
         }
         return right;
       }

       void main() {
         ivec2 coords = getOutputCoords();
         int batch = coords[0];
         int valueIndex = coords[1];

         float value = getValues(batch, valueIndex);

         setOutput(float(findBound(batch, value)));
       }
     `}}/**
 * @license
 * Copyright 2022 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function RB(n){const{inputs:t,backend:e,attrs:s}=n,{sortedSequence:o,values:r}=t,{side:i}=s,a=new NB(o.shape[0],o.shape[1],r.shape[1],i),c=[[o.shape[1]]];return e.runWebGLProgram(a,[o,r],"int32",c)}const $B={kernelName:$f,backendName:"webgl",kernelFunc:RB};/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class GB{constructor(t,e,s){this.variableNames=["c","a","b"],this.outputShape=e;let o,r;if(s>4)throw Error(`Where for rank ${s} is not yet supported`);if(s===1)r="resRC",o="resRC";else{const a=["resRC.x","resRC.y","resRC.z","resRC.w"],c=[],l=[];for(let u=0;u<e.length;u++)l.push(`${a[u]}`),u<t&&c.push(`${a[u]}`);o=c.join(),r=l.join()}const i=Wt(s);this.userCode=`
      void main() {
        ${i} resRC = getOutputCoords();
        float cVal = getC(${o});
        if (cVal >= 1.0) {
          setOutput(getA(${r}));
        } else {
          setOutput(getB(${r}));
        }
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function LB(n){const{inputs:t,backend:e}=n,{condition:s,t:o,e:r}=t,i=new GB(s.shape.length,o.shape,o.shape.length);return e.runWebGLProgram(i,[s,o,r],_e(o.dtype,r.dtype))}const EB={kernelName:uc,backendName:"webgl",kernelFunc:LB};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const DB=`
  // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
  // see: https://arxiv.org/abs/1706.02515
  float scaleAlpha = ${Pc};
  float scale = ${Oc};
  return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
`,WB=Tt({opSnippet:DB}),MB={kernelName:ri,backendName:"webgl",kernelFunc:WB};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const VB=br+`
  return 1.0 / (1.0 + exp(-1.0 * x));
`,FB=Tt({opSnippet:VB,packedOpSnippet:`
  vec4 result = 1.0 / (1.0 + exp(-1.0 * x));
  bvec4 isNaN = isnan(x);

  result.r = isNaN.r ? x.r : result.r;
  result.g = isNaN.g ? x.g : result.g;
  result.b = isNaN.b ? x.b : result.b;
  result.a = isNaN.a ? x.a : result.a;

  return result;
`,cpuKernelImpl:Sz}),zB={kernelName:li,backendName:"webgl",kernelFunc:FB};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const XB=Tt({opSnippet:`
  if (isnan(x)) { return 0.0; }
  return sign(x);
`}),AB={kernelName:ci,backendName:"webgl",kernelFunc:XB};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const PB=br+`
  return sin(x);
`,OB=`
  vec4 result = sin(x);
  bvec4 isNaN = isnan(x);
  ${To}
  return result;
`,KB=Tt({opSnippet:PB,packedOpSnippet:OB}),ZB={kernelName:ii,backendName:"webgl",kernelFunc:KB};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const BB=Tt({opSnippet:`
  float e2x = exp(x);
  return (e2x - 1.0 / e2x) / 2.0;
`}),HB={kernelName:ai,backendName:"webgl",kernelFunc:BB};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const _B=Tt({opSnippet:`
  float epsilon = 1.1920928955078125e-7;
  float threshold = log(epsilon) + 2.0;

  bool too_large = x > -threshold;
  bool too_small = x < threshold;

  float result;
  float exp_x = exp(x);

  if (too_large){
    result = x;
  }
  else if (too_small){
    result = exp_x;
  }
  else{
    result = log(exp_x + 1.0);
  }
  return result;
`}),UB={kernelName:ui,backendName:"webgl",kernelFunc:_B};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const YB={kernelName:pc,backendName:"webgl",kernelFunc:n=>{const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{blockShape:r,paddings:i}=s;v(o.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");const a=r.reduce((b,x)=>b*x),c=[[0,0]];c.push(...i);for(let b=1+r.length;b<o.shape.length;++b)c.push([0,0]);const l=[],u=xI({inputs:{x:o},backend:e,attrs:{paddings:c,constantValue:0}}),d=Mi(u.shape,r,a,!1),h=Vi(d.length,r.length,!1),p=Fi(u.shape,r,a,!1),f=tt({inputs:{x:u},backend:e,attrs:{shape:d}}),m=Me({inputs:{x:f},backend:e,attrs:{perm:h}}),g=tt({inputs:{x:m},backend:e,attrs:{shape:p}});return l.push(u),l.push(f),l.push(m),l.forEach(b=>e.disposeIntermediateTensorInfo(b)),g}};/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function QB(n){const{inputs:t,backend:e}=n,{indices:s,values:o,denseShape:r,defaultValue:i}=t;if(r.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
         ${r.shape}`);if(s.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
         ${s.shape}`);if(o.shape.length!==1)throw new Error(`Values must be a vector, saw:
         ${o.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
        ${i.shape}`);const a=e.readSync(s.dataId),c=e.readSync(o.dataId),l=e.readSync(r.dataId),u=e.readSync(i.dataId)[0],[d,h,p,f,m]=Tz(a,s.shape,s.dtype,c,o.dtype,l,u);return[e.makeTensorInfo(h,s.dtype,d),e.makeTensorInfo([h[0]],o.dtype,p),e.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),e.makeTensorInfo([m.length],s.dtype,new Int32Array(m))]}const JB={kernelName:Gf,backendName:"webgl",kernelFunc:QB};/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function jB(n){const{inputs:t,backend:e}=n,{inputIndices:s,inputShape:o,newShape:r}=t;if(s.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${s.shape}`);if(o.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${o.shape}`);if(r.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${r.shape}`);const i=Array.from(e.readSync(o.dataId)),a=e.readSync(s.dataId),c=Array.from(e.readSync(r.dataId)),[l,u,d]=Nz(a,s.shape,s.dtype,i,c);return[e.makeTensorInfo(u,s.dtype,l),e.makeTensorInfo([d.length],r.dtype,new Int32Array(d))]}const qB={kernelName:Lf,backendName:"webgl",kernelFunc:jB};/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function tH(n){const{inputs:t,backend:e}=n,{data:s,indices:o,segmentIds:r}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.shape.length!==1)throw new Error(`Indices should be a vector but received shape
              ${o.shape}`);if(r.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
              ${r.shape}`);const i=e.readSync(s.dataId),a=e.readSync(o.dataId),c=e.readSync(r.dataId),[l,u]=S1(i,s.shape,s.dtype,a,c,!0);return e.makeTensorInfo(u,s.dtype,l)}const eH={kernelName:Ef,backendName:"webgl",kernelFunc:tH};/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function nH(n){const{inputs:t,backend:e}=n,{data:s,indices:o,segmentIds:r}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.shape.length!==1)throw new Error(`Indices should be a vector but received shape
             ${o.shape}`);if(r.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
             ${r.shape}`);const i=e.readSync(s.dataId),a=e.readSync(o.dataId),c=e.readSync(r.dataId),[l,u]=S1(i,s.shape,s.dtype,a,c);return e.makeTensorInfo(u,s.dtype,l)}const sH={kernelName:Df,backendName:"webgl",kernelFunc:nH};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function oH(n){const{inputs:t,backend:e,attrs:s}=n,{sparseIndices:o,sparseValues:r,defaultValue:i}=t,{outputShape:a}=s,{sliceRank:c,numUpdates:l,sliceSize:u,strides:d,outputSize:h}=co(r,o,a),p=!1;if(r.dtype==="string"){const b=e.bufferSync(o),x=e.bufferSync(r),I=xs(e.readSync(i.dataId)[0]),y=vz(b,x,a,h,u,l,c,d,I,p);return e.makeTensorInfo(a,y.dtype,y.values)}const f=new zp(l,c,o.shape.length,r.shape.length,d,[h,1],p),m=e.runWebGLProgram(f,[r,o,i],r.dtype),g=tt({inputs:{x:m},backend:e,attrs:{shape:a}});return e.disposeIntermediateTensorInfo(m),g}const rH={kernelName:Wf,backendName:"webgl",kernelFunc:oH};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function iH(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{numOrSizeSplits:r,axis:i}=s,a=It(i,o.shape)[0],c=Ch(o,r,a),l=o.shape.length,u=new Array(l).fill(0),d=o.shape.slice();return c.map(h=>{const p=[...d];p[a]=h;const f=xr({inputs:{x:o},backend:e,attrs:{begin:u,size:p}});return u[a]+=h,f})}const aH={kernelName:fc,backendName:"webgl",kernelFunc:iH};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const II="return sqrt(x);",cH=Tt({opSnippet:II,packedOpSnippet:II,cpuKernelImpl:Rz}),lH={kernelName:di,backendName:"webgl",kernelFunc:cH};/**
 * @license
 * Copyright 2019 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const uH=Tt({opSnippet:"return x * x;"}),dH={kernelName:zu,backendName:"webgl",kernelFunc:uH};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const wI="return (a - b) * (a - b);",hH=Ce({opSnippet:wI,packedOpSnippet:wI}),pH={kernelName:hi,backendName:"webgl",kernelFunc:hH};/**
 * @license
 * Copyright 2023 Google LLC.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function fH(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t;if(o.dtype!=="string")throw new Error("Input must be of datatype string");const r=e.readSync(o.dataId),i=cs(r),a=$z(i,"string",s);return e.makeTensorInfo(o.shape,"string",a)}const mH={kernelName:Xu,backendName:"webgl",kernelFunc:fH};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function gH({inputs:n,attrs:t,backend:e}){const{x:s}=n,o=Cn+`
    return x > 0.0 ? 1.0 : float(${t.alpha});
  `,r=new jn(s.shape,o);return e.runWebGLProgram(r,[s],s.dtype)}const bH={kernelName:bi,backendName:"webgl",kernelFunc:gH};/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class xH{constructor(t,e,s){this.variableNames=["x"],this.outputShape=s;const o=s.length,r=Wt(s.length),i=Wt(s.length);let a="";if(o===1)a="coords * strides + begin";else{let c=0;a=s.map((l,u)=>(c++,s.length===1?`coords * strides[${u}] + begin[${u}]`:`coords[${c-1}] * strides[${u}] + begin[${u}]`)).join(",")}this.userCode=`
      ${r} begin = ${r}(${t});
      ${r} strides = ${r}(${e});

      void main() {
        ${i} coords = getOutputCoords();
        setOutput(getX(${a}));
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function yH(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{begin:r,end:i,strides:a,beginMask:c,endMask:l,ellipsisMask:u,newAxisMask:d,shrinkAxisMask:h}=s,{finalShapeSparse:p,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:b,begin:x,end:I,strides:y}=sh(o.shape,r,i,a,c,l,u,d,h);let w;if(m)w=tt({inputs:{x:o},backend:e,attrs:{shape:f}});else if(g||b){v(o.shape.length>=1,()=>`Input must have rank at least 1, got: ${o.shape.length}`);const k=th(x,I,y),S=xr({inputs:{x:o},backend:e,attrs:{begin:x,size:k}});w=tt({inputs:{x:S},backend:e,attrs:{shape:f}}),e.disposeIntermediateTensorInfo(S)}else if(e.shouldExecuteOnCPU([o])){const S=e.readSync(o.dataId),T=wt(o.shape,o.dtype,S),R=Gz(p,T,y,x);w=e.makeTensorInfo(f,o.dtype,R.values)}else{const S=new xH(x,y,p);w=e.runWebGLProgram(S,[o],o.dtype)}const C=tt({inputs:{x:w},backend:e,attrs:{shape:f}});return e.disposeIntermediateTensorInfo(w),C}const IH={kernelName:Au,backendName:"webgl",kernelFunc:yH};/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function wH(n){const{inputs:t,backend:e,attrs:s}=n,{separator:o,nGramWidths:r,leftPad:i,rightPad:a,padWidth:c,preserveShortSequences:l}=s,{data:u,dataSplits:d}=t,h=e.readSync(u.dataId),p=e.readSync(d.dataId),[f,m]=Lz(h,p,o,r,i,a,c,l);return[e.makeTensorInfo([f.length],"string",f),e.makeTensorInfo(d.shape,"int32",m)]}const CH={kernelName:Mf,backendName:"webgl",kernelFunc:wH};/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function vH(n){const{inputs:t,backend:e,attrs:s}=n,{skipEmpty:o}=s,{input:r,delimiter:i}=t;if(r.dtype!=="string")throw new Error("Input must be of datatype string");if(r.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${r.shape}`);if(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);const a=e.readSync(r.dataId),c=e.readSync(i.dataId)[0],[l,u,d]=Ez(a,c,o),h=u.length;return[e.makeTensorInfo([h,2],"int32",l),e.makeTensorInfo([h],"string",u),e.makeTensorInfo([2],"int32",new Int32Array(d))]}const SH={kernelName:Vf,backendName:"webgl",kernelFunc:vH};/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function kH(n){const{inputs:t,backend:e,attrs:s}=n,{numBuckets:o}=s,{input:r}=t;if(r.dtype!=="string")throw new Error("Input must be of datatype string");if(o<=0)throw new Error("Number of buckets must be at least 1");const i=e.readSync(r.dataId),a=Dz(i,o);return e.makeTensorInfo(r.shape,"int32",a)}const TH={kernelName:Ff,backendName:"webgl",kernelFunc:kH};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const NH=Tt({opSnippet:"return tan(x);"}),RH={kernelName:fi,backendName:"webgl",kernelFunc:NH};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const $H=Tt({opSnippet:`
  float e2x = exp(-2.0 * abs(x));
  return sign(x) * (1.0 - e2x) / (1.0 + e2x);
`}),GH={kernelName:mi,backendName:"webgl",kernelFunc:$H};/**
 * @license
 * Copyright 2022 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function LH(n){const{inputs:t,backend:e,attrs:s}=n,{tensor:o,indices:r,updates:i}=t,{sliceRank:a,numUpdates:c,sliceSize:l,strides:u,outputSize:d}=co(i,r,o.shape),h=[d/l,l];if(d===0)return e.makeTensorInfo(o.shape,r.dtype);const p=tt({inputs:{x:r},backend:e,attrs:{shape:[c,a]}}),f=tt({inputs:{x:i},backend:e,attrs:{shape:[c,l]}}),m=tt({inputs:{x:o},backend:e,attrs:{shape:h}}),g=new zp(c,a,p.shape.length,f.shape.length,u,h,!1,!0),b=e.runWebGLProgram(g,[f,p,m],m.dtype),x=tt({inputs:{x:b},backend:e,attrs:{shape:o.shape}});return e.disposeIntermediateTensorInfo(p),e.disposeIntermediateTensorInfo(f),e.disposeIntermediateTensorInfo(m),e.disposeIntermediateTensorInfo(b),x}const EH={kernelName:Rf,backendName:"webgl",kernelFunc:LH};/**
 * @license
 * Copyright 2017 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class DH{constructor(t,e){this.variableNames=["A"];const s=new Array(t.length);for(let i=0;i<s.length;i++)s[i]=t[i]*e[i];this.outputShape=s,this.rank=s.length;const o=Wt(this.rank),r=WH(t);this.userCode=`
      void main() {
        ${o} resRC = getOutputCoords();
        setOutput(getA(${r}));
      }
    `}}function WH(n){const t=n.length;if(t>5)throw Error(`Tile for rank ${t} is not yet supported`);if(t===1)return`imod(resRC, ${n[0]})`;const e=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],s=[];for(let o=0;o<n.length;o++)s.push(`imod(${e[o]}, ${n[o]})`);return s.join()}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function CI(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{reps:r}=s;if(o.dtype==="string"||o.shape.length>5){const c=e.readSync(o.dataId),l=o.dtype==="string"?c.map(h=>xs(h)):c,u=wt(o.shape,o.dtype,l),d=Mz(u,r);return e.makeTensorInfo(d.shape,d.dtype,d.values)}const i=new DH(o.shape,r);return e.runWebGLProgram(i,[o],o.dtype)}const MH={kernelName:gi,backendName:"webgl",kernelFunc:CI};class VH{constructor(t){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=t,this.userCode=`
       void main() {
         ivec2 coords = getOutputCoords();
         int batch = coords[0];
         int elemIdx = coords[1];

         // We compare elements pair-wise within a group of size 2 * inc.
         // The comparing rule for each group alternates between ascending
         // and descending. Within each group, we compare each pair at
         // positions i and i+inc. To decide whether an element at position i
         // is x0 or x1, we mod it by 2 * inc, if the result is smaller than
         // inc, it is in the first half of the group, we denote it as x0,
         // otherwise we denote it as x1.
         // For example, as shown in the Bitonic top K paper referenced above,
         // Figure5(a) shows that element[1] is in the
         // second half of the group when group size is 2, but it is in the
         // first half of the group when group size is 4.

         bool isFirstInPair = imod(elemIdx, 2 * inc) < inc;
         int i = isFirstInPair ? elemIdx : elemIdx - inc;

         int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
         int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc));
         float x0 = i0 < n ? getX(batch, i0) : negativeInf;
         float x1 = i1 < n ? getX(batch, i1) : negativeInf;

         // Denotes which direction indices are in (ascending or descending).
         bool reverse = imod(elemIdx, 2 * dir) >= dir;
         bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0);
         if (reverse == isGreater) { // Elements in opposite order of direction
           int iTemp = i0;
           i0 = i1;
           i1 = iTemp;
         }
         if (isFirstInPair) {
            setOutput(float(i0));
         } else {
            setOutput(float(i1));
         }
       }
     `}}class FH{constructor(t){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=t,this.userCode=`
    void main() {
         // Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...
         ivec2 coords = getOutputCoords();
         int batch = coords[0];
         int elemIdx = coords[1];

         // The output size is half of the previous size.
         // If the previous sequence is | | | | _ _ _ _  | | | |  _ _ _ _ (k=4),
         // we only need to output the indices at positions |, the indices at
         // positions _ can be thrown away, see Figure5(b) After Phase 2
         // (Merge phase) in the Bitonic Top K paper referenced above.
         // For example, the paper shows we only need to output the orange bars.
         // The output sequence should look like this | | | | | | | |.
         // Because the sequence is halved, to map the output index back
         // to the previous sequence to find the corresponding value,
         // we need to double the index. When we double the index,
         // we basically interpolate a position, so 2i looks like
         // | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position
         // of each 2k positions by - elemIdx % k. E.g. for output at
         // index 4,5,6,7, we want to get the corresponding element at
         // original index 8,9,10,11, for output at index 8,9,10,11,
         // we want to get the corresponding element at original index
         // 16,17,18,19, so on and so forth.

         int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k));
         int i0 = firstPass == 1 ? i : int(getIndices(batch, i));
         int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k));

         float x0 = getX(batch, i0);
         float x1 = i1 < n ? getX(batch, i1) : x0;

         setOutput(x0 >= x1 ? float(i0) : float(i1));
       }
     `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function Ro(n,t){t!==null&&n.disposeIntermediateTensorInfo(t)}function vI(n){let t=1;for(;t<n;)t*=2;return t}function zH(n){const{inputs:t,backend:e,attrs:s}=n,{x:o}=t,{k:r,sorted:i}=s,a=z().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),c=z().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),l=o.shape,u=l[l.length-1];if(e.shouldExecuteOnCPU([o])||u<a||r>c){const R=e.readSync(o.dataId),[L,V]=Vz(R,l,o.dtype,r,i);return[e.makeTensorInfo(L.shape,L.dtype,L.values),e.makeTensorInfo(V.shape,V.dtype,V.values)]}if(r===0)return l[l.length-1]=0,[e.makeTensorInfo(l,o.dtype,[]),e.makeTensorInfo(l,"int32",[])];if(u===1)return[o,ha({attrs:{shape:l,dtype:"int32",value:0},backend:e})];const d=e.texData.get(o.dataId),h=d!==null&&d.isPacked,p=h?e.unpackTensor(o):o,m=Z(l)/u,g=tt({inputs:{x:p},attrs:{shape:[m,u]},backend:e});h&&Ro(e,p);const b=vI(r),x=vI(u);let I=null;const y=()=>I===null?[g,g]:[g,I],w=(R,L,V)=>{const F=y(),X=new VH(V),P=[[u],[I===null?1:0],[Number.NEGATIVE_INFINITY],[R],[L]],B=I;I=e.runWebGLProgram(X,F,"int32",P),Ro(e,B)};for(let R=1;R<b;R*=2){const L=R*2;for(let V=R;V>=1;V/=2)w(L,V,[m,x])}for(let R=x;R>b;R/=2){const L=y(),V=new FH([m,R/2]),X=[[u],[I===null?1:0],[b]],A=I;I=e.runWebGLProgram(V,L,"int32",X),Ro(e,A);const P=b/2,B=P*2;for(let K=P;K>=1;K/=2)w(B,K,I.shape)}let C=I;I=xr({inputs:{x:I},backend:e,attrs:{begin:0,size:[m,r]}}),Ro(e,C);let k=dI({inputs:{x:g,indices:I},backend:e,attrs:{axis:1,batchDims:1}});Ro(e,g);const S=l.slice(0,-1);S.push(r),C=I,I=tt({inputs:{x:I},attrs:{shape:S},backend:e}),Ro(e,C);const T=k;return k=tt({inputs:{x:k},attrs:{shape:S},backend:e}),Ro(e,T),[k,I]}const XH={kernelName:Pu,backendName:"webgl",kernelFunc:zH};/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class AH{constructor(t,e,s,o,r,i){this.variableNames=["Image","Transforms"],this.outputShape=i;const a=s==="nearest"?1:2;let c;switch(o){case"constant":c=1;break;case"reflect":c=2;break;case"wrap":c=3;break;case"nearest":c=4;break;default:c=1;break}this.userCode=`
            float mapCoord(float outCoord, float len) {
              float inCoord = outCoord;
              if(${c} == 2) {
                if (inCoord < 0.0) {
                  if (len <= 1.0) {
                    inCoord = 0.0;
                  } else {
                    float sz2 = 2.0 * len;
                    if (inCoord < sz2) {
                      inCoord = sz2 * float(int(float(-inCoord / sz2))) +
                      inCoord;
                    }
                    inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;
                  }
                } else if (inCoord > len - 1.0) {
                  if (len <= 1.0) {
                    inCoord = 0.0;
                  } else {
                    float sz2 = 2.0 * len;
                    inCoord -= sz2 * float(int(float(inCoord / sz2)));
                    if (inCoord >= len) {
                      inCoord = sz2 - inCoord - 1.0;
                    }
                  }
                }
                return clamp(inCoord, 0.0, len - 1.0);
              } else if (${c} == 3) {
                if (inCoord < 0.0) {
                  if (len <= 1.0) {
                    inCoord = 0.0;
                  } else {
                    float sz = len - 1.0;
                    inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);
                  }
                } else if (inCoord > len - 1.0) {
                  if (len <= 1.0) {
                    inCoord = 0.0;
                  } else {
                    float sz = len - 1.0;
                    inCoord -= len * float(int(float(inCoord / sz)));
                  }
                }
                return clamp(inCoord, 0.0, len - 1.0);
              } else if (${c} == 4) {
                return clamp(outCoord, 0.0, len - 1.0);
              } else {
                return outCoord;
              }
            }

            float readWithFillValue(int batch, int coordY, int coordX,
              int channel) {
              float outputValue;
              if (0 <= coordY && coordY < ${t} && 0 <= coordX && coordX < ${e}) {
                  outputValue = getImage(batch, coordY, coordX, channel);
              } else {
                outputValue = float(${r});
              }
              return outputValue;
            }

            void main() {
              ivec4 coords = getOutputCoords();
              float outputValue;
              int batch = coords[0];
              int x = coords[2];
              int y = coords[1];
              int channel = coords[3];
              float xf = float(x);
              float yf = float(y);
              float a1 = getTransforms(batch, 0);
              float a2 = getTransforms(batch, 1);
              float a3 = getTransforms(batch, 2);
              float b1 = getTransforms(batch, 3);
              float b2 = getTransforms(batch, 4);
              float b3 = getTransforms(batch, 5);
              float c1 = getTransforms(batch, 6);
              float c2 = getTransforms(batch, 7);
              float projection = c1 * xf + c2 * yf + 1.0;
              if (projection == 0.0) {
                outputValue = float(${r});
              } else {
                float inX = (a1 * xf + a2 * yf + a3) / projection;
                float inY = (b1 * xf + b2 * yf + b3) / projection;
                float mapX = mapCoord(inX, float(${e}));
                float mapY = mapCoord(inY, float(${t}));

                if (${a} == 1) {
                  int coordY = int(round(mapY));
                  int coordX = int(round(mapX));
                  outputValue = readWithFillValue(batch, coordY, coordX,
                    channel);
                } else {
                  float yFloor = floor(mapY);
                  float xFloor = floor(mapX);
                  float yCeil = yFloor + 1.0;
                  float xCeil = xFloor + 1.0;
                  float valueYFloor = (xCeil - mapX) *
                  readWithFillValue(batch, int(yFloor), int(xFloor), channel) +
                  (mapX - xFloor) *
                  readWithFillValue(batch, int(yFloor), int(xCeil), channel);
                  float valueYCeil = (xCeil - mapX) *
                  readWithFillValue(batch, int(yCeil), int(xFloor), channel) +
                  (mapX - xFloor) *
                  readWithFillValue(batch, int(yCeil), int(xCeil), channel);
                  outputValue = (yCeil - mapY) * valueYFloor +
                  (mapY - yFloor) * valueYCeil;
                }
              }
              setOutput(outputValue);
            }
        `}}/**
 * @license
 * Copyright 2021 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function PH(n){const{inputs:t,backend:e,attrs:s}=n,{image:o,transforms:r}=t,{interpolation:i,fillMode:a,fillValue:c,outputShape:l}=s,[u,d,h,p]=o.shape,[f,m]=l??[d,h],g=[u,f,m,p],b=new AH(d,h,i,a,c,g);return e.runWebGLProgram(b,[o,r],"float32")}const OH={kernelName:Ou,backendName:"webgl",kernelFunc:PH};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function KH(n){const{inputs:t,attrs:e,backend:s}=n,{axis:o}=e,{x:r}=t;ra(r,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const i=s.readSync(r.dataId),{outputValues:a,outputShape:c,indices:l}=Fz(i,o,r.shape,r.dtype);return[s.makeTensorInfo(c,r.dtype,a),s.makeTensorInfo([l.length],"int32",l)]}const ZH={kernelName:Ku,backendName:"webgl",kernelFunc:KH};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function BH(n){const{inputs:t,backend:e,attrs:s}=n,{value:o}=t;let{axis:r}=s;r<0&&(r+=o.shape.length);const i=o,a=i.shape.length,c=o.shape[r],l=new Array(a-1);let u=0;for(let m=0;m<a;m++)m!==r&&(l[u++]=i.shape[m]);const d=[],h=new Array(a).fill(0),p=i.shape.slice();p[r]=1;const f=new Array(c);for(let m=0;m<f.length;m++){h[r]=m;const g=xr({inputs:{x:i},backend:e,attrs:{begin:h,size:p}}),b=tt({inputs:{x:g},backend:e,attrs:{shape:l}});f[m]=b,d.push(g)}return d.forEach(m=>e.disposeIntermediateTensorInfo(m)),f}const HH={kernelName:gc,backendName:"webgl",kernelFunc:BH};/**
 * @license
 * Copyright 2018 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */class _H{constructor(t,e){this.variableNames=["x","segmentIds"];const s=t.windowSize,o=t.batchSize,r=t.inSize,i=t.numSegments,a=i*Math.ceil(r/s);this.outputShape=[o,a];const c="0.0",l="sumValue",u=Math.floor(s/4)*4,d=s%4,h=`
        sumValue += dot(values, segFilter);
    `;let p="";r%s>0&&(p=`
        if (inIdx < 0 || inIdx >= ${r}) {
          return initializationValue;
        }
      `);let f="";r%s>0&&(f=`
        if (inIdx < 0 || inIdx >= ${r}) {
          return -1.0;
        }
      `),this.userCode=`
      const float initializationValue = ${c};

      float getValue(int batch, int inIdx) {
        ${p}
        return getX(batch, inIdx);
      }

      float getSegmentIdAtIndex(int inIdx) {
        ${f}
        return getSegmentIds(inIdx);
      }

      void main() {
        ivec2 coords = getOutputCoords();
        int batch = coords[0];
        int outIdx = coords[1];
        int inOffset = int(floor(float(outIdx) / float(
          ${i})) * float(${s}));
        int currentSeg = int(mod(float(outIdx), float(${i})));

        float sumValue = 0.0;

        for (int i = 0; i < ${u}; i += 4) {
          int inIdx = inOffset + i;
          vec4 values = vec4(
            getValue(batch, inIdx),
            getValue(batch, inIdx + 1),
            getValue(batch, inIdx + 2),
            getValue(batch, inIdx + 3)
          );

          vec4 segFilter = vec4(
            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
            int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
            int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
          );

          ${h}
        }

        int inIdx = inOffset + ${u};
        if (${d===1}) {
          vec4 values = vec4(
            getValue(batch, inIdx),
            initializationValue,
            initializationValue,
            initializationValue
          );

          int inIdxSeg = int(getSegmentIdAtIndex(inIdx));

          vec4 segFilter = vec4(
            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
            0,
            0,
            0
          );

          ${h}
        } else if (${d===2}) {
          vec4 values = vec4(
            getValue(batch, inIdx),
            getValue(batch, inIdx + 1),
            initializationValue,
            initializationValue
          );

          vec4 segFilter = vec4(
            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
              0,
              0
          );

          ${h}
        } else if (${d===3}) {
          vec4 values = vec4(
            getValue(batch, inIdx),
            getValue(batch, inIdx + 1),
            getValue(batch, inIdx + 2),
            initializationValue
          );

          vec4 segFilter = vec4(
            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
            int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
            0
          );

          ${h}
        }
        setOutput(${l});
      }
    `}}/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */function UH(n){const{inputs:t,backend:e,attrs:s}=n,{x:o,segmentIds:r}=t,{numSegments:i}=s,a=o.shape.length,c=[];let l=0;const u=Yt([l],a);let d=o;u!=null&&(d=Me({inputs:{x:o},backend:e,attrs:{perm:u}}),c.push(d),l=ee(1,a)[0]);const h=Qg(d.shape,l,i),p=Z([d.shape[l]]),f=tt({inputs:{x:d},backend:e,attrs:{shape:[-1,p]}});c.push(f);const m=nd(o.dtype),g=(y,w,C,k,S)=>{const T=y.shape[0],R=y.shape[1],L=Yg(R,S),V={windowSize:L,inSize:R,batchSize:T,numSegments:S},F=new _H(V,w),X=e.compileAndRun(F,[y,C],k);if(c.push(X),X.shape[1]===S)return X;const A=yI({backend:e,attrs:{start:0,stop:S,step:1,dtype:"float32"}}),P=CI({inputs:{x:A},backend:e,attrs:{reps:[R/L]}});return c.push(A),c.push(P),g(X,w,P,k,S)},b=g(f,"unsortedSegmentSum",r,m,i),x=tt({inputs:{x:b},backend:e,attrs:{shape:h}});let I=x;if(u!=null){c.push(x);const y=Cs(u);I=Me({inputs:{x:I},backend:e,attrs:{perm:y}})}return c.forEach(y=>e.disposeIntermediateTensorInfo(y)),I}const YH={kernelName:bc,backendName:"webgl",kernelFunc:UH};/**
 * @license
 * Copyright 2020 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */const QH=[RX,GX,DX,VX,zX,PX,KX,BX,YX,JX,tA,sA,iA,uA,pA,mA,bA,wA,vA,kA,RA,WA,VA,AA,OA,_A,YA,qA,dX,nP,aP,dP,bP,IP,CP,SP,TP,GP,EP,WP,VP,zP,AP,KP,BP,YP,JP,tO,sO,rO,aO,uO,hO,mO,bO,xO,IO,CO,SO,TO,RO,GO,DO,VO,zO,PO,ZO,HO,UO,uX,QO,rP,jO,tK,nK,pX,oK,iK,cK,dK,fK,gK,xK,IK,vK,kK,NK,LK,DK,MK,XK,PK,KK,BK,_K,JK,tZ,oZ,uZ,gX,fZ,bZ,IZ,vZ,KA,kZ,NZ,$Z,EZ,VZ,mX,zZ,AZ,OZ,ZZ,BZ,ZA,iZ,_Z,QZ,qZ,xX,sB,iB,uB,pB,bB,yB,wB,vB,TB,$B,EB,MB,zB,AB,ZB,HB,DA,cZ,UB,YB,JB,qB,eH,sH,rH,aH,lH,dH,pH,mH,bH,IH,CH,SH,TH,aZ,kX,RH,GH,EH,MH,XH,OH,TX,ZH,HH,YH,TZ];for(const n of QH)qe(n);const SI="[encoded data, 88420 characters]",kI=typeof window<"u"&&window.Blob&&new Blob([atob(SI)],{type:"text/javascript;charset=utf-8"});function JH(n){let t;try{if(t=kI&&(window.URL||window.webkitURL).createObjectURL(kI),!t)throw"";const e=new Worker(t,{name:n==null?void 0:n.name});return e.addEventListener("error",()=>{(window.URL||window.webkitURL).revokeObjectURL(t)}),e}catch{return new Worker("data:application/javascript;base64,"+SI,{name:n==null?void 0:n.name})}finally{t&&(window.URL||window.webkitURL).revokeObjectURL(t)}}const jH=(n,t)=>[[n[0][0]*t[0][0]+n[0][2]*t[2][0],n[0][0]*t[0][1]+n[0][2]*t[2][1],n[0][0]*t[0][2]+n[0][2]*t[2][2],n[0][0]*t[0][3]+n[0][2]*t[2][3]],[n[1][1]*t[1][0]+n[1][2]*t[2][0],n[1][1]*t[1][1]+n[1][2]*t[2][1],n[1][1]*t[1][2]+n[1][2]*t[2][2],n[1][1]*t[1][3]+n[1][2]*t[2][3]],[t[2][0],t[2][1],t[2][2],t[2][3]]],qH=(n,t,e,s)=>{const o=n[0][0]*t+n[0][1]*e+n[0][3],r=n[1][0]*t+n[1][1]*e+n[1][3],i=n[2][0]*t+n[2][1]*e+n[2][3];return{x:o,y:r,z:i}},t9=(n,t,e,s)=>{const{x:o,y:r,z:i}=qH(n,t,e);return{x:o/i,y:r/i}},e9=6,n9=1,s9=10,o9=1,r9=.8,i9=1,qn=1e3;class a9{constructor(t,e,s,o,r,i=!1){this.markerDimensions=t,this.trackingDataList=e,this.projectionTransform=s,this.debugMode=i,this.trackingKeyframeList=[];for(let c=0;c<e.length;c++)this.trackingKeyframeList.push(e[c][i9]);let a=0;for(let c=0;c<this.trackingKeyframeList.length;c++)a=Math.max(a,this.trackingKeyframeList[c].points.length);this.featurePointsListT=[],this.imagePixelsListT=[],this.imagePropertiesListT=[];for(let c=0;c<this.trackingKeyframeList.length;c++){const{featurePoints:l,imagePixels:u,imageProperties:d}=this._prebuild(this.trackingKeyframeList[c],a);this.featurePointsListT[c]=l,this.imagePixelsListT[c]=u,this.imagePropertiesListT[c]=d}this.kernelCaches={}}dummyRun(t){let e=[[1,1,1,1],[1,1,1,1],[1,1,1,1]];for(let s=0;s<this.featurePointsListT.length;s++)this.track(t,e,s)}track(t,e,s){let o={};const r=jH(this.projectionTransform,e),i=this._buildAdjustedModelViewTransform(r);this.markerDimensions[s][0],this.markerDimensions[s][1],this.trackingKeyframeList[s].width,this.trackingKeyframeList[s].height;const a=this.featurePointsListT[s],c=this.imagePixelsListT[s],l=this.imagePropertiesListT[s],u=this._computeProjection(i,t,s),{matchingPointsT:d,simT:h}=this._computeMatching(a,c,l,u),p=d.arraySync(),f=h.arraySync(),m=this.trackingKeyframeList[s],g=[],b=[],x=[];for(let I=0;I<p.length;I++)if(f[I]>r9&&I<m.points.length){x.push(I);const y=t9(r,p[I][0],p[I][1]);b.push(y),g.push({x:m.points[I].x/m.scale,y:m.points[I].y/m.scale,z:0})}return this.debugMode&&(o={projectedImage:u.arraySync(),matchingPoints:d.arraySync(),goodTrack:x,trackedPoints:b}),i.dispose(),u.dispose(),d.dispose(),h.dispose(),{worldCoords:g,screenCoords:b,debugExtra:o}}_computeMatching(t,e,s,o){const r=e9,i=r*2+1,c=s9*n9,l=o9,u=c*2+1,d=o.shape[0],h=o.shape[1],p=t.shape[0];if(!this.kernelCaches.computeMatching){const f={variableNames:["features","markerPixels","markerProperties","targetPixels"],outputShape:[p,u*u],userCode:`
	  void main() {
	    ivec2 coords = getOutputCoords();

	    int featureIndex = coords[0];
	    int searchOffsetIndex = coords[1];

	    int markerWidth = int(getMarkerProperties(0));
	    int markerHeight = int(getMarkerProperties(1));
	    float markerScale = getMarkerProperties(2);

	    int searchOffsetX = imod(searchOffsetIndex, ${u}) * ${l};
	    int searchOffsetY = searchOffsetIndex / ${u} * ${l};

	    int sCenterX = int(getFeatures(featureIndex, 0) * markerScale);
	    int sCenterY = int(getFeatures(featureIndex, 1) * markerScale);

	    int sx = sCenterX + searchOffsetX - ${c};
	    int sy = sCenterY + searchOffsetY - ${c};

	    if (sx < ${r} || sx >= (${h} - ${r}) || sy < ${r} || sy >= (${d} - ${r})) {
	      setOutput(-2.);
	    } 
	    else {
	      float sumPoint = 0.;
	      float sumPointSquare = 0.;
	      float sumTemplate = 0.;
	      float sumTemplateSquare = 0.;
	      float sumPointTemplate = 0.;

	      for (int templateOffsetY = 0; templateOffsetY < ${i}; templateOffsetY++) {
		for (int templateOffsetX = 0; templateOffsetX < ${i}; templateOffsetX++) {
		  int fx2 = sCenterX + templateOffsetX - ${r};
		  int fy2 = sCenterY + templateOffsetY - ${r};

		  int sx2 = sx + templateOffsetX - ${r};
		  int sy2 = sy + templateOffsetY - ${r};

		  int markerPixelIndex = fy2 * markerWidth + fx2;
		  float markerPixel = getMarkerPixels(markerPixelIndex);
		  float targetPixel = getTargetPixels(sy2, sx2);

		  sumTemplate += markerPixel;
		  sumTemplateSquare += markerPixel * markerPixel;
		  sumPoint += targetPixel;
		  sumPointSquare += targetPixel * targetPixel;
		  sumPointTemplate += targetPixel * markerPixel;
		}
	      }

	      // Normalized cross-correlation
	      // !important divide first avoid overflow (e.g. sumPoint / count * sumPoint)
	      float count = float(${i} * ${i});
	      float pointVariance = sqrt(sumPointSquare - sumPoint / count * sumPoint);
	      float templateVariance = sqrt(sumTemplateSquare - sumTemplate / count * sumTemplate);

	      if (pointVariance < 0.0000001) {
		setOutput(-3.);
	      } else if (templateVariance < 0.0000001) {
		//setOutput(sumTemplate);
		setOutput(-4.);
	      } else {
		sumPointTemplate -= sumPoint / count * sumTemplate;
		float sim = sumPointTemplate / pointVariance / templateVariance;  
		setOutput(sim);
	      }
	    }
	  }
	`},m={variableNames:["featurePoints","markerProperties","maxIndex"],outputShape:[p,2],userCode:`
	  void main() {
	    ivec2 coords = getOutputCoords();

	    float markerScale = getMarkerProperties(2);

	    int featureIndex = coords[0];

	    int maxIndex = int(getMaxIndex(featureIndex));
	    int searchLocationIndex = maxIndex / ${u*u};
	    int searchOffsetIndex = imod(maxIndex, ${u*u});

	    if (coords[1] == 0) {
	      int searchOffsetX = imod(searchOffsetIndex, ${u}) * ${l};
	      setOutput(getFeaturePoints(featureIndex, 0) + float(searchOffsetX - ${c}) / markerScale);
	    }
	    else if (coords[1] == 1) {
	      int searchOffsetY = searchOffsetIndex / ${u} * ${l};
	      setOutput(getFeaturePoints(featureIndex, 1) + float(searchOffsetY - ${c}) / markerScale);
	    }
	  }
	`},g={variableNames:["sims","maxIndex"],outputShape:[p],userCode:`
	  void main() {
	    int featureIndex = getOutputCoords();
	    int maxIndex = int(getMaxIndex(featureIndex));
	    setOutput(getSims(featureIndex, maxIndex));
	  }
	`};this.kernelCaches.computeMatching=[f,m,g]}return M(()=>{const f=this.kernelCaches.computeMatching,m=this._compileAndRun(f[0],[t,e,s,o]),g=m.argMax(1),b=this._compileAndRun(f[1],[t,s,g]),x=this._compileAndRun(f[2],[m,g]);return{matchingPointsT:b,simT:x}})}_computeProjection(t,e,s){const o=this.trackingKeyframeList[s].width,r=this.trackingKeyframeList[s].height,i=this.trackingKeyframeList[s].scale,a=o+"-"+r+"-"+i;if(this.kernelCaches.computeProjection||(this.kernelCaches.computeProjection={}),!this.kernelCaches.computeProjection[a]){const c={variableNames:["M","pixel"],outputShape:[r,o],userCode:`
	  void main() {
	      ivec2 coords = getOutputCoords();

	      float m00 = getM(0, 0) * ${qn}.;
	      float m01 = getM(0, 1) * ${qn}.;
	      float m03 = getM(0, 3) * ${qn}.;
	      float m10 = getM(1, 0) * ${qn}.;
	      float m11 = getM(1, 1) * ${qn}.;
	      float m13 = getM(1, 3) * ${qn}.;
	      float m20 = getM(2, 0) * ${qn}.;
	      float m21 = getM(2, 1) * ${qn}.;
	      float m23 = getM(2, 3) * ${qn}.;

	      float y = float(coords[0]) / float(${i});
	      float x = float(coords[1]) / float(${i});
	      float uz = (x * m20) + (y * m21) + m23;
	      float oneOverUz = 1. / uz;

	      float ux = (x * m00) + (y * m01) + m03;
	      float uy = (x * m10) + (y * m11) + m13;

	      ux = floor(ux * oneOverUz + 0.5);
	      uy = floor(uy * oneOverUz + 0.5);
	      setOutput(getPixel(int(uy), int(ux)));
	    }
	`};this.kernelCaches.computeProjection[a]=c}return M(()=>{const c=this.kernelCaches.computeProjection[a];return this._compileAndRun(c,[t,e])})}_buildAdjustedModelViewTransform(t){return M(()=>{let e=[];for(let o=0;o<t.length;o++){e.push([]);for(let r=0;r<t[o].length;r++)e[o].push(t[o][r]/qn)}return tn(e,[3,4])})}_prebuild(t,e){return M(()=>{const s=t.scale,o=[];for(let c=0;c<e;c++)c<t.points.length?o.push([t.points[c].x/s,t.points[c].y/s]):o.push([-1,-1]);const r=tn(t.data,[t.width*t.height]),i=tn([t.width,t.height,t.scale],[3]);return{featurePoints:tn(o,[o.length,2],"float32"),imagePixels:r,imageProperties:i}})}_compileAndRun(t,e){const s=ys().compileAndRun(t,e);return zt().makeTensorFromDataId(s.dataId,s.shape,s.dtype)}}const Fl=[{sigma:.55,points:[[-1,0],[-.5,-.866025],[.5,-.866025],[1,-0],[.5,.866025],[-.5,.866025]]},{sigma:.475,points:[[0,.930969],[-.806243,.465485],[-.806243,-.465485],[-0,-.930969],[.806243,-.465485],[.806243,.465485]]},{sigma:.4,points:[[.847306,-0],[.423653,.733789],[-.423653,.733789],[-.847306,0],[-.423653,-.733789],[.423653,-.733789]]},{sigma:.325,points:[[-0,-.741094],[.641806,-.370547],[.641806,.370547],[0,.741094],[-.641806,.370547],[-.641806,-.370547]]},{sigma:.25,points:[[-.595502,0],[-.297751,-.51572],[.297751,-.51572],[.595502,-0],[.297751,.51572],[-.297751,.51572]]},{sigma:.175,points:[[0,.362783],[-.314179,.181391],[-.314179,-.181391],[-0,-.362783],[.314179,-.181391],[.314179,.181391]]},{sigma:.1,points:[[0,0]]}],$o=[];for(let n=0;n<Fl.length;n++){const t=Fl[n].sigma;for(let e=0;e<Fl[n].points.length;e++){const s=Fl[n].points[e];$o.push([t,s[0],s[1]])}}const Xp={};function c9(n){const t=n.shape[1],e=n.shape[0],s="w"+t+"h"+e;if(!Xp.hasOwnProperty(s)){const o={variableNames:["p"],outputShape:[e,t],userCode:`
        void main() {
          ivec2 coords = getOutputCoords();

          float sum = getP(coords[0], coords[1]-2);
          sum += getP(coords[0], coords[1]-1) * 4.;
          sum += getP(coords[0], coords[1]) * 6.;
          sum += getP(coords[0], coords[1]+1) * 4.;
          sum += getP(coords[0], coords[1]+2);
          setOutput(sum);
        }
      `},r={variableNames:["p"],outputShape:[e,t],userCode:`
        void main() {
          ivec2 coords = getOutputCoords();

          float sum = getP(coords[0]-2, coords[1]);
          sum += getP(coords[0]-1, coords[1]) * 4.;
          sum += getP(coords[0], coords[1]) * 6.;
          sum += getP(coords[0]+1, coords[1]) * 4.;
          sum += getP(coords[0]+2, coords[1]);
          sum /= 256.;
          setOutput(sum);
        }
      `};Xp[s]=[o,r]}return Xp[s]}const l9={kernelName:"BinomialFilter",backendName:"webgl",kernelFunc:n=>{const t=n.inputs.image,e=n.backend,[s,o]=c9(t),r=e.runWebGLProgram(s,[t],t.dtype),i=e.runWebGLProgram(o,[r],t.dtype);return e.disposeIntermediateTensorInfo(r),i}},zl=7,TI=3,u9=TI*TI,Ap=4,d9=(Ap+1)*(Ap+1)/Ap,Pp={};function h9(n){const t=n.shape[1],e=n.shape[0],s="w"+t+"h"+e;if(!Pp.hasOwnProperty(s)){const o={variableNames:["image0","image1","image2"],outputShape:[e,t],userCode:`
        void main() {
          ivec2 coords = getOutputCoords();
    
          int y = coords[0];
          int x = coords[1];
    
          float value = getImage1(y, x);
    
          // Step 1: find local maxima/minima
          if (value * value < ${u9}.) {
            setOutput(0.);
            return;
          }
          if (y < ${zl} || y > ${e-1-zl}) {
            setOutput(0.);
            return;
          }
          if (x < ${zl} || x > ${t-1-zl}) {
            setOutput(0.);
            return;
          }
    
          bool isMax = true;
          bool isMin = true;
          for (int dy = -1; dy <= 1; dy++) {
            for (int dx = -1; dx <= 1; dx++) {
              float value0 = getImage0(y+dy, x+dx);
              float value1 = getImage1(y+dy, x+dx);
              float value2 = getImage2(y+dy, x+dx);
    
        if (value < value0 || value < value1 || value < value2) {
          isMax = false;
        }
        if (value > value0 || value > value1 || value > value2) {
          isMin = false;
        }
            }
          }
    
          if (!isMax && !isMin) {
            setOutput(0.);
            return;
          }
    
          // compute edge score and reject based on threshold
          float dxx = getImage1(y, x+1) + getImage1(y, x-1) - 2. * getImage1(y, x);
          float dyy = getImage1(y+1, x) + getImage1(y-1, x) - 2. * getImage1(y, x);
          float dxy = 0.25 * (getImage1(y-1,x-1) + getImage1(y+1,x+1) - getImage1(y-1,x+1) - getImage1(y+1,x-1));
    
          float det = (dxx * dyy) - (dxy * dxy);
    
          if (abs(det) < 0.0001) { // determinant undefined. no solution
            setOutput(0.);
            return;
          }
    
          float edgeScore = (dxx + dyy) * (dxx + dyy) / det;
    
          if (abs(edgeScore) >= ${d9} ) {
            setOutput(0.);
            return;
          }
          setOutput(getImage1(y,x));
        }
      `};Pp[s]=o}return Pp[s]}const p9={kernelName:"BuildExtremas",backendName:"webgl",kernelFunc:n=>{let{image0:t,image1:e,image2:s}=n.inputs;const o=n.backend,r=h9(e);return t=zt().runKernel("DownsampleBilinear",{image:t}),s=zt().runKernel("UpsampleBilinear",{image:s,targetImage:e}),o.runWebGLProgram(r,[t,e,s],e.dtype)}},pa=36,Op={};function f9(n){const t=n.shape[0];if(!Op.hasOwnProperty(t)){const e={variableNames:["histogram"],outputShape:[n.shape[0]],userCode:`
            void main() {
                int featureIndex = getOutputCoords();

                int maxIndex = 0;
                for (int i = 1; i < ${pa}; i++) {
                    if (getHistogram(featureIndex, i) > getHistogram(featureIndex, maxIndex)) {
                        maxIndex = i;
                    }
                }

                int prev = imod(maxIndex - 1 + ${pa}, ${pa});
                int next = imod(maxIndex + 1, ${pa});

                /**
                 * Fit a quatratic to 3 points. The system of equations is:
                 *
                 * y0 = A*x0^2 + B*x0 + C
                 * y1 = A*x1^2 + B*x1 + C
                 * y2 = A*x2^2 + B*x2 + C
                 *
                 * This system of equations is solved for A,B,C.
                 */
                float p10 = float(maxIndex - 1);
                float p11 = getHistogram(featureIndex, prev); 
                float p20 = float(maxIndex);
                float p21 = getHistogram(featureIndex, maxIndex); 
                float p30 = float(maxIndex + 1);
                float p31 = getHistogram(featureIndex, next); 

                float d1 = (p30-p20)*(p30-p10);
                float d2 = (p10-p20)*(p30-p10);
                float d3 = p10-p20;

                // If any of the denominators are zero then, just use maxIndex.
                    float fbin = float(maxIndex);
                if ( abs(d1) > 0.00001 && abs(d2) > 0.00001 && abs(d3) > 0.00001) {
                float a = p10*p10;
                float b = p20*p20;

                // Solve for the coefficients A,B,C
                float A = ((p31-p21)/d1)-((p11-p21)/d2);
                float B = ((p11-p21)+(A*(b-a)))/d3;
                float C = p11-(A*a)-(B*p10);
                fbin = -B / (2. * A);
                }

                float an = 2.0 *${Math.PI} * (fbin + 0.5) / ${pa}. - ${Math.PI};
                setOutput(an);
            }
            `};Op[t]=e}return Op[t]}const m9={kernelName:"ComputeExtremaAngles",backendName:"webgl",kernelFunc:n=>{const{histograms:t}=n.inputs,e=n.backend,s=f9(t);return e.runWebGLProgram(s,[t],t.dtype)}},NI=7,Kp={};function g9(n,t){const e=`${n}|${t.shape[0]}`;if(!Kp.hasOwnProperty(e)){const s=[];for(let i=1;i<n;i++)s.push("image"+i);let o="float getPixel(int octave, int y, int x) {";for(let i=1;i<n;i++)o+=`
  if (octave == ${i}) {
	return getImage${i}(y, x);
  }
`;o+="}";const r={variableNames:[...s,"extrema","angles","freakPoints"],outputShape:[t.shape[0],$o.length],userCode:`
  ${o}
  void main() {
	ivec2 coords = getOutputCoords();
	int featureIndex = coords[0];
	int freakIndex = coords[1];

	float freakSigma = getFreakPoints(freakIndex, 0);
	float freakX = getFreakPoints(freakIndex, 1);
	float freakY = getFreakPoints(freakIndex, 2);

	int octave = int(getExtrema(featureIndex, 1));
	float inputY = getExtrema(featureIndex, 2);
	float inputX = getExtrema(featureIndex, 3);
	float inputAngle = getAngles(featureIndex);
	float cos = ${NI}. * cos(inputAngle);
	float sin = ${NI}. * sin(inputAngle);

	float yp = inputY + freakX * sin + freakY * cos;
	float xp = inputX + freakX * cos + freakY * -sin;

	int x0 = int(floor(xp));
	int x1 = x0 + 1;
	int y0 = int(floor(yp));
	int y1 = y0 + 1;

	float f1 = getPixel(octave, y0, x0);
	float f2 = getPixel(octave, y0, x1);
	float f3 = getPixel(octave, y1, x0);
	float f4 = getPixel(octave, y1, x1);

	float x1f = float(x1);
	float y1f = float(y1);
	float x0f = float(x0);
	float y0f = float(y0);

	// ratio for interpolation between four neighbouring points
	float value = (x1f - xp) * (y1f - yp) * f1
		+ (xp - x0f) * (y1f - yp) * f2
		+ (x1f - xp) * (yp - y0f) * f3
		+ (xp - x0f) * (yp - y0f) * f4;

	setOutput(value);
  }
`};Kp[e]=r}return Kp[e]}const b9={kernelName:"ComputeExtremaFreak",backendName:"webgl",kernelFunc:n=>{const{gaussianImagesT:t,prunedExtremas:e,prunedExtremasAngles:s,freakPointsT:o,pyramidImagesLength:r}=n.inputs,i=n.backend,a=g9(r,e);return i.runWebGLProgram(a,[...t,e,s,o],"float32")}},RI=($o.length-1)*$o.length/2,x9=Math.ceil(RI/8),Zp={};function y9(n){const t=`${n.shape[0]}`;if(!Zp.hasOwnProperty(t)){const e={variableNames:["freak","p"],outputShape:[n.shape[0],x9],userCode:`
  void main() {
    ivec2 coords = getOutputCoords();
    int featureIndex = coords[0];
    int descIndex = coords[1] * 8;

    int sum = 0;
    for (int i = 0; i < 8; i++) {
      if (descIndex + i >= ${RI}) {
        continue;
      }

      int p1 = int(getP(descIndex + i, 0));
      int p2 = int(getP(descIndex + i, 1));

      float v1 = getFreak(featureIndex, p1);
      float v2 = getFreak(featureIndex, p2);

      if (v1 < v2 + 0.01) {
        sum += int(pow(2.0, float(7 - i)));
      }
    }
    setOutput(float(sum));
  }
`};Zp[t]=e}return Zp[t]}const I9={kernelName:"ComputeFreakDescriptors",backendName:"webgl",kernelFunc:n=>{const{extremaFreaks:t,positionT:e}=n.inputs,{backend:s}=n,o=y9(t);return s.runWebGLProgram(o,[t,e],"int32")}},Bp={};function w9(n,t){const e=`${n}|${t}`;if(!Bp.hasOwnProperty(e)){const s=[];let o="float getPixel(int octave, int y, int x) {";for(let r=1;r<n;r++)s.push("image"+r),o+=`
				if (octave == ${r}) {
					return getImage${r}(y, x);
				}
			`;o+="}",Bp[e]={variableNames:[...s,"extrema"],outputShape:[t,3,3],userCode:`
			${o}
		
			void main() {
				ivec3 coords = getOutputCoords();
				int featureIndex = coords[0];
				float score = getExtrema(featureIndex, 0);
				if (score == 0.0) {
					return;
				}
		
				int dy = coords[1]-1;
				int dx = coords[2]-1;
				int octave = int(getExtrema(featureIndex, 1));
				int y = int(getExtrema(featureIndex, 2));
				int x = int(getExtrema(featureIndex, 3));
				setOutput(getPixel(octave, y+dy, x+dx));
			}
			`}}return Bp[e]}const C9={kernelName:"ComputeLocalization",backendName:"webgl",kernelFunc:n=>{const{prunedExtremasList:t,dogPyramidImagesT:e}=n.inputs,s=n.backend,o=w9(e.length,t.length),r=tn(t,[t.length,t[0].length],"int32");return s.runWebGLProgram(o,[...e.slice(1),r],e[0].dtype)}},v9=.159154943091895,Ir=36,Hp={};function S9(n,t,e){const s=`${e}|${n.shape[0]}|${t.shape[0]}`;if(!Hp.hasOwnProperty(s)){const o=[];for(let c=1;c<e;c++)o.push("image"+c);let r="float getPixel(int octave, int y, int x) {";for(let c=1;c<e;c++)r+=`
            if (octave == ${c}) {
                return getImage${c}(y, x);
            }
            `;r+="}";const i={variableNames:[...o,"extrema","radial"],outputShape:[n.shape[0],t.shape[0],2],userCode:`
                ${r}

                void main() {
                    ivec3 coords = getOutputCoords();
                    int featureIndex = coords[0];
                    int radialIndex = coords[1];
                    int propertyIndex = coords[2];

                    int radialY = int(getRadial(radialIndex, 0));
                    int radialX = int(getRadial(radialIndex, 1));
                    float radialW = getRadial(radialIndex, 2);

                    int octave = int(getExtrema(featureIndex, 1));
                    int y = int(getExtrema(featureIndex, 2));
                    int x = int(getExtrema(featureIndex, 3));

                    int xp = x + radialX;
                    int yp = y + radialY;

                    float dy = getPixel(octave, yp+1, xp) - getPixel(octave, yp-1, xp);
                    float dx = getPixel(octave, yp, xp+1) - getPixel(octave, yp, xp-1);

                    if (propertyIndex == 0) {
                    // be careful that atan(0, 0) gives 1.57 instead of 0 (different from js), but doesn't matter here, coz magnitude is 0
                    
                    float angle = atan(dy, dx) + ${Math.PI};
                    float fbin = angle * ${Ir}. * ${v9};
                    setOutput(fbin);
                    return;
                    }

                    if (propertyIndex == 1) {
                        float mag = sqrt(dx * dx + dy * dy);
                        float magnitude = radialW * mag;
                        setOutput(magnitude);
                        return;
                    }
                }

                `},a={variableNames:["fbinMag"],outputShape:[n.shape[0],Ir],userCode:`
            void main() {
                ivec2 coords = getOutputCoords();
                int featureIndex = coords[0];
                int binIndex = coords[1];

                float sum = 0.;
                for (int i = 0; i < ${t.shape[0]}; i++) {
                    float fbin = getFbinMag(featureIndex, i, 0);
                    int bin = int(floor(fbin - 0.5));
                    int b1 = imod(bin + ${Ir}, ${Ir});
                    int b2 = imod(bin + 1 + ${Ir}, ${Ir});

                    if (b1 == binIndex || b2 == binIndex) {
                        float magnitude = getFbinMag(featureIndex, i, 1);
                        float w2 = fbin - float(bin) - 0.5;
                        float w1 = w2 * -1. + 1.;

                        if (b1 == binIndex) {
                            sum += w1 * magnitude;
                        }
                        if (b2 == binIndex) {
                            sum += w2 * magnitude;
                        }
                    }
                }
                setOutput(sum);
            }
            `};Hp[s]=[i,a]}return Hp[s]}const k9={kernelName:"ComputeOrientationHistograms",backendName:"webgl",kernelFunc:n=>{const{gaussianImagesT:t,prunedExtremasT:e,radialPropertiesT:s,pyramidImagesLength:o}=n.inputs,r=n.backend,[i,a]=S9(e,s,o),c=r.runWebGLProgram(i,[...t,e,s],s.dtype),l=r.runWebGLProgram(a,[c],s.dtype);return r.disposeIntermediateTensorInfo(c),l}},_p={};function T9(n){const t=n.shape[1],e=n.shape[0],s="w"+t+"h"+e;if(!_p.hasOwnProperty(s)){const o={variableNames:["p"],outputShape:[Math.floor(e/2),Math.floor(t/2)],userCode:`
            void main() {
                ivec2 coords = getOutputCoords();
                int y = coords[0] * 2;
                int x = coords[1] * 2;
        
                float sum = getP(y, x) * 0.25;
                sum += getP(y+1,x) * 0.25; 
                sum += getP(y, x+1) * 0.25; 
                sum += getP(y+1,x+1) * 0.25;
                setOutput(sum);
            }
            `};_p[s]=o}return _p[s]}const N9={kernelName:"DownsampleBilinear",backendName:"webgl",kernelFunc:n=>{const t=n.inputs.image,e=n.backend,s=T9(t);return e.runWebGLProgram(s,[t],t.dtype)}},R9={kernelName:"ExtremaReduction",backendName:"webgl",kernelFunc:n=>{const{extremasResultT:t}=n.inputs,e=n.backend,s=t.shape[0],o=t.shape[1],r={variableNames:["extrema"],outputShape:[Math.floor(s/2),Math.floor(o/2)],userCode:`
		  void main() {
			ivec2 coords = getOutputCoords();
			int y = coords[0] * 2;
			int x = coords[1] * 2;
  
			float location = 0.0;
			float values = getExtrema(y, x);
  
			if (getExtrema(y+1, x) != 0.0) {
			  location = 1.0;
		  values = getExtrema(y+1, x);
			}
			else if (getExtrema(y, x+1) != 0.0) {
			  location = 2.0;
		  values = getExtrema(y, x+1);
			}
			else if (getExtrema(y+1, x+1) != 0.0) {
			  location = 3.0;
		  values = getExtrema(y+1, x+1);
			}
  
			if (values < 0.0) {
			  setOutput(location * -1000.0 + values);
			} else {
			  setOutput(location * 1000.0 + values);
			}
		  }
		`};return e.runWebGLProgram(r,[t],t.dtype)}},Xl=36,$9=5,Up={};function G9(n){const t=`h${n.shape[0]}`;if(!Up.hasOwnProperty(t)){const e={variableNames:["histogram"],outputShape:[n.shape[0],Xl],userCode:`
            void main() {
                ivec2 coords = getOutputCoords();

                int featureIndex = coords[0];
                int binIndex = coords[1];

                int prevBin = imod(binIndex - 1 + ${Xl}, ${Xl});
                int nextBin = imod(binIndex + 1, ${Xl});
                float result = 0.274068619061197 * getHistogram(featureIndex, prevBin) + 0.451862761877606 * getHistogram(featureIndex, binIndex) + 0.274068619061197 * getHistogram(featureIndex, nextBin);

                setOutput(result);
            }
            `};Up[t]=e}return Up[t]}const L9={kernelName:"SmoothHistograms",backendName:"webgl",kernelFunc:n=>{let{histograms:t}=n.inputs;const e=n.backend,s=G9(t);for(let o=0;o<$9;o++){const r=t;t=e.runWebGLProgram(s,[t],t.dtype),o>0&&e.disposeIntermediateTensorInfo(r)}return t}},Yp={};function E9(n,t){const e=t.shape[1],s=t.shape[0],o="w"+e+"h"+s;if(!Yp.hasOwnProperty(o)){const r={variableNames:["p"],outputShape:[s,e],userCode:`
              void main() {
                ivec2 coords = getOutputCoords();
                int j = coords[0];
                int i = coords[1];
        
                float sj = 0.5 * float(j) - 0.25; 
                float si = 0.5 * float(i) - 0.25;
        
                float sj0 = floor(sj);
                float sj1 = ceil(sj);
                float si0 = floor(si);
                float si1 = ceil(si);
        
                int sj0I = int(sj0);
                int sj1I = int(sj1);
                int si0I = int(si0);
                int si1I = int(si1);
        
                float sum = 0.0;
                sum += getP(sj0I, si0I) * (si1 - si) * (sj1 - sj);
                sum += getP(sj1I, si0I) * (si1 - si) * (sj - sj0);
                sum += getP(sj0I, si1I) * (si - si0) * (sj1 - sj);
                sum += getP(sj1I, si1I) * (si - si0) * (sj - sj0);
                setOutput(sum);
              }
            `};Yp[o]=r}return Yp[o]}const D9={kernelName:"UpsampleBilinear",backendName:"webgl",kernelFunc:n=>{const{image:t,targetImage:e}=n.inputs,s=n.backend,o=E9(t,e);return s.runWebGLProgram(o,[t],t.dtype)}};qe(l9),qe(p9),qe(m9),qe(b9),qe(I9),qe(C9),qe(k9),qe(N9),qe(R9),qe(L9),qe(D9);const $I=8,W9=5,fa=10,M9=5,Qp=3,V9=1.5;($o.length-1)*$o.length/2;class GI{constructor(t,e,s=!1){this.debugMode=s,this.width=t,this.height=e;let o=0;for(;t>=$I&&e>=$I&&(t/=2,e/=2,o++,o!==W9););this.numOctaves=o,this.tensorCaches={},this.kernelCaches={}}detectImageData(t){const e=new Uint8ClampedArray(4*t.length);for(let o=0;o<t.length;o++)e[4*o]=t[o],e[4*o+1]=t[o],e[4*o+2]=t[o],e[4*o+3]=255;const s=new ImageData(e,this.width,this.height);return this.detect(s)}detect(t){let e=null;const s=[];for(let b=0;b<this.numOctaves;b++){let x,I;b===0?x=this._applyFilter(t):x=this._downsampleBilinear(s[b-1][s[b-1].length-1]),I=this._applyFilter(x),s.push([x,I])}const o=[];for(let b=0;b<this.numOctaves;b++){let x=this._differenceImageBinomial(s[b][0],s[b][1]);o.push(x)}const r=[];for(let b=1;b<this.numOctaves-1;b++){const x=this._buildExtremas(o[b-1],o[b],o[b+1]);r.push(x)}const i=this._applyPrune(r),a=this._computeLocalization(i,o),c=this._computeOrientationHistograms(a,s),l=this._smoothHistograms(c),u=this._computeExtremaAngles(l),d=this._computeExtremaFreak(s,a,u),h=this._computeFreakDescriptors(d),p=a.arraySync(),f=u.arraySync(),m=h.arraySync();this.debugMode&&(e={pyramidImages:s.map(b=>b.map(x=>x.arraySync())),dogPyramidImages:o.map(b=>b?b.arraySync():null),extremasResults:r.map(b=>b.arraySync()),extremaAngles:u.arraySync(),prunedExtremas:i,localizedExtremas:a.arraySync()}),s.forEach(b=>b.forEach(x=>x.dispose())),o.forEach(b=>b&&b.dispose()),r.forEach(b=>b.dispose()),a.dispose(),c.dispose(),l.dispose(),u.dispose(),d.dispose(),h.dispose();const g=[];for(let b=0;b<p.length;b++){if(p[b][0]==0)continue;const x=[];for(let T=0;T<m[b].length;T+=4){const R=m[b][T],L=m[b][T+1],V=m[b][T+2],F=m[b][T+3];let X=R*16777216+L*65536+V*256+F;x.push(X)}const I=p[b][1],y=p[b][2],C=p[b][3]*Math.pow(2,I)+Math.pow(2,I-1)-.5,k=y*Math.pow(2,I)+Math.pow(2,I-1)-.5,S=Math.pow(2,I);g.push({maxima:p[b][0]>0,x:C,y:k,scale:S,angle:f[b],descriptors:x})}return{featurePoints:g,debugExtra:e}}_computeFreakDescriptors(t){if(!this.tensorCaches.computeFreakDescriptors){const s=[],o=[];for(let a=0;a<t.shape[1];a++)for(let c=a+1;c<t.shape[1];c++)s.push(a),o.push(c);const r=tn(s,[s.length]).cast("int32"),i=tn(o,[o.length]).cast("int32");this.tensorCaches.computeFreakDescriptors={positionT:en(On([r,i],1))}}const{positionT:e}=this.tensorCaches.computeFreakDescriptors;return M(()=>zt().runKernel("ComputeFreakDescriptors",{extremaFreaks:t,positionT:e}))}_computeExtremaFreak(t,e,s){this.tensorCaches._computeExtremaFreak||M(()=>{const i=tn($o);this.tensorCaches._computeExtremaFreak={freakPointsT:en(i)}});const{freakPointsT:o}=this.tensorCaches._computeExtremaFreak,r=[];for(let i=1;i<t.length;i++)r.push(t[i][1]);return M(()=>zt().runKernel("ComputeExtremaFreak",{gaussianImagesT:r,prunedExtremas:e,prunedExtremasAngles:s,freakPointsT:o,pyramidImagesLength:t.length}))}_computeExtremaAngles(t){return M(()=>zt().runKernel("ComputeExtremaAngles",{histograms:t}))}_computeOrientationHistograms(t,e){const s=[];for(let r=1;r<e.length;r++)s.push(e[r][1]);this.tensorCaches.orientationHistograms||M(()=>{const r=-1/(2*Qp*Qp),i=Qp*V9,a=Math.ceil(i),c=[];for(let l=-a;l<=a;l++)for(let u=-a;u<=a;u++){const d=u*u+l*l;if(d<=i*i){const h=d*r;let p=(720+h*(720+h*(360+h*(120+h*(30+h*(6+h))))))*.0013888888;c.push([l,u,p])}}this.tensorCaches.orientationHistograms={radialPropertiesT:en(tn(c,[c.length,3]))}});const{radialPropertiesT:o}=this.tensorCaches.orientationHistograms;return M(()=>zt().runKernel("ComputeOrientationHistograms",{gaussianImagesT:s,prunedExtremasT:t,radialPropertiesT:o,pyramidImagesLength:e.length}))}_smoothHistograms(t){return M(()=>zt().runKernel("SmoothHistograms",{histograms:t}))}_computeLocalization(t,e){return M(()=>{const o=zt().runKernel("ComputeLocalization",{prunedExtremasList:t,dogPyramidImagesT:e}).arraySync(),r=[];for(let a=0;a<o.length;a++){r.push([]);for(let c=0;c<o[a].length;c++)r[a].push([])}const i=[];for(let a=0;a<t.length;a++)i[a]=[t[a][0],t[a][1],t[a][2],t[a][3]];for(let a=0;a<i.length;a++){if(i[a][0]===0)continue;const c=o[a],l=.5*(c[1][2]-c[1][0]),u=.5*(c[2][1]-c[0][1]),d=c[1][2]+c[1][0]-2*c[1][1],h=c[2][1]+c[0][1]-2*c[1][1],p=.25*(c[0][0]+c[2][2]-c[0][2]-c[2][0]),f=d*h-p*p,m=(h*-l+-p*-u)/f,g=(-p*-l+d*-u)/f,b=i[a][2]+g,x=i[a][3]+m;Math.abs(f)<1e-4||(i[a][2]=b,i[a][3]=x)}return tn(i,[i.length,i[0].length],"float32")})}_applyPrune(t){const e=fa*fa,s=M9,o=[],r=[];for(let a=0;a<e;a++){r.push([]),o.push([]);for(let c=0;c<s;c++)r[a].push([0,0,0,0]),o[a].push(0)}M(()=>{for(let a=0;a<t.length;a++){const c=zt().runKernel("ExtremaReduction",{extremasResultT:t[a]}),l=a+1,u=c.arraySync(),d=c.shape[0],h=c.shape[1],p=h*2/fa,f=d*2/fa;for(let m=0;m<d;m++)for(let g=0;g<h;g++){const b=u[m][g];if(b==0)continue;const x=b%1e3,I=Math.floor(Math.abs(b)/1e3),y=g*2+(I===2||I===3?1:0),w=m*2+(I===1||I===3?1:0),C=Math.floor(y/p),S=Math.floor(w/f)*fa+C,T=Math.abs(x);let R=s;for(;R>=1&&T>o[S][R-1];)R-=1;if(R<s){for(let L=s-1;L>=R+1;L--)o[S][L]=o[S][L-1],r[S][L][0]=r[S][L-1][0],r[S][L][1]=r[S][L-1][1],r[S][L][2]=r[S][L-1][2],r[S][L][3]=r[S][L-1][3];o[S][R]=T,r[S][R][0]=x,r[S][R][1]=l,r[S][R][2]=w,r[S][R][3]=y}}}});const i=[];for(let a=0;a<e;a++)for(let c=0;c<s;c++)i.push(r[a][c]);return i}_buildExtremas(t,e,s){return M(()=>zt().runKernel("BuildExtremas",{image0:t,image1:e,image2:s}))}_differenceImageBinomial(t,e){return M(()=>t.sub(e))}_applyFilter(t){return M(()=>zt().runKernel("BinomialFilter",{image:t}))}_downsampleBilinear(t){return M(()=>zt().runKernel("DownsampleBilinear",{image:t}))}_compileAndRun(t,e){const s=ys().compileAndRun(t,e);return zt().makeTensorFromDataId(s.dataId,s.shape,s.dtype)}_runWebGLProgram(t,e,s){const o=ys().runWebGLProgram(t,e,s);return zt().makeTensorFromDataId(o.dataId,o.shape,o.dtype)}}class F9{constructor(t,e,s=!1){this.debugMode=s,this.width=t,this.height=e;let o=Math.min(t,e)/2,r=Math.pow(2,Math.round(Math.log(o)/Math.log(2)));this.cropSize=r,this.detector=new GI(r,r,s),this.kernelCaches={},this.lastRandomIndex=4}detect(t){const e=Math.floor(this.height/2-this.cropSize/2),s=Math.floor(this.width/2-this.cropSize/2),o=this._detect(t,s,e);return this.debugMode&&(o.debugExtra.crop={startX:s,startY:e,cropSize:this.cropSize}),o}detectMoving(t){const e=this.lastRandomIndex%3,s=Math.floor(this.lastRandomIndex/3);let o=Math.floor(this.height/2-this.cropSize+s*this.cropSize/2),r=Math.floor(this.width/2-this.cropSize+e*this.cropSize/2);return r<0&&(r=0),o<0&&(o=0),r>=this.width-this.cropSize&&(r=this.width-this.cropSize-1),o>=this.height-this.cropSize&&(o=this.height-this.cropSize-1),this.lastRandomIndex=(this.lastRandomIndex+1)%9,this._detect(t,r,o)}_detect(t,e,s){const o=t.slice([s,e],[this.cropSize,this.cropSize]),{featurePoints:r,debugExtra:i}=this.detector.detect(o);return r.forEach(a=>{a.x+=e,a.y+=s}),this.debugMode&&(i.projectedImage=o.arraySync()),o.dispose(),{featurePoints:r,debugExtra:i}}}const LI=({image:n,ratio:t})=>{const e=Math.round(n.width*t),s=Math.round(n.height*t),o=new Uint8Array(e*s);for(let r=0;r<e;r++){let i=Math.round(1*r/t),a=Math.round(1*(r+1)/t)-1;a>=n.width&&(a=n.width-1);for(let c=0;c<s;c++){let l=Math.round(1*c/t),u=Math.round(1*(c+1)/t)-1;u>=n.height&&(u=n.height-1);let d=0,h=0;for(let p=i;p<=a;p++)for(let f=l;f<=u;f++)d+=1*n.data[f*n.width+p],h+=1;o[c*e+r]=Math.floor(d/h)}}return{data:o,width:e,height:s}},z9=100,X9=n=>{const t=z9/Math.min(n.width,n.height),e=[];let s=t;for(;;)if(e.push(s),s*=Math.pow(2,1/3),s>=.95){s=1;break}e.push(s),e.reverse();const o=[];for(let r=0;r<e.length;r++)n.width*e[r],n.height*e[r],o.push(Object.assign(LI({image:n,ratio:e[r]}),{scale:e[r]}));return o},A9=n=>{const t=Math.min(n.width,n.height),e=[],s=[];e.push(256/t),e.push(128/t);for(let o=0;o<e.length;o++)s.push(Object.assign(LI({image:n,ratio:e[o]}),{scale:e[o]}));return s},P9=n=>{const{v1:t,v2:e}=n;let s=0;for(let o=0;o<t.length;o++){let r=(t[o]^e[o])>>>0;s+=O9(r)}return s},O9=n=>{var t=n-(n>>1&1431655765);return t=(t>>2&858993459)+(t&858993459),t=(t>>4)+t&252645135,t=(t>>8)+t&16711935,t=(t>>16)+t&65535,t},K9=1234,Z9=()=>({seed:K9,arrayShuffle(t){const{arr:e,sampleSize:s}=t;for(let o=0;o<s;o++){this.seed=(214013*this.seed+2531011)%-2147483648;let r=this.seed>>16&32767;r=r%e.length;let i=e[o];e[o]=e[r],e[r]=i}},nextInt(t){this.seed=(214013*this.seed+2531011)%-2147483648;let e=this.seed>>16&32767;return e=e%t,e}}),B9=16,H9=128,Jp=8,_9=n=>{const{points:t,pointIndexes:e,randomizer:s}=n,o=[];for(let c=0;c<e.length;c++)o.push(c);let r=Number.MAX_SAFE_INTEGER,i=-1;const a=[];for(let c=0;c<H9;c++){s.arrayShuffle({arr:o,sampleSize:Jp});let l=0;const u=[];for(let d=0;d<e.length;d++){let h=Number.MAX_SAFE_INTEGER;for(let p=0;p<Jp;p++){const f=e[o[p]],m=P9({v1:t[e[d]].descriptors,v2:t[f].descriptors});m<h&&(u[d]=o[p],h=m)}l+=h}a.push(u),l<r&&(r=l,i=c)}return a[i]},EI=({points:n})=>{const t=[];for(let o=0;o<n.length;o++)t.push(o);const e=Z9();return{rootNode:DI({points:n,pointIndexes:t,centerPointIndex:null,randomizer:e})}},DI=n=>{const{points:t,pointIndexes:e,centerPointIndex:s,randomizer:o}=n;let r=!1;(e.length<=Jp||e.length<=B9)&&(r=!0);const i={};if(!r){const c=_9({points:t,pointIndexes:e,randomizer:o});for(let l=0;l<c.length;l++)i[e[c[l]]]===void 0&&(i[e[c[l]]]=[]),i[e[c[l]]].push(e[l])}Object.keys(i).length===1&&(r=!0);const a={centerPointIndex:s};if(r){a.leaf=!0,a.pointIndexes=[];for(let c=0;c<e.length;c++)a.pointIndexes.push(e[c]);return a}return a.leaf=!1,a.children=[],Object.keys(i).forEach(c=>{a.children.push(DI({points:t,pointIndexes:i[c],centerPointIndex:c,randomizer:o}))}),a};var Go=4294967295;function U9(n,t,e){var s=e/4294967296,o=e;n.setUint32(t,s),n.setUint32(t+4,o)}function WI(n,t,e){var s=Math.floor(e/4294967296),o=e;n.setUint32(t,s),n.setUint32(t+4,o)}function MI(n,t){var e=n.getInt32(t),s=n.getUint32(t+4);return e*4294967296+s}function Y9(n,t){var e=n.getUint32(t),s=n.getUint32(t+4);return e*4294967296+s}var jp,qp,tf,Al=(typeof process>"u"||((jp=process==null?void 0:process.env)===null||jp===void 0?void 0:jp.TEXT_ENCODING)!=="never")&&typeof TextEncoder<"u"&&typeof TextDecoder<"u";function VI(n){for(var t=n.length,e=0,s=0;s<t;){var o=n.charCodeAt(s++);if(o&4294967168)if(!(o&4294965248))e+=2;else{if(o>=55296&&o<=56319&&s<t){var r=n.charCodeAt(s);(r&64512)===56320&&(++s,o=((o&1023)<<10)+(r&1023)+65536)}o&4294901760?e+=4:e+=3}else{e++;continue}}return e}function Q9(n,t,e){for(var s=n.length,o=e,r=0;r<s;){var i=n.charCodeAt(r++);if(i&4294967168)if(!(i&4294965248))t[o++]=i>>6&31|192;else{if(i>=55296&&i<=56319&&r<s){var a=n.charCodeAt(r);(a&64512)===56320&&(++r,i=((i&1023)<<10)+(a&1023)+65536)}i&4294901760?(t[o++]=i>>18&7|240,t[o++]=i>>12&63|128,t[o++]=i>>6&63|128):(t[o++]=i>>12&15|224,t[o++]=i>>6&63|128)}else{t[o++]=i;continue}t[o++]=i&63|128}}var ma=Al?new TextEncoder:void 0,J9=Al?typeof process<"u"&&((qp=process==null?void 0:process.env)===null||qp===void 0?void 0:qp.TEXT_ENCODING)!=="force"?200:0:Go;function j9(n,t,e){t.set(ma.encode(n),e)}function q9(n,t,e){ma.encodeInto(n,t.subarray(e))}var t_=ma!=null&&ma.encodeInto?q9:j9,e_=4096;function FI(n,t,e){for(var s=t,o=s+e,r=[],i="";s<o;){var a=n[s++];if(!(a&128))r.push(a);else if((a&224)===192){var c=n[s++]&63;r.push((a&31)<<6|c)}else if((a&240)===224){var c=n[s++]&63,l=n[s++]&63;r.push((a&31)<<12|c<<6|l)}else if((a&248)===240){var c=n[s++]&63,l=n[s++]&63,u=n[s++]&63,d=(a&7)<<18|c<<12|l<<6|u;d>65535&&(d-=65536,r.push(d>>>10&1023|55296),d=56320|d&1023),r.push(d)}else r.push(a);r.length>=e_&&(i+=String.fromCharCode.apply(String,r),r.length=0)}return r.length>0&&(i+=String.fromCharCode.apply(String,r)),i}var n_=Al?new TextDecoder:null,s_=Al?typeof process<"u"&&((tf=process==null?void 0:process.env)===null||tf===void 0?void 0:tf.TEXT_DECODER)!=="force"?200:0:Go;function o_(n,t,e){var s=n.subarray(t,t+e);return n_.decode(s)}var Pl=function(){function n(t,e){this.type=t,this.data=e}return n}(),r_=function(){var n=function(t,e){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(s,o){s.__proto__=o}||function(s,o){for(var r in o)Object.prototype.hasOwnProperty.call(o,r)&&(s[r]=o[r])},n(t,e)};return function(t,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");n(t,e);function s(){this.constructor=t}t.prototype=e===null?Object.create(e):(s.prototype=e.prototype,new s)}}(),ts=function(n){r_(t,n);function t(e){var s=n.call(this,e)||this,o=Object.create(t.prototype);return Object.setPrototypeOf(s,o),Object.defineProperty(s,"name",{configurable:!0,enumerable:!1,value:t.name}),s}return t}(Error),i_=-1,a_=4294967296-1,c_=17179869184-1;function l_(n){var t=n.sec,e=n.nsec;if(t>=0&&e>=0&&t<=c_)if(e===0&&t<=a_){var s=new Uint8Array(4),o=new DataView(s.buffer);return o.setUint32(0,t),s}else{var r=t/4294967296,i=t&4294967295,s=new Uint8Array(8),o=new DataView(s.buffer);return o.setUint32(0,e<<2|r&3),o.setUint32(4,i),s}else{var s=new Uint8Array(12),o=new DataView(s.buffer);return o.setUint32(0,e),WI(o,4,t),s}}function u_(n){var t=n.getTime(),e=Math.floor(t/1e3),s=(t-e*1e3)*1e6,o=Math.floor(s/1e9);return{sec:e+o,nsec:s-o*1e9}}function d_(n){if(n instanceof Date){var t=u_(n);return l_(t)}else return null}function h_(n){var t=new DataView(n.buffer,n.byteOffset,n.byteLength);switch(n.byteLength){case 4:{var e=t.getUint32(0),s=0;return{sec:e,nsec:s}}case 8:{var o=t.getUint32(0),r=t.getUint32(4),e=(o&3)*4294967296+r,s=o>>>2;return{sec:e,nsec:s}}case 12:{var e=MI(t,4),s=t.getUint32(0);return{sec:e,nsec:s}}default:throw new ts("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(n.length))}}function p_(n){var t=h_(n);return new Date(t.sec*1e3+t.nsec/1e6)}var f_={type:i_,encode:d_,decode:p_},zI=function(){function n(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(f_)}return n.prototype.register=function(t){var e=t.type,s=t.encode,o=t.decode;if(e>=0)this.encoders[e]=s,this.decoders[e]=o;else{var r=1+e;this.builtInEncoders[r]=s,this.builtInDecoders[r]=o}},n.prototype.tryToEncode=function(t,e){for(var s=0;s<this.builtInEncoders.length;s++){var o=this.builtInEncoders[s];if(o!=null){var r=o(t,e);if(r!=null){var i=-1-s;return new Pl(i,r)}}}for(var s=0;s<this.encoders.length;s++){var o=this.encoders[s];if(o!=null){var r=o(t,e);if(r!=null){var i=s;return new Pl(i,r)}}}return t instanceof Pl?t:null},n.prototype.decode=function(t,e,s){var o=e<0?this.builtInDecoders[-1-e]:this.decoders[e];return o?o(t,e,s):new Pl(e,t)},n.defaultCodec=new n,n}();function Ol(n){return n instanceof Uint8Array?n:ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):n instanceof ArrayBuffer?new Uint8Array(n):Uint8Array.from(n)}function m_(n){if(n instanceof ArrayBuffer)return new DataView(n);var t=Ol(n);return new DataView(t.buffer,t.byteOffset,t.byteLength)}var g_=100,b_=2048,x_=function(){function n(t,e,s,o,r,i,a,c){t===void 0&&(t=zI.defaultCodec),e===void 0&&(e=void 0),s===void 0&&(s=g_),o===void 0&&(o=b_),r===void 0&&(r=!1),i===void 0&&(i=!1),a===void 0&&(a=!1),c===void 0&&(c=!1),this.extensionCodec=t,this.context=e,this.maxDepth=s,this.initialBufferSize=o,this.sortKeys=r,this.forceFloat32=i,this.ignoreUndefined=a,this.forceIntegerToFloat=c,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}return n.prototype.reinitializeState=function(){this.pos=0},n.prototype.encodeSharedRef=function(t){return this.reinitializeState(),this.doEncode(t,1),this.bytes.subarray(0,this.pos)},n.prototype.encode=function(t){return this.reinitializeState(),this.doEncode(t,1),this.bytes.slice(0,this.pos)},n.prototype.doEncode=function(t,e){if(e>this.maxDepth)throw new Error("Too deep objects in depth ".concat(e));t==null?this.encodeNil():typeof t=="boolean"?this.encodeBoolean(t):typeof t=="number"?this.encodeNumber(t):typeof t=="string"?this.encodeString(t):this.encodeObject(t,e)},n.prototype.ensureBufferSizeToWrite=function(t){var e=this.pos+t;this.view.byteLength<e&&this.resizeBuffer(e*2)},n.prototype.resizeBuffer=function(t){var e=new ArrayBuffer(t),s=new Uint8Array(e),o=new DataView(e);s.set(this.bytes),this.view=o,this.bytes=s},n.prototype.encodeNil=function(){this.writeU8(192)},n.prototype.encodeBoolean=function(t){t===!1?this.writeU8(194):this.writeU8(195)},n.prototype.encodeNumber=function(t){Number.isSafeInteger(t)&&!this.forceIntegerToFloat?t>=0?t<128?this.writeU8(t):t<256?(this.writeU8(204),this.writeU8(t)):t<65536?(this.writeU8(205),this.writeU16(t)):t<4294967296?(this.writeU8(206),this.writeU32(t)):(this.writeU8(207),this.writeU64(t)):t>=-32?this.writeU8(224|t+32):t>=-128?(this.writeU8(208),this.writeI8(t)):t>=-32768?(this.writeU8(209),this.writeI16(t)):t>=-2147483648?(this.writeU8(210),this.writeI32(t)):(this.writeU8(211),this.writeI64(t)):this.forceFloat32?(this.writeU8(202),this.writeF32(t)):(this.writeU8(203),this.writeF64(t))},n.prototype.writeStringHeader=function(t){if(t<32)this.writeU8(160+t);else if(t<256)this.writeU8(217),this.writeU8(t);else if(t<65536)this.writeU8(218),this.writeU16(t);else if(t<4294967296)this.writeU8(219),this.writeU32(t);else throw new Error("Too long string: ".concat(t," bytes in UTF-8"))},n.prototype.encodeString=function(t){var e=5,s=t.length;if(s>J9){var o=VI(t);this.ensureBufferSizeToWrite(e+o),this.writeStringHeader(o),t_(t,this.bytes,this.pos),this.pos+=o}else{var o=VI(t);this.ensureBufferSizeToWrite(e+o),this.writeStringHeader(o),Q9(t,this.bytes,this.pos),this.pos+=o}},n.prototype.encodeObject=function(t,e){var s=this.extensionCodec.tryToEncode(t,this.context);if(s!=null)this.encodeExtension(s);else if(Array.isArray(t))this.encodeArray(t,e);else if(ArrayBuffer.isView(t))this.encodeBinary(t);else if(typeof t=="object")this.encodeMap(t,e);else throw new Error("Unrecognized object: ".concat(Object.prototype.toString.apply(t)))},n.prototype.encodeBinary=function(t){var e=t.byteLength;if(e<256)this.writeU8(196),this.writeU8(e);else if(e<65536)this.writeU8(197),this.writeU16(e);else if(e<4294967296)this.writeU8(198),this.writeU32(e);else throw new Error("Too large binary: ".concat(e));var s=Ol(t);this.writeU8a(s)},n.prototype.encodeArray=function(t,e){var s=t.length;if(s<16)this.writeU8(144+s);else if(s<65536)this.writeU8(220),this.writeU16(s);else if(s<4294967296)this.writeU8(221),this.writeU32(s);else throw new Error("Too large array: ".concat(s));for(var o=0,r=t;o<r.length;o++){var i=r[o];this.doEncode(i,e+1)}},n.prototype.countWithoutUndefined=function(t,e){for(var s=0,o=0,r=e;o<r.length;o++){var i=r[o];t[i]!==void 0&&s++}return s},n.prototype.encodeMap=function(t,e){var s=Object.keys(t);this.sortKeys&&s.sort();var o=this.ignoreUndefined?this.countWithoutUndefined(t,s):s.length;if(o<16)this.writeU8(128+o);else if(o<65536)this.writeU8(222),this.writeU16(o);else if(o<4294967296)this.writeU8(223),this.writeU32(o);else throw new Error("Too large map object: ".concat(o));for(var r=0,i=s;r<i.length;r++){var a=i[r],c=t[a];this.ignoreUndefined&&c===void 0||(this.encodeString(a),this.doEncode(c,e+1))}},n.prototype.encodeExtension=function(t){var e=t.data.length;if(e===1)this.writeU8(212);else if(e===2)this.writeU8(213);else if(e===4)this.writeU8(214);else if(e===8)this.writeU8(215);else if(e===16)this.writeU8(216);else if(e<256)this.writeU8(199),this.writeU8(e);else if(e<65536)this.writeU8(200),this.writeU16(e);else if(e<4294967296)this.writeU8(201),this.writeU32(e);else throw new Error("Too large extension object: ".concat(e));this.writeI8(t.type),this.writeU8a(t.data)},n.prototype.writeU8=function(t){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,t),this.pos++},n.prototype.writeU8a=function(t){var e=t.length;this.ensureBufferSizeToWrite(e),this.bytes.set(t,this.pos),this.pos+=e},n.prototype.writeI8=function(t){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,t),this.pos++},n.prototype.writeU16=function(t){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,t),this.pos+=2},n.prototype.writeI16=function(t){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,t),this.pos+=2},n.prototype.writeU32=function(t){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,t),this.pos+=4},n.prototype.writeI32=function(t){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,t),this.pos+=4},n.prototype.writeF32=function(t){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,t),this.pos+=4},n.prototype.writeF64=function(t){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,t),this.pos+=8},n.prototype.writeU64=function(t){this.ensureBufferSizeToWrite(8),U9(this.view,this.pos,t),this.pos+=8},n.prototype.writeI64=function(t){this.ensureBufferSizeToWrite(8),WI(this.view,this.pos,t),this.pos+=8},n}(),y_={};function I_(n,t){t===void 0&&(t=y_);var e=new x_(t.extensionCodec,t.context,t.maxDepth,t.initialBufferSize,t.sortKeys,t.forceFloat32,t.ignoreUndefined,t.forceIntegerToFloat);return e.encodeSharedRef(n)}function ef(n){return"".concat(n<0?"-":"","0x").concat(Math.abs(n).toString(16).padStart(2,"0"))}var w_=16,C_=16,v_=function(){function n(t,e){t===void 0&&(t=w_),e===void 0&&(e=C_),this.maxKeyLength=t,this.maxLengthPerKey=e,this.hit=0,this.miss=0,this.caches=[];for(var s=0;s<this.maxKeyLength;s++)this.caches.push([])}return n.prototype.canBeCached=function(t){return t>0&&t<=this.maxKeyLength},n.prototype.find=function(t,e,s){var o=this.caches[s-1];t:for(var r=0,i=o;r<i.length;r++){for(var a=i[r],c=a.bytes,l=0;l<s;l++)if(c[l]!==t[e+l])continue t;return a.str}return null},n.prototype.store=function(t,e){var s=this.caches[t.length-1],o={bytes:t,str:e};s.length>=this.maxLengthPerKey?s[Math.random()*s.length|0]=o:s.push(o)},n.prototype.decode=function(t,e,s){var o=this.find(t,e,s);if(o!=null)return this.hit++,o;this.miss++;var r=FI(t,e,s),i=Uint8Array.prototype.slice.call(t,e,e+s);return this.store(i,r),r},n}(),S_=function(n,t,e,s){function o(r){return r instanceof e?r:new e(function(i){i(r)})}return new(e||(e=Promise))(function(r,i){function a(u){try{l(s.next(u))}catch(d){i(d)}}function c(u){try{l(s.throw(u))}catch(d){i(d)}}function l(u){u.done?r(u.value):o(u.value).then(a,c)}l((s=s.apply(n,t||[])).next())})},nf=function(n,t){var e={label:0,sent:function(){if(r[0]&1)throw r[1];return r[1]},trys:[],ops:[]},s,o,r,i;return i={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(i[Symbol.iterator]=function(){return this}),i;function a(l){return function(u){return c([l,u])}}function c(l){if(s)throw new TypeError("Generator is already executing.");for(;e;)try{if(s=1,o&&(r=l[0]&2?o.return:l[0]?o.throw||((r=o.return)&&r.call(o),0):o.next)&&!(r=r.call(o,l[1])).done)return r;switch(o=0,r&&(l=[l[0]&2,r.value]),l[0]){case 0:case 1:r=l;break;case 4:return e.label++,{value:l[1],done:!1};case 5:e.label++,o=l[1],l=[0];continue;case 7:l=e.ops.pop(),e.trys.pop();continue;default:if(r=e.trys,!(r=r.length>0&&r[r.length-1])&&(l[0]===6||l[0]===2)){e=0;continue}if(l[0]===3&&(!r||l[1]>r[0]&&l[1]<r[3])){e.label=l[1];break}if(l[0]===6&&e.label<r[1]){e.label=r[1],r=l;break}if(r&&e.label<r[2]){e.label=r[2],e.ops.push(l);break}r[2]&&e.ops.pop(),e.trys.pop();continue}l=t.call(n,e)}catch(u){l=[6,u],o=0}finally{s=r=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}},XI=function(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=n[Symbol.asyncIterator],e;return t?t.call(n):(n=typeof __values=="function"?__values(n):n[Symbol.iterator](),e={},s("next"),s("throw"),s("return"),e[Symbol.asyncIterator]=function(){return this},e);function s(r){e[r]=n[r]&&function(i){return new Promise(function(a,c){i=n[r](i),o(a,c,i.done,i.value)})}}function o(r,i,a,c){Promise.resolve(c).then(function(l){r({value:l,done:a})},i)}},wr=function(n){return this instanceof wr?(this.v=n,this):new wr(n)},k_=function(n,t,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=e.apply(n,t||[]),o,r=[];return o={},i("next"),i("throw"),i("return"),o[Symbol.asyncIterator]=function(){return this},o;function i(h){s[h]&&(o[h]=function(p){return new Promise(function(f,m){r.push([h,p,f,m])>1||a(h,p)})})}function a(h,p){try{c(s[h](p))}catch(f){d(r[0][3],f)}}function c(h){h.value instanceof wr?Promise.resolve(h.value.v).then(l,u):d(r[0][2],h)}function l(h){a("next",h)}function u(h){a("throw",h)}function d(h,p){h(p),r.shift(),r.length&&a(r[0][0],r[0][1])}},T_=function(n){var t=typeof n;return t==="string"||t==="number"},ga=-1,sf=new DataView(new ArrayBuffer(0)),N_=new Uint8Array(sf.buffer),of=function(){try{sf.getInt8(0)}catch(n){return n.constructor}throw new Error("never reached")}(),AI=new of("Insufficient data"),R_=new v_,$_=function(){function n(t,e,s,o,r,i,a,c){t===void 0&&(t=zI.defaultCodec),e===void 0&&(e=void 0),s===void 0&&(s=Go),o===void 0&&(o=Go),r===void 0&&(r=Go),i===void 0&&(i=Go),a===void 0&&(a=Go),c===void 0&&(c=R_),this.extensionCodec=t,this.context=e,this.maxStrLength=s,this.maxBinLength=o,this.maxArrayLength=r,this.maxMapLength=i,this.maxExtLength=a,this.keyDecoder=c,this.totalPos=0,this.pos=0,this.view=sf,this.bytes=N_,this.headByte=ga,this.stack=[]}return n.prototype.reinitializeState=function(){this.totalPos=0,this.headByte=ga,this.stack.length=0},n.prototype.setBuffer=function(t){this.bytes=Ol(t),this.view=m_(this.bytes),this.pos=0},n.prototype.appendBuffer=function(t){if(this.headByte===ga&&!this.hasRemaining(1))this.setBuffer(t);else{var e=this.bytes.subarray(this.pos),s=Ol(t),o=new Uint8Array(e.length+s.length);o.set(e),o.set(s,e.length),this.setBuffer(o)}},n.prototype.hasRemaining=function(t){return this.view.byteLength-this.pos>=t},n.prototype.createExtraByteError=function(t){var e=this,s=e.view,o=e.pos;return new RangeError("Extra ".concat(s.byteLength-o," of ").concat(s.byteLength," byte(s) found at buffer[").concat(t,"]"))},n.prototype.decode=function(t){this.reinitializeState(),this.setBuffer(t);var e=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return e},n.prototype.decodeMulti=function(t){return nf(this,function(e){switch(e.label){case 0:this.reinitializeState(),this.setBuffer(t),e.label=1;case 1:return this.hasRemaining(1)?[4,this.doDecodeSync()]:[3,3];case 2:return e.sent(),[3,1];case 3:return[2]}})},n.prototype.decodeAsync=function(t){var e,s,o,r;return S_(this,void 0,void 0,function(){var i,a,c,l,u,d,h,p;return nf(this,function(f){switch(f.label){case 0:i=!1,f.label=1;case 1:f.trys.push([1,6,7,12]),e=XI(t),f.label=2;case 2:return[4,e.next()];case 3:if(s=f.sent(),!!s.done)return[3,5];if(c=s.value,i)throw this.createExtraByteError(this.totalPos);this.appendBuffer(c);try{a=this.doDecodeSync(),i=!0}catch(m){if(!(m instanceof of))throw m}this.totalPos+=this.pos,f.label=4;case 4:return[3,2];case 5:return[3,12];case 6:return l=f.sent(),o={error:l},[3,12];case 7:return f.trys.push([7,,10,11]),s&&!s.done&&(r=e.return)?[4,r.call(e)]:[3,9];case 8:f.sent(),f.label=9;case 9:return[3,11];case 10:if(o)throw o.error;return[7];case 11:return[7];case 12:if(i){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return[2,a]}throw u=this,d=u.headByte,h=u.pos,p=u.totalPos,new RangeError("Insufficient data in parsing ".concat(ef(d)," at ").concat(p," (").concat(h," in the current buffer)"))}})})},n.prototype.decodeArrayStream=function(t){return this.decodeMultiAsync(t,!0)},n.prototype.decodeStream=function(t){return this.decodeMultiAsync(t,!1)},n.prototype.decodeMultiAsync=function(t,e){return k_(this,arguments,function(){var o,r,i,a,c,l,u,d,h;return nf(this,function(p){switch(p.label){case 0:o=e,r=-1,p.label=1;case 1:p.trys.push([1,13,14,19]),i=XI(t),p.label=2;case 2:return[4,wr(i.next())];case 3:if(a=p.sent(),!!a.done)return[3,12];if(c=a.value,e&&r===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(c),o&&(r=this.readArraySize(),o=!1,this.complete()),p.label=4;case 4:p.trys.push([4,9,,10]),p.label=5;case 5:return[4,wr(this.doDecodeSync())];case 6:return[4,p.sent()];case 7:return p.sent(),--r===0?[3,8]:[3,5];case 8:return[3,10];case 9:if(l=p.sent(),!(l instanceof of))throw l;return[3,10];case 10:this.totalPos+=this.pos,p.label=11;case 11:return[3,2];case 12:return[3,19];case 13:return u=p.sent(),d={error:u},[3,19];case 14:return p.trys.push([14,,17,18]),a&&!a.done&&(h=i.return)?[4,wr(h.call(i))]:[3,16];case 15:p.sent(),p.label=16;case 16:return[3,18];case 17:if(d)throw d.error;return[7];case 18:return[7];case 19:return[2]}})})},n.prototype.doDecodeSync=function(){t:for(;;){var t=this.readHeadByte(),e=void 0;if(t>=224)e=t-256;else if(t<192)if(t<128)e=t;else if(t<144){var s=t-128;if(s!==0){this.pushMapState(s),this.complete();continue t}else e={}}else if(t<160){var s=t-144;if(s!==0){this.pushArrayState(s),this.complete();continue t}else e=[]}else{var o=t-160;e=this.decodeUtf8String(o,0)}else if(t===192)e=null;else if(t===194)e=!1;else if(t===195)e=!0;else if(t===202)e=this.readF32();else if(t===203)e=this.readF64();else if(t===204)e=this.readU8();else if(t===205)e=this.readU16();else if(t===206)e=this.readU32();else if(t===207)e=this.readU64();else if(t===208)e=this.readI8();else if(t===209)e=this.readI16();else if(t===210)e=this.readI32();else if(t===211)e=this.readI64();else if(t===217){var o=this.lookU8();e=this.decodeUtf8String(o,1)}else if(t===218){var o=this.lookU16();e=this.decodeUtf8String(o,2)}else if(t===219){var o=this.lookU32();e=this.decodeUtf8String(o,4)}else if(t===220){var s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue t}else e=[]}else if(t===221){var s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue t}else e=[]}else if(t===222){var s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue t}else e={}}else if(t===223){var s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue t}else e={}}else if(t===196){var s=this.lookU8();e=this.decodeBinary(s,1)}else if(t===197){var s=this.lookU16();e=this.decodeBinary(s,2)}else if(t===198){var s=this.lookU32();e=this.decodeBinary(s,4)}else if(t===212)e=this.decodeExtension(1,0);else if(t===213)e=this.decodeExtension(2,0);else if(t===214)e=this.decodeExtension(4,0);else if(t===215)e=this.decodeExtension(8,0);else if(t===216)e=this.decodeExtension(16,0);else if(t===199){var s=this.lookU8();e=this.decodeExtension(s,1)}else if(t===200){var s=this.lookU16();e=this.decodeExtension(s,2)}else if(t===201){var s=this.lookU32();e=this.decodeExtension(s,4)}else throw new ts("Unrecognized type byte: ".concat(ef(t)));this.complete();for(var r=this.stack;r.length>0;){var i=r[r.length-1];if(i.type===0)if(i.array[i.position]=e,i.position++,i.position===i.size)r.pop(),e=i.array;else continue t;else if(i.type===1){if(!T_(e))throw new ts("The type of key must be string or number but "+typeof e);if(e==="__proto__")throw new ts("The key __proto__ is not allowed");i.key=e,i.type=2;continue t}else if(i.map[i.key]=e,i.readCount++,i.readCount===i.size)r.pop(),e=i.map;else{i.key=null,i.type=1;continue t}}return e}},n.prototype.readHeadByte=function(){return this.headByte===ga&&(this.headByte=this.readU8()),this.headByte},n.prototype.complete=function(){this.headByte=ga},n.prototype.readArraySize=function(){var t=this.readHeadByte();switch(t){case 220:return this.readU16();case 221:return this.readU32();default:{if(t<160)return t-144;throw new ts("Unrecognized array type byte: ".concat(ef(t)))}}},n.prototype.pushMapState=function(t){if(t>this.maxMapLength)throw new ts("Max length exceeded: map length (".concat(t,") > maxMapLengthLength (").concat(this.maxMapLength,")"));this.stack.push({type:1,size:t,key:null,readCount:0,map:{}})},n.prototype.pushArrayState=function(t){if(t>this.maxArrayLength)throw new ts("Max length exceeded: array length (".concat(t,") > maxArrayLength (").concat(this.maxArrayLength,")"));this.stack.push({type:0,size:t,array:new Array(t),position:0})},n.prototype.decodeUtf8String=function(t,e){var s;if(t>this.maxStrLength)throw new ts("Max length exceeded: UTF-8 byte length (".concat(t,") > maxStrLength (").concat(this.maxStrLength,")"));if(this.bytes.byteLength<this.pos+e+t)throw AI;var o=this.pos+e,r;return this.stateIsMapKey()&&(!((s=this.keyDecoder)===null||s===void 0)&&s.canBeCached(t))?r=this.keyDecoder.decode(this.bytes,o,t):t>s_?r=o_(this.bytes,o,t):r=FI(this.bytes,o,t),this.pos+=e+t,r},n.prototype.stateIsMapKey=function(){if(this.stack.length>0){var t=this.stack[this.stack.length-1];return t.type===1}return!1},n.prototype.decodeBinary=function(t,e){if(t>this.maxBinLength)throw new ts("Max length exceeded: bin length (".concat(t,") > maxBinLength (").concat(this.maxBinLength,")"));if(!this.hasRemaining(t+e))throw AI;var s=this.pos+e,o=this.bytes.subarray(s,s+t);return this.pos+=e+t,o},n.prototype.decodeExtension=function(t,e){if(t>this.maxExtLength)throw new ts("Max length exceeded: ext length (".concat(t,") > maxExtLength (").concat(this.maxExtLength,")"));var s=this.view.getInt8(this.pos+e),o=this.decodeBinary(t,e+1);return this.extensionCodec.decode(o,s,this.context)},n.prototype.lookU8=function(){return this.view.getUint8(this.pos)},n.prototype.lookU16=function(){return this.view.getUint16(this.pos)},n.prototype.lookU32=function(){return this.view.getUint32(this.pos)},n.prototype.readU8=function(){var t=this.view.getUint8(this.pos);return this.pos++,t},n.prototype.readI8=function(){var t=this.view.getInt8(this.pos);return this.pos++,t},n.prototype.readU16=function(){var t=this.view.getUint16(this.pos);return this.pos+=2,t},n.prototype.readI16=function(){var t=this.view.getInt16(this.pos);return this.pos+=2,t},n.prototype.readU32=function(){var t=this.view.getUint32(this.pos);return this.pos+=4,t},n.prototype.readI32=function(){var t=this.view.getInt32(this.pos);return this.pos+=4,t},n.prototype.readU64=function(){var t=Y9(this.view,this.pos);return this.pos+=8,t},n.prototype.readI64=function(){var t=MI(this.view,this.pos);return this.pos+=8,t},n.prototype.readF32=function(){var t=this.view.getFloat32(this.pos);return this.pos+=4,t},n.prototype.readF64=function(){var t=this.view.getFloat64(this.pos);return this.pos+=8,t},n}(),G_={};function L_(n,t){t===void 0&&(t=G_);var e=new $_(t.extensionCodec,t.context,t.maxStrLength,t.maxBinLength,t.maxArrayLength,t.maxMapLength,t.maxExtLength);return e.decode(n)}const PI=2;class E_{constructor(){this.data=null}compileImageTargets(t,e){return new Promise(async(s,o)=>{const r=[];for(let l=0;l<t.length;l++){const u=t[l],h=this.createProcessCanvas(u).getContext("2d");h.drawImage(u,0,0,u.width,u.height);const p=h.getImageData(0,0,u.width,u.height),f=new Uint8Array(u.width*u.height);for(let g=0;g<f.length;g++){const b=g*4;f[g]=Math.floor((p.data[b]+p.data[b+1]+p.data[b+2])/3)}const m={data:f,height:u.height,width:u.width};r.push(m)}const i=50/r.length;let a=0;this.data=[];for(let l=0;l<r.length;l++){const u=r[l],d=X9(u),h=i/d.length,p=await D_(d,()=>{a+=h,e(a)});this.data.push({targetImage:u,imageList:d,matchingData:p})}for(let l=0;l<r.length;l++){const u=A9(r[l]);this.data[l].trackingImageList=u}const c=await this.compileTrack({progressCallback:e,targetImages:r,basePercent:50});for(let l=0;l<r.length;l++)this.data[l].trackingData=c[l];s(this.data)})}exportData(){const t=[];for(let s=0;s<this.data.length;s++)t.push({targetImage:{width:this.data[s].targetImage.width,height:this.data[s].targetImage.height},trackingData:this.data[s].trackingData,matchingData:this.data[s].matchingData});return I_({v:PI,dataList:t})}importData(t){const e=L_(new Uint8Array(t));if(!e.v||e.v!==PI)return console.error("Your compiled .mind might be outdated. Please recompile"),[];const{dataList:s}=e;this.data=[];for(let o=0;o<s.length;o++)this.data.push({targetImage:s[o].targetImage,trackingData:s[o].trackingData,matchingData:s[o].matchingData});return this.data}createProcessCanvas(t){console.warn("missing createProcessCanvas implementation")}compileTrack({progressCallback:t,targetImages:e,basePercent:s}){console.warn("missing compileTrack implementation")}}const D_=async(n,t)=>{const e=[];for(let s=0;s<n.length;s++){const o=n[s],r=new GI(o.width,o.height);await Xc(),M(()=>{const i=tn(o.data,[o.data.length],"float32").reshape([o.height,o.width]),{featurePoints:a}=r.detect(i),c=a.filter(h=>h.maxima),l=a.filter(h=>!h.maxima),u=EI({points:c}),d=EI({points:l});e.push({maximaPoints:c,minimaPoints:l,maximaPointsCluster:u,minimaPointsCluster:d,width:o.width,height:o.height,scale:o.scale}),t(s)})}return e},OI="[encoded data, 6740 characters]",KI=typeof window<"u"&&window.Blob&&new Blob([atob(OI)],{type:"text/javascript;charset=utf-8"});function W_(n){let t;try{if(t=KI&&(window.URL||window.webkitURL).createObjectURL(KI),!t)throw"";const e=new Worker(t,{name:n==null?void 0:n.name});return e.addEventListener("error",()=>{(window.URL||window.webkitURL).revokeObjectURL(t)}),e}catch{return new Worker("data:application/javascript;base64,"+OI,{name:n==null?void 0:n.name})}finally{t&&(window.URL||window.webkitURL).revokeObjectURL(t)}}class ZI extends E_{createProcessCanvas(t){const e=document.createElement("canvas");return e.width=t.width,e.height=t.height,e}compileTrack({progressCallback:t,targetImages:e,basePercent:s}){return new Promise((o,r)=>{const i=new W_;i.onmessage=a=>{a.data.type==="progress"?t(s+a.data.percent*s/100):a.data.type==="compileDone"&&o(a.data.list)},i.postMessage({type:"compile",targetImages:e})})}}class M_{constructor(t,e){this.width=t,this.height=e,this.texShape=[e,t];const s=document.createElement("canvas").getContext("2d");s.canvas.width=t,s.canvas.height=e,this.context=s,this.program=this.buildProgram(t,e);const o=ys();this.tempPixelHandle=o.makeTensorInfo(this.texShape,"float32"),o.texData.get(this.tempPixelHandle.dataId).usage=2}_loadInput(t){return M(()=>{let e=CT(t);return e=e.mean(2),e})}loadInput(t){const e=this.context;if(e.clearRect(0,0,this.context.canvas.width,this.context.canvas.height),t.width===this.height&&t.height===this.width){let i=this.context.canvas.width/2,a=this.context.canvas.height/2,c=90;e.save(),e.translate(i,a),e.rotate(c*Math.PI/180),e.drawImage(t,-t.width/2,-t.height/2),e.restore()}else this.context.drawImage(t,0,0,t.width,t.height);const o=ys();return o.gpgpu.uploadPixelDataToTexture(o.getTexture(this.tempPixelHandle.dataId),this.context.canvas),this._compileAndRun(this.program,[this.tempPixelHandle])}buildProgram(t,e){const s=z().getNumber("WEBGL_VERSION")===2?"texture":"texture2D";return{variableNames:["A"],outputShape:this.texShape,userCode:`
	void main() {
	  ivec2 coords = getOutputCoords();
	  int texR = coords[0];
	  int texC = coords[1];
	  vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${t}.0, ${e}.0);

	  vec4 values = ${s}(A, uv);
	  setOutput((0.299 * values.r + 0.587 * values.g + 0.114 * values.b) * 255.0);
	}
      `}}_compileAndRun(t,e){const s=ys().compileAndRun(t,e);return zt().makeTensorFromDataId(s.dataId,s.shape,s.dtype)}_runWebGLProgram(t,e,s){const o=ys().runWebGLProgram(t,e,s);return zt().makeTensorFromDataId(o.dataId,o.shape,o.dtype)}}const BI=(n,t)=>{const e=2*Math.PI*t*n;return e/(e+1)},HI=(n,t,e)=>n*t+(1-n)*e;class V_{constructor({minCutOff:t,beta:e}){this.minCutOff=t,this.beta=e,this.dCutOff=.001,this.xPrev=null,this.dxPrev=null,this.tPrev=null,this.initialized=!1}reset(){this.initialized=!1}filter(t,e){if(!this.initialized)return this.initialized=!0,this.xPrev=e,this.dxPrev=e.map(()=>0),this.tPrev=t,e;const{xPrev:s,tPrev:o,dxPrev:r}=this,i=t-o,a=BI(i,this.dCutOff),c=[],l=[],u=[];for(let d=0;d<e.length;d++){c[d]=(e[d]-s[d])/i,l[d]=HI(a,c[d],r[d]);const h=this.minCutOff+this.beta*Math.abs(l[d]),p=BI(i,h);u[d]=HI(p,e[d],s[d])}return this.xPrev=u,this.dxPrev=l,this.tPrev=t,u}}const rf={memory:Nc,nextFrame:Xc},F_=.001,z_=1e3,X_=5,A_=5;class _I{constructor({inputWidth:t,inputHeight:e,onUpdate:s=null,debugMode:o=!1,maxTrack:r=1,warmupTolerance:i=null,missTolerance:a=null,filterMinCF:c=null,filterBeta:l=null}){this.inputWidth=t,this.inputHeight=e,this.maxTrack=r,this.filterMinCF=c===null?F_:c,this.filterBeta=l===null?z_:l,this.warmupTolerance=i===null?X_:i,this.missTolerance=a===null?A_:a,this.cropDetector=new F9(this.inputWidth,this.inputHeight,o),this.inputLoader=new M_(this.inputWidth,this.inputHeight),this.markerDimensions=null,this.onUpdate=s,this.debugMode=o,this.processingVideo=!1,this.interestedTargetIndex=-1,this.trackingStates=[];const u=10,d=1e5,h=45*Math.PI/180,p=this.inputHeight/2/Math.tan(h/2);this.projectionTransform=[[p,0,this.inputWidth/2],[0,p,this.inputHeight/2],[0,0,1]],this.projectionMatrix=this._glProjectionMatrix({projectionTransform:this.projectionTransform,width:this.inputWidth,height:this.inputHeight,near:u,far:d}),this.worker=new JH,this.workerMatchDone=null,this.workerTrackDone=null,this.worker.onmessage=f=>{f.data.type==="matchDone"&&this.workerMatchDone!==null&&this.workerMatchDone(f.data),f.data.type==="trackUpdateDone"&&this.workerTrackDone!==null&&this.workerTrackDone(f.data)}}showTFStats(){console.log(rf.memory().numTensors),console.table(rf.memory())}addImageTargets(t){return new Promise(async(e,s)=>{const r=await(await fetch(t)).arrayBuffer(),i=this.addImageTargetsFromBuffer(r);e(i)})}addImageTargetsFromBuffer(t){const s=new ZI().importData(t),o=[],r=[],i=[];for(let a=0;a<s.length;a++)r.push(s[a].matchingData),o.push(s[a].trackingData),i.push([s[a].targetImage.width,s[a].targetImage.height]);return this.tracker=new a9(i,o,this.projectionTransform,this.inputWidth,this.inputHeight,this.debugMode),this.worker.postMessage({type:"setup",inputWidth:this.inputWidth,inputHeight:this.inputHeight,projectionTransform:this.projectionTransform,debugMode:this.debugMode,matchingDataList:r}),this.markerDimensions=i,{dimensions:i,matchingDataList:r,trackingDataList:o}}dispose(){this.stopProcessVideo(),this.worker.postMessage({type:"dispose"})}dummyRun(t){const e=this.inputLoader.loadInput(t);this.cropDetector.detect(e),this.tracker.dummyRun(e),e.dispose()}getProjectionMatrix(){return this.projectionMatrix}getRotatedZ90Matrix(t){return[-t[1],t[0],t[2],t[3],-t[5],t[4],t[6],t[7],-t[9],t[8],t[10],t[11],-t[13],t[12],t[14],t[15]]}getWorldMatrix(t,e){return this._glModelViewMatrix(t,e)}async _detectAndMatch(t,e){const{featurePoints:s}=this.cropDetector.detectMoving(t),{targetIndex:o,modelViewTransform:r}=await this._workerMatch(s,e);return{targetIndex:o,modelViewTransform:r}}async _trackAndUpdate(t,e,s){const{worldCoords:o,screenCoords:r}=this.tracker.track(t,e,s);return o.length<4?null:await this._workerTrackUpdate(e,{worldCoords:o,screenCoords:r})}processVideo(t){if(this.processingVideo)return;this.processingVideo=!0,this.trackingStates=[];for(let s=0;s<this.markerDimensions.length;s++)this.trackingStates.push({showing:!1,isTracking:!1,currentModelViewTransform:null,trackCount:0,trackMiss:0,filter:new V_({minCutOff:this.filterMinCF,beta:this.filterBeta})});(async()=>{for(;this.processingVideo;){const s=this.inputLoader.loadInput(t);if(this.trackingStates.reduce((r,i)=>r+(i.isTracking?1:0),0)<this.maxTrack){const r=[];for(let c=0;c<this.trackingStates.length;c++)this.trackingStates[c].isTracking!==!0&&(this.interestedTargetIndex!==-1&&this.interestedTargetIndex!==c||r.push(c));const{targetIndex:i,modelViewTransform:a}=await this._detectAndMatch(s,r);i!==-1&&(this.trackingStates[i].isTracking=!0,this.trackingStates[i].currentModelViewTransform=a)}for(let r=0;r<this.trackingStates.length;r++){const i=this.trackingStates[r];if(i.isTracking){let a=await this._trackAndUpdate(s,i.currentModelViewTransform,r);a===null?i.isTracking=!1:i.currentModelViewTransform=a}if(i.showing||i.isTracking&&(i.trackMiss=0,i.trackCount+=1,i.trackCount>this.warmupTolerance&&(i.showing=!0,i.trackingMatrix=null,i.filter.reset())),i.showing&&(i.isTracking?i.trackMiss=0:(i.trackCount=0,i.trackMiss+=1,i.trackMiss>this.missTolerance&&(i.showing=!1,i.trackingMatrix=null,this.onUpdate&&this.onUpdate({type:"updateMatrix",targetIndex:r,worldMatrix:null})))),i.showing){const a=this._glModelViewMatrix(i.currentModelViewTransform,r);i.trackingMatrix=i.filter.filter(Date.now(),a);let c=[];for(let u=0;u<i.trackingMatrix.length;u++)c[u]=i.trackingMatrix[u];t.width===this.inputHeight&&t.height===this.inputWidth&&(c=this.getRotatedZ90Matrix(c)),this.onUpdate&&this.onUpdate({type:"updateMatrix",targetIndex:r,worldMatrix:c})}}s.dispose(),this.onUpdate&&this.onUpdate({type:"processDone"}),await rf.nextFrame()}})()}stopProcessVideo(){this.processingVideo=!1}async detect(t){const e=this.inputLoader.loadInput(t),{featurePoints:s,debugExtra:o}=await this.cropDetector.detect(e);return e.dispose(),{featurePoints:s,debugExtra:o}}async match(t,e){const{modelViewTransform:s,debugExtra:o}=await this._workerMatch(t,[e]);return{modelViewTransform:s,debugExtra:o}}async track(t,e,s){const o=this.inputLoader.loadInput(t),r=this.tracker.track(o,e,s);return o.dispose(),r}async trackUpdate(t,e){return e.worldCoords.length<4?null:await this._workerTrackUpdate(t,e)}_workerMatch(t,e){return new Promise(async(s,o)=>{this.workerMatchDone=r=>{s({targetIndex:r.targetIndex,modelViewTransform:r.modelViewTransform,debugExtra:r.debugExtra})},this.worker.postMessage({type:"match",featurePoints:t,targetIndexes:e})})}_workerTrackUpdate(t,e){return new Promise(async(s,o)=>{this.workerTrackDone=a=>{s(a.modelViewTransform)};const{worldCoords:r,screenCoords:i}=e;this.worker.postMessage({type:"trackUpdate",modelViewTransform:t,worldCoords:r,screenCoords:i})})}_glModelViewMatrix(t,e){const s=this.markerDimensions[e][1];return[t[0][0],-t[1][0],-t[2][0],0,-t[0][1],t[1][1],t[2][1],0,-t[0][2],t[1][2],t[2][2],0,t[0][1]*s+t[0][3],-(t[1][1]*s+t[1][3]),-(t[2][1]*s+t[2][3]),1]}_glProjectionMatrix({projectionTransform:t,width:e,height:s,near:o,far:r}){const i=[[2*t[0][0]/e,0,-(2*t[0][2]/e-1),0],[0,2*t[1][1]/s,-(2*t[1][2]/s-1),0],[0,0,-(r+o)/(r-o),-2*r*o/(r-o)],[0,0,-1,0]],a=[];for(let c=0;c<4;c++)for(let l=0;l<4;l++)a.push(i[l][c]);return a}}const P_=`<div class="mindar-ui-overlay mindar-ui-loading">
  <div class="loader"/>
</div>
`,O_=`<div class="mindar-ui-overlay mindar-ui-compatibility">
  <div class="content">
    <h1>Failed to launch :(</h1>
    <p>
      Looks like your device/browser is not compatible.
    </p>

    <br/>
    <br/>
    <p>
      Please try the following recommended browsers:
    </p>
    <p>
      For Android device - Chrome
    </p>
    <p>
      For iOS device - Safari
    </p>
  </div>
</div>
`,K_=`<div class="mindar-ui-overlay mindar-ui-scanning">
  <div class="scanning">
    <div class="inner">
      <div class="scanline"/>
    </div>
  </div>
</div>
`,Z_=".mindar-ui-overlay{display:flex;align-items:center;justify-content:center;position:absolute;left:0;right:0;top:0;bottom:0;background:transparent;z-index:2}.mindar-ui-overlay.hidden{display:none}.mindar-ui-loading .loader{border:16px solid #222;border-top:16px solid white;opacity:.8;border-radius:50%;width:120px;height:120px;animation:spin 2s linear infinite}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.mindar-ui-compatibility .content{background:black;color:#fff;opacity:.8;text-align:center;margin:20px;padding:20px;min-height:50vh}@media (min-aspect-ratio: 1/1){.mindar-ui-scanning .scanning{width:50vh;height:50vh}}@media (max-aspect-ratio: 1/1){.mindar-ui-scanning .scanning{width:80vw;height:80vw}}.mindar-ui-scanning .scanning .inner{position:relative;width:100%;height:100%;opacity:.8;background:linear-gradient(to right,white 10px,transparent 10px) 0 0,linear-gradient(to right,white 10px,transparent 10px) 0 100%,linear-gradient(to left,white 10px,transparent 10px) 100% 0,linear-gradient(to left,white 10px,transparent 10px) 100% 100%,linear-gradient(to bottom,white 10px,transparent 10px) 0 0,linear-gradient(to bottom,white 10px,transparent 10px) 100% 0,linear-gradient(to top,white 10px,transparent 10px) 0 100%,linear-gradient(to top,white 10px,transparent 10px) 100% 100%;background-repeat:no-repeat;background-size:40px 40px}.mindar-ui-scanning .scanning .inner .scanline{position:absolute;width:100%;height:10px;background:white;animation:move 2s linear infinite}@keyframes move{0%,to{top:0%}50%{top:calc(100% - 10px)}}";class UI{constructor({uiLoading:t,uiScanning:e,uiError:s}){const o=document.createElement("style");o.innerText=Z_,document.head.appendChild(o),t==="yes"?this.loadingModal=this._loadHTML(P_):t!=="no"&&(this.loadingModal=document.querySelector(t)),s==="yes"?this.compatibilityModal=this._loadHTML(O_):s!=="no"&&(this.compatibilityModal=document.querySelector(s)),e==="yes"?this.scanningMask=this._loadHTML(K_):e!=="no"&&(this.scanningMask=document.querySelector(e)),this.hideLoading(),this.hideCompatibility(),this.hideScanning()}showLoading(){this.loadingModal&&this.loadingModal.classList.remove("hidden")}hideLoading(){this.loadingModal&&this.loadingModal.classList.add("hidden")}showCompatibility(){this.compatibilityModal&&this.compatibilityModal.classList.remove("hidden")}hideCompatibility(){this.compatibilityModal&&this.compatibilityModal.classList.add("hidden")}showScanning(){this.scanningMask&&this.scanningMask.classList.remove("hidden")}hideScanning(){this.scanningMask&&this.scanningMask.classList.add("hidden")}_loadHTML(t){const e=document.createElement("template");e.innerHTML=t.trim();const s=e.content.firstChild;return document.getElementsByTagName("body")[0].appendChild(s),s}}window.MINDAR||(window.MINDAR={}),window.MINDAR.IMAGE={Controller:_I,Compiler:ZI,UI},AFRAME.registerSystem("mindar-image-system",{container:null,video:null,processingImage:!1,init:function(){this.anchorEntities=[]},tick:function(){},setup:function({imageTargetSrc:n,maxTrack:t,showStats:e,uiLoading:s,uiScanning:o,uiError:r,missTolerance:i,warmupTolerance:a,filterMinCF:c,filterBeta:l}){this.imageTargetSrc=n,this.maxTrack=t,this.filterMinCF=c,this.filterBeta=l,this.missTolerance=i,this.warmupTolerance=a,this.showStats=e,this.ui=new UI({uiLoading:s,uiScanning:o,uiError:r})},registerAnchor:function(n,t){this.anchorEntities.push({el:n,targetIndex:t})},start:function(){this.container=this.el.sceneEl.parentNode,this.showStats&&(this.mainStats=new Stats,this.mainStats.showPanel(0),this.mainStats.domElement.style.cssText="position:absolute;top:0px;left:0px;z-index:999",this.container.appendChild(this.mainStats.domElement)),this.ui.showLoading(),this._startVideo()},switchTarget:function(n){this.controller.interestedTargetIndex=n},stop:function(){this.pause(),this.video.srcObject.getTracks().forEach(function(t){t.stop()}),this.video.remove(),this.controller.dispose()},pause:function(n=!1){n||this.video.pause(),this.controller.stopProcessVideo()},unpause:function(){this.video.play(),this.controller.processVideo(this.video)},_startVideo:function(){if(this.video=document.createElement("video"),this.video.setAttribute("autoplay",""),this.video.setAttribute("muted",""),this.video.setAttribute("playsinline",""),this.video.style.position="absolute",this.video.style.top="0px",this.video.style.left="0px",this.video.style.zIndex="-2",this.container.appendChild(this.video),!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia){this.el.emit("arError",{error:"VIDEO_FAIL"}),this.ui.showCompatibility();return}navigator.mediaDevices.getUserMedia({audio:!1,video:{facingMode:"environment"}}).then(n=>{this.video.addEventListener("loadedmetadata",()=>{this.video.setAttribute("width",this.video.videoWidth),this.video.setAttribute("height",this.video.videoHeight),this._startAR()}),this.video.srcObject=n}).catch(n=>{console.log("getUserMedia error",n),this.el.emit("arError",{error:"VIDEO_FAIL"})})},_startAR:async function(){const n=this.video;this.container,this.controller=new _I({inputWidth:n.videoWidth,inputHeight:n.videoHeight,maxTrack:this.maxTrack,filterMinCF:this.filterMinCF,filterBeta:this.filterBeta,missTolerance:this.missTolerance,warmupTolerance:this.warmupTolerance,onUpdate:e=>{if(e.type==="processDone")this.mainStats&&this.mainStats.update();else if(e.type==="updateMatrix"){const{targetIndex:s,worldMatrix:o}=e;for(let i=0;i<this.anchorEntities.length;i++)this.anchorEntities[i].targetIndex===s&&this.anchorEntities[i].el.updateWorldMatrix(o);this.anchorEntities.reduce((i,a)=>i||a.el.el.object3D.visible,!1)?this.ui.hideScanning():this.ui.showScanning()}}}),this._resize(),window.addEventListener("resize",this._resize.bind(this));const{dimensions:t}=await this.controller.addImageTargets(this.imageTargetSrc);for(let e=0;e<this.anchorEntities.length;e++){const{el:s,targetIndex:o}=this.anchorEntities[e];o<t.length&&s.setupMarker(t[o])}await this.controller.dummyRun(this.video),this.el.emit("arReady"),this.ui.hideLoading(),this.ui.showScanning(),this.controller.processVideo(this.video)},_resize:function(){const n=this.video,t=this.container;let e,s;const o=n.videoWidth/n.videoHeight,r=t.clientWidth/t.clientHeight;o>r?(s=t.clientHeight,e=s*o):(e=t.clientWidth,s=e/o);const i=this.controller.getProjectionMatrix(),a=2*Math.atan(1/i[5]/s*t.clientHeight)*180/Math.PI,c=i[14]/(i[10]-1),l=i[14]/(i[10]+1);i[5]/i[0];const u=t.clientWidth/t.clientHeight,h=t.getElementsByTagName("a-camera")[0].getObject3D("camera");h.fov=a,h.aspect=u,h.near=c,h.far=l,h.updateProjectionMatrix(),this.video.style.top=-(s-t.clientHeight)/2+"px",this.video.style.left=-(e-t.clientWidth)/2+"px",this.video.style.width=e+"px",this.video.style.height=s+"px"}}),AFRAME.registerComponent("mindar-image",{dependencies:["mindar-image-system"],schema:{imageTargetSrc:{type:"string"},maxTrack:{type:"int",default:1},filterMinCF:{type:"number",default:-1},filterBeta:{type:"number",default:-1},missTolerance:{type:"int",default:-1},warmupTolerance:{type:"int",default:-1},showStats:{type:"boolean",default:!1},autoStart:{type:"boolean",default:!0},uiLoading:{type:"string",default:"yes"},uiScanning:{type:"string",default:"yes"},uiError:{type:"string",default:"yes"}},init:function(){const n=this.el.sceneEl.systems["mindar-image-system"];n.setup({imageTargetSrc:this.data.imageTargetSrc,maxTrack:this.data.maxTrack,filterMinCF:this.data.filterMinCF===-1?null:this.data.filterMinCF,filterBeta:this.data.filterBeta===-1?null:this.data.filterBeta,missTolerance:this.data.missTolerance===-1?null:this.data.missTolerance,warmupTolerance:this.data.warmupTolerance===-1?null:this.data.warmupTolerance,showStats:this.data.showStats,uiLoading:this.data.uiLoading,uiScanning:this.data.uiScanning,uiError:this.data.uiError}),this.data.autoStart&&this.el.sceneEl.addEventListener("renderstart",()=>{n.start()})},remove:function(){this.el.sceneEl.systems["mindar-image-system"].stop()}}),AFRAME.registerComponent("mindar-image-target",{dependencies:["mindar-image-system"],schema:{targetIndex:{type:"number"}},postMatrix:null,init:function(){this.el.sceneEl.systems["mindar-image-system"].registerAnchor(this,this.data.targetIndex),this.invisibleMatrix=new AFRAME.THREE.Matrix4().set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const t=this.el.object3D;t.visible=!1,t.matrixAutoUpdate=!1,t.matrix=this.invisibleMatrix},setupMarker([n,t]){const e=new AFRAME.THREE.Vector3,s=new AFRAME.THREE.Quaternion,o=new AFRAME.THREE.Vector3;e.x=n/2,e.y=n/2+(t-n)/2,o.x=n,o.y=n,o.z=n,this.postMatrix=new AFRAME.THREE.Matrix4,this.postMatrix.compose(e,s,o)},updateWorldMatrix(n){if(this.el.emit("targetUpdate"),!this.el.object3D.visible&&n!==null?this.el.emit("targetFound"):this.el.object3D.visible&&n===null&&this.el.emit("targetLost"),this.el.object3D.visible=n!==null,n===null){this.el.object3D.matrix=this.invisibleMatrix;return}var t=new AFRAME.THREE.Matrix4;t.elements=n,t.multiply(this.postMatrix),this.el.object3D.matrix=t}})})();
