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).........完整代码请登录后点击上方下载按钮下载查看

网友评论0