tensorflow.js实时获取三维人脸标志点三维脸部轮廓代码

代码语言:html

所属分类:多媒体

代码描述:tensorflow.js实时获取三维人脸标志点三维脸部轮廓代码,完整代码地址:https://github.com/tensorflow/tfjs-models/tree/master/face-landmarks-detection

代码标签: 三维 人脸 标志 三维 脸部 轮廓

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<script src="https://cdn.jsdelivr.net/npm/three@0.106.2/build/three.min.js"></script>
<!-- Load scatter-gl.js -->
<script src="https://cdn.jsdelivr.net/npm/scatter-gl@0.0.1/lib/scatter-gl.min.js"></script>
<style>
  .canvas-wrapper, #scatter-gl-container {
    display: inline-block;
    vertical-align: top;
  }

  #scatter-gl-container {
    border: solid 1px black;
    position: relative;
  }

  /* center the canvas within its wrapper */
  #scatter-gl-container canvas {
    left: 50%;
    position: absolute;
    top: 50%;
    transform: translate3d(-50%, -50%, 0);
  }
</style>
</head>
<body>
  <div id="main">
    <div class="container">
      <div class="canvas-wrapper">
        <canvas id="output"></canvas>
        <video id="video" playsinline style="
          -webkit-transform: scaleX(-1);
          transform: scaleX(-1);
          visibility: hidden;
          width: auto;
          height: auto;
          ">
        </video>
      </div>
      <div id="scatter-gl-container"></div>
    </div>
  </div>
</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.7.6/dat.gui.min.js"></script>
<script>
    /**
    * @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(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(require("path"),require("fs"),require("worker_threads"),require("perf_hooks"),require("os")):"function"==typeof define&&define.amd?define(["path","fs","worker_threads","perf_hooks","os"],t):t((e=e||self).path,e.fs,e.worker_threads,e.perf_hooks,e.os)}(this,(function(e,t,n,r,a){"use strict";e=e&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e,t=t&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t,n=n&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n,r=r&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r,a=a&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a;class s{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class o{refCount(e){return i("refCount")}incRef(e){return i("incRef")}timerAvailable(){return!0}time(e){return i("time")}read(e){return i("read")}readSync(e){return i("readSync")}numDataIds(){return i("numDataIds")}disposeData(e,t){return i("disposeData")}write(e,t,n){return i("write")}move(e,t,n,r,a){return i("move")}memory(){return i("memory")}floatPrecision(){return i("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return i("dispose")}}function i(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function u(e,t,n){return Math.max(e,Math.min(t,n))}function l(e){return e%2==0?e:e+1}function c(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function d(e,t,n=""){c(f(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function p(e,t=[],n=!1){if(null==t&&(t=[]),Array.isArray(e)||S(e)&&!n)for(let r=0;r<e.length;++r)p(e[r],t,n);else t.push(e);return t}function h(e){if(0===e.length)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function f(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function m(e){return e%1==0}function g(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function y(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function b(e,t=(e=>0),n){return new Promise((r,a)=>{let s=0;const o=()=>{if(e())return void r();s++;const i=t(s);null!=n&&s>=n?a():setTimeout(o,i)};o()})}function x(e,t){let n=1,r=-1;for(let t=0;t<e.length;++t)if(e[t]>=0)n*=e[t];else if(-1===e[t]){if(-1!==r)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${r} and dim ${t}`);r=t}else if(e[t]<0)throw Error(`Shapes can not be < 0. Found ${e[t]} at dim ${t}`);if(-1===r){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(0===n)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!=0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);const a=e.slice();return a[r]=t/n,a}function k(e,t){const n=t.length;return c((e=null==e?t.map((e,t)=>t):[].concat(e)).every(e=>e>=-n&&e<n),()=>`All values in axis param must be in range [-${n}, ${n}) but got axis `+e),c(e.every(e=>m(e)),()=>"All values in axis param must be integers but got axis "+e),e.map(e=>e<0?n+e:e)}function w(e,t){const n=[],r=[],a=null!=t&&Array.isArray(t)&&0===t.length,s=null==t||a?null:k(t,e).sort();let o=0;for(let t=0;t<e.length;++t){if(null!=s){if(s[o]===t&&1!==e[t])throw new Error(`Can't squeeze axis ${t} since its dim '${e[t]}' is not 1`);(null==s[o]||s[o]>t)&&1===e[t]&&(n.push(e[t]),r.push(t)),s[o]<=t&&o++}1!==e[t]&&(n.push(e[t]),r.push(t))}return{newShape:n,keptDims:r}}function v(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else{if("bool"!==e)throw new Error("Unknown data type "+e);n=new Uint8Array(t)}return n}function I(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else if("bool"===e)n=new Uint8Array(t);else{if("string"!==e)throw new Error("Unknown data type "+e);n=new Array(t)}return n}function N(e,t){return"complex64"!==t&&(("float32"!==t||"complex64"===e)&&(("int32"!==t||"float32"===e||"complex64"===e)&&("bool"!==t||"bool"!==e)))}function S(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function C(e){if("float32"===e||"int32"===e)return 4;if("complex64"===e)return 8;if("bool"===e)return 1;throw new Error("Unknown dtype "+e)}function T(e){return"string"==typeof e||e instanceof String}function E(e){return Array.isArray(e)?E(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":"number"==typeof e?"float32":T(e)?"string":function(e){return"boolean"==typeof e}(e)?"bool":"float32"}function $(e){return!!(e&&e.constructor&&e.call&&e.apply)}function _(e,t){for(let n=t;n<e;++n)if(e%n==0)return n;return e}function A(e){const t=e.length;if(t<2)return[];const n=new Array(t-1);n[t-2]=e[t-1];for(let r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}function R(e,t){if(0===e.length)return t[0];const n=e.reduce((e,t)=>e*t);if(0===n)return[];if(n!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}.`);return function e(t,n,r){const a=new Array;if(1===n.length){const e=n[0];for(let n=0;n<e;n++)a[n]=r[t+n]}else{const s=n[0],o=n.slice(1),i=o.reduce((e,t)=>e*t);for(let n=0;n<s;n++)a[n]=e(t+n*i,o,r)}return a}(0,e,t)}function M(e,t){if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t)return new Uint8Array(e);throw new Error("Unknown data type "+t)}function F(e,t){const n=e.reduce((e,t)=>e*t,1);if(null==t||"float32"===t)return R(e,new Float32Array(n));if("int32"===t)return R(e,new Int32Array(n));if("bool"===t)return R(e,new Uint8Array(n));throw new Error("Unknown data type "+t)}function D(e){e.forEach(t=>{c(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function O(e,t,n){if(0===t)return 0;if(1===t)return e[0];let r=e[e.length-1];for(let t=0;t<e.length-1;++t)r+=n[t]*e[t];return r}function P(e,t,n){if(0===t)return[];if(1===t)return[e];const r=new Array(t);for(let t=0;t<r.length-1;++t)r[t]=Math.floor(e/n[t]),e-=r[t]*n[t];return r[r.length-1]=e,r}function L(e){return e&&e.then&&"function"==typeof e.then}class B{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${t}.`),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},null!=this.urlFlags[e]){const t=this.urlFlags[e];console.warn(`Setting feature override from URL ${e}: ${t}.`),this.set(e,t)}}async getAsync(e){return e in this.flags||(this.flags[e]=await this.evaluateFlag(e)),this.flags[e]}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(L(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(null==this.flagRegistry[e])throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,null!=this.flagRegistry[e].setHook&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(null==this.flagRegistry[e])throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if("undefined"==typeof this.global||"undefined"==typeof this.global.location||"undefined"==typeof this.global.location.search)return;const e=function(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(e,...n)=>(function(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}(t,n[0],n[1]),n.join("="))),t}(this.global.location.search);if("tfjsflags"in e){e.tfjsflags.split(",").forEach(e=>{const[t,n]=e.split(":");this.urlFlags[t]=function(e,t){if("true"===(t=t.toLowerCase())||"false"===t)return"true"===t;if(""+ +t===t)return+t;throw new Error(`Could not parse value flag value ${t} for flag ${e}.`)}(t,n)})}}}function W(){return V}let z,V=null;function U(){if(null==z){let e;if("undefined"!=typeof window)e=window;else if("undefined"!=typeof global)e=global;else if("undefined"!=typeof process)e=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");e=self}z=e}return z}function G(e,t){const n=function(){const e=U();return null==e._tfGlobals&&(e._tfGlobals=new Map),e._tfGlobals}();if(n.has(e))return n.get(e);{const r=t();return n.set(e,r),n.get(e)}}const H=G("kernelRegistry",()=>new Map),j=G("gradRegistry",()=>new Map);function q(e,t){const n=Q(e,t);return H.get(n)}function K(e){return j.get(e)}function X(e){const t=H.entries(),n=[];for(;;){const{done:r,value:a}=t.next();if(r)break;const[s,o]=a,[i]=s.split("_");i===e&&n.push(o)}return n}function Y(e){const{kernelName:t,backendName:n}=e,r=Q(t,n);H.has(r)&&console.warn(`The kernel '${t}' for backend '${n}' is already registered`),H.set(r,e)}function Q(e,t){return`${t}_${e}`}function J(e,t){return"string"===t?te(e):Z([e],t)}function Z(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=p(e)),W().getBool("DEBUG")&&function(e,t){for(let n=0;n<e.length;n++){const r=e[n];if(isNaN(r)||!isFinite(r))throw Error(`A tensor of type ${t} being uploaded contains ${r}.`)}}(e,t),function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t))return e;if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t){const t=new Uint8Array(e.length);for(let n=0;n<t.length;++n)0!==Math.round(e[n])&&(t[n]=1);return t}throw new Error("Unknown data type "+t)}function ee(){return W().platform.now()}function te(e,t="utf-8"){return t=t||"utf-8",W().platform.encode(e,t)}function ne(e,t="utf-8"){return t=t||"utf-8",W().platform.decode(e,t)}class re{constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new se)}profileKernel(e,t,n){let r;const a=()=>{r=n()};let s;const o=ee();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(a);else{a();for(const e of r)e.dataSync();s=Promise.resolve({kernelMs:ee()-o})}if(W().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t<r.length;t++){const n=r[t];n.data().then(t=>{ae(t,n.dtype,e)})}return{kernelName:e,outputs:r,inputs:t,timeMs:s.then(e=>e.kernelMs),extraInfo:s.then(e=>null!=e.getExtraProfileInfo?e.getExtraProfileInfo():"")}}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:r,inputs:a,extraInfo:s}=e;n.forEach(e=>{Promise.all([e.data(),r,s]).then(n=>{this.logger.logKernelProfile(t,e,n[0],n[1],a,n[2])})})}}function ae(e,t,n){if("float32"!==t)return!1;for(let t=0;t<e.length;t++){const r=e[t];if(isNaN(r)||!isFinite(r))return console.warn(`Found ${r} in the result of '${n}'`),!0}return!1}class se{logKernelProfile(e,t,n,r,a,s){const o="number"==typeof r?y(r+"ms",9):r.error,i=y(e,25),u=t.rank,l=t.size,c=y(t.shape.toString(),14);let d="";for(const e in a){const n=a[e];if(null!=n){const r=n.shape||t.shape,a=r.length;d+=`${e}: ${a}D ${a>0?r:""} `}}console.log(`%c${i}\t%c${o}\t%c${u}D ${c}\t%c${l}\t%c${d}\t%c${s}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function oe(e,t,n,r){const a=A(t),s=function(e,t,n,r){const a=h(t),s=r[r.length-1],o=new Array(s).fill(0),i=t.length,u="complex64"===n?le(e):e;if(i>1)for(let e=0;e<a/s;e++){const t=e*s;for(let e=0;e<s;e++)o[e]=Math.max(o[e],ie(u[t+e],0,n).length)}return o}(e,t,n,a),o=t.length,i=function e(t,n,r,a,s,o=!0){const i="complex64"===r?2:1,u=n[0],l=n.length;if(0===l){if("complex64"===r){return[ie(le(t)[0],0,r)]}return"bool"===r?[ue(t[0])]:[t[0].toString()]}if(1===l){if(u>20){const e=3*i;let n=Array.from(t.slice(0,e)),a=Array.from(t.slice((u-3)*i,u*i));return"complex64"===r&&(n=le(n),a=le(a)),["["+n.map((e,t)=>ie(e,s[t],r)).join(", ")+", ..., "+a.map((e,t)=>ie(e,s[u-3+t],r)).join(", ")+"]"]}return["["+("complex64"===r?le(t):Array.from(t)).map((e,t)=>ie(e,s[t],r)).join(", ")+"]"]}const c=n.slice(1),d=a.slice(1),p=a[0]*i,h=[];if(u>20){for(let n=0;n<3;n++){const a=n*p,o=a+p;h.push(...e(t.slice(a,o),c,r,d,s,!1))}h.push("...");for(let n=u-3;n<u;n++){const a=n*p,o=a+p;h.push(...e(t.slice(a,o),c,r,d,s,n===u-1))}}else for(let n=0;n<u;n++){const a=n*p,o=a+p;h.push(...e(t.slice(a,o),c,r,d,s,n===u-1))}const f=2===l?",":"";h[0]="["+h[0]+f;for(let e=1;e<h.length-1;e++)h[e]=" "+h[e]+f;let m=",\n";for(let e=2;e<l;e++)m+="\n";return h[h.length-1]=" "+h[h.length-1]+"]"+(o?"":m),h}(e,t,n,a,s),u=["Tensor"];return r&&(u.push("  dtype: "+n),u.push("  rank: "+o),u.push(`  shape: [${t}]`),u.push("  values:")),u.push(i.map(e=>"    "+e).join("\n")),u.join("\n")}function ie(e,t,n){let r;return r=Array.isArray(e)?parseFloat(e[0].toFixed(7))+" + "+parseFloat(e[1].toFixed(7))+"j":T(e)?`'${e}'`:"bool"===n?ue(e):parseFloat(e.toFixed(7)).toString(),y(r,t)}function ue(e){return 0===e?"false":"true"}function le(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class ce{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=h(e),null!=n){const e=n.length;c(e===this.size,()=>`Length of values '${e}' does not match the size inferred by the shape '${this.size}'.`)}if("complex64"===t)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||I(t,this.size),this.strides=A(e)}set(e,...t){0===t.length&&(t=[0]),c(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);const n=this.locToIndex(t);this.values[n]=e}get(...e){0===e.length&&(e=[0]);let t=0;for(const n of e){if(n<0||n>=this.shape[t]){const t=`Requested out of range element at ${e}.   Buffer shape=`+this.shape;throw new Error(t)}t++}let n=e[e.length-1];for(let t=0;t<e.length-1;++t)n+=this.strides[t]*e[t];return this.values[n]}locToIndex(e){if(0===this.rank)return 0;if(1===this.rank)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(0===this.rank)return[];if(1===this.rank)return[e];const t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return de().makeTensor(this.values,this.shape,this.dtype)}}let de=null,pe=null;class he{constructor(e,t,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=h(e),this.strides=A(e),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return pe.buffer(this.shape,this.dtype,e)}bufferSync(){return pe.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return R(this.shape,e)}arraySync(){return R(this.shape,this.dataSync())}async data(){this.throwIfDisposed();const e=de().read(this.dataId);if("string"===this.dtype){const t=await e;try{return t.map(e=>ne(e))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataSync(){this.throwIfDisposed();const e=de().readSync(this.dataId);if("string"===this.dtype)try{return e.map(e=>ne(e))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await de().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(de().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return pe.print(this,e)}clone(){return this.throwIfDisposed(),pe.clone(this)}toString(e=!1){return oe(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),pe.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),de().makeVariable(this,e,t,n)}}Object.defineProperty(he,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),G("Tensor",()=>he);class fe extends he{constructor(e,t,n,r){super(e.shape,e.dtype,e.dataId,r),this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!f(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);de().disposeTensor(this),this.dataId=e.dataId,de().incRef(this,null)}dispose(){de().disposeVariable(this),this.isDisposedInternal=!0}}var me,ge,ye,be,xe;Object.defineProperty(fe,Symbol.hasInstance,{value:e=>e instanceof he&&null!=e.assign&&e.assign instanceof Function}),function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"}(me||(me={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(ge||(ge={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(ye||(ye={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(be||(be={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(xe||(xe={}));const ke={float32:be,int32:ge,bool:ye,complex64:xe};function we(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return ke[e][t]}function ve(e){return we(e,"int32")}function Ie(e){const t=[];return function e(t,n,r){if(null==t)return;if(t instanceof he)return void n.push(t);if(a=t,!Array.isArray(a)&&"object"!=typeof a)return;var a;const s=t;for(const t in s){const a=s[t];r.has(a)||(r.add(a),e(a,n,r))}}(e,t,new Set),t}function Ne(e){return null!=e.kernelName}class Se{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null,get kernelNames(){return Array.from(new Set(this.kernels.map(e=>e.name)))}}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class Ce{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Se}async ready(){if(null!=this.pendingBackendInit)return this.pendingBackendInit.then(()=>{});if(null!=this.backendInstance)return;const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t];if(await this.initializeBackend(n).success)return void await this.setBackend(n)}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(null!=this.pendingBackendInit)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(null==this.backendInstance){const{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry)){if(!(e in this.registryFactory))return null;{const{asyncInit:t}=this.initializeBackend(e);if(t)return null}}return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(console.warn(e+" backend was already registered. Reusing existing backend factory."),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(null==this.registryFactory[e])throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,null==this.registry[e]){this.backendInstance=null;const{success:t,asyncInit:n}=this.initializeBackend(e);if(!(n?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new re(this.backendInstance),!0}setupRegisteredKernels(){X(this.backendName).forEach(e=>{null!=e.setupFunc&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){X(e).forEach(t=>{null!=t.disposeFunc&&t.disposeFunc(this.registry[e])})}initializeBackend(e){const t=this.registryFactory[e];if(null==t)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const n=t.factory();if(!n||n instanceof o||"function"!=typeof n.then)return this.registry[e]=n,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,r=n.then(n=>!(t<this.pendingBackendInitId)&&(this.registry[e]=n,this.pendingBackendInit=null,!0)).catch(n=>(t<this.pendingBackendInitId||(this.pendingBackendInit=null,console.warn(`Initialization of backend ${e} failed`),console.warn(n.stack||n.message)),!1));return this.pendingBackendInit=r,{success:r,asyncInit:!0}}}catch(t){return console.warn(`Initialization of backend ${e} failed`),console.warn(t.stack||t.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(e+" backend not found in registry");this.backendName===e&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],{success:r,asyncInit:a}=this.initializeBackend(n);if(a||r)return{name:n,asyncInit:a}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const n=this.state.tensorInfo.get(t),r=n.backend,a=this.readSync(t),s=r.refCount(t);r.disposeData(t,!0),n.backend=e,e.move(t,a,n.shape,n.dtype,s),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n,r=null;if(null==t){if("function"!=typeof e)throw new Error("Please provide a function to tidy()");t=e}else{if("string"!=typeof e&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof t)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");r=e}return this.scopedRun(()=>this.startScope(r),()=>this.endScope(n),()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n))}scopedRun(e,t,n){e();try{const e=n();return t(),e}catch(e){throw t(),e}}nextTensorId(){return Ce.nextTensorId++}nextVariableId(){return Ce.nextVariableId++}clone(e){const t=Ee.runKernel("Identity",{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],e=>({x:()=>{const t={x:e},n={dtype:"float32"};return Ee.runKernel("Cast",t,n)}}),[],{}),t}runKernel(e,t,n){if(!(null!=q(e,this.backendName)))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const r=this.backend.numDataIds();let a=0;n.forEach(e=>{a+="complex64"===e.dtype?3:1});const s=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],o=r-t-a-s;if(o>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${o} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[];const r=this.isTapeOn(),a=this.state.numBytes,s=this.state.numTensors;let o,i;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const u=Ne(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(Ne(e)){const{kernelName:t,inputs:a,attrs:s}=e;null==this.backendName&&this.backend;const u=q(t,this.backendName);c(null!=u,()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`),o=()=>{const e=this.backend.numDataIds();i=u.kernelFunc({inputs:a,attrs:s,backend:this.backend});const o=Array.isArray(i)?i:[i];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,o);const l=o.map(e=>{if(null!=e.rank)return e;const{dataId:t,shape:n,dtype:r}=e;return this.makeTensorFromDataId(t,n,r)});if(r){const e=this.getTensorsForGradient(t,a,l);n=this.saveTensorsForBackwardMode(e)}return l}}else{const{forwardFunc:t}=e,a=e=>{r&&(n=e.map(e=>this.keep(this.clone(e))))};o=()=>{const e=this.backend.numDataIds();i=this.tidy(()=>t(this.backend,a));const n=Array.isArray(i)?i:[i];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(u,e,n),n}}const{inputs:l,attrs:d}=e,p=Ne(e)?null:e.backwardsFunc;let h;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(h=this.profiler.profileKernel(u,l,()=>o()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(h),t=h.outputs):t=o()}),r&&this.addTapeNode(u,l,t,p,n,d),this.state.profiling&&this.state.activeProfile.kernels.push({name:u,bytesAdded:this.state.numBytes-a,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-s,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(l).map(e=>null!=l[e]?l[e].shape:null),outputShapes:t.map(e=>e.shape),kernelTimeMs:h.timeMs,extraInfo:h.extraInfo}),Array.isArray(i)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(e=>this.keep(this.clone(e)))}getTensorsForGradient(e,t,n){const r=K(e);if(null!=r){const e=r.inputsToSave||[],a=r.outputsToSave||[];let s;r.saveAllInputs?(c(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),s=Object.keys(t).map(e=>t[e])):s=e.map(e=>t[e]);const o=n.filter((e,t)=>a[t]);return s.concat(o)}return[]}makeTensor(e,t,n,r){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;let a=e;"string"===n&&T(e[0])&&(a=e.map(e=>te(e)));const s=r.write(a,t,n),o=new he(t,n,s,this.nextTensorId());if(this.trackTensor(o,r),"string"===n){const e=this.state.tensorInfo.get(s),t=function(e){if(null==e)return 0;let t=0;return e.forEach(e=>t+=e.length),t}(a);this.state.numBytes+=t-e.bytes,e.bytes=t}return o}makeTensorFromDataId(e,t,n,r){const a=new he(t,n=n||"float32",e,this.nextTensorId());return this.trackTensor(a,r),a}makeVariable(e,t=!0,n,r){n=n||this.nextVariableId().toString(),null!=r&&r!==e.dtype&&(e=e.cast(r));const a=new fe(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[a.name])throw new Error(`Variable with name ${a.name} was already registered`);return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a}trackTensor(e,t){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*C(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof fe||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;const t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,"string"===e.dtype&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),"complex64"!==e.dtype&&"string"!==e.dtype){const t=e.size*C(e.dtype);this.state.numBytes-=t}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),null!=this.state.registeredVariables[e.name]&&delete this.state.registeredVariables[e.name]}memory(){const e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,null==e.reasons&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(e=>e.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const e of this.state.activeProfile.kernels)e.kernelTimeMs=await e.kernelTimeMs,e.extraInfo=await e.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&0===this.state.kernelDepth}addTapeNode(e,t,n,r,a,s){const o={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:a},i=K(e);null!=i&&(r=i.gradFunc),null!=r&&(o.gradient=e=>(e=e.map((e,t)=>{if(null==e){const e=n[t],r=M(e.size,e.dtype);return this.makeTensor(r,e.shape,e.dtype)}return e}),r(e.length>1?e:e[0],a,s))),this.state.activeTape.push(o)}keep(e){return e.kept=!0,e}startTape(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=Ie(e),n=new Set(t.map(e=>e.id));for(let e=0;e<this.state.activeScope.track.length;e++){const t=this.state.activeScope.track[e];t.kept||n.has(t.id)||t.dispose()}const r=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(e=>{e.kept||e.scopeId!==r.id||this.track(e)})}gradients(e,t,n,r=!1){if(c(t.length>0,()=>"gradients() received an empty list of xs."),null!=n&&"float32"!==n.dtype)throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);const a=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));c(a instanceof he,()=>"The result y returned by f() must be a tensor.");const s=function(e,t,n){const r={},a={};for(let e=0;e<t.length;e++)r[t[e].id]=!0;for(let n=0;n<e.length;n++){const s=e[n],o=s.inputs;for(const e in o){const n=o[e];let i=!1;for(let e=0;e<t.length;e++)if(r[n.id]){s.outputs.forEach(e=>r[e.id]=!0),i=!0,a[s.id]=!0;break}if(i)break}}const s={};s[n.id]=!0;const o={};for(let t=e.length-1;t>=0;t--){const n=e[t],r=n.inputs;for(let e=0;e<n.outputs.length;e++)if(s[n.outputs[e].id]){for(const e in r)s[r[e].id]=!0,o[n.id]=!0;break}}const i=[];for(let t=0;t<e.length;t++){const n=e[t];if(a[n.id]&&o[n.id]){const e={};for(const t in n.inputs){const a=n.inputs[t];r[a.id]&&(e[t]=a)}const t=Object.assign({},n);t.inputs=e,t.outputs=n.outputs,i.push(t)}}return i}(this.state.activeTape,t,a);if(!r&&0===s.length&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",()=>{const e={};e[a.id]=null==n?function(e){const t=function(e,t){const n=M(e,t);for(let e=0;e<n.length;e++)n[e]=1;return n}(h(e),"float32");return Ee.makeTensor(t,e,"float32")}(a.shape):n,function(e,t,n,r){for(let a=t.length-1;a>=0;a--){const s=t[a],o=[];if(s.outputs.forEach(t=>{const n=e[t.id];null!=n?o.push(n):o.push(null)}),null==s.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);const i=s.gradient(o);for(const t in s.inputs){if(!(t in i))throw new Error(`Cannot backprop through input ${t}. Available gradients found: ${Object.keys(i)}.`);const a=n(()=>i[t]());if("float32"!==a.dtype)throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${t} must have 'float32' dtype, but has '${a.dtype}'`);const o=s.inputs[t];if(!f(a.shape,o.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${t}' has shape '${a.shape}', which does not match the shape of the input '${o.shape}'`);if(null==e[o.id])e[o.id]=a;else{const t=e[o.id];e[o.id]=r(t,a),t.dispose()}}}}(e,s,e=>this.tidy(e),$e);const r=t.map(t=>e[t.id]);return 0===this.state.gradientDepth&&(this.state.activeTape.forEach(e=>{for(const t of e.saved)t.dispose()}),this.state.activeTape=null),{value:a,grads:r}})}customGrad(e){return c($(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{let n;c(t.every(e=>e instanceof he),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");const r={};t.forEach((e,t)=>{r[t]=e});return this.runKernelFunc({forwardFunc:(r,a)=>(n=e(...t,a),c(n.value instanceof he,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),c($(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),backwardsFunc:(e,r)=>{const a=n.gradFunc(e,r),s=Array.isArray(a)?a:[a];c(s.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),c(s.every(e=>e instanceof he),()=>"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 o={};return s.forEach((e,t)=>{o[t]=()=>e}),o},inputs:r})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}async time(e){const t=ee(),n=await this.backend.time(e);return n.wallMs=ee()-t,n}track(e){return null!=this.state.activeScope&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new Se;for(const e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}function Te(){const e=U();if(null==e._tfengine){const t=new B(e);e._tfengine=new Ce(t)}var t;return t=e._tfengine.ENV,V=t,de=()=>e._tfengine,e._tfengine}Ce.nextTensorId=0,Ce.nextVariableId=0;const Ee=Te();function $e(e,t){const n={a:e,b:t};return Ee.runKernel("Add",n)}function _e(){if("undefined"!=typeof navigator&&null!=navigator){const e=navigator.userAgent||navigator.vendor||window.opera;return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(e)||/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(e.substr(0,4))}return!1}function Ae(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}const Re=W();function Me(e,t){let n=e;if(S(e))return"string"===t?[]:[e.length];if(!Array.isArray(e))return[];const r=[];for(;Array.isArray(n)||S(n)&&"string"!==t;)r.push(n.length),n=n[0];return Array.isArray(e)&&W().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&function e(t,n,r){if(r=r||[],!Array.isArray(t)&&!S(t))return void c(0===n.length,()=>`Element arr[${r.join("][")}] is a primitive, but should be an array/TypedArray of ${n[0]} elements`);c(n.length>0,()=>`Element arr[${r.join("][")}] should be a primitive, but is an array of ${t.length} elements`),c(t.length===n[0],()=>`Element arr[${r.join("][")}] should have ${n[0]} elements, but has ${t.length} elements`);const a=n.slice(1);for(let n=0;n<t.length;++n)e(t[n],a,r.concat(n))}(e,r,[]),r}function Fe(e,t,n,r){if("string_or_numeric"!==e){if(null==e)throw new Error("Expected dtype cannot be null.");if("numeric"!==e&&e!==t||"numeric"===e&&"string"===t)throw new Error(`Argument '${n}' passed to '${r}' must be ${e} tensor, but got ${t} tensor`)}}function De(e,t,n,r="numeric"){if(e instanceof he)return Fe(r,e.dtype,t,n),e;let a=E(e);if("string"!==a&&["bool","int32","float32"].indexOf(r)>=0&&(a=r),Fe(r,a,t,n),null==e||!S(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e){const r=null==e?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${r}'`)}const s=Me(e,a);S(e)||Array.isArray(e)||(e=[e]);const o="string"!==a?Z(e,a):p(e,[],!0);return Ee.makeTensor(o,s,a)}Re.registerFlag("DEBUG",()=>!1,e=>{e&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")}),Re.registerFlag("IS_BROWSER",()=>Ae()),Re.registerFlag("IS_NODE",()=>"undefined"!=typeof process&&"undefined"!=typeof process.versions&&"undefined"!=typeof process.versions.node),Re.registerFlag("IS_CHROME",()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)),Re.registerFlag("PROD",()=>!1),Re.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Re.getBool("DEBUG")),Re.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0),Re.registerFlag("IS_TEST",()=>!1),Re.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0),Re.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);function Oe(e){const t=Object.keys(e);if(1!==t.length)throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with "+t.length+" keys.");let n=t[0];const r=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n+="__op";const a=(...e)=>{Ee.startScope(n);try{const t=r(...e);return L(t)&&console.error("Cannot return a Promise inside of tidy."),Ee.endScope(t),t}catch(e){throw Ee.endScope(null),e}};return Object.defineProperty(a,"name",{value:n,configurable:!0}),a}const Pe=Oe({complex_:function(e,t){const n=De(e,"real","complex"),r=De(t,"imag","complex");d(n.shape,r.shape,`real and imag shapes, ${n.shape} and ${r.shape}, must match in call to tf.complex().`);const a={real:n,imag:r};return Ee.runKernel("Complex",a)}});const Le="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function Be(e){return Le?Buffer.byteLength(e):new Blob([e]).size}function We(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:null==e.modelTopology?0:Be(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:Be(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:e.weightData.byteLength}}class ze{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==ze.instance&&(ze.instance=new ze),ze.instance}static registerSaveRouter(e){ze.getInstance().saveRouters.push(e)}static registerLoadRouter(e){ze.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return ze.getHandlers(e,"save")}static getLoadHandlers(e,t){return ze.getHandlers(e,"load",t)}static getHandlers(e,t,n){const r=[];return("load"===t?ze.getInstance().loadRouters:ze.getInstance().saveRouters).forEach(t=>{const a=t(e,n);null!==a&&r.push(a)}),r}}function Ve(){if(!W().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const e="undefined"==typeof window?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==t)throw new Error("The current browser does not appear to support IndexedDB.");return t}function Ue(e){const t=e.result;t.createObjectStore("models_store",{keyPath:"modelPath"}),t.createObjectStore("model_info_store",{keyPath:"modelPath"})}class Ge{constructor(e){if(this.indexedDB=Ve(),null==e||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise((e,n)=>{const r=this.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=()=>Ue(r),r.onsuccess=()=>{const a=r.result;if(null==t){const t=a.transaction("models_store","readonly"),r=t.objectStore("models_store").get(this.modelPath);r.onsuccess=()=>{if(null==r.result)return a.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));e(r.result.modelArtifacts)},r.onerror=e=>(a.close(),n(r.error)),t.oncomplete=()=>a.close()}else{const r=We(t),s=a.transaction("model_info_store","readwrite");let o=s.objectStore("model_info_store");const i=o.put({modelPath:this.modelPath,modelArtifactsInfo:r});let u;i.onsuccess=()=>{u=a.transaction("models_store","readwrite");const i=u.objectStore("models_store").put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:r});i.onsuccess=()=>e({modelArtifactsInfo:r}),i.onerror=e=>{o=s.objectStore("model_info_store");const t=o.delete(this.modelPath);t.onsuccess=()=>(a.close(),n(i.error)),t.onerror=e=>(a.close(),n(i.error))}},i.onerror=e=>(a.close(),n(i.error)),s.oncomplete=()=>{null==u?a.close():u.oncomplete=()=>a.close()}}},r.onerror=e=>n(r.error)})}}Ge.URL_SCHEME="indexeddb://";const He=e=>{return W().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Ge.URL_SCHEME)?(t=e.slice(Ge.URL_SCHEME.length),new Ge(t)):null;var t};ze.registerSaveRouter(He),ze.registerLoadRouter(He);class je{constructor(){this.indexedDB=Ve()}async listModels(){return new Promise((e,t)=>{const n=this.indexedDB.open("tensorflowjs",1);n.onupgradeneeded=()=>Ue(n),n.onsuccess=()=>{const r=n.result,a=r.transaction("model_info_store","readonly"),s=a.objectStore("model_info_store").getAll();s.onsuccess=()=>{const t={};for(const e of s.result)t[e.modelPath]=e.modelArtifactsInfo;e(t)},s.onerror=e=>(r.close(),t(s.error)),a.oncomplete=()=>r.close()},n.onerror=e=>t(n.error)})}async removeModel(e){var t;return e=(t=e).startsWith(Ge.URL_SCHEME)?t.slice(Ge.URL_SCHEME.length):t,new Promise((t,n)=>{const r=this.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=()=>Ue(r),r.onsuccess=()=>{const a=r.result,s=a.transaction("model_info_store","readwrite"),o=s.objectStore("model_info_store"),i=o.get(e);let u;i.onsuccess=()=>{if(null==i.result)return a.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const r=o.delete(e),s=()=>{u=a.transaction("models_store","readwrite");const r=u.objectStore("models_store").delete(e);r.onsuccess=()=>t(i.result.modelArtifactsInfo),r.onerror=e=>n(i.error)};r.onsuccess=s,r.onerror=e=>(s(),a.close(),n(i.error))}},i.onerror=e=>(a.close(),n(i.error)),s.oncomplete=()=>{null==u?a.close():u.oncomplete=()=>a.close()}},r.onerror=e=>n(r.error)})}}const qe="tensorflowjs_models",Ke="info",Xe="model_topology",Ye="weight_specs",Qe="weight_data",Je="model_metadata";function Ze(e){return{info:[qe,e,Ke].join("/"),topology:[qe,e,Xe].join("/"),weightSpecs:[qe,e,Ye].join("/"),weightData:[qe,e,Qe].join("/"),modelMetadata:[qe,e,Je].join("/")}}function et(e){const t=e.split("/");if(t.length<3)throw new Error("Invalid key format: "+e);return t.slice(1,t.length-1).join("/")}class tt{constructor(e){if(!W().getBool("IS_BROWSER")||"undefined"==typeof window||"undefined"==typeof window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==e||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=Ze(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{const t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),r=We(e);try{this.LS.setItem(this.keys.info,JSON.stringify(r)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(e){if(Le)return Buffer.from(e).toString("base64");const t=new Uint8Array(e);let n="";for(let e=0,r=t.length;e<r;e++)n+=String.fromCharCode(t[e]);return btoa(n)}(e.weightData));const a={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};return null!=e.signature&&(a.signature=e.signature),null!=e.userDefinedMetadata&&(a.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(a.modelInitializer=e.modelInitializer),this.LS.setItem(this.keys.modelMetadata,JSON.stringify(a)),{modelArtifactsInfo:r}}catch(e){throw this.LS.removeItem(this.keys.info),this.LS.removeItem(this.keys.topology),this.LS.removeItem(this.keys.weightSpecs),this.LS.removeItem(this.keys.weightData),this.LS.removeItem(this.keys.modelMetadata),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${r.modelTopologyBytes}, weightSpecsBytes=${r.weightSpecsBytes}, weightDataBytes=${r.weightDataBytes}.`)}}}async load(){const e=JSON.parse(this.LS.getItem(this.keys.info));if(null==e)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if("JSON"!==e.modelTopologyType)throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");const t={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(null==n)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=n;const r=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(null==r)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=r;const a=this.LS.getItem(this.keys.modelMetadata);if(null!=a){const e=JSON.parse(a);t.format=e.format,t.generatedBy=e.generatedBy,t.convertedBy=e.convertedBy,null!=e.signature&&(t.signature=e.signature),null!=e.userDefinedMetadata&&(t.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(t.modelInitializer=e.modelInitializer)}const s=this.LS.getItem(this.keys.weightData);if(null==s)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=function(e){if(Le){const t=Buffer.from(e,"base64");return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n.set([t.charCodeAt(e)],e);return n.buffer}(s),t}}tt.URL_SCHEME="localstorage://";const nt=e=>{return W().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(tt.URL_SCHEME)?(t=e.slice(tt.URL_SCHEME.length),new tt(t)):null;var t};ze.registerSaveRouter(nt),ze.registerLoadRouter(nt);class rt{constructor(){c(W().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),c("undefined"==typeof window||"undefined"!=typeof window.localStorage,()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){const e={},t=qe+"/",n="/"+Ke;for(let r=0;r<this.LS.length;++r){const a=this.LS.key(r);if(a.startsWith(t)&&a.endsWith(n)){e[et(a)]=JSON.parse(this.LS.getItem(a))}}return e}async removeModel(e){var t;const n=Ze(e=(t=e).startsWith(tt.URL_SCHEME)?t.slice(tt.URL_SCHEME.length):t);if(null==this.LS.getItem(n.info))throw new Error(`Cannot find model at path '${e}'`);const r=JSON.parse(this.LS.getItem(n.info));return this.LS.removeItem(n.info),this.LS.removeItem(n.topology),this.LS.removeItem(n.weightSpecs),this.LS.removeItem(n.weightData),r}}class at{constructor(){this.managers={}}static getInstance(){return null==at.instance&&(at.instance=new at),at.instance}static registerManager(e,t){c(null!=e,()=>"scheme must not be undefined or null."),e.endsWith("://")&&(e=e.slice(0,e.indexOf("://"))),c(e.length>0,()=>"scheme must not be an empty string.");const n=at.getInstance();c(null==n.managers[e],()=>`A model store manager is already registered for scheme '${e}'.`),n.managers[e]=t}static getManager(e){const t=this.getInstance().managers[e];if(null==t)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(this.getInstance().managers)}}class st{fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error("Browser's encoder only supports utf-8, but got "+t);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}}if(W().get("IS_BROWSER")){W().setPlatform("browser",new st);try{at.registerManager(tt.URL_SCHEME,new rt)}catch(e){}try{at.registerManager(Ge.URL_SCHEME,new je)}catch(e){}}const ot=()=>require("node-fetch");let it;class ut{constructor(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return null!=W().global.fetch?W().global.fetch(e,t):(null==it&&(it=ot()),it(e,t))}now(){const e=process.hrtime();return 1e3*e[0]+e[1]/1e6}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error("Node built-in encoder only supports utf-8, but got "+t);return this.textEncoder.encode(e)}decode(e,t){return 0===e.length?"":new this.util.TextDecoder(t).decode(e)}}function lt(e,t="float32",n){return t=t||"float32",D(e),new ce(e,t,n)}W().get("IS_NODE")&&W().setPlatform("node",new ut);const ct=Oe({cast_:function(e,t){const n=De(e,"x","cast");if(!function(e){return"bool"===e||"complex64"===e||"float32"===e||"int32"===e||"string"===e}(t))throw new Error("Failed to cast to unknown dtype "+t);if("string"===t&&"string"!==n.dtype||"string"!==t&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");const r={x:n},a={dtype:t};return Ee.runKernel("Cast",r,a)}});const dt=Oe({clone_:function(e){const t={x:De(e,"x","clone","string_or_numeric")};return Ee.runKernel("Identity",t)}});Te();function pt(e,t){const n=e.shape.length,r=t.shape.length;if(n<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${n}.`);if(r<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${r}.`);if("int32"!==t.dtype)throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[r-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[r-1]} vs. ${n}`);if(0===h(e.shape))throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);const a=t.shape,s=a[a.length-1];let o=1;for(let e=0;e<a.length-1;++e)o*=a[e];const i=e.shape,u=a.slice();u.pop();let l=1;for(let e=s;e<n;++e)l*=i[e],u.push(i[e]);const c=[...A(e.shape).map(e=>e/l),1].slice(0,s);return[u,o,l,c]}function ht(e,t,n){const r=t.rank>1?t.shape[t.rank-1]:1,a=t.rank>1?t.rank-1:1,s="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+n.shape+`, indices.shape: ${t.shape}, shape: ${e}`+`, sliceDim: ${r}, and batchDim: ${a}.`;if(n.rank<a)throw new Error(s+` update.rank < ${a}. `);if(e.length<r+(n.rank-a))throw new Error(s+" Output shape length < "+(r+(n.rank-a)));if(n.rank!==a+e.length-r)throw new Error(s+" update.rank != "+(a+e.length-r));for(let e=0;e<a;++e)if(n.shape[e]!==t.shape[e])throw new Error(s+` updates.shape[${e}] (${n.shape[e]}) != indices.shape[${e}] (${t.shape[e]}).`);for(let t=0;t<n.rank-a;++t)if(n.shape[t+a]!==e[t+r])throw new Error(s+` updates.shape[${t+a}] (${n.shape[t+a]}) != shape[${t+a}] (${e[t+a]})`)}function ft(e,t,n){const r=t.shape.length,a=r>1?t.shape[r-1]:1,s=n.length;let o=1;for(let e=a;e<s;++e)o*=n[e];const i=a<1?1:a;return{sliceRank:a,numUpdates:h(t.shape)/i,sliceSize:o,strides:[...A(n.slice(0,a)),1],outputSize:h(n)}}function mt(e,t,n){const r=e.shape.length;c(r===t.length,()=>`Error in slice${r}D: Length of begin ${t} must match the rank of the array (${r}).`),c(r===n.length,()=>`Error in slice${r}D: Length of size ${n} must match the rank of the array (${r}).`);for(let a=0;a<r;++a)c(t[a]+n[a]<=e.shape[a],()=>`Error in slice${r}D: begin[${a}] + size[${a}] (${t[a]+n[a]}) would overflow input.shape[${a}] (${e.shape[a]})`)}function gt(e){const t=[];let n=0;for(;e>0;)1&e&&t.push(n),e/=2,n++;return t}function yt(e,t,n){const r=[];for(let a=0;a<e.length;a++)r[a]=Math.ceil((t[a]-e[a])/n[a]);return r}function bt(e,t,n,r){const a=[...e];for(let e=a.length;e<r.length;e++)a.push(1);for(let e=0;e<n;e++)0===e?a[t]=1:(a.splice(t,0,1),a.pop());return a}function xt(e,t,n){return n<=e?n:n-(t-1)}function kt(e,t){const n=[];for(let r=0;r<e;r++)n.push(t+r);return n}function wt(e,t,n,r,a,s,o,i,u){const l=e.length;let c=new Array(l),d=new Array(l),p=new Array(l);if(t.length&&n>0){const u=t[0],l=n+1;c=vt(o,u,l,r,e),d=It(i,u,l,a,e),p=bt(s,u,l,e)}else for(let t=0;t<l;t++)c[t]=St(o,r,s,e,t,u),d[t]=Ct(i,a,s,e,t,u),p[t]=Nt(s,t,u);return{begin:c,end:d,strides:p}}function vt(e,t,n,r,a){const s=[...a],o=kt(n,t);for(let a=0;a<s.length;a++)if(o.indexOf(a)>-1)s[a]=0;else{const o=xt(t,n,a);let i=r[o];e&1<<o&&(i=0),s[a]=i}return s}function It(e,t,n,r,a){const s=[...a],o=kt(n,t);for(let a=0;a<s.length;a++)if(o.indexOf(a)>-1)s[a]=Number.MAX_SAFE_INTEGER;else{const o=xt(t,n,a);let i=r[o];e&1<<o&&(i=Number.MAX_SAFE_INTEGER),s[a]=i}for(let e=0;e<s.length;e++){const t=a[e];s[e]<0&&(s[e]+=t),s[e]=u(0,s[e],a[e])}return s}function Nt(e,t,n){let r=e[t];return(n&1<<t||null==r)&&(r=1),r}function St(e,t,n,r,a,s){let o=t[a];const i=n[a]||1;(e&1<<a||s&1<<a||null==o)&&(o=i>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);const l=r[a];return o<0&&(o+=l),o=u(0,o,l-1),o}function Ct(e,t,n,r,a,s){let o=t[a];const i=n[a]||1;(e&1<<a||s&1<<a||null==o)&&(o=i>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);const l=r[a];return o<0&&(o+=l),o=i>0?u(0,o,l):u(-1,o,l-1),o}function Tt(e,t,n){let r=n.length;for(let e=0;e<n.length;e++)if(n[e]>1){r=e;break}for(let a=r+1;a<n.length;a++)if(t[a]>0||n[a]!==e[a])return!1;return!0}function Et(e,t){let n=e.length>0?e[e.length-1]:1;for(let r=0;r<e.length-1;r++)n+=e[r]*t[r];return n}function $t(e,t,n){let r;const a=e.shape.length;let s;return r="number"==typeof t?[t,...new Array(a-1).fill(0)]:t.length<a?t.concat(new Array(a-t.length).fill(0)):t.slice(),r.forEach(e=>{c(-1!==e,()=>"slice() does not support negative begin indexing.")}),s=null==n?new Array(a).fill(-1):"number"==typeof n?[n,...new Array(a-1).fill(-1)]:n.length<a?n.concat(new Array(a-n.length).fill(-1)):n,s=s.map((t,n)=>t>=0?t:(c(-1===t,()=>`Negative size values should be exactly -1 but got ${t} for the slice() size at index ${n}.`),e.shape[n]-r[n])),[r,s]}function _t(e,t,n,r,a,s,o,i,u){let l=t.slice(),c=n.slice(),d=r;null==r&&(d=new Array(l.length));const p=gt(o);if(p.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(0!==o&&0!==i)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(0!==o&&0!==u)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");const h=e.length-l.length,f=gt(i),m=e.slice();f.forEach(e=>{l[e]=0,c[e]=1,m.splice(e,0,1)});const{begin:g,end:y,strides:b}=wt(m,p,h,l,c,d,a,s,o);l=g,c=y,d=b;const x=gt(u);x.forEach(e=>{c[e]=l[e]+1,d[e]=1});const k=yt(l,c,d),w=k.filter((e,t)=>-1===x.indexOf(t));return{nonStrided:d.every(e=>1===e),$begin:l,$end:c,$strides:d,size:k,newShape:m,outShape:w}}pe={buffer:lt,cast:ct,clone:dt,print:function(e,t=!1){console.log(e.toString(t))}};var At=Object.freeze({__proto__:null,assertParamsValid:mt,maskToAxes:gt,computeOutShape:yt,stridesWithElidedDims:bt,getNormalizedAxes:wt,startIndicesWithElidedDims:vt,stopIndicesWithElidedDims:It,stridesForAxis:Nt,startForAxis:St,stopForAxis:Ct,isSliceContinous:Tt,computeFlatOffset:Et,parseSliceParams:$t,sliceInfo:_t});function Rt(){return Ee}function Mt(e){return Ee.setBackend(e)}function Ft(e,t,n=1){return Ee.registerBackend(e,t,n)}const Dt=Oe({mul_:function(e,t){let n=De(e,"a","mul"),r=De(t,"b","mul");[n,r]=function(e,t){if(e.dtype===t.dtype)return[e,t];const n=we(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}(n,r);const a={a:n,b:r};return Ee.runKernel("Multiply",a)}});function Ot(e,t,n,r,a="NHWC",s){return Bt(e,[...t,e[3]],n,s,r,null,null,Kt(a))}function Pt(e,t,n,r,a,s,o="channelsLast"){const[i,u]=Vt(t);let l;if("channelsLast"===o)l=[i,u,e[3],e[3]];else{if("channelsFirst"!==o)throw new Error("Unknown dataFormat "+o);l=[i,u,e[1],e[1]]}return Bt(e,l,n,r,a,s,!1,o)}function Lt(e,t,n,r,a,s,o="NDHWC"){const[i,u,l]=Ut(t);let c,d;if("NDHWC"===o)d="channelsLast",c=[i,u,l,e[4],e[4]];else{if("NCDHW"!==o)throw new Error("Unknown dataFormat "+o);d="channelsFirst",c=[i,u,l,e[1],e[1]]}return Wt(e,c,n,r,a,!1,d,s)}function Bt(e,t,n,r,a,s,o=!1,i="channelsLast"){let[u,l,c,d]=[-1,-1,-1,-1];if("channelsLast"===i)[u,l,c,d]=e;else{if("channelsFirst"!==i)throw new Error("Unknown dataFormat "+i);[u,d,l,c]=e}const[p,h,,f]=t,[m,g]=Vt(n),[y,b]=Vt(r),x=Gt(p,y),k=Gt(h,b),{padInfo:w,outHeight:v,outWidth:I}=function(e,t,n,r,a,s,o,i,u){let l,c,d;if("number"==typeof e){l={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};const a=function(e,t,n,r,a){null==r&&(r=zt(e,t,n));const s=e[0],o=e[1],i=Ht((s-t+2*r)/n+1,a),u=Ht((o-t+2*r)/n+1,a);return[i,u]}([t,n],s,r,e,i);c=a[0],d=a[1]}else if("same"===e){c=Math.ceil(t/r),d=Math.ceil(n/a);const e=Math.max(0,(c-1)*r+s-t),i=Math.max(0,(d-1)*a+o-n),u=Math.floor(e/2),p=e-u,h=Math.floor(i/2);l={top:u,bottom:p,left:h,right:i-h,type:"SAME"}}else if("valid"===e)l={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((t-s+1)/r),d=Math.ceil((n-o+1)/a);else{if("object"!=typeof e)throw Error("Unknown padding parameter: "+e);{const p="channelsLast"===u?e[1][0]:e[2][0],h="channelsLast"===u?e[1][1]:e[2][1],f="channelsLast"===u?e[2][0]:e[3][0],m="channelsLast"===u?e[2][1]:e[3][1];l={top:p,bottom:h,left:f,right:m,type:0===p&&0===h&&0===f&&0===m?"VALID":"EXPLICIT"},c=Ht((t-s+p+h)/r+1,i),d=Ht((n-o+f+m)/a+1,i)}}return{padInfo:l,outHeight:c,outWidth:d}}(a,l,c,m,g,x,k,s,i),N=o?f*d:f;let S;return"channelsFirst"===i?S=[u,N,v,I]:"channelsLast"===i&&(S=[u,v,I,N]),{batchSize:u,dataFormat:i,inHeight:l,inWidth:c,inChannels:d,outHeight:v,outWidth:I,outChannels:N,padInfo:w,strideHeight:m,strideWidth:g,filterHeight:p,filterWidth:h,effectiveFilterHeight:x,effectiveFilterWidth:k,dilationHeight:y,dilationWidth:b,inShape:e,outShape:S,filterShape:t}}function Wt(e,t,n,r,a,s=!1,o="channelsLast",i){let[u,l,c,d,p]=[-1,-1,-1,-1,-1];if("channelsLast"===o)[u,l,c,d,p]=e;else{if("channelsFirst"!==o)throw new Error("Unknown dataFormat "+o);[u,p,l,c,d]=e}const[h,f,m,,g]=t,[y,b,x]=Ut(n),[k,w,v]=Ut(r),I=Gt(h,k),N=Gt(f,w),S=Gt(m,v),{padInfo:C,outDepth:T,outHeight:E,outWidth:$}=function(e,t,n,r,a,s,o,i,u,l,c){let d,p,h,f;if("number"==typeof e){d={top:e,bottom:e,left:e,right:e,front:e,back:e,type:0===e?"VALID":"NUMBER"};const s=function(e,t,n,r,a,s){null==a&&(a=zt(e,t,r));const o=e[0],i=e[1],u=e[2],l=Ht((o-t+2*a)/r+1,s),c=Ht((i-t+2*a)/r+1,s),d=Ht((u-t+2*a)/r+1,s);return[l,c,d,n]}([t,n,r,1],i,1,a,e,c);p=s[0],h=s[1],f=s[2]}else if("same"===e){p=Math.ceil(t/a),h=Math.ceil(n/s),f=Math.ceil(r/o);const e=(p-1)*a+i-t,c=(h-1)*s+u-n,m=(f-1)*o+l-r,g=Math.floor(e/2),y=e-g,b=Math.floor(c/2),x=c-b,k=Math.floor(m/2);d={top:b,bottom:x,left:k,right:m-k,front:g,back:y,type:"SAME"}}else{if("valid"!==e)throw Error("Unknown padding parameter: "+e);d={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},p=Math.ceil((t-i+1)/a),h=Math.ceil((n-u+1)/s),f=Math.ceil((r-l+1)/o)}return{padInfo:d,outDepth:p,outHeight:h,outWidth:f}}(a,l,c,d,y,b,x,I,N,S,i),_=s?g*p:g;let A;return"channelsFirst"===o?A=[u,_,T,E,$]:"channelsLast"===o&&(A=[u,T,E,$,_]),{batchSize:u,dataFormat:o,inDepth:l,inHeight:c,inWidth:d,inChannels:p,outDepth:T,outHeight:E,outWidth:$,outChannels:_,padInfo:C,strideDepth:y,strideHeight:b,strideWidth:x,filterDepth:h,filterHeight:f,filterWidth:m,effectiveFilterDepth:I,effectiveFilterHeight:N,effectiveFilterWidth:S,dilationDepth:k,dilationHeight:w,dilationWidth:v,inShape:e,outShape:A,filterShape:t}}function zt(e,t,n,r=1){const a=Gt(t,r);return Math.floor((e[0]*(n-1)-n+a)/2)}function Vt(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function Ut(e){return"number"==typeof e?[e,e,e]:e}function Gt(e,t){return t<=1?e:e+(e-1)*(t-1)}function Ht(e,t){if(!t)return Math.trunc(e);switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error("Unknown roundingMode "+t)}}function jt(e){const[t,n,r]=Vt(e);return 1===t&&1===n&&1===r}function qt(e,t){return jt(e)||jt(t)}function Kt(e){if("NHWC"===e)return"channelsLast";if("NCHW"===e)return"channelsFirst";throw new Error("Unknown dataFormat "+e)}const Xt=Oe({reshape_:function(e,t){const n={x:De(e,"x","reshape","string_or_numeric")},r={shape:t};return Ee.runKernel("Reshape",n,r)}});function Yt(e,t){const n=e.length,r=[];for(let a=0;a<n;a++){const s=n-1-a,o=e[s]||1;(t[t.length-1-a]||1)>1&&1===o&&r.unshift(s)}return r}function Qt(e,t){const n=[];for(let r=0;r<t.length;r++){const a=e[e.length-r-1],s=t.length-r-1,o=t[s];(null==a||1===a&&o>1)&&n.unshift(s)}return n}function Jt(e,t){const n=[],r=Math.max(e.length,t.length);for(let a=0;a<r;a++){let r=e[e.length-a-1];null==r&&(r=1);let s=t[t.length-a-1];if(null==s&&(s=1),1===r)n.unshift(s);else if(1===s)n.unshift(r);else{if(r!==s){throw Error(`Operands could not be broadcast together with shapes ${e} and ${t}.`)}n.unshift(r)}}return n}const Zt=Oe({elu_:function(e){const t={x:De(e,"x","elu")};return Ee.runKernel("Elu",t)}});const en=Oe({leakyRelu_:function(e,t=.2){const n={x:De(e,"x","leakyRelu")},r={alpha:t};return Ee.runKernel("LeakyRelu",n,r)}});const tn=Oe({sum_:function(e,t=null,n=!1){let r=De(e,"x","sum");"bool"===r.dtype&&(r=ct(r,"int32"));const a={x:r},s={axis:t,keepDims:n};return Ee.runKernel("Sum",a,s)}});function nn(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function rn(e,t,n){const r=e.length+t.length,a=[];let s=0,o=0;for(let i=0;i<r;i++)-1===n.indexOf(i)?a.push(e[s++]):a.push(t[o++]);return a}function an(e,t){const n=[],r=e.length;for(let a=0;a<r;a++)-1===t.indexOf(a)&&n.push(e[a]);return[n,t.map(t=>e[t])]}function sn(e,t){return rn(e,t.map(e=>1),t)}function on(e,t,n){c(nn(t,n),()=>e+" supports only inner-most axes for now. "+`Got axes ${t} and rank-${n} input.`)}function un(e,t){if(nn(e,t))return null;const n=[];for(let r=0;r<t;++r)-1===e.indexOf(r)&&n.push(r);return e.forEach(e=>n.push(e)),n}function ln(e){return e.map((e,t)=>[t,e]).sort((e,t)=>e[1]-t[1]).map(e=>e[0])}function cn(e,t){const n=[];for(let r=t-e;r<t;++r)n.push(r);return n}const dn=Oe({prelu_:function(e,t){const n={x:De(e,"x","prelu"),alpha:De(t,"alpha","prelu")};return Ee.runKernel("Prelu",n)}});var pn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function hn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function fn(e,t){return e(t={exports:{}},t.exports),t.exports}var mn=fn((function(e){!function(e,t,n){function r(e){var t,n=this,r=(t=4022871197,function(e){e=e.toString();for(var n=0;n<e.length;n++){var r=.02519603282416938*(t+=e.charCodeAt(n));r-=t=r>>>0,t=(r*=t)>>>0,t+=4294967296*(r-=t)}return 2.3283064365386963e-10*(t>>>0)});n.next=function(){var e=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=e-(n.c=0|e)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(e),n.s0<0&&(n.s0+=1),n.s1-=r(e),n.s1<0&&(n.s1+=1),n.s2-=r(e),n.s2<0&&(n.s2+=1),r=null}function a(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function s(e,t){var n=new r(e),s=t&&t.state,o=n.next;return o.int32=function(){return 4294967296*n.next()|0},o.double=function(){return o()+11102230246251565e-32*(2097152*o()|0)},o.quick=o,s&&("object"==typeof s&&a(s,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=s:n&&n.amd?n((function(){return s})):this.alea=s}(0,e,!1)})),gn=fn((function(e){!function(e,t,n){function r(e){var t=this,n="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=0|n.charCodeAt(r),t.next()}function a(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function s(e,t){var n=new r(e),s=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,s&&("object"==typeof s&&a(s,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=s:n&&n.amd?n((function(){return s})):this.xor128=s}(0,e,!1)})),yn=fn((function(e){!function(e,t,n){function r(e){var t=this,n="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=0|n.charCodeAt(r),r==n.length&&(t.d=t.x<<10^t.x>>>4),t.next()}function a(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function s(e,t){var n=new r(e),s=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,s&&("object"==typeof s&&a(s,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=s:n&&n.amd?n((function(){return s})):this.xorwow=s}(0,e,!1)})),bn=fn((function(e){!function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.x,a=t.i;return e=r[a],n=(e^=e>>>7)^e<<24,n^=(e=r[a+1&7])^e>>>10,n^=(e=r[a+3&7])^e>>>3,n^=(e=r[a+4&7])^e<<7,e=r[a+7&7],n^=(e^=e<<13)^e<<9,r[a]=n,t.i=a+1&7,n},function(e,t){var n,r=[];if(t===(0|t))r[0]=t;else for(t=""+t,n=0;n<t.length;++n)r[7&n]=r[7&n]<<15^t.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&0===r[n];++n);for(8==n?r[7]=-1:r[n],e.x=r,e.i=0,n=256;n>0;--n)e.next()}(t,e)}function a(e,t){return t.x=e.x.slice(),t.i=e.i,t}function s(e,t){null==e&&(e=+new Date);var n=new r(e),s=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,s&&(s.x&&a(s,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=s:n&&n.amd?n((function(){return s})):this.xorshift7=s}(0,e,!1)})),xn=fn((function(e){!function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.w,a=t.X,s=t.i;return t.w=r=r+1640531527|0,n=a[s+34&127],e=a[s=s+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=a[s]=n^e,t.i=s,n+(r^r>>>16)|0},function(e,t){var n,r,a,s,o,i=[],u=128;for(t===(0|t)?(r=t,t=null):(t+="\0",r=0,u=Math.max(u,t.length)),a=0,s=-32;s<u;++s)t&&(r^=t.charCodeAt((s+32)%t.length)),0===s&&(o=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,s>=0&&(o=o+1640531527|0,a=0==(n=i[127&s]^=r+o)?a+1:0);for(a>=128&&(i[127&(t&&t.length||0)]=-1),a=127,s=512;s>0;--s)r=i[a+34&127],n=i[a=a+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,i[a]=r^n;e.w=o,e.X=i,e.i=a}(t,e)}function a(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function s(e,t){null==e&&(e=+new Date);var n=new r(e),s=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,s&&(s.X&&a(s,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=s:n&&n.amd?n((function(){return s})):this.xor4096=s}(0,e,!1)})),kn=fn((function(e){!function(e,t,n){function r(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,r=t.d,a=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^a,a=a-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^a,t.a=a-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):n+=e;for(var r=0;r<n.length+20;r++)t.b^=0|n.charCodeAt(r),t.next()}function a(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function s(e,t){var n=new r(e),s=t&&t.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},o.int32=n.next,o.quick=o,s&&("object"==typeof s&&a(s,n),o.state=function(){return a(n,{})}),o}t&&t.exports?t.exports=s:n&&n.amd?n((function(){return s})):this.tychei=s}(0,e,!1)})),wn=fn((function(e){!function(t,n){var r,a=this,s=n.pow(256,6),o=n.pow(2,52),i=2*o;function u(e,u,h){var f=[],m=d(function e(t,n){var r,a=[],s=typeof t;if(n&&"object"==s)for(r in t)try{a.push(e(t[r],n-1))}catch(e){}return a.length?a:"string"==s?t:t+"\0"}((u=1==u?{entropy:!0}:u||{}).entropy?[e,p(t)]:null==e?function(){try{var e;return r&&(e=r.randomBytes)?e=e(256):(e=new Uint8Array(256),(a.crypto||a.msCrypto).getRandomValues(e)),p(e)}catch(e){var n=a.navigator,s=n&&n.plugins;return[+new Date,a,s,a.screen,p(t)]}}():e,3),f),g=new l(f),y=function(){for(var e=g.g(6),t=s,n=0;e<o;)e=256*(e+n),t*=256,n=g.g(1);for(;e>=i;)e/=2,t/=2,n>>>=1;return(e+n)/t};return y.int32=function(){return 0|g.g(4)},y.quick=function(){return g.g(4)/4294967296},y.double=y,d(p(g.S),t),(u.pass||h||function(e,t,r,a){return a&&(a.S&&c(a,g),e.state=function(){return c(g,{})}),r?(n.random=e,t):e})(y,m,"global"in u?u.global:this==n,u.state)}function l(e){var t,n=e.length,r=this,a=0,s=r.i=r.j=0,o=r.S=[];for(n||(e=[n++]);a<256;)o[a]=a++;for(a=0;a<256;a++)o[a]=o[s=255&s+e[a%n]+(t=o[a])],o[s]=t;(r.g=function(e){for(var t,n=0,a=r.i,s=r.j,o=r.S;e--;)t=o[a=255&a+1],n=256*n+o[255&(o[a]=o[s=255&s+t])+(o[s]=t)];return r.i=a,r.j=s,n})(256)}function c(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function d(e,t){for(var n,r=e+"",a=0;a<r.length;)t[255&a]=255&(n^=19*t[255&a])+r.charCodeAt(a++);return p(t)}function p(e){return String.fromCharCode.apply(0,e)}if(n.seedrandom=u,d(n.random(),t),e.exports){e.exports=u;try{r=require("crypto")}catch(e){}}}([],Math)}));wn.alea=mn,wn.xor128=gn,wn.xorwow=yn,wn.xorshift7=bn,wn.xor4096=xn,wn.tychei=kn;const vn=Oe({relu_:function(e){const t={x:De(e,"x","relu")};return Ee.runKernel("Relu",t)}});const In=Oe({relu6_:function(e){const t={x:De(e,"x","relu6")};return Ee.runKernel("Relu6",t)}});function Nn(e,t){if((S(e)&&"string"!==t||Array.isArray(e))&&"complex64"!==t)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===t&&S(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return function(e,t,n,r){if(null==r&&(r=E(e)),"complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!S(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=t){D(t);const e=h(t),r=h(n);c(e===r,()=>`Based on the provided shape, [${t}], the tensor should have ${e} values but has ${r}`);for(let e=0;e<n.length;++e){const r=n[e],a=e!==n.length-1||r!==h(t.slice(e));c(n[e]===t[e]||!a,()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return S(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==r?Z(e,r):p(e,[],!0),Ee.makeTensor(e,t,r)}(e,[],[],t)}const Sn=Oe({step_:function(e,t=0){const n={x:De(e,"x","step")},r={alpha:t};return Ee.runKernel("Step",n,r)}});function Cn(e,t){const n=[];for(let e=0;e<t.length;e++)t[e]&&n.push(e);const r=lt(e,"int32"),a=lt([n.length,e.length],"int32");for(let t=0;t<n.length;t++){const s=r.indexToLoc(n[t]),o=t*e.length;a.values.set(s,o)}return a.toTensor()}function Tn(e,t,n){const r=function(e,t,n){return function(e,t,n){let r=0,a=e.length,s=0,o=!1;for(;r<a;){s=r+(a-r>>>1);const i=n(t,e[s]);i>0?r=s+1:(a=s,o=!i)}return o?r:-r-1}(e,t,n||En)}(e,t,n),a=r<0?-(r+1):r;e.splice(a,0,t)}function En(e,t){return e>t?1:e<t?-1:0}function $n(e,t,n,r,a){return Rn(e,t,n,r,a,0)}function _n(e,t,n,r,a,s){return Rn(e,t,n,r,a,0,!1,s,!0)}function An(e,t,n,r,a,s){return Rn(e,t,n,r,a,s,!0)}function Rn(e,t,n,r,a,s,o=!1,i=!1,u=!1){const l=[];for(let e=0;e<t.length;e++)t[e]>a&&l.push({score:t[e],boxIndex:e,suppressBeginIndex:0});l.sort(Dn);const c=s>0?-.5/s:0,d=[],p=[];for(;d.length<n&&l.length>0;){const t=l.pop(),{score:n,boxIndex:s,suppressBeginIndex:o}=t;if(n<a)break;let i=!1;for(let n=d.length-1;n>=o;--n){const o=Mn(e,s,d[n]);if(o>=r){i=!0;break}if(t.score=t.score*Fn(r,c,o),t.score<=a)break}t.suppressBeginIndex=d.length,i||(t.score===n?(d.push(s),p.push(t.score)):t.score>a&&Tn(l,t,Dn))}const h=d.length,f=n-h;i&&f>0&&(d.push(...new Array(f).fill(0)),p.push(...new Array(f).fill(0)));const m={selectedIndices:d};return o&&(m.selectedScores=p),u&&(m.validOutputs=h),m}function Mn(e,t,n){const r=e.subarray(4*t,4*t+4),a=e.subarray(4*n,4*n+4),s=Math.min(r[0],r[2]),o=Math.min(r[1],r[3]),i=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),l=Math.min(a[0],a[2]),c=Math.min(a[1],a[3]),d=Math.max(a[0],a[2]),p=Math.max(a[1],a[3]),h=(i-s)*(u-o),f=(d-l)*(p-c);if(h<=0||f<=0)return 0;const m=Math.max(s,l),g=Math.max(o,c),y=Math.min(i,d),b=Math.min(u,p),x=Math.max(y-m,0)*Math.max(b-g,0);return x/(h+f-x)}function Fn(e,t,n){const r=Math.exp(t*n*n);return n<=e?r:0}function Dn(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}function On(e,t){const n=e[0].length;e.forEach((e,t)=>{c(e.length===n,()=>`Error in concat${n}D: rank of tensors[${t}] must be the same as the rank of the rest (${n})`)}),c(t>=0&&t<n,()=>`Error in concat${n}D: axis must be between 0 and ${n-1}.`);const r=e[0];e.forEach((e,a)=>{for(let s=0;s<n;s++)c(s===t||e[s]===r[s],()=>`Error in concat${n}D: Shape of tensors[${a}] (${e}) does not match the shape of the rest (${r}) along the non-concatenated axis ${a}.`)})}function Pn(e,t){const n=e[0].slice();for(let r=1;r<e.length;r++)n[t]+=e[r][t];return n}function Ln(e){return e<=30?e:_(e,Math.floor(Math.sqrt(e)))}function Bn(e,t,n){return[n*("number"==typeof e?e:e[0]),t*("number"==typeof e?e:e[1])]}function Wn(e,t,n,r=!0){let a=[];if(r)a=a.concat(t.slice(0)),a.push(e[0]/n),a=a.concat(e.slice(1));else{a=a.concat(e[0]);const n=t.length;for(let r=0;r<n;++r)a=a.concat([e[r+1]/t[r],t[r]]);a=a.concat(e.slice(n+1))}return a}function zn(e,t,n=!0){const r=[];if(n){r.push(t);for(let n=t+1;n<e;++n)n<=2*t?(r.push(n),r.push(n-(t+1))):r.push(n)}else{const n=[],a=[];for(let r=1;r<e;++r)r>=2*t+1||r%2==1?a.push(r):n.push(r);r.push(...n),r.push(0),r.push(...a)}return r}function Vn(e,t,n,r=!0){const a=[];r?a.push(e[0]/n):a.push(e[0]*n);for(let n=1;n<e.length;++n)n<=t.length?r?a.push(t[n-1]*e[n]):a.push(e[n]/t[n-1]):a.push(e[n]);return a}function Un(e,t){const n=[0];for(let r=0;r<t;++r)n.push(e[r][0]);return n}function Gn(e,t,n){const r=e.slice(0,1);for(let a=0;a<n;++a)r.push(e[a+1]-t[a][0]-t[a][1]);return r}function Hn(...e){W().getBool("IS_TEST")||console.warn(...e)}function jn(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);const n=new Float32Array(2*e.length);for(let r=0;r<n.length;r+=2)n[r]=e[r/2],n[r+1]=t[r/2];return n}function qn(e){const t=new Float32Array(e.length/2),n=new Float32Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=e[r],n[r/2]=e[r+1];return{real:t,imag:n}}function Kn(e){const t=Math.ceil(e.length/4),n=new Float32Array(t),r=new Float32Array(t);for(let t=0;t<e.length;t+=4)n[Math.floor(t/4)]=e[t],r[Math.floor(t/4)]=e[t+1];return{real:n,imag:r}}function Xn(e){const t=Math.floor(e.length/4),n=new Float32Array(t),r=new Float32Array(t);for(let t=2;t<e.length;t+=4)n[Math.floor(t/4)]=e[t],r[Math.floor(t/4)]=e[t+1];return{real:n,imag:r}}function Yn(e,t){return{real:e[2*t],imag:e[2*t+1]}}function Qn(e,t,n,r){e[2*r]=t,e[2*r+1]=n}function Jn(e,t){const n=new Float32Array(e/2),r=new Float32Array(e/2);for(let a=0;a<Math.ceil(e/2);a++){const s=(t?2:-2)*Math.PI*(a/e);n[a]=Math.cos(s),r[a]=Math.sin(s)}return{real:n,imag:r}}function Zn(e,t,n){const r=(n?2:-2)*Math.PI*(e/t);return{real:Math.cos(r),imag:Math.sin(r)}}function er(e,t,n=0){let r=[];if("number"==typeof t)c(e.shape[n]%t==0,()=>"Number of splits must evenly divide the axis."),r=new Array(t).fill(e.shape[n]/t);else{c(t.reduce((e,t)=>(-1===t&&(e+=1),e),0)<=1,()=>"There should be only one negative value in split array.");const a=t.indexOf(-1);if(-1!==a){const r=t.reduce((e,t)=>t>0?e+t:e);t[a]=e.shape[n]-r}c(e.shape[n]===t.reduce((e,t)=>e+t),()=>"The sum of sizes must match the size of the axis dimension."),r=t}return r}function tr(e,t){let n,r=!1;for(e<=30?(n=e,r=!0):n=_(e,Math.floor(Math.sqrt(e)));!r;)n>t||n===e?r=!0:n=_(e,n+1);return n}function nr(e,t,n){const r=[],a=e.length;for(let s=0;s<a;s++)s!==t?r.push(e[s]):r.push(n);return r}function rr(e,t,n,r){const a=t.shape.length,s=e.shape.length;if(0!==r&&(r<-a||r>a))throw new Error(`Expect batchDims in the range of [-${a}, ${a}], but got ${r}`);if(r<0&&(r+=a),r>s)throw new Error(`batchDims (${r}) must be less than rank(x) (\n    ${s}).`);if(n<r)throw new Error(`batchDims (${r}) must be less than or equal to axis (${n}).`);for(let n=0;n<r;++n)if(e.shape[n]!==t.shape[n])throw new Error(`x.shape[${n}]: ${e.shape[n]} should be equal to indices.shape[${n}]: ${t.shape[n]}.`);const o=e.shape[n],i=[];let u=1,l=1,c=1;for(let t=0;t<r;++t)i.push(e.shape[t]),u*=e.shape[t];for(let t=r;t<n;t++)i.push(e.shape[t]),l*=e.shape[t];for(let e=r;e<a;e++)i.push(t.shape[e]);for(let t=n+1;t<s;t++)i.push(e.shape[t]),c*=e.shape[t];return{batchSize:u,sliceSize:c,outerSize:l,dimSize:o,outputShape:i}}var ar=Object.freeze({__proto__:null,segOpComputeOptimalWindowSize:tr,computeOutShape:nr,collectGatherOpShapeInfo:rr});function sr(e){try{return e.map(e=>ne(e))}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8, error: "+e)}}function or(e){return e.map(e=>te(e))}var ir=Object.freeze({__proto__:null,slice_util:At,segment_util:ar,fromUint8ToStringArray:sr,fromStringArrayToUint8:or,upcastType:we,axesAreInnerMostDims:nn,combineLocations:rn,computeOutAndReduceShapes:an,expandShapeToKeepDim:sn,assertAxesAreInnerMostDims:on,getAxesPermutation:un,getUndoAxesPermutation:ln,getInnerMostAxes:cn,getBroadcastDims:Yt,getReductionAxes:Qt,assertAndGetBroadcastShape:Jt,assertParamsConsistent:On,computeOutShape:Pn,computeDilation2DInfo:Ot,computePool2DInfo:Pt,computePool3DInfo:Lt,computeConv2DInfo:Bt,computeConv3DInfo:Wt,computeDefaultPad:zt,tupleValuesAreOne:jt,eitherStridesOrDilationsAreOne:qt,convertConv2DDataFormat:Kt,getFusedDyActivation:function(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return Dt(e,Sn(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)},getFusedBiasGradient:function(e,t){let n=t;const r=Qt(e.shape,t.shape);return r.length>0&&(n=tn(n,r)),Xt(n,e.shape)},applyActivation:function(e,t,n,r){if("linear"===t)return e;if("relu"===t)return vn(e);if("elu"===t)return Zt(e);if("relu6"===t)return In(e);if("prelu"===t)return dn(e,n);if("leakyrelu"===t)return en(e,r);throw new Error(`Unknown fused activation ${t}.`)},shouldFuse:(e,t)=>!(e>0)||"linear"===t,PARALLELIZE_THRESHOLD:30,computeOptimalWindowSize:Ln,getImageCenter:Bn,getReshaped:Wn,getPermuted:zn,getReshapedPermuted:Vn,getSliceBeginCoords:Un,getSliceSize:Gn,prepareAndValidate:pt,validateUpdateShape:ht,validateInput:function(e,t,n){if(t.rank<1)throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);if(e.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${e.rank}.`);if("int32"!==t.dtype)throw new Error("The dtype of 'indices' should be int32, but got dtype: "+t.dtype);if(n.length<1)throw new Error("Output rank must be greater or equal to 1, but got shape: "+n);if(0===n.length){if(0===t.size)throw new Error("Indices specified for empty output. indices shape: "+t.shape);if(0===e.size)throw new Error("Updates specified for empty output. updates shape: "+e.shape)}ht(n,t,e)},calculateShapes:ft,SELU_SCALEALPHA:1.7580993408473768,SELU_SCALE:1.0507009873554805,ERF_P:.3275911,ERF_A1:.254829592,ERF_A2:-.284496736,ERF_A3:1.421413741,ERF_A4:-1.453152027,ERF_A5:1.061405429,warn:Hn,log:function(...e){W().getBool("IS_TEST")||console.log(...e)},mergeRealAndImagArrays:jn,splitRealAndImagArrays:qn,complexWithEvenIndex:Kn,complexWithOddIndex:Xn,getComplexWithIndex:Yn,assignToTypedArray:Qn,exponents:Jn,exponent:Zn,prepareSplitSize:er});const ur={},lr={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function cr(e){if(!(e in ur)){const t=function(e){if(1!==e&&2!==e)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");const t=function(e){if("undefined"!=typeof OffscreenCanvas&&2===e)return new OffscreenCanvas(300,150);if("undefined"!=typeof document)return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}(e);if(t.addEventListener("webglcontextlost",t=>{t.preventDefault(),delete ur[e]},!1),1===e)return t.getContext("webgl",lr)||t.getContext("experimental-webgl",lr);return t.getContext("webgl2",lr)}(e);if(null===t)return console.log("Could not get context for WebGL version",e),null;ur[e]=t}const t=ur[e];return t.isContextLost()?(delete ur[e],cr(e)):(t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.BLEND),t.disable(t.DITHER),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SAMPLE_COVERAGE),t.enable(t.SCISSOR_TEST),t.enable(t.CULL_FACE),t.cullFace(t.BACK),ur[e])}var dr,pr,hr;function fr(e,t){return[t,e]}function mr(e){const t=h(e);return g(Math.ceil(t/4))}function gr(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function yr(e,t){const n=e;let r,a,s,o,i,u,l,c,d,p;return 2===W().getNumber("WEBGL_VERSION")?(r=n.R32F,a=n.R16F,s=n.RGBA16F,o=n.RGBA32F,i=n.RED,l=4,c=1,d=n.HALF_FLOAT,p=n.FLOAT):(r=e.RGBA,a=e.RGBA,s=e.RGBA,o=n.RGBA,i=e.RGBA,l=4,c=4,d=null!=t?t.HALF_FLOAT_OES:null,p=e.FLOAT),u=e.RGBA,{internalFormatFloat:r,internalFormatHalfFloat:a,internalFormatPackedHalfFloat:s,internalFormatPackedFloat:o,textureFormatFloat:i,downloadTextureFormat:u,downloadUnpackNumChannels:l,defaultNumChannels:c,textureTypeHalfFloat:d,textureTypeFloat:p}}function br(e,t){const n=t();return W().getBool("DEBUG")&&function(e){const t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+function(e,t){switch(t){case e.NO_ERROR:return"NO_ERROR";case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return"Unknown error code "+t}}(e,t))}(e),n}!function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"}(dr||(dr={})),function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"}(pr||(pr={})),function(e){e[e.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",e[e.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",e[e.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",e[e.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",e[e.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"}(hr||(hr={}));function xr(e){return!!(W().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===e||5.96e-8<Math.abs(e)&&Math.abs(e)<65504)}function kr(e,t){return $r(e,()=>e.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function wr(e,t){const n=$r(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(br(e,()=>e.shaderSource(n,t)),br(e,()=>e.compileShader(n)),!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw function(e,t){const n=vr.exec(t);if(null==n)return console.log("Couldn't parse line number in error: "+t),void console.log(e);const r=+n[1],a=e.split("\n"),s=a.length.toString().length+2,o=a.map((e,t)=>y((t+1).toString(),s)+e);let i=0;for(let e=0;e<o.length;e++)i=Math.max(o[e].length,i);const u=o.slice(0,r-1),l=o.slice(r-1,r),c=o.slice(r);console.log(u.join("\n")),console.log(t.split("\n")[0]),console.log("%c "+y(l[0],i),"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(c.join("\n"))}(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}const vr=/ERROR: [0-9]+:([0-9]+):/g;function Ir(e,t){if(br(e,()=>e.validateProgram(t)),!1===e.getProgramParameter(t,e.VALIDATE_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function Nr(e,t,n,r,a,s,o){const i=e.getAttribLocation(t,n);return-1!==i&&(br(e,()=>e.bindBuffer(e.ARRAY_BUFFER,r)),br(e,()=>e.vertexAttribPointer(i,a,e.FLOAT,!1,s,o)),br(e,()=>e.enableVertexAttribArray(i)),!0)}function Sr(e,t,n){!function(e,t){const n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=t+e.TEXTURE0;if(r<e.TEXTURE0||r>n){throw new Error(`textureUnit must be in ${`[gl.TEXTURE0, gl.TEXTURE${n}]`}.`)}}(e,n),br(e,()=>e.activeTexture(e.TEXTURE0+n)),br(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function Cr(e,t,n){br(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),br(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function Tr(e,t){br(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),br(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Er(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+function(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+t}}(e,t))}function $r(e,t,n){const r=br(e,()=>t());if(null==r)throw new Error(n);return r}function _r(e,t=2){return h(e.slice(0,e.length-t))}function Ar(e){if(0===e.length)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function Rr(e){let t=[1,1,1];return 0===e.length||1===e.length&&1===e[0]||(t=[_r(e),...Ar(e)]),t}function Mr(e){return e%2==0}function Fr(e,t){if(f(e=e.slice(-2),t=t.slice(-2)))return!0;if(!e.length||!t.length)return!0;if(0===e[0]||0===e[1]||0===t[0]||0===t[1])return!0;if(e.length!==t.length){const n=e.slice(-1)[0],r=t.slice(-1)[0];if(n===r)return!0;if(Mr(n)&&Mr(r)&&(1===e[0]||1===t[0]))return!0}return e[1]===t[1]&&Mr(e[0])&&Mr(t[0])}let Dr,Or;function Pr(e,t){return null!=e.getExtension(t)}function Lr(e){try{if(null!=cr(e))return!0}catch(e){return console.log("Error when getting WebGL context: ",e),!1}return!1}function Br(e){if(0===e)return!1;const t=cr(e);if(1!==e){if(Pr(t,"EXT_color_buffer_float"))return Wr(t);const e="EXT_color_buffer_half_float";if(Pr(t,e)){const n=t.getExtension(e);return function(e,t){const n=yr(e,t),r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r);e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,1,1,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);const a=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,a),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);const s=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(r),e.deleteFramebuffer(a),s}(t,n)}return!1}if(!Pr(t,"OES_texture_float"))return!1;if(!Pr(t,"WEBGL_color_buffer_float"))return!1;return Wr(t)}function Wr(e){const t=yr(e),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n);e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,1,1,0,t.textureFormatFloat,t.textureTypeFloat,null);const r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);const a=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(r),a}function zr(e,t){Array.isArray(e)||(e=[e]),e.forEach(e=>{null!=e&&c("complex64"!==e.dtype,()=>t+" does not support complex64 tensors in the WebGL backend.")})}const Vr=W();function Ur(){let e,t,n,r,a,s,o,i,u,l;return 2===W().getNumber("WEBGL_VERSION")?(e="#version 300 es",t="in",n="out",r="in",a="texture",s="outputColor",o="out vec4 outputColor;",i="\n      bool isnan_custom(float val) {\n        return (val > 0.0 || val < 0.0) ? false : val != 0.0;\n      }\n\n      bvec4 isnan_custom(vec4 val) {\n        return bvec4(isnan_custom(val.x),\n          isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\n      }\n\n      #define isnan(value) isnan_custom(value)\n    ",u="",l="\n      #define round(value) newRound(value)\n      int newRound(float value) {\n        return int(floor(value + 0.5));\n      }\n\n      ivec4 newRound(vec4 value) {\n        return ivec4(floor(value + vec4(0.5)));\n      }\n    "):(e="",t="attribute",n="varying",r="varying",a="texture2D",s="gl_FragColor",o="",i="\n      #define isnan(value) isnan_custom(value)\n      bool isnan_custom(float val) {\n        return (val > 0. || val < 1. || val == 0.) ? false : true;\n      }\n      bvec4 isnan_custom(vec4 val) {\n        return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n      }\n    ",u="\n      uniform float INFINITY;\n\n      bool isinf(float val) {\n        return abs(val) == INFINITY;\n      }\n      bvec4 isinf(vec4 val) {\n        return equal(abs(val), vec4(INFINITY));\n      }\n    ",l="\n      int round(float value) {\n        return int(floor(value + 0.5));\n      }\n\n      ivec4 round(vec4 value) {\n        return ivec4(floor(value + vec4(0.5)));\n      }\n    "),{version:e,attribute:t,varyingVs:n,varyingFs:r,texture2D:a,output:s,defineOutput:o,defineSpecialNaN:i,defineSpecialInf:u,defineRound:l}}function Gr(e,t,n="index"){const r=A(t);return r.map((t,a)=>`${`int ${e[a]} = ${n} / ${t}`}; ${a===r.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * ${t}`:`index -= ${e[a]} * ${t}`};`).join("")}function Hr(e){const t=A(e).map(e=>e.toString());return`\n  int getFlatIndex(ivec3 coords) {\n    return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;\n  }\n`}Vr.registerFlag("HAS_WEBGL",()=>Vr.getNumber("WEBGL_VERSION")>0),Vr.registerFlag("WEBGL_VERSION",()=>Lr(2)?2:Lr(1)?1:0),Vr.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1),Vr.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>2===Vr.get("WEBGL_VERSION")),Vr.registerFlag("WEBGL_CPU_FORWARD",()=>!0),Vr.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1),Vr.registerFlag("WEBGL_PACK",()=>Vr.getBool("HAS_WEBGL")),Vr.registerFlag("WEBGL_PACK_NORMALIZATION",()=>Vr.getBool("WEBGL_PACK")),Vr.registerFlag("WEBGL_PACK_CLIP",()=>Vr.getBool("WEBGL_PACK")),Vr.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>!1),Vr.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>Vr.getBool("WEBGL_PACK")),Vr.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>Vr.getBool("WEBGL_PACK")),Vr.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>Vr.getBool("WEBGL_PACK")),Vr.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>Vr.getBool("WEBGL_PACK")),Vr.registerFlag("WEBGL_PACK_REDUCE",()=>Vr.getBool("WEBGL_PACK")),Vr.registerFlag("WEBGL_LAZILY_UNPACK",()=>Vr.getBool("WEBGL_PACK")),Vr.registerFlag("WEBGL_CONV_IM2COL",()=>Vr.getBool("WEBGL_PACK")),Vr.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>function(e){if(null==Dr){const t=cr(e);Dr=t.getParameter(t.MAX_TEXTURE_SIZE)}return Dr}(Vr.getNumber("WEBGL_VERSION"))),Vr.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>function(e){if(null==Or){const t=cr(e);Or=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Or)}(Vr.getNumber("WEBGL_VERSION"))),Vr.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{const e=Vr.getNumber("WEBGL_VERSION");return 0===e?0:function(e){if(0===e)return 0;let t;const n=cr(e);return t=Pr(n,"EXT_disjoint_timer_query_webgl2")&&2===e?2:Pr(n,"EXT_disjoint_timer_query")?1:0,t}(e)}),Vr.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>Vr.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!_e()),Vr.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>function(e){if(0===e)return!1;const t=cr(e);if(1===e){if(!Pr(t,"OES_texture_float"))return!1}else if(!Pr(t,"EXT_color_buffer_float"))return!1;return Wr(t)}(Vr.getNumber("WEBGL_VERSION"))),Vr.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>!Vr.getBool("WEBGL_FORCE_F16_TEXTURES")&&Vr.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")),Vr.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>Br(Vr.getNumber("WEBGL_VERSION"))),Vr.registerFlag("WEBGL_FENCE_API_ENABLED",()=>{return 2===(e=Vr.getNumber("WEBGL_VERSION"))&&null!=cr(e).fenceSync;var e}),Vr.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>Vr.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0),Vr.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",()=>-1,e=>{if(e<0&&-1!==e)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${e}.`)}),Vr.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>_e()&&Vr.getBool("IS_CHROME")?1:-1,e=>{if(e<0&&-1!==e)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${e}.`)});const jr="\n  const float FLOAT_MAX = 1.70141184e38;\n  const float FLOAT_MIN = 1.17549435e-38;\n\n  lowp vec4 encode_float(highp float v) {\n    if (isnan(v)) {\n      return vec4(255, 255, 255, 255);\n    }\n\n    highp float av = abs(v);\n\n    if(av < FLOAT_MIN) {\n      return vec4(0.0, 0.0, 0.0, 0.0);\n    } else if(v > FLOAT_MAX) {\n      return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n    } else if(v < -FLOAT_MAX) {\n      return vec4(0.0, 0.0,  128.0, 255.0) / 255.0;\n    }\n\n    highp vec4 c = vec4(0,0,0,0);\n\n    highp float e = floor(log2(av));\n    highp float m = exp2(fract(log2(av))) - 1.0;\n\n    c[2] = floor(128.0 * m);\n    m -= c[2] / 128.0;\n    c[1] = floor(32768.0 * m);\n    m -= c[1] / 32768.0;\n    c[0] = floor(8388608.0 * m);\n\n    highp float ebias = e + 127.0;\n    c[3] = floor(ebias / 2.0);\n    ebias -= c[3] * 2.0;\n    c[2] += floor(ebias) * 128.0;\n\n    c[3] += 128.0 * step(0.0, -v);\n\n    return c / 255.0;\n  }\n";class qr{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=dr.DENSE;const t=mr(e),n=Ur();this.outputShape=e,this.userCode=`\n      ivec3 outCoordsFromFlatIndex(int index) {\n        ${Gr(["r","c","d"],e)}\n        return ivec3(r, c, d);\n      }\n\n      void main() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n          vec2(${t[0]}, ${t[1]}));\n        int index = 4 * (resTexRC.x * ${t[1]} + resTexRC.y);\n\n        vec4 result = vec4(0.);\n\n        for (int i=0; i<4; i++) {\n          int flatIndex = index + i;\n          ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n          result[i] = getA(rc.x, rc.y, rc.z);\n        }\n\n        ${n.output} = result;\n      }\n    `}}class Kr{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=dr.DENSE;const t=mr(e),n=Ur();this.outputShape=e,this.userCode=`\n      ivec3 outCoordsFromFlatIndex(int index) {\n        ${Gr(["r","c","d"],e)}\n        return ivec3(r, c, d);\n      }\n\n      void main() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n          vec2(${t[0]}, ${t[1]}));\n        int index = 4 * (resTexRC.x * ${t[1]} + resTexRC.y);\n\n        vec4 result = vec4(0.);\n\n        for (int i=0; i<4; i++) {\n          int flatIndex = index + i;\n          ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n          result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n        }\n\n        ${n.output} = result;\n      }\n    `}}class Xr{constructor(e){this.variableNames=["A"],this.outTexUsage=pr.DOWNLOAD;const t=Ur();this.outputShape=e,this.userCode=`\n      ${jr}\n\n      void main() {\n        float x = getAAtOutCoords();\n        ${t.output} = encode_float(x);\n      }\n    `}}class Yr{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=pr.DOWNLOAD;const t=Ur();this.outputShape=e,this.userCode=`\n      ${jr}\n\n      void main() {\n        ivec3 coords = getOutputCoords();\n        float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n        ${t.output} = encode_float(x);\n      }\n    `}}class Qr{constructor(e,t,n=!1){this.variableNames=["A"];const r=Ur(),[a,s]=t;this.outputShape=e;let o="result";n&&(o="floor(result * 255. + 0.5)"),this.userCode=`\n      ${Hr(e)}\n\n      void main() {\n        ivec3 coords = getOutputCoords();\n\n        int flatIndex = getFlatIndex(coords);\n        int offset = imod(flatIndex, 4);\n\n        flatIndex = idiv(flatIndex, 4, 1.);\n\n        int r = flatIndex / ${s};\n        int c = imod(flatIndex, ${s});\n        vec2 uv = (vec2(c, r) + halfCR) / vec2(${s}.0, ${a}.0);\n        vec4 values = ${r.texture2D}(A, uv);\n\n        float result;\n\n        if(offset == 0) {\n          result = values[0];\n        } else if(offset == 1) {\n          result = values[1];\n        } else if(offset == 2) {\n          result = values[2];\n        } else {\n          result = values[3];\n        }\n\n        ${r.output} = vec4(${o}, 0., 0., 0.);\n      }\n    `}}class Jr{constructor(e,t,n=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const r=Ur(),[a,s]=t;this.outputShape=e;let o="",i="result";n&&(i="floor(result * 255. + 0.5)");for(let t=0;t<=1;t++)for(let n=0;n<=1;n++){const i=2*t+n;o+=`\n          localCoords = coords;\n          if(localCoords[2] + ${n} < ${e[2]}) {\n            localCoords[2] += ${n};\n            if(localCoords[1] + ${t} < ${e[1]}) {\n              localCoords[1] += ${t};\n\n              flatIndex = getFlatIndex(localCoords);\n              offset = imod(flatIndex, 4);\n\n              flatIndex = idiv(flatIndex, 4, 1.);\n\n              r = flatIndex / ${s};\n              c = imod(flatIndex, ${s});\n              uv = (vec2(c, r) + halfCR) / vec2(${s}.0, ${a}.0);\n              values = ${r.texture2D}(A, uv);\n\n              if(offset == 0) {\n                result[${i}] = values[0];\n              } else if(offset == 1) {\n                result[${i}] = values[1];\n              } else if(offset == 2) {\n                result[${i}] = values[2];\n              } else {\n                result[${i}] = values[3];\n              }\n            }\n          }\n        `}this.userCode=`\n      ${Hr(e)}\n\n      void main() {\n        ivec3 coords = getOutputCoords();\n\n        vec4 result = vec4(0.);\n        int flatIndex, r, c, offset;\n        ivec3 localCoords;\n        vec2 uv;\n        vec4 values;\n\n        ${o}\n\n        ${r.output} = ${i};\n      }\n    `}}function Zr(e){const t=Ur();return function(e,t){const n=$r(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(br(e,()=>e.shaderSource(n,t)),br(e,()=>e.compileShader(n)),!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw console.log(e.getShaderInfoLog(n)),new Error("Failed to compile vertex shader.");return n}(e,`${t.version}\n    precision highp float;\n    ${t.attribute} vec3 clipSpacePos;\n    ${t.attribute} vec2 uv;\n    ${t.varyingVs} vec2 resultUV;\n\n    void main() {\n      gl_Position = vec4(clipSpacePos, 1);\n      resultUV = uv;\n    }`)}function ea(e){return function(e,t){const n=$r(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return br(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),br(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}(e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function ta(e){return function(e,t){const n=$r(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return br(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),br(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}(e,new Uint16Array([0,1,2,2,1,3]))}function na(e,t,n,r,a,s){!function(e,t){const n=W().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){throw new Error("Requested texture size "+`[${e}x${t}]`+" is invalid.")}if(e>n||t>n){throw new Error("Requested texture size "+`[${e}x${t}]`+" greater than WebGL maximum on this browser / GPU "+`[${n}x${n}]`+".")}}(t,n);const o=function(e){return $r(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}(e),i=e.TEXTURE_2D;return br(e,()=>e.bindTexture(i,o)),br(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),br(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),br(e,()=>e.texParameteri(i,e.TEXTURE_MIN_FILTER,e.NEAREST)),br(e,()=>e.texParameteri(i,e.TEXTURE_MAG_FILTER,e.NEAREST)),br(e,()=>e.texImage2D(i,0,r,t,n,0,a,s,null)),br(e,()=>e.bindTexture(e.TEXTURE_2D,null)),o}function ra(e){return e.internalFormatFloat}function aa(e){return e.internalFormatHalfFloat}function sa(e){return e.downloadTextureFormat}function oa(e){return e.internalFormatPackedFloat}function ia(e){return e.internalFormatPackedHalfFloat}function ua(e,t,n,r,a,s,o,i){const u=e,l=new Float32Array(function(e,t){const[n,r]=gr(e,t);return n*r*4}(s,o));return u.bindBuffer(u.PIXEL_PACK_BUFFER,t),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,l),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),l}class la{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];const t=W().getNumber("WEBGL_VERSION");null!=e?(this.gl=e,function(e,t){ur[e]=t}(t,e)):this.gl=cr(t);let n="WEBGL_color_buffer_float";if(1===W().getNumber("WEBGL_VERSION")){const e="OES_texture_float",t="OES_texture_half_float";if(this.textureFloatExtension=kr(this.gl,e),Pr(this.gl,t))this.textureHalfFloatExtension=kr(this.gl,t);else if(W().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),Pr(this.gl,"EXT_color_buffer_half_float"))this.colorBufferHalfFloatExtension=kr(this.gl,"EXT_color_buffer_half_float");else if(W().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",Pr(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!Pr(this.gl,"EXT_color_buffer_half_float"))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float")}this.vertexBuffer=ea(this.gl),this.indexBuffer=ta(this.gl),this.framebuffer=function(e){return $r(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}(this.gl),this.textureConfig=yr(this.gl,this.textureHalfFloatExtension)}get debug(){return W().getBool("DEBUG")}dispose(){if(this.disposed)return;null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture.  This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");const e=this.gl;br(e,()=>e.finish()),br(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),br(e,()=>e.deleteFramebuffer(this.framebuffer)),br(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),br(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),br(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,s]=fr(t,n);return na(e,a,s,ra(r),r.textureFormatFloat,e.FLOAT)}(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,s]=fr(t,n);return na(e,a,s,aa(r),r.textureFormatFloat,r.textureTypeHalfFloat)}(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,s]=fr(t,n);return na(e,a,s,sa(r),e.RGBA,e.UNSIGNED_BYTE)}(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),function(e,t,n){br(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?br(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):br(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),br(e,()=>e.bindTexture(e.TEXTURE_2D,null))}(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,r){this.throwIfDisposed(),function(e,t,n,r,a,s){let o,i,u;br(e,()=>e.bindTexture(e.TEXTURE_2D,t)),a instanceof Uint8Array?(o=new Uint8Array(n*r*4),i=e.UNSIGNED_BYTE,u=e.RGBA):(o=new Float32Array(n*r*4),i=e.FLOAT,u=s.internalFormatPackedFloat),o.set(a),br(e,()=>e.texImage2D(e.TEXTURE_2D,0,u,n,r,0,e.RGBA,i,o)),br(e,()=>e.bindTexture(e.TEXTURE_2D,null))}(this.gl,e,t,n,r,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,s]=gr(t,n);return na(e,a,s,ia(r),e.RGBA,r.textureTypeHalfFloat)}(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,r){const[a,s]=gr(t,n);return na(e,a,s,oa(r),e.RGBA,e.FLOAT)}(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(Tr(this.gl,this.framebuffer),this.outputTexture=null),br(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,()=>function(e,t,n,r){const[a,s]=fr(t,n),o=new Uint8Array(t*n*4);return br(e,()=>e.readPixels(0,0,a,s,r.downloadTextureFormat,e.UNSIGNED_BYTE,o)),new Float32Array(o.buffer)}(this.gl,t,n,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,n,r,a,s){return ua(this.gl,e,0,0,0,a,s,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return function(e,t,n){const r=e,a=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,t),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,a),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),a}(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);const r=function(e,t,n,r){const a=e.createBuffer();br(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,a));const s=16*t*n;return br(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,s,e.STREAM_READ)),br(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),br(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),a}(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r}createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(W().getBool("WEBGL_FENCE_API_ENABLED")){const r=e,a=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{const e=r.clientWaitSync(a,0,0);return e===r.ALREADY_SIGNALED||e===r.CONDITION_SATISFIED},t=a}else W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,()=>function(e,t,n){const r=new Float32Array(t*n*4);return br(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,r)),r}(this.gl,t,n))}createProgram(e){this.throwIfDisposed();const t=this.gl,n=wr(t,e),r=Zr(t),a=function(e){return $r(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}(t);return br(t,()=>t.attachShader(a,r)),br(t,()=>t.attachShader(a,n)),function(e,t){if(br(e,()=>e.linkProgram(t)),!1===e.getProgramParameter(t,e.LINK_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}(t,a),this.debug&&Ir(t,a),this.vertexAttrsAreBound||(this.setProgram(a),this.vertexAttrsAreBound=function(e,t,n){return br(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),Nr(e,t,"clipSpacePos",n,3,20,0)&&Nr(e,t,"uv",n,2,20,12)}(t,this.program,this.vertexBuffer)),a}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&br(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,null!=this.program&&this.debug&&Ir(this.gl,this.program),br(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?function(e,t,n){return $r(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}(this.gl,e,t):function(e,t,n){return e.getUniformLocation(t,n)}(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),br(this.gl,()=>this.gl.getAttribLocation(e,t))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),function(e,t,n,r){br(e,()=>Sr(e,t,r)),br(e,()=>e.uniform1i(n,r))}(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();const[r,a]=gr(t,n);this.setOutputMatrixTextureDriver(e,r,a)}setOutputMatrixWriteRegion(e,t,n,r){this.setOutputMatrixWriteRegionDriver(n,e,r,t)}setOutputPackedMatrixWriteRegion(e,t,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){null!=this.program&&Ir(this.gl,this.program),Er(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const e=this.gl;this.debug&&this.debugValidate(),br(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),br(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=kr(this.gl,2===W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(2===W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const e=this.gl,t=this.getQueryTimerExtensionWebGL2(),n=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,n),n}const e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(2===W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const e=this.gl,t=this.getQueryTimerExtensionWebGL2();return void e.endQuery(t.TIME_ELAPSED_EXT)}const e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await b(()=>this.disposed||this.isQueryAvailable(e,W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(0===t)return null;if(2===t){const t=this.gl;return t.getQueryParameter(e,t.QUERY_RESULT)/1e6}{const t=this.getQueryTimerExtensionWebGL1();return t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(0===t)return!0;if(2===t){const t=this.gl,n=this.getQueryTimerExtensionWebGL2(),r=t.getQueryParameter(e,t.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),r&&!this.disjoint}{const t=this.getQueryTimerExtensionWebGL1(),n=t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(t.GPU_DISJOINT_EXT)),n&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){const e=function(e){let t=0;for(;t<e.length;++t){if(!e[t]())break}return t-1}(this.itemsToPoll.map(e=>e.isDoneFn));for(let t=0;t<=e;++t){const{resolveFn:e}=this.itemsToPoll[t];e()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1||b(()=>(this.pollItems(),0===this.itemsToPoll.length))}bindTextureToFrameBuffer(e){this.throwIfDisposed(),Cr(this.gl,e,this.framebuffer),this.debug&&Er(this.gl)}unbindTextureToFrameBuffer(){null!=this.outputTexture?(Cr(this.gl,this.outputTexture,this.framebuffer),this.debug&&Er(this.gl)):Tr(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);const n=t();return this.unbindTextureToFrameBuffer(),n}setOutputMatrixTextureDriver(e,t,n){this.throwIfDisposed();const r=this.gl;Cr(r,e,this.framebuffer),this.debug&&Er(r),this.outputTexture=e,br(r,()=>r.viewport(0,0,t,n)),br(r,()=>r.scissor(0,0,t,n))}setOutputMatrixWriteRegionDriver(e,t,n,r){this.throwIfDisposed(),br(this.gl,()=>this.gl.scissor(e,t,n,r))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(null==this.program)throw new Error("No GPU program is currently set.")}}const{getBroadcastDims:ca}=ir;function da(e,t,n,r){const a=[];e.forEach(e=>{const t=h(e.shapeInfo.logicalShape);e.shapeInfo.isUniform?a.push(`uniform float ${e.name}${t>1?`[${t}]`:""};`):(a.push(`uniform sampler2D ${e.name};`),a.push(`uniform int offset${e.name};`))});const s=a.join("\n"),o=e.map(e=>function(e,t,n=!1){let r="";r+=n?ha(e):pa(e);const a=e.shapeInfo.logicalShape,s=t.logicalShape;a.length<=s.length&&(r+=n?function(e,t){const n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),a="get"+r+"AtOutCoords",s=e.shapeInfo.logicalShape.length,o=t.logicalShape.length,i=ca(e.shapeInfo.logicalShape,t.logicalShape),u=wa(o),l=o-s;let c;const d=["x","y","z","w","u","v"];c=0===s?"":o<2&&i.length>=1?"coords = 0;":i.map(e=>`coords.${d[e+l]} = 0;`).join("\n");let p="";p=o<2&&s>0?"coords":e.shapeInfo.logicalShape.map((e,t)=>"coords."+d[t+l]).join(", ");let f="return outputValue;";const m=1===h(e.shapeInfo.logicalShape),g=1===h(t.logicalShape);if(1!==s||m||g){if(m&&!g)f=1===o?"\n        return vec4(outputValue.x, outputValue.x, 0., 0.);\n      ":"\n        return vec4(outputValue.x);\n      ";else if(i.length){const e=s-2,t=s-1;i.indexOf(e)>-1&&i.indexOf(t)>-1?f="return vec4(outputValue.x);":i.indexOf(e)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":i.indexOf(t)>-1&&(f="return vec4(outputValue.xx, outputValue.zz);")}}else f="\n      return vec4(outputValue.xy, outputValue.xy);\n    ";return`\n    vec4 ${a}() {\n      ${u} coords = getOutputCoords();\n      ${c}\n      vec4 outputValue = get${r}(${p});\n      ${f}\n    }\n  `}(e,t):function(e,t){const n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),a="get"+r+"AtOutCoords",s=t.texShape,o=e.shapeInfo.texShape,i=e.shapeInfo.logicalShape.length,u=t.logicalShape.length;if(!e.shapeInfo.isUniform&&i===u&&null==e.shapeInfo.flatOffset&&f(o,s))return`\n      float ${a}() {\n        return sampleTexture(${n}, resultUV);\n      }\n    `;const l=wa(u),c=ca(e.shapeInfo.logicalShape,t.logicalShape),d=u-i;let p;const h=["x","y","z","w","u","v"];p=0===i?"":u<2&&c.length>=1?"coords = 0;":c.map(e=>`coords.${h[e+d]} = 0;`).join("\n");let m="";m=u<2&&i>0?"coords":e.shapeInfo.logicalShape.map((e,t)=>"coords."+h[t+d]).join(", ");return`\n    float ${a}() {\n      ${l} coords = getOutputCoords();\n      ${p}\n      return get${r}(${m});\n    }\n  `}(e,t));return r}(e,t,r)).join("\n"),i=t.texShape,u=Ur(),l=function(e){return`\n    float sampleTexture(sampler2D textureSampler, vec2 uv) {\n      return ${e.texture2D}(textureSampler, uv).r;\n    }\n  `}(u);let c,d,p=function(e){return`${e.version}\n    precision highp float;\n    precision highp int;\n    precision highp sampler2D;\n    ${e.varyingFs} vec2 resultUV;\n    ${e.defineOutput}\n    const vec2 halfCR = vec2(0.5, 0.5);\n\n    struct ivec5\n    {\n      int x;\n      int y;\n      int z;\n      int w;\n      int u;\n    };\n\n    struct ivec6\n    {\n      int x;\n      int y;\n      int z;\n      int w;\n      int u;\n      int v;\n    };\n\n    uniform float NAN;\n    ${e.defineSpecialNaN}\n    ${e.defineSpecialInf}\n    ${e.defineRound}\n\n    int imod(int x, int y) {\n      return x - y * (x / y);\n    }\n\n    int idiv(int a, int b, float sign) {\n      int res = a / b;\n      int mod = imod(a, b);\n      if (sign < 0. && mod != 0) {\n        res -= 1;\n      }\n      return res;\n    }\n\n    //Based on the work of Dave Hoskins\n    //https://www.shadertoy.com/view/4djSRW\n    #define HASHSCALE1 443.8975\n    float random(float seed){\n      vec2 p = resultUV * seed;\n      vec3 p3  = fract(vec3(p.xyx) * HASHSCALE1);\n      p3 += dot(p3, p3.yzx + 19.19);\n      return fract((p3.x + p3.y) * p3.z);\n    }\n\n    ${fa}\n    ${ma}\n    ${ga}\n  `}(u);t.isPacked?(c=function(e,t){switch(e.length){case 0:return ba();case 1:return function(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(1===n[0])return`\n      int getOutputCoords() {\n        return 2 * int(resultUV.x * ${n[1]}.0);\n      }\n    `;if(1===n[1])return`\n      int getOutputCoords() {\n        return 2 * int(resultUV.y * ${n[0]}.0);\n      }\n    `;return`\n    int getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(${n[0]}, ${n[1]}));\n      return 2 * (resTexRC.x * ${n[1]} + resTexRC.y);\n    }\n  `}(0,t);case 2:return function(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(f(e,t))return`\n      ivec2 getOutputCoords() {\n        return 2 * ivec2(resultUV.yx * vec2(${n[0]}, ${n[1]}));\n      }\n    `;const r=Math.ceil(e[1]/2);return`\n    ivec2 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(${n[0]}, ${n[1]}));\n\n      int index = resTexRC.x * ${n[1]} + resTexRC.y;\n      int r = 2 * (index / ${r});\n      int c = imod(index, ${r}) * 2;\n\n      return ivec2(r, c);\n    }\n  `}(e,t);case 3:return function(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(e[2]/2),a=r*Math.ceil(e[1]/2);return`\n    ivec3 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(${n[0]}, ${n[1]}));\n      int index = resTexRC.x * ${n[1]} + resTexRC.y;\n\n      int b = index / ${a};\n      index -= b * ${a};\n\n      int r = 2 * (index / ${r});\n      int c = imod(index, ${r}) * 2;\n\n      return ivec3(b, r, c);\n    }\n  `}(e,t);default:return function(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(e[e.length-1]/2),a=r*Math.ceil(e[e.length-2]/2);let s=a,o="",i="b, r, c";for(let t=2;t<e.length-1;t++)s*=e[e.length-t-1],o=`\n      int b${t} = index / ${s};\n      index -= b${t} * ${s};\n    `+o,i=`b${t}, `+i;return`\n    ivec${e.length} getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(${n[0]}, ${n[1]}));\n      int index = resTexRC.x * ${n[1]} + resTexRC.y;\n\n      ${o}\n\n      int b = index / ${a};\n      index -= b * ${a};\n\n      int r = 2 * (index / ${r});\n      int c = imod(index, ${r}) * 2;\n\n      return ivec${e.length}(${i});\n    }\n  `}(e,t)}}(t.logicalShape,i),d=function(e){return`\n    void setOutput(vec4 val) {\n      ${e.output} = val;\n    }\n  `}(u)):(c=function(e,t){switch(e.length){case 0:return ba();case 1:return function(e,t){if(1===t[0])return`\n      int getOutputCoords() {\n        return int(resultUV.x * ${t[1]}.0);\n      }\n    `;if(1===t[1])return`\n      int getOutputCoords() {\n        return int(resultUV.y * ${t[0]}.0);\n      }\n    `;return`\n    int getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(${t[0]}, ${t[1]}));\n      return resTexRC.x * ${t[1]} + resTexRC.y;\n    }\n  `}(0,t);case 2:return function(e,t){if(f(e,t))return`\n      ivec2 getOutputCoords() {\n        return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));\n      }\n    `;if(1===e[1])return`\n      ivec2 getOutputCoords() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n                               vec2(${t[0]}, ${t[1]}));\n        int index = resTexRC.x * ${t[1]} + resTexRC.y;\n        return ivec2(index, 0);\n      }\n    `;if(1===e[0])return`\n      ivec2 getOutputCoords() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n                               vec2(${t[0]}, ${t[1]}));\n        int index = resTexRC.x * ${t[1]} + resTexRC.y;\n        return ivec2(0, index);\n      }\n    `;return`\n    ivec2 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(${t[0]}, ${t[1]}));\n      int index = resTexRC.x * ${t[1]} + resTexRC.y;\n      int r = index / ${e[1]};\n      int c = index - r * ${e[1]};\n      return ivec2(r, c);\n    }\n  `}(e,t);case 3:return function(e,t){const n=Gr(["r","c","d"],e);return`\n    ivec3 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(${t[0]}, ${t[1]}));\n      int index = resTexRC.x * ${t[1]} + resTexRC.y;\n      ${n}\n      return ivec3(r, c, d);\n    }\n  `}(e,t);case 4:return function(e,t){const n=Gr(["r","c","d","d2"],e);return`\n    ivec4 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n        vec2(${t[0]}, ${t[1]}));\n      int index = resTexRC.x * ${t[1]} + resTexRC.y;\n      ${n}\n      return ivec4(r, c, d, d2);\n    }\n  `}(e,t);case 5:return function(e,t){const n=Gr(["r","c","d","d2","d3"],e);return`\n    ivec5 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},\n                             ${t[1]}));\n\n      int index = resTexRC.x * ${t[1]} + resTexRC.y;\n\n      ${n}\n\n      ivec5 outShape = ivec5(r, c, d, d2, d3);\n      return outShape;\n    }\n  `}(e,t);case 6:return function(e,t){const n=Gr(["r","c","d","d2","d3","d4"],e);return`\n    ivec6 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n        vec2(${t[0]}, ${t[1]}));\n      int index = resTexRC.x * ${t[1]} + resTexRC.y;\n\n      ${n}\n\n      ivec6 result = ivec6(r, c, d, d2, d3, d4);\n      return result;\n    }\n  `}(e,t);default:throw new Error(e.length+"-D output sampling is not yet supported")}}(t.logicalShape,i),d=function(e){return`\n    void setOutput(float val) {\n      ${e.output} = vec4(val, 0, 0, 0);\n    }\n  `}(u)),r&&(p+=ya);return[p,l,d,s,c,o,n].join("\n")}function pa(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return function(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`float ${n}() {return ${t};}`;const[r,a]=e.shapeInfo.texShape;if(1===r&&1===a)return`\n      float ${n}() {\n        return sampleTexture(${t}, halfCR);\n      }\n    `;const[s,o]=e.shapeInfo.texShape,i=xa(t);return`\n    float ${n}() {\n      vec2 uv = uvFromFlat(${s}, ${o}, ${i});\n      return sampleTexture(${t}, uv);\n    }\n  `}(e);case 1:return function(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`\n      float ${n}(int index) {\n        ${ka(e)}\n      }\n    `;const r=e.shapeInfo.texShape,a=r[0],s=r[1];if(1===s&&1===a)return`\n      float ${n}(int index) {\n        return sampleTexture(${t}, halfCR);\n      }\n    `;const o=xa(t);if(1===s)return`\n      float ${n}(int index) {\n        vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / ${a}.0);\n        return sampleTexture(${t}, uv);\n      }\n    `;if(1===a)return`\n      float ${n}(int index) {\n        vec2 uv = vec2((float(index + ${o}) + 0.5) / ${s}.0, 0.5);\n        return sampleTexture(${t}, uv);\n      }\n    `;return`\n    float ${n}(int index) {\n      vec2 uv = uvFromFlat(${a}, ${s}, index + ${o});\n      return sampleTexture(${t}, uv);\n    }\n  `}(e);case 2:return function(e){const t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=e.shapeInfo.texShape;if(null!=a&&f(t,a)){const e=a[0],t=a[1];return`\n    float ${r}(int row, int col) {\n      vec2 uv = (vec2(col, row) + halfCR) / vec2(${t}.0, ${e}.0);\n      return sampleTexture(${n}, uv);\n    }\n  `}const{newShape:s,keptDims:o}=w(t),i=s;if(i.length<t.length){const t=va(e,i),n=["row","col"];return`\n      ${pa(t)}\n      float ${r}(int row, int col) {\n        return ${r}(${Ia(n,o)});\n      }\n    `}if(e.shapeInfo.isUniform)return`\n      float ${r}(int row, int col) {\n        int index = round(dot(vec2(row, col), vec2(${t[1]}, 1)));\n        ${ka(e)}\n      }\n    `;const u=a[0],l=a[1],c=xa(n);if(1===l)return`\n    float ${r}(int row, int col) {\n      float index = dot(vec3(row, col, ${c}), vec3(${t[1]}, 1, 1));\n      vec2 uv = vec2(0.5, (index + 0.5) / ${u}.0);\n      return sampleTexture(${n}, uv);\n    }\n  `;if(1===u)return`\n    float ${r}(int row, int col) {\n      float index = dot(vec3(row, col, ${c}), vec3(${t[1]}, 1, 1));\n      vec2 uv = vec2((index + 0.5) / ${l}.0, 0.5);\n      return sampleTexture(${n}, uv);\n    }\n  `;return`\n  float ${r}(int row, int col) {\n    // Explicitly use integer operations as dot() only works on floats.\n    int index = row * ${t[1]} + col + ${c};\n    vec2 uv = uvFromFlat(${u}, ${l}, index);\n    return sampleTexture(${n}, uv);\n  }\n`}(e);case 3:return function(e){const t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=t[1]*t[2],s=t[2],{newShape:o,keptDims:i}=w(t),u=o;if(u.length<t.length){const t=va(e,u),n=["row","col","depth"];return`\n        ${pa(t)}\n        float ${r}(int row, int col, int depth) {\n          return ${r}(${Ia(n,i)});\n        }\n      `}if(e.shapeInfo.isUniform)return`\n      float ${r}(int row, int col, int depth) {\n        int index = round(dot(vec3(row, col, depth),\n                          vec3(${a}, ${s}, 1)));\n        ${ka(e)}\n      }\n    `;const l=e.shapeInfo.texShape,c=l[0],d=l[1],p=e.shapeInfo.flatOffset;if(d===a&&null==p)return`\n        float ${r}(int row, int col, int depth) {\n          float texR = float(row);\n          float texC = dot(vec2(col, depth), vec2(${s}, 1));\n          vec2 uv = (vec2(texC, texR) + halfCR) /\n                     vec2(${d}.0, ${c}.0);\n          return sampleTexture(${n}, uv);\n        }\n      `;if(d===s&&null==p)return`\n    float ${r}(int row, int col, int depth) {\n      float texR = dot(vec2(row, col), vec2(${t[1]}, 1));\n      float texC = float(depth);\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${d}.0, ${c}.0);\n      return sampleTexture(${n}, uv);\n    }\n  `;const h=xa(n);return`\n      float ${r}(int row, int col, int depth) {\n        // Explicitly use integer operations as dot() only works on floats.\n        int index = row * ${a} + col * ${s} + depth + ${h};\n        vec2 uv = uvFromFlat(${c}, ${d}, index);\n        return sampleTexture(${n}, uv);\n      }\n  `}(e);case 4:return function(e){const t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=t[3],s=t[2]*a,o=t[1]*s,{newShape:i,keptDims:u}=w(t);if(i.length<t.length){const t=va(e,i),n=["row","col","depth","depth2"];return`\n      ${pa(t)}\n      float ${r}(int row, int col, int depth, int depth2) {\n        return ${r}(${Ia(n,u)});\n      }\n    `}if(e.shapeInfo.isUniform)return`\n      float ${r}(int row, int col, int depth, int depth2) {\n        int index = round(dot(vec4(row, col, depth, depth2),\n                          vec4(${o}, ${s}, ${a}, 1)));\n        ${ka(e)}\n      }\n    `;const l=e.shapeInfo.flatOffset,c=e.shapeInfo.texShape,d=c[0],p=c[1];if(p===o&&null==l)return`\n      float ${r}(int row, int col, int depth, int depth2) {\n        float texR = float(row);\n        float texC =\n            dot(vec3(col, depth, depth2),\n                vec3(${s}, ${a}, 1));\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2(${p}.0, ${d}.0);\n        return sampleTexture(${n}, uv);\n      }\n    `;if(p===a&&null==l)return`\n      float ${r}(int row, int col, int depth, int depth2) {\n        float texR = dot(vec3(row, col, depth),\n                         vec3(${t[1]*t[2]}, ${t[2]}, 1));\n        float texC = float(depth2);\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2(${p}.0, ${d}.0);\n        return sampleTexture(${n}, uv);\n      }\n    `;const h=xa(n);return`\n    float ${r}(int row, int col, int depth, int depth2) {\n      // Explicitly use integer operations as dot() only works on floats.\n      int index = row * ${o} + col * ${s} +\n          depth * ${a} + depth2;\n      vec2 uv = uvFromFlat(${d}, ${p}, index + ${h});\n      return sampleTexture(${n}, uv);\n    }\n  `}(e);case 5:return function(e){const t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=t[4],s=t[3]*a,o=t[2]*s,i=t[1]*o,{newShape:u,keptDims:l}=w(t);if(u.length<t.length){const t=va(e,u),n=["row","col","depth","depth2","depth3"];return`\n      ${pa(t)}\n      float ${r}(int row, int col, int depth, int depth2, int depth3) {\n        return ${r}(${Ia(n,l)});\n      }\n    `}if(e.shapeInfo.isUniform)return`\n      float ${r}(int row, int col, int depth, int depth2, int depth3) {\n        float index = dot(\n          vec4(row, col, depth, depth2),\n          vec4(${i}, ${o}, ${s}, ${a})) +\n          depth3;\n        ${ka(e)}\n      }\n    `;const c=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,p=d[0],h=d[1];if(h===i&&null==c)return`\n      float ${r}(int row, int col, int depth, int depth2, int depth3) {\n        int texR = row;\n        float texC = dot(vec4(col, depth, depth2, depth3),\n                         vec4(${o}, ${s}, ${a}, 1));\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2(${h}.0, ${p}.0);\n        return sampleTexture(${n}, uv);\n      }\n    `;if(h===a&&null==c)return`\n      float ${r}(int row, int col, int depth, int depth2, int depth3) {\n        float texR = dot(\n          vec4(row, col, depth, depth2),\n          vec4(${t[1]*t[2]*t[3]},\n               ${t[2]*t[3]}, ${t[3]}, 1));\n        int texC = depth3;\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2(${h}.0, ${p}.0);\n        return sampleTexture(${n}, uv);\n      }\n    `;const f=xa(n);return`\n    float ${r}(int row, int col, int depth, int depth2, int depth3) {\n      // Explicitly use integer operations as dot() only works on floats.\n      int index = row * ${i} + col * ${o} + depth * ${s} +\n          depth2 * ${a} + depth3 + ${f};\n      vec2 uv = uvFromFlat(${p}, ${h}, index);\n      return sampleTexture(${n}, uv);\n    }\n  `}(e);case 6:return function(e){const t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:a,keptDims:s}=w(t);if(a.length<t.length){const t=va(e,a),n=["row","col","depth","depth2","depth3","depth4"];return`\n      ${pa(t)}\n      float ${r}(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        return ${r}(${Ia(n,s)});\n      }\n    `}const o=t[5],i=t[4]*o,u=t[3]*i,l=t[2]*u,c=t[1]*l;if(e.shapeInfo.isUniform)return`\n      float ${r}(int row, int col, int depth,\n                  int depth2, int depth3, int depth4) {\n        int index = round(dot(\n          vec4(row, col, depth, depth2),\n          vec4(${c}, ${l}, ${u}, ${i})) +\n          dot(\n            vec2(depth3, depth4),\n            vec2(${o}, 1)));\n        ${ka(e)}\n      }\n    `;const d=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,h=p[0],f=p[1];if(f===c&&null==d)return`\n      float ${r}(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        int texR = row;\n        float texC = dot(vec4(col, depth, depth2, depth3),\n          vec4(${l}, ${u}, ${i}, ${o})) +\n               float(depth4);\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2(${f}.0, ${h}.0);\n        return sampleTexture(${n}, uv);\n      }\n    `;if(f===o&&null==d)return`\n      float ${r}(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        float texR = dot(vec4(row, col, depth, depth2),\n          vec4(${t[1]*t[2]*t[3]*t[4]},\n               ${t[2]*t[3]*t[4]},\n               ${t[3]*t[4]},\n               ${t[4]})) + float(depth3);\n        int texC = depth4;\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2(${f}.0, ${h}.0);\n        return sampleTexture(${n}, uv);\n      }\n    `;const m=xa(n);return`\n    float ${r}(int row, int col, int depth,\n                  int depth2, int depth3, int depth4) {\n      // Explicitly use integer operations as dot() only works on floats.\n      int index = row * ${c} + col * ${l} + depth * ${u} +\n          depth2 * ${i} + depth3 * ${o} + depth4 + ${m};\n      vec2 uv = uvFromFlat(${h}, ${f}, index);\n      return sampleTexture(${n}, uv);\n    }\n  `}(e);default:throw new Error(t.length+"-D input sampling is not yet supported")}}function ha(e){switch(e.shapeInfo.logicalShape.length){case 0:return function(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),r=Ur();return`\n    vec4 ${n}() {\n      return ${r.texture2D}(${t}, halfCR);\n    }\n  `}(e);case 1:return function(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),r=e.shapeInfo.texShape,a=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],s=Ur();return`\n    vec4 ${n}(int index) {\n      vec2 uv = packedUVfrom1D(\n        ${a[0]}, ${a[1]}, index);\n      return ${s.texture2D}(${t}, uv);\n    }\n  `}(e);case 2:return function(e){const t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=e.shapeInfo.texShape,s=a[0],o=a[1],i=Ur();if(null!=a&&f(t,a))return`\n      vec4 ${r}(int row, int col) {\n        vec2 uv = (vec2(col, row) + halfCR) / vec2(${o}.0, ${s}.0);\n\n        return ${i.texture2D}(${n}, uv);\n      }\n    `;const u=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],l=Math.ceil(t[1]/2);return`\n    vec4 ${r}(int row, int col) {\n      vec2 uv = packedUVfrom2D(${l}, ${u[0]}, ${u[1]}, row, col);\n      return ${i.texture2D}(${n}, uv);\n    }\n  `}(e);case 3:return function(e){const t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),a=e.shapeInfo.texShape,s=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];if(1===t[0]){const n=t.slice(1),a=[1,2],s=va(e,n),o=["b","row","col"];return`\n        ${ha(s)}\n        vec4 ${r}(int b, int row, int col) {\n          return ${r}(${Ia(o,a)});\n        }\n      `}const o=s[0],i=s[1],u=Math.ceil(t[2]/2),l=u*Math.ceil(t[1]/2),c=Ur();return`\n    vec4 ${r}(int b, int row, int col) {\n      vec2 uv = packedUVfrom3D(\n        ${o}, ${i}, ${l}, ${u}, b, row, col);\n      return ${c.texture2D}(${n}, uv);\n    }\n  `}(e);default:return function(e){const t=e.shapeInfo.logicalShape,n=t.length,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),s=e.shapeInfo.texShape,o=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],i=o[0],u=o[1],l=Math.ceil(t[n-1]/2);let c=l*Math.ceil(t[n-2]/2),d="int b, int row, int col",p=`b * ${c} + (row / 2) * ${l} + (col / 2)`;for(let e=2;e<n-1;e++)d=`int b${e}, `+d,c*=t[n-e-1],p=`b${e} * ${c} + `+p;const h=Ur();return`\n    vec4 ${a}(${d}) {\n      int index = ${p};\n      int texR = index / ${u};\n      int texC = index - texR * ${u};\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${u}, ${i});\n      return ${h.texture2D}(${r}, uv);\n    }\n  `}(e)}}const fa="\nvec2 uvFromFlat(int texNumR, int texNumC, int index) {\n  int texR = index / texNumC;\n  int texC = index - texR * texNumC;\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n  int texelIndex = index / 2;\n  int texR = texelIndex / texNumC;\n  int texC = texelIndex - texR * texNumC;\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",ma="\nvec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,\n  int texNumC, int row, int col) {\n  int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n  int texR = texelIndex / texNumC;\n  int texC = texelIndex - texR * texNumC;\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",ga="\nvec2 packedUVfrom3D(int texNumR, int texNumC,\n    int texelsInBatch, int texelsInLogicalRow, int b,\n    int row, int col) {\n  int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n  int texR = index / texNumC;\n  int texC = index - texR * texNumC;\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",ya="\n  float getChannel(vec4 frag, vec2 innerDims) {\n    vec2 modCoord = mod(innerDims, 2.);\n    return modCoord.x == 0. ?\n      (modCoord.y == 0. ? frag.r : frag.g) :\n      (modCoord.y == 0. ? frag.b : frag.a);\n  }\n  float getChannel(vec4 frag, int dim) {\n    float modCoord = mod(float(dim), 2.);\n    return modCoord == 0. ? frag.r : frag.g;\n  }\n";function ba(){return"\n    int getOutputCoords() {\n      return 0;\n    }\n  "}function xa(e){return"offset"+e}function ka(e){const t=e.name,n=h(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`\n    for (int i = 0; i < ${n}; i++) {\n      if (i == index) {\n        return ${t}[i];\n      }\n    }\n  `}function wa(e){if(e<=1)return"int";if(2===e)return"ivec2";if(3===e)return"ivec3";if(4===e)return"ivec4";if(5===e)return"ivec5";if(6===e)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function va(e,t){const n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function Ia(e,t){return t.map(t=>e[t]).join(", ")}function Na(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);e.forEach((e,n)=>{const r=e.logicalShape,a=t[n],s=a.shape;if(!f(r,s))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${r} and ${s} must match`);if(e.isUniform&&a.isUniform)return;const o=e.texShape,i=a.isUniform?null:a.texData.texShape;if(!f(o,i))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${o} and ${i} must match`)})}function Sa(e,t){Array.isArray(e)||(e=[e]),e.forEach(e=>{null!=e&&c("complex64"!==e.dtype,()=>t+" does not support complex64 tensors in the CPU backend.")})}function Ca(e){const t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}const Ta={kernelName:"Abs",backendName:"cpu",kernelFunc:e=>{const{x:t}=e.inputs,n=e.backend;Sa(t,"abs");let r=new Float32Array(h(t.shape));return r=Ca(n.data.get(t.dataId).values),n.makeOutput(r,t.shape,"float32")}};function Ea(e){return(t,n,r,a,s)=>{const o=Jt(t,n),i=o.length,u=A(o),l=v(s,h(o)),c=t.length,d=n.length,p=A(t),f=A(n),m=Yt(t,o),g=Yt(n,o);if(m.length+g.length===0)for(let t=0;t<l.length;++t)l[t]=e(r[t%r.length],a[t%a.length]);else for(let t=0;t<l.length;++t){const n=P(t,i,u),s=n.slice(-c);m.forEach(e=>s[e]=0);const o=O(s,c,p),h=n.slice(-d);g.forEach(e=>h[e]=0);const y=O(h,d,f);l[t]=e(r[o],a[y])}return[l,o]}}function $a(e){const{inputs:t,backend:n}=e,{real:r,imag:a}=t,s=n.data.get(r.dataId).values,o=n.data.get(a.dataId).values,i=n.makeTensorInfo(r.shape,"complex64");return n.data.get(i.dataId).complexTensorInfos={real:n.makeTensorInfo(r.shape,"float32",s),imag:n.makeTensorInfo(a.shape,"float32",o)},i}const _a={kernelName:"Complex",backendName:"cpu",kernelFunc:$a};function Aa(e,t,n="float32"){if("complex64"===n){return $a({inputs:{real:Aa(e,t,"float32"),imag:Aa(e,t,"float32")},backend:e})}const r=M(h(t),n);return e.makeTensorInfo(t,n,r)}function Ra(e){const{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}const Ma={kernelName:"Identity",backendName:"cpu",kernelFunc:Ra};function Fa(e){const{inputs:t,backend:n}=e,{input:r}=t,a=n.data.get(r.dataId).complexTensorInfos.real,s=n.data.get(a.dataId).values;return n.makeTensorInfo(a.shape,a.dtype,s)}const Da={kernelName:"Real",backendName:"cpu",kernelFunc:Fa};function Oa(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dtype:s}=r;if("complex64"===s){if("complex64"===a.dtype)return Ra({inputs:{x:a},backend:n});const e=Aa(n,a.shape,a.dtype),t=Oa({inputs:{x:a},backend:n,attrs:{dtype:"float32"}}),r=$a({inputs:{real:t,imag:e},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),r}if("complex64"===a.dtype){const e=Fa({inputs:{input:a},backend:n}),t=Oa({inputs:{x:e},backend:n,attrs:{dtype:s}});return n.disposeIntermediateTensorInfo(e),t}if(!N(a.dtype,s)){const e=Ra({inputs:{x:a},backend:n});return{dataId:e.dataId,shape:e.shape,dtype:s}}if("int32"===s){const e=n.data.get(a.dataId).values,t=Int32Array.from(e);return n.makeTensorInfo(a.shape,"int32",t)}if("bool"===s){const e=n.data.get(a.dataId).values,t=Z([0],a.dtype),[r,s]=Ea((e,t)=>e!==t?1:0)(a.shape,[],e,t,"bool");return n.makeTensorInfo(s,"bool",r)}throw new Error(`Error in Cast: failed to cast ${a.dtype} to ${s}`)}const Pa={kernelName:"Cast",backendName:"cpu",kernelFunc:Oa};function La(e,t,n,r){return null==n?({inputs:n,backend:a})=>{const{a:s,b:o}=n,i=a;Sa([s,o],e);const u=i.data.get(s.dataId).values,l=i.data.get(o.dataId).values,c=r||s.dtype,[d,p]=t(s.shape,o.shape,u,l,c);return i.makeTensorInfo(p,c,d)}:({inputs:e,backend:a})=>{const{a:s,b:o}=e,i=a;if("complex64"===s.dtype||"complex64"===o.dtype){const e=Oa({inputs:{x:s},backend:i,attrs:{dtype:"complex64"}}),t=i.data.get(e.dataId),r=t.complexTensorInfos.real,a=t.complexTensorInfos.imag,u=i.data.get(r.dataId).values,l=i.data.get(a.dataId).values,c=Oa({inputs:{x:o},backend:i,attrs:{dtype:"complex64"}}),d=i.data.get(c.dataId),p=d.complexTensorInfos.real,h=d.complexTensorInfos.imag,f=i.data.get(p.dataId).values,m=i.data.get(h.dataId).values,[g,y,b]=n(s.shape,o.shape,u,l,f,m),x=i.makeTensorInfo(b,"float32",g),k=i.makeTensorInfo(b,"float32",y),w=$a({inputs:{real:x,imag:k},backend:i});return i.disposeIntermediateTensorInfo(e),i.disposeIntermediateTensorInfo(c),i.disposeIntermediateTensorInfo(x),i.disposeIntermediateTensorInfo(k),w}{const e=i.data.get(s.dataId).values,n=i.data.get(o.dataId).values,a=r||s.dtype,[u,l]=t(s.shape,o.shape,e,n,a);return i.makeTensorInfo(l,a,u)}}}function Ba(e){return(t,n,r,a,s,o)=>{const i=Jt(t,n),u=h(i),l=i.length,c=A(i),d=v("float32",u),p=v("float32",u),f=Yt(t,i),m=Yt(n,i),g=jn(r,a),y=jn(s,o),b=t.length,x=A(t),k=n.length,w=A(n);if(f.length+m.length===0)for(let t=0;t<d.length;t++){const n=t%g.length,r=t%y.length,a=e(g[2*n],g[2*n+1],y[2*r],y[2*r+1]);d[t]=a.real,p[t]=a.imag}else for(let t=0;t<d.length;t++){const n=P(t,l,c),r=n.slice(-b);f.forEach(e=>r[e]=0);const a=O(r,b,x),s=n.slice(-k);m.forEach(e=>s[e]=0);const o=O(s,k,w),i=e(g[2*a],g[2*a+1],y[2*o],y[2*o+1]);d[t]=i.real,p[t]=i.imag}return[d,p,i]}}const Wa=Ea((e,t)=>e+t),za=La("Add",Wa,Ba((e,t,n,r)=>({real:e+n,imag:t+r}))),Va={kernelName:"Add",backendName:"cpu",kernelFunc:za};function Ua(e,t,n,r,a){const s=h(r),o=M(a,n);for(let n=0;n<e.length;n++){const r=e[n];if(r<0)throw new Error("Input x must be non-negative!");r>=a||(o[r]+=s>0?t[n]:1)}return o}function Ga(e,t,n,r=!1){const a=e.shape[0],s=e.shape[1],o=lt([a,n],t.dtype);for(let i=0;i<a;i++)for(let a=0;a<s;a++){const s=e.get(i,a);if(s<0)throw new Error("Input x must be non-negative!");s>=n||(r?o.set(1,i,s):t.size>0?o.set(o.get(i,s)+t.get(i,a),i,s):o.set(o.get(i,s)+1,i,s))}return o}function Ha(e){return(t,n,r)=>{const a=v(n,t.length);for(let n=0;n<t.length;++n)a[n]=e(t[n],r);return a}}function ja(e,t,n){return({inputs:r,attrs:a,backend:s})=>{const{x:o}=r;if(Sa(o,e),"string"===o.dtype||"string"===n)throw new Error("unaryKernelFunc does not support string input/output");const i=s,u=i.data.get(o.dataId).values,l=h(o.shape),c=n||o.dtype,d=I(c,l);for(let e=0;e<l;++e)d[e]=t(u[e],a);return i.makeTensorInfo(o.shape,c,d)}}function qa(e,t,n){return({inputs:r,attrs:a,backend:s})=>{const{x:o}=r;if(Sa(o,e),"string"===o.dtype||"string"===n)throw new Error("unaryKernelFunc does not support string input/output");const i=s,u=i.data.get(o.dataId).values,l=n||o.dtype,c=t(u,l,a);return i.makeTensorInfo(o.shape,l,c)}}const Ka=Ha(e=>Math.ceil(e)),Xa={kernelName:"Ceil",backendName:"cpu",kernelFunc:qa("Ceil",Ka)};function Ya(e,t,n,r){const a=I(n,h(t));if(r&&"string"!==n){let t=0;e.forEach(e=>{const n=h(e.shape);a.set(e.vals,t),t+=n})}else{let r=0;e.forEach(e=>{const s="string"===n?sr(e.vals):e.vals;let o=0;for(let n=0;n<e.shape[0];++n){const i=n*t[1]+r;for(let t=0;t<e.shape[1];++t)a[i+t]=s[o++]}r+=e.shape[1]})}return a}const Qa=Ha(e=>Math.exp(e)),Ja=qa("Exp",Qa),Za={kernelName:"Exp",backendName:"cpu",kernelFunc:Ja},es=Ha(e=>Math.expm1(e)),ts={kernelName:"Expm1",backendName:"cpu",kernelFunc:qa("Expm1",es)},ns=Ha(e=>Math.floor(e)),rs={kernelName:"Floor",backendName:"cpu",kernelFunc:qa("Floor",ns)};function as(e,t,n){const r=lt(n,e.dtype);for(let n=0;n<r.size;++n){const a=r.indexToLoc(n).slice(),s=a[0],o=a[2],i=t.locToIndex([s,o]);a[2]=t.values[i];const u=e.locToIndex(a);r.values[n]=e.values[u]}return r}const ss=Ea((e,t)=>e>t?1:0),os={kernelName:"Greater",backendName:"cpu",kernelFunc:La("Greater",ss,null,"bool")},is=Ea((e,t)=>e<t?1:0),us={kernelName:"Less",backendName:"cpu",kernelFunc:La("Less",is,null,"bool")};function ls(e,t,n){const r=(t-e)/(n-1),a=M(n,"float32");a[0]=e;for(let e=1;e<a.length;e++)a[e]=a[e-1]+r;return a}const cs=Ha(e=>Math.log(e)),ds={kernelName:"Log",backendName:"cpu",kernelFunc:qa("Log",cs)};function ps(e,t,n,r){const a=v(r,h(n));for(let n=0;n<a.length;++n){const r=n*t;let s=e[r];for(let n=0;n<t;++n){const t=e[r+n];t>s&&(s=t)}a[n]=s}return a}const hs=Ea((e,t)=>Math.max(e,t)),fs={kernelName:"Maximum",backendName:"cpu",kernelFunc:La("Maximum",hs)},ms=Ea((e,t)=>Math.min(e,t)),gs={kernelName:"Minimum",backendName:"cpu",kernelFunc:La("Minimum",ms)},ys=Ea((e,t)=>e*t),bs=Ba((e,t,n,r)=>({real:e*n-t*r,imag:e*r+t*n})),xs=La("Multiply",ys,bs),ks={kernelName:"Multiply",backendName:"cpu",kernelFunc:xs};function ws(e,t,n){const r=J(-1,n);return ys([],t,r,e,n)}const vs={kernelName:"Neg",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t;Sa(r,"neg");const a=n.data.get(r.dataId).values,[s,o]=ws(a,r.shape,r.dtype);return n.makeTensorInfo(o,r.dtype,s)}},Is=Ea((e,t)=>e!==t?1:0),Ns={kernelName:"NotEqual",backendName:"cpu",kernelFunc:La("NotEqual",Is,null,"bool")};function Ss(e,t,n,r,a){const s=t.length,o=h(t),i=A(t),u=A(a),l=v(n,h(a));for(let t=0;t<o;++t){const n=P(t,s,i),a=new Array(n.length);for(let e=0;e<a.length;e++)a[e]=n[r[e]];l[O(a,s,u)]=e[t]}return l}function Cs(e){const{inputs:t,attrs:n,backend:r}=e,{x:a}=t,{perm:s}=n;Sa(a,"transpose");const o=a.shape.length,i=new Array(o);for(let e=0;e<i.length;e++)i[e]=a.shape[s[e]];const u=Ss(r.data.get(a.dataId).values,a.shape,a.dtype,s,i);return{dataId:r.write(u,i,a.dtype),shape:i,dtype:a.dtype}}const Ts={kernelName:"Transpose",backendName:"cpu",kernelFunc:Cs};function Es(e,t,n,r){const[a,s]=an(e,r),o=we(t,"int32"),i=M(h(a),o),u=h(s);for(let e=0;e<i.length;++e){const t=e*u;let r=1;for(let e=0;e<u;++e)r*=n[t+e];i[e]=r}return{outVals:i,outShape:a,outDtype:o}}const $s={kernelName:"Prod",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r;Sa(a,"prod");const i=a.shape.length,u=k(s,a.shape),l=un(u,i);let c=u,d=a;const p=[];null!=l&&(d=Cs({inputs:{x:a},backend:n,attrs:{perm:l}}),p.push(d),c=cn(c.length,i));const h=n.data.get(d.dataId).values,{outVals:f,outShape:m,outDtype:g}=Es(d.shape,d.dtype,h,c);let y=m;return o&&(y=sn(m,u)),p.forEach(e=>n.disposeIntermediateTensorInfo(e)),n.makeTensorInfo(y,g,f)}};function _s(e,t,n,r){if(e===t||e<t&&n<0||t<e&&n>1)return M(0,r);const a=M(Math.abs(Math.ceil((t-e)/n)),r);t<e&&1===n&&(n=-1),a[0]=e;for(let e=1;e<a.length;e++)a[e]=a[e-1]+n;return a}const As=Ha(e=>1/Math.sqrt(e)),Rs={kernelName:"Rsqrt",backendName:"cpu",kernelFunc:qa("Rsqrt",As)};function Ms(e,t,n,r,a){const s=Tt(r,t,n),o=h(n),i=A(r);if(s){const n=Et(t,i);return"string"===a?e.slice(n,n+o):e.subarray(n,n+o)}const u=lt(r,a,"string"===a?sr(e):e),l=lt(n,a);for(let e=0;e<l.size;++e){const n=l.indexToLoc(e),r=n.map((e,n)=>e+t[n]);l.set(u.get(...r),...n)}return"string"===a?or(l.values):l.values}function Fs(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{begin:s,size:o}=r;Sa(a,"slice");const[i,u]=$t(a,s,o);mt(a,i,u);const l=Ms(n.data.get(a.dataId).values,i,u,a.shape,a.dtype);return n.makeTensorInfo(u,a.dtype,l)}const Ds={kernelName:"Slice",backendName:"cpu",kernelFunc:Fs},Os=Ea((e,t)=>{const n=e-t;return n*n}),Ps={kernelName:"SquaredDifference",backendName:"cpu",kernelFunc:La("SquaredDifference",Os)};function Ls(e,t,n,r){const a=lt(e,t.dtype);for(let e=0;e<a.size;e++){const s=a.indexToLoc(e),o=new Array(s.length);for(let e=0;e<o.length;e++)o[e]=s[e]*n[e]+r[e];a.set(t.get(...o),...s)}return a}const Bs=Ea((e,t)=>e-t),Ws=La("Sub",Bs,Ba((e,t,n,r)=>({real:e-n,imag:t-r}))),zs={kernelName:"Sub",backendName:"cpu",kernelFunc:Ws};function Vs(e,t){const n=new Array(e.rank);for(let r=0;r<n.length;r++)n[r]=e.shape[r]*t[r];const r=lt(n,e.dtype);for(let t=0;t<r.values.length;++t){const n=r.indexToLoc(t),a=new Array(e.rank);for(let t=0;t<a.length;t++)a[t]=n[t]%e.shape[t];const s=e.locToIndex(a);r.values[t]=e.values[s]}return r}function Us(e,t,n,r,a){const s=t[t.length-1],[o,i]=[e.length/s,s],u=v(n,o*r),l=v("int32",o*r);for(let t=0;t<o;t++){const n=t*i,a=e.subarray(n,n+i),s=[];for(let e=0;e<a.length;e++)s.push({value:a[e],index:e});s.sort((e,t)=>t.value-e.value);const o=t*r,c=u.subarray(o,o+r),d=l.subarray(o,o+r);for(let e=0;e<r;e++)c[e]=s[e].value,d[e]=s[e].index}const c=t.slice();return c[c.length-1]=r,[lt(c,n,u),lt(c,"int32",l)]}function Gs(e,t,n,r){const a=k(t,n)[0],s=[1,n[0],1];for(let e=0;e<a;e++)s[0]*=n[e];s[1]=n[a];for(let e=a+1;e<n.length;e++)s[2]*=n[e];const o={},i=new Int32Array(n[a]),u=new ce(s,r,e),l=[],c=1===s[0]&&1===s[2];for(let t=0;t<n[a];t++){let n;if(c)n=e[t].toString();else{const e=[];for(let n=0;n<s[0];n++)for(let r=0;r<s[2];r++)e.push(u.get(n,t,r));n=e.join(",")}if(void 0!==o[n])i[t]=o[n];else{const e=Object.keys(o).length;o[n]=e,i[t]=e,l.push(t)}}const d=s.slice();d[1]=Object.keys(o).length;const p=new ce(d,r);l.forEach((e,t)=>{for(let n=0;n<s[0];n++)for(let r=0;r<s[2];r++)p.set(u.get(n,e,r),n,t,r)});const h=n.slice();return h[a]=d[1],{outputValues:p.values,outputShape:h,indices:i}}var Hs=Object.freeze({__proto__:null,simpleAbsImpl:Ca,addImpl:Wa,bincountImpl:Ua,bincountReduceImpl:Ga,ceilImpl:Ka,concatImpl:Ya,expImpl:Qa,expm1Impl:es,floorImpl:ns,gatherV2Impl:as,greaterImpl:ss,lessImpl:is,linSpaceImpl:ls,logImpl:cs,maxImpl:ps,maximumImpl:hs,minimumImpl:ms,multiplyImpl:ys,negImpl:ws,notEqualImpl:Is,prodImpl:Es,rangeImpl:_s,rsqrtImpl:As,sliceImpl:Ms,squaredDifferenceImpl:Os,stridedSliceImpl:Ls,subImpl:Bs,tileImpl:Vs,topKImpl:Us,transposeImpl:Ss,uniqueImpl:Gs});const{addImpl:js,bincountImpl:qs,bincountReduceImpl:Ks,ceilImpl:Xs,concatImpl:Ys,expImpl:Qs,expm1Impl:Js,floorImpl:Zs,gatherV2Impl:eo,greaterImpl:to,lessImpl:no,linSpaceImpl:ro,logImpl:ao,maxImpl:so,maximumImpl:oo,minimumImpl:io,multiplyImpl:uo,negImpl:lo,prodImpl:co,rangeImpl:po,rsqrtImpl:ho,simpleAbsImpl:fo,sliceImpl:mo,stridedSliceImpl:go,subImpl:yo,tileImpl:bo,topKImpl:xo,transposeImpl:ko,uniqueImpl:wo}=Hs;function vo(e,t){return["x","y","z","w","u","v"].slice(0,t).map(t=>`${e}.${t}`)}function Io(e,t){return 1===t?[e]:vo(e,t)}class No{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e;const t=e.length;if(0===t)this.userCode="\n        void main() {\n          setOutput(vec4(getA(), 0., 0., 0.));\n        }\n      ";else{const n=Io("rc",t),r=wa(t),a=function(e,t,n){if(1===e)return"rc > "+t[0];let r="";for(let a=e-2;a<e;a++)r+=`${n[a]} >= ${t[a]}`,a<e-1&&(r+="||");return r}(t,e,n),s=function(e,t,n,r){if(1===e)return"";const a=r.slice(-2);return`\n    int r = ${a[0]};\n    int c = ${a[1]};\n    int rp1 = r + 1;\n    int cp1 = c + 1;\n\n    bool cEdge = cp1 >= ${t};\n    bool rEdge = rp1 >= ${n};\n  `}(t,e[e.length-1],e[e.length-2],n),o=function(e,t){const n=e.length,r=function(e,t){const n=[];for(let r=0;r<=1;r++)for(let a=0;a<=1;a++){let s=`${0===r?"r":"rp1"}, ${0===a?"c":"cp1"}`;for(let n=2;n<e;n++)s=t[t.length-1-n]+","+s;n.push(s)}return n}(n,t);if(1===n)return`getA(rc),\n            rc + 1 >= ${e[0]} ? 0. : getA(rc + 1),\n            0, 0`;return`getA(${r[0]}),\n          cEdge ? 0. : getA(${r[1]}),\n          rEdge ? 0. : getA(${r[2]}),\n          rEdge || cEdge ? 0. : getA(${r[3]})`}(e,n);this.userCode=`\n        void main() {\n          ${r} rc = getOutputCoords();\n\n          if(${a}) {\n            setOutput(vec4(0));\n          } else {\n            ${s}\n\n            setOutput(vec4(${o}));\n          }\n        }\n      `}}}class So{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;let n="";for(let e=0;e<4;e++){let t="thisRC = rc;";e%2==1&&(t+="thisRC.z += 1;"),e>1&&(t+="thisRC.y += 1;"),n+=`\n        ${t}\n        ${e>0?"if(thisRC.y < rows && thisRC.z < cols){":""}\n          int flatIndex = getFlatIndex(thisRC);\n\n          ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n          vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n          result[${e}] =\n            getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n        ${e>0?"}":""}\n      `}var r;this.userCode=`\n      ${r=t,`\n    ivec3 inputCoordsFromReshapedOutCoords(int index) {\n      ${Gr(["r","c","d"],r)}\n      return ivec3(r, c, d);\n    }\n  `}\n      ${Hr(e)}\n\n      void main() {\n        ivec3 rc = getOutputCoords();\n\n        vec4 result = vec4(0.);\n\n        ivec3 thisRC;\n        int rows = ${e[1]};\n        int cols = ${e[2]};\n\n        ${n}\n\n        setOutput(result);\n      }\n    `}}class Co{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(e,t,n){const r=Eo(t,n),a=$o(e,r,n);a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]);const s=To(e,r,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=s,this.log();const e=this.freeTextures[a].shift();return this.usedTextures[a].push(e),e}let o;return r===hr.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):r===hr.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):r===hr.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===hr.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===hr.PACKED_4X1_UNSIGNED_BYTE&&(o=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[a].push(o),this.numUsedTextures++,this._numBytesAllocated+=s,this.log(),o}releaseTexture(e,t,n,r){if(null==this.freeTextures)return;const a=Eo(n,r),s=$o(t,a,r);s in this.freeTextures||(this.freeTextures[s]=[]);const o=To(t,a,this.gpgpu.gl,this.gpgpu.textureConfig,r),i=W().get("WEBGL_DELETE_TEXTURE_THRESHOLD");-1!==i&&this._numBytesAllocated>i?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=o):(this.freeTextures[s].push(e),this.numFreeTextures++,this._numBytesFree+=o),this.numUsedTextures--;const u=this.usedTextures[s],l=u.indexOf(e);if(l<0)throw new Error("Cannot release a texture that was never provided by this texture manager");u.splice(l,1),this.log()}log(){if(!this.logEnabled)return;const e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);const t=this._numBytesFree/this._numBytesAllocated;console.log("Bytes allocated: "+this._numBytesAllocated),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(null!=this.freeTextures){for(const e in this.freeTextures)this.freeTextures[e].forEach(e=>{this.gpgpu.deleteMatrixTexture(e)});for(const e in this.usedTextures)this.usedTextures[e].forEach(e=>{this.gpgpu.deleteMatrixTexture(e)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}}function To(e,t,n,r,a){const s=function(e,t){switch(e){case hr.PACKED_2X2_FLOAT32:return oa(t);case hr.PACKED_2X2_FLOAT16:return ia(t);case hr.UNPACKED_FLOAT32:return ra(t);case hr.UNPACKED_FLOAT16:return aa(t);case hr.PACKED_4X1_UNSIGNED_BYTE:return sa(t);default:throw new Error("Unknown physical texture type "+e)}}(t,r);let o;if(a){const[t,n]=gr(e[0],e[1]);o=t*n}else{const[t,n]=fr(e[0],e[1]);o=t*n}return o*function(e,t){const n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;throw new Error("Unknown internal format "+t)}(n,s)}function Eo(e,t){if(e===pr.UPLOAD)return hr.PACKED_2X2_FLOAT32;if(e===pr.RENDER||null==e)return function(e){return W().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?hr.PACKED_2X2_FLOAT32:hr.UNPACKED_FLOAT32:e?hr.PACKED_2X2_FLOAT16:hr.UNPACKED_FLOAT16}(t);if(e===pr.DOWNLOAD||e===pr.PIXELS)return hr.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+e)}function $o(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class _o{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.userCode=`\n      float unaryOperation(float x) {\n        ${t}\n      }\n\n      void main() {\n        float x = getAAtOutCoords();\n        float y = unaryOperation(x);\n\n        setOutput(y);\n      }\n    `}}const Ao="return abs(x);",Ro="return x;";class Mo{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode=`\n      vec4 unaryOperation(vec4 x) {\n        ${t}\n      }\n\n      void main() {\n        vec4 x = getAAtOutCoords();\n        vec4 y = unaryOperation(x);\n\n        setOutput(y);\n      }\n    `}}class Fo{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;const t=e.length,n=Io("rc",t),r=wa(t),a=function(e,t){if(1===e)return"rc";let n="";for(let r=0;r<e;r++)n+=t[r],r<e-1&&(n+=",");return n}(t,n),s=n.slice(-2),o=t<=1?"rc":`vec2(${s.join(",")})`;this.userCode=`\n      void main() {\n        ${r} rc = getOutputCoords();\n        vec4 packedInput = getA(${a});\n\n        setOutput(getChannel(packedInput, ${o}));\n      }\n    `}}const Do=Cn,Oo={};class Po extends o{constructor(e){if(super(),this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.warnedAboutCPUBackend=!1,this.pendingDeletes=0,this.disposed=!1,!W().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(null==e){const e=cr(W().getNumber("WEBGL_VERSION"));this.binaryCache=((t=W().getNumber("WEBGL_VERSION"))in Oo||(Oo[t]={}),Oo[t]),this.gpgpu=new la(e),this.canvas=e.canvas,this.gpgpuCreatedLocally=!0}else this.gpgpu=e,this.binaryCache={},this.gpgpuCreatedLocally=!1,this.canvas=e.gl.canvas;var t;this.textureManager=new Co(this.gpgpu),this.numMBBeforeWarning=null==W().global.screen?1024:W().global.screen.height*W().global.screen.width*window.devicePixelRatio*600/1024/1024,this.texData=new s(this,Rt())}nextDataId(){return Po.nextDataId++}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(e,t,n){if((W().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||W().getBool("DEBUG"))&&this.checkNumericalProblems(e),"complex64"===n&&null!=e)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const r={id:this.nextDataId()};return this.texData.set(r,{shape:t,dtype:n,values:e,usage:pr.UPLOAD,refCount:1}),r}refCount(e){if(this.texData.has(e)){return this.texData.get(e).refCount}return 0}incRef(e){this.texData.get(e).refCount++}decRef(e){if(this.texData.has(e)){this.texData.get(e).refCount--}}move(e,t,n,r,a){if(W().getBool("DEBUG")&&this.checkNumericalProblems(t),"complex64"===r)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:r,values:t,usage:pr.UPLOAD,refCount:a})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){const t=this.texData.get(e),{values:n,dtype:r,complexTensorInfos:a,slice:s,shape:o,isPacked:i}=t;if(null!=s){let t;t=i?new Mo(o,Ro):new _o(o,Ro);const n=this.runWebGLProgram(t,[{dataId:e,shape:o,dtype:r}],r),a=this.readSync(n.dataId);return this.disposeIntermediateTensorInfo(n),a}if(null!=n)return this.convertAndCacheOnCPU(e);if("string"===r)return n;const u=null!=this.activeTimers;let l,c;if(u&&(l=ee()),"complex64"===r){c=jn(this.readSync(a.real.dataId),this.readSync(a.imag.dataId))}else c=this.getValuesFromTexture(e);return u&&(this.downloadWaitMs+=ee()-l),this.convertAndCacheOnCPU(e,c)}async read(e){if(this.pendingRead.has(e)){const t=this.pendingRead.get(e);return new Promise(e=>t.push(e))}const t=this.texData.get(e),{values:n,shape:r,slice:a,dtype:s,complexTensorInfos:o,isPacked:i}=t;if(null!=a){let t;t=i?new Mo(r,Ro):new _o(r,Ro);const n=this.runWebGLProgram(t,[{dataId:e,shape:r,dtype:s}],s),a=this.read(n.dataId);return this.disposeIntermediateTensorInfo(n),a}if(null!=n)return this.convertAndCacheOnCPU(e);if(!W().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===W().getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let u,l,c=null;if("complex64"!==s&&W().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(e);const t=this.texData.get(u.dataId);c=this.gpgpu.createBufferFromTexture(t.texture,...mr(r))}if(this.pendingRead.set(e,[]),"complex64"!==s&&await this.gpgpu.createAndWaitForFence(),"complex64"===s){const e=await Promise.all([this.read(o.real.dataId),this.read(o.imag.dataId)]);l=jn(e[0],e[1])}else if(null==c)l=this.getValuesFromTexture(e);else{const e=h(r);l=this.gpgpu.downloadFloat32MatrixFromBuffer(c,e)}null!=u&&this.disposeIntermediateTensorInfo(u);const d=this.convertAndCacheOnCPU(e,l),p=this.pendingRead.get(e);return this.pendingRead.delete(e),p.forEach(e=>e(d)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&Rt().removeDataId(e,this),this.pendingDeletes--),d}bufferSync(e){const t=this.readSync(e.dataId);let n=t;if("string"===e.dtype)try{n=t.map(e=>ne(e))}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return lt(e.shape,e.dtype,n)}checkNumericalProblems(e){if(null!=e)for(let t=0;t<e.length;t++){const n=e[t];if(!xr(n)){if(W().getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))throw Error(`The value ${n} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`);throw Error(`The value ${n} cannot be represented on this device.`)}}}getValuesFromTexture(e){const{shape:t,dtype:n,isPacked:r}=this.texData.get(e),a=h(t);if(W().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){const n=this.decode(e),r=this.texData.get(n.dataId),s=this.gpgpu.downloadMatrixFromPackedTexture(r.texture,...mr(t)).subarray(0,a);return this.disposeIntermediateTensorInfo(n),s}const s=W().getBool("WEBGL_PACK")&&!0===r,o=s?Rr(t):t,i=s?new Yr(o):new Xr(o),u=this.runWebGLProgram(i,[{shape:o,dtype:n,dataId:e}],"float32"),l=this.texData.get(u.dataId),c=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(l.texture,l.texShape[0],l.texShape[1]).subarray(0,a);return this.disposeIntermediateTensorInfo(u),c}timerAvailable(){return W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}async time(e){const t=this.activeTimers,n=[];let r=!1;null==this.programTimersStack?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,e();const a=p(this.activeTimers.map(e=>e.query)).filter(e=>null!=e),s=p(this.activeTimers.map(e=>e.name)).filter(e=>null!=e);this.activeTimers=t,r&&(this.programTimersStack=null);const o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};if(W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const e=await Promise.all(a);o.kernelMs=function(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}(e),o.getExtraProfileInfo=()=>e.map((e,t)=>({name:s[t],ms:e})).map(e=>`${e.name}: ${e.ms}`).join(", ")}else o.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,o}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:ee(),endMs:null}}endTimer(e){return W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=ee(),e)}async getQueryTime(e){if(W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);const t=e;return t.endMs-t.startMs}disposeData(e,t=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(t?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!t&&this.texData.get(e).refCount>0)return!1;if(this.pendingRead.has(e))return this.pendingDisposal.add(e),this.pendingDeletes++,!1;this.releaseGPUData(e);const{complexTensorInfos:n}=this.texData.get(e);return null!=n&&(this.disposeData(n.real.dataId,t),this.disposeData(n.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){const{texture:t,dtype:n,texShape:r,usage:a,isPacked:s,slice:o}=this.texData.get(e),i=o&&o.origDataId||e,u=this.dataRefCount.get(i);u>1?this.dataRefCount.set(i,u-1):(this.dataRefCount.delete(i),null!=t&&(this.numBytesInGPU-=this.computeBytes(r,n),this.textureManager.releaseTexture(t,r,a,s)));const l=this.texData.get(e);l.texture=null,l.texShape=null,l.isPacked=!1,l.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture}getDataInfo(e){return this.texData.get(e)}getCPUBackend(){return W().getBool("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=Rt().findBackend("cpu")),this.cpuBackend):null}shouldExecuteOnCPU(e,t=128){const n=this.getCPUBackend();return W().getBool("IS_TEST")||this.warnedAboutCPUBackend||null!=n||(console.warn("Your application contains ops that are small enough to be executed on the CPU backend, however the CPU backend cannot be found. Consider importing the CPU backend (@tensorflow/tfjs-backend-cpu) for better performance."),this.warnedAboutCPUBackend=!0),null!=n&&e.every(e=>null==this.texData.get(e.dataId).texture&&h(e.shape)<t)}getGPGPUContext(){return this.gpgpu}where(e){Hn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");const t=e.dataSync();return Do(e.shape,t)}packedUnaryOp(e,t,n){const r=new Mo(e.shape,t),a=this.compileAndRun(r,[e],n);return Rt().makeTensorFromDataId(a.dataId,a.shape,a.dtype)}abs(e){if(this.shouldExecuteOnCPU([e])&&"complex64"!==e.dtype){const t=fo(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,t)}if(W().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Ao,e.dtype);const t=new _o(e.shape,Ao),n=this.compileAndRun(t,[e]);return Rt().makeTensorFromDataId(n.dataId,n.shape,n.dtype)}makeTensorInfo(e,t,n){let r;if("string"===t&&null!=n&&n.length>0&&T(n[0])){const a=n.map(e=>te(e));r=this.write(a,e,t)}else r=this.write(n,e,t);return this.texData.get(r).usage=null,{dataId:r,shape:e,dtype:t}}makeOutput(e,t,n){const{dataId:r}=this.makeTensorInfo(e,t,n);return Rt().makeTensorFromDataId(r,e,t,this)}unpackTensor(e){const t=new Fo(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new No(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)}packedReshape(e,t){const n=[_r(e.shape),...Ar(e.shape)],r={dtype:e.dtype,shape:n,dataId:e.dataId},a=[_r(t),...Ar(t)],s=new So(a,n),o=this.runWebGLProgram(s,[r],e.dtype,null,!0);return{dataId:o.dataId,shape:t,dtype:o.dtype}}decode(e){const t=this.texData.get(e),{isPacked:n,shape:r,dtype:a}=t,s=Rr(r);let o;o=n?new Kr(s):new qr(s);return{dtype:a,shape:r,dataId:this.runWebGLProgram(o,[{shape:s,dtype:a,dataId:e}],a,null,!0).dataId}}runWebGLProgram(e,t,n,r,a=!1){const s=this.makeTensorInfo(e.outputShape,n),o=this.texData.get(s.dataId);if(e.packedOutput&&(o.isPacked=!0),e.outPackingScheme===dr.DENSE){const t=mr(e.outputShape);o.texShape=t.map(e=>2*e)}if(null!=e.outTexUsage&&(o.usage=e.outTexUsage),0===h(s.shape))return o.values=v(s.dtype,0),s;const i=[],u=t.map(t=>{if("complex64"===t.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let n=this.texData.get(t.dataId);if(null==n.texture){if(!e.packedInputs&&h(t.shape)<=W().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:t.shape,texData:null,isUniform:!0,uniformValues:n.values};e.packedInputs&&(n.isPacked=!0,n.shape=t.shape)}else if(!!n.isPacked!=!!e.packedInputs)t=n.isPacked?this.unpackTensor(t):this.packTensor(t),i.push(t),n=this.texData.get(t.dataId);else if(n.isPacked&&!Fr(n.shape,t.shape)){const e=t,r=t.shape;t.shape=n.shape,t=this.packedReshape(t,r),i.push(t),n=this.texData.get(t.dataId),e.shape=r}return this.uploadToGPU(t.dataId),{shape:t.shape,texData:n,isUniform:!1}});this.uploadToGPU(s.dataId);const l={shape:s.shape,texData:o,isUniform:!1},c=function(e,t,n){let r="";t.concat(n).forEach(e=>{const t=null!=e.texData&&null!=e.texData.slice&&e.texData.slice.flatOffset>0,n=e.isUniform?"uniform":e.texData.texShape;r+=`${e.shape}_${n}_${t}`});const a=e.userCode;let s=e.constructor.name;return s+="_"+r+"_"+a,s}(e,u,l),d=this.getAndSaveBinary(c,()=>function(e,t,n,r){const a=t.userCode,s=n.map((e,n)=>{const r={logicalShape:e.shape,texShape:e.isUniform?null:e.texData.texShape,isUniform:e.isUniform,isPacked:!e.isUniform&&e.texData.isPacked,flatOffset:null};return null!=e.texData&&null!=e.texData.slice&&e.texData.slice.flatOffset>0&&(r.flatOffset=e.texData.slice.flatOffset),{name:t.variableNames[n],shapeInfo:r}}),o=s.map(e=>e.shapeInfo),i={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},u=da(s,i,a,t.packedInputs),l=e.createProgram(u);let c=null;const d=e.getUniformLocation(l,"NAN",!1);1===W().getNumber("WEBGL_VERSION")&&(c=e.getUniformLocation(l,"INFINITY",!1));const p={};for(let n=0;n<t.variableNames.length;n++){const r=t.variableNames[n],a=!1;p[r]=e.getUniformLocation(l,r,a),p["offset"+r]=e.getUniformLocation(l,"offset"+r,a)}return{program:t,source:u,webGLProgram:l,uniformLocations:p,inShapeInfos:o,outShapeInfo:i,infLoc:c,nanLoc:d}}(this.gpgpu,e,u,l)),p=null!=this.activeTimers;let f;p&&(f=this.startTimer()),function(e,t,n,r,a){Na(t.inShapeInfos,n),Na([t.outShapeInfo],[r]);const s=r.texData.texture,o=r.texData.texShape;r.texData.isPacked?e.setOutputPackedMatrixTexture(s,o[0],o[1]):e.setOutputMatrixTexture(s,o[0],o[1]),e.setProgram(t.webGLProgram),1===W().getNumber("WEBGL_VERSION")&&null!==t.infLoc&&e.gl.uniform1f(t.infLoc,1/0),null!==t.nanLoc&&e.gl.uniform1f(t.nanLoc,NaN),n.forEach((n,r)=>{const a=t.program.variableNames[r],s=t.uniformLocations[a],o=t.uniformLocations["offset"+a];if(null!=s)if(n.isUniform)if(h(n.shape)<2)e.gl.uniform1f(s,n.uniformValues[0]);else{let t=n.uniformValues;t instanceof Float32Array||(t=new Float32Array(t)),e.gl.uniform1fv(s,t)}else null!=n.texData.slice&&null!=o&&e.gl.uniform1i(o,n.texData.slice.flatOffset),e.setInputMatrixTexture(n.texData.texture,s,r)}),null!=a&&a(e,t.webGLProgram),e.executeProgram()}(this.gpgpu,d,u,l,r),i.forEach(e=>this.disposeIntermediateTensorInfo(e)),p&&(f=this.endTimer(f),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(f)}));const m=W().get("WEBGL_FLUSH_THRESHOLD");if(m>0){const e=ee();e-this.lastGlFlushTime>m&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=e)}if(!W().getBool("WEBGL_LAZILY_UNPACK")&&o.isPacked&&!1===a){const e=this.unpackTensor(s);return this.disposeIntermediateTensorInfo(s),e}return s}compileAndRun(e,t,n,r,a=!1){n=n||t[0].dtype;return this.runWebGLProgram(e,t,n,r,a)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){if(!this.disposed){if(!W().getBool("IS_TEST")){Object.keys(this.binaryCache).forEach(e=>{this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram),delete this.binaryCache[e]})}this.textureManager.dispose(),null!=this.canvas&&"undefined"!=typeof HTMLCanvasElement&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0}}floatPrecision(){var e,t;return null==this.floatPrecisionValue&&(this.floatPrecisionValue=(e=()=>{if(!W().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=W().getBool("DEBUG");W().set("DEBUG",!1);const t=this.abs(Nn(1e-8)).dataSync()[0];if(W().set("DEBUG",e),t>0)return 32}return 16},Ee.tidy(e,t))),this.floatPrecisionValue}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}uploadToGPU(e){const t=this.texData.get(e),{shape:n,dtype:r,values:a,texture:s,usage:o,isPacked:i}=t;if(null!=s)return;const u=null!=this.activeTimers;let c;u&&(c=ee());let d=t.texShape;if(null==d&&(d=function(e,t=!1){let n=W().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(n*=2,1===(e=e.map((t,n)=>n>=e.length-2?l(e[n]):e[n])).length&&(e=[2,e[0]])),2!==e.length){const t=w(e);e=t.newShape}let r=h(e);if(e.length<=1&&r<=n)return[1,r];if(2===e.length&&e[0]<=n&&e[1]<=n)return e;if(3===e.length&&e[0]*e[1]<=n&&e[2]<=n)return[e[0]*e[1],e[2]];if(3===e.length&&e[0]<=n&&e[1]*e[2]<=n)return[e[0],e[1]*e[2]];if(4===e.length&&e[0]*e[1]*e[2]<=n&&e[3]<=n)return[e[0]*e[1]*e[2],e[3]];if(4===e.length&&e[0]<=n&&e[1]*e[2]*e[3]<=n)return[e[0],e[1]*e[2]*e[3]];if(t){const t=_r(e);let n=2,a=2;return e.length&&([n,a]=Ar(e)),r=t*(n/2)*(a/2),g(r).map(e=>2*e)}return g(r)}(n,i),t.texShape=d),null!=a){const e=Rr(n);let s,o=d[1],l=d[0];const p=a instanceof Uint8Array;i?([o,l]=gr(d[0],d[1]),s=new Jr(e,[l,o],p)):s=new Qr(e,[l,o],p);const h=this.makeTensorInfo([l,o],r);this.texData.get(h.dataId).usage=p?pr.PIXELS:pr.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(h.dataId),o,l,a);const f=!0,m=this.runWebGLProgram(s,[h],r,null,f),g=this.texData.get(m.dataId);t.texture=g.texture,t.texShape=g.texShape,t.isPacked=g.isPacked,t.usage=g.usage,this.disposeIntermediateTensorInfo(h),this.texData.delete(m.dataId),t.values=null,u&&(this.uploadWaitMs+=ee()-c)}else{const e=this.acquireTexture(d,o,r,i);t.texture=e}}convertAndCacheOnCPU(e,t){const n=this.texData.get(e),{dtype:r}=n;return this.releaseGPUData(e),null!=t&&(n.values=function(e,t){if("float32"===t||"complex64"===t)return e;if("int32"===t||"bool"===t){const n="int32"===t?new Int32Array(e.length):new Uint8Array(e.length);for(let t=0;t<n.length;++t)n[t]=Math.round(e[t]);return n}throw new Error("Unknown dtype "+t)}(t,r)),n.values}acquireTexture(e,t,n,r){if(this.numBytesInGPU+=this.computeBytes(e,n),!this.warnedAboutMemory&&this.numBytesInGPU>1024*this.numMBBeforeWarning*1024){const e=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${e} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,r)}computeBytes(e,t){return e[0]*e[1]*C(t)}}Po.nextDataId=0,Ae()&&Ft("webgl",()=>new Po,2);class Lo{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=Jt(t,n),this.userCode=`\n      float binaryOperation(float a, float b) {\n        ${e}\n      }\n\n      void main() {\n        float a = getAAtOutCoords();\n        float b = getBAtOutCoords();\n        setOutput(binaryOperation(a, b));\n      }\n    `}}class Bo{constructor(e,t,n,r=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=Jt(t,n);const a=this.outputShape.length;let s="";if(r)if(0===a||1===h(this.outputShape))s="\n          result.y = 0.;\n          result.z = 0.;\n          result.w = 0.;\n        ";else{if(s=`\n          ${wa(a)} coords = getOutputCoords();\n        `,1===a)s+=`\n            result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;\n            result.z = 0.;\n            result.w = 0.;\n          `;else{const e=Io("coords",a);s+=`\n            bool nextRowOutOfBounds =\n              (${e[a-2]} + 1) >= ${this.outputShape[a-2]};\n            bool nextColOutOfBounds =\n              (${e[a-1]} + 1) >= ${this.outputShape[a-1]};\n            result.y = nextColOutOfBounds ? 0. : result.y;\n            result.z = nextRowOutOfBounds ? 0. : result.z;\n            result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n          `}}this.userCode=`\n      vec4 binaryOperation(vec4 a, vec4 b) {\n        ${e}\n      }\n\n      void main() {\n        vec4 a = getAAtOutCoords();\n        vec4 b = getBAtOutCoords();\n\n        vec4 result = binaryOperation(a, b);\n        ${s}\n\n        setOutput(result);\n      }\n    `}}function Wo(e){const{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}const zo={kernelName:"Identity",backendName:"webgl",kernelFunc:Wo};function Vo(e){const{inputs:t,backend:n}=e,{real:r,imag:a}=t,s=n.makeTensorInfo(r.shape,"complex64"),o=n.texData.get(s.dataId),i=Wo({inputs:{x:r},backend:n}),u=Wo({inputs:{x:a},backend:n});return o.complexTensorInfos={real:i,imag:u},s}const Uo={kernelName:"Complex",backendName:"webgl",kernelFunc:Vo},Go="return (a < 0.) ? b * a : a;",Ho="\n  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n";const jo={kernelName:"LeakyRelu",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{alpha:s}=r,o=n.makeTensorInfo([],"float32",J(s,"float32")),i=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bo(Ho,a.shape,o.shape):new Lo(Go,a.shape,o.shape),u=n.runWebGLProgram(i,[a,o],a.dtype);return n.disposeIntermediateTensorInfo(o),u}},qo="return (a < 0.) ? b * a : a;",Ko="\n  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n";const Xo={kernelName:"Prelu",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r,alpha:a}=t,s=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bo(Ko,r.shape,a.shape):new Lo(qo,r.shape,a.shape);return n.runWebGLProgram(s,[r,a],r.dtype)}};function Yo({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:r}){return({inputs:a,backend:s})=>{const{x:o}=a,i=s,u=r||o.dtype;if(i.shouldExecuteOnCPU([o])&&null!=n){const e=i.texData.get(o.dataId),t=n(e.values,u);return i.makeTensorInfo(o.shape,u,t)}let l;return l=W().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&null!=t?new Mo(o.shape,t):new _o(o.shape,e),i.runWebGLProgram(l,[o],u)}}function Qo({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:r=!1,cpuKernelImpl:a,dtype:s}){return({inputs:o,backend:i})=>{const{a:u,b:l}=o,c=i;if(r&&"complex64"===u.dtype){const t=c.texData.get(u.dataId),n=c.texData.get(l.dataId),[r,a]=[[t.complexTensorInfos.real,n.complexTensorInfos.real],[t.complexTensorInfos.imag,n.complexTensorInfos.imag]].map(t=>{const[n,r]=t,a={dataId:n.dataId,dtype:n.dtype,shape:u.shape},s={dataId:r.dataId,dtype:r.dtype,shape:l.shape},o=new Lo(e,u.shape,l.shape);return c.runWebGLProgram(o,[a,s],we(n.dtype,r.dtype))}),s=Vo({inputs:{real:r,imag:a},backend:c});return c.disposeIntermediateTensorInfo(r),c.disposeIntermediateTensorInfo(a),s}const d=s||we(u.dtype,l.dtype);if(c.shouldExecuteOnCPU([u,l])&&null!=a){const e=c.texData.get(u.dataId),t=c.texData.get(l.dataId),[n,r]=a(u.shape,l.shape,e.values,t.values,d),s=c.makeTensorInfo(r,d);return c.texData.get(s.dataId).values=n,s}let p;return p=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&null!=t?new Bo(t,u.shape,l.shape,n):new Lo(e,u.shape,l.shape),c.runWebGLProgram(p,[u,l],d)}}function Jo(e,t=!1){if("linear"===e)return"return x;";if("relu"===e)return t?"\n  vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n  bvec4 isNaN = isnan(x);\n\n  result.r = isNaN.r ? x.r : result.r;\n  result.g = isNaN.g ? x.g : result.g;\n  result.b = isNaN.b ? x.b : result.b;\n  result.a = isNaN.a ? x.a : result.a;\n\n  return result;\n":"if (isnan(x)) return x;\n  return (x < 0.0) ? 0.0 : x;\n";if("elu"===e)return t?"\n  vec4 result;\n\n  result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n  result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n  result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n  result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n  return result;\n":"return (x >= 0.0) ? x : (exp(x) - 1.0);";if("relu6"===e)return t?"\n  vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n  bvec4 isNaN = isnan(x);\n\n  result.r = isNaN.r ? x.r : result.r;\n  result.g = isNaN.g ? x.g : result.g;\n  result.b = isNaN.b ? x.b : result.b;\n  result.a = isNaN.a ? x.a : result.a;\n\n  return result;\n":"if (isnan(x)) return x;\n  return (x < 0.0) ? 0.0 : min(6.0, x);\n";if("prelu"===e)return t?Ko:qo;if("leakyrelu"===e)return t?Ho:Go;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}class Zo{constructor(e,t,n,r=!1,a=!1,s=!1,o=null,i=!1,u=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n;const l=r?e[1]:e[2],c=Math.ceil(l/2),d=r?"i * 2, rc.y":"rc.y, i * 2",p=a?"rc.z, i * 2":"i * 2, rc.z",h=r?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=a?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let m="",g="";o&&(m=i?`vec4 activation(vec4 a) {\n          vec4 b = getPreluActivationWeightsAtOutCoords();\n          ${o}\n        }`:u?`vec4 activation(vec4 a) {\n          vec4 b = getLeakyreluAlphaAtOutCoords();\n          ${o}\n        }`:`vec4 activation(vec4 x) {\n          ${o}\n        }`,g="result = activation(result);");const y=s?"result += getBiasAtOutCoords();":"";s&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),u&&this.variableNames.push("leakyreluAlpha");let b="rc.x",x="rc.x";e[0]<t[0]?b=`int(min(float(rc.x), ${e[0]-1}.))`:t[0]<e[0]&&(x=`int(min(float(rc.x), ${t[0]-1}.))`),this.userCode=`\n      ${m}\n\n      const float sharedDimension = ${c}.0;\n\n      vec4 dot2x2ARowBCol(ivec3 rc) {\n        vec4 result = vec4(0);\n        for (int i = 0; i < ${c}; i++) {\n          int batchA = ${b};\n          int batchB = ${x};\n          vec4 a = getMatrixA(batchA, ${d});\n          vec4 b = getMatrixB(batchB, ${p});\n\n          // These swizzled products need to be separately added.\n          // See: https://github.com/tensorflow/tfjs/issues/1735\n          result += (${h[0]} * ${f[0]});\n          result += (${h[1]} * ${f[1]});\n        }\n        return result;\n      }\n\n      void main() {\n        ivec3 rc = getOutputCoords();\n        vec4 result = dot2x2ARowBCol(rc);\n\n        ${y}\n\n        ${g}\n\n        setOutput(result);\n      }\n    `}}const ei="return areal * breal - aimag * bimag;",ti="return areal * bimag + aimag * breal;";class ni{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=Jt(t,n),this.userCode=`\n      float binaryOpComplex(\n          float areal, float aimag, float breal, float bimag) {\n        ${e}\n      }\n\n      void main() {\n        float areal = getARealAtOutCoords();\n        float aimag = getAImagAtOutCoords();\n        float breal = getBRealAtOutCoords();\n        float bimag = getBImagAtOutCoords();\n        setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n      }\n    `}}const ri="return a * b;";function ai(e){const{inputs:t,backend:n}=e,{a:r,b:a}=t,s=we(r.dtype,a.dtype);if("complex64"===r.dtype){const e=n.texData.get(r.dataId),t=n.texData.get(a.dataId),s=new ni(ei,r.shape,a.shape),o=new ni(ti,r.shape,a.shape),i=[{dataId:e.complexTensorInfos.real.dataId,dtype:e.complexTensorInfos.real.dtype,shape:r.shape},{dataId:e.complexTensorInfos.imag.dataId,dtype:e.complexTensorInfos.imag.dtype,shape:r.shape},{dataId:t.complexTensorInfos.real.dataId,dtype:t.complexTensorInfos.real.dtype,shape:a.shape},{dataId:t.complexTensorInfos.imag.dataId,dtype:t.complexTensorInfos.imag.dtype,shape:a.shape}],u=n.runWebGLProgram(s,i,"float32"),l=n.runWebGLProgram(o,i,"float32"),c=Vo({inputs:{real:u,imag:l},backend:n});return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(l),c}if(n.shouldExecuteOnCPU([r,a])){const e=n.texData.get(r.dataId),t=n.texData.get(a.dataId),[o,i]=uo(r.shape,a.shape,e.values,t.values,s),u=n.makeTensorInfo(i,s);return n.texData.get(u.dataId).values=o,u}let o;return o=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bo(ri,r.shape,a.shape):new Lo(ri,r.shape,a.shape),n.runWebGLProgram(o,[r,a],s)}const si={kernelName:"Multiply",backendName:"webgl",kernelFunc:ai};function oi(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{shape:s}=r,o=n,i=h(a.shape),u=x(s,i),l=h(u);c(i===l,()=>`The new shape (${u}) has ${l} elements and the old shape (${a.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`);const d=o.texData.get(a.dataId);return!d.isPacked||Fr(a.shape,u)||null!==d.texture&&Fr(d.shape,u)?(o.incRef(a.dataId),{dataId:a.dataId,shape:u,dtype:a.dtype}):function(e,t,n){const r=[_r(e.shape),...Ar(e.shape)],a={dtype:e.dtype,shape:r,dataId:e.dataId},s=[_r(t),...Ar(t)],o=new So(s,r),i=n.runWebGLProgram(o,[a],e.dtype,null,!0);return{dataId:i.dataId,shape:t,dtype:i.dtype}}(a,u,o)}const ii={kernelName:"Reshape",backendName:"webgl",kernelFunc:oi};class ui{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:r,inSize:a,outSize:s}=e;this.outputShape=[r,s];const o=4*Math.floor(n/4),i=n%4;let u="sumValue += dot(values, ones);";if(null!=t){const e=1/t;u=`sumValue += dot(values * ${m(e)?e.toPrecision(2):e}, ones);`}let l="";a%n>0&&(l=`\n        if (inIdx < 0 || inIdx >= ${a}) {\n          return 0.0;\n        }\n      `),this.userCode=`\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n      float getValue(int batch, int inIdx) {\n        ${l}\n        return getX(batch, inIdx);\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n        int outIdx = coords[1];\n        int inOffset = outIdx * ${n};\n\n        float sumValue = 0.0;\n\n        for (int i = 0; i < ${o}; i += 4) {\n          int inIdx = inOffset + i;\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            getValue(batch, inIdx + 3)\n          );\n\n          ${u}\n        }\n\n        int inIdx = inOffset + ${o};\n        if (${1===i}) {\n          vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);\n\n          ${u}\n        } else if (${2===i}) {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1), 0.0, 0.0);\n\n          ${u}\n        } else if (${3===i}) {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2), 0.0);\n\n          ${u}\n        }\n        setOutput(sumValue);\n      }\n    `}}class li{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:r,inSize:a,outSize:s}=e;this.outputShape=[r,s];let o="0.0",i="";"prod"===t?o="1.0":"min"===t?(o="1.0 / 1e-20",i="min"):"max"===t&&(o="-1.0 / 1e-20",i="max");let u=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"sum"===t?u="sumValue":"prod"===t?u="prodValue":"all"===t?u="allValue":"any"===t&&(u="anyValue");const l=4*Math.floor(n/4),c=n%4;let d=`\n      if (${"sum"===t}) {\n        sumValue += dot(values, ones);\n      } else if (${"prod"===t}) {\n        vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n        prodValue *= tmp[0] * tmp[1];\n      } else {\n        minMaxValue = ${i}(values, minMaxValue);\n      }\n    `,p="vec4";"all"===t?(o="1.0",d="\n        bool reducedAllValue = all(values);\n        float floatedReducedAllValue = float(reducedAllValue);\n        allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n      ",p="bvec4"):"any"===t&&(o="0.0",d="\n        bool reducedAnyValue = any(values);\n        float floatedReducedAnyValue = float(reducedAnyValue);\n        anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n      ",p="bvec4");let h="";a%n>0&&(h=`\n        if (inIdx < 0 || inIdx >= ${a}) {\n          return initializationValue;\n        }\n      `),this.userCode=`\n      const float initializationValue = ${o};\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n      float getValue(int batch, int inIdx) {\n        ${h}\n        return getX(batch, inIdx);\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n        int outIdx = coords[1];\n        int inOffset = outIdx * ${n};\n\n        vec4 minMaxValue = vec4(${o});\n        float prodValue = 1.0;\n        float sumValue = 0.0;\n        float allValue = 1.0;\n        float anyValue = 0.0;\n\n        for (int i = 0; i < ${l}; i += 4) {\n          int inIdx = inOffset + i;\n          ${p} values = ${p}(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            getValue(batch, inIdx + 3)\n          );\n\n          ${d}\n        }\n\n        int inIdx = inOffset + ${l};\n        if (${1===c}) {\n          ${p} values = ${p}(\n            getValue(batch, inIdx),\n            initializationValue,\n            initializationValue,\n            initializationValue\n          );\n\n          ${d}\n        } else if (${2===c}) {\n          ${p} values = ${p}(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            initializationValue,\n            initializationValue\n          );\n\n          ${d}\n        } else if (${3===c}) {\n          ${p} values = ${p}(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            initializationValue\n          );\n\n          ${d}\n        }\n        setOutput(${u});\n      }\n    `}}function ci(e,t,n,r){const a=function(e){const t=[];for(;0===t.length||1!==t[t.length-1].outSize;){const n=t.length?t[t.length-1].outSize:e[1],r=Ln(n);t.push({inSize:n,windowSize:r,outSize:Math.ceil(n/r)})}return t}(e.shape);let s=e;for(let o=0;o<a.length;o++){const{inSize:i,windowSize:u,outSize:l}=a[o];let c,d;c="mean"===n?0===o?new ui({windowSize:u,inSize:i,batchSize:e.shape[0],outSize:l},i):new ui({windowSize:u,inSize:i,batchSize:e.shape[0],outSize:l}):new li({windowSize:u,inSize:i,batchSize:e.shape[0],outSize:l},n),d=s,s=r.runWebGLProgram(c,[s],t),d.dataId!==e.dataId&&r.disposeIntermediateTensorInfo(d)}return s}class di{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e[t[r]];this.outputShape=n,this.rank=n.length;const r=wa(this.rank),a=function(e){const t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(t);for(let t=0;t<e.length;t++)r[e[t]]=n[t];return r.join()}(t);this.userCode=`\n    void main() {\n      ${r} resRC = getOutputCoords();\n      setOutput(getA(${a}));\n    }\n    `}}class pi{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;const n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e[t[r]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const r=wa(this.rank),a=vo("rc",this.rank),s=new Array(this.rank);for(let e=0;e<t.length;e++)s[t[e]]=a[e];const o=`vec2(${s.slice(-2).join()})`,i=`++${a[this.rank-1]} < ${n[this.rank-1]}`,u=`getChannel(getA(${s.join()}), ${o})`;this.userCode=`\n    void main() {\n      ${r} rc = getOutputCoords();\n      vec4 result = vec4(0.);\n      result[0] = ${u};\n      if(${i}) {\n        result[1] = ${u};\n      }\n      --${a[this.rank-1]};\n      if(++${a[this.rank-2]} < ${n[this.rank-2]}) {\n        result[2] = ${u};\n        if(${i}) {\n          result[3] = ${u};\n        }\n      }\n      setOutput(result);\n    }\n    `}}function hi(e,t,n){const r=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new pi(e.shape,t):new di(e.shape,t);return n.runWebGLProgram(r,[e],e.dtype)}function fi(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r;return function(e,t,n,r){const a=t,s=e.shape.length,o=k(a,e.shape);let i=o;const u=un(i,s),l=null!=u;let c=e;l&&(c=hi(e,u,r),i=cn(i.length,s)),on("sum",i,s);const[d,p]=an(c.shape,i);let f=d;n&&(f=sn(d,o));const m=h(p),g=oi({inputs:{x:c},attrs:{shape:[h(e.shape)/m,m]},backend:r}),y=ci(g,ve(e.dtype),"sum",r),b=oi({inputs:{x:y},attrs:{shape:f},backend:r});return r.disposeIntermediateTensorInfo(g),r.disposeIntermediateTensorInfo(y),l&&r.disposeIntermediateTensorInfo(c),b}(a,s,o,n)}const mi={kernelName:"Sum",backendName:"webgl",kernelFunc:fi};function gi(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{perm:s}=r,o=n,i=a.shape.length,u=new Array(i);for(let e=0;e<u.length;e++)u[e]=a.shape[s[e]];let l;if(o.shouldExecuteOnCPU([a])){const e=o.texData.get(a.dataId).values,t=ko(e,a.shape,a.dtype,s,u);l=o.makeTensorInfo(u,a.dtype);o.texData.get(l.dataId).values=t}else l=hi(a,s,o);return l}const yi={kernelName:"Transpose",backendName:"webgl",kernelFunc:gi};function bi({a:e,b:t,transposeA:n,transposeB:r,backend:a,bias:s=null,preluActivationWeights:o=null,leakyreluAlpha:i=0,activation:u=null}){const l=e.shape.length,d=t.shape.length,p=n?e.shape[l-2]:e.shape[l-1],f=r?t.shape[d-1]:t.shape[d-2],m=n?e.shape[l-1]:e.shape[l-2],g=r?t.shape[d-2]:t.shape[d-1],y=e.shape.slice(0,-2),b=t.shape.slice(0,-2),x=h(y),k=h(b);c(l>=2&&d>=2&&(x===k||1===x||1===k),()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${y}) and (${b}).`);const w=(x>k?e.shape.slice(0,-2):t.shape.slice(0,-2)).concat([m,g]);c(p===f,()=>`Error in matMul: inner shapes (${p}) and (${f}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${r} must match.`);const v=n?[x,p,m]:[x,m,p],I=r?[k,g,f]:[k,f,g],N=oi({inputs:{x:e},backend:a,attrs:{shape:v}}),S=oi({inputs:{x:t},backend:a,attrs:{shape:I}}),C=[N,S],T=Math.max(x,k),E=n?N.shape[1]:N.shape[2],$=null!=s,_=null!=o,A="leakyrelu"===u,R=null!=u?Jo(u,!0):null;let M;if((1===m||1===g)&&E>1e3&&!1===($||_||A||null!=R)){let e=N,t=S;n&&(e=gi({inputs:{x:N},backend:a,attrs:{perm:[0,2,1]}}),C.push(e)),r&&(t=gi({inputs:{x:S},backend:a,attrs:{perm:[0,2,1]}}),C.push(t));const s=1===g;let o=e;1!==g&&(o=oi({inputs:{x:e},backend:a,attrs:{shape:[T,E,1]}}),C.push(o));const i=1===g?2:1;let u=t;s&&(u=oi({inputs:{x:t},backend:a,attrs:{shape:[T,1,E]}}),C.push(u));const l=ai({inputs:{a:o,b:u},backend:a});M=fi({inputs:{x:l},backend:a,attrs:{axis:i,keepDims:!0}}),C.push(l)}else{const u=we(e.dtype,t.dtype),l=new Zo(v,I,[T,m,g],n,r,$,R,_,A),c=[N,S];if(null!=s&&c.push(s),_&&c.push(o),A){const e=a.makeTensorInfo([],"float32",J(i,"float32"));c.push(e),C.push(e)}M=a.runWebGLProgram(l,c,u)}const F=oi({inputs:{x:M},backend:a,attrs:{shape:w}});C.push(M);for(const e of C)a.disposeIntermediateTensorInfo(e);return F}const xi={kernelName:"_FusedMatMul",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a:a,b:s,bias:o,preluActivationWeights:i}=t,{transposeA:u,transposeB:l,activation:c,leakyreluAlpha:d}=r;return bi({a:a,b:s,transposeA:u,transposeB:l,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:d,activation:c})}};const ki={kernelName:"Abs",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])&&"complex64"!==r.dtype){const e=n.texData.get(r.dataId),t=fo(e.values);return n.makeTensorInfo(r.shape,r.dtype,t)}let a;return a=W().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new Mo(r.shape,"return abs(x);"):new _o(r.shape,"return abs(x);"),n.runWebGLProgram(a,[r],r.dtype)}},wi={kernelName:"Acos",backendName:"webgl",kernelFunc:Yo({opSnippet:"if (isnan(x)) return x;\n  if (abs(x) > 1.) {\n    return NAN;\n  }\n  return acos(x);\n"})},vi={kernelName:"Acosh",backendName:"webgl",kernelFunc:Yo({opSnippet:"if (isnan(x)) return x;\n  if (x < 1.0) return NAN;\nreturn log(x + sqrt(x * x - 1.0));"})},Ii="return a + b;",Ni={kernelName:"Add",backendName:"webgl",kernelFunc:Qo({opSnippet:Ii,packedOpSnippet:Ii,supportsComplex:!0,cpuKernelImpl:js})};class Si{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((e,t)=>"T"+t);const n=[];this.variableNames.forEach(e=>{n.push(`float v${e} = get${e}AtOutCoords();`)});const r=this.variableNames.map(e=>"v"+e).join(" + ");this.userCode=`\n      void main() {\n        ${n.join("\n        ")}\n\n        float result = ${r};\n        setOutput(result);\n      }\n    `}}class Ci{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((e,t)=>"T"+t);const n=[];this.variableNames.forEach(e=>{n.push(`vec4 v${e} = get${e}AtOutCoords();`)});const r=this.variableNames.map(e=>"v"+e).join(" + ");this.userCode=`\n      void main() {\n        ${n.join("\n        ")}\n\n        vec4 result = ${r};\n        setOutput(result);\n      }\n    `}}const Ti={kernelName:"AddN",backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:r}=t,a=n;if(1===a.length)return Wo({inputs:{x:a[0]},backend:r});if(a.length>W().get("WEBGL_MAX_TEXTURES_IN_SHADER")){const t=Math.floor(a.length/2),n=e({inputs:a.slice(0,t),backend:r}),s=e({inputs:a.slice(t),backend:r});return e({inputs:[n,s],backend:r})}const s=a.map(e=>e.dtype).reduce((e,t)=>we(e,t)),o=a.map(e=>e.shape),i=W().getBool("WEBGL_PACK")?new Ci(a[0].shape,o):new Si(a[0].shape,o);return r.runWebGLProgram(i,a,s)}};const Ei={kernelName:"All",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r,i=a.shape.length,u=k(s,a.shape);let l=u;const c=un(l,i);let d=a;null!=c&&(d=gi({inputs:{x:a},backend:n,attrs:{perm:c}}),l=cn(l.length,i)),on("all",l,i);const[p,f]=an(d.shape,l),m=oi({inputs:{x:d},backend:n,attrs:{shape:[-1,h(f)]}}),g=ci(m,m.dtype,"all",n);let y;if(o){y=oi({inputs:{x:g},backend:n,attrs:{shape:sn(p,u)}})}else y=oi({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),null!=c&&n.disposeIntermediateTensorInfo(d),y}};const $i={kernelName:"Any",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r,i=a.shape.length,u=k(s,a.shape);let l=u;const c=un(l,i);let d=a;null!=c&&(d=gi({inputs:{x:a},backend:n,attrs:{perm:c}}),l=cn(l.length,i)),on("any",l,i);const[p,f]=an(d.shape,l),m=oi({inputs:{x:d},backend:n,attrs:{shape:[-1,h(f)]}}),g=ci(m,m.dtype,"any",n);let y;if(o){y=oi({inputs:{x:g},backend:n,attrs:{shape:sn(p,u)}})}else y=oi({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),null!=c&&n.disposeIntermediateTensorInfo(d),y}};class _i{constructor(e,t,n){this.variableNames=["A"];const{windowSize:r,batchSize:a,outSize:s}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[a,s];const o="max"===t?">":"<",i=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n        int outIdx = coords[1];\n        int inOffset = outIdx * ${r};\n\n        int bestIndex = inOffset;\n        float bestValue = getA(batch, bestIndex);\n\n        for (int i = 0; i < ${r}; i++) {\n          int inIdx = ${i};\n          float candidate = getA(batch, inIdx);\n          if (candidate ${o} bestValue) {\n            bestValue = candidate;\n            bestIndex = inIdx;\n          }\n        }\n        setOutput(float(bestIndex));\n      }\n    `}}class Ai{constructor(e,t,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,c(e.length>2,()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`);const a=e[e.length-1],s=Math.ceil(a/t);this.outputShape=e.slice(0,-1),s>1&&this.outputShape.push(s),r||this.variableNames.push("bestIndicesA");const o=this.outputShape,i=o.length,u=wa(i),l=Io("coords",i);let d,p;if(1===s){p=i+1;const e=wa(p);d=`\n        ${e} sourceLocR = ${e}(${l.join()}, 0);\n        ++${l[i-1]};\n        ${e} sourceLocG = ${e}(${l.join()}, 0);\n        ++${l[i-2]};\n        ${e} sourceLocA = ${e}(${l.join()}, 0);\n        --${l[i-1]};\n        ${e} sourceLocB = ${e}(${l.join()}, 0);\n        --${l[i-2]};`}else p=i,d=`\n        ${u} sourceLocR = coords;\n        ++${l[i-1]};\n        ${u} sourceLocG = coords;\n        ++${l[i-2]};\n        ${u} sourceLocA = coords;\n        --${l[i-1]};\n        ${u} sourceLocB = coords;\n        --${l[i-2]};`;const h=["x","y","z","w","u","v"].slice(0,p),f="."+h[p-1],m=h.map(e=>"int "+e),g=Io("sourceLocR",p-1).concat("inIdx.r"),y=Io("sourceLocG",p-1).concat("inIdx.g"),b=Io("sourceLocB",p-1).concat("inIdx.b"),x=Io("sourceLocA",p-1).concat("inIdx.a"),k="max"===n?"greaterThan":"lessThan",w=r?"":`\n          inIdx = round(vec4(getBestIndicesAChannel(${g.join()}),\n                             getBestIndicesAChannel(${y.join()}),\n                             getBestIndicesAChannel(${b.join()}),\n                             getBestIndicesAChannel(${x.join()})));`,v=`vec4(\n            getAChannel(${g.join()}),\n            hasNextCol ? getAChannel(${y.join()}) : 0.,\n            hasNextRow ? getAChannel(${b.join()}) : 0.,\n            hasNextRow && hasNextCol ? getAChannel(${x.join()}) : 0.)`,I=r?"":`\n      float getBestIndicesAChannel(${m.join()}) {\n        return getChannel(getBestIndicesA(${h.join()}),\n                                          vec2(${h.slice(-2).join()}));\n      }`;this.userCode=`\n      float getAChannel(${m.join()}) {\n        return getChannel(getA(${h.join()}),\n                               vec2(${h.slice(-2).join()}));\n      }\n      ${I}\n      void main() {\n        ${u} coords = getOutputCoords();\n        bool hasNextCol = ${l[i-1]} < ${o[i-1]-1};\n        bool hasNextRow = ${l[i-2]} < ${o[i-2]-1};\n        ${d}\n        ivec4 srcIdx = ivec4(sourceLocR${f}, sourceLocG${f},\n          sourceLocB${f}, sourceLocA${f}) * ${t};\n        ivec4 inIdx = srcIdx;\n        vec4 bestIndex = vec4(inIdx);\n        vec4 bestValue = ${v};\n\n        for (int i = 0; i < ${t}; i++) {\n          inIdx = srcIdx;\n          ${w}\n          vec4 candidate = ${v};\n          bvec4 nan = isnan(candidate);\n          bvec4 replace = bvec4(\n            vec4(${k}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n          bestValue = vec4(replace.x  ? candidate.x : bestValue.x,\n                           replace.y  ? candidate.y : bestValue.y,\n                           replace.z  ? candidate.z : bestValue.z,\n                           replace.w  ? candidate.w : bestValue.w);\n          bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n          srcIdx++;\n        }\n        setOutput(bestIndex);\n      }\n    `}}function Ri(e,t,n,r){const a=[n];if(on("arg"+r.charAt(0).toUpperCase()+r.slice(1),a,t.shape.length),!W().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){const n=[],[s,o]=an(t.shape,a),i=h(o),u=oi({inputs:{x:t},backend:e,attrs:{shape:[-1,i]}});n.push(u);const l=function e(t,n,r,a=null){let s=n.shape[0],o=n.shape[1];null!=a&&(s=a.shape[0],o=a.shape[1]);const i=Ln(o),u={windowSize:i,inSize:o,batchSize:s,outSize:Math.ceil(o/i)},l=new _i(u,r,null==a),c=[n];null!=a&&c.push(a);const d=t.runWebGLProgram(l,c,"int32");if(1===d.shape[1])return d;const p=e(t,n,r,d);return t.disposeIntermediateTensorInfo(d),p}(e,u,r);n.push(l);const c=oi({inputs:{x:l},backend:e,attrs:{shape:s}});return n.forEach(t=>e.disposeIntermediateTensorInfo(t)),c}return function e(t,n,r,a=null){const s=null!=a?a.shape:n.shape,o=Ln(s[s.length-1]),i=new Ai(s,o,r,null==a),u=null==a?[n]:[n,a],l=t.runWebGLProgram(i,u,"int32");if(l.shape.length===n.shape.length){const a=e(t,n,r,l);return t.disposeIntermediateTensorInfo(l),a}return l}(e,t,r)}const Mi={kernelName:"ArgMax",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s}=r;let o=k(s,a.shape);const i=un(o,a.shape.length);let u=a;const l=[];null!=i&&(u=gi({inputs:{x:a},backend:n,attrs:{perm:i}}),l.push(u),o=cn(o.length,u.shape.length)),on("argMax",[o[0]],u.shape.length);const c=Ri(n,u,o[0],"max");return l.forEach(e=>n.disposeIntermediateTensorInfo(e)),c}};const Fi={kernelName:"ArgMin",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s}=r;let o=k(s,a.shape);const i=un(o,a.shape.length);let u=a;const l=[];null!=i&&(u=gi({inputs:{x:a},backend:n,attrs:{perm:i}}),l.push(u),o=cn(o.length,u.shape.length)),on("argMin",[o[0]],u.shape.length);const c=Ri(n,u,o[0],"min");return l.forEach(e=>n.disposeIntermediateTensorInfo(e)),c}},Di={kernelName:"Asin",backendName:"webgl",kernelFunc:Yo({opSnippet:"if (isnan(x)) return x;\n  if (abs(x) > 1.) {\n    return NAN;\n  }\n  return asin(x);\n"})},Oi={kernelName:"Asinh",backendName:"webgl",kernelFunc:Yo({opSnippet:"if (isnan(x)) return x;return log(x + sqrt(x * x + 1.0));"})},Pi={kernelName:"Atan",backendName:"webgl",kernelFunc:Yo({opSnippet:"if (isnan(x)) return x;\n  return atan(x);\n"})},Li={kernelName:"Atan2",backendName:"webgl",kernelFunc:Qo({opSnippet:"\n  if (isnan(a)) return a;\n  if (isnan(b)) return b;\n\n  return atan(a, b);\n",packedOpSnippet:"\n  vec4 result = atan(a, b);\n  vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n"})},Bi={kernelName:"Atanh",backendName:"webgl",kernelFunc:Yo({opSnippet:"if (isnan(x)) return x;\n  if ((x < -1.0) || (x > 1.0)) return NAN;\nreturn (log(1.0 + x) - log(1.0 - x)) / 2.0;"})};class Wi{constructor(e,t,n,r=!1,a=!1){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");const s=e.filterWidth,o=e.strideHeight,i=e.strideWidth,u=e.dilationHeight,l=e.dilationWidth,c=e.effectiveFilterHeight,d=e.effectiveFilterWidth,p=e.padInfo.top,h=e.padInfo.left;this.outputShape=e.outShape;const f="avg"===t,m=`((batch  * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let y="0.0";if(f||(y="-1.0 / 1e-20"),n){const t=">=";return void(this.userCode=`\n        const ivec2 strides = ivec2(${o}, ${i});\n        const ivec2 pads = ivec2(${p}, ${h});\n\n        void main() {\n          ivec4 coords = getOutputCoords();\n          int batch = coords[0];\n          int d = coords[3];\n\n          ivec2 xRCCorner = coords.yz * strides - pads;\n          int xRCorner = xRCCorner.x;\n          int xCCorner = xRCCorner.y;\n\n          // max/min x(?, ?, d) to get y(yR, yC, d).\n          // ? = to be determined\n          float minMaxValue = 0.0;\n          float minMaxValueFound = 0.0;\n          int minMaxPosition = 0;\n          float avgValue = 0.0;\n\n          for (int wR = 0; wR < ${c};\n              wR += ${u}) {\n            int xR = xRCorner + wR;\n\n            if (xR < 0 || xR >= ${e.inHeight}) {\n              continue;\n            }\n\n            for (int wC = 0; wC < ${d};\n                wC += ${l}) {\n              int xC = xCCorner + wC;\n\n              if (xC < 0 || xC >= ${e.inWidth}) {\n                continue;\n              }\n\n              float value = getX(batch, xR, xC, d);\n\n              // If a min / max value has already been found, use it. If not,\n              // use the current value.\n              float currMinMaxValue = mix(\n                  value, minMaxValue, minMaxValueFound);\n              if (value ${t} currMinMaxValue) {\n                minMaxValue = value;\n                minMaxValueFound = 1.0;\n                minMaxPosition = ${r?a?m:g:`wR * ${d} + wC`};\n              }\n            }\n          }\n          setOutput(float(minMaxPosition));\n        }\n      `)}let b=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"avg"===t&&(b="avgValue / count");const x=4*Math.floor(s/4),k=s%4,w=`\n      if (${f}) {\n        avgValue += dot(values, ones);\n      } else {\n        minMaxValue = max(values, minMaxValue);\n      }\n    `;this.userCode=`\n      const ivec2 strides = ivec2(${o}, ${i});\n      const ivec2 pads = ivec2(${p}, ${h});\n      const float initializationValue = ${y};\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n      float count = 0.0;\n\n      float getValue(int batch, int xR, int xC, int d) {\n        if (xC < 0 || xC >= ${e.inWidth}) {\n          return initializationValue;\n        }\n        count += 1.0;\n        return getX(batch, xR, xC, d);\n      }\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d = coords[3];\n\n        ivec2 xRCCorner = coords.yz * strides - pads;\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        // max/min x(?, ?, d) to get y(yR, yC, d).\n        // ? = to be determined\n        vec4 minMaxValue = vec4(${y});\n        float avgValue = 0.0;\n        count = 0.0;\n\n        for (int wR = 0; wR < ${c};\n            wR += ${u}) {\n          int xR = xRCorner + wR;\n\n          if (xR < 0 || xR >= ${e.inHeight}) {\n            continue;\n          }\n\n          for (int wC = 0; wC < ${x}; wC += 4) {\n            int xC = xCCorner + wC * ${l};\n\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + ${l}, d),\n              getValue(batch, xR, xC + 2 * ${l}, d),\n              getValue(batch, xR, xC + 3 * ${l}, d)\n            );\n\n            ${w}\n          }\n\n          int xC = xCCorner + ${x};\n          if (${1===k}) {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              initializationValue,\n              initializationValue,\n              initializationValue\n            );\n\n            ${w}\n          } else if (${2===k}) {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + ${l}, d),\n              initializationValue,\n              initializationValue\n            );\n\n            ${w}\n          } else if (${3===k}) {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + ${l}, d),\n              getValue(batch, xR, xC + 2 * ${l}, d),\n              initializationValue\n            );\n\n            ${w}\n          }\n        }\n        setOutput(${b});\n      }\n    `}}class zi{constructor(e,t,n,r=!1,a=!1){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");const s=e.filterWidth,o=e.strideDepth,i=e.strideHeight,u=e.strideWidth,l=e.dilationDepth,c=e.dilationHeight,d=e.dilationWidth,p=e.effectiveFilterDepth,h=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,y=e.padInfo.left;this.outputShape=e.outShape;const b="avg"===t;let x="0.0";if(b||(x="-1.0 / 1e-20"),n){const t=">=";return void(this.userCode=`\n        const ivec3 strides =\n            ivec3(${o}, ${i}, ${u});\n        const ivec3 pads = ivec3(${m}, ${g}, ${y});\n\n        void main() {\n          ivec5 coords = getOutputCoords();\n          int batch = coords.x;\n          int ch = coords.u;\n\n          ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n          int xDCorner = xCorner.x;\n          int xRCorner = xCorner.y;\n          int xCCorner = xCorner.z;\n\n          // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).\n          // ? = to be determined\n          float minMaxValue = 0.0;\n          float minMaxValueFound = 0.0;\n          int minMaxPosition = 0;\n\n          for (int wD = 0; wD < ${p};\n              wD += ${l}) {\n            int xD = xDCorner + wD;\n\n            if (xD < 0 || xD >= ${e.inDepth}) {\n              continue;\n            }\n\n            for (int wR = 0; wR < ${h};\n                wR += ${c}) {\n              int xR = xRCorner + wR;\n\n              if (xR < 0 || xR >= ${e.inHeight}) {\n                continue;\n              }\n\n              for (int wC = 0; wC < ${f};\n                  wC += ${d}) {\n                int xC = xCCorner + wC;\n\n                if (xC < 0 || xC >= ${e.inWidth}) {\n                  continue;\n                }\n\n                float value = getX(batch, xD, xR, xC, ch);\n\n                // If a min / max value has already been found, use it. If not,\n                // use the current value.\n                float currMinMaxValue = mix(\n                    value, minMaxValue, minMaxValueFound);\n                if (value ${t} currMinMaxValue) {\n                  minMaxValue = value;\n                  minMaxValueFound = 1.0;\n                  minMaxPosition = ${r?a?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${h} * ${f} +\n                      wR * ${f} + wC`};\n                }\n              }\n            }\n          }\n          setOutput(float(minMaxPosition));\n        }\n      `)}let k=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"avg"===t&&(k="avgValue / count");const w=4*Math.floor(s/4),v=s%4,I=`\n      if (${b}) {\n        avgValue += dot(values, ones);\n      } else {\n        minMaxValue = max(values, minMaxValue);\n      }\n    `;this.userCode=`\n      const ivec3 strides =\n        ivec3(${o}, ${i}, ${u});\n      const ivec3 pads = ivec3(${m}, ${g}, ${y});\n      const float initializationValue = ${x};\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n      float count = 0.0;\n\n      float getValue(int batch, int xD, int xR, int xC, int ch) {\n        if (xC < 0 || xC >= ${e.inWidth}) {\n          return initializationValue;\n        }\n        count += 1.0;\n        return getX(batch, xD, xR, xC, ch);\n      }\n\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int batch = coords.x;\n        int ch = coords.u;\n\n        ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n        int xDCorner = xCorner.x;\n        int xRCorner = xCorner.y;\n        int xCCorner = xCorner.z;\n\n        // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).\n        // ? = to be determined\n        vec4 minMaxValue = vec4(${x});\n        float avgValue = 0.0;\n        count = 0.0;\n\n        for (int wD = 0; wD < ${p};\n            wD += ${l}) {\n          int xD = xDCorner + wD;\n\n          if (xD < 0 || xD >= ${e.inDepth}) {\n            continue;\n          }\n\n          for (int wR = 0; wR < ${h};\n            wR += ${c}) {\n            int xR = xRCorner + wR;\n\n            if (xR < 0 || xR >= ${e.inHeight}) {\n              continue;\n            }\n\n            for (int wC = 0; wC < ${w}; wC += 4) {\n              int xC = xCCorner + wC * ${d};\n\n              vec4 values = vec4(\n                getValue(batch, xD, xR, xC, ch),\n                getValue(batch, xD, xR, xC + ${d}, ch),\n                getValue(batch, xD, xR, xC + 2 * ${d}, ch),\n                getValue(batch, xD, xR, xC + 3 * ${d}, ch)\n              );\n\n              ${I}\n            }\n\n            int xC = xCCorner + ${w};\n            if (${1===v}) {\n              vec4 values = vec4(\n                getValue(batch, xD, xR, xC, ch),\n                initializationValue,\n                initializationValue,\n                initializationValue\n              );\n\n              ${I}\n            } else if (${2===v}) {\n              vec4 values = vec4(\n                getValue(batch, xD, xR, xC, ch),\n                getValue(batch, xD, xR, xC + ${d}, ch),\n                initializationValue,\n                initializationValue\n              );\n\n              ${I}\n            } else if (${3===v}) {\n              vec4 values = vec4(\n                getValue(batch, xD, xR, xC, ch),\n                getValue(batch, xD, xR, xC + ${d}, ch),\n                getValue(batch, xD, xR, xC + 2 * ${d}, ch),\n                initializationValue\n              );\n\n              ${I}\n            }\n          }\n          setOutput(${k});\n        }\n      }\n    `}}const Vi={kernelName:"AvgPool",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t;zr(a,"avgPool");const{filterSize:s,strides:o,pad:i,dimRoundingMode:u}=r;c(qt(o,1),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '1'`);const l=Pt(a.shape,s,o,1,i,u);if(1===l.filterWidth&&1===l.filterHeight&&f(l.inShape,l.outShape))return Wo({inputs:{x:a},backend:n});const d=new Wi(l,"avg",!1);return n.runWebGLProgram(d,[a],"float32")}};const Ui={kernelName:"AvgPool3D",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{filterSize:s,strides:o,pad:i,dimRoundingMode:u,dataFormat:l}=r,c=Lt(a.shape,s,o,[1,1,1],i,u,l),d=new zi(c,"avg",!1);return n.runWebGLProgram(d,[a],"float32")}};class Gi{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,s=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=i-1-e.padInfo.top,c=u-1-e.padInfo.left,d=1/(t*n);this.userCode=`\n      const ivec2 pads = ivec2(${l}, ${c});\n      const float avgMultiplier = float(${d});\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n\n        ivec2 dyRCCorner = coords.yz - pads;\n        int dyRCorner = dyRCCorner.x;\n        int dyCCorner = dyRCCorner.y;\n\n        // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < ${i};\n            wR += ${s}) {\n          float dyR = float(dyRCorner + wR) / ${r}.0;\n\n          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          for (int wC = 0; wC < ${u};\n            wC+= ${o}) {\n            float dyC = float(dyCCorner + wC) / ${a}.0;\n\n            if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            float dyValue = getDy(b, idyR, idyC, d);\n\n            dotProd += dyValue * avgMultiplier;\n          }\n        }\n        setOutput(dotProd);\n      }\n    `}}class Hi{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,a=e.strideDepth,s=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,u=e.dilationHeight,l=e.dilationWidth,c=e.effectiveFilterDepth,d=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=c-1-e.padInfo.front,f=d-1-e.padInfo.top,m=p-1-e.padInfo.left,g=1/(t*n*r);this.userCode=`\n      const ivec3 pads = ivec3(${h}, ${f}, ${m});\n      const float avgMultiplier = float(${g});\n\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int batch = coords.x;\n        int ch = coords.u;\n\n        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n        int dyDCorner = dyCorner.x;\n        int dyRCorner = dyCorner.y;\n        int dyCCorner = dyCorner.z;\n\n        // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get\n        // dx(xD, xR, xC, ch).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n\n        for (int wD = 0; wD < ${c};\n            wD += ${i}) {\n          float dyD = float(dyDCorner + wD) / ${a}.0;\n\n          if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {\n            continue;\n          }\n          int idyD = int(dyD);\n\n          for (int wR = 0; wR < ${d};\n              wR += ${u}) {\n            float dyR = float(dyRCorner + wR) / ${s}.0;\n\n            if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\n                fract(dyR) > 0.0) {\n              continue;\n            }\n            int idyR = int(dyR);\n\n            for (int wC = 0; wC < ${p};\n                wC += ${l}) {\n              float dyC = float(dyCCorner + wC) / ${o}.0;\n\n              if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n                  fract(dyC) > 0.0) {\n                continue;\n              }\n              int idyC = int(dyC);\n\n              float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n\n              dotProd += dyValue * avgMultiplier;\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    `}}const ji={kernelName:"AvgPool3DGrad",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s}=t,o=s,{filterSize:i,strides:u,pad:l,dimRoundingMode:c}=r,d=Lt(o.shape,i,u,[1,1,1],l,c),p=new Hi(d);return n.runWebGLProgram(p,[a],o.dtype)}};const qi={kernelName:"AvgPoolGrad",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s}=t,o=s;zr([a,s],"avgPoolGrad");const{filterSize:i,strides:u,pad:l}=r,c=Pt(o.shape,i,u,1,l),d=new Gi(c);return n.runWebGLProgram(d,[a],o.dtype)}};const Ki={kernelName:"BatchMatMul",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a:a,b:s}=t,{transposeA:o,transposeB:i}=r;return bi({a:a,b:s,transposeA:o,transposeB:i,backend:n})}};class Xi{constructor(e,t,n,r,a,s){this.outputShape=[],this.variableNames=["x","mean","variance"],Jt(e,t),Jt(e,n);let o="0.0";null!=r&&(Jt(e,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="1.0";null!=a&&(Jt(e,a),this.variableNames.push("scale"),i="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`\n      void main() {\n        float x = getXAtOutCoords();\n        float mean = getMeanAtOutCoords();\n        float variance = getVarianceAtOutCoords();\n        float offset = ${o};\n        float scale = ${i};\n        float inv = scale * inversesqrt(variance + float(${s}));\n        setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n      }\n    `}}class Yi{constructor(e,t,n,r,a,s){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],Jt(e,t),Jt(e,n);let o="vec4(0.0)";null!=r&&(Jt(e,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="vec4(1.0)";null!=a&&(Jt(e,a),this.variableNames.push("scale"),i="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`\n      void main() {\n        vec4 offset = ${o};\n        vec4 scale = ${i};\n\n        vec4 x = getXAtOutCoords();\n        vec4 mean = getMeanAtOutCoords();\n        vec4 variance = getVarianceAtOutCoords();\n\n        vec4 inv = scale * inversesqrt(variance + vec4(${s}));\n\n        setOutput((x - mean) * inv + offset);\n      }\n    `}}const Qi={kernelName:"FusedBatchNorm",backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r,mean:a,variance:s,offset:o,scale:i}=e;c(a.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),c(null==o||a.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),c(null==i||a.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:u}=n;null==u&&(u=.001);const l=[r,a,s];let d=null;null!=o&&(d=o.shape,l.push(o));let p=null;null!=i&&(p=i.shape,l.push(i));const h=W().getBool("WEBGL_PACK_NORMALIZATION")?new Yi(r.shape,a.shape,s.shape,d,p,u):new Xi(r.shape,a.shape,s.shape,d,p,u);return t.runWebGLProgram(h,l,l[0].dtype)}};class Ji{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=wa(this.rank),n=`uniform int start[${this.rank}];`,r=function(e){if(1===e)return"sourceLoc";if(e<=6)return Zi.slice(0,e).map(e=>"sourceLoc."+e).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}(this.rank);let a;a=`\n        ${t} sourceLoc;\n        ${t} coords = getOutputCoords();\n        ${e.map((e,t)=>`sourceLoc.${Zi[t]} = start[${t}] + coords.${Zi[t]};`).join("\n")}\n      `,this.userCode=`\n      ${n}\n      void main() {\n        ${a}\n        setOutput(getSource(${r}));\n      }\n    `}getCustomSetupFunc(e){if(e.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${e.length})`);return(t,n)=>{null==this.startLoc&&(this.startLoc=t.getUniformLocationNoThrow(n,"start"),null==this.startLoc)||t.gl.uniform1iv(this.startLoc,e)}}}const Zi=["x","y","z","w","u","v"];class eu{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;const t=wa(this.rank),n=Io("coords",this.rank),r=Io("sourceLoc",this.rank),a=1===this.rank?"sourceLoc":`vec2(${r.slice(-2).join()})`,s=`getChannel(getSource(${r.join()}), ${a})`,o=`\n      result.x = ${s};\n      if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n        ++${r[this.rank-1]};\n        result.y = ${s};\n        --${r[this.rank-1]};\n      }\n    `,i=1===this.rank?"":`\n      --${n[this.rank-1]};\n      if (++${n[this.rank-2]} < ${e[this.rank-2]}) {\n        ++${r[this.rank-2]};\n        result.z = ${s};\n        if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n          ++${r[this.rank-1]};\n          result.w = ${s};\n        }\n      }\n    `,u=this.rank<=4?`sourceLoc = coords +\n            ${t}(${e.map((e,t)=>`start[${t}]`).join()});`:e.map((e,t)=>`${r[t]} = ${n[t]} + start[${t}];`).join("\n");this.userCode=`\n      uniform int start[${this.rank}];\n      void main() {\n        ${t} coords = getOutputCoords();\n        ${t} sourceLoc;\n        ${u}\n        vec4 result = vec4(0.);\n        ${o}\n        ${i}\n        setOutput(result);\n      }\n    `}getCustomSetupFunc(e){if(e.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${e.length})`);return(t,n)=>{null==this.startLoc&&(this.startLoc=t.getUniformLocationNoThrow(n,"start"),null==this.startLoc)||t.gl.uniform1iv(this.startLoc,e)}}}function tu(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{begin:s,size:o}=r,[i,u]=$t(a,s,o);if(mt(a,i,u),0===h(u))return n.makeTensorInfo(u,a.dtype,[]);if(n.shouldExecuteOnCPU([a])||"string"===a.dtype){const e=n.texData.get(a.dataId),t=mo(e.values,i,u,a.shape,a.dtype);return n.makeTensorInfo(u,a.dtype,t)}const{isPacked:l}=n.texData.get(a.dataId),c=Tt(a.shape,i,u);if(l||!c){const e=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new eu(u):new Ji(u),t=e.getCustomSetupFunc(i);return n.runWebGLProgram(e,[a],a.dtype,t)}return n.uploadToGPU(a.dataId),function(e,t,n,r){const a=r.texData.get(e.dataId),s=r.makeTensorInfo(n,e.dtype),o=r.texData.get(s.dataId);Object.assign(o,a),o.refCount=1,o.shape=n,o.dtype=e.dtype;let i=Et(t,A(e.shape));a.slice&&(i+=a.slice.flatOffset),o.slice={flatOffset:i,origDataId:a.slice&&a.slice.origDataId||e.dataId};const u=r.dataRefCount.get(o.slice.origDataId)||1;return r.dataRefCount.set(o.slice.origDataId,u+1),s}(a,i,u,n)}const nu={kernelName:"Slice",backendName:"webgl",kernelFunc:tu},ru={kernelName:"BatchToSpaceND",backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,crops:o}=r;c(a.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");const i=s.reduce((e,t)=>e*t),u=Wn(a.shape,s,i),l=zn(u.length,s.length),d=Vn(a.shape,s,i),p=Un(o,s.length),h=Gn(d,o,s.length),f=[],m=oi({inputs:{x:a},backend:n,attrs:{shape:u}}),g=gi({inputs:{x:m},backend:n,attrs:{perm:l}}),y=oi({inputs:{x:g},backend:n,attrs:{shape:d}}),b=tu({inputs:{x:y},backend:n,attrs:{begin:p,size:h}});return f.push(m),f.push(g),f.push(y),f.forEach(e=>n.disposeIntermediateTensorInfo(e)),b}};const au={kernelName:"Bincount",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,weights:s}=t,{size:o}=r,i=n.readSync(a.dataId),u=n.readSync(s.dataId),l=qs(i,u,s.dtype,s.shape,o);return n.makeTensorInfo([o],s.dtype,l)}},su=Qo({opSnippet:"return float(a != b);",dtype:"bool"}),ou={kernelName:"NotEqual",backendName:"webgl",kernelFunc:su};function iu(e){const{inputs:t,backend:n}=e,{input:r}=t;return Wo({inputs:{x:n.texData.get(r.dataId).complexTensorInfos.real},backend:n})}const uu={kernelName:"Real",backendName:"webgl",kernelFunc:iu};const lu={kernelName:"Cast",backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:r,attrs:a}=t,{x:s}=n,{dtype:o}=a;if("complex64"===o){if("complex64"===s.dtype)return Wo({inputs:{x:s},backend:r});const t=function e(t,n="float32"){if("complex64"===n){const n=e(t,"float32"),r=e(t,"float32");return Pe(n,r)}const r=M(h(t),n);return Ee.makeTensor(r,t,n)}(s.shape),n=e({inputs:{x:s},backend:r,attrs:{dtype:"float32"}}),a=Vo({inputs:{real:n,imag:t},backend:r});return t.dispose(),r.disposeIntermediateTensorInfo(n),a}if("complex64"===s.dtype){const t=iu({inputs:{input:s},backend:r}),n=e({inputs:{x:t},backend:r,attrs:{dtype:o}});return r.disposeIntermediateTensorInfo(t),n}if(!N(s.dtype,o)){const e=Wo({inputs:{x:s},backend:r});return{dataId:e.dataId,shape:e.shape,dtype:o}}if("int32"===o)return function(e,t){const n=new _o(e.shape,"return float(int(x));"),r=t.runWebGLProgram(n,[e],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}(s,r);if("bool"===o){const e=r.makeTensorInfo([],"bool",v("bool",1)),t=su({inputs:{a:s,b:e},backend:r});return r.disposeIntermediateTensorInfo(e),t}throw new Error(`Error in Cast: failed to cast ${s.dtype} to ${o}`)}},cu="return ceil(x);",du={kernelName:"Ceil",backendName:"webgl",kernelFunc:Yo({opSnippet:cu,packedOpSnippet:cu,cpuKernelImpl:Xs})};class pu{constructor(e){this.variableNames=["A"],this.outputShape=e,this.userCode="\n      uniform float minVal;\n      uniform float maxVal;\n\n      void main() {\n        float value = getAAtOutCoords();\n        if (isnan(value)) {\n          setOutput(value);\n          return;\n        }\n\n        setOutput(clamp(value, minVal, maxVal));\n      }\n    "}getCustomSetupFunc(e,t){return(n,r)=>{null==this.minLoc&&(this.minLoc=n.getUniformLocationNoThrow(r,"minVal"),this.maxLoc=n.getUniformLocationNoThrow(r,"maxVal")),n.gl.uniform1f(this.minLoc,e),n.gl.uniform1f(this.maxLoc,t)}}}class hu{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode="\n      uniform float minVal;\n      uniform float maxVal;\n\n      void main() {\n        vec4 value = getAAtOutCoords();\n\n        if (any(isnan(value))) {\n          setOutput(value);\n          return;\n        }\n\n        setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\n      }\n    "}getCustomSetupFunc(e,t){return(n,r)=>{null==this.minLoc&&(this.minLoc=n.getUniformLocationNoThrow(r,"minVal"),this.maxLoc=n.getUniformLocationNoThrow(r,"maxVal")),n.gl.uniform1f(this.minLoc,e),n.gl.uniform1f(this.maxLoc,t)}}}const fu={kernelName:"ClipByValue",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{clipValueMin:s,clipValueMax:o}=r;let i;i=W().getBool("WEBGL_PACK_CLIP")?new hu(a.shape):new pu(a.shape);const u=i.getCustomSetupFunc(s,o);return n.runWebGLProgram(i,[a],a.dtype,u)}};class mu{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode="\n      void main() {\n        float re = abs(getRealAtOutCoords());\n        float im = abs(getImagAtOutCoords());\n        float mx = max(re, im);\n\n        // sadly the length function in glsl is not underflow-safe\n        // (at least not on Intel GPUs). So the safe solution is\n        // to ensure underflow-safety in all cases.\n        setOutput(\n          mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n        );\n      }\n    "}}function gu(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}const yu={kernelName:"ComplexAbs",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t,a=n.texData.get(r.dataId),s=new mu(r.shape),o=[gu(r,a.complexTensorInfos.real),gu(r,a.complexTensorInfos.imag)];return n.runWebGLProgram(s,o,o[0].dtype)}};class bu{constructor(e){this.outputShape=[],this.outputShape=Pn(e,1),this.variableNames=e.map((e,t)=>"T"+t);const t=new Array(e.length-1);t[0]=e[0][1];for(let n=1;n<t.length;n++)t[n]=t[n-1]+e[n][1];const n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let e=1;e<t.length;e++){const r=t[e-1];n.push(`else if (yC < ${t[e]}) setOutput(getT${e}(yR, yC-${r}));`)}const r=t.length,a=t[t.length-1];n.push(`else setOutput(getT${r}(yR, yC-${a}));`),this.userCode=`\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int yR = coords.x;\n        int yC = coords.y;\n\n        ${n.join("\n        ")}\n      }\n    `}}class xu{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=Pn(e,t);const n=this.outputShape,r=n.length,a=wa(r),s=Io("coords",r),o=["x","y","z","w","u","v"].slice(0,r);this.variableNames=e.map((e,t)=>"T"+t);const i=new Array(e.length-1);i[0]=e[0][t];for(let n=1;n<i.length;n++)i[n]=i[n-1]+e[n][t];const u=o[t],l=o.slice(-2),c=o.join();let d=`if (${u} < ${i[0]}) {\n        return getChannel(\n            getT0(${c}), vec2(${l.join()}));\n        }`;for(let e=1;e<i.length;e++){const t=i[e-1];d+=`\n        if (${u} < ${i[e]}  && ${u} >= ${i[e-1]}) {\n          return getChannel(\n            getT${e}(${ku(o,u,t)}),\n            vec2(${ku(l,u,t)}));\n        }`}const p=i.length,h=i[i.length-1];d+=`\n        return getChannel(\n          getT${p}(${ku(o,u,h)}),\n          vec2(${ku(l,u,h)}));`,this.userCode=`\n      float getValue(${o.map(e=>"int "+e)}) {\n        ${d}\n      }\n\n      void main() {\n        ${a} coords = getOutputCoords();\n        vec4 result = vec4(getValue(${s}), 0., 0., 0.);\n\n        ${s[r-1]} = ${s[r-1]} + 1;\n        if (${s[r-1]} < ${n[r-1]}) {\n          result.g = getValue(${s});\n        }\n\n        ${s[r-2]} = ${s[r-2]} + 1;\n        if (${s[r-2]} < ${n[r-2]}) {\n          result.a = getValue(${s});\n        }\n\n        ${s[r-1]} = ${s[r-1]} - 1;\n        if (${s[r-2]} < ${n[r-2]} &&\n            ${s[r-1]} < ${n[r-1]}) {\n          result.b = getValue(${s});\n        }\n        setOutput(result);\n      }\n    `}}function ku(e,t,n){const r=e.indexOf(t);return e.map((e,t)=>t===r?`${e} - ${n}`:e).join()}function wu(e){const{inputs:t,backend:n}=e,{input:r}=t;return Wo({inputs:{x:n.texData.get(r.dataId).complexTensorInfos.imag},backend:n})}const vu={kernelName:"Imag",backendName:"webgl",kernelFunc:wu};function Iu(e,t,n){const r=Pn(e.map(e=>e.shape),t);return{tensors2D:e.map(e=>oi({inputs:{x:e},attrs:{shape:[-1,h(e.shape.slice(t))]},backend:n})),outShape:r}}function Nu(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r,s=k(a,t[0].shape)[0],o=Pn(t.map(e=>e.shape),s);if(0===h(o))return n.makeTensorInfo(o,t[0].dtype,[]);const i=t.filter(e=>h(e.shape)>0);if(1===i.length)return Wo({inputs:{x:i[0]},backend:n});return On(i.map(e=>e.shape),s),function e(t,n,r){const a=t[0].dtype;if("complex64"===a){const a=t.map(e=>iu({inputs:{input:e},backend:r})),s=t.map(e=>wu({inputs:{input:e},backend:r})),o=e(a,n,r),i=e(s,n,r),u=Vo({inputs:{real:o,imag:i},backend:r});return a.forEach(e=>r.disposeIntermediateTensorInfo(e)),s.forEach(e=>r.disposeIntermediateTensorInfo(e)),r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(i),u}if("string"===a){const{tensors2D:e,outShape:s}=Iu(t,n,r),o=e.map(e=>({vals:r.readSync(e.dataId),shape:e.shape})),i=1===e[0].shape[0],u=Ys(o,s,a,i),l=Pn(t.map(e=>e.shape),n),c=r.makeTensorInfo(l,a,u);return e.forEach(e=>r.disposeIntermediateTensorInfo(e)),c}if(t.length>W().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const a=Math.floor(t.length/2),s=e(t.slice(0,a),n,r),o=e(t.slice(a),n,r),i=e([s,o],n,r);return r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(o),i}if(W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&t[0].shape.length>1){const e=new xu(t.map(e=>e.shape),n);return r.runWebGLProgram(e,t,a)}const{tensors2D:s,outShape:o}=Iu(t,n,r),i=new bu(s.map(e=>e.shape)),u=r.runWebGLProgram(i,s,a);s.forEach(e=>r.disposeIntermediateTensorInfo(e));const l=oi({inputs:{x:u},attrs:{shape:o},backend:r});return r.disposeIntermediateTensorInfo(u),l}(i,s,n)}const Su={kernelName:"Concat",backendName:"webgl",kernelFunc:Nu};class Cu{constructor(e,t=!1,n=null,r=!1,a=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const s=e.padInfo.top,o=e.padInfo.left,i=e.strideHeight,u=e.strideWidth,l=e.dilationHeight,c=e.dilationWidth,d=e.filterHeight,p=e.filterWidth,h=4*Math.floor(e.inChannels/4),f=e.inChannels%4,m="channelsLast"===e.dataFormat,g=m?1:2,y=m?2:3,b=m?3:1;let x="",k="";n&&(x=r?`float activation(float a) {\n          float b = getPreluActivationWeightsAtOutCoords();\n          ${n}\n        }`:a?`float activation(float a) {\n          float b = getLeakyreluAlphaAtOutCoords();\n          ${n}\n        }`:`\n          float activation(float x) {\n            ${n}\n          }\n        `,k="result = activation(result);");const w=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n      ${x}\n\n      const ivec2 strides = ivec2(${i}, ${u});\n      const ivec2 pads = ivec2(${s}, ${o});\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d2 = coords[${b}];\n\n        ivec2 xRCCorner =\n            ivec2(coords[${g}], coords[${y}]) * strides - pads;\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < ${d}; wR++) {\n          int xR = xRCorner + wR * ${l};\n\n          if (xR < 0 || xR >= ${e.inHeight}) {\n            continue;\n          }\n\n          for (int wC = 0; wC < ${p}; wC++) {\n            int xC = xCCorner + wC * ${c};\n\n            if (xC < 0 || xC >= ${e.inWidth}) {\n              continue;\n            }\n\n            for (int d1 = 0; d1 < ${h}; d1 += 4) {\n              vec4 wValues = vec4(\n                getW(wR, wC, d1, d2),\n                getW(wR, wC, d1 + 1, d2),\n                getW(wR, wC, d1 + 2, d2),\n                getW(wR, wC, d1 + 3, d2)\n              );\n\n              if (${m}) {\n                vec4 xValues = vec4(\n                  getX(batch, xR, xC, d1),\n                  getX(batch, xR, xC, d1 + 1),\n                  getX(batch, xR, xC, d1 + 2),\n                  getX(batch, xR, xC, d1 + 3)\n                );\n                dotProd += dot(xValues, wValues);\n              } else {\n                vec4 xValues = vec4(\n                  getX(batch, d1, xR, xC),\n                  getX(batch, d1 + 1, xR, xC),\n                  getX(batch, d1 + 2, xR, xC),\n                  getX(batch, d1 + 3, xR, xC)\n                );\n                dotProd += dot(xValues, wValues);\n              }\n            }\n\n            if (${1===f}) {\n\n              if (${m}) {\n                dotProd +=\n                    getX(batch, xR, xC, ${h}) *\n                    getW(wR, wC, ${h}, d2);\n              } else {\n                dotProd +=\n                    getX(batch, ${h}, xR, xC) *\n                    getW(wR, wC, ${h}, d2);\n              }\n\n            } else if (${2===f}) {\n              vec2 wValues = vec2(\n                getW(wR, wC, ${h}, d2),\n                getW(wR, wC, ${h} + 1, d2)\n              );\n\n              if (${m}) {\n                vec2 xValues = vec2(\n                  getX(batch, xR, xC, ${h}),\n                  getX(batch, xR, xC, ${h} + 1)\n                );\n                dotProd += dot(xValues, wValues);\n              } else {\n                vec2 xValues = vec2(\n                  getX(batch, ${h}, xR, xC),\n                  getX(batch, ${h} + 1, xR, xC)\n                );\n                dotProd += dot(xValues, wValues);\n              }\n\n            } else if (${3===f}) {\n              vec3 wValues = vec3(\n                getW(wR, wC, ${h}, d2),\n                getW(wR, wC, ${h} + 1, d2),\n                getW(wR, wC, ${h} + 2, d2)\n              );\n\n              if (${m}) {\n                vec3 xValues = vec3(\n                  getX(batch, xR, xC, ${h}),\n                  getX(batch, xR, xC, ${h} + 1),\n                  getX(batch, xR, xC, ${h} + 2)\n                );\n                dotProd += dot(xValues, wValues);\n              } else {\n                vec3 xValues = vec3(\n                  getX(batch, ${h}, xR, xC),\n                  getX(batch, ${h} + 1, xR, xC),\n                  getX(batch, ${h} + 2, xR, xC)\n                );\n                dotProd += dot(xValues, wValues);\n              }\n\n            }\n          }\n        }\n\n        float result = dotProd;\n        ${w}\n        ${k}\n        setOutput(result);\n      }\n    `}}class Tu{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const t=e.padInfo.front,n=e.padInfo.top,r=e.padInfo.left,a=e.strideDepth,s=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,u=e.dilationHeight,l=e.dilationWidth,c=e.filterDepth,d=e.filterHeight,p=e.filterWidth,h=4*Math.floor(e.inChannels/4),f=e.inChannels%4;this.userCode=`\n      const ivec3 strides = ivec3(${a}, ${s}, ${o});\n      const ivec3 pads = ivec3(${t}, ${n}, ${r});\n\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int batch = coords.x;\n        int d2 = coords.u;\n\n        ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n        int xFCorner = xFRCCorner.x;\n        int xRCorner = xFRCCorner.y;\n        int xCCorner = xFRCCorner.z;\n\n        // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n        // y(yF, yR, yC, d2). ? = to be determined. : = across all\n        // values in that axis.\n        float dotProd = 0.0;\n        for (int wF = 0; wF < ${c}; wF++) {\n          int xF = xFCorner + wF * ${i};\n\n          if (xF < 0 || xF >= ${e.inDepth}) {\n            continue;\n          }\n\n          for (int wR = 0; wR < ${d}; wR++) {\n            int xR = xRCorner + wR * ${u};\n\n            if (xR < 0 || xR >= ${e.inHeight}) {\n              continue;\n            }\n\n            for (int wC = 0; wC < ${p}; wC++) {\n              int xC = xCCorner + wC * ${l};\n\n              if (xC < 0 || xC >= ${e.inWidth}) {\n                continue;\n              }\n\n              for (int d1 = 0; d1 < ${h}; d1 += 4) {\n                vec4 xValues = vec4(\n                  getX(batch, xF, xR, xC, d1),\n                  getX(batch, xF, xR, xC, d1 + 1),\n                  getX(batch, xF, xR, xC, d1 + 2),\n                  getX(batch, xF, xR, xC, d1 + 3)\n                );\n                vec4 wValues = vec4(\n                  getW(wF, wR, wC, d1, d2),\n                  getW(wF, wR, wC, d1 + 1, d2),\n                  getW(wF, wR, wC, d1 + 2, d2),\n                  getW(wF, wR, wC, d1 + 3, d2)\n                );\n\n                dotProd += dot(xValues, wValues);\n              }\n\n              if (${1===f}) {\n                dotProd +=\n                  getX(batch, xF, xR, xC, ${h}) *\n                  getW(wF, wR, wC, ${h}, d2);\n              } else if (${2===f}) {\n                vec2 xValues = vec2(\n                  getX(batch, xF, xR, xC, ${h}),\n                  getX(batch, xF, xR, xC, ${h} + 1)\n                );\n                vec2 wValues = vec2(\n                  getW(wF, wR, wC, ${h}, d2),\n                  getW(wF, wR, wC, ${h} + 1, d2)\n                );\n                dotProd += dot(xValues, wValues);\n              } else if (${3===f}) {\n                vec3 xValues = vec3(\n                  getX(batch, xF, xR, xC, ${h}),\n                  getX(batch, xF, xR, xC, ${h} + 1),\n                  getX(batch, xF, xR, xC, ${h} + 2)\n                );\n                vec3 wValues = vec3(\n                  getW(wF, wR, wC, ${h}, d2),\n                  getW(wF, wR, wC, ${h} + 1, d2),\n                  getW(wF, wR, wC, ${h} + 2, d2)\n                );\n                dotProd += dot(xValues, wValues);\n              }\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    `}}class Eu{constructor(e,t,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;const{filterWidth:r,inChannels:a,strideWidth:s,strideHeight:o,padInfo:i,outWidth:u,dilationWidth:l,dilationHeight:c,dataFormat:d}=n,{left:p,top:h}=i,f=a*r,m=Ur(),g="channelsLast"===d,y=g?0:1,b=g?1:2;let x="";for(let n=0;n<=1;n++)for(let r=0;r<=1;r++)x+=`\n          blockIndex = rc.y + ${r};\n          pos = rc.x + ${n};\n\n          if(blockIndex < ${e[1]} && pos < ${e[0]}) {\n            offsetY = int(blockIndex / (${u})) * ${o} - ${h};\n            d0 = offsetY + ${c} * (pos / ${f});\n\n            if(d0 < ${t[y]} && d0 >= 0) {\n\n              offsetX = int(mod(float(blockIndex), ${u}.) * ${s}. - ${p}.);\n              d1 = offsetX + ${l} * (int(mod(float(pos), ${f}.) / ${a}.));\n\n              if(d1 < ${t[b]} && d1 >= 0) {\n\n                ch = int(mod(float(pos), ${a}.));\n\n                if (${g}) {\n                  innerDims = vec2(d1, ch);\n                  result[${2*n+r}] = getChannel(\n                    getA(d0, int(innerDims.x),\n                    int(innerDims.y)), innerDims);\n                } else {\n                  innerDims = vec2(d0, d1);\n                  result[${2*n+r}] = getChannel(\n                    getA(ch, int(innerDims.x),\n                    int(innerDims.y)), innerDims);\n                }\n              }\n            }\n          }\n        `;this.userCode=`\n      void main() {\n        ivec2 rc = getOutputCoords();\n\n        vec4 result = vec4(0);\n\n        int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n        vec2 innerDims;\n\n        ${x}\n\n        ${m.output} = result;\n      }\n    `}}function $u({x:e,filter:t,convInfo:n,backend:r,bias:a=null,preluActivationWeights:s=null,leakyreluAlpha:o=0,activation:i=null}){const u=e.shape,l=r.texData.get(e.dataId),d=n.inChannels,p=u[0]*u[1]*u[2],h=n.outChannels,f="channelsLast"===n.dataFormat;let m;const g=[],y=(1===p||1===h)&&d>1e3,b=u[2]%2!=0&&!!l.isPacked;if(!y&&W().getBool("WEBGL_LAZILY_UNPACK")&&W().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&b){const d=f?u[0]*u[1]*(u[2]+1):u[0]*u[2]*(u[3]+1),p={dataId:e.dataId,shape:[1,d,n.inChannels],dtype:e.dtype},h=l.shape;l.shape=l.shape.slice(),l.shape[l.shape.length-2]++,c(Fr(l.shape,p.shape),()=>`packed reshape ${l.shape} to ${p.shape} isn't free`);const y=oi({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}});g.push(y);const b=bi({a:p,b:y,backend:r,transposeA:!1,transposeB:!1,bias:a,activation:i,preluActivationWeights:s,leakyreluAlpha:o}),x=r.texData.get(b.dataId);c(x.isPacked,()=>"batchMatMul result is expected to be packed"),l.shape=h,x.shape=n.outShape,m=Wo({inputs:{x:b},backend:r}),m.shape=n.outShape,g.push(b)}else{const l=oi({inputs:{x:e},backend:r,attrs:{shape:[1,f?u[0]*u[1]*u[2]:u[0]*u[2]*u[3],n.inChannels]}}),c=oi({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}}),d=bi({a:l,b:c,transposeA:!1,transposeB:!1,backend:r,bias:a,activation:i,preluActivationWeights:s,leakyreluAlpha:o});m=oi({inputs:{x:d},backend:r,attrs:{shape:n.outShape}}),g.push(l),g.push(c),g.push(d)}for(const e of g)r.disposeIntermediateTensorInfo(e);return m}function _u({x:e,filter:t,convInfo:n,backend:r,bias:a=null,preluActivationWeights:s=null,leakyreluAlpha:o=0,activation:i=null}){const{filterWidth:u,filterHeight:l,inChannels:c,outWidth:d,outHeight:p,dataFormat:f}=n,m="channelsLast"===f,g=u*l*c,y=p*d,b=[g,y],x=[],k=oi({inputs:{x:e},backend:r,attrs:{shape:e.shape.slice(1)}}),w=oi({inputs:{x:t},backend:r,attrs:{shape:[1,g,h(t.shape)/g]}});x.push(k),x.push(w);const v=new Eu(b,k.shape,n),I=r.runWebGLProgram(v,[k],"float32"),N=oi({inputs:{x:I},backend:r,attrs:{shape:[1,b[0],b[1]]}});x.push(I),x.push(N);const S=null!=a,C=null!=s,T="leakyrelu"===i,E=i?Jo(i,!0):null,$=new Zo(N.shape,w.shape,[1,y,n.outChannels],!0,!1,S,E,C,T),_=[N,w];if(a&&_.push(a),C&&_.push(s),T){const e=r.makeTensorInfo([],"float32",J(o,"float32"));_.push(e),x.push(e)}const A=r.runWebGLProgram($,_,"float32"),R=oi({inputs:{x:A},backend:r,attrs:{shape:m?[1,p,d,n.outChannels]:[1,n.outChannels,p,d]}});x.push(A);for(const e of x)r.disposeIntermediateTensorInfo(e);return R}const Au={kernelName:"Conv2D",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dataFormat:u,dilations:l,dimRoundingMode:c}=r,d=Kt(u),p=Bt(a.shape,s.shape,o,l,i,c,!1,d);let h;if(1!==p.filterHeight||1!==p.filterWidth||1!==p.dilationHeight||1!==p.dilationWidth||1!==p.strideHeight||1!==p.strideWidth||"SAME"!==p.padInfo.type&&"VALID"!==p.padInfo.type)if(W().getBool("WEBGL_CONV_IM2COL")&&1===a.shape[0])h=_u({x:a,filter:s,convInfo:p,backend:n});else{const e=new Cu(p);h=n.runWebGLProgram(e,[a,s],"float32")}else h=$u({x:a,filter:s,convInfo:p,backend:n});const f=oi({inputs:{x:h},backend:n,attrs:{shape:p.outShape}});return n.disposeIntermediateTensorInfo(h),f}};class Ru{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,a=e.padInfo.left,s="channelsLast"===e.dataFormat;this.userCode=`\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int wR = coords.x;\n        int wC = coords.y;\n        int d1 = coords.z;\n        int d2 = coords.w;\n\n        // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n\n        for (int b = 0; b < ${e.batchSize}; b++) {\n          for (int yR = 0; yR < ${e.outHeight}; yR++) {\n            int xR = wR + yR * ${t} - ${r};\n\n            if (xR < 0 || xR >= ${e.inHeight}) {\n              continue;\n            }\n\n            for (int yC = 0; yC < ${e.outWidth}; yC++) {\n              int xC = wC + yC * ${n} - ${a};\n\n              if (xC < 0 || xC >= ${e.inWidth}) {\n                continue;\n              }\n\n              if (${s}) {\n                float dyValue = getDy(b, yR, yC, d2);\n                float xValue = getX(b, xR, xC, d1);\n                dotProd += (xValue * dyValue);\n              } else {\n                float dyValue = getDy(b, d2, yR, yC);\n                float xValue = getX(b, d1, xR, xC);\n                dotProd += (xValue * dyValue);\n              }\n\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    `}}class Mu{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,s="channelsLast"===e.dataFormat,o=t-1-e.padInfo.top,i=n-1-e.padInfo.left,u=s?1:2,l=s?2:3,c=s?3:1;this.userCode=`\n      const ivec2 pads = ivec2(${o}, ${i});\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d1 = coords[${c}];\n\n        ivec2 dyCorner = ivec2(coords[${u}], coords[${l}]) - pads;\n        int dyRCorner = dyCorner.x;\n        int dyCCorner = dyCorner.y;\n\n        // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < ${t}; wR++) {\n          float dyR = float(dyRCorner + wR) / ${r}.0;\n\n          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          int wRPerm = ${t} - 1 - wR;\n\n          for (int wC = 0; wC < ${n}; wC++) {\n            float dyC = float(dyCCorner + wC) / ${a}.0;\n\n            if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            int wCPerm = ${n} - 1 - wC;\n\n            for (int d2 = 0; d2 < ${e.outChannels}; d2++) {\n\n              if (${s}) {\n                float xValue = getDy(batch, idyR, idyC, d2);\n                float wValue = getW(wRPerm, wCPerm, d1, d2);\n                dotProd += xValue * wValue;\n              } else {\n                float xValue = getDy(batch, d2, idyR, idyC);\n                float wValue = getW(wRPerm, wCPerm, d1, d2);\n                dotProd += xValue * wValue;\n              }\n\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    `}}class Fu{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,a=e.padInfo.front,s=e.padInfo.top,o=e.padInfo.left;this.userCode=`\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int wF = coords.x;\n        int wR = coords.y;\n        int wC = coords.z;\n        int d1 = coords.w;\n        int d2 = coords.u;\n\n        float dotProd = 0.0;\n\n        for (int b = 0; b < ${e.batchSize}; b++) {\n          for (int yF = 0; yF < ${e.outDepth}; yF++) {\n            int xF = wF + yF * ${t} - ${a};\n\n            if (xF < 0 || xF >= ${e.inDepth}) {\n              continue;\n            }\n\n            for (int yR = 0; yR < ${e.outHeight}; yR++) {\n              int xR = wR + yR * ${n} - ${s};\n\n              if (xR < 0 || xR >= ${e.inHeight}) {\n                continue;\n              }\n\n              for (int yC = 0; yC < ${e.outWidth}; yC++) {\n                int xC = wC + yC * ${r} - ${o};\n\n                if (xC < 0 || xC >= ${e.inWidth}) {\n                  continue;\n                }\n\n                float dyValue = getDy(b, yF, yR, yC, d2);\n                float xValue = getX(b, xF, xR, xC, d1);\n                dotProd += (xValue * dyValue);\n              }\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    `}}class Du{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,a=e.strideDepth,s=e.strideHeight,o=e.strideWidth,i=t-1-e.padInfo.front,u=n-1-e.padInfo.top,l=r-1-e.padInfo.left;this.userCode=`\n      const ivec3 pads = ivec3(${i}, ${u}, ${l});\n\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int batch = coords.x;\n        int d1 = coords.u;\n\n\n        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n        int dyFCorner = dyCorner.x;\n        int dyRCorner = dyCorner.y;\n        int dyCCorner = dyCorner.z;\n\n        float dotProd = 0.0;\n        for (int wF = 0; wF < ${t}; wF++) {\n          float dyF = float(dyFCorner + wF) / ${a}.0;\n\n          if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {\n            continue;\n          }\n          int idyF = int(dyF);\n\n          int wFPerm = ${t} - 1 - wF;\n\n          for (int wR = 0; wR < ${n}; wR++) {\n            float dyR = float(dyRCorner + wR) / ${s}.0;\n\n            if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\n              fract(dyR) > 0.0) {\n              continue;\n            }\n            int idyR = int(dyR);\n\n            int wRPerm = ${n} - 1 - wR;\n\n            for (int wC = 0; wC < ${r}; wC++) {\n              float dyC = float(dyCCorner + wC) / ${o}.0;\n\n              if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n                  fract(dyC) > 0.0) {\n                continue;\n              }\n              int idyC = int(dyC);\n\n              int wCPerm = ${r} - 1 - wC;\n\n              for (int d2 = 0; d2 < ${e.outChannels}; d2++) {\n                float xValue = getDy(batch, idyF, idyR, idyC, d2);\n                float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n                dotProd += xValue * wValue;\n              }\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    `}}const Ou={kernelName:"Conv2DBackpropFilter",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,dy:s}=t,{strides:o,pad:i,dataFormat:u,dimRoundingMode:l,filterShape:c}=r,d=Kt(u),p=Bt(a.shape,c,o,1,i,l,!1,d),h=new Ru(p);return n.runWebGLProgram(h,[a,s],"float32")}};const Pu={kernelName:"Conv2DBackpropInput",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:s}=t,{inputShape:o,strides:i,pad:u,dataFormat:l,dimRoundingMode:c}=r,d=Kt(l),p=Bt(o,s.shape,i,1,u,c,!1,d),h=new Mu(p);return n.runWebGLProgram(h,[a,s],"float32")}};const Lu={kernelName:"Conv3D",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dilations:u}=r,l=Wt(a.shape,s.shape,o,u,i),c=new Tu(l);return n.runWebGLProgram(c,[a,s],"float32")}};const Bu={kernelName:"Conv3DBackpropFilterV2",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,dy:s}=t,{strides:o,pad:i,filterShape:u}=r,l=Wt(a.shape,u,o,1,i),c=new Fu(l);return n.runWebGLProgram(c,[a,s],"float32")}};const Wu={kernelName:"Conv3DBackpropInputV2",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:s}=t,{pad:o,strides:i,inputShape:u}=r,l=Wt(u,s.shape,i,1,o),c=new Du(l);return n.runWebGLProgram(c,[a,s],"float32")}},zu={kernelName:"Cos",backendName:"webgl",kernelFunc:Yo({opSnippet:"if (isnan(x)) return x;\n  return cos(x);\n"})},Vu={kernelName:"Cosh",backendName:"webgl",kernelFunc:Yo({opSnippet:"\n  float e2x = exp(-x);\n  return (e2x + 1.0 / e2x) / 2.0;\n"})};class Uu{constructor(e,t,n,r,a){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[s,o,i,u]=e,[l]=t,[c,d]=n;this.outputShape=[l,c,d,u];const p="bilinear"===r?1:0,[h,f]=[o-1+".0",i-1+".0"],[m,g,y]=c>1?[""+(o-1)/(c-1),"(y2-y1) * height_ratio",`y1*${h} + float(y)*(height_scale)`]:["0.0","0.0","0.5 * (y1+y2) * "+h],[b,x,k]=d>1?[""+(i-1)/(d-1),"(x2-x1) * width_ratio",`x1*${f} + float(x)*(width_scale)`]:["0.0","0.0","0.5 * (x1+x2) * "+f];this.userCode=`\n      const float height_ratio = float(${m});\n      const float width_ratio = float(${b});\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int y = coords[1];\n        int x = coords[2];\n        int d = coords[3];\n\n        // get box vals\n        float y1 = getBoxes(b,0);\n        float x1 = getBoxes(b,1);\n        float y2 = getBoxes(b,2);\n        float x2 = getBoxes(b,3);\n\n        // get image in batch index\n        int bInd = round(getBoxInd(b));\n        if(bInd < 0 || bInd >= ${s}) {\n          return;\n        }\n\n        float height_scale = ${g};\n        float width_scale = ${x};\n\n        float in_y = ${y};\n        if( in_y < 0.0 || in_y > ${h} ) {\n          setOutput(float(${a}));\n          return;\n        }\n        float in_x = ${k};\n        if( in_x < 0.0 || in_x > ${f} ) {\n          setOutput(float(${a}));\n          return;\n        }\n\n        vec2 sourceFracIndexCR = vec2(in_x,in_y);\n        if(${p} == 1) {\n          // Compute the four integer indices.\n          ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n          ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n          float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n          float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n          float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n          float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n          vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n          float top = topLeft + (topRight - topLeft) * fracCR.x;\n          float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n          float newValue = top + (bottom - top) * fracCR.y;\n          setOutput(newValue);\n        } else {\n          // Compute the coordinators of nearest neighbor point.\n          ivec2 sourceNearestCR = ivec2(floor(\n            sourceFracIndexCR + vec2(0.5,0.5)));\n          float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n          setOutput(newValue);\n        }\n      }\n    `}}const Gu={kernelName:"CropAndResize",backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{image:a,boxes:s,boxInd:o}=t,{cropSize:i,method:u,extrapolationValue:l}=r,c=new Uu(a.shape,s.shape,i,u,l);return n.runWebGLProgram(c,[a,s,o],"float32")}};class Hu{constructor(e,t,n){this.variableNames=["x"],this.outputShape=e;const r=e.length,a=t?"0.0":`getX(${ju(r,"coords")})`,s=e[e.length-1];let o="",i="";t?(o=n?"end != "+(s-1):"end != 0",i=n?"end + 1":"end - 1"):(o=n?"end + pow2 < "+s:"end >= pow2",i=n?"end + pow2":"end - pow2"),this.userCode=`\n      uniform float index;\n      void main() {\n        ${wa(r)} coords = getOutputCoords();\n        int end = ${qu(r,"coords")};\n        float val = ${a};\n        int pow2 = int(pow(2.0, index));\n        if (${o}) {\n          int idx = ${i};\n          ${qu(r,"coords")} = idx;\n          val += getX(${ju(r,"coords")});\n        }\n        setOutput(val);\n      }\n    `}getCustomSetupFunc(e){return(t,n)=>{null==this.index&&(this.index=t.getUniformLocation(n,"index")),t.gl.uniform1f(this.index,e)}}}function ju(e,t){if(1===e)return""+t;if(2===e)return`${t}.x, ${t}.y`;if(3===e)return`${t}.x, ${t}.y, ${t}.z`;if(4===e)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw Error(`Cumulative sum for rank ${e} is not yet supported`)}function qu(e,t){if(1===e)return""+t;if(2===e)return t+".y";if(3===e)return t+".z";if(4===e)return t+".w";throw Error(`Cumulative sum for rank ${e} is not yet supported`)}const Ku={kernelName:"Cumsum",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,exclusive:o,reverse:i}=r,u=a.shape.length,l=un([s],u);let c=a;null!=l&&(c=gi({inputs:{x:a},backend:n,attrs:{perm:l}}));const d=cn(1,u)[0];if(d!==u-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${a.shape.length-1} but got axis=`+s);const p=c.shape[d];let h=Wo({inputs:{x:c},backend:n});for(let e=0;e<=Math.ceil(Math.log2(p))-1;e++){const t=new Hu(c.shape,!1,i),r=t.getCustomSetupFunc(e),a=h;h=n.runWebGLProgram(t,[h],h.dtype,r),n.disposeIntermediateTensorInfo(a)}if(o){const e=new Hu(c.shape,o,i),t=h;h=n.runWebGLProgram(e,[h],h.dtype),n.disposeIntermediateTensorInfo(t)}if(null!=l){const e=gi({inputs:{x:h},backend:n,attrs:{perm:ln(l)}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(c),e}return h}};const Xu={kernelName:"DenseBincount",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,weights:s}=t,{size:o,binaryOutput:i}=r;if(1===a.shape.length){const e=n.readSync(a.dataId),t=n.readSync(s.dataId),r=qs(e,t,s.dtype,s.shape,o);return n.makeTensorInfo([o],s.dtype,r)}if(2===a.shape.length){const e=n.bufferSync(a),t=n.bufferSync(s),r=Ks(e,t,o,i);return n.makeTensorInfo(r.shape,s.dtype,r.values)}throw new Error("Error in denseBincount: input must be at most rank 2, but got rank"+a.shape.length+".")}};class Yu{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode=`\n    void main() {\n      ivec4 coords = getOutputCoords();\n      int b = coords[0];\n      int h = ${this.getHeightCoordString()};\n      int w = ${this.getWidthCoordString()};\n      int d = ${this.getDepthCoordString()};\n\n      int in_h = h / ${t};\n      int offset_h = imod(h, ${t});\n      int in_w = w / ${t};\n      int offset_w = imod(w, ${t});\n      int offset_d = (offset_h * ${t} + offset_w) *\n        ${this.getOutputDepthSize()};\n      int in_d = d + offset_d;\n\n      float result = ${this.getInputSamplingString()};\n      setOutput(result);\n    }\n  `}getHeightCoordString(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"}getWidthCoordString(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"}getDepthCoordString(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"}getOutputDepthSize(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}}const Qu={kernelName:"DepthToSpace",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockSize:s,dataFormat:o}=r;c(s>1,()=>"blockSize should be > 1 for depthToSpace, but was: "+s);const i=a.shape[0],u="NHWC"===o?a.shape[1]:a.shape[2],l="NHWC"===o?a.shape[2]:a.shape[3],d="NHWC"===o?a.shape[3]:a.shape[1],p=u*s,h=l*s,f=d/(s*s),m=new Yu("NHWC"===o?[i,p,h,f]:[i,f,p,h],s,o);return n.runWebGLProgram(m,[a],a.dtype)}};class Ju{constructor(e,t=!1,n=null,r=!1,a=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const s=e.inHeight,o=e.inWidth,i=e.padInfo.top,u=e.padInfo.left,l=e.strideHeight,c=e.strideWidth,d=e.dilationHeight,p=e.dilationWidth,h=e.filterHeight,f=e.filterWidth,m=e.outChannels/e.inChannels;let g="",y="";n&&(g=r?`float activation(float a) {\n          float b = getPreluActivationWeightsAtOutCoords();\n          ${n}\n        }`:a?`float activation(float a) {\n          float b = getLeakyreluAlphaAtOutCoords();\n          ${n}\n        }`:`\n          float activation(float x) {\n            ${n}\n          }\n        `,y="result = activation(result);");const b=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n      ${g}\n\n      const ivec2 strides = ivec2(${l}, ${c});\n      const ivec2 pads = ivec2(${i}, ${u});\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords.x;\n        ivec2 xRCCorner = coords.yz * strides - pads;\n        int d2 = coords.w;\n        int d1 = d2 / ${m};\n        int q = d2 - d1 * ${m};\n\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n        for (int wR = 0; wR < ${h}; wR++) {\n          int xR = xRCorner + wR * ${d};\n\n          if (xR < 0 || xR >= ${s}) {\n            continue;\n          }\n\n          for (int wC = 0; wC < ${f}; wC++) {\n            int xC = xCCorner + wC * ${p};\n\n            if (xC < 0 || xC >= ${o}) {\n              continue;\n            }\n\n            float xVal = getX(batch, xR, xC, d1);\n            float wVal = getW(wR, wC, d1, q);\n            dotProd += xVal * wVal;\n          }\n        }\n\n        float result = dotProd;\n        ${b}\n        ${y}\n        setOutput(result);\n      }\n    `}}class Zu{constructor(e,t=!1,n=null,r=!1,a=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.outShape;const s=e.inHeight,o=e.inWidth,i=e.padInfo.top,u=e.padInfo.left,c=e.strideHeight,d=e.strideWidth,p=e.dilationHeight,h=e.dilationWidth,f=e.filterHeight,m=e.filterWidth,g=m;let y="int xR; int xC; int xCOffset;";for(let e=0;e<f;e++)for(let t=0;t<m;t++)y+=`\n          vec4 xTexelR${e}C${2*t} = vec4(0.);\n          vec4 wR${e}C${t} = vec4(0.);\n          vec4 xR${e}C${t} = vec4(0.);`;for(let e=0;e<f;e++)for(let t=0;t<g;t++){const n=2*t;if(y+=`\n          xR = xRCorner + ${e*p};\n          xC = xCCorner + ${n*h};\n        `,1===d){if(n<m&&(y+=u%2==1?`\n                xCOffset = xC + 1;\n                if(xR >= 0 && xR < ${s} && xCOffset >= 0 && xCOffset < ${o}) {\n                  xTexelR${e}C${n} = getX(batch, xR, xCOffset, d1);\n\n                  // Need to manually clear unused channels in case\n                  // we're reading from recycled texture.\n                  if(xCOffset + 1 >= ${o}) {\n                    xTexelR${e}C${n}.zw = vec2(0.);\n                  }\n                } else {\n                  xTexelR${e}C${n} = vec4(0.);\n                }\n\n                xCOffset = xC + 1 - 2;\n                if(xR >= 0 && xR < ${s} && xCOffset >= 0 && xCOffset < ${o}) {\n                  vec4 previous = getX(batch, xR, xCOffset, d1);\n\n                  // Need to manually clear unused channels in case\n                  // we're reading from recycled texture.\n                  if(xCOffset + 1 >= ${o}) {\n                    previous.zw = vec2(0.);\n                  }\n\n                  xR${e}C${n} = vec4(previous.zw, xTexelR${e}C${n}.xy);\n                } else {\n                  xR${e}C${n} = vec4(0, 0, xTexelR${e}C${n}.xy);\n                }\n              `:`\n                if(xR >= 0 && xR < ${s} && xC >= 0 && xC < ${o}) {\n                  xTexelR${e}C${n} = getX(batch, xR, xC, d1);\n                } else {\n                  xTexelR${e}C${n} = vec4(0.);\n                }\n\n                xR${e}C${n} = xTexelR${e}C${n};\n              `,n+1<m)){const t=u%2==0?l(h):h;h%2==0&&u%2==1||h%2!=0&&u%2!=1?(y+=`\n                  xCOffset = xC + ${u%2} + ${t};\n\n                  if(xR >= 0 && xR < ${s} &&\n                    xCOffset >= 0 && xCOffset < ${o}) {\n                    xTexelR${e}C${n+2} = getX(batch, xR, xCOffset, d1);\n                  }\n                `,h>1&&(y+=`\n                    xCOffset -= 2;\n                    if(xR >= 0 && xR < ${s} &&\n                      xCOffset >= 0 && xCOffset < ${o}) {\n                      xTexelR${e}C${n} = getX(batch, xR, xCOffset, d1);\n                    } else {\n                      xTexelR${e}C${n} = vec4(0.);\n                    }\n                  `),y+=`\n                  xR${e}C${n+1} = vec4(\n                    xTexelR${e}C${n}.zw, xTexelR${e}C${n+2}.xy);\n                `):y+=`\n                  xCOffset = xC + ${t};\n\n                  if(xR >= 0 && xR < ${s} &&\n                    xCOffset >= 0 && xCOffset < ${o}) {\n                    xTexelR${e}C${n+2} = getX(batch, xR, xCOffset, d1);\n                  }\n\n                  xR${e}C${n+1} = xTexelR${e}C${n+2};\n                `}}else n<m&&(y+=`\n              if(xR >= 0 && xR < ${s}) {\n            `,u%2==1?(y+=`\n                xCOffset = xC + 1 - ${d};\n                if(xCOffset >= 0 && xCOffset < ${o}) {\n                  xTexelR${e}C${n} = getX(batch, xR, xCOffset, d1);\n                } else {\n                  xTexelR${e}C${n} = vec4(0.);\n                }\n\n                if(xC + 1 >= 0 && xC + 1 < ${o}) {\n                  xTexelR${e}C${n+2} = getX(batch, xR, xC + 1, d1);\n                } else {\n                  xTexelR${e}C${n+2} = vec4(0.);\n                }\n\n                xR${e}C${n} = vec4(\n                  xTexelR${e}C${n}.zw, xTexelR${e}C${n+2}.zw);\n              `,n+1<m&&(y+=`\n                  vec4 final = vec4(0.);\n                  xCOffset = xC + 1 + ${d};\n                  if(xCOffset >= 0 && xCOffset < ${o}) {\n                    final = getX(batch, xR, xCOffset, d1);\n                  }\n                  xR${e}C${n+1} = vec4(xTexelR${e}C${n+2}.xy, final.xy);\n                `)):(y+=`\n                if(xC >= 0 && xC < ${o}) {\n                  xTexelR${e}C${n} = getX(batch, xR, xC, d1);\n                } else {\n                  xTexelR${e}C${n} = vec4(0.);\n                }\n\n                xCOffset = xC + ${d};\n                if(xCOffset >= 0 && xCOffset < ${o}) {\n                  xTexelR${e}C${n+2} = getX(batch, xR, xCOffset, d1);\n                } else {\n                  xTexelR${e}C${n+2} = vec4(0.);\n                }\n\n                xR${e}C${n} = vec4(\n                  xTexelR${e}C${n}.xy, xTexelR${e}C${n+2}.xy);\n              `,n+1<m&&(y+=`\n                  xR${e}C${n+1} = vec4(\n                    xTexelR${e}C${n}.zw, xTexelR${e}C${n+2}.zw);\n                `)),y+="}");n<m&&(y+=`\n            vec4 wTexelR${e}C${n} = getW(${e}, ${n}, d1, q);\n            wR${e}C${n} = vec4(wTexelR${e}C${n}.xz, wTexelR${e}C${n}.xz);\n          `,n+1<m&&(y+=`\n              vec4 wTexelR${e}C${n+1} = getW(${e}, ${n+1}, d1, q);\n              wR${e}C${n+1} =\n                vec4(wTexelR${e}C${n+1}.xz, wTexelR${e}C${n+1}.xz);`))}for(let e=0;e<f;e++)for(let t=0;t<m;t++)y+=`dotProd += xR${e}C${t} * wR${e}C${t};`;let b="",x="";n&&(b=r?`vec4 activation(vec4 a) {\n          vec4 b = getPreluActivationWeightsAtOutCoords();\n          ${n}\n        }`:a?`vec4 activation(vec4 a) {\n          vec4 b = getLeakyreluAlphaAtOutCoords();\n          ${n}\n        }`:`vec4 activation(vec4 x) {\n          ${n}\n        }`,x="result = activation(result);");const k=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n      ${b}\n\n      const ivec2 strides = ivec2(${c}, ${d});\n      const ivec2 pads = ivec2(${i}, ${u});\n\n      void main() {\n\n        ivec4 coords = getOutputCoords();\n        int batch = coords.x;\n        ivec2 xRCCorner = coords.yz * strides - pads;\n        int d2 = coords.w;\n        int d1 = d2;\n        int q = 0;\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        vec4 dotProd = vec4(0.);\n\n        ${y}\n\n        vec4 result = dotProd;\n        ${k}\n        ${x}\n        setOutput(result);\n      }\n    `}}const el={kernelName:"DepthwiseConv2dNative",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dilations:u,dimRoundingMode:l}=r;let d=u;null==d&&(d=[1,1]),c(qt(o,d),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${d}'`);const p=Bt(a.shape,s.shape,o,d,i,l,!0);let h;return h=W().getBool("WEBGL_PACK_DEPTHWISECONV")&&p.strideWidth<=2&&p.outChannels/p.inChannels==1?new Zu(p):new Ju(p),n.runWebGLProgram(h,[a,s],"float32")}};class tl{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,a=e.padInfo.left,s=e.outChannels/e.inChannels;this.userCode=`\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int wR = coords.x;\n        int wC = coords.y;\n        int d1 = coords.z;\n        int dm = coords.w;\n        int d2 = d1 * ${s} + dm;\n\n        float dotProd = 0.0;\n\n        // TO DO: Vec4 over the batch size\n        for (int b = 0; b < ${e.batchSize}; b++) {\n          for (int yR = 0; yR < ${e.outHeight}; yR++) {\n            int xR = wR + yR * ${t} - ${r};\n\n            if (xR < 0 || xR >= ${e.inHeight}) {\n              continue;\n            }\n\n            for (int yC = 0; yC < ${e.outWidth}; yC++) {\n              int xC = wC + yC * ${n} - ${a};\n\n              if (xC < 0 || xC >= ${e.inWidth}) {\n                continue;\n              }\n\n              float dyValue = getDy(b, yR, yC, d2);\n              float xValue = getX(b, xR, xC, d1);\n              dotProd += (xValue * dyValue);\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    `}}class nl{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,a=e.strideWidth,s=t-1-e.padInfo.top,o=n-1-e.padInfo.left,i=e.outChannels/e.inChannels;this.userCode=`\n      const ivec2 pads = ivec2(${s}, ${o});\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d1 = coords[3];\n        ivec2 dyCorner = coords.yz - pads;\n        int dyRCorner = dyCorner.x;\n        int dyCCorner = dyCorner.y;\n\n        float dotProd = 0.0;\n\n        for (int wR = 0; wR < ${t}; wR++) {\n          float dyR = float(dyRCorner + wR) / ${r}.0;\n\n          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          int wRPerm = ${t} - 1 - wR;\n\n          for (int wC = 0; wC < ${n}; wC++) {\n            float dyC = float(dyCCorner + wC) / ${a}.0;\n\n            if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            int wCPerm = ${n} - 1 - wC;\n\n            // TO DO: Vec4 over the channelMul\n            for (int dm = 0; dm < ${i}; dm++) {\n              int d2 = d1 * ${i} + dm;\n              float xValue = getDy(batch, idyR, idyC, d2);\n              float wValue = getW(wRPerm, wCPerm, d1, dm);\n              dotProd += xValue * wValue;\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    `}}const rl={kernelName:"DepthwiseConv2dNativeBackpropFilter",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,dy:s}=t,{strides:o,dilations:i,pad:u,dimRoundingMode:l,filterShape:c}=r,d=Bt(a.shape,c,o,i,u,l,!0),p=new tl(d);return n.runWebGLProgram(p,[a,s],"float32")}};const al={kernelName:"DepthwiseConv2dNativeBackpropInput",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:s}=t,{strides:o,dilations:i,pad:u,dimRoundingMode:l,inputShape:c}=r,d=Bt(c,s.shape,o,i,u,l,!0),p=new nl(d);return n.runWebGLProgram(p,[a,s],"float32")}};class sl{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode="\n      void main() {\n          ivec2 coords = getOutputCoords();\n          float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\n          setOutput(val);\n      }\n    "}}const ol={kernelName:"Diag",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t,a=[...r.shape,...r.shape],s=h(r.shape),o=oi({inputs:{x:r},backend:n,attrs:{shape:[s]}}),i=new sl(s),u=n.runWebGLProgram(i,[o],o.dtype),l=oi({inputs:{x:u},backend:n,attrs:{shape:a}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(u),l}};class il{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const{inHeight:t,inWidth:n,padInfo:r,strideHeight:a,strideWidth:s,filterHeight:o,filterWidth:i,dilationHeight:u,dilationWidth:l}=e,{top:c,left:d}=r;this.userCode=`\n      const ivec2 strides = ivec2(${a}, ${s});\n      const ivec2 pads = ivec2(${c}, ${d});\n      const float neg_infinity = -3.4e38;\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords.x;\n        int d1 = coords.w;\n        ivec2 outTopLeftCorner =\n            coords.yz * strides - pads;\n        int hBeg = outTopLeftCorner.x;\n        int wBeg = outTopLeftCorner.y;\n\n        float curVal = neg_infinity;\n        for (int h = 0; h < ${o}; h++) {\n          int hIn = hBeg + h * ${u};\n\n          if (hIn >= 0 && hIn < ${t}) {\n            for (int w = 0; w < ${i}; w++) {\n              int wIn = wBeg + w * ${l};\n\n              if (wIn >= 0 && wIn < ${n}) {\n                float xVal = getX(batch, hIn, wIn, d1);\n                float wVal = getW(h, w, d1);\n\n                float val = xVal + wVal;\n                if (val > curVal) {\n                  curVal = val;\n                }\n              }\n            }\n          }\n        }\n\n        float result = curVal;\n        setOutput(result);\n      }\n    `}}const ul={kernelName:"Dilation2D",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dilations:u}=r,l=Ot(a.shape,s.shape,o,i,"NHWC",u);let c;const d=new il(l);c=n.runWebGLProgram(d,[a,s],"float32");const p=oi({inputs:{x:c},backend:n,attrs:{shape:l.outShape}});return n.disposeIntermediateTensorInfo(c),p}},ll={kernelName:"Elu",backendName:"webgl",kernelFunc:Yo({opSnippet:"return (x >= 0.0) ? x : (exp(x) - 1.0);",packedOpSnippet:"\n  vec4 result;\n\n  result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n  result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n  result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n  result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n  return result;\n"})},cl={kernelName:"EluGrad",backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n}=e,{dy:r,y:a}=t,s=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bo("\n  vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n  return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",r.shape,a.shape):new Lo("return (b >= 1.0) ? a : a * (b + 1.0);",r.shape,a.shape);return n.runWebGLProgram(s,[r,a],r.dtype)}},dl={kernelName:"Equal",backendName:"webgl",kernelFunc:Qo({opSnippet:"return float(a == b);",packedOpSnippet:"\n  return vec4(equal(a, b));\n",dtype:"bool"})},pl={kernelName:"Erf",backendName:"webgl",kernelFunc:Yo({opSnippet:'\n  // Error function is calculated approximately with elementary function.\n  // See "Handbook of Mathematical Functions with Formulas,\n  // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n  float p = 0.3275911;\n  float a1 = 0.254829592;\n  float a2 = -0.284496736;\n  float a3 = 1.421413741;\n  float a4 = -1.453152027;\n  float a5 = 1.061405429;\n\n  float sign = sign(x);\n  x = abs(x);\n  float t = 1.0 / (1.0 + p * x);\n  return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));\n'})},hl="return exp(x);",fl=Yo({opSnippet:hl,packedOpSnippet:hl,cpuKernelImpl:Qs}),ml={kernelName:"Exp",backendName:"webgl",kernelFunc:fl};function gl(e){const{inputs:t,attrs:n,backend:r}=e,{dim:a}=n,{input:s}=t,o=s.shape.length,i=s.shape.slice();let u=a;return a<0&&(c(-(o+1)<=a,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),u=o+a+1),i.splice(u,0,1),oi({inputs:{x:s},backend:r,attrs:{shape:i}})}const yl={kernelName:"ExpandDims",backendName:"webgl",kernelFunc:gl},bl="return exp(x) - 1.0;",xl={kernelName:"Expm1",backendName:"webgl",kernelFunc:Yo({opSnippet:bl,packedOpSnippet:bl,cpuKernelImpl:Js})};class kl{constructor(e,t,n){this.variableNames=["real","imag"];const r=t[1];this.outputShape=t;const a=n?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,s=n?r+".0":"1.0";let o;if("real"===e)o="return real * expR - imag * expI;";else{if("imag"!==e)throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);o="return real * expI + imag * expR;"}this.userCode=`\n      const float exponentMultiplier = ${a};\n\n      float unaryOpComplex(float real, float expR, float imag, float expI) {\n        ${o}\n      }\n\n      float mulMatDFT(int batch, int index) {\n        float indexRatio = float(index) / float(${r});\n        float exponentMultiplierTimesIndexRatio =\n            exponentMultiplier * indexRatio;\n\n        float result = 0.0;\n\n        for (int i = 0; i < ${r}; i++) {\n          // x = (-2|2 * PI / N) * index * i;\n          float x = exponentMultiplierTimesIndexRatio * float(i);\n          float expR = cos(x);\n          float expI = sin(x);\n          float real = getReal(batch, i);\n          float imag = getImag(batch, i);\n\n          result +=\n              unaryOpComplex(real, expR, imag, expI) / ${s};\n        }\n\n        return result;\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        setOutput(mulMatDFT(coords[0], coords[1]));\n      }\n    `}}function wl(e,t,n){const r=n.texData.get(e.dataId),a=h(e.shape),s=e.shape[e.shape.length-1],o=oi({inputs:{x:e},backend:n,attrs:{shape:[a/s,s]}}),i=o.shape,u=new kl("real",i,t),l=new kl("imag",i,t),c=[{dataId:r.complexTensorInfos.real.dataId,dtype:r.complexTensorInfos.real.dtype,shape:i},{dataId:r.complexTensorInfos.imag.dataId,dtype:r.complexTensorInfos.imag.dtype,shape:i}],d=n.runWebGLProgram(u,c,"float32"),p=n.runWebGLProgram(l,c,"float32"),f=Vo({inputs:{real:d,imag:p},backend:n});n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p);const m=oi({inputs:{x:f},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(f),m}const vl={kernelName:"FFT",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:r}=t;return wl(r,!1,n)}};class Il{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.outputShape=e,this.userCode="\n      uniform float value;\n      void main() {\n        // Input can be obtained from uniform value.\n        setOutput(value);\n      }\n    "}getCustomSetupFunc(e){return(t,n)=>{null==this.valueLoc&&(this.valueLoc=t.getUniformLocationNoThrow(n,"value")),t.gl.uniform1f(this.valueLoc,e)}}}function Nl(e){const{backend:t,attrs:n}=e,{shape:r,value:a}=n;let{dtype:s}=n;if(s=s||E(a),"string"===s){const e=I(s,h(r));return e.fill(a),t.makeTensorInfo(r,s,e)}{const e=new Il(r,a),n=e.getCustomSetupFunc(a);return t.runWebGLProgram(e,[],s,n)}}const Sl={kernelName:"Fill",backendName:"webgl",kernelFunc:Nl};class Cl{constructor(e){this.variableNames=["Image"],this.outputShape=[];const t=e[2];this.outputShape=e,this.userCode=`\n        void main() {\n          ivec4 coords = getOutputCoords();\n          int x = coords[2];\n\n          int coordX = ${t} - x;\n          float outputValue;\n          if(coordX >= 0 && coordX < ${t}) {\n            outputValue = getImage(coords[0], coords[1], coordX, coords[3]);\n          } else {\n            outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);\n          }\n          setOutput(outputValue);\n        }\n    `}}const Tl={kernelName:"FlipLeftRight",backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:n}=e,r=t,a=new Cl(n.shape);return r.runWebGLProgram(a,[n],n.dtype)}},El="return floor(x);",$l={kernelName:"Floor",backendName:"webgl",kernelFunc:Yo({opSnippet:El,packedOpSnippet:El,cpuKernelImpl:Zs})},_l={kernelName:"FloorDiv",backendName:"webgl",kernelFunc:Qo({opSnippet:"\n  float s = sign(a) * sign(b);\n  int ia = round(a);\n  int ib = round(b);\n  if (ib != 0) {\n    // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n    return float(idiv(ia, ib, s));\n  } else {\n    return NAN;\n  }\n",packedOpSnippet:"\n  ivec4 ia = round(a);\n  ivec4 ib = round(b);\n  bvec4 cond = notEqual(ib, ivec4(0));\n  ivec4 result = ivec4(0);\n  vec4 s = sign(a) * sign(b);\n\n  // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n  if (cond[0]) {\n    result[0] = idiv(ia[0], ib[0], s[0]);\n  }\n  if (cond[1]) {\n    result[1] = idiv(ia[1], ib[1], s[1]);\n  }\n  if (cond[2]) {\n    result[2] = idiv(ia[2], ib[2], s[2]);\n  }\n  if (cond[3]) {\n    result[3] = idiv(ia[3], ib[3], s[3]);\n  }\n  return vec4(result);\n",dtype:"int32"})};class Al{constructor(e){this.variableNames=["A"];const t=Ur(),[n,r]=e;this.outputShape=e,this.userCode=`\n      void main() {\n        ivec3 coords = getOutputCoords();\n        int texR = coords[0];\n        int texC = coords[1];\n        int depth = coords[2];\n        vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}.0, ${n}.0);\n\n        vec4 values = ${t.texture2D}(A, uv);\n        float value;\n        if (depth == 0) {\n          value = values.r;\n        } else if (depth == 1) {\n          value = values.g;\n        } else if (depth == 2) {\n          value = values.b;\n        } else if (depth == 3) {\n          value = values.a;\n        }\n\n        setOutput(floor(value * 255.0 + 0.5));\n      }\n    `}}class Rl{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=Ur(),[n,r]=e;this.outputShape=e,this.userCode=`\n      void main() {\n        ivec3 coords = getOutputCoords();\n        int texR = coords[0];\n        int texC = coords[1];\n        int depth = coords[2];\n\n        vec4 result = vec4(0.);\n\n        for(int row=0; row<=1; row++) {\n          for(int col=0; col<=1; col++) {\n            texC = coords[1] + row;\n            depth = coords[2] + col;\n\n            vec2 uv = (vec2(texC, texR) + halfCR) /\n                       vec2(${r}.0, ${n}.0);\n            vec4 values = ${t.texture2D}(A, uv);\n            float value;\n            if (depth == 0) {\n              value = values.r;\n            } else if (depth == 1) {\n              value = values.g;\n            } else if (depth == 2) {\n              value = values.b;\n            } else if (depth == 3) {\n              value = values.a;\n            }\n\n            result[row * 2 + col] = floor(value * 255.0 + 0.5);\n          }\n        }\n\n        ${t.output} = result;\n      }\n    `}}const Ml={kernelName:"FromPixels",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e;let{pixels:a}=t;const{numChannels:s}=r,o="undefined"!=typeof HTMLVideoElement&&a instanceof HTMLVideoElement,i="undefined"!=typeof HTMLImageElement&&a instanceof HTMLImageElement,[u,l]=o?[a.videoWidth,a.videoHeight]:[a.width,a.height],c=[l,u],d=[l,u,s];(i||o)&&(null==Fl&&(Fl=document.createElement("canvas").getContext("2d")),Fl.canvas.width=u,Fl.canvas.height=l,Fl.drawImage(a,0,0,u,l),a=Fl.canvas);const p=n.makeTensorInfo(c,"int32");n.texData.get(p.dataId).usage=pr.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),a);const h=W().getBool("WEBGL_PACK")?new Rl(d):new Al(d),f=n.runWebGLProgram(h,[p],"int32");return n.disposeData(p.dataId),f}};let Fl;const Dl={kernelName:"FusedConv2D",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s,bias:o,preluActivationWeights:i}=t,{strides:u,pad:l,dataFormat:c,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=r,m=Kt(c),g=Bt(a.shape,s.shape,u,d,l,p,!1,m);let y;const b=[];if(1!==g.filterHeight||1!==g.filterWidth||1!==g.dilationHeight||1!==g.dilationWidth||1!==g.strideHeight||1!==g.strideWidth||"SAME"!==g.padInfo.type&&"VALID"!==g.padInfo.type)if(W().getBool("WEBGL_CONV_IM2COL")&&1===a.shape[0])y=_u({x:a,filter:s,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else{const e=null!=o,t=null!=i,r="leakyrelu"===h,u=h?Jo(h,!1):null,l=new Cu(g,e,u,t,r),c=[a,s];if(o&&c.push(o),i&&c.push(i),r){const e=n.makeTensorInfo([],"float32",J(f,"float32"));c.push(e),b.push(e)}y=n.runWebGLProgram(l,c,"float32")}else y=$u({x:a,filter:s,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});const x=oi({inputs:{x:y},backend:n,attrs:{shape:g.outShape}});return b.push(y),b.forEach(e=>n.disposeIntermediateTensorInfo(e)),x}};const Ol={kernelName:"FusedDepthwiseConv2D",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s,bias:o,preluActivationWeights:i}=t,{strides:u,pad:l,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=r,m=[];let g=d;null==g&&(g=[1,1]),c(qt(u,g),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${u} and dilations '${g}'`);const y=Bt(a.shape,s.shape,u,g,l,p,!0),b=W().getBool("WEBGL_PACK_DEPTHWISECONV")&&y.strideWidth<=2&&y.outChannels/y.inChannels==1,x=h?Jo(h,b):null,k=[a,s],w=null!=o,v=null!=i,I="leakyrelu"===h;if(w&&k.push(o),v&&k.push(i),I){const e=n.makeTensorInfo([],"float32",J(f,"float32"));k.push(e),m.push(e)}let N;N=b?new Zu(y,w,x,v,I):new Ju(y,w,x,v,I);const S=n.runWebGLProgram(N,k,"float32");return m.forEach(e=>n.disposeIntermediateTensorInfo(e)),S}};class Pl{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;const r=wa(t.length),a=wa(n.length),s=this.sliceDim>1?"strides[j]":"strides";this.userCode=`\n        ${r} strides = ${r}(${this.strides});\n         void main() {\n          ${a} coords = getOutputCoords();\n          int flattenIndex = 0;\n          for (int j = 0; j < ${this.sliceDim}; j++) {\n            int index = round(getIndices(coords[0], j));\n            flattenIndex += index * ${s};\n          }\n          setOutput(getX(flattenIndex, coords[1]));\n        }\n      `}}const Ll={kernelName:"GatherNd",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{params:r,indices:a}=t,s=a.shape,o=s[s.length-1],[i,u,l,c]=pt(r,a),d=oi({inputs:{x:a},backend:n,attrs:{shape:[u,o]}}),p=oi({inputs:{x:r},backend:n,attrs:{shape:[h(r.shape)/l,l]}}),f=new Pl(o,c,[u,l]),m=n.runWebGLProgram(f,[p,d],p.dtype),g=oi({inputs:{x:m},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(m),g}};class Bl{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;const n=wa(this.rank),r=function(e,t){const n=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[];for(let t=0;t<e.length;t++)2===t?r.push("int(getIndices(resRC.x, resRC.z))"):r.push(""+n[t]);return r.join()}(e);this.userCode=`\n      void main() {\n        ${n} resRC = getOutputCoords();\n        setOutput(getA(${r}));\n      }\n    `}}const Wl={kernelName:"GatherV2",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,indices:s}=t,{axis:o,batchDims:i}=r,u=rr(a,s,k(o,a.shape)[0],i),l=h(s.shape),c=[],d=oi({inputs:{x:a},backend:n,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),p=oi({inputs:{x:s},backend:n,attrs:{shape:[u.batchSize,l/u.batchSize]}});c.push(d),c.push(p);const f=[u.batchSize,u.outerSize,l/u.batchSize,u.sliceSize];if(n.shouldExecuteOnCPU([a,s])||"string"===a.dtype){const e=n.bufferSync(p),t=n.bufferSync(d),r=eo(t,e,f);return c.forEach(e=>n.disposeIntermediateTensorInfo(e)),n.makeTensorInfo(u.outputShape,r.dtype,r.values)}const m=new Bl(d.shape,f),g=n.runWebGLProgram(m,[d,p],d.dtype);c.push(g);const y=oi({inputs:{x:g},backend:n,attrs:{shape:u.outputShape}});return c.forEach(e=>n.disposeIntermediateTensorInfo(e)),y}},zl={kernelName:"Greater",backendName:"webgl",kernelFunc:Qo({opSnippet:"return float(a > b);",packedOpSnippet:"\n  return vec4(greaterThan(a, b));\n",cpuKernelImpl:to,dtype:"bool"})},Vl={kernelName:"GreaterEqual",backendName:"webgl",kernelFunc:Qo({opSnippet:"return float(a >= b);",packedOpSnippet:"\n  return vec4(greaterThanEqual(a, b));\n",dtype:"bool"})};const Ul={kernelName:"IFFT",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:r}=t;return wl(r,!0,n)}},Gl={kernelName:"IsFinite",backendName:"webgl",kernelFunc:Yo({opSnippet:"return float(!isnan(x) && !isinf(x));",dtype:"bool"})},Hl={kernelName:"IsInf",backendName:"webgl",kernelFunc:Yo({opSnippet:"return float(isinf(x));",dtype:"bool"})},jl={kernelName:"IsNan",backendName:"webgl",kernelFunc:Yo({opSnippet:"return float(isnan(x));",dtype:"bool"})},ql={kernelName:"Less",backendName:"webgl",kernelFunc:Qo({opSnippet:"return float(a < b);",packedOpSnippet:"\n  return vec4(lessThan(a, b));\n",cpuKernelImpl:no,dtype:"bool"})},Kl={kernelName:"LessEqual",backendName:"webgl",kernelFunc:Qo({opSnippet:"return float(a <= b);",packedOpSnippet:"\n  return vec4(lessThanEqual(a, b));\n",dtype:"bool"})};const Xl={kernelName:"LinSpace",backendName:"webgl",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:r,stop:a,num:s}=n,o=ro(r,a,s);return t.makeTensorInfo([o.length],"float32",o)}},Yl={kernelName:"Log",backendName:"webgl",kernelFunc:Yo({opSnippet:"if (x < 0.0) return NAN;\n  return log(x);",packedOpSnippet:"\n  vec4 result = log(x);\n  vec4 isNaN = vec4(lessThan(x, vec4(0.0)));\n  result.r = isNaN.r == 1.0 ? NAN : result.r;\n  result.g = isNaN.g == 1.0 ? NAN : result.g;\n  result.b = isNaN.b == 1.0 ? NAN : result.b;\n  result.a = isNaN.a == 1.0 ? NAN : result.a;\n\n  return result;\n",cpuKernelImpl:ao})},Ql={kernelName:"Log1p",backendName:"webgl",kernelFunc:Yo({opSnippet:"return log(1.0 + x);"})},Jl={kernelName:"LogicalAnd",backendName:"webgl",kernelFunc:Qo({opSnippet:"return float(a >= 1.0 && b >= 1.0);",packedOpSnippet:"\n  return vec4(\n    vec4(greaterThanEqual(a, vec4(1.0))) *\n    vec4(greaterThanEqual(b, vec4(1.0))));\n",dtype:"bool"})},Zl={kernelName:"LogicalNot",backendName:"webgl",kernelFunc:Yo({opSnippet:"return float(!(x >= 1.0));"})},ec={kernelName:"LogicalOr",backendName:"webgl",kernelFunc:Qo({opSnippet:"return float(a >= 1.0 || b >= 1.0);",packedOpSnippet:"\n  return min(\n    vec4(greaterThanEqual(a, vec4(1.0))) +\n    vec4(greaterThanEqual(b, vec4(1.0))),\n    vec4(1.0));\n",dtype:"bool"})};class tc{constructor(e,t,n,r,a){this.variableNames=["x"],this.outputShape=[];const s=t,o=e[3]-1;let i;this.outputShape=e;const u=`float(${n}) + float(${r}) * sum`;i=.5===a?`inversesqrt(${u})`:1===a?`1.0/(${u})`:`exp(log(${u}) * float(-${a}));`,this.userCode=`\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int r = coords[1];\n        int c = coords[2];\n        int d = coords[3];\n        float x = getX(b, r, c, d);\n        float sum = 0.0;\n        for (int j = -${s}; j <= ${s}; j++) {\n          int idx = d + j;\n          if (idx >= 0 && idx <=  ${o}) {\n            float z = getX(b, r, c, idx);\n            sum += z * z;\n          }\n        }\n        float val = x * ${i};\n        setOutput(val);\n      }\n    `}}class nc{constructor(e,t,n,r,a){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;const s=t,o=e[3]-1;let i;this.outputShape=e;const u=`float(${n}) + float(${r}) * sum`;i=.5===a?`inversesqrt(${u})`:1===a?`1.0/(${u})`:`exp(log(${u}) * float(-${a}));`,this.userCode=`\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords.x;\n        int r = coords.y;\n        int c = coords.z;\n        int d = coords.w;\n\n        bool hasNextCol = d < ${this.outputShape[3]};\n        bool hasNextRow = c < ${this.outputShape[2]};\n\n        vec4 sum = vec4(0.);\n        vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n        vec4 xAtOutputCoords = vec4(\n          getChannel(xFragAtOutputCoords, vec2(c, d)),\n          hasNextCol ?\n            getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n          hasNextRow ?\n            getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n        );\n\n        int firstChannel = d - ${s};\n        vec2 cache = vec2(0.);\n        if(firstChannel >= 0){\n          vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n          cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n            if(hasNextRow){\n              cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n            }\n        }\n\n        ivec2 depth = ivec2(d, d + 1);\n        for (int j = - ${s}; j <= ${s}; j++) {\n          ivec2 idx = depth + j;\n          bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n          bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${o}));\n\n          bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n          bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n          if(depthInRange || depthPlusOneInRange){\n            vec4 z = vec4(0.);\n            vec4 xFragAtCurrentDepth;\n            z.xz = cache.xy;\n            if(depthPlusOneInRange && hasNextCol){\n              xFragAtCurrentDepth = idx.y != d ?\n                getX(b, r, c, idx.y) : xFragAtOutputCoords;\n              z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n              if(hasNextRow){\n                z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n              }\n            }\n            cache.xy = z.yw;\n            sum += z * z;\n          }\n        }\n        vec4 result = xAtOutputCoords * ${i};\n        setOutput(result);\n      }\n    `}}const rc={kernelName:"LRN",backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{depthRadius:s,bias:o,alpha:i,beta:u}=r,l=W().getBool("WEBGL_PACK_NORMALIZATION")?new nc(a.shape,s,o,i,u):new tc(a.shape,s,o,i,u);return n.runWebGLProgram(l,[a],a.dtype)}};class ac{constructor(e,t,n,r,a){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=r,this.beta=a,this.userCode=`\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int r = coords[1];\n        int c = coords[2];\n\n        float result = 0.0;\n        for (int d = 0; d < ${this.depth}; ++d) {\n          int depthBegin = int(max(0.0, float(d - ${t})));\n          int depthEnd = int(min(float(${this.depth}),\n              float(d + ${t} + 1)));\n\n          const int MIN_DEPTH_BEGIN = 0;\n          const int MAX_DEPTH_END = ${this.depth};\n\n          float norm = 0.0;\n          for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n            if (k < depthBegin){\n              continue;\n            }\n            else if (k >= depthBegin && k < depthEnd) {\n              norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n            }\n            else {\n              break;\n            }\n          }\n\n          norm = float(${r}) * norm + float(${n});\n\n          for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n            if (k < depthBegin){\n              continue;\n            }\n            else if (k >= depthBegin && k < depthEnd){\n              float dyi = -2.0 * float(${r})\n                * float(${a})\n                * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n                / norm;\n              if (k == d) {\n                dyi += pow(norm, -1.0 * ${a});\n              }\n              if (k == coords[3]) {\n                dyi *= getDy(b, r, c, d);\n                result += dyi;\n              }\n            }\n            else {\n              break;\n            }\n          }\n      }\n      setOutput(result);\n      }\n    `}}const sc={kernelName:"LRNGrad",backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a,y:s,dy:o}=t,{depthRadius:i,bias:u,alpha:l,beta:c}=r,d=new ac(a.shape,i,u,l,c);return n.runWebGLProgram(d,[a,s,o],a.dtype)}};function oc(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{reductionIndices:s,keepDims:o}=r,i=a.shape.length,u=k(s,a.shape);let l=u;const c=un(l,i),d=null!=c,p=n.shouldExecuteOnCPU([a]);let f=a;if(d){if(p){const e=n.texData.get(f.dataId).values,t=new Array(i);for(let e=0;e<t.length;e++)t[e]=a.shape[c[e]];const r=ko(e,a.shape,a.dtype,c,t);f=n.makeTensorInfo(t,a.dtype);n.texData.get(f.dataId).values=r}else f=hi(a,c,n);l=cn(l.length,i)}on("max",l,i);const[m,g]=an(f.shape,l);let y,b=m;if(o&&(b=sn(m,u)),p){const e=n.texData.get(f.dataId).values,t=so(e,h(g),b,a.dtype);y=n.makeTensorInfo(b,a.dtype);n.texData.get(y.dataId).values=t}else y=function(e,t,n,r){const a=h(t),s=oi({inputs:{x:e},attrs:{shape:[h(e.shape)/a,a]},backend:r}),o=ci(s,e.dtype,"max",r),i=oi({inputs:{x:o},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(o),i}(f,g,b,n);return d&&n.disposeIntermediateTensorInfo(f),y}const ic={kernelName:"Max",backendName:"webgl",kernelFunc:oc},uc={kernelName:"Maximum",backendName:"webgl",kernelFunc:Qo({opSnippet:"\n  if (isnan(a)) return a;\n  if (isnan(b)) return b;\n\n  return max(a, b);\n",packedOpSnippet:"\n  vec4 result = vec4(max(a, b));\n  vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n",cpuKernelImpl:oo})};const lc={kernelName:"MaxPool",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t;zr(a,"maxPool");const{filterSize:s,strides:o,pad:i,dimRoundingMode:u}=r;c(qt(o,1),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '1'`);const l=Pt(a.shape,s,o,1,i,u);if(1===l.filterWidth&&1===l.filterHeight&&f(l.inShape,l.outShape))return Wo({inputs:{x:a},backend:n});const d=new Wi(l,"max",!1);return n.runWebGLProgram(d,[a],a.dtype)}};const cc={kernelName:"MaxPool3D",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{filterSize:s,strides:o,pad:i,dataFormat:u,dimRoundingMode:l}=r,c=Lt(a.shape,s,o,[1,1,1],i,l,u),d=new zi(c,"max",!1);return n.runWebGLProgram(d,[a],a.dtype)}};class dc{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideHeight,n=e.strideWidth,r=e.dilationHeight,a=e.effectiveFilterHeight,s=e.effectiveFilterWidth,o=a-1-e.padInfo.top,i=s-1-e.padInfo.left,u=a*s-1;this.userCode=`\n      const ivec2 pads = ivec2(${o}, ${i});\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n\n        ivec2 dyRCCorner = coords.yz - pads;\n        int dyRCorner = dyRCCorner.x;\n        int dyCCorner = dyRCCorner.y;\n\n        // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < ${a};\n          wR += ${r}) {\n          float dyR = float(dyRCorner + wR) / ${t}.0;\n\n          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          for (int wC = 0; wC < ${s}; wC++) {\n            float dyC = float(dyCCorner + wC) / ${n}.0;\n\n            if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            float dyValue = getDy(b, idyR, idyC, d);\n            int maxPosValue = ${u} - int(getMaxPos(b, idyR, idyC, d));\n\n            // Get the current value, check it against the value from the\n            // position matrix.\n            int curPosValue = wR * ${s} + wC;\n            float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n            dotProd += dyValue * mask;\n          }\n        }\n        setOutput(dotProd);\n      }\n    `}}class pc{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,a=e.dilationDepth,s=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterDepth,u=e.effectiveFilterHeight,l=e.effectiveFilterWidth,c=i-1-e.padInfo.front,d=u-1-e.padInfo.top,p=l-1-e.padInfo.left,h=i*u*l-1;this.userCode=`\n      const ivec3 pads = ivec3(${c}, ${d}, ${p});\n\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int batch = coords.x;\n        int ch = coords.u;\n\n        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n        int dyDCorner = dyCorner.x;\n        int dyRCorner = dyCorner.y;\n        int dyCCorner = dyCorner.z;\n\n        // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get\n        // dx(xD, xR, xC, ch).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n\n        for (int wD = 0; wD < ${i};\n           wD += ${a}) {\n          float dyD = float(dyDCorner + wD) / ${t}.0;\n\n          if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {\n            continue;\n          }\n          int idyD = int(dyD);\n\n          for (int wR = 0; wR < ${u};\n              wR += ${s}) {\n            float dyR = float(dyRCorner + wR) / ${n}.0;\n\n            if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\n                fract(dyR) > 0.0) {\n              continue;\n            }\n            int idyR = int(dyR);\n\n            for (int wC = 0; wC < ${l};\n                wC += ${o}) {\n              float dyC = float(dyCCorner + wC) / ${r}.0;\n\n              if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n                  fract(dyC) > 0.0) {\n                continue;\n              }\n              int idyC = int(dyC);\n\n              float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n              int maxPosValue = ${h} -\n                  int(getMaxPos(batch, idyD, idyR, idyC, ch));\n\n              // Get the current value, check it against the value from the\n              // position matrix.\n              int curPosValue =\n                  wD * ${u} * ${l} +\n                  wR * ${l} + wC;\n              float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n              dotProd += dyValue * mask;\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    `}}const hc={kernelName:"MaxPool3DGrad",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s}=t,o=s,{filterSize:i,strides:u,pad:l,dimRoundingMode:c}=r,d=Lt(o.shape,i,u,[1,1,1],l,c),p=new zi(d,"max",!0),h=n.runWebGLProgram(p,[o],o.dtype),f=new pc(d),m=n.runWebGLProgram(f,[a,h],o.dtype);return n.disposeIntermediateTensorInfo(h),m}};const fc={kernelName:"MaxPoolGrad",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s,output:o}=t,i=s;zr([s,o],"maxPoolGrad");const{filterSize:u,strides:l,pad:c,dimRoundingMode:d}=r,p=Pt(i.shape,u,l,1,c,d),h=new Wi(p,"max",!0),f=n.runWebGLProgram(h,[i],i.dtype),m=new dc(p),g=n.runWebGLProgram(m,[a,f],i.dtype);return n.disposeIntermediateTensorInfo(f),g}};const mc={kernelName:"MaxPoolWithArgmax",backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:r}=e,{filterSize:a,strides:s,pad:o,includeBatchInIndex:i}=t,u=n;c(4===r.shape.length,()=>`Error in maxPool: input must be rank 4 but got rank ${r.shape.length}.`);const l=[1,1];c(qt(s,l),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${l}'`);const d=Pt(r.shape,a,s,l,o),[p,h]=function(e,t,n,r){let a=new Wi(n,"max",!1);const s=r.runWebGLProgram(a,[e],"float32");return a=new Wi(n,"max",!0,!0,t),[s,r.runWebGLProgram(a,[e],"float32")]}(r,i,d,u);return[p,h]}};const gc={kernelName:"Mean",backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:r}=e,{keepDims:a,axis:s}=t,o=n,i=r.shape.length,u=k(s,r.shape);let l=u;const c=un(l,i),d=null!=c,p=o.shouldExecuteOnCPU([r]),f=[];let m=r;if(d){if(p){const e=o.texData.get(m.dataId).values,t=new Array(i);for(let e=0;e<t.length;e++)t[e]=r.shape[c[e]];const n=ko(e,r.shape,r.dtype,c,t);m=o.makeTensorInfo(t,r.dtype);o.texData.get(m.dataId).values=n}else m=hi(r,c,o);f.push(m),l=cn(l.length,i)}on("sum",l,i);const[g,y]=an(m.shape,l);let b=g;a&&(b=sn(g,u));const x=function(e,t,n,r){const a=h(t),s=oi({inputs:{x:e},attrs:{shape:[h(e.shape)/a,a]},backend:r}),o=ci(s,"float32","mean",r),i=oi({inputs:{x:o},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(o),i}(m,y,b,o);for(const e of f)o.disposeIntermediateTensorInfo(e);return x}};const yc={kernelName:"Min",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r,i=a.shape.length,u=k(s,a.shape);let l=u;const c=un(l,i);let d=a;null!=c&&(d=gi({inputs:{x:a},backend:n,attrs:{perm:c}}),l=cn(l.length,a.shape.length)),on("min",l,i);const[p,f]=an(d.shape,l),m=oi({inputs:{x:d},backend:n,attrs:{shape:[-1,h(f)]}}),g=ci(m,m.dtype,"min",n);let y;if(o){y=oi({inputs:{x:g},backend:n,attrs:{shape:sn(p,u)}})}else y=oi({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),null!=c&&n.disposeIntermediateTensorInfo(d),y}},bc={kernelName:"Minimum",backendName:"webgl",kernelFunc:Qo({opSnippet:"\n  if (isnan(a)) return a;\n  if (isnan(b)) return b;\n\n  return min(a, b);\n",packedOpSnippet:"\n  vec4 result = vec4(min(a, b));\n  vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n",cpuKernelImpl:io})};class xc{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((t,n)=>t[0]+e[n]+t[1]);const r=e.length,a=wa(r),s=t.map(e=>e[0]).join(","),o=t.map((t,n)=>t[0]+e[n]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r),u="reflect"===n?0:1;this.userCode=1!==r?`\n      ${a} start = ${a}(${s});\n      ${a} end = ${a}(${o});\n\n      void main() {\n        ${a} outC = getOutputCoords();\n        for (int i = 0; i < ${r}; i++) {\n          if (outC[i] < start[i]) {\n            outC[i] = start[i] * 2 - outC[i] - ${u};\n          } else if(outC[i] >= end[i]) {\n            outC[i] = (end[i] - 1) * 2 - outC[i] + ${u};\n          }\n        }\n        ${a} coords = outC - start;\n        setOutput(getX(${i}));\n      }\n    `:`\n        int start = ${s};\n        int end = ${o};\n\n        void main() {\n          int outC = getOutputCoords();\n          if (outC < start) {\n            outC = start * 2 - outC - ${u};\n          } else if(outC >= end) {\n            outC = (end - 1) * 2 - outC + ${u};\n          }\n          setOutput(getX(outC - start));\n        }\n      `}}class kc{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((t,n)=>t[0]+e[n]+t[1]);const r=e.length,a=wa(r),s=t.map(e=>e[0]).join(","),o=t.map((t,n)=>t[0]+e[n]).join(","),i=Io("rc",r),u=Io("source",r),l=`${i[r-1]} < ${this.outputShape[r-1]}`,c=1===r?"source":`vec2(${u.slice(-2).join()})`,d="reflect"===n?0:1;let p="";if(1===r){const e=`\n        ${a} source = rc;\n        if (source < start) {\n          source = start * 2 - source - ${d};\n        } else if (source >= end) {\n          source = (end - 1) * 2 - source + ${d};\n        }\n        source -= start;\n      `;p=`\n        ${a} rc = outputLoc;\n        ${e}\n        result[0] = getChannel(getX(${u.join()}), ${c});\n        ${i[r-1]} += 1;\n        if(${l}) {\n          ${e}\n          result[1] = getChannel(getX(${u.join()}), ${c});\n        }\n      `}else{const e=`\n        ${a} source = rc;\n        ${a} lt = ${a}(lessThan(source, start));\n        ${a} gte = ${a}(greaterThanEqual(source, end));\n        ${a} orig = 1 - (lt + gte);\n        source = orig * source +\n                lt * (start * 2 - source - ${d}) +\n                gte * ((end - 1) * 2 - source + ${d});\n        source -= start;\n      `;p=`\n        ${a} rc = outputLoc;\n        ${e}\n        result[0] = getChannel(getX(${u.join()}), ${c});\n        ${i[r-1]} += 1;\n        if(${l}) {\n          ${e}\n          result[1] = getChannel(getX(${u.join()}), ${c});\n        }\n        rc = outputLoc;\n        ${i[r-2]} += 1;\n        if(${i[r-2]} < ${this.outputShape[r-2]}) {\n          ${e}\n          result[2] = getChannel(getX(${u.join()}), ${c});\n          ${i[r-1]} += 1;\n          if(${l}) {\n            ${e}\n            result[3] = getChannel(getX(${u.join()}), ${c});\n          }\n        }\n      `}this.userCode=`\n      const ${a} start = ${a}(${s});\n      const ${a} end = ${a}(${o});\n\n      void main() {\n        ${a} outputLoc = getOutputCoords();\n        vec4 result = vec4(0.);\n        ${p}\n        setOutput(result);\n      }\n    `}}const wc={kernelName:"MirrorPad",backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r}=e,{paddings:a,mode:s}=n,o=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new kc(r.shape,a,s):new xc(r.shape,a,s);return t.runWebGLProgram(o,[r],r.dtype)}},vc={kernelName:"Mod",backendName:"webgl",kernelFunc:Qo({opSnippet:"if (b == 0.0) return NAN;\n  return mod(a, b);",packedOpSnippet:"\n  vec4 result = mod(a, b);\n  vec4 isNaN = vec4(equal(b, vec4(0.0)));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n"})};class Ic{constructor(e,t,n){this.variableNames=["probs"],this.outputShape=[e,n],this.userCode=`\n      uniform float seed;\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n\n        float r = random(seed);\n        float cdf = 0.0;\n\n        for (int i = 0; i < ${t-1}; i++) {\n          cdf += getProbs(batch, i);\n\n          if (r < cdf) {\n            setOutput(float(i));\n            return;\n          }\n        }\n\n        // If no other event happened, last event happened.\n        setOutput(float(${t-1}));\n      }\n    `}getCustomSetupFunc(e){return(t,n)=>{null==this.seedLoc&&(this.seedLoc=t.getUniformLocation(n,"seed")),t.gl.uniform1f(this.seedLoc,e)}}}const Nc=Qo({opSnippet:"\nif (a == b) {\n  return 1.0;\n};\nreturn a / b;",packedOpSnippet:"\n  // vec4 one = vec4(equal(a, b));\n  // return one + (vec4(1.0) - one) * a / b;\n  vec4 result = a / b;\n  if(a.x == b.x) {\n    result.x = 1.;\n  }\n  if(a.y == b.y) {\n    result.y = 1.;\n  }\n  if(a.z == b.z) {\n    result.z = 1.;\n  }\n  if(a.w == b.w) {\n    result.w = 1.;\n  }\n\n  return result;\n",checkOutOfBounds:!0}),Sc={kernelName:"RealDiv",backendName:"webgl",kernelFunc:Nc},Cc="return a - b;",Tc=Qo({opSnippet:Cc,packedOpSnippet:Cc,supportsComplex:!0,cpuKernelImpl:yo}),Ec={kernelName:"Sub",backendName:"webgl",kernelFunc:Tc};function $c(e){const{inputs:t,backend:n,attrs:r}=e,{logits:a}=t,{dim:s}=r,o=k([s],a.shape),i=oc({inputs:{x:a},backend:n,attrs:{reductionIndices:o,keepDims:!1}}),u=sn(i.shape,o),l=oi({inputs:{x:i},backend:n,attrs:{shape:u}}),c=Tc({inputs:{a:a,b:l},backend:n}),d=fl({inputs:{x:c},backend:n}),p=fi({inputs:{x:d},backend:n,attrs:{axis:o,keepDims:!1}}),h=oi({inputs:{x:p},backend:n,attrs:{shape:u}}),f=Nc({inputs:{a:d,b:h},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),f}const _c={kernelName:"Softmax",backendName:"webgl",kernelFunc:$c};const Ac={kernelName:"Multinomial",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{logits:a}=t,{numSamples:s,seed:o,normalized:i}=r,u=i?a:$c({inputs:{logits:a},backend:n,attrs:{dim:a.shape.length-1}}),l=u.shape[0],c=u.shape[1],d=new Ic(l,c,s),p=d.getCustomSetupFunc(o),h=n.runWebGLProgram(d,[u],"int32",p);return i||n.disposeIntermediateTensorInfo(u),h}},Rc="return -x;";const Mc={kernelName:"Neg",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])){const e=n.texData.get(r.dataId),[t,a]=lo(e.values,r.shape,r.dtype);return n.makeTensorInfo(a,r.dtype,t)}let a;return a=W().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new Mo(r.shape,Rc):new _o(r.shape,Rc),n.runWebGLProgram(a,[r],r.dtype)}},Fc=$n;const Dc={kernelName:"NonMaxSuppressionV3",backendName:"webgl",kernelFunc:function(e){Hn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:r}=e,{boxes:a,scores:s}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:u}=r,l=n.readSync(a.dataId),c=n.readSync(s.dataId),{selectedIndices:d}=Fc(l,c,o,i,u);return n.makeTensorInfo([d.length],"int32",new Int32Array(d))}},Oc=_n;const Pc={kernelName:"NonMaxSuppressionV4",backendName:"webgl",kernelFunc:function(e){Hn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:r}=e,{boxes:a,scores:s}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:u,padToMaxOutputSize:l}=r,c=n.readSync(a.dataId),d=n.readSync(s.dataId),{selectedIndices:p,validOutputs:h}=Oc(c,d,o,i,u,l);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}},Lc=An;const Bc={kernelName:"NonMaxSuppressionV5",backendName:"webgl",kernelFunc:function(e){Hn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:r}=e,{boxes:a,scores:s}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:u,softNmsSigma:l}=r,c=n.readSync(a.dataId),d=n.readSync(s.dataId),p=o,h=i,f=u,m=l,{selectedIndices:g,selectedScores:y}=Lc(c,d,p,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}};class Wc{constructor(e,t,n,r){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int index = round(getIndices(coords.x));\n        setOutput(mix(float(${r}), float(${n}),\n                      float(index == coords.y)));\n      }\n    `}}const zc={kernelName:"OneHot",backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{indices:a}=t,{depth:s,onValue:o,offValue:i}=r,u=h(a.shape),l=new Wc(u,s,o,i),c=oi({inputs:{x:a},backend:n,attrs:{shape:[u]}}),d=n.runWebGLProgram(l,[c],a.dtype);n.disposeIntermediateTensorInfo(c);const p=oi({inputs:{x:d},backend:n,attrs:{shape:[...a.shape,s]}});return n.disposeIntermediateTensorInfo(d),p}};function Vc(e){const{inputs:t,backend:n}=e,{x:r}=t;if("complex64"===r.dtype){const e=iu({inputs:{input:r},backend:n}),t=Vc({inputs:{x:e},backend:n}),a=wu({inputs:{input:r},backend:n}),s=Vc({inputs:{x:a},backend:n}),o=Vo({inputs:{real:t,imag:s},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(s),o}return Nl({attrs:{shape:r.shape,dtype:r.dtype,value:"string"===r.dtype?"":0},backend:n})}const Uc={kernelName:"ZerosLike",backendName:"webgl",kernelFunc:Vc};const Gc={kernelName:"OnesLike",backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:r}=t,{x:a}=n;if("string"===a.dtype)throw new Error("onesLike is not supported under string dtype");if("complex64"===a.dtype){const t=iu({inputs:{input:a},backend:r}),n=e({inputs:{x:t},backend:r}),s=wu({inputs:{input:a},backend:r}),o=Vc({inputs:{x:s},backend:r}),i=Vo({inputs:{real:n,imag:o},backend:r});return r.disposeIntermediateTensorInfo(t),r.disposeIntermediateTensorInfo(n),r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(o),i}return Nl({attrs:{shape:a.shape,dtype:a.dtype,value:1},backend:r})}};const Hc={kernelName:"Pack",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r;if(1===t.length)return gl({inputs:{input:t[0]},backend:n,attrs:{dim:a}});const s=t[0].shape,o=t[0].dtype;t.forEach(e=>{d(s,e.shape,"All tensors passed to stack must have matching shapes"),c(o===e.dtype,()=>"All tensors passed to stack must have matching dtypes")});const i=[],u=Nu({inputs:t.map(e=>{const t=gl({inputs:{input:e},backend:n,attrs:{dim:a}});return i.push(t),t}),backend:n,attrs:{axis:a}});return i.forEach(e=>n.disposeIntermediateTensorInfo(e)),u}};class jc{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((t,n)=>t[0]+e[n]+t[1]);const r=e.length,a=wa(r),s=t.map(e=>e[0]).join(","),o=t.map((t,n)=>t[0]+e[n]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?`\n      ${a} start = ${a}(${s});\n      ${a} end = ${a}(${o});\n      uniform float value;\n\n      void main() {\n        ${a} outC = getOutputCoords();\n        if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n          setOutput(value);\n        } else {\n          ${a} coords = outC - start;\n          setOutput(getX(${i}));\n        }\n      }\n    `:`\n        int start = ${s};\n        int end = ${o};\n        uniform float value;\n\n        void main() {\n          int outC = getOutputCoords();\n          if (outC < start || outC >= end) {\n            setOutput(value);\n          } else {\n            setOutput(getX(outC - start));\n          }\n        }\n      `}getCustomSetupFunc(e){return(t,n)=>{null==this.valueLoc&&(this.valueLoc=t.getUniformLocationNoThrow(n,"value")),t.gl.uniform1f(this.valueLoc,e)}}}class qc{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((t,n)=>t[0]+e[n]+t[1]);const r=e.length,a=wa(r),s=t.map(e=>e[0]).join(","),o=t.map((t,n)=>t[0]+e[n]).join(","),i=Io("rc",r),u=Io("source",r),l=`${i[r-1]} < ${this.outputShape[r-1]}`,c=1===r?"source":`vec2(${u.slice(-2).join()})`,d=[a+" rc = outputLoc;",`${i[r-1]} += 1;\n       if(${l}) {\n      `,1===r?"":`}\n       rc = outputLoc;\n       ${i[r-2]} += 1;\n       if(${i[r-2]} < ${this.outputShape[r-2]}) {`,1===r?"":`  ${i[r-1]} += 1;\n         if(${l}) {`],p=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let h="";for(let e=0,t=1===r?2:4;e<t;e++)h+=`\n        ${d[e]}\n        if (${p}) {\n          result[${e}] = float(value);\n        } else {\n          ${a} source = rc - start;\n          result[${e}] = getChannel(getX(${u.join()}), ${c});\n        }\n      `;h+=1===r?"} ":"}}",this.userCode=`\n      const ${a} start = ${a}(${s});\n      const ${a} end = ${a}(${o});\n      uniform float value;\n\n      void main() {\n        ${a} outputLoc = getOutputCoords();\n        vec4 result = vec4(0.);\n        ${h}\n        setOutput(result);\n      }\n    `}getCustomSetupFunc(e){return(t,n)=>{null==this.valueLoc&&(this.valueLoc=t.getUniformLocationNoThrow(n,"value")),t.gl.uniform1f(this.valueLoc,e)}}}const Kc=e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{paddings:s,constantValue:o}=r,i=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new qc(a.shape,s,o):new jc(a.shape,s,o),u=i.getCustomSetupFunc(o);return n.runWebGLProgram(i,[a],a.dtype,u)},Xc={kernelName:"PadV2",backendName:"webgl",kernelFunc:Kc},Yc={kernelName:"Pow",backendName:"webgl",kernelFunc:Qo({opSnippet:"\n  if(a < 0.0 && floor(b) < b){\n    return NAN;\n  }\n  if (b == 0.0) {\n    return 1.0;\n  }\n  return (round(mod(b, 2.0)) != 1) ?\n      pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",packedOpSnippet:"\n  // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n  vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n  vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n  vec4 result = multiplier * pow(abs(a), b);\n\n  // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n  bvec4 isExpZero = equal(b, vec4(0.0));\n  result.r = isExpZero.r ? 1.0 : result.r;\n  result.g = isExpZero.g ? 1.0 : result.g;\n  result.b = isExpZero.b ? 1.0 : result.b;\n  result.a = isExpZero.a ? 1.0 : result.a;\n\n  vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n"})};const Qc={kernelName:"Prod",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r,i=a.shape.length,u=[],l=k(s,a.shape);let c=l;const d=un(c,i);let p,f=a;if(null!=d&&(f=gi({inputs:{x:a},backend:n,attrs:{perm:d}}),c=cn(c.length,i),u.push(f)),on("prod",c,i),n.shouldExecuteOnCPU([f])){const e=n.texData.get(f.dataId).values,{outVals:t,outShape:r,outDtype:a}=co(f.shape,f.dtype,e,c);p=n.makeTensorInfo(r,a,t)}else{const[e,t]=an(f.shape,c),r=h(t),s=oi({inputs:{x:f},backend:n,attrs:{shape:[-1,r]}}),o=ci(s,ve(a.dtype),"prod",n);p=oi({inputs:{x:o},backend:n,attrs:{shape:e}}),u.push(s),u.push(o)}if(o){u.push(p);const e=sn(p.shape,l);p=oi({inputs:{x:p},backend:n,attrs:{shape:e}})}return u.forEach(e=>n.disposeIntermediateTensorInfo(e)),p}},Jc=e=>{const{backend:t,attrs:n}=e,{start:r,stop:a,step:s,dtype:o}=n,i=po(r,a,s,o);return t.makeTensorInfo([i.length],o,i)},Zc={kernelName:"Range",backendName:"webgl",kernelFunc:Jc},ed={kernelName:"Reciprocal",backendName:"webgl",kernelFunc:Yo({opSnippet:"return 1.0 / x;"})},td={kernelName:"Relu",backendName:"webgl",kernelFunc:Yo({opSnippet:"if (isnan(x)) return x;\n  return (x < 0.0) ? 0.0 : x;\n",packedOpSnippet:"\n  vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n  bvec4 isNaN = isnan(x);\n\n  result.r = isNaN.r ? x.r : result.r;\n  result.g = isNaN.g ? x.g : result.g;\n  result.b = isNaN.b ? x.b : result.b;\n  result.a = isNaN.a ? x.a : result.a;\n\n  return result;\n"})},nd={kernelName:"Relu6",backendName:"webgl",kernelFunc:Yo({opSnippet:"if (isnan(x)) return x;\n  return (x < 0.0) ? 0.0 : min(6.0, x);\n",packedOpSnippet:"\n  vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n  bvec4 isNaN = isnan(x);\n\n  result.r = isNaN.r ? x.r : result.r;\n  result.g = isNaN.g ? x.g : result.g;\n  result.b = isNaN.b ? x.b : result.b;\n  result.a = isNaN.a ? x.a : result.a;\n\n  return result;\n"})};class rd{constructor(e,t,n,r,a){this.variableNames=["A"],this.outputShape=[];const[s,o,i,u]=e;this.outputShape=[s,t,n,u];const l=[r&&t>1?o-1:o,r&&n>1?i-1:i],c=[r&&t>1?t-1:t,r&&n>1?n-1:n];let d;d=a?"(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n      const vec2 effectiveInputOverOutputRatioRC = vec2(\n          ${l[0]/c[0]},\n          ${l[1]/c[1]});\n      const vec2 inputShapeRC = vec2(${o}.0, ${i}.0);\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        ivec2 yRC = coords.yz;\n\n        // Fractional source index.\n        vec2 sourceFracIndexRC = ${d};\n\n        // Compute the four integer indices.\n        ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));\n        ivec2 sourceCeilRC = ivec2(\n          min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n        float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n        float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n        float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n        float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n        vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n        float top = topLeft + (topRight - topLeft) * fracRC.y;\n        float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n        float newValue = top + (bottom - top) * fracRC.x;\n\n        setOutput(newValue);\n      }\n    `}}class ad{constructor(e,t,n,r,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[s,o,i,u]=e;this.outputShape=[s,t,n,u];const l=[r&&t>1?o-1:o,r&&n>1?i-1:i],c=[r&&t>1?t-1:t,r&&n>1?n-1:n];let d;d=a?"(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":"vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n      const vec3 effectiveInputOverOutputRatioRC = vec3(\n          ${l[0]/c[0]},\n          ${l[1]/c[1]},\n          ${l[1]/c[1]});\n      const vec3 inputShapeRC = vec3(${o}.0, ${i}.0,\n                                     ${i}.0);\n\n      float getAValue(int b, int r, int c, int d) {\n        return getChannel(getA(b, r, c, d), vec2(c, d));\n      }\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        // Calculate values for next column in yRC.z.\n        ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n        // Fractional source index.\n        vec3 sourceFracIndexRC = ${d};\n\n        // Compute the four integer indices.\n        ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));\n        ivec3 sourceCeilRC = ivec3(\n          min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n        // Should we calculate next column and row elements in 2x2 packed cell.\n        bool hasNextCol = d < ${u-1};\n        bool hasNextRow = coords.z < ${n-1};\n\n        // In parallel, construct four corners for all four components in\n        // packed 2x2 cell.\n        vec4 topLeft = vec4(\n          getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n          hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n        vec4 bottomLeft = vec4(\n          getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n          hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n        vec4 topRight = vec4(\n          getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n          hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n        vec4 bottomRight = vec4(\n          getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n          hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n        vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n        vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n        vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n        vec4 newValue = mix(top, bottom, fracRC.x);\n\n        setOutput(newValue);\n      }\n    `}}const sd={kernelName:"ResizeBilinear",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:o,size:i}=r,[u,l]=i,c=W().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new ad(a.shape,u,l,s,o):new rd(a.shape,u,l,s,o);return n.runWebGLProgram(c,[a],"float32")}};class od{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,r,a]=t,[,s,o]=e,i=[n&&s>1?r-1:r,n&&o>1?a-1:a],u=[n&&s>1?s-1:s,n&&o>1?o-1:o],l=i[0]/u[0],c=i[1]/u[1],d=1/l,p=1/c,h=2*Math.ceil(d)+2,f=2*Math.ceil(p)+2;this.userCode=`\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        int r = coords[1];\n        int c = coords[2];\n\n        float accumulator = 0.0;\n\n        const float heightScale = float(${l});\n        const float widthScale = float(${c});\n\n        const float invHeightScale = float(${d});\n        const float invWidthScale = float(${p});\n\n        const int winHeight = int(${h});\n        const int winWidth = int(${f});\n\n        // Compute bounds for where in dy we will look\n        float startRLerp = floor(float(r) * invHeightScale);\n        int startDyR = int(startRLerp - float(winHeight / 2));\n\n        float startCLerp = floor(float(c) * invWidthScale);\n        int startDyC = int(startCLerp - float(winWidth / 2));\n\n        // Loop over dy\n        for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n          int dyR = dyROffset + startDyR;\n\n          // Guard against the window exceeding the bounds of dy\n          if (dyR < 0 || dyR >= ${s}) {\n            continue;\n          }\n\n          for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n            int dyC = dyCOffset + startDyC;\n\n            // Guard against the window exceeding the bounds of dy\n            if (dyC < 0 || dyC >= ${o}) {\n              continue;\n            }\n\n            float dxR = float(dyR) * heightScale;\n            int topDxRIndex = int(floor(dxR));\n            int bottomDxRIndex = int(min(ceil(dxR), ${r-1}.0));\n            float dxRLerp = dxR - float(topDxRIndex);\n            float inverseDxRLerp = 1.0 - dxRLerp;\n\n            float dxC = float(dyC) * widthScale;\n            int leftDxCIndex = int(floor(dxC));\n            int rightDxCIndex = int(min(ceil(dxC), ${a-1}.0));\n            float dxCLerp = dxC - float(leftDxCIndex);\n            float inverseDxCLerp = 1.0 - dxCLerp;\n\n            if (r == topDxRIndex && c == leftDxCIndex) {\n              // topLeft\n              accumulator +=\n                getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n            }\n\n            if (r == topDxRIndex && c == rightDxCIndex) {\n              // topRight\n              accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n            }\n\n            if (r == bottomDxRIndex && c == leftDxCIndex) {\n              // bottomLeft\n              accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n            }\n\n            if (r == bottomDxRIndex && c == rightDxCIndex) {\n              // bottomRight\n              accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n            }\n          }\n        }\n        // End loop over dy\n\n        setOutput(accumulator);\n      }\n    `}}const id={kernelName:"ResizeBilinearGrad",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a,dy:s}=t,{alignCorners:o}=r,i=new od(s.shape,a.shape,o);return n.runWebGLProgram(i,[s],s.dtype)}};class ud{constructor(e,t,n,r,a){this.variableNames=["A"],this.outputShape=[];const[s,o,i,u]=e;this.outputShape=[s,t,n,u];const l=[r&&t>1?o-1:o,r&&n>1?i-1:i],c=[r&&t>1?t-1:t,r&&n>1?n-1:n],d=r?"0.5":"0.0";let p;p=a?"max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n      const vec2 effectiveInputOverOutputRatioRC = vec2(\n          ${l[0]/c[0]},\n          ${l[1]/c[1]});\n      const vec2 inputShapeRC = vec2(${o}.0, ${i}.0);\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        ivec2 yRC = coords.yz;\n\n        // Fractional source index.\n        vec2 sourceFracIndexRC = ${p};\n\n        // Compute the coordinators of nearest neighbor point.\n        ivec2 sourceNearestRC = ivec2(\n          min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${d})));\n        float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n        setOutput(newValue);\n      }\n    `}}const ld={kernelName:"ResizeNearestNeighbor",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:o,size:i}=r,[u,l]=i,c=new ud(a.shape,u,l,s,o);return n.runWebGLProgram(c,[a],a.dtype)}};class cd{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,r,a]=t,[,s,o]=e,i=[n&&s>1?r-1:r,n&&o>1?a-1:a],u=[n&&s>1?s-1:s,n&&o>1?o-1:o],l=i[0]/u[0],c=i[1]/u[1],d=1/l,p=1/c,h=2*Math.ceil(d)+2,f=2*Math.ceil(p)+2;this.userCode=`\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        int r = coords[1];\n        int c = coords[2];\n\n        float accumulator = 0.0;\n\n        const float heightScale = float(${l});\n        const float widthScale = float(${c});\n\n        const float invHeightScale = float(${d});\n        const float invWidthScale = float(${p});\n\n        const int winHeight = int(${h});\n        const int winWidth = int(${f});\n\n        // Compute bounds for where in dy we will look\n        float startRLerp = floor(float(r) * invHeightScale);\n        int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n        float startCLerp = floor(float(c) * invWidthScale);\n        int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n        // Loop over dy\n        for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n          int dyR = dyROffset + startDyR;\n\n          // Guard against the window exceeding the bounds of dy\n          if (dyR < 0 || dyR >= ${s}) {\n            continue;\n          }\n\n          for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n            int dyC = dyCOffset + startDyC;\n\n            // Guard against the window exceeding the bounds of dy\n            if (dyC < 0 || dyC >= ${o}) {\n              continue;\n            }\n\n            float sourceFracRow =\n              float(${i[0]}) *\n                (float(dyR) / float(${u[0]}));\n\n            float sourceFracCol =\n                float(${i[1]}) *\n                  (float(dyC) / float(${u[1]}));\n\n            int sourceNearestRow = int(min(\n                float(int(${r}) - 1),\n                ${n} ? float(round(sourceFracRow)) :\n                                  float(floor(sourceFracRow))));\n\n            int sourceNearestCol = int(min(\n                float(int(${a}) - 1),\n                ${n} ? float(round(sourceFracCol)) :\n                                  float(floor(sourceFracCol))));\n\n            if (r == sourceNearestRow && c == sourceNearestCol) {\n              accumulator += getDy(b, dyR, dyC, d);\n            }\n          }\n        }\n        // End loop over dy\n\n        setOutput(accumulator);\n      }\n    `}}const dd={kernelName:"ResizeNearestNeighborGrad",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a,dy:s}=t,{alignCorners:o}=r,i=new cd(s.shape,a.shape,o);return n.runWebGLProgram(i,[s],s.dtype)}};class pd{constructor(e,t){this.variableNames=["x"];const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=e,1===n)return void(this.userCode=`\n        void main() {\n          int coord = getOutputCoords();\n          setOutput(getX(${e[0]} - coord - 1));\n        }\n      `);const r=e.map((n,r)=>(n=>-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - coords[${n}] - 1`:`coords[${n}]`)(r)).join(","),a=wa(n);this.userCode=`\n      void main() {\n        ${a} coords = getOutputCoords();\n        setOutput(getX(${r}));\n      }\n    `}}class hd{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=e;const r=Io("rc",n),a=`${r[n-1]} + 1 < ${this.outputShape[n-1]}`,s=`${r[n-2]} + 1 < ${this.outputShape[n-2]}`,o=wa(n);function i(n){const r=e.map((r,a)=>function(n,r){return-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - ${r[n]} - 1`:""+r[n]}(a,n));return`getChannel(getX(${r.join(",")}), vec2(${r.slice(-2).join(",")}))`}this.userCode=1===n?`\n        void main(){\n          int rc = getOutputCoords();\n          vec4 result = vec4(0.);\n          result.r = getChannel(getX(${e[0]} - rc - 1),\n            ${e[0]} - rc - 1);\n          if(${a}){\n              result.g = getChannel(getX(${e[0]} - (rc  + 1) - 1),\n                ${e[0]} - (rc  + 1) - 1);\n          }\n          setOutput(result);\n        }\n      `:`\n        void main() {\n          ${o} rc = getOutputCoords();\n          vec4 result = vec4(0.);\n          result.r = ${function(e){return i(e)}(r.slice())};\n          if(${a}){\n            result.g = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",i(e)}(r.slice())};\n          }\n          if(${s}) {\n            result.b = ${function(e){return e[n-2]="("+e[n-2]+" + 1)",i(e)}(r.slice())};\n            if(${a}) {\n              result.a = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",e[n-2]="("+e[n-2]+" + 1)",i(e)}(r.slice())};\n            }\n          }\n          setOutput(result);\n        }\n    `}}const fd={kernelName:"Reverse",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dims:s}=r,o=a.shape.length,i=k(s,a.shape);if(0===o)return Wo({inputs:{x:a},backend:n});const u=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new hd(a.shape,i):new pd(a.shape,i);return n.runWebGLProgram(u,[a],a.dtype)}};class md{constructor(e,t){this.variableNames=["Image"],this.outputShape=[];const n=e[1],r=e[2];this.outputShape=e;let a="";a="number"==typeof t?`float outputValue = ${t.toFixed(2)};`:`\n        vec3 fill = vec3(${t.join(",")});\n        float outputValue = fill[coords[3]];`,this.userCode=`\n        uniform vec4 params;\n        void main() {\n          ivec4 coords = getOutputCoords();\n          int x = coords[2];\n          int y = coords[1];\n          float coordXFloat = (float(x) - params[0]) * params[3] -\n            (float(y) - params[1]) * params[2];\n          float coordYFloat = (float(x) - params[0]) * params[2] +\n            (float(y) - params[1]) * params[3];\n          int coordX = int(round(coordXFloat + params[0]));\n          int coordY = int(round(coordYFloat + params[1]));\n          ${a}\n          if(coordX >= 0 && coordX < ${r} && coordY >= 0 && coordY < ${n}) {\n            outputValue = getImage(coords[0], coordY, coordX, coords[3]);\n          }\n          setOutput(outputValue);\n        }\n    `}getCustomSetupFunc(e,t,n,r){return(a,s)=>{null==this.paramsLoc&&(this.paramsLoc=a.getUniformLocationNoThrow(s,"params")),a.gl.uniform4f(this.paramsLoc,e,t,n,r)}}}const gd={kernelName:"RotateWithOffset",backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:r}=e,{radians:a,fillValue:s,center:o}=t,i=n,u=new md(r.shape,s),[l,c]=Bn(o,r.shape[1],r.shape[2]),d=u.getCustomSetupFunc(l,c,Math.sin(a),Math.cos(a));return i.runWebGLProgram(u,[r],r.dtype,d)}},yd={kernelName:"Round",backendName:"webgl",kernelFunc:Yo({opSnippet:"\n  // OpenGL ES does not support round function.\n  // The algorithm is based on banker's rounding.\n  float base = floor(x);\n  if ((x - base) < 0.5) {\n    return floor(x);\n  } else if ((x - base) > 0.5) {\n    return ceil(x);\n  } else {\n    if (mod(base, 2.0) == 0.0) {\n      return base;\n    } else {\n      return base + 1.0;\n    }\n  }\n"})},bd={kernelName:"Rsqrt",backendName:"webgl",kernelFunc:Yo({opSnippet:"return inversesqrt(x);",cpuKernelImpl:ho})};class xd{constructor(e,t,n,r,a,s,o=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=s;const i=wa(a.length),u=wa(s.length);let l="";1===n?l="i":2===n&&(l="i, j");const c=`getIndices(${l})`;let d="";1===r?d="i":2===r&&(d="i, coords[1]");const p=`getUpdates(${d})`,h=t>1?"strides[j]":"strides";this.userCode=`\n        ${i} strides = ${i}(${a});\n\n        void main() {\n          ${u} coords = getOutputCoords();\n          float sum = 0.0;\n          bool found = false;\n          for (int i = 0; i < ${e}; i++) {\n            int flattenedIndex = 0;\n            for (int j = 0; j < ${t}; j++) {\n              int index = round(${c});\n              flattenedIndex += index * ${h};\n            }\n            if (flattenedIndex == coords[0]) {\n              sum += ${p};\n              found = true;\n            }\n          }\n          setOutput(mix(getDefaultValue(), sum, float(found)));\n        }\n      `}}const kd={kernelName:"ScatterNd",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{indices:a,updates:s}=t,{shape:o}=r,{sliceRank:i,numUpdates:u,sliceSize:l,strides:c,outputSize:d}=ft(0,a,o),p=[d/l,l];if(0===d)return n.makeTensorInfo(o,a.dtype);const h=oi({inputs:{x:a},backend:n,attrs:{shape:[u,i]}}),f=oi({inputs:{x:s},backend:n,attrs:{shape:[u,l]}}),m=n.makeTensorInfo([],"float32",new Float32Array([0])),g=new xd(u,i,h.shape.length,f.shape.length,c,p),y=n.runWebGLProgram(g,[f,h,m],f.dtype),b=oi({inputs:{x:y},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(m),b}};class wd{constructor(e,t,n){let r,a;if(this.variableNames=["c","a","b"],this.outputShape=t,n>4)throw Error(`Where for rank ${n} is not yet supported`);if(1===n)a="resRC",r="resRC";else{const n=["resRC.x","resRC.y","resRC.z","resRC.w"],s=[],o=[];for(let r=0;r<t.length;r++)o.push(""+n[r]),r<e&&s.push(""+n[r]);r=s.join(),a=o.join()}const s=wa(n);this.userCode=`\n      void main() {\n        ${s} resRC = getOutputCoords();\n        float cVal = getC(${r});\n        if (cVal >= 1.0) {\n          setOutput(getA(${a}));\n        } else {\n          setOutput(getB(${a}));\n        }\n      }\n    `}}const vd={kernelName:"Select",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:r,t:a,e:s}=t,o=new wd(r.shape.length,a.shape,a.shape.length);return n.runWebGLProgram(o,[r,a,s],we(a.dtype,s.dtype))}},Id={kernelName:"Selu",backendName:"webgl",kernelFunc:Yo({opSnippet:"\n  // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n  // see: https://arxiv.org/abs/1706.02515\n  float scaleAlpha = 1.7580993408473768;\n  float scale = 1.0507009873554805;\n  return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n"})},Nd={kernelName:"Sigmoid",backendName:"webgl",kernelFunc:Yo({opSnippet:"return 1.0 / (1.0 + exp(-1.0 * x));"})},Sd={kernelName:"Sign",backendName:"webgl",kernelFunc:Yo({opSnippet:"\n  if (isnan(x)) { return 0.0; }\n  return sign(x);\n"})},Cd={kernelName:"Sin",backendName:"webgl",kernelFunc:Yo({opSnippet:"if (isnan(x)) return x;\n  return sin(x);\n"})},Td={kernelName:"Sinh",backendName:"webgl",kernelFunc:Yo({opSnippet:"\n  float e2x = exp(x);\n  return (e2x - 1.0 / e2x) / 2.0;\n"})},Ed={kernelName:"Softplus",backendName:"webgl",kernelFunc:Yo({opSnippet:"\n  float epsilon = 1.1920928955078125e-7;\n  float threshold = log(epsilon) + 2.0;\n\n  bool too_large = x > -threshold;\n  bool too_small = x < threshold;\n\n  float result;\n  float exp_x = exp(x);\n\n  if (too_large){\n    result = x;\n  }\n  else if (too_small){\n    result = exp_x;\n  }\n  else{\n    result = log(exp_x + 1.0);\n  }\n  return result;\n"})},$d={kernelName:"SpaceToBatchND",backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,paddings:o}=r;c(a.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");const i=s.reduce((e,t)=>e*t),u=[[0,0]];u.push(...o);for(let e=1+s.length;e<a.shape.length;++e)u.push([0,0]);const l=[],d=Kc({inputs:{x:a},backend:n,attrs:{paddings:u,constantValue:0}}),p=Wn(d.shape,s,i,!1),h=zn(p.length,s.length,!1),f=Vn(d.shape,s,i,!1),m=oi({inputs:{x:d},backend:n,attrs:{shape:p}}),g=gi({inputs:{x:m},backend:n,attrs:{perm:h}}),y=oi({inputs:{x:g},backend:n,attrs:{shape:f}});return l.push(d),l.push(m),l.push(g),l.forEach(e=>n.disposeIntermediateTensorInfo(e)),y}};const _d={kernelName:"SparseToDense",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{sparseIndices:a,sparseValues:s,defaultValue:o}=t,{outputShape:i}=r,{sliceRank:u,numUpdates:l,strides:c,outputSize:d}=ft(0,a,i),p=new xd(l,u,a.shape.length,s.shape.length,c,[d,1],!1),h=n.runWebGLProgram(p,[s,a,o],s.dtype),f=oi({inputs:{x:h},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(h),f}};const Ad={kernelName:"SplitV",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{numOrSizeSplits:s,axis:o}=r,i=k(o,a.shape)[0],u=er(a,s,i),l=a.shape.length,c=new Array(l).fill(0),d=a.shape.slice();return u.map(e=>{const t=[...d];t[i]=e;const r=tu({inputs:{x:a},backend:n,attrs:{begin:c,size:t}});return c[i]+=e,r})}},Rd={kernelName:"Sqrt",backendName:"webgl",kernelFunc:Yo({opSnippet:"return sqrt(x);"})},Md={kernelName:"Square",backendName:"webgl",kernelFunc:Yo({opSnippet:"return x * x;"})},Fd={kernelName:"SquaredDifference",backendName:"webgl",kernelFunc:Qo({opSnippet:"return (a - b) * (a - b);",packedOpSnippet:"return (a - b) * (a - b);"})};const Dd={kernelName:"Step",backendName:"webgl",kernelFunc:function({inputs:e,attrs:t,backend:n}){const{x:r}=e,a=`if (isnan(x)) return x;\n    return x > 0.0 ? 1.0 : float(${t.alpha});\n  `,s=new _o(r.shape,a);return n.runWebGLProgram(s,[r],r.dtype)}};class Od{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const r=n.length,a=wa(n.length),s=wa(n.length);let o="";if(1===r)o="coords * strides + begin";else{let e=0;o=n.map((t,r)=>(e++,1===n.length?`coords * strides[${r}] + begin[${r}]`:`coords[${e-1}] * strides[${r}] + begin[${r}]`)).join(",")}this.userCode=`\n      ${a} begin = ${a}(${e});\n      ${a} strides = ${a}(${t});\n\n      void main() {\n        ${s} coords = getOutputCoords();\n        setOutput(getX(${o}));\n      }\n    `}}const Pd={kernelName:"StridedSlice",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{begin:s,end:o,strides:i,beginMask:u,endMask:l,ellipsisMask:c,newAxisMask:d,shrinkAxisMask:p}=r,{nonStrided:h,$begin:f,$strides:m,size:g,newShape:y,outShape:b}=_t(a.shape,s,o,i,u,l,c,d,p),x=oi({inputs:{x:a},backend:n,attrs:{shape:y}});let k;if(h){const e=tu({inputs:{x:x},backend:n,attrs:{begin:f,size:g}});k=oi({inputs:{x:e},backend:n,attrs:{shape:b}}),n.disposeIntermediateTensorInfo(e)}else if(b.some(e=>0===e))k=n.makeTensorInfo(b,a.dtype,[]);else{if(n.shouldExecuteOnCPU([x])){const e=n.texData.get(x.dataId).values,t=lt(x.shape,x.dtype,e),r=go(b,t,m,f);k=n.makeTensorInfo(b,x.dtype,r.values)}else{const e=new Od(f,m,b);k=n.runWebGLProgram(e,[x],x.dtype)}}const w=oi({inputs:{x:k},backend:n,attrs:{shape:b}});return n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(k),w}},Ld={kernelName:"Tan",backendName:"webgl",kernelFunc:Yo({opSnippet:"return tan(x);"})},Bd={kernelName:"Tanh",backendName:"webgl",kernelFunc:Yo({opSnippet:"\n  float e2x = exp(-2.0 * abs(x));\n  return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n"})};class Wd{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e[r]*t[r];this.outputShape=n,this.rank=n.length;const r=wa(this.rank),a=function(e){const t=e.length;if(t>5)throw Error(`Tile for rank ${t} is not yet supported`);if(1===t)return`imod(resRC, ${e[0]})`;const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[];for(let t=0;t<e.length;t++)r.push(`imod(${n[t]}, ${e[t]})`);return r.join()}(e);this.userCode=`\n      void main() {\n        ${r} resRC = getOutputCoords();\n        setOutput(getA(${a}));\n      }\n    `}}function zd(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{reps:s}=r;if("string"===a.dtype){const e=n.readSync(a.dataId).map(e=>ne(e)),t=lt(a.shape,a.dtype,e),r=bo(t,s);return n.makeTensorInfo(r.shape,r.dtype,r.values)}const o=new Wd(a.shape,s);return n.runWebGLProgram(o,[a],a.dtype)}const Vd={kernelName:"Tile",backendName:"webgl",kernelFunc:zd};const Ud={kernelName:"TopK",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{k:s,sorted:o}=r,i=n.readSync(a.dataId),[u,l]=xo(i,a.shape,a.dtype,s,o);return[n.makeTensorInfo(u.shape,u.dtype,u.values),n.makeTensorInfo(l.shape,l.dtype,l.values)]}};class Gd{constructor(e,t,n,r,a,s){this.variableNames=["Image","Transforms"],this.outputShape=s;const o="nearest"===n?1:2;let i;switch(r){case"constant":i=1;break;case"reflect":i=2;break;case"wrap":i=3;break;case"nearest":i=4;break;default:i=1}this.userCode=`\n            float mapCoord(float outCoord, float len) {\n              float inCoord = outCoord;\n              if(${i} == 2) {\n                if (inCoord < 0.0) {\n                  if (len <= 1.0) {\n                    inCoord = 0.0;\n                  } else {\n                    float sz2 = 2.0 * len;\n                    if (inCoord < sz2) {\n                      inCoord = sz2 * float(int(float(-inCoord / sz2))) +\n                      inCoord;\n                    }\n                    inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;\n                  }\n                } else if (inCoord > len - 1.0) {\n                  if (len <= 1.0) {\n                    inCoord = 0.0;\n                  } else {\n                    float sz2 = 2.0 * len;\n                    inCoord -= sz2 * float(int(float(inCoord / sz2)));\n                    if (inCoord >= len) {\n                      inCoord = sz2 - inCoord - 1.0;\n                    }\n                  }\n                }\n                return clamp(inCoord, 0.0, len - 1.0);\n              } else if (${i} == 3) {\n                if (inCoord < 0.0) {\n                  if (len <= 1.0) {\n                    inCoord = 0.0;\n                  } else {\n                    float sz = len - 1.0;\n                    inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);\n                  }\n                } else if (inCoord > len - 1.0) {\n                  if (len <= 1.0) {\n                    inCoord = 0.0;\n                  } else {\n                    float sz = len - 1.0;\n                    inCoord -= len * float(int(float(inCoord / sz)));\n                  }\n                }\n                return clamp(inCoord, 0.0, len - 1.0);\n              } else if (${i} == 4) {\n                return clamp(outCoord, 0.0, len - 1.0);\n              } else {\n                return outCoord;\n              }\n            }\n\n            float readWithFillValue(int batch, int coordY, int coordX,\n              int channel) {\n              float outputValue;\n              if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) {\n                  outputValue = getImage(batch, coordY, coordX, channel);\n              } else {\n                outputValue = float(${a});\n              }\n              return outputValue;\n            }\n\n            void main() {\n              ivec4 coords = getOutputCoords();\n              float outputValue;\n              int batch = coords[0];\n              int x = coords[2];\n              int y = coords[1];\n              int channel = coords[3];\n              float xf = float(x);\n              float yf = float(y);\n              float a1 = getTransforms(batch, 0);\n              float a2 = getTransforms(batch, 1);\n              float a3 = getTransforms(batch, 2);\n              float b1 = getTransforms(batch, 3);\n              float b2 = getTransforms(batch, 4);\n              float b3 = getTransforms(batch, 5);\n              float c1 = getTransforms(batch, 6);\n              float c2 = getTransforms(batch, 7);\n              float projection = c1 * xf + c2 * yf + 1.0;\n              if (projection == 0.0) {\n                outputValue = float(${a});\n              } else {\n                float inX = (a1 * xf + a2 * yf + a3) / projection;\n                float inY = (b1 * xf + b2 * yf + b3) / projection;\n                float mapX = mapCoord(inX, float(${t}));\n                float mapY = mapCoord(inY, float(${e}));\n\n                if (${o} == 1) {\n                  int coordY = int(round(mapY));\n                  int coordX = int(round(mapX));\n                  outputValue = readWithFillValue(batch, coordY, coordX,\n                    channel);\n                } else {\n                  float yFloor = floor(mapY);\n                  float xFloor = floor(mapX);\n                  float yCeil = yFloor + 1.0;\n                  float xCeil = xFloor + 1.0;\n                  float valueYFloor = (xCeil - mapX) *\n                  readWithFillValue(batch, int(yFloor), int(xFloor), channel) +\n                  (mapX - xFloor) *\n                  readWithFillValue(batch, int(yFloor), int(xCeil), channel);\n                  float valueYCeil = (xCeil - mapX) *\n                  readWithFillValue(batch, int(yCeil), int(xFloor), channel) +\n                  (mapX - xFloor) *\n                  readWithFillValue(batch, int(yCeil), int(xCeil), channel);\n                  outputValue = (yCeil - mapY) * valueYFloor +\n                  (mapY - yFloor) * valueYCeil;\n                }\n              }\n              setOutput(outputValue);\n            }\n        `}}const Hd={kernelName:"Transform",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:a,transforms:s}=t,{interpolation:o,fillMode:i,fillValue:u,outputShape:l}=r,[c,d,p,h]=a.shape,[f,m]=null!=l?l:[d,p],g=new Gd(d,p,o,i,u,[c,f,m,h]);return n.runWebGLProgram(g,[a,s],"float32")}};const jd={kernelName:"Unique",backendName:"webgl",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{axis:a}=n,{x:s}=t;zr(s,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const o=r.readSync(s.dataId),{outputValues:i,outputShape:u,indices:l}=wo(o,a,s.shape,s.dtype);return[r.makeTensorInfo(u,s.dtype,i),r.makeTensorInfo([l.length],"int32",l)]}};const qd={kernelName:"Unpack",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{value:a}=t;let{axis:s}=r;s<0&&(s+=a.shape.length);const o=a,i=o.shape.length,u=a.shape[s],l=new Array(i-1);let c=0;for(let e=0;e<i;e++)e!==s&&(l[c++]=o.shape[e]);const d=[],p=new Array(i).fill(0),h=o.shape.slice();h[s]=1;const f=new Array(u);for(let e=0;e<f.length;e++){p[s]=e;const t=tu({inputs:{x:o},backend:n,attrs:{begin:p,size:h}}),r=oi({inputs:{x:t},backend:n,attrs:{shape:l}});f[e]=r,d.push(t)}return d.forEach(e=>n.disposeIntermediateTensorInfo(e)),f}};class Kd{constructor(e,t){this.variableNames=["x","segmentIds"];const n=e.windowSize,r=e.batchSize,a=e.inSize,s=e.numSegments,o=s*Math.ceil(a/n);this.outputShape=[r,o];const i=4*Math.floor(n/4),u=n%4,l="\n        sumValue += dot(values, segFilter);\n    ";let c="";a%n>0&&(c=`\n        if (inIdx < 0 || inIdx >= ${a}) {\n          return initializationValue;\n        }\n      `);let d="";a%n>0&&(d=`\n        if (inIdx < 0 || inIdx >= ${a}) {\n          return -1.0;\n        }\n      `),this.userCode=`\n      const float initializationValue = 0.0;\n\n      float getValue(int batch, int inIdx) {\n        ${c}\n        return getX(batch, inIdx);\n      }\n\n      float getSegmentIdAtIndex(int inIdx) {\n        ${d}\n        return getSegmentIds(inIdx);\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n        int outIdx = coords[1];\n        int inOffset = int(floor(float(outIdx) / float(\n          ${s})) * float(${n}));\n        int currentSeg = int(mod(float(outIdx), float(${s})));\n\n        float sumValue = 0.0;\n\n        for (int i = 0; i < ${i}; i += 4) {\n          int inIdx = inOffset + i;\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            getValue(batch, inIdx + 3)\n          );\n\n          vec4 segFilter = vec4(\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n          );\n\n          ${l}\n        }\n\n        int inIdx = inOffset + ${i};\n        if (${1===u}) {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            initializationValue,\n            initializationValue,\n            initializationValue\n          );\n\n          int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n          vec4 segFilter = vec4(\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n            0,\n            0,\n            0\n          );\n\n          ${l}\n        } else if (${2===u}) {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            initializationValue,\n            initializationValue\n          );\n\n          vec4 segFilter = vec4(\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n              0,\n              0\n          );\n\n          ${l}\n        } else if (${3===u}) {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            initializationValue\n          );\n\n          vec4 segFilter = vec4(\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n            0\n          );\n\n          ${l}\n        }\n        setOutput(sumValue);\n      }\n    `}}const Xd=[rc,sc,xi,ki,wi,vi,Ni,Ti,Ei,$i,Mi,Fi,Di,Oi,Li,Pi,Bi,Ui,Vi,ji,qi,Ki,Qi,ru,au,lu,du,fu,yu,Uo,Su,Ou,Pu,Au,Bu,Wu,Lu,zu,Vu,Gu,Ku,Xu,Qu,rl,al,el,ol,ul,ll,cl,dl,pl,ml,yl,xl,vl,Sl,Tl,$l,_l,Ml,Dl,Ol,Ll,Wl,zl,Vl,zo,Ul,vu,Gl,Hl,jl,jo,ql,Kl,Xl,Ql,Yl,Jl,Zl,ec,ic,cc,lc,hc,fc,mc,uc,gc,yc,bc,wc,vc,Ac,si,Mc,Dc,Pc,Bc,ou,zc,Gc,Hc,Xc,Yc,Xo,Qc,Zc,uu,Sc,ed,nd,td,ii,sd,id,ld,dd,fd,gd,yd,bd,kd,vd,Id,Nd,Sd,Cd,Td,nu,_c,Ed,$d,_d,Ad,Rd,Md,Fd,Dd,Pd,Ec,mi,Ld,Bd,Vd,Ud,Hd,yi,jd,qd,{kernelName:"UnsortedSegmentSum",backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,segmentIds:s}=t,{numSegments:o}=r,i=a.shape.length,u=[];let l=0;const c=un([l],i);let d=a;null!=c&&(d=gi({inputs:{x:a},backend:n,attrs:{perm:c}}),u.push(d),l=cn(1,i)[0]);const p=nr(d.shape,l,o),f=h([d.shape[l]]),m=oi({inputs:{x:d},backend:n,attrs:{shape:[-1,f]}});u.push(m);const g=ve(a.dtype),y=(e,t,r,a,s)=>{const o=e.shape[0],i=e.shape[1],l=tr(i,s),c=new Kd({windowSize:l,inSize:i,batchSize:o,numSegments:s},t),d=n.compileAndRun(c,[e,r],a);if(u.push(d),d.shape[1]===s)return d;const p=Jc({backend:n,attrs:{start:0,stop:s,step:1,dtype:"float32"}}),h=zd({inputs:{x:p},backend:n,attrs:{reps:[i/l]}});u.push(p),u.push(h);return y(d,t,h,a,s)},b=oi({inputs:{x:y(m,"unsortedSegmentSum",s,g,o)},backend:n,attrs:{shape:p}});let x=b;if(null!=c){u.push(b);const e=ln(c);x=gi({inputs:{x:x},backend:n,attrs:{perm:e}})}return u.forEach(e=>n.disposeIntermediateTensorInfo(e)),x}},Uc];for(const e of Xd)Y(e);const Yd=Cn;class Qd extends o{constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new s(this,Rt())}nextDataId(){return Qd.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,W().get("IS_NODE")&&Hn("\n============================\nHi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.\n============================"));const r={id:this.nextDataId()};return this.data.set(r,{values:e,dtype:n,refCount:1}),r}makeTensorInfo(e,t,n){let r;if("string"===t&&null!=n&&n.length>0&&T(n[0])){const a=n.map(e=>te(e));r=this.write(a,e,t)}else r=this.write(n,e,t);return{dataId:r,shape:e,dtype:t}}refCount(e){if(this.data.has(e)){return this.data.get(e).refCount}return 0}incRef(e){this.data.get(e).refCount++}decRef(e){if(this.data.has(e)){this.data.get(e).refCount--}}move(e,t,n,r,a){this.data.set(e,{values:t,dtype:r,refCount:a})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:n}=this.data.get(e);if("complex64"===t){return jn(this.readSync(n.real.dataId),this.readSync(n.imag.dataId))}return this.data.get(e).values}bufferSync(e){const t=this.readSync(e.dataId);let n=t;if("string"===e.dtype)try{n=t.map(e=>ne(e))}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return lt(e.shape,e.dtype,n)}makeOutput(e,t,n){const r=this.write(e,t,n);return Rt().makeTensorFromDataId(r,t,n,this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;const{complexTensorInfos:n}=this.data.get(e);null!=n&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){const t=ee();e();return{kernelMs:ee()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){Sa([e],"where");const t=this.readSync(e.dataId);return Yd(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}Qd.nextDataId=0,Ft("cpu",()=>new Qd,1);const Jd=ja("Elu",e=>e>=0?e:Math.exp(e)-1),Zd={kernelName:"Elu",backendName:"cpu",kernelFunc:Jd};function ep(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{alpha:s}=r;Sa([a],"leakyRelu");const o=h(a.shape),i=n.data.get(a.dataId).values,u=v("float32",o);for(let e=0;e<i.length;e++)u[e]=i[e]<0?s*i[e]:i[e];return n.makeTensorInfo(a.shape,"float32",u)}const tp={kernelName:"LeakyRelu",backendName:"cpu",kernelFunc:ep},np=Ea((e,t)=>e<0?t*e:e);function rp(e){const{inputs:t,backend:n}=e,{x:r,alpha:a}=t;Sa([r,a],"prelu");const s=n.data.get(r.dataId).values,o=n.data.get(a.dataId).values,[i,u]=np(r.shape,a.shape,s,o,r.dtype);return n.makeTensorInfo(u,r.dtype,i)}const ap={kernelName:"Prelu",backendName:"cpu",kernelFunc:rp},sp=ja("Relu",e=>Math.max(0,e)),op={kernelName:"Relu",backendName:"cpu",kernelFunc:sp},ip=ja("Relu6",e=>Math.min(Math.max(0,e),6)),up={kernelName:"Relu6",backendName:"cpu",kernelFunc:ip};function lp(e,t,n,r,a){if("linear"===n)return Ra({inputs:{x:t},backend:e});if("relu"===n)return sp({inputs:{x:t},backend:e});if("elu"===n)return Jd({inputs:{x:t},backend:e});if("relu6"===n)return ip({inputs:{x:t},backend:e});if("prelu"===n)return rp({inputs:{x:t,alpha:r},backend:e});if("leakyrelu"===n)return ep({inputs:{x:t},backend:e,attrs:{alpha:a}});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function cp(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{shape:s}=r,o=h(a.shape),i=x(s,o),u=h(i);c(o===u,()=>`The new shape (${i}) has ${u} elements and the old shape (${a.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`),n.incRef(a.dataId);const l=n.data.get(a.dataId);if(null!=l.complexTensorInfos){const e=l.complexTensorInfos.real,t=l.complexTensorInfos.imag;e.shape=i,t.shape=i}return{dataId:a.dataId,shape:i,dtype:a.dtype}}const dp={kernelName:"Reshape",backendName:"cpu",kernelFunc:cp};function pp(e){const{inputs:t,backend:n,attrs:r}=e,{a:a,b:s}=t,{transposeA:o,transposeB:i}=r;Sa([a,s],"matMul");const u=a.shape.length,l=s.shape.length,d=o?a.shape[u-2]:a.shape[u-1],p=i?s.shape[l-1]:s.shape[l-2],f=o?a.shape[u-1]:a.shape[u-2],m=i?s.shape[l-2]:s.shape[l-1],g=a.shape.slice(0,-2),y=s.shape.slice(0,-2),b=h(g),x=h(y);c(u>=2&&l>=2&&(b===x||1===b||1===x),()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${g}) and (${y}).`);const k=(b>x?a.shape.slice(0,-2):s.shape.slice(0,-2)).concat([f,m]);c(d===p,()=>`Error in matMul: inner shapes (${d}) and (${p}) of Tensors with shapes ${a.shape} and ${s.shape} and transposeA=${o} and transposeB=${i} must match.`);const w=i?[x,m,p]:[x,p,m],v=cp({inputs:{x:a},backend:n,attrs:{shape:o?[b,d,f]:[b,f,d]}}),I=cp({inputs:{x:s},backend:n,attrs:{shape:w}}),N=o?v.shape[1]:v.shape[2],S=o?v.shape[2]:v.shape[1],C=i?I.shape[1]:I.shape[2],T=Math.max(b,x),E=n.data.get(v.dataId).values,$=n.data.get(I.dataId).values,_=A(v.shape),R=A(I.shape),[M,F,D]=o?[_[0],1,_[1]]:[_[0],_[1],1],[O,P,L]=i?[1,R[1],R[0]]:[R[1],1,R[0]],B=S*C,W=lt([T,S,C],v.dtype),z=W.values,V=n.blockSize;for(let e=0;e<T;e++)for(let t=0;t<S;t+=V)for(let n=0;n<C;n+=V)for(let r=0;r<N;r+=V){const a=Math.min(t+V,S),s=Math.min(n+V,C),o=Math.min(r+V,N);for(let i=t;i<a;i++)for(let t=n;t<s;t++){let n=0;for(let a=r;a<o;a++){const r=Math.min(e,b-1)*M,s=Math.min(e,x-1)*L;n+=E[r+i*F+a*D]*$[a*O+t*P+s]}z[e*B+(i*C+t)]+=n}}return n.disposeIntermediateTensorInfo(v),n.disposeIntermediateTensorInfo(I),n.makeTensorInfo(k,W.dtype,W.values)}const hp={kernelName:"BatchMatMul",backendName:"cpu",kernelFunc:pp};const fp={kernelName:"_FusedMatMul",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{a:a,b:s,bias:o,preluActivationWeights:i}=t,{transposeA:u,transposeB:l,activation:c,leakyreluAlpha:d}=r;let p,h,f;const m=[];p=pp({inputs:{a:a,b:s},attrs:{transposeA:u,transposeB:l},backend:n}),o&&(h=za({inputs:{a:p,b:o},backend:n}),m.push(p),p=h),c&&(f=lp(n,p,c,i,d),m.push(p),p=f);for(const e of m)n.disposeIntermediateTensorInfo(e);return p}},mp={kernelName:"Acos",backendName:"cpu",kernelFunc:ja("Acos",e=>Math.acos(e))},gp={kernelName:"Acosh",backendName:"cpu",kernelFunc:ja("Acosh",e=>Math.acosh(e))};const yp={kernelName:"AddN",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,r=t;Sa(t,"addN");const a=r.map(e=>n.data.get(e.dataId).values),s=lt(r[0].shape,r[0].dtype),o=s.values;for(let e=0;e<r.length;e++){const t=a[e];for(let e=0;e<o.length;e++)o[e]+=t[e]}return n.makeTensorInfo(s.shape,s.dtype,s.values)}};const bp={kernelName:"All",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r;Sa(a,"all");const i=k(s,a.shape);let u=i;const l=un(u,a.shape.length);let c=a;null!=l&&(c=Cs({inputs:{x:a},backend:n,attrs:{perm:l}}),u=cn(u.length,a.shape.length)),on("all",u,c.shape.length);const[d,p]=an(c.shape,u),f=h(p),m=M(h(d),c.dtype),g=n.data.get(c.dataId).values;for(let e=0;e<m.length;++e){const t=e*f;let n=g[t];for(let e=0;e<f;++e){const r=g[t+e];n=n&&r}m[e]=n}null!=l&&n.disposeIntermediateTensorInfo(c);const y=n.makeTensorInfo(d,c.dtype,m);if(o){const e=cp({inputs:{x:y},backend:n,attrs:{shape:sn(d,i)}});return n.disposeIntermediateTensorInfo(y),e}return y}};const xp={kernelName:"Any",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r;Sa(a,"any");const i=k(s,a.shape);let u=i;const l=un(u,a.shape.length);let c=a;null!=l&&(c=Cs({inputs:{x:a},backend:n,attrs:{perm:l}}),u=cn(u.length,a.shape.length)),on("any",u,c.shape.length);const[d,p]=an(c.shape,u),f=h(p),m=M(h(d),c.dtype),g=n.data.get(c.dataId).values;for(let e=0;e<m.length;++e){const t=e*f;let n=g[t];for(let e=0;e<f;++e){const r=g[t+e];n=n||r}m[e]=n}null!=l&&n.disposeIntermediateTensorInfo(c);const y=n.makeTensorInfo(d,c.dtype,m);if(o){const e=cp({inputs:{x:y},backend:n,attrs:{shape:sn(d,i)}});return n.disposeIntermediateTensorInfo(y),e}return y}};const kp={kernelName:"ArgMax",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s}=r;Sa(a,"argMax");let o=k(s,a.shape);const i=un(o,a.shape.length);let u=a;const l=[];null!=i&&(u=Cs({inputs:{x:a},backend:n,attrs:{perm:i}}),l.push(u),o=cn(o.length,u.shape.length)),o=[o[0]],on("argMax",o,u.shape.length);const[c,d]=an(u.shape,o),p=M(h(c),"int32"),f=h(d),m=n.data.get(u.dataId).values;for(let e=0;e<p.length;++e){const t=e*f;let n=m[t],r=0;for(let e=0;e<f;++e){const a=m[t+e];a>n&&(n=a,r=e)}p[e]=r}return l.forEach(e=>n.disposeIntermediateTensorInfo(e)),n.makeTensorInfo(c,"int32",p)}};const wp={kernelName:"ArgMin",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s}=r;Sa(a,"argMin");let o=k(s,a.shape);const i=un(o,a.shape.length);let u=a;const l=[];null!=i&&(u=Cs({inputs:{x:a},backend:n,attrs:{perm:i}}),l.push(u),o=cn(o.length,u.shape.length)),o=[o[0]],on("argMin",o,u.shape.length);const[c,d]=an(u.shape,o),p=M(h(c),"int32"),f=h(d),m=n.data.get(u.dataId).values;for(let e=0;e<p.length;++e){const t=e*f;let n=m[t],r=0;for(let e=0;e<f;++e){const a=m[t+e];a<n&&(n=a,r=e)}p[e]=r}return l.forEach(e=>n.disposeIntermediateTensorInfo(e)),n.makeTensorInfo(c,"int32",p)}},vp={kernelName:"Asin",backendName:"cpu",kernelFunc:ja("Asin",e=>Math.asin(e))},Ip={kernelName:"Asinh",backendName:"cpu",kernelFunc:ja("Asinh",e=>Math.asinh(e))},Np={kernelName:"Atan",backendName:"cpu",kernelFunc:ja("Atan",e=>Math.atan(e))},Sp={kernelName:"Atan2",backendName:"cpu",kernelFunc:La("Atan2",Ea((e,t)=>Math.atan2(e,t)))},Cp={kernelName:"Atanh",backendName:"cpu",kernelFunc:ja("Atanh",e=>Math.atanh(e))};function Tp(e,t,n,r,a,s){const o=a.strideHeight,i=a.strideWidth,u=a.dilationHeight,l=a.dilationWidth,c=a.effectiveFilterHeight,d=a.effectiveFilterWidth,p=a.padInfo.top,h=a.padInfo.left,f="max"===s?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=lt(a.outShape,n),g=m.values,y=a.outShape[1]*a.outShape[2]*a.outShape[3],b=a.outShape[2]*a.outShape[3],x=a.outShape[3];for(let t=0;t<a.batchSize;++t){const n=t*y,m=t*r[0];for(let t=0;t<a.inChannels;++t)for(let y=0;y<a.outHeight;++y){const k=y*o-p,w=Math.max(0,k),v=Math.min(a.inHeight,c+k),I=n+y*b;for(let n=0;n<a.outWidth;++n){const o=n*i-h,c=Math.max(0,o),p=Math.min(a.inWidth,d+o);let y=f,b=0,k=0;for(let n=w;n<v;n+=u){const a=m+n*r[1];for(let n=c;n<p;n+=l){const o=e[a+n*r[2]+t];"max"===s&&o>y?y=o:"avg"===s&&(b+=o,k++)}if(isNaN(y))break}g[I+n*x+t]="avg"===s?b/k:y}}}return m}function Ep(e,t,n,r,a=!1,s=!1){const o=lt(r.outShape,"int32"),i=r.strideHeight,u=r.strideWidth,l=r.dilationHeight,c=r.dilationWidth,d=r.effectiveFilterHeight,p=r.effectiveFilterWidth,h=r.padInfo.top,f=r.padInfo.left,m=lt(t,n,e);for(let e=0;e<r.batchSize;++e)for(let t=0;t<r.inChannels;++t)for(let n=0;n<r.outHeight;++n){const g=n*i-h;let y=g;for(;y<0;)y+=l;const b=Math.min(r.inHeight,d+g);for(let i=0;i<r.outWidth;++i){const d=i*u-f;let h=d;for(;h<0;)h+=c;const x=Math.min(r.inWidth,p+d);let k=Number.NEGATIVE_INFINITY,w=-1;for(let n=y;n<b;n+=l){const o=n-g;for(let i=h;i<x;i+=c){const u=i-d,l=m.get(e,n,i,t);l>k&&(k=l,w=a?s?((e*r.inHeight+n)*r.inWidth+i)*r.inChannels+t:(n*r.inWidth+i)*r.inChannels+t:o*p+u)}}o.set(w,e,n,i,t)}}return o}function $p(e,t,n,r,a,s){const o=a.strideDepth,i=a.strideHeight,u=a.strideWidth,l=a.dilationDepth,c=a.dilationHeight,d=a.dilationWidth,p=a.effectiveFilterDepth,h=a.effectiveFilterHeight,f=a.effectiveFilterWidth,m=a.padInfo.front,g=a.padInfo.top,y=a.padInfo.left,b="max"===s?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=lt(a.outShape,n),k=x.values,w=a.outShape[1]*a.outShape[2]*a.outShape[3]*a.outShape[4],v=a.outShape[2]*a.outShape[3]*a.outShape[4],I=a.outShape[3]*a.outShape[4],N=a.outShape[4];for(let t=0;t<a.batchSize;++t){const n=t*w,x=t*r[0];for(let t=0;t<a.inChannels;++t)for(let w=0;w<a.outDepth;++w){const S=w*o-m;let C=S;for(;C<0;)C+=l;const T=Math.min(a.inDepth,p+S),E=n+w*v;for(let n=0;n<a.outHeight;++n){const o=n*i-g;let p=o;for(;p<0;)p+=c;const m=Math.min(a.inHeight,h+o),w=E+n*I;for(let n=0;n<a.outWidth;++n){const o=n*u-y;let i=o;for(;i<0;)i+=d;const h=Math.min(a.inWidth,f+o),g=w+n*N;let v=b,I=0,S=0;for(let n=C;n<T;n+=l){const a=x+n*r[1];for(let n=p;n<m;n+=c){const o=a+n*r[2];for(let n=i;n<h;n+=d){const a=e[o+n*r[3]+t];if("max"===s&&a>v?v=a:"avg"===s&&(I+=a,S++),isNaN(v))break}if(isNaN(v))break}if(isNaN(v))break}k[g+t]="avg"===s?I/S:v}}}}return x}const _p={kernelName:"AvgPool",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t;Sa(a,"avgPool");const{filterSize:s,strides:o,pad:i,dimRoundingMode:u}=r;c(qt(o,1),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '1'`);const l=Pt(a.shape,s,o,1,i,u);let d;if(1===l.filterWidth&&1===l.filterHeight&&f(l.inShape,l.outShape))d=Ra({inputs:{x:a},backend:n});else{const e=n.data.get(a.dataId).values,t=A(a.shape),r=Tp(e,a.shape,a.dtype,t,l,"avg");d=n.makeTensorInfo(l.outShape,a.dtype,r.values)}return d}};const Ap={kernelName:"AvgPool3D",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{filterSize:s,strides:o,pad:i,dimRoundingMode:u,dataFormat:l}=r;Sa(a,"avgPool3d");const c=Lt(a.shape,s,o,1,i,u,l),d=$p(n.data.get(a.dataId).values,a.shape,a.dtype,A(a.shape),c,"avg");return n.makeTensorInfo(d.shape,"float32",d.values)}};const Rp={kernelName:"AvgPool3DGrad",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s}=t,{filterSize:o,strides:i,pad:u,dimRoundingMode:l}=r;Sa([a,s],"avgPool3DGrad");const c=Lt(s.shape,o,i,1,u,l),d=c.strideDepth,p=c.strideHeight,h=c.strideWidth,f=c.filterDepth,m=c.filterHeight,g=c.filterWidth,y=c.dilationDepth,b=c.dilationHeight,x=c.dilationWidth,k=c.effectiveFilterDepth,w=c.effectiveFilterHeight,v=c.effectiveFilterWidth,I=k-1-c.padInfo.front,N=v-1-c.padInfo.left,S=w-1-c.padInfo.top,C=lt(s.shape,"float32"),T=1/(f*m*g),E=n.bufferSync(a);for(let e=0;e<c.batchSize;++e)for(let t=0;t<c.inChannels;++t)for(let n=0;n<c.inDepth;++n)for(let r=0;r<c.inHeight;++r)for(let a=0;a<c.inWidth;++a){const s=n-I,o=r-S,i=a-N;let u=0;for(let n=0;n<k;n+=y){const r=(s+n)/d;if(!(r<0||r>=c.outDepth||Math.floor(r)!==r))for(let n=0;n<w;n+=b){const a=(o+n)/p;if(!(a<0||a>=c.outHeight||Math.floor(a)!==a))for(let n=0;n<v;n+=x){const s=(i+n)/h;if(s<0||s>=c.outWidth||Math.floor(s)!==s)continue;u+=E.get(e,r,a,s,t)}}}C.set(u*T,e,n,r,a,t)}return n.makeTensorInfo(C.shape,C.dtype,C.values)}};const Mp={kernelName:"AvgPoolGrad",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s}=t,o=s;Sa([a,s],"avgPoolGrad");const{filterSize:i,strides:u,pad:l}=r,c=Pt(o.shape,i,u,1,l),d=c.strideHeight,p=c.strideWidth,h=c.filterHeight,f=c.filterWidth,m=c.dilationHeight,g=c.dilationWidth,y=c.effectiveFilterHeight,b=c.effectiveFilterWidth,x=b-1-c.padInfo.left,k=y-1-c.padInfo.top,w=lt(o.shape,"float32"),v=1/(h*f),I=n.data.get(a.dataId).values,N=lt(a.shape,"float32",I);for(let e=0;e<c.batchSize;++e)for(let t=0;t<c.inChannels;++t)for(let n=0;n<c.inHeight;++n)for(let r=0;r<c.inWidth;++r){const a=n-k,s=r-x;let o=0;for(let n=0;n<y;n+=m){const r=(a+n)/d;if(!(r<0||r>=c.outHeight||Math.floor(r)!==r))for(let n=0;n<b;n+=g){const a=(s+n)/p;if(a<0||a>=c.outWidth||Math.floor(a)!==a)continue;o+=N.get(e,r,a,t)}}w.set(o*v,e,n,r,t)}return n.makeTensorInfo(w.shape,w.dtype,w.values)}};const Fp={kernelName:"FusedBatchNorm",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,scale:s,offset:o,mean:i,variance:u}=t;c(i.shape.length===u.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),c(null==o||i.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),c(null==s||i.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),Sa([a,i,u,s,o],"batchNorm");let{varianceEpsilon:l}=r;null==l&&(l=.001);const d=n.data.get(a.dataId).values,p=n.data.get(i.dataId).values,h=n.data.get(u.dataId).values,f=s?n.data.get(s.dataId).values:new Float32Array([1]),m=o?n.data.get(o.dataId).values:new Float32Array([0]),g=new Float32Array(d.length),y=m.length,b=f.length,x=h.length,k=p.length;let w=0,v=0,I=0,N=0;for(let e=0;e<d.length;++e)g[e]=m[w++]+(d[e]-p[v++])*f[I++]/Math.sqrt(h[N++]+l),w>=y&&(w=0),v>=k&&(v=0),I>=b&&(I=0),N>=x&&(N=0);return n.makeTensorInfo(a.shape,a.dtype,g)}};const Dp={kernelName:"BatchToSpaceND",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,crops:o}=r;Sa([a],"batchToSpaceND");const i=s.reduce((e,t)=>e*t),u=Wn(a.shape,s,i),l=zn(u.length,s.length),c=Vn(a.shape,s,i),d=Un(o,s.length),p=Gn(c,o,s.length),h=cp({inputs:{x:a},backend:n,attrs:{shape:u}}),f=Cs({inputs:{x:h},backend:n,attrs:{perm:l}}),m=cp({inputs:{x:f},backend:n,attrs:{shape:c}}),g=Fs({inputs:{x:m},backend:n,attrs:{begin:d,size:p}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}};const Op={kernelName:"Bincount",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,weights:s}=t,{size:o}=r,i=Ua(n.data.get(a.dataId).values,n.data.get(s.dataId).values,s.dtype,s.shape,o);return n.makeTensorInfo([o],s.dtype,i)}},Pp={kernelName:"ClipByValue",backendName:"cpu",kernelFunc:ja("ClipByValue",(e,t)=>{const n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e})},Lp={kernelName:"ComplexAbs",backendName:"cpu",kernelFunc:e=>{const{x:t}=e.inputs,n=e.backend,r=new Float32Array(h(t.shape)),a=n.data.get(t.dataId),s=a.complexTensorInfos.real,o=a.complexTensorInfos.imag,i=n.data.get(s.dataId).values,u=n.data.get(o.dataId).values;for(let e=0;e<i.length;e++){const t=i[e],n=u[e];r[e]=Math.hypot(t,n)}return n.makeOutput(r,t.shape,"float32")}};function Bp(e){const{inputs:t,backend:n}=e,{input:r}=t,a=n.data.get(r.dataId).complexTensorInfos.imag,s=n.data.get(a.dataId).values;return n.makeTensorInfo(a.shape,a.dtype,s)}const Wp={kernelName:"Imag",backendName:"cpu",kernelFunc:Bp};function zp(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r,s=k(a,t[0].shape)[0];let o=Pn(t.map(e=>e.shape),s);if(0===h(o))return n.makeTensorInfo(o,t[0].dtype,[]);const i=t.filter(e=>h(e.shape)>0);if(1===i.length)return Ra({inputs:{x:i[0]},backend:n});if(On(i.map(e=>e.shape),s),"complex64"===i[0].dtype){const e=i.map(e=>Fa({inputs:{input:e},backend:n})),t=i.map(e=>Bp({inputs:{input:e},backend:n})),r=zp({inputs:e,backend:n,attrs:{axis:s}}),a=zp({inputs:t,backend:n,attrs:{axis:s}}),o=$a({inputs:{real:r,imag:a},backend:n});return e.forEach(e=>n.disposeIntermediateTensorInfo(e)),t.forEach(e=>n.disposeIntermediateTensorInfo(e)),n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(a),o}const u=i.map(e=>{const t=h(e.shape.slice(s));return cp({inputs:{x:e},backend:n,attrs:{shape:[-1,t]}})}),l=u.map(e=>({vals:n.data.get(e.dataId).values,shape:e.shape}));o=Pn(u.map(e=>e.shape),1);const c=1===u[0].shape[0],d=Ya(l,o,t[0].dtype,c),p=Pn(i.map(e=>e.shape),s),f=n.makeTensorInfo(p,t[0].dtype,d);return u.forEach(e=>n.disposeIntermediateTensorInfo(e)),f}const Vp={kernelName:"Concat",backendName:"cpu",kernelFunc:zp};function Up(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dataFormat:u,dilations:l,dimRoundingMode:c}=r;Sa([a,s],"conv2d");const d=Kt(u),p=Bt(a.shape,s.shape,o,l,i,c,!1,d),h=p.filterHeight,f=p.filterWidth,m=p.dilationHeight,g=p.dilationWidth,y=p.padInfo.left,b=p.padInfo.top,x="channelsLast"===p.dataFormat,k=new ce(p.outShape,a.dtype),w=A(a.shape),v=A(s.shape),I=w[0],N=x?w[1]:w[2],S=x?w[2]:1,C=x?1:w[1],T=k.strides[0],E=x?k.strides[1]:k.strides[2],$=x?k.strides[2]:1,_=x?1:k.strides[1],R=n.data.get(a.dataId).values,M=n.data.get(s.dataId).values,F=k.values;for(let e=0;e<p.batchSize;++e){const t=e*I,n=e*T;for(let e=0;e<p.outHeight;++e){const r=n+e*E,a=e*p.strideHeight-b;for(let e=0;e<h;++e){const n=a+e*m;if(n<0||n>=p.inHeight)continue;const s=e*v[0],o=t+n*N;for(let e=0;e<p.outWidth;++e){const t=r+e*$,n=e*p.strideWidth-y;for(let e=0;e<f;++e){const r=n+e*g;if(r<0||r>=p.inWidth)continue;const a=o+r*S;let i=s+e*v[1];for(let e=0;e<p.inChannels;++e){const n=R[a+e*C];for(let e=0;e<p.outChannels;++e)F[t+e*_]+=n*M[i+e];i+=p.outChannels}}}}}}return n.makeTensorInfo(k.shape,k.dtype,F)}const Gp={kernelName:"Conv2D",backendName:"cpu",kernelFunc:Up};const Hp={kernelName:"Conv2DBackpropFilter",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,dy:s}=t,{strides:o,pad:i,dataFormat:u,dimRoundingMode:l,filterShape:c}=r;Sa([a,s],"conv2dBackpropFilter");const d=Kt(u),p=Bt(a.shape,c,o,1,i,l,!1,d),{strideHeight:h,strideWidth:f,filterHeight:m,filterWidth:g}=p,y="channelsLast"===p.dataFormat,b=new ce(p.filterShape,"float32"),x=p.padInfo.left,k=p.padInfo.top,w=n.data.get(a.dataId).values,v=n.data.get(s.dataId).values,I=new ce(a.shape,a.dtype,w),N=new ce(s.shape,s.dtype,v);for(let e=0;e<m;++e){const t=Math.max(0,Math.ceil((k-e)/h)),n=Math.min(p.outHeight,(p.inHeight+k-e)/h);for(let r=0;r<g;++r){const a=Math.max(0,Math.ceil((x-r)/f)),s=Math.min(p.outWidth,(p.inWidth+x-r)/f);for(let o=0;o<p.inChannels;++o)for(let i=0;i<p.outChannels;++i){let u=0;for(let l=0;l<p.batchSize;++l)for(let c=t;c<n;++c){const t=e+c*h-k;for(let e=a;e<s;++e){const n=r+e*f-x;u+=y?I.get(l,t,n,o)*N.get(l,c,e,i):I.get(l,o,t,n)*N.get(l,i,c,e)}}b.set(u,e,r,o,i)}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}};const jp={kernelName:"Conv2DBackpropInput",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:s}=t,{inputShape:o,strides:i,pad:u,dataFormat:l,dimRoundingMode:c}=r;Sa([a,s],"conv2dBackpropInput");const d=A(s.shape),p=A(a.shape);let h=Kt(l);const f=Bt(o,s.shape,i,1,u,c,!1,h),m=new ce(f.inShape,"float32"),g=m.values,y=n.data.get(a.dataId).values,b=n.data.get(s.dataId).values,[x,k,w]=d,{batchSize:v,filterHeight:I,filterWidth:N,inChannels:S,inHeight:C,inWidth:T,outChannels:E,outHeight:$,outWidth:_,strideHeight:R,strideWidth:M}=f;h=f.dataFormat;const F=I-1-f.padInfo.top,D=N-1-f.padInfo.left,O="channelsLast"===h,P=m.strides[0],L=O?m.strides[1]:m.strides[2],B=O?m.strides[2]:1,W=O?1:m.strides[1],z=p[0],V=O?p[1]:p[2],U=O?p[2]:1,G=O?1:p[1];for(let e=0;e<v;++e)for(let t=0;t<S;++t)for(let n=0;n<C;++n){const r=n-F,a=Math.max(0,Math.ceil(r/R)),s=Math.min($,(I+r)/R);for(let o=0;o<T;++o){const i=o-D,u=Math.max(0,Math.ceil(i/M)),l=Math.min(_,(N+i)/M);let c=0;for(let n=a;n<s;++n){const a=n*R-r;for(let r=u;r<l;++r){const s=z*e+V*n+U*r,o=x*(I-1-a)+k*(N-1-(r*M-i))+w*t;for(let e=0;e<E;++e){c+=y[s+G*e]*b[o+e]}}}g[P*e+L*n+B*o+W*t]=c}}return n.makeTensorInfo(m.shape,m.dtype,m.values)}};const qp={kernelName:"Conv3D",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dilations:u}=r;Sa([a,s],"conv3d");const l=Wt(a.shape,s.shape,o,u,i),{filterDepth:c,filterHeight:d,filterWidth:p,dilationDepth:h,dilationHeight:f,dilationWidth:m,padInfo:g}=l,y=g.front,b=g.left,x=g.top,k=new ce(l.outShape,a.dtype),w=n.data.get(a.dataId).values,v=n.data.get(s.dataId).values,I=k.values,N=A(a.shape),S=A(s.shape);for(let e=0;e<l.batchSize;++e){const t=e*N[0],n=e*k.strides[0];for(let e=0;e<l.outDepth;++e){const r=n+e*k.strides[1],a=e*l.strideDepth-y;for(let e=0;e<c;++e){const n=a+e*h;if(n<0||n>=l.inDepth)continue;const s=e*S[0],o=t+n*N[1];for(let e=0;e<l.outHeight;++e){const t=r+e*k.strides[2],n=e*l.strideHeight-x;for(let e=0;e<d;++e){const r=n+e*f;if(r<0||r>=l.inHeight)continue;const a=s+e*S[1],i=o+r*N[2];for(let e=0;e<l.outWidth;++e){const n=t+e*l.outChannels,r=e*l.strideWidth-b;for(let e=0;e<p;++e){const t=r+e*m;if(t<0||t>=l.inWidth)continue;const s=a+e*S[2],o=i+t*l.inChannels;let u=s;for(let e=0;e<l.inChannels;++e){const t=w[o+e];for(let e=0;e<l.outChannels;++e)I[n+e]+=t*v[u+e];u+=l.outChannels}}}}}}}}return n.makeTensorInfo(k.shape,k.dtype,k.values)}};const Kp={kernelName:"Conv3DBackpropFilterV2",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,dy:s}=t,{strides:o,pad:i,filterShape:u}=r;Sa([a,s],"conv3dBackpropFilterV2");const l=A(a.shape),c=A(s.shape),d=Wt(a.shape,u,o,1,i),p=d.strideDepth,h=d.strideHeight,f=d.strideWidth,m=d.filterDepth,g=d.filterHeight,y=d.filterWidth,b=new ce(d.filterShape,"float32"),x=b.values,[k,w,v,I]=b.strides,N=n.data.get(s.dataId).values,[S,C,T,E]=c,$=n.data.get(a.dataId).values,[_,R,M,F]=l,D=d.padInfo.front,O=d.padInfo.left,P=d.padInfo.top;for(let e=0;e<m;++e){const t=Math.max(0,Math.ceil((D-e)/p)),n=Math.min(d.outDepth,(d.inDepth+D-e)/p),r=e*k;for(let a=0;a<g;++a){const s=Math.max(0,Math.ceil((P-a)/h)),o=Math.min(d.outHeight,(d.inHeight+P-a)/h),i=a*w+r;for(let r=0;r<y;++r){const u=Math.max(0,Math.ceil((O-r)/f)),l=Math.min(d.outWidth,(d.inWidth+O-r)/f),c=r*v+i;for(let i=0;i<d.inChannels;++i){const m=i*I+c;for(let c=0;c<d.outChannels;++c){let g=0;for(let m=0;m<d.batchSize;++m){const d=m*_,y=m*S;for(let m=t;m<n;++m){const t=(e+m*p-D)*R+d,n=m*C+y;for(let e=s;e<o;++e){const s=(a+e*h-P)*M+t,o=e*T+n;for(let e=u;e<l;++e){const t=e*E+o;g+=$[(r+e*f-O)*F+s+i]*N[t+c]}}}}x[m+c]=g}}}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}};const Xp={kernelName:"Conv3DBackpropInputV2",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:s}=t,{pad:o,strides:i,inputShape:u}=r;Sa([a],"conv3dBackpropInputV2");const l=A(a.shape),c=A(s.shape),d=Wt(u,s.shape,i,1,o),p=new ce(d.inShape,"float32"),h=p.values,[f,m,g,y]=p.strides,b=n.data.get(a.dataId).values,[x,k,w,v]=l,I=n.data.get(s.dataId).values,[N,S,C,T]=c,{batchSize:E,filterDepth:$,filterHeight:_,filterWidth:R,inChannels:M,inDepth:F,inHeight:D,inWidth:O,outChannels:P,outDepth:L,outHeight:B,outWidth:W,strideDepth:z,strideHeight:V,strideWidth:U}=d,G=$-1-d.padInfo.front,H=_-1-d.padInfo.top,j=R-1-d.padInfo.left;for(let e=0;e<E;++e)for(let t=0;t<M;++t)for(let n=0;n<F;++n){const r=n-G,a=Math.max(0,Math.ceil(r/z)),s=Math.min(L,($+r)/z);for(let o=0;o<D;++o){const i=o-H,u=Math.max(0,Math.ceil(i/V)),l=Math.min(B,(_+i)/V);for(let c=0;c<O;++c){const d=c-j,p=Math.max(0,Math.ceil(d/U)),E=Math.min(W,(R+d)/U);let A=0;for(let n=a;n<s;++n){const a=n*z-r;for(let r=u;r<l;++r){const s=r*V-i;for(let o=p;o<E;++o){const i=x*e+k*n+w*r+v*o,u=N*($-1-a)+S*(_-1-s)+C*(R-1-(o*U-d))+T*t;for(let e=0;e<P;++e){A+=b[i+e]*I[u+e]}}}}h[f*e+m*n+g*o+y*c+t]=A}}}return n.makeTensorInfo(p.shape,p.dtype,p.values)}},Yp={kernelName:"Cos",backendName:"cpu",kernelFunc:ja("Cos",e=>Math.cos(e))},Qp={kernelName:"Cosh",backendName:"cpu",kernelFunc:ja("Cosh",e=>Math.cosh(e))};const Jp={kernelName:"CropAndResize",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{image:a,boxes:s,boxInd:o}=t,{cropSize:i,method:u,extrapolationValue:l}=r,[c,d,p,h]=a.shape,f=s.shape[0],[m,g]=i,y=lt([f,m,g,h],"float32"),b=n.data.get(s.dataId).values,x=n.data.get(o.dataId).values,k=n.data.get(a.dataId).values,w=A(a.shape),v=A(y.shape);for(let e=0;e<f;e++){const t=4*e,n=b[t],r=b[t+1],a=b[t+2],s=b[t+3],o=x[e];if(o>=c)continue;const i=m>1?(a-n)*(d-1)/(m-1):0,f=g>1?(s-r)*(p-1)/(g-1):0;for(let t=0;t<m;t++){const c=m>1?n*(d-1)+t*i:.5*(n+a)*(d-1);if(c<0||c>d-1)for(let n=0;n<g;n++)for(let r=0;r<h;r++){const a=r+n*v[2]+t*v[1]+e*v[0];y.values[a]=l}else if("bilinear"===u){const n=Math.floor(c),a=Math.ceil(c),i=c-n;for(let u=0;u<g;u++){const c=g>1?r*(p-1)+u*f:.5*(r+s)*(p-1);if(c<0||c>p-1){for(let n=0;n<h;n++){const r=n+u*v[2]+t*v[1]+e*v[0];y.values[r]=l}continue}const d=Math.floor(c),m=Math.ceil(c),b=c-d;for(let r=0;r<h;r++){let s=r+d*w[2]+n*w[1]+o*w[0];const l=k[s];s=r+m*w[2]+n*w[1]+o*w[0];const c=k[s];s=r+d*w[2]+a*w[1]+o*w[0];const p=k[s];s=r+m*w[2]+a*w[1]+o*w[0];const h=l+(c-l)*b,f=p+(k[s]-p)*b;s=r+u*v[2]+t*v[1]+e*v[0],y.values[s]=h+(f-h)*i}}}else for(let n=0;n<g;++n){const a=g>1?r*(p-1)+n*f:.5*(r+s)*(p-1);if(a<0||a>p-1){for(let r=0;r<h;r++){const a=r+n*v[2]+t*v[1]+e*v[0];y.values[a]=l}continue}const i=Math.round(a),u=Math.round(c);for(let r=0;r<h;r++){const a=r+i*w[2]+u*w[1]+o*w[0],s=r+n*v[2]+t*v[1]+e*v[0];y.values[s]=k[a]}}}}return n.makeTensorInfo(y.shape,y.dtype,y.values)}};const Zp={kernelName:"Cumsum",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,exclusive:o,reverse:i}=r;Sa(a,"cumsum");const u=un([s],a.shape.length);let l=a;null!=u&&(l=Cs({inputs:{x:a},backend:n,attrs:{perm:u}}));const c=cn(1,a.shape.length)[0];if(c!==l.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${l.shape.length-1} but got axis=${c}`);const d=we(l.dtype,"int32"),p=M(h(l.shape),d),f=n.data.get(l.dataId).values,m=l.shape[l.shape.length-1],g=i?(e,t)=>e+m-t-1:(e,t)=>e+t;for(let e=0;e<f.length;e+=m)for(let t=0;t<m;t++){const n=g(e,t);if(0===t)p[n]=o?0:f[n];else{const r=g(e,t-1);p[n]=o?f[r]+p[r]:f[n]+p[r]}}const y=n.makeTensorInfo(l.shape,d,p);if(null!=u){const e=Cs({inputs:{x:y},backend:n,attrs:{perm:ln(u)}});return n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(l),e}return y}};const eh={kernelName:"DenseBincount",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,weights:s}=t,{size:o,binaryOutput:i}=r;if(1===a.shape.length){const e=Ua(n.data.get(a.dataId).values,n.data.get(s.dataId).values,s.dtype,s.shape,o);return n.makeTensorInfo([o],s.dtype,e)}if(2===a.shape.length){const e=Ga(n.bufferSync(a),n.bufferSync(s),o,i);return n.makeTensorInfo(e.shape,s.dtype,e.values)}throw new Error("Error in denseBincount: input must be at most rank 2, but got rank"+a.shape.length+".")}};const th={kernelName:"DepthToSpace",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockSize:s,dataFormat:o}=r;c("NHWC"===o,()=>"Only NHWC dataFormat supported on CPU for depthToSpace. Got "+o),c(s>1,()=>"blockSize should be > 1 for depthToSpace, but was: "+s);const i=a.shape[0],u=a.shape[1],l=a.shape[2],d=a.shape[3],p=u*s,h=l*s,f=d/(s*s),m=n.data.get(a.dataId).values,g=new Float32Array(i*p*h*f);let y=0;for(let e=0;e<i;++e)for(let t=0;t<p;++t){const n=Math.floor(t/s),r=t%s;for(let t=0;t<h;++t){const a=Math.floor(t/s),o=(r*s+t%s)*f;for(let t=0;t<f;++t){const r=t+o+d*(a+l*(n+u*e));g[y++]=m[r]}}}return n.makeTensorInfo([i,p,h,f],a.dtype,g)}};function nh(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s}=t,{strides:o,pad:i,dilations:u,dimRoundingMode:l}=r;Sa([a,s],"depthwiseConv2DNative");const d=A(a.shape),p=A(s.shape);let h=u;null==h&&(h=[1,1]),c(qt(o,h),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${h}'`);const f=Bt(a.shape,s.shape,o,h,i,l,!0),{filterHeight:m,filterWidth:g,dilationHeight:y,dilationWidth:b,padInfo:x}=f,k=x.left,w=x.top,v=f.outChannels/f.inChannels,I=new ce(f.outShape,a.dtype),N=n.data.get(a.dataId).values,S=n.data.get(s.dataId).values,C=I.values;for(let e=0;e<f.batchSize;++e){const t=e*d[0],n=e*I.strides[0];for(let e=0;e<f.outHeight;++e){const r=n+e*I.strides[1],a=e*f.strideHeight-k;for(let e=0;e<m;++e){const n=a+e*y;if(n<0||n>=f.inHeight)continue;const s=e*p[0],o=t+n*d[1];for(let e=0;e<f.outWidth;++e){const t=r+e*I.strides[2],n=e*f.strideWidth-w;for(let e=0;e<g;++e){const r=n+e*b;if(r<0||r>=f.inWidth)continue;const a=s+e*p[1],i=o+r*f.inChannels;let u=t,l=a;for(let e=0;e<f.inChannels;++e){const t=N[i+e];for(let e=0;e<v;++e)C[u+e]+=t*S[l+e];u+=v,l+=v}}}}}}return n.makeTensorInfo(I.shape,I.dtype,I.values)}const rh={kernelName:"DepthwiseConv2dNative",backendName:"cpu",kernelFunc:nh};const ah={kernelName:"DepthwiseConv2dNativeBackpropFilter",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,dy:s}=t,{strides:o,dilations:i,pad:u,dimRoundingMode:l,filterShape:c}=r;Sa([a,s],"depthwiseConv2dNativeBackpropFilter");const d=Bt(a.shape,c,o,i,u,l,!0),{strideHeight:p,strideWidth:h,filterHeight:f,filterWidth:m}=d,g=new ce(d.filterShape,"float32"),y=d.padInfo.left,b=d.padInfo.top,x=d.outChannels/d.inChannels,k=n.data.get(a.dataId).values,w=new ce(a.shape,a.dtype,k),v=n.data.get(s.dataId).values,I=new ce(s.shape,s.dtype,v);for(let e=0;e<f;++e){const t=Math.max(0,Math.ceil((b-e)/p)),n=Math.min(d.outHeight,(d.inHeight+b-e)/p);for(let r=0;r<m;++r){const a=Math.max(0,Math.ceil((y-r)/h)),s=Math.min(d.outWidth,(d.inWidth+y-r)/h);for(let o=0;o<d.outChannels;++o){const i=Math.trunc(o/x),u=o%x;let l=0;for(let u=0;u<d.batchSize;++u)for(let c=t;c<n;++c){const t=e+c*p-b;for(let e=a;e<s;++e){const n=r+e*h-y;l+=w.get(u,t,n,i)*I.get(u,c,e,o)}}g.set(l,e,r,i,u)}}}return n.makeTensorInfo(g.shape,g.dtype,g.values)}};const sh={kernelName:"DepthwiseConv2dNativeBackpropInput",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,filter:s}=t,{strides:o,dilations:i,pad:u,dimRoundingMode:l,inputShape:c}=r;Sa([a,s],"depthwiseConv2DNativeBackpropInput");const d=A(a.shape),p=A(s.shape),h=Bt(c,s.shape,o,i,u,l,!0),f=new ce(h.inShape,"float32"),m=f.values,[g,y,b]=f.strides,x=n.data.get(a.dataId).values,[k,w,v]=d,I=n.data.get(s.dataId).values,[N,S,C]=p,{batchSize:T,filterHeight:E,filterWidth:$,inChannels:_,inHeight:R,inWidth:M,outChannels:F,outHeight:D,outWidth:O,strideHeight:P,strideWidth:L}=h,B=E-1-h.padInfo.top,W=$-1-h.padInfo.left,z=F/_;for(let e=0;e<T;++e)for(let t=0;t<_;++t)for(let n=0;n<R;++n){const r=n-B,a=Math.max(0,Math.ceil(r/P)),s=Math.min(D,(E+r)/P);for(let o=0;o<M;++o){const i=o-W,u=Math.max(0,Math.ceil(i/L)),l=Math.min(O,($+i)/L);let c=0;for(let n=a;n<s;++n){const a=n*P-r;for(let r=u;r<l;++r){const s=k*e+w*n+v*r,o=N*(E-1-a)+S*($-1-(r*L-i))+C*t;for(let e=0;e<z;++e){c+=x[s+(t*z+e)]*I[o+e]}}}m[g*e+y*n+b*o+t]=c}}return n.makeTensorInfo(f.shape,f.dtype,f.values)}};const oh={kernelName:"Diag",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:r}=t,a=h(r.shape),s=n.data.get(r.dataId).values,o=lt([a,a],r.dtype),i=o.values;for(let e=0;e<s.length;e++)i[e*a+e]=s[e];const u=[...r.shape,...r.shape];return n.makeTensorInfo(u,o.dtype,o.values)}},ih={kernelName:"Dilation2D",backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r,filter:a}=e,{strides:s,pad:o,dilations:i}=n,u=t,l=u.data.get(r.dataId).values,c=r.shape.length,d=u.data.get(a.dataId).values,p=a.shape.length,{batchSize:f,inHeight:m,inWidth:g,inChannels:y,outHeight:b,outWidth:x,padInfo:k,strideHeight:w,strideWidth:v,filterHeight:N,filterWidth:S,dilationHeight:C,dilationWidth:T,outShape:E}=Ot(r.shape,a.shape,s,o,"NHWC",i),$=h(E),_=E.length,R=I(r.dtype,$);for(let e=0;e<f;++e)for(let t=0;t<b;++t){const n=t*w-k.top;for(let s=0;s<x;++s){const o=s*v-k.left;for(let i=0;i<y;++i){let u=Number.MIN_SAFE_INTEGER;for(let t=0;t<N;++t){const s=n+t*C;if(s>=0&&s<m)for(let n=0;n<S;++n){const h=o+n*T;if(h>=0&&h<g){const o=O([e,s,h,i],c,A(r.shape)),f=O([t,n,i],p,A(a.shape)),m=l[o]+d[f];m>u&&(u=m)}}}R[O([e,t,s,i],_,A(E))]=u}}}return{dataId:u.write(Z(R,r.dtype),E,r.dtype),shape:E,dtype:r.dtype}}},uh={kernelName:"Dilation2DBackpropFilter",backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r,filter:a,dy:s}=e,{strides:o,pad:i,dilations:u}=n,l=t,d=R(r.shape,l.data.get(r.dataId).values),p=R(a.shape,l.data.get(a.dataId).values),{batchSize:h,inHeight:f,inWidth:m,inChannels:g,outHeight:y,outWidth:b,padInfo:x,strideHeight:k,strideWidth:w,filterHeight:v,filterWidth:I,dilationHeight:N,dilationWidth:S,outShape:C}=Ot(r.shape,a.shape,o,i,"NHWC",u);c(s.rank===C.length,()=>`Error in Dilation2DBackpropFilter, dy must have the same rank as output ${C.length}, but got `+s.rank);const T=R(C,l.data.get(s.dataId).values),E=F(a.shape,a.dtype);for(let e=0;e<h;++e)for(let t=0;t<y;++t){const n=t*k-x.top;for(let r=0;r<b;++r){const a=r*w-x.left;for(let s=0;s<g;++s){let o=Number.MIN_SAFE_INTEGER,i=0,u=0;for(let t=0;t<v;++t){const r=n+t*N;if(r>=0&&r<f)for(let n=0;n<I;++n){const l=a+n*S;if(l>=0&&l<m){const a=d[e][r][l][s]+p[t][n][s];a>o&&(o=a,i=t,u=n)}}}E[i][u][s]+=T[e][t][r][s]}}}return{dataId:l.write(Z(E,r.dtype),a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}},lh={kernelName:"Dilation2DBackpropInput",backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:r,filter:a,dy:s}=e,{strides:o,pad:i,dilations:u}=n,l=t,d=R(r.shape,l.data.get(r.dataId).values),p=R(a.shape,l.data.get(a.dataId).values),{batchSize:h,inHeight:f,inWidth:m,inChannels:g,outHeight:y,outWidth:b,padInfo:x,strideHeight:k,strideWidth:w,filterHeight:v,filterWidth:I,dilationHeight:N,dilationWidth:S,outShape:C}=Ot(r.shape,a.shape,o,i,"NHWC",u);c(s.rank===C.length,()=>`Error in Dilation2DBackpropInput, dy must have the same rank as output ${C.length}, but got `+s.rank);const T=R(C,l.data.get(s.dataId).values),E=F(r.shape,r.dtype);for(let e=0;e<h;++e)for(let t=0;t<y;++t){const n=t*k-x.top;for(let r=0;r<b;++r){const a=r*w-x.left;for(let s=0;s<g;++s){let o=Number.MIN_SAFE_INTEGER,i=n<0?0:n,u=a<0?0:a;for(let t=0;t<v;++t){const r=n+t*N;if(r>=0&&r<f)for(let n=0;n<I;++n){const l=a+n*S;if(l>=0&&l<m){const a=d[e][r][l][s]+p[t][n][s];a>o&&(o=a,i=r,u=l)}}}E[e][i][u][s]+=T[e][t][r][s]}}}return{dataId:l.write(Z(E,r.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}};const ch={kernelName:"EluGrad",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{dy:r,y:a}=t;Sa([r,a],"eluGrad");const s=new Float32Array(h(a.shape)),o=n.data.get(a.dataId).values,i=n.data.get(r.dataId).values;for(let e=0;e<o.length;++e){const t=o[e];s[e]=t>=1?i[e]:i[e]*(t+1)}return n.makeTensorInfo(a.shape,"float32",s)}},dh=La("Equal",Ea((e,t)=>e===t?1:0),null,"bool"),ph={kernelName:"Equal",backendName:"cpu",kernelFunc:dh},hh={kernelName:"Erf",backendName:"cpu",kernelFunc:ja("Erf",e=>{const t=Math.sign(e),n=Math.abs(e),r=1/(1+.3275911*n);return t*(1-((((1.061405429*r-1.453152027)*r+1.421413741)*r-.284496736)*r+.254829592)*r*Math.exp(-n*n))})};function fh(e){const{inputs:t,backend:n,attrs:r}=e,{input:a}=t,{dim:s}=r,o=a.shape.length,i=a.shape.slice();let u=s;return s<0&&(c(-(o+1)<=s,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),u=o+s+1),i.splice(u,0,1),cp({inputs:{x:a},backend:n,attrs:{shape:i}})}const mh={kernelName:"ExpandDims",backendName:"cpu",kernelFunc:fh},gh=La("RealDiv",Ea((e,t)=>e/t)),yh={kernelName:"RealDiv",backendName:"cpu",kernelFunc:gh};function bh(e,t,n){const r=e.shape,a=r[0],s=r[1],o=n.data.get(e.dataId),i=o.complexTensorInfos.real,u=o.complexTensorInfos.imag,l=[a,s],c=h(l),d=v("float32",c),p=v("float32",c);for(let e=0;e<a;e++){const r=Fs({inputs:{x:i},backend:n,attrs:{begin:[e,0],size:[1,s]}}),a=Fs({inputs:{x:u},backend:n,attrs:{begin:[e,0],size:[1,s]}}),o=$a({inputs:{real:r,imag:a},backend:n}),{real:l,imag:c}=xh(o,t,n),h=jn(l,c);for(let t=0;t<s;t++){const n=Yn(h,t);d[e*s+t]=n.real,p[e*s+t]=n.imag}n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o)}const f=n.makeTensorInfo(l,"float32",d),m=n.makeTensorInfo(l,"float32",p),g=$a({inputs:{real:f,imag:m},backend:n});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}function xh(e,t,n){const r=h(e.shape),a=n.data.get(e.dataId),s=n.data.get(a.complexTensorInfos.real.dataId).values,o=n.data.get(a.complexTensorInfos.imag.dataId).values;if(0==((i=r)&i-1)){const a=function e(t,n,r,a,s){if(1===r)return{real:t,imag:n};const o=jn(t,n),i=r/2,u=Kn(o),l=u.real,c=u.imag,d=[l.length],p=s.makeTensorInfo(d,"float32",l),h=s.makeTensorInfo(d,"float32",c),f=$a({inputs:{real:p,imag:h},backend:s}),m=Xn(o),g=m.real,y=m.imag,b=[g.length],x=s.makeTensorInfo(b,"float32",g),k=s.makeTensorInfo(b,"float32",y),w=$a({inputs:{real:x,imag:k},backend:s}),v=e(l,c,i,a,s),I=v.real,N=v.imag,S=[I.length],C=s.makeTensorInfo(S,"float32",I),T=s.makeTensorInfo(S,"float32",N),E=$a({inputs:{real:C,imag:T},backend:s}),$=e(g,y,i,a,s),_=$.real,A=$.imag,R=[_.length],M=s.makeTensorInfo(R,"float32",_),F=s.makeTensorInfo(R,"float32",A),D=$a({inputs:{real:M,imag:F},backend:s}),O=Jn(r,a),P=[O.real.length],L=s.makeTensorInfo(P,"float32",O.real),B=s.makeTensorInfo(P,"float32",O.imag),W=$a({inputs:{real:L,imag:B},backend:s}),z=xs({inputs:{a:W,b:D},backend:s}),V=za({inputs:{a:E,b:z},backend:s}),U=Ws({inputs:{a:E,b:z},backend:s}),G=Fa({inputs:{input:V},backend:s}),H=Fa({inputs:{input:U},backend:s}),j=Bp({inputs:{input:V},backend:s}),q=Bp({inputs:{input:U},backend:s}),K=zp({inputs:[G,H],backend:s,attrs:{axis:0}}),X=zp({inputs:[j,q],backend:s,attrs:{axis:0}}),Y=s.data.get(K.dataId).values,Q=s.data.get(X.dataId).values;return s.disposeIntermediateTensorInfo(p),s.disposeIntermediateTensorInfo(h),s.disposeIntermediateTensorInfo(f),s.disposeIntermediateTensorInfo(x),s.disposeIntermediateTensorInfo(k),s.disposeIntermediateTensorInfo(w),s.disposeIntermediateTensorInfo(C),s.disposeIntermediateTensorInfo(T),s.disposeIntermediateTensorInfo(E),s.disposeIntermediateTensorInfo(M),s.disposeIntermediateTensorInfo(F),s.disposeIntermediateTensorInfo(D),s.disposeIntermediateTensorInfo(L),s.disposeIntermediateTensorInfo(B),s.disposeIntermediateTensorInfo(W),s.disposeIntermediateTensorInfo(z),s.disposeIntermediateTensorInfo(V),s.disposeIntermediateTensorInfo(U),s.disposeIntermediateTensorInfo(G),s.disposeIntermediateTensorInfo(j),s.disposeIntermediateTensorInfo(H),s.disposeIntermediateTensorInfo(q),s.disposeIntermediateTensorInfo(K),s.disposeIntermediateTensorInfo(X),{real:Y,imag:Q}}(s,o,r,t,n),i=[e.shape[0],e.shape[1]];if(t){const e=n.makeTensorInfo(i,"float32",a.real),t=n.makeTensorInfo(i,"float32",a.imag),s=n.makeTensorInfo([],"float32",J(r,"float32")),o=Ra({inputs:{x:s},backend:n}),u=yh.kernelFunc({inputs:{a:e,b:s},backend:n}),l=yh.kernelFunc({inputs:{a:t,b:o},backend:n}),c=n.data.get(u.dataId).values,d=n.data.get(l.dataId).values;return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(l),{real:c,imag:d}}return a}return qn(function(e,t,n){const r=new Float32Array(2*t);for(let a=0;a<t;a++){let s=0,o=0;for(let r=0;r<t;r++){const i=Zn(a*r,t,n),u=Yn(e,r);s+=u.real*i.real-u.imag*i.imag,o+=u.real*i.imag+u.imag*i.real}n&&(s/=t,o/=t),Qn(r,s,o,a)}return r}(jn(s,o),r,t));var i}const kh={kernelName:"FFT",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:r}=t,a=h(r.shape),s=r.shape[r.shape.length-1],o=cp({inputs:{x:r},backend:n,attrs:{shape:[a/s,s]}}),i=bh(o,!1,n),u=cp({inputs:{x:i},backend:n,attrs:{shape:r.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),u}};function wh(e){const{backend:t,attrs:n}=e,{shape:r,value:a,dtype:s}=n,o=s||E(a),i=I(o,h(r));return function(e,t,n){e.fill(t)}(i,a),t.makeTensorInfo(r,o,i)}const vh={kernelName:"Fill",backendName:"cpu",kernelFunc:wh};const Ih={kernelName:"FlipLeftRight",backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:r}=e,a=n,s=v(r.dtype,h(r.shape)),[o,i,u,l]=r.shape,c=a.data.get(r.dataId).values;for(let e=0;e<o;e++){const t=e*u*i*l;for(let e=0;e<i;e++){const n=e*(u*l);for(let r=0;r<u;r++){const a=r*l;for(let i=0;i<l;i++){const d=[o,e,r,i][2],p=Math.round(u-d),h=t+n+a+i;let f=c[h];if(p>=0&&p<u){f=c[t+n+p*l+i]}s[h]=f}}}}return{dataId:a.write(s,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},Nh={kernelName:"FloorDiv",backendName:"cpu",kernelFunc:La("FloorDiv",Ea((e,t)=>Math.floor(e/t)),null,"int32")};const Sh={kernelName:"FusedConv2D",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s,bias:o,preluActivationWeights:i}=t,{strides:u,pad:l,dataFormat:c,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=r;let m=Up({inputs:{x:a,filter:s},backend:n,attrs:{strides:u,pad:l,dataFormat:c,dilations:d,dimRoundingMode:p}});if(o){const e=m;m=za({inputs:{a:m,b:o},backend:n}),n.disposeIntermediateTensorInfo(e)}if(h){const e=m;m=lp(n,m,h,i,f),n.disposeIntermediateTensorInfo(e)}return m}};const Ch={kernelName:"FusedDepthwiseConv2D",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,filter:s,bias:o,preluActivationWeights:i}=t,{strides:u,pad:l,dataFormat:c,dilations:d,dimRoundingMode:p,activation:h,leakyreluAlpha:f}=r;let m=nh({inputs:{x:a,filter:s},backend:n,attrs:{strides:u,pad:l,dataFormat:c,dilations:d,dimRoundingMode:p}});if(o){const e=m;m=za({inputs:{a:m,b:o},backend:n}),n.disposeIntermediateTensorInfo(e)}if(h){const e=m;m=lp(n,m,h,i,f),n.disposeIntermediateTensorInfo(e)}return m}};const Th={kernelName:"GatherNd",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{params:r,indices:a}=t,s=h(r.shape),o=a.shape,i=o[o.length-1],[u,l,c,d]=pt(r,a);if(0===l)return n.makeTensorInfo(u,r.dtype,[]);const p=lt([l,c],r.dtype),f=n.data.get(a.dataId).values,m=n.data.get(r.dataId).values;for(let e=0;e<l;e++){const t=[];let n=0;for(let r=0;r<i;r++){const a=f[e*i+r];n+=a*d[r],t.push(a)}if(n<0||n>=s/c)throw new Error(`Invalid indices: ${t} does not index into ${r.shape}`);for(let t=0;t<c;t++)p.values[e*c+t]=m[n*c+t]}return n.makeTensorInfo(u,p.dtype,p.values)}};const Eh={kernelName:"GatherV2",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,indices:s}=t,{axis:o,batchDims:i}=r;Sa([a,s],"gatherV2");let u=i;null==i&&(u=0);const l=h(s.shape),c=rr(a,s,k(o,a.shape)[0],u),d=cp({inputs:{x:a},backend:n,attrs:{shape:[c.batchSize,c.outerSize,c.dimSize,c.sliceSize]}}),p=cp({inputs:{x:s},backend:n,attrs:{shape:[c.batchSize,l/c.batchSize]}}),f=[c.batchSize,c.outerSize,l/c.batchSize,c.sliceSize],m=n.bufferSync(p),g=as(n.bufferSync(d),m,f);return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.makeTensorInfo(c.outputShape,g.dtype,g.values)}},$h={kernelName:"GreaterEqual",backendName:"cpu",kernelFunc:La("GreaterEqual",Ea((e,t)=>e>=t?1:0),null,"bool")};const _h={kernelName:"IFFT",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:r}=t,a=h(r.shape),s=r.shape[r.shape.length-1],o=cp({inputs:{x:r},backend:n,attrs:{shape:[a/s,s]}}),i=bh(o,!0,n),u=cp({inputs:{x:i},backend:n,attrs:{shape:r.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),u}},Ah={kernelName:"IsFinite",backendName:"cpu",kernelFunc:ja("IsFinite",e=>Number.isFinite(e)?1:0,"bool")},Rh={kernelName:"IsInf",backendName:"cpu",kernelFunc:ja("IsInf",e=>Math.abs(e)===1/0?1:0,"bool")},Mh={kernelName:"IsNan",backendName:"cpu",kernelFunc:ja("IsNan",e=>Number.isNaN(e)?1:0,"bool")},Fh={kernelName:"LessEqual",backendName:"cpu",kernelFunc:La("LessEqual",Ea((e,t)=>e<=t?1:0),null,"bool")};const Dh={kernelName:"LinSpace",backendName:"cpu",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:r,stop:a,num:s}=n,o=ls(r,a,s);return t.makeTensorInfo([o.length],"float32",o)}},Oh={kernelName:"Log1p",backendName:"cpu",kernelFunc:ja("Log1p",e=>Math.log1p(e))},Ph={kernelName:"LogicalAnd",backendName:"cpu",kernelFunc:La("LogicalAnd",Ea((e,t)=>e&&t),null,"bool")},Lh={kernelName:"LogicalNot",backendName:"cpu",kernelFunc:ja("LogicalNot",e=>e?0:1,"bool")},Bh={kernelName:"LogicalOr",backendName:"cpu",kernelFunc:La("LogicalOr",Ea((e,t)=>e||t),null,"bool")};const Wh={kernelName:"LRN",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{depthRadius:s,bias:o,alpha:i,beta:u}=r;Sa(a,"LRN");const l=a.shape[3],c=l-1,d=n.data.get(a.dataId).values,p=h(a.shape),f=new Float32Array(p);function m(e){const t=e%l;let n=e-t+Math.max(0,t-s);const r=e-t+Math.min(t+s,c);let a=0;for(;n<=r;n++){const e=d[n];a+=e*e}return a}for(let e=0;e<p;e++){const t=m(e),n=d[e]*Math.pow(o+i*t,-u);f[e]=n}return n.makeTensorInfo(a.shape,a.dtype,f)}};const zh={kernelName:"LRNGrad",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,y:s,dy:o}=t,{depthRadius:i,bias:u,alpha:l,beta:c}=r;Sa(o,"LRNGrad");const d=h(o.shape),p=o.shape[3],f=n.data.get(o.dataId).values,m=n.data.get(a.dataId).values,g=n.data.get(s.dataId).values,y=new Float32Array(d),b=d;for(let e=0;e<b;e++){const t=e%p,n=e-t+Math.max(0,t-i),r=e-t+Math.min(p,t+i+1);let a=0;for(let e=n;e<r;e++)a+=Math.pow(m[e],2);a=l*a+u;for(let t=n;t<r;t++){let n=-2*l*c*m[t]*g[e]/a;e===t&&(n+=Math.pow(a,-c)),n*=f[e],y[t]+=n}}return n.makeTensorInfo(o.shape,a.dtype,y)}};function Vh(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{reductionIndices:s,keepDims:o}=r,i=n;let u=a.shape;const l=u.length,c=k(s,u);let d=c;const p=un(d,l);let f=i.data.get(a.dataId).values;if(null!=p){const e=new Array(l);for(let t=0;t<e.length;t++)e[t]=u[p[t]];f=Ss(f,u,a.dtype,p,e),d=cn(d.length,l),u=e}Sa(a,"max"),on("max",d,l);const[m,g]=an(u,d),y=ps(f,h(g),m,a.dtype),b=i.write(y,m,a.dtype);let x=m;if(o){x=sn(m,c)}return{dataId:b,shape:x,dtype:a.dtype}}const Uh={kernelName:"Max",backendName:"cpu",kernelFunc:Vh};const Gh={kernelName:"MaxPool",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t;Sa(a,"maxPool");const{filterSize:s,strides:o,pad:i,dimRoundingMode:u}=r;c(qt(o,1),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '1'`);const l=Pt(a.shape,s,o,1,i,u);let d;if(1===l.filterWidth&&1===l.filterHeight&&f(l.inShape,l.outShape))d=Ra({inputs:{x:a},backend:n});else{const e=n.data.get(a.dataId).values,t=A(a.shape),r=Tp(e,a.shape,a.dtype,t,l,"max");d=n.makeTensorInfo(l.outShape,a.dtype,r.values)}return d}};const Hh={kernelName:"MaxPool3D",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{filterSize:s,strides:o,pad:i,dimRoundingMode:u,dataFormat:l}=r;Sa(a,"maxPool3d");const c=Lt(a.shape,s,o,1,i,u,l),d=$p(n.data.get(a.dataId).values,a.shape,a.dtype,A(a.shape),c,"max");return n.makeTensorInfo(d.shape,"float32",d.values)}};const jh={kernelName:"MaxPool3DGrad",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s}=t,{filterSize:o,strides:i,pad:u,dimRoundingMode:l}=r;Sa([a,s],"maxPool3DGrad");const c=Lt(s.shape,o,i,1,u,l),d=function(e,t){const n=lt(t.outShape,"int32"),r=t.strideDepth,a=t.strideHeight,s=t.strideWidth,o=t.dilationDepth,i=t.dilationHeight,u=t.dilationWidth,l=t.effectiveFilterDepth,c=t.effectiveFilterHeight,d=t.effectiveFilterWidth,p=t.padInfo.front,h=t.padInfo.top,f=t.padInfo.left;for(let m=0;m<t.batchSize;++m)for(let g=0;g<t.inChannels;++g)for(let y=0;y<t.outDepth;++y){const b=y*r-p;let x=b;for(;x<0;)x+=o;const k=Math.min(t.inDepth,l+b);for(let r=0;r<t.outHeight;++r){const l=r*a-h;let p=l;for(;p<0;)p+=i;const w=Math.min(t.inHeight,c+l);for(let a=0;a<t.outWidth;++a){const h=a*s-f;let v=h;for(;v<0;)v+=u;const I=Math.min(t.inWidth,d+h);let N=Number.NEGATIVE_INFINITY,S=-1;for(let t=x;t<k;t+=o){const n=t-b;for(let r=p;r<w;r+=i){const a=r-l;for(let s=v;s<I;s+=u){const o=s-h,i=e.get(m,t,r,s,g);i>=N&&(N=i,S=n*c*d+a*c+o)}}}n.set(S,m,y,r,a,g)}}}return n}(n.bufferSync(s),c),p=c.strideDepth,h=c.strideHeight,f=c.strideWidth,m=c.dilationDepth,g=c.dilationHeight,y=c.dilationWidth,b=c.effectiveFilterDepth,x=c.effectiveFilterHeight,k=c.effectiveFilterWidth,w=b-1-c.padInfo.front,v=k-1-c.padInfo.left,I=x-1-c.padInfo.top,N=lt(s.shape,"float32"),S=n.bufferSync(a);for(let e=0;e<c.batchSize;++e)for(let t=0;t<c.inChannels;++t)for(let n=0;n<c.inDepth;++n)for(let r=0;r<c.inHeight;++r)for(let a=0;a<c.inWidth;++a){const s=n-w,o=r-I,i=a-v;let u=0;for(let n=0;n<b;n+=m){const r=(s+n)/p;if(!(r<0||r>=c.outDepth||Math.floor(r)!==r))for(let a=0;a<x;a+=g){const s=(o+a)/h;if(!(s<0||s>=c.outHeight||Math.floor(s)!==s))for(let o=0;o<k;o+=y){const l=(i+o)/f;if(l<0||l>=c.outWidth||Math.floor(l)!==l)continue;const p=b*x*k-1-d.get(e,r,s,l,t)===n*x*k+a*k+o?1:0;if(0===p)continue;u+=S.get(e,r,s,l,t)*p}}}N.set(u,e,n,r,a,t)}return n.makeTensorInfo(N.shape,N.dtype,N.values)}};const qh={kernelName:"MaxPoolGrad",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{dy:a,input:s,output:o}=t,i=s;Sa([s,o],"maxPoolGrad");const{filterSize:u,strides:l,pad:c,dimRoundingMode:d}=r,p=Pt(i.shape,u,l,1,c,d),h=n.data.get(i.dataId).values,f=lt(p.outShape,i.dtype,Ep(h,i.shape,i.dtype,p).values),m=p.strideHeight,g=p.strideWidth,y=p.dilationHeight,b=p.dilationWidth,x=p.effectiveFilterHeight,k=p.effectiveFilterWidth,w=k-1-p.padInfo.left,v=x-1-p.padInfo.top,I=lt(i.shape,"float32"),N=n.data.get(a.dataId).values,S=lt(a.shape,"float32",N);for(let e=0;e<p.batchSize;++e)for(let t=0;t<p.inChannels;++t)for(let n=0;n<p.inHeight;++n)for(let r=0;r<p.inWidth;++r){const a=n-v,s=r-w;let o=0;for(let n=0;n<x;n+=y){const r=(a+n)/m;if(!(r<0||r>=p.outHeight||Math.floor(r)!==r))for(let a=0;a<k;a+=b){const i=(s+a)/g;if(i<0||i>=p.outWidth||Math.floor(i)!==i)continue;const u=x*k-1-f.get(e,r,i,t)===n*k+a?1:0;if(0===u)continue;o+=S.get(e,r,i,t)*u}}I.set(o,e,n,r,t)}return n.makeTensorInfo(I.shape,I.dtype,I.values)}};const Kh={kernelName:"MaxPoolWithArgmax",backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:r}=e,{filterSize:a,strides:s,pad:o,includeBatchInIndex:i}=t,u=n;Sa(r,"MaxPoolWithArgmax");const l=u.data.get(r.dataId).values,c=Pt(r.shape,a,s,[1,1],o),[d,p]=function(e,t,n,r,a){const s=Tp(e,0,n,A(t),a,"max"),o=Ep(e,t,n,a,!0,r);return[s.values,o.values]}(l,r.shape,r.dtype,i,c),h=u.write(d,c.outShape,r.dtype),f=u.write(p,c.outShape,r.dtype);return[{dataId:h,shape:c.outShape,dtype:r.dtype},{dataId:f,shape:c.outShape,dtype:"int32"}]}};function Xh(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r;let i;Sa(a,"sum"),i="bool"===a.dtype?Oa({inputs:{x:a},backend:n,attrs:{dtype:"int32"}}):Ra({inputs:{x:a},backend:n});const u=i.shape.length,l=k(s,i.shape),c=un(l,u);let d=l,p=i;null!=c&&(p=Cs({inputs:{x:i},backend:n,attrs:{perm:c}}),d=cn(d.length,u)),on("sum",d,p.shape.length);const[f,m]=an(p.shape,d);let g=Aa(n,f,we(p.dtype,"int32"));const y=h(m),b=n.data.get(g.dataId).values,x=n.data.get(p.dataId).values;for(let e=0;e<b.length;++e){const t=e*y;let n=0;for(let e=0;e<y;++e)n+=x[t+e];b[e]=n}if(o){const e=g;g=cp({inputs:{x:g},backend:n,attrs:{shape:sn(g.shape,l)}}),n.disposeIntermediateTensorInfo(e)}return n.disposeIntermediateTensorInfo(i),null!=c&&n.disposeIntermediateTensorInfo(p),g}const Yh={kernelName:"Sum",backendName:"cpu",kernelFunc:Xh};const Qh={kernelName:"Mean",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r,i=k(s,a.shape),u=h(an(a.shape,i)[1]),l=[],c=n.makeTensorInfo([],"float32",new Float32Array([u]));l.push(c);const d=Oa({inputs:{x:a},backend:n,attrs:{dtype:"float32"}});l.push(d);const p=gh({inputs:{a:d,b:c},backend:n});l.push(p);const f=Xh({inputs:{x:p},backend:n,attrs:{axis:s,keepDims:o}});return l.forEach(e=>n.disposeIntermediateTensorInfo(e)),f}};const Jh={kernelName:"Min",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{axis:s,keepDims:o}=r;Sa(a,"min");const i=k(s,a.shape);let u=i;const l=un(u,a.shape.length);let c=a;null!=l&&(c=Cs({inputs:{x:a},backend:n,attrs:{perm:l}}),u=cn(u.length,a.shape.length)),on("min",u,c.shape.length);const[d,p]=an(c.shape,u),f=h(p),m=M(h(d),c.dtype),g=n.data.get(c.dataId).values;for(let e=0;e<m.length;++e){const t=e*f;let n=g[t];for(let e=0;e<f;++e){const r=g[t+e];r<n&&(n=r)}m[e]=n}null!=l&&n.disposeIntermediateTensorInfo(c);const y=n.makeTensorInfo(d,c.dtype,m);if(o){const e=cp({inputs:{x:y},backend:n,attrs:{shape:sn(d,i)}});return n.disposeIntermediateTensorInfo(y),e}return y}};const Zh={kernelName:"MirrorPad",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{paddings:s,mode:o}=r;Sa(a,"mirrorPad");const i=s.map((e,t)=>e[0]+a.shape[t]+e[1]),u=s.map(e=>e[0]),l=s.map((e,t)=>e[0]+a.shape[t]),c="reflect"===o?0:1,d=n.data.get(a.dataId).values,p=a.shape.length,f=A(a.shape),m=h(i),g=i.length,y=A(i),b=v(a.dtype,m);for(let e=0;e<m;e++){let t=P(e,g,y);for(let e=0;e<g;e++)t[e]<u[e]?t[e]=2*u[e]-t[e]-c:t[e]>=l[e]&&(t[e]=2*(l[e]-1)-t[e]+c);t=t.map((e,t)=>e-u[t]);const n=O(t,p,f);b[e]=d[n]}return{dataId:n.write(b,i,a.dtype),shape:i,dtype:a.dtype}}},ef={kernelName:"Mod",backendName:"cpu",kernelFunc:La("Mod",Ea((e,t)=>{const n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t}))};function tf(e){const{inputs:t,backend:n,attrs:r}=e,{logits:a}=t,{dim:s}=r,o=a.shape.length;let i=s;if(-1===i&&(i=o-1),i!==o-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${o} and dim was ${i}`);const u=k([i],a.shape),l=Vh({inputs:{x:a},backend:n,attrs:{reductionIndices:u,keepDims:!1}}),c=sn(l.shape,u),d=cp({inputs:{x:l},backend:n,attrs:{shape:c}}),p=Ws({inputs:{a:a,b:d},backend:n}),h=Ja({inputs:{x:p},backend:n}),f=Xh({inputs:{x:h},backend:n,attrs:{axis:u,keepDims:!1}}),m=cp({inputs:{x:f},backend:n,attrs:{shape:c}}),g=gh({inputs:{a:h,b:m},backend:n});return n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}const nf={kernelName:"Softmax",backendName:"cpu",kernelFunc:tf};const rf={kernelName:"Multinomial",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{logits:a}=t,{numSamples:s,seed:o,normalized:i}=r;Sa(a,"multinomial");const u=i?a:tf({inputs:{logits:a},backend:n,attrs:{dim:-1}}),l=u.shape[0],c=u.shape[1],d=n.data.get(u.dataId).values,p=[l,s],f=M(h(p),"int32");for(let e=0;e<l;++e){const t=e*c,n=new Float32Array(c-1);n[0]=d[t];for(let e=1;e<n.length;++e)n[e]=n[e-1]+d[t+e];const r=(void 0)(o.toString()),a=e*s;for(let e=0;e<s;++e){const t=r();f[a+e]=n.length;for(let r=0;r<n.length;r++)if(t<n[r]){f[a+e]=r;break}}}return i||n.disposeIntermediateTensorInfo(u),n.makeTensorInfo(p,"int32",f)}},af=$n;const sf={kernelName:"NonMaxSuppressionV3",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{boxes:a,scores:s}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:u}=r;Sa(a,"NonMaxSuppression");const l=n.data.get(a.dataId).values,c=n.data.get(s.dataId).values,{selectedIndices:d}=af(l,c,o,i,u);return n.makeTensorInfo([d.length],"int32",new Int32Array(d))}},of=_n;const uf={kernelName:"NonMaxSuppressionV4",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{boxes:a,scores:s}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:u,padToMaxOutputSize:l}=r;Sa(a,"NonMaxSuppressionPadded");const c=n.data.get(a.dataId).values,d=n.data.get(s.dataId).values,{selectedIndices:p,validOutputs:h}=of(c,d,o,i,u,l);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}},lf=An;const cf={kernelName:"NonMaxSuppressionV5",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{boxes:a,scores:s}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:u,softNmsSigma:l}=r;Sa(a,"NonMaxSuppressionWithScore");const c=n.data.get(a.dataId).values,d=n.data.get(s.dataId).values,p=o,h=i,f=u,m=l,{selectedIndices:g,selectedScores:y}=lf(c,d,p,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}};const df={kernelName:"OneHot",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{indices:a}=t,{depth:s,onValue:o,offValue:i}=r;Sa(a,"oneHot");const u=h(a.shape),l=new Float32Array(u*s);l.fill(i);const c=n.data.get(a.dataId).values;for(let e=0;e<u;++e)c[e]>=0&&c[e]<s&&(l[e*s+c[e]]=o);return n.makeTensorInfo([...a.shape,s],"int32",l)}};function pf(e){const{inputs:t,backend:n}=e,{x:r}=t;if("string"===r.dtype)throw new Error("zerosLike is not supported for string tensors");if("complex64"===r.dtype){const e=Fa({inputs:{input:r},backend:n}),t=pf({inputs:{x:e},backend:n}),a=Bp({inputs:{input:r},backend:n}),s=pf({inputs:{x:a},backend:n}),o=$a({inputs:{real:t,imag:s},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(s),o}return wh({backend:n,attrs:{shape:r.shape,value:0,dtype:r.dtype}})}const hf={kernelName:"ZerosLike",backendName:"cpu",kernelFunc:pf};const ff={kernelName:"OnesLike",backendName:"cpu",kernelFunc:function e(t){const{inputs:n,backend:r}=t,{x:a}=n;if("string"===a.dtype)throw new Error("onesLike is not supported for string tensors");if("complex64"===a.dtype){const t=Fa({inputs:{input:a},backend:r}),n=e({inputs:{x:t},backend:r}),s=Bp({inputs:{input:a},backend:r}),o=pf({inputs:{x:s},backend:r}),i=$a({inputs:{real:n,imag:o},backend:r});return r.disposeIntermediateTensorInfo(t),r.disposeIntermediateTensorInfo(n),r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(o),i}return wh({backend:r,attrs:{shape:a.shape,value:1,dtype:a.dtype}})}};function mf(e){const{inputs:t,backend:n,attrs:r}=e,{axis:a}=r;if(1===t.length)return fh({inputs:{input:t[0]},backend:n,attrs:{dim:a}});const s=t[0].shape,o=t[0].dtype;t.forEach(e=>{d(s,e.shape,"All tensors passed to stack must have matching shapes"),c(o===e.dtype,()=>"All tensors passed to stack must have matching dtypes")});const i=[],u=zp({inputs:t.map(e=>{const t=fh({inputs:{input:e},backend:n,attrs:{dim:a}});return i.push(t),t}),backend:n,attrs:{axis:a}});return i.forEach(e=>n.disposeIntermediateTensorInfo(e)),u}const gf={kernelName:"Pack",backendName:"cpu",kernelFunc:mf};const yf={kernelName:"PadV2",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{paddings:s,constantValue:o}=r;Sa(a,"pad");const i=s.map((e,t)=>e[0]+a.shape[t]+e[1]),u=s.map(e=>e[0]),l=n.data.get(a.dataId).values,c=h(a.shape),d=a.shape.length,p=A(a.shape),f=h(i),m=i.length,g=A(i),y=v(a.dtype,f);0!==o&&y.fill(o);for(let e=0;e<c;e++){y[O(P(e,d,p).map((e,t)=>e+u[t]),m,g)]=l[e]}return{dataId:n.write(y,i,a.dtype),shape:i,dtype:a.dtype}}},bf={kernelName:"Pow",backendName:"cpu",kernelFunc:La("Pow",Ea((e,t)=>Math.pow(e,t)))};const xf={kernelName:"Range",backendName:"cpu",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:r,stop:a,dtype:s,step:o}=n,i=_s(r,a,o,s);return t.makeTensorInfo([i.length],s,i)}},kf={kernelName:"Reciprocal",backendName:"cpu",kernelFunc:ja("Reciprocal",e=>1/e)};const wf={kernelName:"ResizeBilinear",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:o,size:i}=r;Sa(a,"resizeBilinear");const u=A(a.shape),[l,c]=i,[d,p,f,m]=a.shape,g=n.data.get(a.dataId).values,y=new Float32Array(h([d,l,c,m])),b=[s&&l>1?p-1:p,s&&c>1?f-1:f],x=[s&&l>1?l-1:l,s&&c>1?c-1:c];let k=0;const w=b[0]/x[0],v=b[1]/x[1];for(let e=0;e<d;e++)for(let t=0;t<l;t++){let n;n=o?w*(t+.5)-.5:w*t;const r=Math.max(0,Math.floor(n)),a=n-r,s=Math.min(p-1,Math.ceil(n)),i=e*u[0]+r*u[1],l=e*u[0]+s*u[1];for(let e=0;e<c;e++){let t;t=o?v*(e+.5)-.5:v*e;const n=Math.max(0,Math.floor(t)),r=t-n,s=Math.min(f-1,Math.ceil(t)),c=i+n*u[2],d=l+n*u[2],p=i+s*u[2],h=l+s*u[2];for(let e=0;e<m;e++){const t=g[c+e],n=g[d+e],s=t+(g[p+e]-t)*r,o=s+(n+(g[h+e]-n)*r-s)*a;y[k++]=o}}}return n.makeTensorInfo([d,l,c,m],"float32",y)}};const vf={kernelName:"ResizeBilinearGrad",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a,dy:s}=t,{alignCorners:o}=r;Sa([s,a],"resizeBilinearGrad");const i=A(a.shape),[u,l,c,d]=a.shape,[,p,h]=s.shape,f=new Float32Array(u*l*c*d),m=[o&&p>1?l-1:l,o&&h>1?c-1:c],g=[o&&p>1?p-1:p,o&&h>1?h-1:h],y=m[0]/g[0],b=m[1]/g[1],x=n.data.get(s.dataId).values;let k=0;for(let e=0;e<u;e++){const t=e*i[0];for(let e=0;e<p;e++){const n=e*y,r=Math.floor(n),a=Math.min(Math.ceil(n),l-1),s=t+r*i[1],o=t+a*i[1],u=n-r,p=1-u;for(let e=0;e<h;e++){const t=e*b,n=Math.floor(t),r=Math.min(Math.ceil(t),c-1),a=t-n,l=1-a,h=s+n*i[2],m=s+r*i[2],g=o+n*i[2],y=o+r*i[2],w=p*l,v=p*a,I=u*l,N=u*a;for(let e=0;e<d;e++){const t=x[k++];f[h+e]+=t*w,f[m+e]+=t*v,f[g+e]+=t*I,f[y+e]+=t*N}}}}return n.makeTensorInfo([u,c,l,d],"float32",f)}};const If={kernelName:"ResizeNearestNeighbor",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:o,size:i}=r;Sa(a,"resizeNearestNeighbor");const u=A(a.shape),[l,c]=i,[d,p,h,f]=a.shape,m=n.data.get(a.dataId).values,g=new Float32Array(d*l*c*f),y=[s&&l>1?p-1:p,s&&c>1?h-1:h],b=[s&&l>1?l-1:l,s&&c>1?c-1:c],x=y[0]/b[0],k=y[1]/b[1];let w=0;for(let e=0;e<d;e++){const t=e*u[0];for(let e=0;e<l;e++){const n=o?x*(e+.5):x*e;let r=Math.min(p-1,s?Math.round(n):Math.floor(n));o&&(r=Math.max(0,r));const a=t+r*u[1];for(let e=0;e<c;e++){const t=o?k*(e+.5):k*e;let n=Math.min(h-1,s?Math.round(t):Math.floor(t));o&&(n=Math.max(0,n));const r=a+n*u[2];for(let e=0;e<f;e++){const t=m[r+e];g[w++]=t}}}}return n.makeTensorInfo([d,l,c,f],a.dtype,g)}};const Nf={kernelName:"ResizeNearestNeighborGrad",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{images:a,dy:s}=t,{alignCorners:o}=r;Sa([s,a],"resizeNearestNeighborGrad");const i=A(a.shape),u=A(s.shape),[l,c,d,p]=a.shape,[,h,f]=s.shape,m=new Float32Array(l*c*d*p),g=n.data.get(s.dataId).values,y=[o&&h>1?c-1:c,o&&f>1?d-1:d],b=[o&&h>1?h-1:h,o&&f>1?f-1:f],x=y[0]/b[0],k=y[1]/b[1],w=1/x,v=1/k,I=2*Math.ceil(w)+2,N=2*Math.ceil(v)+2;for(let e=0;e<l;e++){const t=e*i[0];for(let e=0;e<c;e++){const n=t+e*i[1],r=Math.floor(e*w),a=Math.floor(r-I/2);for(let r=0;r<d;r++){const s=n+r*i[2],l=Math.floor(r*v),y=Math.floor(l-N/2);for(let n=0;n<p;n++){let i=0;for(let s=0;s<I;s++){const l=s+a;if(l<0||l>=h)continue;const p=t+l*u[1],m=l*x;if(e===Math.min(c-1,o?Math.round(m):Math.floor(m)))for(let e=0;e<N;e++){const t=e+y;if(t<0||t>=f)continue;const a=p+t*u[2],s=t*k;r===Math.min(d-1,o?Math.round(s):Math.floor(s))&&(i+=g[a+n])}}m[s+n]=i}}}}return n.makeTensorInfo(a.shape,a.dtype,m)}};const Sf={kernelName:"Reverse",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{dims:s}=r;Sa(a,"reverse");const o=a.shape.length,i=k(s,a.shape);if(0===o)return Ra({inputs:{x:a},backend:n});const u=new ce(a.shape,a.dtype),l=n.bufferSync(a);for(let e=0;e<u.size;e++){const t=u.indexToLoc(e),n=t.slice();i.forEach(e=>n[e]=a.shape[e]-1-n[e]),u.set(l.get(...n),...t)}return n.makeTensorInfo(u.shape,u.dtype,u.values)}},Cf={kernelName:"RotateWithOffset",backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:r}=e,{radians:a,fillValue:s,center:o}=t,i=n,u=v(r.dtype,h(r.shape)),[l,c,d,p]=r.shape,[f,m]=Bn(o,c,d),g=Math.sin(a),y=Math.cos(a),b=i.data.get(r.dataId).values;for(let e=0;e<l;e++){const t=e*d*c*p;for(let e=0;e<c;e++){const n=e*(d*p);for(let r=0;r<d;r++){const a=r*p;for(let o=0;o<p;o++){const i=[l,e,r,o],h=i[2],x=i[1];let k=(h-f)*y-(x-m)*g,w=(h-f)*g+(x-m)*y;k=Math.round(k+f),w=Math.round(w+m);let v=s;if("number"!=typeof s&&(v=3===o?255:s[o]),k>=0&&k<d&&w>=0&&w<c){v=b[t+w*(d*p)+k*p+o]}u[t+n+a+o]=v}}}}return{dataId:i.write(u,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},Tf={kernelName:"Round",backendName:"cpu",kernelFunc:ja("Round",e=>{const t=Math.floor(e);return e-t<.5?Math.floor(e):e-t>.5?Math.ceil(e):t%2==0?t:t+1})};function Ef(e,t,n,r,a,s,o,i,u,l){const c=[r/a,a],d=e.values,p=t.values;if(0===r)return lt(n,t.dtype);const h=lt(c,t.dtype);h.values.fill(u);for(let e=0;e<s;e++){const s=[];let u=0;for(let t=0;t<o;t++){const n=d[e*o+t];s.push(n),u+=n*i[t]}if(u<0||u>=r/a)throw new Error(`Invalid indices: ${s} does not index into ${n}`);for(let n=0;n<a;n++)l?h.values[u*a+n]+=p[e*a+n]:h.values[u*a+n]=0===t.rank?p[0]:p[e*a+n]}return h}const $f={kernelName:"ScatterNd",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{indices:a,updates:s}=t,{shape:o}=r,{sliceRank:i,numUpdates:u,sliceSize:l,strides:c,outputSize:d}=ft(0,a,o),p=Ef(n.bufferSync(a),n.bufferSync(s),o,d,l,u,i,c,0,!0);return n.makeTensorInfo(o,p.dtype,p.values)}};const _f={kernelName:"Select",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:r,t:a,e:s}=t;Sa([r,a,s],"select");const o=r.shape.length,i=n.data.get(r.dataId).values,u=n.data.get(a.dataId).values,l=n.data.get(s.dataId).values,c=we(a.dtype,s.dtype),d=M(h(a.shape),c);let p=0;const f=0===o||o>1||1===a.shape.length?1:h(a.shape.slice(1));for(let e=0;e<i.length;e++)for(let t=0;t<f;t++)1===i[e]?d[p++]=u[e]:d[p++]=l[e];return n.makeTensorInfo(a.shape,c,d)}},Af={kernelName:"Selu",backendName:"cpu",kernelFunc:ja("Selu",e=>e>=0?1.0507009873554805*e:1.7580993408473768*(Math.exp(e)-1))},Rf={kernelName:"Sigmoid",backendName:"cpu",kernelFunc:ja("Sigmoid",e=>1/(1+Math.exp(-e)))},Mf={kernelName:"Sign",backendName:"cpu",kernelFunc:ja("Sign",e=>e<0?-1:e>0?1:0)},Ff={kernelName:"Sin",backendName:"cpu",kernelFunc:ja("Sin",e=>Math.sin(e))},Df={kernelName:"Sinh",backendName:"cpu",kernelFunc:ja("Sinh",e=>Math.sinh(e))},Of=Math.log(1.1920928955078125e-7)+2,Pf={kernelName:"Softplus",backendName:"cpu",kernelFunc:ja("Softplus",e=>{const t=e>-Of,n=e<Of,r=Math.exp(e);let a;return a=n?r:t?e:Math.log(1+r),a})};const Lf={kernelName:"SpaceToBatchND",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{blockShape:s,paddings:o}=r;Sa([a],"spaceToBatchND");const i=h(s),u=[[0,0]];u.push(...o);for(let e=1+s.length;e<a.shape.length;++e)u.push([0,0]);const l=yf.kernelFunc({inputs:{x:a},backend:n,attrs:{paddings:u,constantValue:0}}),c=Wn(l.shape,s,i,!1),d=zn(c.length,s.length,!1),p=Vn(l.shape,s,i,!1),f=cp({inputs:{x:l},backend:n,attrs:{shape:c}}),m=Cs({inputs:{x:f},backend:n,attrs:{perm:d}}),g=cp({inputs:{x:m},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}};const Bf={kernelName:"SparseToDense",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{sparseIndices:a,sparseValues:s,defaultValue:o}=t,{outputShape:i}=r,{sliceRank:u,numUpdates:l,sliceSize:c,strides:d,outputSize:p}=ft(0,a,i),h=Ef(n.bufferSync(a),n.bufferSync(s),i,p,c,l,u,d,n.data.get(o.dataId).values[0],!1);return n.makeTensorInfo(i,h.dtype,h.values)}};const Wf={kernelName:"SplitV",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{numOrSizeSplits:s,axis:o}=r,i=k(o,a.shape)[0],u=er(a,s,i),l=new Array(a.shape.length).fill(0),c=a.shape.slice();return u.map(e=>{const t=[...c];t[i]=e;const r=Fs({inputs:{x:a},backend:n,attrs:{begin:l,size:t}});return l[i]+=e,r})}},zf={kernelName:"Sqrt",backendName:"cpu",kernelFunc:ja("Sqrt",e=>Math.sqrt(e))},Vf={kernelName:"Square",backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{const{x:n}=e,r=t;Sa(n,"square");const a=r.data.get(n.dataId).values,s=new Float32Array(a.length);for(let e=0;e<a.length;++e){const t=a[e];s[e]=t*t}return{dataId:r.write(s,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},Uf={kernelName:"Step",backendName:"cpu",kernelFunc:ja("Step",(e,t)=>{const n=t;return isNaN(e)?NaN:e>0?1:n.alpha})};const Gf={kernelName:"StridedSlice",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{begin:s,end:o,strides:i,beginMask:u,endMask:l,ellipsisMask:c,newAxisMask:d,shrinkAxisMask:p}=r;Sa(a,"stridedSlice");const{nonStrided:h,$begin:f,$strides:m,size:g,newShape:y,outShape:b}=_t(a.shape,s,o,i,u,l,c,d,p),x=cp({inputs:{x:a},backend:n,attrs:{shape:y}});let k;if(h){const e=Fs({inputs:{x:x},backend:n,attrs:{begin:f,size:g}});k=cp({inputs:{x:e},backend:n,attrs:{shape:b}}),n.disposeIntermediateTensorInfo(e)}else if(b.some(e=>0===e))k=n.makeTensorInfo(b,a.dtype,[]);else{const e=Ls(b,n.bufferSync(x),m,f);k=n.makeTensorInfo(e.shape,e.dtype,e.values)}const w=cp({inputs:{x:k},backend:n,attrs:{shape:b}});return n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(k),w}},Hf={kernelName:"Tan",backendName:"cpu",kernelFunc:ja("Tan",e=>Math.tan(e))},jf=ja("Tanh",e=>Math.tanh(e));function qf(e,t,n){switch(n){case"reflect":return function(e,t){let n=e;if(n<0)if(t<=1)n=0;else{const e=2*t;n<e&&(n=e*Math.trunc(-n/e)+n),n=n<-t?n+e:-n-1}else if(n>t-1)if(t<=1)n=0;else{const e=2*t;n-=e*Math.trunc(n/e),n>=t&&(n=e-n-1)}return u(0,n,t-1)}(e,t);case"wrap":return function(e,t){let n=e;if(n<0)if(t<=1)n=0;else{const e=t-1;n+=t*(Math.trunc(-n/e)+1)}else if(n>t-1)if(t<=1)n=0;else{const e=t-1;n-=t*Math.trunc(n/e)}return u(0,n,t-1)}(e,t);case"nearest":return function(e,t){return u(0,e,t-1)}(e,t);case"constant":default:return function(e,t){return e}(e)}}function Kf(e,t,n,r,a,s,o,i,u,l,c){return 0<=i&&i<t&&0<=u&&u<n?e[o*r+i*a+u*s+l]:c}function Xf(e,t,n,r,a,s,o,i,u,l,c){return Kf(e,t,n,r,a,s,o,Math.round(i),Math.round(u),l,c)}function Yf(e,t,n,r,a,s,o,i,u,l,c){const d=Math.floor(i),p=Math.floor(u),h=d+1,f=p+1;return(h-i)*((f-u)*Kf(e,t,n,r,a,s,o,d,p,l,c)+(u-p)*Kf(e,t,n,r,a,s,o,d,f,l,c))+(i-d)*((f-u)*Kf(e,t,n,r,a,s,o,h,p,l,c)+(u-p)*Kf(e,t,n,r,a,s,o,h,f,l,c))}const Qf=[fp,Ta,mp,gp,Va,yp,bp,xp,kp,wp,vp,Ip,Np,Sp,Cp,_p,Ap,Rp,Mp,hp,Fp,Dp,Op,Pa,Xa,Pp,_a,Lp,Vp,Hp,jp,Gp,Kp,Xp,qp,Yp,Qp,Jp,Zp,eh,th,rh,ah,sh,oh,ih,lh,uh,yh,Zd,ch,ph,hh,Za,mh,ts,kh,vh,Ih,rs,Nh,Sh,Ch,Th,Eh,os,$h,Ma,_h,Wp,Ah,Rh,Mh,tp,us,Fh,Dh,ds,Oh,Ph,Lh,Bh,Wh,zh,fs,Gh,Hh,jh,qh,Kh,Uh,Qh,Jh,gs,Zh,ef,rf,ks,vs,sf,uf,cf,Ns,df,ff,gf,yf,bf,ap,$s,xf,Da,kf,op,up,dp,wf,vf,If,Nf,Sf,Cf,Tf,Rs,$f,_f,Af,Rf,Mf,Ff,Df,Ds,nf,Pf,Lf,Bf,Wf,zf,Vf,Ps,Uf,Gf,zs,Yh,Hf,{kernelName:"Tanh",backendName:"cpu",kernelFunc:jf},{kernelName:"Tile",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{reps:s}=r;Sa(a,"tile");const o=Vs(n.bufferSync(a),s);return n.makeTensorInfo(o.shape,o.dtype,o.values)}},{kernelName:"TopK",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a}=t,{k:s,sorted:o}=r;Sa(a,"topk");const i=n.data.get(a.dataId).values,[u,l]=Us(i,a.shape,a.dtype,s);return[n.makeTensorInfo(u.shape,u.dtype,u.values),n.makeTensorInfo(l.shape,l.dtype,l.values)]}},Ts,{kernelName:"Transform",backendName:"cpu",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{image:a,transforms:s}=t,{interpolation:o,fillMode:i,fillValue:u,outputShape:l}=n,[c,d,p,f]=a.shape,[m,g]=null!=l?l:[d,p],y=[c,m,g,f],b=A(a.shape),x=b[0],k=b[1],w=b[2],I=v(a.dtype,h(y));I.fill(u);const N=r.data.get(a.dataId).values,S=r.data.get(s.dataId).values;for(let e=0;e<c;++e){const t=1===s.shape[0]?S:S.subarray(8*e,8*e+8);for(let n=0;n<m;++n)for(let r=0;r<g;++r)for(let a=0;a<f;++a){let s;const l=t[6]*r+t[7]*n+1;if(0===l)continue;const c=(t[0]*r+t[1]*n+t[2])/l,h=(t[3]*r+t[4]*n+t[5])/l,f=qf(c,p,i),m=qf(h,d,i);switch(o){case"nearest":s=Xf(N,d,p,x,k,w,e,m,f,a,u);break;case"bilinear":s=Yf(N,d,p,x,k,w,e,m,f,a,u);break;default:throw new Error("Error in Transform: Expect 'nearest' or 'bilinear', but got "+o)}I[e*x+n*k+r*w+a]=s}return r.makeTensorInfo(y,a.dtype,I)}return{dataId:r.write(I,y,a.dtype),shape:a.shape,dtype:a.dtype}}},{kernelName:"Unique",backendName:"cpu",kernelFunc:function(e){const{inputs:t,attrs:n,backend:r}=e,{axis:a}=n,{x:s}=t;Sa(s,"unique");const o=r.data.get(s.dataId).values,{outputValues:i,outputShape:u,indices:l}=Gs(o,a,s.shape,s.dtype);return[r.makeTensorInfo(u,s.dtype,i),r.makeTensorInfo([l.length],"int32",l)]}},{kernelName:"Unpack",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{value:a}=t;let{axis:s}=r;s<0&&(s+=a.shape.length);const o=a.shape.length,i=a.shape[s],u=new Array(o-1);let l=0;for(let e=0;e<o;e++)e!==s&&(u[l++]=a.shape[e]);const c=new Array(o).fill(0),d=a.shape.slice();d[s]=1;const p=new Array(i);for(let e=0;e<p.length;e++){c[s]=e;const t=Fs({inputs:{x:a},backend:n,attrs:{begin:c,size:d}});p[e]=cp({inputs:{x:t},backend:n,attrs:{shape:u}}),n.disposeIntermediateTensorInfo(t)}return p}},{kernelName:"UnsortedSegmentSum",backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:r}=e,{x:a,segmentIds:s}=t,{numSegments:o}=r;Sa(a,"unsortedSegmentSum");const i=[],u=[],l=a.shape.length-s.shape.length;let c=s;for(let e=0;e<l;++e){const t=fh({inputs:{input:c},backend:n,attrs:{dim:e+1}});c=t,u.push(t)}for(let e=0;e<o;++e){const t=J(e,"int32"),r=n.makeTensorInfo([],"int32",t),s=dh({inputs:{a:r,b:c},backend:n}),o=Oa({inputs:{x:s},backend:n,attrs:{dtype:"float32"}}),l=xs({inputs:{a:o,b:a},backend:n}),d=Xh({inputs:{x:l},backend:n,attrs:{axis:0,keepDims:!1}});i.push(d),u.push(r),u.push(s),u.push(o),u.push(l),u.push(d)}const d=mf({inputs:i,backend:n,attrs:{axis:0}});return u.forEach(e=>n.disposeIntermediateTensorInfo(e)),d}},hf];for(const e of Qf)Y(e);class Jf{refCount(e){return Zf("refCount")}incRef(e){return Zf("incRef")}timerAvailable(){return!0}time(e){return Zf("time")}read(e){return Zf("read")}readSync(e){return Zf("readSync")}numDataIds(){return Zf("numDataIds")}disposeData(e,t){return Zf("disposeData")}write(e,t,n){return Zf("write")}move(e,t,n,r,a){return Zf("move")}memory(){return Zf("memory")}floatPrecision(){return Zf("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return Zf("dispose")}}function Zf(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function em(e){let t=e.length,n=0,r=0;for(;t>0;)r=Math.random()*t|0,t--,n=e[t],e[t]=e[r],e[r]=n}function tm(e,t,n){return Math.max(e,Math.min(t,n))}function nm(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function rm(e,t,n=""){nm(im(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function am(e){nm(null!=e,()=>"The input to the tensor constructor must be a non-null value.")}function sm(e,t=[],n=!1){if(null==t&&(t=[]),Array.isArray(e)||gm(e)&&!n)for(let r=0;r<e.length;++r)sm(e[r],t,n);else t.push(e);return t}function om(e){if(0===e.length)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function im(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function um(e){return e%1==0}function lm(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function cm(e,t){const n=t.length;return nm((e=null==e?t.map((e,t)=>t):[].concat(e)).every(e=>e>=-n&&e<n),()=>`All values in axis param must be in range [-${n}, ${n}) but got axis `+e),nm(e.every(e=>um(e)),()=>"All values in axis param must be integers but got axis "+e),e.map(e=>e<0?n+e:e)}function dm(e,t){const n=[],r=[],a=null!=t&&Array.isArray(t)&&0===t.length,s=null==t||a?null:cm(t,e).sort();let o=0;for(let t=0;t<e.length;++t){if(null!=s){if(s[o]===t&&1!==e[t])throw new Error(`Can't squeeze axis ${t} since its dim '${e[t]}' is not 1`);(null==s[o]||s[o]>t)&&1===e[t]&&(n.push(e[t]),r.push(t)),s[o]<=t&&o++}1!==e[t]&&(n.push(e[t]),r.push(t))}return{newShape:n,keptDims:r}}function pm(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else{if("bool"!==e)throw new Error("Unknown data type "+e);n=new Uint8Array(t)}return n}function hm(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else if("bool"===e)n=new Uint8Array(t);else{if("string"!==e)throw new Error("Unknown data type "+e);n=new Array(t)}return n}function fm(e,t){for(let n=0;n<e.length;n++){const r=e[n];if(isNaN(r)||!isFinite(r))throw Error(`A tensor of type ${t} being uploaded contains ${r}.`)}}function mm(e){return"bool"===e||"complex64"===e||"float32"===e||"int32"===e||"string"===e}function gm(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function ym(e){if("float32"===e||"int32"===e)return 4;if("complex64"===e)return 8;if("bool"===e)return 1;throw new Error("Unknown dtype "+e)}function bm(e){if(null==e)return 0;let t=0;return e.forEach(e=>t+=e.length),t}function xm(e){return"string"==typeof e||e instanceof String}function km(e){return"boolean"==typeof e}function wm(e){return"number"==typeof e}function vm(e){return Array.isArray(e)?vm(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":wm(e)?"float32":xm(e)?"string":km(e)?"bool":"float32"}function Im(e){return!!(e&&e.constructor&&e.call&&e.apply)}function Nm(e,t){for(let n=t;n<e;++n)if(e%n==0)return n;return e}function Sm(e){const t=e.length;if(t<2)return[];const n=new Array(t-1);n[t-2]=e[t-1];for(let r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}function Cm(e,t){if(0===e.length)return t[0];const n=e.reduce((e,t)=>e*t);if(0===n)return[];if(n!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}.`);return function e(t,n,r){const a=new Array;if(1===n.length){const e=n[0];for(let n=0;n<e;n++)a[n]=r[t+n]}else{const s=n[0],o=n.slice(1),i=o.reduce((e,t)=>e*t);for(let n=0;n<s;n++)a[n]=e(t+n*i,o,r)}return a}(0,e,t)}function Tm(e,t){const n=Em(e,t);for(let e=0;e<n.length;e++)n[e]=1;return n}function Em(e,t){if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t)return new Uint8Array(e);throw new Error("Unknown data type "+t)}function $m(e){e.forEach(t=>{nm(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function _m(e){return e&&e.then&&"function"==typeof e.then}class Am{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${t}.`),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},null!=this.urlFlags[e]){const t=this.urlFlags[e];console.warn(`Setting feature override from URL ${e}: ${t}.`),this.set(e,t)}}async getAsync(e){return e in this.flags||(this.flags[e]=await this.evaluateFlag(e)),this.flags[e]}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(_m(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(null==this.flagRegistry[e])throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,null!=this.flagRegistry[e].setHook&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(null==this.flagRegistry[e])throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if("undefined"==typeof this.global||"undefined"==typeof this.global.location||"undefined"==typeof this.global.location.search)return;const e=function(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(e,...n)=>(function(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}(t,n[0],n[1]),n.join("="))),t}(this.global.location.search);if("tfjsflags"in e){e.tfjsflags.split(",").forEach(e=>{const[t,n]=e.split(":");this.urlFlags[t]=function(e,t){if("true"===(t=t.toLowerCase())||"false"===t)return"true"===t;if(""+ +t===t)return+t;throw new Error(`Could not parse value flag value ${t} for flag ${e}.`)}(t,n)})}}}function Rm(){return Fm}let Mm,Fm=null;function Dm(){if(null==Mm){let e;if("undefined"!=typeof window)e=window;else if("undefined"!=typeof global)e=global;else if("undefined"!=typeof process)e=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");e=self}Mm=e}return Mm}function Om(e,t){const n=function(){const e=Dm();return null==e._tfGlobals&&(e._tfGlobals=new Map),e._tfGlobals}();if(n.has(e))return n.get(e);{const r=t();return n.set(e,r),n.get(e)}}const Pm=Om("kernelRegistry",()=>new Map),Lm=Om("gradRegistry",()=>new Map);function Bm(e,t){const n=Um(e,t);return Pm.get(n)}function Wm(e){return Lm.get(e)}function zm(e){const t=Pm.entries(),n=[];for(;;){const{done:r,value:a}=t.next();if(r)break;const[s,o]=a,[i]=s.split("_");i===e&&n.push(o)}return n}function Vm(e){const{kernelName:t,backendName:n}=e,r=Um(t,n);Pm.has(r)&&console.warn(`The kernel '${t}' for backend '${n}' is already registered`),Pm.set(r,e)}function Um(e,t){return`${t}_${e}`}function Gm(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=sm(e)),Rm().getBool("DEBUG")&&fm(e,t),function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t))return e;if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t){const t=new Uint8Array(e.length);for(let n=0;n<t.length;++n)0!==Math.round(e[n])&&(t[n]=1);return t}throw new Error("Unknown data type "+t)}function Hm(){return Rm().platform.now()}function jm(e,t="utf-8"){return t=t||"utf-8",Rm().platform.encode(e,t)}function qm(e,t="utf-8"){return t=t||"utf-8",Rm().platform.decode(e,t)}var Km=Object.freeze({__proto__:null,createScalarValue:function(e,t){return"string"===t?jm(e):Gm([e],t)},toTypedArray:Gm,now:Hm,fetch:function(e,t){return Rm().platform.fetch(e,t)},encodeString:jm,decodeString:qm,shuffle:em,shuffleCombo:function(e,t){if(e.length!==t.length)throw new Error("Array sizes must match to be shuffled together First array length was "+e.length+"Second array length was "+t.length);let n,r,a=e.length,s=0;for(;a>0;)s=Math.random()*a|0,a--,n=e[a],r=t[a],e[a]=e[s],t[a]=t[s],e[s]=n,t[s]=r},clamp:tm,nearestLargerEven:function(e){return e%2==0?e:e+1},sum:function(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t},randUniform:function(e,t){const n=Math.random();return t*n+(1-n)*e},distSquared:function(e,t){let n=0;for(let r=0;r<e.length;r++){const a=Number(e[r])-Number(t[r]);n+=a*a}return n},assert:nm,assertShapesMatch:rm,assertNonNull:am,flatten:sm,sizeFromShape:om,isScalarShape:function(e){return 0===e.length},arraysEqual:im,isInt:um,tanh:function(e){if(null!=Math.tanh)return Math.tanh(e);if(e===1/0)return 1;if(e===-1/0)return-1;{const t=Math.exp(2*e);return(t-1)/(t+1)}},sizeToSquarishShape:function(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]},createShuffledIndices:function(e){const t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return em(t),t},rightPad:lm,repeatedTry:function(e,t=(e=>0),n){return new Promise((r,a)=>{let s=0;const o=()=>{if(e())return void r();s++;const i=t(s);null!=n&&s>=n?a():setTimeout(o,i)};o()})},inferFromImplicitShape:function(e,t){let n=1,r=-1;for(let t=0;t<e.length;++t)if(e[t]>=0)n*=e[t];else if(-1===e[t]){if(-1!==r)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${r} and dim ${t}`);r=t}else if(e[t]<0)throw Error(`Shapes can not be < 0. Found ${e[t]} at dim ${t}`);if(-1===r){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(0===n)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!=0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);const a=e.slice();return a[r]=t/n,a},parseAxisParam:cm,squeezeShape:dm,getTypedArrayFromDType:pm,getArrayFromDType:hm,checkConversionForErrors:fm,isValidDtype:mm,hasEncodingLoss:function(e,t){return"complex64"!==t&&(("float32"!==t||"complex64"===e)&&(("int32"!==t||"float32"===e||"complex64"===e)&&("bool"!==t||"bool"!==e)))},isTypedArray:gm,bytesPerElement:ym,bytesFromStringArray:bm,isString:xm,isBoolean:km,isNumber:wm,inferDtype:vm,isFunction:Im,nearestDivisor:Nm,computeStrides:Sm,toNestedArray:Cm,makeOnesTypedArray:Tm,makeZerosTypedArray:Em,makeZerosNestedTypedArray:function(e,t){const n=e.reduce((e,t)=>e*t,1);if(null==t||"float32"===t)return Cm(e,new Float32Array(n));if("int32"===t)return Cm(e,new Int32Array(n));if("bool"===t)return Cm(e,new Uint8Array(n));throw new Error("Unknown data type "+t)},assertNonNegativeIntegerDimensions:$m,locToIndex:function(e,t,n){if(0===t)return 0;if(1===t)return e[0];let r=e[e.length-1];for(let t=0;t<e.length-1;++t)r+=n[t]*e[t];return r},indexToLoc:function(e,t,n){if(0===t)return[];if(1===t)return[e];const r=new Array(t);for(let t=0;t<r.length-1;++t)r[t]=Math.floor(e/n[t]),e-=r[t]*n[t];return r[r.length-1]=e,r},isPromise:_m});class Xm{constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new Qm)}profileKernel(e,t,n){let r;const a=()=>{r=n()};let s;const o=Hm();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(a);else{a();for(const e of r)e.dataSync();s=Promise.resolve({kernelMs:Hm()-o})}if(Rm().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t<r.length;t++){const n=r[t];n.data().then(t=>{Ym(t,n.dtype,e)})}return{kernelName:e,outputs:r,inputs:t,timeMs:s.then(e=>e.kernelMs),extraInfo:s.then(e=>null!=e.getExtraProfileInfo?e.getExtraProfileInfo():"")}}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:r,inputs:a,extraInfo:s}=e;n.forEach(e=>{Promise.all([e.data(),r,s]).then(n=>{this.logger.logKernelProfile(t,e,n[0],n[1],a,n[2])})})}}function Ym(e,t,n){if("float32"!==t)return!1;for(let t=0;t<e.length;t++){const r=e[t];if(isNaN(r)||!isFinite(r))return console.warn(`Found ${r} in the result of '${n}'`),!0}return!1}class Qm{logKernelProfile(e,t,n,r,a,s){const o="number"==typeof r?lm(r+"ms",9):r.error,i=lm(e,25),u=t.rank,l=t.size,c=lm(t.shape.toString(),14);let d="";for(const e in a){const n=a[e];if(null!=n){const r=n.shape||t.shape,a=r.length;d+=`${e}: ${a}D ${a>0?r:""} `}}console.log(`%c${i}\t%c${o}\t%c${u}D ${c}\t%c${l}\t%c${d}\t%c${s}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function Jm(e,t,n,r){const a=Sm(t),s=function(e,t,n,r){const a=om(t),s=r[r.length-1],o=new Array(s).fill(0),i=t.length,u="complex64"===n?tg(e):e;if(i>1)for(let e=0;e<a/s;e++){const t=e*s;for(let e=0;e<s;e++)o[e]=Math.max(o[e],Zm(u[t+e],0,n).length)}return o}(e,t,n,a),o=t.length,i=function e(t,n,r,a,s,o=!0){const i="complex64"===r?2:1,u=n[0],l=n.length;if(0===l){if("complex64"===r){return[Zm(tg(t)[0],0,r)]}return"bool"===r?[eg(t[0])]:[t[0].toString()]}if(1===l){if(u>20){const e=3*i;let n=Array.from(t.slice(0,e)),a=Array.from(t.slice((u-3)*i,u*i));return"complex64"===r&&(n=tg(n),a=tg(a)),["["+n.map((e,t)=>Zm(e,s[t],r)).join(", ")+", ..., "+a.map((e,t)=>Zm(e,s[u-3+t],r)).join(", ")+"]"]}return["["+("complex64"===r?tg(t):Array.from(t)).map((e,t)=>Zm(e,s[t],r)).join(", ")+"]"]}const c=n.slice(1),d=a.slice(1),p=a[0]*i,h=[];if(u>20){for(let n=0;n<3;n++){const a=n*p,o=a+p;h.push(...e(t.slice(a,o),c,r,d,s,!1))}h.push("...");for(let n=u-3;n<u;n++){const a=n*p,o=a+p;h.push(...e(t.slice(a,o),c,r,d,s,n===u-1))}}else for(let n=0;n<u;n++){const a=n*p,o=a+p;h.push(...e(t.slice(a,o),c,r,d,s,n===u-1))}const f=2===l?",":"";h[0]="["+h[0]+f;for(let e=1;e<h.length-1;e++)h[e]=" "+h[e]+f;let m=",\n";for(let e=2;e<l;e++)m+="\n";return h[h.length-1]=" "+h[h.length-1]+"]"+(o?"":m),h}(e,t,n,a,s),u=["Tensor"];return r&&(u.push("  dtype: "+n),u.push("  rank: "+o),u.push(`  shape: [${t}]`),u.push("  values:")),u.push(i.map(e=>"    "+e).join("\n")),u.join("\n")}function Zm(e,t,n){let r;return r=Array.isArray(e)?parseFloat(e[0].toFixed(7))+" + "+parseFloat(e[1].toFixed(7))+"j":xm(e)?`'${e}'`:"bool"===n?eg(e):parseFloat(e.toFixed(7)).toString(),lm(r,t)}function eg(e){return 0===e?"false":"true"}function tg(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class ng{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=om(e),null!=n){const e=n.length;nm(e===this.size,()=>`Length of values '${e}' does not match the size inferred by the shape '${this.size}'.`)}if("complex64"===t)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||hm(t,this.size),this.strides=Sm(e)}set(e,...t){0===t.length&&(t=[0]),nm(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);const n=this.locToIndex(t);this.values[n]=e}get(...e){0===e.length&&(e=[0]);let t=0;for(const n of e){if(n<0||n>=this.shape[t]){const t=`Requested out of range element at ${e}.   Buffer shape=`+this.shape;throw new Error(t)}t++}let n=e[e.length-1];for(let t=0;t<e.length-1;++t)n+=this.strides[t]*e[t];return this.values[n]}locToIndex(e){if(0===this.rank)return 0;if(1===this.rank)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(0===this.rank)return[];if(1===this.rank)return[e];const t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return rg().makeTensor(this.values,this.shape,this.dtype)}}let rg=null,ag=null;class sg{constructor(e,t,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=om(e),this.strides=Sm(e),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return ag.buffer(this.shape,this.dtype,e)}bufferSync(){return ag.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return Cm(this.shape,e)}arraySync(){return Cm(this.shape,this.dataSync())}async data(){this.throwIfDisposed();const e=rg().read(this.dataId);if("string"===this.dtype){const t=await e;try{return t.map(e=>qm(e))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataSync(){this.throwIfDisposed();const e=rg().readSync(this.dataId);if("string"===this.dtype)try{return e.map(e=>qm(e))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await rg().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(rg().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return ag.print(this,e)}clone(){return this.throwIfDisposed(),ag.clone(this)}toString(e=!1){return Jm(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),ag.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),rg().makeVariable(this,e,t,n)}}Object.defineProperty(sg,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),Om("Tensor",()=>sg);class og extends sg{constructor(e,t,n,r){super(e.shape,e.dtype,e.dataId,r),this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!im(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);rg().disposeTensor(this),this.dataId=e.dataId,rg().incRef(this,null)}dispose(){rg().disposeVariable(this),this.isDisposedInternal=!0}}var ig,ug,lg,cg,dg;Object.defineProperty(og,Symbol.hasInstance,{value:e=>e instanceof sg&&null!=e.assign&&e.assign instanceof Function}),function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"}(ig||(ig={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(ug||(ug={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(lg||(lg={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(cg||(cg={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(dg||(dg={}));const pg={float32:cg,int32:ug,bool:lg,complex64:dg};function hg(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return pg[e][t]}function fg(e,t){if(e.dtype===t.dtype)return[e,t];const n=hg(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function mg(e,t){nm(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function gg(e){const t=[];return function e(t,n,r){if(null==t)return;if(t instanceof sg)return void n.push(t);if(a=t,!Array.isArray(a)&&"object"!=typeof a)return;var a;const s=t;for(const t in s){const a=s[t];r.has(a)||(r.add(a),e(a,n,r))}}(e,t,new Set),t}var yg=Object.freeze({__proto__:null,makeTypesMatch:fg,assertTypesMatch:mg,isTensorInList:function(e,t){return t.some(t=>t.id===e.id)},getTensorsInContainer:gg});function bg(e){return null!=e.kernelName}class xg{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null,get kernelNames(){return Array.from(new Set(this.kernels.map(e=>e.name)))}}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class kg{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new xg}async ready(){if(null!=this.pendingBackendInit)return this.pendingBackendInit.then(()=>{});if(null!=this.backendInstance)return;const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t];if(await this.initializeBackend(n).success)return void await this.setBackend(n)}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(null!=this.pendingBackendInit)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(null==this.backendInstance){const{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry)){if(!(e in this.registryFactory))return null;{const{asyncInit:t}=this.initializeBackend(e);if(t)return null}}return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(console.warn(e+" backend was already registered. Reusing existing backend factory."),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(null==this.registryFactory[e])throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,null==this.registry[e]){this.backendInstance=null;const{success:t,asyncInit:n}=this.initializeBackend(e);if(!(n?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new Xm(this.backendInstance),!0}setupRegisteredKernels(){zm(this.backendName).forEach(e=>{null!=e.setupFunc&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){zm(e).forEach(t=>{null!=t.disposeFunc&&t.disposeFunc(this.registry[e])})}initializeBackend(e){const t=this.registryFactory[e];if(null==t)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const n=t.factory();if(!n||n instanceof Jf||"function"!=typeof n.then)return this.registry[e]=n,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,r=n.then(n=>!(t<this.pendingBackendInitId)&&(this.registry[e]=n,this.pendingBackendInit=null,!0)).catch(n=>(t<this.pendingBackendInitId||(this.pendingBackendInit=null,console.warn(`Initialization of backend ${e} failed`),console.warn(n.stack||n.message)),!1));return this.pendingBackendInit=r,{success:r,asyncInit:!0}}}catch(t){return console.warn(`Initialization of backend ${e} failed`),console.warn(t.stack||t.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(e+" backend not found in registry");this.backendName===e&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],{success:r,asyncInit:a}=this.initializeBackend(n);if(a||r)return{name:n,asyncInit:a}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const n=this.state.tensorInfo.get(t),r=n.backend,a=this.readSync(t),s=r.refCount(t);r.disposeData(t,!0),n.backend=e,e.move(t,a,n.shape,n.dtype,s),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n,r=null;if(null==t){if("function"!=typeof e)throw new Error("Please provide a function to tidy()");t=e}else{if("string"!=typeof e&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof t)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");r=e}return this.scopedRun(()=>this.startScope(r),()=>this.endScope(n),()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n))}scopedRun(e,t,n){e();try{const e=n();return t(),e}catch(e){throw t(),e}}nextTensorId(){return kg.nextTensorId++}nextVariableId(){return kg.nextVariableId++}clone(e){const t=vg.runKernel("Identity",{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],e=>({x:()=>{const t={x:e},n={dtype:"float32"};return vg.runKernel("Cast",t,n)}}),[],{}),t}runKernel(e,t,n){if(!(null!=Bm(e,this.backendName)))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const r=this.backend.numDataIds();let a=0;n.forEach(e=>{a+="complex64"===e.dtype?3:1});const s=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],o=r-t-a-s;if(o>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${o} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[];const r=this.isTapeOn(),a=this.state.numBytes,s=this.state.numTensors;let o,i;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const u=bg(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(bg(e)){const{kernelName:t,inputs:a,attrs:s}=e;null==this.backendName&&this.backend;const u=Bm(t,this.backendName);nm(null!=u,()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`),o=()=>{const e=this.backend.numDataIds();i=u.kernelFunc({inputs:a,attrs:s,backend:this.backend});const o=Array.isArray(i)?i:[i];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,o);const l=o.map(e=>{if(null!=e.rank)return e;const{dataId:t,shape:n,dtype:r}=e;return this.makeTensorFromDataId(t,n,r)});if(r){const e=this.getTensorsForGradient(t,a,l);n=this.saveTensorsForBackwardMode(e)}return l}}else{const{forwardFunc:t}=e,a=e=>{r&&(n=e.map(e=>this.keep(this.clone(e))))};o=()=>{const e=this.backend.numDataIds();i=this.tidy(()=>t(this.backend,a));const n=Array.isArray(i)?i:[i];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(u,e,n),n}}const{inputs:l,attrs:c}=e,d=bg(e)?null:e.backwardsFunc;let p;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(p=this.profiler.profileKernel(u,l,()=>o()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),t=p.outputs):t=o()}),r&&this.addTapeNode(u,l,t,d,n,c),this.state.profiling&&this.state.activeProfile.kernels.push({name:u,bytesAdded:this.state.numBytes-a,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-s,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(l).map(e=>null!=l[e]?l[e].shape:null),outputShapes:t.map(e=>e.shape),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(i)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(e=>this.keep(this.clone(e)))}getTensorsForGradient(e,t,n){const r=Wm(e);if(null!=r){const e=r.inputsToSave||[],a=r.outputsToSave||[];let s;r.saveAllInputs?(nm(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),s=Object.keys(t).map(e=>t[e])):s=e.map(e=>t[e]);const o=n.filter((e,t)=>a[t]);return s.concat(o)}return[]}makeTensor(e,t,n,r){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;let a=e;"string"===n&&xm(e[0])&&.........完整代码请登录后点击上方下载按钮下载查看

网友评论0