UNPKG

@robotical/martyblocks

Version:

MartyBlocks based on Scratch for Marty the Robot by Robotical

2 lines 1.09 MB
/*! For license information please see MLModelWorker.js.LICENSE.txt */ var JC=Object.defineProperty,QC=(e,t,n)=>t in e?JC(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,oe=(e,t,n)=>(QC(e,"symbol"!=typeof t?t+"":t,n),n);function Gp(e,t){for(var n=0;n<t.length;n++){const s=t[n];if("string"!=typeof s&&!Array.isArray(s))for(const t in s)if("default"!==t&&!(t in e)){const n=Object.getOwnPropertyDescriptor(s,t);n&&Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>s[t]})}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}class Fc{constructor(){oe(this,"output",[]),oe(this,"predictionIdx",-1)}}var fn=(e=>(e.PREPARE_ENGINE="PREPARE_ENGINE",e.TRAIN="TRAIN",e.STOP_TRAINING="STOP_TRAINING",e.PREDICT="PREDICT",e.PREDICT_ACCELEROMETER="PREDICT_ACCELEROMETER",e.RESET_MODEL="RESET_MODEL",e.SAVE_MODEL="SAVE_MODEL",e.LOAD_MODEL="LOAD_MODEL",e.LOAD_AUDIO_MODEL="LOAD_AUDIO_MODEL",e.SET_TRAINING_DATA="SET_TRAINING_DATA",e.STREAM_AUDIO="STREAM_AUDIO",e.AUDIO_START_LISTENING="AUDIO_START_LISTENING",e.STOP_AUDIO_LISTENING="STOP_AUDIO_LISTENING",e.LOAD_TM_MODEL="LOAD_TM_MODEL",e))(fn||{});class Br{constructor(){oe(this,"isTraining",!1),oe(this,"isTrained",!1),oe(this,"isPrediction",!1),oe(this,"i",0),oe(this,"iterations",0),oe(this,"preprocessTime"),oe(this,"modelFitTime",0),oe(this,"lossValues",[]),oe(this,"accuracyValues",[]),oe(this,"historyReset"),oe(this,"lossPoint"),oe(this,"accuracyPoint"),oe(this,"stoppedEarly"),oe(this,"backend"),oe(this,"memory"),oe(this,"accuracy",0),oe(this,"isCorrect",[]),oe(this,"examples",[]),oe(this,"predictions",new Fc),oe(this,"modelPredictTime",0)}}const ZC=1e-7,e$=1e-4;class Hp{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 xd{refCount(e){return Nn("refCount")}incRef(e){return Nn("incRef")}timerAvailable(){return!0}time(e){return Nn("time")}read(e){return Nn("read")}readSync(e){return Nn("readSync")}readToGPU(e,t){return Nn("readToGPU")}numDataIds(){return Nn("numDataIds")}disposeData(e,t){return Nn("disposeData")}write(e,t,n){return Nn("write")}move(e,t,n,s,a){return Nn("move")}createTensorFromGPUData(e,t,n){return Nn("createTensorFromGPUData")}memory(){return Nn("memory")}floatPrecision(){return Nn("floatPrecision")}epsilon(){return 32===this.floatPrecision()?ZC:e$}dispose(){return Nn("dispose")}}function Nn(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 kl(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,Ko(e,t,n)}function so(e,t,n){return Math.max(e,Math.min(t,n))}function qp(e){return e%2==0?e:e+1}function Ko(e,t,n){const s=e[t];e[t]=e[n],e[n]=s}function t$(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function v(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function yd(e,t,n=""){v(Ye(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function wd(e){v(null!=e,()=>"The input to the tensor constructor must be a non-null value.")}function M(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 Ye(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 aa(e){return e%1==0}function rp(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function ea(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function Gg(e,t=e=>0,n,s){return new Promise((a,r)=>{let i=0;const o=()=>{if(e())return void a();i++;const l=t(i);null!=n&&i>=n?r():null!=s?s(o,l):setTimeout(o,l)};o()})}function jp(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 a=e.slice();return a[s]=t/n,a}function Ae(e,t){const n=t.length;return v((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}`),v(e.every(e=>aa(e)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(e=>e<0?n+e:e)}function Sr(e,t){const n=[],s=[],a=null!=t&&Array.isArray(t)&&0===t.length,r=null==t||a?null:Ae(t,e).sort();let i=0;for(let t=0;t<e.length;++t){if(null!=r){if(r[i]===t&&1!==e[t])throw new Error(`Can't squeeze axis ${t} since its dim '${e[t]}' is not 1`);(null==r[i]||r[i]>t)&&1===e[t]&&(n.push(e[t]),s.push(t)),r[i]<=t&&i++}1!==e[t]&&(n.push(e[t]),s.push(t))}return{newShape:n,keptDims:s}}function en(e,t){return Nt(e,t)}function Nt(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else if("bool"===e)n=new Uint8Array(t);else{if("string"!==e)throw new Error(`Unknown data type ${e}`);n=new Array(t)}return n}function n$(e,t){for(let n=0;n<e.length;n++){const s=e[n];if(isNaN(s)||!isFinite(s))throw Error(`A tensor of type ${t} being uploaded contains ${s}.`)}}function s$(e){return"bool"===e||"complex64"===e||"float32"===e||"int32"===e||"string"===e}function Wx(e,t){return!("complex64"===t||"float32"===t&&"complex64"!==e||"int32"===t&&"float32"!==e&&"complex64"!==e||"bool"===t&&"bool"===e)}function ia(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 r$(e){if(null==e)return 0;let t=0;return e.forEach(e=>t+=e.length),t}function Wl(e){return"string"==typeof e||e instanceof String}function o$(e){return"boolean"==typeof e}function op(e){return"number"==typeof e}function Io(e){return Array.isArray(e)?Io(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":op(e)?"float32":Wl(e)?"string":o$(e)?"bool":"float32"}function ap(e){return!!(e&&e.constructor&&e.call&&e.apply)}function ip(e,t){for(let n=t;n<e;++n)if(e%n===0)return n;return e}function me(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 Vx(e,t,n,s=!1){const a=new Array;if(1===t.length){const r=t[0]*(s?2:1);for(let t=0;t<r;t++)a[t]=n[e+t]}else{const r=t[0],i=t.slice(1),o=i.reduce((e,t)=>e*t)*(s?2:1);for(let t=0;t<r;t++)a[t]=Vx(e+t*o,i,n,s)}return a}function ms(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 Vx(0,e,t,n)}function a$(e,t){if(Array.isArray(e))return e;if("float32"===t)return e instanceof Float32Array?e:new Float32Array(e);if("int32"===t)return e instanceof Int32Array?e:new Int32Array(e);if("bool"===t||"string"===t)return Uint8Array.from(new Int32Array(e));throw new Error(`Unknown dtype ${t}`)}function Kp(e,t){const n=tn(e,t);for(let e=0;e<n.length;e++)n[e]=1;return n}function tn(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 Ux(e,t){const n=e.reduce((e,t)=>e*t,1);if(null==t||"float32"===t)return ms(e,new Float32Array(n));if("int32"===t)return ms(e,new Int32Array(n));if("bool"===t)return ms(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function tr(e){e.forEach(t=>{v(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function As(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 va(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 Id(e){return e&&e.then&&"function"==typeof e.then}const Hg="tfjsflags";class i${constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=l$,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&(H().getBool("IS_TEST")||H().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];H().getBool("IS_TEST")||H().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(Id(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);Hg in e&&e[Hg].split(",").forEach(e=>{const[t,n]=e.split(":");this.urlFlags[t]=c$(t,n)})}}function l$(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(e,...n)=>(u$(t,n[0],n[1]),n.join("="))),t}function u$(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function c$(e,t){const n=t.toLowerCase();return"true"===n||"false"===n?"true"===n:""+ +n===n?+n:t}function H(){return Gx}let Fh,Gx=null;function d$(e){Gx=e}function Hx(){if(null==Fh){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}Fh=e}return Fh}function h$(){const e=Hx();return null==e._tfGlobals&&(e._tfGlobals=new Map),e._tfGlobals}function Xp(e,t){const n=h$();if(n.has(e))return n.get(e);{const s=t();return n.set(e,s),n.get(e)}}const Vl="Abs",Ca="Acos",$a="Acosh",ko="Add",Ul="AddN",Gl="All",Hl="Any",ql="ArgMax",jl="ArgMin",Sa="Asin",Na="Asinh",Ta="Atan",Ea="Atanh",_a="Atan2",Ra="AvgPool",kd="AvgPoolGrad",Kl="AvgPool3D",vd="AvgPool3DGrad",Aa="BatchMatMul",Xl="BatchToSpaceND",Yl="Bincount",Cd="BitwiseAnd",p$="BroadcastTo",Yp="BroadcastArgs",Da="Cast",Fa="Ceil",vo="ClipByValue",Jp="Complex",$d="ComplexAbs",Jl="Concat",Ma="Conv2D",Qp="Conv2DBackpropFilter",Oa="Conv2DBackpropInput",La="Conv3D",Ql="Conv3DBackpropFilterV2",Zl="Conv3DBackpropInputV2",Pa="Cos",za="Cosh",eu="Cumprod",Ba="Cumsum",tu="CropAndResize",Sd="DenseBincount",nu="DepthToSpace",Wa="DepthwiseConv2dNative",Zp="DepthwiseConv2dNativeBackpropFilter",ef="DepthwiseConv2dNativeBackpropInput",tf="Diag",Va="Dilation2D",vl="Dilation2DBackpropInput",Cl="Dilation2DBackpropFilter",f$="Draw",Ua="RealDiv",nf="Einsum",Ga="Elu",su="EluGrad",Ha="Erf",ru="Equal",qa="Exp",ou="ExpandDims",ja="Expm1",sf="FFT",Nd="Fill",au="FlipLeftRight",Ka="Floor",Xa="FloorDiv",Ya="FusedBatchNorm",iu="GatherV2",Td="GatherNd",lu="Greater",Ja="GreaterEqual",Qa="Identity",rf="IFFT",of="Imag",Za="IsFinite",ei="IsInf",ti="IsNan",ni="LeakyRelu",uu="Less",cu="LessEqual",Ed="LinSpace",si="Log",ri="Log1p",du="LogicalAnd",hu="LogicalNot",pu="LogicalOr",m$="LogicalXor",g$="LogSoftmax",oi="LRN",fu="LRNGrad",ai="Max",ii="Maximum",li="MaxPool",_d="MaxPoolGrad",mu="MaxPool3D",Rd="MaxPool3DGrad",af="MaxPoolWithArgmax",ui="Mean",ci="Min",di="Minimum",hi="MirrorPad",pi="Mod",Ad="Multinomial",fi="Multiply",gu="Neg",bu="NotEqual",xu="NonMaxSuppressionV3",yu="NonMaxSuppressionV4",wu="NonMaxSuppressionV5",Iu="OnesLike",mi="OneHot",ku="Pack",gi="PadV2",bi="Pow",xi="Prelu",yi="Prod",qx="RaggedGather",jx="RaggedRange",Kx="RaggedTensorToTensor",Dd="Range",lf="Real",wi="Reciprocal",Ii="Relu",vu="Reshape",ki="ResizeNearestNeighbor",Cu="ResizeNearestNeighborGrad",vi="ResizeBilinear",$u="ResizeBilinearGrad",Ci="Relu6",$i="Reverse",Si="Round",Ni="Rsqrt",Fd="ScatterNd",Md="TensorScatterUpdate",Od="SearchSorted",Su="Select",Ti="Selu",Nu="Slice",Ei="Sin",_i="Sinh",Ri="Sign",Ai="Sigmoid",Di="Softplus",Fi="Sqrt",Mi="Sum",Tu="SpaceToBatchND",Eu="SplitV",Oi="Softmax",uf="SparseFillEmptyRows",Ld="SparseReshape",cf="SparseSegmentMean",df="SparseSegmentSum",Pd="SparseToDense",Li="SquaredDifference",zd="Square",hf="StaticRegexReplace",_u="StridedSlice",pf="StringNGrams",ff="StringSplit",mf="StringToHashBucketFast",Pi="Sub",zi="Tan",Bi="Tanh",Co="Tile",Ru="TopK",Au="Transform",hr="Transpose",Bd="Unique",Du="Unpack",Wd="UnsortedSegmentSum",Fu="ZerosLike",$o="Step",b$="FromPixels",Mu="RotateWithOffset",la="_FusedMatMul",ua="FusedConv2D",Vd="FusedDepthwiseConv2D";function Ln(...e){H().getBool("IS_TEST")||H().getBool("PROD")||console.warn(...e)}function x$(...e){H().getBool("IS_TEST")||H().getBool("PROD")||console.log(...e)}const Bc=Xp("kernelRegistry",()=>new Map),lp=Xp("gradRegistry",()=>new Map);function qg(e,t){const n=Xx(e,t);return Bc.get(n)}function jg(e){return lp.get(e)}function Kg(e){const t=Bc.entries(),n=[];for(;;){const{done:s,value:a}=t.next();if(s)break;const[r,i]=a,[o]=r.split("_");o===e&&n.push(i)}return n}function gf(e){const{kernelName:t,backendName:n}=e,s=Xx(t,n);Bc.has(s)&&Ln(`The kernel '${t}' for backend '${n}' is already registered`),Bc.set(s,e)}function y$(e){const{kernelName:t}=e;lp.has(t)&&H().getBool("DEBUG")&&Ln(`Overriding the gradient for '${t}'`),lp.set(t,e)}function Xx(e,t){return`${t}_${e}`}function Yx(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}var Js="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function bf(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function w$(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var n=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var s=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(n,t,s.get?s:{enumerable:!0,get:function(){return e[t]}})}),n}var Jx=mt,Zn=null;try{Zn=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 mt(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function Dn(e){return!0===(e&&e.__isLong__)}mt.prototype.__isLong__,Object.defineProperty(mt.prototype,"__isLong__",{value:!0}),mt.isLong=Dn;var Xg={},Yg={};function So(e,t){var n,s,a;return t?(a=0<=(e>>>=0)&&e<256)&&(s=Yg[e])?s:(n=gt(e,(0|e)<0?-1:0,!0),a&&(Yg[e]=n),n):(a=-128<=(e|=0)&&e<128)&&(s=Xg[e])?s:(n=gt(e,e<0?-1:0,!1),a&&(Xg[e]=n),n)}function es(e,t){if(isNaN(e))return t?Kr:ts;if(t){if(e<0)return Kr;if(e>=Qx)return ty}else{if(e<=-Qg)return En;if(e+1>=Qg)return ey}return e<0?es(-e,t).neg():gt(e%ca|0,e/ca|0,t)}function gt(e,t,n){return new mt(e,t,n)}mt.fromInt=So,mt.fromNumber=es,mt.fromBits=gt;var Wc=Math.pow;function xf(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return ts;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 xf(e.substring(1),t,n).neg();for(var a=es(Wc(n,8)),r=ts,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=es(Wc(n,o));r=r.mul(u).add(es(l))}else r=(r=r.mul(a)).add(es(l))}return r.unsigned=t,r}function ks(e,t){return"number"==typeof e?es(e,t):"string"==typeof e?xf(e,t):gt(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}mt.fromString=xf,mt.fromValue=ks;var Jg=65536,I$=1<<24,ca=Jg*Jg,Qx=ca*ca,Qg=Qx/2,Zg=So(I$),ts=So(0);mt.ZERO=ts;var Kr=So(0,!0);mt.UZERO=Kr;var Qo=So(1);mt.ONE=Qo;var Zx=So(1,!0);mt.UONE=Zx;var up=So(-1);mt.NEG_ONE=up;var ey=gt(-1,2147483647,!1);mt.MAX_VALUE=ey;var ty=gt(-1,-1,!0);mt.MAX_UNSIGNED_VALUE=ty;var En=gt(0,-2147483648,!1);mt.MIN_VALUE=En;var le=mt.prototype;le.toInt=function(){return this.unsigned?this.low>>>0:this.low},le.toNumber=function(){return this.unsigned?(this.high>>>0)*ca+(this.low>>>0):this.high*ca+(this.low>>>0)},le.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(En)){var t=es(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 a=es(Wc(e,6),this.unsigned),r=this,i="";;){var o=r.div(a),l=(r.sub(o.mul(a)).toInt()>>>0).toString(e);if((r=o).isZero())return l+i;for(;l.length<6;)l="0"+l;i=""+l+i}},le.getHighBits=function(){return this.high},le.getHighBitsUnsigned=function(){return this.high>>>0},le.getLowBits=function(){return this.low},le.getLowBitsUnsigned=function(){return this.low>>>0},le.getNumBitsAbs=function(){if(this.isNegative())return this.eq(En)?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},le.isZero=function(){return 0===this.high&&0===this.low},le.eqz=le.isZero,le.isNegative=function(){return!this.unsigned&&this.high<0},le.isPositive=function(){return this.unsigned||this.high>=0},le.isOdd=function(){return!(1&~this.low)},le.isEven=function(){return!(1&this.low)},le.equals=function(e){return Dn(e)||(e=ks(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},le.eq=le.equals,le.notEquals=function(e){return!this.eq(e)},le.neq=le.notEquals,le.ne=le.notEquals,le.lessThan=function(e){return this.comp(e)<0},le.lt=le.lessThan,le.lessThanOrEqual=function(e){return this.comp(e)<=0},le.lte=le.lessThanOrEqual,le.le=le.lessThanOrEqual,le.greaterThan=function(e){return this.comp(e)>0},le.gt=le.greaterThan,le.greaterThanOrEqual=function(e){return this.comp(e)>=0},le.gte=le.greaterThanOrEqual,le.ge=le.greaterThanOrEqual,le.compare=function(e){if(Dn(e)||(e=ks(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},le.comp=le.compare,le.negate=function(){return!this.unsigned&&this.eq(En)?En:this.not().add(Qo)},le.neg=le.negate,le.add=function(e){Dn(e)||(e=ks(e));var t=this.high>>>16,n=65535&this.high,s=this.low>>>16,a=65535&this.low,r=e.high>>>16,i=65535&e.high,o=e.low>>>16,l=0,u=0,c=0,h=0;return c+=(h+=a+(65535&e.low))>>>16,u+=(c+=s+o)>>>16,l+=(u+=n+i)>>>16,l+=t+r,gt((c&=65535)<<16|(h&=65535),(l&=65535)<<16|(u&=65535),this.unsigned)},le.subtract=function(e){return Dn(e)||(e=ks(e)),this.add(e.neg())},le.sub=le.subtract,le.multiply=function(e){if(this.isZero())return ts;if(Dn(e)||(e=ks(e)),Zn)return gt(Zn.mul(this.low,this.high,e.low,e.high),Zn.get_high(),this.unsigned);if(e.isZero())return ts;if(this.eq(En))return e.isOdd()?En:ts;if(e.eq(En))return this.isOdd()?En:ts;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(Zg)&&e.lt(Zg))return es(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,n=65535&this.high,s=this.low>>>16,a=65535&this.low,r=e.high>>>16,i=65535&e.high,o=e.low>>>16,l=65535&e.low,u=0,c=0,h=0,d=0;return h+=(d+=a*l)>>>16,c+=(h+=s*l)>>>16,h&=65535,c+=(h+=a*o)>>>16,u+=(c+=n*l)>>>16,c&=65535,u+=(c+=s*o)>>>16,c&=65535,u+=(c+=a*i)>>>16,u+=t*l+n*o+s*i+a*r,gt((h&=65535)<<16|(d&=65535),(u&=65535)<<16|(c&=65535),this.unsigned)},le.mul=le.multiply,le.divide=function(e){if(Dn(e)||(e=ks(e)),e.isZero())throw Error("division by zero");var t,n,s;if(Zn)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?gt((this.unsigned?Zn.div_u:Zn.div_s)(this.low,this.high,e.low,e.high),Zn.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?Kr:ts;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Kr;if(e.gt(this.shru(1)))return Zx;s=Kr}else{if(this.eq(En))return e.eq(Qo)||e.eq(up)?En:e.eq(En)?Qo:(t=this.shr(1).div(e).shl(1)).eq(ts)?e.isNegative()?Qo:up:(n=this.sub(e.mul(t)),s=t.add(n.div(e)));if(e.eq(En))return this.unsigned?Kr:ts;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=ts}for(n=this;n.gte(e);){t=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(t)/Math.LN2),r=a<=48?1:Wc(2,a-48),i=es(t),o=i.mul(e);o.isNegative()||o.gt(n);)o=(i=es(t-=r,this.unsigned)).mul(e);i.isZero()&&(i=Qo),s=s.add(i),n=n.sub(o)}return s},le.div=le.divide,le.modulo=function(e){return Dn(e)||(e=ks(e)),Zn?gt((this.unsigned?Zn.rem_u:Zn.rem_s)(this.low,this.high,e.low,e.high),Zn.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},le.mod=le.modulo,le.rem=le.modulo,le.not=function(){return gt(~this.low,~this.high,this.unsigned)},le.and=function(e){return Dn(e)||(e=ks(e)),gt(this.low&e.low,this.high&e.high,this.unsigned)},le.or=function(e){return Dn(e)||(e=ks(e)),gt(this.low|e.low,this.high|e.high,this.unsigned)},le.xor=function(e){return Dn(e)||(e=ks(e)),gt(this.low^e.low,this.high^e.high,this.unsigned)},le.shiftLeft=function(e){return Dn(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?gt(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):gt(0,this.low<<e-32,this.unsigned)},le.shl=le.shiftLeft,le.shiftRight=function(e){return Dn(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?gt(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):gt(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},le.shr=le.shiftRight,le.shiftRightUnsigned=function(e){if(Dn(e)&&(e=e.toInt()),0===(e&=63))return this;var t=this.high;return e<32?gt(this.low>>>e|t<<32-e,t>>>e,this.unsigned):gt(32===e?t:t>>>e-32,0,this.unsigned)},le.shru=le.shiftRightUnsigned,le.shr_u=le.shiftRightUnsigned,le.toSigned=function(){return this.unsigned?gt(this.low,this.high,!1):this},le.toUnsigned=function(){return this.unsigned?this:gt(this.low,this.high,!0)},le.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},le.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]},le.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]},mt.fromBytes=function(e,t,n){return n?mt.fromBytesLE(e,t):mt.fromBytesBE(e,t)},mt.fromBytesLE=function(e,t){return new mt(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},mt.fromBytesBE=function(e,t){return new mt(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};const ny=bf(Jx),k$=Gp({__proto__:null,default:ny},[Jx]),Hr=ny||k$;function Ud(e){return Hr.fromString(e,!0,16)}const sy=Ud("c3a5c85c97cb3127"),Ur=Ud("b492b66fbe98f273"),ln=Ud("9ae16a3b2f90404f");function cp(e){return e.xor(e.shru(47))}function ry(e,t,n){const s=e.slice(t,t+n);return Hr.fromBytes(Array.from(s),!0,!0)}function ut(e,t){return ry(e,t,8)}function eb(e,t){return ry(e,t,4)}function Vt(e,t){return 0===t?e:e.shru(t).or(e.shl(64-t))}function pr(e,t,n=Ud("9ddfea08eb382d69")){let s=e.xor(t).mul(n);s=s.xor(s.shru(47));let a=t.xor(s).mul(n);return a=a.xor(a.shru(47)),a=a.mul(n),a}function v$(e,t,n,s,a,r){a=a.add(e),r=Vt(r.add(a).add(s),21);const i=a;return a=(a=a.add(t)).add(n),r=r.add(Vt(a,44)),[a.add(s),r.add(i)]}function xc(e,t,n,s){return v$(ut(e,t),ut(e,t+8),ut(e,t+16),ut(e,t+24),n,s)}function C$(e,t=e.length){if(t>=8){const n=ln.add(2*t),s=ut(e,0).add(ln),a=ut(e,t-8);return pr(Vt(a,37).mul(n).add(s),Vt(s,25).add(a).mul(n),n)}if(t>=4){const n=ln.add(2*t);return pr(eb(e,0).shl(3).add(t),eb(e,t-4),n)}if(t>0){const n=e[0]+(e[t>>1]<<8),s=t+(e[t-1]<<2);return cp(ln.mul(n).xor(sy.mul(s))).mul(ln)}return ln}function $$(e,t=e.length){const n=ln.add(2*t),s=ut(e,0).mul(Ur),a=ut(e,8),r=ut(e,t-8).mul(n),i=ut(e,t-16).mul(ln);return pr(Vt(s.add(a),43).add(Vt(r,30)).add(i),s.add(Vt(a.add(ln),18)).add(r),n)}function S$(e,t=e.length){const n=ln.add(2*t),s=ut(e,0).mul(ln),a=ut(e,8),r=ut(e,t-8).mul(n),i=ut(e,t-16).mul(ln),o=Vt(s.add(a),43).add(Vt(r,30)).add(i),l=pr(o,s.add(Vt(a.add(ln),18)).add(r),n),u=ut(e,16).mul(n),c=ut(e,24),h=o.add(ut(e,t-32)).mul(n),d=l.add(ut(e,t-24)).mul(n);return pr(Vt(u.add(c),43).add(Vt(h,30)).add(d),u.add(Vt(c.add(s),18)).add(h),n)}function N$(e,t=e.length){const n=Hr.fromNumber(81,!0);if(t<=32)return t<=16?C$(e,t):$$(e,t);if(t<=64)return S$(e,t);let s=n,a=n.mul(Ur).add(113),r=cp(a.mul(ln).add(113)).mul(ln),i=[Hr.UZERO,Hr.UZERO],o=[Hr.UZERO,Hr.UZERO];s=s.mul(ln).add(ut(e,0));let l=0;const u=64*(t-1>>6),c=u+(t-1&63)-63;do{s=Vt(s.add(a).add(i[0]).add(ut(e,l+8)),37).mul(Ur),a=Vt(a.add(i[1]).add(ut(e,l+48)),42).mul(Ur),s=s.xor(o[1]),a=a.add(i[0]).add(ut(e,l+40)),r=Vt(r.add(o[0]),33).mul(Ur),i=xc(e,l,i[1].mul(Ur),s.add(o[0])),o=xc(e,l+32,r.add(o[1]),a.add(ut(e,l+16))),[r,s]=[s,r],l+=64}while(l!==u);const h=Ur.add(r.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=Vt(s.add(a).add(i[0]).add(ut(e,l+8)),37).mul(h),a=Vt(a.add(i[1]).add(ut(e,l+48)),42).mul(h),s=s.xor(o[1].mul(9)),a=a.add(i[0].mul(9).add(ut(e,l+40))),r=Vt(r.add(o[0]),33).mul(h),i=xc(e,l,i[1].mul(h),s.add(o[0])),o=xc(e,l+32,r.add(o[1]),a.add(ut(e,l+16))),[r,s]=[s,r],pr(pr(i[0],o[0],h).add(cp(a).mul(sy)).add(r),pr(i[1],o[1],h).add(s),h)}function Nr(e,t){return"string"===t?fr(e):No([e],t)}function T$(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}function No(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=ro(e)),H().getBool("DEBUG")&&n$(e,t),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 Ct(){return H().platform.now()}function E$(e,t){return H().platform.fetch(e,t)}function fr(e,t="utf-8"){return t=t||"utf-8",H().platform.encode(e,t)}function br(e,t="utf-8"){return t=t||"utf-8",H().platform.decode(e,t)}function Wn(e){return null!=H().platform.isTypedArray?H().platform.isTypedArray(e):Yx(e)}function ro(e,t=[],n=!1){if(null==t&&(t=[]),"boolean"==typeof e||"number"==typeof e||"string"==typeof e||Id(e)||null==e||Wn(e)&&n)t.push(e);else if(Array.isArray(e)||Wn(e))for(let s=0;s<e.length;++s)ro(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 a=0;a<=s;a++)ro(e[a],t,n)}return t}class _${constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new A$)}profileKernel(e,t,n){let s;const a=()=>{s=n()};let r;const i=Ct();if(this.backendTimer.timerAvailable())r=this.backendTimer.time(a);else{a();for(const e of s)e.dataSync();r=Promise.resolve({kernelMs:Ct()-i})}if(H().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t<s.length;t++){const n=s[t];n.data().then(t=>{R$(t,n.dtype,e)})}return{kernelName:e,outputs:s,inputs:t,timeMs:r.then(e=>e.kernelMs),extraInfo:r.then(e=>null!=e.getExtraProfileInfo?e.getExtraProfileInfo():"")}}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:s,inputs:a,extraInfo:r}=e;n.forEach(e=>{Promise.all([e.data(),s,r]).then(n=>{this.logger.logKernelProfile(t,e,n[0],n[1],a,n[2])})})}}function R$(e,t,n){if("float32"!==t)return!1;for(let t=0;t<e.length;t++){const s=e[t];if(isNaN(s)||!isFinite(s))return console.warn(`Found ${s} in the result of '${n}'`),!0}return!1}class A${logKernelProfile(e,t,n,s,a,r){const i="number"==typeof s?ea(`${s}ms`,9):s.error,o=ea(e,25),l=t.rank,u=t.size,c=ea(t.shape.toString(),14);let h="";for(const e in a){const n=a[e];if(null!=n){const s=n.shape||t.shape,a=s.length;h+=`${e}: ${a}D ${a>0?s:""} `}}console.log(`%c${o}\t%c${i}\t%c${l}D ${c}\t%c${u}\t%c${h}\t%c${r}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function D$(e,t,n){const s={},a={};for(let e=0;e<t.length;e++)s[t[e].id]=!0;for(let n=0;n<e.length;n++){const r=e[n],i=r.inputs;for(const e in i){const n=i[e];let o=!1;for(let e=0;e<t.length;e++)if(s[n.id]){r.outputs.forEach(e=>s[e.id]=!0),o=!0,a[r.id]=!0;break}if(o)break}}const r={};r[n.id]=!0;const i={};for(let t=e.length-1;t>=0;t--){const n=e[t],s=n.inputs;for(let e=0;e<n.outputs.length;e++)if(r[n.outputs[e].id]){for(const e in s)r[s[e].id]=!0,i[n.id]=!0;break}}const o=[];for(let t=0;t<e.length;t++){const n=e[t];if(a[n.id]&&i[n.id]){const e={};for(const t in n.inputs){const a=n.inputs[t];s[a.id]&&(e[t]=a)}const t=Object.assign({},n);t.inputs=e,t.outputs=n.outputs,o.push(t)}}return o}function F$(e,t,n,s){for(let a=t.length-1;a>=0;a--){const r=t[a],i=[];if(r.outputs.forEach(t=>{const n=e[t.id];null!=n?i.push(n):i.push(null)}),null==r.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${r.kernelName}.`);const o=r.gradient(i);for(const t in r.inputs){if(!(t in o))throw new Error(`Cannot backprop through input ${t}. Available gradients found: ${Object.keys(o)}.`);const a=n(()=>o[t]());if("float32"!==a.dtype)throw new Error(`Error in gradient for op ${r.kernelName}. The gradient of input ${t} must have 'float32' dtype, but has '${a.dtype}'`);const i=r.inputs[t];if(!Ye(a.shape,i.shape))throw new Error(`Error in gradient for op ${r.kernelName}. The gradient of input '${t}' has shape '${a.shape}', which does not match the shape of the input '${i.shape}'`);if(null==e[i.id])e[i.id]=a;else{const t=e[i.id];e[i.id]=s(t,a),t.dispose()}}}}const tb=20,ol=3,Mh=7;function M$(e,t,n,s){const a=me(t),r=O$(e,t,n,a),i=t.length,o=Mc(e,t,n,a,r),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 O$(e,t,n,s){const a=M(t),r=s[s.length-1],i=new Array(r).fill(0),o=t.length,l="complex64"===n?dl(e):e;if(o>1)for(let e=0;e<a/r;e++){const t=e*r;for(let e=0;e<r;e++)i[e]=Math.max(i[e],cl(l[t+e],0,n).length)}return i}function cl(e,t,n){let s;return s=Array.isArray(e)?`${parseFloat(e[0].toFixed(7))} + ${parseFloat(e[1].toFixed(7))}j`:Wl(e)?`'${e}'`:"bool"===n?oy(e):parseFloat(e.toFixed(7)).toString(),ea(s,t)}function oy(e){return 0===e?"false":"true"}function Mc(e,t,n,s,a,r=!0){const i="complex64"===n?2:1,o=t[0],l=t.length;if(0===l){if("complex64"===n){return[cl(dl(e)[0],0,n)]}return"bool"===n?[oy(e[0])]:[e[0].toString()]}if(1===l){if(o>20){const t=3*i;let s=Array.from(e.slice(0,t)),r=Array.from(e.slice((o-3)*i,o*i));return"complex64"===n&&(s=dl(s),r=dl(r)),["["+s.map((e,t)=>cl(e,a[t],n)).join(", ")+", ..., "+r.map((e,t)=>cl(e,a[o-3+t],n)).join(", ")+"]"]}return["["+("complex64"===n?dl(e):Array.from(e)).map((e,t)=>cl(e,a[t],n)).join(", ")+"]"]}const u=t.slice(1),c=s.slice(1),h=s[0]*i,d=[];if(o>20){for(let t=0;t<3;t++){const s=t*h,r=s+h;d.push(...Mc(e.slice(s,r),u,n,c,a,!1))}d.push("...");for(let t=o-3;t<o;t++){const s=t*h,r=s+h;d.push(...Mc(e.slice(s,r),u,n,c,a,t===o-1))}}else for(let t=0;t<o;t++){const s=t*h,r=s+h;d.push(...Mc(e.slice(s,r),u,n,c,a,t===o-1))}const p=2===l?",":"";d[0]="["+(o>0?d[0]+p:"");for(let e=1;e<d.length-1;e++)d[e]=" "+d[e]+p;let f=",\n";for(let e=2;e<l;e++)f+="\n";return d[d.length-1]=" "+d[d.length-1]+"]"+(r?"":f),d}function dl(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class Xt{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=M(e),null!=n){const e=n.length;v(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||Nt(t,this.size),this.strides=me(e)}set(e,...t){0===t.length&&(t=[0]),v(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 hs().makeTensor(this.values,this.shape,this.dtype)}}let hs=null,Xo=null;function L$(e){hs=e}function P$(e){Xo=e}class pt{constructor(e,t,n,s){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=M(e),this.strides=me(e),this.dataId=n,this.id=s,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return Xo.buffer(this.shape,this.dtype,e)}bufferSync(){return Xo.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return ms(this.shape,e,"complex64"===this.dtype)}arraySync(){return ms(this.shape,this.dataSync(),"complex64"===this.dtype)}async data(){this.throwIfDisposed();const e=hs().read(this.dataId);if("string"===this.dtype){const t=await e;try{return t.map(e=>br(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(),hs().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=hs().readSync(this.dataId);if("string"===this.dtype)try{return e.map(e=>br(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 hs().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),hs().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Xo.print(this,e)}clone(){return this.throwIfDisposed(),Xo.clone(this)}toString(e=!1){return M$(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Xo.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),hs().makeVariable(this,e,t,n)}}function q(){return Xp("Tensor",()=>pt)}Object.defineProperty(pt,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),q();class Vc extends pt{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(!Ye(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);hs().disposeTensor(this),this.dataId=e.dataId,hs().incRef(this,null)}dispose(){hs().disposeVariable(this),this.isDisposedInternal=!0}}var nb,dp,hp,pp,fp;Object.defineProperty(Vc,Symbol.hasInstance,{value:e=>e instanceof pt&&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"}(nb||(nb={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(dp||(dp={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(hp||(hp={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(pp||(pp={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(fp||(fp={}));const z$={float32:pp,int32:dp,bool:hp,complex64:fp};function _n(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return z$[e][t]}function yf(e){return _n(e,"int32")}function ay(e){return null!=e&&"object"==typeof e&&"texture"in e&&e.texture instanceof WebGLTexture}function iy(e){return"undefined"!=typeof GPUBuffer&&null!=e&&"object"==typeof e&&"buffer"in e&&e.buffer instanceof GPUBuffer}function Et(e,t){if(e.dtype===t.dtype)return[e,t];const n=_n(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function wf(e,t){return t.some(t=>t.id===e.id)}function xr(e){const t=[];return ly(e,t,new Set),t}function ly(e,t,n){if(null==e)return;if(e instanceof pt)return void t.push(e);if(!B$(e))return;const s=e;for(const e in s){const a=s[e];n.has(a)||(n.add(a),ly(a,t,n))}}function B$(e){return Array.isArray(e)||"object"==typeof e}function Oh(e){return null!=e.kernelName}class sb{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 da{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new sb}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?(Ln(`${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 _$(this.backendInstance),!0}setupRegisteredKernels(){Kg(this.backendName).forEach(e=>{null!=e.setupFunc&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){Kg(e).forEach(t=>{null!=t.disposeFunc&&t.disposeFunc(this.registry[e])})}initializeBackend(e){const t=this.registryFactory[e];if(null==t)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const n=t.factory();if(!n||n instanceof xd||"function"!=typeof n.then)return this.registry[e]=n,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,s=n.then(n=>!(t<this.pendingBackendInitId)&&(this.registry[e]=n,this.pendingBackendInit=null,!0)).catch(n=>(t<this.pendingBackendInitId||(this.pendingBackendInit=null,Ln(`Initialization of backend ${e} failed`),Ln(n.stack||n.message)),!1));return this.pendingBackendInit=s,{success:s,asyncInit:!0}}}catch(t){return Ln(`Initialization of backend ${e} failed`),Ln(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:a}=this.initializeBackend(n);if(a||s)return{name:n,asyncInit:a}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const n=this.state.tensorInfo.get(t),s=n.backend,a=this.readSync(t),r=s.refCount(t);s.disposeData(t,!0),n.backend=e,e.move(t,a,n.shape,n.dtype,r),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n,s=null;if(null==t){if("function"!=typeof e)throw new Error("Please provide a function to tidy()");t=e}else{if("string"!=typeof e&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof t)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");s=e}return this.scopedRun(()=>this.startScope(s),()=>this.endScope(n),()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n))}scopedRun(e,t,n){e();try{const e=n();return t(),e}catch(e){throw t(),e}}nextTensorId(){return da.nextTensorId++}nextVariableId(){return da.nextVariableId++}clone(e){const t=F.runKernel(Qa,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],e=>({x:()=>{const t={x:e},n={dtype:"float32"};return F.runKernel(Da,t,n)}}),[],{}),t}runKernel(e,t,n){if(null==this.backendName&&this.backend,null==qg(e,this.backendName))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const s=this.backend.numDataIds();let a=0;n.forEach(e=>{a+="complex64"===e.dtype?3:1});const r=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=s-t-a-r;if(i>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${i} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[];const s=this.isTapeOn(),a=this.state.numBytes,r=this.state.numTensors;let i,o;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const l=Oh(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(Oh(e)){const{kernelName:t,inputs:a,attrs:r}=e;null==this.backendName&&this.backend;const l=qg(t,this.backendName);v(null!=l,()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`),i=()=>{const e=this.backend.numDataIds();o=l.kernelFunc({inputs:a,attrs:r,backend:this.backend});const i=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,i);const u=i.map(e=>null!=e.rank?e:this.makeTensorFromTensorInfo(e));if(s){const e=this.getTensorsForGradient(t,a,u);n=this.saveTensorsForBackwardMode(e)}return u}}else{const{forwardFunc:t}=e,a=e=>{s&&(n=e.map(e=>this.keep(this.clone(e))))};i=()=>{const e=this.backend.numDataIds();o=this.tidy(()=>t(this.backend,a));const n=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,e,n),n}}const{inputs:u,attrs:c}=e,h=Oh(e)?null:e.backwardsFunc;let d;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(d=this.profiler.profileKernel(l,u,()=>i()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(d),t=d.outputs):t=i()}),s&&this.addTapeNode(l,u,t,h,n,c),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-a,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-r,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(u).map(e=>null!=u[e]?u[e].shape:null),outputShapes:t.map(e=>e.shape),kernelTimeMs:d.timeMs,extraInfo:d.extraInfo}),Array.isArray(o)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(e=>this.keep(this.clone(e)))}getTensorsForGradient(e,t,n){const s=jg(e);if(null!=s){const e=s.inputsToSave||[],a=s.outputsToSave||[];let r;s.saveAllInputs?(v(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),r=Object.keys(t).map(e=>t[e])):r=e.map(e=>t[e]);const i=n.filter((e,t)=>a[t]);return r.concat(i)}return[]}makeTensor(e,t,n,s){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",s=s||this.backend;let a=e;"string"===n&&Wl(e[0])&&(a=e.map(e=>fr(e)));const r=s.write(a,t,n),i=new pt(t,n,r,this.nextTensorId());if(this.trackTensor(i,s),"string"===n){const e=this.state.tensorInfo.get(r),t=r$(a);this.state.numBytes+=t-e.bytes,e.bytes=t}return i}makeTensorFromDataId(e,t,n,s){const a={dataId:e,shape:t,dtype:n=n||"float32"};return this.makeTensorFromTensorInfo(a,s)}makeTensorFromTensorInfo(e,t){const{dataId:n,shape:s,dtype:a}=e,r=new pt(s,a,n,this.nextTensorId());return this.trackTensor(r,t),r}makeVariable(e,t=!0,n,s){n=n||this.nextVariableId().toString(),null!=s&&s!==e.dtype&&(e=e.cast(s));const a=new Vc(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[a.name])throw new Error(`Variable with name ${a.name} was already registered`);return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a}trackTensor(e,t){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*ia(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 Vc||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*ia(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.activePro