/** * @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,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).tf=e.tf||{})}(this,(function(e){"use strict";function t(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 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=>p(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 M(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 M(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 F(e){return e&&e.then&&"function"==typeof e.then}const C="tfjsflags";class P{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=O,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&(L().getBool("IS_TEST")||L().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];L().getBool("IS_TEST")||L().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(F(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(C 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 O(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 L(){return e.ENV}let z;function U(){if(null==z){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}z=e}return z}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)}}e.ENV=null;const G="Acos",q="Acosh",K="Add",V="AddN",H="ArgMax",j="ArgMin",J="Asin",Z="Asinh",Y="Atan",X="Atanh",Q="Atan2",ee="AvgPool",te="AvgPool3D",ne="BatchMatMul",re="BatchToSpaceND",se="Bincount",oe="BitwiseAnd",ae="BroadcastArgs",ie="Cast",le="Ceil",ue="ClipByValue",ce="Complex",he="ComplexAbs",de="Concat",pe="Conv2D",fe="Conv2DBackpropFilter",ge="Conv2DBackpropInput",me="Conv3D",be="Conv3DBackpropInputV2",ye="Cosh",we="Cumprod",ke="Cumsum",ve="CropAndResize",xe="DenseBincount",Ee="DepthToSpace",Se="DepthwiseConv2dNative",$e="DepthwiseConv2dNativeBackpropFilter",Ae="DepthwiseConv2dNativeBackpropInput",_e="Diag",Ie="Dilation2D",Ne="Draw",Me="RealDiv",Te="Einsum",De="Equal",Re="ExpandDims",Be="Expm1",Fe="Fill",Ce="FlipLeftRight",Pe="Floor",Oe="FloorDiv",Le="FusedBatchNorm",ze="GatherV2",Ue="GatherNd",We="Greater",Ge="GreaterEqual",qe="Identity",Ke="IFFT",Ve="Imag",He="IsFinite",je="IsInf",Je="IsNan",Ze="LeakyRelu",Ye="Less",Xe="LessEqual",Qe="LinSpace",et="Log1p",tt="LogicalAnd",nt="LogicalNot",rt="LogicalOr",st="Maximum",ot="MaxPool",at="MaxPool3D",it="MaxPoolWithArgmax",lt="Mean",ut="Minimum",ct="MirrorPad",ht="Multinomial",dt="Multiply",pt="NotEqual",ft="NonMaxSuppressionV3",gt="NonMaxSuppressionV4",mt="NonMaxSuppressionV5",bt="OnesLike",yt="OneHot",wt="Pack",kt="PadV2",vt="Prelu",xt="Prod",Et="RaggedGather",St="RaggedRange",$t="RaggedTensorToTensor",At="Range",_t="Real",It="Reciprocal",Nt="Relu",Mt="Reshape",Tt="ResizeNearestNeighbor",Dt="ResizeBilinear",Rt="Relu6",Bt="Reverse",Ft="Round",Ct="Rsqrt",Pt="ScatterNd",Ot="TensorScatterUpdate",Lt="SearchSorted",zt="Select",Ut="Selu",Wt="Slice",Gt="Sinh",qt="Sign",Kt="Sigmoid",Vt="Softplus",Ht="Sqrt",jt="SpaceToBatchND",Jt="SplitV",Zt="Softmax",Yt="SparseFillEmptyRows",Xt="SparseReshape",Qt="SparseSegmentMean",en="SparseSegmentSum",tn="SparseToDense",nn="SquaredDifference",rn="StaticRegexReplace",sn="StridedSlice",on="StringNGrams",an="StringSplit",ln="StringToHashBucketFast",un="Tanh",cn="Tile",hn="TopK",dn="Transform",pn="Transpose",fn="Unique",gn="Unpack",mn="UnsortedSegmentSum",bn="ZerosLike",yn="Step",wn="FromPixels",kn="RotateWithOffset",vn="_FusedMatMul",xn="FusedConv2D",En="FusedDepthwiseConv2D";function Sn(...e){L().getBool("IS_TEST")||L().getBool("PROD")||console.warn(...e)}const $n=W("kernelRegistry",(()=>new Map)),An=W("gradRegistry",(()=>new Map));function _n(e,t){const n=Tn(e,t);return $n.get(n)}function In(e){return An.get(e)}function Nn(e){const t=$n.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 Mn(e){const{kernelName:t,backendName:n}=e,r=Tn(t,n);$n.has(r)&&Sn(`The kernel '${t}' for backend '${n}' is already registered`),$n.set(r,e)}function Tn(e,t){return`${t}_${e}`}function Dn(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}var Rn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Bn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Fn=Pn,Cn=null;try{Cn=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 Pn(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function On(e){return!0===(e&&e.__isLong__)}Pn.prototype.__isLong__,Object.defineProperty(Pn.prototype,"__isLong__",{value:!0}),Pn.isLong=On;var Ln={},zn={};function Un(e,t){var n,r,s;return t?(s=0<=(e>>>=0)&&e<256)&&(r=zn[e])?r:(n=Gn(e,(0|e)<0?-1:0,!0),s&&(zn[e]=n),n):(s=-128<=(e|=0)&&e<128)&&(r=Ln[e])?r:(n=Gn(e,e<0?-1:0,!1),s&&(Ln[e]=n),n)}function Wn(e,t){if(isNaN(e))return t?Xn:Yn;if(t){if(e<0)return Xn;if(e>=jn)return rr}else{if(e<=-Jn)return sr;if(e+1>=Jn)return nr}return e<0?Wn(-e,t).neg():Gn(e%Hn|0,e/Hn|0,t)}function Gn(e,t,n){return new Pn(e,t,n)}Pn.fromInt=Un,Pn.fromNumber=Wn,Pn.fromBits=Gn;var qn=Math.pow;function Kn(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return Yn;if("number"==typeof t?(n=t,t=!1):t=!!t,(n=n||10)<2||360)throw Error("interior hyphen");if(0===r)return Kn(e.substring(1),t,n).neg();for(var s=Wn(qn(n,8)),o=Yn,a=0;a>>0:this.low},or.toNumber=function(){return this.unsigned?(this.high>>>0)*Hn+(this.low>>>0):this.high*Hn+(this.low>>>0)},or.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}},or.getHighBits=function(){return this.high},or.getHighBitsUnsigned=function(){return this.high>>>0},or.getLowBits=function(){return this.low},or.getLowBitsUnsigned=function(){return this.low>>>0},or.getNumBitsAbs=function(){if(this.isNegative())return this.eq(sr)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<=0},or.isOdd=function(){return 1==(1&this.low)},or.isEven=function(){return 0==(1&this.low)},or.equals=function(e){return On(e)||(e=Vn(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},or.eq=or.equals,or.notEquals=function(e){return!this.eq(e)},or.neq=or.notEquals,or.ne=or.notEquals,or.lessThan=function(e){return this.comp(e)<0},or.lt=or.lessThan,or.lessThanOrEqual=function(e){return this.comp(e)<=0},or.lte=or.lessThanOrEqual,or.le=or.lessThanOrEqual,or.greaterThan=function(e){return this.comp(e)>0},or.gt=or.greaterThan,or.greaterThanOrEqual=function(e){return this.comp(e)>=0},or.gte=or.greaterThanOrEqual,or.ge=or.greaterThanOrEqual,or.compare=function(e){if(On(e)||(e=Vn(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},or.comp=or.compare,or.negate=function(){return!this.unsigned&&this.eq(sr)?sr:this.not().add(Qn)},or.neg=or.negate,or.add=function(e){On(e)||(e=Vn(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,Gn((c&=65535)<<16|(h&=65535),(l&=65535)<<16|(u&=65535),this.unsigned)},or.subtract=function(e){return On(e)||(e=Vn(e)),this.add(e.neg())},or.sub=or.subtract,or.multiply=function(e){if(this.isZero())return Yn;if(On(e)||(e=Vn(e)),Cn)return Gn(Cn.mul(this.low,this.high,e.low,e.high),Cn.get_high(),this.unsigned);if(e.isZero())return Yn;if(this.eq(sr))return e.isOdd()?sr:Yn;if(e.eq(sr))return this.isOdd()?sr:Yn;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(Zn)&&e.lt(Zn))return Wn(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,Gn((h&=65535)<<16|(d&=65535),(u&=65535)<<16|(c&=65535),this.unsigned)},or.mul=or.multiply,or.divide=function(e){if(On(e)||(e=Vn(e)),e.isZero())throw Error("division by zero");var t,n,r;if(Cn)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?Gn((this.unsigned?Cn.div_u:Cn.div_s)(this.low,this.high,e.low,e.high),Cn.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?Xn:Yn;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Xn;if(e.gt(this.shru(1)))return er;r=Xn}else{if(this.eq(sr))return e.eq(Qn)||e.eq(tr)?sr:e.eq(sr)?Qn:(t=this.shr(1).div(e).shl(1)).eq(Yn)?e.isNegative()?Qn:tr:(n=this.sub(e.mul(t)),r=t.add(n.div(e)));if(e.eq(sr))return this.unsigned?Xn:Yn;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=Yn}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:qn(2,s-48),a=Wn(t),i=a.mul(e);i.isNegative()||i.gt(n);)i=(a=Wn(t-=o,this.unsigned)).mul(e);a.isZero()&&(a=Qn),r=r.add(a),n=n.sub(i)}return r},or.div=or.divide,or.modulo=function(e){return On(e)||(e=Vn(e)),Cn?Gn((this.unsigned?Cn.rem_u:Cn.rem_s)(this.low,this.high,e.low,e.high),Cn.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},or.mod=or.modulo,or.rem=or.modulo,or.not=function(){return Gn(~this.low,~this.high,this.unsigned)},or.and=function(e){return On(e)||(e=Vn(e)),Gn(this.low&e.low,this.high&e.high,this.unsigned)},or.or=function(e){return On(e)||(e=Vn(e)),Gn(this.low|e.low,this.high|e.high,this.unsigned)},or.xor=function(e){return On(e)||(e=Vn(e)),Gn(this.low^e.low,this.high^e.high,this.unsigned)},or.shiftLeft=function(e){return On(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?Gn(this.low<>>32-e,this.unsigned):Gn(0,this.low<>>e|this.high<<32-e,this.high>>e,this.unsigned):Gn(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},or.shr=or.shiftRight,or.shiftRightUnsigned=function(e){if(On(e)&&(e=e.toInt()),0===(e&=63))return this;var t=this.high;return e<32?Gn(this.low>>>e|t<<32-e,t>>>e,this.unsigned):Gn(32===e?t:t>>>e-32,0,this.unsigned)},or.shru=or.shiftRightUnsigned,or.shr_u=or.shiftRightUnsigned,or.toSigned=function(){return this.unsigned?Gn(this.low,this.high,!1):this},or.toUnsigned=function(){return this.unsigned?this:Gn(this.low,this.high,!0)},or.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},or.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]},or.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]},Pn.fromBytes=function(e,t,n){return n?Pn.fromBytesLE(e,t):Pn.fromBytesBE(e,t)},Pn.fromBytesLE=function(e,t){return new Pn(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},Pn.fromBytesBE=function(e,t){return new Pn(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var ar=Bn(Fn);const ir=ar||t({__proto__:null,default:ar},[Fn]);function lr(e){return ir.fromString(e,!0,16)}const ur=lr("c3a5c85c97cb3127"),cr=lr("b492b66fbe98f273"),hr=lr("9ae16a3b2f90404f");function dr(e){return e.xor(e.shru(47))}function pr(e,t,n){const r=e.slice(t,t+n);return ir.fromBytes(Array.from(r),!0,!0)}function fr(e,t){return pr(e,t,8)}function gr(e,t){return pr(e,t,4)}function mr(e,t){return 0===t?e:e.shru(t).or(e.shl(64-t))}function br(e,t,n=lr("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 yr(e,t,n,r){return function(e,t,n,r,s,o){s=s.add(e),o=mr(o.add(s).add(r),21);const a=s;return s=(s=s.add(t)).add(n),o=o.add(mr(s,44)),[s.add(r),o.add(a)]}(fr(e,t),fr(e,t+8),fr(e,t+16),fr(e,t+24),n,r)}function wr(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=Sr(e)),L().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=hr.add(2*t),r=fr(e,0).add(hr),s=fr(e,t-8);return br(mr(s,37).mul(n).add(r),mr(r,25).add(s).mul(n),n)}if(t>=4){const n=hr.add(2*t);return br(gr(e,0).shl(3).add(t),gr(e,t-4),n)}if(t>0){const n=e[0]+(e[t>>1]<<8),r=t+(e[t-1]<<2);return dr(hr.mul(n).xor(ur.mul(r))).mul(hr)}return hr}(e,t):function(e,t=e.length){const n=hr.add(2*t),r=fr(e,0).mul(cr),s=fr(e,8),o=fr(e,t-8).mul(n),a=fr(e,t-16).mul(hr);return br(mr(r.add(s),43).add(mr(o,30)).add(a),r.add(mr(s.add(hr),18)).add(o),n)}(e,t);if(t<=64)return function(e,t=e.length){const n=hr.add(2*t),r=fr(e,0).mul(hr),s=fr(e,8),o=fr(e,t-8).mul(n),a=fr(e,t-16).mul(hr),i=mr(r.add(s),43).add(mr(o,30)).add(a),l=br(i,r.add(mr(s.add(hr),18)).add(o),n),u=fr(e,16).mul(n),c=fr(e,24),h=i.add(fr(e,t-32)).mul(n),d=l.add(fr(e,t-24)).mul(n);return br(mr(u.add(c),43).add(mr(h,30)).add(d),u.add(mr(c.add(r),18)).add(h),n)}(e,t);let r=n,s=n.mul(cr).add(113),o=dr(s.mul(hr).add(113)).mul(hr),a=[ir.UZERO,ir.UZERO],i=[ir.UZERO,ir.UZERO];r=r.mul(hr).add(fr(e,0));let l=0;const u=64*(t-1>>6),c=u+(t-1&63)-63;do{r=mr(r.add(s).add(a[0]).add(fr(e,l+8)),37).mul(cr),s=mr(s.add(a[1]).add(fr(e,l+48)),42).mul(cr),r=r.xor(i[1]),s=s.add(a[0]).add(fr(e,l+40)),o=mr(o.add(i[0]),33).mul(cr),a=yr(e,l,a[1].mul(cr),r.add(i[0])),i=yr(e,l+32,o.add(i[1]),s.add(fr(e,l+16))),[o,r]=[r,o],l+=64}while(l!==u);const h=cr.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=mr(r.add(s).add(a[0]).add(fr(e,l+8)),37).mul(h),s=mr(s.add(a[1]).add(fr(e,l+48)),42).mul(h),r=r.xor(i[1].mul(9)),s=s.add(a[0].mul(9).add(fr(e,l+40))),o=mr(o.add(i[0]),33).mul(h),a=yr(e,l,a[1].mul(h),r.add(i[0])),i=yr(e,l+32,o.add(i[1]),s.add(fr(e,l+16))),[o,r]=[r,o],br(br(a[0],i[0],h).add(dr(s).mul(ur)).add(o),br(a[1],i[1],h).add(r),h)},flatten:Sr,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:lr,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:p,isNumber:$,isPromise:F,isScalarShape:function(e){return 0===e.length},isString:E,isTypedArray:Er,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:kr,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:f,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=kr();if(this.backendTimer.timerAvailable())o=this.backendTimer.time(s);else{s();for(const e of r)e.dataSync();o=Promise.resolve({kernelMs:kr()-a})}if(L().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t{_r(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 _r(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 Nr(e,t,n,r){const s=N(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?Rr(e):e;if(i>1)for(let e=0;e" "+e)).join("\n")),l.join("\n")}function Mr(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?Tr(e):parseFloat(e.toFixed(7)).toString(),f(r,t)}function Tr(e){return 0===e?"false":"true"}function Dr(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[Mr(Rr(e)[0],0,n)]}return"bool"===n?[Tr(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=Rr(r),o=Rr(o)),["["+r.map(((e,t)=>Mr(e,s[t],n))).join(", ")+", ..., "+o.map(((e,t)=>Mr(e,s[i-3+t],n))).join(", ")+"]"]}return["["+("complex64"===n?Rr(e):Array.from(e)).map(((e,t)=>Mr(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(...Dr(e.slice(r,o),u,n,c,s,!1))}d.push("...");for(let t=i-3;t0?d[0]+p:"");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=N(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;txr(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(),Fr().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=Fr().readSync(this.dataId);if("string"===this.dtype)try{return e.map((e=>xr(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 Fr().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),Fr().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Cr.print(this,e)}clone(){return this.throwIfDisposed(),Cr.clone(this)}toString(e=!1){return Nr(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Cr.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Fr().makeVariable(this,e,t,n)}}function Or(){return W("Tensor",(()=>Pr))}Object.defineProperty(Pr,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),Or();class Lr extends Pr{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`);Fr().disposeTensor(this),this.dataId=e.dataId,Fr().incRef(this,null)}dispose(){Fr().disposeVariable(this),this.isDisposedInternal=!0}}var zr,Ur,Wr,Gr,qr;Object.defineProperty(Lr,Symbol.hasInstance,{value:e=>e instanceof Pr&&null!=e.assign&&e.assign instanceof Function}),e.Rank=void 0,(zr=e.Rank||(e.Rank={})).R0="R0",zr.R1="R1",zr.R2="R2",zr.R3="R3",zr.R4="R4",zr.R5="R5",zr.R6="R6",function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(Ur||(Ur={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(Wr||(Wr={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(Gr||(Gr={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(qr||(qr={}));const Kr={float32:Gr,int32:Ur,bool:Wr,complex64:qr};function Vr(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return Kr[e][t]}function Hr(e){return null!=e&&"object"==typeof e&&"texture"in e&&e.texture instanceof WebGLTexture}function jr(e){return"undefined"!=typeof GPUBuffer&&null!=e&&"object"==typeof e&&"buffer"in e&&e.buffer instanceof GPUBuffer}function Jr(e,t){if(e.dtype===t.dtype)return[e,t];const n=Vr(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function Zr(e,t){i(e.dtype===t.dtype,(()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`))}function Yr(e){const t=[];return Xr(e,t,new Set),t}function Xr(e,t,n){if(null==e)return;if(e instanceof Pr)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),Xr(r,t,n))}}var Qr={__proto__:null,assertTypesMatch:Zr,getTensorsInContainer:Yr,isTensorInList:function(e,t){return t.some((t=>t.id===e.id))},makeTypesMatch:Jr};function es(e){return null!=e.kernelName}class ts{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 ns{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new ts}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){Nn(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 ns.nextTensorId++}nextVariableId(){return ns.nextVariableId++}clone(e){const t=ss.runKernel(qe,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e},n={dtype:"float32"};return ss.runKernel(ie,t,n)}})),[],{}),t}runKernel(e,t,n){null==this.backendName&&this.backend;if(!(null!=_n(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=es(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(es(e)){const{kernelName:t,inputs:s,attrs:o}=e;null==this.backendName&&this.backend;const u=_n(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=es(e)?null:e.backwardsFunc;let p;return this.scopedRun((()=>this.state.kernelDepth++),(()=>this.state.kernelDepth--),(()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(p=this.profiler.profileKernel(u,c,(()=>a())),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),t=p.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:p.timeMs,extraInfo:p.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=In(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=>vr(e))));const o=r.write(s,t,n),a=new Pr(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 Pr(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 Lr(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 Lr||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=In(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=Yr(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 Pr,(()=>"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 ss.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)),os);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 Pr)),(()=>"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 Pr,(()=>"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 Pr)),(()=>"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=kr(),n=await this.backend.time(e);return n.wallMs=kr()-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 ts;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 rs(){const t=U();if(null==t._tfengine){const e=new P(t);t._tfengine=new ns(e)}var n;return n=t._tfengine.ENV,e.ENV=n,Fr=()=>t._tfengine,t._tfengine}ns.nextTensorId=0,ns.nextVariableId=0;const ss=rs();function os(e,t){const n={a:e,b:t};return ss.runKernel(K,n)}let as;function is(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}var ls={__proto__:null,isBrowser:is,isMobile:function(e){if(void 0!==as)return as;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){as=e}};const us=L();function cs(e,t){let n=e;if(Er(e))return"string"===t?[]:[e.length];if(Hr(e)){const t=e.channels||"RGBA";return[e.height,e.width*t.length]}if(jr(e))return[e.buffer.size/(null==t?4:v(t))];if(!Array.isArray(e))return[];const r=[];for(;Array.isArray(n)||Er(n)&&"string"!==t;)r.push(n.length),n=n[0];return Array.isArray(e)&&L().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&hs(e,r,[]),r}function hs(e,t,n){if(n=n||[],!Array.isArray(e)&&!Er(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),ds(r,s,t,n),null==e||!Er(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=cs(e,s);Er(e)||Array.isArray(e)||(e=[e]);const a="string"!==s?wr(e,s):Sr(e,[],!0);return ss.makeTensor(a,o,s)}function fs(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)=>ps(e,`${t}[${s}]`,n,r)))}us.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.")})),us.registerFlag("IS_BROWSER",(()=>is())),us.registerFlag("IS_NODE",(()=>"undefined"!=typeof process&&"undefined"!=typeof process.versions&&"undefined"!=typeof process.versions.node)),us.registerFlag("IS_CHROME",(()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor))),us.registerFlag("IS_SAFARI",(()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor))),us.registerFlag("PROD",(()=>!1)),us.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(()=>us.getBool("DEBUG"))),us.registerFlag("DEPRECATION_WARNINGS_ENABLED",(()=>!0)),us.registerFlag("IS_TEST",(()=>!1)),us.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",(()=>us.getBool("DEBUG"))),us.registerFlag("WRAP_TO_IMAGEBITMAP",(()=>!1)),us.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",(()=>!1)),us.registerFlag("USE_SETTIMEOUTCUSTOM",(()=>!1));const gs="__op";function ms(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+=gs;const s=(...e)=>{ss.startScope(n);try{const t=r(...e);return F(t)&&console.error("Cannot return a Promise inside of tidy."),ss.endScope(t),t}catch(e){throw ss.endScope(null),e}};return Object.defineProperty(s,"name",{value:n,configurable:!0}),s}const bs=ms({complex_:function(e,t){const n=ps(e,"real","complex"),r=ps(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 ss.runKernel(ce,s)}});function ys(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(jr(e)||Hr(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 ss.backend.createTensorFromGPUData(e,t||n,r)}if(!Er(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){B(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 Er(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==r?wr(e,r):Sr(e,[],!0),ss.makeTensor(e,t,r)}function ws(e,t,n){return ys(e,t,cs(e,n),n)}const ks={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};class vs{static join(e){return new vs(e).slice()}constructor(e){if(this.shards=[],this.previousShardIndex=0,null==e)return;if(e instanceof Array||(e=[e]),0===(e=e.map((e=>Er(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 xs(e,t){return ss.tidy(e,t)}function Es(e){Yr(e).forEach((e=>e.dispose()))}function Ss(e){return ss.keep(e)}function $s(){return ss.backendName}function As(){return ss.backend}function _s(e,t){const n=new vs(e),r={};let s=0;for(const e of t){const t=Is(e,((e,t)=>n.slice(s+e,s+t)));r[e.name]=Ms(e,n.slice(s,s+t)),s+=t}return r}function Is(e,t){const n=c(e.shape);let r;if("quantization"in e){const t=e.quantization;r=ks[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 Rs="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function Bs(e){return Rs?Buffer.byteLength(e,"utf8"):new Blob([e]).size}function Fs(e){for(e=e.trim();e.endsWith("/");)e=e.slice(0,e.length-1);const t=e.split("/");return t[t.length-1]}function Cs(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 Ps(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 Os(e,t){let n,r;return null!=e.weightsManifest&&([n,r]=await t(e.weightsManifest)),Ps(e,n,r)}function Ls(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:Bs(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:Bs(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:new vs(e.weightData).byteLength}}function zs(e){const t=[];for(const n of e)t.push(...n.weights);return t}class Us{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==Us.instance&&(Us.instance=new Us),Us.instance}static registerSaveRouter(e){Us.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Us.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Us.getHandlers(e,"save")}static getLoadHandlers(e,t){return Us.getHandlers(e,"load",t)}static getHandlers(e,t,n){const r=[];return("load"===t?Us.getInstance().loadRouters:Us.getInstance().saveRouters).forEach((t=>{const s=t(e,n);null!==s&&r.push(s)})),r}}const Ws="tensorflowjs",Gs="models_store",qs="model_info_store";function Ks(){if(!L().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 Vs(e){const t=e.result;t.createObjectStore(Gs,{keyPath:"modelPath"}),t.createObjectStore(qs,{keyPath:"modelPath"})}class Hs{constructor(e){if(this.indexedDB=Ks(),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(Ws,1);r.onupgradeneeded=()=>Vs(r),r.onsuccess=()=>{const s=r.result;if(null==t){const t=s.transaction(Gs,"readonly"),r=t.objectStore(Gs).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=vs.join(t.weightData);const r=Ls(t),o=s.transaction(qs,"readwrite");let a,i,l=o.objectStore(qs);try{a=l.put({modelPath:this.modelPath,modelArtifactsInfo:r})}catch(e){return n(e)}a.onsuccess=()=>{i=s.transaction(Gs,"readwrite");const a=i.objectStore(Gs);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(qs);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)}))}}Hs.URL_SCHEME="indexeddb://";const js=e=>{return L().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Hs.URL_SCHEME)?(t=e.slice(Hs.URL_SCHEME.length),new Hs(t)):null;var t};Us.registerSaveRouter(js),Us.registerLoadRouter(js);class Js{constructor(){this.indexedDB=Ks()}async listModels(){return new Promise(((e,t)=>{const n=this.indexedDB.open(Ws,1);n.onupgradeneeded=()=>Vs(n),n.onsuccess=()=>{const r=n.result,s=r.transaction(qs,"readonly"),o=s.objectStore(qs).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(Hs.URL_SCHEME)?t.slice(Hs.URL_SCHEME.length):t,new Promise(((t,n)=>{const r=this.indexedDB.open(Ws,1);r.onupgradeneeded=()=>Vs(r),r.onsuccess=()=>{const s=r.result,o=s.transaction(qs,"readwrite"),a=o.objectStore(qs),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(Gs,"readwrite");const r=l.objectStore(Gs).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 Zs="/",Ys="tensorflowjs_models",Xs="info",Qs="model_topology",eo="weight_specs",to="weight_data",no="model_metadata";function ro(e){return{info:[Ys,e,Xs].join(Zs),topology:[Ys,e,Qs].join(Zs),weightSpecs:[Ys,e,eo].join(Zs),weightData:[Ys,e,to].join(Zs),modelMetadata:[Ys,e,no].join(Zs)}}function so(e){for(const t of Object.values(e))window.localStorage.removeItem(t)}function oo(e){const t=e.split(Zs);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Zs)}class ao{constructor(e){if(!L().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=ro(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=Ls(e),s=vs.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(Rs)return Buffer.from(e).toString("base64");const t=new Uint8Array(e);let n="";for(let e=0,r=t.length;e{return L().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ao.URL_SCHEME)?(t=e.slice(ao.URL_SCHEME.length),new ao(t)):null;var t};Us.registerSaveRouter(io),Us.registerLoadRouter(io);class lo{constructor(){i(L().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=Ys+Zs,n=Zs+Xs;for(let r=0;r"scheme must not be undefined or null.")),e.endsWith(uo)&&(e=e.slice(0,e.indexOf(uo))),i(e.length>0,(()=>"scheme must not be an empty string."));const n=co.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=co.getInstance().managers[e];if(null==t)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(co.getInstance().managers)}}function ho(e){if(-1===e.indexOf(uo))throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${co.getSchemes().join(",")}`);return{scheme:e.split(uo)[0],path:e.split(uo)[1]}}async function po(e,t,n=!1){i(e!==t,(()=>`Old path and new path are the same: '${e}'`));const r=Us.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=Us.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=ho(e).scheme,u=ho(e).path,c=l===ho(e).scheme,h=await s.load();n&&c&&await co.getManager(l).removeModel(u);const d=await a.save(h);return n&&!c&&await co.getManager(l).removeModel(u),d.modelArtifactsInfo}class fo{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&&L().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 Dn(e)}}if(L().get("IS_BROWSER")){L().setPlatform("browser",new fo);try{co.registerManager(ao.URL_SCHEME,new lo)}catch(e){}try{co.registerManager(Hs.URL_SCHEME,new Js)}catch(e){}}const go=()=>require("node-fetch");let mo;class bo{constructor(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return null!=L().global.fetch?L().global.fetch(e,t):(null==mo&&(mo=go()),mo(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 yo(e,t="float32",n){return t=t||"float32",B(e),new Br(e,t,n)}L().get("IS_NODE")&&!L().get("IS_BROWSER")&&L().setPlatform("node",new bo);const wo=ms({cast_:function(e,t){const n=ps(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 ss.runKernel(ie,r,s)}});const ko=ms({clone_:function(e){const t={x:ps(e,"x","clone","string_or_numeric")};return ss.runKernel(qe,t)}});function vo(e,t=!1){console.log(e.toString(t))}rs();Cr={buffer:yo,cast:wo,clone:ko,print:vo};const xo=ms({add_:function(e,t){let n=ps(e,"a","add"),r=ps(t,"b","add");[n,r]=Jr(n,r);const s={a:n,b:r};return ss.runKernel(K,s)}});const Eo=ms({floorDiv_:function(e,t){let n=ps(e,"a","floorDiv"),r=ps(t,"b","floorDiv");[n,r]=Jr(n,r);const s={a:n,b:r};return ss.runKernel(Oe,s)}});const So=ms({div_:function(e,t){let n=ps(e,"a","div"),r=ps(t,"b","div");if([n,r]=Jr(n,r),"int32"===n.dtype&&"int32"===r.dtype)return Eo(n,r);const s={a:n,b:r};return ss.runKernel(Me,s,{})}});const $o=ms({mul_:function(e,t){let n=ps(e,"a","mul"),r=ps(t,"b","mul");[n,r]=Jr(n,r);const s={a:n,b:r};return ss.runKernel(dt,s)}});const Ao=ms({abs_:function(e){const t=ps(e,"x","abs");if("complex64"===t.dtype){const e={x:t};return ss.runKernel(he,e)}{const e={x:t};return ss.runKernel("Abs",e)}}});const _o=ms({acos_:function(e){const t={x:ps(e,"x","acos")};return ss.runKernel(G,t)}});const Io=ms({acosh_:function(e){const t={x:ps(e,"x","acosh")};return ss.runKernel(q,t)}});const No=ms({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)=>ps(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 ss.runKernel(V,r)}});const Mo=ms({all_:function(e,t=null,n=!1){const r={x:ps(e,"x","all","bool")},s={axis:t,keepDims:n};return ss.runKernel("All",r,s)}});const To=ms({any_:function(e,t=null,n=!1){const r={x:ps(e,"x","any","bool")},s={axis:t,keepDims:n};return ss.runKernel("Any",r,s)}});const Do=ms({argMax_:function(e,t=0){const n={x:ps(e,"x","argMax")},r={axis:t};return ss.runKernel(H,n,r)}});const Ro=ms({argMin_:function(e,t=0){const n={x:ps(e,"x","argMin")},r={axis:t};return ss.runKernel(j,n,r)}});const Bo=ms({asin_:function(e){const t={x:ps(e,"x","asin")};return ss.runKernel(J,t)}});const Fo=ms({asinh_:function(e){const t={x:ps(e,"x","asinh")};return ss.runKernel(Z,t)}});const Co=ms({atan_:function(e){const t={x:ps(e,"x","atan")};return ss.runKernel(Y,t)}});const Po=ms({atan2_:function(e,t){let n=ps(e,"a","atan2"),r=ps(t,"b","atan2");[n,r]=Jr(n,r);const s={a:n,b:r};return ss.runKernel(Q,s)}});const Oo=ms({atanh_:function(e){const t={x:ps(e,"x","atanh")};return ss.runKernel(X,t)}});function Lo(e,t,n,r,s,o,a="channelsLast"){const[i,l]=Go(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 zo(e,u,n,r,s,o,!1,a)}function zo(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,p,,f]=t,[g,m]=Go(n),[b,y]=Go(r),w=Ko(d,b),k=Ko(p,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=Wo(e,t,n));const o=e[0],a=e[1],i=Vo((o-t+2*r)/n+1,s),l=Vo((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,p=Math.floor(i/2);u={top:l,bottom:d,left:p,right:i-p,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],p="channelsLast"===l?e[1][1]:e[2][1],f="channelsLast"===l?e[2][0]:e[3][0],g="channelsLast"===l?e[2][1]:e[3][1];u={top:d,bottom:p,left:f,right:g,type:0===d&&0===p&&0===f&&0===g?"VALID":"EXPLICIT"},c=Vo((t-o+d+p)/r+1,i),h=Vo((n-a+f+g)/s+1,i)}}return{padInfo:u,outHeight:c,outWidth:h}}(s,u,c,g,m,w,k,o,i),S=a?f*h:f;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:p,effectiveFilterHeight:w,effectiveFilterWidth:k,dilationHeight:b,dilationWidth:y,inShape:e,outShape:$,filterShape:t}}function Uo(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[p,f,g,,m]=t,[b,y,w]=qo(n),[k,v,x]=qo(r),E=Ko(p,k),S=Ko(f,v),$=Ko(g,x),{padInfo:A,outDepth:_,outHeight:I,outWidth:N}=function(e,t,n,r,s,o,a,i,l,u,c){let h,d,p,f;"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=Wo(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]=Vo((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],p=g[1],f=g[2]}else{if("same"!==e)throw Error(`Unknown padding parameter: ${e}`);{d=Math.ceil(t/s),p=Math.ceil(n/o),f=Math.ceil(r/a);const e=(d-1)*s+i-t,c=(p-1)*o+l-n,g=(f-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:p,outWidth:f}}(s,u,c,h,b,y,w,E,S,$,i),M=o?m*d:m;let T;return"channelsFirst"===a?T=[l,M,_,I,N]:"channelsLast"===a&&(T=[l,_,I,N,M]),{batchSize:l,dataFormat:a,inDepth:u,inHeight:c,inWidth:h,inChannels:d,outDepth:_,outHeight:I,outWidth:N,outChannels:M,padInfo:A,strideDepth:b,strideHeight:y,strideWidth:w,filterDepth:p,filterHeight:f,filterWidth:g,effectiveFilterDepth:E,effectiveFilterHeight:S,effectiveFilterWidth:$,dilationDepth:k,dilationHeight:v,dilationWidth:x,inShape:e,outShape:T,filterShape:t}}function Wo(e,t,n,r=1){const s=Ko(t,r);return Math.floor((e[0]*(n-1)-n+s)/2)}function Go(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function qo(e){return"number"==typeof e?[e,e,e]:e}function Ko(e,t){return t<=1?e:e+(e-1)*(t-1)}function Vo(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 Ho(e){const[t,n,r]=Go(e);return 1===t&&1===n&&1===r}function jo(e,t){return Ho(e)||Ho(t)}function Jo(e){return Go(e).every((e=>e>0))}function Zo(e){if("NHWC"===e)return"channelsLast";if("NCHW"===e)return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function Yo(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(p(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(p(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`))}))}))}}}const Xo=ms({reshape_:function(e,t){const n={x:ps(e,"x","reshape","string_or_numeric")},r={shape:t};return ss.runKernel(Mt,n,r)}});const Qo=ms({avgPool_:function(e,t,n,r,s){const o=ps(e,"x","avgPool","float32");i(jo(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=Xo(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}.`)),Yo("avgPool",r,s);const u={x:a},c={filterSize:t,strides:n,pad:r,dimRoundingMode:s};let h=ss.runKernel(ee,u,c);return h=wo(h,o.dtype),l?Xo(h,[h.shape[1],h.shape[2],h.shape[3]]):h}});const ea=ms({avgPool3d_:function(e,t,n,r,s,o="NDHWC"){const a=ps(e,"x","avgPool3d","float32");let l=a,u=!1;4===a.rank&&(u=!0,l=Xo(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}'`)),Yo("avgPool3d",r,s);const c={x:l},h={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:o};let d=ss.runKernel(te,c,h);return d=wo(d,l.dtype),u?Xo(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}});const ta=ms({concat_:function(e,t=0){i(e.length>=1,(()=>"Pass at least one tensor to concat"));const n=fs(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 ko(n[0]);const r=n,s={axis:t};return ss.runKernel(de,r,s)}});const na=ms({matMul_:function(e,t,n=!1,r=!1){let s=ps(e,"a","matMul"),o=ps(t,"b","matMul");[s,o]=Jr(s,o);const a={a:s,b:o},i={transposeA:n,transposeB:r};return ss.runKernel(ne,a,i)}});const ra=ms({sigmoid_:function(e){const t={x:ps(e,"x","sigmoid","float32")};return ss.runKernel(Kt,t)}});const sa=ms({slice_:function(e,t,n){const r=ps(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 ss.runKernel(Wt,s,o)}});const oa=ms({tanh_:function(e){const t={x:ps(e,"x","tanh","float32")};return ss.runKernel(un,t)}});const aa=ms({basicLSTMCell_:function(e,t,n,r,s,o){const a=ps(e,"forgetBias","basicLSTMCell"),i=ps(t,"lstmKernel","basicLSTMCell"),l=ps(n,"lstmBias","basicLSTMCell"),u=ps(r,"data","basicLSTMCell"),c=ps(s,"c","basicLSTMCell"),h=ps(o,"h","basicLSTMCell"),d=ta([u,h],1),p=na(d,i),f=xo(p,l),g=f.shape[0],m=f.shape[1]/4,b=[g,m],y=sa(f,[0,0],b),w=sa(f,[0,m],b),k=sa(f,[0,2*m],b),v=sa(f,[0,3*m],b),x=xo($o(ra(y),oa(w)),$o(c,ra(xo(a,k))));return[x,$o(oa(x),ra(v))]}});const ia=ms({batchToSpaceND_:function(e,t,n){const r=ps(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 ss.runKernel(re,o,a)}});const la=ms({batchNorm_:function(e,t,n,r,s,o){null==o&&(o=.001);const a=ps(e,"x","batchNorm"),l=ps(t,"mean","batchNorm"),u=ps(n,"variance","batchNorm");let c,h;null!=s&&(c=ps(s,"scale","batchNorm")),null!=r&&(h=ps(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?Xo(e,[1,1,1,e.size]):2===e.rank?Xo(e,[1,1,e.shape[0],e.shape[1]]):3===e.rank?Xo(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e,t}(a),p={x:d,scale:c,offset:h,mean:l,variance:u},f={varianceEpsilon:o},g=ss.runKernel(Le,p,f);return Xo(g,a.shape)}});const ua=ms({batchNorm2d_:function(e,t,n,r,s,o){const a=ps(e,"x","batchNorm"),l=ps(t,"mean","batchNorm"),u=ps(n,"variance","batchNorm");let c,h;return null!=s&&(c=ps(s,"scale","batchNorm")),null!=r&&(h=ps(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}.`)),la(a,l,u,h,c,o)}});const ca=ms({batchNorm3d_:function(e,t,n,r,s,o){const a=ps(e,"x","batchNorm"),l=ps(t,"mean","batchNorm"),u=ps(n,"variance","batchNorm");let c,h;return null!=s&&(c=ps(s,"scale","batchNorm")),null!=r&&(h=ps(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}.`)),la(a,l,u,h,c,o)}});const ha=ms({batchNorm4d_:function(e,t,n,r,s,o){const a=ps(e,"x","batchNorm"),l=ps(t,"mean","batchNorm"),u=ps(n,"variance","batchNorm");let c,h;return null!=s&&(c=ps(s,"scale","batchNorm")),null!=r&&(h=ps(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}.`)),la(a,l,u,h,c,o)}});const da=ms({bincount_:function(e,t,n){const r=ps(e,"x","bincount"),s=ps(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 ss.runKernel(se,o,a)}});const pa=ms({bitwiseAnd_:function(e,t){const n=ps(e,"x","bitwiseAnd"),r=ps(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 ss.runKernel(oe,s)}});const fa=ms({broadcastArgs_:function(e,t){const n=ps(e,"s0","broadcastArgs","int32"),r=ps(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 ss.runKernel(ae,s)}});const ga=ms({broadcastTo_:function(e,t){let n=ps(e,"broadcastTo","x");const r=n.shape;if(B(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 ko(n);const a={x:n},i={reps:o};return ss.runKernel(cn,a,i)}});const ma=ms({ceil_:function(e){const t={x:ps(e,"x","ceil","float32")};return ss.runKernel(le,t)}});function ba(e,t,n){B(e);const r={shape:e,value:t,dtype:n=n||A(t)};return ss.runKernel(Fe,{},r)}const ya=ms({clipByValue_:function(e,t,n){const r=ps(e,"x","clipByValue");if(i(t<=n,(()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`)),t===n)return ba(r.shape,t,r.dtype);const s={x:r},o={clipValueMin:t,clipValueMax:n};return ss.runKernel(ue,s,o)}});const wa=ms({concat1d_:function(e){return ta(e,0)}});const ka=ms({concat2d_:function(e,t){return ta(e,t)}});const va=ms({concat3d_:function(e,t){return ta(e,t)}});const xa=ms({concat4d_:function(e,t){return ta(e,t)}});const Ea=ms({conv2d_:function(e,t,n,r,s="NHWC",o=[1,1],a){const l=ps(e,"x","conv2d","float32"),u=ps(t,"filter","conv2d","float32");let c=l,h=!1;3===l.rank&&(h=!0,c=Xo(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}.`)),Yo("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(jo(n,o),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`)),i(Jo(o),(()=>"Error in conv2D: Dilated rates should be larger than 0.")),i(Jo(n),(()=>"Error in conv2D: Strides should be larger than 0."));const p={x:c,filter:u},f={strides:n,pad:r,dataFormat:s,dilations:o,dimRoundingMode:a},g=ss.runKernel(pe,p,f);return h?Xo(g,[g.shape[1],g.shape[2],g.shape[3]]):g}});const Sa=ms({conv1d_:function(e,t,n,r,s="NWC",o=1,a){const l=ps(e,"x","conv1d"),u=ps(t,"filter","conv1d");let c=l,h=!1;2===l.rank&&(h=!0,c=Xo(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}.`)),Yo("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(jo(n,o),(()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${o}'`)),i(Jo(o),(()=>"Error in conv1D: Dilated rates should be larger than 0.")),i(Jo(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=Xo(u,[1,u.shape[0],u.shape[1],u.shape[2]]),p=Xo(c,[c.shape[0],1,c.shape[1],c.shape[2]]),f=Ea(p,d,[1,n],r,"NHWC",[1,o],a);return Xo(f,h?[f.shape[2],f.shape[3]]:[f.shape[0],f.shape[2],f.shape[3]])}});const $a=ms({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=Xo(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]}.`)),Yo("conv2dDerInput",s,a);const p={dy:u,filter:n},f={strides:r,pad:s,dataFormat:o,dimRoundingMode:a,inputShape:l},g=ss.runKernel(ge,p,f);return c?Xo(g,[g.shape[1],g.shape[2],g.shape[3]]):g}});const Aa=ms({conv2dTranspose_:function(e,t,n,r,s,o){const a=ps(e,"x","conv2dTranspose"),i=ps(t,"filter","conv2dTranspose");return $a(n,a,i,r,s,"NHWC",o)}});const _a=ms({conv3d_:function(e,t,n,r,s="NDHWC",o=[1,1,1]){const a=ps(e,"x","conv3d"),l=ps(t,"filter","conv3d");let u=a,c=!1;4===a.rank&&(c=!0,u=Xo(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(jo(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(Jo(o),(()=>"Error in conv3D: Dilated rates should be larger than 0.")),i(Jo(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},p=ss.runKernel(me,h,d);return c?Xo(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}});const Ia=ms({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=Xo(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},p=ss.runKernel(be,h,d);return l?Xo(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}});const Na=ms({conv3dTranspose_:function(e,t,n,r,s){const o=ps(e,"x","conv3dTranspose"),a=ps(t,"filter","conv3dTranspose");return Ia(n,o,a,r,s)}});const Ma=ms({cos_:function(e){const t={x:ps(e,"x","cos","float32")};return ss.runKernel("Cos",t)}});const Ta=ms({cosh_:function(e){const t={x:ps(e,"x","cosh","float32")};return ss.runKernel(ye,t)}});const Da=ms({cumprod_:function(e,t=0,n=!1,r=!1){const s={x:ps(e,"x","cumprod")},o={axis:t,exclusive:n,reverse:r};return ss.runKernel(we,s,o)}});const Ra=ms({cumsum_:function(e,t=0,n=!1,r=!1){const s={x:ps(e,"x","cumsum")},o={axis:t,exclusive:n,reverse:r};return ss.runKernel(ke,s,o)}});const Ba=ms({denseBincount_:function(e,t,n,r=!1){const s=ps(e,"x","denseBincount"),o=ps(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 ss.runKernel(xe,a,l)}});const Fa=ms({depthToSpace_:function(e,t,n="NHWC"){const r=ps(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 ss.runKernel(Ee,l,u)}});const Ca=ms({depthwiseConv2d_:function(e,t,n,r,s="NHWC",o=[1,1],a){const l=ps(e,"x","depthwiseConv2d","float32"),u=ps(t,"filter","depthwiseConv2d","float32");let c=l,h=!1;3===l.rank&&(h=!0,c=Xo(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]}.`)),Yo("depthwiseConv2d",r,a);const p={x:c,filter:u},f={strides:n,pad:r,dataFormat:s,dilations:o,dimRoundingMode:a},g=ss.runKernel(Se,p,f);return h?Xo(g,[g.shape[1],g.shape[2],g.shape[3]]):g}});const Pa=ms({diag_:function(e){const t={x:ps(e,"x","diag")};return ss.runKernel(_e,t)}});const Oa=ms({dilation2d_:function(e,t,n,r,s=[1,1],o="NHWC"){const a=ps(e,"x","dilation2d"),l=ps(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=Xo(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},p=ss.runKernel(Ie,h,d);return c?Xo(p,[p.shape[1],p.shape[2],p.shape[3]]):p}});function La(e,t){const n=e.length,r=[];for(let s=0;s1&&1===a&&r.unshift(o)}return r}function za(e,t){const n=[];for(let r=0;r1)&&n.unshift(o)}return n}function Ua(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=Xo(n,[1,-1]),t=Xo(r,[-1,1]),s=na(e,t);return Xo(s,[])}if(1===n.rank&&2===r.rank){const e=Xo(n,[1,-1]),t=Xo(r,[r.shape[0],r.shape[1]]),s=na(e,t);return Xo(s,[s.size])}if(2===n.rank&&1===r.rank){const e=Xo(r,[-1,1]),t=na(n,e);return Xo(t,[t.size])}{const e=Xo(r,[r.shape[0],r.shape[1]]);return na(n,e)}}});const ja=ms({einsum_:function(e,...t){const n=t.map(((e,t)=>ps(e,`tensors${t}`,"einsum"))),r={equation:e};return ss.runKernel(Te,n,r)}});const Ja=ms({elu_:function(e){const t={x:ps(e,"x","elu","float32")};return ss.runKernel("Elu",t)}});const Za=ms({ensureShape_:function(e,t){const n=ps(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 Ya=ms({erf_:function(e){let t=ps(e,"x","erf");i("int32"===t.dtype||"float32"===t.dtype,(()=>"Input dtype must be `int32` or `float32`.")),"int32"===t.dtype&&(t=wo(t,"float32"));const n={x:t};return ss.runKernel("Erf",n)}});function Xa(e,t){for(let n=0;n1)),t)}const ti=ms({max_:function(e,t=null,n=!1){const r={x:ps(e,"x","max")},s={reductionIndices:t,keepDims:n};return ss.runKernel("Max",r,s)}});const ni=ms({min_:function(e,t=null,n=!1){const r={x:ps(e,"x","min")},s={axis:t,keepDims:n};return ss.runKernel("Min",r,s)}});const ri=ms({pow_:function(e,t){let n=ps(e,"base","pow"),r=ps(t,"exp","pow");[n,r]=Jr(n,r);const s={a:n,b:r};return ss.runKernel("Pow",s)}});function si(e,t){if((Er(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&&Er(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return ys(e,[],[],t)}const oi=ms({sqrt_:function(e){const t={x:ps(e,"x","sqrt","float32")};return ss.runKernel(Ht,t)}});const ai=ms({square_:function(e){const t=ps(e,"x","square");return ss.runKernel("Square",{x:t},{})}});const ii=ms({sum_:function(e,t=null,n=!1){let r=ps(e,"x","sum");"bool"===r.dtype&&(r=wo(r,"int32"));const s={x:r},o={axis:t,keepDims:n};return ss.runKernel("Sum",s,o)}});function li(e,t,n=null){if(0===e.rank)return Ao(e);if(1!==e.rank&&null===n)return li(Xo(e,[-1]),t,n);if(1===e.rank||"number"==typeof n||Array.isArray(n)&&1===n.length){if(1===t)return ii(Ao(e),n);if(t===1/0)return ti(Ao(e),n);if(t===-1/0)return ni(Ao(e),n);if("euclidean"===t||2===t)return oi(ii(ri(Ao(e),si(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&2===n.length){if(1===t)return ti(ii(Ao(e),n[0]),n[1]-1);if(t===1/0)return ti(ii(Ao(e),n[1]),n[0]);if(t===-1/0)return ni(ii(Ao(e),n[1]),n[0]);if("fro"===t||"euclidean"===t)return oi(ii(ai(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const ui=ms({norm_:function(e,t="euclidean",n=null,r=!1){const s=li(e=ps(e,"x","norm"),t,n);let o=s.shape;if(r){const t=g(n,e.shape);o=ei(s.shape,t)}return Xo(s,o)}});const ci=ms({euclideanNorm_:function(e,t=null,n=!1){return ui(e,"euclidean",t,n)}});const hi=ms({exp_:function(e){const t={x:ps(e,"x","exp")};return ss.runKernel("Exp",t)}});const di=ms({expandDims_:function(e,t=0){const n=ps(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 ss.runKernel(Re,r,s)}});const pi=ms({expm1_:function(e){const t={x:ps(e,"x","expm1")};return ss.runKernel(Be,t)}});const fi=ms({tile_:function(e,t){const n=ps(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 ss.runKernel(cn,r,s)}});const gi=ms({eye_:function(e,t,n,r="float32"){null==t&&(t=e);const s=yo([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(p(t),(()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`));let a=o,l=!1;3===o.rank&&(l=!0,a=Xo(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=ss.runKernel("LRN",u,c);return l?Xo(h,[h.shape[1],h.shape[2],h.shape[3]]):h}});const Ii=ms({log_:function(e){const t={x:ps(e,"x","log","float32")};return ss.runKernel("Log",t)}});const Ni=ms({log1p_:function(e){const t={x:ps(e,"x","log1p")};return ss.runKernel(et,t)}});function Mi(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 Lr)),(()=>"The varList passed in variableGrads(f, varList) must be an array of variables"));const n=null!=t;if(!n){t=[];for(const e in ss.registeredVariables)t.push(ss.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}=ss.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 Ti(e){return ss.customGrad(e)}function Di(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 Ri=ms({neg_:function(e){const t={x:ps(e,"x","neg")};return ss.runKernel("Neg",t)}});const Bi=ms({softplus_:function(e){const t={x:ps(e,"x","softplus")};return ss.runKernel(Vt,t)}});const Fi=ms({logSigmoid_:function(e){const t=ps(e,"x","logSigmoid"),n=Ti((e=>({value:Ri(Bi(Ri(e))),gradFunc:t=>$o(t,ra(Ri(e)))})));return n(t)}});const Ci=ms({sub_:function(e,t){let n=ps(e,"a","sub"),r=ps(t,"b","sub");[n,r]=Jr(n,r);const s={a:n,b:r};return ss.runKernel("Sub",s)}});const Pi=ms({logSoftmax_:function(e,t=-1){const n=ps(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=Ti(((e,n)=>{const r=ti(e,t,!0),s=Ci(e,r),o=Ci(wo(s,"float32"),Ii(ii(hi(s),t,!0)));n([o]);return{value:o,gradFunc:(e,n)=>{const[r]=n,s=hi(r);return Ci(e,$o(ii(e,t,!0),s))}}}));return r(n)}});const Oi=ms({logSumExp_:function(e,t=null,n=!1){const r=ps(e,"x","logSumExp"),s=g(t,r.shape),o=ti(r,s,!0),a=Ci(r,o),i=hi(a),l=ii(i,s),u=Ii(l),c=xo(Xo(o,u.shape),u);if(n){const e=ei(c.shape,s);return Xo(c,e)}return c}});const Li=ms({logicalAnd_:function(e,t){const n=ps(e,"a","logicalAnd","bool"),r=ps(t,"b","logicalAnd","bool");Ua(n.shape,r.shape);const s={a:n,b:r};return ss.runKernel(tt,s)}});const zi=ms({logicalNot_:function(e){const t={x:ps(e,"x","logicalNot","bool")};return ss.runKernel(nt,t)}});const Ui=ms({logicalOr_:function(e,t){const n=ps(e,"a","logicalOr","bool"),r=ps(t,"b","logicalOr","bool");Ua(n.shape,r.shape);const s={a:n,b:r};return ss.runKernel(rt,s)}});const Wi=ms({logicalXor_:function(e,t){const n=ps(e,"a","logicalXor","bool"),r=ps(t,"b","logicalXor","bool");return Ua(n.shape,r.shape),Li(Ui(e,t),zi(Li(e,t)))}}),Gi=2147483648;const qi=ms({searchSorted_:function(e,t,n="left"){const r=ps(e,"sortedSequence","searchSorted"),s=ps(t,"values","searchSorted"),o=r.shape[r.shape.length-1],a=s.shape[s.shape.length-1],i=Xo(r,[-1,o]),l=Xo(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)>=Gi)throw new Error("values tensor size must less than 2147483648");if(i.shape[1]>=Gi)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 ss.runKernel(Lt,u,h)}});const Ki=ms({maxPool_:function(e,t,n,r,s){const o=ps(e,"x","maxPool");let a=o,l=!1;3===o.rank&&(l=!0,a=Xo(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(jo(n,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`)),Yo("maxPool",r,s);const u={x:a},c={filterSize:t,strides:n,pad:r,dimRoundingMode:s},h=ss.runKernel(ot,u,c);return l?Xo(h,[h.shape[1],h.shape[2],h.shape[3]]):h}});const Vi=ms({maxPool3d_:function(e,t=[1,1,1],n,r,s,o="NDHWC"){const a=ps(e,"x","maxPool3d");let l=a,u=!1;4===a.rank&&(u=!0,l=Xo(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}`)),Yo("maxPool3d",r,s);const c={x:l},h={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:o},d=ss.runKernel(at,c,h);return u?Xo(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}});const Hi=ms({maxPoolWithArgmax_:function(e,t,n,r,s=!1){const o={x:ps(e,"x","maxPoolWithArgmax")},a={filterSize:t,strides:n,pad:r,includeBatchInIndex:s},i=ss.runKernel(it,o,a);return{result:i[0],indexes:i[1]}}});const ji=ms({maximum_:function(e,t){let n=ps(e,"a","maximum"),r=ps(t,"b","maximum");[n,r]=Jr(n,r),"bool"===n.dtype&&(n=wo(n,"int32"),r=wo(r,"int32")),Ua(n.shape,r.shape);const s={a:n,b:r};return ss.runKernel(st,s)}});const Ji=ms({mean_:function(e,t=null,n=!1){const r={x:ps(e,"x","mean")},s={axis:t,keepDims:n};return ss.runKernel(lt,r,s)}});function Zi(e,t="float32"){if(B(e),"complex64"===t){const t=Zi(e,"float32"),n=Zi(e,"float32");return bs(t,n)}const n=R(c(e),t);return ss.makeTensor(n,e,t)}function Yi(e,t="float32"){if(B(e),"complex64"===t){const t=Yi(e,"float32"),n=Zi(e,"float32");return bs(t,n)}const n=D(c(e),t);return ss.makeTensor(n,e,t)}const Xi=ms({minimum_:function(e,t){let n=ps(e,"a","minimum"),r=ps(t,"b","minimum");[n,r]=Jr(n,r),"bool"===n.dtype&&(n=wo(n,"int32"),r=wo(r,"int32")),Ua(n.shape,r.shape);const s={a:n,b:r};return ss.runKernel(ut,s)}});const Qi=ms({mirrorPad_:function(e,t,n){i("reflect"===n||"symmetric"===n,(()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`));const r=ps(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 ss.runKernel(ct,a,o)}});const el=ms({mod_:function(e,t){let n=ps(e,"a","mod"),r=ps(t,"b","mod");[n,r]=Jr(n,r);const s={a:n,b:r};return ss.runKernel("Mod",s)}});const tl=ms({moments_:function(e,t=null,n=!1){const r=g(t,(e=ps(e,"x","moments")).shape),s=Ji(e,r,n);let o=s.shape;n||(o=ei(s.shape,r));const a=ai(Ci(wo(e,"float32"),Xo(s,o)));return{mean:s,variance:Ji(a,r,n)}}});const nl=ms({multiRNNCell_:function(e,t,n,r){const s=ps(t,"data","multiRNNCell"),o=fs(n,"c","multiRNNCell"),a=fs(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?Xo(s,[1,-1]):s},l={numSamples:t,seed:n,normalized:r},u=ss.runKernel(ht,i,l);return 1===a?Xo(u,[u.size]):u}});const sl=ms({notEqual_:function(e,t){let n=ps(e,"a","notEqual","string_or_numeric"),r=ps(t,"b","notEqual","string_or_numeric");[n,r]=Jr(n,r),Ua(n.shape,r.shape);const s={a:n,b:r};return ss.runKernel(pt,s)}});const ol=ms({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:ps(e,"indices","oneHot","int32")},a={dtype:s,depth:t,onValue:n,offValue:r};return ss.runKernel(yt,o,a)}});const al=ms({onesLike_:function(e){const t={x:ps(e,"x","onesLike")};return ss.runKernel(bt,t)}});const il=ms({outerProduct_:function(e,t){const n=ps(e,"v1","outerProduct"),r=ps(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=Xo(n,[-1,1]),o=Xo(r,[1,-1]);return na(s,o)}});const ll=ms({pad_:function(e,t,n=0){const r=ps(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 ss.runKernel(kt,o,s)}});const ul=ms({pad1d_:function(e,t,n=0){return i(2===t.length,(()=>"Invalid number of paddings. Must be length of 2.")),ll(e,[t],n)}});const cl=ms({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.")),ll(e,t,n)}});const hl=ms({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.")),ll(e,t,n)}});const dl=ms({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.")),ll(e,t,n)}});const pl=ms({spaceToBatchND_:function(e,t,n){const r=ps(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 ss.runKernel(jt,s,o)}});const fl=ms({pool_:function(e,t,n,r,s,o,a){null==s&&(s=[1,1]),null==o&&(o=1),0===r&&(r="valid");const l=ps(e,"x","maxPool");let u=l,c=!1;3===l.rank&&(c=!0,u=Xo(l,[1,l.shape[0],l.shape[1],l.shape[2]])),i(jo(o,s),(()=>`Error in pool: Either strides or dilations must be 1. Got strides ${o} and dilations '${s}'`));const h=Lo(u.shape,t,o,s,r),d=[h.dilationHeight,h.dilationWidth];let p;p="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 f=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,p),b=f?r:"valid",y=f?u:pl(u,d,g),w=("avg"===n?()=>Qo(y,t,o,b,a):()=>Ki(y,t,o,b,a))(),k=f?w:ia(w,d,m);return c?Xo(k,[k.shape[1],k.shape[2],k.shape[3]]):k}});const gl=ms({prelu_:function(e,t){const n={x:ps(e,"x","prelu"),alpha:ps(t,"alpha","prelu")};return ss.runKernel(vt,n)}});const ml=ms({prod_:function(e,t=null,n=!1){let r=ps(e,"x","prod");"bool"===r.dtype&&(r=wo(r,"int32"));const s={x:r},o={axis:t,keepDims:n};return ss.runKernel(xt,s,o)}});const bl=ms({raggedGather_:function(e,t,n,r){const s={paramsNestedSplits:e.map(((e,t)=>ps(e,`tensors${t}`,"raggedGather","int32"))),paramsDenseValues:ps(t,"paramsDenseValues","raggedGather"),indices:ps(n,"indices","raggedGather","int32")},o={outputRaggedRank:r},a=ss.runKernel(Et,s,o);return{outputNestedSplits:a.slice(0,a.length-1),outputDenseValues:a[a.length-1]}}});const yl=ms({raggedRange_:function(e,t,n){const r=ps(e,"starts","raggedRange"),s={starts:r,limits:ps(t,"limits","raggedRange",r.dtype),deltas:ps(n,"deltas","raggedRange",r.dtype)},o=ss.runKernel(St,s);return{rtNestedSplits:o[0],rtDenseValues:o[1]}}});const wl=ms({raggedTensorToTensor_:function(e,t,n,r,s){const o=ps(e,"shape","raggedTensorToTensor","int32"),a=ps(t,"values","raggedTensorToTensor"),i={shape:o,values:a,defaultValue:ps(n,"defaultValue","raggedTensorToTensor",a.dtype),rowPartitionTensors:r.map(((e,t)=>ps(e,`tensors${t}`,"raggedTensorToTensor","int32")))},l={rowPartitionTypes:s};return ss.runKernel($t,i,l)}});const kl=ms({rand_:function(e,t,n){B(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,e,!1)}(vl);var xl=vl.exports,El={exports:{}};!function(e){!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,e,!1)}(El);var Sl=El.exports,$l={exports:{}};!function(e){!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,e,!1)}($l);var Al=$l.exports,_l={exports:{}};!function(e){!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,e,!1)}(_l);var Il=_l.exports,Nl={exports:{}};!function(e){!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,e,!1)}(Nl);var Ml=Nl.exports,Tl={exports:{}};!function(e){!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,e,!1)}(Tl);var Dl=Tl.exports,Rl={exports:{}};!function(e){!function(t,n,r){var s,o=256,a=r.pow(o,6),i=r.pow(2,52),l=2*i,u=255;function c(e,u,c){var m=[],b=f(p((u=1==u?{entropy:!0}:u||{}).entropy?[e,g(n)]:null==e?function(){try{var e;return s&&(e=s.randomBytes)?e=e(o):(e=new Uint8Array(o),(t.crypto||t.msCrypto).getRandomValues(e)),g(e)}catch(e){var r=t.navigator,a=r&&r.plugins;return[+new Date,t,a,t.screen,g(n)]}}():e,3),m),y=new h(m),w=function(){for(var e=y.g(6),t=a,n=0;e=l;)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(g(y.S),n),(u.pass||c||function(e,t,n,s){return s&&(s.S&&d(s,y),e.state=function(){return d(y,{})}),n?(r.random=e,t):e})(w,b,"global"in u?u.global:this==r,u.state)}function h(e){var t,n=e.length,r=this,s=0,a=r.i=r.j=0,i=r.S=[];for(n||(e=[n++]);sn)}var Kl={__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;nql(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])?Gl(e,n,((e,t)=>e==t)):Gl(e,t,((e,t)=>ql(e,t,0)))},expectNumbersClose:function(e,t,n){if(null==n&&(n=Wl()),!ql(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:Wl};class Vl{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=Ul.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 Hl{constructor(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n;const s=r||Math.random();this.randu=Ul.alea(s.toString()),this.randn=new Vl(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=Ul.alea(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}const Jl=ms({randomGamma_:function(e,t,n=1,r="float32",s){if(B(e),null==n&&(n=1),null==r&&(r="float32"),"float32"!==r&&"int32"!==r)throw new Error(`Unsupported data type ${r}`);const o=new Hl(t,n,r,s),a=yo(e,r);for(let e=0;e`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`)),ou(t,0)}});const iu=ms({reverse2d_:function(e,t){const n=ps(e,"x","reverse");return i(2===n.rank,(()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`)),ou(n,t)}});const lu=ms({reverse3d_:function(e,t){const n=ps(e,"x","reverse");return i(3===n.rank,(()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`)),ou(n,t)}});const uu=ms({reverse4d_:function(e,t){const n=ps(e,"x","reverse");return i(4===n.rank,(()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`)),ou(n,t)}});const cu=ms({round_:function(e){const t={x:ps(e,"x","round")};return ss.runKernel(Ft,t)}});const hu=ms({rsqrt_:function(e){const t={x:ps(e,"x","rsqrt","float32")};return ss.runKernel(Ct,t)}});const du=ms({selu_:function(e){const t={x:ps(e,"x","selu")};return ss.runKernel(Ut,t)}});const pu=ms({separableConv2d_:function(e,t,n,r,s,o=[1,1],a="NHWC"){const l=ps(e,"x","separableConv2d"),u=ps(t,"depthwiseFilter","separableConv2d"),c=ps(n,"pointwiseFilter","separableConv2d");let h=l,d=!1;if(3===l.rank&&(d=!0,h=Xo(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 p=u.shape[2],f=u.shape[3];i(c.shape[2]===p*f,(()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${p*f}, but got ${c.shape[2]}.`));const g=Ca(h,u,r,s,a,o),m=Ea(g,c,1,"valid",a);return d?Xo(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const fu=async function(e,t){const n=ps(e,"x","setdiff1d"),r=ps(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`)),sa(r,[t],[n])}});const wu=ms({slice2d_:function(e,t,n){const r=ps(e,"x","slice2d");return i(2===r.rank,(()=>`slice2d expects a rank-2 tensor, but got a rank-${r.rank} tensor`)),sa(r,t,n)}});const ku=ms({slice3d_:function(e,t,n){const r=ps(e,"x","slice3d");return i(3===r.rank,(()=>`slice3d expects a rank-3 tensor, but got a rank-${r.rank} tensor`)),sa(r,t,n)}});const vu=ms({slice4d_:function(e,t,n){const r=ps(e,"x","slice4d");return i(4===r.rank,(()=>`slice4d expects a rank-4 tensor, but got a rank-${r.rank} tensor`)),sa(r,t,n)}});const xu=ms({softmax_:function(e,t=-1){const n=ps(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 ss.runKernel(Zt,r,s)}});const Eu=ms({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 ss.runKernel("FFT",t)}});const Su=ms({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 ss.runKernel(Ke,t)}});const $u=ms({irfft_:function(e){const t=e.shape[e.shape.length-1],n=e.size/t;let r;if(t<=2){const s=Xo(e,[n,t]);r=Su(s)}else{const s=[n,2*(t-1)],o=Xo(tu(e),[n,t]),a=Xo(ki(e),[n,t]),i=ou(sa(o,[0,1],[n,t-2]),1),l=$o(ou(sa(a,[0,1],[n,t-2]),1),si(-1)),u=ta([o,i],1),c=ta([a,l],1),h=Xo(bs(u,c),[s[0],s[1]]);r=Su(h)}if(r=tu(r),3===e.rank&&0!==e.shape[0]){const t=r,n=e.shape[0];r=Xo(r,[n,r.shape[0]/n,r.shape[1]]),t.dispose()}return r}});const Au=ms({split_:function(e,t,n=0){const r={x:ps(e,"x","split")},s={numOrSizeSplits:t,axis:n};return ss.runKernel(Jt,r,s)}});const _u=ms({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=sa(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=ta([e,Zi(r)],e.shape.length-1),n=t}else s=e;const o=Ka(s),a=Xo(bs(s,o),[r,n]),l=Eu(a),u=Math.floor(n/2)+1,c=tu(l),h=ki(l),d=Au(c,[u,n-u],c.shape.length-1),p=Au(h,[u,n-u],h.shape.length-1),f=s.shape.slice();return f[s.shape.length-1]=u,Xo(bs(d[0],p[0]),f)}});const Iu=ms({squaredDifference_:function(e,t){let n=ps(e,"a","squaredDifference"),r=ps(t,"b","squaredDifference");[n,r]=Jr(n,r),Ua(n.shape,r.shape);const s={a:n,b:r};return ss.runKernel(nn,s,{})}});const Nu=ms({squeeze_:function(e,t){const n=ps(e,"x","squeeze","string_or_numeric");return Xo(n,m(n.shape,t).newShape)}});const Mu=ms({stack_:function(e,t=0){const n=fs(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 ss.runKernel(wt,r,s)}});const Tu=ms({step_:function(e,t=0){const n={x:ps(e,"x","step")},r={alpha:t};return ss.runKernel(yn,n,r)}});const Du=ms({stridedSlice_:function(e,t,n,r,s=0,o=0,a=0,i=0,l=0){const u={x:ps(e,"x","stridedSlice","string_or_numeric")},c={begin:t,end:n,strides:r,beginMask:s,endMask:o,ellipsisMask:a,newAxisMask:i,shrinkAxisMask:l};return ss.runKernel(sn,u,c)}});const Ru=ms({tan_:function(e){const t={x:ps(e,"x","tan","float32")};return ss.runKernel("Tan",t)}});function Bu(e,t){u(e);const n=cs(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return ys(e,null,n,t)}function Fu(e,t,n){if(u(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const r=cs(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 ys(e,t,r,n)}function Cu(e,t,n){if(u(e),null!=t&&3!==t.length)throw new Error("tensor3d() requires shape to have three numbers");const r=cs(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 ys(e,t,r,n)}function Pu(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]=ss.runKernel(hn,o,a);return{values:i,indices:l}}});const Gu=ms({truncatedNormal_:function(e,t=0,n=1,r,s){if(B(e),null!=r&&"bool"===r)throw new Error("Unsupported data type $ { dtype }");const o=new Vl(t,n,r,!0,s),a=yo(e,r);for(let e=0;e0,(()=>"The input tensor must be at least 1D"));const r={x:n},s={axis:t},[o,a]=ss.runKernel(fn,r,s);return{values:o,indices:a}}});const Ku=ms({unsortedSegmentSum_:function(e,t,n){const r=ps(e,"x","unsortedSegmentSum"),s=ps(t,"segmentIds","unsortedSegmentSum","int32");i(p(n),(()=>"numSegments must be of dtype int"));const o={x:r,segmentIds:s},a={numSegments:n};return ss.runKernel(mn,o,a)}});const Vu=ms({unstack_:function(e,t=0){const n=ps(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 ss.runKernel(gn,r,s)}});function Hu(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?xs((()=>{let e=tu(r),t=ki(r);return e=ss.runKernel(pn,{x:e},o),t=ss.runKernel(pn,{x:t},o),n&&(t=Ri(t)),bs(e,t)})):ss.runKernel(pn,s,o)}});const Yu=ms({movingAverage_:function(e,t,n,r,s=!0){const o=ps(e,"v","movingAverage"),a=ps(t,"x","movingAverage"),l=ps(n,"decay","movingAverage");Zr(o,a),i(d(o.shape,a.shape),(()=>"Shape mismatch in v and x"));const u=si(1),c=Ci(u,l);let h=$o(Ci(a,o),c);if(s){i(null!=r,(()=>"When using zeroDebias: true, step is required."));const e=ps(r,"step","movingAverage");h=So(h,Ci(u,ri(l,e)))}return xo(o,h)}});const Xu=ms({scatterND_:function(e,t,n){B(n);const r=ps(e,"indices","scatterND","int32"),s=ps(t,"updates","scatterND");Ou(s,r,n);const o={indices:r,updates:s},a={shape:n};return ss.runKernel(Pt,o,a)}});const Qu=ms({sparseToDense_:function(e,t,n,r=0){B(n);const s=ps(e,"sparseIndices","sparseToDense","int32"),o=ps(t,"sparseValues","sparseToDense","string_or_numeric"),a=ps(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 ss.runKernel(tn,i,l)}});const ec=ms({gatherND_:function(e,t){const n=ps(t,"indices","gatherND","int32"),r={params:ps(e,"x","gatherND","string_or_numeric"),indices:n};return ss.runKernel(Ue,r)}});const tc=ms({dropout_:function(e,t,n,r){const s=ps(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 Pr?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]}).`)),Yo("conv2dDerFilter",s,a);const d={x:l,dy:u},p={strides:r,pad:s,dataFormat:o,dimRoundingMode:a,filterShape:n};return ss.runKernel(fe,d,p)}});function ac(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return $o(e,Tu(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function ic(e,t){let n=t;const r=za(e.shape,t.shape);return r.length>0&&(n=ii(n,r)),Xo(n,e.shape)}function lc(e,t,n,r){if("linear"===t)return e;if("relu"===t)return ru(e);if("elu"===t)return Ja(e);if("relu6"===t)return su(e);if("prelu"===t)return gl(e,n);if("leakyrelu"===t)return Si(e,r);if("sigmoid"===t)return ra(e);throw new Error(`Unknown fused activation ${t}.`)}const uc=(e,t)=>!(e>0)||"linear"===t;const cc=ms({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===uc(ss.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=Ea(e,t,n,r,s,o,a);return null!=l&&(d=xo(d,l)),lc(d,u,c,h)}const d=ps(e,"x","conv2d","float32"),p=ps(t,"filter","conv2d","float32");let f=d,g=!1;3===d.rank&&(g=!0,f=Xo(d,[1,d.shape[0],d.shape[1],d.shape[2]])),i(4===f.rank,(()=>`Error in fused conv2d: input must be rank 4, but got rank ${f.rank}.`)),i(4===p.rank,(()=>`Error in fused conv2d: filter must be rank 4, but got rank ${p.rank}.`)),Yo("fused conv2d",r,a);const m="NHWC"===s?f.shape[3]:f.shape[1];i(p.shape[2]===m,(()=>`Error in conv2d: depth of input (${m}) must match input depth for filter ${p.shape[2]}.`)),i(jo(n,o),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`));const b=zo(f.shape,p.shape,n,o,r,a);let y,w;if(null!=l&&(y=ps(l,"bias","fused conv2d"),[y]=Jr(y,d),"NHWC"===s?Ua(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{Ua(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=ps(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=ac(e,c,u);i(Ho(o),(()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${o}'`));const p=[$a(l.shape,d,a,n,r),oc(l,d,a.shape,n,r)];if(null!=h){const e=ic(h,d);p.push(e)}return p},v={x:f,filter:p,bias:y,preluActivationWeights:w},x={strides:n,pad:r,dataFormat:s,dilations:o,dimRoundingMode:a,activation:u,leakyreluAlpha:h};if(null==l){const e=Ti(((e,t,n)=>{let r=ss.runKernel(xn,v,x);return n([t,e,r]),g&&(r=Xo(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:k}}));return e(f,p)}{const e=Ti(((e,t,n,r)=>{let s=ss.runKernel(xn,v,x);return r([t,e,s,n]),g&&(s=Xo(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:k}}));return e(f,p,y)}}});const hc=ms({depthwiseConv2dNativeBackpropFilter_:function(e,t,n,r,s,o=[1,1],a){let i=e;3===e.rank&&(i=Xo(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;3===l.rank&&(l=Xo(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 ss.runKernel($e,u,c)}});const dc=ms({depthwiseConv2dNativeBackpropInput_:function(e,t,n,r,s,o=[1,1],a){let i=t,l=!1;3===t.rank&&(l=!0,i=Xo(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=ss.runKernel(Ae,u,c);return l?Xo(h,[h.shape[1],h.shape[2],h.shape[3]]):h}});const pc=ms({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===uc(ss.state.gradientDepth,u)){let i=Ca(e,t,n,r,s,o,a);return null!=l&&(i=xo(i,l)),lc(i,u,c,h)}const d=ps(e,"x","depthwiseConv2d","float32"),p=ps(t,"filter","depthwiseConv2d","float32");let f=d,g=!1;3===d.rank&&(g=!0,f=Xo(d,[1,d.shape[0],d.shape[1],d.shape[2]])),i(4===f.rank,(()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${f.rank}.`)),i(4===p.rank,(()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${p.rank}.`)),i(f.shape[3]===p.shape[2],(()=>`Error in fused depthwiseConv2d: number of input channels (${f.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`)),null==o&&(o=[1,1]),i(jo(n,o),(()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`)),Yo("fused depthwiseConv2d",r,a);const m=zo(f.shape,p.shape,n,o,r,a,!0);let b,y;null!=l&&(b=ps(l,"bias","fused conv2d"),[b]=Jr(b,d),Ua(m.outShape,b.shape)),null!=c&&(y=ps(c,"prelu weights","fused depthwiseConv2d"));const w=(e,t)=>{i(Ho(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=ac(e,c,u),p=dc(l.shape,d,s,n,r,o,a),f=hc(l,d,s.shape,n,r,o,a);if(null!=h){return[p,f,ic(b,d)]}return[p,f]},k={x:f,filter:p,bias:b,preluActivationWeights:y},v={strides:n,pad:r,dataFormat:s,dilations:o,dimRoundingMode:a,activation:u,leakyreluAlpha:h};if(null==l){const e=Ti(((e,t,n)=>{let r=ss.runKernel(En,k,v);return n([t,e,r]),g&&(r=Xo(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:w}}));return e(f,p)}{const e=Ti(((e,t,n,r)=>{let s=ss.runKernel(En,k,v);return r([t,e,s,n]),g&&(s=Xo(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:w}}));return e(f,p,b)}}});const fc=ms({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:r=!1,bias:s,activation:o="linear",preluActivationWeights:a,leakyreluAlpha:l=.2}){if(!1===uc(ss.state.gradientDepth,o)){let i=na(e,t,n,r);return null!=s&&(i=xo(i,s)),lc(i,o,a,l)}let u=ps(e,"a","fused matMul"),h=ps(t,"b","fused matMul");[u,h]=Jr(u,h);const d=n?u.shape[u.rank-2]:u.shape[u.rank-1],p=r?h.shape[h.rank-1]:h.shape[h.rank-2],f=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===p,(()=>`Error in fused matMul: inner shapes (${d}) and (${p}) of Tensors with shapes ${u.shape} and ${h.shape} and transposeA=${n} and transposeB=${r} must match.`));const k=Ua(u.shape.slice(0,-2),h.shape.slice(0,-2)).concat([f,g]),v=Xo(u,n?[y,d,f]:[y,f,d]),x=Xo(h,r?[w,g,p]:[w,p,g]);let E,S;null!=s&&(E=ps(s,"bias","fused matMul"),[E]=Jr(E,u),Ua(k,E.shape)),null!=a&&(S=ps(a,"prelu weights","fused matMul"));const $=(e,t)=>{const[a,i,l,u]=t,c=ac(Xo(e,l.shape),l,o);let h,d;if(n||r?!n&&r?(h=na(c,i,!1,!1),d=na(c,a,!0,!1)):n&&!r?(h=na(i,c,!1,!0),d=na(a,c,!1,!1)):(h=na(i,c,!0,!0),d=na(c,a,!0,!0)):(h=na(c,i,!1,!0),d=na(a,c,!0,!1)),null!=s){return[h,d,ic(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=Ti(((e,t,n)=>{const r=ss.runKernel(vn,A,_);return n([e,t,r]),{value:Xo(r,k),gradFunc:$}}));return e(v,x)}{const e=Ti(((e,t,n,r)=>{const s=ss.runKernel(vn,A,_);return r([e,t,s,n]),{value:Xo(s,k),gradFunc:$}}));return e(v,x,E)}}});var gc={__proto__:null,conv2d:cc,depthwiseConv2d:pc,matMul:fc};const mc=ms({hammingWindow_:function(e){return rc(e,.54,.46)}});const bc=ms({hannWindow_:function(e){return rc(e,.5,.5)}});const yc=ms({frame_:function(e,t,n,r=!1,s=0){let o=0;const a=[];for(;o+t<=e.size;)a.push(sa(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 ss.runKernel(ve,h,d)}});const vc=ms({flipLeftRight_:function(e){const t=ps(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 ss.runKernel(Ce,n,{})}});const xc=ms({grayscaleToRGB_:function(e){const t=ps(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,fi(t,s)}});const Ec=ms({rgbToGrayscale_:function(e){const t=ps(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=wo(t,"float32"),a=Bu([.2989,.587,.114]);let l;switch(t.rank){case 2:l=ja("ij,j->i",o,a);break;case 3:l=ja("ijk,k->ij",o,a);break;case 4:l=ja("ijkl,l->ijk",o,a);break;case 5:l=ja("ijklm,m->ijkl",o,a);break;case 6:l=ja("ijklmn,n->ijklm",o,a);break;default:throw new Error("Not a valid tensor rank.")}return l=di(l,-1),wo(l,s)}});const Sc=ms({rotateWithOffset_:function(e,t,n=0,r=.5){const s=ps(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 ss.runKernel(kn,o,a)}});function $c(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 Ac=ms({nonMaxSuppression_:function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY){const o=ps(e,"boxes","nonMaxSuppression","float32"),a=ps(t,"scores","nonMaxSuppression","float32"),i=$c(o,a,n,r,s),l={maxOutputSize:n=i.maxOutputSize,iouThreshold:r=i.iouThreshold,scoreThreshold:s=i.scoreThreshold};return ss.runKernel(ft,{boxes:o,scores:a},l)}});function _c(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||Ic)}(e,t,n),s=r<0?-(r+1):r;e.splice(s,0,t)}function Ic(e,t){return e>t?1:es&&u.push({score:t[e],boxIndex:e,suppressBeginIndex:0});u.sort(Fc);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=Rc(e,o,h[n]);if(a>=r){i=!0;break}if(t.score=t.score*Bc(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&&_c(u,t,Fc))}const p=h.length,f=n-p;i&&f>0&&(h.push(...new Array(f).fill(0)),d.push(...new Array(f).fill(0)));const g={selectedIndices:h};return a&&(g.selectedScores=d),l&&(g.validOutputs=p),g}function Rc(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]),p=(i-o)*(l-a),f=(h-u)*(d-c);if(p<=0||f<=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/(p+f-w)}function Bc(e,t,n){const r=Math.exp(t*n*n);return n<=e?r:0}function Fc(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}const Cc=async function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY){const o=ps(e,"boxes","nonMaxSuppressionAsync"),a=ps(t,"scores","nonMaxSuppressionAsync"),i=$c(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}=Nc(u,c,n,r,s);return o!==e&&o.dispose(),a!==t&&a.dispose(),Bu(h,"int32")};const Pc=ms({nonMaxSuppressionWithScore_:function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,o=0){const a=ps(e,"boxes","nonMaxSuppression"),i=ps(t,"scores","nonMaxSuppression"),l=$c(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=ss.runKernel(mt,u,c);return{selectedIndices:h[0],selectedScores:h[1]}}});const Oc=async function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,o=0){const a=ps(e,"boxes","nonMaxSuppressionAsync"),i=ps(t,"scores","nonMaxSuppressionAsync"),l=$c(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:p}=Tc(c,h,n,r,s,o);return a!==e&&a.dispose(),i!==t&&i.dispose(),{selectedIndices:Bu(d,"int32"),selectedScores:Bu(p)}};const Lc=ms({nonMaxSuppressionPadded_:function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,o=!1){const a=ps(e,"boxes","nonMaxSuppression"),i=ps(t,"scores","nonMaxSuppression"),l=$c(a,i,n,r,s,null),u={boxes:a,scores:i},c={maxOutputSize:l.maxOutputSize,iouThreshold:l.iouThreshold,scoreThreshold:l.scoreThreshold,padToMaxOutputSize:o},h=ss.runKernel(gt,u,c);return{selectedIndices:h[0],validOutputs:h[1]}}});const zc=async function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,o=!1){const a=ps(e,"boxes","nonMaxSuppressionAsync"),i=ps(t,"scores","nonMaxSuppressionAsync"),l=$c(a,i,n,r,s,null),u=l.maxOutputSize,c=l.iouThreshold,h=l.scoreThreshold,[d,p]=await Promise.all([a.data(),i.data()]),{selectedIndices:f,validOutputs:g}=Mc(d,p,u,c,h,o);return a!==e&&a.dispose(),i!==t&&i.dispose(),{selectedIndices:Bu(f,"int32"),validOutputs:si(g,"int32")}};const Uc=ms({resizeBilinear_:function(e,t,n=!1,r=!1){const s=ps(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=Xo(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const l={images:o},u={alignCorners:n,halfPixelCenters:r,size:t},c=ss.runKernel(Dt,l,u);return a?Xo(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});const Wc=ms({resizeNearestNeighbor_:function(e,t,n=!1,r=!1){const s=ps(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=Xo(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const l={images:o},u={alignCorners:n,halfPixelCenters:r,size:t},c=ss.runKernel(Tt,l,u);return a?Xo(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});const Gc=ms({threshold_:function(e,t="binary",n=!1,r=.5){const s=ps(e,"image","threshold"),o=s.shape[0]*s.shape[1];let a,l,u,c,h=$o(Bu([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]=Au(s,[1,1,1],-1);const e=$o(a,.2989),t=$o(l,.587),n=$o(u,.114);c=xo(xo(e,t),n)}else c=e;if("otsu"===t){h=function(e,t){let n,r,s,o,a,i,l=Bu([-1]),u=Bu([0]),c=Bu([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 ss.runKernel(dn,u,c)}});const Kc=ms({bandPart_:function(e,t,n){const r=ps(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=ps(t<0?o:t,"numLower","bandPart")):(i("int32"===t.dtype,(()=>"bandPart(): numLower's dtype must be an int32.")),l=qa($i(t,0),o,Xi(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=ps(n<0?a:n,"numUpper","bandPart")):(i("int32"===n.dtype,(()=>"bandPart(): numUpper's dtype must be an int32.")),u=qa($i(n,0),a,Xi(n,a)));const c=Xo(eu(0,o,1,"int32"),[-1,1]),h=eu(0,a,1,"int32"),d=Ci(c,h),p=Li(Ai(d,l),wi(d,Ri(u))),f=Zi([o,a],r.dtype);return Xo(Mu(Vu(Xo(r,[-1,o,a])).map((e=>qa(p,e,f)))),s)}});const Vc=ms({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=Au(e,e.shape[0],0).map((e=>Nu(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=gi(n),o=ko(e);const a=Fu([[1]],[1,1]);let l=ko(a);const u=n>=r?r:n;for(let e=0;e{const t=sa(o,[e,e],[n-e,1]),i=ui(t),u=sa(o,[e,e],[1,1]),c=qa(yi(u,0),Fu([[-1]]),Fu([[1]])),h=Ci(u,$o(c,i)),d=So(t,h);l=1===d.shape[0]?ko(a):ta([a,sa(d,[1,0],[d.shape[0]-1,d.shape[1]])],0);const p=Ri(So(na(c,h),i)),f=sa(o,[e,0],[n-e,r]),g=$o(p,l),m=Zu(l);if(0===e)o=Ci(f,na(g,na(m,f)));else{const t=Ci(f,na(g,na(m,f)));o=ta([sa(o,[0,0],[e,r]),t],0)}const b=Zu(g),y=sa(s,[0,e],[n,s.shape[1]-e]);if(0===e)s=Ci(y,na(na(y,l),b));else{const t=Ci(y,na(na(y,l),b));s=ta([sa(s,[0,0],[n,e]),t],1)}return[l,o,s]})),Es([t,i,u])}return!t&&n>r&&(s=sa(s,[0,0],[n,r]),o=sa(o,[0,0],[r,r])),[s,o]}))}const jc=ms({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 Hc(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce(((e,t)=>e*t)),r=Vu(Xo(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),s=[],o=[];r.forEach((e=>{const[n,r]=Hc(e,t);s.push(n),o.push(r)}));return[Xo(Mu(s,0),e.shape),Xo(Mu(o,0),e.shape)]}}});var Jc;e.Reduction=void 0,(Jc=e.Reduction||(e.Reduction={}))[Jc.NONE=0]="NONE",Jc[Jc.MEAN=1]="MEAN",Jc[Jc.SUM=2]="SUM",Jc[Jc.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS";const Zc=ms({computeWeightedLoss_:function(t,n,r=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const s=ps(t,"losses","computeWeightedLoss");let o=null;null!=n&&(o=ps(n,"weights","computeWeightedLoss"));const a=null==o?s:$o(s,o);if(r===e.Reduction.NONE)return a;if(r===e.Reduction.SUM)return ii(a);if(r===e.Reduction.MEAN){if(null==o)return Ji(a);{const e=s.size/o.size,t=So(ii(a),ii(o));return e>1?So(t,si(e)):t}}if(r===e.Reduction.SUM_BY_NONZERO_WEIGHTS){if(null==o)return So(ii(a),si(s.size));{const e=$o(o,Yi(s.shape)),t=wo(ii(sl(e,si(0))),"float32");return So(ii(a),t)}}throw Error(`Unknown reduction: ${r}`)}});const Yc=ms({absoluteDifference_:function(t,n,r,s=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const o=ps(t,"labels","absoluteDifference"),a=ps(n,"predictions","absoluteDifference");let i=null;null!=r&&(i=ps(r,"weights","absoluteDifference")),l(o.shape,a.shape,"Error in absoluteDifference: ");const u=Ao(Ci(o,a));return Zc(u,i,s)}});const Xc=ms({cosineDistance_:function(t,n,r,s,o=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const a=ps(t,"labels","cosineDistance"),i=ps(n,"predictions","cosineDistance");let u=null;null!=s&&(u=ps(s,"weights","cosineDistance")),l(a.shape,i.shape,"Error in cosineDistance: ");const c=si(1),h=Ci(c,ii($o(a,i),r,!0));return Zc(h,u,o)}});const Qc=ms({hingeLoss_:function(t,n,r,s=e.Reduction.SUM_BY_NONZERO_WEIGHTS){let o=ps(t,"labels","hingeLoss");const a=ps(n,"predictions","hingeLoss");let i=null;null!=r&&(i=ps(r,"weights","hingeLoss")),l(o.shape,a.shape,"Error in hingeLoss: ");const u=si(1);o=Ci($o(si(2),o),u);const c=ru(Ci(u,$o(o,a)));return Zc(c,i,s)}});const eh=ms({huberLoss_:function(t,n,r,s=1,o=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const a=ps(t,"labels","huberLoss"),i=ps(n,"predictions","huberLoss");let u=null;null!=r&&(u=ps(r,"weights","huberLoss")),l(a.shape,i.shape,"Error in huberLoss: ");const c=si(s),h=Ao(Ci(i,a)),d=Xi(h,c),p=Ci(h,d),f=xo($o(si(.5),ai(d)),$o(c,p));return Zc(f,u,o)}});const th=ms({logLoss_:function(t,n,r,s=1e-7,o=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const a=ps(t,"labels","logLoss"),i=ps(n,"predictions","logLoss");let u=null;null!=r&&(u=ps(r,"weights","logLoss")),l(a.shape,i.shape,"Error in logLoss: ");const c=si(1),h=si(s),d=Ri($o(a,Ii(xo(i,h)))),p=$o(Ci(c,a),Ii(xo(Ci(c,i),h))),f=Ci(d,p);return Zc(f,u,o)}});const nh=ms({meanSquaredError_:function(t,n,r,s=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const o=ps(t,"labels","meanSquaredError"),a=ps(n,"predictions","meanSquaredError");let i=null;null!=r&&(i=ps(r,"weights","meanSquaredError")),l(o.shape,a.shape,"Error in meanSquaredError: ");const u=Iu(o,a);return Zc(u,i,s)}});const rh=ms({sigmoidCrossEntropy_:function(t,n,r,s=0,o=e.Reduction.SUM_BY_NONZERO_WEIGHTS){let a=ps(t,"multiClassLabels","sigmoidCrossEntropy");const i=ps(n,"logits","sigmoidCrossEntropy");let u=null;if(null!=r&&(u=ps(r,"weights","sigmoidCrossEntropy")),l(a.shape,i.shape,"Error in sigmoidCrossEntropy: "),s>0){const e=si(s),t=si(1),n=si(.5);a=xo($o(a,Ci(t,e)),$o(n,e))}const c=function(e,t){const n=ps(e,"labels","sigmoidCrossEntropyWithLogits"),r=ps(t,"logits","sigmoidCrossEntropyWithLogits");l(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");const s=ru(r),o=$o(r,n),a=Ni(hi(Ri(Ao(r))));return xo(Ci(s,o),a)}(a,i);return Zc(c,u,o)}});const sh=ms({softmaxCrossEntropy_:function(t,n,r,s=0,o=e.Reduction.SUM_BY_NONZERO_WEIGHTS){let a=ps(t,"onehotLabels","softmaxCrossEntropy");const i=ps(n,"logits","softmaxCrossEntropy");let u=null;if(null!=r&&(u=ps(r,"weights","softmaxCrossEntropy")),l(a.shape,i.shape,"Error in softmaxCrossEntropy: "),s>0){const e=si(s),t=si(1),n=si(a.shape[1]);a=xo($o(a,Ci(t,e)),So(e,n))}const c=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=Ti(((e,t,r)=>{const s=Oi(t,[n],!0),o=Ci(wo(t,"float32"),s);r([e,o]);const a=Ri($o(o,e));return{value:ii(a,[n]),gradFunc:(e,t)=>{const[r,s]=t,o=ei(e.shape,[n]);return[$o(Xo(e,o),Ci(wo(r,"float32"),hi(s))),$o(Xo(e,o),Ci(hi(s),wo(r,"float32")))]}}}));return r(e,t)}(a,i);return Zc(c,u,o)}});const oh=ms({sparseFillEmptyRows_:function(e,t,n,r){const s=ps(e,"indices","sparseFillEmptyRows","int32"),o=ps(t,"values","sparseFillEmptyRows"),a=ps(n,"denseShape","sparseFillEmptyRows","int32"),i=ps(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=ss.runKernel(Yt,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}});const ah=ms({sparseReshape_:function(e,t,n){const r=ps(e,"inputIndices","sparseReshape","int32"),s=ps(t,"inputShape","sparseReshape","int32"),o=ps(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=ss.runKernel(Xt,a);return{outputIndices:i[0],outputShape:i[1]}}});const ih=ms({sparseSegmentMean_:function(e,t,n){const r=ps(e,"data","sparseSegmentMean"),s=ps(t,"indices","sparseSegmentMean","int32"),o=ps(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 ss.runKernel(Qt,a)}});const lh=ms({sparseSegmentSum_:function(e,t,n){const r=ps(e,"data","sparseSegmentSum"),s=ps(t,"indices","sparseSegmentSum","int32"),o=ps(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 ss.runKernel(en,a)}});const uh=ms({stringNGrams_:function(e,t,n,r,s,o,a,i){const l=ps(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=ps(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=ss.runKernel(on,h,c);return{nGrams:d[0],nGramsSplits:d[1]}}});const ch={fft:Eu,ifft:Su,rfft:_u,irfft:$u},hh={hammingWindow:mc,hannWindow:bc,frame:yc,stft:wc},dh={flipLeftRight:vc,grayscaleToRGB:xc,resizeNearestNeighbor:Wc,resizeBilinear:Uc,rgbToGrayscale:Ec,rotateWithOffset:Sc,cropAndResize:kc,nonMaxSuppression:Ac,nonMaxSuppressionAsync:Cc,nonMaxSuppressionWithScore:Pc,nonMaxSuppressionWithScoreAsync:Oc,nonMaxSuppressionPadded:Lc,nonMaxSuppressionPaddedAsync:zc,threshold:Gc,transform:qc},ph={bandPart:Kc,gramSchmidt:Vc,qr:jc},fh={absoluteDifference:Yc,computeWeightedLoss:Zc,cosineDistance:Xc,hingeLoss:Qc,huberLoss:eh,logLoss:th,meanSquaredError:nh,sigmoidCrossEntropy:rh,softmaxCrossEntropy:sh},gh={sparseFillEmptyRows:oh,sparseReshape:ah,sparseSegmentMean:ih,sparseSegmentSum:lh},mh={stringNGrams:uh,stringSplit:ms({stringSplit_:function(e,t,n=!0){const r=ps(e,"input","stringSplit","string"),s=ps(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=ss.runKernel(an,a,o);return{indices:i[0],values:i[1],shape:i[2]}}}),stringToHashBucketFast:ms({stringToHashBucketFast_:function(e,t){const n=ps(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 ss.runKernel(ln,s,r)}}),staticRegexReplace:ms({staticRegexReplace_:function(e,t,n,r=!0){const s=ps(e,"input","staticRegexReplace","string"),o={pattern:t,rewrite:n,replaceGlobal:r};return ss.runKernel(rn,{x:s},o)}})},bh=new Map,yh=new Map;class wh{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class kh{constructor(){this.classNameMap={}}static getMap(){return null==kh.instance&&(kh.instance=new kh),kh.instance}static register(e){kh.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function vh(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 kh.register(e),bh.set(r,e),yh.set(e,r),e}var xh={__proto__:null,Serializable:wh,SerializationMap:kh,getRegisteredName:function(e){return yh.has(e)?yh.get(e):e.className},registerClass:vh};class Eh extends wh{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 Es(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 Mi(e,t)}dispose(){null!=this.iterations_&&Es(this.iterations_)}async saveIterations(){return null==this.iterations_&&(this.iterations_=0),{name:"iter",tensor:si(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(Eh,Symbol.hasInstance,{value:e=>null!=e.minimize&&null!=e.computeGradients&&null!=e.applyGradients});class Sh extends Eh{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=ss.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const r=ss.registeredVariables[t];null==this.accumulatedGrads[n]&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:xs((()=>Ka(r).variable(false)))}),null==this.accumulatedUpdates[n]&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:xs((()=>Ka(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;xs((()=>{const e=xo($o(o,this.rho),$o(ai(s),1-this.rho)),t=$o(So(oi(xo(a,this.epsilon)),oi(xo(o,this.epsilon))),s),n=xo($o(a,this.rho),$o(ai(t),1-this.rho));o.assign(e),a.assign(n);const i=xo($o(t,-this.learningRate),r);r.assign(i)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedUpdates&&(Es(this.accumulatedGrads.map((e=>e.variable))),Es(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 $h extends Eh{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=ss.registeredVariables[t];if(null==this.accumulatedGrads[n]){const e=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:xs((()=>ba(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;xs((()=>{const e=xo(o,ai(s));o.assign(e);const t=xo($o(So(s,oi(xo(e,ss.backend.epsilon()))),-this.learningRate),r);r.assign(t)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedGrads&&Es(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 Ah extends Eh{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=[],xs((()=>{this.accBeta1=si(t).variable(),this.accBeta2=si(n).variable()})),null==r&&(this.epsilon=ss.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);xs((()=>{const n=Ci(1,this.accBeta1),r=Ci(1,this.accBeta2);t.forEach(((t,s)=>{const o=ss.registeredVariables[t];null==this.accumulatedFirstMoment[s]&&(this.accumulatedFirstMoment[s]={originalName:`${t}/m`,variable:xs((()=>Ka(o).variable(false)))}),null==this.accumulatedSecondMoment[s]&&(this.accumulatedSecondMoment[s]={originalName:`${t}/v`,variable:xs((()=>Ka(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=xo($o(i,this.beta1),$o(a,1-this.beta1)),c=xo($o(l,this.beta2),$o(ai(a),1-this.beta2)),h=So(u,n),d=So(c,r);i.assign(u),l.assign(c);const p=xo($o(So(h,xo(oi(d),this.epsilon)),-this.learningRate),o);o.assign(p)})),this.accBeta1.assign($o(this.accBeta1,this.beta1)),this.accBeta2.assign($o(this.accBeta2,this.beta2))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&Es(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedSecondMoment&&Es(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),xs((()=>{this.accBeta1.assign(ri(this.beta1,this.iterations_+1)),this.accBeta2.assign(ri(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 _h extends Eh{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=[],xs((()=>{this.iteration=si(0).variable(),this.accBeta1=si(t).variable()})),null==r&&(this.epsilon=ss.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);xs((()=>{const n=Ci(1,this.accBeta1),r=So(-this.learningRate,xo($o(this.iteration,this.decay),1));t.forEach(((t,s)=>{const o=ss.registeredVariables[t];null==this.accumulatedFirstMoment[s]&&(this.accumulatedFirstMoment[s]={originalName:`${t}/m`,variable:Ka(o).variable(false)}),null==this.accumulatedWeightedInfNorm[s]&&(this.accumulatedWeightedInfNorm[s]={originalName:`${t}/v`,variable:Ka(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=xo($o(i,this.beta1),$o(a,1-this.beta1)),c=$o(l,this.beta2),h=Ao(a),d=ji(c,h);i.assign(u),l.assign(d);const p=xo($o(So(r,n),So(u,xo(d,this.epsilon))),o);o.assign(p)})),this.iteration.assign(xo(this.iteration,1)),this.accBeta1.assign($o(this.accBeta1,this.beta1))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&Es(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedWeightedInfNorm&&Es(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 Ih extends Eh{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=ss.registeredVariables[t];xs((()=>{const e=xo($o(this.c,r),s);s.assign(e)}))})),this.incrementIterations()}setLearningRate(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=Ss(si(-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 Nh extends Ih{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=si(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const r=ss.registeredVariables[t];if(null==this.accumulations[n]){const e=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:xs((()=>Ka(r).variable(e)))}}const s=this.accumulations[n].variable,o=Array.isArray(e)?e[n].tensor:e[t];null!=o&&xs((()=>{let e;const t=xo($o(this.m,s),o);e=this.useNesterov?xo($o(this.c,xo(o,$o(t,this.m))),r):xo($o(this.c,t),r),s.assign(t),r.assign(e)}))})),this.incrementIterations()}dispose(){this.m.dispose(),null!=this.accumulations&&Es(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 Mh extends Eh{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=ss.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=ss.registeredVariables[t],s=!1;null==this.accumulatedMeanSquares[n]&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:xs((()=>Ka(r).variable(s)))}),null==this.accumulatedMoments[n]&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:xs((()=>Ka(r).variable(s)))}),null==this.accumulatedMeanGrads[n]&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:xs((()=>Ka(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;xs((()=>{const e=xo($o(a,this.decay),$o(ai(o),1-this.decay));if(this.centered){const t=this.accumulatedMeanGrads[n].variable,s=xo($o(t,this.decay),$o(o,1-this.decay)),l=So($o(o,this.learningRate),oi(Ci(e,xo(ai(s),this.epsilon)))),u=xo($o(i,this.momentum),l);a.assign(e),t.assign(s),i.assign(u);const c=Ci(r,u);r.assign(c)}else{const e=xo($o(a,this.decay),$o(ai(o),1-this.decay)),t=xo($o(i,this.momentum),So($o(o,this.learningRate),oi(xo(e,this.epsilon))));a.assign(e),i.assign(t);const n=Ci(r,t);r.assign(n)}}))})),this.incrementIterations()}dispose(){null!=this.accumulatedMeanSquares&&Es(this.accumulatedMeanSquares.map((e=>e.variable))),null!=this.accumulatedMeanGrads&&this.centered&&Es(this.accumulatedMeanGrads.map((e=>e.variable))),null!=this.accumulatedMoments&&Es(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 Th=[Sh,$h,Ah,_h,Nh,Mh,Ih];function Dh(e){return new Promise((e=>setTimeout(e))).then(e)}class Rh{constructor(e){if(!L().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Rh.URL_SCHEME)&&(e=e.slice(Rh.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=vs.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=Cs(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 Dh((()=>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 Dh((()=>e.dispatchEvent(new MouseEvent("click"))))}return{modelArtifactsInfo:Ls(e)}}}}Rh.URL_SCHEME="downloads://";class Bh{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=Os(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=>Fs(e.name))),r={};for(const s of e)s.paths.forEach((e=>{const s=Fs(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 Fh(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 Ch(e,t){null==t&&(t={});const n=null==t.fetchFunc?L().platform.fetch:t.fetchFunc,r=e.map((e=>n(e,t.requestInit,{isBinary:!0}))),s=(null==t.onProgress?await Promise.all(r):await Fh(r,t.onProgress,0,.5)).map((e=>e.arrayBuffer()));return null==t.onProgress?await Promise.all(s):await Fh(s,t.onProgress,.5,1)}function Ph(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=ks[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 p=0;return l.forEach((e=>{const n=t[e].paths.length,r=new vs(h.slice(p,p+n));o[e].forEach((e=>{const t=_s(r.slice(e.groupOffset,e.groupOffset+e.sizeBytes),[e.manifestEntry]);for(const e in t)d[e]=t[e]})),p+=n})),d}}Us.registerSaveRouter((e=>L().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Rh.URL_SCHEME)?function(e="model"){return new Rh(e)}(e.slice(Rh.URL_SCHEME.length)):null));class Oh{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=L().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=Cs(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=vs.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:Ls(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 Os(await this.loadModelJSON(),(e=>this.loadWeights(e)))}async loadStream(){const e=await this.loadModelJSON(),t=await this.getWeightUrls(e.weightsManifest),n=zs(e.weightsManifest);return Object.assign(Object.assign({},e),{weightSpecs:n,getWeightStream:()=>function(e,t){var n;const r=null==t.fetchFunc?L().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[zs(e),await Ch(t,this.loadOptions)]}}function Lh(e){return null!=e.match(Oh.URL_SCHEME_REGEX)}Oh.URL_SCHEME_REGEX=/^https?:\/\//;const zh=(e,t)=>{if("undefined"==typeof fetch&&(null==t||null==t.fetchFunc))return null;{let n=!0;if(n=Array.isArray(e)?e.every((e=>Lh(e))):Lh(e),n)return Uh(e,t)}return null};function Uh(e,t){return new Oh(e,t)}Us.registerSaveRouter(zh),Us.registerLoadRouter(zh);class Wh{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}}class Gh{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}}class qh{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}}function Kh(e,t,n,r){if(1===arguments.length){return null!=e.modelTopology||null!=e.weightSpecs?new Wh(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 Wh({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 Wh({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r})}var Vh={__proto__:null,CompositeArrayBuffer:vs,browserFiles:function(e){return new Bh(e)},browserHTTPRequest:function(e,t){return Uh(e,t)},concatenateArrayBuffers:function(e){return vs.join(e)},copyModel:async function(e,t){return po(e,t,!1)},decodeWeights:_s,decodeWeightsStream:async function(e,t){const n={},r=e.getReader();let s=new ArrayBuffer(0);for(const e of t){const t=await Ns(e,(async(e,t)=>(s=await Ts(r,s,t),s.slice(e,t))));s=await Ts(r,s,t);const o=s.slice(0,t);s=s.slice(t);const a=Ms(e,o);if(n[e.name]=a,"webgpu"===$s()){const e=As();"uploadToGPU"in e&&c(a.shape)>=L().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;eUs.getLoadHandlers(e,t),getModelArtifactsForJSON:Os,getModelArtifactsForJSONSync:Ps,getModelArtifactsInfoForJSON:Ls,getSaveHandlers:e=>Us.getSaveHandlers(e),getWeightSpecs:zs,http:Uh,isHTTPScheme:Lh,listModels:async function(){const e=co.getSchemes(),t={};for(const n of e){const e=await co.getManager(n).listModels();for(const r in e){t[n+uo+r]=e[r]}}return t},loadWeights:async function(e,t="",n,r){return Ph((e=>Ch(e,{requestInit:r})))(e,t,n)},moveModel:async function(e,t){return po(e,t,!0)},registerLoadRouter:e=>Us.registerLoadRouter(e),registerSaveRouter:e=>Us.registerSaveRouter(e),removeModel:async function(e){const t=ho(e);return co.getManager(t.scheme).removeModel(t.path)},weightsLoaderFactory:Ph,withSaveHandler:function(e){return new Gh(e)},withSaveHandlerSync:function(e){return new Gh(e)}};var Hh={__proto__:null,confusionMatrix:ms({confusionMatrix_:function(e,t,n){const r=ps(e,"labels","confusionMatrix"),s=ps(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=ol(wo(r,"int32"),n),a=ol(wo(s,"int32"),n),l=Zu(o),u=na(l,a);return wo(u,"int32")}})};let jh,Jh=!1;function Zh(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!=_n(wn,ss.backendName)){const n={pixels:e},r={numChannels:t};return ss.runKernel(wn,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==jh)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.");jh=new OffscreenCanvas(1,1).getContext("2d")}else jh=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});jh.canvas.width=l,jh.canvas.height=u,jh.drawImage(e,0,0,l,u),c=jh.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 Qh={__proto__:null,draw:function(e,t,n){let r=ps(e,"img","draw");if(!(e instanceof Pr)){const e=r;r=wo(e,"int32"),e.dispose()}Xh(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};ss.runKernel(Ne,s,o)},fromPixels:ms({fromPixels_:Zh}),fromPixelsAsync:async function(e,t=3){let n=null;if(L().getBool("WRAP_TO_IMAGEBITMAP")&&Yh(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 Zh(n,t)},toPixels:async function(e,t){let n=ps(e,"img","toPixels");if(!(e instanceof Pr)){const e=n;n=wo(e,"int32"),e.dispose()}Xh(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(!Jh){null!=_n(Ne,ss.backendName)&&(console.warn("tf.browser.toPixels is not efficient to draw tensor on canvas. Please try tf.browser.draw instead."),Jh=!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 ed(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 td={__proto__:null,prepareAndValidate:ed};function nd(e,t,n,r){const s=[...e];for(let e=s.length;e-1)o[s]=0;else{const a=rd(t,n,s);let i=r[a];e&1<-1)a[s]=Number.MAX_SAFE_INTEGER;else{const o=rd(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 ud(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 cd(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 hd={__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=od(a,l,u,r,e),h=ad(i,l,u,s,e),d=nd(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]=cd(d.begin[t],0,d.strides[t],r,s,o),d.end[t]=cd(d.end[t],1,d.strides[t],r,s,o);const e=1===d.strides[t]&&0===d.begin[t]&&d.end[t]===r;p=p&&e,f=f&&(0===t&&1===d.strides[t]||e)}else p=p&&1===d.strides[t]&&a,f=f&&(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:p,sliceDim0:f,isSimpleSlice:g,begin:d.begin,end:d.end,strides:d.strides}},startForAxis:ld,startIndicesWithElidedDims:od,stopForAxis:ud,stopIndicesWithElidedDims:ad,stridesForAxis:id,stridesWithElidedDims:nd};class dd{static sgd(e){return new Ih(e)}static momentum(e,t,n=!1){return new Nh(e,t,n)}static rmsprop(e,t=.9,n=0,r=null,s=!1){return new Mh(e,t,n,r,s)}static adam(e=.001,t=.9,n=.999,r=null){return new Ah(e,t,n,r)}static adadelta(e=.001,t=.95,n=null){return new Sh(e,t,n)}static adamax(e=.002,t=.9,n=.999,r=null,s=0){return new _h(e,t,n,r,s)}static adagrad(e,t=.1){return new $h(e,t)}}const pd=dd,fd="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:e=>e();var gd;!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"}(gd||(gd={}));const md="->",bd=/->/g;function yd(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:Xa,calculateShapes:Lu,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:Yo,combineLocations:Qa,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;r1)throw new Error('Equation must contain exactly one arrow ("->").');const[r,s]=e.split(md);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;evr(e)))},fromUint8ToStringArray:function(e){try{return e.map((e=>xr(e)))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}},getAxesPermutation:function(e,t){if(Xa(e,t))return null;const n=[];for(let r=0;rn.push(e))),n},getBroadcastDims:La,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:ic,getFusedDyActivation:ac,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]===gd.FIRST_DIM_SIZE?e.length-1:e.length},getReductionAxes:za,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){L().getBool("IS_TEST")||L().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:uc,slice_util:hd,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:Ou,validateUpdateShape:Pu,warn:Sn},kd={__proto__:null,nonMaxSuppressionV3Impl:Nc,nonMaxSuppressionV4Impl:Mc,nonMaxSuppressionV5Impl:Tc,whereImpl:Hu};!function(){for(const e of Th)vh(e)}(),e.Abs="Abs",e.Acos=G,e.Acosh=q,e.AdadeltaOptimizer=Sh,e.AdagradOptimizer=$h,e.AdamOptimizer=Ah,e.AdamaxOptimizer=_h,e.Add=K,e.AddN=V,e.All="All",e.Any="Any",e.ArgMax=H,e.ArgMin=j,e.Asin=J,e.Asinh=Z,e.Atan=Y,e.Atan2=Q,e.Atanh=X,e.AvgPool=ee,e.AvgPool3D=te,e.AvgPool3DGrad="AvgPool3DGrad",e.AvgPoolGrad="AvgPoolGrad",e.BatchMatMul=ne,e.BatchToSpaceND=re,e.Bincount=se,e.BitwiseAnd=oe,e.BroadcastArgs=ae,e.BroadcastTo="BroadcastTo",e.Cast=ie,e.Ceil=le,e.ClipByValue=ue,e.Complex=ce,e.ComplexAbs=he,e.Concat=de,e.Conv2D=pe,e.Conv2DBackpropFilter=fe,e.Conv2DBackpropInput=ge,e.Conv3D=me,e.Conv3DBackpropFilterV2="Conv3DBackpropFilterV2",e.Conv3DBackpropInputV2=be,e.Cos="Cos",e.Cosh=ye,e.CropAndResize=ve,e.Cumprod=we,e.Cumsum=ke,e.DataStorage=class{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}},e.DenseBincount=xe,e.DepthToSpace=Ee,e.DepthwiseConv2dNative=Se,e.DepthwiseConv2dNativeBackpropFilter=$e,e.DepthwiseConv2dNativeBackpropInput=Ae,e.Diag=_e,e.Dilation2D=Ie,e.Dilation2DBackpropFilter="Dilation2DBackpropFilter",e.Dilation2DBackpropInput="Dilation2DBackpropInput",e.Draw=Ne,e.Einsum=Te,e.Elu="Elu",e.EluGrad="EluGrad",e.Environment=P,e.Equal=De,e.Erf="Erf",e.Exp="Exp",e.ExpandDims=Re,e.Expm1=Be,e.FFT="FFT",e.Fill=Fe,e.FlipLeftRight=Ce,e.Floor=Pe,e.FloorDiv=Oe,e.FromPixels=wn,e.FusedBatchNorm=Le,e.FusedConv2D=xn,e.FusedDepthwiseConv2D=En,e.GatherNd=Ue,e.GatherV2=ze,e.Greater=We,e.GreaterEqual=Ge,e.IFFT=Ke,e.Identity=qe,e.Imag=Ve,e.IsFinite=He,e.IsInf=je,e.IsNan=Je,e.KernelBackend=n,e.LRN="LRN",e.LRNGrad="LRNGrad",e.LeakyRelu=Ze,e.Less=Ye,e.LessEqual=Xe,e.LinSpace=Qe,e.Log="Log",e.Log1p=et,e.LogSoftmax="LogSoftmax",e.LogicalAnd=tt,e.LogicalNot=nt,e.LogicalOr=rt,e.LogicalXor="LogicalXor",e.LowerBound="LowerBound",e.MatrixBandPart="MatrixBandPart",e.Max="Max",e.MaxPool=ot,e.MaxPool3D=at,e.MaxPool3DGrad="MaxPool3DGrad",e.MaxPoolGrad="MaxPoolGrad",e.MaxPoolWithArgmax=it,e.Maximum=st,e.Mean=lt,e.Min="Min",e.Minimum=ut,e.MirrorPad=ct,e.Mod="Mod",e.MomentumOptimizer=Nh,e.Multinomial=ht,e.Multiply=dt,e.Neg="Neg",e.NonMaxSuppressionV3=ft,e.NonMaxSuppressionV4=gt,e.NonMaxSuppressionV5=mt,e.NotEqual=pt,e.OP_SCOPE_SUFFIX=gs,e.OneHot=yt,e.OnesLike=bt,e.Optimizer=Eh,e.OptimizerConstructors=dd,e.Pack=wt,e.PadV2=kt,e.Pool="Pool",e.Pow="Pow",e.Prelu=vt,e.Prod=xt,e.RMSPropOptimizer=Mh,e.RaggedGather=Et,e.RaggedRange=St,e.RaggedTensorToTensor=$t,e.Range=At,e.Real=_t,e.RealDiv=Me,e.Reciprocal=It,e.Relu=Nt,e.Relu6=Rt,e.Reshape=Mt,e.ResizeBilinear=Dt,e.ResizeBilinearGrad="ResizeBilinearGrad",e.ResizeNearestNeighbor=Tt,e.ResizeNearestNeighborGrad="ResizeNearestNeighborGrad",e.Reverse=Bt,e.RotateWithOffset=kn,e.Round=Ft,e.Rsqrt=Ct,e.SGDOptimizer=Ih,e.ScatterNd=Pt,e.SearchSorted=Lt,e.Select=zt,e.Selu=Ut,e.Sigmoid=Kt,e.Sign=qt,e.Sin="Sin",e.Sinh=Gt,e.Slice=Wt,e.Softmax=Zt,e.Softplus=Vt,e.SpaceToBatchND=jt,e.SparseFillEmptyRows=Yt,e.SparseReshape=Xt,e.SparseSegmentMean=Qt,e.SparseSegmentSum=en,e.SparseToDense=tn,e.SplitV=Jt,e.Sqrt=Ht,e.Square="Square",e.SquaredDifference=nn,e.StaticRegexReplace=rn,e.Step=yn,e.StridedSlice=sn,e.StringNGrams=on,e.StringSplit=an,e.StringToHashBucketFast=ln,e.Sub="Sub",e.Sum="Sum",e.Tan="Tan",e.Tanh=un,e.Tensor=Pr,e.TensorBuffer=Br,e.TensorScatterUpdate=Ot,e.Tile=cn,e.TopK=hn,e.Transform=dn,e.Transpose=pn,e.Unique=fn,e.Unpack=gn,e.UnsortedSegmentSum=mn,e.UpperBound="UpperBound",e.Variable=Lr,e.ZerosLike=bn,e._FusedMatMul=vn,e.abs=Ao,e.acos=_o,e.acosh=Io,e.add=xo,e.addN=No,e.all=Mo,e.any=To,e.argMax=Do,e.argMin=Ro,e.asin=Bo,e.asinh=Fo,e.atan=Co,e.atan2=Po,e.atanh=Oo,e.avgPool=Qo,e.avgPool3d=ea,e.backend=As,e.backend_util=wd,e.basicLSTMCell=aa,e.batchNorm=la,e.batchNorm2d=ua,e.batchNorm3d=ca,e.batchNorm4d=ha,e.batchToSpaceND=ia,e.bincount=da,e.bitwiseAnd=pa,e.booleanMaskAsync=Ju,e.broadcastArgs=fa,e.broadcastTo=ga,e.broadcast_util=Wa,e.browser=Qh,e.buffer=yo,e.cast=wo,e.ceil=ma,e.clipByValue=ya,e.clone=ko,e.complex=bs,e.concat=ta,e.concat1d=wa,e.concat2d=ka,e.concat3d=va,e.concat4d=xa,e.conv1d=Sa,e.conv2d=Ea,e.conv2dTranspose=Aa,e.conv3d=_a,e.conv3dTranspose=Na,e.copyRegisteredKernels=function(e,t){Nn(e).forEach((e=>{Mn(Object.assign({},e,{backendName:t}))}))},e.cos=Ma,e.cosh=Ta,e.cosineWindow=rc,e.cumprod=Da,e.cumsum=Ra,e.customGrad=Ti,e.denseBincount=Ba,e.deprecationWarn=function(e){L().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")},e.depthToSpace=Fa,e.depthwiseConv2d=Ca,e.device_util=ls,e.diag=Pa,e.dilation2d=Oa,e.disableDeprecationWarnings=function(){L().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")},e.dispose=Es,e.disposeVariables=function(){ss.disposeVariables()},e.div=So,e.divNoNan=Va,e.dot=Ha,e.dropout=tc,e.einsum=ja,e.elu=Ja,e.enableDebugMode=function(){L().set("DEBUG",!0)},e.enableProdMode=function(){L().set("PROD",!0)},e.enclosingPowerOfTwo=nc,e.engine=function(){return ss},e.ensureShape=Za,e.env=L,e.equal=Ga,e.erf=Ya,e.euclideanNorm=ci,e.exp=hi,e.expandDims=di,e.expm1=pi,e.eye=gi,e.fft=Eu,e.fill=ba,e.findBackend=function(e){return ss.findBackend(e)},e.findBackendFactory=function(e){return ss.findBackendFactory(e)},e.floor=mi,e.floorDiv=Eo,e.fused=gc,e.gather=bi,e.gatherND=ec,e.gather_util=td,e.getBackend=$s,e.getGradient=In,e.getKernel=_n,e.getKernelsForBackend=Nn,e.grad=function(e){return i(_(e),(()=>"The f passed in grad(f) must be a function")),(t,n)=>{const r=ps(t,"x","tf.grad","string_or_numeric"),s=null!=n?ps(n,"dy","tf.grad"):null;return ss.tidy((()=>{const{value:t,grads:n}=ss.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)"),Di(n),n[0]}))}},e.grads=function(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=fs(t,"args","tf.grads","string_or_numeric"),s=null!=n?ps(n,"dy","tf.grads"):null;return ss.tidy((()=>{const{value:t,grads:n}=ss.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,...])"),Di(n),n}))}},e.greater=yi,e.greaterEqual=wi,e.ifft=Su,e.imag=ki,e.image=dh,e.inTopKAsync=sc,e.io=Vh,e.irfft=$u,e.isFinite=vi,e.isInf=xi,e.isNaN=Ei,e.keep=Ss,e.kernel_impls=kd,e.leakyRelu=Si,e.less=$i,e.lessEqual=Ai,e.linalg=ph,e.linspace=function(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");const r={start:e,stop:t,num:n};return ss.runKernel(Qe,{},r)},e.localResponseNormalization=_i,e.log=Ii,e.log1p=Ni,e.logSigmoid=Fi,e.logSoftmax=Pi,e.logSumExp=Oi,e.logicalAnd=Li,e.logicalNot=zi,e.logicalOr=Ui,e.logicalXor=Wi,e.losses=fh,e.lowerBound=function(e,t){return qi(e,t,"left")},e.matMul=na,e.math=Hh,e.max=ti,e.maxPool=Ki,e.maxPool3d=Vi,e.maxPoolWithArgmax=Hi,e.maximum=ji,e.mean=Ji,e.memory=function(){return ss.memory()},e.meshgrid=function(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=ps(e,"x","meshgrid",e instanceof Pr?e.dtype:"float32");if(void 0===t)return[r];let s=ps(t,"y","meshgrid",t instanceof Pr?t.dtype:"float32");const o=c(r.shape),a=c(s.shape);return"xy"===n?(r=Xo(r,[1,-1]),s=Xo(s,[-1,1]),[na(Yi([a,1],r.dtype),r),na(s,Yi([1,o],s.dtype))]):(r=Xo(r,[-1,1]),s=Xo(s,[1,-1]),[na(r,Yi([1,a],r.dtype)),na(Yi([o,1],s.dtype),s)])},e.min=ni,e.minimum=Xi,e.mirrorPad=Qi,e.mod=el,e.moments=tl,e.movingAverage=Yu,e.mul=$o,e.multiRNNCell=nl,e.multinomial=rl,e.neg=Ri,e.nextFrame=function(){return new Promise((e=>fd((()=>e()))))},e.norm=ui,e.notEqual=sl,e.oneHot=ol,e.ones=Yi,e.onesLike=al,e.op=ms,e.outerProduct=il,e.pad=ll,e.pad1d=ul,e.pad2d=cl,e.pad3d=hl,e.pad4d=dl,e.pool=fl,e.pow=ri,e.prelu=gl,e.print=vo,e.prod=ml,e.profile=function(e){return ss.profile(e)},e.raggedGather=bl,e.raggedRange=yl,e.raggedTensorToTensor=wl,e.rand=kl,e.randomGamma=Jl,e.randomNormal=Zl,e.randomStandardNormal=Yl,e.randomUniform=Xl,e.randomUniformInt=Ql,e.range=eu,e.ready=function(){return ss.ready()},e.real=tu,e.reciprocal=nu,e.registerBackend=function(e,t,n=1){return ss.registerBackend(e,t,n)},e.registerGradient=function(e){const{kernelName:t}=e;An.has(t)&&L().getBool("DEBUG")&&Sn(`Overriding the gradient for '${t}'`),An.set(t,e)},e.registerKernel=Mn,e.relu=ru,e.relu6=su,e.removeBackend=function(e){ss.removeBackend(e)},e.reshape=Xo,e.reverse=ou,e.reverse1d=au,e.reverse2d=iu,e.reverse3d=lu,e.reverse4d=uu,e.rfft=_u,e.round=cu,e.rsqrt=hu,e.scalar=si,e.scatterND=Xu,e.scatter_util=zu,e.searchSorted=qi,e.selu=du,e.separableConv2d=pu,e.serialization=xh,e.setBackend=function(e){return ss.setBackend(e)},e.setPlatform=function(e,t){L().setPlatform(e,t)},e.setdiff1dAsync=fu,e.sigmoid=ra,e.sign=gu,e.signal=hh,e.sin=mu,e.sinh=bu,e.slice=sa,e.slice1d=yu,e.slice2d=wu,e.slice3d=ku,e.slice4d=vu,e.slice_util=hd,e.softmax=xu,e.softplus=Bi,e.spaceToBatchND=pl,e.sparse=gh,e.sparseToDense=Qu,e.spectral=ch,e.split=Au,e.sqrt=oi,e.square=ai,e.squaredDifference=Iu,e.squeeze=Nu,e.stack=Mu,e.step=Tu,e.stridedSlice=Du,e.string=mh,e.sub=Ci,e.sum=ii,e.sumOutType=function(e){return Vr(e,"int32")},e.tan=Ru,e.tanh=oa,e.tensor=ws,e.tensor1d=Bu,e.tensor2d=Fu,e.tensor3d=Cu,e.tensor4d=function(e,t,n){if(u(e),null!=t&&4!==t.length)throw new Error("tensor4d() requires shape to have four numbers");const r=cs(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 ys(e,t,r,n)},e.tensor5d=function(e,t,n){if(u(e),null!=t&&5!==t.length)throw new Error("tensor5d() requires shape to have five numbers");const r=cs(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 ys(e,t,r,n)},e.tensor6d=function(e,t,n){if(u(e),null!=t&&6!==t.length)throw new Error("tensor6d() requires shape to have six numbers");const r=cs(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 ys(e,t=t||r,r,n)},e.tensorScatterUpdate=Uu,e.tensor_util=Qr,e.test_util=Kl,e.tidy=xs,e.tile=fi,e.time=function(e){return ss.time(e)},e.topk=Wu,e.train=pd,e.transpose=Zu,e.truncatedNormal=Gu,e.unique=qu,e.unregisterGradient=function(e){if(!An.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);An.delete(e)},e.unregisterKernel=function(e,t){const n=Tn(e,t);if(!$n.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);$n.delete(n)},e.unsortedSegmentSum=Ku,e.unstack=Vu,e.upcastType=Vr,e.upperBound=function(e,t){return qi(e,t,"right")},e.util=$r,e.valueAndGrad=function(e){return i(_(e),(()=>"The f passed in valueAndGrad(f) must be a function")),(t,n)=>{i(t instanceof Pr,(()=>"The x passed in valueAndGrad(f)(x) must be a tensor")),i(null==n||n instanceof Pr,(()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"));const{grads:r,value:s}=ss.gradients((()=>e(t)),[t],n);return Di(r),{grad:r[0],value:s}}},e.valueAndGrads=function(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 Pr)),(()=>"The args passed in valueAndGrads(f)(args) must be array of tensors")),i(null==n||n instanceof Pr,(()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"));const r=ss.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,...])"),Di(r.grads),r}},e.variable=function(e,t=!0,n,r){return ss.makeVariable(e,t,n,r)},e.variableGrads=Mi,e.version_core="4.15.0",e.where=qa,e.whereAsync=ju,e.zeros=Zi,e.zerosLike=Ka})); //# sourceMappingURL=tf-core.es2017.min.js.map