/** * @license * Copyright 2023 Google LLC. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============================================================================= */ function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(n){if("default"!==n&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}}))})),e}class t{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class n{refCount(e){return r("refCount")}incRef(e){return r("incRef")}timerAvailable(){return!0}time(e){return r("time")}read(e){return r("read")}readSync(e){return r("readSync")}readToGPU(e,t){return r("readToGPU")}numDataIds(){return r("numDataIds")}disposeData(e,t){return r("disposeData")}write(e,t,n){return r("write")}move(e,t,n,s,o){return r("move")}createTensorFromGPUData(e,t,n){return r("createTensorFromGPUData")}memory(){return r("memory")}floatPrecision(){return r("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return r("dispose")}}function r(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function s(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,a(e,t,n)}function o(e,t,n){return Math.max(e,Math.min(t,n))}function a(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function i(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function l(e,t,n=""){i(d(e,t),(()=>n+` Shapes ${e} and ${t} must match`))}function u(e){i(null!=e,(()=>"The input to the tensor constructor must be a non-null value."))}function c(e){if(0===e.length)return 1;let t=e[0];for(let n=1;nt)):[].concat(e)).every((e=>e>=-n&&e`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`)),i(e.every((e=>f(e))),(()=>`All values in axis param must be integers but got axis ${e}`)),e.map((e=>e<0?n+e:e))}function m(e,t){const n=[],r=[],s=null!=t&&Array.isArray(t)&&0===t.length,o=null==t||s?null:g(t,e).sort();let a=0;for(let t=0;tt)&&1===e[t]&&(n.push(e[t]),r.push(t)),o[a]<=t&&a++}1!==e[t]&&(n.push(e[t]),r.push(t))}return{newShape:n,keptDims:r}}function b(e,t){return y(e,t)}function y(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else if("bool"===e)n=new Uint8Array(t);else{if("string"!==e)throw new Error(`Unknown data type ${e}`);n=new Array(t)}return n}function w(e,t){for(let n=0;nt+=e.length)),t}function E(e){return"string"==typeof e||e instanceof String}function S(e){return"boolean"==typeof e}function $(e){return"number"==typeof e}function A(e){return Array.isArray(e)?A(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":$(e)?"float32":E(e)?"string":S(e)?"bool":"float32"}function _(e){return!!(e&&e.constructor&&e.call&&e.apply)}function I(e,t){for(let n=t;n=0;--r)n[r]=n[r+1]*e[r+1];return n}function N(e,t,n,r=!1){const s=new Array;if(1===t.length){const o=t[0]*(r?2:1);for(let t=0;te*t))*(r?2:1);for(let t=0;te*t))*(n?2:1);if(0===r)return[];if(r!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return N(0,e,t,n)}function D(e,t){const n=R(e,t);for(let e=0;e{i(Number.isInteger(t)&&t>=0,(()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`))}))}function B(e){return e&&e.then&&"function"==typeof e.then}class C{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=P,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&(O().getBool("IS_TEST")||O().getBool("PROD")||console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${e}.`)),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},null!=this.urlFlags[e]){const t=this.urlFlags[e];O().getBool("IS_TEST")||O().getBool("PROD")||console.warn(`Setting feature override from URL ${e}: ${t}.`),this.set(e,t)}}async getAsync(e){return e in this.flags||(this.flags[e]=await this.evaluateFlag(e)),this.flags[e]}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(B(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getString(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(null==this.flagRegistry[e])throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,null!=this.flagRegistry[e].setHook&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(null==this.flagRegistry[e])throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if("undefined"==typeof this.global||"undefined"==typeof this.global.location||"undefined"==typeof this.global.location.search)return;const e=this.getQueryParams(this.global.location.search);if("tfjsflags"in e){e.tfjsflags.split(",").forEach((e=>{const[t,n]=e.split(":");this.urlFlags[t]=function(e,t){const n=t.toLowerCase();return"true"===n||"false"===n?"true"===n:""+ +n===n?+n:t}(0,n)}))}}}function P(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,((e,...n)=>(function(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}(t,n[0],n[1]),n.join("=")))),t}function O(){return z}let L,z=null;function U(){if(null==L){let e;if("undefined"!=typeof window)e=window;else if("undefined"!=typeof global)e=global;else if("undefined"!=typeof process)e=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");e=self}L=e}return L}function W(e,t){const n=function(){const e=U();return null==e._tfGlobals&&(e._tfGlobals=new Map),e._tfGlobals}();if(n.has(e))return n.get(e);{const r=t();return n.set(e,r),n.get(e)}}const G="Abs",K="Acos",q="Acosh",V="Add",H="AddN",j="All",J="Any",Z="ArgMax",Y="ArgMin",X="Asin",Q="Asinh",ee="Atan",te="Atanh",ne="Atan2",re="AvgPool",se="AvgPoolGrad",oe="AvgPool3D",ae="AvgPool3DGrad",ie="BatchMatMul",le="BatchToSpaceND",ue="Bincount",ce="BitwiseAnd",he="BroadcastTo",de="BroadcastArgs",fe="Cast",pe="Ceil",ge="ClipByValue",me="Complex",be="ComplexAbs",ye="Concat",we="Conv2D",ke="Conv2DBackpropFilter",ve="Conv2DBackpropInput",xe="Conv3D",Ee="Conv3DBackpropFilterV2",Se="Conv3DBackpropInputV2",$e="Cos",Ae="Cosh",_e="Cumprod",Ie="Cumsum",Me="CropAndResize",Ne="DenseBincount",Te="DepthToSpace",De="DepthwiseConv2dNative",Re="DepthwiseConv2dNativeBackpropFilter",Fe="DepthwiseConv2dNativeBackpropInput",Be="Diag",Ce="Dilation2D",Pe="Dilation2DBackpropInput",Oe="Dilation2DBackpropFilter",Le="Draw",ze="RealDiv",Ue="Einsum",We="Elu",Ge="EluGrad",Ke="Erf",qe="Equal",Ve="Exp",He="ExpandDims",je="Expm1",Je="FFT",Ze="Fill",Ye="FlipLeftRight",Xe="Floor",Qe="FloorDiv",et="FusedBatchNorm",tt="GatherV2",nt="GatherNd",rt="Greater",st="GreaterEqual",ot="Identity",at="IFFT",it="Imag",lt="IsFinite",ut="IsInf",ct="IsNan",ht="LeakyRelu",dt="Less",ft="LessEqual",pt="LinSpace",gt="Log",mt="Log1p",bt="LogicalAnd",yt="LogicalNot",wt="LogicalOr",kt="LogicalXor",vt="LogSoftmax",xt="LowerBound",Et="LRN",St="LRNGrad",$t="MatrixBandPart",At="Max",_t="Maximum",It="MaxPool",Mt="MaxPoolGrad",Nt="MaxPool3D",Tt="MaxPool3DGrad",Dt="MaxPoolWithArgmax",Rt="Mean",Ft="Min",Bt="Minimum",Ct="MirrorPad",Pt="Mod",Ot="Multinomial",Lt="Multiply",zt="Neg",Ut="NotEqual",Wt="NonMaxSuppressionV3",Gt="NonMaxSuppressionV4",Kt="NonMaxSuppressionV5",qt="OnesLike",Vt="OneHot",Ht="Pack",jt="PadV2",Jt="Pool",Zt="Pow",Yt="Prelu",Xt="Prod",Qt="RaggedGather",en="RaggedRange",tn="RaggedTensorToTensor",nn="Range",rn="Real",sn="Reciprocal",on="Relu",an="Reshape",ln="ResizeNearestNeighbor",un="ResizeNearestNeighborGrad",cn="ResizeBilinear",hn="ResizeBilinearGrad",dn="Relu6",fn="Reverse",pn="Round",gn="Rsqrt",mn="ScatterNd",bn="TensorScatterUpdate",yn="SearchSorted",wn="Select",kn="Selu",vn="Slice",xn="Sin",En="Sinh",Sn="Sign",$n="Sigmoid",An="Softplus",_n="Sqrt",In="Sum",Mn="SpaceToBatchND",Nn="SplitV",Tn="Softmax",Dn="SparseFillEmptyRows",Rn="SparseReshape",Fn="SparseSegmentMean",Bn="SparseSegmentSum",Cn="SparseToDense",Pn="SquaredDifference",On="Square",Ln="StaticRegexReplace",zn="StridedSlice",Un="StringNGrams",Wn="StringSplit",Gn="StringToHashBucketFast",Kn="Sub",qn="Tan",Vn="Tanh",Hn="Tile",jn="TopK",Jn="Transform",Zn="Transpose",Yn="Unique",Xn="Unpack",Qn="UnsortedSegmentSum",er="UpperBound",tr="ZerosLike",nr="Step",rr="FromPixels",sr="RotateWithOffset",or="_FusedMatMul",ar="FusedConv2D",ir="FusedDepthwiseConv2D";function lr(...e){O().getBool("IS_TEST")||O().getBool("PROD")||console.warn(...e)}const ur=W("kernelRegistry",(()=>new Map)),cr=W("gradRegistry",(()=>new Map));function hr(e,t){const n=wr(e,t);return ur.get(n)}function dr(e){return cr.get(e)}function fr(e){const t=ur.entries(),n=[];for(;;){const{done:r,value:s}=t.next();if(r)break;const[o,a]=s,[i]=o.split("_");i===e&&n.push(a)}return n}function pr(e){const{kernelName:t,backendName:n}=e,r=wr(t,n);ur.has(r)&&lr(`The kernel '${t}' for backend '${n}' is already registered`),ur.set(r,e)}function gr(e){const{kernelName:t}=e;cr.has(t)&&O().getBool("DEBUG")&&lr(`Overriding the gradient for '${t}'`),cr.set(t,e)}function mr(e,t){const n=wr(e,t);if(!ur.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);ur.delete(n)}function br(e){if(!cr.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);cr.delete(e)}function yr(e,t){fr(e).forEach((e=>{pr(Object.assign({},e,{backendName:t}))}))}function wr(e,t){return`${t}_${e}`}function kr(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}var vr="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function xr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Er=$r,Sr=null;try{Sr=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(e){}function $r(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function Ar(e){return!0===(e&&e.__isLong__)}$r.prototype.__isLong__,Object.defineProperty($r.prototype,"__isLong__",{value:!0}),$r.isLong=Ar;var _r={},Ir={};function Mr(e,t){var n,r,s;return t?(s=0<=(e>>>=0)&&e<256)&&(r=Ir[e])?r:(n=Tr(e,(0|e)<0?-1:0,!0),s&&(Ir[e]=n),n):(s=-128<=(e|=0)&&e<128)&&(r=_r[e])?r:(n=Tr(e,e<0?-1:0,!1),s&&(_r[e]=n),n)}function Nr(e,t){if(isNaN(e))return t?zr:Lr;if(t){if(e<0)return zr;if(e>=Cr)return qr}else{if(e<=-Pr)return Vr;if(e+1>=Pr)return Kr}return e<0?Nr(-e,t).neg():Tr(e%Br|0,e/Br|0,t)}function Tr(e,t,n){return new $r(e,t,n)}$r.fromInt=Mr,$r.fromNumber=Nr,$r.fromBits=Tr;var Dr=Math.pow;function Rr(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return Lr;if("number"==typeof t?(n=t,t=!1):t=!!t,(n=n||10)<2||360)throw Error("interior hyphen");if(0===r)return Rr(e.substring(1),t,n).neg();for(var s=Nr(Dr(n,8)),o=Lr,a=0;a>>0:this.low},Hr.toNumber=function(){return this.unsigned?(this.high>>>0)*Br+(this.low>>>0):this.high*Br+(this.low>>>0)},Hr.toString=function(e){if((e=e||10)<2||36>>0).toString(e);if((o=i).isZero())return l+a;for(;l.length<6;)l="0"+l;a=""+l+a}},Hr.getHighBits=function(){return this.high},Hr.getHighBitsUnsigned=function(){return this.high>>>0},Hr.getLowBits=function(){return this.low},Hr.getLowBitsUnsigned=function(){return this.low>>>0},Hr.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Vr)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<=0},Hr.isOdd=function(){return 1==(1&this.low)},Hr.isEven=function(){return 0==(1&this.low)},Hr.equals=function(e){return Ar(e)||(e=Fr(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},Hr.eq=Hr.equals,Hr.notEquals=function(e){return!this.eq(e)},Hr.neq=Hr.notEquals,Hr.ne=Hr.notEquals,Hr.lessThan=function(e){return this.comp(e)<0},Hr.lt=Hr.lessThan,Hr.lessThanOrEqual=function(e){return this.comp(e)<=0},Hr.lte=Hr.lessThanOrEqual,Hr.le=Hr.lessThanOrEqual,Hr.greaterThan=function(e){return this.comp(e)>0},Hr.gt=Hr.greaterThan,Hr.greaterThanOrEqual=function(e){return this.comp(e)>=0},Hr.gte=Hr.greaterThanOrEqual,Hr.ge=Hr.greaterThanOrEqual,Hr.compare=function(e){if(Ar(e)||(e=Fr(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},Hr.comp=Hr.compare,Hr.negate=function(){return!this.unsigned&&this.eq(Vr)?Vr:this.not().add(Ur)},Hr.neg=Hr.negate,Hr.add=function(e){Ar(e)||(e=Fr(e));var t=this.high>>>16,n=65535&this.high,r=this.low>>>16,s=65535&this.low,o=e.high>>>16,a=65535&e.high,i=e.low>>>16,l=0,u=0,c=0,h=0;return c+=(h+=s+(65535&e.low))>>>16,u+=(c+=r+i)>>>16,l+=(u+=n+a)>>>16,l+=t+o,Tr((c&=65535)<<16|(h&=65535),(l&=65535)<<16|(u&=65535),this.unsigned)},Hr.subtract=function(e){return Ar(e)||(e=Fr(e)),this.add(e.neg())},Hr.sub=Hr.subtract,Hr.multiply=function(e){if(this.isZero())return Lr;if(Ar(e)||(e=Fr(e)),Sr)return Tr(Sr.mul(this.low,this.high,e.low,e.high),Sr.get_high(),this.unsigned);if(e.isZero())return Lr;if(this.eq(Vr))return e.isOdd()?Vr:Lr;if(e.eq(Vr))return this.isOdd()?Vr:Lr;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(Or)&&e.lt(Or))return Nr(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,n=65535&this.high,r=this.low>>>16,s=65535&this.low,o=e.high>>>16,a=65535&e.high,i=e.low>>>16,l=65535&e.low,u=0,c=0,h=0,d=0;return h+=(d+=s*l)>>>16,c+=(h+=r*l)>>>16,h&=65535,c+=(h+=s*i)>>>16,u+=(c+=n*l)>>>16,c&=65535,u+=(c+=r*i)>>>16,c&=65535,u+=(c+=s*a)>>>16,u+=t*l+n*i+r*a+s*o,Tr((h&=65535)<<16|(d&=65535),(u&=65535)<<16|(c&=65535),this.unsigned)},Hr.mul=Hr.multiply,Hr.divide=function(e){if(Ar(e)||(e=Fr(e)),e.isZero())throw Error("division by zero");var t,n,r;if(Sr)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?Tr((this.unsigned?Sr.div_u:Sr.div_s)(this.low,this.high,e.low,e.high),Sr.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?zr:Lr;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return zr;if(e.gt(this.shru(1)))return Wr;r=zr}else{if(this.eq(Vr))return e.eq(Ur)||e.eq(Gr)?Vr:e.eq(Vr)?Ur:(t=this.shr(1).div(e).shl(1)).eq(Lr)?e.isNegative()?Ur:Gr:(n=this.sub(e.mul(t)),r=t.add(n.div(e)));if(e.eq(Vr))return this.unsigned?zr:Lr;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();r=Lr}for(n=this;n.gte(e);){t=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));for(var s=Math.ceil(Math.log(t)/Math.LN2),o=s<=48?1:Dr(2,s-48),a=Nr(t),i=a.mul(e);i.isNegative()||i.gt(n);)i=(a=Nr(t-=o,this.unsigned)).mul(e);a.isZero()&&(a=Ur),r=r.add(a),n=n.sub(i)}return r},Hr.div=Hr.divide,Hr.modulo=function(e){return Ar(e)||(e=Fr(e)),Sr?Tr((this.unsigned?Sr.rem_u:Sr.rem_s)(this.low,this.high,e.low,e.high),Sr.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},Hr.mod=Hr.modulo,Hr.rem=Hr.modulo,Hr.not=function(){return Tr(~this.low,~this.high,this.unsigned)},Hr.and=function(e){return Ar(e)||(e=Fr(e)),Tr(this.low&e.low,this.high&e.high,this.unsigned)},Hr.or=function(e){return Ar(e)||(e=Fr(e)),Tr(this.low|e.low,this.high|e.high,this.unsigned)},Hr.xor=function(e){return Ar(e)||(e=Fr(e)),Tr(this.low^e.low,this.high^e.high,this.unsigned)},Hr.shiftLeft=function(e){return Ar(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?Tr(this.low<>>32-e,this.unsigned):Tr(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):Tr(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},Hr.shr=Hr.shiftRight,Hr.shiftRightUnsigned=function(e){if(Ar(e)&&(e=e.toInt()),0===(e&=63))return this;var t=this.high;return e<32?Tr(this.low>>>e|t<<32-e,t>>>e,this.unsigned):Tr(32===e?t:t>>>e-32,0,this.unsigned)},Hr.shru=Hr.shiftRightUnsigned,Hr.shr_u=Hr.shiftRightUnsigned,Hr.toSigned=function(){return this.unsigned?Tr(this.low,this.high,!1):this},Hr.toUnsigned=function(){return this.unsigned?this:Tr(this.low,this.high,!0)},Hr.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},Hr.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},Hr.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},$r.fromBytes=function(e,t,n){return n?$r.fromBytesLE(e,t):$r.fromBytesBE(e,t)},$r.fromBytesLE=function(e,t){return new $r(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},$r.fromBytesBE=function(e,t){return new $r(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var jr=xr(Er);const Jr=jr||e({__proto__:null,default:jr},[Er]);function Zr(e){return Jr.fromString(e,!0,16)}const Yr=Zr("c3a5c85c97cb3127"),Xr=Zr("b492b66fbe98f273"),Qr=Zr("9ae16a3b2f90404f");function es(e){return e.xor(e.shru(47))}function ts(e,t,n){const r=e.slice(t,t+n);return Jr.fromBytes(Array.from(r),!0,!0)}function ns(e,t){return ts(e,t,8)}function rs(e,t){return ts(e,t,4)}function ss(e,t){return 0===t?e:e.shru(t).or(e.shl(64-t))}function os(e,t,n=Zr("9ddfea08eb382d69")){let r=e.xor(t).mul(n);r=r.xor(r.shru(47));let s=t.xor(r).mul(n);return s=s.xor(s.shru(47)),s=s.mul(n),s}function as(e,t,n,r){return function(e,t,n,r,s,o){s=s.add(e),o=ss(o.add(s).add(r),21);const a=s;return s=(s=s.add(t)).add(n),o=o.add(ss(s,44)),[s.add(r),o.add(a)]}(ns(e,t),ns(e,t+8),ns(e,t+16),ns(e,t+24),n,r)}function is(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=ds(e)),O().getBool("DEBUG")&&w(e,t),function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t))return e;if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t){const t=new Uint8Array(e.length);for(let n=0;n=8){const n=Qr.add(2*t),r=ns(e,0).add(Qr),s=ns(e,t-8);return os(ss(s,37).mul(n).add(r),ss(r,25).add(s).mul(n),n)}if(t>=4){const n=Qr.add(2*t);return os(rs(e,0).shl(3).add(t),rs(e,t-4),n)}if(t>0){const n=e[0]+(e[t>>1]<<8),r=t+(e[t-1]<<2);return es(Qr.mul(n).xor(Yr.mul(r))).mul(Qr)}return Qr}(e,t):function(e,t=e.length){const n=Qr.add(2*t),r=ns(e,0).mul(Xr),s=ns(e,8),o=ns(e,t-8).mul(n),a=ns(e,t-16).mul(Qr);return os(ss(r.add(s),43).add(ss(o,30)).add(a),r.add(ss(s.add(Qr),18)).add(o),n)}(e,t);if(t<=64)return function(e,t=e.length){const n=Qr.add(2*t),r=ns(e,0).mul(Qr),s=ns(e,8),o=ns(e,t-8).mul(n),a=ns(e,t-16).mul(Qr),i=ss(r.add(s),43).add(ss(o,30)).add(a),l=os(i,r.add(ss(s.add(Qr),18)).add(o),n),u=ns(e,16).mul(n),c=ns(e,24),h=i.add(ns(e,t-32)).mul(n),d=l.add(ns(e,t-24)).mul(n);return os(ss(u.add(c),43).add(ss(h,30)).add(d),u.add(ss(c.add(r),18)).add(h),n)}(e,t);let r=n,s=n.mul(Xr).add(113),o=es(s.mul(Qr).add(113)).mul(Qr),a=[Jr.UZERO,Jr.UZERO],i=[Jr.UZERO,Jr.UZERO];r=r.mul(Qr).add(ns(e,0));let l=0;const u=64*(t-1>>6),c=u+(t-1&63)-63;do{r=ss(r.add(s).add(a[0]).add(ns(e,l+8)),37).mul(Xr),s=ss(s.add(a[1]).add(ns(e,l+48)),42).mul(Xr),r=r.xor(i[1]),s=s.add(a[0]).add(ns(e,l+40)),o=ss(o.add(i[0]),33).mul(Xr),a=as(e,l,a[1].mul(Xr),r.add(i[0])),i=as(e,l+32,o.add(i[1]),s.add(ns(e,l+16))),[o,r]=[r,o],l+=64}while(l!==u);const h=Xr.add(o.and(255).shl(1));return l=c,i[0]=i[0].add(t-1&63),a[0]=a[0].add(i[0]),i[0]=i[0].add(a[0]),r=ss(r.add(s).add(a[0]).add(ns(e,l+8)),37).mul(h),s=ss(s.add(a[1]).add(ns(e,l+48)),42).mul(h),r=r.xor(i[1].mul(9)),s=s.add(a[0].mul(9).add(ns(e,l+40))),o=ss(o.add(i[0]),33).mul(h),a=as(e,l,a[1].mul(h),r.add(i[0])),i=as(e,l+32,o.add(i[1]),s.add(ns(e,l+16))),[o,r]=[r,o],os(os(a[0],i[0],h).add(es(s).mul(Yr)).add(o),os(a[1],i[1],h).add(r),h)},flatten:ds,getArrayFromDType:y,getTypedArrayFromDType:b,hasEncodingLoss:function(e,t){return"complex64"!==t&&(("float32"!==t||"complex64"===e)&&(("int32"!==t||"float32"===e||"complex64"===e)&&("bool"!==t||"bool"!==e)))},hexToLong:Zr,indexToLoc:function(e,t,n){if(0===t)return[];if(1===t)return[e];const r=new Array(t);for(let t=0;t=0)n*=e[t];else if(-1===e[t]){if(-1!==r)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${r} and dim ${t}`);r=t}else if(e[t]<0)throw Error(`Shapes can not be < 0. Found ${e[t]} at dim ${t}`);if(-1===r){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(0===n)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!=0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);const s=e.slice();return s[r]=t/n,s},isBoolean:S,isFunction:_,isInt:f,isNumber:$,isPromise:B,isScalarShape:function(e){return 0===e.length},isString:E,isTypedArray:hs,isValidDtype:k,locToIndex:function(e,t,n){if(0===t)return 0;if(1===t)return e[0];let r=e[e.length-1];for(let t=0;te*t),1);if(null==t||"float32"===t)return T(e,new Float32Array(n));if("int32"===t)return T(e,new Int32Array(n));if("bool"===t)return T(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)},makeZerosTypedArray:R,nearestDivisor:I,nearestLargerEven:function(e){return e%2==0?e:e+1},now:ls,parseAxisParam:g,randUniform:function(e,t){const n=Math.random();return t*n+(1-n)*e},repeatedTry:function(e,t=(e=>0),n,r){return new Promise(((s,o)=>{let a=0;const i=()=>{if(e())return void s();a++;const l=t(a);null!=n&&a>=n?o():null!=r?r(i,l):setTimeout(i,l)};i()}))},rightPad:p,shuffle:s,shuffleCombo:function(e,t){if(e.length!==t.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${e.length}Second array length was ${t.length}`);let n=e.length,r=0;for(;n>0;)r=Math.random()*n|0,n--,a(e,n,r),a(t,n,r)},sizeFromShape:c,sizeToSquarishShape:function(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]},squeezeShape:m,sum:function(e){let t=0;for(let n=0;n{r=n()};let o;const a=ls();if(this.backendTimer.timerAvailable())o=this.backendTimer.time(s);else{s();for(const e of r)e.dataSync();o=Promise.resolve({kernelMs:ls()-a})}if(O().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t{gs(t,n.dtype,e)}))}return{kernelName:e,outputs:r,inputs:t,timeMs:o.then((e=>e.kernelMs)),extraInfo:o.then((e=>null!=e.getExtraProfileInfo?e.getExtraProfileInfo():""))}}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:r,inputs:s,extraInfo:o}=e;n.forEach((e=>{Promise.all([e.data(),r,o]).then((n=>{this.logger.logKernelProfile(t,e,n[0],n[1],s,n[2])}))}))}}function gs(e,t,n){if("float32"!==t)return!1;for(let t=0;t0?r:""} `}}console.log(`%c${i}\t%c${a}\t%c${l}D ${c}\t%c${u}\t%c${h}\t%c${o}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function bs(e,t,n,r){const s=M(t),o=function(e,t,n,r){const s=c(t),o=r[r.length-1],a=new Array(o).fill(0),i=t.length,l="complex64"===n?vs(e):e;if(i>1)for(let e=0;e" "+e)).join("\n")),l.join("\n")}function ys(e,t,n){let r;return r=Array.isArray(e)?`${parseFloat(e[0].toFixed(7))} + ${parseFloat(e[1].toFixed(7))}j`:E(e)?`'${e}'`:"bool"===n?ws(e):parseFloat(e.toFixed(7)).toString(),p(r,t)}function ws(e){return 0===e?"false":"true"}function ks(e,t,n,r,s,o=!0){const a="complex64"===n?2:1,i=t[0],l=t.length;if(0===l){if("complex64"===n){return[ys(vs(e)[0],0,n)]}return"bool"===n?[ws(e[0])]:[e[0].toString()]}if(1===l){if(i>20){const t=3*a;let r=Array.from(e.slice(0,t)),o=Array.from(e.slice((i-3)*a,i*a));return"complex64"===n&&(r=vs(r),o=vs(o)),["["+r.map(((e,t)=>ys(e,s[t],n))).join(", ")+", ..., "+o.map(((e,t)=>ys(e,s[i-3+t],n))).join(", ")+"]"]}return["["+("complex64"===n?vs(e):Array.from(e)).map(((e,t)=>ys(e,s[t],n))).join(", ")+"]"]}const u=t.slice(1),c=r.slice(1),h=r[0]*a,d=[];if(i>20){for(let t=0;t<3;t++){const r=t*h,o=r+h;d.push(...ks(e.slice(r,o),u,n,c,s,!1))}d.push("...");for(let t=i-3;t0?d[0]+f:"");for(let e=1;e`Length of values '${e}' does not match the size inferred by the shape '${this.size}'.`))}if("complex64"===t)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||y(t,this.size),this.strides=M(e)}set(e,...t){0===t.length&&(t=[0]),i(t.length===this.rank,(()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`));const n=this.locToIndex(t);this.values[n]=e}get(...e){0===e.length&&(e=[0]);let t=0;for(const n of e){if(n<0||n>=this.shape[t]){const t=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(t)}t++}let n=e[e.length-1];for(let t=0;tcs(e)))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataToGPU(e){return this.throwIfDisposed(),Es().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=Es().readSync(this.dataId);if("string"===this.dtype)try{return e.map((e=>cs(e)))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await Es().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),Es().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Ss.print(this,e)}clone(){return this.throwIfDisposed(),Ss.clone(this)}toString(e=!1){return bs(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Ss.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Es().makeVariable(this,e,t,n)}}function As(){return W("Tensor",(()=>$s))}Object.defineProperty($s,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),As();class _s extends $s{constructor(e,t,n,r){super(e.shape,e.dtype,e.dataId,r),this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!d(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Es().disposeTensor(this),this.dataId=e.dataId,Es().incRef(this,null)}dispose(){Es().disposeVariable(this),this.isDisposedInternal=!0}}var Is,Ms,Ns,Ts,Ds;Object.defineProperty(_s,Symbol.hasInstance,{value:e=>e instanceof $s&&null!=e.assign&&e.assign instanceof Function}),function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"}(Is||(Is={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(Ms||(Ms={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(Ns||(Ns={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(Ts||(Ts={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(Ds||(Ds={}));const Rs={float32:Ts,int32:Ms,bool:Ns,complex64:Ds};function Fs(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return Rs[e][t]}function Bs(e){return Fs(e,"int32")}function Cs(e){return null!=e&&"object"==typeof e&&"texture"in e&&e.texture instanceof WebGLTexture}function Ps(e){return"undefined"!=typeof GPUBuffer&&null!=e&&"object"==typeof e&&"buffer"in e&&e.buffer instanceof GPUBuffer}function Os(e,t){if(e.dtype===t.dtype)return[e,t];const n=Fs(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function Ls(e,t){i(e.dtype===t.dtype,(()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`))}function zs(e){const t=[];return Us(e,t,new Set),t}function Us(e,t,n){if(null==e)return;if(e instanceof $s)return void t.push(e);if(r=e,!Array.isArray(r)&&"object"!=typeof r)return;var r;const s=e;for(const e in s){const r=s[e];n.has(r)||(n.add(r),Us(r,t,n))}}var Ws={__proto__:null,assertTypesMatch:Ls,getTensorsInContainer:zs,isTensorInList:function(e,t){return t.some((t=>t.id===e.id))},makeTypesMatch:Os};function Gs(e){return null!=e.kernelName}class Ks{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null,get kernelNames(){return Array.from(new Set(this.kernels.map((e=>e.name))))}}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class qs{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Ks}async ready(){if(null!=this.pendingBackendInit)return this.pendingBackendInit.then((()=>{}));if(null!=this.backendInstance)return;const e=this.getSortedBackends();for(let t=0;t{null!=e.setupFunc&&e.setupFunc(this.backendInstance)}))}disposeRegisteredKernels(e){fr(e).forEach((t=>{null!=t.disposeFunc&&t.disposeFunc(this.registry[e])}))}initializeBackend(e){const t=this.registryFactory[e];if(null==t)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const r=t.factory();if(!r||r instanceof n||"function"!=typeof r.then)return this.registry[e]=r,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,n=r.then((n=>!(t(tthis.registryFactory[t].priority-this.registryFactory[e].priority))}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;tthis.startScope(r)),(()=>this.endScope(n)),(()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n)))}scopedRun(e,t,n){e();try{const e=n();return t(),e}catch(e){throw t(),e}}nextTensorId(){return qs.nextTensorId++}nextVariableId(){return qs.nextVariableId++}clone(e){const t=Hs.runKernel("Identity",{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e},n={dtype:"float32"};return Hs.runKernel("Cast",t,n)}})),[],{}),t}runKernel(e,t,n){null==this.backendName&&this.backend;if(!(null!=hr(e,this.backendName)))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const r=this.backend.numDataIds();let s=0;n.forEach((e=>{s+="complex64"===e.dtype?3:1}));const o=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],a=r-t-s-o;if(a>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${a} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[];const r=this.isTapeOn(),s=this.state.numBytes,o=this.state.numTensors;let a,l;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const u=Gs(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(Gs(e)){const{kernelName:t,inputs:s,attrs:o}=e;null==this.backendName&&this.backend;const u=hr(t,this.backendName);i(null!=u,(()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`)),a=()=>{const e=this.backend.numDataIds();l=u.kernelFunc({inputs:s,attrs:o,backend:this.backend});const a=Array.isArray(l)?l:[l];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,a);const i=a.map((e=>null!=e.rank?e:this.makeTensorFromTensorInfo(e)));if(r){const e=this.getTensorsForGradient(t,s,i);n=this.saveTensorsForBackwardMode(e)}return i}}else{const{forwardFunc:t}=e,s=e=>{r&&(n=e.map((e=>this.keep(this.clone(e)))))};a=()=>{const e=this.backend.numDataIds();l=this.tidy((()=>t(this.backend,s)));const n=Array.isArray(l)?l:[l];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(u,e,n),n}}const{inputs:c,attrs:h}=e,d=Gs(e)?null:e.backwardsFunc;let f;return this.scopedRun((()=>this.state.kernelDepth++),(()=>this.state.kernelDepth--),(()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(f=this.profiler.profileKernel(u,c,(()=>a())),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(f),t=f.outputs):t=a()})),r&&this.addTapeNode(u,c,t,d,n,h),this.state.profiling&&this.state.activeProfile.kernels.push({name:u,bytesAdded:this.state.numBytes-s,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-o,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(c).map((e=>null!=c[e]?c[e].shape:null)),outputShapes:t.map((e=>e.shape)),kernelTimeMs:f.timeMs,extraInfo:f.extraInfo}),Array.isArray(l)?t:t[0]}saveTensorsForBackwardMode(e){const t=e.map((e=>this.keep(this.clone(e))));return t}getTensorsForGradient(e,t,n){const r=dr(e);if(null!=r){const e=r.inputsToSave||[],s=r.outputsToSave||[];let o;r.saveAllInputs?(i(Array.isArray(t),(()=>"saveAllInputs is true, expected inputs to be an array.")),o=Object.keys(t).map((e=>t[e]))):o=e.map((e=>t[e]));const a=n.filter(((e,t)=>s[t]));return o.concat(a)}return[]}makeTensor(e,t,n,r){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;let s=e;"string"===n&&E(e[0])&&(s=e.map((e=>us(e))));const o=r.write(s,t,n),a=new $s(t,n,o,this.nextTensorId());if(this.trackTensor(a,r),"string"===n){const e=this.state.tensorInfo.get(o),t=x(s);this.state.numBytes+=t-e.bytes,e.bytes=t}return a}makeTensorFromDataId(e,t,n,r){const s={dataId:e,shape:t,dtype:n=n||"float32"};return this.makeTensorFromTensorInfo(s,r)}makeTensorFromTensorInfo(e,t){const{dataId:n,shape:r,dtype:s}=e,o=new $s(r,s,n,this.nextTensorId());return this.trackTensor(o,t),o}makeVariable(e,t=!0,n,r){n=n||this.nextVariableId().toString(),null!=r&&r!==e.dtype&&(e=e.cast(r));const s=new _s(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[s.name])throw new Error(`Variable with name ${s.name} was already registered`);return this.state.registeredVariables[s.name]=s,this.incRef(s,this.backend),s}trackTensor(e,t){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*v(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof _s||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;const t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,"string"===e.dtype&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),"complex64"!==e.dtype&&"string"!==e.dtype){const t=e.size*v(e.dtype);this.state.numBytes-=t}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),null!=this.state.registeredVariables[e.name]&&delete this.state.registeredVariables[e.name]}memory(){const e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,null==e.reasons&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map((e=>e.totalBytesSnapshot))),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const e of this.state.activeProfile.kernels)e.kernelTimeMs=await e.kernelTimeMs,e.extraInfo=await e.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&0===this.state.kernelDepth}addTapeNode(e,t,n,r,s,o){const a={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:s},i=dr(e);null!=i&&(r=i.gradFunc),null!=r&&(a.gradient=e=>(e=e.map(((e,t)=>{if(null==e){const e=n[t],r=R(e.size,e.dtype);return this.makeTensor(r,e.shape,e.dtype)}return e})),r(e.length>1?e:e[0],s,o))),this.state.activeTape.push(a)}keep(e){return e.kept=!0,e}startTape(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=zs(e),n=new Set(t.map((e=>e.id)));for(let e=0;e{e.kept||e.scopeId!==r.id||this.track(e)}))}gradients(e,t,n,r=!1){if(i(t.length>0,(()=>"gradients() received an empty list of xs.")),null!=n&&"float32"!==n.dtype)throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);const s=this.scopedRun((()=>this.startTape()),(()=>this.endTape()),(()=>this.tidy("forward",e)));i(s instanceof $s,(()=>"The result y returned by f() must be a tensor."));const o=function(e,t,n){const r={},s={};for(let e=0;er[e.id]=!0)),i=!0,s[o.id]=!0;break}if(i)break}}const o={};o[n.id]=!0;const a={};for(let t=e.length-1;t>=0;t--){const n=e[t],r=n.inputs;for(let e=0;e0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",(()=>{const e={};e[s.id]=null==n?function(e){const t=D(c(e),"float32");return Hs.makeTensor(t,e,"float32")}(s.shape):n,function(e,t,n,r){for(let s=t.length-1;s>=0;s--){const o=t[s],a=[];if(o.outputs.forEach((t=>{const n=e[t.id];null!=n?a.push(n):a.push(null)})),null==o.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${o.kernelName}.`);const i=o.gradient(a);for(const t in o.inputs){if(!(t in i))throw new Error(`Cannot backprop through input ${t}. Available gradients found: ${Object.keys(i)}.`);const s=n((()=>i[t]()));if("float32"!==s.dtype)throw new Error(`Error in gradient for op ${o.kernelName}. The gradient of input ${t} must have 'float32' dtype, but has '${s.dtype}'`);const a=o.inputs[t];if(!d(s.shape,a.shape))throw new Error(`Error in gradient for op ${o.kernelName}. The gradient of input '${t}' has shape '${s.shape}', which does not match the shape of the input '${a.shape}'`);if(null==e[a.id])e[a.id]=s;else{const t=e[a.id];e[a.id]=r(t,s),t.dispose()}}}}(e,o,(e=>this.tidy(e)),js);const r=t.map((t=>e[t.id]));return 0===this.state.gradientDepth&&(this.state.activeTape.forEach((e=>{for(const t of e.saved)t.dispose()})),this.state.activeTape=null),{value:s,grads:r}}))}customGrad(e){return i(_(e),(()=>"The f passed in customGrad(f) must be a function.")),(...t)=>{let n;i(t.every((e=>e instanceof $s)),(()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors"));const r={};t.forEach(((e,t)=>{r[t]=e}));return this.runKernelFunc({forwardFunc:(r,s)=>(n=e(...t,s),i(n.value instanceof $s,(()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor")),i(_(n.gradFunc),(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function.")),n.value),backwardsFunc:(e,r)=>{const s=n.gradFunc(e,r),o=Array.isArray(s)?s:[s];i(o.length===t.length,(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...).")),i(o.every((e=>e instanceof $s)),(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."));const a={};return o.forEach(((e,t)=>{a[t]=()=>e})),a},inputs:r})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}readToGPU(e,t){return this.state.tensorInfo.get(e).backend.readToGPU(e,t)}async time(e){const t=ls(),n=await this.backend.time(e);return n.wallMs=ls()-t,n}track(e){return null!=this.state.activeScope&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new Ks;for(const e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}function Vs(){const e=U();if(null==e._tfengine){const t=new C(e);e._tfengine=new qs(t)}var t;return t=e._tfengine.ENV,z=t,Es=()=>e._tfengine,e._tfengine}qs.nextTensorId=0,qs.nextVariableId=0;const Hs=Vs();function js(e,t){const n={a:e,b:t};return Hs.runKernel("Add",n)}let Js;function Zs(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}var Ys={__proto__:null,isBrowser:Zs,isMobile:function(e){if(void 0!==Js)return Js;if(e||"undefined"!=typeof navigator&&null!=navigator){if(e||(e=navigator),"ReactNative"===e.product)return!0;const t=e.userAgent||e.vendor||("undefined"!=typeof window?window.opera:"");if(!t){const t=e;return t.userAgentData&&t.userAgentData.mobile}return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))}return!1},mockIsMobile:function(e){Js=e}};const Xs=O();function Qs(e,t){let n=e;if(hs(e))return"string"===t?[]:[e.length];if(Cs(e)){const t=e.channels||"RGBA";return[e.height,e.width*t.length]}if(Ps(e))return[e.buffer.size/(null==t?4:v(t))];if(!Array.isArray(e))return[];const r=[];for(;Array.isArray(n)||hs(n)&&"string"!==t;)r.push(n.length),n=n[0];return Array.isArray(e)&&O().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&eo(e,r,[]),r}function eo(e,t,n){if(n=n||[],!Array.isArray(e)&&!hs(e))return void i(0===t.length,(()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`));i(t.length>0,(()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`)),i(e.length===t[0],(()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`));const r=t.slice(1);for(let t=0;t=0&&(s=r),to(r,s,t,n),null==e||!hs(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e){const r=null==e?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${r}'`)}const o=Qs(e,s);hs(e)||Array.isArray(e)||(e=[e]);const a="string"!==s?is(e,s):ds(e,[],!0);return Hs.makeTensor(a,o,s)}function ro(e,t,n,r="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map(((e,s)=>no(e,`${t}[${s}]`,n,r)))}Xs.registerFlag("DEBUG",(()=>!1),(e=>{e&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")})),Xs.registerFlag("IS_BROWSER",(()=>Zs())),Xs.registerFlag("IS_NODE",(()=>"undefined"!=typeof process&&"undefined"!=typeof process.versions&&"undefined"!=typeof process.versions.node)),Xs.registerFlag("IS_CHROME",(()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor))),Xs.registerFlag("IS_SAFARI",(()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor))),Xs.registerFlag("PROD",(()=>!1)),Xs.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(()=>Xs.getBool("DEBUG"))),Xs.registerFlag("DEPRECATION_WARNINGS_ENABLED",(()=>!0)),Xs.registerFlag("IS_TEST",(()=>!1)),Xs.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",(()=>Xs.getBool("DEBUG"))),Xs.registerFlag("WRAP_TO_IMAGEBITMAP",(()=>!1)),Xs.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",(()=>!1)),Xs.registerFlag("USE_SETTIMEOUTCUSTOM",(()=>!1));const so="__op";function oo(e){const t=Object.keys(e);if(1!==t.length)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0];const r=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n+="__op";const s=(...e)=>{Hs.startScope(n);try{const t=r(...e);return B(t)&&console.error("Cannot return a Promise inside of tidy."),Hs.endScope(t),t}catch(e){throw Hs.endScope(null),e}};return Object.defineProperty(s,"name",{value:n,configurable:!0}),s}const ao=oo({complex_:function(e,t){const n=no(e,"real","complex"),r=no(t,"imag","complex");l(n.shape,r.shape,`real and imag shapes, ${n.shape} and ${r.shape}, must match in call to tf.complex().`);const s={real:n,imag:r};return Hs.runKernel("Complex",s)}});function io(e,t,n,r){if(null==r)r=A(e);else if("complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(Ps(e)||Cs(e)){if("float32"!==r&&"int32"!==r)throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${r}.`);return Hs.backend.createTensorFromGPUData(e,t||n,r)}if(!hs(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=t){F(t);const e=c(t),r=c(n);i(e===r,(()=>`Based on the provided shape, [${t}], the tensor should have ${e} values but has ${r}`));for(let e=0;e`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `))}}return hs(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==r?is(e,r):ds(e,[],!0),Hs.makeTensor(e,t,r)}function lo(e,t,n){return io(e,t,Qs(e,n),n)}const uo={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};class co{static join(e){return new co(e).slice()}constructor(e){if(this.shards=[],this.previousShardIndex=0,null==e)return;if(e instanceof Array||(e=[e]),0===(e=e.map((e=>hs(e)?e.buffer:e))).length)return;this.bufferUniformSize=e[0].byteLength;let t=0;for(let n=0;n=this.byteLength)return-1;if(null!=this.bufferUniformSize)return this.previousShardIndex=Math.floor(e/this.bufferUniformSize),this.previousShardIndex;function t(t){return e=t.end?1:0}if(0===t(this.shards[this.previousShardIndex]))return this.previousShardIndex;const n=function(e,t){let n=0,r=e.length;for(;n<=r;){const s=Math.floor((r-n)/2)+n,o=t(e[s]);if(0===o)return s;o<0?r=s:n=s+1}return-1}(this.shards,t);return-1===n?-1:(this.previousShardIndex=n,this.previousShardIndex)}}function ho(){O().set("PROD",!0)}function fo(){O().set("DEBUG",!0)}function po(){O().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function go(e){O().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function mo(){Hs.disposeVariables()}function bo(){return Hs}function yo(){return Hs.memory()}function wo(e){return Hs.profile(e)}function ko(e,t){return Hs.tidy(e,t)}function vo(e){zs(e).forEach((e=>e.dispose()))}function xo(e){return Hs.keep(e)}function Eo(e){return Hs.time(e)}function So(e){return Hs.setBackend(e)}function $o(){return Hs.ready()}function Ao(){return Hs.backendName}function _o(e){Hs.removeBackend(e)}function Io(e){return Hs.findBackend(e)}function Mo(e){return Hs.findBackendFactory(e)}function No(e,t,n=1){return Hs.registerBackend(e,t,n)}function To(){return Hs.backend}function Do(e,t){O().setPlatform(e,t)}function Ro(e,t){const n=new co(e),r={};let s=0;for(const e of t){const t=Fo(e,((e,t)=>n.slice(s+e,s+t)));r[e.name]=Co(e,n.slice(s,s+t)),s+=t}return r}function Fo(e,t){const n=c(e.shape);let r;if("quantization"in e){const t=e.quantization;r=uo[t.dtype]}else{if("string"===e.dtype){let e=0;for(let r=0;r{let t=e<<13,n=0;for(;0==(8388608&t);)n-=8388608,t<<=1;return t&=-8388609,n+=947912704,t|n},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let e=1024;e<2048;e++)t[e]=939524096+(e-1024<<13);return t}(),t=function(){const e=new Uint32Array(64);e[0]=0,e[31]=1199570944,e[32]=2147483648,e[63]=3347054592;for(let t=1;t<31;t++)e[t]=t<<23;for(let t=33;t<63;t++)e[t]=2147483648+(t-32<<23);return e}(),n=function(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}();return r=>{const s=new ArrayBuffer(4*r.length),o=new Uint32Array(s);for(let s=0;s>10]+(1023&a)]+t[a>>10];o[s]=i}return new Float32Array(s)}}();a=e(u)}}else{if("int32"!==r)throw new Error(`Unsupported dtype in weight '${n}': ${r}`);if("uint8"!==s.dtype&&"uint16"!==s.dtype)throw new Error(`Unsupported quantization type ${s.dtype} for weight type int32.`);a=new Int32Array(u.length);for(let e=0;e{if(t+=e.byteLength,n.push(e.byteLength===e.buffer.byteLength?e:new e.constructor(e)),!(e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${e.constructor.name}`)}));const r=new Uint8Array(t);let s=0;return n.forEach((e=>{r.set(new Uint8Array(e.buffer),s),s+=e.byteLength})),r.buffer}const Lo="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function zo(e){return Lo?Buffer.byteLength(e,"utf8"):new Blob([e]).size}function Uo(e){for(e=e.trim();e.endsWith("/");)e=e.slice(0,e.length-1);const t=e.split("/");return t[t.length-1]}function Wo(e,t){const n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return null!=e.signature&&(n.signature=e.signature),null!=e.userDefinedMetadata&&(n.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(n.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(n.initializerSignature=e.initializerSignature),null!=e.trainingConfig&&(n.trainingConfig=e.trainingConfig),n}function Go(e,t,n){const r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(null!=e.trainingConfig&&(r.trainingConfig=e.trainingConfig),null!=e.weightsManifest){if(!t)throw new Error("modelJSON has weightsManifest but weightSpecs is null");if(!n)throw new Error("modelJSON has weightsManifest but weightData is null");r.weightSpecs=t,r.weightData=n}return null!=e.signature&&(r.signature=e.signature),null!=e.userDefinedMetadata&&(r.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(r.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(r.initializerSignature=e.initializerSignature),r}async function Ko(e,t){let n,r;return null!=e.weightsManifest&&([n,r]=await t(e.weightsManifest)),Go(e,n,r)}function qo(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:null==e.modelTopology?0:zo(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:zo(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:new co(e.weightData).byteLength}}function Vo(e){const t=[];for(const n of e)t.push(...n.weights);return t}class Ho{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==Ho.instance&&(Ho.instance=new Ho),Ho.instance}static registerSaveRouter(e){Ho.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Ho.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Ho.getHandlers(e,"save")}static getLoadHandlers(e,t){return Ho.getHandlers(e,"load",t)}static getHandlers(e,t,n){const r=[];return("load"===t?Ho.getInstance().loadRouters:Ho.getInstance().saveRouters).forEach((t=>{const s=t(e,n);null!==s&&r.push(s)})),r}}function jo(){if(!O().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const e="undefined"==typeof window?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==t)throw new Error("The current browser does not appear to support IndexedDB.");return t}function Jo(e){const t=e.result;t.createObjectStore("models_store",{keyPath:"modelPath"}),t.createObjectStore("model_info_store",{keyPath:"modelPath"})}class Zo{constructor(e){if(this.indexedDB=jo(),null==e||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise(((e,n)=>{const r=this.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=()=>Jo(r),r.onsuccess=()=>{const s=r.result;if(null==t){const t=s.transaction("models_store","readonly"),r=t.objectStore("models_store").get(this.modelPath);r.onsuccess=()=>{if(null==r.result)return s.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));e(r.result.modelArtifacts)},r.onerror=e=>(s.close(),n(r.error)),t.oncomplete=()=>s.close()}else{t.weightData=co.join(t.weightData);const r=qo(t),o=s.transaction("model_info_store","readwrite");let a,i,l=o.objectStore("model_info_store");try{a=l.put({modelPath:this.modelPath,modelArtifactsInfo:r})}catch(e){return n(e)}a.onsuccess=()=>{i=s.transaction("models_store","readwrite");const a=i.objectStore("models_store");let u;try{u=a.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:r})}catch(e){return n(e)}u.onsuccess=()=>e({modelArtifactsInfo:r}),u.onerror=e=>{l=o.objectStore("model_info_store");const t=l.delete(this.modelPath);t.onsuccess=()=>(s.close(),n(u.error)),t.onerror=e=>(s.close(),n(u.error))}},a.onerror=e=>(s.close(),n(a.error)),o.oncomplete=()=>{null==i?s.close():i.oncomplete=()=>s.close()}}},r.onerror=e=>n(r.error)}))}}Zo.URL_SCHEME="indexeddb://";const Yo=e=>{return O().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Zo.URL_SCHEME)?(t=e.slice(Zo.URL_SCHEME.length),new Zo(t)):null;var t};Ho.registerSaveRouter(Yo),Ho.registerLoadRouter(Yo);class Xo{constructor(){this.indexedDB=jo()}async listModels(){return new Promise(((e,t)=>{const n=this.indexedDB.open("tensorflowjs",1);n.onupgradeneeded=()=>Jo(n),n.onsuccess=()=>{const r=n.result,s=r.transaction("model_info_store","readonly"),o=s.objectStore("model_info_store").getAll();o.onsuccess=()=>{const t={};for(const e of o.result)t[e.modelPath]=e.modelArtifactsInfo;e(t)},o.onerror=e=>(r.close(),t(o.error)),s.oncomplete=()=>r.close()},n.onerror=e=>t(n.error)}))}async removeModel(e){var t;return e=(t=e).startsWith(Zo.URL_SCHEME)?t.slice(Zo.URL_SCHEME.length):t,new Promise(((t,n)=>{const r=this.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=()=>Jo(r),r.onsuccess=()=>{const s=r.result,o=s.transaction("model_info_store","readwrite"),a=o.objectStore("model_info_store"),i=a.get(e);let l;i.onsuccess=()=>{if(null==i.result)return s.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const r=a.delete(e),o=()=>{l=s.transaction("models_store","readwrite");const r=l.objectStore("models_store").delete(e);r.onsuccess=()=>t(i.result.modelArtifactsInfo),r.onerror=e=>n(i.error)};r.onsuccess=o,r.onerror=e=>(o(),s.close(),n(i.error))}},i.onerror=e=>(s.close(),n(i.error)),o.oncomplete=()=>{null==l?s.close():l.oncomplete=()=>s.close()}},r.onerror=e=>n(r.error)}))}}const Qo="tensorflowjs_models",ea="info",ta="model_topology",na="weight_specs",ra="weight_data",sa="model_metadata";function oa(e){return{info:[Qo,e,ea].join("/"),topology:[Qo,e,ta].join("/"),weightSpecs:[Qo,e,na].join("/"),weightData:[Qo,e,ra].join("/"),modelMetadata:[Qo,e,sa].join("/")}}function aa(e){for(const t of Object.values(e))window.localStorage.removeItem(t)}function ia(e){const t=e.split("/");if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join("/")}class la{constructor(e){if(!O().getBool("IS_BROWSER")||"undefined"==typeof window||"undefined"==typeof window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==e||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=oa(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{const t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),r=qo(e),s=co.join(e.weightData);try{this.LS.setItem(this.keys.info,JSON.stringify(r)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(e){if(Lo)return Buffer.from(e).toString("base64");const t=new Uint8Array(e);let n="";for(let e=0,r=t.length;e{return O().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(la.URL_SCHEME)?(t=e.slice(la.URL_SCHEME.length),new la(t)):null;var t};Ho.registerSaveRouter(ua),Ho.registerLoadRouter(ua);class ca{constructor(){i(O().getBool("IS_BROWSER"),(()=>"Current environment is not a web browser")),i("undefined"==typeof window||"undefined"!=typeof window.localStorage,(()=>"Current browser does not appear to support localStorage")),this.LS=window.localStorage}async listModels(){const e={},t=Qo+"/",n="/"+ea;for(let r=0;r"scheme must not be undefined or null.")),e.endsWith("://")&&(e=e.slice(0,e.indexOf("://"))),i(e.length>0,(()=>"scheme must not be an empty string."));const n=ha.getInstance();i(null==n.managers[e],(()=>`A model store manager is already registered for scheme '${e}'.`)),n.managers[e]=t}static getManager(e){const t=ha.getInstance().managers[e];if(null==t)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(ha.getInstance().managers)}}function da(e){if(-1===e.indexOf("://"))throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${ha.getSchemes().join(",")}`);return{scheme:e.split("://")[0],path:e.split("://")[1]}}async function fa(e,t,n=!1){i(e!==t,(()=>`Old path and new path are the same: '${e}'`));const r=Ho.getLoadHandlers(e);i(r.length>0,(()=>`Copying failed because no load handler is found for source URL ${e}.`)),i(r.length<2,(()=>`Copying failed because more than one (${r.length}) load handlers for source URL ${e}.`));const s=r[0],o=Ho.getSaveHandlers(t);i(o.length>0,(()=>`Copying failed because no save handler is found for destination URL ${t}.`)),i(o.length<2,(()=>`Copying failed because more than one (${r.length}) save handlers for destination URL ${t}.`));const a=o[0],l=da(e).scheme,u=da(e).path,c=l===da(e).scheme,h=await s.load();n&&c&&await ha.getManager(l).removeModel(u);const d=await a.save(h);return n&&!c&&await ha.getManager(l).removeModel(u),d.modelArtifactsInfo}class pa{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}setTimeoutCustom(e,t){"undefined"!=typeof window&&O().getBool("USE_SETTIMEOUTCUSTOM")?(this.functionRefs.push(e),setTimeout((()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")}),t),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",(e=>{if(e.source===window&&e.data.name===this.messageName){e.stopPropagation();(0,this.functionRefs[e.data.index])(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0)}}),!0))):setTimeout(e,t)}isTypedArray(e){return kr(e)}}if(O().get("IS_BROWSER")){O().setPlatform("browser",new pa);try{ha.registerManager(la.URL_SCHEME,new ca)}catch(e){}try{ha.registerManager(Zo.URL_SCHEME,new Xo)}catch(e){}}const ga=()=>require("node-fetch");let ma;class ba{constructor(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return null!=O().global.fetch?O().global.fetch(e,t):(null==ma&&(ma=ga()),ma(e,t))}now(){const e=process.hrtime();return 1e3*e[0]+e[1]/1e6}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return 0===e.length?"":new this.util.TextDecoder(t).decode(e)}isTypedArray(e){return this.util.types.isFloat32Array(e)||this.util.types.isInt32Array(e)||this.util.types.isUint8Array(e)||this.util.types.isUint8ClampedArray(e)}}function ya(e,t="float32",n){return t=t||"float32",F(e),new xs(e,t,n)}O().get("IS_NODE")&&!O().get("IS_BROWSER")&&O().setPlatform("node",new ba);const wa=oo({cast_:function(e,t){const n=no(e,"x","cast");if(!k(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if("string"===t&&"string"!==n.dtype||"string"!==t&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");const r={x:n},s={dtype:t};return Hs.runKernel("Cast",r,s)}});const ka=oo({clone_:function(e){const t={x:no(e,"x","clone","string_or_numeric")};return Hs.runKernel("Identity",t)}});function va(e,t=!1){console.log(e.toString(t))}Vs();Ss={buffer:ya,cast:wa,clone:ka,print:va};const xa=oo({add_:function(e,t){let n=no(e,"a","add"),r=no(t,"b","add");[n,r]=Os(n,r);const s={a:n,b:r};return Hs.runKernel("Add",s)}});const Ea=oo({floorDiv_:function(e,t){let n=no(e,"a","floorDiv"),r=no(t,"b","floorDiv");[n,r]=Os(n,r);const s={a:n,b:r};return Hs.runKernel("FloorDiv",s)}});const Sa=oo({div_:function(e,t){let n=no(e,"a","div"),r=no(t,"b","div");if([n,r]=Os(n,r),"int32"===n.dtype&&"int32"===r.dtype)return Ea(n,r);const s={a:n,b:r};return Hs.runKernel("RealDiv",s,{})}});const $a=oo({mul_:function(e,t){let n=no(e,"a","mul"),r=no(t,"b","mul");[n,r]=Os(n,r);const s={a:n,b:r};return Hs.runKernel("Multiply",s)}});const Aa=oo({abs_:function(e){const t=no(e,"x","abs");if("complex64"===t.dtype){const e={x:t};return Hs.runKernel("ComplexAbs",e)}{const e={x:t};return Hs.runKernel("Abs",e)}}});const _a=oo({acos_:function(e){const t={x:no(e,"x","acos")};return Hs.runKernel("Acos",t)}});const Ia=oo({acosh_:function(e){const t={x:no(e,"x","acosh")};return Hs.runKernel("Acosh",t)}});const Ma=oo({addN_:function(e){i(Array.isArray(e),(()=>"The argument passed to tf.addN() must be a list of tensors")),i(e.length>=1,(()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`));const t=e.map(((e,t)=>no(e,`tensors${t}`,"addN"))),n=t[0];t.forEach((e=>{if(e.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")})),t.forEach((e=>{if(!d(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));const r=t;return Hs.runKernel("AddN",r)}});const Na=oo({all_:function(e,t=null,n=!1){const r={x:no(e,"x","all","bool")},s={axis:t,keepDims:n};return Hs.runKernel("All",r,s)}});const Ta=oo({any_:function(e,t=null,n=!1){const r={x:no(e,"x","any","bool")},s={axis:t,keepDims:n};return Hs.runKernel("Any",r,s)}});const Da=oo({argMax_:function(e,t=0){const n={x:no(e,"x","argMax")},r={axis:t};return Hs.runKernel("ArgMax",n,r)}});const Ra=oo({argMin_:function(e,t=0){const n={x:no(e,"x","argMin")},r={axis:t};return Hs.runKernel("ArgMin",n,r)}});const Fa=oo({asin_:function(e){const t={x:no(e,"x","asin")};return Hs.runKernel("Asin",t)}});const Ba=oo({asinh_:function(e){const t={x:no(e,"x","asinh")};return Hs.runKernel("Asinh",t)}});const Ca=oo({atan_:function(e){const t={x:no(e,"x","atan")};return Hs.runKernel("Atan",t)}});const Pa=oo({atan2_:function(e,t){let n=no(e,"a","atan2"),r=no(t,"b","atan2");[n,r]=Os(n,r);const s={a:n,b:r};return Hs.runKernel("Atan2",s)}});const Oa=oo({atanh_:function(e){const t={x:no(e,"x","atanh")};return Hs.runKernel("Atanh",t)}});function La(e,t,n,r,s,o,a="channelsLast"){const[i,l]=Ga(t);let u;if("channelsLast"===a)u=[i,l,e[3],e[3]];else{if("channelsFirst"!==a)throw new Error(`Unknown dataFormat ${a}`);u=[i,l,e[1],e[1]]}return za(e,u,n,r,s,o,!1,a)}function za(e,t,n,r,s,o,a=!1,i="channelsLast"){let[l,u,c,h]=[-1,-1,-1,-1];if("channelsLast"===i)[l,u,c,h]=e;else{if("channelsFirst"!==i)throw new Error(`Unknown dataFormat ${i}`);[l,h,u,c]=e}const[d,f,,p]=t,[g,m]=Ga(n),[b,y]=Ga(r),w=qa(d,b),k=qa(f,y),{padInfo:v,outHeight:x,outWidth:E}=function(e,t,n,r,s,o,a,i,l){let u,c,h;if("number"==typeof e){u={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};const s=function(e,t,n,r,s){null==r&&(r=Wa(e,t,n));const o=e[0],a=e[1],i=Va((o-t+2*r)/n+1,s),l=Va((a-t+2*r)/n+1,s);return[i,l]}([t,n],o,r,e,i);c=s[0],h=s[1]}else if("same"===e){c=Math.ceil(t/r),h=Math.ceil(n/s);const e=Math.max(0,(c-1)*r+o-t),i=Math.max(0,(h-1)*s+a-n),l=Math.floor(e/2),d=e-l,f=Math.floor(i/2);u={top:l,bottom:d,left:f,right:i-f,type:"SAME"}}else if("valid"===e)u={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((t-o+1)/r),h=Math.ceil((n-a+1)/s);else{if("object"!=typeof e)throw Error(`Unknown padding parameter: ${e}`);{const d="channelsLast"===l?e[1][0]:e[2][0],f="channelsLast"===l?e[1][1]:e[2][1],p="channelsLast"===l?e[2][0]:e[3][0],g="channelsLast"===l?e[2][1]:e[3][1];u={top:d,bottom:f,left:p,right:g,type:0===d&&0===f&&0===p&&0===g?"VALID":"EXPLICIT"},c=Va((t-o+d+f)/r+1,i),h=Va((n-a+p+g)/s+1,i)}}return{padInfo:u,outHeight:c,outWidth:h}}(s,u,c,g,m,w,k,o,i),S=a?p*h:p;let $;return"channelsFirst"===i?$=[l,S,x,E]:"channelsLast"===i&&($=[l,x,E,S]),{batchSize:l,dataFormat:i,inHeight:u,inWidth:c,inChannels:h,outHeight:x,outWidth:E,outChannels:S,padInfo:v,strideHeight:g,strideWidth:m,filterHeight:d,filterWidth:f,effectiveFilterHeight:w,effectiveFilterWidth:k,dilationHeight:b,dilationWidth:y,inShape:e,outShape:$,filterShape:t}}function Ua(e,t,n,r,s,o=!1,a="channelsLast",i){let[l,u,c,h,d]=[-1,-1,-1,-1,-1];if("channelsLast"===a)[l,u,c,h,d]=e;else{if("channelsFirst"!==a)throw new Error(`Unknown dataFormat ${a}`);[l,d,u,c,h]=e}const[f,p,g,,m]=t,[b,y,w]=Ka(n),[k,v,x]=Ka(r),E=qa(f,k),S=qa(p,v),$=qa(g,x),{padInfo:A,outDepth:_,outHeight:I,outWidth:M}=function(e,t,n,r,s,o,a,i,l,u,c){let h,d,f,p;"valid"===e&&(e=0);if("number"==typeof e){h={top:e,bottom:e,left:e,right:e,front:e,back:e,type:0===e?"VALID":"NUMBER"};const g=function(e,t,n,r,s,o){null==s&&(s=Wa(e,t[0],r[0]));const a=[0,0,0,n];for(let n=0;n<3;n++)e[n]+2*s>=t[n]&&(a[n]=Va((e[n]-t[n]+2*s)/r[n]+1,o));return a}([t,n,r,1],[i,l,u],1,[s,o,a],e,c);d=g[0],f=g[1],p=g[2]}else{if("same"!==e)throw Error(`Unknown padding parameter: ${e}`);{d=Math.ceil(t/s),f=Math.ceil(n/o),p=Math.ceil(r/a);const e=(d-1)*s+i-t,c=(f-1)*o+l-n,g=(p-1)*a+u-r,m=Math.floor(e/2),b=e-m,y=Math.floor(c/2),w=c-y,k=Math.floor(g/2);h={top:y,bottom:w,left:k,right:g-k,front:m,back:b,type:"SAME"}}}return{padInfo:h,outDepth:d,outHeight:f,outWidth:p}}(s,u,c,h,b,y,w,E,S,$,i),N=o?m*d:m;let T;return"channelsFirst"===a?T=[l,N,_,I,M]:"channelsLast"===a&&(T=[l,_,I,M,N]),{batchSize:l,dataFormat:a,inDepth:u,inHeight:c,inWidth:h,inChannels:d,outDepth:_,outHeight:I,outWidth:M,outChannels:N,padInfo:A,strideDepth:b,strideHeight:y,strideWidth:w,filterDepth:f,filterHeight:p,filterWidth:g,effectiveFilterDepth:E,effectiveFilterHeight:S,effectiveFilterWidth:$,dilationDepth:k,dilationHeight:v,dilationWidth:x,inShape:e,outShape:T,filterShape:t}}function Wa(e,t,n,r=1){const s=qa(t,r);return Math.floor((e[0]*(n-1)-n+s)/2)}function Ga(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function Ka(e){return"number"==typeof e?[e,e,e]:e}function qa(e,t){return t<=1?e:e+(e-1)*(t-1)}function Va(e,t){if(!t)return Math.trunc(e);switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error(`Unknown roundingMode ${t}`)}}function Ha(e){const[t,n,r]=Ga(e);return 1===t&&1===n&&1===r}function ja(e,t){return Ha(e)||Ha(t)}function Ja(e){return Ga(e).every((e=>e>0))}function Za(e){if("NHWC"===e)return"channelsLast";if("NCHW"===e)return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function Ya(e,t,n){if(null!=n){if("string"==typeof t)throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);if("number"==typeof t)i(f(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`));else{if("object"!=typeof t)throw Error(`Error in ${e}: Unknown padding parameter: ${t}`);t.forEach((t=>{t.forEach((t=>{i(f(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`))}))}))}}}const Xa=oo({reshape_:function(e,t){const n={x:no(e,"x","reshape","string_or_numeric")},r={shape:t};return Hs.runKernel("Reshape",n,r)}});const Qa=oo({avgPool_:function(e,t,n,r,s){const o=no(e,"x","avgPool","float32");i(ja(n,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`));let a=o,l=!1;3===o.rank&&(l=!0,a=Xa(o,[1,o.shape[0],o.shape[1],o.shape[2]])),i(4===a.rank,(()=>`Error in avgPool: x must be rank 4 but got rank ${a.rank}.`)),Ya("avgPool",r,s);const u={x:a},c={filterSize:t,strides:n,pad:r,dimRoundingMode:s};let h=Hs.runKernel("AvgPool",u,c);return h=wa(h,o.dtype),l?Xa(h,[h.shape[1],h.shape[2],h.shape[3]]):h}});const ei=oo({avgPool3d_:function(e,t,n,r,s,o="NDHWC"){const a=no(e,"x","avgPool3d","float32");let l=a,u=!1;4===a.rank&&(u=!0,l=Xa(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),i(5===l.rank,(()=>`Error in avgPool3d: x must be rank 5 but got rank ${l.rank}.`)),i("NDHWC"===o,(()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${o}`)),i("number"==typeof n&&n>0||Array.isArray(n)&&n[0]>0&&n[1]>0&&n[2]>0,(()=>`Error in avgPool3d: Stride must be > 0, but got '${n}'`)),Ya("avgPool3d",r,s);const c={x:l},h={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:o};let d=Hs.runKernel("AvgPool3D",c,h);return d=wa(d,l.dtype),u?Xa(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}});const ti=oo({concat_:function(e,t=0){i(e.length>=1,(()=>"Pass at least one tensor to concat"));const n=ro(e,"tensors","concat","string_or_numeric");if("complex64"===n[0].dtype&&n.forEach((e=>{if("complex64"!==e.dtype)throw new Error(`Cannot concatenate complex64 tensors with a tensor\n with dtype ${e.dtype}. `)})),1===n.length)return ka(n[0]);const r=n,s={axis:t};return Hs.runKernel("Concat",r,s)}});const ni=oo({matMul_:function(e,t,n=!1,r=!1){let s=no(e,"a","matMul"),o=no(t,"b","matMul");[s,o]=Os(s,o);const a={a:s,b:o},i={transposeA:n,transposeB:r};return Hs.runKernel("BatchMatMul",a,i)}});const ri=oo({sigmoid_:function(e){const t={x:no(e,"x","sigmoid","float32")};return Hs.runKernel("Sigmoid",t)}});const si=oo({slice_:function(e,t,n){const r=no(e,"x","slice","string_or_numeric");if(0===r.rank)throw new Error("Slicing scalar is not possible");const s={x:r},o={begin:t,size:n};return Hs.runKernel("Slice",s,o)}});const oi=oo({tanh_:function(e){const t={x:no(e,"x","tanh","float32")};return Hs.runKernel("Tanh",t)}});const ai=oo({basicLSTMCell_:function(e,t,n,r,s,o){const a=no(e,"forgetBias","basicLSTMCell"),i=no(t,"lstmKernel","basicLSTMCell"),l=no(n,"lstmBias","basicLSTMCell"),u=no(r,"data","basicLSTMCell"),c=no(s,"c","basicLSTMCell"),h=no(o,"h","basicLSTMCell"),d=ti([u,h],1),f=ni(d,i),p=xa(f,l),g=p.shape[0],m=p.shape[1]/4,b=[g,m],y=si(p,[0,0],b),w=si(p,[0,m],b),k=si(p,[0,2*m],b),v=si(p,[0,3*m],b),x=xa($a(ri(y),oi(w)),$a(c,ri(xa(a,k))));return[x,$a(oi(x),ri(v))]}});const ii=oo({batchToSpaceND_:function(e,t,n){const r=no(e,"x","batchToSpaceND"),s=t.reduce(((e,t)=>e*t));i(r.rank>=1+t.length,(()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`)),i(n.length===t.length,(()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`)),i(r.shape[0]%s==0,(()=>`input tensor batch is ${r.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${s}`));const o={x:r},a={blockShape:t,crops:n};return Hs.runKernel("BatchToSpaceND",o,a)}});const li=oo({batchNorm_:function(e,t,n,r,s,o){null==o&&(o=.001);const a=no(e,"x","batchNorm"),l=no(t,"mean","batchNorm"),u=no(n,"variance","batchNorm");let c,h;null!=s&&(c=no(s,"scale","batchNorm")),null!=r&&(h=no(r,"offset","batchNorm")),i(l.rank===u.rank,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),i(null==h||l.rank===h.rank,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),i(null==c||l.rank===c.rank,(()=>"Batch normalization gradient requires mean and scale to have equal ranks."));const d=function(e){let t;return t=0===e.rank||1===e.rank?Xa(e,[1,1,1,e.size]):2===e.rank?Xa(e,[1,1,e.shape[0],e.shape[1]]):3===e.rank?Xa(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e,t}(a),f={x:d,scale:c,offset:h,mean:l,variance:u},p={varianceEpsilon:o},g=Hs.runKernel("FusedBatchNorm",f,p);return Xa(g,a.shape)}});const ui=oo({batchNorm2d_:function(e,t,n,r,s,o){const a=no(e,"x","batchNorm"),l=no(t,"mean","batchNorm"),u=no(n,"variance","batchNorm");let c,h;return null!=s&&(c=no(s,"scale","batchNorm")),null!=r&&(h=no(r,"offset","batchNorm")),i(2===a.rank,(()=>`Error in batchNorm2D: x must be rank 2 but got rank ${a.rank}.`)),i(2===l.rank||1===l.rank,(()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${l.rank}.`)),i(2===u.rank||1===u.rank,(()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${u.rank}.`)),null!=c&&i(2===c.rank||1===c.rank,(()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`)),null!=h&&i(2===h.rank||1===h.rank,(()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${h.rank}.`)),li(a,l,u,h,c,o)}});const ci=oo({batchNorm3d_:function(e,t,n,r,s,o){const a=no(e,"x","batchNorm"),l=no(t,"mean","batchNorm"),u=no(n,"variance","batchNorm");let c,h;return null!=s&&(c=no(s,"scale","batchNorm")),null!=r&&(h=no(r,"offset","batchNorm")),i(3===a.rank,(()=>`Error in batchNorm3D: x must be rank 3 but got rank ${a.rank}.`)),i(3===l.rank||1===l.rank,(()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${l.rank}.`)),i(3===u.rank||1===u.rank,(()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${u.rank}.`)),null!=c&&i(3===c.rank||1===c.rank,(()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${c.rank}.`)),null!=h&&i(3===h.rank||1===h.rank,(()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${h.rank}.`)),li(a,l,u,h,c,o)}});const hi=oo({batchNorm4d_:function(e,t,n,r,s,o){const a=no(e,"x","batchNorm"),l=no(t,"mean","batchNorm"),u=no(n,"variance","batchNorm");let c,h;return null!=s&&(c=no(s,"scale","batchNorm")),null!=r&&(h=no(r,"offset","batchNorm")),i(4===a.rank,(()=>`Error in batchNorm4D: x must be rank 4 but got rank ${a.rank}.`)),i(4===l.rank||1===l.rank,(()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${l.rank}.`)),i(4===u.rank||1===u.rank,(()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${u.rank}.`)),null!=c&&i(4===c.rank||1===c.rank,(()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${c.rank}.`)),null!=h&&i(4===h.rank||1===h.rank,(()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${h.rank}.`)),li(a,l,u,h,c,o)}});const di=oo({bincount_:function(e,t,n){const r=no(e,"x","bincount"),s=no(t,"weights","bincount");i("int32"===r.dtype,(()=>`Error in bincount: input dtype must be int32, but got ${r.dtype}`)),i(n>=0,(()=>`size must be non-negative, but got ${n}.`)),i(s.size===r.size||0===s.size,(()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${r.shape}, weights shape: ${s.shape}.`));const o={x:r,weights:s},a={size:n};return Hs.runKernel("Bincount",o,a)}});const fi=oo({bitwiseAnd_:function(e,t){const n=no(e,"x","bitwiseAnd"),r=no(t,"y","bitwiseAnd");if(!d(n.shape,r.shape))throw new Error(`BitwiseAnd: Tensors must have the same shape. x: ${n.shape}, y: ${r.shape}`);if("int32"!==n.dtype||"int32"!==r.dtype)throw new Error(`BitwiseAnd: Only supports 'int32' values in tensor, found type of x: ${n.dtype} and type of y: ${r.dtype}`);const s={a:n,b:r};return Hs.runKernel("BitwiseAnd",s)}});const pi=oo({broadcastArgs_:function(e,t){const n=no(e,"s0","broadcastArgs","int32"),r=no(t,"s1","broadcastArgs","int32");if(1!==n.rank)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${n.rank}`);if(1!==r.rank)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${r.rank}`);const s={s0:n,s1:r};return Hs.runKernel("BroadcastArgs",s)}});const gi=oo({broadcastTo_:function(e,t){let n=no(e,"broadcastTo","x");const r=n.shape;if(F(t),t.lengthn.rank){const e=n.shape.slice();for(;e.length=0;e--)if(s[e]===t[e])o[e]=1;else if(1!==n.shape[e])throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${t}].`);if(0===o.map(((e,t)=>e>1?t:-1)).filter((e=>e>=0)).length)return ka(n);const a={x:n},i={reps:o};return Hs.runKernel("Tile",a,i)}});const mi=oo({ceil_:function(e){const t={x:no(e,"x","ceil","float32")};return Hs.runKernel("Ceil",t)}});function bi(e,t,n){F(e);const r={shape:e,value:t,dtype:n=n||A(t)};return Hs.runKernel("Fill",{},r)}const yi=oo({clipByValue_:function(e,t,n){const r=no(e,"x","clipByValue");if(i(t<=n,(()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`)),t===n)return bi(r.shape,t,r.dtype);const s={x:r},o={clipValueMin:t,clipValueMax:n};return Hs.runKernel("ClipByValue",s,o)}});const wi=oo({concat1d_:function(e){return ti(e,0)}});const ki=oo({concat2d_:function(e,t){return ti(e,t)}});const vi=oo({concat3d_:function(e,t){return ti(e,t)}});const xi=oo({concat4d_:function(e,t){return ti(e,t)}});const Ei=oo({conv2d_:function(e,t,n,r,s="NHWC",o=[1,1],a){const l=no(e,"x","conv2d","float32"),u=no(t,"filter","conv2d","float32");let c=l,h=!1;3===l.rank&&(h=!0,c=Xa(l,[1,l.shape[0],l.shape[1],l.shape[2]])),i(4===c.rank,(()=>`Error in conv2d: input must be rank 4, but got rank ${c.rank}.`)),i(4===u.rank,(()=>`Error in conv2d: filter must be rank 4, but got rank ${u.rank}.`)),Ya("conv2d",r,a);const d="NHWC"===s?c.shape[3]:c.shape[1];i(d===u.shape[2],(()=>`Error in conv2d: depth of input (${d}) must match input depth for filter ${u.shape[2]}.`)),i(ja(n,o),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`)),i(Ja(o),(()=>"Error in conv2D: Dilated rates should be larger than 0.")),i(Ja(n),(()=>"Error in conv2D: Strides should be larger than 0."));const f={x:c,filter:u},p={strides:n,pad:r,dataFormat:s,dilations:o,dimRoundingMode:a},g=Hs.runKernel("Conv2D",f,p);return h?Xa(g,[g.shape[1],g.shape[2],g.shape[3]]):g}});const Si=oo({conv1d_:function(e,t,n,r,s="NWC",o=1,a){const l=no(e,"x","conv1d"),u=no(t,"filter","conv1d");let c=l,h=!1;2===l.rank&&(h=!0,c=Xa(l,[1,l.shape[0],l.shape[1]])),i(3===c.rank,(()=>`Error in conv1d: input must be rank 3, but got rank ${c.rank}.`)),i(3===u.rank,(()=>`Error in conv1d: filter must be rank 3, but got rank ${u.rank}.`)),Ya("conv1d",r,a),i(c.shape[2]===u.shape[1],(()=>`Error in conv1d: depth of input (${c.shape[2]}) must match input depth for filter ${u.shape[1]}.`)),i(ja(n,o),(()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${o}'`)),i(Ja(o),(()=>"Error in conv1D: Dilated rates should be larger than 0.")),i(Ja(n),(()=>"Error in conv1D: Stride should be larger than 0.")),i("NWC"===s,(()=>`Error in conv1d: got dataFormat of ${s} but only NWC is currently supported.`));const d=Xa(u,[1,u.shape[0],u.shape[1],u.shape[2]]),f=Xa(c,[c.shape[0],1,c.shape[1],c.shape[2]]),p=Ei(f,d,[1,n],r,"NHWC",[1,o],a);return Xa(p,h?[p.shape[2],p.shape[3]]:[p.shape[0],p.shape[2],p.shape[3]])}});const $i=oo({conv2DBackpropInput_:function(e,t,n,r,s,o="NHWC",a){i(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let l=e,u=t,c=!1;3===t.rank&&(c=!0,u=Xa(t,[1,t.shape[0],t.shape[1],t.shape[2]]),l=[1,e[0],e[1],e[2]]),i(4===l.length,(()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${l.length}.`)),i(4===u.rank,(()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${u.rank}`)),i(4===n.rank,(()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`));const h="NHWC"===o?l[3]:l[1],d="NHWC"===o?u.shape[3]:u.shape[1];i(h===n.shape[2],(()=>`Error in conv2dDerInput: depth of input (${h}) must match input depth for filter ${n.shape[2]}.`)),i(d===n.shape[3],(()=>`Error in conv2dDerInput: depth of output (${d}) must match output depth for filter ${n.shape[3]}.`)),Ya("conv2dDerInput",s,a);const f={dy:u,filter:n},p={strides:r,pad:s,dataFormat:o,dimRoundingMode:a,inputShape:l},g=Hs.runKernel("Conv2DBackpropInput",f,p);return c?Xa(g,[g.shape[1],g.shape[2],g.shape[3]]):g}});const Ai=oo({conv2dTranspose_:function(e,t,n,r,s,o){const a=no(e,"x","conv2dTranspose"),i=no(t,"filter","conv2dTranspose");return $i(n,a,i,r,s,"NHWC",o)}});const _i=oo({conv3d_:function(e,t,n,r,s="NDHWC",o=[1,1,1]){const a=no(e,"x","conv3d"),l=no(t,"filter","conv3d");let u=a,c=!1;4===a.rank&&(c=!0,u=Xa(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),i(5===u.rank,(()=>`Error in conv3d: input must be rank 5, but got rank ${u.rank}.`)),i(5===l.rank,(()=>`Error in conv3d: filter must be rank 5, but got rank ${l.rank}.`)),i(u.shape[4]===l.shape[3],(()=>`Error in conv3d: depth of input (${u.shape[4]}) must match input depth for filter ${l.shape[3]}.`)),i(ja(n,o),(()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`)),i("NDHWC"===s,(()=>`Error in conv3d: got dataFormat of ${s} but only NDHWC is currently supported.`)),i(Ja(o),(()=>"Error in conv3D: Dilated rates should be larger than 0.")),i(Ja(n),(()=>"Error in conv3D: Strides should be larger than 0."));const h={x:u,filter:l},d={strides:n,pad:r,dataFormat:s,dilations:o},f=Hs.runKernel("Conv3D",h,d);return c?Xa(f,[f.shape[1],f.shape[2],f.shape[3],f.shape[4]]):f}});const Ii=oo({conv3DBackpropInput_:function(e,t,n,r,s){i(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let o=e,a=t,l=!1;4===t.rank&&(l=!0,a=Xa(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),o=[1,e[0],e[1],e[2],e[3]]);const u=o[4],c=a.shape[4];i(5===o.length,(()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${o.length}.`)),i(5===a.rank,(()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${a.rank}`)),i(5===n.rank,(()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`)),i(u===n.shape[3],(()=>`Error in conv3dDerInput: depth of input (${u}) must match input depth for filter ${n.shape[3]}.`)),i(c===n.shape[4],(()=>`Error in conv3dDerInput: depth of output (${c}) must match output depth for filter ${n.shape[4]}.`));const h={dy:a,filter:n},d={pad:s,strides:r,inputShape:o},f=Hs.runKernel("Conv3DBackpropInputV2",h,d);return l?Xa(f,[f.shape[1],f.shape[2],f.shape[3],f.shape[4]]):f}});const Mi=oo({conv3dTranspose_:function(e,t,n,r,s){const o=no(e,"x","conv3dTranspose"),a=no(t,"filter","conv3dTranspose");return Ii(n,o,a,r,s)}});const Ni=oo({cos_:function(e){const t={x:no(e,"x","cos","float32")};return Hs.runKernel("Cos",t)}});const Ti=oo({cosh_:function(e){const t={x:no(e,"x","cosh","float32")};return Hs.runKernel("Cosh",t)}});const Di=oo({cumprod_:function(e,t=0,n=!1,r=!1){const s={x:no(e,"x","cumprod")},o={axis:t,exclusive:n,reverse:r};return Hs.runKernel("Cumprod",s,o)}});const Ri=oo({cumsum_:function(e,t=0,n=!1,r=!1){const s={x:no(e,"x","cumsum")},o={axis:t,exclusive:n,reverse:r};return Hs.runKernel("Cumsum",s,o)}});const Fi=oo({denseBincount_:function(e,t,n,r=!1){const s=no(e,"x","denseBincount"),o=no(t,"weights","denseBincount");i("int32"===s.dtype,(()=>`Error in denseBincount: input dtype must be int32, but got ${s.dtype}`)),i(s.rank<=2,(()=>`Error in denseBincount: input must be at most rank 2, but got rank ${s.rank}.`)),i(n>=0,(()=>`size must be non-negative, but got ${n}.`)),i(o.size===s.size||0===o.size,(()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${s.shape}, weights shape: ${o.shape}.`));const a={x:s,weights:o},l={size:n,binaryOutput:r};return Hs.runKernel("DenseBincount",a,l)}});const Bi=oo({depthToSpace_:function(e,t,n="NHWC"){const r=no(e,"x","depthToSpace","float32"),s="NHWC"===n?r.shape[1]:r.shape[2],o="NHWC"===n?r.shape[2]:r.shape[3],a="NHWC"===n?r.shape[3]:r.shape[1];i(t>1,(()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`)),i(s*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${s} and ${t} for depthToSpace with input shape\n ${r.shape}`)),i(o*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${o} and ${t} for depthToSpace with input shape\n ${r.shape}`)),i(a%(t*t)==0,(()=>`Dimension size must be evenly divisible by ${t*t} but is ${a} for depthToSpace with input shape ${r.shape}`));const l={x:r},u={blockSize:t,dataFormat:n};return Hs.runKernel("DepthToSpace",l,u)}});const Ci=oo({depthwiseConv2d_:function(e,t,n,r,s="NHWC",o=[1,1],a){const l=no(e,"x","depthwiseConv2d","float32"),u=no(t,"filter","depthwiseConv2d","float32");let c=l,h=!1;3===l.rank&&(h=!0,c=Xa(l,[1,l.shape[0],l.shape[1],l.shape[2]])),i(4===c.rank,(()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`)),i(4===u.rank,(()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${u.rank}.`));const d="NHWC"===s?c.shape[3]:c.shape[1];i(d===u.shape[2],(()=>`Error in depthwiseConv2d: number of input channels (${d}) must match the inChannels dimension in filter ${u.shape[2]}.`)),Ya("depthwiseConv2d",r,a);const f={x:c,filter:u},p={strides:n,pad:r,dataFormat:s,dilations:o,dimRoundingMode:a},g=Hs.runKernel("DepthwiseConv2dNative",f,p);return h?Xa(g,[g.shape[1],g.shape[2],g.shape[3]]):g}});const Pi=oo({diag_:function(e){const t={x:no(e,"x","diag")};return Hs.runKernel("Diag",t)}});const Oi=oo({dilation2d_:function(e,t,n,r,s=[1,1],o="NHWC"){const a=no(e,"x","dilation2d"),l=no(t,"filter","dilation2d");i(3===a.rank||4===a.rank,(()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${a.rank}.`)),i(3===l.rank,(()=>`Error in dilation2d: filter must be rank 3, but got rank ${l.rank}.`)),i("NHWC"===o,(()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${o}`));let u=a,c=!1;3===a.rank&&(u=Xa(a,[1,a.shape[0],a.shape[1],a.shape[2]]),c=!0),i(u.shape[3]===l.shape[2],(()=>`Error in dilation2d: input and filter must have the same depth: ${u.shape[3]} vs ${l.shape[2]}`));const h={x:u,filter:l},d={strides:n,pad:r,dilations:s},f=Hs.runKernel("Dilation2D",h,d);return c?Xa(f,[f.shape[1],f.shape[2],f.shape[3]]):f}});function Li(e,t){const n=e.length,r=[];for(let s=0;s1&&1===a&&r.unshift(o)}return r}function zi(e,t){const n=[];for(let r=0;r1)&&n.unshift(o)}return n}function Ui(e,t){const n=Math.max(e.length,t.length),r=new Array(n);for(let s=0;s`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${r.rank}.`));const s=1===n.rank?n.size:n.shape[1],o=1===r.rank?r.size:r.shape[0];if(i(s===o,(()=>`Error in dot: inner dimensions of inputs must match, but got ${s} and ${o}.`)),1===n.rank&&1===r.rank){const e=Xa(n,[1,-1]),t=Xa(r,[-1,1]),s=ni(e,t);return Xa(s,[])}if(1===n.rank&&2===r.rank){const e=Xa(n,[1,-1]),t=Xa(r,[r.shape[0],r.shape[1]]),s=ni(e,t);return Xa(s,[s.size])}if(2===n.rank&&1===r.rank){const e=Xa(r,[-1,1]),t=ni(n,e);return Xa(t,[t.size])}{const e=Xa(r,[r.shape[0],r.shape[1]]);return ni(n,e)}}});const ji=oo({einsum_:function(e,...t){const n=t.map(((e,t)=>no(e,`tensors${t}`,"einsum"))),r={equation:e};return Hs.runKernel("Einsum",n,r)}});const Ji=oo({elu_:function(e){const t={x:no(e,"x","elu","float32")};return Hs.runKernel("Elu",t)}});const Zi=oo({ensureShape_:function(e,t){const n=no(e,"x","ensureShape","string_or_numeric");if(!h(n.shape,t))throw new Error(`EnsureShape: Shape of tensor ${n.shape} is not compatible with expected shape ${t}`);return e}});const Yi=oo({erf_:function(e){let t=no(e,"x","erf");i("int32"===t.dtype||"float32"===t.dtype,(()=>"Input dtype must be `int32` or `float32`.")),"int32"===t.dtype&&(t=wa(t,"float32"));const n={x:t};return Hs.runKernel("Erf",n)}});function Xi(e,t){for(let n=0;n1)),t)}const tl=oo({max_:function(e,t=null,n=!1){const r={x:no(e,"x","max")},s={reductionIndices:t,keepDims:n};return Hs.runKernel("Max",r,s)}});const nl=oo({min_:function(e,t=null,n=!1){const r={x:no(e,"x","min")},s={axis:t,keepDims:n};return Hs.runKernel("Min",r,s)}});const rl=oo({pow_:function(e,t){let n=no(e,"base","pow"),r=no(t,"exp","pow");[n,r]=Os(n,r);const s={a:n,b:r};return Hs.runKernel("Pow",s)}});function sl(e,t){if((hs(e)&&"string"!==t||Array.isArray(e))&&"complex64"!==t)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===t&&hs(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return io(e,[],[],t)}const ol=oo({sqrt_:function(e){const t={x:no(e,"x","sqrt","float32")};return Hs.runKernel("Sqrt",t)}});const al=oo({square_:function(e){const t=no(e,"x","square");return Hs.runKernel("Square",{x:t},{})}});const il=oo({sum_:function(e,t=null,n=!1){let r=no(e,"x","sum");"bool"===r.dtype&&(r=wa(r,"int32"));const s={x:r},o={axis:t,keepDims:n};return Hs.runKernel("Sum",s,o)}});function ll(e,t,n=null){if(0===e.rank)return Aa(e);if(1!==e.rank&&null===n)return ll(Xa(e,[-1]),t,n);if(1===e.rank||"number"==typeof n||Array.isArray(n)&&1===n.length){if(1===t)return il(Aa(e),n);if(t===1/0)return tl(Aa(e),n);if(t===-1/0)return nl(Aa(e),n);if("euclidean"===t||2===t)return ol(il(rl(Aa(e),sl(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&2===n.length){if(1===t)return tl(il(Aa(e),n[0]),n[1]-1);if(t===1/0)return tl(il(Aa(e),n[1]),n[0]);if(t===-1/0)return nl(il(Aa(e),n[1]),n[0]);if("fro"===t||"euclidean"===t)return ol(il(al(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const ul=oo({norm_:function(e,t="euclidean",n=null,r=!1){const s=ll(e=no(e,"x","norm"),t,n);let o=s.shape;if(r){const t=g(n,e.shape);o=el(s.shape,t)}return Xa(s,o)}});const cl=oo({euclideanNorm_:function(e,t=null,n=!1){return ul(e,"euclidean",t,n)}});const hl=oo({exp_:function(e){const t={x:no(e,"x","exp")};return Hs.runKernel("Exp",t)}});const dl=oo({expandDims_:function(e,t=0){const n=no(e,"x","expandDims","string_or_numeric");i(t<=n.rank,(()=>"Axis must be <= rank of the tensor"));const r={input:n},s={dim:t};return Hs.runKernel("ExpandDims",r,s)}});const fl=oo({expm1_:function(e){const t={x:no(e,"x","expm1")};return Hs.runKernel("Expm1",t)}});const pl=oo({tile_:function(e,t){const n=no(e,"x","tile","string_or_numeric");i(n.rank===t.length,(()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`));const r={x:n},s={reps:t};return Hs.runKernel("Tile",r,s)}});const gl=oo({eye_:function(e,t,n,r="float32"){null==t&&(t=e);const s=ya([e,t],r),o=e<=t?e:t;for(let e=0;e`Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank ${o.rank}.`)),i(f(t),(()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`));let a=o,l=!1;3===o.rank&&(l=!0,a=Xa(o,[1,o.shape[0],o.shape[1],o.shape[2]]));const u={x:a},c={depthRadius:t,bias:n,alpha:r,beta:s},h=Hs.runKernel("LRN",u,c);return l?Xa(h,[h.shape[1],h.shape[2],h.shape[3]]):h}});const Ml=oo({log_:function(e){const t={x:no(e,"x","log","float32")};return Hs.runKernel("Log",t)}});const Nl=oo({log1p_:function(e){const t={x:no(e,"x","log1p")};return Hs.runKernel("Log1p",t)}});function Tl(e){return i(_(e),(()=>"The f passed in grad(f) must be a function")),(t,n)=>{const r=no(t,"x","tf.grad","string_or_numeric"),s=null!=n?no(n,"dy","tf.grad"):null;return Hs.tidy((()=>{const{value:t,grads:n}=Hs.gradients((()=>e(r)),[r],s);return null!=s&&l(t.shape,s.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Pl(n),n[0]}))}}function Dl(e){return i(_(e),(()=>"The f passed in grads(f) must be a function")),(t,n)=>{i(Array.isArray(t),(()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s"));const r=ro(t,"args","tf.grads","string_or_numeric"),s=null!=n?no(n,"dy","tf.grads"):null;return Hs.tidy((()=>{const{value:t,grads:n}=Hs.gradients((()=>e(...r)),r,s);return null!=s&&l(t.shape,s.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Pl(n),n}))}}function Rl(e){return i(_(e),(()=>"The f passed in valueAndGrad(f) must be a function")),(t,n)=>{i(t instanceof $s,(()=>"The x passed in valueAndGrad(f)(x) must be a tensor")),i(null==n||n instanceof $s,(()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"));const{grads:r,value:s}=Hs.gradients((()=>e(t)),[t],n);return Pl(r),{grad:r[0],value:s}}}function Fl(e){return i(_(e),(()=>"The f passed in valueAndGrads(f) must be a function")),(t,n)=>{i(Array.isArray(t)&&t.every((e=>e instanceof $s)),(()=>"The args passed in valueAndGrads(f)(args) must be array of tensors")),i(null==n||n instanceof $s,(()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"));const r=Hs.gradients((()=>e(...t)),t,n);return null!=n&&l(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Pl(r.grads),r}}function Bl(e,t){i(_(e),(()=>"The f passed in variableGrads(f) must be a function")),i(null==t||Array.isArray(t)&&t.every((e=>e instanceof _s)),(()=>"The varList passed in variableGrads(f, varList) must be an array of variables"));const n=null!=t;if(!n){t=[];for(const e in Hs.registeredVariables)t.push(Hs.registeredVariables[e])}const r=n?t.filter((e=>!e.trainable)):null,s=t.length;t=t.filter((e=>e.trainable)),i(t.length>0,(()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${s} variables is trainable.`));const{value:o,grads:a}=Hs.gradients(e,t,null,!0);i(a.some((e=>null!=e)),(()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize().")),i(0===o.rank,(()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${o.rank} tensor`));const l={};return t.forEach(((e,t)=>{null!=a[t]&&(l[e.name]=a[t])})),null!=r&&r.forEach((e=>l[e.name]=null)),{value:o,grads:l}}function Cl(e){return Hs.customGrad(e)}function Pl(e){if(e.filter((e=>null==e)).length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\n the f you passed encloses all operations that lead from x to y.")}const Ol=oo({neg_:function(e){const t={x:no(e,"x","neg")};return Hs.runKernel("Neg",t)}});const Ll=oo({softplus_:function(e){const t={x:no(e,"x","softplus")};return Hs.runKernel("Softplus",t)}});const zl=oo({logSigmoid_:function(e){const t=no(e,"x","logSigmoid"),n=Cl((e=>({value:Ol(Ll(Ol(e))),gradFunc:t=>$a(t,ri(Ol(e)))})));return n(t)}});const Ul=oo({sub_:function(e,t){let n=no(e,"a","sub"),r=no(t,"b","sub");[n,r]=Os(n,r);const s={a:n,b:r};return Hs.runKernel("Sub",s)}});const Wl=oo({logSoftmax_:function(e,t=-1){const n=no(e,"logits","logSoftmax");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);const r=Cl(((e,n)=>{const r=tl(e,t,!0),s=Ul(e,r),o=Ul(wa(s,"float32"),Ml(il(hl(s),t,!0)));n([o]);return{value:o,gradFunc:(e,n)=>{const[r]=n,s=hl(r);return Ul(e,$a(il(e,t,!0),s))}}}));return r(n)}});const Gl=oo({logSumExp_:function(e,t=null,n=!1){const r=no(e,"x","logSumExp"),s=g(t,r.shape),o=tl(r,s,!0),a=Ul(r,o),i=hl(a),l=il(i,s),u=Ml(l),c=xa(Xa(o,u.shape),u);if(n){const e=el(c.shape,s);return Xa(c,e)}return c}});const Kl=oo({logicalAnd_:function(e,t){const n=no(e,"a","logicalAnd","bool"),r=no(t,"b","logicalAnd","bool");Ui(n.shape,r.shape);const s={a:n,b:r};return Hs.runKernel("LogicalAnd",s)}});const ql=oo({logicalNot_:function(e){const t={x:no(e,"x","logicalNot","bool")};return Hs.runKernel("LogicalNot",t)}});const Vl=oo({logicalOr_:function(e,t){const n=no(e,"a","logicalOr","bool"),r=no(t,"b","logicalOr","bool");Ui(n.shape,r.shape);const s={a:n,b:r};return Hs.runKernel("LogicalOr",s)}});const Hl=oo({logicalXor_:function(e,t){const n=no(e,"a","logicalXor","bool"),r=no(t,"b","logicalXor","bool");return Ui(n.shape,r.shape),Kl(Vl(e,t),ql(Kl(e,t)))}});const jl=oo({searchSorted_:function(e,t,n="left"){const r=no(e,"sortedSequence","searchSorted"),s=no(t,"values","searchSorted"),o=r.shape[r.shape.length-1],a=s.shape[s.shape.length-1],i=Xa(r,[-1,o]),l=Xa(s,[-1,a]);if(i.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(i.shape[0]!==l.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(c(l.shape)>=2147483648)throw new Error("values tensor size must less than 2147483648");if(i.shape[1]>=2147483648)throw new Error(`trailing dim_size must less than 2147483648 for int32 output type, was ${i.shape[1]}`);const u={sortedSequence:i,values:l},h={side:n};return Hs.runKernel("SearchSorted",u,h)}});function Jl(e,t){return jl(e,t,"left")}const Zl=oo({maxPool_:function(e,t,n,r,s){const o=no(e,"x","maxPool");let a=o,l=!1;3===o.rank&&(l=!0,a=Xa(o,[1,o.shape[0],o.shape[1],o.shape[2]])),i(4===a.rank,(()=>`Error in maxPool: input must be rank 4 but got rank ${a.rank}.`)),i(ja(n,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`)),Ya("maxPool",r,s);const u={x:a},c={filterSize:t,strides:n,pad:r,dimRoundingMode:s},h=Hs.runKernel("MaxPool",u,c);return l?Xa(h,[h.shape[1],h.shape[2],h.shape[3]]):h}});const Yl=oo({maxPool3d_:function(e,t=[1,1,1],n,r,s,o="NDHWC"){const a=no(e,"x","maxPool3d");let l=a,u=!1;4===a.rank&&(u=!0,l=Xa(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),i(5===l.rank,(()=>`Error in maxPool3d: x must be rank 5 but got rank ${l.rank}.`)),i("NDHWC"===o,(()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${o}`)),Ya("maxPool3d",r,s);const c={x:l},h={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:o},d=Hs.runKernel("MaxPool3D",c,h);return u?Xa(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}});const Xl=oo({maxPoolWithArgmax_:function(e,t,n,r,s=!1){const o={x:no(e,"x","maxPoolWithArgmax")},a={filterSize:t,strides:n,pad:r,includeBatchInIndex:s},i=Hs.runKernel("MaxPoolWithArgmax",o,a);return{result:i[0],indexes:i[1]}}});const Ql=oo({maximum_:function(e,t){let n=no(e,"a","maximum"),r=no(t,"b","maximum");[n,r]=Os(n,r),"bool"===n.dtype&&(n=wa(n,"int32"),r=wa(r,"int32")),Ui(n.shape,r.shape);const s={a:n,b:r};return Hs.runKernel("Maximum",s)}});const eu=oo({mean_:function(e,t=null,n=!1){const r={x:no(e,"x","mean")},s={axis:t,keepDims:n};return Hs.runKernel("Mean",r,s)}});function tu(e,t="float32"){if(F(e),"complex64"===t){const t=tu(e,"float32"),n=tu(e,"float32");return ao(t,n)}const n=R(c(e),t);return Hs.makeTensor(n,e,t)}function nu(e,t="float32"){if(F(e),"complex64"===t){const t=nu(e,"float32"),n=tu(e,"float32");return ao(t,n)}const n=D(c(e),t);return Hs.makeTensor(n,e,t)}function ru(e,t,{indexing:n="xy"}={}){if("xy"!==n&&"ij"!==n)throw new TypeError(`${n} is not a valid third argument to meshgrid`);if(void 0===e)return[];let r=no(e,"x","meshgrid",e instanceof $s?e.dtype:"float32");if(void 0===t)return[r];let s=no(t,"y","meshgrid",t instanceof $s?t.dtype:"float32");const o=c(r.shape),a=c(s.shape);return"xy"===n?(r=Xa(r,[1,-1]),s=Xa(s,[-1,1]),[ni(nu([a,1],r.dtype),r),ni(s,nu([1,o],s.dtype))]):(r=Xa(r,[-1,1]),s=Xa(s,[1,-1]),[ni(r,nu([1,a],r.dtype)),ni(nu([o,1],s.dtype),s)])}const su=oo({minimum_:function(e,t){let n=no(e,"a","minimum"),r=no(t,"b","minimum");[n,r]=Os(n,r),"bool"===n.dtype&&(n=wa(n,"int32"),r=wa(r,"int32")),Ui(n.shape,r.shape);const s={a:n,b:r};return Hs.runKernel("Minimum",s)}});const ou=oo({mirrorPad_:function(e,t,n){i("reflect"===n||"symmetric"===n,(()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`));const r=no(e,"x","mirrorPad");if(0===r.rank)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");i(t.length===r.rank,(()=>`Padding doesn't match input. Must be ${r.rank}. Got ${t.length}.`));const s="reflect"===n?1:0;for(let e=0;e"Invalid number of paddings. Must be length of 2 each.")),i(t[e][0]>=0&&t[e][0]<=r.shape[e]-s&&t[e][1]>=0&&t[e][1]<=r.shape[e]-s,(()=>`Padding in dimension ${e} cannot be greater than or equal to ${r.shape[e]-s} or less than 0 for input of shape ${r.shape}`));const o={paddings:t,mode:n},a={x:r};return Hs.runKernel("MirrorPad",a,o)}});const au=oo({mod_:function(e,t){let n=no(e,"a","mod"),r=no(t,"b","mod");[n,r]=Os(n,r);const s={a:n,b:r};return Hs.runKernel("Mod",s)}});const iu=oo({moments_:function(e,t=null,n=!1){const r=g(t,(e=no(e,"x","moments")).shape),s=eu(e,r,n);let o=s.shape;n||(o=el(s.shape,r));const a=al(Ul(wa(e,"float32"),Xa(s,o)));return{mean:s,variance:eu(a,r,n)}}});const lu=oo({multiRNNCell_:function(e,t,n,r){const s=no(t,"data","multiRNNCell"),o=ro(n,"c","multiRNNCell"),a=ro(r,"h","multiRNNCell");let i=s;const l=[];for(let t=0;t2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${a}`);n=n||Math.random();const i={logits:1===a?Xa(s,[1,-1]):s},l={numSamples:t,seed:n,normalized:r},u=Hs.runKernel("Multinomial",i,l);return 1===a?Xa(u,[u.size]):u}});const cu=oo({notEqual_:function(e,t){let n=no(e,"a","notEqual","string_or_numeric"),r=no(t,"b","notEqual","string_or_numeric");[n,r]=Os(n,r),Ui(n.shape,r.shape);const s={a:n,b:r};return Hs.runKernel("NotEqual",s)}});const hu=oo({oneHot_:function(e,t,n=1,r=0,s="int32"){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const o={indices:no(e,"indices","oneHot","int32")},a={dtype:s,depth:t,onValue:n,offValue:r};return Hs.runKernel("OneHot",o,a)}});const du=oo({onesLike_:function(e){const t={x:no(e,"x","onesLike")};return Hs.runKernel("OnesLike",t)}});const fu=oo({outerProduct_:function(e,t){const n=no(e,"v1","outerProduct"),r=no(t,"v2","outerProduct");i(1===n.rank&&1===r.rank,(()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${r.rank}.`));const s=Xa(n,[-1,1]),o=Xa(r,[1,-1]);return ni(s,o)}});const pu=oo({pad_:function(e,t,n=0){const r=no(e,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const s={paddings:t,constantValue:n},o={x:r};return Hs.runKernel("PadV2",o,s)}});const gu=oo({pad1d_:function(e,t,n=0){return i(2===t.length,(()=>"Invalid number of paddings. Must be length of 2.")),pu(e,[t],n)}});const mu=oo({pad2d_:function(e,t,n=0){return i(2===t.length&&2===t[0].length&&2===t[1].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),pu(e,t,n)}});const bu=oo({pad3d_:function(e,t,n=0){return i(3===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),pu(e,t,n)}});const yu=oo({pad4d_:function(e,t,n=0){return i(4===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length&&2===t[3].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),pu(e,t,n)}});const wu=oo({spaceToBatchND_:function(e,t,n){const r=no(e,"x","spaceToBatchND");i(r.rank>=1+t.length,(()=>`input rank ${r.rank} should be > than [blockShape] ${t.length}`)),i(n.length===t.length,(()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`)),i(r.shape.reduce(((e,r,s)=>s>0&&s<=t.length?e&&(r+n[s-1][0]+n[s-1][1])%t[s-1]==0:e),!0),(()=>`input spatial dimensions ${r.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`));const s={x:r},o={blockShape:t,paddings:n};return Hs.runKernel("SpaceToBatchND",s,o)}});const ku=oo({pool_:function(e,t,n,r,s,o,a){null==s&&(s=[1,1]),null==o&&(o=1),0===r&&(r="valid");const l=no(e,"x","maxPool");let u=l,c=!1;3===l.rank&&(c=!0,u=Xa(l,[1,l.shape[0],l.shape[1],l.shape[2]])),i(ja(o,s),(()=>`Error in pool: Either strides or dilations must be 1. Got strides ${o} and dilations '${s}'`));const h=La(u.shape,t,o,s,r),d=[h.dilationHeight,h.dilationWidth];let f;f="same"===r?function(e,t){const n=e.map(((e,n)=>e+(e-1)*(t[n]-1))).map((e=>e-1)),r=n.map((e=>Math.floor(e/2))),s=n.map(((e,t)=>e-r[t]));return n.map(((e,t)=>[r[t],s[t]]))}([h.filterHeight,h.filterWidth],d):[[0,0],[0,0]];const p=1===d[0]&&1===d[1],[g,m]=function(e,t,n){const r=n.map((e=>e[0])),s=n.map((e=>e[1])),o=e.concat(r,s),a=t.map(((e,t)=>(e-o[t]%e)%e)),i=s.map(((e,t)=>e+a[t])),l=t.map(((e,t)=>[r[t],i[t]])),u=t.map(((e,t)=>[0,a[t]]));return[l,u]}([h.inHeight,h.inWidth],d,f),b=p?r:"valid",y=p?u:wu(u,d,g),w=("avg"===n?()=>Qa(y,t,o,b,a):()=>Zl(y,t,o,b,a))(),k=p?w:ii(w,d,m);return c?Xa(k,[k.shape[1],k.shape[2],k.shape[3]]):k}});const vu=oo({prelu_:function(e,t){const n={x:no(e,"x","prelu"),alpha:no(t,"alpha","prelu")};return Hs.runKernel("Prelu",n)}});const xu=oo({prod_:function(e,t=null,n=!1){let r=no(e,"x","prod");"bool"===r.dtype&&(r=wa(r,"int32"));const s={x:r},o={axis:t,keepDims:n};return Hs.runKernel("Prod",s,o)}});const Eu=oo({raggedGather_:function(e,t,n,r){const s={paramsNestedSplits:e.map(((e,t)=>no(e,`tensors${t}`,"raggedGather","int32"))),paramsDenseValues:no(t,"paramsDenseValues","raggedGather"),indices:no(n,"indices","raggedGather","int32")},o={outputRaggedRank:r},a=Hs.runKernel("RaggedGather",s,o);return{outputNestedSplits:a.slice(0,a.length-1),outputDenseValues:a[a.length-1]}}});const Su=oo({raggedRange_:function(e,t,n){const r=no(e,"starts","raggedRange"),s={starts:r,limits:no(t,"limits","raggedRange",r.dtype),deltas:no(n,"deltas","raggedRange",r.dtype)},o=Hs.runKernel("RaggedRange",s);return{rtNestedSplits:o[0],rtDenseValues:o[1]}}});const $u=oo({raggedTensorToTensor_:function(e,t,n,r,s){const o=no(e,"shape","raggedTensorToTensor","int32"),a=no(t,"values","raggedTensorToTensor"),i={shape:o,values:a,defaultValue:no(n,"defaultValue","raggedTensorToTensor",a.dtype),rowPartitionTensors:r.map(((e,t)=>no(e,`tensors${t}`,"raggedTensorToTensor","int32")))},l={rowPartitionTypes:s};return Hs.runKernel("RaggedTensorToTensor",i,l)}});const Au=oo({rand_:function(e,t,n){F(e);const r=c(e);let s=null;if(null==n||"float32"===n)s=new Float32Array(r);else if("int32"===n)s=new Int32Array(r);else{if("bool"!==n)throw new Error(`Unknown data type ${n}`);s=new Uint8Array(r)}for(let e=0;e>>0,t=(r*=t)>>>0,t+=4294967296*(r-=t)}return 2.3283064365386963e-10*(t>>>0)});n.next=function(){var e=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=e-(n.c=0|e)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(e),n.s0<0&&(n.s0+=1),n.s1-=r(e),n.s1<0&&(n.s1+=1),n.s2-=r(e),n.s2<0&&(n.s2+=1),r=null}function s(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function o(e,t){var n=new r(e),o=t&&t.state,a=n.next;return a.int32=function(){return 4294967296*n.next()|0},a.double=function(){return a()+11102230246251565e-32*(2097152*a()|0)},a.quick=a,o&&("object"==typeof o&&s(o,n),a.state=function(){return s(n,{})}),a}t&&t.exports?t.exports=o:n&&n.amd?n((function(){return o})):this.alea=o}(0,_u,!1);var Iu=_u.exports,Mu={exports:{}};!function(e,t,n){function r(e){var t=this,n="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:n+=e;for(var r=0;r>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,o&&("object"==typeof o&&s(o,n),a.state=function(){return s(n,{})}),a}t&&t.exports?t.exports=o:n&&n.amd?n((function(){return o})):this.xor128=o}(0,Mu,!1);var Nu=Mu.exports,Tu={exports:{}};!function(e,t,n){function r(e){var t=this,n="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:n+=e;for(var r=0;r>>4),t.next()}function s(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function o(e,t){var n=new r(e),o=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,o&&("object"==typeof o&&s(o,n),a.state=function(){return s(n,{})}),a}t&&t.exports?t.exports=o:n&&n.amd?n((function(){return o})):this.xorwow=o}(0,Tu,!1);var Du=Tu.exports,Ru={exports:{}};!function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.x,s=t.i;return e=r[s],n=(e^=e>>>7)^e<<24,n^=(e=r[s+1&7])^e>>>10,n^=(e=r[s+3&7])^e>>>3,n^=(e=r[s+4&7])^e<<7,e=r[s+7&7],n^=(e^=e<<13)^e<<9,r[s]=n,t.i=s+1&7,n},function(e,t){var n,r=[];if(t===(0|t))r[0]=t;else for(t=""+t,n=0;n0;--n)e.next()}(t,e)}function s(e,t){return t.x=e.x.slice(),t.i=e.i,t}function o(e,t){null==e&&(e=+new Date);var n=new r(e),o=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,o&&(o.x&&s(o,n),a.state=function(){return s(n,{})}),a}t&&t.exports?t.exports=o:n&&n.amd?n((function(){return o})):this.xorshift7=o}(0,Ru,!1);var Fu=Ru.exports,Bu={exports:{}};!function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.w,s=t.X,o=t.i;return t.w=r=r+1640531527|0,n=s[o+34&127],e=s[o=o+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=s[o]=n^e,t.i=o,n+(r^r>>>16)|0},function(e,t){var n,r,s,o,a,i=[],l=128;for(t===(0|t)?(r=t,t=null):(t+="\0",r=0,l=Math.max(l,t.length)),s=0,o=-32;o>>15,r^=r<<4,r^=r>>>13,o>=0&&(a=a+1640531527|0,s=0==(n=i[127&o]^=r+a)?s+1:0);for(s>=128&&(i[127&(t&&t.length||0)]=-1),s=127,o=512;o>0;--o)r=i[s+34&127],n=i[s=s+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,i[s]=r^n;e.w=a,e.X=i,e.i=s}(t,e)}function s(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function o(e,t){null==e&&(e=+new Date);var n=new r(e),o=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,o&&(o.X&&s(o,n),a.state=function(){return s(n,{})}),a}t&&t.exports?t.exports=o:n&&n.amd?n((function(){return o})):this.xor4096=o}(0,Bu,!1);var Cu=Bu.exports,Pu={exports:{}};!function(e,t,n){function r(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,r=t.d,s=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^s,s=s-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^s,t.a=s-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):n+=e;for(var r=0;r>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,o&&("object"==typeof o&&s(o,n),a.state=function(){return s(n,{})}),a}t&&t.exports?t.exports=o:n&&n.amd?n((function(){return o})):this.tychei=o}(0,Pu,!1);var Ou,Lu=Pu.exports,zu={exports:{}};Ou=zu,function(e,t,n){var r,s=256,o=n.pow(s,6),a=n.pow(2,52),i=2*a,l=255;function u(l,u,g){var m=[],b=f(d((u=1==u?{entropy:!0}:u||{}).entropy?[l,p(t)]:null==l?function(){try{var n;return r&&(n=r.randomBytes)?n=n(s):(n=new Uint8Array(s),(e.crypto||e.msCrypto).getRandomValues(n)),p(n)}catch(n){var o=e.navigator,a=o&&o.plugins;return[+new Date,e,a,e.screen,p(t)]}}():l,3),m),y=new c(m),w=function(){for(var e=y.g(6),t=o,n=0;e=i;)e/=2,t/=2,n>>>=1;return(e+n)/t};return w.int32=function(){return 0|y.g(4)},w.quick=function(){return y.g(4)/4294967296},w.double=w,f(p(y.S),t),(u.pass||g||function(e,t,r,s){return s&&(s.S&&h(s,y),e.state=function(){return h(y,{})}),r?(n.random=e,t):e})(w,b,"global"in u?u.global:this==n,u.state)}function c(e){var t,n=e.length,r=this,o=0,a=r.i=r.j=0,i=r.S=[];for(n||(e=[n++]);on)}var Xu={__proto__:null,TEST_EPSILON_FLOAT16:.1,createVideoElement:function(e){const t=document.createElement("video");return"playsInline"in t&&(t.playsInline=!0),t.muted=!0,t.loop=!0,t.style.position="fixed",t.style.left="0px",t.style.top="0px",t.preload="auto",t.appendChild(e),new Promise((e=>{t.addEventListener("loadeddata",(n=>e(t))),t.load()}))},encodeStrings:function e(t){for(let n=0;nYu(e,t,n)))},expectArraysEqual:function(e,t){const n="string"==typeof t||"number"==typeof t||"boolean"==typeof t?[t]:t;return E(e)||E(e[0])||E(t)||E(t[0])?Zu(e,n,((e,t)=>e==t)):Zu(e,t,((e,t)=>Yu(e,t,0)))},expectNumbersClose:function(e,t,n){if(null==n&&(n=Ju()),!Yu(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`);"undefined"!=typeof expect&&expect().nothing()},expectPromiseToFail:function(e,t){e().then((()=>t.fail()),(()=>t())),"undefined"!=typeof expect&&expect().nothing()},expectValuesInRange:function(e,t,n){for(let r=0;rn)throw new Error(`Value out of range:${e[r]} low: ${t}, high: ${n}`)},play:async function(e){await e.play(),"requestVideoFrameCallback"in e&&await new Promise((t=>{e.requestVideoFrameCallback(t)}))},testEpsilon:Ju};class Qu{constructor(e,t,n,r,s){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);const o=s||Math.random();this.random=ju.alea(o.toString())}nextValue(){if(!isNaN(this.nextVal)){const e=this.nextVal;return this.nextVal=NaN,e}let e,t,n=!1;for(;!n;){let r,s,o;do{r=2*this.random()-1,s=2*this.random()-1,o=r*r+s*s}while(o>=1||0===o);const a=Math.sqrt(-2*Math.log(o)/o);e=this.mean+this.stdDev*r*a,t=this.mean+this.stdDev*s*a,this.truncated&&!this.isValidTruncated(e)||(n=!0)}return this.truncated&&!this.isValidTruncated(t)||(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return null==this.dtype||"float32"===this.dtype?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}}class ec{constructor(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n;const s=r||Math.random();this.randu=ju.alea(s.toString()),this.randn=new Qu(0,1,n,!1,this.randu()),this.d=e<1?e+2/3:e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,r,s,o;for(;;){do{r=this.randn.nextValue(),o=1+this.c*r}while(o<=0);if(o*=o*o,e=r*r,t=1-.331*e*e,n=.5*e+this.d*(1-o+Math.log(o)),s=this.randu(),snull==this.dtype||"float32"===this.dtype,this.min=e,this.range=t-e,this.dtype=n,null==r&&(r=Math.random()),"number"==typeof r&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=ju.alea(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}const nc=oo({randomGamma_:function(e,t,n=1,r="float32",s){if(F(e),null==n&&(n=1),null==r&&(r="float32"),"float32"!==r&&"int32"!==r)throw new Error(`Unsupported data type ${r}`);const o=new ec(t,n,r,s),a=ya(e,r);for(let e=0;e`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`)),dc(t,0)}});const pc=oo({reverse2d_:function(e,t){const n=no(e,"x","reverse");return i(2===n.rank,(()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`)),dc(n,t)}});const gc=oo({reverse3d_:function(e,t){const n=no(e,"x","reverse");return i(3===n.rank,(()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`)),dc(n,t)}});const mc=oo({reverse4d_:function(e,t){const n=no(e,"x","reverse");return i(4===n.rank,(()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`)),dc(n,t)}});const bc=oo({round_:function(e){const t={x:no(e,"x","round")};return Hs.runKernel("Round",t)}});const yc=oo({rsqrt_:function(e){const t={x:no(e,"x","rsqrt","float32")};return Hs.runKernel("Rsqrt",t)}});const wc=oo({selu_:function(e){const t={x:no(e,"x","selu")};return Hs.runKernel("Selu",t)}});const kc=oo({separableConv2d_:function(e,t,n,r,s,o=[1,1],a="NHWC"){const l=no(e,"x","separableConv2d"),u=no(t,"depthwiseFilter","separableConv2d"),c=no(n,"pointwiseFilter","separableConv2d");let h=l,d=!1;if(3===l.rank&&(d=!0,h=Xa(l,[1,l.shape[0],l.shape[1],l.shape[2]])),"NCHW"===a)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");i(4===h.rank,(()=>`Error in separableConv2d: input must be rank 4, but got rank ${h.rank}.`)),i(4===u.rank,(()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${u.rank}.`)),i(4===c.rank,(()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${u.rank}.`)),i(1===c.shape[0],(()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${c.shape[0]}.`)),i(1===c.shape[1],(()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${c.shape[1]}.`));const f=u.shape[2],p=u.shape[3];i(c.shape[2]===f*p,(()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${f*p}, but got ${c.shape[2]}.`));const g=Ci(h,u,r,s,a,o),m=Ei(g,c,1,"valid",a);return d?Xa(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const vc=async function(e,t){const n=no(e,"x","setdiff1d"),r=no(t,"y","setdiff1d");i(n.dtype===r.dtype,(()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${r.dtype}).`)),i(1===n.rank,(()=>`x should be 1D tensor, but got x (${n.shape}).`)),i(1===r.rank,(()=>`y should be 1D tensor, but got y (${r.shape}).`));const s=await n.data(),o=await r.data(),a=new Set(o);let l=0;for(let e=0;e`slice1d expects a rank-1 tensor, but got a rank-${r.rank} tensor`)),si(r,[t],[n])}});const Ac=oo({slice2d_:function(e,t,n){const r=no(e,"x","slice2d");return i(2===r.rank,(()=>`slice2d expects a rank-2 tensor, but got a rank-${r.rank} tensor`)),si(r,t,n)}});const _c=oo({slice3d_:function(e,t,n){const r=no(e,"x","slice3d");return i(3===r.rank,(()=>`slice3d expects a rank-3 tensor, but got a rank-${r.rank} tensor`)),si(r,t,n)}});const Ic=oo({slice4d_:function(e,t,n){const r=no(e,"x","slice4d");return i(4===r.rank,(()=>`slice4d expects a rank-4 tensor, but got a rank-${r.rank} tensor`)),si(r,t,n)}});const Mc=oo({softmax_:function(e,t=-1){const n=no(e,"logits","softmax","float32");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);const r={logits:n},s={dim:t};return Hs.runKernel("Softmax",r,s)}});const Nc=oo({fft_:function(e){i("complex64"===e.dtype,(()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`));const t={input:e};return Hs.runKernel("FFT",t)}});const Tc=oo({ifft_:function(e){i("complex64"===e.dtype,(()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`));const t={input:e};return Hs.runKernel("IFFT",t)}});const Dc=oo({irfft_:function(e){const t=e.shape[e.shape.length-1],n=e.size/t;let r;if(t<=2){const s=Xa(e,[n,t]);r=Tc(s)}else{const s=[n,2*(t-1)],o=Xa(lc(e),[n,t]),a=Xa(kl(e),[n,t]),i=dc(si(o,[0,1],[n,t-2]),1),l=$a(dc(si(a,[0,1],[n,t-2]),1),sl(-1)),u=ti([o,i],1),c=ti([a,l],1),h=Xa(ao(u,c),[s[0],s[1]]);r=Tc(h)}if(r=lc(r),3===e.rank&&0!==e.shape[0]){const t=r,n=e.shape[0];r=Xa(r,[n,r.shape[0]/n,r.shape[1]]),t.dispose()}return r}});const Rc=oo({split_:function(e,t,n=0){const r={x:no(e,"x","split")},s={numOrSizeSplits:t,axis:n};return Hs.runKernel("SplitV",r,s)}});const Fc=oo({rfft_:function(e,t){i("float32"===e.dtype,(()=>`The dtype for rfft() must be real value but got ${e.dtype}`));let n=e.shape[e.shape.length-1];const r=e.size/n;let s;if(null!=t&&t0)),o=e.shape.map((e=>e));o[e.shape.length-1]=t,s=si(e,r,o),n=t}else if(null!=t&&t>n){const r=e.shape.map((e=>e));r[e.shape.length-1]=t-n,s=ti([e,tu(r)],e.shape.length-1),n=t}else s=e;const o=qi(s),a=Xa(ao(s,o),[r,n]),l=Nc(a),u=Math.floor(n/2)+1,c=lc(l),h=kl(l),d=Rc(c,[u,n-u],c.shape.length-1),f=Rc(h,[u,n-u],h.shape.length-1),p=s.shape.slice();return p[s.shape.length-1]=u,Xa(ao(d[0],f[0]),p)}});const Bc=oo({squaredDifference_:function(e,t){let n=no(e,"a","squaredDifference"),r=no(t,"b","squaredDifference");[n,r]=Os(n,r),Ui(n.shape,r.shape);const s={a:n,b:r};return Hs.runKernel("SquaredDifference",s,{})}});const Cc=oo({squeeze_:function(e,t){const n=no(e,"x","squeeze","string_or_numeric");return Xa(n,m(n.shape,t).newShape)}});const Pc=oo({stack_:function(e,t=0){const n=ro(e,"tensors","stack","string_or_numeric");i(n.length>=1,(()=>"Pass at least one tensor to tf.stack")),n.length>0&&i(t<=n[0].rank,(()=>"Axis must be <= rank of the tensor"));const r=n,s={axis:t};return Hs.runKernel("Pack",r,s)}});const Oc=oo({step_:function(e,t=0){const n={x:no(e,"x","step")},r={alpha:t};return Hs.runKernel("Step",n,r)}});const Lc=oo({stridedSlice_:function(e,t,n,r,s=0,o=0,a=0,i=0,l=0){const u={x:no(e,"x","stridedSlice","string_or_numeric")},c={begin:t,end:n,strides:r,beginMask:s,endMask:o,ellipsisMask:a,newAxisMask:i,shrinkAxisMask:l};return Hs.runKernel("StridedSlice",u,c)}});const zc=oo({tan_:function(e){const t={x:no(e,"x","tan","float32")};return Hs.runKernel("Tan",t)}});function Uc(e,t){u(e);const n=Qs(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return io(e,null,n,t)}function Wc(e,t,n){if(u(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const r=Qs(e,n);if(2!==r.length&&1!==r.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return io(e,t,r,n)}function Gc(e,t,n){if(u(e),null!=t&&3!==t.length)throw new Error("tensor3d() requires shape to have three numbers");const r=Qs(e,n);if(3!==r.length&&1!==r.length)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return io(e,t,r,n)}function Kc(e,t,n){if(u(e),null!=t&&4!==t.length)throw new Error("tensor4d() requires shape to have four numbers");const r=Qs(e,n);if(4!==r.length&&1!==r.length)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return io(e,t,r,n)}function qc(e,t,n){if(u(e),null!=t&&5!==t.length)throw new Error("tensor5d() requires shape to have five numbers");const r=Qs(e,n);if(5!==r.length&&1!==r.length)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return io(e,t,r,n)}function Vc(e,t,n){if(u(e),null!=t&&6!==t.length)throw new Error("tensor6d() requires shape to have six numbers");const r=Qs(e,n);if(6!==r.length&&1!==r.length)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(1===r.length&&null==t)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return io(e,t=t||r,r,n)}function Hc(e,t,n){const r=t.rank>1?t.shape[t.rank-1]:1,s=t.rank>1?t.rank-1:1,o=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${r}, and batchDim: ${s}.`;if(n.rank1?t.shape[r-1]:1,o=n.length;let a=1;for(let e=s;e= 0 but got ${t}`);if(t>s)throw new Error(`'k' passed to topk() must be <= the last dimension (${s}) but got ${t}`);const o={x:r},a={k:t,sorted:n},[i,l]=Hs.runKernel("TopK",o,a);return{values:i,indices:l}}});const Qc=oo({truncatedNormal_:function(e,t=0,n=1,r,s){if(F(e),null!=r&&"bool"===r)throw new Error("Unsupported data type $ { dtype }");const o=new Qu(t,n,r,!0,s),a=ya(e,r);for(let e=0;e0,(()=>"The input tensor must be at least 1D"));const r={x:n},s={axis:t},[o,a]=Hs.runKernel("Unique",r,s);return{values:o,indices:a}}});const th=oo({unsortedSegmentSum_:function(e,t,n){const r=no(e,"x","unsortedSegmentSum"),s=no(t,"segmentIds","unsortedSegmentSum","int32");i(f(n),(()=>"numSegments must be of dtype int"));const o={x:r,segmentIds:s},a={numSegments:n};return Hs.runKernel("UnsortedSegmentSum",o,a)}});const nh=oo({unstack_:function(e,t=0){const n=no(e,"x","unstack","string_or_numeric");i(t>=-n.shape.length&&t`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`));const r={value:n},s={axis:t};return Hs.runKernel("Unpack",r,s)}});function rh(e,t){return jl(e,t,"right")}function sh(e,t=!0,n,r){return Hs.makeVariable(e,t,n,r)}function oh(e,t){const n=[];for(let e=0;e0,(()=>"mask cannot be scalar")),l(u.slice(o,o+a),s.shape,"mask's shape must match the first K dimensions of tensor's shape,");let c=1;for(let e=o;et)).reverse()),i(r.rank===t.length,(()=>`Error in transpose: rank of input ${r.rank} must match length of perm ${t}.`)),t.forEach((e=>{i(e>=0&&e"All entries in 'perm' must be between 0 and "+(r.rank-1)+` but got ${t}`))})),r.rank<=1)return r.clone();const s={x:r},o={perm:t};return"complex64"===r.dtype?ko((()=>{let e=lc(r),t=kl(r);return e=Hs.runKernel("Transpose",{x:e},o),t=Hs.runKernel("Transpose",{x:t},o),n&&(t=Ol(t)),ao(e,t)})):Hs.runKernel("Transpose",s,o)}});const uh=oo({movingAverage_:function(e,t,n,r,s=!0){const o=no(e,"v","movingAverage"),a=no(t,"x","movingAverage"),l=no(n,"decay","movingAverage");Ls(o,a),i(d(o.shape,a.shape),(()=>"Shape mismatch in v and x"));const u=sl(1),c=Ul(u,l);let h=$a(Ul(a,o),c);if(s){i(null!=r,(()=>"When using zeroDebias: true, step is required."));const e=no(r,"step","movingAverage");h=Sa(h,Ul(u,rl(l,e)))}return xa(o,h)}});const ch=oo({scatterND_:function(e,t,n){F(n);const r=no(e,"indices","scatterND","int32"),s=no(t,"updates","scatterND");jc(s,r,n);const o={indices:r,updates:s},a={shape:n};return Hs.runKernel("ScatterNd",o,a)}});const hh=oo({sparseToDense_:function(e,t,n,r=0){F(n);const s=no(e,"sparseIndices","sparseToDense","int32"),o=no(t,"sparseValues","sparseToDense","string_or_numeric"),a=no(r,"defaultValue","sparseToDense",o.dtype);!function(e,t,n,r){if("int32"!==e.dtype)throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);const s=e.rank>0?e.shape[0]:1,o=e.rank>1?e.shape[1]:1;if(n.length!==o)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${o}.`);const a=t.size;if(0!==t.rank&&(1!==t.rank||a!==s))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${s}]`);if(t.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(s,o,n,a);const i={sparseIndices:s,sparseValues:o,defaultValue:a},l={outputShape:n};return Hs.runKernel("SparseToDense",i,l)}});const dh=oo({gatherND_:function(e,t){const n=no(t,"indices","gatherND","int32"),r={params:no(e,"x","gatherND","string_or_numeric"),indices:n};return Hs.runKernel("GatherNd",r)}});const fh=oo({dropout_:function(e,t,n,r){const s=no(e,"x","dropout");if(i("float32"===s.dtype,(()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${s.dtype} tensor instead.`)),i(t>=0&&t<1,(()=>`rate must be a float in the range [0, 1), but got ${t}.`)),0===t)return e instanceof $s?s.clone():s;const o=function(e,t){if(null==t)return e.shape.slice();if(d(e.shape,t))return t;if(e.shape.length===t.length){const n=[];for(let r=0;r1,(()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${r.rank}`)),i(r.rank-1===s.rank,(()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${r.rank} and targets rank ${s.rank}`)),l(r.shape.slice(0,r.shape.length-1),s.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const o=r.shape[r.shape.length-1];i(n>0&&n<=o,(()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${o}), but got ${n}`));const a=await r.data(),u=await s.data(),[c,h]=[a.length/o,o],d=b("bool",c);for(let e=0;et.value-e.value)),d[e]=0;for(let t=0;t`Error in conv2dDerFilter: input must be rank 4, but got shape ${l.shape}.`)),i(4===u.rank,(()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${u.shape}.`)),i(4===n.length,(()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`));const c="NHWC"===o?l.shape[3]:l.shape[1],h="NHWC"===o?u.shape[3]:u.shape[1];i(c===n[2],(()=>`Error in conv2dDerFilter: depth of input ${c}) must match input depth in filter (${n[2]}.`)),i(h===n[3],(()=>`Error in conv2dDerFilter: depth of dy (${h}) must match output depth for filter (${n[3]}).`)),Ya("conv2dDerFilter",s,a);const d={x:l,dy:u},f={strides:r,pad:s,dataFormat:o,dimRoundingMode:a,filterShape:n};return Hs.runKernel("Conv2DBackpropFilter",d,f)}});function yh(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return $a(e,Oc(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function wh(e,t){let n=t;const r=zi(e.shape,t.shape);return r.length>0&&(n=il(n,r)),Xa(n,e.shape)}function kh(e,t,n,r){if("linear"===t)return e;if("relu"===t)return cc(e);if("elu"===t)return Ji(e);if("relu6"===t)return hc(e);if("prelu"===t)return vu(e,n);if("leakyrelu"===t)return Sl(e,r);if("sigmoid"===t)return ri(e);throw new Error(`Unknown fused activation ${t}.`)}const vh=(e,t)=>!(e>0)||"linear"===t;const xh=oo({fusedConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:s="NHWC",dilations:o=[1,1],dimRoundingMode:a,bias:l,activation:u="linear",preluActivationWeights:c,leakyreluAlpha:h}){if(u=u||"linear",!1===vh(Hs.state.gradientDepth,u)){i("NHWC"===s,(()=>`Error in fused conv2d: got dataFormat of ${s} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`));let d=Ei(e,t,n,r,s,o,a);return null!=l&&(d=xa(d,l)),kh(d,u,c,h)}const d=no(e,"x","conv2d","float32"),f=no(t,"filter","conv2d","float32");let p=d,g=!1;3===d.rank&&(g=!0,p=Xa(d,[1,d.shape[0],d.shape[1],d.shape[2]])),i(4===p.rank,(()=>`Error in fused conv2d: input must be rank 4, but got rank ${p.rank}.`)),i(4===f.rank,(()=>`Error in fused conv2d: filter must be rank 4, but got rank ${f.rank}.`)),Ya("fused conv2d",r,a);const m="NHWC"===s?p.shape[3]:p.shape[1];i(f.shape[2]===m,(()=>`Error in conv2d: depth of input (${m}) must match input depth for filter ${f.shape[2]}.`)),i(ja(n,o),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`));const b=za(p.shape,f.shape,n,o,r,a);let y,w;if(null!=l&&(y=no(l,"bias","fused conv2d"),[y]=Os(y,d),"NHWC"===s?Ui(b.outShape,y.shape):(i(y.shape.length<=1,(()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${y.shape.length}.`)),i(0===y.shape.length||y.shape[0]===b.outChannels||1===y.shape[0],(()=>`Error in fused conv2d: bias shape (${y.shape}) is not compatible with the number of output channels (${b.outChannels})`)))),null!=c){const e=c.shape;if(i(e.length<=1||3===e.length,(()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${e.length}.`)),1===e.length)i(1===e[0]||e[0]===b.outChannels,(()=>`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the number of output channels (${b.outChannels}).`));else if(3===e.length)try{Ui(e,b.outShape)}catch(t){const n=`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the output shape of the conv2d (${b.outShape}).`;throw Error(n)}w=no(c,"prelu weights","fused conv2d")}const k=(e,t)=>{i("NHWC"===s,(()=>`Error in gradient of fused conv2D: got dataFormat of ${s} but only NHWC is currently supported.`));const[a,l,c,h]=t,d=yh(e,c,u);i(Ha(o),(()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${o}'`));const f=[$i(l.shape,d,a,n,r),bh(l,d,a.shape,n,r)];if(null!=h){const e=wh(h,d);f.push(e)}return f},v={x:p,filter:f,bias:y,preluActivationWeights:w},x={strides:n,pad:r,dataFormat:s,dilations:o,dimRoundingMode:a,activation:u,leakyreluAlpha:h};if(null==l){const e=Cl(((e,t,n)=>{let r=Hs.runKernel("FusedConv2D",v,x);return n([t,e,r]),g&&(r=Xa(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:k}}));return e(p,f)}{const e=Cl(((e,t,n,r)=>{let s=Hs.runKernel("FusedConv2D",v,x);return r([t,e,s,n]),g&&(s=Xa(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:k}}));return e(p,f,y)}}});const Eh=oo({depthwiseConv2dNativeBackpropFilter_:function(e,t,n,r,s,o=[1,1],a){let i=e;3===e.rank&&(i=Xa(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;3===l.rank&&(l=Xa(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const u={x:i,dy:l},c={strides:r,pad:s,dimRoundingMode:a,dilations:o,filterShape:n};return Hs.runKernel("DepthwiseConv2dNativeBackpropFilter",u,c)}});const Sh=oo({depthwiseConv2dNativeBackpropInput_:function(e,t,n,r,s,o=[1,1],a){let i=t,l=!1;3===t.rank&&(l=!0,i=Xa(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const u={dy:i,filter:n},c={strides:r,pad:s,dimRoundingMode:a,dilations:o,inputShape:e},h=Hs.runKernel("DepthwiseConv2dNativeBackpropInput",u,c);return l?Xa(h,[h.shape[1],h.shape[2],h.shape[3]]):h}});const $h=oo({fusedDepthwiseConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:s="NHWC",dilations:o=[1,1],dimRoundingMode:a,bias:l,activation:u="linear",preluActivationWeights:c,leakyreluAlpha:h}){if(!1===vh(Hs.state.gradientDepth,u)){let i=Ci(e,t,n,r,s,o,a);return null!=l&&(i=xa(i,l)),kh(i,u,c,h)}const d=no(e,"x","depthwiseConv2d","float32"),f=no(t,"filter","depthwiseConv2d","float32");let p=d,g=!1;3===d.rank&&(g=!0,p=Xa(d,[1,d.shape[0],d.shape[1],d.shape[2]])),i(4===p.rank,(()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${p.rank}.`)),i(4===f.rank,(()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${f.rank}.`)),i(p.shape[3]===f.shape[2],(()=>`Error in fused depthwiseConv2d: number of input channels (${p.shape[3]}) must match the inChannels dimension in filter ${f.shape[2]}.`)),null==o&&(o=[1,1]),i(ja(n,o),(()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`)),Ya("fused depthwiseConv2d",r,a);const m=za(p.shape,f.shape,n,o,r,a,!0);let b,y;null!=l&&(b=no(l,"bias","fused conv2d"),[b]=Os(b,d),Ui(m.outShape,b.shape)),null!=c&&(y=no(c,"prelu weights","fused depthwiseConv2d"));const w=(e,t)=>{i(Ha(o),(()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`));const[s,l,c,h]=t,d=yh(e,c,u),f=Sh(l.shape,d,s,n,r,o,a),p=Eh(l,d,s.shape,n,r,o,a);if(null!=h){return[f,p,wh(b,d)]}return[f,p]},k={x:p,filter:f,bias:b,preluActivationWeights:y},v={strides:n,pad:r,dataFormat:s,dilations:o,dimRoundingMode:a,activation:u,leakyreluAlpha:h};if(null==l){const e=Cl(((e,t,n)=>{let r=Hs.runKernel("FusedDepthwiseConv2D",k,v);return n([t,e,r]),g&&(r=Xa(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:w}}));return e(p,f)}{const e=Cl(((e,t,n,r)=>{let s=Hs.runKernel("FusedDepthwiseConv2D",k,v);return r([t,e,s,n]),g&&(s=Xa(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:w}}));return e(p,f,b)}}});const Ah=oo({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:r=!1,bias:s,activation:o="linear",preluActivationWeights:a,leakyreluAlpha:l=.2}){if(!1===vh(Hs.state.gradientDepth,o)){let i=ni(e,t,n,r);return null!=s&&(i=xa(i,s)),kh(i,o,a,l)}let u=no(e,"a","fused matMul"),h=no(t,"b","fused matMul");[u,h]=Os(u,h);const d=n?u.shape[u.rank-2]:u.shape[u.rank-1],f=r?h.shape[h.rank-1]:h.shape[h.rank-2],p=n?u.shape[u.rank-1]:u.shape[u.rank-2],g=r?h.shape[h.rank-2]:h.shape[h.rank-1],m=u.shape.slice(0,-2),b=h.shape.slice(0,-2),y=c(m),w=c(b);i(d===f,(()=>`Error in fused matMul: inner shapes (${d}) and (${f}) of Tensors with shapes ${u.shape} and ${h.shape} and transposeA=${n} and transposeB=${r} must match.`));const k=Ui(u.shape.slice(0,-2),h.shape.slice(0,-2)).concat([p,g]),v=Xa(u,n?[y,d,p]:[y,p,d]),x=Xa(h,r?[w,g,f]:[w,f,g]);let E,S;null!=s&&(E=no(s,"bias","fused matMul"),[E]=Os(E,u),Ui(k,E.shape)),null!=a&&(S=no(a,"prelu weights","fused matMul"));const $=(e,t)=>{const[a,i,l,u]=t,c=yh(Xa(e,l.shape),l,o);let h,d;if(n||r?!n&&r?(h=ni(c,i,!1,!1),d=ni(c,a,!0,!1)):n&&!r?(h=ni(i,c,!1,!0),d=ni(a,c,!1,!1)):(h=ni(i,c,!0,!0),d=ni(c,a,!0,!0)):(h=ni(c,i,!1,!0),d=ni(a,c,!0,!1)),null!=s){return[h,d,wh(u,c)]}return[h,d]},A={a:v,b:x,bias:E,preluActivationWeights:S},_={transposeA:n,transposeB:r,activation:o,leakyreluAlpha:l};if(null==s){const e=Cl(((e,t,n)=>{const r=Hs.runKernel("_FusedMatMul",A,_);return n([e,t,r]),{value:Xa(r,k),gradFunc:$}}));return e(v,x)}{const e=Cl(((e,t,n,r)=>{const s=Hs.runKernel("_FusedMatMul",A,_);return r([e,t,s,n]),{value:Xa(s,k),gradFunc:$}}));return e(v,x,E)}}});var _h={__proto__:null,conv2d:xh,depthwiseConv2d:$h,matMul:Ah};const Ih=oo({hammingWindow_:function(e){return gh(e,.54,.46)}});const Mh=oo({hannWindow_:function(e){return gh(e,.5,.5)}});const Nh=oo({frame_:function(e,t,n,r=!1,s=0){let o=0;const a=[];for(;o+t<=e.size;)a.push(si(e,o,t)),o+=n;if(r)for(;o`Error in cropAndResize: image must be rank 4,but got rank ${a.rank}.`)),i(2===l.rank&&4===l.shape[1],(()=>`Error in cropAndResize: boxes must be have size [${c},4] but had shape ${l.shape}.`)),i(1===u.rank&&u.shape[0]===c,(()=>`Error in cropAndResize: boxInd must be have size [${c}] but had shape ${l.shape}.`)),i(2===r.length,(()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${r.length}.`)),i(r[0]>=1&&r[1]>=1,(()=>`cropSize must be atleast [1,1], but was ${r}`)),i("bilinear"===s||"nearest"===s,(()=>`method must be bilinear or nearest, but was ${s}`));const h={image:a,boxes:l,boxInd:u},d={method:s,extrapolationValue:o,cropSize:r};return Hs.runKernel("CropAndResize",h,d)}});const Rh=oo({flipLeftRight_:function(e){const t=no(e,"image","flipLeftRight","float32");i(4===t.rank,(()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`));const n={image:t};return Hs.runKernel("FlipLeftRight",n,{})}});const Fh=oo({grayscaleToRGB_:function(e){const t=no(e,"image","grayscaleToRGB"),n=t.rank-1,r=t.shape[n];i(t.rank>=2,(()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`)),i(1===r,(()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${r}.`));const s=new Array(t.rank);return s.fill(1,0,n),s[n]=3,pl(t,s)}});const Bh=oo({rgbToGrayscale_:function(e){const t=no(e,"image","RGBToGrayscale"),n=t.rank-1,r=t.shape[n];i(t.rank>=2,(()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${t.rank}.`)),i(3===r,(()=>`Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${r}.`));const s=t.dtype,o=wa(t,"float32"),a=Uc([.2989,.587,.114]);let l;switch(t.rank){case 2:l=ji("ij,j->i",o,a);break;case 3:l=ji("ijk,k->ij",o,a);break;case 4:l=ji("ijkl,l->ijk",o,a);break;case 5:l=ji("ijklm,m->ijkl",o,a);break;case 6:l=ji("ijklmn,n->ijklm",o,a);break;default:throw new Error("Not a valid tensor rank.")}return l=dl(l,-1),wa(l,s)}});const Ch=oo({rotateWithOffset_:function(e,t,n=0,r=.5){const s=no(e,"image","rotateWithOffset","float32");i(4===s.rank,(()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${s.rank}.`));const o={image:s},a={radians:t,fillValue:n,center:r};return Hs.runKernel("RotateWithOffset",o,a)}});function Ph(e,t,n,r,s,o){null==r&&(r=.5),null==s&&(s=Number.NEGATIVE_INFINITY),null==o&&(o=0);const a=e.shape[0];return n=Math.min(n,a),i(0<=r&&r<=1,(()=>`iouThreshold must be in [0, 1], but was '${r}'`)),i(2===e.rank,(()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`)),i(4===e.shape[1],(()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`)),i(1===t.rank,(()=>"scores must be a 1D tensor")),i(t.shape[0]===a,(()=>`scores has incompatible shape with boxes. Expected ${a}, but was ${t.shape[0]}`)),i(0<=o&&o<=1,(()=>`softNmsSigma must be in [0, 1], but was '${o}'`)),{maxOutputSize:n,iouThreshold:r,scoreThreshold:s,softNmsSigma:o}}const Oh=oo({nonMaxSuppression_:function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY){const o=no(e,"boxes","nonMaxSuppression","float32"),a=no(t,"scores","nonMaxSuppression","float32"),i=Ph(o,a,n,r,s),l={maxOutputSize:n=i.maxOutputSize,iouThreshold:r=i.iouThreshold,scoreThreshold:s=i.scoreThreshold};return Hs.runKernel("NonMaxSuppressionV3",{boxes:o,scores:a},l)}});function Lh(e,t,n){const r=function(e,t,n){return function(e,t,n){let r=0,s=e.length,o=0,a=!1;for(;r>>1);const i=n(t,e[o]);i>0?r=o+1:(s=o,a=!i)}return a?r:-r-1}(e,t,n||zh)}(e,t,n),s=r<0?-(r+1):r;e.splice(s,0,t)}function zh(e,t){return e>t?1:es&&u.push({score:t[e],boxIndex:e,suppressBeginIndex:0});u.sort(Hh);const c=o>0?-.5/o:0,h=[],d=[];for(;h.length0;){const t=u.pop(),{score:n,boxIndex:o,suppressBeginIndex:a}=t;if(n=a;--n){const a=qh(e,o,h[n]);if(a>=r){i=!0;break}if(t.score=t.score*Vh(r,c,a),t.score<=s)break}t.suppressBeginIndex=h.length,i||(t.score===n?(h.push(o),d.push(t.score)):t.score>s&&Lh(u,t,Hh))}const f=h.length,p=n-f;i&&p>0&&(h.push(...new Array(p).fill(0)),d.push(...new Array(p).fill(0)));const g={selectedIndices:h};return a&&(g.selectedScores=d),l&&(g.validOutputs=f),g}function qh(e,t,n){const r=e.subarray(4*t,4*t+4),s=e.subarray(4*n,4*n+4),o=Math.min(r[0],r[2]),a=Math.min(r[1],r[3]),i=Math.max(r[0],r[2]),l=Math.max(r[1],r[3]),u=Math.min(s[0],s[2]),c=Math.min(s[1],s[3]),h=Math.max(s[0],s[2]),d=Math.max(s[1],s[3]),f=(i-o)*(l-a),p=(h-u)*(d-c);if(f<=0||p<=0)return 0;const g=Math.max(o,u),m=Math.max(a,c),b=Math.min(i,h),y=Math.min(l,d),w=Math.max(b-g,0)*Math.max(y-m,0);return w/(f+p-w)}function Vh(e,t,n){const r=Math.exp(t*n*n);return n<=e?r:0}function Hh(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}const jh=async function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY){const o=no(e,"boxes","nonMaxSuppressionAsync"),a=no(t,"scores","nonMaxSuppressionAsync"),i=Ph(o,a,n,r,s);n=i.maxOutputSize,r=i.iouThreshold,s=i.scoreThreshold;const l=await Promise.all([o.data(),a.data()]),u=l[0],c=l[1],{selectedIndices:h}=Uh(u,c,n,r,s);return o!==e&&o.dispose(),a!==t&&a.dispose(),Uc(h,"int32")};const Jh=oo({nonMaxSuppressionWithScore_:function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,o=0){const a=no(e,"boxes","nonMaxSuppression"),i=no(t,"scores","nonMaxSuppression"),l=Ph(a,i,n,r,s,o),u={boxes:a,scores:i},c={maxOutputSize:n=l.maxOutputSize,iouThreshold:r=l.iouThreshold,scoreThreshold:s=l.scoreThreshold,softNmsSigma:o=l.softNmsSigma},h=Hs.runKernel("NonMaxSuppressionV5",u,c);return{selectedIndices:h[0],selectedScores:h[1]}}});const Zh=async function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,o=0){const a=no(e,"boxes","nonMaxSuppressionAsync"),i=no(t,"scores","nonMaxSuppressionAsync"),l=Ph(a,i,n,r,s,o);n=l.maxOutputSize,r=l.iouThreshold,s=l.scoreThreshold,o=l.softNmsSigma;const u=await Promise.all([a.data(),i.data()]),c=u[0],h=u[1],{selectedIndices:d,selectedScores:f}=Gh(c,h,n,r,s,o);return a!==e&&a.dispose(),i!==t&&i.dispose(),{selectedIndices:Uc(d,"int32"),selectedScores:Uc(f)}};const Yh=oo({nonMaxSuppressionPadded_:function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,o=!1){const a=no(e,"boxes","nonMaxSuppression"),i=no(t,"scores","nonMaxSuppression"),l=Ph(a,i,n,r,s,null),u={boxes:a,scores:i},c={maxOutputSize:l.maxOutputSize,iouThreshold:l.iouThreshold,scoreThreshold:l.scoreThreshold,padToMaxOutputSize:o},h=Hs.runKernel("NonMaxSuppressionV4",u,c);return{selectedIndices:h[0],validOutputs:h[1]}}});const Xh=async function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,o=!1){const a=no(e,"boxes","nonMaxSuppressionAsync"),i=no(t,"scores","nonMaxSuppressionAsync"),l=Ph(a,i,n,r,s,null),u=l.maxOutputSize,c=l.iouThreshold,h=l.scoreThreshold,[d,f]=await Promise.all([a.data(),i.data()]),{selectedIndices:p,validOutputs:g}=Wh(d,f,u,c,h,o);return a!==e&&a.dispose(),i!==t&&i.dispose(),{selectedIndices:Uc(p,"int32"),validOutputs:sl(g,"int32")}};const Qh=oo({resizeBilinear_:function(e,t,n=!1,r=!1){const s=no(e,"images","resizeBilinear");i(3===s.rank||4===s.rank,(()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${s.rank}.`)),i(2===t.length,(()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`)),i(!1===r||!1===n,(()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false."));let o=s,a=!1;3===s.rank&&(a=!0,o=Xa(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const l={images:o},u={alignCorners:n,halfPixelCenters:r,size:t},c=Hs.runKernel("ResizeBilinear",l,u);return a?Xa(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});const ed=oo({resizeNearestNeighbor_:function(e,t,n=!1,r=!1){const s=no(e,"images","resizeNearestNeighbor");i(3===s.rank||4===s.rank,(()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${s.rank}.`)),i(2===t.length,(()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`)),i("float32"===s.dtype||"int32"===s.dtype,(()=>"`images` must have `int32` or `float32` as dtype")),i(!1===r||!1===n,(()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false."));let o=s,a=!1;3===s.rank&&(a=!0,o=Xa(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const l={images:o},u={alignCorners:n,halfPixelCenters:r,size:t},c=Hs.runKernel("ResizeNearestNeighbor",l,u);return a?Xa(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});const td=oo({threshold_:function(e,t="binary",n=!1,r=.5){const s=no(e,"image","threshold"),o=s.shape[0]*s.shape[1];let a,l,u,c,h=$a(Uc([r]),255);if(i(3===s.rank,(()=>`Error in threshold: image must be rank 3,but got rank ${s.rank}.`)),i(3===s.shape[2]||1===s.shape[2],(()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${s.shape[2]}.`)),i("int32"===s.dtype||"float32"===s.dtype,(()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${s.dtype}.`)),i("otsu"===t||"binary"===t,(()=>`Method must be binary or otsu, but was ${t}`)),3===s.shape[2]){[a,l,u]=Rc(s,[1,1,1],-1);const e=$a(a,.2989),t=$a(l,.587),n=$a(u,.114);c=xa(xa(e,t),n)}else c=e;if("otsu"===t){h=function(e,t){let n,r,s,o,a,i,l=Uc([-1]),u=Uc([0]),c=Uc([0]);for(let h=0;h`Error in transform: image must be rank 4,but got rank ${a.rank}.`)),i(2===l.rank&&(l.shape[0]===a.shape[0]||1===l.shape[0])&&8===l.shape[1],(()=>"Error in transform: Input transform should be batch x 8 or 1 x 8")),i(null==o||2===o.length,(()=>`Error in transform: outputShape must be [height, width] or null, but got ${o}.`));const u={image:a,transforms:l},c={interpolation:n,fillMode:r,fillValue:s,outputShape:o};return Hs.runKernel("Transform",u,c)}});const rd=oo({bandPart_:function(e,t,n){const r=no(e,"a","bandPart");i(r.rank>=2,(()=>`bandPart(): Rank must be at least 2, got ${r.rank}.`));const s=r.shape,[o,a]=r.shape.slice(-2);let l,u;"number"==typeof t?(i(t%1==0,(()=>`bandPart(): numLower must be an integer, got ${t}.`)),i(t<=o,(()=>`bandPart(): numLower (${t}) must not be greater than the number of rows (${o}).`)),l=no(t<0?o:t,"numLower","bandPart")):(i("int32"===t.dtype,(()=>"bandPart(): numLower's dtype must be an int32.")),l=Ki($l(t,0),o,su(t,o))),"number"==typeof n?(i(n%1==0,(()=>`bandPart(): numUpper must be an integer, got ${n}.`)),i(n<=a,(()=>`bandPart(): numUpper (${n}) must not be greater than the number of columns (${a}).`)),u=no(n<0?a:n,"numUpper","bandPart")):(i("int32"===n.dtype,(()=>"bandPart(): numUpper's dtype must be an int32.")),u=Ki($l(n,0),a,su(n,a)));const c=Xa(ic(0,o,1,"int32"),[-1,1]),h=ic(0,a,1,"int32"),d=Ul(c,h),f=Kl(Al(d,l),wl(d,Ol(u))),p=tu([o,a],r.dtype);return Xa(Pc(nh(Xa(r,[-1,o,a])).map((e=>Ki(f,e,p)))),s)}});const sd=oo({gramSchmidt_:function(e){let t;if(Array.isArray(e)){t=!1,i(null!=e&&e.length>0,(()=>"Gram-Schmidt process: input must not be null, undefined, or empty"));const n=e[0].shape[0];for(let t=1;t`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[t].shape[0]} vs. ${n})`))}else t=!0,e=Rc(e,e.shape[0],0).map((e=>Cc(e,[0])));i(e.length<=e[0].shape[0],(()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`));const n=[],r=e;for(let t=0;t{let e=r[t];if(t>0)for(let r=0;r{i(2===e.shape.length,(()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`));const n=e.shape[0],r=e.shape[1];let s=gl(n),o=ka(e);const a=Wc([[1]],[1,1]);let l=ka(a);const u=n>=r?r:n;for(let e=0;e{const t=si(o,[e,e],[n-e,1]),i=ul(t),u=si(o,[e,e],[1,1]),c=Ki(yl(u,0),Wc([[-1]]),Wc([[1]])),h=Ul(u,$a(c,i)),d=Sa(t,h);l=1===d.shape[0]?ka(a):ti([a,si(d,[1,0],[d.shape[0]-1,d.shape[1]])],0);const f=Ol(Sa(ni(c,h),i)),p=si(o,[e,0],[n-e,r]),g=$a(f,l),m=lh(l);if(0===e)o=Ul(p,ni(g,ni(m,p)));else{const t=Ul(p,ni(g,ni(m,p)));o=ti([si(o,[0,0],[e,r]),t],0)}const b=lh(g),y=si(s,[0,e],[n,s.shape[1]-e]);if(0===e)s=Ul(y,ni(ni(y,l),b));else{const t=Ul(y,ni(ni(y,l),b));s=ti([si(s,[0,0],[n,e]),t],1)}return[l,o,s]})),vo([t,i,u])}return!t&&n>r&&(s=si(s,[0,0],[n,r]),o=si(o,[0,0],[r,r])),[s,o]}))}const ad=oo({qr_:function(e,t=!1){if(i(e.rank>=2,(()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`)),2===e.rank)return od(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce(((e,t)=>e*t)),r=nh(Xa(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),s=[],o=[];r.forEach((e=>{const[n,r]=od(e,t);s.push(n),o.push(r)}));return[Xa(Pc(s,0),e.shape),Xa(Pc(o,0),e.shape)]}}});var id;!function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}(id||(id={}));const ld=oo({computeWeightedLoss_:function(e,t,n=id.SUM_BY_NONZERO_WEIGHTS){const r=no(e,"losses","computeWeightedLoss");let s=null;null!=t&&(s=no(t,"weights","computeWeightedLoss"));const o=null==s?r:$a(r,s);if(n===id.NONE)return o;if(n===id.SUM)return il(o);if(n===id.MEAN){if(null==s)return eu(o);{const e=r.size/s.size,t=Sa(il(o),il(s));return e>1?Sa(t,sl(e)):t}}if(n===id.SUM_BY_NONZERO_WEIGHTS){if(null==s)return Sa(il(o),sl(r.size));{const e=$a(s,nu(r.shape)),t=wa(il(cu(e,sl(0))),"float32");return Sa(il(o),t)}}throw Error(`Unknown reduction: ${n}`)}});const ud=oo({absoluteDifference_:function(e,t,n,r=id.SUM_BY_NONZERO_WEIGHTS){const s=no(e,"labels","absoluteDifference"),o=no(t,"predictions","absoluteDifference");let a=null;null!=n&&(a=no(n,"weights","absoluteDifference")),l(s.shape,o.shape,"Error in absoluteDifference: ");const i=Aa(Ul(s,o));return ld(i,a,r)}});const cd=oo({cosineDistance_:function(e,t,n,r,s=id.SUM_BY_NONZERO_WEIGHTS){const o=no(e,"labels","cosineDistance"),a=no(t,"predictions","cosineDistance");let i=null;null!=r&&(i=no(r,"weights","cosineDistance")),l(o.shape,a.shape,"Error in cosineDistance: ");const u=sl(1),c=Ul(u,il($a(o,a),n,!0));return ld(c,i,s)}});const hd=oo({hingeLoss_:function(e,t,n,r=id.SUM_BY_NONZERO_WEIGHTS){let s=no(e,"labels","hingeLoss");const o=no(t,"predictions","hingeLoss");let a=null;null!=n&&(a=no(n,"weights","hingeLoss")),l(s.shape,o.shape,"Error in hingeLoss: ");const i=sl(1);s=Ul($a(sl(2),s),i);const u=cc(Ul(i,$a(s,o)));return ld(u,a,r)}});const dd=oo({huberLoss_:function(e,t,n,r=1,s=id.SUM_BY_NONZERO_WEIGHTS){const o=no(e,"labels","huberLoss"),a=no(t,"predictions","huberLoss");let i=null;null!=n&&(i=no(n,"weights","huberLoss")),l(o.shape,a.shape,"Error in huberLoss: ");const u=sl(r),c=Aa(Ul(a,o)),h=su(c,u),d=Ul(c,h),f=xa($a(sl(.5),al(h)),$a(u,d));return ld(f,i,s)}});const fd=oo({logLoss_:function(e,t,n,r=1e-7,s=id.SUM_BY_NONZERO_WEIGHTS){const o=no(e,"labels","logLoss"),a=no(t,"predictions","logLoss");let i=null;null!=n&&(i=no(n,"weights","logLoss")),l(o.shape,a.shape,"Error in logLoss: ");const u=sl(1),c=sl(r),h=Ol($a(o,Ml(xa(a,c)))),d=$a(Ul(u,o),Ml(xa(Ul(u,a),c))),f=Ul(h,d);return ld(f,i,s)}});const pd=oo({meanSquaredError_:function(e,t,n,r=id.SUM_BY_NONZERO_WEIGHTS){const s=no(e,"labels","meanSquaredError"),o=no(t,"predictions","meanSquaredError");let a=null;null!=n&&(a=no(n,"weights","meanSquaredError")),l(s.shape,o.shape,"Error in meanSquaredError: ");const i=Bc(s,o);return ld(i,a,r)}});const gd=oo({sigmoidCrossEntropy_:function(e,t,n,r=0,s=id.SUM_BY_NONZERO_WEIGHTS){let o=no(e,"multiClassLabels","sigmoidCrossEntropy");const a=no(t,"logits","sigmoidCrossEntropy");let i=null;if(null!=n&&(i=no(n,"weights","sigmoidCrossEntropy")),l(o.shape,a.shape,"Error in sigmoidCrossEntropy: "),r>0){const e=sl(r),t=sl(1),n=sl(.5);o=xa($a(o,Ul(t,e)),$a(n,e))}const u=function(e,t){const n=no(e,"labels","sigmoidCrossEntropyWithLogits"),r=no(t,"logits","sigmoidCrossEntropyWithLogits");l(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");const s=cc(r),o=$a(r,n),a=Nl(hl(Ol(Aa(r))));return xa(Ul(s,o),a)}(o,a);return ld(u,i,s)}});const md=oo({softmaxCrossEntropy_:function(e,t,n,r=0,s=id.SUM_BY_NONZERO_WEIGHTS){let o=no(e,"onehotLabels","softmaxCrossEntropy");const a=no(t,"logits","softmaxCrossEntropy");let i=null;if(null!=n&&(i=no(n,"weights","softmaxCrossEntropy")),l(o.shape,a.shape,"Error in softmaxCrossEntropy: "),r>0){const e=sl(r),t=sl(1),n=sl(o.shape[1]);o=xa($a(o,Ul(t,e)),Sa(e,n))}const u=function(e,t,n=-1){if(-1===n&&(n=t.rank-1),n!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was ${n}`);const r=Cl(((e,t,r)=>{const s=Gl(t,[n],!0),o=Ul(wa(t,"float32"),s);r([e,o]);const a=Ol($a(o,e));return{value:il(a,[n]),gradFunc:(e,t)=>{const[r,s]=t,o=el(e.shape,[n]);return[$a(Xa(e,o),Ul(wa(r,"float32"),hl(s))),$a(Xa(e,o),Ul(hl(s),wa(r,"float32")))]}}}));return r(e,t)}(o,a);return ld(u,i,s)}});const bd=oo({sparseFillEmptyRows_:function(e,t,n,r){const s=no(e,"indices","sparseFillEmptyRows","int32"),o=no(t,"values","sparseFillEmptyRows"),a=no(n,"denseShape","sparseFillEmptyRows","int32"),i=no(r,"defaultValue","sparseFillEmptyRows",o.dtype);if(2!==s.rank)throw new Error(`Indices should be Tensor2D but received shape\n ${s.shape}`);if(1!==o.rank)throw new Error(`Values should be Tensor1D but received shape ${o.shape}`);if(1!==a.rank)throw new Error(`Dense shape should be Tensor1D but received shape ${a.shape}`);if(0!==i.rank)throw new Error(`Default value should be a scalar but received shape ${i.shape}`);const l={indices:s,values:o,denseShape:a,defaultValue:i},u=Hs.runKernel("SparseFillEmptyRows",l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}});const yd=oo({sparseReshape_:function(e,t,n){const r=no(e,"inputIndices","sparseReshape","int32"),s=no(t,"inputShape","sparseReshape","int32"),o=no(n,"newShape","sparseReshape","int32");if(2!==r.rank)throw new Error(`Input indices should be Tensor2D but received shape\n ${r.shape}`);if(1!==s.rank)throw new Error(`Input shape should be Tensor1D but received shape ${s.shape}`);if(1!==o.rank)throw new Error(`New shape should be Tensor1D but received shape ${o.shape}`);const a={inputIndices:r,inputShape:s,newShape:o},i=Hs.runKernel("SparseReshape",a);return{outputIndices:i[0],outputShape:i[1]}}});const wd=oo({sparseSegmentMean_:function(e,t,n){const r=no(e,"data","sparseSegmentMean"),s=no(t,"indices","sparseSegmentMean","int32"),o=no(n,"segmentIds","sparseSegmentMean","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==s.rank)throw new Error(`Indices should be Tensor1D but received shape\n ${s.shape}`);if(1!==o.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n ${o.shape}`);const a={data:r,indices:s,segmentIds:o};return Hs.runKernel("SparseSegmentMean",a)}});const kd=oo({sparseSegmentSum_:function(e,t,n){const r=no(e,"data","sparseSegmentSum"),s=no(t,"indices","sparseSegmentSum","int32"),o=no(n,"segmentIds","sparseSegmentSum","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==s.rank)throw new Error(`Indices should be Tensor1D but received shape\n ${s.shape}`);if(1!==o.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n ${o.shape}`);const a={data:r,indices:s,segmentIds:o};return Hs.runKernel("SparseSegmentSum",a)}});const vd=oo({stringNGrams_:function(e,t,n,r,s,o,a,i){const l=no(e,"data","stringNGrams","string");if("string"!==l.dtype)throw new Error("Data must be of datatype string");if(1!==l.shape.length)throw new Error(`Data must be a vector, saw: ${l.shape}`);const u=no(t,"dataSplits","stringNGrams");if("int32"!==u.dtype)throw new Error("Data splits must be of datatype int32");const c={separator:n,nGramWidths:r,leftPad:s,rightPad:o,padWidth:a,preserveShortSequences:i},h={data:l,dataSplits:u},d=Hs.runKernel("StringNGrams",h,c);return{nGrams:d[0],nGramsSplits:d[1]}}});const xd={fft:Nc,ifft:Tc,rfft:Fc,irfft:Dc},Ed={hammingWindow:Ih,hannWindow:Mh,frame:Nh,stft:Th},Sd={flipLeftRight:Rh,grayscaleToRGB:Fh,resizeNearestNeighbor:ed,resizeBilinear:Qh,rgbToGrayscale:Bh,rotateWithOffset:Ch,cropAndResize:Dh,nonMaxSuppression:Oh,nonMaxSuppressionAsync:jh,nonMaxSuppressionWithScore:Jh,nonMaxSuppressionWithScoreAsync:Zh,nonMaxSuppressionPadded:Yh,nonMaxSuppressionPaddedAsync:Xh,threshold:td,transform:nd},$d={bandPart:rd,gramSchmidt:sd,qr:ad},Ad={absoluteDifference:ud,computeWeightedLoss:ld,cosineDistance:cd,hingeLoss:hd,huberLoss:dd,logLoss:fd,meanSquaredError:pd,sigmoidCrossEntropy:gd,softmaxCrossEntropy:md},_d={sparseFillEmptyRows:bd,sparseReshape:yd,sparseSegmentMean:wd,sparseSegmentSum:kd},Id={stringNGrams:vd,stringSplit:oo({stringSplit_:function(e,t,n=!0){const r=no(e,"input","stringSplit","string"),s=no(t,"delimiter","stringSplit","string");if(1!==r.rank)throw new Error(`Input should be Tensor1D but received shape ${r.shape}`);if(0!==s.rank)throw new Error(`Delimiter should be a scalar but received shape ${s.shape}`);const o={skipEmpty:n},a={input:r,delimiter:s},i=Hs.runKernel("StringSplit",a,o);return{indices:i[0],values:i[1],shape:i[2]}}}),stringToHashBucketFast:oo({stringToHashBucketFast_:function(e,t){const n=no(e,"input","stringToHashBucketFast","string"),r={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");const s={input:n};return Hs.runKernel("StringToHashBucketFast",s,r)}}),staticRegexReplace:oo({staticRegexReplace_:function(e,t,n,r=!0){const s=no(e,"input","staticRegexReplace","string"),o={pattern:t,rewrite:n,replaceGlobal:r};return Hs.runKernel("StaticRegexReplace",{x:s},o)}})},Md=new Map,Nd=new Map;class Td{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class Dd{constructor(){this.classNameMap={}}static getMap(){return null==Dd.instance&&(Dd.instance=new Dd),Dd.instance}static register(e){Dd.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function Rd(e,t,n){i(null!=e.className,(()=>"Class being registered does not have the static className property defined.")),i("string"==typeof e.className,(()=>"className is required to be a string, but got type "+typeof e.className)),i(e.className.length>0,(()=>"Class being registered has an empty-string as its className, which is disallowed.")),"undefined"==typeof t&&(t="Custom"),"undefined"==typeof n&&(n=e.className);const r=t+">"+n;return Dd.register(e),Md.set(r,e),Nd.set(e,r),e}var Fd={__proto__:null,Serializable:Td,SerializationMap:Dd,getRegisteredName:function(e){return Nd.has(e)?Nd.get(e):e.className},registerClass:Rd};class Bd extends Td{minimize(e,t=!1,n){const{value:r,grads:s}=this.computeGradients(e,n);if(null!=n){const e=n.map((e=>({name:e.name,tensor:s[e.name]})));this.applyGradients(e)}else this.applyGradients(s);return vo(s),t?r:(r.dispose(),null)}get iterations(){return null==this.iterations_&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return Bl(e,t)}dispose(){null!=this.iterations_&&vo(this.iterations_)}async saveIterations(){return null==this.iterations_&&(this.iterations_=0),{name:"iter",tensor:sl(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}}Object.defineProperty(Bd,Symbol.hasInstance,{value:e=>null!=e.minimize&&null!=e.computeGradients&&null!=e.applyGradients});class Cd extends Bd{static get className(){return"Adadelta"}constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],null==n&&(this.epsilon=Hs.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const r=Hs.registeredVariables[t];null==this.accumulatedGrads[n]&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:ko((()=>qi(r).variable(false)))}),null==this.accumulatedUpdates[n]&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:ko((()=>qi(r).variable(false)))});const s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const o=this.accumulatedGrads[n].variable,a=this.accumulatedUpdates[n].variable;ko((()=>{const e=xa($a(o,this.rho),$a(al(s),1-this.rho)),t=$a(Sa(ol(xa(a,this.epsilon)),ol(xa(o,this.epsilon))),s),n=xa($a(a,this.rho),$a(al(t),1-this.rho));o.assign(e),a.assign(n);const i=xa($a(t,-this.learningRate),r);r.assign(i)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedUpdates&&(vo(this.accumulatedGrads.map((e=>e.variable))),vo(this.accumulatedUpdates.map((e=>e.variable))))}async getWeights(){const e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){const t=(e=await this.extractIterations(e)).length/2;this.accumulatedGrads=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(false)}))),this.accumulatedUpdates=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(false)})))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}}class Pd extends Bd{static get className(){return"Adagrad"}constructor(e,t=.1){super(),this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const r=Hs.registeredVariables[t];if(null==this.accumulatedGrads[n]){const e=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:ko((()=>bi(r.shape,this.initialAccumulatorValue).variable(e)))}}const s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const o=this.accumulatedGrads[n].variable;ko((()=>{const e=xa(o,al(s));o.assign(e);const t=xa($a(Sa(s,ol(xa(e,Hs.backend.epsilon()))),-this.learningRate),r);r.assign(t)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedGrads&&vo(this.accumulatedGrads.map((e=>e.variable)))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e);this.accumulatedGrads=e.map((e=>({originalName:e.name,variable:e.tensor.variable(false)})))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}class Od extends Bd{static get className(){return"Adam"}constructor(e,t,n,r=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],ko((()=>{this.accBeta1=sl(t).variable(),this.accBeta2=sl(n).variable()})),null==r&&(this.epsilon=Hs.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);ko((()=>{const n=Ul(1,this.accBeta1),r=Ul(1,this.accBeta2);t.forEach(((t,s)=>{const o=Hs.registeredVariables[t];null==this.accumulatedFirstMoment[s]&&(this.accumulatedFirstMoment[s]={originalName:`${t}/m`,variable:ko((()=>qi(o).variable(false)))}),null==this.accumulatedSecondMoment[s]&&(this.accumulatedSecondMoment[s]={originalName:`${t}/v`,variable:ko((()=>qi(o).variable(false)))});const a=Array.isArray(e)?e[s].tensor:e[t];if(null==a)return;const i=this.accumulatedFirstMoment[s].variable,l=this.accumulatedSecondMoment[s].variable,u=xa($a(i,this.beta1),$a(a,1-this.beta1)),c=xa($a(l,this.beta2),$a(al(a),1-this.beta2)),h=Sa(u,n),d=Sa(c,r);i.assign(u),l.assign(c);const f=xa($a(Sa(h,xa(ol(d),this.epsilon)),-this.learningRate),o);o.assign(f)})),this.accBeta1.assign($a(this.accBeta1,this.beta1)),this.accBeta2.assign($a(this.accBeta2,this.beta2))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&vo(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedSecondMoment&&vo(this.accumulatedSecondMoment.map((e=>e.variable)))}async getWeights(){const e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e),ko((()=>{this.accBeta1.assign(rl(this.beta1,this.iterations_+1)),this.accBeta2.assign(rl(this.beta2,this.iterations_+1))}));const t=e.length/2;this.accumulatedFirstMoment=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(false)}))),this.accumulatedSecondMoment=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(false)})))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}}class Ld extends Bd{static get className(){return"Adamax"}constructor(e,t,n,r=null,s=0){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.decay=s,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],ko((()=>{this.iteration=sl(0).variable(),this.accBeta1=sl(t).variable()})),null==r&&(this.epsilon=Hs.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);ko((()=>{const n=Ul(1,this.accBeta1),r=Sa(-this.learningRate,xa($a(this.iteration,this.decay),1));t.forEach(((t,s)=>{const o=Hs.registeredVariables[t];null==this.accumulatedFirstMoment[s]&&(this.accumulatedFirstMoment[s]={originalName:`${t}/m`,variable:qi(o).variable(false)}),null==this.accumulatedWeightedInfNorm[s]&&(this.accumulatedWeightedInfNorm[s]={originalName:`${t}/v`,variable:qi(o).variable(false)});const a=Array.isArray(e)?e[s].tensor:e[t];if(null==a)return;const i=this.accumulatedFirstMoment[s].variable,l=this.accumulatedWeightedInfNorm[s].variable,u=xa($a(i,this.beta1),$a(a,1-this.beta1)),c=$a(l,this.beta2),h=Aa(a),d=Ql(c,h);i.assign(u),l.assign(d);const f=xa($a(Sa(r,n),Sa(u,xa(d,this.epsilon))),o);o.assign(f)})),this.iteration.assign(xa(this.iteration,1)),this.accBeta1.assign($a(this.accBeta1,this.beta1))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&vo(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedWeightedInfNorm&&vo(this.accumulatedWeightedInfNorm.map((e=>e.variable)))}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(e){throw new Error("setWeights() is not implemented for Adamax yet.")}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)}}class zd extends Bd{static get className(){return"SGD"}constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const r=Array.isArray(e)?e[n].tensor:e[t];if(null==r)return;const s=Hs.registeredVariables[t];ko((()=>{const e=xa($a(this.c,r),s);s.assign(e)}))})),this.incrementIterations()}setLearningRate(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=xo(sl(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(0!==(e=await this.extractIterations(e)).length)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}}class Ud extends zd{static get className(){return"Momentum"}constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=sl(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const r=Hs.registeredVariables[t];if(null==this.accumulations[n]){const e=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:ko((()=>qi(r).variable(e)))}}const s=this.accumulations[n].variable,o=Array.isArray(e)?e[n].tensor:e[t];null!=o&&ko((()=>{let e;const t=xa($a(this.m,s),o);e=this.useNesterov?xa($a(this.c,xa(o,$a(t,this.m))),r):xa($a(this.c,t),r),s.assign(t),r.assign(e)}))})),this.incrementIterations()}dispose(){this.m.dispose(),null!=this.accumulations&&vo(this.accumulations.map((e=>e.variable)))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e);this.accumulations=e.map((e=>({originalName:e.name,variable:e.tensor.variable(false)})))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}class Wd extends Bd{static get className(){return"RMSProp"}constructor(e,t=.9,n=0,r=null,s=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=r,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=s,null==r&&(this.epsilon=Hs.backend.epsilon()),null==e)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const r=Hs.registeredVariables[t],s=!1;null==this.accumulatedMeanSquares[n]&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:ko((()=>qi(r).variable(s)))}),null==this.accumulatedMoments[n]&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:ko((()=>qi(r).variable(s)))}),null==this.accumulatedMeanGrads[n]&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:ko((()=>qi(r).variable(s)))});const o=Array.isArray(e)?e[n].tensor:e[t];if(null==o)return;const a=this.accumulatedMeanSquares[n].variable,i=this.accumulatedMoments[n].variable;ko((()=>{const e=xa($a(a,this.decay),$a(al(o),1-this.decay));if(this.centered){const t=this.accumulatedMeanGrads[n].variable,s=xa($a(t,this.decay),$a(o,1-this.decay)),l=Sa($a(o,this.learningRate),ol(Ul(e,xa(al(s),this.epsilon)))),u=xa($a(i,this.momentum),l);a.assign(e),t.assign(s),i.assign(u);const c=Ul(r,u);r.assign(c)}else{const e=xa($a(a,this.decay),$a(al(o),1-this.decay)),t=xa($a(i,this.momentum),Sa($a(o,this.learningRate),ol(xa(e,this.epsilon))));a.assign(e),i.assign(t);const n=Ul(r,t);r.assign(n)}}))})),this.incrementIterations()}dispose(){null!=this.accumulatedMeanSquares&&vo(this.accumulatedMeanSquares.map((e=>e.variable))),null!=this.accumulatedMeanGrads&&this.centered&&vo(this.accumulatedMeanGrads.map((e=>e.variable))),null!=this.accumulatedMoments&&vo(this.accumulatedMoments.map((e=>e.variable)))}async getWeights(){const e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e);const t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))),this.accumulatedMoments=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))),this.centered&&(this.accumulatedMeanGrads=e.slice(2*t,3*t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}}const Gd=[Cd,Pd,Od,Ld,Ud,Wd,zd];function Kd(e){return new Promise((e=>setTimeout(e))).then(e)}class qd{constructor(e){if(!O().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(qd.URL_SCHEME)&&(e=e.slice(qd.URL_SCHEME.length)),null!=e&&0!==e.length||(e="model"),this.modelJsonFileName=e+".json",this.weightDataFileName=e+".weights.bin"}async save(e){if("undefined"==typeof document)throw new Error("Browser downloads are not supported in this environment since `document` is not present");const t=co.join(e.weightData),n=window.URL.createObjectURL(new Blob([t],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{const t=Wo(e,[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}]),r=window.URL.createObjectURL(new Blob([JSON.stringify(t)],{type:"application/json"})),s=null==this.modelJsonAnchor?document.createElement("a"):this.modelJsonAnchor;if(s.download=this.modelJsonFileName,s.href=r,await Kd((()=>s.dispatchEvent(new MouseEvent("click")))),null!=e.weightData){const e=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor;e.download=this.weightDataFileName,e.href=n,await Kd((()=>e.dispatchEvent(new MouseEvent("click"))))}return{modelArtifactsInfo:qo(e)}}}}qd.URL_SCHEME="downloads://";class Vd{constructor(e){if(null==e||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.jsonFile=e[0],this.weightsFiles=e.slice(1)}async load(){return new Promise(((e,t)=>{const n=new FileReader;n.onload=n=>{const r=JSON.parse(n.target.result),s=r.modelTopology;if(null==s)return void t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));if(null==r.weightsManifest)return void t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));if(0===this.weightsFiles.length)return void e({modelTopology:s});const o=Ko(r,(e=>this.loadWeights(e)));e(o)},n.onerror=e=>t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),n.readAsText(this.jsonFile)}))}loadWeights(e){const t=[],n=[];for(const r of e)t.push(...r.weights),n.push(...r.paths);const r=this.checkManifestAndWeightFiles(e),s=n.map((e=>this.loadWeightsFile(e,r[e])));return Promise.all(s).then((e=>[t,e]))}loadWeightsFile(e,t){return new Promise(((n,r)=>{const s=new FileReader;s.onload=e=>{const t=e.target.result;n(t)},s.onerror=t=>r(`Failed to weights data from file of path '${e}'.`),s.readAsArrayBuffer(t)}))}checkManifestAndWeightFiles(e){const t=[],n=this.weightsFiles.map((e=>Uo(e.name))),r={};for(const s of e)s.paths.forEach((e=>{const s=Uo(e);if(-1!==t.indexOf(s))throw new Error(`Duplicate file basename found in weights manifest: '${s}'`);if(t.push(s),-1===n.indexOf(s))throw new Error(`Weight file with basename '${s}' is not provided.`);r[e]=this.weightsFiles[n.indexOf(s)]}));if(t.length!==this.weightsFiles.length)throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);return r}}function Hd(e,t,n,r){!function(e){i(null!=e&&Array.isArray(e)&&e.length>0,(()=>"promises must be a none empty array"))}(e),function(e,t){i(e>=0&&e<=1,(()=>`Progress fraction must be in range [0, 1], but got startFraction ${e}`)),i(t>=0&&t<=1,(()=>`Progress fraction must be in range [0, 1], but got endFraction ${t}`)),i(t>=e,(()=>`startFraction must be no more than endFraction, but got startFraction ${e} and endFraction ${t}`))}(n=null==n?0:n,r=null==r?1:r);let s=0;return Promise.all(e.map((o=>(o.then((o=>{const a=n+ ++s/e.length*(r-n);return t(a),o})),o))))}async function jd(e,t){null==t&&(t={});const n=null==t.fetchFunc?O().platform.fetch:t.fetchFunc,r=e.map((e=>n(e,t.requestInit,{isBinary:!0}))),s=(null==t.onProgress?await Promise.all(r):await Hd(r,t.onProgress,0,.5)).map((e=>e.arrayBuffer()));return null==t.onProgress?await Promise.all(s):await Hd(s,t.onProgress,.5,1)}function Jd(e){return async(t,n="",r)=>{const s=t.map((()=>!1)),o={},a=null!=r?r.map((()=>!1)):[],i=[];if(t.forEach(((e,t)=>{let n=0;e.weights.forEach((e=>{const l="quantization"in e?e.quantization.dtype:e.dtype,u=uo[l]*c(e.shape),h=()=>{s[t]=!0,null==o[t]&&(o[t]=[]),o[t].push({manifestEntry:e,groupOffset:n,sizeBytes:u})};null!=r?r.forEach(((t,n)=>{t===e.name&&(h(),a[n]=!0)})):h(),i.push(e.name),n+=u}))})),!a.every((e=>e))){const e=r.filter(((e,t)=>!a[t]));throw new Error(`Could not find weights in manifest with names: ${e.join(", ")}. \nManifest JSON has weights with names: ${i.join(", ")}.`)}const l=s.reduce(((e,t,n)=>(t&&e.push(n),e)),[]),u=[];l.forEach((e=>{t[e].paths.forEach((e=>{const t=n+(n.endsWith("/")?"":"/")+e;u.push(t)}))}));const h=await e(u),d={};let f=0;return l.forEach((e=>{const n=t[e].paths.length,r=new co(h.slice(f,f+n));o[e].forEach((e=>{const t=Ro(r.slice(e.groupOffset,e.groupOffset+e.sizeBytes),[e.manifestEntry]);for(const e in t)d[e]=t[e]})),f+=n})),d}}Ho.registerSaveRouter((e=>O().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(qd.URL_SCHEME)?function(e="model"){return new qd(e)}(e.slice(qd.URL_SCHEME.length)):null));class Zd{constructor(e,t){if(this.DEFAULT_METHOD="POST",null==t&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.weightUrlConverter=t.weightUrlConverter,null!=t.fetchFunc?(i("function"==typeof t.fetchFunc,(()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)")),this.fetch=t.fetchFunc):this.fetch=O().platform.fetch,i(null!=e&&e.length>0,(()=>"URL path for http must not be null, undefined or empty.")),Array.isArray(e)&&i(2===e.length,(()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`)),this.path=e,null!=t.requestInit&&null!=t.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{},this.loadOptions=t}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const n=Wo(e,[{paths:["./model.weights.bin"],weights:e.weightSpecs}]);if(t.body.append("model.json",new Blob([JSON.stringify(n)],{type:"application/json"}),"model.json"),null!=e.weightData){const n=co.join(e.weightData);t.body.append("model.weights.bin",new Blob([n],{type:"application/octet-stream"}),"model.weights.bin")}const r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:qo(e),responses:[r]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.status}.`)}async loadModelJSON(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(e){let t=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?t+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":t+=" Please make sure the server is serving valid JSON for this request.",new Error(t)}const n=t.modelTopology,r=t.weightsManifest;if(null==n&&null==r)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return t}async load(){if(this.loadOptions.streamWeights)return this.loadStream();return Ko(await this.loadModelJSON(),(e=>this.loadWeights(e)))}async loadStream(){const e=await this.loadModelJSON(),t=await this.getWeightUrls(e.weightsManifest),n=Vo(e.weightsManifest);return Object.assign(Object.assign({},e),{weightSpecs:n,getWeightStream:()=>function(e,t){var n;const r=null==t.fetchFunc?O().platform.fetch:t.fetchFunc;let s,o=0;return null===(n=t.onProgress)||void 0===n||n.call(t,0),new ReadableStream({pull:async n=>{for(var a;ot?e.substring(n):"";return[r+"/",s]}(t),s=this.weightPathPrefix||n,o=[],a=[];for(const t of e)for(const e of t.paths)null!=this.weightUrlConverter?a.push(this.weightUrlConverter(e)):o.push(s+e+r);return this.weightUrlConverter&&o.push(...await Promise.all(a)),o}async loadWeights(e){const t=await this.getWeightUrls(e);return[Vo(e),await jd(t,this.loadOptions)]}}function Yd(e){return null!=e.match(Zd.URL_SCHEME_REGEX)}Zd.URL_SCHEME_REGEX=/^https?:\/\//;const Xd=(e,t)=>{if("undefined"==typeof fetch&&(null==t||null==t.fetchFunc))return null;{let n=!0;if(n=Array.isArray(e)?e.every((e=>Yd(e))):Yd(e),n)return Qd(e,t)}return null};function Qd(e,t){return new Zd(e,t)}Ho.registerSaveRouter(Xd),Ho.registerLoadRouter(Xd);class ef{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}}class tf{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}}class nf{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}}function rf(e,t,n,r){if(1===arguments.length){return null!=e.modelTopology||null!=e.weightSpecs?new ef(e):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new ef({modelTopology:e}))}return console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new ef({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r})}var sf={__proto__:null,CompositeArrayBuffer:co,browserFiles:function(e){return new Vd(e)},browserHTTPRequest:function(e,t){return Qd(e,t)},concatenateArrayBuffers:function(e){return co.join(e)},copyModel:async function(e,t){return fa(e,t,!1)},decodeWeights:Ro,decodeWeightsStream:async function(e,t){const n={},r=e.getReader();let s=new ArrayBuffer(0);for(const e of t){const t=await Bo(e,(async(e,t)=>(s=await Po(r,s,t),s.slice(e,t))));s=await Po(r,s,t);const o=s.slice(0,t);s=s.slice(t);const a=Co(e,o);if(n[e.name]=a,"webgpu"===Ao()){const e=To();"uploadToGPU"in e&&c(a.shape)>=O().get("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD")&&e.uploadToGPU(a.dataId)}}return n},encodeWeights:async function(e,t){const n=[],r=[],s=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);for(let o=0;o{const t=await i.bytes(),n=t.reduce(((e,t)=>e+t.length),0)+4*t.length,r=new Uint8Array(n);let s=0;for(let e=0;eHo.getLoadHandlers(e,t),getModelArtifactsForJSON:Ko,getModelArtifactsForJSONSync:Go,getModelArtifactsInfoForJSON:qo,getSaveHandlers:e=>Ho.getSaveHandlers(e),getWeightSpecs:Vo,http:Qd,isHTTPScheme:Yd,listModels:async function(){const e=ha.getSchemes(),t={};for(const n of e){const e=await ha.getManager(n).listModels();for(const r in e){t[n+"://"+r]=e[r]}}return t},loadWeights:async function(e,t="",n,r){return Jd((e=>jd(e,{requestInit:r})))(e,t,n)},moveModel:async function(e,t){return fa(e,t,!0)},registerLoadRouter:e=>Ho.registerLoadRouter(e),registerSaveRouter:e=>Ho.registerSaveRouter(e),removeModel:async function(e){const t=da(e);return ha.getManager(t.scheme).removeModel(t.path)},weightsLoaderFactory:Jd,withSaveHandler:function(e){return new tf(e)},withSaveHandlerSync:function(e){return new tf(e)}};var of={__proto__:null,confusionMatrix:oo({confusionMatrix_:function(e,t,n){const r=no(e,"labels","confusionMatrix"),s=no(t,"predictions","confusionMatrix");i(null==n||n>0&&Number.isInteger(n),(()=>`If provided, numClasses must be a positive integer, but got ${n}`)),i(1===r.rank,(()=>`Expected the rank of labels to be 1, but got ${r.rank}`)),i(1===s.rank,(()=>`Expected the rank of predictions to be 1, but got ${s.rank}`)),i(r.shape[0]===s.shape[0],(()=>`Mismatch in the number of examples: ${r.shape[0]} vs. ${s.shape[0]}. Labels and predictions should have the same number of elements.`)),i(n>0&&Number.isInteger(n),(()=>`numClasses is required to be a positive integer, but got ${n}`));const o=hu(wa(r,"int32"),n),a=hu(wa(s,"int32"),n),l=lh(o),u=ni(l,a);return wa(u,"int32")}})};let af,lf=!1;function uf(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(null==e)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,r=!1,s=!1,o=!1,a=!1,i=!1;if(e.data instanceof Uint8Array)n=!0;else if("undefined"!=typeof ImageData&&e instanceof ImageData)r=!0;else if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)s=!0;else if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)o=!0;else if(null!=e.getContext)a=!0;else{if(!("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap))throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${e.constructor.name}`);i=!0}if(null!=hr("FromPixels",Hs.backendName)){const n={pixels:e},r={numChannels:t};return Hs.runKernel("FromPixels",n,r)}const[l,u]=s?[e.videoWidth,e.videoHeight]:[e.width,e.height];let c,h;if(a)c=e.getContext("2d").getImageData(0,0,l,u).data;else if(r||n)c=e.data;else if(o||s||i){if(null==af)if("undefined"==typeof document){if("undefined"==typeof OffscreenCanvas||"undefined"==typeof OffscreenCanvasRenderingContext2D)throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");af=new OffscreenCanvas(1,1).getContext("2d")}else af=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});af.canvas.width=l,af.canvas.height=u,af.drawImage(e,0,0,l,u),c=af.getImageData(0,0,l,u).data}if(4===t)h=new Int32Array(c);else{const e=l*u;h=new Int32Array(e*t);for(let n=0;n4||2===t)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${t}`);if("float32"!==e.dtype&&"int32"!==e.dtype)throw new Error(`Unsupported type for toPixels: ${e.dtype}. Please use float32 or int32 tensors.`)}var df={__proto__:null,draw:function(e,t,n){let r=no(e,"img","draw");if(!(e instanceof $s)){const e=r;r=wa(e,"int32"),e.dispose()}hf(r),function(e){const t=(null==e?void 0:e.alpha)||1;if(t>1||t<0)throw new Error(`Alpha value ${t} is suppoed to be in range [0 - 1].`)}(null==n?void 0:n.imageOptions);const s={image:r},o={canvas:t,options:n};Hs.runKernel("Draw",s,o)},fromPixels:oo({fromPixels_:uf}),fromPixelsAsync:async function(e,t=3){let n=null;if(O().getBool("WRAP_TO_IMAGEBITMAP")&&cf(e)){let t;try{t=await createImageBitmap(e,{premultiplyAlpha:"none"})}catch(e){t=null}n=null!=t&&t.width===e.width&&t.height===e.height?t:e}else n=e;return uf(n,t)},toPixels:async function(e,t){let n=no(e,"img","toPixels");if(!(e instanceof $s)){const e=n;n=wa(e,"int32"),e.dispose()}hf(n);const[r,s]=n.shape.slice(0,2),o=2===n.rank?1:n.shape[2],a=await n.data(),i="float32"===n.dtype?255:1,l=new Uint8ClampedArray(s*r*4);for(let e=0;e1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${s}.`)}else if("int32"===n.dtype&&(s<0||s>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${s}.`);1===o?(t[0]=s*i,t[1]=s*i,t[2]=s*i):t[r]=s*i}const r=4*e;l[r+0]=Math.round(t[0]),l[r+1]=Math.round(t[1]),l[r+2]=Math.round(t[2]),l[r+3]=Math.round(t[3])}if(null!=t){if(!lf){null!=hr("Draw",Hs.backendName)&&(console.warn("tf.browser.toPixels is not efficient to draw tensor on canvas. Please try tf.browser.draw instead."),lf=!0)}t.width=s,t.height=r;const e=t.getContext("2d"),n=new ImageData(l,s,r);e.putImageData(n,0,0)}return n!==e&&n.dispose(),l}};function ff(e,t){const n=e.shape.length,r=t.shape.length;if(n<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${n}.`);if(r<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${r}.`);if("int32"!==t.dtype)throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[r-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[r-1]} vs. ${n}`);if(0===c(e.shape))throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);const s=t.shape,o=s[s.length-1];let a=1;for(let e=0;ee/u)),1].slice(0,o);return[l,a,u,h]}var pf={__proto__:null,prepareAndValidate:ff};function gf(e,t,n,r){const s=[...e];for(let e=s.length;e-1)o[s]=0;else{const a=mf(t,n,s);let i=r[a];e&1<-1)a[s]=Number.MAX_SAFE_INTEGER;else{const o=mf(t,n,s);let i=r[o];e&1<0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);const u=r[s];return i<0&&(i+=u),i=o(0,i,u-1),i}function xf(e,t,n,r,s,a){let i=t[s];const l=n[s]||1;(e&1<0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);const u=r[s];return i<0&&(i+=u),i=l>0?o(0,i,u):o(-1,i,u-1),i}function Ef(e,t,n,r,s,o){if(s[t])return n>0?o[t]:o[t+1&1];{const t=e<0?r+e:e;return to[1]?o[1]:t}}var Sf={__proto__:null,assertParamsValid:function(e,t,n){const r=e.shape.length;i(r===t.length,(()=>`Error in slice${r}D: Length of begin ${t} must match the rank of the array (${r}).`)),i(r===n.length,(()=>`Error in slice${r}D: Length of size ${n} must match the rank of the array (${r}).`));for(let s=0;s`Error in slice${r}D: begin[${s}] + size[${s}] (${t[s]+n[s]}) would overflow input.shape[${s}] (${e.shape[s]})`))},computeFlatOffset:function(e,t){let n=e.length>0?e[e.length-1]:1;for(let r=0;r0){const l=t[0],u=n+1;c=yf(a,l,u,r,e),h=wf(i,l,u,s,e),d=gf(o,l,u,e)}else for(let t=0;t1){r=e;break}for(let s=r+1;s0||n[s]!==e[s])return!1;return!0},maskToAxes:function(e){const t=[];let n=0;for(;e>0;)1&e&&t.push(n),e/=2,n++;return t},parseSliceParams:function(e,t,n){let r;const s=e.shape.length;let o;return r="number"==typeof t?[t,...new Array(s-1).fill(0)]:t.length{i(-1!==e,(()=>"slice() does not support negative begin indexing."))})),o=null==n?new Array(s).fill(-1):"number"==typeof n?[n,...new Array(s-1).fill(-1)]:n.lengtht>=0?t:(i(-1===t,(()=>`Negative size values should be exactly -1 but got ${t} for the slice() size at index ${n}.`)),e.shape[n]-r[n]))),[r,o]},sliceInfo:function(e,t,n,r,s,o,a,i,l){let u;if(null==r?(u=new Array(t.length),u.fill(1)):u=r,null!=a&&0!=(a&a-1))throw new Error("Multiple ellipses in slice is not allowed.");let c=!1;const h={dims:u.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:n.slice(),strides:u.slice(),beginMask:s,endMask:o,ellipsisMask:a,newAxisMask:i,shrinkAxisMask:l};for(let e=0;e0?0:-1,d.strides[t]>0?r:r-1];if(n&&d.strides[t]<=0)throw Error("only stride 1 allowed on non-range indexing.");g=g&&1===d.strides[t];const a=!!(d.beginMask&1<=r)throw Error(`slice index ${d.begin[t]} of dimension ${t} out of bounds.`)}else d.begin[t]=Ef(d.begin[t],0,d.strides[t],r,s,o),d.end[t]=Ef(d.end[t],1,d.strides[t],r,s,o);const e=1===d.strides[t]&&0===d.begin[t]&&d.end[t]===r;f=f&&e,p=p&&(0===t&&1===d.strides[t]||e)}else f=f&&1===d.strides[t]&&a,p=p&&(0===t&&1===d.strides[t]||a);let i,l=!1;if(d.beginValid&&d.endValid?(i=d.end[t]-d.begin[t],l=!0):n?(i=1,l=!0):a&&r>=0&&(i=d.strides[t]<0?-r:r,l=!0),l){let e;e=0===i||i<0!=d.strides[t]<0?0:Math.trunc(i/d.strides[t])+(i%d.strides[t]!=0?1:0),m.push(e)}else m.push(-1)}for(let e=0;e=0?b.push(m[t]):-2===t&&b.push(1)}return{finalShapeSparse:b.filter(((e,t)=>-2!==d.finalShapeGatherIndices[t])),finalShape:b,isIdentity:f,sliceDim0:p,isSimpleSlice:g,begin:d.begin,end:d.end,strides:d.strides}},startForAxis:vf,startIndicesWithElidedDims:yf,stopForAxis:xf,stopIndicesWithElidedDims:wf,stridesForAxis:kf,stridesWithElidedDims:gf};const $f="4.15.0";class Af{static sgd(e){return new zd(e)}static momentum(e,t,n=!1){return new Ud(e,t,n)}static rmsprop(e,t=.9,n=0,r=null,s=!1){return new Wd(e,t,n,r,s)}static adam(e=.001,t=.9,n=.999,r=null){return new Od(e,t,n,r)}static adadelta(e=.001,t=.95,n=null){return new Cd(e,t,n)}static adamax(e=.002,t=.9,n=.999,r=null,s=0){return new Ld(e,t,n,r,s)}static adagrad(e,t=.1){return new Pd(e,t)}}const _f=Af,If="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:e=>e();function Mf(){return new Promise((e=>If((()=>e()))))}var Nf;!function(e){e[e.FIRST_DIM_SIZE=0]="FIRST_DIM_SIZE",e[e.VALUE_ROWIDS=1]="VALUE_ROWIDS",e[e.ROW_LENGTHS=2]="ROW_LENGTHS",e[e.ROW_SPLITS=3]="ROW_SPLITS",e[e.ROW_LIMITS=4]="ROW_LIMITS",e[e.ROW_STARTS=5]="ROW_STARTS"}(Nf||(Nf={}));const Tf=/->/g;function Df(e,t){const n=[];for(let r=0;r`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`))},assertParamsConsistent:function(e,t){const n=e[0].length;e.forEach(((e,t)=>{i(e.length===n,(()=>`Error in concat${n}D: rank of tensors[${t}] must be the same as the rank of the rest (${n})`))})),i(t>=0&&t`Error in concat${n}D: axis must be between 0 and ${n-1}.`));const r=e[0];e.forEach(((e,s)=>{for(let o=0;o`Error in concat${n}D: Shape of tensors[${s}] (${e}) does not match the shape of the rest (${r}) along the non-concatenated axis ${s}.`))}))},assignToTypedArray:function(e,t,n,r){e[2*r]=t,e[2*r+1]=n},axesAreInnerMostDims:Xi,calculateShapes:Jc,checkEinsumDimSizes:function(e,t,n){const r=new Array(e);for(let e=0;e`Expected dimension ${r[t[e][n]]} at axis ${n} of input shaped ${JSON.stringify(s)}, but got dimension ${s[n]}`))}},checkPadOnDimRoundingMode:Ya,combineLocations:Qi,combineRaggedTensorToTensorShapes:function(e,t,n){let r=new Array;if(null==n&&null==t)return r;if(null==t)for(;r.length=0)if(i>=0){if(i!==o)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.shape[${s+e}] = ${o} but shape[${s+e}] = ${i}`)}else r[a]=o}return r},complexWithEvenIndex:function(e){const t=Math.ceil(e.length/4),n=new Float32Array(t),r=new Float32Array(t);for(let t=0;te[t]))]},computeOutShape:function(e,t){const n=e[0].slice();for(let r=1;r".length;if(n<1)throw new Error("Equations without an arrow are not supported.");if(n>1)throw new Error('Equation must contain exactly one arrow ("->").');const[r,s]=e.split("->");i(-1===r.indexOf("..."),(()=>'The ellipsis notation ("...") is not supported yet.'));const o=r.split(","),a=o.length;if(t!==a)throw new Error(`Expected ${a} input tensors, received ${t}`);if(a>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");const l=[];for(let e=0;e-1!==e.indexOf(t))))throw new Error(`Output subscripts contain the label ${t} not present in the input subscripts.`);-1===l.indexOf(t)&&l.push(t)}for(let e=0;eus(e)))},fromUint8ToStringArray:function(e){try{return e.map((e=>cs(e)))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}},getAxesPermutation:function(e,t){if(Xi(e,t))return null;const n=[];for(let r=0;rn.push(e))),n},getBroadcastDims:Li,getComplexWithIndex:function(e,t){return{real:e[2*t],imag:e[2*t+1]}},getEinsumComputePath:function(e,t){const n=e,r=[];let s=0;0===e.length&&n.push(-1),s=e.length+1;for(let e=0;e-1!==e)),{permutationIndices:n,expandDims:r}},getFusedBiasGradient:wh,getFusedDyActivation:yh,getImageCenter:function(e,t,n){return[n*("number"==typeof e?e:e[0]),t*("number"==typeof e?e:e[1])]},getInnerMostAxes:function(e,t){const n=[];for(let r=t-e;r=2*t+1||r%2==1?s.push(r):n.push(r);r.push(...n),r.push(0),r.push(...s)}return r},getRaggedRank:function(e){return 0===e.length?0:e[0]===Nf.FIRST_DIM_SIZE?e.length-1:e.length},getReductionAxes:zi,getReshaped:function(e,t,n,r=!0){let s=[];if(r)s=s.concat(t.slice(0)),s.push(e[0]/n),s=s.concat(e.slice(1));else{s=s.concat(e[0]);const n=t.length;for(let r=0;r= ${n}`},getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:function(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"},getSparseReshapeInputOutputMismatchErrorMessage:function(e,t){return`Input to reshape is a tensor with ${c(e)} dense values, but the requested shape has ${c(t)}. inputShape=${e} outputShape=${t}`},getSparseReshapeInputOutputMultipleErrorMessage:function(e,t){return`Input to reshape is a SparseTensor with ${c(e)}\n dense values, but the requested shape requires a multiple of ${c(t)}. inputShape=${e} outputShape= ${t}`},getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:function(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`},getSparseReshapeNegativeOutputDimErrorMessage:function(e,t){return`size ${e} must be non-negative, not ${t}`},getSparseSegmentReductionIndicesOutOfRangeErrorMessage:function(e,t,n){return`Bad: indices[${e}] == ${t} out of range [0, ${n})`},getSparseSegmentReductionNegativeSegmentIdsErrorMessage:function(){return"segment ids must be >= 0"},getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:function(){return"segment ids are not increasing"},getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:function(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`},getUndoAxesPermutation:function(e){return e.map(((e,t)=>[t,e])).sort(((e,t)=>e[1]-t[1])).map((e=>e[0]))},isIdentityPermutation:function(e){return e.every(((e,t)=>e===t))},log:function(...e){O().getBool("IS_TEST")||O().getBool("PROD")||console.log(...e)},mergeRealAndImagArrays:function(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);const n=new Float32Array(2*e.length);for(let r=0;r"Number of splits must evenly divide the axis.")),r=new Array(t).fill(e.shape[n]/t);else{i(t.reduce(((e,t)=>(-1===t&&(e+=1),e)),0)<=1,(()=>"There should be only one negative value in split array."));const s=t.indexOf(-1);if(-1!==s){const r=t.reduce(((e,t)=>t>0?e+t:e));t[s]=e.shape[n]-r}i(e.shape[n]===t.reduce(((e,t)=>e+t)),(()=>"The sum of sizes must match the size of the axis dimension.")),r=t}return r},segment_util:{__proto__:null,collectGatherOpShapeInfo:function(e,t,n,r){const s=t.shape.length,o=e.shape.length;if(0!==r&&(r<-s||r>s))throw new Error(`Expect batchDims in the range of [-${s}, ${s}], but got ${r}`);if(r<0&&(r+=s),r>o)throw new Error(`batchDims (${r}) must be less than rank(x) (\n ${o}).`);if(nt||n===e?r=!0:n=I(e,n+1);return n}},shouldFuse:vh,slice_util:Sf,splitRealAndImagArrays:function(e){const t=new Float32Array(e.length/2),n=new Float32Array(e.length/2);for(let r=0;r=r)throw new Error(`defaultValue.shape=${e} and ragged tensor flatValues.shape=${t}, are incompatible: defaultValue.rank = ${n} must be less than ragged tensor input flatValues.rank = ${r})`);for(let s=0;s=0&&r>=0&&1!==n&&n!==r)throw new Error(`defaultValue.shape=${e}, and ragged tensor input flatValues.shape=${t} are incompatible: defaultValue.shape[${s-e.length}] = ${n} but ragged tensor input.flatValues.shape[${s-e.length}] = ${r}`)}},validateInput:jc,validateUpdateShape:Hc,warn:lr},Ff={__proto__:null,nonMaxSuppressionV3Impl:Uh,nonMaxSuppressionV4Impl:Wh,nonMaxSuppressionV5Impl:Gh,whereImpl:oh};!function(){for(const e of Gd)Rd(e)}();export{G as Abs,K as Acos,q as Acosh,Cd as AdadeltaOptimizer,Pd as AdagradOptimizer,Od as AdamOptimizer,Ld as AdamaxOptimizer,V as Add,H as AddN,j as All,J as Any,Z as ArgMax,Y as ArgMin,X as Asin,Q as Asinh,ee as Atan,ne as Atan2,te as Atanh,re as AvgPool,oe as AvgPool3D,ae as AvgPool3DGrad,se as AvgPoolGrad,ie as BatchMatMul,le as BatchToSpaceND,ue as Bincount,ce as BitwiseAnd,de as BroadcastArgs,he as BroadcastTo,fe as Cast,pe as Ceil,ge as ClipByValue,me as Complex,be as ComplexAbs,ye as Concat,we as Conv2D,ke as Conv2DBackpropFilter,ve as Conv2DBackpropInput,xe as Conv3D,Ee as Conv3DBackpropFilterV2,Se as Conv3DBackpropInputV2,$e as Cos,Ae as Cosh,Me as CropAndResize,_e as Cumprod,Ie as Cumsum,t as DataStorage,Ne as DenseBincount,Te as DepthToSpace,De as DepthwiseConv2dNative,Re as DepthwiseConv2dNativeBackpropFilter,Fe as DepthwiseConv2dNativeBackpropInput,Be as Diag,Ce as Dilation2D,Oe as Dilation2DBackpropFilter,Pe as Dilation2DBackpropInput,Le as Draw,z as ENV,Ue as Einsum,We as Elu,Ge as EluGrad,C as Environment,qe as Equal,Ke as Erf,Ve as Exp,He as ExpandDims,je as Expm1,Je as FFT,Ze as Fill,Ye as FlipLeftRight,Xe as Floor,Qe as FloorDiv,rr as FromPixels,et as FusedBatchNorm,ar as FusedConv2D,ir as FusedDepthwiseConv2D,nt as GatherNd,tt as GatherV2,rt as Greater,st as GreaterEqual,at as IFFT,ot as Identity,it as Imag,lt as IsFinite,ut as IsInf,ct as IsNan,n as KernelBackend,Et as LRN,St as LRNGrad,ht as LeakyRelu,dt as Less,ft as LessEqual,pt as LinSpace,gt as Log,mt as Log1p,vt as LogSoftmax,bt as LogicalAnd,yt as LogicalNot,wt as LogicalOr,kt as LogicalXor,xt as LowerBound,$t as MatrixBandPart,At as Max,It as MaxPool,Nt as MaxPool3D,Tt as MaxPool3DGrad,Mt as MaxPoolGrad,Dt as MaxPoolWithArgmax,_t as Maximum,Rt as Mean,Ft as Min,Bt as Minimum,Ct as MirrorPad,Pt as Mod,Ud as MomentumOptimizer,Ot as Multinomial,Lt as Multiply,zt as Neg,Wt as NonMaxSuppressionV3,Gt as NonMaxSuppressionV4,Kt as NonMaxSuppressionV5,Ut as NotEqual,so as OP_SCOPE_SUFFIX,Vt as OneHot,qt as OnesLike,Bd as Optimizer,Af as OptimizerConstructors,Ht as Pack,jt as PadV2,Jt as Pool,Zt as Pow,Yt as Prelu,Xt as Prod,Wd as RMSPropOptimizer,Qt as RaggedGather,en as RaggedRange,tn as RaggedTensorToTensor,nn as Range,Is as Rank,rn as Real,ze as RealDiv,sn as Reciprocal,id as Reduction,on as Relu,dn as Relu6,an as Reshape,cn as ResizeBilinear,hn as ResizeBilinearGrad,ln as ResizeNearestNeighbor,un as ResizeNearestNeighborGrad,fn as Reverse,sr as RotateWithOffset,pn as Round,gn as Rsqrt,zd as SGDOptimizer,mn as ScatterNd,yn as SearchSorted,wn as Select,kn as Selu,$n as Sigmoid,Sn as Sign,xn as Sin,En as Sinh,vn as Slice,Tn as Softmax,An as Softplus,Mn as SpaceToBatchND,Dn as SparseFillEmptyRows,Rn as SparseReshape,Fn as SparseSegmentMean,Bn as SparseSegmentSum,Cn as SparseToDense,Nn as SplitV,_n as Sqrt,On as Square,Pn as SquaredDifference,Ln as StaticRegexReplace,nr as Step,zn as StridedSlice,Un as StringNGrams,Wn as StringSplit,Gn as StringToHashBucketFast,Kn as Sub,In as Sum,qn as Tan,Vn as Tanh,$s as Tensor,xs as TensorBuffer,bn as TensorScatterUpdate,Hn as Tile,jn as TopK,Jn as Transform,Zn as Transpose,Yn as Unique,Xn as Unpack,Qn as UnsortedSegmentSum,er as UpperBound,_s as Variable,tr as ZerosLike,or as _FusedMatMul,Aa as abs,_a as acos,Ia as acosh,xa as add,Ma as addN,Na as all,Ta as any,Da as argMax,Ra as argMin,Fa as asin,Ba as asinh,Ca as atan,Pa as atan2,Oa as atanh,Qa as avgPool,ei as avgPool3d,To as backend,Rf as backend_util,ai as basicLSTMCell,li as batchNorm,ui as batchNorm2d,ci as batchNorm3d,hi as batchNorm4d,ii as batchToSpaceND,di as bincount,fi as bitwiseAnd,ih as booleanMaskAsync,pi as broadcastArgs,gi as broadcastTo,Wi as broadcast_util,df as browser,ya as buffer,wa as cast,mi as ceil,yi as clipByValue,ka as clone,ao as complex,ti as concat,wi as concat1d,ki as concat2d,vi as concat3d,xi as concat4d,Si as conv1d,Ei as conv2d,Ai as conv2dTranspose,_i as conv3d,Mi as conv3dTranspose,yr as copyRegisteredKernels,Ni as cos,Ti as cosh,gh as cosineWindow,Di as cumprod,Ri as cumsum,Cl as customGrad,Fi as denseBincount,go as deprecationWarn,Bi as depthToSpace,Ci as depthwiseConv2d,Ys as device_util,Pi as diag,Oi as dilation2d,po as disableDeprecationWarnings,vo as dispose,mo as disposeVariables,Sa as div,Vi as divNoNan,Hi as dot,fh as dropout,ji as einsum,Ji as elu,fo as enableDebugMode,ho as enableProdMode,ph as enclosingPowerOfTwo,bo as engine,Zi as ensureShape,O as env,Gi as equal,Yi as erf,cl as euclideanNorm,hl as exp,dl as expandDims,fl as expm1,gl as eye,Nc as fft,bi as fill,Io as findBackend,Mo as findBackendFactory,ml as floor,Ea as floorDiv,_h as fused,bl as gather,dh as gatherND,pf as gather_util,Ao as getBackend,dr as getGradient,hr as getKernel,fr as getKernelsForBackend,Tl as grad,Dl as grads,yl as greater,wl as greaterEqual,Tc as ifft,kl as imag,Sd as image,mh as inTopKAsync,sf as io,Dc as irfft,vl as isFinite,xl as isInf,El as isNaN,xo as keep,Ff as kernel_impls,Sl as leakyRelu,$l as less,Al as lessEqual,$d as linalg,_l as linspace,Il as localResponseNormalization,Ml as log,Nl as log1p,zl as logSigmoid,Wl as logSoftmax,Gl as logSumExp,Kl as logicalAnd,ql as logicalNot,Vl as logicalOr,Hl as logicalXor,Ad as losses,Jl as lowerBound,ni as matMul,of as math,tl as max,Zl as maxPool,Yl as maxPool3d,Xl as maxPoolWithArgmax,Ql as maximum,eu as mean,yo as memory,ru as meshgrid,nl as min,su as minimum,ou as mirrorPad,au as mod,iu as moments,uh as movingAverage,$a as mul,lu as multiRNNCell,uu as multinomial,Ol as neg,Mf as nextFrame,ul as norm,cu as notEqual,hu as oneHot,nu as ones,du as onesLike,oo as op,fu as outerProduct,pu as pad,gu as pad1d,mu as pad2d,bu as pad3d,yu as pad4d,ku as pool,rl as pow,vu as prelu,va as print,xu as prod,wo as profile,Eu as raggedGather,Su as raggedRange,$u as raggedTensorToTensor,Au as rand,nc as randomGamma,rc as randomNormal,sc as randomStandardNormal,oc as randomUniform,ac as randomUniformInt,ic as range,$o as ready,lc as real,uc as reciprocal,No as registerBackend,gr as registerGradient,pr as registerKernel,cc as relu,hc as relu6,_o as removeBackend,Xa as reshape,dc as reverse,fc as reverse1d,pc as reverse2d,gc as reverse3d,mc as reverse4d,Fc as rfft,bc as round,yc as rsqrt,sl as scalar,ch as scatterND,Zc as scatter_util,jl as searchSorted,wc as selu,kc as separableConv2d,Fd as serialization,So as setBackend,Do as setPlatform,vc as setdiff1dAsync,ri as sigmoid,xc as sign,Ed as signal,Ec as sin,Sc as sinh,si as slice,$c as slice1d,Ac as slice2d,_c as slice3d,Ic as slice4d,Sf as slice_util,Mc as softmax,Ll as softplus,wu as spaceToBatchND,_d as sparse,hh as sparseToDense,xd as spectral,Rc as split,ol as sqrt,al as square,Bc as squaredDifference,Cc as squeeze,Pc as stack,Oc as step,Lc as stridedSlice,Id as string,Ul as sub,il as sum,Bs as sumOutType,zc as tan,oi as tanh,lo as tensor,Uc as tensor1d,Wc as tensor2d,Gc as tensor3d,Kc as tensor4d,qc as tensor5d,Vc as tensor6d,Yc as tensorScatterUpdate,Ws as tensor_util,Xu as test_util,ko as tidy,pl as tile,Eo as time,Xc as topk,_f as train,lh as transpose,Qc as truncatedNormal,eh as unique,br as unregisterGradient,mr as unregisterKernel,th as unsortedSegmentSum,nh as unstack,Fs as upcastType,rh as upperBound,fs as util,Rl as valueAndGrad,Fl as valueAndGrads,sh as variable,Bl as variableGrads,$f as version_core,Ki as where,ah as whereAsync,tu as zeros,qi as zerosLike}; //# sourceMappingURL=tf-core.fesm.min.js.map