UNPKG

@robotical/martyblocks

Version:
227 lines 1.78 MB
var b8=Object.defineProperty,IS=Object.getOwnPropertySymbols,x8=Object.prototype.hasOwnProperty,w8=Object.prototype.propertyIsEnumerable,ug=Math.pow,cg=(e,t,n)=>t in e?b8(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,hg=(e,t)=>{for(var n in t||(t={}))x8.call(t,n)&&cg(e,n,t[n]);if(IS)for(var n of IS(t))w8.call(t,n)&&cg(e,n,t[n]);return e},ie=(e,t,n)=>(cg(e,"symbol"!=typeof t?t+"":t,n),n),_=(e,t,n)=>new Promise((s,r)=>{var a=e=>{try{o(n.next(e))}catch(e){r(e)}},i=e=>{try{o(n.throw(e))}catch(e){r(e)}},o=e=>e.done?s(e.value):Promise.resolve(e.value).then(a,i);o((n=n.apply(e,t)).next())});!function(){"use strict";class e{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 t{refCount(e){return n("refCount")}incRef(e){return n("incRef")}timerAvailable(){return!0}time(e){return n("time")}read(e){return n("read")}readSync(e){return n("readSync")}readToGPU(e,t){return n("readToGPU")}numDataIds(){return n("numDataIds")}disposeData(e,t){return n("disposeData")}write(e,t,s){return n("write")}move(e,t,s,r,a){return n("move")}createTensorFromGPUData(e,t,s){return n("createTensorFromGPUData")}memory(){return n("memory")}floatPrecision(){return n("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return n("dispose")}}function n(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`)} /** * @license * Copyright 2020 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 s(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,i(e,t,n)}function r(e,t,n){return Math.max(e,Math.min(t,n))}function a(e){return e%2==0?e:e+1}function i(e,t,n){const s=e[t];e[t]=e[n],e[n]=s}function o(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function l(e,t,n=""){o(h(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function u(e){o(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||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function p(e){return e%1==0}function d(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function f(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function m(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 g(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 y(e,t){const n=t.length;return o((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}`),o(e.every(e=>p(e)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(e=>e<0?n+e:e)}function b(e,t){const n=[],s=[],r=null!=t&&Array.isArray(t)&&0===t.length,a=null==t||r?null:y(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 x(e,t){return w(e,t)}function w(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 v(e,t){return!("complex64"===t||"float32"===t&&"complex64"!==e||"int32"===t&&"float32"!==e&&"complex64"!==e||"bool"===t&&"bool"===e)}function k(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 I(e){return"string"==typeof e||e instanceof String}function N(e){return"number"==typeof e}function S(e){return Array.isArray(e)?S(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":N(e)?"float32":I(e)?"string":function(e){return"boolean"==typeof e}(e)?"bool":"float32"}function T(e){return!!(e&&e.constructor&&e.call&&e.apply)}function $(e,t){for(let n=t;n<e;++n)if(e%n===0)return n;return e}function C(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 E(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]=E(e+t*o,i,n,s)}return r}function R(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 E(0,e,t,n)}function A(e,t){const n=F(e,t);for(let e=0;e<n.length;e++)n[e]=1;return n}function F(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 D(e,t){const n=e.reduce((e,t)=>e*t,1);if(null==t||"float32"===t)return R(e,new Float32Array(n));if("int32"===t)return R(e,new Int32Array(n));if("bool"===t)return R(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function O(e){e.forEach(t=>{o(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function M(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 L(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 z(e){return e&&e.then&&"function"==typeof e.then} /** * @license * Copyright 2017 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. * ============================================================================= */const P="tfjsflags";class B{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=W,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&(V().getBool("IS_TEST")||V().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];V().getBool("IS_TEST")||V().getBool("PROD")||console.warn(`Setting feature override from URL ${e}: ${t}.`),this.set(e,t)}}getAsync(e){return _(this,null,function*(){return e in this.flags||(this.flags[e]=yield this.evaluateFlag(e)),this.flags[e]})}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(z(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);P in e&&e[P].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 W(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 V(){return G}let U,G=null;function H(){if(null==U){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}U=e}return U}function j(e,t){const n=function(){const e=H();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",K="Acos",X="Acosh",Y="Add",J="AddN",Z="All",Q="Any",ee="ArgMax",te="ArgMin",ne="Asin",se="Asinh",re="Atan",ae="Atanh",oe="Atan2",le="AvgPool",ue="AvgPoolGrad",ce="AvgPool3D",he="AvgPool3DGrad",pe="BatchMatMul",de="BatchToSpaceND",fe="Bincount",me="BitwiseAnd",ge="BroadcastArgs",ye="Cast",be="Ceil",xe="ClipByValue",we="Complex",ve="ComplexAbs",ke="Concat",Ie="Conv2D",Ne="Conv2DBackpropFilter",Se="Conv2DBackpropInput",Te="Conv3D",$e="Conv3DBackpropFilterV2",Ce="Conv3DBackpropInputV2",Ee="Cos",_e="Cosh",Re="Cumprod",Ae="Cumsum",Fe="CropAndResize",De="DenseBincount",Oe="DepthToSpace",Me="DepthwiseConv2dNative",Le="DepthwiseConv2dNativeBackpropFilter",ze="DepthwiseConv2dNativeBackpropInput",Pe="Diag",Be="Dilation2D",We="Dilation2DBackpropInput",Ve="Dilation2DBackpropFilter",Ue="RealDiv",Ge="Einsum",He="Elu",je="EluGrad",qe="Erf",Ke="Equal",Xe="Exp",Ye="ExpandDims",Je="Expm1",Ze="FFT",Qe="Fill",et="FlipLeftRight",tt="Floor",nt="FloorDiv",st="FusedBatchNorm",rt="GatherV2",at="GatherNd",it="Greater",ot="GreaterEqual",lt="Identity",ut="IFFT",ct="Imag",ht="IsFinite",pt="IsInf",dt="IsNan",ft="LeakyRelu",mt="Less",gt="LessEqual",yt="LinSpace",bt="Log",xt="Log1p",wt="LogicalAnd",vt="LogicalNot",kt="LogicalOr",It="LRN",Nt="LRNGrad",St="Max",Tt="Maximum",$t="MaxPool",Ct="MaxPoolGrad",Et="MaxPool3D",_t="MaxPool3DGrad",Rt="MaxPoolWithArgmax",At="Mean",Ft="Min",Dt="Minimum",Ot="MirrorPad",Mt="Mod",Lt="Multinomial",zt="Multiply",Pt="Neg",Bt="NotEqual",Wt="NonMaxSuppressionV3",Vt="NonMaxSuppressionV4",Ut="NonMaxSuppressionV5",Gt="OnesLike",Ht="OneHot",jt="Pack",qt="PadV2",Kt="Pow",Xt="Prelu",Yt="Prod",Jt="RaggedGather",Zt="RaggedRange",Qt="RaggedTensorToTensor",en="Range",tn="Real",nn="Reciprocal",sn="Relu",rn="Reshape",an="ResizeNearestNeighbor",on="ResizeNearestNeighborGrad",ln="ResizeBilinear",un="ResizeBilinearGrad",cn="Relu6",hn="Reverse",pn="Round",dn="Rsqrt",fn="ScatterNd",mn="TensorScatterUpdate",gn="SearchSorted",yn="Select",bn="Selu",xn="Slice",wn="Sin",vn="Sinh",kn="Sign",In="Sigmoid",Nn="Softplus",Sn="Sqrt",Tn="Sum",$n="SpaceToBatchND",Cn="SplitV",En="Softmax",_n="SparseFillEmptyRows",Rn="SparseReshape",An="SparseSegmentMean",Fn="SparseSegmentSum",Dn="SparseToDense",On="SquaredDifference",Mn="Square",Ln="StaticRegexReplace",zn="StridedSlice",Pn="StringNGrams",Bn="StringSplit",Wn="StringToHashBucketFast",Vn="Sub",Un="Tan",Gn="Tanh",Hn="Tile",jn="TopK",qn="Transform",Kn="Transpose",Xn="Unique",Yn="Unpack",Jn="UnsortedSegmentSum",Zn="ZerosLike",Qn="Step",es="FromPixels",ts="RotateWithOffset",ns="_FusedMatMul",ss="FusedConv2D",rs="FusedDepthwiseConv2D"; /** * @license * Copyright 2018 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 as(...e){V().getBool("IS_TEST")||V().getBool("PROD")||console.warn(...e)} /** * @license * Copyright 2019 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. * ============================================================================= */ const is=j("kernelRegistry",()=>new Map),os=j("gradRegistry",()=>new Map);function ls(e,t){const n=ds(e,t);return is.get(n)}function us(e){return os.get(e)}function cs(e){const t=is.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 hs(e){const{kernelName:t,backendName:n}=e,s=ds(t,n);is.has(s)&&as(`The kernel '${t}' for backend '${n}' is already registered`),is.set(s,e)}function ps(e){const{kernelName:t}=e;os.has(t)&&V().getBool("DEBUG")&&as(`Overriding the gradient for '${t}'`),os.set(t,e)}function ds(e,t){return`${t}_${e}` /** * @license * Copyright 2023 Google LLC. * 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 fs(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}var ms="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};var gs=bs,ys=null;try{ys=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(Ws){}function bs(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function xs(e){return!0===(e&&e.__isLong__)}bs.prototype.__isLong__,Object.defineProperty(bs.prototype,"__isLong__",{value:!0}),bs.isLong=xs;var ws={},vs={};function ks(e,t){var n,s,r;return t?(r=0<=(e>>>=0)&&e<256)&&(s=vs[e])?s:(n=Ns(e,(0|e)<0?-1:0,!0),r&&(vs[e]=n),n):(r=-128<=(e|=0)&&e<128)&&(s=ws[e])?s:(n=Ns(e,e<0?-1:0,!1),r&&(ws[e]=n),n)}function Is(e,t){if(isNaN(e))return t?Fs:As;if(t){if(e<0)return Fs;if(e>=Es)return zs}else{if(e<=-_s)return Ps;if(e+1>=_s)return Ls}return e<0?Is(-e,t).neg():Ns(e%Cs|0,e/Cs|0,t)}function Ns(e,t,n){return new bs(e,t,n)}bs.fromInt=ks,bs.fromNumber=Is,bs.fromBits=Ns;var Ss=Math.pow;function Ts(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return As;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 Ts(e.substring(1),t,n).neg();for(var r=Is(Ss(n,8)),a=As,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=Is(Ss(n,o));a=a.mul(u).add(Is(l))}else a=(a=a.mul(r)).add(Is(l))}return a.unsigned=t,a}function $s(e,t){return"number"==typeof e?Is(e,t):"string"==typeof e?Ts(e,t):Ns(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}bs.fromString=Ts,bs.fromValue=$s;var Cs=4294967296,Es=Cs*Cs,_s=Es/2,Rs=ks(1<<24),As=ks(0);bs.ZERO=As;var Fs=ks(0,!0);bs.UZERO=Fs;var Ds=ks(1);bs.ONE=Ds;var Os=ks(1,!0);bs.UONE=Os;var Ms=ks(-1);bs.NEG_ONE=Ms;var Ls=Ns(-1,2147483647,!1);bs.MAX_VALUE=Ls;var zs=Ns(-1,-1,!0);bs.MAX_UNSIGNED_VALUE=zs;var Ps=Ns(0,-2147483648,!1);bs.MIN_VALUE=Ps;var Bs=bs.prototype;Bs.toInt=function(){return this.unsigned?this.low>>>0:this.low},Bs.toNumber=function(){return this.unsigned?(this.high>>>0)*Cs+(this.low>>>0):this.high*Cs+(this.low>>>0)},Bs.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(Ps)){var t=Is(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=Is(Ss(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}},Bs.getHighBits=function(){return this.high},Bs.getHighBitsUnsigned=function(){return this.high>>>0},Bs.getLowBits=function(){return this.low},Bs.getLowBitsUnsigned=function(){return this.low>>>0},Bs.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Ps)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&!(e&1<<t);t--);return 0!=this.high?t+33:t+1},Bs.isZero=function(){return 0===this.high&&0===this.low},Bs.eqz=Bs.isZero,Bs.isNegative=function(){return!this.unsigned&&this.high<0},Bs.isPositive=function(){return this.unsigned||this.high>=0},Bs.isOdd=function(){return!(1&~this.low)},Bs.isEven=function(){return!(1&this.low)},Bs.equals=function(e){return xs(e)||(e=$s(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},Bs.eq=Bs.equals,Bs.notEquals=function(e){return!this.eq(e)},Bs.neq=Bs.notEquals,Bs.ne=Bs.notEquals,Bs.lessThan=function(e){return this.comp(e)<0},Bs.lt=Bs.lessThan,Bs.lessThanOrEqual=function(e){return this.comp(e)<=0},Bs.lte=Bs.lessThanOrEqual,Bs.le=Bs.lessThanOrEqual,Bs.greaterThan=function(e){return this.comp(e)>0},Bs.gt=Bs.greaterThan,Bs.greaterThanOrEqual=function(e){return this.comp(e)>=0},Bs.gte=Bs.greaterThanOrEqual,Bs.ge=Bs.greaterThanOrEqual,Bs.compare=function(e){if(xs(e)||(e=$s(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},Bs.comp=Bs.compare,Bs.negate=function(){return!this.unsigned&&this.eq(Ps)?Ps:this.not().add(Ds)},Bs.neg=Bs.negate,Bs.add=function(e){xs(e)||(e=$s(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,Ns((c&=65535)<<16|(h&=65535),(l&=65535)<<16|(u&=65535),this.unsigned)},Bs.subtract=function(e){return xs(e)||(e=$s(e)),this.add(e.neg())},Bs.sub=Bs.subtract,Bs.multiply=function(e){if(this.isZero())return As;if(xs(e)||(e=$s(e)),ys)return Ns(ys.mul(this.low,this.high,e.low,e.high),ys.get_high(),this.unsigned);if(e.isZero())return As;if(this.eq(Ps))return e.isOdd()?Ps:As;if(e.eq(Ps))return this.isOdd()?Ps:As;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(Rs)&&e.lt(Rs))return Is(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,Ns((h&=65535)<<16|(p&=65535),(u&=65535)<<16|(c&=65535),this.unsigned)},Bs.mul=Bs.multiply,Bs.divide=function(e){if(xs(e)||(e=$s(e)),e.isZero())throw Error("division by zero");var t,n,s;if(ys)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?Ns((this.unsigned?ys.div_u:ys.div_s)(this.low,this.high,e.low,e.high),ys.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?Fs:As;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Fs;if(e.gt(this.shru(1)))return Os;s=Fs}else{if(this.eq(Ps))return e.eq(Ds)||e.eq(Ms)?Ps:e.eq(Ps)?Ds:(t=this.shr(1).div(e).shl(1)).eq(As)?e.isNegative()?Ds:Ms:(n=this.sub(e.mul(t)),s=t.add(n.div(e)));if(e.eq(Ps))return this.unsigned?Fs:As;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=As}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:Ss(2,r-48),i=Is(t),o=i.mul(e);o.isNegative()||o.gt(n);)o=(i=Is(t-=a,this.unsigned)).mul(e);i.isZero()&&(i=Ds),s=s.add(i),n=n.sub(o)}return s},Bs.div=Bs.divide,Bs.modulo=function(e){return xs(e)||(e=$s(e)),ys?Ns((this.unsigned?ys.rem_u:ys.rem_s)(this.low,this.high,e.low,e.high),ys.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},Bs.mod=Bs.modulo,Bs.rem=Bs.modulo,Bs.not=function(){return Ns(~this.low,~this.high,this.unsigned)},Bs.and=function(e){return xs(e)||(e=$s(e)),Ns(this.low&e.low,this.high&e.high,this.unsigned)},Bs.or=function(e){return xs(e)||(e=$s(e)),Ns(this.low|e.low,this.high|e.high,this.unsigned)},Bs.xor=function(e){return xs(e)||(e=$s(e)),Ns(this.low^e.low,this.high^e.high,this.unsigned)},Bs.shiftLeft=function(e){return xs(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?Ns(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):Ns(0,this.low<<e-32,this.unsigned)},Bs.shl=Bs.shiftLeft,Bs.shiftRight=function(e){return xs(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?Ns(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):Ns(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},Bs.shr=Bs.shiftRight,Bs.shiftRightUnsigned=function(e){if(xs(e)&&(e=e.toInt()),0===(e&=63))return this;var t=this.high;return e<32?Ns(this.low>>>e|t<<32-e,t>>>e,this.unsigned):Ns(32===e?t:t>>>e-32,0,this.unsigned)},Bs.shru=Bs.shiftRightUnsigned,Bs.shr_u=Bs.shiftRightUnsigned,Bs.toSigned=function(){return this.unsigned?Ns(this.low,this.high,!1):this},Bs.toUnsigned=function(){return this.unsigned?this:Ns(this.low,this.high,!0)},Bs.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},Bs.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]},Bs.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]},bs.fromBytes=function(e,t,n){return n?bs.fromBytesLE(e,t):bs.fromBytesBE(e,t)},bs.fromBytesLE=function(e,t){return new bs(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},bs.fromBytesBE=function(e,t){return new bs(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var Ws,Vs=(Ws=gs)&&Ws.__esModule&&Object.prototype.hasOwnProperty.call(Ws,"default")?Ws.default:Ws,Us=function(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)} /** * @license * Copyright 2020 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. * ============================================================================= */({__proto__:null,default:Vs},[gs]); /** * @license * Copyright 2021 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */const Gs=Vs||Us;function Hs(e){return Gs.fromString(e,!0,16)}const js=Hs("c3a5c85c97cb3127"),qs=Hs("b492b66fbe98f273"),Ks=Hs("9ae16a3b2f90404f");function Xs(e){return e.xor(e.shru(47))}function Ys(e,t,n){const s=e.slice(t,t+n);return Gs.fromBytes(Array.from(s),!0,!0)}function Js(e,t){return Ys(e,t,8)}function Zs(e,t){return Ys(e,t,4)}function Qs(e,t){return 0===t?e:e.shru(t).or(e.shl(64-t))}function er(e,t,n=Hs("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 tr(e,t,n,s){return function(e,t,n,s,r,a){r=r.add(e),a=Qs(a.add(r).add(s),21);const i=r;return r=(r=r.add(t)).add(n),a=a.add(Qs(r,44)),[r.add(s),a.add(i)]}(Js(e,t),Js(e,t+8),Js(e,t+16),Js(e,t+24),n,s)}function nr(e,t=e.length){const n=Gs.fromNumber(81,!0);if(t<=32)return t<=16?function(e,t=e.length){if(t>=8){const n=Ks.add(2*t),s=Js(e,0).add(Ks),r=Js(e,t-8);return er(Qs(r,37).mul(n).add(s),Qs(s,25).add(r).mul(n),n)}if(t>=4){const n=Ks.add(2*t);return er(Zs(e,0).shl(3).add(t),Zs(e,t-4),n)}if(t>0){const n=e[0]+(e[t>>1]<<8),s=t+(e[t-1]<<2);return Xs(Ks.mul(n).xor(js.mul(s))).mul(Ks)}return Ks}(e,t):function(e,t=e.length){const n=Ks.add(2*t),s=Js(e,0).mul(qs),r=Js(e,8),a=Js(e,t-8).mul(n),i=Js(e,t-16).mul(Ks);return er(Qs(s.add(r),43).add(Qs(a,30)).add(i),s.add(Qs(r.add(Ks),18)).add(a),n)}(e,t);if(t<=64)return function(e,t=e.length){const n=Ks.add(2*t),s=Js(e,0).mul(Ks),r=Js(e,8),a=Js(e,t-8).mul(n),i=Js(e,t-16).mul(Ks),o=Qs(s.add(r),43).add(Qs(a,30)).add(i),l=er(o,s.add(Qs(r.add(Ks),18)).add(a),n),u=Js(e,16).mul(n),c=Js(e,24),h=o.add(Js(e,t-32)).mul(n),p=l.add(Js(e,t-24)).mul(n);return er(Qs(u.add(c),43).add(Qs(h,30)).add(p),u.add(Qs(c.add(s),18)).add(h),n)}(e,t);let s=n,r=n.mul(qs).add(113),a=Xs(r.mul(Ks).add(113)).mul(Ks),i=[Gs.UZERO,Gs.UZERO],o=[Gs.UZERO,Gs.UZERO];s=s.mul(Ks).add(Js(e,0));let l=0;const u=64*(t-1>>6),c=u+(t-1&63)-63;do{s=Qs(s.add(r).add(i[0]).add(Js(e,l+8)),37).mul(qs),r=Qs(r.add(i[1]).add(Js(e,l+48)),42).mul(qs),s=s.xor(o[1]),r=r.add(i[0]).add(Js(e,l+40)),a=Qs(a.add(o[0]),33).mul(qs),i=tr(e,l,i[1].mul(qs),s.add(o[0])),o=tr(e,l+32,a.add(o[1]),r.add(Js(e,l+16))),[a,s]=[s,a],l+=64}while(l!==u);const h=qs.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=Qs(s.add(r).add(i[0]).add(Js(e,l+8)),37).mul(h),r=Qs(r.add(i[1]).add(Js(e,l+48)),42).mul(h),s=s.xor(o[1].mul(9)),r=r.add(i[0].mul(9).add(Js(e,l+40))),a=Qs(a.add(o[0]),33).mul(h),i=tr(e,l,i[1].mul(h),s.add(o[0])),o=tr(e,l+32,a.add(o[1]),r.add(Js(e,l+16))),[a,s]=[s,a],er(er(i[0],o[0],h).add(Xs(r).mul(js)).add(a),er(i[1],o[1],h).add(s),h)} /** * @license * Copyright 2017 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 sr(e,t){return"string"===t?ir(e):rr([e],t)}function rr(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=ur(e)),V().getBool("DEBUG")&&function(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}.`)}}(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 ar(){return V().platform.now()}function ir(e,t="utf-8"){return t=t||"utf-8",V().platform.encode(e,t)}function or(e,t="utf-8"){return t=t||"utf-8",V().platform.decode(e,t)}function lr(e){return null!=V().platform.isTypedArray?V().platform.isTypedArray(e):fs(e)}function ur(e,t=[],n=!1){if(null==t&&(t=[]),"boolean"==typeof e||"number"==typeof e||"string"==typeof e||z(e)||null==e||lr(e)&&n)t.push(e);else if(Array.isArray(e)||lr(e))for(let s=0;s<e.length;++s)ur(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++)ur(e[r],t,n)}return t} /** * @license * Copyright 2018 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. * ============================================================================= */class cr{constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new pr)}profileKernel(e,t,n){let s;const r=()=>{s=n()};let a;const i=ar();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(r);else{r();for(const e of s)e.dataSync();a=Promise.resolve({kernelMs:ar()-i})}if(V().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t<s.length;t++){const n=s[t];n.data().then(t=>{hr(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 hr(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 pr{logKernelProfile(e,t,n,s,r,a){const i="number"==typeof s?f(`${s}ms`,9):s.error,o=f(e,25),l=t.rank,u=t.size,c=f(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")}} /** * @license * Copyright 2017 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 dr(e,t,n,s){const r=C(t),a=function(e,t,n,s){const r=c(t),a=s[s.length-1],i=new Array(a).fill(0),o=t.length,l="complex64"===n?yr(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],fr(l[t+e],0,n).length)}return i}(e,t,n,r),i=t.length,o=gr(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 fr(e,t,n){let s;return s=Array.isArray(e)?`${parseFloat(e[0].toFixed(7))} + ${parseFloat(e[1].toFixed(7))}j`:I(e)?`'${e}'`:"bool"===n?mr(e):parseFloat(e.toFixed(7)).toString(),f(s,t)}function mr(e){return 0===e?"false":"true"}function gr(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[fr(yr(e)[0],0,n)]}return"bool"===n?[mr(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=yr(s),a=yr(a)),["["+s.map((e,t)=>fr(e,r[t],n)).join(", ")+", ..., "+a.map((e,t)=>fr(e,r[o-3+t],n)).join(", ")+"]"]}return["["+("complex64"===n?yr(e):Array.from(e)).map((e,t)=>fr(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(...gr(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(...gr(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(...gr(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 yr(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t} /** * @license * Copyright 2017 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. * ============================================================================= */class br{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=c(e),null!=n){const e=n.length;o(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||w(t,this.size),this.strides=C(e)}set(e,...t){0===t.length&&(t=[0]),o(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 xr().makeTensor(this.values,this.shape,this.dtype)}}let xr=null,wr=null;class vr{constructor(e,t,n,s){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=c(e),this.strides=C(e),this.dataId=n,this.id=s,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}buffer(){return _(this,null,function*(){const e=yield this.data();return wr.buffer(this.shape,this.dtype,e)})}bufferSync(){return wr.buffer(this.shape,this.dtype,this.dataSync())}array(){return _(this,null,function*(){const e=yield this.data();return R(this.shape,e,"complex64"===this.dtype)})}arraySync(){return R(this.shape,this.dataSync(),"complex64"===this.dtype)}data(){return _(this,null,function*(){this.throwIfDisposed();const e=xr().read(this.dataId);if("string"===this.dtype){const t=yield e;try{return t.map(e=>or(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(),xr().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=xr().readSync(this.dataId);if("string"===this.dtype)try{return e.map(e=>or(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}bytes(){return _(this,null,function*(){this.throwIfDisposed();const e=yield xr().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)})}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),xr().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return wr.print(this,e)}clone(){return this.throwIfDisposed(),wr.clone(this)}toString(e=!1){return dr(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),wr.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),xr().makeVariable(this,e,t,n)}}function kr(){return j("Tensor",()=>vr)}Object.defineProperty(vr,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),kr();class Ir extends vr{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(!h(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);xr().disposeTensor(this),this.dataId=e.dataId,xr().incRef(this,null)}dispose(){xr().disposeVariable(this),this.isDisposedInternal=!0}} /** * @license * Copyright 2017 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. * ============================================================================= */ var Nr,Sr,Tr,$r,Cr;Object.defineProperty(Ir,Symbol.hasInstance,{value:e=>e instanceof vr&&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"}(Nr||(Nr={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(Sr||(Sr={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(Tr||(Tr={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}($r||($r={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(Cr||(Cr={}));const Er={float32:$r,int32:Sr,bool:Tr,complex64:Cr};function _r(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return Er[e][t]}function Rr(e){return _r(e,"int32")}function Ar(e){return null!=e&&"object"==typeof e&&"texture"in e&&e.texture instanceof WebGLTexture}function Fr(e){return"undefined"!=typeof GPUBuffer&&null!=e&&"object"==typeof e&&"buffer"in e&&e.buffer instanceof GPUBuffer} /** * @license * Copyright 2018 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 Dr(e,t){if(e.dtype===t.dtype)return[e,t];const n=_r(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function Or(e,t){return t.some(t=>t.id===e.id)}function Mr(e){const t=[];return Lr(e,t,new Set),t}function Lr(e,t,n){if(null==e)return;if(e instanceof vr)return void t.push(e);if(!function(e){return Array.isArray(e)||"object"==typeof e} /** * @license * Copyright 2018 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. * ============================================================================= */(e))return;const s=e;for(const e in s){const r=s[e];n.has(r)||(n.add(r),Lr(r,t,n))}}function zr(e){return null!=e.kernelName}class Pr{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 Br{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Pr}ready(){return _(this,null,function*(){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(yield this.initializeBackend(n).success)return void(yield 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?(as(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}setBackend(e){return _(this,null,function*(){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?yield t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new cr(this.backendInstance),!0})}setupRegisteredKernels(){cs(this.backendName).forEach(e=>{null!=e.setupFunc&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){cs(e).forEach(t=>{null!=t.disposeFunc&&t.disposeFunc(this.registry[e])})}initializeBackend(e){const n=this.registryFactory[e];if(null==n)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const s=n.factory();if(!s||s instanceof t||"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,as(`Initialization of backend ${e} failed`),as(n.stack||n.message)),!1));return this.pendingBackendInit=n,{success:n,asyncInit:!0}}}catch(t){return as(`Initialization of backend ${e} failed`),as(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 argum