UNPKG

@tensorflow/tfjs

Version:

An open-source machine learning framework.

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