UNPKG

@tensorflow/tfjs-core

Version:

Hardware-accelerated JavaScript library for machine intelligence

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