@tensorflow/tfjs
Version:
An open-source machine learning framework.
17 lines • 1.1 MB
JavaScript
/**
* @license
* Copyright 2023 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).tf=e.tf||{})}(this,(function(e){"use strict";function t(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(n){if("default"!==n&&!(n in e)){var s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,s.get?s:{enumerable:!0,get:function(){return t[n]}})}}))})),Object.freeze(e)}class n{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class s{refCount(e){return r("refCount")}incRef(e){return r("incRef")}timerAvailable(){return!0}time(e){return r("time")}read(e){return r("read")}readSync(e){return r("readSync")}readToGPU(e,t){return r("readToGPU")}numDataIds(){return r("numDataIds")}disposeData(e,t){return r("disposeData")}write(e,t,n){return r("write")}move(e,t,n,s,a){return r("move")}createTensorFromGPUData(e,t,n){return r("createTensorFromGPUData")}memory(){return r("memory")}floatPrecision(){return r("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return r("dispose")}}function r(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function a(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,l(e,t,n)}function i(e,t,n){return Math.max(e,Math.min(t,n))}function o(e){return e%2==0?e:e+1}function l(e,t,n){const s=e[t];e[t]=e[n],e[n]=s}function u(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function c(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function h(e,t,n=""){c(m(e,t),(()=>n+` Shapes ${e} and ${t} must match`))}function p(e){c(null!=e,(()=>"The input to the tensor constructor must be a non-null value."))}function d(e){if(0===e.length)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function f(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(null!==e[n]&&null!==t[n]&&e[n]!==t[n])return!1;return!0}function m(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function g(e){return e%1==0}function y(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function b(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function x(e,t=(e=>0),n,s){return new Promise(((r,a)=>{let i=0;const o=()=>{if(e())return void r();i++;const l=t(i);null!=n&&i>=n?a():null!=s?s(o,l):setTimeout(o,l)};o()}))}function w(e,t){let n=1,s=-1;for(let t=0;t<e.length;++t)if(e[t]>=0)n*=e[t];else if(-1===e[t]){if(-1!==s)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${s} and dim ${t}`);s=t}else if(e[t]<0)throw Error(`Shapes can not be < 0. Found ${e[t]} at dim ${t}`);if(-1===s){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(0===n)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!=0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);const r=e.slice();return r[s]=t/n,r}function v(e,t){const n=t.length;return c((e=null==e?t.map(((e,t)=>t)):[].concat(e)).every((e=>e>=-n&&e<n)),(()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`)),c(e.every((e=>g(e))),(()=>`All values in axis param must be integers but got axis ${e}`)),e.map((e=>e<0?n+e:e))}function k(e,t){const n=[],s=[],r=null!=t&&Array.isArray(t)&&0===t.length,a=null==t||r?null:v(t,e).sort();let i=0;for(let t=0;t<e.length;++t){if(null!=a){if(a[i]===t&&1!==e[t])throw new Error(`Can't squeeze axis ${t} since its dim '${e[t]}' is not 1`);(null==a[i]||a[i]>t)&&1===e[t]&&(n.push(e[t]),s.push(t)),a[i]<=t&&i++}1!==e[t]&&(n.push(e[t]),s.push(t))}return{newShape:n,keptDims:s}}function N(e,t){return I(e,t)}function I(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else if("bool"===e)n=new Uint8Array(t);else{if("string"!==e)throw new Error(`Unknown data type ${e}`);n=new Array(t)}return n}function S(e,t){for(let n=0;n<e.length;n++){const s=e[n];if(isNaN(s)||!isFinite(s))throw Error(`A tensor of type ${t} being uploaded contains ${s}.`)}}function T(e){return"bool"===e||"complex64"===e||"float32"===e||"int32"===e||"string"===e}function C(e,t){return"complex64"!==t&&(("float32"!==t||"complex64"===e)&&(("int32"!==t||"float32"===e||"complex64"===e)&&("bool"!==t||"bool"!==e)))}function $(e){if("float32"===e||"int32"===e)return 4;if("complex64"===e)return 8;if("bool"===e)return 1;throw new Error(`Unknown dtype ${e}`)}function E(e){if(null==e)return 0;let t=0;return e.forEach((e=>t+=e.length)),t}function A(e){return"string"==typeof e||e instanceof String}function R(e){return"boolean"==typeof e}function _(e){return"number"==typeof e}function F(e){return Array.isArray(e)?F(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":_(e)?"float32":A(e)?"string":R(e)?"bool":"float32"}function D(e){return!!(e&&e.constructor&&e.call&&e.apply)}function O(e,t){for(let n=t;n<e;++n)if(e%n==0)return n;return e}function M(e){const t=e.length;if(t<2)return[];const n=new Array(t-1);n[t-2]=e[t-1];for(let s=t-3;s>=0;--s)n[s]=n[s+1]*e[s+1];return n}function L(e,t,n,s=!1){const r=new Array;if(1===t.length){const a=t[0]*(s?2:1);for(let t=0;t<a;t++)r[t]=n[e+t]}else{const a=t[0],i=t.slice(1),o=i.reduce(((e,t)=>e*t))*(s?2:1);for(let t=0;t<a;t++)r[t]=L(e+t*o,i,n,s)}return r}function z(e,t,n=!1){if(0===e.length)return t[0];const s=e.reduce(((e,t)=>e*t))*(n?2:1);if(0===s)return[];if(s!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return L(0,e,t,n)}function P(e,t){if(Array.isArray(e))return e;if("float32"===t)return e instanceof Float32Array?e:new Float32Array(e);if("int32"===t)return e instanceof Int32Array?e:new Int32Array(e);if("bool"===t||"string"===t)return Uint8Array.from(new Int32Array(e));throw new Error(`Unknown dtype ${t}`)}function B(e,t){const n=W(e,t);for(let e=0;e<n.length;e++)n[e]=1;return n}function W(e,t){if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t)return new Uint8Array(e);throw new Error(`Unknown data type ${t}`)}function V(e,t){const n=e.reduce(((e,t)=>e*t),1);if(null==t||"float32"===t)return z(e,new Float32Array(n));if("int32"===t)return z(e,new Int32Array(n));if("bool"===t)return z(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function U(e){e.forEach((t=>{c(Number.isInteger(t)&&t>=0,(()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`))}))}function G(e,t,n){if(0===t)return 0;if(1===t)return e[0];let s=e[e.length-1];for(let t=0;t<e.length-1;++t)s+=n[t]*e[t];return s}function H(e,t,n){if(0===t)return[];if(1===t)return[e];const s=new Array(t);for(let t=0;t<s.length-1;++t)s[t]=Math.floor(e/n[t]),e-=s[t]*n[t];return s[s.length-1]=e,s}function j(e){return e&&e.then&&"function"==typeof e.then}const q="tfjsflags";class K{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=X,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&(Y().getBool("IS_TEST")||Y().getBool("PROD")||console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${e}.`)),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},null!=this.urlFlags[e]){const t=this.urlFlags[e];Y().getBool("IS_TEST")||Y().getBool("PROD")||console.warn(`Setting feature override from URL ${e}: ${t}.`),this.set(e,t)}}async getAsync(e){return e in this.flags||(this.flags[e]=await this.evaluateFlag(e)),this.flags[e]}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(j(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getString(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(null==this.flagRegistry[e])throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,null!=this.flagRegistry[e].setHook&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(null==this.flagRegistry[e])throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(void 0===this.global||void 0===this.global.location||void 0===this.global.location.search)return;const e=this.getQueryParams(this.global.location.search);if(q in e){e.tfjsflags.split(",").forEach((e=>{const[t,n]=e.split(":");this.urlFlags[t]=function(e,t){const n=t.toLowerCase();return"true"===n||"false"===n?"true"===n:""+ +n===n?+n:t}(0,n)}))}}}function X(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,((e,...n)=>(function(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}(t,n[0],n[1]),n.join("=")))),t}function Y(){return e.ENV}let Z;function J(){if(null==Z){let e;if("undefined"!=typeof window)e=window;else if("undefined"!=typeof global)e=global;else if("undefined"!=typeof process)e=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");e=self}Z=e}return Z}function Q(e,t){const n=function(){const e=J();return null==e._tfGlobals&&(e._tfGlobals=new Map),e._tfGlobals}();if(n.has(e))return n.get(e);{const s=t();return n.set(e,s),n.get(e)}}e.ENV=null;const ee="Abs",te="Acos",ne="Acosh",se="Add",re="AddN",ae="All",ie="Any",oe="ArgMax",le="ArgMin",ue="Asin",ce="Asinh",he="Atan",pe="Atanh",de="Atan2",fe="AvgPool",me="AvgPoolGrad",ge="AvgPool3D",ye="AvgPool3DGrad",be="BatchMatMul",xe="BatchToSpaceND",we="Bincount",ve="BitwiseAnd",ke="BroadcastTo",Ne="BroadcastArgs",Ie="Cast",Se="Ceil",Te="ClipByValue",Ce="Complex",$e="ComplexAbs",Ee="Concat",Ae="Conv2D",Re="Conv2DBackpropFilter",_e="Conv2DBackpropInput",Fe="Conv3D",De="Conv3DBackpropFilterV2",Oe="Conv3DBackpropInputV2",Me="Cos",Le="Cosh",ze="Cumprod",Pe="Cumsum",Be="CropAndResize",We="DenseBincount",Ve="DepthToSpace",Ue="DepthwiseConv2dNative",Ge="DepthwiseConv2dNativeBackpropFilter",He="DepthwiseConv2dNativeBackpropInput",je="Diag",qe="Dilation2D",Ke="Dilation2DBackpropInput",Xe="Dilation2DBackpropFilter",Ye="Draw",Ze="RealDiv",Je="Einsum",Qe="Elu",et="EluGrad",tt="Erf",nt="Equal",st="Exp",rt="ExpandDims",at="Expm1",it="FFT",ot="Fill",lt="FlipLeftRight",ut="Floor",ct="FloorDiv",ht="FusedBatchNorm",pt="GatherV2",dt="GatherNd",ft="Greater",mt="GreaterEqual",gt="Identity",yt="IFFT",bt="Imag",xt="IsFinite",wt="IsInf",vt="IsNan",kt="LeakyRelu",Nt="Less",It="LessEqual",St="LinSpace",Tt="Log",Ct="Log1p",$t="LogicalAnd",Et="LogicalNot",At="LogicalOr",Rt="LogSoftmax",_t="LRN",Ft="LRNGrad",Dt="Max",Ot="Maximum",Mt="MaxPool",Lt="MaxPoolGrad",zt="MaxPool3D",Pt="MaxPool3DGrad",Bt="MaxPoolWithArgmax",Wt="Mean",Vt="Min",Ut="Minimum",Gt="MirrorPad",Ht="Mod",jt="Multinomial",qt="Multiply",Kt="Neg",Xt="NotEqual",Yt="NonMaxSuppressionV3",Zt="NonMaxSuppressionV4",Jt="NonMaxSuppressionV5",Qt="OnesLike",en="OneHot",tn="Pack",nn="PadV2",sn="Pow",rn="Prelu",an="Prod",on="RaggedGather",ln="RaggedRange",un="RaggedTensorToTensor",cn="Range",hn="Real",pn="Reciprocal",dn="Relu",fn="Reshape",mn="ResizeNearestNeighbor",gn="ResizeNearestNeighborGrad",yn="ResizeBilinear",bn="ResizeBilinearGrad",xn="Relu6",wn="Reverse",vn="Round",kn="Rsqrt",Nn="ScatterNd",In="TensorScatterUpdate",Sn="SearchSorted",Tn="Select",Cn="Selu",$n="Slice",En="Sin",An="Sinh",Rn="Sign",_n="Sigmoid",Fn="Softplus",Dn="Sqrt",On="Sum",Mn="SpaceToBatchND",Ln="SplitV",zn="Softmax",Pn="SparseFillEmptyRows",Bn="SparseReshape",Wn="SparseSegmentMean",Vn="SparseSegmentSum",Un="SparseToDense",Gn="SquaredDifference",Hn="Square",jn="StaticRegexReplace",qn="StridedSlice",Kn="StringNGrams",Xn="StringSplit",Yn="StringToHashBucketFast",Zn="Sub",Jn="Tan",Qn="Tanh",es="Tile",ts="TopK",ns="Transform",ss="Transpose",rs="Unique",as="Unpack",is="UnsortedSegmentSum",os="ZerosLike",ls="Step",us="FromPixels",cs="RotateWithOffset",hs="_FusedMatMul",ps="FusedConv2D",ds="FusedDepthwiseConv2D";function fs(...e){Y().getBool("IS_TEST")||Y().getBool("PROD")||console.warn(...e)}const ms=Q("kernelRegistry",(()=>new Map)),gs=Q("gradRegistry",(()=>new Map));function ys(e,t){const n=ks(e,t);return ms.get(n)}function bs(e){return gs.get(e)}function xs(e){const t=ms.entries(),n=[];for(;;){const{done:s,value:r}=t.next();if(s)break;const[a,i]=r,[o]=a.split("_");o===e&&n.push(i)}return n}function ws(e){const{kernelName:t,backendName:n}=e,s=ks(t,n);ms.has(s)&&fs(`The kernel '${t}' for backend '${n}' is already registered`),ms.set(s,e)}function vs(e){const{kernelName:t}=e;gs.has(t)&&Y().getBool("DEBUG")&&fs(`Overriding the gradient for '${t}'`),gs.set(t,e)}function ks(e,t){return`${t}_${e}`}function Ns(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}var Is="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Ss(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ts=$s,Cs=null;try{Cs=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(e){}function $s(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function Es(e){return!0===(e&&e.__isLong__)}$s.prototype.__isLong__,Object.defineProperty($s.prototype,"__isLong__",{value:!0}),$s.isLong=Es;var As={},Rs={};function _s(e,t){var n,s,r;return t?(r=0<=(e>>>=0)&&e<256)&&(s=Rs[e])?s:(n=Ds(e,(0|e)<0?-1:0,!0),r&&(Rs[e]=n),n):(r=-128<=(e|=0)&&e<128)&&(s=As[e])?s:(n=Ds(e,e<0?-1:0,!1),r&&(As[e]=n),n)}function Fs(e,t){if(isNaN(e))return t?Us:Vs;if(t){if(e<0)return Us;if(e>=Ps)return Ks}else{if(e<=-Bs)return Xs;if(e+1>=Bs)return qs}return e<0?Fs(-e,t).neg():Ds(e%zs|0,e/zs|0,t)}function Ds(e,t,n){return new $s(e,t,n)}$s.fromInt=_s,$s.fromNumber=Fs,$s.fromBits=Ds;var Os=Math.pow;function Ms(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return Vs;if("number"==typeof t?(n=t,t=!1):t=!!t,(n=n||10)<2||36<n)throw RangeError("radix");var s;if((s=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===s)return Ms(e.substring(1),t,n).neg();for(var r=Fs(Os(n,8)),a=Vs,i=0;i<e.length;i+=8){var o=Math.min(8,e.length-i),l=parseInt(e.substring(i,i+o),n);if(o<8){var u=Fs(Os(n,o));a=a.mul(u).add(Fs(l))}else a=(a=a.mul(r)).add(Fs(l))}return a.unsigned=t,a}function Ls(e,t){return"number"==typeof e?Fs(e,t):"string"==typeof e?Ms(e,t):Ds(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}$s.fromString=Ms,$s.fromValue=Ls;var zs=4294967296,Ps=zs*zs,Bs=Ps/2,Ws=_s(1<<24),Vs=_s(0);$s.ZERO=Vs;var Us=_s(0,!0);$s.UZERO=Us;var Gs=_s(1);$s.ONE=Gs;var Hs=_s(1,!0);$s.UONE=Hs;var js=_s(-1);$s.NEG_ONE=js;var qs=Ds(-1,2147483647,!1);$s.MAX_VALUE=qs;var Ks=Ds(-1,-1,!0);$s.MAX_UNSIGNED_VALUE=Ks;var Xs=Ds(0,-2147483648,!1);$s.MIN_VALUE=Xs;var Ys=$s.prototype;Ys.toInt=function(){return this.unsigned?this.low>>>0:this.low},Ys.toNumber=function(){return this.unsigned?(this.high>>>0)*zs+(this.low>>>0):this.high*zs+(this.low>>>0)},Ys.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(Xs)){var t=Fs(e),n=this.div(t),s=n.mul(t).sub(this);return n.toString(e)+s.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var r=Fs(Os(e,6),this.unsigned),a=this,i="";;){var o=a.div(r),l=(a.sub(o.mul(r)).toInt()>>>0).toString(e);if((a=o).isZero())return l+i;for(;l.length<6;)l="0"+l;i=""+l+i}},Ys.getHighBits=function(){return this.high},Ys.getHighBitsUnsigned=function(){return this.high>>>0},Ys.getLowBits=function(){return this.low},Ys.getLowBitsUnsigned=function(){return this.low>>>0},Ys.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Xs)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<<t);t--);return 0!=this.high?t+33:t+1},Ys.isZero=function(){return 0===this.high&&0===this.low},Ys.eqz=Ys.isZero,Ys.isNegative=function(){return!this.unsigned&&this.high<0},Ys.isPositive=function(){return this.unsigned||this.high>=0},Ys.isOdd=function(){return 1==(1&this.low)},Ys.isEven=function(){return 0==(1&this.low)},Ys.equals=function(e){return Es(e)||(e=Ls(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},Ys.eq=Ys.equals,Ys.notEquals=function(e){return!this.eq(e)},Ys.neq=Ys.notEquals,Ys.ne=Ys.notEquals,Ys.lessThan=function(e){return this.comp(e)<0},Ys.lt=Ys.lessThan,Ys.lessThanOrEqual=function(e){return this.comp(e)<=0},Ys.lte=Ys.lessThanOrEqual,Ys.le=Ys.lessThanOrEqual,Ys.greaterThan=function(e){return this.comp(e)>0},Ys.gt=Ys.greaterThan,Ys.greaterThanOrEqual=function(e){return this.comp(e)>=0},Ys.gte=Ys.greaterThanOrEqual,Ys.ge=Ys.greaterThanOrEqual,Ys.compare=function(e){if(Es(e)||(e=Ls(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},Ys.comp=Ys.compare,Ys.negate=function(){return!this.unsigned&&this.eq(Xs)?Xs:this.not().add(Gs)},Ys.neg=Ys.negate,Ys.add=function(e){Es(e)||(e=Ls(e));var t=this.high>>>16,n=65535&this.high,s=this.low>>>16,r=65535&this.low,a=e.high>>>16,i=65535&e.high,o=e.low>>>16,l=0,u=0,c=0,h=0;return c+=(h+=r+(65535&e.low))>>>16,u+=(c+=s+o)>>>16,l+=(u+=n+i)>>>16,l+=t+a,Ds((c&=65535)<<16|(h&=65535),(l&=65535)<<16|(u&=65535),this.unsigned)},Ys.subtract=function(e){return Es(e)||(e=Ls(e)),this.add(e.neg())},Ys.sub=Ys.subtract,Ys.multiply=function(e){if(this.isZero())return Vs;if(Es(e)||(e=Ls(e)),Cs)return Ds(Cs.mul(this.low,this.high,e.low,e.high),Cs.get_high(),this.unsigned);if(e.isZero())return Vs;if(this.eq(Xs))return e.isOdd()?Xs:Vs;if(e.eq(Xs))return this.isOdd()?Xs:Vs;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(Ws)&&e.lt(Ws))return Fs(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,n=65535&this.high,s=this.low>>>16,r=65535&this.low,a=e.high>>>16,i=65535&e.high,o=e.low>>>16,l=65535&e.low,u=0,c=0,h=0,p=0;return h+=(p+=r*l)>>>16,c+=(h+=s*l)>>>16,h&=65535,c+=(h+=r*o)>>>16,u+=(c+=n*l)>>>16,c&=65535,u+=(c+=s*o)>>>16,c&=65535,u+=(c+=r*i)>>>16,u+=t*l+n*o+s*i+r*a,Ds((h&=65535)<<16|(p&=65535),(u&=65535)<<16|(c&=65535),this.unsigned)},Ys.mul=Ys.multiply,Ys.divide=function(e){if(Es(e)||(e=Ls(e)),e.isZero())throw Error("division by zero");var t,n,s;if(Cs)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?Ds((this.unsigned?Cs.div_u:Cs.div_s)(this.low,this.high,e.low,e.high),Cs.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?Us:Vs;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Us;if(e.gt(this.shru(1)))return Hs;s=Us}else{if(this.eq(Xs))return e.eq(Gs)||e.eq(js)?Xs:e.eq(Xs)?Gs:(t=this.shr(1).div(e).shl(1)).eq(Vs)?e.isNegative()?Gs:js:(n=this.sub(e.mul(t)),s=t.add(n.div(e)));if(e.eq(Xs))return this.unsigned?Us:Vs;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();s=Vs}for(n=this;n.gte(e);){t=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));for(var r=Math.ceil(Math.log(t)/Math.LN2),a=r<=48?1:Os(2,r-48),i=Fs(t),o=i.mul(e);o.isNegative()||o.gt(n);)o=(i=Fs(t-=a,this.unsigned)).mul(e);i.isZero()&&(i=Gs),s=s.add(i),n=n.sub(o)}return s},Ys.div=Ys.divide,Ys.modulo=function(e){return Es(e)||(e=Ls(e)),Cs?Ds((this.unsigned?Cs.rem_u:Cs.rem_s)(this.low,this.high,e.low,e.high),Cs.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},Ys.mod=Ys.modulo,Ys.rem=Ys.modulo,Ys.not=function(){return Ds(~this.low,~this.high,this.unsigned)},Ys.and=function(e){return Es(e)||(e=Ls(e)),Ds(this.low&e.low,this.high&e.high,this.unsigned)},Ys.or=function(e){return Es(e)||(e=Ls(e)),Ds(this.low|e.low,this.high|e.high,this.unsigned)},Ys.xor=function(e){return Es(e)||(e=Ls(e)),Ds(this.low^e.low,this.high^e.high,this.unsigned)},Ys.shiftLeft=function(e){return Es(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?Ds(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):Ds(0,this.low<<e-32,this.unsigned)},Ys.shl=Ys.shiftLeft,Ys.shiftRight=function(e){return Es(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?Ds(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):Ds(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},Ys.shr=Ys.shiftRight,Ys.shiftRightUnsigned=function(e){if(Es(e)&&(e=e.toInt()),0===(e&=63))return this;var t=this.high;return e<32?Ds(this.low>>>e|t<<32-e,t>>>e,this.unsigned):Ds(32===e?t:t>>>e-32,0,this.unsigned)},Ys.shru=Ys.shiftRightUnsigned,Ys.shr_u=Ys.shiftRightUnsigned,Ys.toSigned=function(){return this.unsigned?Ds(this.low,this.high,!1):this},Ys.toUnsigned=function(){return this.unsigned?this:Ds(this.low,this.high,!0)},Ys.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},Ys.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},Ys.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},$s.fromBytes=function(e,t,n){return n?$s.fromBytesLE(e,t):$s.fromBytesBE(e,t)},$s.fromBytesLE=function(e,t){return new $s(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},$s.fromBytesBE=function(e,t){return new $s(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var Zs=Ss(Ts);const Js=Zs||t({__proto__:null,default:Zs},[Ts]);function Qs(e){return Js.fromString(e,!0,16)}const er=Qs("c3a5c85c97cb3127"),tr=Qs("b492b66fbe98f273"),nr=Qs("9ae16a3b2f90404f");function sr(e){return e.xor(e.shru(47))}function rr(e,t,n){const s=e.slice(t,t+n);return Js.fromBytes(Array.from(s),!0,!0)}function ar(e,t){return rr(e,t,8)}function ir(e,t){return rr(e,t,4)}function or(e,t){return 0===t?e:e.shru(t).or(e.shl(64-t))}function lr(e,t,n=Qs("9ddfea08eb382d69")){let s=e.xor(t).mul(n);s=s.xor(s.shru(47));let r=t.xor(s).mul(n);return r=r.xor(r.shru(47)),r=r.mul(n),r}function ur(e,t,n,s){return function(e,t,n,s,r,a){r=r.add(e),a=or(a.add(r).add(s),21);const i=r;return r=(r=r.add(t)).add(n),a=a.add(or(r,44)),[r.add(s),a.add(i)]}(ar(e,t),ar(e,t+8),ar(e,t+16),ar(e,t+24),n,s)}function cr(e,t=e.length){const n=Js.fromNumber(81,!0);if(t<=32)return t<=16?function(e,t=e.length){if(t>=8){const n=nr.add(2*t),s=ar(e,0).add(nr),r=ar(e,t-8);return lr(or(r,37).mul(n).add(s),or(s,25).add(r).mul(n),n)}if(t>=4){const n=nr.add(2*t);return lr(ir(e,0).shl(3).add(t),ir(e,t-4),n)}if(t>0){const n=e[0]+(e[t>>1]<<8),s=t+(e[t-1]<<2);return sr(nr.mul(n).xor(er.mul(s))).mul(nr)}return nr}(e,t):function(e,t=e.length){const n=nr.add(2*t),s=ar(e,0).mul(tr),r=ar(e,8),a=ar(e,t-8).mul(n),i=ar(e,t-16).mul(nr);return lr(or(s.add(r),43).add(or(a,30)).add(i),s.add(or(r.add(nr),18)).add(a),n)}(e,t);if(t<=64)return function(e,t=e.length){const n=nr.add(2*t),s=ar(e,0).mul(nr),r=ar(e,8),a=ar(e,t-8).mul(n),i=ar(e,t-16).mul(nr),o=or(s.add(r),43).add(or(a,30)).add(i),l=lr(o,s.add(or(r.add(nr),18)).add(a),n),u=ar(e,16).mul(n),c=ar(e,24),h=o.add(ar(e,t-32)).mul(n),p=l.add(ar(e,t-24)).mul(n);return lr(or(u.add(c),43).add(or(h,30)).add(p),u.add(or(c.add(s),18)).add(h),n)}(e,t);let s=n,r=n.mul(tr).add(113),a=sr(r.mul(nr).add(113)).mul(nr),i=[Js.UZERO,Js.UZERO],o=[Js.UZERO,Js.UZERO];s=s.mul(nr).add(ar(e,0));let l=0;const u=64*(t-1>>6),c=u+(t-1&63)-63;do{s=or(s.add(r).add(i[0]).add(ar(e,l+8)),37).mul(tr),r=or(r.add(i[1]).add(ar(e,l+48)),42).mul(tr),s=s.xor(o[1]),r=r.add(i[0]).add(ar(e,l+40)),a=or(a.add(o[0]),33).mul(tr),i=ur(e,l,i[1].mul(tr),s.add(o[0])),o=ur(e,l+32,a.add(o[1]),r.add(ar(e,l+16))),[a,s]=[s,a],l+=64}while(l!==u);const h=tr.add(a.and(255).shl(1));return l=c,o[0]=o[0].add(t-1&63),i[0]=i[0].add(o[0]),o[0]=o[0].add(i[0]),s=or(s.add(r).add(i[0]).add(ar(e,l+8)),37).mul(h),r=or(r.add(i[1]).add(ar(e,l+48)),42).mul(h),s=s.xor(o[1].mul(9)),r=r.add(i[0].mul(9).add(ar(e,l+40))),a=or(a.add(o[0]),33).mul(h),i=ur(e,l,i[1].mul(h),s.add(o[0])),o=ur(e,l+32,a.add(o[1]),r.add(ar(e,l+16))),[a,s]=[s,a],lr(lr(i[0],o[0],h).add(sr(r).mul(er)).add(a),lr(i[1],o[1],h).add(s),h)}function hr(e,t){return"string"===t?mr(e):pr([e],t)}function pr(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=br(e)),Y().getBool("DEBUG")&&S(e,t),function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t))return e;if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t){const t=new Uint8Array(e.length);for(let n=0;n<t.length;++n)0!==Math.round(e[n])&&(t[n]=1);return t}throw new Error(`Unknown data type ${t}`)}function dr(){return Y().platform.now()}function fr(e,t){return Y().platform.fetch(e,t)}function mr(e,t="utf-8"){return t=t||"utf-8",Y().platform.encode(e,t)}function gr(e,t="utf-8"){return t=t||"utf-8",Y().platform.decode(e,t)}function yr(e){return null!=Y().platform.isTypedArray?Y().platform.isTypedArray(e):Ns(e)}function br(e,t=[],n=!1){if(null==t&&(t=[]),"boolean"==typeof e||"number"==typeof e||"string"==typeof e||j(e)||null==e||yr(e)&&n)t.push(e);else if(Array.isArray(e)||yr(e))for(let s=0;s<e.length;++s)br(e[s],t,n);else{let s=-1;for(const t of Object.keys(e))/^([1-9]+[0-9]*|0)$/.test(t)&&(s=Math.max(s,Number(t)));for(let r=0;r<=s;r++)br(e[r],t,n)}return t}var xr=Object.freeze({__proto__:null,arraysEqual:m,arraysEqualWithNull:f,assert:c,assertNonNegativeIntegerDimensions:U,assertNonNull:p,assertShapesMatch:h,bytesFromStringArray:E,bytesPerElement:$,checkConversionForErrors:S,clamp:i,computeStrides:M,convertBackendValuesAndArrayBuffer:P,createScalarValue:hr,createShuffledIndices:function(e){const t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return a(t),t},decodeString:gr,distSquared:function(e,t){let n=0;for(let s=0;s<e.length;s++){const r=Number(e[s])-Number(t[s]);n+=r*r}return n},encodeString:mr,fetch:fr,fingerPrint64:cr,flatten:br,getArrayFromDType:I,getTypedArrayFromDType:N,hasEncodingLoss:C,hexToLong:Qs,indexToLoc:H,inferDtype:F,inferFromImplicitShape:w,isBoolean:R,isFunction:D,isInt:g,isNumber:_,isPromise:j,isScalarShape:function(e){return 0===e.length},isString:A,isTypedArray:yr,isValidDtype:T,locToIndex:G,makeOnesTypedArray:B,makeZerosNestedTypedArray:V,makeZerosTypedArray:W,nearestDivisor:O,nearestLargerEven:o,now:dr,parseAxisParam:v,randUniform:function(e,t){const n=Math.random();return t*n+(1-n)*e},repeatedTry:x,rightPad:b,shuffle:a,shuffleCombo:function(e,t){if(e.length!==t.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${e.length}Second array length was ${t.length}`);let n=e.length,s=0;for(;n>0;)s=Math.random()*n|0,n--,l(e,n,s),l(t,n,s)},sizeFromShape:d,sizeToSquarishShape:y,squeezeShape:k,sum:u,swap:l,tanh:function(e){if(null!=Math.tanh)return Math.tanh(e);if(e===1/0)return 1;if(e===-1/0)return-1;{const t=Math.exp(2*e);return(t-1)/(t+1)}},toNestedArray:z,toTypedArray:pr});class wr{constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new kr)}profileKernel(e,t,n){let s;const r=()=>{s=n()};let a;const i=dr();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(r);else{r();for(const e of s)e.dataSync();a=Promise.resolve({kernelMs:dr()-i})}if(Y().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t<s.length;t++){const n=s[t];n.data().then((t=>{vr(t,n.dtype,e)}))}return{kernelName:e,outputs:s,inputs:t,timeMs:a.then((e=>e.kernelMs)),extraInfo:a.then((e=>null!=e.getExtraProfileInfo?e.getExtraProfileInfo():""))}}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:s,inputs:r,extraInfo:a}=e;n.forEach((e=>{Promise.all([e.data(),s,a]).then((n=>{this.logger.logKernelProfile(t,e,n[0],n[1],r,n[2])}))}))}}function vr(e,t,n){if("float32"!==t)return!1;for(let t=0;t<e.length;t++){const s=e[t];if(isNaN(s)||!isFinite(s))return console.warn(`Found ${s} in the result of '${n}'`),!0}return!1}class kr{logKernelProfile(e,t,n,s,r,a){const i="number"==typeof s?b(`${s}ms`,9):s.error,o=b(e,25),l=t.rank,u=t.size,c=b(t.shape.toString(),14);let h="";for(const e in r){const n=r[e];if(null!=n){const s=n.shape||t.shape,r=s.length;h+=`${e}: ${r}D ${r>0?s:""} `}}console.log(`%c${o}\t%c${i}\t%c${l}D ${c}\t%c${u}\t%c${h}\t%c${a}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function Nr(e,t,n,s){const r=M(t),a=function(e,t,n,s){const r=d(t),a=s[s.length-1],i=new Array(a).fill(0),o=t.length,l="complex64"===n?Cr(e):e;if(o>1)for(let e=0;e<r/a;e++){const t=e*a;for(let e=0;e<a;e++)i[e]=Math.max(i[e],Ir(l[t+e],0,n).length)}return i}(e,t,n,r),i=t.length,o=Tr(e,t,n,r,a),l=["Tensor"];return s&&(l.push(` dtype: ${n}`),l.push(` rank: ${i}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(o.map((e=>" "+e)).join("\n")),l.join("\n")}function Ir(e,t,n){let s;return s=Array.isArray(e)?`${parseFloat(e[0].toFixed(7))} + ${parseFloat(e[1].toFixed(7))}j`:A(e)?`'${e}'`:"bool"===n?Sr(e):parseFloat(e.toFixed(7)).toString(),b(s,t)}function Sr(e){return 0===e?"false":"true"}function Tr(e,t,n,s,r,a=!0){const i="complex64"===n?2:1,o=t[0],l=t.length;if(0===l){if("complex64"===n){return[Ir(Cr(e)[0],0,n)]}return"bool"===n?[Sr(e[0])]:[e[0].toString()]}if(1===l){if(o>20){const t=3*i;let s=Array.from(e.slice(0,t)),a=Array.from(e.slice((o-3)*i,o*i));return"complex64"===n&&(s=Cr(s),a=Cr(a)),["["+s.map(((e,t)=>Ir(e,r[t],n))).join(", ")+", ..., "+a.map(((e,t)=>Ir(e,r[o-3+t],n))).join(", ")+"]"]}return["["+("complex64"===n?Cr(e):Array.from(e)).map(((e,t)=>Ir(e,r[t],n))).join(", ")+"]"]}const u=t.slice(1),c=s.slice(1),h=s[0]*i,p=[];if(o>20){for(let t=0;t<3;t++){const s=t*h,a=s+h;p.push(...Tr(e.slice(s,a),u,n,c,r,!1))}p.push("...");for(let t=o-3;t<o;t++){const s=t*h,a=s+h;p.push(...Tr(e.slice(s,a),u,n,c,r,t===o-1))}}else for(let t=0;t<o;t++){const s=t*h,a=s+h;p.push(...Tr(e.slice(s,a),u,n,c,r,t===o-1))}const d=2===l?",":"";p[0]="["+(o>0?p[0]+d:"");for(let e=1;e<p.length-1;e++)p[e]=" "+p[e]+d;let f=",\n";for(let e=2;e<l;e++)f+="\n";return p[p.length-1]=" "+p[p.length-1]+"]"+(a?"":f),p}function Cr(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class $r{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=d(e),null!=n){const e=n.length;c(e===this.size,(()=>`Length of values '${e}' does not match the size inferred by the shape '${this.size}'.`))}if("complex64"===t)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||I(t,this.size),this.strides=M(e)}set(e,...t){0===t.length&&(t=[0]),c(t.length===this.rank,(()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`));const n=this.locToIndex(t);this.values[n]=e}get(...e){0===e.length&&(e=[0]);let t=0;for(const n of e){if(n<0||n>=this.shape[t]){const t=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(t)}t++}let n=e[e.length-1];for(let t=0;t<e.length-1;++t)n+=this.strides[t]*e[t];return this.values[n]}locToIndex(e){if(0===this.rank)return 0;if(1===this.rank)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(0===this.rank)return[];if(1===this.rank)return[e];const t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Er().makeTensor(this.values,this.shape,this.dtype)}}let Er=null,Ar=null,Rr=null;class _r{constructor(e,t,n,s){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=d(e),this.strides=M(e),this.dataId=n,this.id=s,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return Ar.buffer(this.shape,this.dtype,e)}bufferSync(){return Ar.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return z(this.shape,e,"complex64"===this.dtype)}arraySync(){return z(this.shape,this.dataSync(),"complex64"===this.dtype)}async data(){this.throwIfDisposed();const e=Er().read(this.dataId);if("string"===this.dtype){const t=await e;try{return t.map((e=>gr(e)))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataToGPU(e){return this.throwIfDisposed(),Er().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=Er().readSync(this.dataId);if("string"===this.dtype)try{return e.map((e=>gr(e)))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await Er().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),Er().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Ar.print(this,e)}clone(){return this.throwIfDisposed(),Ar.clone(this)}toString(e=!1){return Nr(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Ar.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Er().makeVariable(this,e,t,n)}}function Fr(){return Q("Tensor",(()=>_r))}Object.defineProperty(_r,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),Fr();class Dr extends _r{constructor(e,t,n,s){super(e.shape,e.dtype,e.dataId,s),this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!m(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Er().disposeTensor(this),this.dataId=e.dataId,Er().incRef(this,null)}dispose(){Er().disposeVariable(this),this.isDisposedInternal=!0}}var Or,Mr,Lr,zr,Pr;Object.defineProperty(Dr,Symbol.hasInstance,{value:e=>e instanceof _r&&null!=e.assign&&e.assign instanceof Function}),e.Rank=void 0,(Or=e.Rank||(e.Rank={})).R0="R0",Or.R1="R1",Or.R2="R2",Or.R3="R3",Or.R4="R4",Or.R5="R5",Or.R6="R6",function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(Mr||(Mr={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(Lr||(Lr={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(zr||(zr={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(Pr||(Pr={}));const Br={float32:zr,int32:Mr,bool:Lr,complex64:Pr};function Wr(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return Br[e][t]}function Vr(e){return Wr(e,"int32")}function Ur(e){return null!=e&&"object"==typeof e&&"texture"in e&&e.texture instanceof WebGLTexture}function Gr(e){return"undefined"!=typeof GPUBuffer&&null!=e&&"object"==typeof e&&"buffer"in e&&e.buffer instanceof GPUBuffer}function Hr(e,t){if(e.dtype===t.dtype)return[e,t];const n=Wr(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function jr(e,t){c(e.dtype===t.dtype,(()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`))}function qr(e,t){return t.some((t=>t.id===e.id))}function Kr(e){const t=[];return Xr(e,t,new Set),t}function Xr(e,t,n){if(null==e)return;if(e instanceof _r)return void t.push(e);if(s=e,!Array.isArray(s)&&"object"!=typeof s)return;var s;const r=e;for(const e in r){const s=r[e];n.has(s)||(n.add(s),Xr(s,t,n))}}var Yr=Object.freeze({__proto__:null,assertTypesMatch:jr,getTensorsInContainer:Kr,isTensorInList:qr,makeTypesMatch:Hr});function Zr(e){return null!=e.kernelName}class Jr{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null,get kernelNames(){return Array.from(new Set(this.kernels.map((e=>e.name))))}}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class Qr{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Jr}async ready(){if(null!=this.pendingBackendInit)return this.pendingBackendInit.then((()=>{}));if(null!=this.backendInstance)return;const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t];if(await this.initializeBackend(n).success)return void await this.setBackend(n)}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(null!=this.pendingBackendInit)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(null==this.backendInstance){const{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry)){if(!(e in this.registryFactory))return null;{const{asyncInit:t}=this.initializeBackend(e);if(t)return null}}return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(fs(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(null==this.registryFactory[e])throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,null==this.registry[e]){this.backendInstance=null;const{success:t,asyncInit:n}=this.initializeBackend(e);if(!(n?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new wr(this.backendInstance),!0}setupRegisteredKernels(){xs(this.backendName).forEach((e=>{null!=e.setupFunc&&e.setupFunc(this.backendInstance)}))}disposeRegisteredKernels(e){xs(e).forEach((t=>{null!=t.disposeFunc&&t.disposeFunc(this.registry[e])}))}initializeBackend(e){const t=this.registryFactory[e];if(null==t)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const n=t.factory();if(!n||n instanceof s||"function"!=typeof n.then)return this.registry[e]=n,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,s=n.then((n=>!(t<this.pendingBackendInitId)&&(this.registry[e]=n,this.pendingBackendInit=null,!0))).catch((n=>(t<this.pendingBackendInitId||(this.pendingBackendInit=null,fs(`Initialization of backend ${e} failed`),fs(n.stack||n.message)),!1)));return this.pendingBackendInit=s,{success:s,asyncInit:!0}}}catch(t){return fs(`Initialization of backend ${e} failed`),fs(t.stack||t.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort(((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority))}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],{success:s,asyncInit:r}=this.initializeBackend(n);if(r||s)return{name:n,asyncInit:r}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const n=this.state.tensorInfo.get(t),s=n.backend,r=this.readSync(t),a=s.refCount(t);s.disposeData(t,!0),n.backend=e,e.move(t,r,n.shape,n.dtype,a),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n,s=null;if(null==t){if("function"!=typeof e)throw new Error("Please provide a function to tidy()");t=e}else{if("string"!=typeof e&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof t)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");s=e}return this.scopedRun((()=>this.startScope(s)),(()=>this.endScope(n)),(()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n)))}scopedRun(e,t,n){e();try{const e=n();return t(),e}catch(e){throw t(),e}}nextTensorId(){return Qr.nextTensorId++}nextVariableId(){return Qr.nextVariableId++}clone(e){const t=ta.runKernel(gt,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e},n={dtype:"float32"};return ta.runKernel(Ie,t,n)}})),[],{}),t}runKernel(e,t,n){null==this.backendName&&this.backend;if(!(null!=ys(e,this.backendName)))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const s=this.backend.numDataIds();let r=0;n.forEach((e=>{r+="complex64"===e.dtype?3:1}));const a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=s-t-r-a;if(i>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${i} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[];const s=this.isTapeOn(),r=this.state.numBytes,a=this.state.numTensors;let i,o;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const l=Zr(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(Zr(e)){const{kernelName:t,inputs:r,attrs:a}=e;null==this.backendName&&this.backend;const l=ys(t,this.backendName);c(null!=l,(()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`)),i=()=>{const e=this.backend.numDataIds();o=l.kernelFunc({inputs:r,attrs:a,backend:this.backend});const i=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,i);const u=i.map((e=>null!=e.rank?e:this.makeTensorFromTensorInfo(e)));if(s){const e=this.getTensorsForGradient(t,r,u);n=this.saveTensorsForBackwardMode(e)}return u}}else{const{forwardFunc:t}=e,r=e=>{s&&(n=e.map((e=>this.keep(this.clone(e)))))};i=()=>{const e=this.backend.numDataIds();o=this.tidy((()=>t(this.backend,r)));const n=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,e,n),n}}const{inputs:u,attrs:h}=e,p=Zr(e)?null:e.backwardsFunc;let d;return this.scopedRun((()=>this.state.kernelDepth++),(()=>this.state.kernelDepth--),(()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(d=this.profiler.profileKernel(l,u,(()=>i())),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(d),t=d.outputs):t=i()})),s&&this.addTapeNode(l,u,t,p,n,h),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-r,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-a,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(u).map((e=>null!=u[e]?u[e].shape:null)),outputShapes:t.map((e=>e.shape)),kernelTimeMs:d.timeMs,extraInfo:d.extraInfo}),Array.isArray(o)?t:t[0]}saveTensorsForBackwardMode(e){const t=e.map((e=>this.keep(this.clone(e))));return t}getTensorsForGradient(e,t,n){const s=bs(e);if(null!=s){const e=s.inputsToSave||[],r=s.outputsToSave||[];let a;s.saveAllInputs?(c(Array.isArray(t),(()=>"saveAllInputs is true, expected inputs to be an array.")),a=Object.keys(t).map((e=>t[e]))):a=e.map((e=>t[e]));const i=n.filter(((e,t)=>r[t]));return a.concat(i)}return[]}makeTensor(e,t,n,s){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",s=s||this.backend;let r=e;"string"===n&&A(e[0])&&(r=e.map((e=>mr(e))));const a=s.write(r,t,n),i=new _r(t,n,a,this.nextTensorId());if(this.trackTensor(i,s),"string"===n){const e=this.state.tensorInfo.get(a),t=E(r);this.state.numBytes+=t-e.bytes,e.bytes=t}return i}makeTensorFromDataId(e,t,n,s){const r={dataId:e,shape:t,dtype:n=n||"float32"};return this.makeTensorFromTensorInfo(r,s)}makeTensorFromTensorInfo(e,t){const{dataId:n,shape:s,dtype:r}=e,a=new _r(s,r,n,this.nextTensorId());return this.trackTensor(a,t),a}makeVariable(e,t=!0,n,s){n=n||this.nextVariableId().toString(),null!=s&&s!==e.dtype&&(e=e.cast(s));const r=new Dr(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[r.name])throw new Error(`Variable with name ${r.name} was already registered`);return this.state.registeredVariables[r.name]=r,this.incRef(r,this.backend),r}trackTensor(e,t){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*$(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof Dr||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;const t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,"string"===e.dtype&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),"complex64"!==e.dtype&&"string"!==e.dtype){const t=e.size*$(e.dtype);this.state.numBytes-=t}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),null!=this.state.registeredVariables[e.name]&&delete this.state.registeredVariables[e.name]}memory(){const e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,null==e.reasons&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map((e=>e.totalBytesSnapshot))),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const e of this.state.activeProfile.kernels)e.kernelTimeMs=await e.kernelTimeMs,e.extraInfo=await e.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&0===this.state.kernelDepth}addTapeNode(e,t,n,s,r,a){const i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:r},o=bs(e);null!=o&&(s=o.gradFunc),null!=s&&