face-api/dist/face-api.js

3982 lines
1.1 MiB

var faceapi=(()=>{var wm=Object.defineProperty,y7=Object.prototype.hasOwnProperty,Lm=(r,l)=>()=>(l||(l={exports:{}},r(l.exports,l)),l.exports),NC=r=>wm(r,"__esModule",{value:!0}),uu=(r,l)=>{NC(r);for(var u in l)wm(r,u,{get:l[u],enumerable:!0})},b7=(r,l)=>{if(NC(r),typeof l=="object"||typeof l=="function")for(let u in l)!y7.call(r,u)&&u!=="default"&&wm(r,u,{get:()=>l[u],enumerable:!0});return r},Xe=r=>r&&r.__esModule?r:b7(wm({},"default",{value:r,enumerable:!0}),r);var RC=Lm((Lc,CC)=>{"use strict";var w7=function(){if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof lr!="undefined")return lr;throw new Error("unable to locate global object")},lr=w7();CC.exports=Lc=lr.fetch;lr.fetch&&(Lc.default=lr.fetch.bind(lr));Lc.Headers=lr.Headers;Lc.Request=lr.Request;Lc.Response=lr.Response});var Je=Lm((Sm,OC)=>{(function(r,l){typeof Sm=="object"&&typeof OC!="undefined"?l(Sm):typeof define=="function"&&define.amd?define(["exports"],l):(r=r||self,l(r.tf=r.tf||{}))})(Sm,function(r){"use strict";const l=1e-7,u=1e-4;class p{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class g{time(e){return f("time")}read(e){return f("read")}readSync(e){return f("readSync")}numDataIds(){return f("numDataIds")}disposeData(e){return f("disposeData")}write(e,t,n){return f("write")}move(e,t,n,s){return f("move")}memory(){return f("memory")}floatPrecision(){return f("floatPrecision")}epsilon(){return this.floatPrecision()===32?l:u}batchMatMul(e,t,n,s){return f("batchMatMul")}fusedBatchMatMul({a:e,b:t,transposeA:n,transposeB:s,bias:i,activation:o,preluActivationWeights:a}){return f("fusedBatchMatMul")}slice(e,t,n){return f("slice")}stridedSlice(e,t,n,s){return f("stridedSlice")}unstack(e,t){return f("unstack")}reverse(e,t){return f("reverse")}concat(e,t){return f("concat")}neg(e){return f("neg")}add(e,t){return f("add")}addN(e){return f("addN")}subtract(e,t){return f("subtract")}multiply(e,t){return f("multiply")}realDivide(e,t){return f("realDivide")}floorDiv(e,t){return f("floorDiv")}sum(e,t){return f("sum")}prod(e,t){return f("prod")}unsortedSegmentSum(e,t,n){return f("unsortedSegmentSum")}argMin(e,t){return f("argMin")}argMax(e,t){return f("argMax")}equal(e,t){return f("equal")}notEqual(e,t){return f("notEqual")}less(e,t){return f("less")}lessEqual(e,t){return f("lessEqual")}greater(e,t){return f("greater")}greaterEqual(e,t){return f("greaterEqual")}logicalNot(e){return f("logicalNot")}logicalAnd(e,t){return f("logicalAnd")}logicalOr(e,t){return f("logicalOr")}where(e){return f("where")}select(e,t,n){return f("select")}topk(e,t,n){return f("topk")}min(e,t){return f("min")}minimum(e,t){return f("minimum")}mod(e,t){return f("mod")}max(e,t){return f("max")}maximum(e,t){return f("maximum")}all(e,t){return f("all")}any(e,t){return f("any")}squaredDifference(e,t){return f("squaredDifference")}ceil(e){return f("ceil")}floor(e){return f("floor")}round(e){return f("round")}sign(e){return f("sign")}isNaN(e){return f("isNaN")}isInf(e){return f("isInf")}isFinite(e){return f("isFinite")}pow(e,t){return f("pow")}exp(e){return f("exp")}expm1(e){return f("expm1")}softmax(e,t){return f("softmax")}log(e){return f("log")}log1p(e){return f("log1p")}sqrt(e){return f("sqrt")}rsqrt(e){return f("rsqrt")}square(e){return f("square")}reciprocal(e){return f("reciprocal")}relu(e){return f("relu")}relu6(e){return f("relu6")}prelu(e,t){return f("prelu")}elu(e){return f("elu")}eluDer(e,t){return f("eluDer")}selu(e){return f("selu")}int(e){return f("int")}clip(e,t,n){return f("clip")}abs(e){return f("abs")}complexAbs(e){return f("complexAbs")}sigmoid(e){return f("sigmoid")}softplus(e){return f("softplus")}sin(e){return f("sin")}cos(e){return f("cos")}tan(e){return f("tan")}asin(e){return f("asin")}acos(e){return f("acos")}atan(e){return f("atan")}atan2(e,t){return f("atan2")}sinh(e){return f("sinh")}cosh(e){return f("cosh")}tanh(e){return f("tanh")}asinh(e){return f("asinh")}acosh(e){return f("acosh")}atanh(e){return f("atanh")}erf(e){return f("erf")}step(e,t){return f("step")}fusedConv2d({input:e,filter:t,convInfo:n,bias:s,activation:i,preluActivationWeights:o}){return f("fusedConv2d")}conv2d(e,t,n){return f("conv2d")}conv2dDerInput(e,t,n){return f("conv2dDerInput")}conv2dDerFilter(e,t,n){return f("conv2dDerFilter")}fusedDepthwiseConv2D({input:e,filter:t,convInfo:n,bias:s,activation:i,preluActivationWeights:o}){return f("fusedDepthwiseConv2D")}depthwiseConv2D(e,t,n){return f("depthwiseConv2D")}depthwiseConv2DDerInput(e,t,n){return f("depthwiseConv2DDerInput")}depthwiseConv2DDerFilter(e,t,n){return f("depthwiseConv2DDerFilter")}conv3d(e,t,n){return f("conv3d")}conv3dDerInput(e,t,n){return f("conv3dDerInput")}conv3dDerFilter(e,t,n){return f("conv3dDerFilter")}maxPool(e,t){return f("maxPool")}maxPoolBackprop(e,t,n,s){return f("maxPoolBackprop")}avgPool(e,t){return f("avgPool")}avgPoolBackprop(e,t,n){return f("avgPoolBackprop")}avgPool3d(e,t){return f("avgPool3d")}avgPool3dBackprop(e,t,n){return f("avgPool3dBackprop")}maxPool3d(e,t){return f("maxPool3d")}maxPool3dBackprop(e,t,n,s){return f("maxPool3dBackprop")}reshape(e,t){return f("reshape")}cast(e,t){return f("cast")}tile(e,t){return f("tile")}pad(e,t,n){return f("pad")}transpose(e,t){return f("transpose")}gather(e,t,n){return f("gather")}gatherND(e,t){return f("gatherND")}scatterND(e,t,n){return f("scatterND")}batchToSpaceND(e,t,n){return f("batchToSpaceND")}spaceToBatchND(e,t,n){return f("spaceToBatchND")}resizeBilinear(e,t,n,s){return f("resizeBilinear")}resizeBilinearBackprop(e,t,n){return f("resizeBilinearBackprop")}resizeNearestNeighbor(e,t,n,s){return f("resizeNearestNeighbor")}resizeNearestNeighborBackprop(e,t,n){return f("resizeNearestNeighborBackprop")}batchNorm(e,t,n,s,i,o){return f("batchNorm")}localResponseNormalization4D(e,t,n,s,i){return f("localResponseNormalization4D")}LRNGrad(e,t,n,s,i,o,a){return f("LRNGrad")}multinomial(e,t,n,s){return f("multinomial")}oneHot(e,t,n,s){return f("oneHot")}cumsum(e,t,n,s){return f("cumsum")}nonMaxSuppression(e,t,n,s,i){return f("nonMaxSuppression")}fft(e){return f("fft")}ifft(e){return f("ifft")}complex(e,t){return f("complex")}real(e){return f("real")}imag(e){return f("imag")}cropAndResize(e,t,n,s,i,o){return f("cropAndResize")}depthToSpace(e,t,n){return f("depthToSpace")}split(e,t,n){return f("split")}sparseToDense(e,t,n,s){return f("sparseToDense")}diag(e){return f("diag")}fill(e,t,n){return f("fill")}onesLike(e){return f("onesLike")}zerosLike(e){return f("zerosLike")}linspace(e,t,n){return f("linspace")}dispose(){return f("dispose")}}function f(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`)}const I="tfjsflags";class S{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}setPlatform(e,t){this.platform!=null&&console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${t}.`),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},this.urlFlags[e]!=null){const s=this.urlFlags[e];console.warn(`Setting feature override from URL ${e}: ${s}.`),this.set(e,s)}}async getAsync(e){return e in this.flags?this.flags[e]:(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(t instanceof Promise)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)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(this.flagRegistry[e]==null)throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,this.flagRegistry[e].setHook!=null&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(this.flagRegistry[e]==null)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(typeof this.global=="undefined"||typeof this.global.location=="undefined"||typeof this.global.location.search=="undefined")return;const e=x(this.global.location.search);if(I in e){const t=e[I].split(",");t.forEach(n=>{const[s,i]=n.split(":");this.urlFlags[s]=O(s,i)})}}}function x(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...s)=>(v(t,s[0],s[1]),s.join("="))),t}function v(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function O(e,t){if(t=t.toLowerCase(),t==="true"||t==="false")return t==="true";if(`${+t}`===t)return+t;throw new Error(`Could not parse value flag value ${t} for flag ${e}.`)}function C(){return r.ENV}r.ENV=null;function U(e){r.ENV=e}let G;function ne(){if(G==null){let e;if(typeof window!="undefined")e=window;else if(typeof global!="undefined")e=global;else if(typeof process!="undefined")e=process;else if(typeof self!="undefined")e=self;else throw new Error("Could not find a global object");G=e}return G}function te(){const e=ne();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function oe(e,t){const n=te();if(n.has(e))return n.get(e);{const s=t();return n.set(e,s),n.get(e)}}const ge="Abs",fe="Acos",Ae="Acosh",Te="Add",Ve="AddN",rt="All",Ct="Any",Ut="ArgMax",Kt="ArgMin",Dn="Asin",An="Asinh",vn="Atan",Zs="Atanh",Si="Atan2",Qs="AvgPool",ya="AvgPoolBackprop",ol="AvgPool3D",ax="AvgPool3DBackprop",_g="BatchMatMul",Wg="BatchToSpaceND",$g="BroadcastTo",al="Cast",cl="Ceil",ll="ClipByValue",Ug="Complex",qu="Concat",Bg="Conv2D",cx="Conv2DBackpropFilter",Mg="Conv2DBackpropInput",Pg="Conv3D",lx="Conv3DBackpropFilterV2",hx="Conv3DBackpropInputV2",ba="Cos",hl="Cosh",zg="Cumsum",ux="CropAndResize",dx="DepthToSpace",Gg="DepthwiseConv2dNative",px="DepthwiseConv2dNativeBackpropFilter",mx="DepthwiseConv2dNativeBackpropInput",fx="Diag",ju="Dilation2D",Ku="Dilation2DBackpropInput",Xu="Dilation2DBackpropFilter",wa="Div",ul="Elu",gx="EluGrad",dl="Erf",yx="Equal",pl="Exp",ml="Expm1",Vg="FFT",bx="Fill",Ju="FlipLeftRight",fl="Floor",Yg="FloorDiv",gl="FusedBatchNorm",Hg="GatherV2",wx="GatherNd",Lx="Greater",qg="GreaterEqual",yl="Identity",jg="IFFT",Kg="Imag",bl="IsFinite",wl="IsInf",Ll="IsNan",Sx="Less",Ix="LessEqual",xx="LinSpace",Sl="Log",Il="Log1p",Tx="LogicalAnd",Zu="LogicalNot",Ax="LogicalOr",Xg="LogSoftmax",Jg="LRN",vx="LRNBackprop",xl="Max",Zg="Maximum",Tl="MaxPool",Qu="MaxPoolBackprop",Qg="MaxPool3D",Nx="MaxPool3DBackprop",ed="MaxPoolWithArgmax",YD="Mean",ey="Min",ty="Minimum",ny="Mod",Al="Multiply",sy="Negate",td="NotEqual",iy="NonMaxSuppressionV3",nd="NonMaxSuppressionV4",sd="NonMaxSuppressionV5",ry="OnesLike",oy="OneHot",id="PadV2",HD="Pool",ay="Pow",cy="Prelu",Cx="Prod",Rx="Range",ly="Real",vl="Reciprocal",hy="Relu",Nl="Reshape",uy="ResizeNearestNeighbor",Ox="ResizeNearestNeighborGrad",dy="ResizeBilinear",Ex="ResizeBilinearGrad",py="Relu6",my="Reverse",Cl="Round",Rl="Rsqrt",Dx="ScatterNd",fy="SelectV2",Ol="Selu",rd="Slice",La="Sin",El="Sinh",Dl="Sign",kl="Sigmoid",Fl="Softplus",_l="Sqrt",gy="Sum",od="SpaceToBatchND",yy="SplitV",by="Softmax",Sa="SquaredDifference",ad="Square",Wl="Sub",kx="SparseToDense",Fx="StridedSlice",Ia="Tan",$l="Tanh",wy="Tile",_x="TopK",Ul="Transpose",cd="Unique",Ly="Unpack",Sy="UnsortedSegmentSum",Iy="ZerosLike",Bl="Step",ld="FromPixels",hd="RotateWithOffset",xy="_FusedMatMul",Ty="FusedConv2D",Ay="FusedDepthwiseConv2D";const xa=oe("kernelRegistry",()=>new Map),Ml=oe("gradRegistry",()=>new Map);function vy(e,t){const n=Cy(e,t);return xa.get(n)}function Ny(e){return Ml.get(e)}function ud(e){const t=xa.entries(),n=[];for(;;){const{done:s,value:i}=t.next();if(s)break;const[o,a]=i,[c]=o.split("_");c===e&&n.push(a)}return n}function dd(e){const{kernelName:t,backendName:n}=e,s=Cy(t,n);xa.has(s)&&console.warn(`The kernel '${t}' for backend '${n}' is already registered`),xa.set(s,e)}function Wx(e){const{kernelName:t}=e;Ml.has(t)&&(C().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${t}'`)),Ml.set(t,e)}function qD(e,t){const n=Cy(e,t);if(!xa.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);xa.delete(n)}function jD(e){if(!Ml.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);Ml.delete(e)}function KD(e,t){const n=ud(e);n.forEach(s=>{const i=Object.assign({},s,{backendName:t});dd(i)})}function Cy(e,t){return`${t}_${e}`}function Ry(e){let t=e.length,n=0,s=0;for(;t>0;)s=Math.random()*t|0,t--,n=e[t],e[t]=e[s],e[s]=n}function Pl(e,t,n){return Math.max(e,Math.min(t,n))}function Oy(e){return e%2===0?e:e+1}function $x(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function XD(e,t){const n=Math.random();return t*n+(1-n)*e}function JD(e,t){let n=0;for(let s=0;s<e.length;s++){const i=Number(e[s])-Number(t[s]);n+=i*i}return n}function k(e,t){if(!e)throw new Error(typeof t=="string"?t:t())}function pt(e,t,n=""){k(ot(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function yo(e){k(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function qi(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||wn(e)&&!n)for(let s=0;s<e.length;++s)qi(e[s],t,n);else t.push(e);return t}function we(e){if(e.length===0)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function ZD(e){return e.length===0}function ot(e,t){if(e===t)return!0;if(e==null||t==null)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function Bt(e){return e%1===0}function QD(e){if(Math.tanh!=null)return Math.tanh(e);if(e===Infinity)return 1;if(e===-Infinity)return-1;{const t=Math.exp(2*e);return(t-1)/(t+1)}}function pd(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function ek(e){const t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return Ry(t),t}function bo(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function Ey(e,t=s=>0,n){return new Promise((s,i)=>{let o=0;const a=()=>{if(e()){s();return}o++;const c=t(o);if(n!=null&&o>=n){i();return}setTimeout(a,c)};a()})}function md(e,t){let n=1,s=-1;for(let o=0;o<e.length;++o)if(e[o]>=0)n*=e[o];else if(e[o]===-1){if(s!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${s} and dim ${o}`);s=o}else if(e[o]<0)throw Error(`Shapes can not be < 0. Found ${e[o]} at dim ${o}`);if(s===-1){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(n===0)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 i=e.slice();return i[s]=t/n,i}function gt(e,t){const n=t.length;return e=e==null?t.map((s,i)=>i):[].concat(e),k(e.every(s=>s>=-n&&s<n),()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),k(e.every(s=>Bt(s)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(s=>s<0?n+s:s)}function Ir(e,t){const n=[],s=[],i=t!=null&&Array.isArray(t)&&t.length===0,o=t==null||i?null:gt(t,e).sort();let a=0;for(let c=0;c<e.length;++c){if(o!=null){if(o[a]===c&&e[c]!==1)throw new Error(`Can't squeeze axis ${c} since its dim '${e[c]}' is not 1`);(o[a]==null||o[a]>c)&&e[c]===1&&(n.push(e[c]),s.push(c)),o[a]<=c&&a++}e[c]!==1&&(n.push(e[c]),s.push(c))}return{newShape:n,keptDims:s}}function bn(e,t){let n=null;if(e==null||e==="float32")n=new Float32Array(t);else if(e==="int32")n=new Int32Array(t);else if(e==="bool")n=new Uint8Array(t);else throw new Error(`Unknown data type ${e}`);return n}function wo(e,t){let n=null;if(e==null||e==="float32")n=new Float32Array(t);else if(e==="int32")n=new Int32Array(t);else if(e==="bool")n=new Uint8Array(t);else if(e==="string")n=new Array(t);else throw new Error(`Unknown data type ${e}`);return n}function Ux(e,t){for(let n=0;n<e.length;n++){const s=e[n];if(isNaN(s)||!isFinite(s))throw Error(`A tensor of type ${t} being uploaded contains ${s}.`)}}function Bx(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function Dy(e,t){return t==="complex64"||(t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64")?!1:!(t==="bool"&&e==="bool")}function wn(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function ky(e){if(e==="float32"||e==="int32")return 4;if(e==="complex64")return 8;if(e==="bool")return 1;throw new Error(`Unknown dtype ${e}`)}function Mx(e){if(e==null)return 0;let t=0;return e.forEach(n=>t+=n.length),t}function xr(e){return typeof e=="string"||e instanceof String}function Px(e){return typeof e=="boolean"}function fd(e){return typeof e=="number"}function Ta(e){return Array.isArray(e)?Ta(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":fd(e)?"float32":xr(e)?"string":Px(e)?"bool":"float32"}function Tr(e){return!!(e&&e.constructor&&e.call&&e.apply)}function gd(e,t){for(let n=t;n<e;++n)if(e%n===0)return n;return e}function Ot(e){const t=e.length;if(t<2)return[];const n=new Array(t-1);n[t-2]=e[t-1];for(let s=t-3;s>=0;--s)n[s]=n[s+1]*e[s+1];return n}function zx(e,t){return t==="string"?$y(e):Ar([e],t)}function Ar(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=qi(e)),C().getBool("DEBUG")&&Ux(e,t),tk(e,t))return e;if(t==null||t==="float32"||t==="complex64")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool"){const n=new Uint8Array(e.length);for(let s=0;s<n.length;++s)Math.round(e[s])!==0&&(n[s]=1);return n}else throw new Error(`Unknown data type ${t}`)}function Gx(e,t,n){const s=new Array;if(t.length===1){const i=t[0];for(let o=0;o<i;o++)s[o]=n[e+o]}else{const i=t[0],o=t.slice(1),a=o.reduce((c,h)=>c*h);for(let c=0;c<i;c++)s[c]=Gx(e+c*a,o,n)}return s}function ys(e,t){if(e.length===0)return t[0];const n=e.reduce((s,i)=>s*i);if(n===0)return[];if(n!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}.`);return Gx(0,e,t)}function tk(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function Fy(e,t){const n=Aa(e,t);for(let s=0;s<n.length;s++)n[s]=1;return n}function Aa(e,t){if(t==null||t==="float32"||t==="complex64")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool")return new Uint8Array(e);throw new Error(`Unknown data type ${t}`)}function _y(e,t){const n=e.reduce((s,i)=>s*i,1);if(t==null||t==="float32")return ys(e,new Float32Array(n));if(t==="int32")return ys(e,new Int32Array(n));if(t==="bool")return ys(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function Yn(){return C().platform.now()}function Wy(e){e.forEach(t=>{k(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function Vx(e,t){return C().platform.fetch(e,t)}function $y(e,t="utf-8"){return t=t||"utf-8",C().platform.encode(e,t)}function zl(e,t="utf-8"){return t=t||"utf-8",C().platform.decode(e,t)}function ei(e,t,n){if(t===0)return 0;if(t===1)return e[0];let s=e[e.length-1];for(let i=0;i<e.length-1;++i)s+=n[i]*e[i];return s}function va(e,t,n){if(t===0)return[];if(t===1)return[e];const s=new Array(t);for(let i=0;i<s.length-1;++i)s[i]=Math.floor(e/n[i]),e-=s[i]*n[i];return s[s.length-1]=e,s}var nk=Object.freeze({__proto__:null,shuffle:Ry,clamp:Pl,nearestLargerEven:Oy,sum:$x,randUniform:XD,distSquared:JD,assert:k,assertShapesMatch:pt,assertNonNull:yo,flatten:qi,sizeFromShape:we,isScalarShape:ZD,arraysEqual:ot,isInt:Bt,tanh:QD,sizeToSquarishShape:pd,createShuffledIndices:ek,rightPad:bo,repeatedTry:Ey,inferFromImplicitShape:md,parseAxisParam:gt,squeezeShape:Ir,getTypedArrayFromDType:bn,getArrayFromDType:wo,checkConversionForErrors:Ux,isValidDtype:Bx,hasEncodingLoss:Dy,isTypedArray:wn,bytesPerElement:ky,bytesFromStringArray:Mx,isString:xr,isBoolean:Px,isNumber:fd,inferDtype:Ta,isFunction:Tr,nearestDivisor:gd,computeStrides:Ot,createScalarValue:zx,toTypedArray:Ar,toNestedArray:ys,makeOnesTypedArray:Fy,makeZerosTypedArray:Aa,makeZerosNestedTypedArray:_y,now:Yn,assertNonNegativeIntegerDimensions:Wy,fetch:Vx,encodeString:$y,decodeString:zl,locToIndex:ei,indexToLoc:va});class sk{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new rk)}profileKernel(e,t,n){let s;const i=()=>{s=n()},o=this.backendTimer.time(i);for(let c=0;c<s.length;c++){const h=s[c];h.data().then(d=>{ik(d,h.dtype,e)})}const a={kernelName:e,outputs:s,inputs:t,timeMs:o.then(c=>c.kernelMs),extraInfo:o.then(c=>c.getExtraProfileInfo!=null?c.getExtraProfileInfo():"")};return a}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:s,inputs:i,extraInfo:o}=e;n.forEach(a=>{Promise.all([a.data(),s,o]).then(c=>{this.logger.logKernelProfile(t,a,c[0],c[1],i,c[2])})})}}function ik(e,t,n){if(t!=="float32")return!1;for(let s=0;s<e.length;s++){const i=e[s];if(isNaN(i)||!isFinite(i))return console.warn(`Found ${i} in the result of '${n}'`),!0}return!1}class rk{logKernelProfile(e,t,n,s,i,o){const a=typeof s=="number"?bo(`${s}ms`,9):s.error,c=bo(e,25),h=t.rank,d=t.size,m=bo(t.shape.toString(),14);let y="";for(const b in i){const w=i[b];if(w!=null){const L=w.shape||t.shape,T=L.length;y+=`${b}: ${T}D ${T>0?L:""} `}}console.log(`%c${c} %c${a} %c${h}D ${m} %c${d} %c${y} %c${o}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function ok(e,t,n){const s={},i={};for(let h=0;h<t.length;h++)s[t[h].id]=!0;for(let h=0;h<e.length;h++){const d=e[h],m=d.inputs;for(const y in m){const b=m[y];let w=!1;for(let L=0;L<t.length;L++)if(s[b.id]){d.outputs.forEach(T=>s[T.id]=!0),w=!0,i[d.id]=!0;break}if(w)break}}const o={};o[n.id]=!0;const a={};for(let h=e.length-1;h>=0;h--){const d=e[h],m=d.inputs;for(let y=0;y<d.outputs.length;y++)if(o[d.outputs[y].id]){for(const b in m)o[m[b].id]=!0,a[d.id]=!0;break}}const c=[];for(let h=0;h<e.length;h++){const d=e[h];if(i[d.id]&&a[d.id]){const m={};for(const b in d.inputs){const w=d.inputs[b];s[w.id]&&(m[b]=w)}const y=Object.assign({},d);y.inputs=m,y.outputs=d.outputs,c.push(y)}}return c}function ak(e,t,n,s){for(let i=t.length-1;i>=0;i--){const o=t[i],a=[];if(o.outputs.forEach(h=>{const d=e[h.id];d!=null?a.push(d):a.push(null)}),o.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${o.kernelName}.`);const c=o.gradient(a);for(const h in o.inputs){if(!(h in c))throw new Error(`Cannot backprop through input ${h}. Available gradients found: ${Object.keys(c)}.`);const d=n(()=>c[h]());if(d.dtype!=="float32")throw new Error(`Error in gradient for op ${o.kernelName}. The gradient of input ${h} must have 'float32' dtype, but has '${d.dtype}'`);const m=o.inputs[h];if(!ot(d.shape,m.shape))throw new Error(`Error in gradient for op ${o.kernelName}. The gradient of input '${h}' has shape '${d.shape}', which does not match the shape of the input '${m.shape}'`);if(e[m.id]==null)e[m.id]=d;else{const y=e[m.id];e[m.id]=s(y,d),y.dispose()}}}}const Yx=20,Gl=3,Uy=7;function ck(e,t,n,s){const i=Ot(t),o=lk(e,t,n,i),a=t.length,c=yd(e,t,n,i,o),h=["Tensor"];return s&&(h.push(` dtype: ${n}`),h.push(` rank: ${a}`),h.push(` shape: [${t}]`),h.push(" values:")),h.push(c.map(d=>" "+d).join(`
`)),h.join(`
`)}function lk(e,t,n,s){const i=we(t),o=s[s.length-1],a=new Array(o).fill(0),c=t.length,h=n==="complex64"?Yl(e):e;if(c>1)for(let d=0;d<i/o;d++){const m=d*o;for(let y=0;y<o;y++)a[y]=Math.max(a[y],Vl(h[m+y],0,n).length)}return a}function Vl(e,t,n){let s;return Array.isArray(e)?s=`${parseFloat(e[0].toFixed(Uy))} + ${parseFloat(e[1].toFixed(Uy))}j`:xr(e)?s=`'${e}'`:n==="bool"?s=Hx(e):s=parseFloat(e.toFixed(Uy)).toString(),bo(s,t)}function Hx(e){return e===0?"false":"true"}function yd(e,t,n,s,i,o=!0){const a=n==="complex64"?2:1,c=t[0],h=t.length;if(h===0){if(n==="complex64"){const T=Yl(e);return[Vl(T[0],0,n)]}return n==="bool"?[Hx(e[0])]:[e[0].toString()]}if(h===1){if(c>Yx){const A=Gl*a;let N=Array.from(e.slice(0,A)),E=Array.from(e.slice((c-Gl)*a,c*a));return n==="complex64"&&(N=Yl(N),E=Yl(E)),["["+N.map((D,F)=>Vl(D,i[F],n)).join(", ")+", ..., "+E.map((D,F)=>Vl(D,i[c-Gl+F],n)).join(", ")+"]"]}const T=n==="complex64"?Yl(e):Array.from(e);return["["+T.map((A,N)=>Vl(A,i[N],n)).join(", ")+"]"]}const d=t.slice(1),m=s.slice(1),y=s[0]*a,b=[];if(c>Yx){for(let T=0;T<Gl;T++){const A=T*y,N=A+y;b.push(...yd(e.slice(A,N),d,n,m,i,!1))}b.push("...");for(let T=c-Gl;T<c;T++){const A=T*y,N=A+y;b.push(...yd(e.slice(A,N),d,n,m,i,T===c-1))}}else for(let T=0;T<c;T++){const A=T*y,N=A+y;b.push(...yd(e.slice(A,N),d,n,m,i,T===c-1))}const w=h===2?",":"";b[0]="["+b[0]+w;for(let T=1;T<b.length-1;T++)b[T]=" "+b[T]+w;let L=`,
`;for(let T=2;T<h;T++)L+=`
`;return b[b.length-1]=" "+b[b.length-1]+"]"+(o?"":L),b}function Yl(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class vr{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=we(e),n!=null){const s=n.length;k(s===this.size,()=>`Length of values '${s}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")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||wo(t,this.size),this.strides=Ot(e)}set(e,...t){t.length===0&&(t=[0]),k(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){e.length===0&&(e=[0]);let t=0;for(const s of e){if(s<0||s>=this.shape[t]){const i=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(i)}t++}let n=e[e.length-1];for(let s=0;s<e.length-1;++s)n+=this.strides[s]*e[s];return this.values[n]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];const t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Ii().makeTensor(this.values,this.shape,this.dtype)}}let Ii=null,Na=null,qx=null;function hk(e){Ii=e}function uk(e){Na=e}function dk(e){qx=e}class Q{constructor(e,t,n,s){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=we(e),this.strides=Ot(e),this.dataId=n,this.id=s,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return Na.buffer(this.shape,this.dtype,e)}bufferSync(){return Na.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return ys(this.shape,e)}arraySync(){return ys(this.shape,this.dataSync())}async data(){this.throwIfDisposed();const e=Ii().read(this.dataId);if(this.dtype==="string"){const t=await e;try{return t.map(n=>zl(n))}catch(n){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataSync(){this.throwIfDisposed();const e=Ii().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>zl(t))}catch(t){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 Ii().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){if(this.isDisposed)return;Ii().disposeTensor(this),this.isDisposedInternal=!0}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Na.print(this,e)}clone(){return this.throwIfDisposed(),Na.clone(this)}toString(e=!1){const t=this.dataSync();return ck(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Na.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Ii().makeVariable(this,e,t,n)}}Object.defineProperty(Q,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});class Hl extends Q{constructor(e,t,n,s){super(e.shape,e.dtype,e.dataId,s);this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!ot(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Ii().disposeTensor(this),this.dataId=e.dataId,Ii().incRef(this,null)}dispose(){Ii().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(Hl,Symbol.hasInstance,{value:e=>e instanceof Q&&e.assign!=null&&e.assign instanceof Function});(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(r.Rank||(r.Rank={}));var By;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(By||(By={}));var My;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(My||(My={}));var Py;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(Py||(Py={}));var zy;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(zy||(zy={}));const pk={float32:Py,int32:By,bool:My,complex64:zy};function Nn(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return pk[e][t]}function bd(e){return Nn(e,"int32")}function Mt(e,t){if(e.dtype===t.dtype)return[e,t];const n=Nn(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function jx(e,t){k(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function wd(e,t){return t.some(n=>n.id===e.id)}function ji(e){const t=[],n=new Set;return Kx(e,t,n),t}function Kx(e,t,n){if(e==null)return;if(e instanceof Q){t.push(e);return}if(!mk(e))return;const s=e;for(const i in s){const o=s[i];n.has(o)||(n.add(o),Kx(o,t,n))}}function mk(e){return Array.isArray(e)||typeof e=="object"}var fk=Object.freeze({__proto__:null,makeTypesMatch:Mt,assertTypesMatch:jx,isTensorInList:wd,getTensorsInContainer:ji});class Xx{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}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class ql{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Xx}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],s=await this.initializeBackend(n).success;if(s){await this.setBackend(n);return}}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(this.pendingBackendInit!=null)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(this.backendInstance==null){const{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry))if(e in this.registryFactory){const{asyncInit:t}=this.initializeBackend(e);if(t)return null}else return null;return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(console.warn(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(this.registryFactory[e]==null)throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,this.registry[e]==null){this.backendInstance=null;const{success:t,asyncInit:n}=this.initializeBackend(e),s=n?await t:t;if(!s)return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new sk(this.backendInstance),!0}setupRegisteredKernels(){const e=ud(this.backendName);e.forEach(t=>{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){const t=ud(e);t.forEach(n=>{n.disposeFunc!=null&&n.disposeFunc(this.registry[e])})}initializeBackend(e){const t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const n=t.factory();if(n&&!(n instanceof g)&&typeof n.then=="function"){const s=++this.pendingBackendInitId,i=n.then(o=>s<this.pendingBackendInitId?!1:(this.registry[e]=o,this.pendingBackendInit=null,!0)).catch(o=>(s<this.pendingBackendInitId||(this.pendingBackendInit=null,console.warn(`Initialization of backend ${e} failed`),console.warn(o.stack||o.message)),!1));return this.pendingBackendInit=i,{success:i,asyncInit:!0}}else return this.registry[e]=n,{success:!0,asyncInit:!1}}catch(n){return console.warn(`Initialization of backend ${e} failed`),console.warn(n.stack||n.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(Object.keys(this.registryFactory).length===0)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],{success:s,asyncInit:i}=this.initializeBackend(n);if(i||s)return{name:n,asyncInit:i}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const n=this.state.tensorInfo.get(t),s=n.backend,i=this.readSync(t);s.disposeData(t),n.backend=e,e.move(t,i,n.shape,n.dtype),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n=null;if(t==null){if(typeof e!="function")throw new Error("Please provide a function to tidy()");t=e}else{if(typeof e!="string"&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof t!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");n=e}let s;return this.scopedRun(()=>this.startScope(n),()=>this.endScope(s),()=>(s=t(),s instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),s))}scopedRun(e,t,n){e();try{const s=n();return t(),s}catch(s){throw t(),s}}nextTensorId(){return ql.nextTensorId++}nextVariableId(){return ql.nextVariableId++}clone(e){const t=this.makeTensorFromDataId(e.dataId,e.shape,e.dtype),n={x:e},s=o=>({x:()=>{const a="float32",c={x:o},h={dtype:a};return V.runKernelFunc(d=>d.cast(o,a),c,null,al,h)}}),i=[];return this.addTapeNode(this.state.activeScope.name,n,[t],s,i,{}),t}runKernel(e,t,n,s,i){const o=null,a=null;return this.runKernelFunc(o,t,a,e,n,s,i)}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const s=this.backend.numDataIds();let i=0;n.forEach(c=>{i+=c.dtype==="complex64"?3:1});const o=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],a=s-t-i-o;if(a>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${a} data ids) after running '${e}'`)}runKernelFunc(e,t,n,s,i,o,a){let c,h=[];const d=this.isTapeOn();s==null&&(s=this.state.activeScope!=null?this.state.activeScope.name:"");const m=this.state.numBytes,y=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let b;const w=vy(s,this.backendName);let L;if(w!=null)b=()=>{const A=this.backend.numDataIds();L=w.kernelFunc({inputs:t,attrs:i,backend:this.backend});const N=Array.isArray(L)?L:[L];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(s,A,N);const E=N.map(({dataId:D,shape:F,dtype:_})=>this.makeTensorFromDataId(D,F,_));if(d){let D=this.getTensorsForGradient(s,t,E);if(D==null){a==null&&(a=[]);const F=E.filter((_,B)=>a[B]);D=(o||[]).slice().concat(F)}h=this.saveTensorsForBackwardMode(D)}return E};else{const A=N=>{if(!d)return;h=N.map(E=>this.keep(this.clone(E)))};b=()=>{const N=this.backend.numDataIds();L=this.tidy(()=>e(this.backend,A));const E=Array.isArray(L)?L:[L];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(s,N,E),E}}let T;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?c=b():(T=this.profiler.profileKernel(s,t,()=>b()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(T),c=T.outputs)}),d&&this.addTapeNode(s,t,c,n,h,i),this.state.profiling&&this.state.activeProfile.kernels.push({name:s,bytesAdded:this.state.numBytes-m,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-y,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(t).map(A=>t[A]!=null?t[A].shape:null),outputShapes:c.map(A=>A.shape),kernelTimeMs:T.timeMs,extraInfo:T.extraInfo}),Array.isArray(L)?c:c[0]}saveTensorsForBackwardMode(e){const t=e.map(n=>this.keep(this.clone(n)));return t}getTensorsForGradient(e,t,n){const s=Ny(e);if(s!=null){const i=s.inputsToSave||[],o=s.outputsToSave||[];let a;s.saveAllInputs?(k(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),a=Object.keys(t).map(h=>t[h])):a=i.map(h=>t[h]);const c=n.filter((h,d)=>o[d]);return a.concat(c)}return null}makeTensor(e,t,n,s){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",s=s||this.backend;let i=e;n==="string"&&xr(e[0])&&(i=e.map(c=>$y(c)));const o=s.write(i,t,n),a=new Q(t,n,o,this.nextTensorId());if(this.incRef(a,s),n==="string"){const c=this.state.tensorInfo.get(o),h=Mx(i);this.state.numBytes+=h-c.bytes,c.bytes=h}return a}makeTensorFromDataId(e,t,n,s){n=n||"float32";const i=new Q(t,n,e,this.nextTensorId());return this.incRef(i,s),i}makeVariable(e,t=!0,n,s){n=n||this.nextVariableId().toString(),s!=null&&s!==e.dtype&&(e=e.cast(s));const i=new Hl(e,t,n,this.nextTensorId());if(this.state.registeredVariables[i.name]!=null)throw new Error(`Variable with name ${i.name} was already registered`);return this.state.registeredVariables[i.name]=i,this.incRef(i,this.backend),i}incRef(e,t){const n=this.state.tensorInfo.has(e.dataId)?this.state.tensorInfo.get(e.dataId).refCount:0;if(this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++,n===0){this.state.numDataBuffers++;let s=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(s=e.size*ky(e.dtype)),this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:s,refCount:0}),this.state.numBytes+=s}this.state.tensorInfo.get(e.dataId).refCount++,e instanceof Hl||this.track(e)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;this.state.numTensors--,e.dtype==="string"&&this.state.numStringTensors--;const t=this.state.tensorInfo.get(e.dataId),n=t.refCount;n<=1?(e.dtype!=="complex64"&&(this.state.numBytes-=t.bytes),this.state.numDataBuffers--,t.backend.disposeData(e.dataId),this.state.tensorInfo.delete(e.dataId)):this.state.tensorInfo.get(e.dataId).refCount--}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),this.state.registeredVariables[e.name]!=null&&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,e.reasons==null&&(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(s=>s.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const s of this.state.activeProfile.kernels)s.kernelTimeMs=await s.kernelTimeMs,s.extraInfo=await s.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,n,s,i,o){const a={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:i},c=Ny(e);c!=null&&(s=c.gradFunc),s!=null&&(a.gradient=h=>(h=h.map((d,m)=>{if(d==null){const y=n[m],b=Aa(y.size,y.dtype);return this.makeTensor(b,y.shape,y.dtype)}return d}),s(h.length>1?h:h[0],i,o))),this.state.activeTape.push(a)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(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=ji(e),n=new Set(t.map(i=>i.id));for(let i=0;i<this.state.activeScope.track.length;i++){const o=this.state.activeScope.track[i];!o.kept&&!n.has(o.id)&&o.dispose()}const s=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(i=>{!i.kept&&i.scopeId===s.id&&this.track(i)})}gradients(e,t,n,s=!1){if(k(t.length>0,()=>"gradients() received an empty list of xs."),n!=null&&n.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);const i=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));k(i instanceof Q,()=>"The result y returned by f() must be a tensor.");const o=ok(this.state.activeTape,t,i);if(!s&&o.length===0&&t.length>0)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 a={};a[i.id]=n==null?gk(i.shape):n,ak(a,o,h=>this.tidy(h),yk);const c=t.map(h=>a[h.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(h=>{for(const d of h.saved)d.dispose()}),this.state.activeTape=null),{value:i,grads:c}})}customGrad(e){return k(Tr(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{k(t.every(i=>i instanceof Q),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n;const s={};return t.forEach((i,o)=>{s[o]=i}),this.runKernelFunc((i,o)=>(n=e(...t,o),k(n.value instanceof Q,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),k(Tr(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),s,(i,o)=>{const a=n.gradFunc(i,o),c=Array.isArray(a)?a:[a];k(c.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(...)."),k(c.every(d=>d instanceof Q),()=>"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 h={};return c.forEach((d,m)=>{h[m]=()=>d}),h})}}readSync(e){const t=this.state.tensorInfo.get(e);return t.backend.readSync(e)}read(e){const t=this.state.tensorInfo.get(e);return t.backend.read(e)}async time(e){const t=Yn(),n=await this.backend.time(e);return n.wallMs=Yn()-t,n}track(e){return this.state.activeScope!=null&&(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 Xx;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}}ql.nextTensorId=0,ql.nextVariableId=0;function gk(e){const t=Fy(we(e),"float32");return V.makeTensor(t,e,"float32")}function Jx(){const e=ne();if(e._tfengine==null){const t=new S(e);e._tfengine=new ql(t)}return U(e._tfengine.ENV),hk(()=>e._tfengine),e._tfengine}const V=Jx();function yk(e,t){const n={a:e,b:t};return V.runKernelFunc((s,i)=>{const o=s.add(e,t);return i([e,t]),o},n,null,Te)}function bk(){return typeof navigator!="undefined"&&navigator!=null}function Zx(){if(bk()){const e=navigator.userAgent||navigator.vendor||window.opera;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(e)||/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(e.substr(0,4))}return!1}function Gy(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var wk=Object.freeze({__proto__:null,isMobile:Zx,isBrowser:Gy});const Ki=C();Ki.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.")}),Ki.registerFlag("IS_BROWSER",()=>Gy()),Ki.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined"),Ki.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)),Ki.registerFlag("PROD",()=>!1),Ki.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Ki.getBool("DEBUG")),Ki.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0),Ki.registerFlag("IS_TEST",()=>!1);function xi(e,t){let n=e;if(wn(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];const s=[];for(;Array.isArray(n)||wn(n)&&t!=="string";)s.push(n.length),n=n[0];return Array.isArray(e)&&C().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&Qx(e,s,[]),s}function Qx(e,t,n){if(n=n||[],!Array.isArray(e)&&!wn(e)){k(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}k(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),k(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);const s=t.slice(1);for(let i=0;i<e.length;++i)Qx(e[i],s,n.concat(i))}function eT(e,t,n,s){if(e==null)return;if(e!=="numeric"&&e!==t||e==="numeric"&&t==="string")throw new Error(`Argument '${n}' passed to '${s}' must be ${e} tensor, but got ${t} tensor`)}function W(e,t,n,s="numeric"){if(e instanceof Q)return eT(s,e.dtype,t,n),e;let i=Ta(e);if(i!=="string"&&["bool","int32","float32"].indexOf(s)>=0&&(i=s),eT(s,i,t,n),e==null||!wn(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){const h=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${h}'`)}const o=xi(e,i);!wn(e)&&!Array.isArray(e)&&(e=[e]);const a=!0,c=i!=="string"?Ar(e,i):qi(e,[],a);return V.makeTensor(c,o,i)}function jl(e,t,n,s="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);const i=e;return i.map((o,a)=>W(o,`${t}[${a}]`,n),s)}const tT="__op";function P(e){const t=Object.keys(e);if(t.length!==1)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 s=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n=n+tT;const i=(...o)=>{V.startScope(n);try{const a=s(...o);return a instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),V.endScope(a),a}catch(a){throw V.endScope(null),a}};return Object.defineProperty(i,"name",{value:n,configurable:!0}),i}function Lk(e,t){const n=W(e,"real","complex"),s=W(t,"imag","complex");pt(n.shape,s.shape,`real and imag shapes, ${n.shape} and ${s.shape}, must match in call to tf.complex().`);const i=a=>a.complex(n,s),o={real:n,imag:s};return V.runKernelFunc(i,o,null,Ug)}const Ti=P({complex_:Lk});function Nr(e,t,n,s){if(s==null&&(s=Ta(e)),s==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!wn(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string")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(t!=null){Wy(t);const i=we(t),o=we(n);k(i===o,()=>`Based on the provided shape, [${t}], the tensor should have ${i} values but has ${o}`);for(let a=0;a<n.length;++a){const c=n[a],h=a===n.length-1?c!==we(t.slice(a)):!0;k(n[a]===t[a]||!h,()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return!wn(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=s!=="string"?Ar(e,s):qi(e,[],!0),V.makeTensor(e,t,s)}function en(e,t,n){const s=xi(e,n);return Nr(e,t,s,n)}const Vy={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};const Ld=4;async function Yy(e,t){const n=[],s=[],i=Array.isArray(e)?e.map(a=>a.name):Object.keys(e);for(let a=0;a<i.length;++a){const c=i[a],h=Array.isArray(e)?e[a].tensor:e[c];if(h.dtype!=="float32"&&h.dtype!=="int32"&&h.dtype!=="bool"&&h.dtype!=="string"&&h.dtype!=="complex64")throw new Error(`Unsupported dtype in weight '${c}': ${h.dtype}`);const d={name:c,shape:h.shape,dtype:h.dtype};if(h.dtype==="string"){const m=new Promise(async y=>{const b=await h.bytes(),w=b.reduce((A,N)=>A+N.length,0)+Ld*b.length,L=new Uint8Array(w);let T=0;for(let A=0;A<b.length;A++){const N=b[A],E=new Uint8Array(new Uint32Array([N.length]).buffer);L.set(E,T),T+=Ld,L.set(N,T),T+=N.length}y(L)});s.push(m)}else s.push(h.data());t!=null&&(d.group=t),n.push(d)}const o=await Promise.all(s);return{data:Sk(o),specs:n}}function Sd(e,t){const n={};let s,i=0;for(const o of t){const a=o.name,c=o.dtype,h=o.shape,d=we(h);let m;if("quantization"in o){const y=o.quantization;if(y.dtype==="uint8"||y.dtype==="uint16"){if(!("min"in y&&"scale"in y))throw new Error(`Weight ${o.name} with quantization ${y.dtype} doesn't have corresponding metadata min and scale.`)}else if(y.dtype==="float16"){if(c!=="float32")throw new Error(`Weight ${o.name} is quantized with ${y.dtype} which only supports weights of type float32 not ${c}.`)}else throw new Error(`Weight ${o.name} has unknown quantization dtype ${y.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);const b=Vy[y.dtype],w=e.slice(i,i+d*b),L=y.dtype==="uint8"?new Uint8Array(w):new Uint16Array(w);if(c==="float32")if(y.dtype==="uint8"||y.dtype==="uint16"){m=new Float32Array(L.length);for(let T=0;T<L.length;T++){const A=L[T];m[T]=A*y.scale+y.min}}else if(y.dtype==="float16")s===void 0&&(s=Nk()),m=s(L);else throw new Error(`Unsupported quantization type ${y.dtype} for weight type float32.`);else if(c==="int32"){if(y.dtype!=="uint8"&&y.dtype!=="uint16")throw new Error(`Unsupported quantization type ${y.dtype} for weight type int32.`);m=new Int32Array(L.length);for(let T=0;T<L.length;T++){const A=L[T];m[T]=Math.round(A*y.scale+y.min)}}else throw new Error(`Unsupported dtype in weight '${a}': ${c}`);i+=d*b}else if(c==="string"){const y=we(o.shape);m=[];for(let b=0;b<y;b++){const w=new Uint32Array(e.slice(i,i+Ld))[0];i+=Ld;const L=new Uint8Array(e.slice(i,i+w));m.push(L),i+=w}}else{const y=Vy[c],b=e.slice(i,i+d*y);if(c==="float32")m=new Float32Array(b);else if(c==="int32")m=new Int32Array(b);else if(c==="bool")m=new Uint8Array(b);else if(c==="complex64"){m=new Float32Array(b);const w=new Float32Array(m.length/2),L=new Float32Array(m.length/2);for(let N=0;N<w.length;N++)w[N]=m[N*2],L[N]=m[N*2+1];const T=en(w,h,"float32"),A=en(L,h,"float32");n[a]=Ti(T,A)}else throw new Error(`Unsupported dtype in weight '${a}': ${c}`);i+=d*y}c!=="complex64"&&(n[a]=en(m,h,c))}return n}function Sk(e){if(e===null)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0;const n=[];e.forEach(o=>{if(t+=o.byteLength,n.push(o.byteLength===o.buffer.byteLength?o:new o.constructor(o)),!(o instanceof Float32Array||o instanceof Int32Array||o instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${o.constructor.name}`)});const s=new Uint8Array(t);let i=0;return n.forEach(o=>{s.set(new Uint8Array(o.buffer),i),i+=o.byteLength}),s.buffer}const Hy=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function nT(e){return Hy?Buffer.byteLength(e):new Blob([e]).size}function Ik(e){if(Hy)return Buffer.from(e).toString("base64");const t=new Uint8Array(e);let n="";for(let s=0,i=t.length;s<i;s++)n+=String.fromCharCode(t[s]);return btoa(n)}function xk(e){if(Hy){const s=Buffer.from(e,"base64");return s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength)}const t=atob(e),n=new Uint8Array(t.length);for(let s=0;s<t.length;++s)n.set([t.charCodeAt(s)],s);return n.buffer}function Id(e){if(e.length===1)return e[0];let t=0;e.forEach(i=>{t+=i.byteLength});const n=new Uint8Array(t);let s=0;return e.forEach(i=>{n.set(new Uint8Array(i),s),s+=i.byteLength}),n.buffer}function sT(e){const t="/";for(e=e.trim();e.endsWith(t);)e=e.slice(0,e.length-1);const n=e.split(t);return n[n.length-1]}function Kl(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:e.modelTopology==null?0:nT(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:nT(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function Tk(){const e=n=>{let s=n<<13,i=0;for(;(s&8388608)===0;)i-=8388608,s<<=1;return s&=~8388608,i+=947912704,s|i},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let n=1024;n<2048;n++)t[n]=939524096+(n-1024<<13);return t}function Ak(){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}function vk(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function Nk(){const e=Tk(),t=Ak(),n=vk();return s=>{const i=new ArrayBuffer(4*s.length),o=new Uint32Array(i);for(let a=0;a<s.length;a++){const c=s[a],h=e[n[c>>10]+(c&1023)]+t[c>>10];o[a]=h}return new Float32Array(i)}}class Xt{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Xt.instance==null&&(Xt.instance=new Xt),Xt.instance}static registerSaveRouter(e){Xt.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Xt.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Xt.getHandlers(e,"save")}static getLoadHandlers(e,t){return Xt.getHandlers(e,"load",t)}static getHandlers(e,t,n){const s=[],i=t==="load"?Xt.getInstance().loadRouters:Xt.getInstance().saveRouters;return i.forEach(o=>{const a=o(e,n);a!==null&&s.push(a)}),s}}const Ck=e=>Xt.registerSaveRouter(e),Rk=e=>Xt.registerLoadRouter(e),qy=e=>Xt.getSaveHandlers(e),jy=(e,t)=>Xt.getLoadHandlers(e,t);const xd="tensorflowjs",Ky=1,Lo="models_store",Cr="model_info_store";async function _Z(){const e=Xy();return new Promise((t,n)=>{const s=e.deleteDatabase(xd);s.onsuccess=()=>t(),s.onerror=i=>n(i)})}function Xy(){if(!C().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const e=typeof window=="undefined"?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(t==null)throw new Error("The current browser does not appear to support IndexedDB.");return t}function Jy(e){const t=e.result;t.createObjectStore(Lo,{keyPath:"modelPath"}),t.createObjectStore(Cr,{keyPath:"modelPath"})}class So{constructor(e){if(this.indexedDB=Xy(),e==null||!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((n,s)=>{const i=this.indexedDB.open(xd,Ky);i.onupgradeneeded=()=>Jy(i),i.onsuccess=()=>{const o=i.result;if(t==null){const a=o.transaction(Lo,"readonly"),c=a.objectStore(Lo),h=c.get(this.modelPath);h.onsuccess=()=>{if(h.result==null)return o.close(),s(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));n(h.result.modelArtifacts)},h.onerror=d=>(o.close(),s(h.error)),a.oncomplete=()=>o.close()}else{const a=Kl(t),c=o.transaction(Cr,"readwrite");let h=c.objectStore(Cr);const d=h.put({modelPath:this.modelPath,modelArtifactsInfo:a});let m;d.onsuccess=()=>{m=o.transaction(Lo,"readwrite");const y=m.objectStore(Lo),b=y.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:a});b.onsuccess=()=>n({modelArtifactsInfo:a}),b.onerror=w=>{h=c.objectStore(Cr);const L=h.delete(this.modelPath);L.onsuccess=()=>(o.close(),s(b.error)),L.onerror=T=>(o.close(),s(b.error))}},d.onerror=y=>(o.close(),s(d.error)),c.oncomplete=()=>{m==null?o.close():m.oncomplete=()=>o.close()}}},i.onerror=o=>s(i.error)})}}So.URL_SCHEME="indexeddb://";const iT=e=>C().getBool("IS_BROWSER")&&(!Array.isArray(e)&&e.startsWith(So.URL_SCHEME))?Ok(e.slice(So.URL_SCHEME.length)):null;Xt.registerSaveRouter(iT),Xt.registerLoadRouter(iT);function Ok(e){return new So(e)}function Ek(e){return e.startsWith(So.URL_SCHEME)?e.slice(So.URL_SCHEME.length):e}class Dk{constructor(){this.indexedDB=Xy()}async listModels(){return new Promise((e,t)=>{const n=this.indexedDB.open(xd,Ky);n.onupgradeneeded=()=>Jy(n),n.onsuccess=()=>{const s=n.result,i=s.transaction(Cr,"readonly"),o=i.objectStore(Cr),a=o.getAll();a.onsuccess=()=>{const c={};for(const h of a.result)c[h.modelPath]=h.modelArtifactsInfo;e(c)},a.onerror=c=>(s.close(),t(a.error)),i.oncomplete=()=>s.close()},n.onerror=s=>t(n.error)})}async removeModel(e){return e=Ek(e),new Promise((t,n)=>{const s=this.indexedDB.open(xd,Ky);s.onupgradeneeded=()=>Jy(s),s.onsuccess=()=>{const i=s.result,o=i.transaction(Cr,"readwrite"),a=o.objectStore(Cr),c=a.get(e);let h;c.onsuccess=()=>{if(c.result==null)return i.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const d=a.delete(e),m=()=>{h=i.transaction(Lo,"readwrite");const y=h.objectStore(Lo),b=y.delete(e);b.onsuccess=()=>t(c.result.modelArtifactsInfo),b.onerror=w=>n(c.error)};d.onsuccess=m,d.onerror=y=>(m(),i.close(),n(c.error))}},c.onerror=d=>(i.close(),n(c.error)),o.oncomplete=()=>{h==null?i.close():h.oncomplete=()=>i.close()}},s.onerror=i=>n(s.error)})}}const Ai="/",Io="tensorflowjs_models",rT="info",kk="model_topology",Fk="weight_specs",_k="weight_data",Wk="model_metadata";function WZ(){if(!C().getBool("IS_BROWSER")||typeof window=="undefined"||typeof window.localStorage=="undefined")throw new Error("purgeLocalStorageModels() cannot proceed because local storage is unavailable in the current environment.");const e=window.localStorage,t=[];for(let n=0;n<e.length;++n){const s=e.key(n),i=Io+Ai;if(s.startsWith(i)&&s.length>i.length){e.removeItem(s);const o=aT(s);t.indexOf(o)===-1&&t.push(o)}}return t}function oT(e){return{info:[Io,e,rT].join(Ai),topology:[Io,e,kk].join(Ai),weightSpecs:[Io,e,Fk].join(Ai),weightData:[Io,e,_k].join(Ai),modelMetadata:[Io,e,Wk].join(Ai)}}function aT(e){const t=e.split(Ai);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Ai)}function $k(e){return e.startsWith(xo.URL_SCHEME)?e.slice(xo.URL_SCHEME.length):e}class xo{constructor(e){if(!C().getBool("IS_BROWSER")||typeof window=="undefined"||typeof window.localStorage=="undefined")throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,e==null||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=oT(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),s=Kl(e);try{return this.LS.setItem(this.keys.info,JSON.stringify(s)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,Ik(e.weightData)),this.LS.setItem(this.keys.modelMetadata,JSON.stringify({format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,userDefinedMetadata:e.userDefinedMetadata})),{modelArtifactsInfo:s}}catch(i){throw this.LS.removeItem(this.keys.info),this.LS.removeItem(this.keys.topology),this.LS.removeItem(this.keys.weightSpecs),this.LS.removeItem(this.keys.weightData),this.LS.removeItem(this.keys.modelMetadata),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${s.modelTopologyBytes}, weightSpecsBytes=${s.weightSpecsBytes}, weightDataBytes=${s.weightDataBytes}.`)}}}async load(){const e=JSON.parse(this.LS.getItem(this.keys.info));if(e==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(e.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");const t={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(n==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=n;const s=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(s==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=s;const i=this.LS.getItem(this.keys.modelMetadata);if(i!=null){const a=JSON.parse(i);t.format=a.format,t.generatedBy=a.generatedBy,t.convertedBy=a.convertedBy,t.userDefinedMetadata=a.userDefinedMetadata}const o=this.LS.getItem(this.keys.weightData);if(o==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=xk(o),t}}xo.URL_SCHEME="localstorage://";const cT=e=>C().getBool("IS_BROWSER")&&(!Array.isArray(e)&&e.startsWith(xo.URL_SCHEME))?Uk(e.slice(xo.URL_SCHEME.length)):null;Xt.registerSaveRouter(cT),Xt.registerLoadRouter(cT);function Uk(e){return new xo(e)}class Bk{constructor(){k(C().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),k(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){const e={},t=Io+Ai,n=Ai+rT;for(let s=0;s<this.LS.length;++s){const i=this.LS.key(s);if(i.startsWith(t)&&i.endsWith(n)){const o=aT(i);e[o]=JSON.parse(this.LS.getItem(i))}}return e}async removeModel(e){e=$k(e);const t=oT(e);if(this.LS.getItem(t.info)==null)throw new Error(`Cannot find model at path '${e}'`);const n=JSON.parse(this.LS.getItem(t.info));return this.LS.removeItem(t.info),this.LS.removeItem(t.topology),this.LS.removeItem(t.weightSpecs),this.LS.removeItem(t.weightData),n}}const Ca="://";class bs{constructor(){this.managers={}}static getInstance(){return bs.instance==null&&(bs.instance=new bs),bs.instance}static registerManager(e,t){k(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(Ca)&&(e=e.slice(0,e.indexOf(Ca))),k(e.length>0,()=>"scheme must not be an empty string.");const n=bs.getInstance();k(n.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),n.managers[e]=t}static getManager(e){const t=this.getInstance().managers[e];if(t==null)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(this.getInstance().managers)}}function Td(e){if(e.indexOf(Ca)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${bs.getSchemes().join(",")}`);return{scheme:e.split(Ca)[0],path:e.split(Ca)[1]}}async function lT(e,t,n=!1){k(e!==t,()=>`Old path and new path are the same: '${e}'`);const s=Xt.getLoadHandlers(e);k(s.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),k(s.length<2,()=>`Copying failed because more than one (${s.length}) load handlers for source URL ${e}.`);const i=s[0],o=Xt.getSaveHandlers(t);k(o.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),k(o.length<2,()=>`Copying failed because more than one (${s.length}) save handlers for destination URL ${t}.`);const a=o[0],c=Td(e).scheme,h=Td(e).path,d=c===Td(e).scheme,m=await i.load();n&&d&&await bs.getManager(c).removeModel(h);const y=await a.save(m);return n&&!d&&await bs.getManager(c).removeModel(h),y.modelArtifactsInfo}async function Mk(){const e=bs.getSchemes(),t={};for(const n of e){const s=await bs.getManager(n).listModels();for(const i in s){const o=n+Ca+i;t[o]=s[i]}}return t}async function Pk(e){const t=Td(e),n=bs.getManager(t.scheme);return n.removeModel(t.path)}async function zk(e,t){const n=!1;return lT(e,t,n)}async function Gk(e,t){const n=!0;return lT(e,t,n)}class Vk{fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return this.textEncoder==null&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}}if(C().get("IS_BROWSER")){C().setPlatform("browser",new Vk);try{bs.registerManager(xo.URL_SCHEME,new Bk)}catch(e){}try{bs.registerManager(So.URL_SCHEME,new Dk)}catch(e){}}const Yk={importFetch:()=>RC()};let Ra;function $Z(){Ra=null}function UZ(e){Ra=e}function BZ(){return Ra}class Hk{constructor(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return C().global.fetch!=null?C().global.fetch(e,t):(Ra==null&&(Ra=Yk.importFetch()),Ra(e,t))}now(){const e=process.hrtime();return e[0]*1e3+e[1]/1e6}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return e.length===0?"":new this.util.TextDecoder(t).decode(e)}}C().get("IS_NODE")&&C().setPlatform("node",new Hk);function Ze(e,t="float32",n){return t=t||"float32",Wy(e),new vr(e,t,n)}function qk(e,t){const n=W(e,"x","cast");if(!Bx(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&n.dtype!=="string"||t!=="string"&&n.dtype==="string")throw new Error("Only strings can be casted to strings");const s={x:n},i={dtype:t};return V.runKernelFunc(o=>o.cast(n,t),s,null,al,i)}const ve=P({cast_:qk});function jk(e){const t=W(e,"x","clone",null),n=()=>V.makeTensorFromDataId(t.dataId,t.shape,t.dtype),s={x:t};return V.runKernelFunc(n,s,null,yl)}const Rr=P({clone_:jk});function hT(e,t=!1){console.log(e.toString(t))}Jx();const Kk={buffer:Ze,cast:ve,clone:Rr,print:hT};uk(Kk);const Xk="model",Jk=".json",Zk=".weights.bin";function uT(e){return new Promise(t=>setTimeout(t)).then(e)}class Oa{constructor(e){if(!C().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Oa.URL_SCHEME)&&(e=e.slice(Oa.URL_SCHEME.length)),(e==null||e.length===0)&&(e=Xk),this.modelTopologyFileName=e+Jk,this.weightDataFileName=e+Zk}async save(e){if(typeof document=="undefined")throw new Error("Browser downloads are not supported in this environment since `document` is not present");const t=window.URL.createObjectURL(new Blob([e.weightData],{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 n=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],s={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:n},i=window.URL.createObjectURL(new Blob([JSON.stringify(s)],{type:"application/json"})),o=this.jsonAnchor==null?document.createElement("a"):this.jsonAnchor;if(o.download=this.modelTopologyFileName,o.href=i,await uT(()=>o.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){const a=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;a.download=this.weightDataFileName,a.href=t,await uT(()=>a.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Kl(e)}}}}Oa.URL_SCHEME="downloads://";class Qk{constructor(e){if(e==null||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.files=e}async load(){const e=this.files[0],t=this.files.slice(1);return new Promise((n,s)=>{const i=new FileReader;i.onload=o=>{const a=JSON.parse(o.target.result),c=a.modelTopology;if(c==null){s(new Error(`modelTopology field is missing from file ${e.name}`));return}t.length===0&&n({modelTopology:c});const h=a.weightsManifest;if(h==null){s(new Error(`weightManifest field is missing from file ${e.name}`));return}let d;try{d=this.checkManifestAndWeightFiles(h,t)}catch(w){s(w);return}const m=[],y=[],b=[];h.forEach(w=>{w.paths.forEach(L=>{y.push(L),b.push(null)}),m.push(...w.weights)}),h.forEach(w=>{w.paths.forEach(L=>{const T=new FileReader;T.onload=A=>{const N=A.target.result,E=y.indexOf(L);b[E]=N,b.indexOf(null)===-1&&n({modelTopology:c,weightSpecs:m,weightData:Id(b),format:a.format,generatedBy:a.generatedBy,convertedBy:a.convertedBy,userDefinedMetadata:a.userDefinedMetadata})},T.onerror=A=>s(`Failed to weights data from file of path '${L}'.`),T.readAsArrayBuffer(d[L])})})},i.onerror=o=>s(`Failed to read model topology and weights manifest JSON from file '${e.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),i.readAsText(e)})}checkManifestAndWeightFiles(e,t){const n=[],s=t.map(o=>sT(o.name)),i={};for(const o of e)o.paths.forEach(a=>{const c=sT(a);if(n.indexOf(c)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${c}'`);if(n.push(c),s.indexOf(c)===-1)throw new Error(`Weight file with basename '${c}' is not provided.`);i[a]=t[s.indexOf(c)]});if(n.length!==t.length)throw new Error(`Mismatch in the number of files in weights manifest (${n.length}) and the number of weight files provided (${t.length}).`);return i}}const eF=e=>C().getBool("IS_BROWSER")&&(!Array.isArray(e)&&e.startsWith(Oa.URL_SCHEME))?tF(e.slice(Oa.URL_SCHEME.length)):null;Xt.registerSaveRouter(eF);function tF(e="model"){return new Oa(e)}function nF(e){return new Qk(e)}function dT(e,t,n,s){a(e),n=n==null?0:n,s=s==null?1:s,c(n,s);let i=0;const o=h=>(h.then(d=>{const m=n+ ++i/e.length*(s-n);return t(m),d}),h);function a(h){k(h!=null&&Array.isArray(h)&&h.length>0,()=>"promises must be a none empty array")}function c(h,d){k(h>=0&&h<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${h}`),k(d>=0&&d<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${d}`),k(d>=h,()=>`startFraction must be no more than endFraction, but got startFraction ${h} and endFraction ${d}`)}return Promise.all(e.map(o))}async function pT(e,t){t==null&&(t={});const n=t.fetchFunc==null?C().platform.fetch:t.fetchFunc,s=e.map(y=>n(y,t.requestInit,{isBinary:!0})),i=0,o=.5,a=t.onProgress==null?await Promise.all(s):await dT(s,t.onProgress,i,o),c=a.map(y=>y.arrayBuffer()),h=.5,d=1,m=t.onProgress==null?await Promise.all(c):await dT(c,t.onProgress,h,d);return m}async function mT(e,t="",n,s){const i=a=>pT(a,{requestInit:s}),o=fT(i);return o(e,t,n)}function fT(e){return async(t,n="",s)=>{const i=t.map(()=>!1),o={},a=s!=null?s.map(()=>!1):[],c=[];if(t.forEach((w,L)=>{let T=0;w.weights.forEach(A=>{const N="quantization"in A?A.quantization.dtype:A.dtype,E=Vy[N]*we(A.shape),D=()=>{i[L]=!0,o[L]==null&&(o[L]=[]),o[L].push({manifestEntry:A,groupOffset:T,sizeBytes:E})};s!=null?s.forEach((F,_)=>{F===A.name&&(D(),a[_]=!0)}):D(),c.push(A.name),T+=E})}),!a.every(w=>w)){const w=s.filter((L,T)=>!a[T]);throw new Error(`Could not find weights in manifest with names: ${w.join(", ")}.
Manifest JSON has weights with names: ${c.join(", ")}.`)}const h=i.reduce((w,L,T)=>(L&&w.push(T),w),[]),d=[];h.forEach(w=>{t[w].paths.forEach(L=>{const T=n+(n.endsWith("/")?"":"/")+L;d.push(T)})});const m=await e(d),y={};let b=0;return h.forEach(w=>{const L=t[w].paths.length;let T=0;for(let F=0;F<L;F++)T+=m[b+F].byteLength;const A=new ArrayBuffer(T),N=new Uint8Array(A);let E=0;for(let F=0;F<L;F++){const _=new Uint8Array(m[b+F]);N.set(_,E),E+=_.byteLength}const D=o[w];D.forEach(F=>{const _=A.slice(F.groupOffset,F.groupOffset+F.sizeBytes),B=Sd(_,[F.manifestEntry]);for(const $ in B)y[$]=B[$]}),b+=L}),y}}const sF="application/octet-stream",iF="application/json";class Zy{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(k(typeof t.fetchFunc=="function",()=>"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=C().platform.fetch,k(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&k(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}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=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],s={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,userDefinedMetadata:e.userDefinedMetadata,weightsManifest:n};t.body.append("model.json",new Blob([JSON.stringify(s)],{type:iF}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:sF}),"model.weights.bin");const i=await this.fetch(this.path,t);if(i.ok)return{modelArtifactsInfo:Kl(e),responses:[i]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${i.status}.`)}async load(){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(b){let w=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?w+=" 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.":w+=" Please make sure the server is serving valid JSON for this request.",new Error(w)}const n=t.modelTopology,s=t.weightsManifest,i=t.generatedBy,o=t.convertedBy,a=t.format,c=t.userDefinedMetadata;if(n==null&&s==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);let h,d;if(s!=null){const b=await this.loadWeights(s);[h,d]=b}const m={modelTopology:n,weightSpecs:h,weightData:d,userDefinedMetadata:c,generatedBy:i,convertedBy:o,format:a},y=t.modelInitializer;return y&&(m.modelInitializer=y),m}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,s]=rF(t),i=this.weightPathPrefix||n,o=[];for(const d of e)o.push(...d.weights);const a=[],c=[];for(const d of e)for(const m of d.paths)this.weightUrlConverter!=null?c.push(this.weightUrlConverter(m)):a.push(i+m+s);this.weightUrlConverter&&a.push(...await Promise.all(c));const h=await pT(a,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[o,Id(h)]}}Zy.URL_SCHEME_REGEX=/^https?:\/\//;function rF(e){const t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),s=e.substring(0,t),i=n>t?e.substring(n):"";return[s+"/",i]}function Qy(e){return e.match(Zy.URL_SCHEME_REGEX)!=null}const gT=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(s=>Qy(s)):n=Qy(e),n)return eb(e,t)}return null};Xt.registerSaveRouter(gT),Xt.registerLoadRouter(gT);function eb(e,t){return new Zy(e,t)}function Ad(e,t){return eb(e,t)}class tb{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}}class oF{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}}function aF(e,t,n,s){if(arguments.length===1){const i=e.modelTopology!=null||e.weightSpecs!=null;return i?new tb(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 tb({modelTopology:e}))}else 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 tb({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:s})}function cF(e){return new oF(e)}var lF=Object.freeze({__proto__:null,browserFiles:nF,browserHTTPRequest:Ad,concatenateArrayBuffers:Id,decodeWeights:Sd,encodeWeights:Yy,fromMemory:aF,getLoadHandlers:jy,getModelArtifactsInfoForJSON:Kl,getSaveHandlers:qy,http:eb,isHTTPScheme:Qy,loadWeights:mT,registerLoadRouter:Rk,registerSaveRouter:Ck,weightsLoaderFactory:fT,withSaveHandler:cF,copyModel:zk,listModels:Mk,moveModel:Gk,removeModel:Pk});function hF(e,t){const n=W(e,"x","reshape",null),s={x:n},i={shape:t},o=(a,c)=>(t=md(t,n.size),k(n.size===we(t),()=>"new shape and old shape must have the same number of elements."),c([n]),a.reshape(n,t));return V.runKernelFunc(o,s,null,Nl,i)}const K=P({reshape_:hF});function uF(e,t,n=!1,s=!1){let i=W(e,"a","matMul"),o=W(t,"b","matMul");[i,o]=Mt(i,o),k(i.rank>=2&&o.rank>=2&&i.rank===o.rank,()=>`Error in matMul: inputs must have the same rank of at least 2, got ranks ${i.rank} and ${o.rank}.`);const a=n?i.shape[i.rank-2]:i.shape[i.rank-1],c=s?o.shape[o.rank-1]:o.shape[o.rank-2],h=n?i.shape[i.rank-1]:i.shape[i.rank-2],d=s?o.shape[o.rank-2]:o.shape[o.rank-1],m=i.shape.slice(0,-2),y=o.shape.slice(0,-2),b=we(m),w=we(y);k(ot(m,y),()=>`Error in matMul: outer dimensions (${m}) and (${y}) of Tensors with shapes ${i.shape} and ${o.shape} must match.`),k(a===c,()=>`Error in matMul: inner shapes (${a}) and (${c}) of Tensors with shapes ${i.shape} and ${o.shape} and transposeA=${n} and transposeB=${s} must match.`);const L=i.shape.slice(0,-2).concat([h,d]),T=n?K(i,[b,a,h]):K(i,[b,h,a]),A=s?K(o,[w,d,c]):K(o,[w,c,d]),N=(_,B)=>(B([T,A]),_.batchMatMul(T,A,n,s)),E={a:T,b:A},D={transposeA:n,transposeB:s},F=V.runKernelFunc(N,E,null,_g,D);return K(F,L)}const at=P({matMul_:uF});function dF(e,t,n=1,s=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const i=W(e,"indices","oneHot","int32"),o=[...i.shape,t],a=(d,m)=>(m([i]),K(d.oneHot(K(i,[i.size]),t,n,s),o)),c={indices:i},h={depth:t,onValue:n,offValue:s};return V.runKernelFunc(a,c,null,oy,h)}const To=P({oneHot_:dF});function pF(e,t){const n=W(e,"x","transpose");if(t==null&&(t=n.shape.map((o,a)=>a).reverse()),k(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(o=>{k(o>=0&&o<n.rank,()=>`All entries in 'perm' must be between 0 and ${n.rank-1} but got ${t}`)}),n.rank<=1)return n.clone();const s={x:n},i={perm:t};return V.runKernelFunc(o=>o.transpose(n,t),s,null,Ul,i)}const Me=P({transpose_:pF});function mF(e,t,n){const s=W(e,"labels","confusionMatrix"),i=W(t,"predictions","confusionMatrix");k(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),k(s.rank===1,()=>`Expected the rank of labels to be 1, but got ${s.rank}`),k(i.rank===1,()=>`Expected the rank of predictions to be 1, but got ${i.rank}`),k(s.shape[0]===i.shape[0],()=>`Mismatch in the number of examples: ${s.shape[0]} vs. ${i.shape[0]}. Labels and predictions should have the same number of elements.`),k(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);const o=To(ve(s,"int32"),n),a=To(ve(i,"int32"),n),c=Me(o);return ve(at(c,a),"int32")}const fF=P({confusionMatrix_:mF});var gF=Object.freeze({__proto__:null,confusionMatrix:fF});function yT(e,t,n){if(yo(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");const s=xi(e,n);if(s.length!==3&&s.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Nr(e,t,s,n)}let Ea;function yF(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(e==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,s=!1,i=!1,o=!1,a=!1;if(e.data instanceof Uint8Array)n=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)s=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)i=!0;else if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)o=!0;else if(e.getContext!=null)a=!0;else 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}`);if(i){const w=2;if(i&&e.readyState<w)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.")}const c=vy(ld,V.backendName);if(c!=null){const w={pixels:e},L={numChannels:t};return V.runKernel(ld,w,L)}const[h,d]=i?[e.videoWidth,e.videoHeight]:[e.width,e.height];let m;a?m=e.getContext("2d").getImageData(0,0,h,d).data:s||n?m=e.data:(o||i)&&(Ea==null&&(Ea=document.createElement("canvas").getContext("2d")),Ea.canvas.width=h,Ea.canvas.height=d,Ea.drawImage(e,0,0,h,d),m=Ea.getImageData(0,0,h,d).data);let y;if(t===4)y=new Int32Array(m);else{const w=h*d;y=new Int32Array(w*t);for(let L=0;L<w;L++)for(let T=0;T<t;++T)y[L*t+T]=m[L*4+T]}const b=[d,h,t];return yT(y,b,"int32")}async function bF(e,t){let n=W(e,"img","toPixels");if(!(e instanceof Q)){const d=n;n=ve(d,"int32"),d.dispose()}if(n.rank!==2&&n.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${n.rank}.`);const[s,i]=n.shape.slice(0,2),o=n.rank===2?1:n.shape[2];if(o>4||o===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${o}`);if(n.dtype!=="float32"&&n.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`);const a=await n.data(),c=n.dtype==="float32"?255:1,h=new Uint8ClampedArray(i*s*4);for(let d=0;d<s*i;++d){const m=[0,0,0,255];for(let b=0;b<o;b++){const w=a[d*o+b];if(n.dtype==="float32"){if(w<0||w>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${w}.`)}else if(n.dtype==="int32"&&(w<0||w>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${w}.`);o===1?(m[0]=w*c,m[1]=w*c,m[2]=w*c):m[b]=w*c}const y=d*4;h[y+0]=Math.round(m[0]),h[y+1]=Math.round(m[1]),h[y+2]=Math.round(m[2]),h[y+3]=Math.round(m[3])}if(t!=null){t.width=i,t.height=s;const d=t.getContext("2d"),m=new ImageData(h,i,s);d.putImageData(m,0,0)}return n!==e&&n.dispose(),h}const bT=P({fromPixels_:yF});var wF=Object.freeze({__proto__:null,toPixels:bF,fromPixels:bT});function vd(e,t){if(e.rank<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${e.rank}.`);if(t.rank<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);if(t.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[t.rank-1]>e.rank)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[t.rank-1]} vs. ${e.rank}`);if(e.size===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);const n=t.shape,s=n[n.length-1];let i=1;for(let d=0;d<n.length-1;++d)i*=n[d];const o=e.shape,a=n.slice();a.pop();let c=1;for(let d=s;d<e.rank;++d)c*=o[d],a.push(o[d]);const h=[...Ot(e.shape).map(d=>d/c),1].slice(0,s);return[a,i,c,h]}var LF=Object.freeze({__proto__:null,prepareAndValidate:vd});function nb(e,t,n){const s=t.rank>1?t.shape[t.rank-1]:1,i=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: ${s}, and batchDim: ${i}.`;if(n.rank<i)throw new Error(o+` update.rank < ${i}. `);if(e.length<s+(n.rank-i))throw new Error(o+` Output shape length < ${s+(n.rank-i)}`);if(n.rank!==i+e.length-s)throw new Error(o+` update.rank != ${i+e.length-s}`);for(let a=0;a<i;++a)if(n.shape[a]!==t.shape[a])throw new Error(o+` updates.shape[${a}] (${n.shape[a]}) != indices.shape[${a}] (${t.shape[a]}).`);for(let a=0;a<n.rank-i;++a)if(n.shape[a+i]!==e[a+s])throw new Error(o+` updates.shape[${a+i}] (${n.shape[a+i]}) != shape[${a+i}] (${e[a+i]})`)}function sb(e,t,n){if(t.rank<1)throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);if(e.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${e.rank}.`);if(t.dtype!=="int32")throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${t.dtype}`);if(n.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${n}`);if(n.length===0){if(t.size===0)throw new Error(`Indices specified for empty output. indices shape: ${t.shape}`);if(e.size===0)throw new Error(`Updates specified for empty output. updates shape: ${e.shape}`)}nb(n,t,e)}function Da(e,t,n){const s=t.shape.length,i=s>1?t.shape[s-1]:1,o=n.length;let a=1;for(let y=i;y<o;++y)a*=n[y];const c=i<1?1:i,h=we(t.shape)/c,d=[...Ot(n.slice(0,i)),1],m=we(n);return{sliceRank:i,numUpdates:h,sliceSize:a,strides:d,outputSize:m}}var SF=Object.freeze({__proto__:null,validateUpdateShape:nb,validateInput:sb,calculateShapes:Da});function ib(e,t,n){const s=e.shape.length;k(s===t.length,()=>`Error in slice${s}D: Length of begin ${t} must match the rank of the array (${s}).`),k(s===n.length,()=>`Error in slice${s}D: Length of size ${n} must match the rank of the array (${s}).`);for(let i=0;i<s;++i)k(t[i]+n[i]<=e.shape[i],()=>`Error in slice${s}D: begin[${i}] + size[${i}] (${t[i]+n[i]}) would overflow input.shape[${i}] (${e.shape[i]})`)}function Nd(e){const t=[];let n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function Cd(e,t,n){const s=[];for(let i=0;i<e.length;i++)s[i]=Math.ceil((t[i]-e[i])/n[i]);return s}function wT(e,t,n,s){const i=[...e];for(let o=i.length;o<s.length;o++)i.push(1);for(let o=0;o<n;o++)o===0?i[t]=1:(i.splice(t,0,1),i.pop());return i}function LT(e,t,n){return n<=e?n:n-(t-1)}function ST(e,t){const n=[];for(let s=0;s<e;s++)n.push(t+s);return n}function IT(e,t,n,s,i,o,a,c,h){const d=e.length;let m=new Array(d),y=new Array(d),b=new Array(d);if(t.length&&n>0){const w=t[0],L=n+1;m=xT(a,w,L,s,e),y=TT(c,w,L,i,e),b=wT(o,w,L,e)}else for(let w=0;w<d;w++)m[w]=vT(a,s,o,e,w,h),y[w]=NT(c,i,o,e,w,h),b[w]=AT(o,w,h);return{begin:m,end:y,strides:b}}function xT(e,t,n,s,i){const o=[...i],a=ST(n,t);for(let c=0;c<o.length;c++)if(a.indexOf(c)>-1)o[c]=0;else{const h=LT(t,n,c);let d=s[h];e&1<<h&&(d=0),o[c]=d}return o}function TT(e,t,n,s,i){const o=[...i],a=ST(n,t);for(let c=0;c<o.length;c++)if(a.indexOf(c)>-1)o[c]=Number.MAX_SAFE_INTEGER;else{const h=LT(t,n,c);let d=s[h];e&1<<h&&(d=Number.MAX_SAFE_INTEGER),o[c]=d}for(let c=0;c<o.length;c++){const h=i[c];o[c]<0&&(o[c]+=h),o[c]=Pl(0,o[c],i[c])}return o}function AT(e,t,n){let s=e[t];return(n&1<<t||s==null)&&(s=1),s}function vT(e,t,n,s,i,o){let a=t[i];const c=n[i]||1;(e&1<<i||o&1<<i||a==null)&&(c>0?a=Number.MIN_SAFE_INTEGER:a=Number.MAX_SAFE_INTEGER);const h=s[i];return a<0&&(a+=h),a=Pl(0,a,h-1),a}function NT(e,t,n,s,i,o){let a=t[i];const c=n[i]||1;(e&1<<i||o&1<<i||a==null)&&(c>0?a=Number.MAX_SAFE_INTEGER:a=Number.MIN_SAFE_INTEGER);const h=s[i];return a<0&&(a+=h),c>0?a=Pl(0,a,h):a=Pl(-1,a,h-1),a}function rb(e,t,n){let s=n.length;for(let i=0;i<n.length;i++)if(n[i]>1){s=i;break}for(let i=s+1;i<n.length;i++)if(t[i]>0||n[i]!==e[i])return!1;return!0}function ob(e,t){let n=e.length>0?e[e.length-1]:1;for(let s=0;s<e.length-1;s++)n+=e[s]*t[s];return n}function Rd(e,t,n){let s;const i=e.shape.length;typeof t=="number"?s=[t,...new Array(i-1).fill(0)]:t.length<i?s=t.concat(new Array(i-t.length).fill(0)):s=t.slice(),s.forEach(a=>{k(a!==-1,()=>"slice() does not support negative begin indexing.")});let o;return n==null?o=new Array(i).fill(-1):typeof n=="number"?o=[n,...new Array(i-1).fill(-1)]:n.length<i?o=n.concat(new Array(i-n.length).fill(-1)):o=n,o=o.map((a,c)=>a>=0?a:(k(a===-1,()=>`Negative size values should be exactly -1 but got ${a} for the slice() size at index ${c}.`),e.shape[c]-s[c])),[s,o]}var CT=Object.freeze({__proto__:null,assertParamsValid:ib,maskToAxes:Nd,computeOutShape:Cd,stridesWithElidedDims:wT,getNormalizedAxes:IT,startIndicesWithElidedDims:xT,stopIndicesWithElidedDims:TT,stridesForAxis:AT,startForAxis:vT,stopForAxis:NT,isSliceContinous:rb,computeFlatOffset:ob,parseSliceParams:Rd});class Ao{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class Fs{constructor(){this.classNameMap={}}static getMap(){return Fs.instance==null&&(Fs.instance=new Fs),Fs.instance}static register(e){Fs.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function me(e){k(e.className!=null,()=>"Class being registered does not have the static className property defined."),k(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),k(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),Fs.register(e)}var IF=Object.freeze({__proto__:null,Serializable:Ao,SerializationMap:Fs,registerClass:me});const xF=.001,RT=.1;function TF(e,t,n){return n==null&&(n=Od()),ab(e,t,(s,i)=>lb(s,i,n))}function Od(){return V.backend.floatPrecision()===32?xF:RT}function ab(e,t,n){let s=!0;if((wn(e)||wn(t))&&(s=!1),wn(e)&&wn(t)&&(s=!0),s){const a=e.constructor.name,c=t.constructor.name;if(a!==c)throw new Error(`Arrays are of different type. Actual: ${a}. Expected: ${c}`)}if(Array.isArray(e)&&Array.isArray(t)){const a=xi(e),c=xi(t);if(!ot(a,c))throw new Error(`Arrays have different shapes. Actual: [${a}]. Expected: [${c}]`)}const i=wn(e)?e:qi(e),o=wn(t)?t:qi(t);if(i.length!==o.length)throw new Error(`Arrays have different lengths actual: ${i.length} vs expected: ${o.length}.
Actual: ${i}.
Expected: ${o}.`);for(let a=0;a<o.length;++a){const c=i[a],h=o[a];if(!n(c,h))throw new Error(`Arrays differ: actual[${a}] = ${c}, expected[${a}] = ${h}.
Actual: ${i}.
Expected: ${o}.`)}}function AF(e,t){e().then(()=>t.fail(),()=>t())}function vF(e,t){const n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return xr(e)||xr(e[0])||xr(t)||xr(t[0])?ab(e,n,(s,i)=>s==i):ab(e,t,(s,i)=>lb(s,i,0))}function cb(e,t,n){if(n==null&&(n=Od()),!lb(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function lb(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function NF(e,t,n){for(let s=0;s<e.length;s++)if(e[s]<t||e[s]>n)throw new Error(`Value out of range:${e[s]} low: ${t}, high: ${n}`)}function CF(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}var RF=Object.freeze({__proto__:null,TEST_EPSILON_FLOAT16:RT,expectArraysClose:TF,testEpsilon:Od,expectPromiseToFail:AF,expectArraysEqual:vF,expectNumbersClose:cb,expectValuesInRange:NF,expectArrayBuffersEqual:CF});const OT="2.6.0";function OF(){C().set("PROD",!0)}function EF(){C().set("DEBUG",!0)}function DF(){C().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function nn(e){C().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}dk(nn);function kF(){V.disposeVariables()}function _s(){return V}function Ed(){return V.memory()}function FF(e){return V.profile(e)}function ee(e,t){return V.tidy(e,t)}function He(e){const t=ji(e);t.forEach(n=>n.dispose())}function Cn(e){return V.keep(e)}function _F(e){return V.time(e)}function ET(e){return V.setBackend(e)}function WF(){return V.ready()}function $F(){return V.backendName}function UF(e){V.removeBackend(e)}function BF(e){return V.findBackend(e)}function MF(e){return V.findBackendFactory(e)}function hb(e,t,n=1){return V.registerBackend(e,t,n)}function DT(){return V.backend}function PF(e,t){C().setPlatform(e,t)}function zF(e,t){let n=W(e,"a","add"),s=W(t,"b","add");[n,s]=Mt(n,s);const i=(a,c)=>{const h=a.add(n,s);return c([n,s]),h},o={a:n,b:s};return V.runKernelFunc(i,o,null,Te)}const be=P({add_:zF});function GF(e,t){let n=W(e,"a","floorDiv"),s=W(t,"b","floorDiv");[n,s]=Mt(n,s);const i=(a,c)=>{const h=a.floorDiv(n,s);return c([n,s]),h},o={a:n,b:s};return V.runKernelFunc(i,o,null,Yg)}const Dd=P({floorDiv_:GF});function VF(e,t){let n=W(e,"a","div"),s=W(t,"b","div");if([n,s]=Mt(n,s),n.dtype==="int32"&&s.dtype==="int32")return Dd(n,s);const i=(c,h)=>{const d=c.realDivide(n,s);return h([n,s]),d},o={a:n,b:s},a={};return V.runKernelFunc(i,o,null,wa,a)}const _e=P({div_:VF});function YF(e,t){let n=W(e,"a","mul"),s=W(t,"b","mul");[n,s]=Mt(n,s);const i=(a,c)=>{const h=a.multiply(n,s);return c([n,s]),h},o={a:n,b:s};return V.runKernelFunc(i,o,null,Al)}const X=P({mul_:YF});function HF(e){const t=W(e,"x","abs"),n={x:t};return V.runKernelFunc((s,i)=>(i([t]),t.dtype==="complex64"?s.complexAbs(t):s.abs(t)),n,null,ge)}const sn=P({abs_:HF});function qF(e){const t=W(e,"x","acos"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.acos(t);return i([t]),o},n,null,fe)}const ub=P({acos_:qF});function jF(e){const t=W(e,"x","acosh"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.acosh(t);return i([t]),o},n,null,Ae)}const db=P({acosh_:jF});function KF(e){k(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),k(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);const t=e.map((o,a)=>W(o,`tensors${a}`,"addN")),n=t[0];t.forEach(o=>{if(o.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(o=>{if(!ot(o.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});const s=(o,a)=>{const c=o.addN(t);return a(t),c},i=t;return V.runKernelFunc(s,i,null,Ve)}const kT=P({addN_:KF});function pb(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function FT(e,t,n){const s=e.length+t.length,i=[];let o=0,a=0;for(let c=0;c<s;c++)n.indexOf(c)===-1?i.push(e[o++]):i.push(t[a++]);return i}function Rn(e,t){const n=[],s=e.length;for(let o=0;o<s;o++)t.indexOf(o)===-1&&n.push(e[o]);const i=t.map(o=>e[o]);return[n,i]}function On(e,t){const n=t.map(s=>1);return FT(e,n,t)}function ts(e,t,n){k(pb(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function kn(e,t){if(pb(e,t))return null;const n=[];for(let s=0;s<t;++s)e.indexOf(s)===-1&&n.push(s);return e.forEach(s=>n.push(s)),n}function Xl(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function ws(e,t){const n=[];for(let s=t-e;s<t;++s)n.push(s);return n}function XF(e,t=null,n=!1){let s=W(e,"x","all","bool");const i=c=>{const h=gt(t,s.shape);let d=h;const m=kn(d,s.rank);m!=null&&(s=Me(s,m),d=ws(d.length,s.rank));const y=c.all(s,d);if(n){const b=On(y.shape,h);return K(y,b)}return y},o={x:s},a={axis:t,keepDims:n};return V.runKernelFunc(i,o,null,rt,a)}const kd=P({all_:XF});function JF(e,t=null,n=!1){let s=W(e,"x","any","bool");const i=c=>{const h=gt(t,s.shape);let d=h;const m=kn(d,s.rank);m!=null&&(s=Me(s,m),d=ws(d.length,s.rank));const y=c.any(s,d);if(n){const b=On(y.shape,h);return K(y,b)}return y},o={x:s},a={axis:t,keepDims:n};return V.runKernelFunc(i,o,null,Ct,a)}const Jl=P({any_:JF});function ZF(e,t=0){let n=W(e,"x","argMax");const s=(a,c)=>{c([n]);let h=gt(t,n.shape);const d=kn(h,n.rank);return d!=null&&(n=Me(n,d),h=ws(h.length,n.rank)),a.argMax(n,h[0])},i={x:n},o={axis:t};return V.runKernelFunc(s,i,null,Ut,o)}const Zl=P({argMax_:ZF});function QF(e,t=0){let n=W(e,"x","argMin");const s=(a,c)=>{c([n]),t==null&&(t=0);let h=gt(t,n.shape);const d=kn(h,n.rank);return d!=null&&(n=Me(n,d),h=ws(h.length,n.rank)),a.argMin(n,h[0])},i={x:n},o={axis:t};return V.runKernelFunc(s,i,null,Kt,o)}const mb=P({argMin_:QF});function e_(e){const t=W(e,"x","asin"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.asin(t);return i([t]),o},n,null,Dn)}const fb=P({asin_:e_});function t_(e){const t=W(e,"x","asinh"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.asinh(t);return i([t]),o},n,null,An)}const gb=P({asinh_:t_});function n_(e){const t=W(e,"x","atan"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.atan(t);return i([t]),o},n,null,vn)}const yb=P({atan_:n_});function s_(e,t){let n=W(e,"a","atan2"),s=W(t,"b","atan2");[n,s]=Mt(n,s);const i=(a,c)=>{const h=a.atan2(n,s);return c([n,s]),h},o={a:n,b:s};return V.runKernelFunc(i,o,null,Si)}const bb=P({atan2_:s_});function i_(e){const t=W(e,"x","atanh"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.atanh(t);return i([t]),o},n,null,Zs)}const wb=P({atanh_:i_});function Fd(e,t,n,s,i="NHWC",o){const a=e[3],c=[...t,a],h=th(i);return vi(e,c,n,o,s,null,null,h)}function Fn(e,t,n,s,i,o,a="channelsLast"){const[c,h]=_d(t);let d;if(a==="channelsLast")d=[c,h,e[3],e[3]];else if(a==="channelsFirst")d=[c,h,e[1],e[1]];else throw new Error(`Unknown dataFormat ${a}`);return vi(e,d,n,s,i,o,!1,a)}function Ql(e,t,n,s,i,o,a="NDHWC"){const[c,h,d]=Sb(t);let m,y;if(a==="NDHWC")y="channelsLast",m=[c,h,d,e[4],e[4]];else if(a==="NCDHW")y="channelsFirst",m=[c,h,d,e[1],e[1]];else throw new Error(`Unknown dataFormat ${a}`);return eh(e,m,n,s,i,!1,y,o)}function vi(e,t,n,s,i,o,a=!1,c="channelsLast"){let[h,d,m,y]=[-1,-1,-1,-1];if(c==="channelsLast")[h,d,m,y]=e;else if(c==="channelsFirst")[h,y,d,m]=e;else throw new Error(`Unknown dataFormat ${c}`);const[b,w,,L]=t,[T,A]=_d(n),[N,E]=_d(s),D=ka(b,N),F=ka(w,E),{padInfo:_,outHeight:B,outWidth:$}=a_(i,d,m,T,A,D,F,o,c),H=a?L*y:L;let q;return c==="channelsFirst"?q=[h,H,B,$]:c==="channelsLast"&&(q=[h,B,$,H]),{batchSize:h,dataFormat:c,inHeight:d,inWidth:m,inChannels:y,outHeight:B,outWidth:$,outChannels:H,padInfo:_,strideHeight:T,strideWidth:A,filterHeight:b,filterWidth:w,effectiveFilterHeight:D,effectiveFilterWidth:F,dilationHeight:N,dilationWidth:E,inShape:e,outShape:q,filterShape:t}}function eh(e,t,n,s,i,o=!1,a="channelsLast",c){let[h,d,m,y,b]=[-1,-1,-1,-1,-1];if(a==="channelsLast")[h,d,m,y,b]=e;else if(a==="channelsFirst")[h,b,d,m,y]=e;else throw new Error(`Unknown dataFormat ${a}`);const[w,L,T,,A]=t,[N,E,D]=Sb(n),[F,_,B]=Sb(s),$=ka(w,F),H=ka(L,_),q=ka(T,B),{padInfo:J,outDepth:re,outHeight:ce,outWidth:ue}=c_(i,d,m,y,N,E,D,$,H,q,c),he=o?A*b:A;let de;return a==="channelsFirst"?de=[h,he,re,ce,ue]:a==="channelsLast"&&(de=[h,re,ce,ue,he]),{batchSize:h,dataFormat:a,inDepth:d,inHeight:m,inWidth:y,inChannels:b,outDepth:re,outHeight:ce,outWidth:ue,outChannels:he,padInfo:J,strideDepth:N,strideHeight:E,strideWidth:D,filterDepth:w,filterHeight:L,filterWidth:T,effectiveFilterDepth:$,effectiveFilterHeight:H,effectiveFilterWidth:q,dilationDepth:F,dilationHeight:_,dilationWidth:B,inShape:e,outShape:de,filterShape:t}}function r_(e,t,n,s,i){s==null&&(s=Lb(e,t,n));const o=e[0],a=e[1],c=vo((o-t+2*s)/n+1,i);k(Bt(c),()=>`The output # of rows (${c}) must be an integer. Change the stride and/or zero pad parameters`);const h=vo((a-t+2*s)/n+1,i);return k(Bt(h),()=>`The output # of columns (${h}) must be an integer. Change the stride and/or zero pad parameters`),[c,h]}function o_(e,t,n,s,i,o){i==null&&(i=Lb(e,t,s));const a=e[0],c=e[1],h=e[2],d=vo((a-t+2*i)/s+1,o);k(Bt(d),()=>`The output # of depths (${d}) must be an integer. Change the stride and/or zero pad parameters`);const m=vo((c-t+2*i)/s+1,o);k(Bt(m),()=>`The output # of rows (${m}) must be an integer. Change the stride and/or zero pad parameters`);const y=vo((h-t+2*i)/s+1,o);return k(Bt(y),()=>`The output # of columns (${y}) must be an integer. Change the stride and/or zero pad parameters`),[d,m,y,n]}function Lb(e,t,n,s=1){const i=ka(t,s);return Math.floor((e[0]*(n-1)-n+i)/2)}function _d(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function Sb(e){return typeof e=="number"?[e,e,e]:e}function ka(e,t){return t<=1?e:e+(e-1)*(t-1)}function a_(e,t,n,s,i,o,a,c,h){let d,m,y;if(typeof e=="number"){const b=e===0?"VALID":"NUMBER";d={top:e,bottom:e,left:e,right:e,type:b};const w=r_([t,n],o,s,e,c);m=w[0],y=w[1]}else if(e==="same"){m=Math.ceil(t/s),y=Math.ceil(n/i);const b=Math.max(0,(m-1)*s+o-t),w=Math.max(0,(y-1)*i+a-n),L=Math.floor(b/2),T=b-L,A=Math.floor(w/2),N=w-A;d={top:L,bottom:T,left:A,right:N,type:"SAME"}}else if(e==="valid")d={top:0,bottom:0,left:0,right:0,type:"VALID"},m=Math.ceil((t-o+1)/s),y=Math.ceil((n-a+1)/i);else if(typeof e=="object"){const b=h==="channelsLast"?e[1][0]:e[2][0],w=h==="channelsLast"?e[1][1]:e[2][1],L=h==="channelsLast"?e[2][0]:e[3][0],T=h==="channelsLast"?e[2][1]:e[3][1],A=b===0&&w===0&&L===0&&T===0?"VALID":"EXPLICIT";d={top:b,bottom:w,left:L,right:T,type:A},m=vo((t-o+b+w)/s+1,c),y=vo((n-a+L+T)/i+1,c)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:d,outHeight:m,outWidth:y}}function c_(e,t,n,s,i,o,a,c,h,d,m){let y,b,w,L;if(typeof e=="number"){const T=e===0?"VALID":"NUMBER";y={top:e,bottom:e,left:e,right:e,front:e,back:e,type:T};const A=o_([t,n,s,1],c,1,i,e,m);b=A[0],w=A[1],L=A[2]}else if(e==="same"){b=Math.ceil(t/i),w=Math.ceil(n/o),L=Math.ceil(s/a);const T=(b-1)*i+c-t,A=(w-1)*o+h-n,N=(L-1)*a+d-s,E=Math.floor(T/2),D=T-E,F=Math.floor(A/2),_=A-F,B=Math.floor(N/2),$=N-B;y={top:F,bottom:_,left:B,right:$,front:E,back:D,type:"SAME"}}else if(e==="valid")y={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},b=Math.ceil((t-c+1)/i),w=Math.ceil((n-h+1)/o),L=Math.ceil((s-d+1)/a);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:y,outDepth:b,outHeight:w,outWidth:L}}function vo(e,t){if(!t)return 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 Or(e){const[t,n,s]=_d(e);return t===1&&n===1&&s===1}function rn(e,t){return Or(e)||Or(t)}function th(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function l_(e,t,n,s,i){const o=W(e,"x","avgPool","float32"),a=1;k(rn(n,a),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`);let c=o,h=!1;o.rank===3&&(h=!0,c=K(o,[1,o.shape[0],o.shape[1],o.shape[2]])),k(c.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${c.rank}.`),i!=null&&k(Bt(s),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);const d=(w,L)=>{const T=Fn(c.shape,t,n,1,s,i);return L([c]),T.filterWidth===1&&T.filterHeight===1&&ot(T.inShape,T.outShape)?c.clone():w.avgPool(c,T)},m={x:c},y={filterSize:t,strides:n,pad:s,dimRoundingMode:i};let b=V.runKernelFunc(d,m,null,Qs,y);return b=ve(b,o.dtype),h?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const nh=P({avgPool_:l_});function h_(e,t,n,s,i,o="NDHWC",a){a==null?a=[1,1,1]:nn("dilations is deprecated, this field will be gone in v3.0.0.");const c=W(e,"x","avgPool3d","float32");let h=c,d=!1;c.rank===4&&(d=!0,h=K(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),k(h.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${h.rank}.`),k(o==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${o}`),k(rn(n,a),()=>`Error in avgPool3d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),i!=null&&k(Bt(s),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);const m=(L,T)=>{a==null&&(a=[1,1,1]);const A=Ql(h.shape,t,n,a,s,i,o);return T([h]),L.avgPool3d(h,A)},y={x:h},b={filterSize:t,strides:n,pad:s,dimRoundingMode:i,dataFormat:o,dilations:a};let w=V.runKernelFunc(m,y,null,ol,b);return w=ve(w,h.dtype),d?K(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}const Ib=P({avgPool3d_:h_});function xb(e,t){const n=e[0].length;e.forEach((i,o)=>{k(i.length===n,()=>`Error in concat${n}D: rank of tensors[${o}] must be the same as the rank of the rest (${n})`)}),k(t>=0&&t<n,()=>`Error in concat${n}D: axis must be between 0 and ${n-1}.`);const s=e[0];e.forEach((i,o)=>{for(let a=0;a<n;a++)k(a===t||i[a]===s[a],()=>`Error in concat${n}D: Shape of tensors[${o}] (${i}) does not match the shape of the rest (${s}) along the non-concatenated axis ${o}.`)})}function Er(e,t){const n=e[0].slice();for(let s=1;s<e.length;s++)n[t]+=e[s][t];return n}function u_(e,t=0){k(e.length>=1,()=>"Pass at least one tensor to concat");let n=jl(e,"tensors","concat");n[0].dtype==="complex64"&&n.forEach(a=>{if(a.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
with dtype ${a.dtype}. `)});const s=(a,c)=>{const h=gt(t,n[0].shape)[0],d=Er(n.map(b=>b.shape),h);if(we(d)===0)return en([],d);if(n=n.filter(b=>b.size>0),n.length===1)return n[0];const m=n.map(b=>b.shape);xb(m,h);const y=a.concat(n,h);return c(n),y},i=n,o={axis:t};return V.runKernelFunc(s,i,null,qu,o)}const Pt=P({concat_:u_});function d_(e){const t=W(e,"x","sigmoid"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.sigmoid(t);return i([o]),o},n,null,kl)}const Ni=P({sigmoid_:d_});function p_(e,t,n){const s=W(e,"x","slice");if(s.rank===0)throw new Error("Slicing scalar is not possible");const i=(c,h)=>{const[d,m]=Rd(s,t,n);return ib(s,d,m),h([s]),c.slice(s,d,m)},o={x:s},a={begin:t,size:n};return V.runKernelFunc(i,o,null,rd,a)}const nt=P({slice_:p_});function m_(e){const t=W(e,"x","tanh"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.tanh(t);return i([o]),o},n,null,$l)}const Fa=P({tanh_:m_});function f_(e,t,n,s,i,o){const a=W(e,"forgetBias","basicLSTMCell"),c=W(t,"lstmKernel","basicLSTMCell"),h=W(n,"lstmBias","basicLSTMCell"),d=W(s,"data","basicLSTMCell"),m=W(i,"c","basicLSTMCell"),y=W(o,"h","basicLSTMCell"),b=Pt([d,y],1),w=at(b,c),L=be(w,h),T=L.shape[0],A=L.shape[1]/4,N=[T,A],E=nt(L,[0,0],N),D=nt(L,[0,A],N),F=nt(L,[0,A*2],N),_=nt(L,[0,A*3],N),B=be(X(Ni(E),Fa(D)),X(m,Ni(be(a,F)))),$=X(Fa(B),Ni(_));return[B,$]}const g_=P({basicLSTMCell_:f_});function y_(e,t,n){const s=W(e,"x","batchToSpaceND"),i=t.reduce((h,d)=>h*d);k(s.rank>=1+t.length,()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`),k(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),k(s.shape[0]%i===0,()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${i}`);const o=h=>h.batchToSpaceND(s,t,n),a={x:s},c={blockShape:t,crops:n};return V.runKernelFunc(o,a,null,Wg,c)}const sh=P({batchToSpaceND_:y_});function b_(e){let t;return e.rank===0||e.rank===1?t=K(e,[1,1,1,e.size]):e.rank===2?t=K(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=K(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function w_(e,t,n,s,i,o){o==null&&(o=.001);const a=W(e,"x","batchNorm"),c=W(t,"mean","batchNorm"),h=W(n,"variance","batchNorm");let d;i!=null&&(d=W(i,"scale","batchNorm"));let m;s!=null&&(m=W(s,"offset","batchNorm")),k(c.rank===h.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),k(m==null||c.rank===m.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),k(d==null||c.rank===d.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const y=b_(a),b=(A,N)=>(N([y,c,h,d]),A.batchNorm(y,Wd(c),Wd(h),Wd(m),Wd(d),o)),w={x:y,scale:d,offset:m,mean:c,variance:h},L={varianceEpsilon:o},T=V.runKernelFunc(b,w,null,gl,L);return K(T,a.shape)}function Wd(e){return e==null?null:e.rank===0?K(e,[e.size]):e.rank===1?e:e.rank===2?K(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?K(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e}const No=P({batchNorm_:w_});function L_(e,t,n,s,i,o){const a=W(e,"x","batchNorm"),c=W(t,"mean","batchNorm"),h=W(n,"variance","batchNorm");let d;i!=null&&(d=W(i,"scale","batchNorm"));let m;return s!=null&&(m=W(s,"offset","batchNorm")),k(a.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${a.rank}.`),k(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${c.rank}.`),k(h.rank===2||h.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${h.rank}.`),d!=null&&k(d.rank===2||d.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${d.rank}.`),m!=null&&k(m.rank===2||m.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${m.rank}.`),No(a,c,h,m,d,o)}const _T=P({batchNorm2d_:L_});function S_(e,t,n,s,i,o){const a=W(e,"x","batchNorm"),c=W(t,"mean","batchNorm"),h=W(n,"variance","batchNorm");let d;i!=null&&(d=W(i,"scale","batchNorm"));let m;return s!=null&&(m=W(s,"offset","batchNorm")),k(a.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${a.rank}.`),k(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${c.rank}.`),k(h.rank===3||h.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${h.rank}.`),d!=null&&k(d.rank===3||d.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${d.rank}.`),m!=null&&k(m.rank===3||m.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${m.rank}.`),No(a,c,h,m,d,o)}const WT=P({batchNorm3d_:S_});function I_(e,t,n,s,i,o){const a=W(e,"x","batchNorm"),c=W(t,"mean","batchNorm"),h=W(n,"variance","batchNorm");let d;i!=null&&(d=W(i,"scale","batchNorm"));let m;return s!=null&&(m=W(s,"offset","batchNorm")),k(a.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${a.rank}.`),k(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${c.rank}.`),k(h.rank===4||h.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${h.rank}.`),d!=null&&k(d.rank===4||d.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${d.rank}.`),m!=null&&k(m.rank===4||m.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${m.rank}.`),No(a,c,h,m,d,o)}const $T=P({batchNorm4d_:I_});function x_(e,t){let n=W(e,"broadcastTo","x");const s=n.shape;if(t.some(m=>!(m>0)||m%1!==0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.length<n.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${n.rank}.`);if(t.length>n.rank){const m=n.shape.slice();for(;m.length<t.length;)m.unshift(1);n=K(n,m)}const i=n.shape,o=Array.from(t);for(let m=t.length-1;m>=0;m--)if(i[m]===t[m])o[m]=1;else if(n.shape[m]!==1)throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${t}].`);const a=o.map((m,y)=>m>1?y:-1).filter(m=>m>=0);if(a.length===0)return Rr(n);const c=m=>m.tile(n,o),h={x:n},d={shape:t,inputShape:i};return V.runKernelFunc(c,h,null,$g,d)}const ih=P({broadcastTo_:x_});function T_(e){const t=W(e,"x","ceil"),n={x:t};return V.runKernelFunc(s=>s.ceil(t),n,null,cl)}const Tb=P({ceil_:T_});function A_(e,t,n){const s=W(e,"x","clipByValue");k(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`);const i={x:s},o={clipValueMin:t,clipValueMax:n};return V.runKernelFunc((a,c)=>{const h=a.clip(s,t,n);return c([s]),h},i,null,ll,o)}const Hn=P({clipByValue_:A_});function v_(e){return Pt(e,0)}const UT=P({concat1d_:v_});function N_(e,t){return Pt(e,t)}const BT=P({concat2d_:N_});function C_(e,t){return Pt(e,t)}const MT=P({concat3d_:C_});function R_(e,t){return Pt(e,t)}const PT=P({concat4d_:R_});function O_(e,t,n,s,i="NHWC",o=[1,1],a){const c=W(e,"x","conv2d"),h=W(t,"filter","conv2d");let d=c,m=!1;c.rank===3&&(m=!0,d=K(c,[1,c.shape[0],c.shape[1],c.shape[2]])),k(d.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${d.rank}.`),k(h.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${h.rank}.`),a!=null&&k(Bt(s),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`);const y=i==="NHWC"?d.shape[3]:d.shape[1];k(y===h.shape[2],()=>`Error in conv2d: depth of input (${y}) must match input depth for filter ${h.shape[2]}.`),k(rn(n,o),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`);const b=(A,N)=>{const E=th(i),D=vi(d.shape,h.shape,n,o,s,a,!1,E),F=A.conv2d(d,h,D);return N([d,h]),F},w={x:d,filter:h},L={strides:n,pad:s,dataFormat:i,dilations:o,dimRoundingMode:a},T=V.runKernelFunc(b,w,null,Bg,L);return m?K(T,[T.shape[1],T.shape[2],T.shape[3]]):T}const Xi=P({conv2d_:O_});function E_(e,t,n,s,i="NWC",o=1,a){const c=W(e,"x","conv1d"),h=W(t,"filter","conv1d");let d=c,m=!1;c.rank===2&&(m=!0,d=K(c,[1,c.shape[0],c.shape[1]])),k(d.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${d.rank}.`),k(h.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${h.rank}.`),a!=null&&k(Bt(s),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`),k(d.shape[2]===h.shape[1],()=>`Error in conv1d: depth of input (${d.shape[2]}) must match input depth for filter ${h.shape[1]}.`),k(rn(n,o),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${o}'`),k(i==="NWC",()=>`Error in conv1d: got dataFormat of ${i} but only NWC is currently supported.`);const y=K(h,[1,h.shape[0],h.shape[1],h.shape[2]]),b=K(d,[d.shape[0],1,d.shape[1],d.shape[2]]),w=[1,n],L=[1,o],T="NHWC",A=Xi(b,y,w,s,T,L,a);return m?K(A,[A.shape[2],A.shape[3]]):K(A,[A.shape[0],A.shape[2],A.shape[3]])}const $d=P({conv1d_:E_});function D_(e,t,n,s,i,o="NHWC",a){k(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let c=e,h=t,d=!1;t.rank===3&&(d=!0,h=K(t,[1,t.shape[0],t.shape[1],t.shape[2]]),c=[1,e[0],e[1],e[2]]),k(c.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${c.length}.`),k(h.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${h.rank}`),k(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);const m=o==="NHWC"?c[3]:c[1],y=o==="NHWC"?h.shape[3]:h.shape[1];k(m===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${m}) must match input depth for filter ${n.shape[2]}.`),k(y===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${y}) must match output depth for filter ${n.shape[3]}.`),a!=null&&k(Bt(i),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${a} but got pad ${i}.`);const b=(A,N)=>{const E=1,D=th(o),F=vi(c,n.shape,s,E,i,a,!1,D),_=A.conv2dDerInput(h,n,F);return N([h,n]),_},w={dy:h,filter:n},L={strides:s,pad:i,dataFormat:o,dimRoundingMode:a,inputShape:c},T=V.runKernelFunc(b,w,null,Mg,L);return d?K(T,[T.shape[1],T.shape[2],T.shape[3]]):T}const Ab=P({conv2DBackpropInput_:D_});function k_(e,t,n,s,i,o){const a=W(e,"x","conv2dTranspose"),c=W(t,"filter","conv2dTranspose");return Ab(n,a,c,s,i,"NHWC",o)}const Ud=P({conv2dTranspose_:k_});function F_(e,t,n,s,i="NDHWC",o=[1,1,1]){const a=W(e,"x","conv3d"),c=W(t,"filter","conv3d");let h=a,d=!1;a.rank===4&&(d=!0,h=K(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),k(h.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${h.rank}.`),k(c.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${c.rank}.`),k(h.shape[4]===c.shape[3],()=>`Error in conv3d: depth of input (${h.shape[4]}) must match input depth for filter ${c.shape[3]}.`),k(rn(n,o),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),k(i==="NDHWC",()=>`Error in conv3d: got dataFormat of ${i} but only NDHWC is currently supported.`);const m=(L,T)=>{const A=eh(h.shape,c.shape,n,o,s),N=L.conv3d(h,c,A);return T([h,c]),N},y={x:h,filter:c},b={strides:n,pad:s,dataFormat:i,dilations:o},w=V.runKernelFunc(m,y,null,Pg,b);return d?K(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}const vb=P({conv3d_:F_});function __(e,t,n,s,i){k(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let o=e,a=t,c=!1;t.rank===4&&(c=!0,a=K(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 h=o[4],d=a.shape[4];k(o.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${o.length}.`),k(a.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${a.rank}`),k(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),k(h===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${h}) must match input depth for filter ${n.shape[3]}.`),k(d===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${d}) must match output depth for filter ${n.shape[4]}.`);const m=L=>{const T=1,A=eh(o,n.shape,s,T,i);return L.conv3dDerInput(a,n,A)},y={dy:a},b={pad:i},w=V.runKernelFunc(m,y,null,hx,b);return c?K(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}const zT=P({conv3DBackpropInput_:__});function W_(e,t,n,s,i){const o=W(e,"x","conv3dTranspose"),a=W(t,"filter","conv3dTranspose");return zT(n,o,a,s,i)}const $_=P({conv3dTranspose_:W_});function U_(e){const t=W(e,"x","cos"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.cos(t);return i([t]),o},n,null,ba)}const rh=P({cos_:U_});function B_(e){const t=W(e,"x","cosh"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.cosh(t);return i([t]),o},n,null,hl)}const Bd=P({cosh_:B_});function M_(e,t=0,n=!1,s=!1){const i=W(e,"x","cumsum"),o=(h,d)=>{const m=kn([t],i.rank);let y=i;m!=null&&(y=Me(i,m));const b=ws(1,i.rank)[0];let w=h.cumsum(y,b,n,s);if(d([i]),m!=null){const L=Xl(m);w=Me(w,L)}return w},a={x:i},c={axis:t,exclusive:n,reverse:s};return V.runKernelFunc(o,a,null,zg,c)}const Md=P({cumsum_:M_});function P_(e,t,n="NHWC"){const s=W(e,"x","depthToSpace"),i=n==="NHWC"?s.shape[1]:s.shape[2],o=n==="NHWC"?s.shape[2]:s.shape[3],a=n==="NHWC"?s.shape[3]:s.shape[1];k(i*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${i} and ${t} for depthToSpace with input shape
${s.shape}`),k(o*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${o} and ${t} for depthToSpace with input shape
${s.shape}`),k(a%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${a} for depthToSpace with input shape ${s.shape}`);const c=m=>m.depthToSpace(s,t,n),h={x:s},d={blockSize:t,dataFormat:n};return V.runKernelFunc(c,h,null,dx,d)}const Nb=P({depthToSpace_:P_});function z_(e,t,n,s,i="NHWC",o=[1,1],a){const c=W(e,"x","depthwiseConv2d"),h=W(t,"filter","depthwiseConv2d");let d=c,m=!1;c.rank===3&&(m=!0,d=K(c,[1,c.shape[0],c.shape[1],c.shape[2]])),k(d.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${d.rank}.`),k(h.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${h.rank}.`),k(d.shape[3]===h.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${d.shape[3]}) must match the inChannels dimension in filter ${h.shape[2]}.`),a!=null&&k(Bt(s),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`);const y=(T,A)=>{o==null&&(o=[1,1]),k(rn(n,o),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`);const N=vi(d.shape,h.shape,n,o,s,a,!0),E=T.depthwiseConv2D(d,h,N);return A([d,h]),E},b={x:d,filter:h},w={strides:n,pad:s,dataFormat:i,dilations:o,dimRoundingMode:a},L=V.runKernelFunc(y,b,null,Gg,w);return m?K(L,[L.shape[1],L.shape[2],L.shape[3]]):L}const Co=P({depthwiseConv2d_:z_});function G_(e){const t=W(e,"x","diag"),n=i=>{const o=K(t,[t.size]),a=i.diag(o),c=[...e.shape,...e.shape];return K(a,c)},s={x:t};return V.runKernelFunc(n,s,null,fx)}const V_=P({diag_:G_});function Y_(e,t,n,s,i=[1,1],o="NHWC"){const a=W(e,"x","dilation2d"),c=W(t,"filter","dilation2d");k(a.rank===3||a.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${a.rank}.`),k(c.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${c.rank}.`),k(o==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${o}`);let h=a,d=!1;a.rank===3&&(h=K(a,[1,a.shape[0],a.shape[1],a.shape[2]]),d=!0);const m={x:h,filter:c},y={strides:n,pad:s,dilations:i},b=V.runKernel(ju,m,y);return d?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const Cb=P({dilation2d_:Y_});function Ro(e,t){const n=e.length,s=[];for(let i=0;i<n;i++){const o=n-1-i,a=e[o]||1,c=t[t.length-1-i]||1;c>1&&a===1&&s.unshift(o)}return s}function on(e,t){const n=[];for(let s=0;s<t.length;s++){const i=e[e.length-s-1],o=t.length-s-1,a=t[o];(i==null||i===1&&a>1)&&n.unshift(o)}return n}function tt(e,t){const n=[],s=Math.max(e.length,t.length);for(let i=0;i<s;i++){let o=e[e.length-i-1];o==null&&(o=1);let a=t[t.length-i-1];if(a==null&&(a=1),o===1)n.unshift(a);else if(a===1)n.unshift(o);else if(o!==a){const c=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(c)}else n.unshift(o)}return n}function H_(e,t){let n=W(e,"a","equal"),s=W(t,"b","equal");[n,s]=Mt(n,s),tt(n.shape,s.shape);const i=a=>a.equal(n,s),o={a:n,b:s};return V.runKernelFunc(i,o,null,yx)}const ti=P({equal_:H_});function q_(e,t,n){const s=W(t,"a","where"),i=W(n,"b","where"),o=W(e,"condition","where","bool"),a=tt(s.shape,i.shape),c=ih(s,a),h=ih(i,a);o.rank===1&&k(o.shape[0]===s.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),o.rank!==1&&pt(o.shape,h.shape,"Error in where: ");const d=(y,b)=>{const w=y.select(o,c,h);return b([o]),w},m={condition:o,t:c,e:h};return V.runKernelFunc(d,m,null,fy)}const _n=P({where_:q_});function j_(e){const t=W(e,"x","zerosLike"),n={x:t};return V.runKernelFunc(s=>s.zerosLike(t),n,null,Iy)}const Qe=P({zerosLike_:j_});function K_(e,t){let n=W(e,"a","div"),s=W(t,"b","div");[n,s]=Mt(n,s);const i=_e(n,s),o=Qe(i),a=ti(s,o);return _n(a,o,i)}const Rb=P({divNoNan_:K_});function X_(e,t){const n=W(e,"t1","dot"),s=W(t,"t2","dot");k((n.rank===1||n.rank===2)&&(s.rank===1||s.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${s.rank}.`);const i=n.rank===1?n.size:n.shape[1],o=s.rank===1?s.size:s.shape[0];if(k(i===o,()=>`Error in dot: inner dimensions of inputs must match, but got ${i} and ${o}.`),n.rank===1&&s.rank===1){const a=K(n,[1,-1]),c=K(s,[-1,1]),h=at(a,c);return K(h,[])}else if(n.rank===1&&s.rank===2){const a=K(n,[1,-1]),c=K(s,[s.shape[0],s.shape[1]]),h=at(a,c);return K(h,[h.size])}else if(n.rank===2&&s.rank===1){const a=K(s,[-1,1]),c=at(n,a);return K(c,[c.size])}else{const a=K(s,[s.shape[0],s.shape[1]]),c=at(n,a);return c}}const GT=P({dot_:X_});function J_(e){const t=W(e,"x","elu"),n=(i,o)=>{const a=i.elu(t);return o([a]),a},s={x:t};return V.runKernelFunc(n,s,null,ul)}const Oo=P({elu_:J_});function Z_(e){let t=W(e,"x","erf");k(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=ve(t,"float32"));const n={x:t};return V.runKernelFunc((s,i)=>{const o=s.erf(t);return i([t]),o},n,null,dl)}const Ob=P({erf_:Z_});function Q_(e){const t=W(e,"x","exp"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.exp(t);return i([o]),o},n,null,pl)}const Ls=P({exp_:Q_});function eW(e,t=0){const n=null,s=W(e,"x","expandDims",n);k(t<=s.rank,()=>"Axis must be <= rank of the tensor");const i=s.shape.slice();return t<0&&(k(-(s.rank+1)<=t,()=>`Axis must be in the interval [${-(s.rank+1)}, ${s.rank}]`),t=s.rank+t+1),i.splice(t,0,1),K(s,i)}const qn=P({expandDims_:eW});function tW(e){const t=W(e,"x","expm1"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.expm1(t);return i([t]),o},n,null,ml)}const Eb=P({expm1_:tW});function nW(e,t){const n=null,s=W(e,"x","tile",n);k(s.rank===t.length,()=>`Error in transpose: rank of input ${s.rank} must match length of reps ${t}.`);const i=(h,d)=>{const m=h.tile(s,t);return d([s]),m},o=[s],a={x:s},c={reps:t};return V.runKernelFunc(i,a,null,wy,c,o)}const Dr=P({tile_:nW});function sW(e,t,n,s="float32"){t==null&&(t=e);const i=Ze([e,t],s),o=e<=t?e:t;for(let c=0;c<o;++c)i.set(1,c,c);const a=K(i.toTensor(),[e,t]);if(n==null)return a;if(n.length===1)return Dr(qn(a,0),[n[0],1,1]);if(n.length===2)return Dr(qn(qn(a,0),0),[n[0],n[1],1,1]);if(n.length===3)return Dr(qn(qn(qn(a,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${n.length}D.`)}const Pd=P({eye_:sW});function oh(e,t,n){const s={shape:e,value:t,dtype:n};return V.runKernelFunc(i=>i.fill(e,t,n),{},null,bx,s)}function iW(e){const t=W(e,"x","floor"),n={x:t};return V.runKernelFunc(s=>s.floor(t),n,null,fl)}const _a=P({floor_:iW});const Db=30;function ah(e){return e<=Db?e:gd(e,Math.floor(Math.sqrt(e)))}function rW(e,t){let n=!1,s;for(e<=Db?(s=e,n=!0):s=gd(e,Math.floor(Math.sqrt(e)));!n;)s>t||s===e?n=!0:s=gd(e,s+1);return s}function oW(e,t,n){const s=[],i=e.length;for(let o=0;o<i;o++)o!==t?s.push(e[o]):s.push(n);return s}function VT(e,t,n){const s=e.shape[n],i=[];let o=1,a=1;for(let c=0;c<n;c++)i.push(e.shape[c]),o*=e.shape[c];for(let c=0;c<t.rank;c++)i.push(t.shape[c]);for(let c=n+1;c<e.rank;c++)i.push(e.shape[c]),a*=e.shape[c];return{batchSize:o,sliceSize:a,dimSize:s,outputShape:i}}var aW=Object.freeze({__proto__:null,segOpComputeOptimalWindowSize:rW,computeOutShape:oW,collectGatherOpShapeInfo:VT});function cW(e,t,n=0){const s=W(e,"x","gather"),i=W(t,"indices","gather","int32"),o={x:s,indices:i},a={axis:n},c=(h,d)=>{const m=gt(n,s.shape)[0],y=VT(s,i,m),b=h.gather(s,K(i,[i.size]),m);return d([s,i]),K(b,y.outputShape)};return V.runKernelFunc(c,o,null,Hg,a)}const Wa=P({gather_:cW});function lW(e,t){let n=W(e,"a","greater"),s=W(t,"b","greater");[n,s]=Mt(n,s),tt(n.shape,s.shape);const i=a=>a.greater(n,s),o={a:n,b:s};return V.runKernelFunc(i,o,null,Lx)}const Ss=P({greater_:lW});function hW(e,t){let n=W(e,"a","greaterEqual"),s=W(t,"b","greaterEqual");[n,s]=Mt(n,s),tt(n.shape,s.shape);const i=(a,c)=>{const h=a.greaterEqual(n,s);return c([n,s]),h},o={a:n,b:s};return V.runKernelFunc(i,o,null,qg)}const Ji=P({greaterEqual_:hW});function uW(e){const t=W(e,"input","imag"),n=i=>i.imag(t),s={input:t};return V.runKernelFunc(n,s,null,Kg)}const $a=P({imag_:uW});function dW(e){const t=W(e,"x","isFinite"),n={x:t};return V.runKernelFunc(s=>s.isFinite(t),n,null,bl)}const YT=P({isFinite_:dW});function pW(e){const t=W(e,"x","isInf"),n={x:t};return V.runKernelFunc(s=>s.isInf(t),n,null,wl)}const HT=P({isInf_:pW});function mW(e){const t=W(e,"x","isNaN"),n={x:t};return V.runKernelFunc(s=>s.isNaN(t),n,null,Ll)}const qT=P({isNaN_:mW});function fW(e,t){let n=W(e,"a","maximum"),s=W(t,"b","maximum");[n,s]=Mt(n,s),n.dtype==="bool"&&(n=ve(n,"int32"),s=ve(s,"int32")),tt(n.shape,s.shape);const i=(a,c)=>{const h=a.maximum(n,s);return c([n,s]),h},o={a:n,b:s};return V.runKernelFunc(i,o,null,Zg)}const Ws=P({maximum_:fW});function Ne(e,t){if((wn(e)&&t!=="string"||Array.isArray(e))&&t!=="complex64")throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if(t==="string"&&wn(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");const n=[],s=[];return Nr(e,n,s,t)}function gW(e,t=.2){const n=W(e,"x","leakyRelu");return Ws(X(Ne(t),n),n)}const zd=P({leakyRelu_:gW});function yW(e,t){let n=W(e,"a","less"),s=W(t,"b","less");[n,s]=Mt(n,s),tt(n.shape,s.shape);const i=a=>a.less(n,s),o={a:n,b:s};return V.runKernelFunc(i,o,null,Sx)}const ch=P({less_:yW});function bW(e,t){let n=W(e,"a","lessEqual"),s=W(t,"b","lessEqual");[n,s]=Mt(n,s),tt(n.shape,s.shape);const i=(a,c)=>{const h=a.lessEqual(n,s);return c([n,s]),h},o={a:n,b:s};return V.runKernelFunc(i,o,null,Ix)}const kr=P({lessEqual_:bW});function jT(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");const s={start:e,stop:t,num:n};return V.runKernelFunc(i=>i.linspace(e,t,n),{},null,xx,s)}function wW(e,t=5,n=1,s=1,i=.5){const o=W(e,"x","localResponseNormalization");k(o.rank===4||o.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
rank ${o.rank}.`),k(Bt(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let a=o,c=!1;o.rank===3&&(c=!0,a=K(o,[1,o.shape[0],o.shape[1],o.shape[2]]));const h=(b,w)=>{const L=b.localResponseNormalization4D(a,t,n,s,i);return w([a,L]),L},d={x:a},m={depthRadius:t,bias:n,alpha:s,beta:i},y=V.runKernelFunc(h,d,null,Jg,m);return c?K(y,[y.shape[1],y.shape[2],y.shape[3]]):y}const kb=P({localResponseNormalization_:wW});function LW(e){const t=W(e,"x","log"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.log(t);return i([t]),o},n,null,Sl)}const ns=P({log_:LW});function SW(e){const t=W(e,"x","log1p"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.log1p(t);return i([t]),o},n,null,Il)}const Gd=P({log1p_:SW});function IW(e){return k(Tr(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{const s=W(t,"x","tf.grad",null),i=n!=null?W(n,"dy","tf.grad"):null;return V.tidy(()=>{const{value:o,grads:a}=V.gradients(()=>e(s),[s],i);return i!=null&&pt(o.shape,i.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Vd(a),a[0]})}}function xW(e){return k(Tr(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{k(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");const s=jl(t,"args","tf.grads",null),i=n!=null?W(n,"dy","tf.grads"):null;return V.tidy(()=>{const{value:o,grads:a}=V.gradients(()=>e(...s),s,i);return i!=null&&pt(o.shape,i.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Vd(a),a})}}function TW(e){return k(Tr(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{k(t instanceof Q,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),k(n==null||n instanceof Q,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");const{grads:s,value:i}=V.gradients(()=>e(t),[t],n);return Vd(s),{grad:s[0],value:i}}}function AW(e){return k(Tr(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{k(Array.isArray(t)&&t.every(i=>i instanceof Q),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),k(n==null||n instanceof Q,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");const s=V.gradients(()=>e(...t),t,n);return n!=null&&pt(s.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Vd(s.grads),s}}function Fb(e,t){k(Tr(e),()=>"The f passed in variableGrads(f) must be a function"),k(t==null||Array.isArray(t)&&t.every(d=>d instanceof Hl),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const n=t!=null;if(!n){t=[];for(const d in V.registeredVariables)t.push(V.registeredVariables[d])}const s=n?t.filter(d=>!d.trainable):null,i=t.length;t=t.filter(d=>d.trainable),k(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${i} variables is trainable.`);const o=!0,{value:a,grads:c}=V.gradients(e,t,null,o);k(c.some(d=>d!=null),()=>"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()."),k(a.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`);const h={};return t.forEach((d,m)=>{c[m]!=null&&(h[d.name]=c[m])}),s!=null&&s.forEach(d=>h[d.name]=null),{value:a,grads:h}}function Ci(e){return V.customGrad(e)}function Vd(e){const t=e.filter(n=>n==null).length;if(t>0)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.`)}function vW(e){const t=W(e,"x","neg"),n={x:t};return V.runKernelFunc(s=>s.neg(t),n,null,sy)}const zt=P({neg_:vW});function NW(e){const t=W(e,"x","softplus"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.softplus(t);return i([t]),o},n,null,Fl)}const Ua=P({softplus_:NW});function CW(e){const t=W(e,"x","logSigmoid"),n=Ci(s=>{const i=zt(Ua(zt(s))),o=a=>{const c=X(a,Ni(zt(s)));return c};return{value:i,gradFunc:o}});return n(t)}const KT=P({logSigmoid_:CW});function RW(e,t=null,n=!1){const s=W(e,"x","max"),i=(c,h)=>{const d=gt(t,s.shape);let m=d;const y=kn(m,s.rank);let b=s;y!=null&&(b=Me(s,y),m=ws(m.length,b.rank));const w=c.max(b,m);y!=null&&b.dispose();let L=w;if(n){const T=On(L.shape,gt(t,s.shape));L=K(L,T),w.dispose()}return h([s,L]),L},o={x:s},a={reductionIndices:t,keepDims:n};return V.runKernelFunc(i,o,null,xl,a)}const jn=P({max_:RW});function OW(e,t){let n=W(e,"a","sub"),s=W(t,"b","sub");[n,s]=Mt(n,s);const i=(a,c)=>{const h=a.subtract(n,s);return c([n,s]),h},o={a:n,b:s};return V.runKernelFunc(i,o,null,Wl)}const Ce=P({sub_:OW});function EW(e,t=null,n=!1){let s=W(e,"x","sum");s.dtype==="bool"&&(s=ve(s,"int32"));const i=(c,h)=>{h([s]);const d=gt(t,s.shape),m=kn(d,s.rank);let y=d,b=s;m!=null&&(b=Me(s,m),y=ws(y.length,s.rank));let w=c.sum(b,y);if(n){const L=On(w.shape,d);w=K(w,L)}return w},o={x:s},a={axis:t,keepDims:n};return V.runKernelFunc(i,o,null,gy,a)}const Ue=P({sum_:EW});function DW(e,t=-1){const n=W(e,"logits","logSoftmax");if(t===-1&&(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 s=(a,c)=>{const h=!0,d=jn(e,t,!0),m=Ce(e,d),y=Ce(ve(m,"float32"),ns(Ue(Ls(m),t,h)));return c([y]),y},i={logits:n},o={axis:t};return V.runKernelFunc(s,i,null,Xg,o)}const Yd=P({logSoftmax_:DW});function kW(e,t=null,n=!1){const s=W(e,"x","logSumExp"),i=gt(t,s.shape),o=jn(s,i,!0),a=Ce(s,o),c=Ls(a),h=Ue(c,i),d=ns(h),m=be(K(o,d.shape),d);if(n){const y=On(m.shape,i);return K(m,y)}return m}const _b=P({logSumExp_:kW});function FW(e,t){const n=W(e,"a","logicalAnd","bool"),s=W(t,"b","logicalAnd","bool");tt(n.shape,s.shape);const i={a:n,b:s};return V.runKernelFunc(o=>o.logicalAnd(n,s),i,null,Tx)}const $s=P({logicalAnd_:FW});function _W(e){const t=W(e,"x","logicalNot","bool"),n={x:t};return V.runKernelFunc(s=>s.logicalNot(t),n,null,Zu)}const lh=P({logicalNot_:_W});function WW(e,t){const n=W(e,"a","logicalOr","bool"),s=W(t,"b","logicalOr","bool");tt(n.shape,s.shape);const i={a:n,b:s};return V.runKernelFunc(o=>o.logicalOr(n,s),i,null,Ax)}const Hd=P({logicalOr_:WW});function $W(e,t){const n=W(e,"a","logicalXor","bool"),s=W(t,"b","logicalXor","bool");return tt(n.shape,s.shape),$s(Hd(e,t),lh($s(e,t)))}const XT=P({logicalXor_:$W});function UW(e,t,n,s,i){const o=W(e,"x","maxPool"),a=1;let c=o,h=!1;o.rank===3&&(h=!0,c=K(o,[1,o.shape[0],o.shape[1],o.shape[2]])),k(c.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${c.rank}.`),k(rn(n,a),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),i!=null&&k(Bt(s),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);const d=(w,L)=>{const T=Fn(c.shape,t,n,1,s,i);let A;return T.filterWidth===1&&T.filterHeight===1&&ot(T.inShape,T.outShape)?A=c.clone():A=w.maxPool(c,T),L([c,A]),A},m={x:c},y={filterSize:t,strides:n,pad:s,dimRoundingMode:i},b=V.runKernelFunc(d,m,null,Tl,y);return h?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const hh=P({maxPool_:UW});function BW(e,t=[1,1,1],n,s,i,o="NDHWC",a){a==null?a=[1,1,1]:nn("dilations is deprecated, this field will be gone in v3.0.0.");const c=W(e,"x","maxPool3d");let h=c,d=!1;c.rank===4&&(d=!0,h=K(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),k(h.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${h.rank}.`),k(o==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${o}`),k(rn(n,a),()=>`Error in maxPool3d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),i!=null&&k(Bt(s),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);const m=(L,T)=>{a==null&&(a=[1,1,1]);const A=Ql(h.shape,t,n,a,s,i,o),N=L.maxPool3d(h,A);return T([h,N]),N},y={x:h},b={filterSize:t,strides:n,pad:s,dimRoundingMode:i,dataFormat:o,dilations:a},w=V.runKernelFunc(m,y,null,Qg,b);return d?K(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}const Wb=P({maxPool3d_:BW});function MW(e,t,n,s,i=!1){const o=W(e,"x","maxPoolWithArgmax"),a={x:o},c={filterSize:t,strides:n,pad:s,includeBatchInIndex:i},h=V.runKernel(ed,a,c);return{result:h[0],indexes:h[1]}}const JT=P({maxPoolWithArgmax_:MW});function ct(e,t="float32"){if(t==="complex64"){const s=ct(e,"float32"),i=ct(e,"float32");return Ti(s,i)}const n=Aa(we(e),t);return V.makeTensor(n,e,t)}function ni(e,t="float32"){if(t==="complex64"){const s=ni(e,"float32"),i=ct(e,"float32");return Ti(s,i)}const n=Fy(we(e),t);return V.makeTensor(n,e,t)}function PW(e,t=null,n=!1){const s=W(e,"x","mean"),i=gt(t,s.shape),o=Rn(s.shape,i),a=o[1],c=we(a),h=Ci(d=>{const m=Ne(c),y=m.dtype===d.dtype?d:ve(d,m.dtype),b=_e(y,m),w=Ue(b,t,n),L=T=>{const A=d.shape.slice();i.forEach(D=>{A[D]=1});const N=K(T,A),E=_e(X(N,ni(d.shape,"float32")),c);return E};return{value:w,gradFunc:L}});return h(s)}const Gt=P({mean_:PW});function zW(e,t=null,n=!1){const s=W(e,"x","min"),i=(c,h)=>{const d=gt(t,s.shape);let m=d;const y=kn(m,s.rank);let b=s;y!=null&&(b=Me(s,y),m=ws(m.length,s.rank));const w=c.min(b,m);y!=null&&b.dispose();let L=w;if(n){const T=On(L.shape,d);L=K(w,T),w.dispose()}return h([s,L]),L},o={x:s},a={axis:t,keepDims:n};return V.runKernelFunc(i,o,null,ey,a)}const Ba=P({min_:zW});function GW(e,t){let n=W(e,"a","minimum"),s=W(t,"b","minimum");[n,s]=Mt(n,s),n.dtype==="bool"&&(n=ve(n,"int32"),s=ve(s,"int32")),tt(n.shape,s.shape);const i=(a,c)=>{const h=a.minimum(n,s);return c([n,s]),h},o={a:n,b:s};return V.runKernelFunc(i,o,null,ty)}const Eo=P({minimum_:GW});function VW(e,t){let n=W(e,"a","mod"),s=W(t,"b","mod");[n,s]=Mt(n,s);const i=(a,c)=>{const h=a.mod(n,s);return c([n,s]),h},o={a:n,b:s};return V.runKernelFunc(i,o,null,ny)}const qd=P({mod_:VW});function YW(e){const t=W(e,"x","square"),n={},s=[t],i=[];return V.runKernelFunc((o,a)=>(a([t]),o.square(t)),{x:t},null,"Square",n,s,i)}const wt=P({square_:YW});function HW(e,t=null,n=!1){e=W(e,"x","moments");const s=gt(t,e.shape),i=Gt(e,s,n);let o=i.shape;n||(o=On(i.shape,s));const a=wt(Ce(ve(e,"float32"),K(i,o))),c=Gt(a,s,n);return{mean:i,variance:c}}const jd=P({moments_:HW});function qW(e,t,n,s){const i=W(t,"data","multiRNNCell"),o=jl(n,"c","multiRNNCell"),a=jl(s,"h","multiRNNCell");let c=i;const h=[];for(let y=0;y<e.length;y++){const b=e[y](c,o[y],a[y]);h.push(b[0]),h.push(b[1]),c=b[1]}const d=[],m=[];for(let y=0;y<h.length;y+=2)d.push(h[y]),m.push(h[y+1]);return[d,m]}const jW=P({multiRNNCell_:qW});function KW(e,t,n,s=!1){const i=W(e,"logits","multinomial"),o=i.size,a=i.rank;if(o<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${o}.`);if(a>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${a}`);n=n||Math.random();const c=a===1?K(i,[1,-1]):i,h=V.runKernelFunc(d=>d.multinomial(c,s,t,n),{logits2D:c});return a===1?K(h,[h.size]):h}const ZT=P({multinomial_:KW});function XW(e,t){let n=W(e,"a","notEqual"),s=W(t,"b","notEqual");[n,s]=Mt(n,s),tt(n.shape,s.shape);const i=a=>a.notEqual(n,s),o={a:n,b:s};return V.runKernelFunc(i,o,null,td)}const Fr=P({notEqual_:XW});function JW(e){const t=W(e,"input","real"),n=i=>i.real(t),s={input:t};return V.runKernelFunc(n,s,null,ly)}const Do=P({real_:JW});function ZW(e){const t=W(e,"x","onesLike"),n=(i,o)=>{if(t.dtype==="complex64"){const a=En(Do(t)),c=Qe($a(t));return Ti(a,c)}return i.onesLike(t)},s={x:t};return V.runKernelFunc(n,s,null,ry)}const En=P({onesLike_:ZW});function QW(e,t){const n=W(e,"v1","outerProduct"),s=W(t,"v2","outerProduct");k(n.rank===1&&s.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${s.rank}.`);const i=K(n,[-1,1]),o=K(s,[1,-1]);return at(i,o)}const e$=P({outerProduct_:QW});function t$(e,t,n=0){const s=W(e,"x","pad");if(s.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const i=(c,h)=>(h([s]),c.pad(s,t,n)),o={paddings:t,constantValue:n},a={x:s};return V.runKernelFunc(i,a,null,id,o)}const Ri=P({pad_:t$});function n$(e,t,n=0){return k(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),Ri(e,[t],n)}const s$=P({pad1d_:n$});function i$(e,t,n=0){return k(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Ri(e,t,n)}const r$=P({pad2d_:i$});function o$(e,t,n=0){return k(t.length===3&&t[0].length===2&&t[1].length===2&&t[2].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Ri(e,t,n)}const a$=P({pad3d_:o$});function c$(e,t,n=0){return k(t.length===4&&t[0].length===2&&t[1].length===2&&t[2].length===2&&t[3].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Ri(e,t,n)}const l$=P({pad4d_:c$});function h$(e,t,n){const s=W(e,"x","spaceToBatchND");k(s.rank>=1+t.length,()=>`input rank ${s.rank} should be > than [blockShape] ${t.length}`),k(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),k(s.shape.reduce((c,h,d)=>d>0&&d<=t.length?c&&(h+n[d-1][0]+n[d-1][1])%t[d-1]===0:c,!0),()=>`input spatial dimensions ${s.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);const i=c=>c.spaceToBatchND(s,t,n),o={x:s},a={blockShape:t,paddings:n};return V.runKernelFunc(i,o,null,od,a)}const uh=P({spaceToBatchND_:h$});function u$(e,t,n,s,i,o){i==null&&(i=[1,1]),o==null&&(o=1),s===0&&(s="valid");const a=W(e,"x","maxPool");let c=a,h=!1;a.rank===3&&(h=!0,c=K(a,[1,a.shape[0],a.shape[1],a.shape[2]])),k(rn(o,i),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${o} and dilations '${i}'`);const d=Fn(c.shape,t,o,i,s),m=[d.dilationHeight,d.dilationWidth];let y;s==="same"?y=p$([d.filterHeight,d.filterWidth],m):y=[[0,0],[0,0]];const b=m[0]===1&&m[1]===1,[w,L]=d$([d.inHeight,d.inWidth],m,y),T=b?s:"valid",A=b?c:uh(c,m,w),N=n==="avg"?()=>nh(A,t,o,T):()=>hh(A,t,o,T),E=N(),D=b?E:sh(E,m,L);return h?K(D,[D.shape[1],D.shape[2],D.shape[3]]):D}function d$(e,t,n){const s=n.map(m=>m[0]),i=n.map(m=>m[1]),o=e.concat(s,i),a=t.map((m,y)=>(m-o[y]%m)%m),c=i.map((m,y)=>m+a[y]),h=t.map((m,y)=>[s[y],c[y]]),d=t.map((m,y)=>[0,a[y]]);return[h,d]}function p$(e,t){const n=e.map((a,c)=>a+(a-1)*(t[c]-1)),s=n.map(a=>a-1),i=s.map(a=>Math.floor(a/2)),o=s.map((a,c)=>a-i[c]);return s.map((a,c)=>[i[c],o[c]])}const QT=P({pool_:u$});function m$(e,t){let n=W(e,"base","pow"),s=W(t,"exp","pow");[n,s]=Mt(n,s);const i={a:n,b:s},o=(a,c)=>{const h=a.pow(n,s);return c([n,s,h]),h};return V.runKernelFunc(o,i,null,ay)}const si=P({pow_:m$});function f$(e,t){const n=W(e,"x","prelu"),s=W(t,"alpha","prelu"),i=(a,c)=>{const h=a.prelu(n,s);return c([n,s]),h},o={x:n,alpha:s};return V.runKernelFunc(i,o,null,cy)}const dh=P({prelu_:f$});function g$(e,t=null,n=!1){let s=W(e,"x","prod");const i=c=>{s.dtype==="bool"&&(s=ve(s,"int32"));const h=gt(t,s.shape),d=kn(h,s.rank);let m=h,y=s;d!=null&&(y=Me(s,d),m=ws(m.length,s.rank));let b=c.prod(y,m);if(n){const w=On(b.shape,h);b=K(b,w)}return b},o={x:s},a={axis:t,keepDims:n};return V.runKernelFunc(i,o,null,Cx,a)}const Kd=P({prod_:g$});function y$(e,t,n){const s=we(e);let i=null;if(n==null||n==="float32")i=new Float32Array(s);else if(n==="int32")i=new Int32Array(s);else if(n==="bool")i=new Uint8Array(s);else throw new Error(`Unknown data type ${n}`);for(let o=0;o<s;o++)i[o]=t();return V.makeTensor(i,e,n)}const b$=P({rand_:y$});var Ma=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function MZ(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function ko(e,t){return t={exports:{}},e(t,t.exports),t.exports}function PZ(e){return e&&e.default||e}function zZ(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}var w$=ko(function(e){(function(t,n,s){function i(h){var d=this,m=c();d.next=function(){var y=2091639*d.s0+d.c*23283064365386963e-26;return d.s0=d.s1,d.s1=d.s2,d.s2=y-(d.c=y|0)},d.c=1,d.s0=m(" "),d.s1=m(" "),d.s2=m(" "),d.s0-=m(h),d.s0<0&&(d.s0+=1),d.s1-=m(h),d.s1<0&&(d.s1+=1),d.s2-=m(h),d.s2<0&&(d.s2+=1),m=null}function o(h,d){return d.c=h.c,d.s0=h.s0,d.s1=h.s1,d.s2=h.s2,d}function a(h,d){var m=new i(h),y=d&&d.state,b=m.next;return b.int32=function(){return m.next()*4294967296|0},b.double=function(){return b()+(b()*2097152|0)*11102230246251565e-32},b.quick=b,y&&(typeof y=="object"&&o(y,m),b.state=function(){return o(m,{})}),b}function c(){var h=4022871197,d=function(m){m=m.toString();for(var y=0;y<m.length;y++){h+=m.charCodeAt(y);var b=.02519603282416938*h;h=b>>>0,b-=h,b*=h,h=b>>>0,b-=h,h+=b*4294967296}return(h>>>0)*23283064365386963e-26};return d}n&&n.exports?n.exports=a:s&&s.amd?s(function(){return a}):this.alea=a})(Ma,e,!1)}),L$=ko(function(e){(function(t,n,s){function i(c){var h=this,d="";h.x=0,h.y=0,h.z=0,h.w=0,h.next=function(){var y=h.x^h.x<<11;return h.x=h.y,h.y=h.z,h.z=h.w,h.w^=h.w>>>19^y^y>>>8},c===(c|0)?h.x=c:d+=c;for(var m=0;m<d.length+64;m++)h.x^=d.charCodeAt(m)|0,h.next()}function o(c,h){return h.x=c.x,h.y=c.y,h.z=c.z,h.w=c.w,h}function a(c,h){var d=new i(c),m=h&&h.state,y=function(){return(d.next()>>>0)/4294967296};return y.double=function(){do var b=d.next()>>>11,w=(d.next()>>>0)/4294967296,L=(b+w)/(1<<21);while(L===0);return L},y.int32=d.next,y.quick=y,m&&(typeof m=="object"&&o(m,d),y.state=function(){return o(d,{})}),y}n&&n.exports?n.exports=a:s&&s.amd?s(function(){return a}):this.xor128=a})(Ma,e,!1)}),S$=ko(function(e){(function(t,n,s){function i(c){var h=this,d="";h.next=function(){var y=h.x^h.x>>>2;return h.x=h.y,h.y=h.z,h.z=h.w,h.w=h.v,(h.d=h.d+362437|0)+(h.v=h.v^h.v<<4^(y^y<<1))|0},h.x=0,h.y=0,h.z=0,h.w=0,h.v=0,c===(c|0)?h.x=c:d+=c;for(var m=0;m<d.length+64;m++)h.x^=d.charCodeAt(m)|0,m==d.length&&(h.d=h.x<<10^h.x>>>4),h.next()}function o(c,h){return h.x=c.x,h.y=c.y,h.z=c.z,h.w=c.w,h.v=c.v,h.d=c.d,h}function a(c,h){var d=new i(c),m=h&&h.state,y=function(){return(d.next()>>>0)/4294967296};return y.double=function(){do var b=d.next()>>>11,w=(d.next()>>>0)/4294967296,L=(b+w)/(1<<21);while(L===0);return L},y.int32=d.next,y.quick=y,m&&(typeof m=="object"&&o(m,d),y.state=function(){return o(d,{})}),y}n&&n.exports?n.exports=a:s&&s.amd?s(function(){return a}):this.xorwow=a})(Ma,e,!1)}),I$=ko(function(e){(function(t,n,s){function i(c){var h=this;h.next=function(){var m=h.x,y=h.i,b,w,L;return b=m[y],b^=b>>>7,w=b^b<<24,b=m[y+1&7],w^=b^b>>>10,b=m[y+3&7],w^=b^b>>>3,b=m[y+4&7],w^=b^b<<7,b=m[y+7&7],b=b^b<<13,w^=b^b<<9,m[y]=w,h.i=y+1&7,w};function d(m,y){var b,w,L=[];if(y===(y|0))w=L[0]=y;else for(y=""+y,b=0;b<y.length;++b)L[b&7]=L[b&7]<<15^y.charCodeAt(b)+L[b+1&7]<<13;for(;L.length<8;)L.push(0);for(b=0;b<8&&L[b]===0;++b);for(b==8?w=L[7]=-1:w=L[b],m.x=L,m.i=0,b=256;b>0;--b)m.next()}d(h,c)}function o(c,h){return h.x=c.x.slice(),h.i=c.i,h}function a(c,h){c==null&&(c=+new Date);var d=new i(c),m=h&&h.state,y=function(){return(d.next()>>>0)/4294967296};return y.double=function(){do var b=d.next()>>>11,w=(d.next()>>>0)/4294967296,L=(b+w)/(1<<21);while(L===0);return L},y.int32=d.next,y.quick=y,m&&(m.x&&o(m,d),y.state=function(){return o(d,{})}),y}n&&n.exports?n.exports=a:s&&s.amd?s(function(){return a}):this.xorshift7=a})(Ma,e,!1)}),x$=ko(function(e){(function(t,n,s){function i(c){var h=this;h.next=function(){var m=h.w,y=h.X,b=h.i,w,L;return h.w=m=m+1640531527|0,L=y[b+34&127],w=y[b=b+1&127],L^=L<<13,w^=w<<17,L^=L>>>15,w^=w>>>12,L=y[b]=L^w,h.i=b,L+(m^m>>>16)|0};function d(m,y){var b,w,L,T,A,N=[],E=128;for(y===(y|0)?(w=y,y=null):(y=y+"\0",w=0,E=Math.max(E,y.length)),L=0,T=-32;T<E;++T)y&&(w^=y.charCodeAt((T+32)%y.length)),T===0&&(A=w),w^=w<<10,w^=w>>>15,w^=w<<4,w^=w>>>13,T>=0&&(A=A+1640531527|0,b=N[T&127]^=w+A,L=b==0?L+1:0);for(L>=128&&(N[(y&&y.length||0)&127]=-1),L=127,T=4*128;T>0;--T)w=N[L+34&127],b=N[L=L+1&127],w^=w<<13,b^=b<<17,w^=w>>>15,b^=b>>>12,N[L]=w^b;m.w=A,m.X=N,m.i=L}d(h,c)}function o(c,h){return h.i=c.i,h.w=c.w,h.X=c.X.slice(),h}function a(c,h){c==null&&(c=+new Date);var d=new i(c),m=h&&h.state,y=function(){return(d.next()>>>0)/4294967296};return y.double=function(){do var b=d.next()>>>11,w=(d.next()>>>0)/4294967296,L=(b+w)/(1<<21);while(L===0);return L},y.int32=d.next,y.quick=y,m&&(m.X&&o(m,d),y.state=function(){return o(d,{})}),y}n&&n.exports?n.exports=a:s&&s.amd?s(function(){return a}):this.xor4096=a})(Ma,e,!1)}),T$=ko(function(e){(function(t,n,s){function i(c){var h=this,d="";h.next=function(){var y=h.b,b=h.c,w=h.d,L=h.a;return y=y<<25^y>>>7^b,b=b-w|0,w=w<<24^w>>>8^L,L=L-y|0,h.b=y=y<<20^y>>>12^b,h.c=b=b-w|0,h.d=w<<16^b>>>16^L,h.a=L-y|0},h.a=0,h.b=0,h.c=2654435769|0,h.d=1367130551,c===Math.floor(c)?(h.a=c/4294967296|0,h.b=c|0):d+=c;for(var m=0;m<d.length+20;m++)h.b^=d.charCodeAt(m)|0,h.next()}function o(c,h){return h.a=c.a,h.b=c.b,h.c=c.c,h.d=c.d,h}function a(c,h){var d=new i(c),m=h&&h.state,y=function(){return(d.next()>>>0)/4294967296};return y.double=function(){do var b=d.next()>>>11,w=(d.next()>>>0)/4294967296,L=(b+w)/(1<<21);while(L===0);return L},y.int32=d.next,y.quick=y,m&&(typeof m=="object"&&o(m,d),y.state=function(){return o(d,{})}),y}n&&n.exports?n.exports=a:s&&s.amd?s(function(){return a}):this.tychei=a})(Ma,e,!1)}),Fo=ko(function(e){(function(t,n){var s=this,i=256,o=6,a=52,c="random",h=n.pow(i,o),d=n.pow(2,a),m=d*2,y=i-1,b;function w(F,_,B){var $=[];_=_==!0?{entropy:!0}:_||{};var H=N(A(_.entropy?[F,D(t)]:F==null?E():F,3),$),q=new L($),J=function(){for(var re=q.g(o),ce=h,ue=0;re<d;)re=(re+ue)*i,ce*=i,ue=q.g(1);for(;re>=m;)re/=2,ce/=2,ue>>>=1;return(re+ue)/ce};return J.int32=function(){return q.g(4)|0},J.quick=function(){return q.g(4)/4294967296},J.double=J,N(D(q.S),t),(_.pass||B||function(re,ce,ue,he){return he&&(he.S&&T(he,q),re.state=function(){return T(q,{})}),ue?(n[c]=re,ce):re})(J,H,"global"in _?_.global:this==n,_.state)}n["seed"+c]=w;function L(F){var _,B=F.length,$=this,H=0,q=$.i=$.j=0,J=$.S=[];for(B||(F=[B++]);H<i;)J[H]=H++;for(H=0;H<i;H++)J[H]=J[q=y&q+F[H%B]+(_=J[H])],J[q]=_;($.g=function(re){for(var ce,ue=0,he=$.i,de=$.j,le=$.S;re--;)ce=le[he=y&he+1],ue=ue*i+le[y&(le[he]=le[de=y&de+ce])+(le[de]=ce)];return $.i=he,$.j=de,ue})(i)}function T(F,_){return _.i=F.i,_.j=F.j,_.S=F.S.slice(),_}function A(F,_){var B=[],$=typeof F,H;if(_&&$=="object")for(H in F)try{B.push(A(F[H],_-1))}catch(q){}return B.length?B:$=="string"?F:F+"\0"}function N(F,_){for(var B=F+"",$,H=0;H<B.length;)_[y&H]=y&($^=_[y&H]*19)+B.charCodeAt(H++);return D(_)}function E(){try{var F;return b&&(F=b.randomBytes)?F=F(i):(F=new Uint8Array(i),(s.crypto||s.msCrypto).getRandomValues(F)),D(F)}catch($){var _=s.navigator,B=_&&_.plugins;return[+new Date,s,B,s.screen,D(t)]}}function D(F){return String.fromCharCode.apply(0,F)}if(N(n.random(),t),e.exports){e.exports=w;try{b=require("crypto")}catch(F){}}})([],Math)});Fo.alea=w$,Fo.xor128=L$,Fo.xorwow=S$,Fo.xorshift7=I$,Fo.xor4096=x$,Fo.tychei=T$;var A$=Fo,Pa=A$.alea;class $b{constructor(e,t,n,s,i){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=s,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);const o=i||Math.random();this.random=Pa(o.toString())}nextValue(){if(!isNaN(this.nextVal)){const s=this.nextVal;return this.nextVal=NaN,s}let e,t,n=!1;for(;!n;){let s,i,o;do s=2*this.random()-1,i=2*this.random()-1,o=s*s+i*i;while(o>=1||o===0);const a=Math.sqrt(-2*Math.log(o)/o);e=this.mean+this.stdDev*s*a,t=this.mean+this.stdDev*i*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 this.dtype==null||this.dtype==="float32"?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}}class v${constructor(e,t,n,s){this.alpha=e,this.beta=1/t,this.dtype=n;const i=s||Math.random();this.randu=Pa(i.toString()),this.randn=new $b(0,1,n,!1,this.randu()),e<1?this.d=e+2/3:this.d=e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,s,i,o;for(;;){do s=this.randn.nextValue(),o=1+this.c*s;while(o<=0);if(o*=o*o,e=s*s,t=1-.331*e*e,n=.5*e+this.d*(1-o+Math.log(o)),i=this.randu(),i<t||Math.log(i)<n)break}return o=1/this.beta*this.d*o,this.alpha<1&&(o*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(o)}convertValue(e){return this.dtype==="float32"?e:Math.round(e)}}class N${constructor(e=0,t=1,n,s){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=n,s==null&&(s=Math.random()),typeof s=="number"&&(s=s.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=Pa(s)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}function GZ(e){const t=e.length,n=O$(e),s=R$(e),i=t/6*(Math.pow(n,2)+.25*Math.pow(s-3,2)),o=5.991;if(i>o)throw new Error(`Invalid p-value for JB: ${i}`)}function VZ(e,t,n,s){s==null&&(s=Od());const i=Ub(e);cb(i,t,s),cb(C$(e,i),n,s)}function Ub(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t/e.length}function C$(e,t){let n=0;for(let s=0;s<e.length;s++){const i=e[s]-t;n+=i*i}return Math.sqrt(n/e.length)}function R$(e){const t=Ub(e),n=e.length;let s=0,i=0;for(let o=0;o<n;o++){const a=e[o]-t;s+=Math.pow(a,2),i+=Math.pow(a,4)}return 1/n*i/Math.pow(1/n*s,2)}function O$(e){const t=Ub(e),n=e.length;let s=0,i=0;for(let o=0;o<n;o++){const a=e[o]-t;s+=Math.pow(a,2),i+=Math.pow(a,3)}return 1/n*i/Math.pow(1/(n-1)*s,3/2)}function E$(e,t,n=1,s="float32",i){if(n==null&&(n=1),s==null&&(s="float32"),s!=="float32"&&s!=="int32")throw new Error(`Unsupported data type ${s}`);const o=new v$(t,n,s,i),a=Ze(e,s);for(let c=0;c<a.values.length;c++)a.values[c]=o.nextValue();return a.toTensor()}const D$=P({randomGamma_:E$});function k$(e,t=0,n=1,s,i){if(s!=null&&s==="bool")throw new Error(`Unsupported data type ${s}`);const o=new $b(t,n,s,!1,i),a=Ze(e,s);for(let c=0;c<a.values.length;c++)a.values[c]=o.nextValue();return a.toTensor()}const Bb=P({randomNormal_:k$});function F$(e,t=0,n=1,s="float32",i){const o=Ze(e,s),a=new N$(t,n,null,i);for(let c=0;c<o.values.length;c++)o.values[c]=a.nextValue();return o.toTensor()}const _o=P({randomUniform_:F$});function ss(e,t){yo(e);const n=xi(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");const s=null;return Nr(e,s,n,t)}function ph(e,t,n=1,s="float32"){if(n===0)throw new Error("Cannot have a step of zero");const i=()=>{const a=e===t,c=e<t&&n<0,h=t<e&&n>1;if(a||c||h)return ct([0],s);const d=Math.abs(Math.ceil((t-e)/n)),m=Aa(d,s);t<e&&n===1&&(n=-1),m[0]=e;for(let y=1;y<m.length;y++)m[y]=m[y-1]+n;return ss(m,s)},o={start:e,stop:t,step:n,dtype:s};return V.runKernelFunc(i,{},null,Rx,o)}function _$(e){const t=W(e,"x","reciprocal"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.reciprocal(t);return i([t]),o},n,null,vl)}const Mb=P({reciprocal_:_$});function W$(e){const t=W(e,"x","relu"),n=(i,o)=>(o([t]),t.dtype==="bool"?ve(t,"int32"):i.relu(t)),s={x:t};return V.runKernelFunc(n,s,null,hy)}const Oi=P({relu_:W$});function $$(e){const t=W(e,"x","relu6"),n=(i,o)=>(o([t]),t.dtype==="bool"?ve(t,"int32"):i.relu6(t)),s={x:t};return V.runKernelFunc(n,s,null,py)}const Pb=P({relu6_:$$});function U$(e,t){const n=W(e,"x","reverse"),s=a=>{const c=gt(t,n.shape);if(n.rank===0)return Rr(n);const h=a.reverse(n,c);return K(h,n.shape)},i={x:n},o={dims:t};return V.runKernelFunc(s,i,null,my,o)}const Is=P({reverse_:U$});function B$(e){const t=W(e,"x","reverse");return k(t.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),Is(t,0)}const M$=P({reverse1d_:B$});function P$(e,t){const n=W(e,"x","reverse");return k(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),Is(n,t)}const z$=P({reverse2d_:P$});function G$(e,t){const n=W(e,"x","reverse");return k(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),Is(n,t)}const V$=P({reverse3d_:G$});function Y$(e,t){const n=W(e,"x","reverse");return k(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),Is(n,t)}const H$=P({reverse4d_:Y$});function q$(e){const t=W(e,"x","round"),n={x:t};return V.runKernelFunc(s=>s.round(t),n,null,Cl)}const zb=P({round_:q$});function j$(e){const t=W(e,"x","rsqrt"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.rsqrt(t);return i([t]),o},n,null,Rl)}const Xd=P({rsqrt_:j$});function K$(e){const t=W(e,"x","selu"),n=(i,o)=>{const a=i.selu(t);return o([t]),a},s={x:t};return V.runKernelFunc(n,s,null,Ol)}const Jd=P({selu_:K$});function X$(e,t,n,s,i,o=[1,1],a="NHWC"){const c=W(e,"x","separableConv2d"),h=W(t,"depthwiseFilter","separableConv2d"),d=W(n,"pointwiseFilter","separableConv2d");let m=c,y=!1;if(c.rank===3&&(y=!0,m=K(c,[1,c.shape[0],c.shape[1],c.shape[2]])),a==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");k(m.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${m.rank}.`),k(h.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${h.rank}.`),k(d.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${h.rank}.`),k(d.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${d.shape[0]}.`),k(d.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${d.shape[1]}.`);const b=h.shape[2],w=h.shape[3];k(d.shape[2]===b*w,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${b*w}, but got ${d.shape[2]}.`);const L=Co(m,h,s,i,a,o),T=1,A=Xi(L,d,T,"valid",a);return y?K(A,[A.shape[1],A.shape[2],A.shape[3]]):A}const Gb=P({separableConv2d_:X$});async function J$(e,t){const n=W(e,"x","setdiff1d"),s=W(t,"y","setdiff1d");k(n.dtype===s.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${s.dtype}).`),k(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),k(s.rank===1,()=>`y should be 1D tensor, but got y (${s.shape}).`);const i=await n.data(),o=await s.data(),a=new Set(o);let c=0;for(let m=0;m<i.length;m++)a.has(i[m])||c++;const h=new vr([c],n.dtype),d=new vr([c],"int32");for(let m=0,y=0;m<i.length;m++)a.has(i[m])||(h.values[y]=i[m],d.values[y]=m,y++);return[h.toTensor(),d.toTensor()]}const eA=J$;function Z$(e){const t=W(e,"x","sign"),n={x:t};return V.runKernelFunc(s=>s.sign(t),n,null,Dl)}const Vb=P({sign_:Z$});function Q$(e){const t=W(e,"x","sin"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.sin(t);return i([t]),o},n,null,La)}const Zd=P({sin_:Q$});function eU(e){const t=W(e,"x","sinh"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.sinh(t);return i([t]),o},n,null,El)}const Qd=P({sinh_:eU});function tU(e,t,n){const s=W(e,"x","slice1d");return k(s.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`),nt(s,[t],[n])}const ep=P({slice1d_:tU});function nU(e,t,n){const s=W(e,"x","slice2d");return k(s.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`),nt(s,t,n)}const Yb=P({slice2d_:nU});function sU(e,t,n){const s=W(e,"x","slice3d");return k(s.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`),nt(s,t,n)}const tp=P({slice3d_:sU});function iU(e,t,n){const s=W(e,"x","slice4d");return k(s.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`),nt(s,t,n)}const mh=P({slice4d_:iU});function rU(e,t=-1){const n=W(e,"logits","softmax","float32");if(t===-1&&(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 s={logits:n},i={dim:t};return V.runKernelFunc((o,a)=>{const c=o.softmax(n,t);return a([c]),c},s,null,by,i)}const Wo=P({softmax_:rU});function oU(e){k(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);const t={input:e};return V.runKernelFunc(n=>{const s=e.shape[e.shape.length-1],i=e.size/s,o=e.as2D(i,s),a=n.fft(o);return a.reshape(e.shape)},t,null,Vg)}const fh=P({fft_:oU});function aU(e){k(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);const t={input:e};return V.runKernelFunc(n=>{const s=e.shape[e.shape.length-1],i=e.size/s,o=K(e,[i,s]),a=n.ifft(o);return K(a,e.shape)},t,null,jg)}const za=P({ifft_:aU});function cU(e){const t=e.shape[e.shape.length-1],n=e.size/t;let s;if(t<=2){const i=K(e,[n,t]);s=za(i)}else{const i=[n,2*(t-1)],o=K(Do(e),[n,t]),a=K($a(e),[n,t]),c=Is(nt(o,[0,1],[n,t-2]),1),h=X(Is(nt(a,[0,1],[n,t-2]),1),Ne(-1)),d=Pt([o,c],1),m=Pt([a,h],1),y=K(Ti(d,m),[i[0],i[1]]);s=za(y)}if(s=Do(s),e.rank===3&&e.shape[0]!==0){const i=s,o=e.shape[0];s=K(s,[o,s.shape[0]/o,s.shape[1]]),i.dispose()}return s}const np=P({irfft_:cU});function tA(e,t,n=0){let s=[];if(typeof t=="number")k(e.shape[n]%t===0,()=>"Number of splits must evenly divide the axis."),s=new Array(t).fill(e.shape[n]/t);else{const i=t.reduce((a,c)=>(c===-1&&(a+=1),a),0);k(i<=1,()=>"There should be only one negative value in split array.");const o=t.indexOf(-1);if(o!==-1){const a=t.reduce((c,h)=>h>0?c+h:c);t[o]=e.shape[n]-a}k(e.shape[n]===t.reduce((a,c)=>a+c),()=>"The sum of sizes must match the size of the axis dimension."),s=t}return s}function lU(e,t,n=0){const s=W(e,"x","split"),i=(c,h)=>{const d=gt(n,s.shape)[0],m=tA(s,t,d);return c.split(s,m,d)},o={x:s},a={numOrSizeSplits:t,axis:n};return V.runKernelFunc(i,o,null,yy,a)}const is=P({split_:lU});function hU(e,t){k(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let n=e.shape[e.shape.length-1];const s=e.size/n;let i;if(t!=null&&t<n){const L=e.shape.map(A=>0),T=e.shape.map(A=>A);T[e.shape.length-1]=t,i=nt(e,L,T),n=t}else if(t!=null&&t>n){const L=e.shape.map(T=>T);L[e.shape.length-1]=t-n,i=Pt([e,ct(L)],e.shape.length-1),n=t}else i=e;const o=Qe(i),a=K(Ti(i,o),[s,n]),c=fh(a),h=Math.floor(n/2)+1,d=Do(c),m=$a(c),y=is(d,[h,n-h],d.shape.length-1),b=is(m,[h,n-h],m.shape.length-1),w=i.shape.slice();return w[i.shape.length-1]=h,K(Ti(y[0],b[0]),w)}const gh=P({rfft_:hU});function uU(e){const t=W(e,"x","sqrt"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.sqrt(t);return i([t]),o},n,null,_l)}const Ln=P({sqrt_:uU});function dU(e,t){let n=W(e,"a","squaredDifference"),s=W(t,"b","squaredDifference");[n,s]=Mt(n,s),tt(n.shape,s.shape);const i=(c,h)=>{const d=c.squaredDifference(n,s);return h([n,s]),d},o={a:n,b:s},a={};return V.runKernelFunc(i,o,null,Sa,a)}const yh=P({squaredDifference_:dU});function pU(e,t){const n=W(e,"x","squeeze");return K(n,Ir(n.shape,t).newShape)}const _r=P({squeeze_:pU});function mU(e,t=0){const n=jl(e,"tensors","stack");if(k(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length===1)return qn(n[0],t);const s=n[0].rank,i=n[0].shape,o=n[0].dtype;k(t<=s,()=>"Axis must be <= rank of the tensor"),n.forEach(c=>{pt(i,c.shape,"All tensors passed to stack must have matching shapes"),k(o===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});const a=n.map(c=>qn(c,t));return Pt(a,t)}const rs=P({stack_:mU});function fU(e,t=0){const n=W(e,"x","step"),s={x:n},i={alpha:t};return V.runKernelFunc(o=>o.step(n,t),s,null,Bl,i)}const Ga=P({step_:fU});function gU(e,t,n,s,i=0,o=0,a=0,c=0,h=0){let d=W(e,"x","stridedSlice");const m=w=>{s==null&&(s=new Array(t.length));const L=Nd(a);if(L.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(a!==0&&c!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(a!==0&&h!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");const T=d.rank-t.length,A=Nd(c),N=d.shape.slice();A.forEach(J=>{t[J]=0,n[J]=1,N.splice(J,0,1)}),d=K(d,N);const{begin:E,end:D,strides:F}=IT(d.shape,L,T,t,n,s,i,o,a);t=E,n=D,s=F;const _=Nd(h);_.forEach(J=>{n[J]=t[J]+1,s[J]=1});const B=Cd(t,n,s),$=B.filter((J,re)=>_.indexOf(re)===-1),H=s.every(J=>J===1);if(H)return K(nt(d,t,B),$);const q=w.stridedSlice(d,t,n,s);return K(q,$)},y={x:d},b={begin:t,end:n,strides:s,beginMask:i,endMask:o,ellipsisMask:a,newAxisMask:c,shrinkAxisMask:h};return V.runKernelFunc(m,y,null,Fx,b)}const Hb=P({stridedSlice_:gU});function yU(e){const t=W(e,"x","tan"),n={x:t};return V.runKernelFunc((s,i)=>{const o=s.tan(t);return i([t]),o},n,null,Ia)}const qb=P({tan_:yU});function Wr(e,t,n){if(yo(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");const s=xi(e,n);if(s.length!==2&&s.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Nr(e,t,s,n)}function Va(e,t,n){if(yo(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");const s=xi(e,n);if(s.length!==4&&s.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Nr(e,t,s,n)}function bU(e,t,n){if(yo(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");const s=xi(e,n);if(s.length!==5&&s.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Nr(e,t,s,n)}function wU(e,t,n){if(yo(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");const s=xi(e,n);if(s.length!==6&&s.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(s.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||s,Nr(e,t,s,n)}function LU(e,t=1,n=!0){const s=W(e,"x","topk");if(s.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");const i=s.shape[s.shape.length-1];if(t>i)throw new Error(`'k' passed to topk() must be <= the last dimension (${i}) but got ${t}`);const o={x:s},a={k:t,sorted:n},[c,h]=V.runKernelFunc(d=>d.topk(s,t,n),o,null,_x,a);return{values:c,indices:h}}const jb=P({topk_:LU});function SU(e,t=0,n=1,s,i){if(s!=null&&s==="bool")throw new Error("Unsupported data type $ { dtype }");const o=new $b(t,n,s,!0,i),a=Ze(e,s);for(let c=0;c<a.values.length;c++)a.values[c]=o.nextValue();return a.toTensor()}const bh=P({truncatedNormal_:SU});function IU(e,t=0){const n=W(e,"x","unique",null);k(n.rank>0,()=>"The input tensor must be at least 1D");const s={x:n},i={axis:t},[o,a]=V.runKernel(cd,s,i);return{values:o,indices:a}}const sp=P({unique_:IU});function xU(e,t,n){const s=W(e,"x","unsortedSegmentSum"),i=W(t,"segmentIds","unsortedSegmentSum","int32");k(Bt(n),()=>"numSegments must be of dtype int");const o={x:s,segmentIds:i},a={numSegments:n},c=(h,d)=>{const m=h.unsortedSegmentSum(s,i,n);return d([i]),m};return V.runKernelFunc(c,o,null,Sy,a)}const Kb=P({unsortedSegmentSum_:xU});function TU(e,t=0){const n=W(e,"x","unstack");k(t>=-n.shape.length&&t<n.shape.length,()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`),t<0&&(t+=n.shape.length);const s={value:n},i={axis:t},o=a=>a.unstack(n,t);return V.runKernelFunc(o,s,null,Ly,i)}const Ei=P({unstack_:TU});function nA(e,t=!0,n,s){return V.makeVariable(e,t,n,s)}function ip(e,t){const n=[];for(let o=0;o<t.length;o++)t[o]&&n.push(o);const s=Ze(e,"int32"),i=Ze([n.length,e.length],"int32");for(let o=0;o<n.length;o++){const a=s.indexToLoc(n[o]),c=o*e.length;i.values.set(a,c)}return i.toTensor()}async function AU(e){const t=W(e,"condition","whereAsync","bool"),n=await t.data(),s=ip(t.shape,n);return e!==t&&t.dispose(),s}const Xb=AU;async function vU(e,t,n){const s=W(e,"tensor","boolMask"),i=W(t,"mask","boolMask","bool"),o=n==null?0:n,a=i.rank,c=s.shape;k(a>0,()=>"mask cannot be scalar"),pt(c.slice(o,o+a),i.shape,"mask's shape must match the first K dimensions of tensor's shape,");let h=1;for(let T=o;T<o+a;T++)h*=c[T];const d=c.slice(0,o).concat([h],c.slice(o+a)),m=K(s,d),y=K(i,[-1]),b=await Xb(y),w=_r(b,[1]),L=Wa(m,w,o);return e!==s&&s.dispose(),t!==i&&i.dispose(),w.dispose(),m.dispose(),y.dispose(),b.dispose(),L}const NU=vU;function CU(e,t){nn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","notEqualStrict"),s=W(t,"b","notEqualStrict");return pt(n.shape,s.shape,"Error in notEqualStrict: "),Fr(n,s)}function RU(e,t){nn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","lessStrict"),s=W(t,"b","lessStrict");return pt(n.shape,s.shape,"Error in lessStrict: "),ch(n,s)}function OU(e,t){nn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","equalStrict"),s=W(t,"b","equalStrict");return pt(n.shape,s.shape,"Error in equalStrict: "),ti(n,s)}function EU(e,t){nn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","lessEqualStrict"),s=W(t,"b","lessEqualStrict");return pt(n.shape,s.shape,"Error in lessEqualStrict: "),kr(n,s)}function DU(e,t){nn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","greaterStrict"),s=W(t,"b","greaterStrict");return pt(n.shape,s.shape,"Error in greaterStrict: "),Ss(n,s)}function kU(e,t){nn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","greaterEqualStrict"),s=W(t,"b","greaterEqualStrict");return pt(n.shape,s.shape,"Error in greaterEqualStrict: "),Ji(n,s)}const sA=P({equalStrict_:OU}),iA=P({greaterEqualStrict_:kU}),rA=P({greaterStrict_:DU}),oA=P({lessEqualStrict_:EU}),aA=P({lessStrict_:RU}),cA=P({notEqualStrict_:CU});function FU(e,t){nn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","addStrict"),s=W(t,"b","addStrict");return pt(n.shape,s.shape,"Error in addStrict: "),be(n,s)}function _U(e,t){nn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","subStrict"),s=W(t,"b","subStrict");return pt(n.shape,s.shape,"Error in subStrict: "),Ce(n,s)}function WU(e,t){return nn("strict variants of ops have been deprecated and will be removed in future"),pt(e.shape,t.shape,"Error in powStrict: "),si(e,t)}function $U(e,t){nn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","mul"),s=W(t,"b","mul");return pt(n.shape,s.shape,"Error in multiplyStrict: "),X(n,s)}function UU(e,t){nn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","div"),s=W(t,"b","div");return pt(n.shape,s.shape,"Error in divideStrict: "),_e(n,s)}function BU(e,t){nn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","modStrict"),s=W(t,"b","modStrict");return pt(n.shape,s.shape,"Error in modStrict: "),qd(n,s)}function MU(e,t){nn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","minimumStrict"),s=W(t,"b","minimumStrict");return pt(n.shape,s.shape,"Error in minimumStrict: "),Eo(n,s)}function PU(e,t){nn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","maximumStrict"),s=W(t,"b","maximumStrict");return pt(n.shape,s.shape,"Error in maximumStrict: "),Ws(n,s)}function zU(e,t){nn("strict variants of ops have been deprecated and will be removed in future");const n=W(e,"a","squaredDifferenceStrict"),s=W(t,"b","squaredDifferenceStrict");return pt(n.shape,s.shape,"Error in squaredDifferenceStrict: "),yh(n,s)}const lA=P({addStrict_:FU}),hA=P({divStrict_:UU}),uA=P({maximumStrict_:PU}),dA=P({minimumStrict_:MU}),pA=P({modStrict_:BU}),mA=P({mulStrict_:$U}),fA=P({powStrict_:WU}),gA=P({squaredDifferenceStrict_:zU}),yA=P({subStrict_:_U});function GU(e,t="euclidean",n=null,s=!1){e=W(e,"x","norm");const i=bA(e,t,n);let o=i.shape;if(s){const a=gt(n,e.shape);o=On(i.shape,a)}return K(i,o)}function bA(e,t,n=null){if(e.rank===0)return sn(e);if(e.rank!==1&&n===null)return bA(K(e,[-1]),t,n);if(e.rank===1||typeof n=="number"||Array.isArray(n)&&n.length===1){if(t===1)return Ue(sn(e),n);if(t===Infinity)return jn(sn(e),n);if(t===-Infinity)return Ba(sn(e),n);if(t==="euclidean"||t===2)return Ln(Ue(si(sn(e),Ne(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&n.length===2){if(t===1)return jn(Ue(sn(e),n[0]),n[1]-1);if(t===Infinity)return jn(Ue(sn(e),n[1]),n[0]);if(t===-Infinity)return Ba(Ue(sn(e),n[1]),n[0]);if(t==="fro"||t==="euclidean")return Ln(Ue(wt(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const rp=P({norm_:GU});function VU(e,t,n,s,i=!0){const o=W(e,"v","movingAverage"),a=W(t,"x","movingAverage"),c=W(n,"decay","movingAverage");jx(o,a),k(ot(o.shape,a.shape),()=>"Shape mismatch in v and x");const h=Ne(1),d=Ce(h,c);let m=X(Ce(a,o),d);if(i){k(s!=null,()=>"When using zeroDebias: true, step is required.");const y=W(s,"step","movingAverage");m=_e(m,Ce(h,si(c,y)))}return be(o,m)}const YU=P({movingAverage_:VU});function HU(e,t,n){const s=W(e,"indices","scatterND","int32"),i=W(t,"updates","scatterND");sb(i,s,n);const o=h=>h.scatterND(s,i,n),a={indices:s,updates:i},c={shape:n};return V.runKernelFunc(o,a,null,Dx,c)}const wA=P({scatterND_:HU});function qU(e,t,n,s){if(e.dtype!=="int32")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 i=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(!(t.rank===0||t.rank===1&&a===i))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${i}]`);if(t.dtype!==s.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function jU(e,t,n,s=0){const i=W(e,"sparseIndices","sparseToDense","int32"),o=W(t,"sparseValues","sparseToDense"),a=W(s,"defaultValue","sparseToDense",o.dtype);qU(i,o,n,a);const c={sparseIndices:i,sparseValues:o,defaultValue:a},h={outputShape:n};return V.runKernelFunc(d=>d.sparseToDense(i,o,n,a),c,null,kx,h)}const Jb=P({sparseToDense_:jU});function KU(e,t){const n=W(t,"indices","gatherND","int32"),s=W(e,"x","gatherND"),i=a=>a.gatherND(s,n),o={params:s,indices:n};return V.runKernelFunc(i,o,null,wx)}const LA=P({gatherND_:KU});function XU(e,t){if(t==null)return e.shape.slice();if(ot(e.shape,t))return t;if(e.shape.length===t.length){const n=[];for(let s=0;s<e.shape.length;s++)t[s]==null&&e.shape[s]!=null?n.push(e.shape[s]):n.push(t[s]);return n}return t}function JU(e,t,n,s){const i=W(e,"x","dropout");if(k(i.dtype==="float32",()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${i.dtype} tensor instead.`),k(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof Q?i.clone():i;const o=XU(i,n),a=1-t,c=_e(_a(be(_o(o,0,1,"float32",s),a)),a);return X(i,c)}const SA=P({dropout_:JU});function IA(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function Zb(e,t,n){const s=1-e%2,i=new Float32Array(e);for(let o=0;o<e;++o){const a=2*Math.PI*o/(e+s-1);i[o]=t-n*Math.cos(a)}return ss(i,"float32")}async function ZU(e,t,n=1){const s=W(e,"predictions","inTopK"),i=W(t,"targets","inTopK");k(s.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${s.rank}`),k(s.rank-1===i.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${s.rank} and targets rank ${i.rank}`),pt(s.shape.slice(0,s.shape.length-1),i.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const o=s.shape[s.shape.length-1];k(n>0&&n<=o,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${o}), but got ${n}`);const a=await s.data(),c=await i.data(),[h,d]=[a.length/o,o],m=bn("bool",h);for(let y=0;y<h;y++){const b=y*d,w=a.subarray(b,b+d),L=[];for(let T=0;T<w.length;T++)L.push({value:w[T],index:T});L.sort((T,A)=>A.value-T.value),m[y]=0;for(let T=0;T<n;T++)if(L[T].index===c[y]){m[y]=1;break}}return e!==s&&s.dispose(),t!==i&&i.dispose(),en(m,i.shape,"bool")}const QU=ZU;function eB(e,t,n,s,i,o="NHWC",a){let c=e;e.rank===3&&(c=K(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let h=t;h.rank===3&&(h=K(t,[1,t.shape[0],t.shape[1],t.shape[2]])),k(c.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${c.shape}.`),k(h.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${h.shape}.`),k(n.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);const d=o==="NHWC"?c.shape[3]:c.shape[1],m=o==="NHWC"?h.shape[3]:h.shape[1];k(d===n[2],()=>`Error in conv2dDerFilter: depth of input ${d}) must match input depth in filter (${n[2]}.`),k(m===n[3],()=>`Error in conv2dDerFilter: depth of dy (${m}) must match output depth for filter (${n[3]}).`),a!=null&&k(Bt(i),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${a} but got pad ${i}.`);const y=L=>{const T=1,A=th(o),N=vi(c.shape,n,s,T,i,a,!1,A);return L.conv2dDerFilter(c,h,N)},b={x:c,dy:h},w={strides:s,pad:i,dataFormat:o,dimRoundingMode:a};return V.runKernelFunc(y,b,null,cx,w)}const Qb=P({conv2DBackpropFilter_:eB});function op(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return X(e,Ga(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function ap(e,t){let n=t;const s=on(e.shape,t.shape);return s.length>0&&(n=Ue(n,s)),K(n,e.shape)}function cp(e,t,n){if(t==="linear")return e;if(t==="relu")return Oi(e);if(t==="elu")return Oo(e);if(t==="relu6")return Pb(e);if(t==="prelu")return dh(e,n);throw new Error(`Unknown fused activation ${t}.`)}const lp=(e,t)=>{const n=e>0;return!n||t==="linear"};function tB({x:e,filter:t,strides:n,pad:s,dataFormat:i="NHWC",dilations:o=[1,1],dimRoundingMode:a,bias:c,activation:h="linear",preluActivationWeights:d}){if(h=h||"linear",lp(V.state.gradientDepth,h)===!1){let _=Xi(e,t,n,s,i,o,a);return c!=null&&(_=be(_,c)),cp(_,h,d)}const m=W(e,"x","conv2d"),y=W(t,"filter","conv2d");let b=m,w=!1;m.rank===3&&(w=!0,b=K(m,[1,m.shape[0],m.shape[1],m.shape[2]])),k(b.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${b.rank}.`),k(y.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${y.rank}.`),a!=null&&k(Bt(s),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`),k(b.shape[3]===y.shape[2],()=>`Error in conv2d: depth of input (${b.shape[3]}) must match input depth for filter ${y.shape[2]}.`),k(rn(n,o),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),k(i==="NHWC",()=>`Error in conv2d: got dataFormat of ${i} but only NHWC is currently supported.`);const L=vi(b.shape,y.shape,n,o,s,a);let T;c!=null&&(T=W(c,"bias","fused conv2d"),[T]=Mt(T,m),tt(L.outShape,T.shape));let A;d!=null&&(A=W(d,"prelu weights","fused conv2d"));const N=(_,B)=>{const[$,H,q,J]=B,re=op(_,q,h);k(Or(o),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${o}'`);const ce=Ab(H.shape,re,$,n,s),ue=Qb(H,re,$.shape,n,s),he=[ce,ue];if(J!=null){const de=ap(J,re);he.push(de)}return he},E=_=>{const B=_.fusedConv2d({input:b,filter:y,convInfo:L,bias:T,activation:h,preluActivationWeights:A});return B},D={x:b,filter:y,bias:T,preluActivationWeights:A},F={strides:n,pad:s,dataFormat:i,dilations:o,dimRoundingMode:a,activation:h};if(c==null){const _=Ci((B,$,H)=>{let q=V.runKernelFunc(E,D,null,Ty,F);return H([$,B,q]),w&&(q=K(q,[q.shape[1],q.shape[2],q.shape[3]])),{value:q,gradFunc:N}});return _(b,y)}else{const _=Ci((B,$,H,q)=>{let J=V.runKernelFunc(E,D,null,Ty,F);return q([$,B,J,H]),w&&(J=K(J,[J.shape[1],J.shape[2],J.shape[3]])),{value:J,gradFunc:N}});return _(b,y,T)}}const ew=P({fusedConv2d_:tB});function nB(e,t,n,s){let i=e;e.rank===3&&(i=K(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let o=t;o.rank===3&&(o=K(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const a=h=>h.depthwiseConv2DDerFilter(i,o,s),c={x:i,dy:o};return V.runKernelFunc(a,c,null,px)}const xA=P({depthwiseConv2dNativeBackpropFilter_:nB});function sB(e,t,n,s){let i=t,o=!1;t.rank===3&&(o=!0,i=K(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const a=d=>d.depthwiseConv2DDerInput(i,n,s),c={dy:i},h=V.runKernelFunc(a,c,null,mx);return o?K(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const TA=P({depthwiseConv2dNativeBackpropInput_:sB});function iB({x:e,filter:t,strides:n,pad:s,dataFormat:i="NHWC",dilations:o=[1,1],dimRoundingMode:a,bias:c,activation:h="linear",preluActivationWeights:d}){if(lp(V.state.gradientDepth,h)===!1){let _=Co(e,t,n,s,i,o,a);return c!=null&&(_=be(_,c)),cp(_,h,d)}const m=W(e,"x","depthwiseConv2d"),y=W(t,"filter","depthwiseConv2d");let b=m,w=!1;m.rank===3&&(w=!0,b=K(m,[1,m.shape[0],m.shape[1],m.shape[2]])),k(b.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${b.rank}.`),k(y.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${y.rank}.`),k(b.shape[3]===y.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${b.shape[3]}) must match the inChannels dimension in filter ${y.shape[2]}.`),o==null&&(o=[1,1]),k(rn(n,o),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),a!=null&&k(Bt(s),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${a} but got pad ${s}.`);const L=vi(b.shape,y.shape,n,o,s,a,!0);let T;c!=null&&(T=W(c,"bias","fused conv2d"),[T]=Mt(T,m),tt(L.outShape,T.shape));let A;d!=null&&(A=W(d,"prelu weights","fused depthwiseConv2d"));const N=(_,B)=>{k(Or(o),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`);const[$,H,q,J]=B,re=op(_,q,h),ce=TA(H.shape,re,$,L),ue=xA(H,re,$.shape,L);if(J!=null){const he=ap(T,re);return[ce,ue,he]}return[ce,ue]},E=_=>{const B=_.fusedDepthwiseConv2D({input:b,filter:y,convInfo:L,bias:T,activation:h,preluActivationWeights:A});return B},D={x:b,filter:y,bias:T,preluActivationWeights:A},F={strides:n,pad:s,dataFormat:i,dilations:o,dimRoundingMode:a,activation:h};if(c==null){const _=Ci((B,$,H)=>{let q=V.runKernelFunc(E,D,null,Ay,F);return H([$,B,q]),w&&(q=K(q,[q.shape[1],q.shape[2],q.shape[3]])),{value:q,gradFunc:N}});return _(b,y)}else{const _=Ci((B,$,H,q)=>{let J=V.runKernelFunc(E,D,null,Ay,F);return q([$,B,J,H]),w&&(J=K(J,[J.shape[1],J.shape[2],J.shape[3]])),{value:J,gradFunc:N}});return _(b,y,T)}}const AA=P({fusedDepthwiseConv2d_:iB});function rB({a:e,b:t,transposeA:n=!1,transposeB:s=!1,bias:i,activation:o="linear",preluActivationWeights:a}){if(lp(V.state.gradientDepth,o)===!1){let J=at(e,t,n,s);return i!=null&&(J=be(J,i)),cp(J,o,a)}let c=W(e,"a","fused matMul"),h=W(t,"b","fused matMul");[c,h]=Mt(c,h);const d=n?c.shape[c.rank-2]:c.shape[c.rank-1],m=s?h.shape[h.rank-1]:h.shape[h.rank-2],y=n?c.shape[c.rank-1]:c.shape[c.rank-2],b=s?h.shape[h.rank-2]:h.shape[h.rank-1],w=c.shape.slice(0,-2),L=h.shape.slice(0,-2),T=we(w),A=we(L);k(c.rank>=2&&h.rank>=2&&c.rank===h.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${c.rank} and ${h.rank}.`),k(ot(w,L),()=>`Error in fused matMul: outer dimensions (${w}) and (${L}) of Tensors with shapes ${c.shape} and ${h.shape} must match.`),k(d===m,()=>`Error in fused matMul: inner shapes (${d}) and (${m}) of Tensors with shapes ${c.shape} and ${h.shape} and transposeA=${n} and transposeB=${s} must match.`);const N=c.shape.slice(0,-2).concat([y,b]),E=n?K(c,[T,d,y]):K(c,[T,y,d]),D=s?K(h,[A,b,m]):K(h,[A,m,b]);let F;i!=null&&(F=W(i,"bias","fused matMul"),[F]=Mt(F,c),tt(N,F.shape));let _;a!=null&&(_=W(a,"prelu weights","fused matMul"));const B=(J,re)=>{const[ce,ue,he,de]=re,le=op(K(J,he.shape),he,o);let ye,pe;if(!n&&!s?(ye=at(le,ue,!1,!0),pe=at(ce,le,!0,!1)):!n&&s?(ye=at(le,ue,!1,!1),pe=at(le,ce,!0,!1)):n&&!s?(ye=at(ue,le,!1,!0),pe=at(ce,le,!1,!1)):(ye=at(ue,le,!0,!0),pe=at(le,ce,!0,!0)),i!=null){const Ie=ap(de,le);return[ye,pe,Ie]}else return[ye,pe]},$=J=>{const re=J.fusedBatchMatMul({a:E,b:D,transposeA:n,transposeB:s,bias:F,activation:o,preluActivationWeights:_});return re},H={a:E,b:D,bias:F,preluActivationWeights:_},q={transposeA:n,transposeB:s,activation:o};if(i==null){const J=Ci((re,ce,ue)=>{const he=V.runKernelFunc($,H,null,xy,q);return ue([re,ce,he]),{value:K(he,N),gradFunc:B}});return J(E,D)}else{const J=Ci((re,ce,ue,he)=>{const de=V.runKernelFunc($,H,null,xy,q);return he([re,ce,de,ue]),{value:K(de,N),gradFunc:B}});return J(E,D,F)}}const hp=P({fusedMatMul_:rB});var oB=Object.freeze({__proto__:null,conv2d:ew,depthwiseConv2d:AA,matMul:hp});function aB(e){return Zb(e,.54,.46)}const cB=P({hammingWindow_:aB});function lB(e){return Zb(e,.5,.5)}const vA=P({hannWindow_:lB});function hB(e,t,n,s=!1,i=0){let o=0;const a=[];for(;o+t<=e.size;)a.push(nt(e,o,t)),o+=n;if(s)for(;o<e.size;){const c=o+t-e.size,h=Pt([nt(e,o,t-c),oh([c],i)]);a.push(h),o+=n}return a.length===0?Wr([],[0,t]):K(Pt(a),[a.length,t])}const NA=P({frame_:hB});function uB(e,t,n,s,i=vA){s==null&&(s=IA(t));const o=NA(e,t,n),a=X(o,i(t)),c=[];for(let h=0;h<o.shape[0];h++)c.push(gh(nt(a,[h,0],[1,t]),s));return Pt(c)}const dB=P({stft_:uB});function pB(e,t,n,s,i,o){const a=W(e,"image","cropAndResize"),c=W(t,"boxes","cropAndResize","float32"),h=W(n,"boxInd","cropAndResize","int32");i=i||"bilinear",o=o||0;const d=c.shape[0];k(a.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${a.rank}.`),k(c.rank===2&&c.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${d},4] but had shape ${c.shape}.`),k(h.rank===1&&h.shape[0]===d,()=>`Error in cropAndResize: boxInd must be have size [${d}] but had shape ${c.shape}.`),k(s.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`),k(s[0]>=1&&s[1]>=1,()=>`cropSize must be atleast [1,1], but was ${s}`),k(i==="bilinear"||i==="nearest",()=>`method must be bilinear or nearest, but was ${i}`);const m=L=>L.cropAndResize(a,c,h,s,i,o),y={image:a,boxes:c,boxInd:h},b={method:i,extrapolationValue:o,cropSize:s},w=V.runKernelFunc(m,y,null,ux,b);return w}const mB=P({cropAndResize_:pB});function fB(e){const t=W(e,"image","flipLeftRight","float32");k(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);const n={image:t},s=V.runKernel(Ju,n,{});return s}const gB=P({flipLeftRight_:fB});function yB(e,t,n=0,s=.5){const i=W(e,"image","rotateWithOffset","float32");k(i.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${i.rank}.`);const o={image:i},a={radians:t,fillValue:n,center:s},c=V.runKernel(hd,o,a);return c}const bB=P({rotateWithOffset_:yB});function Ya(e,t,n,s,i,o){s==null&&(s=.5),i==null&&(i=Number.NEGATIVE_INFINITY),o==null&&(o=0);const a=e.shape[0];return n=Math.min(n,a),k(0<=s&&s<=1,()=>`iouThreshold must be in [0, 1], but was '${s}'`),k(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),k(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),k(t.rank===1,()=>"scores must be a 1D tensor"),k(t.shape[0]===a,()=>`scores has incompatible shape with boxes. Expected ${a}, but was ${t.shape[0]}`),k(0<=o&&o<=1,()=>`softNmsSigma must be in [0, 1], but was '${o}'`),{maxOutputSize:n,iouThreshold:s,scoreThreshold:i,softNmsSigma:o}}function wB(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY){const o=W(e,"boxes","nonMaxSuppression"),a=W(t,"scores","nonMaxSuppression"),c=Ya(o,a,n,s,i);n=c.maxOutputSize,s=c.iouThreshold,i=c.scoreThreshold;const h={maxOutputSize:n,iouThreshold:s,scoreThreshold:i};return V.runKernelFunc(d=>d.nonMaxSuppression(o,a,n,s,i),{boxes:o,scores:a},null,iy,h)}const LB=P({nonMaxSuppression_:wB});function SB(e,t,n){const s=IB(e,t,n),i=s<0?-(s+1):s;e.splice(i,0,t)}function IB(e,t,n){return TB(e,t,n||xB)}function xB(e,t){return e>t?1:e<t?-1:0}function TB(e,t,n){let s=0,i=e.length,o=0,a=!1;for(;s<i;){o=s+(i-s>>>1);const c=n(t,e[o]);c>0?s=o+1:(i=o,a=!c)}return a?s:-s-1}function up(e,t,n,s,i){return tw(e,t,n,s,i,0).selectedIndices}function dp(e,t,n,s,i,o){return tw(e,t,n,s,i,0,!1,o,!0)}function pp(e,t,n,s,i,o){return tw(e,t,n,s,i,o,!0)}function tw(e,t,n,s,i,o,a=!1,c=!1,h=!1){const d=[];for(let A=0;A<t.length;A++)t[A]>i&&d.push({score:t[A],boxIndex:A,suppressBeginIndex:0});d.sort(CA);const m=o>0?-.5/o:0,y=[],b=[];for(;y.length<n&&d.length>0;){const A=d.pop(),{score:N,boxIndex:E,suppressBeginIndex:D}=A;if(N<i)break;let F=!1;for(let _=y.length-1;_>=D;--_){const B=AB(e,E,y[_]);if(B>=s){F=!0;break}if(A.score=A.score*vB(s,m,B),A.score<=i)break}A.suppressBeginIndex=y.length,F||(A.score===N?(y.push(E),b.push(A.score)):A.score>i&&SB(d,A,CA))}const w=y.length,L=n-w;c&&L>0&&(y.push(...new Array(L).fill(0)),b.push(...new Array(L).fill(0)));const T={selectedIndices:ss(y,"int32")};return a&&(T.selectedScores=ss(b,"float32")),h&&(T.validOutputs=Ne(w,"int32")),T}function AB(e,t,n){const s=e.subarray(t*4,t*4+4),i=e.subarray(n*4,n*4+4),o=Math.min(s[0],s[2]),a=Math.min(s[1],s[3]),c=Math.max(s[0],s[2]),h=Math.max(s[1],s[3]),d=Math.min(i[0],i[2]),m=Math.min(i[1],i[3]),y=Math.max(i[0],i[2]),b=Math.max(i[1],i[3]),w=(c-o)*(h-a),L=(y-d)*(b-m);if(w<=0||L<=0)return 0;const T=Math.max(o,d),A=Math.max(a,m),N=Math.min(c,y),E=Math.min(h,b),D=Math.max(N-T,0)*Math.max(E-A,0);return D/(w+L-D)}function vB(e,t,n){const s=Math.exp(t*n*n);return n<=e?s:0}function CA(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function NB(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY){const o=W(e,"boxes","nonMaxSuppressionAsync"),a=W(t,"scores","nonMaxSuppressionAsync"),c=Ya(o,a,n,s,i);n=c.maxOutputSize,s=c.iouThreshold,i=c.scoreThreshold;const h=await Promise.all([o.data(),a.data()]),d=h[0],m=h[1],y=up(d,m,n,s,i);return o!==e&&o.dispose(),a!==t&&a.dispose(),y}const CB=NB;function RB(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY,o=0){const a=W(e,"boxes","nonMaxSuppression"),c=W(t,"scores","nonMaxSuppression"),h=Ya(a,c,n,s,i,o);n=h.maxOutputSize,s=h.iouThreshold,i=h.scoreThreshold,o=h.softNmsSigma;const d={boxes:a,scores:c},m={maxOutputSize:n,iouThreshold:s,scoreThreshold:i,softNmsSigma:o},y=V.runKernel(sd,d,m);return{selectedIndices:y[0],selectedScores:y[1]}}const OB=P({nonMaxSuppressionWithScore_:RB});async function EB(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY,o=0){const a=W(e,"boxes","nonMaxSuppressionAsync"),c=W(t,"scores","nonMaxSuppressionAsync"),h=Ya(a,c,n,s,i,o);n=h.maxOutputSize,s=h.iouThreshold,i=h.scoreThreshold,o=h.softNmsSigma;const d=await Promise.all([a.data(),c.data()]),m=d[0],y=d[1],b=pp(m,y,n,s,i,o);return a!==e&&a.dispose(),c!==t&&c.dispose(),b}const DB=EB;function kB(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY,o=!1){const a=W(e,"boxes","nonMaxSuppression"),c=W(t,"scores","nonMaxSuppression"),h=Ya(a,c,n,s,i,null),d=h.maxOutputSize,m=h.iouThreshold,y=h.scoreThreshold,b={boxes:a,scores:c},w={maxOutputSize:d,iouThreshold:m,scoreThreshold:y,padToMaxOutputSize:o},L=V.runKernel(nd,b,w);return{selectedIndices:L[0],validOutputs:L[1]}}const FB=P({nonMaxSuppressionPadded_:kB});async function _B(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY,o=!1){const a=W(e,"boxes","nonMaxSuppressionAsync"),c=W(t,"scores","nonMaxSuppressionAsync"),h=Ya(a,c,n,s,i,null),d=h.maxOutputSize,m=h.iouThreshold,y=h.scoreThreshold,[b,w]=await Promise.all([a.data(),c.data()]),L=dp(b,w,d,m,y,o);return a!==e&&a.dispose(),c!==t&&c.dispose(),L}const WB=_B;function $B(e,t,n=!1){const s=W(e,"images","resizeBilinear");k(s.rank===3||s.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${s.rank}.`),k(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`);let i=s,o=!1;s.rank===3&&(o=!0,i=K(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const[a,c]=t,h=(b,w)=>(w([i]),b.resizeBilinear(i,a,c,n)),d={images:i},m={alignCorners:n,size:t},y=V.runKernelFunc(h,d,null,dy,m);return o?K(y,[y.shape[1],y.shape[2],y.shape[3]]):y}const RA=P({resizeBilinear_:$B});function UB(e,t,n=!1){const s=W(e,"images","resizeNearestNeighbor");k(s.rank===3||s.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${s.rank}.`),k(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),k(s.dtype==="float32"||s.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype");let i=s,o=!1;s.rank===3&&(o=!0,i=K(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const[a,c]=t,h={images:i},d={alignCorners:n,size:t},m=(b,w)=>(w([i]),b.resizeNearestNeighbor(i,a,c,n)),y=V.runKernelFunc(m,h,null,uy,d);return o?K(y,[y.shape[1],y.shape[2],y.shape[3]]):y}const OA=P({resizeNearestNeighbor_:UB});function BB(e,t,n){k(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),k(n%1===0,()=>`bandPart(): numUpper must be an integer, got ${n}.`);const s=W(e,"a","bandPart");k(s.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${s.rank}.`);const i=s.shape,[o,a]=s.shape.slice(-2);if(!(t<=o))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${o}).`);if(!(n<=a))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${a}).`);t<0&&(t=o),n<0&&(n=a);const c=K(ph(0,o,1,"int32"),[-1,1]),h=ph(0,a,1,"int32"),d=Ce(c,h),m=$s(kr(d,Ne(+t,"int32")),Ji(d,Ne(-n,"int32"))),y=ct([o,a],s.dtype);return K(rs(Ei(K(s,[-1,o,a])).map(b=>_n(m,b,y))),i)}const MB=P({bandPart_:BB});function PB(e){let t;if(Array.isArray(e)){t=!1,k(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");const i=e[0].shape[0];for(let o=1;o<e.length;++o)k(e[o].shape[0]===i,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[o].shape[0]} vs. ${i})`)}else t=!0,e=is(e,e.shape[0],0).map(i=>_r(i,[0]));k(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);const n=[],s=e;for(let i=0;i<e.length;++i)n.push(V.tidy(()=>{let o=s[i];if(i>0)for(let a=0;a<i;++a){const c=X(Ue(X(n[a],o)),n[a]);o=Ce(o,c)}return _e(o,rp(o,"euclidean"))}));return t?rs(n,0):n}const zB=P({gramSchmidt_:PB});function GB(e,t=!1){if(k(e.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return EA(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce((h,d)=>h*d),s=Ei(K(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),i=[],o=[];s.forEach(h=>{const[d,m]=EA(h,t);i.push(d),o.push(m)});const a=K(rs(i,0),e.shape),c=K(rs(o,0),e.shape);return[a,c]}}function EA(e,t=!1){return V.tidy(()=>{k(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);const n=e.shape[0],s=e.shape[1];let i=Pd(n),o=Rr(e);const a=Wr([[1]],[1,1]);let c=Rr(a);const h=n>=s?s:n;for(let d=0;d<h;++d){const m=o,y=c,b=i;[c,o,i]=V.tidy(()=>{const w=nt(o,[d,d],[n-d,1]),L=rp(w),T=nt(o,[d,d],[1,1]),A=_n(Ss(T,0),Wr([[-1]]),Wr([[1]])),N=Ce(T,X(A,L)),E=_e(w,N);E.shape[0]===1?c=Rr(a):c=Pt([a,nt(E,[1,0],[E.shape[0]-1,E.shape[1]])],0);const D=zt(_e(at(A,N),L)),F=nt(o,[d,0],[n-d,s]),_=X(D,c),B=Me(c);if(d===0)o=Ce(F,at(_,at(B,F)));else{const q=Ce(F,at(_,at(B,F)));o=Pt([nt(o,[0,0],[d,s]),q],0)}const $=Me(_),H=nt(i,[0,d],[n,i.shape[1]-d]);if(d===0)i=Ce(H,at(at(H,c),$));else{const q=Ce(H,at(at(H,c),$));i=Pt([nt(i,[0,0],[n,d]),q],1)}return[c,o,i]}),He([m,y,b])}return!t&&n>s&&(i=nt(i,[0,0],[n,s]),o=nt(o,[0,0],[s,s])),[i,o]})}const VB=P({qr_:GB});(function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"})(r.Reduction||(r.Reduction={}));function YB(e,t,n=r.Reduction.SUM_BY_NONZERO_WEIGHTS){const s=W(e,"losses","computeWeightedLoss");let i=null;t!=null&&(i=W(t,"weights","computeWeightedLoss"));const o=i==null?s:X(s,i);if(n===r.Reduction.NONE)return o;if(n===r.Reduction.SUM)return Ue(o);if(n===r.Reduction.MEAN){if(i==null)return Gt(o);{const a=s.size/i.size,c=_e(Ue(o),Ue(i));return a>1?_e(c,Ne(a)):c}}if(n===r.Reduction.SUM_BY_NONZERO_WEIGHTS){if(i==null)return _e(Ue(o),Ne(s.size));{const a=X(i,ni(s.shape)),c=ve(Ue(Fr(a,Ne(0))),"float32");return _e(Ue(o),c)}}throw Error(`Unknown reduction: ${n}`)}const Zi=P({computeWeightedLoss_:YB});function HB(e,t,n,s=r.Reduction.SUM_BY_NONZERO_WEIGHTS){const i=W(e,"labels","absoluteDifference"),o=W(t,"predictions","absoluteDifference");let a=null;n!=null&&(a=W(n,"weights","absoluteDifference")),pt(i.shape,o.shape,"Error in absoluteDifference: ");const c=sn(Ce(i,o));return Zi(c,a,s)}const qB=P({absoluteDifference_:HB});function jB(e,t,n,s,i=r.Reduction.SUM_BY_NONZERO_WEIGHTS){const o=W(e,"labels","cosineDistance"),a=W(t,"predictions","cosineDistance");let c=null;s!=null&&(c=W(s,"weights","cosineDistance")),pt(o.shape,a.shape,"Error in cosineDistance: ");const h=Ne(1),d=Ce(h,Ue(X(o,a),n,!0));return Zi(d,c,i)}const KB=P({cosineDistance_:jB});function XB(e,t,n,s=r.Reduction.SUM_BY_NONZERO_WEIGHTS){let i=W(e,"labels","hingeLoss");const o=W(t,"predictions","hingeLoss");let a=null;n!=null&&(a=W(n,"weights","hingeLoss")),pt(i.shape,o.shape,"Error in hingeLoss: ");const c=Ne(1);i=Ce(X(Ne(2),i),c);const h=Oi(Ce(c,X(i,o)));return Zi(h,a,s)}const JB=P({hingeLoss_:XB});function ZB(e,t,n,s=1,i=r.Reduction.SUM_BY_NONZERO_WEIGHTS){const o=W(e,"labels","huberLoss"),a=W(t,"predictions","huberLoss");let c=null;n!=null&&(c=W(n,"weights","huberLoss")),pt(o.shape,a.shape,"Error in huberLoss: ");const h=Ne(s),d=sn(Ce(a,o)),m=Eo(d,h),y=Ce(d,m),b=be(X(Ne(.5),wt(m)),X(h,y));return Zi(b,c,i)}const QB=P({huberLoss_:ZB});function eM(e,t,n,s=1e-7,i=r.Reduction.SUM_BY_NONZERO_WEIGHTS){const o=W(e,"labels","logLoss"),a=W(t,"predictions","logLoss");let c=null;n!=null&&(c=W(n,"weights","logLoss")),pt(o.shape,a.shape,"Error in logLoss: ");const h=Ne(1),d=Ne(s),m=zt(X(o,ns(be(a,d)))),y=X(Ce(h,o),ns(be(Ce(h,a),d))),b=Ce(m,y);return Zi(b,c,i)}const tM=P({logLoss_:eM});function nM(e,t,n,s=r.Reduction.SUM_BY_NONZERO_WEIGHTS){const i=W(e,"labels","meanSquaredError"),o=W(t,"predictions","meanSquaredError");let a=null;n!=null&&(a=W(n,"weights","meanSquaredError")),pt(i.shape,o.shape,"Error in meanSquaredError: ");const c=yh(i,o);return Zi(c,a,s)}const sM=P({meanSquaredError_:nM});function iM(e,t){const n=W(e,"labels","sigmoidCrossEntropyWithLogits"),s=W(t,"logits","sigmoidCrossEntropyWithLogits");pt(n.shape,s.shape,"Error in sigmoidCrossEntropyWithLogits: ");const i=Oi(s),o=X(s,n),a=Gd(Ls(zt(sn(s))));return be(Ce(i,o),a)}function rM(e,t,n,s=0,i=r.Reduction.SUM_BY_NONZERO_WEIGHTS){let o=W(e,"multiClassLabels","sigmoidCrossEntropy");const a=W(t,"logits","sigmoidCrossEntropy");let c=null;if(n!=null&&(c=W(n,"weights","sigmoidCrossEntropy")),pt(o.shape,a.shape,"Error in sigmoidCrossEntropy: "),s>0){const d=Ne(s),m=Ne(1),y=Ne(.5);o=be(X(o,Ce(m,d)),X(y,d))}const h=iM(o,a);return Zi(h,c,i)}const oM=P({sigmoidCrossEntropy_:rM});function aM(e,t,n=-1){if(n===-1&&(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 s=Ci((i,o,a)=>{const c=!0,h=_b(o,[n],c),d=Ce(ve(o,"float32"),h);a([i,d]);const m=zt(X(d,i)),y=Ue(m,[n]),b=(w,L)=>{const[T,A]=L,N=On(w.shape,[n]);return[X(K(w,N),Ce(ve(T,"float32"),Ls(A))),X(K(w,N),Ce(Ls(A),ve(T,"float32")))]};return{value:y,gradFunc:b}});return s(e,t)}function cM(e,t,n,s=0,i=r.Reduction.SUM_BY_NONZERO_WEIGHTS){let o=W(e,"onehotLabels","softmaxCrossEntropy");const a=W(t,"logits","softmaxCrossEntropy");let c=null;if(n!=null&&(c=W(n,"weights","softmaxCrossEntropy")),pt(o.shape,a.shape,"Error in softmaxCrossEntropy: "),s>0){const d=Ne(s),m=Ne(1),y=Ne(o.shape[1]);o=be(X(o,Ce(m,d)),_e(d,y))}const h=aM(o,a);return Zi(h,c,i)}const lM=P({softmaxCrossEntropy_:cM});const hM={fft:fh,ifft:za,rfft:gh,irfft:np},uM={hammingWindow:cB,hannWindow:vA,frame:NA,stft:dB},$r={flipLeftRight:gB,resizeNearestNeighbor:OA,resizeBilinear:RA,rotateWithOffset:bB,cropAndResize:mB,nonMaxSuppression:LB,nonMaxSuppressionAsync:CB,nonMaxSuppressionWithScore:OB,nonMaxSuppressionWithScoreAsync:DB,nonMaxSuppressionPadded:FB,nonMaxSuppressionPaddedAsync:WB},DA={bandPart:MB,gramSchmidt:zB,qr:VB},dM={absoluteDifference:qB,computeWeightedLoss:Zi,cosineDistance:KB,hingeLoss:JB,huberLoss:QB,logLoss:tM,meanSquaredError:sM,sigmoidCrossEntropy:oM,softmaxCrossEntropy:lM};class Qi extends Ao{minimize(e,t=!1,n){const{value:s,grads:i}=this.computeGradients(e,n);if(n!=null){const o=n.map(a=>({name:a.name,tensor:i[a.name]}));this.applyGradients(o)}else this.applyGradients(i);return He(i),t?s:(s.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return Fb(e,t)}dispose(){this.iterations_!=null&&He(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Ne(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(Qi,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});class wh extends Qi{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=V.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,s)=>{const i=V.registeredVariables[n],o=!1;this.accumulatedGrads[s]==null&&(this.accumulatedGrads[s]={originalName:`${n}/accum_grad`,variable:ee(()=>Qe(i).variable(o))}),this.accumulatedUpdates[s]==null&&(this.accumulatedUpdates[s]={originalName:`${n}/accum_var`,variable:ee(()=>Qe(i).variable(o))});const a=Array.isArray(e)?e[s].tensor:e[n];if(a==null)return;const c=this.accumulatedGrads[s].variable,h=this.accumulatedUpdates[s].variable;ee(()=>{const d=be(X(c,this.rho),X(wt(a),1-this.rho)),m=X(_e(Ln(be(h,this.epsilon)),Ln(be(c,this.epsilon))),a),y=be(X(h,this.rho),X(wt(m),1-this.rho));c.assign(d),h.assign(y);const b=be(X(m,-this.learningRate),i);i.assign(b)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(He(this.accumulatedGrads.map(e=>e.variable)),He(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){const e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=e.length/2,n=!1;this.accumulatedGrads=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}}wh.className="Adadelta",me(wh);class Lh extends Qi{constructor(e,t=.1){super();this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,s)=>{const i=V.registeredVariables[n];if(this.accumulatedGrads[s]==null){const c=!1;this.accumulatedGrads[s]={originalName:`${n}/accumulator`,variable:ee(()=>oh(i.shape,this.initialAccumulatorValue).variable(c))}}const o=Array.isArray(e)?e[s].tensor:e[n];if(o==null)return;const a=this.accumulatedGrads[s].variable;ee(()=>{const c=be(a,wt(o));a.assign(c);const h=be(X(_e(o,Ln(be(c,V.backend.epsilon()))),-this.learningRate),i);i.assign(h)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&He(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);const t=!1;this.accumulatedGrads=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}Lh.className="Adagrad",me(Lh);class Sh extends Qi{constructor(e,t,n,s=null){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],ee(()=>{this.accBeta1=Ne(t).variable(),this.accBeta2=Ne(n).variable()}),s==null&&(this.epsilon=V.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);ee(()=>{const n=Ce(1,this.accBeta1),s=Ce(1,this.accBeta2);t.forEach((i,o)=>{const a=V.registeredVariables[i],c=!1;this.accumulatedFirstMoment[o]==null&&(this.accumulatedFirstMoment[o]={originalName:`${i}/m`,variable:ee(()=>Qe(a).variable(c))}),this.accumulatedSecondMoment[o]==null&&(this.accumulatedSecondMoment[o]={originalName:`${i}/v`,variable:ee(()=>Qe(a).variable(c))});const h=Array.isArray(e)?e[o].tensor:e[i];if(h==null)return;const d=this.accumulatedFirstMoment[o].variable,m=this.accumulatedSecondMoment[o].variable,y=be(X(d,this.beta1),X(h,1-this.beta1)),b=be(X(m,this.beta2),X(wt(h),1-this.beta2)),w=_e(y,n),L=_e(b,s);d.assign(y),m.assign(b);const T=be(X(_e(w,be(Ln(L),this.epsilon)),-this.learningRate),a);a.assign(T)}),this.accBeta1.assign(X(this.accBeta1,this.beta1)),this.accBeta2.assign(X(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&He(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&He(this.accumulatedSecondMoment.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e),ee(()=>{this.accBeta1.assign(si(this.beta1,this.iterations_+1)),this.accBeta2.assign(si(this.beta2,this.iterations_+1))});const t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.tensor.variable(n)}))}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)}}Sh.className="Adam",me(Sh);class Ih extends Qi{constructor(e,t,n,s=null,i=0){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.decay=i,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],ee(()=>{this.iteration=Ne(0).variable(),this.accBeta1=Ne(t).variable()}),s==null&&(this.epsilon=V.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);ee(()=>{const n=Ce(1,this.accBeta1),s=_e(-this.learningRate,be(X(this.iteration,this.decay),1));t.forEach((i,o)=>{const a=V.registeredVariables[i],c=!1;this.accumulatedFirstMoment[o]==null&&(this.accumulatedFirstMoment[o]={originalName:`${i}/m`,variable:Qe(a).variable(c)}),this.accumulatedWeightedInfNorm[o]==null&&(this.accumulatedWeightedInfNorm[o]={originalName:`${i}/v`,variable:Qe(a).variable(c)});const h=Array.isArray(e)?e[o].tensor:e[i];if(h==null)return;const d=this.accumulatedFirstMoment[o].variable,m=this.accumulatedWeightedInfNorm[o].variable,y=be(X(d,this.beta1),X(h,1-this.beta1)),b=X(m,this.beta2),w=sn(h),L=Ws(b,w);d.assign(y),m.assign(L);const T=be(X(_e(s,n),_e(y,be(L,this.epsilon))),a);a.assign(T)}),this.iteration.assign(be(this.iteration,1)),this.accBeta1.assign(X(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&He(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&He(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)}}Ih.className="Adamax",me(Ih);class Ha extends Qi{constructor(e){super();this.learningRate=e,this.setLearningRate(e)}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,s)=>{const i=Array.isArray(e)?e[s].tensor:e[n];if(i==null)return;const o=V.registeredVariables[n];ee(()=>{const a=be(X(this.c,i),o);o.assign(a)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=Cn(Ne(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(e=await this.extractIterations(e),e.length!==0)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}}Ha.className="SGD",me(Ha);class xh extends Ha{constructor(e,t,n=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Ne(this.momentum)}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,s)=>{const i=V.registeredVariables[n];if(this.accumulations[s]==null){const c=!1;this.accumulations[s]={originalName:`${n}/momentum`,variable:ee(()=>Qe(i).variable(c))}}const o=this.accumulations[s].variable,a=Array.isArray(e)?e[s].tensor:e[n];if(a==null)return;ee(()=>{let c;const h=be(X(this.m,o),a);this.useNesterov?c=be(X(this.c,be(a,X(h,this.m))),i):c=be(X(this.c,h),i),o.assign(h),i.assign(c)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&He(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);const t=!1;this.accumulations=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}xh.className="Momentum",me(xh);class Th extends Qi{constructor(e,t=.9,n=0,s=null,i=!1){super();if(this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=s,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=i,s==null&&(this.epsilon=V.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,s)=>{const i=V.registeredVariables[n],o=!1;this.accumulatedMeanSquares[s]==null&&(this.accumulatedMeanSquares[s]={originalName:`${n}/rms`,variable:ee(()=>Qe(i).variable(o))}),this.accumulatedMoments[s]==null&&(this.accumulatedMoments[s]={originalName:`${n}/momentum`,variable:ee(()=>Qe(i).variable(o))}),this.accumulatedMeanGrads[s]==null&&this.centered&&(this.accumulatedMeanGrads[s]={originalName:`${n}/mg`,variable:ee(()=>Qe(i).variable(o))});const a=Array.isArray(e)?e[s].tensor:e[n];if(a==null)return;const c=this.accumulatedMeanSquares[s].variable,h=this.accumulatedMoments[s].variable;ee(()=>{const d=be(X(c,this.decay),X(wt(a),1-this.decay));if(this.centered){const m=this.accumulatedMeanGrads[s].variable,y=be(X(m,this.decay),X(a,1-this.decay)),b=_e(X(a,this.learningRate),Ln(Ce(d,be(wt(y),this.epsilon)))),w=be(X(h,this.momentum),b);c.assign(d),m.assign(y),h.assign(w);const L=Ce(i,w);i.assign(L)}else{const m=be(X(c,this.decay),X(wt(a),1-this.decay)),y=be(X(h,this.momentum),_e(X(a,this.learningRate),Ln(be(m,this.epsilon))));c.assign(m),h.assign(y);const b=Ce(i,y);i.assign(b)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&He(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&He(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&He(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(t=>({name:t.originalName,tensor:t.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(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,t*2).map(s=>({originalName:s.name,variable:s.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(s=>({originalName:s.name,variable:s.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)}}Th.className="RMSProp",me(Th);class $o{static sgd(e){return new Ha(e)}static momentum(e,t,n=!1){return new xh(e,t,n)}static rmsprop(e,t=.9,n=0,s=null,i=!1){return new Th(e,t,n,s,i)}static adam(e=.001,t=.9,n=.999,s=null){return new Sh(e,t,n,s)}static adadelta(e=.001,t=.95,n=null){return new wh(e,t,n)}static adamax(e=.002,t=.9,n=.999,s=null,i=0){return new Ih(e,t,n,s,i)}static adagrad(e,t=.1){return new Lh(e,t)}}const Uo={sgd:$o.sgd,momentum:$o.momentum,adadelta:$o.adadelta,adagrad:$o.adagrad,rmsprop:$o.rmsprop,adamax:$o.adamax,adam:$o.adam};const pM=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function mp(){return new Promise(e=>pM(()=>e()))}function nw(e,t,n){const s=n*(typeof e=="number"?e:e[0]),i=t*(typeof e=="number"?e:e[1]);return[s,i]}function Ah(e,t,n,s=!0){let i=[];if(s)i=i.concat(t.slice(0)),i.push(e[0]/n),i=i.concat(e.slice(1));else{i=i.concat(e[0]);const o=t.length;for(let a=0;a<o;++a)i=i.concat([e[a+1]/t[a],t[a]]);i=i.concat(e.slice(o+1))}return i}function vh(e,t,n=!0){const s=[];if(n){s.push(t);for(let i=t+1;i<e;++i)i<=2*t?(s.push(i),s.push(i-(t+1))):s.push(i)}else{const i=[],o=[];for(let a=1;a<e;++a)a>=t*2+1||a%2===1?o.push(a):i.push(a);s.push(...i),s.push(0),s.push(...o)}return s}function Nh(e,t,n,s=!0){const i=[];s?i.push(e[0]/n):i.push(e[0]*n);for(let o=1;o<e.length;++o)o<=t.length?s?i.push(t[o-1]*e[o]):i.push(e[o]/t[o-1]):i.push(e[o]);return i}function sw(e,t){const n=[0];for(let s=0;s<t;++s)n.push(e[s][0]);return n}function iw(e,t,n){const s=e.slice(0,1);for(let i=0;i<n;++i)s.push(e[i+1]-t[i][0]-t[i][1]);return s}const fp=1.7580993408473768,gp=1.0507009873554805;const rw=.3275911,ow=.254829592,aw=-.284496736,cw=1.421413741,lw=-1.453152027,hw=1.061405429;function qa(...e){C().getBool("IS_TEST")||console.warn(...e)}function mM(...e){C().getBool("IS_TEST")||console.log(...e)}function er(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(e.length*2);for(let s=0;s<n.length;s+=2)n[s]=e[s/2],n[s+1]=t[s/2];return n}function kA(e){const t=new Float32Array(e.length/2),n=new Float32Array(e.length/2);for(let s=0;s<e.length;s+=2)t[s/2]=e[s],n[s/2]=e[s+1];return{real:t,imag:n}}function FA(e){const t=Math.ceil(e.length/4),n=new Float32Array(t),s=new Float32Array(t);for(let i=0;i<e.length;i+=4)n[Math.floor(i/4)]=e[i],s[Math.floor(i/4)]=e[i+1];return{real:n,imag:s}}function _A(e){const t=Math.floor(e.length/4),n=new Float32Array(t),s=new Float32Array(t);for(let i=2;i<e.length;i+=4)n[Math.floor(i/4)]=e[i],s[Math.floor(i/4)]=e[i+1];return{real:n,imag:s}}function uw(e,t){const n=e[t*2],s=e[t*2+1];return{real:n,imag:s}}function WA(e,t,n,s){e[s*2]=t,e[s*2+1]=n}function $A(e,t){const n=new Float32Array(e/2),s=new Float32Array(e/2);for(let i=0;i<Math.ceil(e/2);i++){const o=(t?2:-2)*Math.PI*(i/e);n[i]=Math.cos(o),s[i]=Math.sin(o)}return{real:n,imag:s}}function UA(e,t,n){const s=(n?2:-2)*Math.PI*(e/t),i=Math.cos(s),o=Math.sin(s);return{real:i,imag:o}}function BA(e,t,n){if(t==="complex64"){if(e.dtype==="complex64")return e.clone();const s=ct(e.shape),i=ve(e,"float32"),o=n.complex(i,s);return s.dispose(),i.dispose(),o}if(!Dy(e.dtype,t))return V.makeTensorFromDataId(e.dataId,e.shape,t);if(e.dtype==="complex64"){const s=n.real(e),i=ve(s,t);return s.dispose(),i}if(t==="int32")return n.int(e);if(t==="bool"){const s=Ne(0,e.dtype),i=n.notEqual(e,s);return s.dispose(),i}else throw new Error(`Error in Cast: failed to cast ${e.dtype} to ${t}`)}function MA(e,t){return V.makeTensorFromDataId(e.dataId,t,e.dtype)}function dw(e,t,n){const s=(t-e)/(n-1),i=Aa(n,"float32");i[0]=e;for(let o=1;o<i.length;o++)i[o]=i[o-1]+s;return ss(i,"float32")}var pw=Object.freeze({__proto__:null,slice_util:CT,segment_util:aW,castTensor:BA,reshapeTensor:MA,linspaceImpl:dw,upcastType:Nn,axesAreInnerMostDims:pb,combineLocations:FT,computeOutAndReduceShapes:Rn,expandShapeToKeepDim:On,assertAxesAreInnerMostDims:ts,getAxesPermutation:kn,getUndoAxesPermutation:Xl,getInnerMostAxes:ws,getBroadcastDims:Ro,getReductionAxes:on,assertAndGetBroadcastShape:tt,assertParamsConsistent:xb,computeOutShape:Er,computeDilation2DInfo:Fd,computePool2DInfo:Fn,computePool3DInfo:Ql,computeConv2DInfo:vi,computeConv3DInfo:eh,computeDefaultPad:Lb,tupleValuesAreOne:Or,eitherStridesOrDilationsAreOne:rn,convertConv2DDataFormat:th,getFusedDyActivation:op,getFusedBiasGradient:ap,applyActivation:cp,shouldFuse:lp,PARALLELIZE_THRESHOLD:Db,computeOptimalWindowSize:ah,getImageCenter:nw,getReshaped:Ah,getPermuted:vh,getReshapedPermuted:Nh,getSliceBeginCoords:sw,getSliceSize:iw,prepareAndValidate:vd,validateUpdateShape:nb,validateInput:sb,calculateShapes:Da,SELU_SCALEALPHA:fp,SELU_SCALE:gp,ERF_P:rw,ERF_A1:ow,ERF_A2:aw,ERF_A3:cw,ERF_A4:lw,ERF_A5:hw,warn:qa,log:mM,mergeRealAndImagArrays:er,splitRealAndImagArrays:kA,complexWithEvenIndex:FA,complexWithOddIndex:_A,getComplexWithIndex:uw,assignToTypedArray:WA,exponents:$A,exponent:UA,prepareSplitSize:tA});function mw(e,t,n){const s=new Array(e.rank).fill(0),i=e.shape.slice();return t.map(o=>{const a=[...i];a[n]=o;const c=nt(e,s,a);return s[n]+=o,c})}function fw(e,t){const n=new Array(e.rank);for(let i=0;i<n.length;i++)n[i]=e.shape[i]*t[i];const s=Ze(n,e.dtype);for(let i=0;i<s.values.length;++i){const o=s.indexToLoc(i),a=new Array(e.rank);for(let h=0;h<a.length;h++)a[h]=o[h]%e.shape[h];const c=e.locToIndex(a);s.values[i]=e.values[c]}return s.toTensor()}function gw(e,t,n,s,i){const o=t[t.length-1],[a,c]=[e.length/o,o],h=bn(n,a*s),d=bn("int32",a*s);for(let y=0;y<a;y++){const b=y*c,w=e.subarray(b,b+c),L=[];for(let E=0;E<w.length;E++)L.push({value:w[E],index:E});L.sort((E,D)=>D.value-E.value);const T=y*s,A=h.subarray(T,T+s),N=d.subarray(T,T+s);for(let E=0;E<s;E++)A[E]=L[E].value,N[E]=L[E].index}const m=t.slice();return m[m.length-1]=s,[en(h,m,n),en(d,m,"int32")]}var fM=Object.freeze({__proto__:null,nonMaxSuppressionV3Impl:up,nonMaxSuppressionV4Impl:dp,nonMaxSuppressionV5Impl:pp,split:mw,tile:fw,topkImpl:gw,whereImpl:ip});const gM={kernelName:ge,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,Ga(ve(n,"float32"),-1))}}};const yM={kernelName:fe,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const s=wt(ve(n,"float32")),i=Ln(Ce(Ne(1),s));return zt(_e(e,i))}}}};const bM={kernelName:Ae,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const s=Ln(Ce(wt(ve(n,"float32")),1));return _e(e,s)}}}};const wM={kernelName:Te,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=tt(n.shape,s.shape),o=()=>{let c=e;const h=on(n.shape,i);return h.length>0&&(c=Ue(c,h)),K(c,n.shape)},a=()=>{let c=e;const h=on(s.shape,i);return h.length>0&&(c=Ue(c,h)),K(c,s.shape)};return{a:o,b:a}}};const LM={kernelName:Ve,saveAllInputs:!0,gradFunc:(e,t)=>{const n={};return t.forEach((s,i)=>{n[i]=()=>e.clone()}),n}};const SM={kernelName:Ut,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Qe(n)}}};const IM={kernelName:Kt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Qe(n)}}};const xM={kernelName:Dn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_e(e,Ln(Ce(Ne(1),wt(ve(n,"float32")))))}}};const TM={kernelName:An,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const s=Ln(be(Ne(1),wt(ve(n,"float32"))));return _e(e,s)}}}};const AM={kernelName:Si,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=tt(n.shape,s.shape),o=()=>{const c=be(wt(n),wt(s));let h=X(e,_e(s,c));const d=on(n.shape,i);return d.length>0&&(h=Ue(h,d)),K(h,n.shape)},a=()=>{const c=be(wt(n),wt(s));let h=zt(X(e,_e(n,c)));const d=on(s.shape,i);return d.length>0&&(h=Ue(h,d)),K(h,s.shape)};return{a:o,b:a}}};const vM={kernelName:vn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_e(e,be(wt(ve(n,"float32")),1))}}};const NM={kernelName:Zs,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_e(e,Ce(Ne(1),wt(ve(n,"float32"))))}}};function CM(e,t,n,s,i=[1,1,1],o,a){const c=W(e,"dy","avgPool3dBackprop"),h=W(t,"input","avgPool3dBackprop");let d=c,m=h,y=!1;h.rank===4&&(y=!0,d=K(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]]),m=K(h,[1,h.shape[0],h.shape[1],h.shape[2],h.shape[3]])),k(d.rank===5,()=>`Error in avgPool3dBackprop: dy must be rank 5 but got rank ${d.rank}.`),k(m.rank===5,()=>`Error in avgPool3dBackprop: input must be rank 5 but got rank ${m.rank}.`),k(rn(s,i),()=>`Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides ${s} and dilations '${i}'`),a!=null&&k(Bt(o),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);const b=A=>{const N=Ql(m.shape,n,s,i,o,a);return A.avgPool3dBackprop(d,m,N)},w={dy:d,input:m},L={filterSize:n,strides:s,dilations:i,pad:o,dimRoundingMode:a},T=V.runKernelFunc(b,w,null,ax,L);return y?K(T,[T.shape[1],T.shape[2],T.shape[3],T.shape[4]]):T}const RM=P({avgPool3dBackprop_:CM});const OM={kernelName:ol,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{filterSize:i,strides:o,dilations:a,pad:c,dimRoundingMode:h}=n,d=a==null?[1,1,1]:a;return{x:()=>RM(e,s,i,o,d,c,h)}}};function EM(e,t,n,s,i){const o=W(e,"dy","avgPoolBackprop"),a=W(t,"input","avgPoolBackprop");k(a.rank===o.rank,()=>`Rank of input (${a.rank}) does not match rank of dy (${o.rank})`);let c=a,h=o,d=!1;a.rank===3&&(d=!0,c=K(a,[1,a.shape[0],a.shape[1],a.shape[2]]),h=K(o,[1,o.shape[0],o.shape[1],o.shape[2]])),k(h.rank===4,()=>`Error in avgPoolBackprop: dy must be rank 4 but got rank ${h.rank}.`),k(c.rank===4,()=>`Error in avgPoolBackprop: input must be rank 4 but got rank ${c.rank}.`);const m=L=>{const T=Fn(c.shape,n,s,1,i);return L.avgPoolBackprop(h,c,T)},y={dy:h,input:c},b={filterSize:n,strides:s,pad:i},w=V.runKernelFunc(m,y,null,ya,b);return d?K(w,[w.shape[1],w.shape[2],w.shape[3]]):w}const DM=P({avgPoolBackprop_:EM});const kM={kernelName:Qs,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{filterSize:i,strides:o,pad:a}=n;return{x:()=>DM(e,s,i,o,a)}}};const FM={kernelName:_g,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{const[s,i]=t,{transposeA:o,transposeB:a}=n;return!o&&!a?{a:()=>at(e,i,!1,!0),b:()=>at(s,e,!0,!1)}:!o&&a?{a:()=>at(e,i,!1,!1),b:()=>at(e,s,!0,!1)}:o&&!a?{a:()=>at(i,e,!1,!0),b:()=>at(s,e,!1,!1)}:{a:()=>at(i,e,!0,!0),b:()=>at(e,s,!0,!0)}}};const _M={kernelName:Wg,gradFunc:(e,t,n)=>{const{blockShape:s,crops:i}=n;return{x:()=>uh(e,s,i)}}};const WM={kernelName:$g,gradFunc:(e,t,n)=>{const s=n,i=s.inputShape,o=s.shape,a=Array.from(o);for(let h=i.length-1;h>=0;h--)if(i[h]===o[h])a[h]=1;else if(i[h]!==1)throw new Error(`broadcastTo(): [${i}] cannot be broadcast to [${o}].`);const c=[];for(let h=0;h<a.length;h++)a[h]>1&&c.push(h);return{x:()=>Ue(e,c,!0)}}};const $M={kernelName:al,gradFunc:e=>({x:()=>e.clone()})};const UM={kernelName:cl,gradFunc:e=>({x:()=>Qe(e)})};const BM={kernelName:ll,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{clipValueMin:i,clipValueMax:o}=n;return{x:()=>_n($s(Ji(s,i),kr(s,o)),e,Qe(e))}}};const MM={kernelName:qu,saveAllInputs:!0,gradFunc:(e,t,n)=>{const s=t.map(h=>h.shape),{axis:i}=n,o=gt(i,t[0].shape)[0],a=s.map(h=>h[o]),c=is(e,a,o);return c.map(h=>()=>h)}};const PM={kernelName:Bg,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[s,i]=t,{dilations:o,strides:a,pad:c,dataFormat:h}=n;return k(Or(o),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${o}'`),{x:()=>Ab(s.shape,e,i,a,c,h),filter:()=>Qb(s,e,i.shape,a,c,h)}}};const zM={kernelName:Mg,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{const[s,i]=t,{strides:o,pad:a,dataFormat:c,dimRoundingMode:h}=n;return{dy:()=>Xi(e,i,o,a,c,1,h),filter:()=>Qb(e,s,i.shape,o,a,c,h)}}};function GM(e,t,n,s,i){let o=e;e.rank===4&&(o=K(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let a=t;a.rank===4&&(a=K(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),k(o.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${o.shape}.`),k(a.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${a.shape}.`),k(n.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`),k(o.shape[4]===n[3],()=>`Error in conv3dDerFilter: depth of input ${o.shape[4]}) must match input depth in filter (${n[3]}.`),k(a.shape[4]===n[4],()=>`Error in conv3dDerFilter: depth of dy (${a.shape[4]}) must match output depth for filter (${n[4]}).`);const c=m=>{const y=1,b=eh(o.shape,n,s,y,i);return m.conv3dDerFilter(o,a,b)},h={x:o,y:a},d={strides:s,pad:i};return V.runKernelFunc(c,h,null,lx,d)}const VM=P({conv3DBackpropFilter_:GM});const YM={kernelName:Pg,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:s,strides:i,pad:o}=n;k(Or(s),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);const[a,c]=t;return{x:()=>zT(a.shape,e,c,i,o),filter:()=>VM(a,e,c.shape,i,o)}}};const HM={kernelName:ba,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(zt(Zd(ve(n,"float32"))),e)}}};const qM={kernelName:hl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(Qd(ve(n,"float32")),e)}}};const jM={kernelName:zg,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{axis:i,exclusive:o,reverse:a}=n;return{x:()=>{const c=kn([i],s.rank);let h=Md(e,i,o,!a);return c!=null&&(h=Me(h,c)),h}}}};const KM={kernelName:Gg,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:s,strides:i,pad:o,dimRoundingMode:a}=n,c=s==null?[1,1]:s;k(Or(c),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${c}'`);const[h,d]=t;k(h.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${h.rank}.`),k(d.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${d.rank}.`),k(h.shape[3]===d.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${h.shape[3]}) must match the inChannels dimension in filter ${d.shape[2]}.`),k(rn(i,c),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'.`),a!=null&&k(Bt(o),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);const m=vi(h.shape,d.shape,i,c,o,a,!0);return{x:()=>TA(h.shape,e,d,m),filter:()=>xA(h,e,d.shape,m)}}};const XM={kernelName:ju,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[s,i]=t,o={x:s,filter:i,dy:e},a={x:s,filter:i,dy:e};return{x:()=>V.runKernel(Ku,o,n),filter:()=>V.runKernel(Xu,a,n)}}};const JM={kernelName:wa,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=tt(n.shape,s.shape),o=()=>{const c=_e(e,ve(s,"float32")),h=on(n.shape,i);return h.length>0?K(Ue(c,h),n.shape):c},a=()=>{let c=X(e,ve(n,"float32"));const h=on(s.shape,i);h.length>0&&(c=K(Ue(c,h),s.shape));const d=wt(s);return zt(_e(c,ve(d,"float32")))};return{a:o,b:a}}};const ZM={kernelName:ul,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t,s=o=>o.eluDer(e,n),i={dy:e,y:n};return{x:()=>V.runKernelFunc(s,i,null,gx)}}};const QM={kernelName:dl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,s=X(Ls(zt(wt(n))),2/Math.sqrt(Math.PI));return{x:()=>X(e,s)}}};const eP={kernelName:pl,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,n)}}};const tP={kernelName:ml,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,Ls(n))}}};const nP={kernelName:fl,gradFunc:e=>({x:()=>Qe(e)})};const sP={kernelName:Yg,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=tt(n.shape,s.shape),o=()=>{const c=_e(e,ve(s,"float32")),h=on(n.shape,i);return h.length>0?K(Ue(c,h),n.shape):c},a=()=>{let c=X(e,ve(n,"float32"));const h=on(s.shape,i);h.length>0&&(c=K(Ue(c,h),s.shape));const d=wt(s);return zt(_e(c,ve(d,"float32")))};return{a:o,b:a}}};const iP={kernelName:gl,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{const{varianceEpsilon:s}=n,[i,o,a,c]=t,h=c==null?Ne(1):c,d=on(o.shape,i.shape),m=[];if(o.rank===1){for(let F=0;F<i.shape.length-1;++F)m.push(i.shape[F]);m.push(1)}const y=Ce(i,o),b=X(e,h),w=Xd(be(a,Ne(s))),L=X(X(X(w,w),w),Ne(-.5)),T=()=>o.rank===1?K(X(X(e,Dr(K(w,[1,1,1,o.shape[0]]),m)),h),i.shape):K(X(X(e,w),h),i.shape),A=()=>{let F=X(X(w,Ne(-1)),b);return o.rank===1&&(F=Ue(F,d)),K(F,o.shape)},N=()=>{let F=X(X(L,y),b);return o.rank===1&&(F=Ue(F,d)),K(F,o.shape)},E=()=>{const F=X(y,w);let _=X(e,F);return o.rank===1&&(_=Ue(_,d)),K(_,o.shape)},D=()=>{let F=e;return o.rank===1&&(F=Ue(F,d)),K(F,o.shape)};return{x:T,mean:A,variance:N,scale:E,offset:D}}};const rP={kernelName:Hg,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{const[s,i]=t,{axis:o}=n,a=gt(o,s.shape)[0],c=()=>{const h=s.shape,d=i.size,m=h.slice(0,a),y=m.length,b=h.slice(o,h.length).slice(1),w=b.length,L=PA(0,y),T=PA(y+1,y+1+w),A=zA([m,[d],b]),N=K(e,A),E=K(i,[d]),D=zA([[y],L,T]),F=Me(N,D);let _=Kb(F,E,s.shape[a]);const B=Xl(D);return _=Me(_,B),_};return{x:c,indices:()=>i}}};function PA(e,t){const n=[];for(let s=e;s<t;++s)n.push(s);return n}function zA(e){const t=[];for(let n=0;n<e.length;++n)for(let s=0;s<e[n].length;++s)t.push(e[n][s]);return t}const oP={kernelName:qg,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t;return{a:()=>Qe(n),b:()=>Qe(s)}}};const aP={kernelName:yl,gradFunc:e=>({x:()=>ve(e,"float32")})};const cP={kernelName:bl,gradFunc:e=>({x:()=>Qe(e)})};const lP={kernelName:wl,gradFunc:e=>({x:()=>Qe(e)})};const hP={kernelName:Ll,gradFunc:e=>({x:()=>Qe(e)})};const uP={kernelName:Il,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_e(e,be(n,1))}}};const dP={kernelName:Sl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_e(e,ve(n,"float32"))}}};const pP={kernelName:Xg,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s]=t,{axis:i}=n;return{logits:()=>{const o=!0,a=Ls(s);return Ce(e,X(Ue(e,i,o),a))}}}};function mP(e,t,n,s=5,i=1,o=1,a=.5){const c=m=>m.LRNGrad(n,e,t,s,i,o,a),h={x:e,y:t,dy:n},d={depthRadius:s,bias:i,alpha:o,beta:a};return V.runKernelFunc(c,h,null,vx,d)}const fP=P({localResponseNormalizationBackprop_:mP});const gP={kernelName:Jg,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,i]=t,{depthRadius:o,bias:a,alpha:c,beta:h}=n;return{x:()=>fP(s,i,e,o,a,c,h)}}};function GA(e,t,n,s,i){return t.rank<n.rank&&(t=K(t,On(t.shape,s))),e.rank<n.rank&&(e=K(e,On(e.shape,s))),{x:()=>{const o=X(e,ve(ti(n,t),e.dtype));return i==null?o:Me(o,i)}}}const VA={kernelName:xl,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const s=n,{reductionIndices:i}=s,[o,a]=t,c=gt(i,o.shape),h=kn(c,o.rank),d=GA(e,a,o,c,h);return{x:()=>{let m=d.x();return h!=null&&(m=Me(m)),m}}}};const yP={kernelName:Zg,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=()=>X(e,ve(Ji(n,s),"float32")),o=()=>X(e,ve(ch(n,s),"float32"));return{a:i,b:o}}};function bP(e,t,n,s,i,o=[1,1,1],a,c){const h=W(e,"dy","maxPool3dBackprop"),d=W(t,"input","maxPool3dBackprop"),m=W(n,"output","maxPool3dBackprop");let y=h,b=d,w=m,L=!1;d.rank===4&&(L=!0,y=K(h,[1,h.shape[0],h.shape[1],h.shape[2],h.shape[3]]),b=K(d,[1,d.shape[0],d.shape[1],d.shape[2],d.shape[3]]),w=K(m,[1,m.shape[0],m.shape[1],m.shape[2],m.shape[3]])),k(y.rank===5,()=>`Error in maxPool3dBackprop: dy must be rank 5 but got rank ${y.rank}.`),k(b.rank===5,()=>`Error in maxPool3dBackprop: input must be rank 5 but got rank ${b.rank}.`),k(w.rank===5,()=>`Error in maxPool3dBackprop: output must be rank 5 but got rank ${w.rank}.`),k(rn(i,o),()=>`Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides ${i} and dilations '${o}'`),c!=null&&k(Bt(a),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${c} but got pad ${a}.`);const T=D=>{const F=Ql(b.shape,s,i,o,a,c);return D.maxPool3dBackprop(y,b,w,F)},A={dy:y,input:b,output:w},N={filterSize:s,strides:i,dilations:o,pad:a,dimRoundingMode:c},E=V.runKernelFunc(T,A,null,Nx,N);return L?K(E,[E.shape[1],E.shape[2],E.shape[3],E.shape[4]]):E}const wP=P({maxPool3dBackprop_:bP});const LP={kernelName:Qg,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,i]=t,{filterSize:o,strides:a,dilations:c,pad:h,dimRoundingMode:d}=n,m=c==null?[1,1,1]:c;return{x:()=>wP(e,s,i,o,a,m,h,d)}}};function SP(e,t,n,s,i,o,a){const c=W(e,"dy","maxPoolBackprop"),h=W(t,"input","maxPoolBackprop"),d=W(n,"output","maxPoolBackprop");k(h.rank===c.rank,()=>`Rank of input (${h.rank}) does not match rank of dy (${c.rank})`),k(c.rank===4,()=>`Error in maxPoolBackprop: dy must be rank 4 but got rank ${c.rank}.`),k(h.rank===4,()=>`Error in maxPoolBackprop: input must be rank 4 but got rank ${h.rank}.`),a!=null&&k(Bt(o),()=>`Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);const m=w=>{const L=Fn(h.shape,s,i,1,o,a);return w.maxPoolBackprop(c,h,d,L)},y={dy:c,input:h,output:d},b={filterSize:s,strides:i,pad:o,dimRoundingMode:a};return V.runKernelFunc(m,y,null,Qu,b)}const IP=P({maxPoolBackprop_:SP});const xP={kernelName:Tl,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,i]=t,{filterSize:o,strides:a,pad:c}=n;return{x:()=>IP(e,s,i,o,a,c)}}};const TP={kernelName:ey,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const s=n,{axis:i}=s,[o,a]=t,c=gt(i,o.shape),h=kn(c,o.rank),d=GA(e,a,o,c,h);return{x:()=>{let m=d.x();return h!=null&&(m=Me(m)),m}}}};const AP={kernelName:ty,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=()=>X(e,ve(kr(n,s),"float32")),o=()=>X(e,ve(Ss(n,s),"float32"));return{a:i,b:o}}};const vP={kernelName:ny,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=tt(n.shape,s.shape),o=()=>{const c=on(n.shape,i);return c.length>0?K(Ue(e,c),n.shape):e},a=()=>{const c=X(e,zt(_a(_e(n,s)))),h=on(s.shape,i);return h.length>0?K(Ue(c,h),s.shape):c};return{a:o,b:a}}};const NP={kernelName:Al,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=tt(n.shape,s.shape),o=()=>{const c=X(e,ve(s,"float32")),h=on(n.shape,i);return h.length>0?K(Ue(c,h),n.shape):c},a=()=>{const c=X(e,ve(n,"float32")),h=on(s.shape,i);return h.length>0?K(Ue(c,h),s.shape):c};return{a:o,b:a}}};const CP={kernelName:sy,gradFunc:e=>({x:()=>zt(e)})};const RP={kernelName:oy,inputsToSave:["indices"],gradFunc:(e,t)=>{const n=t[0];return{indices:()=>ct(n.shape,"float32")}}};const OP={kernelName:ry,gradFunc:e=>({x:()=>Qe(e)})};const YA={kernelName:id,inputsToSave:["x"],gradFunc:(e,t,n)=>{const s=t[0],{paddings:i}=n,o=i.map(a=>a[0]);return{x:()=>nt(e,o,s.shape)}}};const EP={kernelName:ay,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[n,s,i]=t,o=n,a=s,c=tt(o.shape,a.shape),h=()=>{const m=ve(a,"float32");let y=X(e,X(m,si(o,Ce(m,Ne(1)))));const b=on(o.shape,c);return b.length>0&&(y=Ue(y,b)),K(y,o.shape)},d=()=>{const m=Ss(o,0),y=_n(m,ns(o),Qe(o));let b=X(e,X(i,y));const w=on(a.shape,c);return w.length>0&&(b=Ue(b,w)),K(b,a.shape)};return{a:h,b:d}}};const DP={kernelName:cy,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[n,s]=t,i=Ss(n,0);return{x:()=>_n(i,e,X(e,s)),alpha:()=>{let o=_n(i,Qe(e),X(e,n));const a=on(s.shape,e.shape);return a.length>0&&(o=Ue(o,a)),K(o,s.shape)}}}};const kP={kernelName:vl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_e(e,zt(wt(n)))}}};const FP={kernelName:py,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,s=X(kr(n,6),Ga(n));return{x:()=>X(e,ve(s,"float32"))}}};const _P={kernelName:hy,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,ve(Ga(n),"float32"))}}};const WP={kernelName:Nl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>K(e,n.shape)}}};const $P={kernelName:dy,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[s]=t,i=c=>{const{alignCorners:h}=n;return c.resizeBilinearBackprop(e,s,h)},o={images:s},a=()=>V.runKernelFunc(i,o,null,Ex,n);return{images:a}}};const UP={kernelName:uy,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[s]=t,i=c=>{const{alignCorners:h}=n;return c.resizeNearestNeighborBackprop(e,s,h)},o={images:s},a=()=>V.runKernelFunc(i,o,null,Ox,n);return{images:a}}};const BP={kernelName:my,gradFunc:(e,t,n)=>{const{dims:s}=n,i=gt(s,e.shape);return{x:()=>Is(e,i)}}};const MP={kernelName:Cl,gradFunc:e=>({x:()=>Qe(e)})};const PP={kernelName:Rl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>zt(_e(e,X(si(n,1.5),2)))}}};const zP={kernelName:fy,inputsToSave:["condition"],gradFunc:(e,t)=>{const[n]=t;return{condition:()=>ve(Qe(n),"float32"),t:()=>X(e,ve(n,e.dtype)),e:()=>X(e,ve(lh(n),e.dtype))}}};const GP={kernelName:Ol,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const s=Ss(n,Ne(0)),i=Ne(fp),o=Ne(gp),a=X(e,o),c=X(X(e,i),Ls(ve(n,"float32")));return _n(s,a,c)}}}};const VP={kernelName:kl,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,X(n,Ce(Ne(1),n)))}}};const YP={kernelName:Dl,gradFunc:e=>({x:()=>Qe(e)})};const HP={kernelName:La,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(rh(ve(n,"float32")),e)}}};const qP={kernelName:El,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(Bd(ve(n,"float32")),e)}}};const jP={kernelName:rd,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{begin:i,size:o}=n,a=s.shape,[c,h]=Rd(s,i,o),d=[];for(let m=0;m<e.rank;m++)d.push([c[m],a[m]-c[m]-h[m]]);return{x:()=>Ri(e,d)}}};const KP={kernelName:by,outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s]=t,{dim:i}=n,o=!0,a=X(e,s);return{logits:()=>Ce(a,X(Ue(a,[i],o),s))}}};const XP={kernelName:Fl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,Ni(n))}}};const HA={kernelName:od,gradFunc:(e,t,n)=>{const{blockShape:s,paddings:i}=n;return{x:()=>sh(e,s,i)}}};const qA={kernelName:yy,gradFunc:(e,t,n)=>{const{axis:s}=n;return{x:()=>Pt(e,s)}}};const JP={kernelName:_l,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_e(e,X(Ln(ve(n,"float32")),2))}}};const ZP={kernelName:ad,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,X(ve(n,"float32"),2))}}};const QP={kernelName:Sa,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=Ne(2),o=()=>X(e,X(i,Ce(n,s))),a=()=>X(e,X(i,Ce(s,n)));return{a:o,b:a}}};const ez={kernelName:Bl,gradFunc:e=>({x:()=>Qe(e)})};const tz={kernelName:Wl,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=tt(n.shape,s.shape),o=()=>{let c=e;const h=on(n.shape,i);return h.length>0&&(c=Ue(c,h)),K(c,n.shape)},a=()=>{let c=e;const h=on(s.shape,i);return h.length>0&&(c=Ue(c,h)),K(zt(c),s.shape)};return{a:o,b:a}}};const nz={kernelName:gy,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,i=s.shape.slice(),{axis:o}=n,a=gt(o,s.shape);a.forEach(d=>{i[d]=1});const c=K(e,i),h=X(c,ni(s.shape,"float32"));return{x:()=>h}}};const sz={kernelName:Ia,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_e(e,wt(rh(n)))}}};const iz={kernelName:$l,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(Ce(Ne(1),wt(n)),e)}}};const rz={kernelName:wy,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{reps:i}=n,o=()=>{let a=Qe(s);if(s.rank===1)for(let c=0;c<i[0];++c)a=be(a,nt(e,[c*s.shape[0]],[s.shape[0]]));else if(s.rank===2)for(let c=0;c<i[0];++c)for(let h=0;h<i[1];++h)a=be(a,nt(e,[c*s.shape[0],h*s.shape[1]],[s.shape[0],s.shape[1]]));else if(s.rank===3)for(let c=0;c<i[0];++c)for(let h=0;h<i[1];++h)for(let d=0;d<i[2];++d)a=be(a,nt(e,[c*s.shape[0],h*s.shape[1],d*s.shape[2]],[s.shape[0],s.shape[1],s.shape[2]]));else if(s.rank===4)for(let c=0;c<i[0];++c)for(let h=0;h<i[1];++h)for(let d=0;d<i[2];++d)for(let m=0;m<i[3];++m)a=be(a,nt(e,[c*s.shape[0],h*s.shape[1],d*s.shape[2],m*s.shape[3]],[s.shape[0],s.shape[1],s.shape[2],s.shape[3]]));else throw new Error(`Gradient for tile operation is not implemented for rank-${s.rank} tensors yet.`);return a};return{x:o}}};const oz={kernelName:Ul,gradFunc:(e,t,n)=>{const s=n,{perm:i}=s,o=Xl(i);return{x:()=>Me(e,o)}}};const az={kernelName:Ly,gradFunc:(e,t,n)=>{const s=n,{axis:i}=s;return{value:()=>rs(e,i)}}};const cz={kernelName:Sy,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[n]=t,s=()=>lz(e,n);return{x:s}}};function lz(e,t){const n=Ws(t,Qe(t)),s=Wa(e,n);let i=Ji(t,Ne(0,"int32"));const o=s.rank-i.rank;for(let c=0;c<o;++c)i=qn(i,c+1);i=$s(i,ni(s.shape,"bool"));const a=Qe(s);return _n(i,s,a)}const hz={kernelName:Iy,gradFunc:e=>({x:()=>Qe(e)})};const uz=[gM,yM,bM,wM,LM,SM,IM,xM,TM,AM,vM,NM,OM,kM,FM,_M,WM,$M,UM,BM,MM,zM,PM,YM,HM,qM,jM,KM,XM,JM,ZM,QM,eP,tP,sP,nP,iP,rP,oP,aP,cP,lP,hP,uP,dP,pP,gP,VA,VA,yP,LP,xP,TP,AP,vP,NP,CP,RP,OP,YA,YA,EP,DP,kP,FP,_P,WP,$P,UP,BP,MP,PP,zP,GP,VP,YP,HP,qP,jP,KP,XP,HA,HA,qA,qA,JP,QP,ZP,ez,tz,nz,sz,iz,rz,oz,az,cz,hz];for(const e of uz)Wx(e);Q.prototype.abs=function(){return this.throwIfDisposed(),sn(this)};Q.prototype.acos=function(){return this.throwIfDisposed(),ub(this)};Q.prototype.acosh=function(){return this.throwIfDisposed(),db(this)};Q.prototype.addStrict=function(e){return this.throwIfDisposed(),lA(this,e)};Q.prototype.add=function(e){return this.throwIfDisposed(),be(this,e)};Q.prototype.all=function(e,t){return this.throwIfDisposed(),kd(this,e,t)};Q.prototype.any=function(e,t){return this.throwIfDisposed(),Jl(this,e,t)};Q.prototype.argMax=function(e){return this.throwIfDisposed(),Zl(this,e)};Q.prototype.argMin=function(e){return this.throwIfDisposed(),mb(this,e)};Q.prototype.asScalar=function(){return this.throwIfDisposed(),k(this.size===1,()=>"The array must have only 1 element."),K(this,[])};Q.prototype.asType=function(e){return this.throwIfDisposed(),ve(this,e)};Q.prototype.as1D=function(){return this.throwIfDisposed(),K(this,[this.size])};Q.prototype.as2D=function(e,t){return this.throwIfDisposed(),K(this,[e,t])};Q.prototype.as3D=function(e,t,n){return this.throwIfDisposed(),K(this,[e,t,n])};Q.prototype.as4D=function(e,t,n,s){return this.throwIfDisposed(),K(this,[e,t,n,s])};Q.prototype.as5D=function(e,t,n,s,i){return this.throwIfDisposed(),K(this,[e,t,n,s,i])};Q.prototype.asin=function(){return this.throwIfDisposed(),fb(this)};Q.prototype.asinh=function(){return this.throwIfDisposed(),gb(this)};Q.prototype.atan=function(){return this.throwIfDisposed(),yb(this)};Q.prototype.atan2=function(e){return this.throwIfDisposed(),bb(this,e)};Q.prototype.atanh=function(){return this.throwIfDisposed(),wb(this)};Q.prototype.avgPool=function(e,t,n,s){return this.throwIfDisposed(),nh(this,e,t,n,s)};Q.prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),sh(this,e,t)};Q.prototype.batchNorm=function(e,t,n,s,i){return this.throwIfDisposed(),No(this,e,t,n,s,i)};Q.prototype.broadcastTo=function(e){return this.throwIfDisposed(),ih(this,e)};Q.prototype.cast=function(e){return this.throwIfDisposed(),ve(this,e)};Q.prototype.ceil=function(){return this.throwIfDisposed(),Tb(this)};Q.prototype.clipByValue=function(e,t){return this.throwIfDisposed(),Hn(this,e,t)};Q.prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof Q&&(e=[e]),Pt([this,...e],t)};Q.prototype.conv1d=function(e,t,n,s,i,o){return this.throwIfDisposed(),$d(this,e,t,n,s,i,o)};Q.prototype.conv2dTranspose=function(e,t,n,s,i){return this.throwIfDisposed(),Ud(this,e,t,n,s,i)};Q.prototype.conv2d=function(e,t,n,s,i,o){return this.throwIfDisposed(),Xi(this,e,t,n,s,i,o)};Q.prototype.cos=function(){return this.throwIfDisposed(),rh(this)};Q.prototype.cosh=function(){return this.throwIfDisposed(),Bd(this)};Q.prototype.cumsum=function(e,t,n){return this.throwIfDisposed(),Md(this,e,t,n)};Q.prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),Nb(this,e,t)};Q.prototype.depthwiseConv2D=function(e,t,n,s,i,o){return nn("depthwiseConv2D is deprecated, use depthwiseConv2d instead"),this.throwIfDisposed(),Co(this,e,t,n,s,i,o)};Q.prototype.depthwiseConv2d=function(e,t,n,s,i,o){return this.throwIfDisposed(),Co(this,e,t,n,s,i,o)};Q.prototype.dilation2d=function(e,t,n,s,i){return this.throwIfDisposed(),Cb(this,e,t,n,s,i)};Q.prototype.divNoNan=function(e){return this.throwIfDisposed(),Rb(this,e)};Q.prototype.divStrict=function(e){return this.throwIfDisposed(),hA(this,e)};Q.prototype.div=function(e){return this.throwIfDisposed(),_e(this,e)};Q.prototype.dot=function(e){return this.throwIfDisposed(),GT(this,e)};Q.prototype.elu=function(){return this.throwIfDisposed(),Oo(this)};Q.prototype.equalStrict=function(e){return this.throwIfDisposed(),sA(this,e)};Q.prototype.equal=function(e){return this.throwIfDisposed(),ti(this,e)};Q.prototype.erf=function(){return this.throwIfDisposed(),Ob(this)};Q.prototype.exp=function(){return this.throwIfDisposed(),Ls(this)};Q.prototype.expandDims=function(e){return this.throwIfDisposed(),qn(this,e)};Q.prototype.expm1=function(){return this.throwIfDisposed(),Eb(this)};Q.prototype.fft=function(){return this.throwIfDisposed(),fh(this)};Q.prototype.flatten=function(){return this.throwIfDisposed(),K(this,[this.size])};Q.prototype.floor=function(){return this.throwIfDisposed(),_a(this)};Q.prototype.floorDiv=function(e){return this.throwIfDisposed(),Dd(this,e)};Q.prototype.gather=function(e,t){return this.throwIfDisposed(),Wa(this,e,t)};Q.prototype.greaterEqualStrict=function(e){return this.throwIfDisposed(),iA(this,e)};Q.prototype.greaterEqual=function(e){return this.throwIfDisposed(),Ji(this,e)};Q.prototype.greaterStrict=function(e){return this.throwIfDisposed(),rA(this,e)};Q.prototype.greater=function(e){return this.throwIfDisposed(),Ss(this,e)};Q.prototype.ifft=function(){return this.throwIfDisposed(),za(this)};Q.prototype.irfft=function(){return this.throwIfDisposed(),np(this)};Q.prototype.isFinite=function(){return this.throwIfDisposed(),YT(this)};Q.prototype.isInf=function(){return this.throwIfDisposed(),HT(this)};Q.prototype.isNaN=function(){return this.throwIfDisposed(),qT(this)};Q.prototype.leakyRelu=function(e){return this.throwIfDisposed(),zd(this,e)};Q.prototype.lessEqualStrict=function(e){return this.throwIfDisposed(),oA(this,e)};Q.prototype.lessEqual=function(e){return this.throwIfDisposed(),kr(this,e)};Q.prototype.lessStrict=function(e){return this.throwIfDisposed(),aA(this,e)};Q.prototype.less=function(e){return this.throwIfDisposed(),ch(this,e)};Q.prototype.localResponseNormalization=function(e,t,n,s){return this.throwIfDisposed(),kb(this,e,t,n,s)};Q.prototype.logSigmoid=function(){return this.throwIfDisposed(),KT(this)};Q.prototype.logSoftmax=function(e){return this.throwIfDisposed(),Yd(this,e)};Q.prototype.logSumExp=function(e,t){return this.throwIfDisposed(),_b(this,e,t)};Q.prototype.log=function(){return this.throwIfDisposed(),ns(this)};Q.prototype.log1p=function(){return this.throwIfDisposed(),Gd(this)};Q.prototype.logicalAnd=function(e){return this.throwIfDisposed(),$s(this,e)};Q.prototype.logicalNot=function(){return this.throwIfDisposed(),lh(this)};Q.prototype.logicalOr=function(e){return this.throwIfDisposed(),Hd(this,e)};Q.prototype.logicalXor=function(e){return this.throwIfDisposed(),XT(this,e)};Q.prototype.matMul=function(e,t,n){return this.throwIfDisposed(),at(this,e,t,n)};Q.prototype.maxPool=function(e,t,n,s){return this.throwIfDisposed(),hh(this,e,t,n,s)};Q.prototype.max=function(e,t){return this.throwIfDisposed(),jn(this,e,t)};Q.prototype.maximumStrict=function(e){return this.throwIfDisposed(),uA(this,e)};Q.prototype.maximum=function(e){return this.throwIfDisposed(),Ws(this,e)};Q.prototype.mean=function(e,t){return this.throwIfDisposed(),Gt(this,e,t)};Q.prototype.min=function(e,t){return this.throwIfDisposed(),Ba(this,e,t)};Q.prototype.minimumStrict=function(e){return this.throwIfDisposed(),dA(this,e)};Q.prototype.minimum=function(e){return this.throwIfDisposed(),Eo(this,e)};Q.prototype.modStrict=function(e){return this.throwIfDisposed(),pA(this,e)};Q.prototype.mod=function(e){return this.throwIfDisposed(),qd(this,e)};Q.prototype.mulStrict=function(e){return this.throwIfDisposed(),mA(this,e)};Q.prototype.mul=function(e){return this.throwIfDisposed(),X(this,e)};Q.prototype.neg=function(){return this.throwIfDisposed(),zt(this)};Q.prototype.norm=function(e,t,n){return this.throwIfDisposed(),rp(this,e,t,n)};Q.prototype.notEqualStrict=function(e){return this.throwIfDisposed(),cA(this,e)};Q.prototype.notEqual=function(e){return this.throwIfDisposed(),Fr(this,e)};Q.prototype.oneHot=function(e,t=1,n=0){return this.throwIfDisposed(),To(this,e,t,n)};Q.prototype.onesLike=function(){return this.throwIfDisposed(),En(this)};Q.prototype.pad=function(e,t){return this.throwIfDisposed(),Ri(this,e,t)};Q.prototype.pool=function(e,t,n,s,i){return this.throwIfDisposed(),QT(this,e,t,n,s,i)};Q.prototype.powStrict=function(e){return this.throwIfDisposed(),fA(this,e)};Q.prototype.pow=function(e){return this.throwIfDisposed(),si(this,e)};Q.prototype.prelu=function(e){return this.throwIfDisposed(),dh(this,e)};Q.prototype.prod=function(e,t){return this.throwIfDisposed(),Kd(this,e,t)};Q.prototype.reciprocal=function(){return this.throwIfDisposed(),Mb(this)};Q.prototype.relu=function(){return this.throwIfDisposed(),Oi(this)};Q.prototype.relu6=function(){return this.throwIfDisposed(),Pb(this)};Q.prototype.reshapeAs=function(e){return this.throwIfDisposed(),K(this,e.shape)};Q.prototype.reshape=function(e){return this.throwIfDisposed(),K(this,e)};Q.prototype.resizeBilinear=function(e,t){return this.throwIfDisposed(),RA(this,e,t)};Q.prototype.resizeNearestNeighbor=function(e,t){return this.throwIfDisposed(),OA(this,e,t)};Q.prototype.reverse=function(e){return this.throwIfDisposed(),Is(this,e)};Q.prototype.rfft=function(){return this.throwIfDisposed(),gh(this)};Q.prototype.round=function(){return this.throwIfDisposed(),zb(this)};Q.prototype.rsqrt=function(){return this.throwIfDisposed(),Xd(this)};Q.prototype.selu=function(){return this.throwIfDisposed(),Jd(this)};Q.prototype.separableConv2d=function(e,t,n,s,i,o){return this.throwIfDisposed(),Gb(this,e,t,n,s,i,o)};Q.prototype.sigmoid=function(){return this.throwIfDisposed(),Ni(this)};Q.prototype.sign=function(){return this.throwIfDisposed(),Vb(this)};Q.prototype.sin=function(){return this.throwIfDisposed(),Zd(this)};Q.prototype.sinh=function(){return this.throwIfDisposed(),Qd(this)};Q.prototype.slice=function(e,t){return this.throwIfDisposed(),nt(this,e,t)};Q.prototype.softmax=function(e){return this.throwIfDisposed(),Wo(this,e)};Q.prototype.softplus=function(){return this.throwIfDisposed(),Ua(this)};Q.prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),uh(this,e,t)};Q.prototype.split=function(e,t){return this.throwIfDisposed(),is(this,e,t)};Q.prototype.sqrt=function(){return this.throwIfDisposed(),Ln(this)};Q.prototype.square=function(){return this.throwIfDisposed(),wt(this)};Q.prototype.squaredDifference=function(e){return this.throwIfDisposed(),yh(this,e)};Q.prototype.squaredDifferenceStrict=function(e){return this.throwIfDisposed(),gA(this,e)};Q.prototype.squeeze=function(e){return this.throwIfDisposed(),_r(this,e)};Q.prototype.stack=function(e,t){this.throwIfDisposed();const n=e instanceof Q?[this,e]:[this,...e];return rs(n,t)};Q.prototype.step=function(e){return this.throwIfDisposed(),Ga(this,e)};Q.prototype.stridedSlice=function(e,t,n,s,i,o,a,c){return this.throwIfDisposed(),Hb(this,e,t,n,s,i,o,a,c)};Q.prototype.subStrict=function(e){return this.throwIfDisposed(),yA(this,e)};Q.prototype.sub=function(e){return this.throwIfDisposed(),Ce(this,e)};Q.prototype.sum=function(e,t){return this.throwIfDisposed(),Ue(this,e,t)};Q.prototype.tan=function(){return this.throwIfDisposed(),qb(this)};Q.prototype.tanh=function(){return this.throwIfDisposed(),Fa(this)};Q.prototype.tile=function(e){return this.throwIfDisposed(),Dr(this,e)};Q.prototype.toBool=function(){return this.throwIfDisposed(),ve(this,"bool")};Q.prototype.toFloat=function(){return this.throwIfDisposed(),ve(this,"float32")};Q.prototype.toInt=function(){return this.throwIfDisposed(),ve(this,"int32")};Q.prototype.topk=function(e,t){return this.throwIfDisposed(),jb(this,e,t)};Q.prototype.transpose=function(e){return this.throwIfDisposed(),Me(this,e)};Q.prototype.unique=function(e){return this.throwIfDisposed(),sp(this,e)};Q.prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),Kb(this,e,t)};Q.prototype.unstack=function(e){return this.throwIfDisposed(),Ei(this,e)};Q.prototype.where=function(e,t){return this.throwIfDisposed(),_n(e,this,t)};Q.prototype.zerosLike=function(){return this.throwIfDisposed(),Qe(this)};let yp;function an(){return yp==null&&(yp=DT().epsilon()),yp}function YZ(e){yp=e}function ii(){return"channelsLast"}class tr extends Error{constructor(e){super(e);Object.setPrototypeOf(this,tr.prototype)}}class ri extends Error{constructor(e){super(e);Object.setPrototypeOf(this,ri.prototype)}}class j extends Error{constructor(e){super(e);Object.setPrototypeOf(this,j.prototype)}}class ze extends Error{constructor(e){super(e);Object.setPrototypeOf(this,ze.prototype)}}class jA extends Error{constructor(e){super(e);Object.setPrototypeOf(this,jA.prototype)}}class dz extends Error{constructor(e){super(e);Object.setPrototypeOf(this,dz.prototype)}}function Bo(e,t){if(Array.isArray(e)){let n=[];for(let s=0;s<t;s++)n=n.concat(e);return n}else{const n=new Array(t);return n.fill(e),n}}function xs(e,t){if(!e)throw new jA(t)}function KA(e,t){let n=0;for(const s of e)s===t&&n++;return n}function Kn(e){return e.length===1?e[0]:e}function Rt(e){return Array.isArray(e)?e:[e]}function HZ(e){const t=Rt(e);let n="";for(const s of t){if(s.id==null)throw new j(`Object ${s} passed to objectListUid without an id`);n!==""&&(n=n+", "),n=`${n}${Math.abs(s.id)}`}return n}function nr(e){const t=e.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2"),n=t.replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return n[0]!=="_"?n:"private"+n}function Mo(e){return e.length<=1||e.indexOf("_")===-1?e:e.replace(/[_]+(\w|$)/g,(t,n)=>n.toUpperCase())}let Us={};function yw(e){if(e==null)return null;const t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function bw(e){if(e==null||typeof e!="object")return;if(Array.isArray(e))e.forEach(t=>bw(t));else{const t=Object.keys(e);for(const n of t){const s=e[n];s!=null&&typeof s=="object"&&(!Array.isArray(s)&&s.type==="ndarray"&&typeof s.value=="number"?e[n]=s.value:bw(s))}}}function Ch(e,t={},n={},s="object",i=!1){if(typeof e=="string"){const o=e;let a;if(o in n)a=n[o];else if(o in Us)a=Us[o];else if(a=t[o],a==null)throw new j(`Unknown ${s}: ${e}. This may be due to one of the following reasons:
1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return a}else{const o=e;if(o.className==null||o.config==null)throw new j(`${s}: Improper config format: ${JSON.stringify(o)}.
'className' and 'config' must set.`);const a=o.className;let c,h;if(a in n?[c,h]=n[a]:a in Us?[c,h]=Us.className:a in t&&([c,h]=t[a]),c==null)throw new j(`Unknown ${s}: ${a}. This may be due to one of the following reasons:
1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(h!=null){const d={};for(const w of Object.keys(Us))d[w]=Us[w];for(const w of Object.keys(n))d[w]=n[w];const m=o.config;m.customObjects=d;const y=Object.assign({},Us);for(const w of Object.keys(n))Us[w]=n[w];bw(o.config);const b=h(c,o.config,n,i);return Us=Object.assign({},y),b}else{const d=Object.assign({},Us);for(const y of Object.keys(n))Us[y]=n[y];const m=new c(o.config);return Us=Object.assign({},d),m}}}function pz(e,t){return e<t?-1:e>t?1:0}function bp(e,t){return-1*pz(e,t)}function qZ(e){switch(e){case"float32":return"float32";default:throw new j(`Invalid dtype: ${e}`)}}function jZ(e,t){if(e==null||t==null)return e===t;if(e.length!==t.length)return!1;for(let n=0;n<e.length;++n)if(e[n]!==t[n])return!1;return!0}function Ur(e){if(e==null)return e;const t=[];for(const n of e)t.indexOf(n)===-1&&t.push(n);return t}function mz(e){if(e==null)throw new j(`Invalid value in obj: ${JSON.stringify(e)}`);for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function ja(e,t,n){if(n==null)return;if(e.indexOf(n)<0)throw new j(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function ww(e,t,n=0,s=Infinity){return xs(n>=0),xs(s>=n),Array.isArray(e)&&e.length>=n&&e.length<=s&&e.every(i=>typeof i===t)}function pn(e,t){Array.isArray(e)?(k(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,s)=>pn(n,`element ${s+1} of ${t}`))):k(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${XA(e)}.`)}function XA(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>XA(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function fz(e,t){let n=Yn(),s;const i=(...o)=>{const a=Yn();return a-n<t||(n=a,s=e(...o)),s};return i}function JA(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function KZ(...e){xs(e.length>0,"arrayOfValues is empty");for(const t of e)xs(Array.isArray(t),"one of the values is not an array"),xs(t.length>0,"one of the values is empty");return e.reduce((t,n)=>t.length===0?n.map(s=>[s]):n.map(s=>t.map(i=>[...i,s])).reduce((s,i)=>s.concat(i),[]),[])}function Lw(e,t){return ee(()=>Ln(Ue(X(e,e),t,!0)))}class Rh extends Ao{getConfig(){return{}}}class Sw extends Rh{constructor(e){super();this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return ee(()=>{const t=Lw(e,this.axis),n=Hn(t,0,this.maxValue);return X(e,_e(n,be(an(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}Sw.className="MaxNorm",me(Sw);class Iw extends Rh{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return ee(()=>_e(e,be(an(),Lw(e,this.axis))))}getConfig(){return{axis:this.axis}}}Iw.className="UnitNorm",me(Iw);class xw extends Rh{apply(e){return Oi(e)}}xw.className="NonNeg",me(xw);class Tw extends Rh{constructor(e){super();this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=e.minValue!=null?e.minValue:this.defaultMinValue,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.rate=e.rate!=null?e.rate:this.defaultRate,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return ee(()=>{const t=Lw(e,this.axis),n=be(X(this.rate,Hn(t,this.minValue,this.maxValue)),X(1-this.rate,t));return X(e,_e(n,be(an(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}Tw.className="MinMaxNorm",me(Tw);const ZA={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function cn(e){return yw(e)}function QA(e,t={}){return Ch(e,Fs.getMap().classNameMap,t,"constraint")}function ln(e){if(e==null)return null;if(typeof e=="string"){const t=e in ZA?ZA[e]:e,n={className:t,config:{}};return QA(n)}else return e instanceof Rh?e:QA(e)}function gz(e){return new Sw(e)}function yz(e){return new Iw(e)}function bz(){return new xw}function wz(e){return new Tw(e)}var Lz=Object.freeze({__proto__:null,maxNorm:gz,unitNorm:yz,nonNeg:bz,minMaxNorm:wz});const Sz=["channelsFirst","channelsLast"],Iz=["valid","same","causal"],xz=["max","avg"],Tz=["sum","mul","concat","ave"],XZ=["temporal"];const Ka=new Map;function Vt(e){ja(Sz,"DataFormat",e)}function Ts(e){ja(Iz,"PaddingMode",e)}function ev(e){ja(xz,"PoolMode",e)}const Oh=[],tv="/";function Po(e,t){Oh.push(e);try{const n=t();return Oh.pop(),n}catch(n){throw Oh.pop(),n}}function Az(){return Oh.length===0?"":Oh.join(tv)+tv}function nv(e){if(!iv(e))throw new Error("Not a valid tensor name: '"+e+"'");return Az()+e}function sv(e){if(!iv(e))throw new Error("Not a valid tensor name: '"+e+"'");Ka.has(e)||Ka.set(e,0);const t=Ka.get(e);if(Ka.set(e,Ka.get(e)+1),t>0){const n=`${e}_${t}`;return Ka.set(n,1),n}else return e}const vz=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function iv(e){return!!e.match(vz)}function Nz(e){return e===parseInt(e.toString(),10)}function Br(e,t,n){t==null&&(t=0),n==null&&(n=e.length);let s=1;for(let i=t;i<n;++i)s*=e[i];return s}function wp(e){return e=Array.isArray(e)?new Float32Array(e):e,ss(e)}function Xa(e){return Ba(wp(e)).dataSync()[0]}function Mr(e){return jn(wp(e)).dataSync()[0]}function Cz(e){return Ue(wp(e)).dataSync()[0]}function Rz(e){return Cz(e)/e.length}function JZ(e){const t=Ce(wp(e),Ne(Rz(e))),n=Ue(X(t,t)).dataSync()[0];return n/e.length}function ZZ(e){const t=e.slice().sort((i,o)=>i-o),n=Math.floor((t.length-1)/2),s=Math.ceil((t.length-1)/2);return n===s?t[n]:(t[n]+t[s])/2}function oi(e,t){if(t<e)throw new j(`end (${t}) < begin (${e}) is forbidden.`);const n=[];for(let s=e;s<t;++s)n.push(s);return n}let rv="webgl";function QZ(e){ET(e),rv=e}function eQ(){return rv}function tQ(){return!1}function nQ(e){const t=e.shape;return t.length>0?t.reduce((n,s)=>n*s):1}function Eh(e,t){return e.asType(t)}function Dh(e,t=-1){const n=e.shape.slice();return t<0&&(t=n.length+t+1),n.splice(t,0,1),e.reshape(n)}function Oz(e,t){return ee(()=>{if(e.shape.length!==2)throw new j(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);const n=Dh(e,1);return Nw(n,[1,t,1])})}function Ez(e){const t=[Br(e.shape)];return e.reshape(t)}function Dz(e){if(e.rank<=1)throw new j(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);const t=[e.shape[0],Br(e.shape,1)];return e.reshape(t)}function zo(e,t,n){return ee(()=>{switch(e.rank){case 1:return ep(e,t,n);case 2:return Yb(e,[t,0],[n,e.shape[1]]);case 3:return tp(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return mh(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return nt(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return nt(e,[t,0,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4],e.shape[5]]);default:throw new j(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Aw(e,t,n){return ee(()=>{switch(e.rank){case 1:return ep(e,t,n);case 2:return Yb(e,[0,t],[e.shape[0],n]);case 3:return tp(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return mh(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new j(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Lp(e,t,n,s){return ee(()=>{switch(e.rank){case 1:return ep(e,t,n);case 2:switch(s){case 1:return zo(e,t,n);case 2:return Aw(e,t,n);default:throw new j(`The axis is not within the rank of the tensor ${s}`)}case 3:switch(s){case 1:return zo(e,t,n);case 2:return tp(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return Aw(e,t,n);default:throw new j(`The axis is not within the rank of the tensor ${s}`)}case 4:switch(s){case 1:return zo(e,t,n);case 2:return mh(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return mh(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return Aw(e,t,n);default:throw new j(`The axis is not within the rank of the tensor ${s}`)}default:throw new j(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function vw(e,t=-1){let n;return t<0&&(n=e[0].rank,n!==0?t=n:t=0),t===e[0].rank&&(t=-1),Pt(e,t)}function ov(e,t){switch(e.rank){case 1:return UT([e,t]);case 2:return BT([e,t],0);case 3:return MT([e,t],0);case 4:return PT([e,t],0);default:throw new j(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function Nw(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new j(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return Dr(e,t)}function Sp(e,t=0,n=1,s,i){return Bb(e,t,n,s,i)}function Di(e,t,n,s){if(e.rank<2||t.rank<2)throw new ze(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3){const i=e.shape.slice(-1)[0],o=t.shape.slice(-2)[0];if(i!==o)throw new ze(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${e.shape} and y shape = ${t.shape}`)}if(e.rank===2&&t.rank===2){const i=!1,o=!1;return hp({a:e,b:t,transposeA:i,transposeB:o,bias:s?Cw(e.rank,s,ii()):null,activation:n})}else{const i=e.shape.slice(),o=i.pop();e=e.reshape([-1,o]);const a=t.shape.slice(),c=a.pop(),h=a.pop(),d=[...a,c],m=Array.from({length:t.rank},(L,T)=>T===0?t.rank-2:T<=t.rank-2?T-1:T);t=t.transpose(m).reshape([h,-1]);const y=[...i,...d],b=!1,w=!1;return hp({a:e,b:t,transposeA:b,transposeB:w,bias:s?Cw(e.rank,s,ii()):null,activation:n}).reshape(y)}}function sQ(e){return ee(()=>{const t=Qe(e),n=En(e);return _n(ti(e,t),t,_n(Ss(e,Qe(e)),n,X(-1,n)))})}function iQ(e,t){return ee(()=>{if(e.rank!==1)throw new Error("Only 1D one-hot tensors are supported in the deeplearn backend, at present.");return e=e.toInt(),To(e,t).toFloat()})}function av(e,t,n){return ee(()=>(Array.isArray(t)?t=ss(t,"int32"):t=t.toInt(),Wa(e,t,n)))}function kh(e){return X(e,e)}function rQ(e,t){return ee(()=>{if(typeof t=="number"&&(t=Ne(Math.round(t),"int32")),t.dtype!=="int32")throw new ze(`Non-int32 dtype (${t.dtype}) is not supported by pow() yet`);return si(e,t)})}function Cw(e,t,n){const s=t.shape;if(t.rank!==1&&t.rank!==e)throw new j(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(e===5){if(n==="channelsFirst")return s.length===1?t.reshape([1,s[0],1,1,1]):t.reshape([1,s[3],s[0],s[1],s[2]]);if(n==="channelsLast")return s.length===1?t.reshape([1,1,1,1,s[0]]):t.reshape([1].concat(s))}else if(e===4){if(n==="channelsFirst")return s.length===1?t.reshape([1,s[0],1,1]):t.reshape([1,s[2],s[0],s[1]]);if(n==="channelsLast")return s.length===1?t.reshape([1,1,1,s[0]]):t.reshape([1].concat(s))}else if(e===3){if(n==="channelsFirst")return s.length===1?t.reshape([1,s[0],1]):t.reshape([1,s[1],s[0]]);if(n==="channelsLast")return s.length===1?t.reshape([1,1,s[0]]):t.reshape([1].concat(s))}else if(e<3)return t;throw new j(`Unsupported input rank by biasAdd: ${t.rank}`)}function ki(e,t,n){return ee(()=>(n==null&&(n=ii()),Vt(n),e.add(Cw(e.rank,t,n))))}function kz(e,t=1){if(t!==1)throw new ze(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return Oo(e)}function Fz(e){return ee(()=>_e(e,sn(e).add(1)))}function cv(e,t,n,s){return ee(()=>SA(e,t,n,s))}function _z(e){return ee(()=>{const t=be(.5,X(.2,e));return Hn(t,0,1)})}function Fh(e,t,n=!1){return n?e():t()}const Wz=["fanIn","fanOut","fanAvg"],$z=["normal","uniform","truncatedNormal"],oQ=["Zeros","Ones","Constant","RandomNormal","RandomUniform","TruncatedNormal","VarianceScaling","Orthogonal","Identity"];function Uz(e){ja(Wz,"FanMode",e)}function Bz(e){ja($z,"Distribution",e)}class Bs extends Ao{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class Rw extends Bs{apply(e,t){return ct(e,t)}}Rw.className="Zeros",me(Rw);class Ip extends Bs{apply(e,t){return ni(e,t)}}Ip.className="Ones",me(Ip);class Ow extends Bs{constructor(e){super();if(typeof e!="object")throw new j(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new j(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return ee(()=>X(Ne(this.value),ni(e,t)))}getConfig(){return{value:this.value}}}Ow.className="Constant",me(Ow);class Ew extends Bs{constructor(e){super();this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=e.minval||this.DEFAULT_MINVAL,this.maxval=e.maxval||this.DEFAULT_MAXVAL,this.seed=e.seed}apply(e,t){return _o(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}Ew.className="RandomUniform",me(Ew);class Dw extends Bs{constructor(e){super();this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if(t=t||"float32",t!=="float32"&&t!=="int32")throw new ze(`randomNormal does not support dType ${t}.`);return Sp(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}Dw.className="RandomNormal",me(Dw);class kw extends Bs{constructor(e){super();this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if(t=t||"float32",t!=="float32"&&t!=="int32")throw new ze(`truncatedNormal does not support dType ${t}.`);return bh(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}kw.className="TruncatedNormal",me(kw);class Fw extends Bs{constructor(e){super();this.gain=e.gain!=null?e.gain:1}apply(e,t){return ee(()=>{if(e.length!==2||e[0]!==e[1])throw new j("Identity matrix initializer can only be used for 2D square matrices.");return X(this.gain,Pd(e[0]))})}getConfig(){return{gain:this.gain}}}Fw.className="Identity",me(Fw);function Mz(e,t="channelsLast"){let n,s;if(Vt(t),e.length===2)n=e[0],s=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){const i=Br(e,2);n=e[1]*i,s=e[0]*i}else if(t==="channelsLast"){const i=Br(e,0,e.length-2);n=e[e.length-2]*i,s=e[e.length-1]*i}}else{const i=Br(e);n=Math.sqrt(i),s=Math.sqrt(i)}return[n,s]}class Xn extends Bs{constructor(e){super();if(e.scale<0)throw new j(`scale must be a positive float. Got: ${e.scale}`);this.scale=e.scale==null?1:e.scale,this.mode=e.mode==null?"fanIn":e.mode,Uz(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,Bz(this.distribution),this.seed=e.seed}apply(e,t){const n=Mz(e),s=n[0],i=n[1];let o=this.scale;if(this.mode==="fanIn"?o/=Math.max(1,s):this.mode==="fanOut"?o/=Math.max(1,i):o/=Math.max(1,(s+i)/2),this.distribution==="normal"){const a=Math.sqrt(o);if(t=t||"float32",t!=="float32"&&t!=="int32")throw new ze(`${this.getClassName()} does not support dType ${t}.`);return bh(e,0,a,t,this.seed)}else{const a=Math.sqrt(3*o);return _o(e,-a,a,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}Xn.className="VarianceScaling",me(Xn);class xp extends Xn{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Xn.className}}xp.className="GlorotUniform",me(xp);class Tp extends Xn{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Xn.className}}Tp.className="GlorotNormal",me(Tp);class Ap extends Xn{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Xn.className}}Ap.className="HeNormal",me(Ap);class vp extends Xn{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Xn.className}}vp.className="HeUniform",me(vp);class Np extends Xn{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Xn.className}}Np.className="LeCunNormal",me(Np);class Cp extends Xn{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Xn.className}}Cp.className="LeCunNormal",me(Cp);class _w extends Bs{constructor(e){super();if(this.DEFAULT_GAIN=1,this.gain=e.gain==null?this.DEFAULT_GAIN:e.gain,this.seed=e.seed,this.seed!=null)throw new ze("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return ee(()=>{if(e.length<2)throw new ze("Shape must be at least 2D.");e[0]*e[1]>2e3&&console.warn(`Orthogonal initializer is being called on a matrix with more than 2000 (${e[0]*e[1]}) elements: Slowness may result.`);const n=e[0]>e[1]?[e[1],e[0]]:e,s=Sp(n,0,1,"float32");let i=DA.gramSchmidt(s);return e[0]>e[1]&&(i=i.transpose()),X(this.gain,i)})}getConfig(){return{gain:this.gain,seed:this.seed}}}_w.className="Orthogonal",me(_w);const lv={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function hv(e,t={}){return Ch(e,Fs.getMap().classNameMap,t,"initializer")}function Yt(e){return yw(e)}function Ft(e){if(typeof e=="string"){const t=e in lv?lv[e]:e;if(t==="GlorotNormal")return new Tp;if(t==="GlorotUniform")return new xp;if(t==="HeNormal")return new Ap;if(t==="HeUniform")return new vp;if(t==="LeCunNormal")return new Np;if(t==="LeCunUniform")return new Cp;{const n={};return n.className=t,n.config={},hv(n)}}else return e instanceof Bs?e:hv(e)}function Pz(){return new Rw}function zz(){return new Ip}function Gz(e){return new Ow(e)}function Vz(e){return new Ew(e)}function Yz(e){return new Dw(e)}function Hz(e){return new kw(e)}function qz(e){return new Fw(e)}function jz(e){return new Xn(e)}function Kz(e){return new xp(e)}function Xz(e){return new Tp(e)}function Jz(e){return new Ap(e)}function Zz(e){return new vp(e)}function Qz(e){return new Np(e)}function e3(e){return new Cp(e)}function t3(e){return new _w(e)}var n3=Object.freeze({__proto__:null,zeros:Pz,ones:zz,constant:Gz,randomUniform:Vz,randomNormal:Yz,truncatedNormal:Hz,identity:qz,varianceScaling:jz,glorotUniform:Kz,glorotNormal:Xz,heNormal:Jz,heUniform:Zz,leCunNormal:Qz,leCunUniform:e3,orthogonal:t3});let s3=0;function uv(){return s3++}const Rp={};function Op(e=""){return e in Rp||(Rp[e]=0),Rp[e]+=1,e+Rp[e].toString()}function Ww(e){return Array.isArray(e)&&Array.isArray(e[0])}function Ep(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function Ke(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new j(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function St(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(e.length===1)return e=e,e[0];throw new j(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function Dp(e){let t=0;for(const n of e)n.shape.length===0?t+=1:t+=n.shape.reduce((s,i)=>s*i);return t}const dv="Variable";class ai{constructor(e,t="float32",n=dv,s=!0,i=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=uv(),n=n==null?dv:n,this.originalName=nv(n),this.name=sv(this.originalName),this.trainable_=s,this.constraint=i,this.val=nA(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),i3(this.val,e),this.val.id!==e.id&&(this.val.assign(e),this.constraint!=null&&this.val.assign(this.constraint.apply(this.val))),this}dispose(){this.assertNotDisposed(),this.val.dispose()}assertNotDisposed(){if(this.val.isDisposed)throw new Error(`LayersVariable ${this.name} is already disposed.`)}get trainable(){return this.trainable_}set trainable(e){this.trainable_=e,this.val.trainable=e}}function i3(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function aQ(e,t,n,s){return new ai(e,t,n,!0,s)}function cQ(e,t,n){return new ai(ct(e),t,n)}function lQ(e,t,n){return new ai(Qe(e),t,n)}function hQ(e,t,n){const s=ni(e);return new ai(s,t,n)}function uQ(e,t,n){const s=En(e);return new ai(s,t,n)}function dQ(e,t,n){return new ai(Pd(e),t,n)}function pQ(e,t,n,s,i,o="randomUniform"){return new ai(_o(e,t,n,s),s,o)}function mQ(e,t=0,n=1,s,i,o="truncatedNormal"){if(s=s||"float32",s!=="float32"&&s!=="int32")throw new ze(`randomNormal does not support dType ${s}.`);return new ai(bh(e,t,n,s,i),s,o)}function fQ(e,t=0,n=1,s,i,o="randomNormal"){if(s=s||"float32",s!=="float32"&&s!=="int32")throw new ze(`randomNormalVariable does not support dType ${s}.`);return new ai(Bb(e,t,n,s,i),s,o)}function gQ(e,t){return e.write(t)}function yQ(e,t){return e.write(be(e.read(),t))}function bQ(e,t){return e.write(Ce(e.read(),t))}function $w(e){return e.map(t=>t.read())}function Uw(e){e.forEach(t=>{const n=t[0];n.write(t[1])})}function wQ(e,t){const n=t.map(i=>i.read()),s=Fb(e,n);return t.map(i=>s.grads[i.name])}class mn{constructor(e){this.dtype=e.dtype,this.shape=e.shape,e.shape!=null?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}}class ci{constructor(e,t,n,s,i,o,a){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=s,this.callArgs=i,this.outputTensorIndex=a,this.id=uv(),o!=null&&(this.originalName=nv(o),this.name=sv(this.originalName)),this.rank=t.length}}let r3=0;class kp{constructor(e,t){this.callArgs=t,this.id=r3++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(const n of e.inboundLayers)n!=null&&n.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){const e=[];for(const t of this.inboundLayers)t!=null?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}}let o3=0;class lt extends Ao{constructor(e={}){super();this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=o3++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let t=e.name;if(!t){const n=this.getClassName();t=nr(n)+"_"+Op(n)}if(this.name=t,this.trainable_=e.trainable==null?!0:e.trainable,e.inputShape!=null||e.batchInputShape!=null){let n;if(e.batchInputShape!=null)n=e.batchInputShape;else if(e.inputShape!=null){let i=null;e.batchSize!=null&&(i=e.batchSize),n=[i].concat(e.inputShape)}this.batchInputShape=n;let s=e.dtype;s==null&&(s=e.inputDType),s==null&&(s="float32"),this.dtype=s}e.weights!=null?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(this.inboundNodes.length===0)throw new ri(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new j(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return Kn(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return Kn(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new tr(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(this.inboundNodes.length===0)throw new tr(`Layer ${this.name} is not connected, no input to return.`);return Kn(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new tr(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new tr(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return Kn(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map(e=>e())}get updates(){return this._updates}get built(){return this._built}set built(e){this._built=e}get trainable(){return this.trainable_}set trainable(e){this._trainableWeights.forEach(t=>t.trainable=e),this.trainable_=e}get trainableWeights(){return this.trainable_?this._trainableWeights.filter(e=>e.trainable):[]}set trainableWeights(e){this._trainableWeights=e}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter(e=>!e.trainable).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(e){this._nonTrainableWeights=e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(e){if(e=Rt(e),this.inputSpec==null||this.inputSpec.length===0)return;const t=Rt(this.inputSpec);if(e.length!==t.length)throw new j(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let n=0;n<e.length;n++){const s=e[n],i=t[n];if(i==null)continue;const o=s.rank;if(i.ndim!=null&&o!==i.ndim)throw new j(`Input ${n} is incompatible with layer ${this.name}: expected ndim=${i.ndim}, found ndim=${o}`);if(i.maxNDim!=null&&o>i.maxNDim)throw new j(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${i.maxNDim}, found ndim=${o}`);if(i.minNDim!=null&&o<i.minNDim)throw new j(`Input ${n} is incompatible with layer ${this.name}: expected min_ndim=${i.minNDim}, found ndim=${o}.`);if(i.dtype!=null&&s.dtype!==i.dtype)throw new j(`Input ${n} is incompatible with layer ${this.name} : expected dtype=${i.dtype}, found dtype=${s.dtype}.`);if(i.axes){const a=s.shape;for(const c in i.axes){const h=Number(c),d=i.axes[c],m=h>=0?a[h]:a[a.length+h];if(d!=null&&[d,null].indexOf(m)===-1)throw new j(`Input ${n} is incompatible with layer ${this.name}: expected axis ${h} of input shape to have value ${d} but got shape ${a}.`)}}if(i.shape!=null)for(let a=0;a<i.shape.length;++a){const c=i.shape[a],h=s.shape[a];if(c!=null&&h!=null&&c!==h)throw new j(`Input ${n} is incompatible with layer ${this.name}: expected shape=${i.shape}, found shape=${s.shape}.`)}}}call(e,t){return e}invokeCallHook(e,t){this._callHook!=null&&this._callHook(e,t)}setCallHook(e){this._callHook=e}clearCallHook(){this._callHook=null}apply(e,t){t=t||{},this.assertNotDisposed();const n=Rt(e);let s=!0;for(const o of n)if(!(o instanceof ci)){s=!1;break}let i=!0;for(const o of n)if(o instanceof ci){i=!1;break}if(s===i)throw new j("Arguments to apply() must be all SymbolicTensors or all Tensors");return Po(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);const o=[];for(const a of Rt(e))o.push(a.shape);this.build(Kn(o)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&i&&(this._refCount=1)}if(this.assertInputCompatibility(e),i){let o=this.call(e,t);const a=Rt(o),c=[];for(let h of a)n.indexOf(h)!==-1&&(h=h.clone()),c.push(h);if(o=Kn(c),this.activityRegularizer!=null)throw new ze("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return o}else{const o=a3(e),a=this.computeOutputShape(o);let c;const h=c3(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?o[0]:o),a!=null&&a.length>0&&Array.isArray(a[0])?c=a.map((d,m)=>new ci(h,d,this,Rt(e),t,this.name,m)):c=new ci(h,a,this,Rt(e),t,this.name),this.addInboundNode(e,c,null,null,o,a,t),this._refCount++,this.activityRegularizer!=null)throw new ze("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return c}})}warnOnIncompatibleInputShape(e){if(this.batchInputShape==null)return;if(e.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach((n,s)=>{n!=null&&e[s]!=null&&e[s]!==n&&(t=!0)}),t&&console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(this.inboundNodes==null||this.inboundNodes.length===0)throw new tr(`The layer ${this.name} has never been called and thus has no defined output shape.`);const e=[];for(const t of this.inboundNodes){const n=JSON.stringify(t.outputShapes);e.indexOf(n)===-1&&e.push(n)}if(e.length===1){const t=this.inboundNodes[0].outputShapes;return Array.isArray(t)&&Array.isArray(t[0])&&t.length===1?t[0]:t}else throw new tr(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`)}countParams(){if(!this.built)throw new ri(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Dp(this.weights)}build(e){this.built=!0}getWeights(e=!1){return $w(e?this.trainableWeights:this.weights)}setWeights(e){ee(()=>{const t=this.weights;if(t.length!==e.length)throw new j(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(t.length===0)return;const n=[],s=$w(t);for(let i=0;i<s.length;++i){const o=s[i],a=t[i],c=e[i];if(!ot(o.shape,c.shape))throw new j(`Layer weight shape ${o.shape} not compatible with provided weight shape ${c.shape}`);n.push([a,c])}Uw(n)})}addWeight(e,t,n,s,i,o,a){if(this._addedWeightNames.indexOf(e)!==-1)throw new j(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),n==null&&(n="float32"),this.fastWeightInitDuringBuild&&(s=Ft("zeros"));const c=s.apply(t,n),h=new ai(c,n,e,o,a);return c.dispose(),i!=null&&this.addLoss(()=>i.apply(h.read())),o==null&&(o=!0),o?this._trainableWeights.push(h):this._nonTrainableWeights.push(h),h}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){if(e==null||Array.isArray(e)&&e.length===0)return;e=Rt(e),this._losses!==void 0&&this._losses!==null&&this.losses.push(...e)}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(t!=null)if(Array.isArray(t))t.forEach(n=>{if(n!=null)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)});else throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);return null}return t}addInboundNode(e,t,n,s,i,o,a=null){const c=Rt(e);t=Rt(t),n=Rt(n),s=Rt(s),i=Ep(i),o=Ep(o);const h=[],d=[],m=[];for(const y of c)h.push(y.sourceLayer),d.push(y.nodeIndex),m.push(y.tensorIndex);new kp({outboundLayer:this,inboundLayers:h,nodeIndices:d,tensorIndices:m,inputTensors:c,outputTensors:t,inputMasks:n,outputMasks:s,inputShapes:i,outputShapes:o},a);for(let y=0;y<t.length;y++)t[y].sourceLayer=this,t[y].nodeIndex=this.inboundNodes.length-1,t[y].tensorIndex=y}getConfig(){const e={name:this.name,trainable:this.trainable};return this.batchInputShape!=null&&(e.batchInputShape=this.batchInputShape),this.dtype!=null&&(e.dtype=this.dtype),e}disposeWeights(){return this.weights.forEach(e=>e.dispose()),this.weights.length}assertNotDisposed(){if(this._refCount===0)throw new Error(`Layer '${this.name}' is already disposed.`)}dispose(){if(!this.built)throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);if(this._refCount===null)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return--this._refCount===0&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}}function a3(e){e=Rt(e);const t=[];for(const n of e)t.push(n.shape);return Kn(t)}function c3(e){return"float32"}function pv(e,t,n){if((t==null||n!=null&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),t.inboundNodes.length===0)return[e];{const s=t.inboundNodes[n];if(s.inboundLayers.length===0)return s.inputTensors;{const i=[];for(let o=0;o<s.inboundLayers.length;o++){const a=s.inputTensors[o],c=s.inboundLayers[o],h=s.nodeIndices[o],d=pv(a,c,h);for(const m of d)i.indexOf(m)===-1&&i.push(m)}return i}}}class Ja extends lt{constructor(e){super({dtype:e.dtype,name:e.name!=null?e.name:Op("input").toString()});if(e.batchSize==null&&(e.batchSize=null),e.sparse==null&&(e.sparse=!1),this.trainable=!1,this.built=!0,this.sparse=e.sparse,e.inputShape!=null&&e.batchInputShape!=null)throw new j("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");let t=e.batchInputShape;if(t==null){if(e.inputShape==null)throw new j("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(e.batchSize!=null)throw new j("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");const n=e.dtype||"float32";this.batchInputShape=t,this.dtype=n,this.inputSpec=[{shape:t}];const s=new ci(this.dtype,this.batchInputShape,this,[],{},this.name);s.nodeIndex=0,s.tensorIndex=0,new kp({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[s],outputTensors:[s],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new j(`Cannot pass any input to an InputLayer's apply() method. InputLayer name: ${this.name}`)}dispose(){return{refCountAfterDispose:this._refCount,numDisposedVariables:0}}getConfig(){return{batchInputShape:this.batchInputShape,dtype:this.dtype,sparse:this.sparse,name:this.name}}}Ja.className="InputLayer",me(Ja);function mv(e){if(e.batchShape==null&&e.shape==null)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(e.batchShape!=null&&e.shape!=null)throw new j("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let t=e.batchShape;e.shape!=null&&t==null&&(t=[null].concat(e.shape));let n=e.dtype;n==null&&(n="float32");const s=new Ja({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}),i=s.inboundNodes[0].outputTensors;return i[0]}async function Pr(e){if(e==null)return;const t=[],n=[],s=[];for(const i in e){const o=e[i];if(typeof o!="number"){const a=o;t.push(a.data()),n.push(i),s.push(a)}}if(t.length>0){const i=await Promise.all(t);for(let o=0;o<i.length;++o)e[n[o]]=i[o][0];He(s)}}function fv(e){if(e==null)return;for(const t in e){const n=e[t];typeof n!="number"&&n.dispose()}}var gv;(function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"})(gv||(gv={}));const l3=125;class Za{constructor(){this.validationData=null}setParams(e){this.params=e}async onEpochBegin(e,t){}async onEpochEnd(e,t){}async onBatchBegin(e,t){}async onBatchEnd(e,t){}async onTrainBegin(e){}async onTrainEnd(e){}setModel(e){}}class yv{constructor(e,t=10){e==null&&(e=[]),this.callbacks=e,this.queueLength=t}append(e){this.callbacks.push(e)}setParams(e){for(const t of this.callbacks)t.setParams(e)}setModel(e){for(const t of this.callbacks)t.setModel(e)}async onEpochBegin(e,t){t==null&&(t={});for(const n of this.callbacks)await n.onEpochBegin(e,t)}async onEpochEnd(e,t){t==null&&(t={});for(const n of this.callbacks)await n.onEpochEnd(e,t)}async onBatchBegin(e,t){t==null&&(t={});for(const n of this.callbacks)await n.onBatchBegin(e,t)}async onBatchEnd(e,t){t==null&&(t={});for(const n of this.callbacks)await n.onBatchEnd(e,t)}async onTrainBegin(e){e==null&&(e={});for(const t of this.callbacks)await t.onTrainBegin(e)}async onTrainEnd(e){e==null&&(e={});for(const t of this.callbacks)await t.onTrainEnd(e)}}class h3 extends Za{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){t==null&&(t={});const n=t.size==null?0:t.size;this.seen+=n;for(const s in t){const i=t[s];if(typeof i=="number")this.totals.hasOwnProperty(s)||(this.totals[s]=0),this.totals[s]=this.totals[s]+i*n;else{let o;s in this.totals?o=this.totals[s]:this.totals[s]=0;const a=ee(()=>be(this.totals[s],X(i,n)));this.totals[s]=a,o!=null&&o.dispose()}}}async onEpochEnd(e,t){if(t!=null)for(const n of this.params.metrics){if(this.totals[n]==null)continue;typeof this.totals[n]=="number"?t[n]=this.totals[n]/this.seen:ee(()=>{const s=X(_e(1,this.seen),this.totals[n]);t[n]=s,this.totals[n].dispose(),Cn(t[n])})}}}class bv extends Za{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){t==null&&(t={}),this.epoch.push(e);for(const n in t)this.history[n]==null&&(this.history[n]=[]),this.history[n].push(t[n])}async syncData(){const e=[],t=[],n=[];for(const i in this.history){const o=this.history[i];for(let a=0;a<o.length;++a)if(typeof o[a]!="number"){const c=o[a];e.push(c.data()),t.push(i),n.push(a)}}const s=await Promise.all(e);for(let i=0;i<s.length;++i){const o=this.history[t[i]][n[i]];o.dispose(),this.history[t[i]][n[i]]=s[i][0]}}}class wv extends Za{constructor(e,t){super();if(this.currentEpoch=0,this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=l3),this.yieldEvery==="never"&&e.onYield!=null)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");fd(this.yieldEvery)&&(this.maybeWait=fz(this.maybeWait.bind(this),this.yieldEvery)),this.trainBegin=e.onTrainBegin,this.trainEnd=e.onTrainEnd,this.epochBegin=e.onEpochBegin,this.epochEnd=e.onEpochEnd,this.batchBegin=e.onBatchBegin,this.batchEnd=e.onBatchEnd,this.yield=e.onYield}async maybeWait(e,t,n){const s=[];this.yield!=null&&(await Pr(n),s.push(this.yield(e,t,n))),s.push(mp()),await Promise.all(s)}async onEpochBegin(e,t){this.currentEpoch=e,this.epochBegin!=null&&(await Pr(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){const n=[];this.epochEnd!=null&&(await Pr(t),n.push(this.epochEnd(e,t))),this.yieldEvery==="epoch"&&n.push(mp()),await Promise.all(n)}async onBatchBegin(e,t){this.batchBegin!=null&&(await Pr(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){const n=[];this.batchEnd!=null&&(await Pr(t),n.push(this.batchEnd(e,t))),this.yieldEvery==="batch"?n.push(mp()):fd(this.yieldEvery)&&n.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(n)}async onTrainBegin(e){this.trainBegin!=null&&(await Pr(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await Pr(e),await this.trainEnd(e))}}function Lv(e,t){if(e==null&&(e={}),e instanceof Za)return[e];if(Array.isArray(e)&&e[0]instanceof Za)return e;const n=Rt(e);return n.map(s=>new wv(s,t))}class Ms{constructor(){}static registerCallbackConstructor(e,t){k(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),Ms.checkForDuplicate(t),Ms.constructors[e]==null&&(Ms.constructors[e]=[]),Ms.constructors[e].push(t)}static checkForDuplicate(e){for(const t in Ms.constructors){const n=Ms.constructors[+t];n.forEach(s=>{if(s===e)throw new j("Duplicate callback constructor.")})}}static clear(){Ms.constructors={}}static createCallbacks(e){const t=[];for(const n in Ms.constructors){const s=+n;e>=s&&t.push(...Ms.constructors[s])}return t.map(n=>new n)}}Ms.constructors={};function Sv(e,t,n,s,i,o,a,c,h){const d=new bv,m=[new h3,...Ms.createCallbacks(t)];e!=null&&m.push(...e),m.push(d);const y=new yv(m);return y.setParams({epochs:n,initialEpoch:s,samples:i,steps:o,batchSize:a,verbose:t,doValidation:c,metrics:h}),{callbackList:y,history:d}}function li(e,t={},n=!1){return Ch(e,Fs.getMap().classNameMap,t,"layer",n)}function Fp(e,t){return ee(()=>{e.dtype!=="float32"&&(e=e.asType("float32"));const n=Ue(kh(e),t,!0),s=oh(n.shape,an()),i=Ln(Ws(n,s));return _e(e,i)})}function sr(e,t){return ee(()=>Gt(kh(Ce(t,e)),-1))}function Qa(e,t){return ee(()=>Gt(sn(Ce(t,e)),-1))}function zr(e,t){return ee(()=>{const n=Ce(e,t),s=Hn(sn(e),an(),Number.MAX_VALUE),i=sn(_e(n,s));return X(100,Gt(i,-1))})}function Bw(e,t){return ee(()=>{const n=Hn(t,an(),Number.MAX_VALUE),s=ns(be(1,n)),i=Hn(e,an(),Number.MAX_VALUE),o=ns(be(1,i));return Gt(kh(Ce(s,o)),-1)})}function u3(e,t){return ee(()=>{const n=Ws(0,Ce(1,X(e,t)));return Gt(kh(n),-1)})}function d3(e,t){return ee(()=>{const n=Ws(0,Ce(1,X(e,t)));return Gt(n,-1)})}function p3(e,t){return ee(()=>{const n=Ue(X(e,t),-1),s=jn(X(Ce(1,e),t),-1);return Ws(0,be(1,Ce(s,n)))})}function m3(e,t){return ee(()=>{const n=Math.log(2),s=Ce(t,e),i=Ce(be(s,Ua(X(-2,s))),n);return Gt(i,-1)})}function _h(e,t,n=!1){return ee(()=>{if(n)t=Wo(t);else{const s=Ue(t,t.shape.length-1,!0);t=_e(t,s)}return t=Hn(t,an(),1-an()),zt(Ue(X(e.toFloat(),ns(t)),t.shape.length-1))})}function _p(e,t,n=!1){return ee(()=>{const s=_a(Ez(e)).toInt();t=Hn(t,an(),1-an());const i=t.shape,o=To(s,i[i.length-1]).reshape(i);return _h(o,t,n)})}function f3(e,t){if(!ot(e.shape,t.shape))throw new j(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return ee(()=>{const n=t.relu(),s=t.abs().neg();return n.sub(t.mul(e)).add(s.exp().log1p())})}function Wp(e,t){return ee(()=>{let n;return n=Hn(t,an(),1-an()),n=ns(_e(n,Ce(1,n))),Gt(f3(e,n),-1)})}function Mw(e,t){return ee(()=>{const n=Hn(e,an(),1),s=Hn(t,an(),1);return Ue(X(e,ns(_e(n,s))),-1)})}function g3(e,t){return ee(()=>{const n=ns(be(an(),t));return Gt(Ce(t,X(e,n)),-1)})}function $p(e,t){return ee(()=>{const n=Fp(e,-1),s=Fp(t,-1),i=X(n,s);return zt(Ue(i,-1))})}const LQ=sr,SQ=sr,IQ=Qa,xQ=Qa,TQ=zr,AQ=zr,vQ=Bw,NQ=Bw,CQ=Mw,RQ=Mw,OQ=$p,Up={meanSquaredError:sr,meanAbsoluteError:Qa,meanAbsolutePercentageError:zr,meanSquaredLogarithmicError:Bw,squaredHinge:u3,hinge:d3,categoricalHinge:p3,logcosh:m3,categoricalCrossentropy:_h,sparseCategoricalCrossentropy:_p,binaryCrossentropy:Wp,kullbackLeiblerDivergence:Mw,poisson:g3,cosineProximity:$p};function Pw(e){if(typeof e=="string"){if(e in Up)return Up[e];let t=`Unknown loss ${e}`;throw e.toLowerCase().includes("softmaxcrossentropy")&&(t=`Unknown loss ${e}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new j(t)}else return e}function zw(e,t){return ee(()=>{const n=X(.5,En(t)),s=Eh(Ss(t,n),e.dtype);return Gt(ti(e,s),-1)})}function Gw(e,t){return ee(()=>Eh(ti(Zl(e,-1),Zl(t,-1)),"float32"))}function Iv(e,t){return ee(()=>$s(e.equal(1),t.equal(1)).sum().cast("float32"))}function y3(e,t){return ee(()=>$s(e.equal(1),t.equal(0)).sum().cast("float32"))}function b3(e,t){return ee(()=>$s(e.equal(0),t.equal(1)).sum().cast("float32"))}function xv(e,t){return ee(()=>{const n=Iv(e,t),s=b3(e,t),i=n.add(s);return _n(Ss(i,0),n.div(i),0).cast("float32")})}function w3(e,t){return ee(()=>{const n=Iv(e,t),s=y3(e,t),i=n.add(s);return _n(Ss(i,0),n.div(i),0).cast("float32")})}function Tv(e,t){return Wp(e,t)}function Av(e,t){return e.rank===t.rank&&(e=e.squeeze([e.rank-1])),t=t.argMax(-1),t.dtype!==e.dtype&&(t=t.asType(e.dtype)),ti(e,t).asType("float32")}function EQ(e,t){throw new ze}function DQ(e,t){throw new ze}const L3=sr,S3=sr,I3=Qa,x3=Qa,T3=zr,A3=zr,Vw=_h,v3=$p,vv=_p,Bp={binaryAccuracy:zw,categoricalAccuracy:Gw,precision:xv,categoricalCrossentropy:Vw,sparseCategoricalCrossentropy:vv,mse:L3,MSE:S3,mae:I3,MAE:x3,mape:T3,MAPE:A3,cosine:v3};function N3(e){if(typeof e=="string"&&e in Bp)return Bp[e];if(typeof e!="string"&&e!=null)return e;throw new j(`Unknown metric ${e}`)}function Mp(e){if(xs(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(const n of Object.keys(Up))if(Up[n]===e){t=n;break}if(t!==void 0)return t;for(const n of Object.keys(Bp))if(Bp[n]===e){t=n;break}return t!==void 0?t:e.name}}function C3(e){const t={Adagrad:()=>Uo.adagrad(.01),Adadelta:()=>Uo.adadelta(1,.95,an()),Adam:()=>Uo.adam(.001,.9,.999,an()),Adamax:()=>Uo.adamax(.002,.9,.999,an(),0),RMSProp:()=>Uo.rmsprop(.001,.9,0,an()),SGD:()=>Uo.sgd(.01)};if(t.adagrad=t.Adagrad,t.adadelta=t.Adadelta,t.adam=t.Adam,t.adamax=t.Adamax,t.rmsprop=t.RMSProp,t.sgd=t.SGD,e in t)return t[e]();throw new j(`Unknown Optimizer ${e}`)}const Nv=1*1024*1024;function Cv(e,t,n=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!Yw(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){const s=JSON.stringify(e);s.length>Nv&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${s.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= ${Nv}.`)}}function Yw(e){if(e===null)return!0;if(typeof e=="object")if(Object.getPrototypeOf(e)===Object.prototype){const t=Object.keys(e);for(const n of t){if(typeof n!="string")return!1;if(!Yw(e[n]))return!1}return!0}else if(Array.isArray(e)){for(const t of e)if(!Yw(t))return!1;return!0}else return!1;else{const t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function R3(e,t,n,s=console.log){const i=E3(e),o=["Layer (type)","Output shape","Param #"];i?(t=t||65,n=n||[.45,.85,1]):(t=t||98,n=n||[.33,.55,.67,1]),n[n.length-1]<=1&&(n=n.map(m=>Math.floor(t*m)));let a;if(!i){o.push("Receives inputs"),a=[];for(const m in e.nodesByDepth)a.push(...e.nodesByDepth[m])}s("_".repeat(t)),Pp(o,n,s),s("=".repeat(t));const c=e.layers;for(let m=0;m<c.length;++m)i?D3(c[m],n,s):k3(c[m],n,a,s),s((m===c.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();const h=O3(e),d=Dp(e.nonTrainableWeights);s(`Total params: ${h+d}`),s(`Trainable params: ${h}`),s(`Non-trainable params: ${d}`),s("_".repeat(t))}function O3(e){let t;return e.collectedTrainableWeights!=null?t=Dp(e.collectedTrainableWeights):t=Dp(e.trainableWeights),t}function E3(e){let t=!0;const n=[],s=[];for(const i in e.nodesByDepth)n.push(e.nodesByDepth[i]);for(const i of n){if(i.length>1||i.length===1&&i[0].inboundLayers.length>1){t=!1;break}s.push(...i)}if(t)for(const i of e.layers){let o=!1;for(const a of i.inboundNodes)if(s.indexOf(a)!==-1)if(o){t=!1;break}else o=!0;if(!t)break}return t}function Pp(e,t,n=console.log){let s="";for(let i=0;i<e.length;++i)i>0&&(s=s.slice(0,s.length-1)+" "),s+=e[i],s=s.slice(0,t[i]),s+=" ".repeat(t[i]-s.length);n(s)}function D3(e,t,n){let s;try{s=JSON.stringify(e.outputShape)}catch(c){s="multiple"}const i=e.name,o=e.getClassName(),a=[`${i} (${o})`,s,e.countParams().toString()];Pp(a,t,n)}function k3(e,t,n,s){let i;try{i=JSON.stringify(e.outputShape)}catch(m){i="multiple"}const o=[];for(const m of e.inboundNodes){if(n!=null&&n.length>0&&n.indexOf(m)===-1)continue;for(let y=0;y<m.inboundLayers.length;++y){const b=m.inboundLayers[y].name,w=m.nodeIndices[y],L=m.tensorIndices[y];o.push(`${b}[${w}][${L}]`)}}const a=e.name,c=e.getClassName(),h=o.length===0?"":o[0],d=[`${a} (${c})`,i,e.countParams().toString(),h];Pp(d,t,s);for(let m=1;m<o.length;++m)Pp(["","","",o[m]],t,s)}function Rv(e,t,n){return(e==="inboundNodes"||e==="outputLayers"||e==="inputLayers")&&t===0&&typeof n=="string"}function Wh(e,t){if(e===null)return null;if(typeof e=="string")return Mo(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){const n=[],s=e.length;for(let i=0;i<s;++i){const o=e[i];Rv(t,i,o)?n.push(o):n.push(Wh(o,t))}return n}else{const n={};for(const s of Object.keys(e)){const i=e[s];if(s==="name"&&typeof i=="string")n[s]=i;else{const o=Mo(s);n[o]=Wh(i,o)}}return n}}function Hw(e,t){if(e==null)return null;if(typeof e=="string")return nr(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){const n=[],s=e.length;for(let i=0;i<s;++i){const o=e[i];Rv(t,i,o)?n.push(o):n.push(Hw(o,t))}return n}else{const n={};for(const s of Object.keys(e)){const i=e[s],o=nr(s);(s==="name"||s==="className")&&typeof i=="string"?n[o]=i:n[o]=Hw(i,s)}return n}}const zp="2.6.0";function F3(e,t){if(e.dtype==null||e.dtype===t.dtype)return t;try{return ve(t,e.dtype)}catch(n){throw new j(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}class Go{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof Go)for(const t in e.id2Value)this.id2Value[t]=e.id2Value[t],t in e.id2Mask&&(this.id2Mask[t]=e.id2Mask[t]);else{if(e==null)return;for(const t of e)this.add(t.key,t.value)}}add(e,t,n){if(this.id2Value[e.id]==null)this.id2Value[e.id]=F3(e,t),this.name2Id[e.name]=e.id,n!=null&&(this.id2Mask[e.id]=n);else throw new j(`Duplicate key: name=${e.name}, id=${e.id}`);return this}addFeed(e){this.add(e.key,e.value)}hasKey(e){return this.id2Value[e.id]!=null}names(){return Object.keys(this.name2Id)}getValue(e){if(e instanceof ci){if(this.id2Value[e.id]==null)throw new j(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}else{const t=this.name2Id[e];if(t==null)throw new j(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof ci){if(this.id2Value[e.id]==null)throw new j(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}else{const t=this.name2Id[e];if(t==null)throw new j(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){this.id2Mask!=null&&He(this.id2Mask)}}const qw={},Ov={};function $h(e,t,n,s){const i=n==null?!1:n.training,o=Array.isArray(e),a=o?e:[e],c=a.map(L=>L.name),h=[],d=t.names();for(const L of c)d.indexOf(L)!==-1?h.push(t.getValue(L)):h.push(null);s!=null&&(s.maxNumTensors=-Infinity,s.minNumTensors=Infinity);const m=c.join(",")+"|"+t.names().join(",");let y,b;if(qw[m]==null){const L=_3(a,t);y=L.sorted,b=L.recipientCounts,qw[m]=y,Ov[m]=b}y=qw[m],b={},i||Object.assign(b,Ov[m]);const w=new Go(t);for(let L=0;L<y.length;++L){if(s!=null){const q=Ed().numTensors;q>s.maxNumTensors&&(s.maxNumTensors=q),q<s.minNumTensors&&(s.minNumTensors=q)}const T=y[L],A=T.sourceLayer;if(A instanceof Ja)continue;const N=[],E=[],D=[];let F=!1;for(const q of T.inputs){const J=w.getValue(q),re=w.getMask(q);N.push(J),E.push(re),re!=null&&(F=!0),i||(b[q.name]--,b[q.name]===0&&!t.hasKey(q)&&c.indexOf(q.name)===-1&&!J.isDisposed&&q.sourceLayer.stateful!==!0&&D.push(J))}F&&(n=n||{},n.mask=E[0]);const _=Rt(A.apply(N,n));let B=null;A.supportsMasking&&(B=A.computeMask(N,E));const $=$3(T),H=Array.isArray($)?$:[$];for(let q=0;q<H.length;++q){w.hasKey(H[q])||w.add(H[q],_[q],Array.isArray(B)?B[0]:B);const J=c.indexOf(H[q].name);J!==-1&&(h[J]=_[q])}i||He(D)}return w.disposeMasks(),o?h:h[0]}function _3(e,t){k(e!=null&&e.length>0,()=>"Expected at least one fetch, got none");let n=[],s={};if(e.length===1){const i=Ev(e[0],t);n=i.sorted,s=i.recipientMap}else{const i=new Set;for(const o of e){const{sorted:a,recipientMap:c}=Ev(o,t);for(const h of a)i.has(h.name)||(n.push(h),i.add(h.name));for(const h in c)s[h]==null&&(s[h]=new Set),c[h].forEach(d=>s[h].add(d))}}return{sorted:n,recipientCounts:W3(s)}}function W3(e){const t={};for(const n in e)t[n]=e[n].size;return t}function Ev(e,t){const n=new Set,s=[],i={};for(const c of t.names())n.add(c);const o=[],a=[];for(o.push(e);o.length>0;){const c=o[o.length-1];if(n.has(c.name)){o.pop();continue}const h=a[a.length-1]===o.length-1;if(c.inputs.length===0||h)o.pop(),s.push(c),n.add(c.name),h&&a.pop();else{a.push(o.length-1);for(const d of c.inputs){if(i[d.name]==null&&(i[d.name]=new Set),i[d.name].add(c.name),n.has(d.name))continue;o.push(d)}}}return{sorted:s,recipientMap:i}}function $3(e){let t;if(e.sourceLayer.inboundNodes.length===1)t=e.sourceLayer.output;else{let n=null;for(let s=0;s<e.sourceLayer.inboundNodes.length;++s)for(const i of e.sourceLayer.inboundNodes[s].outputTensors)if(i.id===e.id){n=s;break}t=e.sourceLayer.getOutputAt(n)}return t}class Fi extends lt{constructor(e){super({});if(this.containerNodes=new Set,this.name=e.name,this.name==null){const N=this.getClassName().toLowerCase();this.name=Op(N)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(e.inputs)?this.inputs=e.inputs.slice():this.inputs=[e.inputs],Array.isArray(e.outputs)?this.outputs=e.outputs.slice():this.outputs=[e.outputs],Ur(this.inputs).length!==this.inputs.length)throw new j(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(N=>N.name)}`);Ur(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map(N=>N.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(const N of this.outputs){const E=N.sourceLayer,D=N.nodeIndex,F=N.tensorIndex;this.outputLayers.push(E),this.outputLayersNodeIndices.push(D),this.outputLayersTensorIndices.push(F)}for(const N of this.inputs){const E=N.sourceLayer,D=N.nodeIndex,F=N.tensorIndex;xs(D===0,"input layer has >1 nodes"),xs(F===0,"input layer has >1 tensors"),this.inputLayers.push(E),this.inputLayersNodeIndices.push(D),this.inputLayersTensorIndices.push(F)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let N=0;N<this.inputLayers.length;N++){const E=this.inputLayers[N];if(!(E instanceof Ja))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${N} (0-based) originates from layer type ${E.getClassName()}.`);this.inputNames.push(E.name),this.feedInputShapes.push(E.batchInputShape),this.feedInputNames.push(E.name)}for(const N of this.outputLayers)this.outputNames.push(N.name);this.internalInputShapes=this.inputs.map(N=>N.shape),this.internalOutputShapes=this.outputs.map(N=>N.shape);const t={},n={},s={},i={},o={},a=[],c=(N,E,D,F,_,B)=>{(F==null||_==null||B==null)&&(F=N.sourceLayer,_=N.nodeIndex,B=N.tensorIndex);const $=F.inboundNodes[_];if(D.indexOf($)!==-1)throw new ri(`The tensor ${N.name} at layer "${F.name}" is part of a cycle.`);if(E.indexOf($)!==-1)return;this.containerNodes.add(Fi.nodeKey(F,_)),F.id in o||(o[F.id]=Object.keys(o).length),D.indexOf($)===-1&&D.push($);const H=$.inboundLayers.length;for(let q=0;q<H;q++){const J=$.inputTensors[q],re=$.inboundLayers[q],ce=$.nodeIndices[q],ue=$.tensorIndices[q];c(J,E,D,re,ce,ue)}for(E.push($);D.indexOf($)>=0;)D.splice(D.indexOf($),1);a.push($)},h=[],d=[];for(const N of this.outputs)c(N,h,d);const m=a.slice().reverse();for(const N of m){n[N.id]=N,N.id in t||(t[N.id]=0);let E=t[N.id];const D=s[N.outboundLayer.id]==null?0:s[N.outboundLayer.id];E=Math.max(E,D),s[N.outboundLayer.id]=E,i[N.outboundLayer.id]=N.outboundLayer,t[N.id]=E;for(let F=0;F<N.inboundLayers.length;F++){const _=N.inboundLayers[F],B=N.nodeIndices[F],$=_.inboundNodes[B],H=t[$.id]==null?0:t[$.id];t[$.id]=Math.max(E+1,H),n[$.id]=$}}const y={};for(const N in t){const E=t[N];E in y||(y[E]=[]),y[E].push(n[N])}const b={};for(const N in s){const E=s[N];E in b||(b[E]=[]),b[E].push(i[N])}let w=Object.keys(b).map(N=>parseInt(N,10)).sort(bp);this.layers=[];for(const N of w){const E=b[N];E.sort((D,F)=>{const _=o[D.id],B=o[F.id];return _<B?-1:_>B?1:0});for(const D of E)D instanceof Fi&&this.internalContainerRefs.push(D),this.layers.push(D)}this.layersByDepth=b,w=Object.keys(y).map(N=>parseInt(N,10)).sort(bp);const L=this.inputs.slice(),T=[];for(const N of w)for(const E of y[N]){const D=E.outboundLayer;if(D!=null){for(const F of E.inputTensors)if(L.indexOf(F)===-1)throw new ri(`Graph disconnected: cannot obtain value for tensor ${F} at layer "${D.name}". The following previous layers were accessed without issue: ${T}`);for(const F of E.outputTensors)L.push(F);T.push(D.name)}}this.nodesByDepth=y;const A=this.layers.map(N=>N.name);for(const N of A){const E=A.filter(D=>D===N).length;if(E!==1)throw new ri(`The name "${N}" is used ${E} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(A))}this.outboundNodes=[],this.inboundNodes=[],new kp({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(N=>null),outputMasks:this.outputs.map(N=>null),inputShapes:this.inputs.map(N=>N.shape),outputShapes:this.outputs.map(N=>N.shape)}),this.built=!0,this._refCount=1}assertNotDisposed(){if(this._refCount===0)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();const e={refCountAfterDispose:null,numDisposedVariables:0};if(--this._refCount===0){for(const t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(const t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach(t=>{t._trainableWeights.forEach(n=>n.trainable=e)}),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new j("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(const t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const n of this.layers)t.push(...n.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){const n={};let s=0;for(const o of this.layers)for(const a of o.weights){if(n[a.originalName]!=null)throw new j(`Duplicate weight name: ${a.originalName}`);n[a.originalName]=a,s++}const i=[];for(const o in e){let a=o;if(n[o]==null){const c=o.split("/"),h=c.slice(0,-2).concat([c[c.length-1]]);a=h.join("/")}if(n[a]!=null)i.push([n[a],e[o]]);else if(t)throw new j(`Provided weight data has no target variable: ${o}`);delete n[a]}if(t){const o=[];for(const a in n)o.push(a);if(o.length>0)throw new j(`${o.length} of ${s} weights are not set: ${o}`)}Uw(i)}updatedConfig(){const e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${zp}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){const n=Hw(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return ee(()=>{e=Rt(e);const n=new Go;for(let s=0;s<this.inputs.length;++s)n.add(this.inputs[s],e[s]);return $h(this.outputs,n,t)})}computeMask(e,t){return ee(()=>{e=Rt(e);let n;return t==null?n=Bo(null,e.length):n=Rt(t),this.runInternalGraph(e,n)[1]})}computeOutputShape(e){const t=Ep(e);if(t.length!==this.inputLayers.length)throw new j(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);const n={};for(let a=0;a<t.length;a++){const c=this.inputLayers[a],h=t[a],d=c.name+"_0_0";n[d]=h}const s=Object.keys(this.nodesByDepth).map(a=>parseInt(a,10)).sort(bp);if(s.length>1)for(const a of s){const c=this.nodesByDepth[a];for(const h of c){const d=h.outboundLayer;if(this.inputLayers.map(L=>L.id).indexOf(d.id)!==-1)continue;const m=[];for(let L=0;L<h.inboundLayers.length;L++){const T=h.inboundLayers[L],A=h.nodeIndices[L],N=h.tensorIndices[L],E=`${T.name}_${A}_${N}`,D=n[E];m.push(D)}const y=d.computeOutputShape(Kn(m)),b=Ep(y),w=d.inboundNodes.indexOf(h);for(let L=0;L<b.length;L++){const T=`${d.name}_${w}_${L}`;n[T]=b[L]}}}const i=[],o=[];for(let a=0;a<this.outputLayers.length;a++){const c=this.outputLayers[a],h=this.outputLayersNodeIndices[a],d=this.outputLayersTensorIndices[a],m=`${c.name}_${h}_${d}`;o.push(m)}for(let a=0;a<o.length;a++){const c=o[a];xs(c in n),i.push(n[c])}return Kn(i)}runInternalGraph(e,t){t==null&&(t=Bo(null,e.length));const n={};for(let c=0;c<this.inputs.length;++c){const h=this.inputs[c],d=e[c],m=t[c];n[h.id]=[d,m]}const s=Object.keys(this.nodesByDepth).map(c=>parseInt(c,10)).sort(bp);for(const c of s){const h=this.nodesByDepth[c];for(const d of h){const m=d.outboundLayer,y=d.inputTensors,b=d.outputTensors,w=new Array;for(const L of y)L.id in n&&w.push(n[L.id]);if(w.length===y.length){let L={},T,A,N,E;if(d.callArgs!=null&&(L=d.callArgs),w.length===1){const[D,F]=w[0];L.mask==null&&(L.mask=F),N=Rt(m.call(D,L)),E=Rt(m.computeMask(D,F)),T=[D],A=[F]}else T=w.map(D=>D[0]),A=w.map(D=>D[1]),L.mask==null&&(L.mask=A),N=Rt(m.call(T,L)),E=Rt(m.computeMask(T,A));if(m.activityRegularizer)throw new ze("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let D=0;D<b.length;++D){const F=b[D],_=N[D],B=E[D];n[F.id]=[_,B]}}}}const i=[],o=[],a=[];for(const c of this.outputs){xs(c.id in n,`Could not compute output ${c.name} : ${c.id}`);const[h,d]=n[c.id];a.push(h.shape),i.push(h),o.push(d)}return[i,o,a]}buildNodeConversionMap(e){const t={};let n;for(const s of this.layers){n=s instanceof Fi?1:0;for(let i=0;i<s.inboundNodes.length;i++){const o=Fi.nodeKey(s,i);this.containerNodes.has(o)&&(t[o]=n,n+=1)}}return t}getLayer(e,t){if(t!=null){if(this.layers.length<=t)throw new j(`Was asked to retrieve layer at index ${t}, but model only has ${this.layers.length} layer(s).`);return this.layers[t]}else if(e==null)throw new j("Provide either a layer name or layer index");for(const n of this.layers)if(n.name===e)return n;throw new j(`No such layer: ${e}`)}calculateLosses(){return ee(()=>{const e=[];for(const t of this.layers)for(let n=0;n<t.inboundNodes.length;++n){const s=Fi.nodeKey(t,n);this.containerNodes.has(s)&&e.push(...t.calculateLosses())}return e})}getConfig(){const e={name:this.name},t=this.buildNodeConversionMap(this.layers),n=[];for(const o of this.layers){const a=o.getClassName(),c=o.getConfig(),h=[];for(let m=0;m<o.inboundNodes.length;m++){const y=o.inboundNodes[m],b=Fi.nodeKey(o,m);let w={};if(this.containerNodes.has(b)){if(y.callArgs)try{JSON.stringify(y.callArgs),w=y.callArgs}catch(L){console.warn(`Layer ${o.name} was passed non-serializable keyword arguments: ${y.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),w={}}if(y.inboundLayers.length>0){const L=[];for(let T=0;T<y.inboundLayers.length;T++){const A=y.inboundLayers[T],N=y.nodeIndices[T],E=y.tensorIndices[T],D=Fi.nodeKey(A,N);let F=t[D];F==null&&(F=0),L.push([A.name,F,E,w])}h.push(L)}}}const d={};d.name=o.name,d.className=a,d.config=c,d.inboundNodes=h,n.push(d)}e.layers=n;const s=[];for(let o=0;o<this.inputLayers.length;o++){const a=this.inputLayers[o],c=this.inputLayersNodeIndices[o],h=Fi.nodeKey(a,c);if(!this.containerNodes.has(h))continue;let d=t[h];d==null&&(d=0);const m=this.inputLayersTensorIndices[o];s.push([a.name,d,m])}e.inputLayers=s;const i=[];for(let o=0;o<this.outputLayers.length;o++){const a=this.outputLayers[o],c=this.outputLayersNodeIndices[o],h=Fi.nodeKey(a,c);if(!this.containerNodes.has(h))continue;let d=t[h];d==null&&(d=0);const m=this.outputLayersTensorIndices[o];i.push([a.name,d,m])}return e.outputLayers=i,e}static fromConfig(e,t,n={},s=!1){const i={},o={};function a(T,A){T.name in o?o[T.name].push(A):o[T.name]=[A]}function c(T,A){const N=[];let E;for(const D of A){const F=D[0],_=D[1],B=D[2];if(E=D[3]==null?{}:D[3],!(F in i)){a(T,A);return}const $=i[F];if($.inboundNodes.length<=_){a(T,A);return}const H=$.inboundNodes[_];N.push(H.outputTensors[B])}N.length>0&&T.apply(Kn(N),E)}function h(T){const A=T.name,N=li(T,t.customObjects!=null?t.customObjects:{});N.setFastWeightInitDuringBuild(s),i[A]=N;const E=T.inboundNodes;E.forEach(D=>{if(!(D instanceof Array))throw new j(`Corrupted configuration, expected array for nodeData: ${D}`);a(N,D)})}const d=t.name,m=t.layers;for(const T of m)h(T);for(;!mz(o);)for(const T of m){const A=i[T.name];if(A.name in o){const N=o[A.name];delete o[A.name];for(const E of N)c(A,E)}}const y=[],b=[],w=t.inputLayers;for(const T of w){const A=T[0],N=T[1],E=T[2];xs(A in i);const D=i[A],F=D.inboundNodes[N].outputTensors;y.push(F[E])}const L=t.outputLayers;for(const T of L){const A=T[0],N=T[1],E=T[2];xs(A in i);const D=i[A],F=D.inboundNodes[N].outputTensors;b.push(F[E])}return new e({inputs:y,outputs:b,name:d})}get stateful(){if(this._stateful)throw new j("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(const e of this.layers)if(e.stateful)return!0;return!1}resetStates(){ee(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}}function Dv(e,t,n){const s=t.length;if(e==null||Array.isArray(e)&&e.length===0)return t.map(i=>null);if(s===1)return Array.isArray(e)&&e.length===1?e:typeof e=="object"&&t[0]in e?[e[t[0]]]:[e];if(Array.isArray(e)){if(e.length!==s)throw new Error(`Provided ${n} is an array of ${e.length} element(s), but the model has ${s} outputs. Make sure a set of weights is provided for each model output.`);return e}else if(typeof e=="object"&&Object.keys(e).length>0&&typeof e[Object.keys(e)[0]]=="object"){const i=[];return t.forEach(o=>{o in e?i.push(e[o]):i.push(null)}),i}else throw new Error(`The model has multiple (${s}) outputs, so ${n} must be either an array with ${s} elements or an object with ${t} keys. Provided ${n} not understood: ${JSON.stringify(e)}`)}function kv(e,t){return Dv(e,t,"classWeight")}function kQ(e,t){return Dv(e,t,"sampleWeight")}async function Fv(e,t,n,s){if(t!=null||s!=null)throw new Error("Support sampleWeight is not implemented yet");if(n!=null){const i=ee(()=>{if(e.shape.length===1)return e.clone();if(e.shape.length===2)if(e.shape[1]>1){const c=1;return e.argMax(c)}else{if(e.shape[1]===1)return e.reshape([e.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${e.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}else throw new Error(`Unexpected rank of target (y) tensor (${e.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)}),o=Array.from(await i.data());He(i);const a=[];return o.forEach(c=>{if(n[c]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${c} exists in the data but not in classWeight`);a.push(n[c])}),ss(a,"float32")}else return null}function U3(e,t){return X(e,t)}const B3=32;function _v(e,t){let n,s;const i=t;n=i.xs,s=i.ys,k(n!=null&&s!=null,()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${t}`);const o=Wv("input",e.inputNames,n),a=Wv("output",e.outputNames,s),c=o[0].shape[0];k(o.length===e.inputs.length,()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${o.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`),k(a.length===e.outputs.length,()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${a.length} outputs. (Expected output keys: ${JSON.stringify(e.outputNames)})`);for(let h=0;h<o.length;h++)k(o[h].shape[0]===c,()=>`Batch size mismatch: input ${e.inputNames[h]} has ${o[h].shape[0]}; expected ${c} based on input ${e.inputNames[0]}.`);for(let h=0;h<a.length;h++)k(a[h].shape[0]===c,()=>`Batch size mismatch: output ${e.outputNames[h]} has ${a[h].shape[0]}; expected ${c} based on input ${e.inputNames[0]}.`);return{xs:o,ys:a}}function Wv(e,t,n){if(n instanceof Q)return[n];if(Array.isArray(n))return k(n.length===t.length,()=>`Received an array of ${n.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`),n;{const s=[];for(const i of t){if(n[i]==null)throw new j(`The feature data generated by the dataset lacks the required ${e} key '${i}'.`);s.push(n[i])}return s}}function M3(e){if(e.length===3)throw new ze("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}async function P3(e,t,n){const s=n.batchesPerEpoch!=null;if(k(e.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),k(n!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),k(n.epochs!=null&&n.epochs>0&&Number.isInteger(n.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${n.epochs}`),k(!s||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${n.batchesPerEpoch}`),k(n.validationSplit==null,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;try{const i=n.validationData!=null;let o,a;if(i)if($v(n.validationData))k(n.validationBatches==null||n.validationBatches>0&&Number.isInteger(n.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${n.validationBatches}`);else{const A=M3(n.validationData);o=A.xs,a=A.ys}const c=e.makeTrainFunction(),h=e.getDedupedMetricsNames();let d;i?d=h.slice().concat(h.map(A=>"val_"+A)):d=h.slice();const m=Lv(n.callbacks,n.yieldEvery),y=n.verbose==null?1:n.verbose,{callbackList:b,history:w}=Sv(m,y,n.epochs,null,null,z3(t,n),null,i,d);b.setModel(e),e.history=w,await b.onTrainBegin(),e.stopTraining_=!1;let L=n.initialEpoch==null?0:n.initialEpoch,T=await t.iterator();for(;L<n.epochs;){const A={};await b.onEpochBegin(L);let N=0,E=0;for(s||(T=await t.iterator());s?N<n.batchesPerEpoch:!0;){const D=await T.next();if(s&&D.done){console.warn(`You provided \`batchesPerEpoch\` as ${n.batchesPerEpoch}, but your dataset iterator ran out of data after ${N} batches; interrupting training. Make sure that your dataset can generate at least \`batchesPerEpoch * epochs\` batches (in this case, ${n.batchesPerEpoch*n.epochs} batches). You may need to use the repeat() function when building your dataset.`);break}if(D.value!=null){const{xs:F,ys:_}=_v(e,D.value),B={};B.batch=E,B.size=F[0].shape[0],await b.onBatchBegin(E,B);const $=[];if(n.classWeight!=null){const J=kv(n.classWeight,e.outputNames);for(let re=0;re<J.length;++re)$.push(await Fv(_[re],null,J[re]))}const H=F.concat(_).concat($),q=c(H);He(H);for(let J=0;J<h.length;++J){const re=h[J],ce=q[J];B[re]=ce,Cn(ce)}await b.onBatchEnd(E,B),fv(B),E++,N++}if(s?N>=n.batchesPerEpoch:D.done){if(i){let F;$v(n.validationData)?F=Rt(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):F=Rt(e.evaluate(o,a,{batchSize:n.validationBatchSize==null?B3:n.validationBatchSize,verbose:0}));for(let _=0;_<e.metricsNames.length;++_)A[`val_${e.metricsNames[_]}`]=F[_]}break}if(e.stopTraining_)break}if(await b.onEpochEnd(L,A),L++,e.stopTraining_)break}return await b.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}function z3(e,t){let n=null;return t.batchesPerEpoch!=null?n=t.batchesPerEpoch:Number.isFinite(e.size)&&(n=e.size),n}function $v(e){return typeof e.iterator=="function"}function G3(e){return typeof e.next=="function"}async function V3(e,t,n){n=n||{};const s=n.batches!=null,i=e.testFunction;let o=[];if(n.verbose>0)throw new ze("Verbose mode is not implemented yet.");k(!s||n.batches>0&&Number.isInteger(n.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(n.batches)}`);const a=G3(t)?t:await t.iterator();let c=0,h=0;for(;s?h<n.batches:!0;){const d=await a.next();if(o=ee(()=>{if(d.value){const{xs:m,ys:y}=_v(e,d.value),b=m.concat(y),w=ee(()=>i(b));if(He(b),h===0)for(let T=0;T<w.length;++T)o.push(Ne(0));const L=b[0].shape[0];for(let T=0;T<w.length;++T){const A=w[T],N=o[T];o[T]=ee(()=>be(o[T],X(L,A))),h>0&&He(N)}He(w),c+=L,++h}return o}),d.done){s&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${n.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let d=0;d<o.length;++d){const m=o[d];o[d]=_e(o[d],c),He(m)}return Kn(o)}function jw(e){k(e>0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function Uh(e,t,n){return e==null?[null]:Array.isArray(e)?e.map(s=>zo(s,t,n-t)):zo(e,t,n-t)}function Kw(e,t){return ee(()=>e==null?null:Array.isArray(e)?e.map(n=>Kw(n,t)):av(e,t.dtype==="int32"?t:t.toInt()))}function Xw(e,t){const n=[];let s=0,i=null;for(;s<e;)i=s+t,i>=e&&(i=e),n.push([s,i]),s=i;return n}async function Y3(e,t,n,s,i,o,a,c,h,d,m,y,b,w,L){i==null&&(i=32),o==null&&(o=1),m==null&&(m=!0),b==null&&(b=0);let T=!1;if(h!=null&&d!=null&&(T=!0),L!=null&&(T=!0,w==null))throw new j("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");const A=e.checkNumSamples(n,i,w,"steps_per_epoch");let N;A!=null&&(N=oi(0,A)),a==null&&(a=1);const{callbackList:E,history:D}=Sv(c,a,o,b,A,w,i,T,y);E.setModel(e),e.history=D,await E.onTrainBegin(),e.stopTraining_=!1;for(let F=b;F<o;++F){await E.onEpochBegin(F);const _={};if(w!=null)throw new ze("stepsPerEpoch mode is not implemented yet.");{if(m==="batch")throw new ze("batch shuffling is not implemneted yet");m&&Ry(N);const B=ss(N),$=Xw(A,i);for(let H=0;H<$.length;++H){const q={};if(await E.onBatchBegin(H,q),ee(()=>{const J=$[H][0],re=$[H][1],ce=zo(B,J,re-J);q.batch=H,q.size=re-J;const ue=Kw(n,ce),he=t(ue);for(let de=0;de<s.length;++de){const le=s[de],ye=he[de];q[le]=ye,Cn(ye)}if(H===$.length-1&&T){const de=e.testLoop(h,d,i);for(let le=0;le<s.length;++le){const ye=s[le],pe=de[le];Cn(pe),_["val_"+ye]=pe}}}),await E.onBatchEnd(H,q),fv(q),e.stopTraining_)break}B.dispose()}if(await E.onEpochEnd(F,_),e.stopTraining_)break}return await E.onTrainEnd(),await e.history.syncData(),e.history}async function H3(e,t,n,s={}){if(e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;let i,o,a,c,h,d,m;try{const y=s.batchSize==null?32:s.batchSize;jw(y);const b=!1,w=await e.standardizeUserData(t,n,s.sampleWeight,s.classWeight,b,y);i=w[0],o=w[1],m=w[2];let L=!1,T;if(s.validationData!=null&&s.validationData.length>0){if(L=!0,s.validationData.length===2)a=s.validationData[0],c=s.validationData[1];else throw s.validationData.length===3?new ze("validationData including sample weights is not supported yet."):new j(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${s.validationData} is invalid.`);const $=!0,H=await e.standardizeUserData(a,c,null,null,$,y);h=H[0],d=H[1],T=h.concat(d)}else if(s.validationSplit!=null&&s.validationSplit>0&&s.validationSplit<1){L=!0;const $=Math.floor(i[0].shape[0]*(1-s.validationSplit)),H=i[0].shape[0];h=Uh(i,$,H),i=Uh(i,0,$),d=Uh(o,$,H),o=Uh(o,0,$),T=h.concat(d)}else s.validationSteps!=null&&(L=!0);const A=i.concat(o).concat(m);e.checkTrainableWeightsConsistency();const N=e.makeTrainFunction(),E=e.getDedupedMetricsNames();let D,F;L?(e.makeTestFunction(),D=e.testFunction,F=E.slice().concat(E.map($=>"val_"+$))):(D=null,T=[],F=E.slice());const _=Lv(s.callbacks,s.yieldEvery),B=await Y3(e,N,A,E,y,s.epochs,s.verbose,_,D,T,s.shuffle,F,s.initialEpoch,null,null);return B}finally{e.isTraining=!1,Vo(i,t),Vo(o,n),Vo(h,a),Vo(d,c),m!=null&&He(m)}}function Uv(e){const t=[];e instanceof Q&&(e=[e]);for(let n=0;n<e.length;++n){const s=e[n];if(s.rank===1)t.push(Dh(s,1));else{if(s.rank===0)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(s)}}return t}function Vo(e,t){if(e==null)return;const n=[];if(t instanceof Q)n.push(t.id);else if(Array.isArray(t))t.forEach(i=>n.push(i.id));else if(t!=null)for(const i in t){const o=t[i];n.push(o.id)}const s=[];if(e instanceof Q)n.indexOf(e.id)===-1&&s.push(e);else if(Array.isArray(e))e.forEach(i=>{n.indexOf(i.id)===-1&&s.push(i)});else if(e!=null)for(const i in e){const o=e[i];n.indexOf(o.id)===-1&&s.push(o)}s.forEach(i=>{i.isDisposed||i.dispose()})}function q3(e){return e instanceof Q}function Jw(e){return Array.isArray(e)}function Bv(e){return!q3(e)&&!Jw(e)}function Mv(e,t,n,s=!0,i=""){if(t==null||t.length===0){if(e!=null){let a=!1;if(Jw(e)&&e.length>0)a=!0;else if(Bv(e)){for(const c in e)if(e.hasOwnProperty(c)){a=!0;break}}else a=!0;if(a)throw new j(`Error when checking model ${i} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(a=>null);let o;if(Bv(e)){e=e,o=[];for(const a of t){if(e[a]==null)throw new j(`No data provided for "${a}". Need data for each key in: ${t}`);o.push(e[a])}}else if(Jw(e)){if(e=e,e.length!==t.length)throw new j(`Error when checking model ${i}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);o=e}else{if(e=e,t.length>1)throw new j(`The model ${i} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);o=[e]}if(o=Uv(o),n!=null)for(let a=0;a<t.length;++a){if(n[a]==null)continue;const c=o[a];if(c.shape.length!==n[a].length)throw new j(`Error when checking ${i}: expected ${t[a]} to have ${n[a].length} dimension(s). but got array with shape ${c.shape}`);for(let h=0;h<n[a].length;++h){if(h===0&&!s)continue;const d=c.shape[h],m=n[a][h];if(m!=null&&m>=0&&d!==m)throw new j(`Error when checking ${i}: expected ${t[a]} to have shape [${n[a]}], but got array with shape [${c.shape}].`)}}return o}function j3(e,t,n){const s=Ur(e.map(o=>o.shape[0]));s.sort();const i=Ur(t.map(o=>o.shape[0]));if(i.sort(),s.length>1)throw new j(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(o=>o.shape))}`);if(i.length>1)throw new j(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(o=>o.shape))}`);if(s.length>0&&i.length>0&&!ot(s,i))throw new j(`Input Tensors should have the same number of samples as target Tensors. Found ${s[0]} input sample(s) and ${i[0]} target sample(s).`)}function K3(e,t,n){const s=[sr,Wp,_h];for(let i=0;i<e.length;++i){const o=e[i],a=t[i],c=n[i];if(a==null)continue;if(a===_h&&o.shape[o.shape.length-1]===1)throw new j(`You are passing a target array of shape ${o.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(s.indexOf(a)!==-1){const h=o.shape.slice(1),d=c.slice(1);for(let m=0;m<h.length;++m){const y=h[m],b=d[m];if(b!=null&&y!==b)throw new j(`A target Tensor with shape ${o.shape} was passed for an output of shape ${c}, while using a loss function that expects targets to have the same shape as the output.`)}}}}function Pv(e,t,n,s=!0,i=""){let o;if(Array.isArray(e)){if(e.length!==t.length)throw new j(`Error when checking model ${i}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${t.length} Tensor(s), but instead got ${e.length} Tensors(s).`);o=e}else{if(t.length>1)throw new j(`The model expects ${t.length} ${i} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);o=[e]}if(n!=null)for(let a=0;a<t.length;++a){if(n[a]==null)continue;const c=o[a];if(c.shape.length!==n[a].length)throw new j(`Error when checking ${i}: expected ${t[a]} to have ${n[a].length} dimension(s), but got array with shape ${JSON.stringify(c.shape)}`);for(let h=0;h<n[a].length;++h){if(h===0&&!s)continue;const d=c.shape[h],m=n[a][h];if(m!=null&&m!==d)throw new j(`Error when checking ${i}: expected ${t[a]} to have shape ${JSON.stringify(n[a])} but got array with shape ${JSON.stringify(c.shape)}.`)}}}function X3(e,t){if(e==null||Array.isArray(e)&&e.length===0)return t.map(s=>[]);let n;if(typeof e=="string"||typeof e=="function")n=[e];else if(Array.isArray(e)||typeof e=="object")n=e;else throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);if(Array.isArray(n))return t.map(s=>n);{const s=[];for(const i of t){let o=n.hasOwnProperty(i)?n[i]:[];Array.isArray(o)||(o=[o]),s.push(o)}return s}}const J3="layers-model";class ir extends Fi{constructor(e){super(e);this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new j("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");R3(this,e,t,n)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=C3(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Qi))throw new j("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(!Array.isArray(e.loss)&&typeof e.loss!="string"&&typeof e.loss!="function"){e.loss=e.loss;for(const o in e.loss)if(this.outputNames.indexOf(o)===-1)throw new j(`Unknown entry in loss dictionary: "${o}". Only expected the following keys: ${this.outputNames}`);for(const o of this.outputNames)e.loss[o]==null&&console.warn(`Output "${o}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${o} during training`),t.push(Pw(e.loss[o]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new j(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);const o=e.loss;t=o.map(a=>Pw(a))}else{const o=Pw(e.loss);this.outputs.forEach(a=>{t.push(o)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let o=0;o<this.outputs.length;++o){const a=this.internalOutputShapes[o],c=this.outputNames[o];this.feedOutputNames.push(c),this.feedOutputShapes.push(a),this.feedLossFns.push(this.lossFunctions[o])}const n=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],Po("loss",()=>{for(let o=0;o<this.outputs.length;++o){if(n.indexOf(o)!==-1)continue;const a=this.lossFunctions[o];this.outputs.length>1&&(this.metricsTensors.push([a,o]),this.metricsNames.push(this.outputNames[o]+"_loss"))}});const s=X3(e.metrics,this.outputNames),i=(o,a,c)=>{this.outputNames.length>1&&(a=this.outputNames[o]+"_"+a),this.metricsNames.push(a),this.metricsTensors.push([c,o])};Po("metric",()=>{for(let o=0;o<this.outputs.length;++o){if(n.indexOf(o)!==-1)continue;const a=s[o],c=h=>{const d="";let m,y,b;for(const w of h){if(typeof w=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(w)!==-1){const T=this.internalOutputShapes[o];T[T.length-1]===1||this.lossFunctions[o]===Wp?["accuracy","acc"].indexOf(w)!==-1?y=zw:["crossentropy","ce"].indexOf(w)!==-1&&(y=Tv):this.lossFunctions[o]===_p?["accuracy","acc"].indexOf(w)!==-1?y=Av:["crossentropy","ce"].indexOf(w)!==-1&&(y=vv):["accuracy","acc"].indexOf(w)!==-1?y=Gw:["crossentropy","ce"].indexOf(w)!==-1&&(y=Vw);let A;["accuracy","acc"].indexOf(w)!==-1?A="acc":["crossentropy","ce"].indexOf(w)!==-1&&(A="ce"),b=y,m=d+A}else{const T=N3(w);b=T,m=d+Mp(w)}let L;Po(m,()=>{L=b}),i(o,m,L)}};c(a)}}),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){if(this.collectedTrainableWeights==null)return;this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(e,t,n={}){const s=n.batchSize==null?32:n.batchSize;jw(s);const i=!0,o=this.standardizeUserDataXY(e,t,i,s);try{const a=o[0].concat(o[1]);this.makeTestFunction();const c=this.testFunction,h=this.testLoop(c,a,s,n.verbose,n.steps);return Kn(h)}finally{Vo(o[0],e),Vo(o[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),V3(this,e,t)}checkNumSamples(e,t,n,s="steps"){let i;if(n!=null){if(i=null,t!=null)throw new j(`If ${s} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else if(e!=null)Array.isArray(e)?i=e[0].shape[0]:i=e.shape[0];else throw new j(`Either the input data should have a defined shape, or ${s} shoud be specified.`);return i}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new j("`outputs` is an empty Array, which is not allowed.");const n=Array.isArray(t),s=n?t:[t],i=this.retrieveSymbolicTensors(s),o=new Go;if(e instanceof Q&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new j(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let c=0;c<this.inputs.length;++c)o.add(this.inputs[c],e[c])}else for(const c of this.inputs){const h=e[c.name];if(h==null)throw new j(`No value is provided for the model's input ${c.name}`);o.add(c,h)}const a=$h(i,o);return n?a:a[0]}retrieveSymbolicTensors(e){const t=Bo(null,e.length);let n=e.length;for(const s of this.layers){const i=Array.isArray(s.output)?s.output:[s.output],o=i.map(a=>a.name);for(let a=0;a<e.length;++a){const c=o.indexOf(e[a]);if(c!==-1&&(t[a]=i[c],n--),n===0)break}if(n===0)break}if(n>0){const s=[];throw t.forEach((i,o)=>{i==null&&s.push(e[o])}),new j(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(s)}`)}return t}predictLoop(e,t=32,n=!1){return ee(()=>{const s=this.checkNumSamples(e);if(n)throw new ze("Verbose predictLoop() is not implemented yet.");const i=Xw(s,t),o=this.outputs.map(a=>[]);for(let a=0;a<i.length;++a){const c=ee(()=>{const h=i[a][0],d=i[a][1],m=Uh(e,h,d),y=[];if(Array.isArray(m))for(let w=0;w<m.length;++w)y.push({key:this.inputs[w],value:m[w]});else y.push({key:this.inputs[0],value:m});const b=new Go(y);return $h(this.outputs,b)});c.forEach((h,d)=>o[d].push(h))}return Kn(o.map(a=>Pt(a,0)))})}predict(e,t={}){const n=Uv(e);Pv(n,this.inputNames,this.feedInputShapes,!1);try{const s=t.batchSize==null?32:t.batchSize;return jw(s),this.predictLoop(n,s)}finally{Vo(n,e)}}predictOnBatch(e){Pv(e,this.inputNames,this.feedInputShapes,!0);const t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,s){if(this.optimizer_==null)throw new ri("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");const i=[];for(let o=0;o<this.feedOutputShapes.length;++o){const a=this.feedOutputShapes[o],c=this.feedLossFns[o];c===_p?i.push(a.slice(0,a.length-1).concat([1])):i.push(a)}if(e=Mv(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=Mv(t,this.feedOutputNames,i,!1,"target"),j3(e,t,null),K3(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&s!=null&&s>0&&e[0].shape[0]%s!==0)throw new j(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${s}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,s,i=!0,o){const[a,c]=this.standardizeUserDataXY(e,t,i,o);if(n!=null)throw new Error("sample weight is not supported yet.");let h=null;if(s!=null){const d=kv(s,this.outputNames);h=[];for(let m=0;m<d.length;++m)h.push(await Fv(c[m],null,d[m]))}return[a,c,h]}testLoop(e,t,n,s=0,i){return ee(()=>{const o=this.checkNumSamples(t,n,i,"steps"),a=[];if(s>0)throw new ze("Verbose mode is not implemented yet.");if(i!=null)throw new ze("steps mode in testLoop() is not implemented yet");{const c=Xw(o,n),h=ss(oi(0,o));for(let d=0;d<c.length;++d){const m=c[d][0],y=c[d][1],b=zo(h,m,y-m),w=Kw(t,b),L=e(w);if(d===0)for(let T=0;T<L.length;++T)a.push(Ne(0));for(let T=0;T<L.length;++T){const A=L[T];a[T]=be(a[T],X(y-m,A))}}for(let d=0;d<a.length;++d)a[d]=_e(a[d],o)}return a})}getDedupedMetricsNames(){const e=this.metricsNames,t=[];for(let n=0;n<e.length;++n){const s=e[n];let i=s;if(KA(e,s)>1){const o=KA(e.slice(0,n),s);i+=`_${o}`}t.push(i)}return t}makeTrainFunction(){return e=>{const t=[],n=e.slice(0,this.inputs.length),s=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),i=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),o=[],a=()=>{const m=[];for(let L=0;L<this.inputs.length;++L)m.push({key:this.inputs[L],value:n[L]});const y=new Go(m),b=$h(this.outputs,y,{training:!0});let w;for(let L=0;L<this.lossFunctions.length;++L){const T=this.lossFunctions[L];let A=T(s[L],b[L]);i[L]!=null&&(A=U3(A,i[L]));const N=Gt(A);t.push(N),L===0?w=A:w=be(w,A)}for(let L=0;L<this.metricsTensors.length;++L){let T;if(this.outputs.length>1&&L<this.outputs.length)T=t[L];else{const A=this.metricsTensors[L][0],N=this.metricsTensors[L][1];T=Gt(A(s[N],b[N]))}Cn(T),o.push(T)}return w=Gt(w),this.calculateLosses().forEach(L=>{w=be(w,L)}),w},c=this.collectedTrainableWeights.map(m=>m.read()),h=!0,d=this.optimizer_.minimize(a,h,c);return[d].concat(o)}}makeTestFunction(){this.testFunction=e=>ee(()=>{const t=[];let n;const s=e.slice(0,this.inputs.length),i=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),o=[];for(let h=0;h<this.inputs.length;++h)o.push({key:this.inputs[h],value:s[h]});const a=new Go(o),c=$h(this.outputs,a);for(let h=0;h<this.lossFunctions.length;++h){const d=this.lossFunctions[h],m=Gt(d(i[h],c[h]));h===0?n=m:n=be(n,m),t.push(n)}for(let h=0;h<this.metricsTensors.length;++h){const d=this.metricsTensors[h][0],m=this.metricsTensors[h][1],y=Gt(d(i[m],c[m]));t.push(y)}return t})}async fit(e,t,n={}){return H3(this,e,t,n)}async fitDataset(e,t){return P3(this,e,t)}async trainOnBatch(e,t){const n=await this.standardizeUserData(e,t),s=n[0],i=n[1],o=this.makeTrainFunction(),a=o(s.concat(i)),c=[];for(const h of a){const d=await h.data();c.push(d[0])}return He(a),Kn(c)}getNamedWeights(e){const t=[],n=e!=null&&e.trainableOnly,s=n?this.trainableWeights:this.weights,i=this.getWeights(n);for(let o=0;o<s.length;++o){if(n&&!s[o].trainable)continue;t.push({name:s[o].originalName,tensor:i[o]})}return t}set stopTraining(e){this.stopTraining_=e}get stopTraining(){return this.stopTraining_}get optimizer(){return this.optimizer_}set optimizer(e){this.optimizer_!==e&&(this.optimizer_=e,this.isOptimizerOwned=!1)}dispose(){const e=super.dispose();if(e.refCountAfterDispose===0&&this.optimizer!=null&&this.isOptimizerOwned){const t=Ed().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-Ed().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=nr(this.loss);else if(Array.isArray(this.loss)){for(const t of this.loss)if(typeof t!="string")throw new Error("Serialization of non-string loss is not supported.");e=this.loss.map(t=>nr(t))}else{const t=Object.keys(this.loss);e={};const n=this.loss;for(const s of t)if(typeof n[s]=="string")e[s]=nr(n[s]);else throw new Error("Serialization of non-string loss is not supported.")}return e}getMetricIdentifiers(){if(typeof this.metrics=="string"||typeof this.metrics=="function")return[nr(Mp(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>nr(Mp(e)));{const e={};for(const t in this.metrics)e[t]=nr(Mp(this.metrics[t]));return e}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(e){if(e.weighted_metrics!=null)throw new Error("Loading weight_metrics is not supported yet.");if(e.loss_weights!=null)throw new Error("Loading loss_weights is not supported yet.");if(e.sample_weight_mode!=null)throw new Error("Loading sample_weight_mode is not supported yet.");const t=Wh(e.optimizer_config),n=li(t);let s;if(typeof e.loss=="string")s=Mo(e.loss);else if(Array.isArray(e.loss))s=e.loss.map(o=>Mo(o));else if(e.loss!=null){s={};for(const o in e.loss)s[o]=Mo(e.loss[o])}let i;if(Array.isArray(e.metrics))i=e.metrics.map(o=>Mo(o));else if(e.metrics!=null){i={};for(const o in e.metrics)i[o]=Mo(e.metrics[o])}this.compile({loss:s,metrics:i,optimizer:n})}async save(e,t){if(typeof e=="string"){const h=qy(e);if(h.length===0)throw new j(`Cannot find any save handlers for URL '${e}'`);if(h.length>1)throw new j(`Found more than one (${h.length}) save handlers for URL '${e}'`);e=h[0]}if(e.save==null)throw new j("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const n=await Yy(this.getNamedWeights(t)),s=!1,i=null,o=this.toJSON(i,s),a={modelTopology:o,format:J3,generatedBy:`TensorFlow.js tfjs-layers v${zp}`,convertedBy:null},c=t==null?!1:t.includeOptimizer;if(c&&this.optimizer!=null){a.trainingConfig=this.getTrainingConfig();const h="optimizer",{data:d,specs:m}=await Yy(await this.optimizer.getWeights(),h);n.specs.push(...m),n.data=Id([n.data,d])}if(this.userDefinedMetadata!=null){const h=!0;Cv(this.userDefinedMetadata,this.name,h),a.userDefinedMetadata=this.userDefinedMetadata}return a.weightData=n.data,a.weightSpecs=n.specs,e.save(a)}setUserDefinedMetadata(e){Cv(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}ir.className="Model",me(ir);class zv extends ir{}zv.className="Functional",me(zv);async function Z3(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let n=e.modelTopology;n.model_config!=null&&(n=n.model_config);const s=Wh(n),i=li(s,t);if(e.weightsManifest!=null){const o=await mT(e.weightsManifest,e.pathPrefix,i.weights.map(c=>c.originalName)),a={};for(const c of i.weights)a[c.originalName]=o[c.originalName];i.loadWeights(a),He(o)}return i}async function Q3(e,t){if(t==null&&(t={}),typeof e=="string"){const n=jy(e,t);if(n.length===0)n.push(Ad(e,t));else if(n.length>1)throw new j(`Found more than one (${n.length}) load handlers for URL '${e}'`);e=n[0]}return eG(e,void 0,t)}async function eG(e,t,n){if(n==null&&(n={}),e.load==null)throw new j("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const s=await e.load();let i=s.modelTopology;i.model_config!=null&&(i=i.model_config);const o=n.strict==null?!0:n.strict,a=s.weightData!=null&&s.weightSpecs!=null&&o,c=li(Wh(i),t,a),h=s.trainingConfig;if(h!=null&&c.loadTrainingConfig(h),s.userDefinedMetadata!=null&&c.setUserDefinedMetadata(s.userDefinedMetadata),s.weightData!=null){if(s.weightSpecs==null)throw new j("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");const{modelWeights:d,optimizerWeights:m}=tG(s.weightData,s.weightSpecs);c.loadWeights(d,o),c.optimizer!=null&&m.length>0&&await c.optimizer.setWeights(m),He(d),He(m.map(y=>y.tensor))}return c}function tG(e,t){const n=Sd(e,t),s={},i=[];return t.forEach(o=>{o.group==="optimizer"?i.push({name:o.name,tensor:n[o.name]}):s[o.name]=n[o.name]}),{modelWeights:s,optimizerWeights:i}}class ec extends ir{constructor(e){super({inputs:[],outputs:[]});if(e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:Op("sequential_"),e.layers!=null)for(const t of e.layers)this.add(t)}checkShape(e){const t=e.inboundNodes[0].outputTensors[0].shape;if(t.some(n=>n<0))throw new j(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const t=e instanceof ec||e instanceof ir;let n;if(t){if(n=e,n.outputs.length!==1)throw new j("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(n.inputs.length!==1)throw new j("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(this.outputs.length===0){if(e.inboundNodes.length===0){if(e.batchInputShape==null)throw new j("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const s=mv({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(s)}if(t)this.outputs=n.outputs,this.inputs=n.inputs;else{if(e.inboundNodes.length!==1)throw new j(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${e.name} which has ${e.inboundNodes.length} pre-existing inbound connections.`);if(e.inboundNodes[0].outputTensors.length!==1)throw new j("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[e.inboundNodes[0].outputTensors[0]],this.inputs=pv(this.outputs[0])}this.inboundNodes=[],new kp({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Bo(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(s=>s.shape),outputShapes:this.outputs[0].shape})}else{const s=e.apply(this.outputs[0]);if(Array.isArray(s))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[s],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(this.layers.length===0)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),this.layers.length===0)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{const e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return this.model==null&&this.build(),this.model.call(e,t)}build(e){if(St(e),this.inputs.length===0||this.outputs.length===0)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new ir({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(e,t,n=console.log){this.built||this.build(),super.summary(e,t,n)}setWeights(e){this.model==null&&this.build(),this.model.setWeights(e)}evaluate(e,t,n={}){if(!this.built)throw new ri("The model needs to be compiled before being used.");return this.model.evaluate(e,t,n)}async evaluateDataset(e,t){if(!this.built)throw new ri("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return this.model==null&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return this.model==null&&this.build(),this.model.predictOnBatch(e)}compile(e){this.build(),this.model.compile(e),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return this.model==null?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,n={}){if(!this.built)throw new ri("The model needs to be compiled before being used.");return this.model.fit(e,t,n)}async fitDataset(e,t){if(!this.built)throw new ri("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,n={},s=!1){let i,o={};if(t instanceof Array){if(!(t[0].className!=null)||t[0].className==="Merge")throw new j("Legacy serialization format not supported yet.");i=t}else k(t.layers!=null,()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."),i=t.layers,delete t.layers,o=t;const a=new e(o);if(!(a instanceof ec))throw new ze(`Sequential.fromConfig called on non-Sequential input: ${a}`);for(const c of i){const h=void 0,d=li(c,h,s);s&&d.setFastWeightInitDuringBuild(!0),a.add(d)}return a}set stopTraining(e){if(this.model==null)throw new j("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(this.model==null)throw new j("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){const e=[];for(const t of this.layers){const n={};n.className=t.getClassName(),n.config=t.getConfig(),e.push(n)}return{name:this.name,layers:e}}}ec.className="Sequential",me(ec);function nG(e){return new ir(e)}function sG(e){return new ec(e)}function iG(e,t){return t==null&&(t={}),Q3(e,t)}function Gv(e){return mv(e)}function rG(e,t){Ms.registerCallbackConstructor(e,t)}class os extends Ao{getConfig(){return{}}}class Vv extends os{apply(e,t=1){return kz(e,t)}}Vv.className="elu",me(Vv);class Yv extends os{apply(e){return Jd(e)}}Yv.className="selu",me(Yv);class Hv extends os{apply(e){return Oi(e)}}Hv.className="relu",me(Hv);class qv extends os{apply(e){return ee(()=>Eo(6,Oi(e)))}}qv.className="relu6",me(qv);class jv extends os{apply(e){return e}}jv.className="linear",me(jv);class Kv extends os{apply(e){return Ni(e)}}Kv.className="sigmoid",me(Kv);class Xv extends os{apply(e){return _z(e)}}Xv.className="hardSigmoid",me(Xv);class Jv extends os{apply(e){return Ua(e)}}Jv.className="softplus",me(Jv);class Zv extends os{apply(e){return Fz(e)}}Zv.className="softsign",me(Zv);class Qv extends os{apply(e){return Fa(e)}}Qv.className="tanh",me(Qv);class Zw extends os{apply(e,t=-1){return Wo(e,t)}}Zw.className="softmax",me(Zw);class eN extends os{apply(e,t=-1){return Yd(e,t)}}eN.className="logSoftmax",me(eN);class tN extends os{apply(e,t=1){return ee(()=>Ni(e.mul(t)).mul(e))}}tN.className="swish",me(tN);function Gr(e){return e.getClassName()}function Qw(e,t={}){return Ch(e,Fs.getMap().classNameMap,t,"activation")}function Vr(e){if(e==null){const t={};return t.className="linear",t.config={},Qw(t)}if(typeof e=="string"){const t={};return t.className=e,t.config={},Qw(t)}else return e instanceof os?e:Qw(e)}function eL(e){if(e!=null&&typeof e!="object")throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${e}`)}class nN extends Ao{}class Bh extends nN{constructor(e){super();eL(e),this.l1=e==null||e.l1==null?.01:e.l1,this.l2=e==null||e.l2==null?.01:e.l2,this.hasL1=this.l1!==0,this.hasL2=this.l2!==0}apply(e){return ee(()=>{let t=ct([1]);return this.hasL1&&(t=be(t,Ue(X(this.l1,sn(e))))),this.hasL2&&(t=be(t,Ue(X(this.l2,kh(e))))),t.asScalar()})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}}Bh.className="L1L2",me(Bh);function oG(e){return eL(e),new Bh({l1:e!=null?e.l1:null,l2:0})}function aG(e){return eL(e),new Bh({l2:e!=null?e.l2:null,l1:0})}const sN={l1l2:"L1L2"};function It(e){return yw(e)}function iN(e,t={}){return Ch(e,Fs.getMap().classNameMap,t,"regularizer")}function _t(e){if(e==null)return null;if(typeof e=="string"){const t=e in sN?sN[e]:e,n={className:t,config:{}};return iN(n)}else return e instanceof nN?e:iN(e)}class tL extends lt{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=Ke(e);let n=Oi(e);return this.maxValue!=null&&(n=Hn(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}}tL.className="ReLU",me(tL);class nL extends lt{constructor(e){super(e==null?{}:e);this.DEFAULT_ALPHA=.3,e==null&&(e={}),this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){const n=Ke(e);return zd(n,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}nL.className="LeakyReLU",me(nL);class sL extends lt{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=Ft(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=_t(e.alphaRegularizer),this.alphaConstraint=ln(e.alphaConstraint),e.sharedAxes==null)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else if(typeof e.sharedAxes=="number")this.sharedAxes=[e.sharedAxes];else throw new j(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=St(e);const t=e.slice(1);if(this.sharedAxes!=null)for(const s of this.sharedAxes)t[s-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);const n={};if(this.sharedAxes!=null)for(let s=1;s<e.length;++s)n[s]=e[s];this.inputSpec=[new mn({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=Ke(e),dh(e,this.alpha.read())}getConfig(){const e={alphaInitializer:Yt(this.alphaInitializer),alphaRegularizer:It(this.alphaRegularizer),alphaConstraint:cn(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}}sL.className="PReLU",me(sL);class iL extends lt{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA=1,e==null&&(e={}),e.alpha!=null&&e.alpha!==this.DEFAULT_ALPHA)throw new ze(`Non-default alpha value (${e.alpha}) is not supported by the ELU layer yet.`);this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){const n=Ke(e);return Oo(n)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}iL.className="ELU",me(iL);class rL extends lt{constructor(e){super(e==null?{}:e);this.DEFAULT_THETA=1,e==null&&(e={}),this.theta=e.theta==null?this.DEFAULT_THETA:e.theta}call(e,t){const n=Ke(e);return n.mul(Eh(n.greater(this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){const e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}}rL.className="ThresholdedReLU",me(rL);class oL extends lt{constructor(e){super(e==null?{}:e);this.DEFAULT_AXIS=1,e==null&&(e={}),this.softmax=new Zw().apply,this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis}call(e,t){const n=Ke(e);return this.softmax(n,this.axis)}computeOutputShape(e){return e}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}oL.className="Softmax",me(oL);function tc(e,t,n){if(typeof e=="number")return Bo(e,t);if(e.length!==t)throw new j(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${e.length} elements.`);for(let s=0;s<t;++s){const i=e[s];if(!Nz(i))throw new j(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(e)} including a non-integer number ${i}`)}return e}function hi(e,t,n,s,i=1){if(e==null)return e;const o=t+(t-1)*(i-1);let a;return n==="same"?a=e:a=e-o+1,Math.floor((a+s-1)/s)}function Gp(e,t,n,s){if(e==null)return null;if(s==="valid")e=e*t+Mr([n-t,0]);else if(s==="same")e=e*t;else throw new j(`Unsupport padding mode: ${s}.`);return e}function aL(e,t){return ee(()=>(Vt(t),t==="channelsFirst"?Me(e,[0,2,3,1]):e))}function rN(e,t){return ee(()=>(Vt(t),t==="channelsFirst"?Me(e,[0,2,3,4,1]):e))}function oN(e,t,n,s=1,i="valid",o,a=1){return ee(()=>{if(o==null&&(o=ii()),Vt(o),e.shape.length!==3)throw new j(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new j(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(n!=null&&n.shape.length!==1)throw new j(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(o==="channelsFirst"&&(e=Me(e,[0,2,1])),i==="causal")throw new ze("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let c=$d(e,t,s,i==="same"?"same":"valid","NWC",a);return n!=null&&(c=ki(c,n)),c})}function FQ(e,t,n=1,s="valid",i,o=1){return ee(()=>(Vt(i),oN(e,t,null,n,s,i,o)))}function _Q(e,t,n=[1,1],s="valid",i,o){return ee(()=>(Vt(i),cL(e,t,null,n,s,i,o)))}function cL(e,t,n,s=[1,1],i="valid",o,a,c=null){return ee(()=>{if(o==null&&(o=ii()),Vt(o),e.rank!==3&&e.rank!==4)throw new j(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new j(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let h=aL(e,o);if(i==="causal")throw new ze("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return h=ew({x:h,filter:t,strides:s,pad:i==="same"?"same":"valid",dilations:a,dataFormat:"NHWC",bias:n,activation:c}),o==="channelsFirst"&&(h=Me(h,[0,3,1,2])),h})}function WQ(e,t,n=[1,1,1],s="valid",i,o){return ee(()=>(Vt(i),aN(e,t,null,n,s,i,o)))}function aN(e,t,n,s=[1,1,1],i="valid",o,a){return ee(()=>{if(o==null&&(o=ii()),Vt(o),e.rank!==4&&e.rank!==5)throw new j(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new j(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let c=rN(e,o);if(i==="causal")throw new ze("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return c=vb(c,t,s,i==="same"?"same":"valid","NDHWC",a),n!=null&&(c=ki(c,n)),o==="channelsFirst"&&(c=Me(c,[0,4,1,2,3])),c})}class lL extends lt{constructor(e,t){super(t);if(this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",lL.verifyArgs(t),this.rank=e,pn(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new ze(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=tc(t.kernelSize,e,"kernelSize"),this.strides=tc(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,Ts(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,Vt(this.dataFormat),this.activation=Vr(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=Ft(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=ln(t.biasConstraint),this.biasRegularizer=_t(t.biasRegularizer),this.activityRegularizer=_t(t.activityRegularizer),this.dilationRate=tc(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new j(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(this.rank===2){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==2)throw new j(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(this.rank===3){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==3)throw new j(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(xs("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!ww(e.kernelSize,"number",1,3))throw new j(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){const e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:Gr(this.activation),useBias:this.useBias,biasInitializer:Yt(this.biasInitializer),biasRegularizer:It(this.biasRegularizer),activityRegularizer:It(this.activityRegularizer),biasConstraint:cn(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class Mh extends lL{constructor(e,t){super(e,t);this.kernel=null,Mh.verifyArgs(t),this.filters=t.filters,pn(this.filters,"filters"),this.kernelInitializer=Ft(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=ln(t.kernelConstraint),this.kernelRegularizer=_t(t.kernelRegularizer)}build(e){e=St(e);const t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new j(`The channel dimension of the input should be defined. Found ${e[t]}`);const n=e[t],s=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:n}}],this.built=!0}call(e,t){return ee(()=>{e=Ke(e);let n;const s=this.bias==null?null:this.bias.read(),i=JA(this.activation.getClassName());if(i!=null&&this.rank===2)n=cL(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate,i);else{if(this.rank===1)n=oN(e,this.kernel.read(),s,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)n=cL(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)n=aN(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new ze("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(n=this.activation.apply(n))}return n})}computeOutputShape(e){e=St(e);const t=[],n=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let i=0;i<n.length;++i){const o=hi(n[i],this.kernelSize[i],this.padding,this.strides[i],typeof this.dilationRate=="number"?this.dilationRate:this.dilationRate[i]);t.push(o)}let s=[e[0]];return this.dataFormat==="channelsLast"?(s=s.concat(t),s.push(this.filters)):(s.push(this.filters),s=s.concat(t)),s}getConfig(){const e={filters:this.filters,kernelInitializer:Yt(this.kernelInitializer),kernelRegularizer:It(this.kernelRegularizer),kernelConstraint:cn(this.kernelConstraint)},t=super.getConfig();return Object.assign(e,t),e}static verifyArgs(e){if(!("filters"in e)||typeof e.filters!="number"||e.filters<1)throw new j(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}}class Ph extends Mh{constructor(e){super(2,e);Ph.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!ww(e.kernelSize,"number",1,2))throw new j(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}Ph.className="Conv2D",me(Ph);class Vp extends Mh{constructor(e){super(3,e);Vp.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!(Array.isArray(e.kernelSize)&&(e.kernelSize.length===1||e.kernelSize.length===3)))throw new j(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}Vp.className="Conv3D",me(Vp);class hL extends Ph{constructor(e){super(e);if(this.inputSpec=[new mn({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new j(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=St(e),e.length!==4)throw new j("Input should have rank 4; Received input shape: "+JSON.stringify(e));const t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new j("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],s=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",s,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new mn({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return ee(()=>{let n=Ke(e);if(n.shape.length!==4)throw new j(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);const s=n.shape,i=s[0];let o,a;this.dataFormat==="channelsFirst"?(o=2,a=3):(o=1,a=2);const c=s[o],h=s[a],d=this.kernelSize[0],m=this.kernelSize[1],y=this.strides[0],b=this.strides[1],w=Gp(c,y,d,this.padding),L=Gp(h,b,m,this.padding),T=[i,w,L,this.filters];this.dataFormat!=="channelsLast"&&(n=Me(n,[0,2,3,1]));let A=Ud(n,this.kernel.read(),T,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(A=Me(A,[0,3,1,2])),this.bias!=null&&(A=ki(A,this.bias.read(),this.dataFormat)),this.activation!=null&&(A=this.activation.apply(A)),A})}computeOutputShape(e){e=St(e);const t=e.slice();let n,s,i;this.dataFormat==="channelsFirst"?(n=1,s=2,i=3):(n=3,s=1,i=2);const o=this.kernelSize[0],a=this.kernelSize[1],c=this.strides[0],h=this.strides[1];return t[n]=this.filters,t[s]=Gp(t[s],c,o,this.padding),t[i]=Gp(t[i],h,a,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}hL.className="Conv2DTranspose",me(hL);class cN extends Mh{constructor(e,t){super(e,t);if(this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,t.filters==null)throw new j("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new j("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(t.padding!=null&&t.padding!=="same"&&t.padding!=="valid")throw new j(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=t.depthMultiplier==null?1:t.depthMultiplier,this.depthwiseInitializer=Ft(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=_t(t.depthwiseRegularizer),this.depthwiseConstraint=ln(t.depthwiseConstraint),this.pointwiseInitializer=Ft(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=_t(t.pointwiseRegularizer),this.pointwiseConstraint=ln(t.pointwiseConstraint)}build(e){if(e=St(e),e.length<this.rank+2)throw new j(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank+2}, but received input shape: ${JSON.stringify(e)}`);const t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null||e[t]<0)throw new j(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);const n=e[t],s=this.kernelSize.concat([n,this.depthMultiplier]),i=[];for(let a=0;a<this.rank;++a)i.push(1);i.push(n*this.depthMultiplier,this.filters);const o=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",s,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,o,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",i,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,o,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,o,this.biasConstraint):this.bias=null,this.inputSpec=[new mn({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return ee(()=>{e=Ke(e);let n;if(this.rank===1)throw new ze("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=Me(e,[0,2,3,1])),n=Gb(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(n=ki(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),this.dataFormat==="channelsFirst"&&(n=Me(n,[0,3,1,2])),n})}getConfig(){const e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=Yt(this.depthwiseInitializer),e.pointwiseInitializer=Yt(this.pointwiseInitializer),e.depthwiseRegularizer=It(this.depthwiseRegularizer),e.pointwiseRegularizer=It(this.pointwiseRegularizer),e.depthwiseConstraint=cn(this.depthwiseConstraint),e.pointwiseConstraint=cn(this.pointwiseConstraint),e}}cN.className="SeparableConv";class uL extends cN{constructor(e){super(2,e)}}uL.className="SeparableConv2D",me(uL);class Yp extends Mh{constructor(e){super(1,e);Yp.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){const e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!ww(e.kernelSize,"number",1,1))throw new j(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}Yp.className="Conv1D",me(Yp);class dL extends lt{constructor(e){super(e);typeof e.cropping=="number"?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:typeof e.cropping[0]=="number"?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=e.dataFormat===void 0?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return this.dataFormat==="channelsFirst"?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return ee(()=>{if(e=Ke(e),this.dataFormat==="channelsLast"){const n=Lp(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Lp(n,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{const n=Lp(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Lp(n,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}})}getConfig(){const e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}dL.className="Cropping2D",me(dL);class pL extends lt{constructor(e){super(e);this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=e.size==null?this.DEFAULT_SIZE:e.size,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat}computeOutputShape(e){if(this.dataFormat==="channelsFirst"){const t=e[2]==null?null:this.size[0]*e[2],n=e[3]==null?null:this.size[1]*e[3];return[e[0],e[1],t,n]}else{const t=e[1]==null?null:this.size[0]*e[1],n=e[2]==null?null:this.size[1]*e[2];return[e[0],t,n,e[3]]}}call(e,t){return ee(()=>{let n=Ke(e);const s=n.shape;if(this.dataFormat==="channelsFirst"){n=Me(n,[0,2,3,1]);const i=this.size[0]*s[2],o=this.size[1]*s[3],a=n.resizeNearestNeighbor([i,o]);return Me(a,[0,3,1,2])}else{const i=this.size[0]*s[1],o=this.size[1]*s[2];return n.resizeNearestNeighbor([i,o])}})}getConfig(){const e={size:this.size,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}pL.className="UpSampling2D",me(pL);function cG(e,t,n=[1,1],s="valid",i,o){return ee(()=>{i==null&&(i=ii()),Vt(i);let a=aL(e,i);if(e.rank!==4)throw new j(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new j(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return a=Co(a,t,n,s==="same"?"same":"valid","NHWC",o),i==="channelsFirst"&&(a=Me(a,[0,3,1,2])),a})}class mL extends lL{constructor(e){super(2,e);this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=Ft(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=ln(e.depthwiseConstraint),this.depthwiseRegularizer=_t(e.depthwiseRegularizer)}build(e){if(e=St(e),e.length<4)throw new j(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);const t=this.dataFormat==="channelsFirst"?1:3;if(e[t]==null||e[t]<0)throw new j(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);const n=e[t],s=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",s,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return ee(()=>{e=Ke(e);let n=cG(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(n=ki(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),n})}computeOutputShape(e){e=St(e);const t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],s=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,i=hi(t,this.kernelSize[0],this.padding,this.strides[0]),o=hi(n,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],s,i,o]:[e[0],i,o,s]}getConfig(){const e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=Yt(this.depthwiseInitializer),e.depthwiseRegularizer=It(this.depthwiseRegularizer),e.depthwiseConstraint=cn(this.depthwiseRegularizer),e}}mL.className="DepthwiseConv2D",me(mL);function lN(e,t,n,s){if(Array.isArray(e)){if(t!=null||n!=null)throw new j("When inputs is an array, neither initialState or constants should be provided");s!=null&&(n=e.slice(e.length-s,e.length),e=e.slice(0,e.length-s)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function i(o){return o==null||Array.isArray(o)?o:[o]}return t=i(t),n=i(n),{inputs:e,initialState:t,constants:n}}function hN(e,t,n,s=!1,i,o,a=!1,c=!1){return ee(()=>{const h=t.shape.length;if(h<3)throw new j(`Input should be at least 3D, but is ${h}D.`);const d=[1,0].concat(oi(2,h));if(t=Me(t,d),o!=null)throw new ze("The rnn() functoin of the deeplearn.js backend does not support constants yet.");a&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),i!=null&&(i=i.asType("bool").asType("float32"),i.rank===h-1&&(i=qn(i,-1)),i=Me(i,d)),s&&(t=Is(t,0),i!=null&&(i=Is(i,0)));const m=[];let y,b=n;const w=t.shape[0],L=Ei(t);let T;i!=null&&(T=Ei(i));for(let N=0;N<w;++N){const E=L[N],D=ee(()=>e(E,b));if(i==null)y=D[0],b=D[1];else{const F=ee(()=>{const _=T[N],B=En(_).sub(_),$=D[0].mul(_).add(b[0].mul(B)),H=b.map((q,J)=>D[1][J].mul(_).add(q.mul(B)));return{output:$,newStates:H}});y=F.output,b=F.newStates}c&&m.push(y)}let A;if(c){const N=1;A=rs(m,N)}return[y,A,b]})}class _i extends lt{constructor(e){super(e);let t;if(e.cell==null)throw new j("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new jp({cells:e.cell}):t=e.cell,t.stateSize==null)throw new j("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=e.returnSequences==null?!1:e.returnSequences,this.returnState=e.returnState==null?!1:e.returnState,this.goBackwards=e.goBackwards==null?!1:e.goBackwards,this._stateful=e.stateful==null?!1:e.stateful,this.unroll=e.unroll==null?!1:e.unroll,this.supportsMasking=!0,this.inputSpec=[new mn({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(this.states_==null){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;return oi(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){Ww(e)&&(e=e[0]),e=e;let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);const n=t[0];let s;if(this.returnSequences?s=[e[0],e[1],n]:s=[e[0],n],this.returnState){const i=[];for(const o of t)i.push([e[0],o]);return[s].concat(i)}else return s}computeMask(e,t){return ee(()=>{Array.isArray(t)&&(t=t[0]);const n=this.returnSequences?t:null;if(this.returnState){const s=this.states.map(i=>null);return[n].concat(s)}else return n})}get states(){if(this.states_==null){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let n=0;n<e;++n)t.push(null);return t}else return this.states_}set states(e){this.states_=e}build(e){const t=null;if(this.numConstants!=null)throw new ze("Constants support is not implemented in RNN yet.");Ww(e)&&(e=e[0]),e=e;const n=this.stateful?e[0]:null,s=e.slice(2);this.inputSpec[0]=new mn({shape:[n,null,...s]});const i=[e[0]].concat(e.slice(2));if(t!=null)throw new ze("Constants support is not implemented in RNN yet.");this.cell.build(i);let o;if(Array.isArray(this.cell.stateSize)?o=this.cell.stateSize:o=[this.cell.stateSize],this.stateSpec!=null){if(!ot(this.stateSpec.map(a=>a.shape[a.shape.length-1]),o))throw new j(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=o.map(a=>new mn({shape:[null,a]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){ee(()=>{if(!this.stateful)throw new tr("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape[0];if(n==null)throw new j("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.states_==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(s=>ct([n,s])):this.states_=[ct([n,this.cell.stateSize])];else if(e==null)He(this.states_),this.keptStates!=null&&(He(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(s=>ct([n,s])):this.states_[0]=ct([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new j(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t===!0?this.keptStates.push(this.states_.slice()):He(this.states_);for(let s=0;s<this.states_.length;++s){const i=e[s],o=Array.isArray(this.cell.stateSize)?this.cell.stateSize[s]:this.cell.stateSize,a=[n,o];if(!ot(i.shape,a))throw new j(`State ${s} is incompatible with layer ${this.name}: expected shape=${a}, received shape=${i.shape}`);this.states_[s]=i}}this.states_=this.states_.map(s=>Cn(s.clone()))})}apply(e,t){let n=t==null?null:t.initialState,s=t==null?null:t.constants;t==null&&(t={});const i=lN(e,n,s,this.numConstants);e=i.inputs,n=i.initialState,s=i.constants;let o=[],a=[];if(n!=null){t.initialState=n,o=o.concat(n),this.stateSpec=[];for(const h of n)this.stateSpec.push(new mn({shape:h.shape}));a=a.concat(this.stateSpec)}s!=null&&(t.constants=s,o=o.concat(s),this.numConstants=s.length);const c=o[0]instanceof ci;if(c){const h=[e].concat(o),d=this.inputSpec.concat(a),m=this.inputSpec;this.inputSpec=d;const y=super.apply(h,t);return this.inputSpec=m,y}else return super.apply(e,t)}call(e,t){return ee(()=>{const n=t==null?null:t.mask,s=t==null?null:t.training;let i=t==null?null:t.initialState;e=Ke(e),i==null&&(this.stateful?i=this.states_:i=this.getInitialState(e));const o=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(i.length!==o)throw new j(`RNN Layer has ${o} state(s) but was passed ${i.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");const a={training:s},c=(w,L)=>{const T=this.cell.call([w].concat(L),a);return[T[0],T.slice(1)]},h=hN(c,e,i,this.goBackwards,n,null,this.unroll,this.returnSequences),d=h[0],m=h[1],y=h[2];this.stateful&&this.resetStates(y,s);const b=this.returnSequences?m:d;return this.returnState?[b].concat(y):b})}getInitialState(e){return ee(()=>{let t=ct(e.shape);return t=Ue(t,[1,2]),t=Dh(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(n=>n>1?Nw(t,[1,n]):t):this.cell.stateSize>1?[Nw(t,[1,this.cell.stateSize])]:[t]})}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.cell!=null&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){const e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};this.numConstants!=null&&(t.numConstants=this.numConstants);const n=this.cell.getConfig();return this.getClassName()===_i.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign({},n,e,t)}static fromConfig(e,t,n={}){const s=t.cell,i=li(s,n);return new e(Object.assign(t,{cell:i}))}}_i.className="RNN",me(_i);class nc extends lt{}class Hp extends nc{constructor(e){super(e);this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,pn(this.units,"units"),this.activation=Vr(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Ft(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ft(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ft(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=_t(e.kernelRegularizer),this.recurrentRegularizer=_t(e.recurrentRegularizer),this.biasRegularizer=_t(e.biasRegularizer),this.kernelConstraint=ln(e.kernelConstraint),this.recurrentConstraint=ln(e.recurrentConstraint),this.biasConstraint=ln(e.biasConstraint),this.dropout=Xa([1,Mr([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Xa([1,Mr([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=St(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return ee(()=>{if(e=e,e.length!==2)throw new j(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];const s=t.training==null?!1:t.training;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Yr({ones:()=>En(e),rate:this.dropout,training:s})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Yr({ones:()=>En(n),rate:this.recurrentDropout,training:s}));let i;const o=this.dropoutMask,a=this.recurrentDropoutMask;o!=null?i=Di(X(e,o),this.kernel.read()):i=Di(e,this.kernel.read()),this.bias!=null&&(i=ki(i,this.bias.read())),a!=null&&(n=X(n,a));let c=be(i,Di(n,this.recurrentKernel.read()));return this.activation!=null&&(c=this.activation.apply(c)),[c,c]})}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Gr(this.activation),useBias:this.useBias,kernelInitializer:Yt(this.kernelInitializer),recurrentInitializer:Yt(this.recurrentInitializer),biasInitializer:Yt(this.biasInitializer),kernelRegularizer:It(this.kernelRegularizer),recurrentRegularizer:It(this.recurrentRegularizer),biasRegularizer:It(this.biasRegularizer),activityRegularizer:It(this.activityRegularizer),kernelConstraint:cn(this.kernelConstraint),recurrentConstraint:cn(this.recurrentConstraint),biasConstraint:cn(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign({},e,t)}}Hp.className="SimpleRNNCell",me(Hp);class fL extends _i{constructor(e){e.cell=new Hp(e),super(e)}call(e,t){return ee(()=>{this.cell.dropoutMask!=null&&(He(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(He(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=t==null?null:t.mask,s=t==null?null:t.training,i=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:i})})}static fromConfig(e,t){return new e(t)}}fL.className="SimpleRNN",me(fL);class qp extends nc{constructor(e){super(e);if(this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new j("GRUCell does not support reset_after parameter set to true.");this.units=e.units,pn(this.units,"units"),this.activation=Vr(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Vr(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Ft(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ft(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ft(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=_t(e.kernelRegularizer),this.recurrentRegularizer=_t(e.recurrentRegularizer),this.biasRegularizer=_t(e.biasRegularizer),this.kernelConstraint=ln(e.kernelConstraint),this.recurrentConstraint=ln(e.recurrentConstraint),this.biasConstraint=ln(e.biasConstraint),this.dropout=Xa([1,Mr([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Xa([1,Mr([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=St(e);const t=e[e.length-1];this.kernel=this.addWeight("kernel",[t,this.units*3],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*3],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units*3],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return ee(()=>{if(e=e,e.length!==2)throw new j(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);const n=t.training==null?!1:t.training;let s=e[1];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Yr({ones:()=>En(e),rate:this.dropout,training:n,count:3})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Yr({ones:()=>En(s),rate:this.recurrentDropout,training:n,count:3}));const i=this.dropoutMask,o=this.recurrentDropoutMask;let a,c,h;0<this.dropout&&this.dropout<1&&(e=X(e,i[0]));let d=Di(e,this.kernel.read());this.useBias&&(d=ki(d,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(s=X(s,o[0]));const m=this.recurrentKernel.read(),[y,b]=is(m,[2*this.units,this.units],m.rank-1),w=Di(s,y),[L,T,A]=is(d,3,d.rank-1),[N,E]=is(w,2,w.rank-1);a=this.recurrentActivation.apply(be(L,N)),c=this.recurrentActivation.apply(be(T,E));const D=Di(X(c,s),b);h=this.activation.apply(be(A,D));const F=be(X(a,s),X(be(1,zt(a)),h));return[F,F]})}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Gr(this.activation),recurrentActivation:Gr(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Yt(this.kernelInitializer),recurrentInitializer:Yt(this.recurrentInitializer),biasInitializer:Yt(this.biasInitializer),kernelRegularizer:It(this.kernelRegularizer),recurrentRegularizer:It(this.recurrentRegularizer),biasRegularizer:It(this.biasRegularizer),activityRegularizer:It(this.activityRegularizer),kernelConstraint:cn(this.kernelConstraint),recurrentConstraint:cn(this.recurrentConstraint),biasConstraint:cn(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign({},e,t)}}qp.className="GRUCell",me(qp);class gL extends _i{constructor(e){e.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new qp(e),super(e)}call(e,t){return ee(()=>{this.cell.dropoutMask!=null&&(He(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(He(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=t==null?null:t.mask,s=t==null?null:t.training,i=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:i})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}}gL.className="GRU",me(gL);class zh extends nc{constructor(e){super(e);this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,pn(this.units,"units"),this.activation=Vr(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Vr(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Ft(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ft(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ft(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=_t(e.kernelRegularizer),this.recurrentRegularizer=_t(e.recurrentRegularizer),this.biasRegularizer=_t(e.biasRegularizer),this.kernelConstraint=ln(e.kernelConstraint),this.recurrentConstraint=ln(e.recurrentConstraint),this.biasConstraint=ln(e.biasConstraint),this.dropout=Xa([1,Mr([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Xa([1,Mr([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;e=St(e);const n=e[e.length-1];this.kernel=this.addWeight("kernel",[n,this.units*4],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*4],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint);let s;if(this.useBias){if(this.unitForgetBias){const i=this.biasInitializer,o=this.units;s=new(t=class extends Bs{apply(c,h){const d=i.apply([o]),m=new Ip().apply([o]),y=i.apply([o*2]);return ov(ov(d,m),y)}},t.className="CustomInit",t)}else s=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,s,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return ee(()=>{const n=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new j(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let s=e[1];const i=e[2];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Yr({ones:()=>En(e),rate:this.dropout,training:n,count:4})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Yr({ones:()=>En(s),rate:this.recurrentDropout,training:n,count:4}));const o=this.dropoutMask,a=this.recurrentDropoutMask;let c,h,d,m;0<this.dropout&&this.dropout<1&&(e=X(e,o[0]));let y=Di(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(s=X(s,a[0])),y=be(y,Di(s,this.recurrentKernel.read())),this.useBias&&(y=ki(y,this.bias.read()));const[b,w,L,T]=is(y,4,y.rank-1);c=this.recurrentActivation.apply(b),h=this.recurrentActivation.apply(w),d=be(X(h,i),X(c,this.activation.apply(L))),m=this.recurrentActivation.apply(T);const A=X(m,this.activation.apply(d));return[A,A,d]})}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Gr(this.activation),recurrentActivation:Gr(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Yt(this.kernelInitializer),recurrentInitializer:Yt(this.recurrentInitializer),biasInitializer:Yt(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:It(this.kernelRegularizer),recurrentRegularizer:It(this.recurrentRegularizer),biasRegularizer:It(this.biasRegularizer),activityRegularizer:It(this.activityRegularizer),kernelConstraint:cn(this.kernelConstraint),recurrentConstraint:cn(this.recurrentConstraint),biasConstraint:cn(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign({},e,t)}}zh.className="LSTMCell",me(zh);class yL extends _i{constructor(e){e.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new zh(e),super(e)}call(e,t){return ee(()=>{this.cell.dropoutMask!=null&&(He(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(He(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=t==null?null:t.mask,s=t==null?null:t.training,i=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:i})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}}yL.className="LSTM",me(yL);class jp extends nc{constructor(e){super(e);this.cells=e.cells}get stateSize(){const e=[];for(const t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return ee(()=>{e=e;let n=e.slice(1);const s=[];for(const a of this.cells.slice().reverse())Array.isArray(a.stateSize)?s.push(n.splice(0,a.stateSize.length)):s.push(n.splice(0,1));s.reverse();const i=[];let o;for(let a=0;a<this.cells.length;++a){const c=this.cells[a];n=s[a],a===0?o=[e[0]].concat(n):o=[o[0]].concat(n),o=c.call(o,t),i.push(o.slice(1))}n=[];for(const a of i.slice().reverse())n.push(...a);return[o[0]].concat(n)})}build(e){Ww(e)&&(e=e[0]),e=e;let t;this.cells.forEach((n,s)=>{Po(`RNNCell_${s}`,()=>{n.build(e),Array.isArray(n.stateSize)?t=n.stateSize[0]:t=n.stateSize,e=[e[0],t]})}),this.built=!0}getConfig(){const e=super.getConfig(),t=i=>({className:i.getClassName(),config:i.getConfig()}),n=this.cells.map(t),s={cells:n};return Object.assign({},e,s)}static fromConfig(e,t,n={}){const s=[];for(const i of t.cells)s.push(li(i,n));return new e({cells:s})}get trainableWeights(){if(!this.trainable)return[];const e=[];for(const t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const n of this.cells)t.push(...n.trainableWeights);return t.concat(e)}return e}getWeights(){const e=[];for(const t of this.cells)e.push(...t.weights);return $w(e)}setWeights(e){const t=[];for(const n of this.cells){const s=n.weights.length,i=e.splice(s);for(let o=0;o<n.weights.length;++o)t.push([n.weights[o],i[o]])}Uw(t)}}jp.className="StackedRNNCells",me(jp);function Yr(e){const{ones:t,rate:n,training:s=!1,count:i=1}=e,o=()=>cv(t(),n),a=()=>Fh(o,t,s);if(!i||i<=1)return Cn(a().clone());const c=Array(i).fill(void 0).map(a);return c.map(h=>Cn(h.clone()))}var lG=function(e,t){var n={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,s=Object.getOwnPropertySymbols(e);i<s.length;i++)t.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(e,s[i])&&(n[s[i]]=e[s[i]]);return n};class $Q extends nc{}class uN extends _i{constructor(e){if(e.unroll)throw new ze("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new ze("It is not possible at the moment to stack convolutional cells.");super(e);this.inputSpec=[new mn({ndim:5})]}call(e,t){return ee(()=>{if(this.cell.dropoutMask!=null&&(He(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(He(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new j("ConvRNN2D cell does not support constants");const n=t==null?null:t.mask,s=t==null?null:t.training,i=t==null?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:i})})}computeOutputShape(e){let t=this.computeSingleOutputShape(e);return this.returnSequences||(t=[t[0],...t.slice(2)]),this.returnState&&(t=[t,...Array(2).fill([e[0],...t.slice(-3)])]),t}getInitialState(e){return ee(()=>{const{stateSize:t}=this.cell,n=e.shape,s=this.computeSingleOutputShape(n),i=[s[0],...s.slice(2)],o=ct(i);return Array.isArray(t)?Array(t.length).fill(o):[o]})}resetStates(e,t=!1){ee(()=>{if(!this.stateful)throw new tr("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape,s=this.computeSingleOutputShape(n),i=[s[0],...s.slice(2)],o=n[0];if(o==null)throw new j("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.getStates()==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>ct(i)):this.states_=[ct(i)];else if(e==null)He(this.states_),this.keptStates!=null&&(He(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>ct(i)):this.states_[0]=ct(i);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new j(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t?this.keptStates.push(this.states_.slice()):He(this.states_);for(let a=0;a<this.states_.length;++a){const c=e[a],h=i;if(!ot(c.shape,h))throw new j(`State ${a} is incompatible with layer ${this.name}: expected shape=${h}, received shape=${c.shape}`);this.states_[a]=c}}this.states_=this.states_.map(a=>Cn(a.clone()))})}computeSingleOutputShape(e){const{dataFormat:t,filters:n,kernelSize:s,padding:i,strides:o,dilationRate:a}=this.cell,c=t==="channelsFirst",h=e[c?3:2],d=e[c?4:3],m=hi(h,s[0],i,o[0],a[0]),y=hi(d,s[1],i,o[1],a[1]),b=[...e.slice(0,2),...c?[n,m,y]:[m,y,n]];return b}}uN.className="ConvRNN2D";class Kp extends zh{constructor(e){const{filters:t,kernelSize:n,strides:s,padding:i,dataFormat:o,dilationRate:a}=e;super(Object.assign({},e,{units:t}));this.filters=t,pn(this.filters,"filters"),this.kernelSize=tc(n,2,"kernelSize"),this.kernelSize.forEach(c=>pn(c,"kernelSize")),this.strides=tc(s||1,2,"strides"),this.strides.forEach(c=>pn(c,"strides")),this.padding=i||"valid",Ts(this.padding),this.dataFormat=o||"channelsLast",Vt(this.dataFormat),this.dilationRate=tc(a||1,2,"dilationRate"),this.dilationRate.forEach(c=>pn(c,"dilationRate"))}build(e){var t;e=St(e);const n=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[n]==null)throw new j(`The channel dimension of the input should be defined. Found ${e[n]}`);const s=e[n],i=4,o=this.kernelSize.concat([s,this.filters*i]);this.kernel=this.addWeight("kernel",o,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);const a=this.kernelSize.concat([this.filters,this.filters*i]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",a,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let c;if(this.unitForgetBias){const h=this.biasInitializer,d=this.filters;c=new(t=class extends Bs{apply(y,b){const w=h.apply([d]),L=ni([d]),T=h.apply([d*2]);return vw([w,L,T])}},t.className="CustomInit",t)}else c=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*i],null,c,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return ee(()=>{if(e.length!==3)throw new j(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);const n=t.training||!1,s=e[0],i=e[1],o=e[2],a=4;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Yr({ones:()=>En(s),rate:this.dropout,training:n,count:a}));const c=this.dropoutMask,h=(Ie,Se,Ee)=>!Se||!Se[Ee]?Ie:X(Se[Ee],Ie);let d=h(s,c,0),m=h(s,c,1),y=h(s,c,2),b=h(s,c,3);0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Yr({ones:()=>En(i),rate:this.recurrentDropout,training:n,count:a}));const w=this.recurrentDropoutMask;let L=h(i,w,0),T=h(i,w,1),A=h(i,w,2),N=h(i,w,3);const E=3,[D,F,_,B]=is(this.kernel.read(),a,E),[$,H,q,J]=this.useBias?is(this.bias.read(),a):[null,null,null,null];d=this.inputConv(d,D,$,this.padding),m=this.inputConv(m,F,H,this.padding),y=this.inputConv(y,_,q,this.padding),b=this.inputConv(b,B,J,this.padding);const[re,ce,ue,he]=is(this.recurrentKernel.read(),a,E);L=this.recurrentConv(L,re),T=this.recurrentConv(T,ce),A=this.recurrentConv(A,ue),N=this.recurrentConv(N,he);const de=this.recurrentActivation.apply(be(d,L)),le=this.recurrentActivation.apply(be(m,T)),ye=be(X(le,o),X(de,this.activation.apply(be(y,A)))),pe=X(this.recurrentActivation.apply(be(b,N)),this.activation.apply(ye));return[pe,pe,ye]})}getConfig(){const e=super.getConfig(),{units:t}=e,n=lG(e,["units"]),s={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign({},n,s)}inputConv(e,t,n,s){const i=Xi(e,t,this.strides,s||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return n?ki(i,n,this.dataFormat):i}recurrentConv(e,t){const n=1;return Xi(e,t,n,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}}Kp.className="ConvLSTM2DCell",me(Kp);class bL extends uN{constructor(e){const t=new Kp(e);super(Object.assign({},e,{cell:t}))}static fromConfig(e,t){return new e(t)}}bL.className="ConvLSTM2D",me(bL);class Xp extends lt{constructor(e){super(e);this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(this.noiseShape==null)return this.noiseShape;const t=e.shape,n=[];for(let s=0;s<this.noiseShape.length;++s)n.push(this.noiseShape[s]==null?t[s]:this.noiseShape[s]);return n}call(e,t){return ee(()=>{this.invokeCallHook(e,t);const n=Ke(e);if(0<this.rate&&this.rate<1){const s=t.training==null?!1:t.training,i=this.getNoiseShape(n),o=Fh(()=>cv(n,this.rate,i,this.seed),()=>n,s);return o}return e})}getConfig(){const e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}}Xp.className="Dropout",me(Xp);class wL extends Xp{constructor(e){super(e);this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}wL.className="SpatialDropout1D",me(wL);class LL extends lt{constructor(e){super(e);if(this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.batchInputShape==null&&e.inputShape==null&&e.inputDim!=null){let t=null;e.batchSize!=null&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,pn(this.units,"units"),this.activation=Vr(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=Ft(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=Ft(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=ln(e.kernelConstraint),this.biasConstraint=ln(e.biasConstraint),this.kernelRegularizer=_t(e.kernelRegularizer),this.biasRegularizer=_t(e.biasRegularizer),this.activityRegularizer=_t(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=St(e);const t=e[e.length-1];this.kernel==null&&(this.kernel=this.addWeight("kernel",[t,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:t}}],this.built=!0}computeOutputShape(e){e=St(e);const t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return ee(()=>{this.invokeCallHook(e,t);const n=Ke(e),s=JA(this.activation.getClassName());let i;return s!=null?i=Di(n,this.kernel.read(),s,this.bias?this.bias.read():null):(i=Di(n,this.kernel.read()),this.bias!=null&&(i=ki(i,this.bias.read())),this.activation!=null&&(i=this.activation.apply(i))),i})}getConfig(){const e={units:this.units,activation:Gr(this.activation),useBias:this.useBias,kernelInitializer:Yt(this.kernelInitializer),biasInitializer:Yt(this.biasInitializer),kernelRegularizer:It(this.kernelRegularizer),biasRegularizer:It(this.biasRegularizer),activityRegularizer:It(this.activityRegularizer),kernelConstraint:cn(this.kernelConstraint),biasConstraint:cn(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}LL.className="Dense",me(LL);class SL extends lt{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=St(e);for(const t of e.slice(1))if(t==null)throw new j(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[e[0],Br(e,1)]}call(e,t){return ee(()=>{this.invokeCallHook(e,t);let n=Ke(e);if(this.dataFormat==="channelsFirst"&&n.rank>1){const s=[0];for(let i=2;i<n.rank;++i)s.push(i);s.push(1),n=n.transpose(s)}return Dz(n)})}getConfig(){const e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);const t=super.getConfig();return Object.assign(e,t),e}}SL.className="Flatten",me(SL);class IL extends lt{constructor(e){super(e);this.supportsMasking=!0,this.activation=Vr(e.activation)}call(e,t){return ee(()=>{this.invokeCallHook(e,t);const n=Ke(e);return this.activation.apply(n)})}getConfig(){const e={activation:Gr(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}IL.className="Activation",me(IL);class xL extends lt{constructor(e){super(e);this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return ee(()=>(e=Ke(e),Oz(e,this.n)))}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}xL.className="RepeatVector",me(xL);class TL extends lt{constructor(e){super(e);this.targetShape=e.targetShape;for(let t=0;t<this.targetShape.length;++t)this.isUnknown(this.targetShape[t])&&(this.targetShape[t]=null)}isUnknown(e){return e<0||e==null}fixUnknownDimension(e,t){const n="Total size of new array must be unchanged.",s=t.slice();let i=1,o=null;for(let c=0;c<s.length;++c){const h=s[c];if(this.isUnknown(h))if(o===null)o=c;else throw new j("Can only specifiy one unknown dimension.");else i*=h}const a=Br(e);if(o!==null){if(i===0||a%i!==0)throw new j(n);s[o]=a/i}else if(a!==i)throw new j(n);return s}computeOutputShape(e){let t=!1;for(let n=0;n<e.length;++n)if(this.isUnknown(e[n])){t=!0;break}return t?e.slice(0,1).concat(this.targetShape):e.slice(0,1).concat(this.fixUnknownDimension(e.slice(1),this.targetShape))}call(e,t){return ee(()=>{this.invokeCallHook(e,t);const n=Ke(e),s=n.shape,i=s.slice(0,1).concat(this.fixUnknownDimension(s.slice(1),this.targetShape));return n.reshape(i)})}getConfig(){const e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}}TL.className="Reshape",me(TL);class AL extends lt{constructor(e){super(e);if(e.dims==null)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);const t=oi(1,e.dims.length+1);if(!ot(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new mn({ndim:this.dims.length+1})]}computeOutputShape(e){e=St(e);const t=e.slice();return this.dims.forEach((n,s)=>{t[s+1]=e[n]}),t}call(e,t){return Me(Ke(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}}AL.className="Permute",me(AL);class vL extends lt{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null?this.maskValue=e.maskValue==null?0:e.maskValue:this.maskValue=0}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){const n=Ke(e),s=-1;return Jl(Fr(n,this.maskValue),s)}call(e,t){return ee(()=>{this.invokeCallHook(e,t);const n=Ke(e),s=-1,i=!0,o=Jl(Fr(n,this.maskValue),s,i),a=n.mul(o.asType(n.dtype));return a})}}vL.className="Masking",me(vL);class NL extends lt{constructor(e){super(e);if(this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",e.batchInputShape==null&&e.inputShape==null){let t=null;e.batchSize!=null&&(t=e.batchSize),e.inputLength==null?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(Rt(e.inputLength))}this.inputDim=e.inputDim,pn(this.inputDim,"inputDim"),this.outputDim=e.outputDim,pn(this.outputDim,"outputDim"),this.embeddingsInitializer=Ft(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=_t(e.embeddingsRegularizer),this.activityRegularizer=_t(e.activityRegularizer),this.embeddingsConstraint=ln(e.embeddingsConstraint),this.maskZero=e.maskZero,this.supportsMasking=e.maskZero,this.inputLength=e.inputLength}build(e){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0}warnOnIncompatibleInputShape(e){}computeMask(e,t){return ee(()=>this.maskZero?(e=Ke(e),Fr(e,Qe(e))):null)}computeOutputShape(e){if(e=St(e),this.inputLength==null)return[...e,this.outputDim];const t=Rt(this.inputLength);if(t.length!==e.length-1)throw new j(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let s=0;s<t.length;++s){const i=t[s],o=e[s+1];if(i!=null&&o!=null&&i!==o)throw new j(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);i==null&&(t[n]=o),n++}}return[e[0],...t,this.outputDim]}call(e,t){return ee(()=>{this.invokeCallHook(e,t);let n=Ke(e);n.dtype!=="int32"&&(n=Eh(n,"int32"));const s=av(this.embeddings.read(),n.as1D());return s.reshape(St(this.computeOutputShape(n.shape)))})}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Yt(this.embeddingsInitializer),embeddingsRegularizer:It(this.embeddingsRegularizer),activityRegularizer:It(this.activityRegularizer),embeddingsConstraint:cn(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}}NL.className="Embedding",me(NL);class Yo extends lt{constructor(e){super(e||{});this.supportsMasking=!0}mergeFunction(e){throw new ze}computeElementwiseOpOutputShape(e,t){if(e==null||t==null)return null;if(e.length<t.length)return this.computeElementwiseOpOutputShape(t,e);if(t.length===0)return e;const n=e.slice(0,e.length-t.length);for(let s=0;s<t.length;++s){const i=e[e.length-t.length+s],o=t[s];if(i==null||o==null||i<0||o<0)n.push(null);else if(i===1)n.push(o);else if(o===1)n.push(i);else{if(i!==o)throw new j("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));n.push(i)}}return n}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[St(e)]),e=e,e.length<2)throw new j(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);let t=[];for(const i of e)i!=null&&i[0]!==null&&t.push(i[0]);if(t=Ur(t),t.length>1)throw new j(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let n=e[0]==null?null:e[0].slice(1);for(let i=1;i<e.length;++i){const o=e[i]==null?null:e[i].slice(1);n=this.computeElementwiseOpOutputShape(n,o)}const s=e.map(i=>i.length);e.indexOf(null)===-1&&Ur(s).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return ee(()=>{if(e=e,this.reshapeRequired){const n=[],s=e.map(i=>i.rank);if(s.indexOf(null)===-1){const i=Mr(s);for(let o of e){const a=o.rank;for(let c=0;c<i-a;++c)o=Dh(o,1);n.push(o)}return this.mergeFunction(n)}else{let i=!1;for(const c of e){const h=c.rank;if(h==null){const d=c.shape,m=d[0],y=d.slice(1).concat([m]);let b=c.reshape([m].concat(Br(d.slice(1))));b=Me(b,[1,0]),b=b.reshape(y),n.push(b),i=!0}else if(h>1){const d=oi(1,h).concat([0]);n.push(Me(c,d)),i=!0}else n.push(c)}let o=this.mergeFunction(n);const a=o.rank;if(i){if(a==null){const c=o.shape,h=c.length,d=c[h-1],m=[d].concat(c.slice(0,c.length-1));o=Me(o.reshape([-1,d]),[1,0]).reshape(m)}else if(a>1){const c=[a-1].concat(oi(0,a-1));o=Me(o,c)}}return o}}else return this.mergeFunction(e)})}computeOutputShape(e){e=e;let t;e[0]==null?t=null:t=e[0].slice(1);for(let s=1;s<e.length;++s){const i=e[s]==null?null:e[s].slice(1);t=this.computeElementwiseOpOutputShape(t,i)}let n=[];for(const s of e)s!=null&&s[0]!==null&&n.push(s[0]);return n=Ur(n),n.length===1?t=n.concat(t):t=[null].concat(t),t}computeMask(e,t){return ee(()=>{if(t==null)return null;if(!Array.isArray(t))throw new j("`mask` should be an Array");if(!Array.isArray(e))throw new j("`inputs` should be an Array");if(t.length!==e.length)throw new j(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(s=>s==null))return null;t=t.map(s=>s==null?s:qn(s,0));let n=t[0];for(let s=1;s<t.length-1;++s)n=$s(n,t[s]);return n})}}class Gh extends Yo{constructor(e){super(e)}mergeFunction(e){return ee(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=be(t,e[n]);return t})}}Gh.className="Add",me(Gh);function UQ(e){if(Array.isArray(e)){const t=new Gh({});return t.apply(e)}else return new Gh(e)}class Vh extends Yo{constructor(e){super(e)}mergeFunction(e){return ee(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=X(t,e[n]);return t})}}Vh.className="Multiply",me(Vh);function BQ(e){if(Array.isArray(e)){const t=new Vh({});return t.apply(e)}else return new Vh(e)}class Yh extends Yo{constructor(e){super(e)}mergeFunction(e){return ee(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=be(t,e[n]);return X(1/e.length,t)})}}Yh.className="Average",me(Yh);function MQ(e){if(Array.isArray(e)){const t=new Yh({});return t.apply(e)}else return new Yh(e)}class Hh extends Yo{constructor(e){super(e)}mergeFunction(e){return ee(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=Ws(t,e[n]);return t})}}Hh.className="Maximum",me(Hh);function PQ(e){if(Array.isArray(e)){const t=new Hh({});return t.apply(e)}else return new Hh(e)}class qh extends Yo{constructor(e){super(e)}mergeFunction(e){return ee(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=Eo(t,e[n]);return t})}}qh.className="Minimum",me(qh);function zQ(e){if(Array.isArray(e)){const t=new qh({});return t.apply(e)}else return new qh(e)}class jh extends Yo{constructor(e){super(e);this.DEFAULT_AXIS=-1,e==null&&(e={}),this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){if(!(Array.isArray(e)&&Array.isArray(e[0]))||e.length===1)throw new j("A `Concatenate` layer should be called on a list of at least 2 inputs");e=e;let t=!0;for(const s of e)if(s!=null){t=!1;break}if(t)return;const n=[];for(let s=0;s<e.length;++s){const i=e[s].slice();i.splice(this.axis,1);let o=!1;for(const a of n)if(ot(a,i)){o=!0;break}o||n.push(i)}if(n.length>1)throw new j("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return ee(()=>vw(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new j("A `Concatenate` layer should be called on a list of inputs.");const t=e,n=t[0].slice(),s=this.axis<0?n.length+this.axis:this.axis;for(const i of t.slice(1)){if(n[s]==null||i[s]==null){n[s]=null;break}n[s]+=i[s]}return n}computeMask(e,t){if(t==null)return null;if(!Array.isArray(t))throw new j("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new j("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new j(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return ee(()=>{let n=!0;if(t.forEach(o=>{if(o!=null){n=!1;return}}),n)return null;const s=[];for(let o=0;o<e.length;++o)t[o]==null?s.push(En(e[o]).asType("bool")):t[o].rank<e[o].rank?s.push(qn(t[o],-1)):s.push(t[o]);const i=Pt(s,this.axis);return kd(i,-1,!1)})}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}jh.className="Concatenate",me(jh);function GQ(e){if(Array.isArray(e)){const t=new jh({});return t.apply(e)}else return new jh(e)}function Kh(e,t){for(;e<0;)e+=t;return e}function hG(e,t,n){if(e.shape.length>3||t.shape.length>3)throw new ze("batchDot is not implemented for tensors of 4D or higher rank yet");if(k(e.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`),k(e.shape.length>=2,()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`),typeof n=="number"&&(n=[n,n]),e.dtype==="complex64"||t.dtype==="complex64")throw new ze("batchDot is not implemented for complex64-type Tensors yet.");const s=e.shape.length,i=t.shape.length;n==null&&(n=[s-1,i-2]);const o=n;return ee(()=>{let a;if(s>i){a=s-i;const h=[];for(let d=0;d<a;++d)h.push(1);t=t.reshape(t.shape.concat(h))}else if(i>s){a=i-s;const h=[];for(let d=0;d<a;++d)h.push(1);e=e.reshape(e.shape.concat(h))}else a=0;let c;if(e.shape.length===2&&t.shape.length===2)o[0]===o[1]?c=e.mul(t).sum(o[0]):c=e.transpose([1,0]).mul(t).sum(o[1]);else{const h=o[0]!==e.shape.length-1,d=o[1]===t.shape.length-1;c=e.matMul(t,h,d)}if(a>0){let h;s>i?h=s+i-3:h=s-1;const d=[];for(let m=h;m<h+a;++m)d.push(m);c=c.squeeze(d)}return c.shape.length===1&&(c=c.expandDims(1)),c})}class CL extends Yo{constructor(e){super(e);this.axes=e.axes,this.normalize=e.normalize==null?!1:e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){k(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");const t=e[0],n=e[1];if(t.length>3||n.length>3)throw new ze("Dot layer does not support tensors of 4D or higher rank yet.");const s=this.interpretAxes(t,n);if(t[s[0]]!==n[s[1]])throw new j(`Dimension incompatibility: ${t[s[0]]} !== ${n[s[1]]}`)}mergeFunction(e){if(e.length!==2)throw new j(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t=e[0],n=e[1],s;return Array.isArray(this.axes)?s=this.axes.map((i,o)=>Kh(i,e[o].shape.length)):s=[Kh(this.axes,t.shape.length),Kh(this.axes,n.shape.length)],this.normalize&&(t=Fp(t,s[0]),n=Fp(n,s[1])),hG(t,n,s)}interpretAxes(e,t){let n;return Array.isArray(this.axes)?n=this.axes:n=[Kh(this.axes,e.length),Kh(this.axes,t.length)],n}computeOutputShape(e){k(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");const t=e[0].slice(),n=e[1].slice();if(t.length>3||n.length>3)throw new ze("Dot layer does not support tensors of 4D or higher rank yet.");const s=this.interpretAxes(t,n);t.splice(s[0],1),n.splice(s[1],1),n.splice(0,1);const i=t.concat(n);return i.length===1&&i.push(1),i}computeMask(e,t){return null}getConfig(){const e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}}CL.className="Dot",me(CL);class RL extends lt{constructor(e){super(e);this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return ee(()=>{this.invokeCallHook(e,t);const n=Ke(e),s=()=>Sp(n.shape,0,this.stddev).add(n),i=Fh(s,()=>n,t.training||!1);return i})}}RL.className="GaussianNoise",me(RL);class OL extends lt{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return ee(()=>{this.invokeCallHook(e,t);const n=Ke(e);if(this.rate>0&&this.rate<1){const s=()=>{const i=Math.sqrt(this.rate/(1-this.rate));return n.mul(Sp(n.shape,1,i))};return Fh(s,()=>n,t.training||!1)}return n})}}OL.className="GaussianDropout",me(OL);class EL extends lt{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Ke(e).shape}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return ee(()=>{if(this.rate<1&&this.rate>0){const n=this._getNoiseShape(e),s=()=>{const i=Ke(e),o=1.6732632423543772,a=1.0507009873554805,c=-o*a;let h=Ji(_o(n),this.rate);h=Eh(h,"float32");const d=((1-this.rate)*(1+this.rate*c**2))**-.5,m=-d*c*this.rate,y=i.mul(h).add(h.add(-1).mul(c));return y.mul(d).add(m)};return Fh(s,()=>Ke(e),t.training||!1)}return e})}}EL.className="AlphaDropout",me(EL);function Xh(e,t,n,s,i,o=.001){let a;if(e.rank===2)a=_T(e,t,n,s,i,o);else if(e.rank===3)a=WT(e,t,n,s,i,o);else if(e.rank===4)a=$T(e,t,n,s,i,o);else throw new ze(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return a}function uG(e,t,n,s,i=.001){return ee(()=>{const o=jd(e,s),a=o.mean,c=o.variance,h=Xh(e,a,c,n,t,i);return[h,a,c]})}function dG(e,t,n,s,i=.001){return ee(()=>{const o=jd(e,s),a=o.mean,c=o.variance,h=[];for(const L of oi(0,e.rank))s.indexOf(L)!==-1?h.push(1):h.push(e.shape[L]);const d=a.reshape(h),m=c.reshape(h),y=t==null?null:t.reshape(h),b=n==null?null:n.reshape(h),w=Xh(e,d,m,b,y,i);return[w,a,c]})}function pG(e,t,n,s,i=.001){return ot(s.slice().sort(),oi(0,e.rank-1))?uG(e,t,n,s,i):dG(e,t,n,s,i)}class DL extends lt{constructor(e){e==null&&(e={}),super(e),this.supportsMasking=!0,this.axis=e.axis==null?-1:e.axis,this.momentum=e.momentum==null?.99:e.momentum,this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=Ft(e.betaInitializer||"zeros"),this.gammaInitializer=Ft(e.gammaInitializer||"ones"),this.movingMeanInitializer=Ft(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=Ft(e.movingVarianceInitializer||"ones"),this.betaConstraint=ln(e.betaConstraint),this.gammaConstraint=ln(e.gammaConstraint),this.betaRegularizer=_t(e.betaRegularizer),this.gammaRegularizer=_t(e.gammaRegularizer)}build(e){e=St(e);const t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(n==null)throw new j(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new mn({ndim:e.length,axes:{[t]:n}})];const s=[n];this.scale&&(this.gamma=this.addWeight("gamma",s,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",s,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",s,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",s,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return ee(()=>{const n=t.training==null?!1:t.training,s=Ke(e),i=s.shape,o=i.length,a=oi(0,o),c=this.axis>=0?this.axis:this.axis+o;a.splice(c,1);const h=Bo(1,o);h[c]=i[c];const d=a.slice();d.sort();const m=!ot(d,oi(0,o).slice(0,o-1)),y=()=>{if(m){const N=this.movingMean.read().reshape(h),E=this.movingVariance.read().reshape(h),D=this.center?this.beta.read().reshape(h):null,F=this.scale?this.gamma.read().reshape(h):null;return Xh(s,N,E,D,F,this.epsilon)}else return Xh(s,this.movingMean.read(),this.movingVariance.read(),this.beta==null?null:this.beta.read(),this.gamma==null?null:this.gamma.read(),this.epsilon)};if(!n)return y();const[b,w,L]=pG(s,this.gamma.read(),this.beta.read(),a,this.epsilon),T=(N,E,D)=>{ee(()=>{const F=1-D,_=N.read(),B=_.sub(E).mul(F);N.write(_.sub(B))})},A=()=>{T(this.movingMean,w,this.momentum),T(this.movingVariance,L,this.momentum)};return A(),b})}getConfig(){const e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Yt(this.betaInitializer),gammaInitializer:Yt(this.gammaInitializer),movingMeanInitializer:Yt(this.movingMeanInitializer),movingVarianceInitializer:Yt(this.movingVarianceInitializer),betaRegularizer:It(this.betaRegularizer),gammaRegularizer:It(this.gammaRegularizer),betaConstraint:cn(this.betaConstraint),gammaConstraint:cn(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}}DL.className="BatchNormalization",me(DL);class kL extends lt{constructor(e){if(e==null&&(e={}),super(e),this.axis=e.axis==null?-1:e.axis,typeof this.axis=="number"){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else if(Array.isArray(this.axis)){for(const t of this.axis)if(!Number.isInteger(t))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}else throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=Ft(e.betaInitializer||"zeros"),this.gammaInitializer=Ft(e.gammaInitializer||"ones"),this.betaRegularizer=_t(e.betaRegularizer),this.gammaRegularizer=_t(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=St(e);const t=e.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let i=0;i<this.axis.length;++i)this.axis[i]<0&&(this.axis[i]+=t);for(const i of this.axis)if(i<0||i>=t)throw new Error(`Invalid axis: ${i}`);if(this.axis.length!==Ur(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);const n=this.axis.map(i=>e[i]),s=!0;this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,s):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,s):this.beta=null,this.built=!0}call(e,t){const n=Ke(e),s=n.shape,i=s.length;return ee(()=>{const o=!0;let{mean:a,variance:c}=jd(n,this.axis,o);const h=Bo(1,i);for(const L of this.axis)h[L]=s[L];const d=L=>L!=null&&L.shape.length!==i&&this.axis!==[i-1]?L.reshape(h):L;let m=d(this.gamma.read()),y=d(this.beta.read());const b=[],w=[];for(let L=0;L<i;++L)this.axis.indexOf(L)!==-1?(b.push(s[L]),w.push(1)):(b.push(1),w.push(s[L]));return a=a.tile(b),c=c.tile(b),m=m.tile(w),y=y.tile(w),Xh(n,a,c,y,m,this.epsilon)})}getConfig(){const e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Yt(this.betaInitializer),gammaInitializer:Yt(this.gammaInitializer),betaRegularizer:It(this.betaRegularizer),gammaRegularizer:It(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}}kL.className="LayerNormalization",me(kL);function VQ(e,t){return ee(()=>{if(e.rank!==3)throw new j(`temporalPadding expects input tensor to be 3-D, but received a ${e.rank}-D tensor.`);if(t==null&&(t=[1,1]),t.length!==2)throw new j(`temporalPadding expects input padding pattern to be a length-2 array, but received a length-${t.length} array.`);const n=[[0,0],t,[0,0]];return Ri(e,n)})}function mG(e,t,n){return ee(()=>{if(e.rank!==4)throw new j(`temporalPadding expects input tensor to be 4-D, but received a ${e.rank}-D tensor.`);if(t==null&&(t=[[1,1],[1,1]]),t.length!==2||t[0].length!==2||t[1].length!==2)throw new j("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(n==null&&(n=ii()),n!=="channelsLast"&&n!=="channelsFirst")throw new j(`Unknown data format: ${n}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let s;return n==="channelsFirst"?s=[[0,0],[0,0],t[0],t[1]]:s=[[0,0],t[0],t[1],[0,0]],Ri(e,s)})}class FL extends lt{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?ii():e.dataFormat,e.padding==null)this.padding=[[1,1],[1,1]];else if(typeof e.padding=="number")this.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,e.padding.length!==2)throw new j(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,n;if(typeof e.padding[0]=="number")t=[e.padding[0],e.padding[0]],n=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,e.padding[0].length!==2)throw new j(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);if(t=e.padding[0],e.padding[1].length!==2)throw new j(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);n=e.padding[1]}this.padding=[t,n]}this.inputSpec=[new mn({ndim:4})]}computeOutputShape(e){e=St(e);let t,n;return this.dataFormat==="channelsFirst"?(e[2]!=null&&e[2]>=0?t=e[2]+this.padding[0][0]+this.padding[0][1]:t=null,e[3]!=null&&e[3]>=0?n=e[3]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],e[1],t,n]):(e[1]!=null&&e[1]>=0?t=e[1]+this.padding[0][0]+this.padding[0][1]:t=null,e[2]!=null&&e[2]>=0?n=e[2]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],t,n,e[3]])}call(e,t){return ee(()=>mG(Ke(e),this.padding,this.dataFormat))}getConfig(){const e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}FL.className="ZeroPadding2D",me(FL);function Jp(e,t,n,s,i,o){return ee(()=>{Vt(i),ev(o),Ts(s),n==null&&(n=[1,1]),s==null&&(s="valid"),i==null&&(i=ii()),o==null&&(o="max"),e=aL(e,i);let a;const c=s==="same"?"same":"valid";return o==="max"?a=hh(e,t,n,c):a=nh(e,t,n,c),i==="channelsFirst"&&(a=Me(a,[0,3,1,2])),a})}function dN(e,t,n,s,i,o){return ee(()=>{Vt(i),ev(o),Ts(s),n==null&&(n=[1,1,1]),s==null&&(s="valid"),i==null&&(i=ii()),o==null&&(o="max"),e=rN(e,i);let a;const c=s==="same"?"same":"valid";return o==="max"?a=Wb(e,t,n,c):a=Ib(e,t,n,c),i==="channelsFirst"&&(a=Me(a,[0,4,1,2,3])),a})}class pN extends lt{constructor(e){if(e.poolSize==null&&(e.poolSize=2),super(e),typeof e.poolSize=="number")this.poolSize=[e.poolSize];else if(Array.isArray(e.poolSize)&&e.poolSize.length===1&&typeof e.poolSize[0]=="number")this.poolSize=e.poolSize;else throw new j(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(pn(this.poolSize,"poolSize"),e.strides==null)this.strides=this.poolSize;else if(typeof e.strides=="number")this.strides=[e.strides];else if(Array.isArray(e.strides)&&e.strides.length===1&&typeof e.strides[0]=="number")this.strides=e.strides;else throw new j(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);pn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,Ts(this.padding),this.inputSpec=[new mn({ndim:3})]}computeOutputShape(e){e=St(e);const t=hi(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return ee(()=>{this.invokeCallHook(e,t),e=Dh(Ke(e),2);const n=this.poolingFunction(Ke(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return _r(n,[2])})}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class _L extends pN{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return Vt(i),Ts(s),Jp(e,t,n,s,i,"max")}}_L.className="MaxPooling1D",me(_L);class WL extends pN{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return Vt(i),Ts(s),Jp(e,t,n,s,i,"avg")}}WL.className="AveragePooling1D",me(WL);class mN extends lt{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==2)throw new j(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides];pn(this.poolSize,"poolSize"),pn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Vt(this.dataFormat),Ts(this.padding),this.inputSpec=[new mn({ndim:4})]}computeOutputShape(e){e=St(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=hi(t,this.poolSize[0],this.padding,this.strides[0]),n=hi(n,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n]:[e[0],t,n,e[3]]}call(e,t){return ee(()=>(this.invokeCallHook(e,t),this.poolingFunction(Ke(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class $L extends mN{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return Vt(i),Ts(s),Jp(e,t,n,s,i,"max")}}$L.className="MaxPooling2D",me($L);class UL extends mN{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return Vt(i),Ts(s),Jp(e,t,n,s,i,"avg")}}UL.className="AveragePooling2D",me(UL);class fN extends lt{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==3)throw new j(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides,e.strides];pn(this.poolSize,"poolSize"),pn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Vt(this.dataFormat),Ts(this.padding),this.inputSpec=[new mn({ndim:5})]}computeOutputShape(e){e=St(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],s=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=hi(t,this.poolSize[0],this.padding,this.strides[0]),n=hi(n,this.poolSize[1],this.padding,this.strides[1]),s=hi(s,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n,s]:[e[0],t,n,s,e[4]]}call(e,t){return ee(()=>(this.invokeCallHook(e,t),this.poolingFunction(Ke(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class BL extends fN{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return Vt(i),Ts(s),dN(e,t,n,s,i,"max")}}BL.className="MaxPooling3D",me(BL);class ML extends fN{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return Vt(i),Ts(s),dN(e,t,n,s,i,"avg")}}ML.className="AveragePooling3D",me(ML);class gN extends lt{constructor(e){super(e);this.inputSpec=[new mn({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new ze}}class PL extends gN{constructor(e){super(e||{})}call(e,t){return ee(()=>{const n=Ke(e);return Gt(n,1)})}}PL.className="GlobalAveragePooling1D",me(PL);class zL extends gN{constructor(e){super(e||{})}call(e,t){return ee(()=>{const n=Ke(e);return jn(n,1)})}}zL.className="GlobalMaxPooling1D",me(zL);class yN extends lt{constructor(e){super(e);this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Vt(this.dataFormat),this.inputSpec=[new mn({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new ze}getConfig(){const e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class GL extends yN{call(e,t){return ee(()=>{const n=Ke(e);return this.dataFormat==="channelsLast"?Gt(n,[1,2]):Gt(n,[2,3])})}}GL.className="GlobalAveragePooling2D",me(GL);class VL extends yN{call(e,t){return ee(()=>{const n=Ke(e);return this.dataFormat==="channelsLast"?jn(n,[1,2]):jn(n,[2,3])})}}VL.className="GlobalMaxPooling2D",me(VL);class bN extends lt{constructor(e){super(e);this.layer=e.layer}build(e){this.built=!0}get trainable(){return this.layer!=null?this.layer.trainable:!1}set trainable(e){this.layer!=null&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){const e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,n={}){const s=t.layer,i=li(s,n);delete t.layer;const o={layer:i};return Object.assign(o,t),new e(o)}}class YL extends bN{constructor(e){super(e);this.supportsMasking=!0}build(e){if(e=St(e),e.length<3)throw new j(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];const t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){e=St(e);const t=[e[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),s=e[1];return[n[0],s].concat(n.slice(1))}call(e,t){return ee(()=>{e=Ke(e);const n=(o,a)=>{const c=Ke(this.layer.call(o,t));return[c,[]]},s=hN(n,e,[],!1,null,null,!1,!0),i=s[1];return i})}}YL.className="TimeDistributed",me(YL);function fG(e){ja(Tz,"BidirectionalMergeMode",e)}const gG="concat";class HL extends bN{constructor(e){super(e);const t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=li(n),t.goBackwards=!(t.goBackwards===!0);const s={};if(s.className=e.layer.getClassName(),s.config=t,this.backwardLayer=li(s),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?gG:e.mergeMode,fG(this.mergeMode),e.weights)throw new ze("weights support is not implemented for Bidirectional layer yet.");this._stateful=e.layer.stateful,this.returnSequences=e.layer.returnSequences,this.returnState=e.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=e.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(e){this._trainable=e,this.forwardLayer!=null&&(this.forwardLayer.trainable=e),this.backwardLayer!=null&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){const t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))}computeOutputShape(e){let t=this.forwardLayer.computeOutputShape(e);Array.isArray(t)&&Array.isArray(t[0])||(t=[t]),t=t;let n,s,i;return this.returnState&&(i=t.slice(1)),n=t[0],n=n,this.mergeMode==="concat"?(n[n.length-1]*=2,s=[n]):this.mergeMode==null?s=[n,n.slice()]:s=[n],this.returnState?this.mergeMode==null?s.concat(i).concat(i.slice()):[n].concat(i).concat(i.slice()):Kn(s)}apply(e,t){let n=t==null?null:t.initialState,s=t==null?null:t.constants;t==null&&(t={});const i=lN(e,n,s,this.numConstants);if(e=i.inputs,n=i.initialState,s=i.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(n==null||n.length===0)&&s==null)return super.apply(e,t);const o=[],a=[];if(n!=null){const h=n.length;if(h%2>0)throw new j("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,o.push(...n);const d=n.map(m=>new mn({shape:m.shape}));this.forwardLayer.stateSpec=d.slice(0,h/2),this.backwardLayer.stateSpec=d.slice(h/2),a.push(...d)}if(s!=null)throw new ze("Support for constants in Bidirectional layers is not implemented yet.");const c=o[0]instanceof ci;for(const h of o)if(h instanceof ci!==c)throw new j("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(c){const h=[e].concat(o),d=this.inputSpec.concat(a),m=this.inputSpec;this.inputSpec=d;const y=super.apply(h,t);return this.inputSpec=m,y}else return super.apply(e,t)}call(e,t){return ee(()=>{const n=t.initialState;let s,i;if(n==null)s=this.forwardLayer.call(e,t),i=this.backwardLayer.call(e,t);else{const c=n.slice(0,n.length/2),h=n.slice(n.length/2);s=this.forwardLayer.call(e,Object.assign(t,{initialState:c})),i=this.backwardLayer.call(e,Object.assign(t,{initialState:h}))}let o;this.returnState&&(Array.isArray(s)&&(o=s.slice(1).concat(i.slice(1))),s=s[0],i=i[0]),this.returnSequences&&(i=Is(i,1));let a;return this.mergeMode==="concat"?a=vw([s,i]):this.mergeMode==="sum"?a=be(s,i):this.mergeMode==="ave"?a=X(.5,be(s,i)):this.mergeMode==="mul"?a=X(s,i):this.mergeMode==null&&(a=[s,i]),this.returnState?this.mergeMode==null?a.concat(o):[a].concat(o):a})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){Po(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),Po(this.backwardLayer.name,()=>{this.backwardLayer.build(e)}),this.built=!0}computeMask(e,t){Array.isArray(t)&&(t=t[0]);let n;if(this.returnSequences?this.mergeMode==null?n=[t,t]:n=t:this.mergeMode==null?n=[null,null]:n=null,this.returnState){const s=this.forwardLayer.states,i=s.map(o=>null);return Array.isArray(n)?n.concat(i).concat(i):[n].concat(i).concat(i)}else return n}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.forwardLayer!=null&&this.forwardLayer.setFastWeightInitDuringBuild(e),this.backwardLayer!=null&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){const e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){const n=li(t.layer);if(delete t.layer,t.numConstants!=null)throw new ze("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const s=t;return s.layer=n,new e(s)}}HL.className="Bidirectional",me(HL);function yG(e){return new Ja(e)}function bG(e){return new iL(e)}function wG(e){return new tL(e)}function LG(e){return new nL(e)}function SG(e){return new sL(e)}function IG(e){return new oL(e)}function xG(e){return new rL(e)}function TG(e){return new Yp(e)}function AG(e){return new Ph(e)}function vG(e){return new hL(e)}function NG(e){return new Vp(e)}function CG(e){return new uL(e)}function RG(e){return new dL(e)}function OG(e){return new pL(e)}function EG(e){return new mL(e)}function DG(e){return new IL(e)}function kG(e){return new LL(e)}function FG(e){return new Xp(e)}function _G(e){return new wL(e)}function WG(e){return new SL(e)}function $G(e){return new xL(e)}function UG(e){return new TL(e)}function BG(e){return new AL(e)}function MG(e){return new NL(e)}function PG(e){return new Gh(e)}function zG(e){return new Yh(e)}function GG(e){return new jh(e)}function VG(e){return new Hh(e)}function YG(e){return new qh(e)}function HG(e){return new Vh(e)}function qG(e){return new CL(e)}function jG(e){return new DL(e)}function KG(e){return new kL(e)}function XG(e){return new FL(e)}function qL(e){return new WL(e)}function JG(e){return qL(e)}function ZG(e){return qL(e)}function jL(e){return new UL(e)}function QG(e){return jL(e)}function eV(e){return jL(e)}function KL(e){return new ML(e)}function tV(e){return KL(e)}function nV(e){return KL(e)}function sV(e){return new PL(e)}function iV(e){return new GL(e)}function wN(e){return new zL(e)}function LN(e){return new VL(e)}function SN(e){return new _L(e)}function IN(e){return new $L(e)}function rV(e){return new BL(e)}function oV(e){return new gL(e)}function aV(e){return new qp(e)}function cV(e){return new yL(e)}function lV(e){return new zh(e)}function hV(e){return new fL(e)}function uV(e){return new Hp(e)}function dV(e){return new bL(e)}function pV(e){return new Kp(e)}function mV(e){return new _i(e)}function fV(e){return new jp(e)}function gV(e){return new HL(e)}function yV(e){return new YL(e)}const bV=wN,wV=LN,LV=SN,SV=IN;function IV(e){return new RL(e)}function xV(e){return new OL(e)}function TV(e){return new EL(e)}function AV(e){return new vL(e)}var vV=Object.freeze({__proto__:null,inputLayer:yG,elu:bG,reLU:wG,leakyReLU:LG,prelu:SG,softmax:IG,thresholdedReLU:xG,conv1d:TG,conv2d:AG,conv2dTranspose:vG,conv3d:NG,separableConv2d:CG,cropping2D:RG,upSampling2d:OG,depthwiseConv2d:EG,activation:DG,dense:kG,dropout:FG,spatialDropout1d:_G,flatten:WG,repeatVector:$G,reshape:UG,permute:BG,embedding:MG,add:PG,average:zG,concatenate:GG,maximum:VG,minimum:YG,multiply:HG,dot:qG,batchNormalization:jG,layerNormalization:KG,zeroPadding2d:XG,averagePooling1d:qL,avgPool1d:JG,avgPooling1d:ZG,averagePooling2d:jL,avgPool2d:QG,avgPooling2d:eV,averagePooling3d:KL,avgPool3d:tV,avgPooling3d:nV,globalAveragePooling1d:sV,globalAveragePooling2d:iV,globalMaxPooling1d:wN,globalMaxPooling2d:LN,maxPooling1d:SN,maxPooling2d:IN,maxPooling3d:rV,gru:oV,gruCell:aV,lstm:cV,lstmCell:lV,simpleRNN:hV,simpleRNNCell:uV,convLstm2d:dV,convLstm2dCell:pV,rnn:mV,stackedRNNCells:fV,bidirectional:gV,timeDistributed:yV,globalMaxPool1d:bV,globalMaxPool2d:wV,maxPool1d:LV,maxPool2d:SV,Layer:lt,RNN:_i,RNNCell:nc,input:Gv,gaussianNoise:IV,gaussianDropout:xV,alphaDropout:TV,masking:AV});function NV(e,t){return zw(e,t)}function CV(e,t){return Tv(e,t)}function RV(e,t){return Av(e,t)}function OV(e,t){return Gw(e,t)}function EV(e,t){return Vw(e,t)}function DV(e,t){return xv(e,t)}function kV(e,t){return w3(e,t)}function FV(e,t){return $p(e,t)}function _V(e,t){return Qa(e,t)}function WV(e,t){return zr(e,t)}function $V(e,t){return zr(e,t)}function UV(e,t){return zr(e,t)}function BV(e,t){return sr(e,t)}function MV(e,t){return sr(e,t)}function PV(e,t){return sr(e,t)}var zV=Object.freeze({__proto__:null,binaryAccuracy:NV,binaryCrossentropy:CV,sparseCategoricalAccuracy:RV,categoricalAccuracy:OV,categoricalCrossentropy:EV,precision:DV,recall:kV,cosineProximity:FV,meanAbsoluteError:_V,meanAbsolutePercentageError:WV,MAPE:$V,mape:UV,meanSquaredError:BV,MSE:MV,mse:PV});var GV=Object.freeze({__proto__:null,modelFromJSON:Z3});function VV(e){return new Bh(e)}function YV(e){return oG(e)}function HV(e){return aG(e)}var qV=Object.freeze({__proto__:null,l1l2:VV,l1:YV,l2:HV});class xN extends Za{constructor(){super(...arguments);this.model=null}setModel(e){if(!(e instanceof ir))throw new Error("model must be a LayersModel, not some other Container");this.model=e}}function Zp(e,t){return e<t}function TN(e,t){return e>t}class AN extends xN{constructor(e){super();if(e==null&&(e={}),e.restoreBestWeights)throw new ze("restoreBestWeights = True is not implemented in EarlyStopping yet.");this.monitor=e.monitor||"val_loss",this.minDelta=Math.abs(e.minDelta||0),this.patience=e.patience||0,this.verbose=e.verbose||0,this.mode=e.mode||"auto",this.baseline=e.baseline,["auto","min","max"].indexOf(this.mode)===-1&&(console.warn(`EarlyStopping mode '${this.mode}' is invalid. Falling back to mode 'auto'.`),this.mode="auto"),this.mode==="min"?this.monitorFunc=Zp:this.mode==="max"?this.monitorFunc=TN:this.monitor.indexOf("acc")!==-1?this.monitorFunc=TN:this.monitorFunc=Zp,this.monitorFunc===Zp&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Zp?Infinity:-Infinity}async onEpochEnd(e,t){await Pr(t);const n=this.getMonitorValue(t);if(n==null)return;this.monitorFunc(n-this.minDelta,this.best)?(this.best=n,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0))}async onTrainEnd(e){this.stoppedEpoch>0&&this.verbose&&console.log(`Epoch ${this.stoppedEpoch}: early stopping.`)}getMonitorValue(e){e==null&&(e={});const t=e[this.monitor];return t==null&&console.warn(`Metric for EarlyStopping ${this.monitor} is not available. Available metrics are: ${Object.keys(e)}`),t}}function jV(e){return new AN(e)}const KV={earlyStopping:jV};var ui;(function(e){e[e.DT_INVALID=0]="DT_INVALID",e[e.DT_FLOAT=1]="DT_FLOAT",e[e.DT_DOUBLE=2]="DT_DOUBLE",e[e.DT_INT32=3]="DT_INT32",e[e.DT_UINT8=4]="DT_UINT8",e[e.DT_INT16=5]="DT_INT16",e[e.DT_INT8=6]="DT_INT8",e[e.DT_STRING=7]="DT_STRING",e[e.DT_COMPLEX64=8]="DT_COMPLEX64",e[e.DT_INT64=9]="DT_INT64",e[e.DT_BOOL=10]="DT_BOOL",e[e.DT_QINT8=11]="DT_QINT8",e[e.DT_QUINT8=12]="DT_QUINT8",e[e.DT_QINT32=13]="DT_QINT32",e[e.DT_BFLOAT16=14]="DT_BFLOAT16",e[e.DT_FLOAT_REF=101]="DT_FLOAT_REF",e[e.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",e[e.DT_INT32_REF=103]="DT_INT32_REF",e[e.DT_UINT8_REF=104]="DT_UINT8_REF",e[e.DT_INT16_REF=105]="DT_INT16_REF",e[e.DT_INT8_REF=106]="DT_INT8_REF",e[e.DT_STRING_REF=107]="DT_STRING_REF",e[e.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",e[e.DT_INT64_REF=109]="DT_INT64_REF",e[e.DT_BOOL_REF=110]="DT_BOOL_REF",e[e.DT_QINT8_REF=111]="DT_QINT8_REF",e[e.DT_QUINT8_REF=112]="DT_QUINT8_REF",e[e.DT_QINT32_REF=113]="DT_QINT32_REF",e[e.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF"})(ui||(ui={}));var vN;(function(e){let t;(function(n){n[n.LEGACY=0]="LEGACY",n[n.V1=1]="V1",n[n.V2=2]="V2"})(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))})(vN||(vN={}));const XL={};function XV(e,t){const n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};XL[e]=n}function NN(e){return XL[e]}function JV(e){delete XL[e]}function R(e,t,n,s){const i=t.inputParams[e];if(i&&i.inputIndexStart!==void 0){const a=i.inputIndexStart,c=i.inputIndexEnd===0?void 0:i.inputIndexEnd===void 0?a+1:i.inputIndexEnd;if(i.type==="tensor")return Jn(t.inputNames[i.inputIndexStart],n,s);if(i.type==="tensors"){const m=t.inputNames.slice(a,c);return m.map(y=>Jn(y,n,s))}const h=Jn(t.inputNames.slice(a)[0],n,s),d=h.dataSync();return i.type==="number"?d[0]:ys(h.shape,d)}const o=t.attrParams[e];return o&&o.value}function Jn(e,t,n){const[s,i]=as(e),o=n.currentContextIds.find(a=>!!t[Qp(s,a)]);return o!==void 0?t[Qp(s,o)][i]:void 0}function ZV(e,t,n){return t[Qp(e,n.currentContextId)]}function rr(e,t){const[n,s]=as(e);return[Qp(n,t&&t.currentContextId),s]}function Qp(e,t){return t?`${e}-${t}`:e}function as(e){const t=e.split(":");if(t.length===1)return[e,0];const n=t[0];return[n,Number(t[t.length-1])]}function YQ(e,t){const n=[];for(let s=0;s<e.length;s+=t)n.push(e.slice(s,s+t));return n}function em(e,t,n){let s=R("pad",e,t,n);if(s==="explicit"){s=R("explicitPaddings",e,t,n);const i=[[0,0],[0,0],[0,0],[0,0]];for(let o=0;o<4;o++)i[o][0]=s[o*2],i[o][1]=s[o*2+1];return i}return s}function or(e){return e.kept?e:Rr(e)}const QV=[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];var eY=Object.freeze({__proto__:null,json:QV});const tY=[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"clip_value_min",name:"clipValueMin",type:"number"},{tfName:"clip_value_max",name:"clipValueMax",type:"number"}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"clipValueMin",name:"clipValueMin",type:"number",defaultValue:0},{tfName:"clipValueMax",name:"clipValueMax",type:"number",defaultValue:6}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Prod",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axes",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];var nY=Object.freeze({__proto__:null,json:tY});const sY=[{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]}];var iY=Object.freeze({__proto__:null,json:sY});const rY=[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}];var oY=Object.freeze({__proto__:null,json:rY});const aY=[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}];var cY=Object.freeze({__proto__:null,json:aY});const lY=[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV4",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"T_threshold",name:"threshold",type:"dtype",notSupported:!0},{tfName:"pad_to_max_output_size",name:"padToMaxOutputSize",type:"bool"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];var hY=Object.freeze({__proto__:null,json:lY});const uY=[{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}];var dY=Object.freeze({__proto__:null,json:uY});const pY=[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}];var mY=Object.freeze({__proto__:null,json:pY});const fY=[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]}];var gY=Object.freeze({__proto__:null,json:fY});const yY=[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SelectV2",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];var bY=Object.freeze({__proto__:null,json:yY});const wY=[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];var LY=Object.freeze({__proto__:null,json:wY});const SY=[{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"SparseToDense",category:"normalization",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!0,notSupported:!0}]}];var IY=Object.freeze({__proto__:null,json:SY});const xY=[{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}];var TY=Object.freeze({__proto__:null,json:xY});const AY=[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool",notSupported:!0}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]}];var vY=Object.freeze({__proto__:null,json:AY});const NY=[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}];var CY=Object.freeze({__proto__:null,json:NY});const RY=[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]}];var OY=Object.freeze({__proto__:null,json:RY});class CN{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[eY,nY,iY,oY,cY,hY,dY,bY,gY,mY,LY,IY,TY,vY,CY,OY],t=[].concat(...e.map(n=>n.json));this.opMappers=t.reduce((n,s)=>(n[s.tfOpName]=s,n),{})}transformGraph(e,t={}){const n=e.node,s=[],i=[],o=[],a=n.reduce((L,T)=>(L[T.name]=this.mapNode(T),T.op.startsWith("Placeholder")?s.push(L[T.name]):T.op==="Const"?i.push(L[T.name]):(T.input==null||T.input.length===0)&&o.push(L[T.name]),L),{});let c=[];const h=[];let d={},m={};t!=null&&(d=this.mapSignatureEntries(t.inputs),m=this.mapSignatureEntries(t.outputs));const y=Object.keys(a);y.forEach(L=>{const T=a[L];T.inputNames.forEach(A=>{const[N]=rr(A);T.inputs.push(a[N]),a[N].children.push(T)})}),Object.keys(m).length===0?y.forEach(L=>{const T=a[L];T.children.length===0&&h.push(T)}):Object.keys(m).forEach(L=>{const[T]=rr(L),A=a[T];A!=null&&(A.signatureKey=m[L],h.push(A))}),Object.keys(d).length>0?Object.keys(d).forEach(L=>{const[T]=rr(L),A=a[T];A&&(A.signatureKey=d[L],c.push(A))}):c=s;let b={};e.library!=null&&e.library.function!=null&&(b=e.library.function.reduce((L,T)=>(L[T.signature.name]=this.mapFunction(T),L),{}));const w={nodes:a,inputs:c,outputs:h,weights:i,placeholders:s,signature:t,functions:b};return o.length>0&&(w.initNodes=o),w}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,n)=>(t[e[n].name]=n,t),{})}mapNode(e){const t=NN(e.op)||this.opMappers[e.op]||{};e.attr==null&&(e.attr={});const n={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(s=>s.startsWith("^")?s.substr(1):s),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr};return t.inputs!=null&&(n.inputParams=t.inputs.reduce((s,i)=>(s[i.name]={type:i.type,inputIndexStart:i.start,inputIndexEnd:i.end},s),{})),t.attrs!=null&&(n.attrParams=t.attrs.reduce((s,i)=>{const o=i.type;let a;switch(i.type){case"string":a=JL(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=JL(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"string[]":a=rS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=rS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"number":a=QL(e.attr,i.tfName,i.defaultValue||0),a===void 0&&!!i.tfDeprecatedName&&(a=QL(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"number[]":a=iS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=iS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"bool":a=ZL(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=ZL(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"bool[]":a=aS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=aS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"shape":a=sS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=sS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"shape[]":a=oS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=oS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"dtype":a=tS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=tS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"dtype[]":a=nS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=nS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"func":a=ON(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=ON(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${i.type} for op: ${e.op}`)}return s[i.name]={value:a,type:o},s},{})),n}mapFunction(e){const t=e.nodeDef,n=[],s=[];let i={};t!=null&&(i=t.reduce((m,y)=>(m[y.name]=this.mapNode(y),y.op==="Const"&&s.push(m[y.name]),m),{}));const o=[],a=[];e.signature.inputArg.forEach(m=>{const[y]=rr(m.name),b={name:y,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:eS(m.type),type:"dtype"}},children:[]};b.signatureKey=m.name,o.push(b),i[y]=b});const c=Object.keys(i);c.forEach(m=>{const y=i[m];y.inputNames.forEach(b=>{const[w]=rr(b);y.inputs.push(i[w]),i[w].children.push(y)})});const h=e.ret;e.signature.outputArg.forEach(m=>{const[y,b]=rr(h[m.name]),w=i[y];w!=null&&(w.defaultOutput=b,a.push(w))});const d=this.mapArgsToSignature(e);return{nodes:i,inputs:o,outputs:a,weights:s,placeholders:n,signature:d}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n),t),{}),outputs:e.signature.outputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n,e.ret),t),{})}}mapArgToTensorInfo(e,t){let n=e.name;return t!=null&&(n=t[n]),{name:n,dtype:e.type}}}function EY(e){const t=C().global;if(typeof t.atob!="undefined")return t.atob(e);if(typeof Buffer!="undefined")return new Buffer(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}function RN(e,t){const n=Array.isArray(e)?String.fromCharCode.apply(null,e):EY(e);return t?n:n.toLowerCase()}function JL(e,t,n,s=!1){const i=e[t];return i!=null?RN(i.s,s):n}function ZL(e,t,n){const s=e[t];return s?s.b:n}function QL(e,t,n){const s=e[t]||{},i=s.i!=null?s.i:s.f!=null?s.f:n;return typeof i=="number"?i:parseInt(i,10)}function eS(e){typeof e=="string"&&(e=ui[e]);switch(e){case ui.DT_FLOAT:return"float32";case ui.DT_INT32:case ui.DT_INT64:case ui.DT_INT8:case ui.DT_UINT8:return"int32";case ui.DT_BOOL:return"bool";case ui.DT_DOUBLE:return"float32";case ui.DT_STRING:return"string";default:return null}}function ON(e,t,n){const s=e[t];return s&&s.func?s.func.name:n}function tS(e,t,n){const s=e[t];return s&&s.type?eS(s.type):n}function nS(e,t,n){const s=e[t];return s&&s.list&&s.list.type?s.list.type.map(i=>eS(i)):n}function EN(e){return e.unknownRank?void 0:e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function sS(e,t,n){const s=e[t];return s&&s.shape?EN(s.shape):n}function iS(e,t,n){const s=e[t];return s?((s.list.f&&s.list.f.length?s.list.f:s.list.i)||[]).map(i=>typeof i=="number"?i:parseInt(i,10)):n}function rS(e,t,n,s=!1){const i=e[t];return i&&i.list&&i.list.s?i.list.s.map(o=>RN(o,s)):n}function oS(e,t,n){const s=e[t];return s&&s.list&&s.list.shape?s.list.shape.map(i=>EN(i)):n}function aS(e,t,n){const s=e[t];return s&&s.list&&s.list.b?s.list.b:n}class DY{constructor(e,t,n){this.node=e,this.tensorMap=t,this.context=n,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(s=>this.getInput(s)),e.rawAttrs!=null&&(this.attrs=Object.keys(e.rawAttrs).reduce((s,i)=>(s[i]=this.getAttr(i),s),{}))}getInput(e){return Jn(e,this.tensorMap,this.context)}getAttr(e,t){const n=this.node.rawAttrs[e];if(n.tensor!=null)return Jn(e,this.tensorMap,this.context);if(n.i!=null||n.f!=null)return QL(this.node.rawAttrs,e,t);if(n.s!=null)return JL(this.node.rawAttrs,e,t);if(n.b!=null)return ZL(this.node.rawAttrs,e,t);if(n.shape!=null)return sS(this.node.rawAttrs,e,t);if(n.type!=null)return tS(this.node.rawAttrs,e,t);if(n.list!=null){if(n.list.i!=null||n.list.f!=null)return iS(this.node.rawAttrs,e,t);if(n.list.s!=null)return rS(this.node.rawAttrs,e,t);if(n.list.shape!=null)return oS(this.node.rawAttrs,e,t);if(n.list.b!=null)return aS(this.node.rawAttrs,e,t);if(n.list.type!=null)return nS(this.node.rawAttrs,e,t)}return t}}const kY=(e,t,n)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[be(R("a",e,t,n),R("b",e,t,n))];case"AddN":return[kT(R("tensors",e,t,n))];case"FloorMod":case"Mod":return[qd(R("a",e,t,n),R("b",e,t,n))];case"Mul":return[X(R("a",e,t,n),R("b",e,t,n))];case"RealDiv":case"Div":return[_e(R("a",e,t,n),R("b",e,t,n))];case"DivNoNan":return[Rb(R("a",e,t,n),R("b",e,t,n))];case"FloorDiv":return[Dd(R("a",e,t,n),R("b",e,t,n))];case"Sub":return[Ce(R("a",e,t,n),R("b",e,t,n))];case"Minimum":return[Eo(R("a",e,t,n),R("b",e,t,n))];case"Maximum":return[Ws(R("a",e,t,n),R("b",e,t,n))];case"Pow":return[si(R("a",e,t,n),R("b",e,t,n))];case"SquaredDifference":return[yh(R("a",e,t,n),R("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},HQ="arithmetic";const FY=(e,t,n)=>{switch(e.op){case"Abs":case"ComplexAbs":return[sn(R("x",e,t,n))];case"Acos":return[ub(R("x",e,t,n))];case"Acosh":return[db(R("x",e,t,n))];case"Asin":return[fb(R("x",e,t,n))];case"Asinh":return[gb(R("x",e,t,n))];case"Atan":return[yb(R("x",e,t,n))];case"Atan2":return[bb(R("x",e,t,n),R("y",e,t,n))];case"Atanh":return[wb(R("x",e,t,n))];case"Ceil":return[Tb(R("x",e,t,n))];case"Complex":return[Ti(R("real",e,t,n),R("imag",e,t,n))];case"Cos":return[rh(R("x",e,t,n))];case"Cosh":return[Bd(R("x",e,t,n))];case"Elu":return[Oo(R("x",e,t,n))];case"Erf":return[Ob(R("x",e,t,n))];case"Exp":return[Ls(R("x",e,t,n))];case"Expm1":return[Eb(R("x",e,t,n))];case"Floor":return[_a(R("x",e,t,n))];case"Log":return[ns(R("x",e,t,n))];case"Log1p":return[Gd(R("x",e,t,n))];case"Imag":return[$a(R("x",e,t,n))];case"Neg":return[zt(R("x",e,t,n))];case"Reciprocal":return[Mb(R("x",e,t,n))];case"Real":return[Do(R("x",e,t,n))];case"Relu":return[Oi(R("x",e,t,n))];case"Round":return[zb(R("x",e,t,n))];case"Selu":return[Jd(R("x",e,t,n))];case"Sigmoid":return[Ni(R("x",e,t,n))];case"Sin":return[Zd(R("x",e,t,n))];case"Sign":return[Vb(R("x",e,t,n))];case"Sinh":return[Qd(R("x",e,t,n))];case"Softplus":return[Ua(R("x",e,t,n))];case"Sqrt":return[Ln(R("x",e,t,n))];case"Square":return[wt(R("x",e,t,n))];case"Tanh":return[Fa(R("x",e,t,n))];case"Tan":return[qb(R("x",e,t,n))];case"Relu6":case"ClipByValue":return[Hn(R("x",e,t,n),R("clipValueMin",e,t,n),R("clipValueMax",e,t,n))];case"Rsqrt":return[Xd(Jn(e.inputNames[0],t,n))];case"Prod":return[Kd(R("x",e,t,n),R("axes",e,t,n))];case"LeakyRelu":return[zd(R("x",e,t,n),R("alpha",e,t,n))];case"Prelu":return[dh(R("x",e,t,n),R("alpha",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},qQ="basic_math";function Ps(e,t,n=""){k(_Y(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function _Y(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==-1&&t[n]!==-1&&e[n]!==t[n])return!1;return!0}class WY{constructor(e,t,n,s,i,o,a){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=s,this.identicalElementShapes=i,this.dynamicSize=o,this.clearAfterRead=a,this.tensors=[],this.closed_=!1,this.idTensor=Ne(0),Cn(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.tensor.id))&&t.tensor.dispose()}),this.tensors=[],this.closed_=!0,this.idTensor.dispose()}size(){return this.tensors.length}read(e){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||e>=this.size())throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);const t=this.tensors[e];if(t.cleared)throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor}readMany(e){return e.map(t=>this.read(t))}write(e,t){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);const n=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},
because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=t.shape),Ps(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);n.tensor=t,Cn(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((n,s)=>this.write(n,t[s]))}gather(e,t){if(!!t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let s=0;s<this.size();s++)e.push(s)}if(e.length===0)return en([],[0].concat(this.elementShape));const n=this.readMany(e);return Ps(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),rs(n,0)}concat(e){if(!!e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(this.size()===0)return en([],[0].concat(this.elementShape));const t=[];for(let s=0;s<this.size();s++)t.push(s);const n=this.readMany(t);return Ps(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),Pt(n,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);if(e.length!==t.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);const n=Math.max(...e);if(!this.dynamicSize&&n>=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(e,Ei(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0;const s=e.map(c=>(n+=c,n));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to
tensor.shape[0], but sum of lengths is
${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);const i=n===0?0:t.size/n,o=[];ee(()=>{t=K(t,[1,n,i]);for(let c=0;c<e.length;++c){const h=c===0?0:s[c-1],d=[0,h,0],m=[1,e[c],i];o[c]=K(nt(t,d,m),this.elementShape)}return o});const a=[];for(let c=0;c<e.length;c++)a[c]=c;this.writeMany(a,o)}}class Jh{constructor(e,t,n,s=-1){this.tensors=e,this.elementShape=t,this.elementDtype=n,e!=null&&e.forEach(i=>{if(n!==i.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${i.dtype}`);Ps(t,i.shape,"TensorList shape mismatch: "),Cn(i)}),this.idTensor=Ne(0),this.maxNumElements=s,Cn(this.idTensor)}get id(){return this.idTensor.id}copy(){return new Jh([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.id))&&t.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(n!==-1&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);return Ps(e,this.elementShape,"TensorList shape mismatch: "),ee(()=>{const s=this.tensors.map(i=>K(i,e));return rs(s,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");const n=this.tensors.pop();return Ps(n.shape,e,"TensorList shape mismatch: "),K(n,e)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Ps(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Cn(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(this.maxNumElements!==-1&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);this.tensors.length=e}getItem(e,t,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(this.tensors[e]==null)throw new Error(`element at index ${e} is null.`);return Ps(this.tensors[e].shape,t,"TensorList shape mismatch: "),this.tensors[e]}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);Ps(this.elementShape,t.shape,"TensorList shape mismatch: "),Cn(t),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);return Ps(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size()),e.length===0?en([],[0].concat(this.elementShape)):ee(()=>{const s=e.map(i=>K(this.tensors[i],n));return rs(s,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);return Ps(this.elementShape,t,"TensorList shape mismatch: "),this.size()===0?en([],[0].concat(this.elementShape)):ee(()=>{const n=this.tensors.map(s=>K(s,t));return Pt(n,0)})}}function $Y(e,t,n){const s=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);const i=e.shape.slice(1);Ps(i,t,"TensorList shape mismatch: ");const o=Ei(e);return new Jh(o,t,s)}function UY(e,t,n){return new Jh([],e,t,n)}function BY(e,t,n,s){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);const i=Math.max(...t);if(s!=null&&s!==-1&&i>=s)throw new Error(`Max index must be < array size (${i} vs. ${s})`);const o=new Jh([],n,e.dtype,s),a=Ei(e,0);return t.forEach((c,h)=>{o.setItem(c,a[h])}),o}function MY(e,t,n){let s=0;const i=t.map(h=>(s+=h,s));if(s!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to
tensor.shape[0], but sum of lengths is
${s}, and tensor's shape is: ${e.shape}`);const o=s===0?0:e.size/s,a=ee(()=>{const h=[];e=K(e,[1,s,o]);for(let d=0;d<t.length;++d){const m=d===0?0:i[d-1],y=[0,m,0],b=[1,t[d],o];h[d]=K(nt(e,y,b),n)}return e.dispose(),h}),c=new Jh([],n,e.dtype,t.length);for(let h=0;h<a.length;h++)c.setItem(h,a[h]);return c}const PY=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{const s=R("thenBranch",e,t,n),i=R("elseBranch",e,t,n),o=R("cond",e,t,n),a=R("args",e,t,n),c=await o.data();return c[0]?n.functionMap[s].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap):n.functionMap[i].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{const s=R("body",e,t,n),i=R("cond",e,t,n),o=R("args",e,t,n),a=await n.functionMap[i].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap),c=o.map(m=>m.id);let h=await a[0].data();a.forEach(m=>{!m.kept&&c.indexOf(m.id)===-1&&m.dispose()});let d=o;for(;h[0];){const m=d;d=await n.functionMap[s].executeFunctionAsync(d,n.tensorArrayMap,n.tensorListMap);const y=d.map(w=>w.id);m.forEach(w=>{!w.kept&&c.indexOf(w.id)===-1&&y.indexOf(w.id)===-1&&w.dispose()});const b=await n.functionMap[i].executeFunctionAsync(d,n.tensorArrayMap,n.tensorListMap);h=await b[0].data(),b.forEach(w=>{!w.kept&&c.indexOf(w.id)===-1&&y.indexOf(w.id)===-1&&w.dispose()})}return d}case"LoopCond":{const s=R("pred",e,t,n);return[or(s)]}case"Switch":{const s=R("pred",e,t,n);let i=R("data",e,t,n);return i.kept||(i=or(i)),(await s.data())[0]?[void 0,i]:[i,void 0]}case"Merge":{const s=e.inputNames.find(i=>Jn(i,t,n)!==void 0);if(s){const i=Jn(s,t,n);return[or(i)]}return}case"Enter":{const s=R("frameName",e,t,n),i=R("tensor",e,t,n);return n.enterFrame(s),[or(i)]}case"Exit":{const s=R("tensor",e,t,n);return n.exitFrame(),[or(s)]}case"NextIteration":{const s=R("tensor",e,t,n);return n.nextIteration(),[or(s)]}case"TensorArrayV3":{const s=R("size",e,t,n),i=R("dtype",e,t,n),o=R("elementShape",e,t,n),a=R("dynamicSize",e,t,n),c=R("clearAfterRead",e,t,n),h=R("identicalElementShapes",e,t,n),d=R("name",e,t,n),m=new WY(d,i,s,o,h,a,c);return n.addTensorArray(m),[m.idTensor,Ne(1)]}case"TensorArrayWriteV3":{const s=R("tensorArrayId",e,t,n),i=R("index",e,t,n),o=R("tensor",e,t,n),a=n.getTensorArray(s.id);return a.write(i,o),[a.idTensor]}case"TensorArrayReadV3":{const s=R("tensorArrayId",e,t,n),i=R("index",e,t,n),o=n.getTensorArray(s.id);return[o.read(i)]}case"TensorArrayGatherV3":{const s=R("tensorArrayId",e,t,n),i=R("indices",e,t,n),o=R("dtype",e,t,n),a=n.getTensorArray(s.id);return[a.gather(i,o)]}case"TensorArrayScatterV3":{const s=R("tensorArrayId",e,t,n),i=R("indices",e,t,n),o=R("tensor",e,t,n),a=n.getTensorArray(s.id);return a.scatter(i,o),[a.idTensor]}case"TensorArrayConcatV3":{const s=R("tensorArrayId",e,t,n),i=n.getTensorArray(s.id),o=R("dtype",e,t,n);return[i.concat(o)]}case"TensorArraySplitV3":{const s=R("tensorArrayId",e,t,n),i=R("tensor",e,t,n),o=R("lengths",e,t,n),a=n.getTensorArray(s.id);return a.split(o,i),[a.idTensor]}case"TensorArraySizeV3":{const s=R("tensorArrayId",e,t,n),i=n.getTensorArray(s.id);return[Ne(i.size(),"int32")]}case"TensorArrayCloseV3":{const s=R("tensorArrayId",e,t,n),i=n.getTensorArray(s.id);return i.clearAndClose(),[i.idTensor]}case"TensorListSetItem":{const s=R("tensorListId",e,t,n),i=R("index",e,t,n),o=R("tensor",e,t,n),a=n.getTensorList(s.id);return a.setItem(i,o),[a.idTensor]}case"TensorListGetItem":{const s=R("tensorListId",e,t,n),i=R("index",e,t,n),o=R("elementShape",e,t,n),a=R("elementDType",e,t,n),c=n.getTensorList(s.id);return[c.getItem(i,o,a)]}case"TensorListScatterV2":case"TensorListScatter":{const s=R("indices",e,t,n),i=R("tensor",e,t,n),o=R("elementShape",e,t,n),a=R("numElements",e,t,n),c=BY(i,s,o,a);return n.addTensorList(c),[c.idTensor]}case"TensorListReserve":{const s=R("elementShape",e,t,n),i=R("elementDType",e,t,n),o=R("numElements",e,t,n),a=UY(s,i,o);return n.addTensorList(a),[a.idTensor]}case"TensorListGather":{const s=R("tensorListId",e,t,n),i=R("indices",e,t,n),o=R("elementShape",e,t,n),a=R("elementDType",e,t,n),c=n.getTensorList(s.id);return[c.gather(i,a,o)]}case"TensorListStack":{const s=R("tensorListId",e,t,n),i=R("elementShape",e,t,n),o=R("elementDType",e,t,n),a=R("numElements",e,t,n),c=n.getTensorList(s.id);return[c.stack(i,o,a)]}case"TensorListFromTensor":{const s=R("tensor",e,t,n),i=R("elementShape",e,t,n),o=R("elementDType",e,t,n),a=$Y(s,i,o);return n.addTensorList(a),[a.idTensor]}case"TensorListConcat":{const s=R("tensorListId",e,t,n),i=n.getTensorList(s.id),o=R("dtype",e,t,n),a=R("elementShape",e,t,n);return[i.concat(o,a)]}case"TensorListPushBack":{const s=R("tensorListId",e,t,n),i=R("tensor",e,t,n),o=n.getTensorList(s.id);return o.pushBack(i),[o.idTensor]}case"TensorListPopBack":{const s=R("tensorListId",e,t,n),i=R("elementShape",e,t,n),o=R("elementDType",e,t,n),a=n.getTensorList(s.id);return[a.popBack(i,o)]}case"TensorListSplit":{const s=R("tensor",e,t,n),i=R("elementShape",e,t,n),o=R("lengths",e,t,n),a=MY(s,o,i);return n.addTensorList(a),[a.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},jQ="control";function DN(e,t,n){const[s,i]=R("fusedOps",e,t,n),o=s==="biasadd",a=i==="prelu",c=s==="fusedbatchnorm",h=R("numArgs",e,t,n);if(o){if(a&&h!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!a&&h!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(c)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported.");const d=R("strides",e,t,n),m=em(e,t,n),y=R("dataFormat",e,t,n).toUpperCase(),b=R("dilations",e,t,n),[w,L]=R("args",e,t,n);return{stride:d,pad:m,dataFormat:y,dilations:b,biasArg:w,preluArg:L,activationFunc:i}}const zY=(e,t,n)=>{switch(e.op){case"Conv1D":{const s=R("stride",e,t,n),i=R("pad",e,t,n),o=R("dataFormat",e,t,n).toUpperCase(),a=R("dilation",e,t,n);return[$d(R("x",e,t,n),R("filter",e,t,n),s,i,o,a)]}case"Conv2D":{const s=R("strides",e,t,n),i=em(e,t,n),o=R("dataFormat",e,t,n).toUpperCase(),a=R("dilations",e,t,n);return[Xi(R("x",e,t,n),R("filter",e,t,n),[s[1],s[2]],i,o,[a[1],a[2]])]}case"_FusedConv2D":{const{stride:s,pad:i,dataFormat:o,dilations:a,biasArg:c,preluArg:h,activationFunc:d}=DN(e,t,n);return[ew({x:R("x",e,t,n),filter:R("filter",e,t,n),strides:[s[1],s[2]],pad:i,dataFormat:o,dilations:[a[1],a[2]],bias:c,activation:d,preluActivationWeights:h})]}case"FusedDepthwiseConv2dNative":{const{stride:s,pad:i,dataFormat:o,dilations:a,biasArg:c,preluArg:h,activationFunc:d}=DN(e,t,n);return[AA({x:R("x",e,t,n),filter:R("filter",e,t,n),strides:[s[1],s[2]],pad:i,dataFormat:o,dilations:[a[1],a[2]],bias:c,activation:d,preluActivationWeights:h})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const s=R("outputShape",e,t,n),i=R("strides",e,t,n),o=em(e,t,n);return[Ud(R("x",e,t,n),R("filter",e,t,n),s,[i[1],i[2]],o)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const s=R("strides",e,t,n),i=em(e,t,n),o=R("dilations",e,t,n),a=R("dataFormat",e,t,n).toUpperCase();return[Co(R("input",e,t,n),R("filter",e,t,n),[s[1],s[2]],i,a,[o[1],o[2]])]}case"Conv3D":{const s=R("strides",e,t,n),i=R("pad",e,t,n),o=R("dataFormat",e,t,n).toUpperCase(),a=R("dilations",e,t,n);return[vb(R("x",e,t,n),R("filter",e,t,n),[s[1],s[2],s[3]],i,o,[a[1],a[2],a[3]])]}case"AvgPool":{const s=R("strides",e,t,n),i=R("pad",e,t,n),o=R("kernelSize",e,t,n);return[nh(R("x",e,t,n),[o[1],o[2]],[s[1],s[2]],i)]}case"MaxPool":{const s=R("strides",e,t,n),i=R("pad",e,t,n),o=R("kernelSize",e,t,n);return[hh(R("x",e,t,n),[o[1],o[2]],[s[1],s[2]],i)]}case"MaxPoolWithArgmax":{const s=R("strides",e,t,n),i=R("pad",e,t,n),o=R("kernelSize",e,t,n),a=R("includeBatchInIndex",e,t,n),{result:c,indexes:h}=JT(R("x",e,t,n),[o[1],o[2]],[s[1],s[2]],i,a);return[c,h]}case"AvgPool3D":{const s=R("strides",e,t,n),i=R("pad",e,t,n),o=R("kernelSize",e,t,n);return[Ib(R("x",e,t,n),[o[1],o[2],o[3]],[s[1],s[2],s[3]],i)]}case"MaxPool3D":{const s=R("strides",e,t,n),i=R("pad",e,t,n),o=R("kernelSize",e,t,n);return[Wb(R("x",e,t,n),[o[1],o[2],o[3]],[s[1],s[2],s[3]],i)]}case"Dilation2D":{const s=R("strides",e,t,n),i=R("pad",e,t,n),o=R("dilations",e,t,n),a=s[1],c=s[2],h=o[1],d=o[2];return[Cb(R("x",e,t,n),R("filter",e,t,n),[a,c],i,[h,d],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},KQ="convolution";const GY=(e,t,n)=>{switch(e.op){case"Fill":{const s=R("shape",e,t,n),i=R("dtype",e,t,n),o=R("value",e,t,n);return[oh(s,o,i)]}case"LinSpace":{const s=R("start",e,t,n),i=R("stop",e,t,n),o=R("num",e,t,n);return[jT(s,i,o)]}case"Multinomial":{const s=R("logits",e,t,n),i=R("numSamples",e,t,n),o=R("seed",e,t,n);return[ZT(s,i,o)]}case"OneHot":{const s=R("indices",e,t,n),i=R("depth",e,t,n),o=R("onValue",e,t,n),a=R("offValue",e,t,n);return[To(s,i,o,a)]}case"Ones":return[ni(R("shape",e,t,n),R("dtype",e,t,n))];case"OnesLike":return[En(R("x",e,t,n))];case"RandomUniform":return[_o(R("shape",e,t,n),R("minval",e,t,n),R("maxval",e,t,n),R("dtype",e,t,n))];case"Range":{const s=R("start",e,t,n),i=R("stop",e,t,n),o=R("step",e,t,n);return[ph(s,i,o,R("dtype",e,t,n))]}case"TruncatedNormal":{const s=R("shape",e,t,n),i=R("mean",e,t,n),o=R("stdDev",e,t,n),a=R("seed",e,t,n);return[bh(s,i,o,R("dtype",e,t,n),a)]}case"Zeros":return[ct(R("shape",e,t,n),R("dtype",e,t,n))];case"ZerosLike":return[Qe(R("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},XQ="creation";function cS(e,t,n){const s=R("boxes",e,t,n),i=R("scores",e,t,n),o=R("maxOutputSize",e,t,n),a=R("iouThreshold",e,t,n),c=R("scoreThreshold",e,t,n),h=R("softNmsSigma",e,t,n);return{boxes:s,scores:i,maxOutputSize:o,iouThreshold:a,scoreThreshold:c,softNmsSigma:h}}const VY=async(e,t,n)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:s,scores:i,maxOutputSize:o,iouThreshold:a,scoreThreshold:c,softNmsSigma:h}=cS(e,t,n),d=await $r.nonMaxSuppressionWithScoreAsync(s,i,o,a,c,h);return[d.selectedIndices,d.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:s,scores:i,maxOutputSize:o,iouThreshold:a,scoreThreshold:c}=cS(e,t,n),h=R("padToMaxOutputSize",e,t,n),d=await $r.nonMaxSuppressionPaddedAsync(s,i,o,a,c,h);return[d.selectedIndices,d.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:s,scores:i,maxOutputSize:o,iouThreshold:a,scoreThreshold:c}=cS(e,t,n);return[await $r.nonMaxSuppressionAsync(s,i,o,a,c)]}case"Where":{const s=ve(R("condition",e,t,n),"bool"),i=[await Xb(s)];return s.dispose(),i}case"ListDiff":return eA(R("x",e,t,n),R("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}},JQ="dynamic";const YY=(e,t,n)=>{switch(e.op){case"TopKV2":{const s=R("x",e,t,n),i=R("k",e,t,n),o=R("sorted",e,t,n),a=jb(s,i,o);return[a.values,a.indices]}case"Unique":{const s=R("x",e,t,n),i=sp(s);return[i.values,i.indices]}case"UniqueV2":{const s=R("x",e,t,n),i=R("axis",e,t,n),o=sp(s,i);return[o.values,o.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},ZQ="evaluation";const HY=(e,t,n)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const s=R("default",e,t,n);return[Jn(e.name,t,n)||s];case"Placeholder":return[Jn(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{const d=R("x",e,t,n);return[or(d)]}case"IdentityN":return R("x",e,t,n).map(d=>or(d));case"Snapshot":const i=R("x",e,t,n);return[or(i)];case"Shape":return[ss(R("x",e,t,n).shape,"int32")];case"ShapeN":return R("x",e,t,n).map(d=>ss(d.shape));case"Size":return[Ne(R("x",e,t,n).size,"int32")];case"Rank":return[Ne(R("x",e,t,n).rank,"int32")];case"NoOp":return[Ne(1)];case"Print":const o=R("x",e,t,n),a=R("data",e,t,n),c=R("message",e,t,n),h=R("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(c);for(let d=0;d<a.length;d++)console.log(Array.prototype.slice.call(a[d].dataSync()).slice(0,h));return[o];default:throw TypeError(`Node type ${e.op} is not implemented`)}},QQ="graph";const qY=(e,t,n)=>{switch(e.op){case"ResizeBilinear":{const s=R("images",e,t,n),i=R("size",e,t,n),o=R("alignCorners",e,t,n);return[$r.resizeBilinear(s,[i[0],i[1]],o)]}case"ResizeNearestNeighbor":{const s=R("images",e,t,n),i=R("size",e,t,n),o=R("alignCorners",e,t,n);return[$r.resizeNearestNeighbor(s,[i[0],i[1]],o)]}case"CropAndResize":{const s=R("image",e,t,n),i=R("boxes",e,t,n),o=R("boxInd",e,t,n),a=R("cropSize",e,t,n),c=R("method",e,t,n),h=R("extrapolationValue",e,t,n);return[$r.cropAndResize(s,i,o,a,c,h)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},eee="image";const jY=(e,t,n)=>{switch(e.op){case"Equal":return[ti(R("a",e,t,n),R("b",e,t,n))];case"NotEqual":return[Fr(R("a",e,t,n),R("b",e,t,n))];case"Greater":return[Ss(R("a",e,t,n),R("b",e,t,n))];case"GreaterEqual":return[Ji(R("a",e,t,n),R("b",e,t,n))];case"Less":return[ch(R("a",e,t,n),R("b",e,t,n))];case"LessEqual":return[kr(R("a",e,t,n),R("b",e,t,n))];case"LogicalAnd":return[$s(R("a",e,t,n),R("b",e,t,n))];case"LogicalNot":return[lh(R("a",e,t,n))];case"LogicalOr":return[Hd(R("a",e,t,n),R("b",e,t,n))];case"Select":case"SelectV2":return[_n(R("condition",e,t,n),R("a",e,t,n),R("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},tee="logical";const KY=(e,t,n)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[at(R("a",e,t,n),R("b",e,t,n),R("transposeA",e,t,n),R("transposeB",e,t,n))];case"Transpose":return[Me(R("x",e,t,n),R("perm",e,t,n))];case"_FusedMatMul":const[s,i]=R("fusedOps",e,t,n),o=s==="biasadd",a=i==="prelu",c=R("numArgs",e,t,n);if(o){if(a&&c!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!a&&c!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}const[h,d]=R("args",e,t,n);return[hp({a:R("a",e,t,n),b:R("b",e,t,n),transposeA:R("transposeA",e,t,n),transposeB:R("transposeB",e,t,n),bias:h,activation:i,preluActivationWeights:d})];default:throw TypeError(`Node type ${e.op} is not implemented`)}},nee="matrices";const XY=(e,t,n)=>{switch(e.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[No(R("x",e,t,n),R("mean",e,t,n),R("variance",e,t,n),R("offset",e,t,n),R("scale",e,t,n),R("epsilon",e,t,n))];case"FusedBatchNormV3":return[No(R("x",e,t,n),R("mean",e,t,n),R("variance",e,t,n),R("offset",e,t,n),R("scale",e,t,n),R("epsilon",e,t,n))];case"LRN":return[kb(R("x",e,t,n),R("radius",e,t,n),R("bias",e,t,n),R("alpha",e,t,n),R("beta",e,t,n))];case"Softmax":return[Wo(R("x",e,t,n))];case"LogSoftmax":return[Yd(R("x",e,t,n))];case"SparseToDense":return[Jb(R("sparseIndices",e,t,n),R("outputShape",e,t,n),R("sparseValues",e,t,n),R("defaultValue",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},see="normalization";const JY=(e,t,n)=>{switch(e.op){case"Max":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[jn(R("x",e,t,n),s,i)]}case"Mean":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[Gt(R("x",e,t,n),s,i)]}case"Min":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[Ba(R("x",e,t,n),s,i)]}case"Sum":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[Ue(R("x",e,t,n),s,i)]}case"All":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[kd(R("x",e,t,n),s,i)]}case"Any":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[Jl(R("x",e,t,n),s,i)]}case"ArgMax":{const s=R("axis",e,t,n);return[Zl(R("x",e,t,n),s)]}case"ArgMin":{const s=R("axis",e,t,n);return[mb(R("x",e,t,n),s)]}case"Prod":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[Kd(R("x",e,t,n),s,i)]}case"Cumsum":{const s=R("axis",e,t,n),i=R("exclusive",e,t,n),o=R("reverse",e,t,n);return[Md(R("x",e,t,n),s,i,o)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},iee="reduction";const ZY=(e,t,n)=>{switch(e.op){case"ConcatV2":case"Concat":{const s=R("n",e,t,n),i=R("axis",e,t,n);let o=R("tensors",e,t,n);return o=o.slice(0,s),[Pt(o,i)]}case"GatherV2":case"Gather":{const s=R("axis",e,t,n),i=R("x",e,t,n),o=R("indices",e,t,n);return[Wa(i,ve(o,"int32"),s)]}case"ReverseV2":case"Reverse":{const s=R("axis",e,t,n),i=R("x",e,t,n);return[Is(i,s)]}case"Slice":{const s=R("begin",e,t,n),i=R("size",e,t,n);return[nt(R("x",e,t,n),s,i)]}case"StridedSlice":{const s=R("begin",e,t,n),i=R("end",e,t,n),o=R("strides",e,t,n),a=R("beginMask",e,t,n),c=R("endMask",e,t,n),h=R("ellipsisMask",e,t,n),d=R("newAxisMask",e,t,n),m=R("shrinkAxisMask",e,t,n),y=R("x",e,t,n);return[Hb(y,s,i,o,a,c,h,d,m)]}case"Pack":return ee(()=>{const s=R("axis",e,t,n),i=R("tensors",e,t,n),o=i[0].shape,a=_r(i[0]).shape,c=i.map(h=>{const d=ot(h.shape,o);if(!d&&!ot(_r(h).shape,a))throw new Error("the input tensors shape does not match");return d?h:K(h,o)});return[rs(c,s)]});case"Unpack":{const s=R("axis",e,t,n),i=R("tensor",e,t,n);return Ei(i,s)}case"Tile":{const s=R("reps",e,t,n);return[Dr(R("x",e,t,n),s)]}case"Split":case"SplitV":{const s=R("axis",e,t,n),i=R("numOrSizeSplits",e,t,n),o=R("x",e,t,n);return is(o,i,s)}case"ScatterNd":{const s=R("indices",e,t,n),i=R("values",e,t,n),o=R("shape",e,t,n);return[wA(s,i,o)]}case"GatherNd":{const s=R("x",e,t,n),i=R("indices",e,t,n);return[LA(s,i)]}case"SparseToDense":{const s=R("sparseIndices",e,t,n),i=R("outputShape",e,t,n),o=R("sparseValues",e,t,n),a=R("defaultValue",e,t,n);return[Jb(s,o,i,o.dtype===a.dtype?a:ve(a,o.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},ree="slice_join";const QY=(e,t,n)=>{switch(e.op){case"FFT":return[fh(R("x",e,t,n))];case"IFFT":return[za(R("x",e,t,n))];case"RFFT":return[gh(R("x",e,t,n))];case"IRFFT":return[np(R("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},oee="spectral";const eH=(e,t,n)=>{switch(e.op){case"Cast":return[ve(R("x",e,t,n),R("dtype",e,t,n))];case"ExpandDims":{const s=R("axis",e,t,n);return[qn(R("x",e,t,n),s)]}case"Squeeze":{const s=R("axis",e,t,n);return[_r(R("x",e,t,n),s)]}case"Reshape":return[K(R("x",e,t,n),R("shape",e,t,n))];case"PadV2":case"Pad":return[Ri(R("x",e,t,n),R("padding",e,t,n),R("constantValue",e,t,n))];case"SpaceToBatchND":{const s=R("blockShape",e,t,n),i=R("paddings",e,t,n);return[uh(R("x",e,t,n),s,i)]}case"BatchToSpaceND":{const s=R("blockShape",e,t,n),i=R("crops",e,t,n);return[sh(R("x",e,t,n),s,i)]}case"DepthToSpace":{const s=R("blockSize",e,t,n),i=R("dataFormat",e,t,n).toUpperCase();return[Nb(R("x",e,t,n),s,i)]}case"BroadcastTo":return[ih(R("x",e,t,n),R("shape",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},aee="transformation";function kN(e,t,n){const s=((i,o,a)=>{switch(i.category){case"arithmetic":return ee(()=>kY(i,o,a));case"basic_math":return ee(()=>FY(i,o,a));case"control":return PY(i,o,a);case"convolution":return ee(()=>zY(i,o,a));case"creation":return ee(()=>GY(i,o,a));case"dynamic":return VY(i,o,a);case"evaluation":return ee(()=>YY(i,o,a));case"image":return ee(()=>qY(i,o,a));case"graph":return ee(()=>HY(i,o,a));case"logical":return ee(()=>jY(i,o,a));case"matrices":return ee(()=>KY(i,o,a));case"normalization":return ee(()=>XY(i,o,a));case"reduction":return ee(()=>JY(i,o,a));case"slice_join":return ee(()=>ZY(i,o,a));case"spectral":return ee(()=>QY(i,o,a));case"transformation":return ee(()=>eH(i,o,a));case"custom":const c=NN(i.op);if(c&&c.customExecutor)return c.customExecutor(new DY(i,o,a));throw TypeError(`Custom op ${i.op} is not registered.`);default:throw TypeError(`Unknown op '${i.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(e,t,n);return s instanceof Promise?s.then(i=>[].concat(i)):[].concat(s)}class FN{constructor(e={},t={},n={},s={}){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=s,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){const e=[];for(let t=0;t<this.contexts.length-1;t++){const n=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(n))}e.push(""),this._currentContextIds=e}contextIdforContexts(e){return e?e.map(t=>t.id===0&&t.iterationId===0?"":`${t.frameName}-${t.iterationId}`).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(this.contexts&&this.contexts.length>1)this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift();else throw new Error("Cannot exit frame, the context is empty")}nextIteration(){if(this.contexts&&this.contexts.length>0){this.contexts=this.contexts.slice(),this.lastId++;const e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}else throw new Error("Cannot increase frame iteration, the context is empty")}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(const t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(const t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}}function _N(e,t,n,s){const i=new Set,o=[];let a=null,c=null;const h=new Set,d=Object.keys(e).map(b=>as(b)[0]);let m=[];s!=null&&(m=s.map(b=>as(b.name)[0]));const y=[...t];for(;y.length>0;){const b=y.pop();if((WN(b)||iH(b))&&(a==null&&(a=b,c=a.children.map(w=>w.name).filter(w=>i.has(w)))),i.add(b.name),n[b.name]!=null)continue;if(d.indexOf(b.name)!==-1)continue;if(m.indexOf(b.name)!==-1)continue;if(b.inputs.length===0){o.push(b.name);continue}b.inputs.forEach(w=>{if(h.has(w.name))return;h.add(w.name),y.push(w)})}return{inputs:e,outputs:t,usedNodes:i,missingInputs:o,dynamicNode:a,syncInputs:c}}function tH(e,t,n){const{usedNodes:s,inputs:i}=n,o=[],a=Object.keys(i).map(m=>as(m)[0]).map(m=>e.nodes[m]),c=e.initNodes;a.forEach(m=>{s.has(m.name)&&o.push(m)}),e.weights.forEach(m=>{s.has(m.name)&&o.push(m)}),c!=null&&c.forEach(m=>{s.has(m.name)&&o.push(m)});const h=new Set,d=[];for(;o.length>0;){const m=o.pop();h.add(m.name),t[m.name]||d.push(m),m.children.forEach(y=>{!h.has(y.name)&&s.has(y.name)&&y.inputs.every(b=>h.has(b.name))&&o.push(y)})}return d}const nH=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],sH=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"];function WN(e){return nH.indexOf(e.op)>=0}function iH(e){return sH.indexOf(e.op)>=0}class lS{constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this._functions={},this._functionExecutorMap={},this._outputs=e.outputs,this._inputs=e.inputs,this._initNodes=e.initNodes,this._signature=e.signature,this._functions=e.functions,e.functions!=null&&Object.keys(e.functions).forEach(n=>{this._functionExecutorMap[n]=new lS(e.functions[n],this)})}get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){const t=Object.keys(e).map(n=>e[n].map(s=>s.id));this._weightIds=[].concat(...t),this._weightMap=e}get inputs(){return this._inputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(e=>e.signatureKey||e.name)}get outputNodes(){return this._outputs.map(e=>{const t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t})}get functions(){return Object.keys(this._functions).reduce((e,t)=>(e[t]=this._functions[t].signature,e),{})}getCompilationKey(e,t){const n=e.map(i=>i.name).sort(),s=t.map(i=>i.name).sort();return n.join(this.SEPERATOR)+"--"+s.join(this.SEPERATOR)}compile(e,t){const n=_N(e,t,this.weightMap,this._initNodes),{missingInputs:s,dynamicNode:i,syncInputs:o}=n;if(i!=null)throw new Error(`This execution contains the node '${i.name}', which has the dynamic op '${i.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${o}]`);if(s.length>0){const a=t.map(h=>h.name),c=Object.keys(e);throw new Error(`Cannot compute the outputs [${a}] from the provided inputs [${c}]. Missing the following inputs: [${s}]`)}return tH(this.graph,this.weightMap,n)}execute(e,t){e=this.mapInputs(e);const n=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);const s=n.map(m=>this.graph.nodes[as(m)[0]]),i=t.map(m=>as(m)[0]);let o=i.map(m=>this.graph.nodes[m]);o.length===0&&(o=this._outputs);const a=this.getCompilationKey(s,o);let c=this.compiledMap.get(a);c==null&&(c=this.compile(e,o),this.compiledMap.set(a,c));const h={},d={};return ee(()=>{const m=new FN(this.weightMap,h,d,this.functionExecutorMap),y=Object.assign({},this.weightMap);Object.keys(e).forEach(L=>{const[T,A]=as(L),N=[];N[A]=e[L],y[T]=N});const b=this.getFrozenTensorIds(y),w={};for(let L=0;L<c.length;L++){const T=c[L];if(!y[T.name]){const A=kN(T,y,m);if(A instanceof Promise)throw new Error(`The execution of the op '${T.op}' returned a promise. Please use model.executeAsync() instead.`);y[T.name]=A,this.checkTensorForDisposal(T.name,T,y,m,b,i,w)}}return this.parent==null&&m.dispose(b),t.map(L=>Jn(L,y,m))})}getFrozenTensorIds(e){const t=[].concat.apply([],Object.keys(e).map(n=>e[n]).map(n=>n.map(s=>s.id)));return new Set(t)}checkTensorForDisposal(e,t,n,s,i,o,a){if(t.category==="control"||o.indexOf(e)!==-1)return;n[e].forEach(c=>{c!=null&&(a[c.id]=(a[c.id]||0)+t.children.length)}),t.inputs.forEach(c=>{if(c.category!=="control"){const h=ZV(c.name,n,s);h!=null&&h.forEach(d=>{if(d&&!i.has(d.id)){const m=a[d.id];m===1?(d.dispose(),delete a[d.id]):m!=null&&a[d.id]--}})}})}async executeAsync(e,t){return this._executeAsync(e,t)}async _executeAsync(e,t,n=!1,s={},i={}){n||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));const o=new FN(this.weightMap,s,i,this.functionExecutorMap),a=await this.executeWithControlFlow(e,o,t,n),c=t.map(y=>Jn(y,a,o)),h=c.map(y=>y.id),d=Object.keys(e).map(y=>e[y].id),m=new Set([...h,...d,...this.weightIds]);return Object.keys(a).forEach(y=>{const b=a[y];b.forEach(w=>{w&&!w.isDisposed&&!m.has(w.id)&&w.dispose()})}),this.parent==null&&o.dispose(m),c}async executeFunctionAsync(e,t,n){const s=e.reduce((i,o,a)=>(i[this.inputs[a].name]=o,i),{});return this._executeAsync(s,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,s){const i=Object.keys(e),o=i.map(E=>this.graph.nodes[as(E)[0]]),a=n.map(E=>as(E)[0]),c=a.map(E=>this.graph.nodes[E]),{usedNodes:h,missingInputs:d,dynamicNode:m,syncInputs:y}=_N(e,c,this.weightMap),b=[...o,...this.graph.weights].map(E=>({node:E,contexts:t.currentContext})),w=Object.assign({},this.weightMap);Object.keys(e).forEach(E=>{const[D,F]=as(E),_=[];_[F]=e[E],w[D]=_});const L={},T=this.getFrozenTensorIds(w),A={};for(;b.length>0;){const E=this.processStack(o,b,t,w,A,T,a,L,h);await Promise.all(E)}m==null&&!s&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");const N=c.filter(E=>!WN(E)&&!Jn(E.name,w,t)).map(E=>E.name);if(N.length>0){let E="";throw m!=null&&(E=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${y}]`),new Error(`Cannot compute the outputs [${N}] from the provided inputs [${i}]. Consider providing the following inputs: [${d}]. ${E}`)}return w}processStack(e,t,n,s,i,o,a,c,h){const d=[];for(;t.length>0;){const m=t.pop();n.currentContext=m.contexts;let y="";if(m.node.op==="Enter"&&R("isConstant",m.node,s,n)&&([y]=rr(m.node.name,n)),e.indexOf(m.node)===-1){const b=kN(m.node,s,n);y||([y]=rr(m.node.name,n));const w=n.currentContext;b instanceof Promise?d.push(b.then(L=>(s[y]=L,n.currentContext=w,this.checkTensorForDisposal(y,m.node,s,n,o,a,c),this.processChildNodes(m.node,t,n,s,i,h),L))):(s[y]=b,this.checkTensorForDisposal(y,m.node,s,n,o,a,c),this.processChildNodes(m.node,t,n,s,i,h))}else this.processChildNodes(m.node,t,n,s,i,h)}return d}processChildNodes(e,t,n,s,i,o){e.children.forEach(a=>{const[c]=rr(a.name,n);if(i[c]||!o.has(a.name))return;a.op==="Merge"?a.inputNames.some(h=>!!Jn(h,s,n))&&(i[c]=!0,t.push({contexts:n.currentContext,node:a})):a.inputNames.every(h=>!!Jn(h,s,n))&&(i[c]=!0,t.push({contexts:n.currentContext,node:a}))})}dispose(){Object.keys(this.weightMap).forEach(e=>this.weightMap[e].forEach(t=>t.dispose()))}checkInputShapeAndType(e){Object.keys(e).forEach(t=>{const n=e[t],[s]=as(t),i=this.graph.nodes[s];if(i.attrParams.shape&&i.attrParams.shape.value){const o=i.attrParams.shape.value,a=o.length===n.shape.length&&n.shape.every((c,h)=>o[h]===-1||o[h]===c);k(a,()=>`The shape of dict['${i.name}'] provided in model.execute(dict) must be [${o}], but was [${n.shape}]`)}i.attrParams.dtype&&i.attrParams.dtype.value&&k(n.dtype===i.attrParams.dtype.value,()=>`The dtype of dict['${i.name}'] provided in model.execute(dict) must be ${i.attrParams.dtype.value}, but was ${n.dtype}`)})}mapInputs(e){const t={};for(const n in e)if(this._signature!=null&&this._signature.inputs!=null&&this._signature.inputs[n]!=null){const s=this._signature.inputs[n];t[s.name]=e[n]}else t[n]=e[n];return t}checkInputs(e){const t=Object.keys(e).filter(n=>{const[s]=as(n);return this.graph.nodes[s]==null});if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map(t=>{if(this._signature!=null&&this._signature.outputs!=null&&this._signature.outputs[t]!=null){const n=this._signature.outputs[t];return n.name}return t},{})}checkOutputs(e){e.forEach(t=>{const[n]=as(t);if(!this.graph.nodes[n])throw new Error(`The output '${t}' is not found in the graph`)})}}const rH="?tfjs-format=file",oH="model.json";class $N{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={})}get modelVersion(){return this.version}get inputNodes(){return this.executor.inputNodes}get outputNodes(){return this.executor.outputNodes}get inputs(){return this.executor.inputs}get outputs(){return this.executor.outputs}get weights(){return this.executor.weightMap}findIOHandler(){const e=this.modelUrl;if(e.load!=null)this.handler=e;else if(this.loadOptions.requestInit!=null)this.handler=Ad(e,this.loadOptions);else{const t=jy(e,this.loadOptions);if(t.length===0)t.push(Ad(e,this.loadOptions));else if(t.length>1)throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);this.handler=t[0]}}async load(){if(this.findIOHandler(),this.handler.load==null)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const e=await this.handler.load();return this.loadSync(e)}loadSync(e){this.artifacts=e;const t=this.artifacts.modelTopology;let n={};this.artifacts.userDefinedMetadata!=null&&(n=this.artifacts.userDefinedMetadata.signature),this.version=`${t.versions.producer}.${t.versions.minConsumer}`;const s=Sd(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new lS(CN.Instance.transformGraph(t,n)),this.executor.weightMap=this.convertTensorMapToTensorsMap(s),e.modelInitializer!=null){const i=CN.Instance.transformGraph(e.modelInitializer);this.initializer=new lS(i),this.initializer.weightMap=this.executor.weightMap,this.initializer.execute({},[])}return!0}async save(e,t){if(typeof e=="string"){const n=qy(e);if(n.length===0)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(n.length>1)throw new Error(`Found more than one (${n.length}) save handlers for URL '${e}'`);e=n[0]}if(e.save==null)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return e.save(this.artifacts)}predict(e,t){return this.execute(e,this.outputNodes)}normalizeInputs(e){if(!(e instanceof Q)&&!Array.isArray(e))return e;if(e=Array.isArray(e)?e:[e],e.length!==this.inputNodes.length)throw new Error(`Input tensor count mismatch,the graph model has ${this.inputNodes.length} placeholders, while there are ${e.length} input tensors.`);return this.inputNodes.reduce((t,n,s)=>(t[n]=e[s],t),{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}execute(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=this.executor.execute(e,t);return n.length>1?n:n[0]}async executeAsync(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=await this.executor.executeAsync(e,t);return n.length>1?n:n[0]}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,n)=>(t[n]=[e[n]],t),{})}dispose(){this.executor.dispose(),this.initializer&&this.initializer.dispose()}}async function aH(e,t={}){if(e==null)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");t==null&&(t={}),t.fromTFHub&&(e.load==null&&(e.endsWith("/")||(e=e+"/"),e=`${e}${oH}${rH}`));const n=new $N(e,t);return await n.load(),n}const UN="2.6.0";function cH(e,t){return tm(e,t)}function tm(e,t,n=new Map,s=new Set){if(e==null)return null;if(s.has(e))throw new Error("Circular references are not supported.");if(n.has(e))return n.get(e);const i=t(e);if(i.recurse&&i.value!==null)throw new Error("A deep map function may not return both a value and recurse=true.");if(i.recurse)if(sc(e)){const o=Array.isArray(e)?[]:{};s.add(e);for(const a in e){const c=e[a],h=tm(c,t,n,s);o[a]=h}return s.delete(e),o}else throw new Error(`Can't recurse into non-iterable type: ${e}`);else return n.set(e,i.value),i.value}function lH(e,t=MN){return BN(e,t)}function BN(e,t,n=new Set){const s=e[0];if(n.has(s))throw new Error("Circular references are not supported.");const i=t(e);if(i.recurse&&i.value!==null)throw new Error("A deep zip function may not return both a value and recurse=true.");if(i.recurse)if(sc(s)){const o=Array.isArray(s)?[]:{};n.add(s);for(const a in s){const c=e.map(d=>d[a]),h=BN(c,t,n);o[a]=h}return n.delete(s),o}else throw new Error(`Can't recurse into non-iterable type: ${s}`);else return i.value}function MN(e){return e===null?null:sc(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function PN(e,t){const n=new Map;tm(e,t,n);for(const i of Array.from(n.keys())){const o=n.get(i);if(o instanceof Promise){const a=await o;n.set(i,a)}}const s=tm(e,t,n);return s}function sc(e){return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof Q))}function hH(e){return e==null||uH(e)||Array.isArray(e)||typeof e=="object"&&e instanceof Q||wn(e)}function uH(e){return e===null||typeof e!="object"&&typeof e!="function"}function dH(e){return cH(e,pH)}function pH(e){return e instanceof Q?{value:e.clone(),recurse:!1}:sc(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}class zN{constructor(e){if(this.capacity=e,this.begin=0,this.end=0,e==null)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(e<1)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=new Array(e),this.doubledCapacity=2*e}wrap(e){for(;e<0;)e+=this.doubledCapacity;return e%this.doubledCapacity}get(e){if(e<0)throw new RangeError("Can't get item at a negative index.");return this.data[e%this.capacity]}set(e,t){if(e<0)throw new RangeError("Can't set item at a negative index.");this.data[e%this.capacity]=t}length(){let e=this.end-this.begin;return e<0&&(e=this.doubledCapacity+e),e}isFull(){return this.length()===this.capacity}isEmpty(){return this.length()===0}push(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,e),this.end=this.wrap(this.end+1)}pushAll(e){for(const t of e)this.push(t)}pop(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);const e=this.get(this.end);return this.set(this.end,void 0),e}unshift(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,e)}shift(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");const e=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),e}shuffleExcise(e){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");const t=this.wrap(this.begin+e),n=this.get(t);return this.set(t,this.pop()),n}}class hS extends zN{constructor(){super(hS.INITIAL_CAPACITY)}isFull(){return!1}push(e){super.isFull()&&this.expand(),super.push(e)}unshift(e){super.isFull()&&this.expand(),super.unshift(e)}expand(){const e=this.capacity*2,t=new Array(e),n=this.length();for(let s=0;s<n;s++)t[s]=this.get(this.wrap(this.begin+s));this.data=t,this.capacity=e,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=n}}hS.INITIAL_CAPACITY=32;function GN(e){return new fH(e)}function cee(e){let t=e;return Zh(()=>({value:t++,done:!1}))}function Zh(e){return new gH(e)}function VN(e,t){return new HN(e,t)}function lee(e,t,n){return VN(Zh(e).take(t),n)}function mH(e,t=Hr.FAIL){return new AH(e,t)}class fn{async toArray(){const e=[];let t=await this.next();for(;!t.done;)e.push(t.value),t=await this.next();return e}async toArrayForTest(){const e=this.prefetch(100),t=[];let n=await e.next();for(;!n.done;)t.push(n.value),n=await e.next();return t}async resolveFully(){let e=await this.next();for(;!e.done;)e=await this.next()}async resolveWhile(e){let t=await this.next(),n=e(t.value);for(;!t.done&&n;)t=await this.next(),n=e(t.value)}handleErrors(e){return new xH(this,e)}filter(e){return new SH(this,e)}map(e){return new IH(this,e)}mapAsync(e){return new YN(this,e)}serialMapAsync(e){return new YN(this,e).serial()}flatmap(e){return new TH(this,e)}async forEachAsync(e){return this.map(e).resolveFully()}async serialForEach(e){return this.serialMapAsync(e).resolveWhile(t=>t===!0)}rowMajorBatch(e,t=!0){return new LH(this,e,t)}columnMajorBatch(e,t=!0,n=MN){const s=this.rowMajorBatch(e,t);return s.map(i=>lH(i,n))}concatenate(e,t){return new HN(GN([this,e]),t)}take(e){return e<0||e==null?this:new wH(this,e)}skip(e){return e<0||e==null?this:new bH(this,e)}prefetch(e){return new qN(this,e)}shuffle(e,t){return new vH(this,e,t)}serial(){return new yH(this)}}class fH extends fn{constructor(e){super();this.items=e,this.trav=0}summary(){return`Array of ${this.items.length} items`}async next(){if(this.trav>=this.items.length)return{value:null,done:!0};const e=this.items[this.trav];return this.trav++,{value:dH(e),done:!1}}}class gH extends fn{constructor(e){super();this.nextFn=e}summary(){return"Function call"}async next(){try{return this.nextFn()}catch(e){throw e.message=`Error thrown while iterating through a dataset: ${e.message}`,e}}}class yH extends fn{constructor(e){super();this.upstream=e,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Serial`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){return this.upstream.next()}}class bH extends fn{constructor(e,t){super();this.upstream=e,this.maxCount=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Skip`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.count++<this.maxCount;){const e=await this.upstream.next();if(e.done)return e;He(e.value)}return this.upstream.next()}}class wH extends fn{constructor(e,t){super();this.upstream=e,this.maxCount=t,this.count=0}summary(){return`${this.upstream.summary()} -> Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}}class LH extends fn{constructor(e,t,n=!0){super();this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=n,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> RowMajorBatch`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){const e=[];for(;e.length<this.batchSize;){const t=await this.upstream.next();if(t.done)return this.enableSmallLastBatch&&e.length>0?{value:e,done:!1}:{value:null,done:!0};e.push(t.value)}return{value:e,done:!1}}}class SH extends fn{constructor(e,t){super();this.upstream=e,this.predicate=t,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Filter`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;){const e=await this.upstream.next();if(e.done||this.predicate(e.value))return e;He(e.value)}}}class IH extends fn{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Map`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=ji(e.value),n=this.transform(e.value),s=ji(n);for(const i of t)wd(i,s)||i.dispose();return{value:n,done:!1}}}class xH extends fn{constructor(e,t){super();this.upstream=e,this.handler=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> handleErrors`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;)try{return await this.upstream.next()}catch(e){if(!this.handler(e))return{value:null,done:!0}}}}class YN extends fn{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> AsyncMap`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=ji(e.value),n=await this.transform(e.value),s=ji(n);for(const i of t)wd(i,s)||i.dispose();return{value:n,done:!1}}}class uS extends fn{constructor(){super();this.outputQueue=new hS,this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.outputQueue.length()===0;)if(!await this.pump())return{value:null,done:!0};return{value:this.outputQueue.shift(),done:!1}}}class TH extends uS{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Flatmap`}async pump(){const e=await this.upstream.next();if(e.done)return!1;const t=ji(e.value),n=this.transform(e.value),s=ji(n);this.outputQueue.pushAll(n);for(const i of t)wd(i,s)||i.dispose();return!0}}class HN extends fn{constructor(e,t){super();this.baseErrorHandler=t,this.lastRead=null,this.iterator=null,this.moreIterators=e}summary(){const e="TODO: fill in upstream of chained summaries";return`${e} -> Chained`}async next(){return this.lastRead=this.readFromChain(this.lastRead),this.lastRead}async readFromChain(e){if(await e,this.iterator==null){const n=await this.moreIterators.next();if(n.done)return{value:null,done:!0};this.iterator=n.value,this.baseErrorHandler!=null&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler))}const t=await this.iterator.next();return t.done?(this.iterator=null,this.readFromChain(e)):t}}var Hr;(function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"})(Hr||(Hr={}));class AH extends fn{constructor(e,t=Hr.FAIL){super();this.iterators=e,this.mismatchMode=t,this.count=0,this.currentPromise=null}summary(){const e="TODO: fill in upstream of zip summaries";return`{${e}} -> Zip`}async nextState(e){await e;let t=0,n=0;function s(o){if(o instanceof fn){const a=o.next();return{value:a.then(c=>(t++,c.done&&n++,c.value)),recurse:!1}}else return{value:null,recurse:!0}}const i=await PN(this.iterators,s);if(t===n)return{value:null,done:!0};if(n>0)switch(this.mismatchMode){case Hr.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case Hr.SHORTEST:return{value:null,done:!0};case Hr.LONGEST:default:}return this.count++,{value:i,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}}class qN extends fn{constructor(e,t){super();this.upstream=e,this.bufferSize=t,this.buffer=new zN(t)}summary(){return`${this.upstream.summary()} -> Prefetch`}refill(){for(;!this.buffer.isFull();){const e=this.upstream.next();this.buffer.push(e)}}next(){return this.refill(),this.buffer.shift()}}class vH extends qN{constructor(e,t,n){super(e,t);this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=Pa(n||Yn().toString()),this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}randomInt(e){return Math.floor(this.random()*e)}chooseIndex(){return this.randomInt(this.buffer.length())}async serialNext(){for(this.upstreamExhausted||this.refill();!this.buffer.isEmpty();){const e=this.chooseIndex(),t=await this.buffer.shuffleExcise(e);if(t.done)this.upstreamExhausted=!0;else return this.refill(),t}return{value:null,done:!0}}}class ic{constructor(){this.size=null}batch(e,t=!0){const n=this;k(e>0,()=>`batchSize needs to be positive, but it is
${e}`);let s;return this.size===Infinity||this.size==null?s=this.size:t?s=Math.ceil(this.size/e):s=Math.floor(this.size/e),cs(async()=>(await n.iterator()).columnMajorBatch(e,t,RH),s)}concatenate(e){const t=this;let n;return this.size===Infinity||e.size===Infinity?n=Infinity:this.size!=null&&e.size!=null?n=this.size+e.size:n=null,cs(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){const t=this;let n;return this.size===Infinity?n=Infinity:n=null,cs(async()=>(await t.iterator()).filter(s=>ee(()=>e(s))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){const t=this;return cs(async()=>(await t.iterator()).map(n=>ee(()=>e(n))),this.size)}mapAsync(e){const t=this;return cs(async()=>(await t.iterator()).mapAsync(e),this.size)}prefetch(e){if(e==null)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");const t=this;return cs(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){const t=this;let n;return this.size!=null&&e>0?n=this.size*e:e===0?n=0:this.size!=null&&(e===void 0||e<0)?n=Infinity:n=null,cs(async()=>{const s=Zh(async()=>({value:await t.iterator(),done:!1}));return VN(s.take(e))},n)}skip(e){const t=this;let n;return this.size!=null&&e>=0&&this.size>=e?n=this.size-e:this.size!=null&&(this.size<e||e===void 0||e<0)?n=0:n=null,cs(async()=>(await t.iterator()).skip(e),n)}shuffle(e,t,n=!0){if(e==null||e<0)throw this.size==null?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);const s=this,i=Pa(t||Yn().toString());return cs(async()=>{let o=i.int32();return n&&(o+=i.int32()),(await s.iterator()).shuffle(e,o.toString())},this.size)}take(e){const t=this;let n;return this.size!=null&&this.size>e?n=e:this.size!=null&&this.size<=e?n=this.size:n=null,cs(async()=>(await t.iterator()).take(e),n)}async toArray(){if(this.size===Infinity)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===Infinity)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}}ic.MAX_BUFFER_SIZE=1e4;function cs(e,t=null){return new class extends ic{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function NH(e){return cs(async()=>GN(e),e.length)}function CH(e){if(!sc(e))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(e))for(let n=0;n<e.length;n++)t=t==null?e[n].size:Math.min(t,e[n].size);else if(e instanceof Object)for(const n in e)t=t==null?e[n].size:Math.min(t,e[n].size);return cs(async()=>{const n=await PN(e,s=>{if(s instanceof ic)return{value:s.iterator(),recurse:!1};if(sc(s))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return mH(n,Hr.SHORTEST)},t)}function RH(e){if(e===null)return null;const t=e[0];if(hH(t)){const n=OH(e);return{value:n,recurse:!1}}return{value:null,recurse:!0}}function OH(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof Q?rs(e):en(e)}class jN extends ic{constructor(e){super();this.input=e}async iterator(){const e=await this.input.iterator(),t=e.decodeUTF8(),n=t.split(`
`).map(s=>(s.endsWith("\r")&&(s=s.slice(0,-1)),s));return n}}const nm='"',Qh=Symbol("out"),KN=Symbol("field"),sm=Symbol("quote"),dS=Symbol("quoteafterquote"),XN=Symbol("quoteinquote");class JN extends ic{constructor(e,t){super();this.input=e,this.hasHeader=!0,this.fullColumnNames=null,this.columnNamesValidated=!1,this.columnConfigs=null,this.configuredColumnsOnly=!1,this.delimiter=",",this.delimWhitespace=!1,this.base=new jN(e),t||(t={}),this.hasHeader=!(t.hasHeader===!1),this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(k(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){const e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&k(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);const t=this.fullColumnNames.reduce((s,i)=>(s[i]=s[i]+1||1,s),{}),n=Object.keys(t).filter(s=>t[s]>1);if(k(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs)for(const s of Object.keys(this.columnConfigs)){const i=this.fullColumnNames.indexOf(s);if(i===-1)throw new Error('The key "'+s+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){const e=await this.base.iterator(),t=await e.next();if(t.done)throw new Error("No data was found for CSV parsing.");const n=t.value,s=this.parseRow(n,!1);return s}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){const t=this.parseRow(e),n={},s={};for(let i=0;i<this.fullColumnNames.length;i++){const o=this.fullColumnNames[i],a=this.columnConfigs?this.columnConfigs[o]:null;if(this.configuredColumnsOnly&&!a)continue;{const c=t[i];let h=null;if(c==="")if(a&&a.default!==void 0)h=a.default;else{if(a&&(a.required||a.isLabel))throw new Error(`Required column ${o} is empty in this line: ${e}`);h=void 0}else{const d=Number(c);if(isNaN(d))a&&a.dtype==="bool"?h=this.getBoolean(c):h=c;else if(!a||!a.dtype)h=d;else switch(a.dtype){case"float32":h=d;break;case"int32":h=Math.floor(d);break;case"bool":h=this.getBoolean(c);break;default:h=d}}a&&a.isLabel?s[o]=h:n[o]=h}}return Object.keys(s).length===0?n:{xs:n,ys:s}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){const n=[];let s=0;const i=e.length;let o=Qh;for(let a=0;a<i;a++)switch(o){case Qh:switch(e.charAt(a)){case nm:s=a+1,o=sm;break;case this.delimiter:if(s=a+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),o=Qh;break;default:o=KN,s=a;break}break;case KN:switch(e.charAt(a)){case this.delimiter:n.push(e.substring(s,a)),o=Qh,s=a+1;break;default:}break;case sm:switch(e.charAt(a)){case nm:o=dS;break;default:}break;case dS:switch(e.charAt(a)){case this.delimiter:n.push(e.substring(s,a-1)),o=Qh,s=a+1;break;case nm:o=sm;break;default:o=XN;break}break;case XN:switch(e.charAt(a)){case nm:o=sm;break;default:}break;default:}if(o===dS?n.push(e.substring(s,i-1)):n.push(e.substring(s)),t&&n.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${n}`);return n}}class ZN extends fn{constructor(e){super();this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;const t=Math.log2(this.fftSize);if(this.fftSize<0||t<4||t>14||!Number.isInteger(t))throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);if(this.numFrames=e.numFramesPerSpectrogram||43,this.sampleRateHz=e.sampleRateHz,this.columnTruncateLength=e.columnTruncateLength||this.fftSize,this.audioTrackConstraints=e.audioTrackConstraints,this.smoothingTimeConstant=e.smoothingTimeConstant||0,this.includeSpectrogram=!(e.includeSpectrogram===!1),this.includeWaveform=e.includeWaveform===!0,!this.includeSpectrogram&&!this.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.")}summary(){return"microphone"}static async create(e={}){if(C().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");const t=new ZN(e);return await t.start(),t}async start(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:this.audioTrackConstraints==null?!0:this.audioTrackConstraints,video:!1})}catch(n){throw new Error(`Error thrown while initializing video stream: ${n.message}`)}if(!this.stream)throw new Error("Could not obtain audio from microphone.");const e=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new e,!this.sampleRateHz)this.sampleRateHz=this.audioContext.sampleRate;else if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error(`Mismatch in sampling rate: Expected: ${this.sampleRateHz}; Actual: ${this.audioContext.sampleRate}`);const t=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=this.fftSize*2,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,t.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize);return}async next(){if(this.isClosed)return{value:null,done:!0};let e,t;const n=await this.getAudioData();if(this.includeSpectrogram){const s=this.flattenQueue(n.freqDataQueue);e=this.getTensorFromAudioDataArray(s,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){const s=this.flattenQueue(n.timeDataQueue);t=this.getTensorFromAudioDataArray(s,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:e,waveform:t},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){const e=[],t=[];let n=0;return new Promise(s=>{const i=setInterval(()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-Infinity&&s({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++n===this.numFrames&&(clearInterval(i),s({freqDataQueue:e,timeDataQueue:t}))},this.fftSize/this.sampleRateHz*1e3)})}stop(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),this.stream!=null&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())}toArray(){throw new Error("Can not convert infinite audio stream to array.")}getSampleRate(){return this.sampleRateHz}flattenQueue(e){const t=e[0].length,n=new Float32Array(e.length*t);return e.forEach((s,i)=>n.set(s,i*t)),n}getTensorFromAudioDataArray(e,t){const n=new Float32Array(we(t));return n.set(e,n.length-e.length),en(n,t)}}class QN extends fn{constructor(e,t){super();if(this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=ss([0],"int32"),this.webcamConfig.centerCrop){const n=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,s=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,i=(1-n)/2,o=(1-s)/2,a=i+n,c=s+o;this.cropBox=Wr([o,i,c,a],[1,4])}else this.cropBox=Wr([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(C().get("IS_NODE"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!t.resizeWidth||!t.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=t.resizeWidth,e.height=t.resizeHeight}const n=new QN(e,t);return await n.start(),n}async start(){this.webcamConfig.facingMode&&k(this.webcamConfig.facingMode==="user"||this.webcamConfig.facingMode==="environment",()=>`Invalid webcam facing mode: ${this.webcamConfig.facingMode}. Please provide 'user' or 'environment'`);try{this.stream=await navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})}catch(e){throw e.message=`Error thrown while initializing video stream: ${e.message}`,e}if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(e){console.log(e),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,new Promise(e=>{this.webcamVideoElement.onloadedmetadata=()=>{e()}})}async next(){if(this.isClosed)return{value:null,done:!0};let e;try{e=bT(this.webcamVideoElement)}catch(t){throw new Error(`Error thrown converting video to pixels: ${JSON.stringify(t)}`)}if(this.resize)try{return{value:this.cropAndResizeFrame(e),done:!1}}catch(t){throw new Error(`Error thrown cropping the video: ${t.message}`)}finally{e.dispose()}else return{value:e,done:!1}}needToResize(){return!!(this.webcamConfig.resizeWidth&&this.webcamConfig.resizeHeight&&(this.webcamVideoElement.width!==this.webcamConfig.resizeWidth||this.webcamVideoElement.height!==this.webcamConfig.resizeHeight))}cropAndResizeFrame(e){return ee(()=>{const t=e.toFloat().expandDims(0);let n;n=$r.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");const s=n.shape;return n.reshape(s.slice(1))})}async capture(){return(await this.next()).value}stop(){const e=this.stream.getTracks();e.forEach(t=>t.stop());try{this.webcamVideoElement.srcObject=null}catch(t){console.log(t),this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}}class e0{}class t0 extends fn{split(e){return new EH(this,e)}}class EH extends t0{constructor(e,t){super();this.upstream=e,this.impl=new DH(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class DH extends uS{constructor(e,t){super();this.upstream=e,this.separator=t,this.carryover=""}summary(){return`${this.upstream.summary()} -> Split('${this.separator}')`}async pump(){const e=await this.upstream.next();if(e.done)return this.carryover===""?!1:(this.outputQueue.push(this.carryover),this.carryover="",!0);const t=e.value.split(this.separator);t[0]=this.carryover+t[0];for(const n of t.slice(0,-1))this.outputQueue.push(n);return this.carryover=t[t.length-1],!0}}class kH extends fn{decodeUTF8(){return new FH(this)}}class FH extends t0{constructor(e){super();this.upstream=e,this.impl=new _H(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class _H extends uS{constructor(e){super();if(this.upstream=e,C().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{const{StringDecoder:t}=require("string_decoder");this.decoder=new t("utf8")}}summary(){return`${this.upstream.summary()} -> Utf8`}async pump(){const e=await this.upstream.next();let t;if(e.done)return!1;t=e.value;let n;return C().get("IS_BROWSER")?n=this.decoder.decode(t,{stream:!0}):n=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0}}class n0 extends kH{constructor(e,t={}){super();this.file=e,this.options=t,k(e instanceof Uint8Array||(C().get("IS_BROWSER")?e instanceof File||e instanceof Blob:!1),()=>"FileChunkIterator only supports File, Blob and Uint8Array right now."),this.offset=t.offset||0,this.chunkSize=t.chunkSize||1024*1024}summary(){return`FileChunks ${this.file}`}async next(){if(this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size))return{value:null,done:!0};const e=new Promise((t,n)=>{const s=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)t(new Uint8Array(this.file.slice(this.offset,s)));else{const i=new FileReader;i.onload=a=>{let c=i.result;if(c instanceof ArrayBuffer&&(c=new Uint8Array(c)),!(c instanceof Uint8Array))return n(new TypeError("FileReader returned unknown type."));t(c)},i.onabort=a=>n(new Error("Aborted")),i.onerror=a=>n(new Error(a.type));const o=this.file.slice(this.offset,s);i.readAsArrayBuffer(o)}this.offset=s});return{value:await e,done:!1}}}async function WH(e,t={}){let n,s;typeof e=="string"?n=e:(n=e.url,s=$H(e));const i=await Vx(n,s);if(i.ok){const o=new Uint8Array(await i.arrayBuffer());return new n0(o,t)}else throw new Error(i.statusText)}const $H=e=>{const t={method:e.method,headers:e.headers,body:e.body,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,referrer:e.referrer,integrity:e.integrity};return t};function s0(e){return typeof e=="string"&&e.substr(0,7)==="file://"}class i0 extends e0{constructor(e,t={}){super();this.input=e,this.options=t}async iterator(){if(s0(this.input)&&C().get("IS_NODE")){const e=require("fs");this.input=e.readFileSync(this.input.substr(7))}return new n0(this.input,this.options)}}class r0 extends e0{constructor(e,t={}){super();this.url=e,this.fileOptions=t}async iterator(){return s0(this.url)?new i0(this.url,this.fileOptions).iterator():WH(this.url,this.fileOptions)}}function UH(e,t={}){return new JN(new r0(e),t)}function BH(e){const t=Zh(e);return cs(async()=>t)}function MH(e){return cs(async()=>{const t=await e();return Zh(()=>t.next())})}async function PH(e,t){return QN.create(e,t)}async function zH(e){return ZN.create(e)}const o0="2.6.0";var GH=Object.freeze({__proto__:null,array:NH,Dataset:ic,zip:CH,CSVDataset:JN,TextLineDataset:jN,csv:UH,func:BH,generator:MH,microphone:zH,webcam:PH,FileDataSource:i0,URLDataSource:r0,version_data:o0});function xe(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{n!=null&&k(n.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}const VH=up,YH=mw,HH=fw,qH=gw,jH=ip;function pS(e,t,n,s){if(n==="linear")return e.linear(t);if(n==="relu")return e.relu(t);if(n==="elu")return Oo(t);if(n==="relu6")return e.relu6(t);if(n==="prelu")return e.prelu(t,s);throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}class KH extends g{constructor(){super();this.blockSize=48,this.firstUse=!0,this.data=new p(this,_s())}write(e,t,n){this.firstUse&&(this.firstUse=!1,C().get("IS_NODE")&&qa(`
============================
Hi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.
============================`));const s={};return this.data.set(s,{values:e,dtype:n,refCount:1}),s}makeTensorInfo(e,t,n){const s=this.write(n,e,t);return{dataId:s,shape:e,dtype:t}}incRef(e){const t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){const t=this.data.get(e);t.refCount--}}move(e,t,n,s){this.data.set(e,{values:t,dtype:s,refCount:1})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:n}=this.data.get(e);if(t==="complex64"){const s=this.readSync(n.real.dataId),i=this.readSync(n.imag.dataId);return er(s,i)}return this.data.get(e).values}bufferSync(e){const t=this.readSync(e.dataId);let n=t;if(e.dtype==="string")try{n=t.map(s=>zl(s))}catch(s){throw new Error("Failed to decode encoded string bytes into utf-8")}return Ze(e.shape,e.dtype,n)}makeOutput(e,t,n){const s=this.write(e,t,n);return _s().makeTensorFromDataId(s,t,n,this)}disposeData(e){if(this.data.has(e)){const{complexTensorInfos:t}=this.data.get(e);t!=null&&(this.disposeData(t.real.dataId),this.disposeData(t.imag.dataId)),this.data.delete(e)}}disposeIntermediateTensorInfo(e){const t=e.dataId;if(this.data.has(t)){const n=this.data.get(t);n.refCount--,n.refCount<1&&this.disposeData(t)}}async time(e){const t=Yn();e();const n=Yn()-t;return{kernelMs:n}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}stridedSlice(e,t,n,s){xe(e,"stridedSlice");const i=Cd(t,n,s);if(i.some(c=>c===0))return en([],i);const o=Ze(i,e.dtype),a=this.bufferSync(e);for(let c=0;c<o.size;c++){const h=o.indexToLoc(c),d=new Array(h.length);for(let m=0;m<d.length;m++)d[m]=h[m]*s[m]+t[m];o.set(a.get(...d),...h)}return o.toTensor()}diag(e){const t=this.readSync(e.dataId),n=Ze([e.size,e.size],e.dtype),s=n.values;for(let i=0;i<t.length;i++)s[i*e.size+i]=t[i];return n.toTensor()}unstack(e,t){const n=e.shape[t],s=new Array(e.rank-1);let i=0;for(let h=0;h<e.rank;h++)h!==t&&(s[i++]=e.shape[h]);const o=new Array(e.rank).fill(0),a=e.shape.slice();a[t]=1;const c=new Array(n);for(let h=0;h<c.length;h++)o[t]=h,c[h]=nt(e,o,a).reshape(s);return c}reverse(e,t){xe(e,"reverse");const n=Ze(e.shape,e.dtype),s=this.bufferSync(e);for(let i=0;i<n.size;i++){const o=n.indexToLoc(i),a=o.slice();t.forEach(c=>a[c]=e.shape[c]-1-a[c]),n.set(s.get(...a),...o)}return n.toTensor()}neg(e){return xe(e,"neg"),X(Ne(-1),e)}addN(e){xe(e,"addN");const t=e.map(i=>this.readSync(i.dataId)),n=Ze(e[0].shape,e[0].dtype),s=n.values;for(let i=0;i<e.length;i++){const o=t[i];for(let a=0;a<s.length;a++)s[a]+=o[a]}return n.toTensor()}softmax(e,t){const n=gt([t],e.shape),s=jn(e,n),i=On(s.shape,n),o=Ce(e,s.reshape(i)),a=Ls(o),c=this.sum(a,n).reshape(i);return _e(a,c)}pow(e,t){return xe([e,t],"pow"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>Math.pow(n,s))}batchMatMul(e,t,n,s){xe([e,t],"matMul");const i=n?e.shape[1]:e.shape[2],o=n?e.shape[2]:e.shape[1],a=s?t.shape[1]:t.shape[2],c=e.shape[0],h=this.readSync(e.dataId),d=this.readSync(t.dataId),[m,y,b]=n?[e.strides[0],1,e.strides[1]]:[e.strides[0],e.strides[1],1],[w,L,T]=s?[1,t.strides[1],t.strides[0]]:[t.strides[1],1,t.strides[0]],A=o*a,N=Ze([c,o,a],e.dtype),E=N.values,D=this.blockSize;for(let F=0;F<c;F++)for(let _=0;_<o;_+=D)for(let B=0;B<a;B+=D)for(let $=0;$<i;$+=D){const H=Math.min(_+D,o),q=Math.min(B+D,a),J=Math.min($+D,i);for(let re=_;re<H;re++)for(let ce=B;ce<q;ce++){let ue=0;for(let he=$;he<J;he++)ue+=h[F*m+re*y+he*b]*d[he*w+ce*L+F*T];E[F*A+(re*a+ce)]+=ue}}return N.toTensor()}fusedBatchMatMul({a:e,b:t,transposeA:n,transposeB:s,bias:i,activation:o,preluActivationWeights:a}){let c=this.batchMatMul(e,t,n,s);return i&&(c=be(c,i)),o&&(c=pS(this,c,o,a)),c}floorDiv(e,t){xe([e,t],"floorDiv");const n=(i,o)=>Math.floor(i/o),s="int32";return this.broadcastedBinaryOp(e,t,s,n)}sum(e,t){xe(e,"sum"),ts("sum",t,e.rank);const[n,s]=Rn(e.shape,t),i=Nn(e.dtype,"int32"),o=ct(n,i),a=we(s),c=this.readSync(o.dataId),h=this.readSync(e.dataId);for(let d=0;d<c.length;++d){const m=d*a;let y=0;for(let b=0;b<a;++b)y+=h[m+b];c[d]=y}return o}prod(e,t){xe(e,"sum");const[n,s]=Rn(e.shape,t),i=Nn(e.dtype,"int32"),o=ct(n,i),a=we(s),c=this.readSync(o.dataId),h=this.readSync(e.dataId);for(let d=0;d<c.length;++d){const m=d*a;let y=1;for(let b=0;b<a;++b)y*=h[m+b];c[d]=y}return o}unsortedSegmentSum(e,t,n){xe(e,"unsortedSegmentSum");const s=[],i=e.rank-t.rank;for(let o=0;o<i;++o)t=t.expandDims(o+1);for(let o=0;o<n;++o){const a=Ne(o,"int32"),c=ti(a,t).asType("float32"),h=c.mul(e).sum(0);s.push(h)}return rs(s)}argMin(e,t){xe(e,"argMin");const n=[t];ts("argMin",n,e.rank);const[s,i]=Rn(e.shape,n),o=ct(s,"int32"),a=we(i),c=this.readSync(o.dataId),h=this.readSync(e.dataId);for(let d=0;d<c.length;++d){const m=d*a;let y=h[m],b=0;for(let w=0;w<a;++w){const L=h[m+w];L<y&&(y=L,b=w)}c[d]=b}return o}argMax(e,t){xe(e,"argMax");const n=[t];ts("argMax",n,e.rank);const[s,i]=Rn(e.shape,n),o=ct(s,"int32"),a=we(i),c=this.readSync(o.dataId),h=this.readSync(e.dataId);for(let d=0;d<c.length;++d){const m=d*a;let y=h[m],b=0;for(let w=0;w<a;++w){const L=h[m+w];L>y&&(y=L,b=w)}c[d]=b}return o}cumsum(e,t,n,s){if(xe(e,"cumsum"),t!==e.rank-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${e.rank-1} but got axis=${t}`);const i=Nn(e.dtype,"int32"),o=ct(e.shape,i),a=this.readSync(o.dataId),c=this.readSync(e.dataId),h=e.shape[e.rank-1],d=s?(m,y)=>m+h-y-1:(m,y)=>m+y;for(let m=0;m<c.length;m+=h)for(let y=0;y<h;y++){const b=d(m,y);if(y===0)a[b]=n?0:c[b];else{const w=d(m,y-1);a[b]=n?c[w]+a[w]:c[b]+a[w]}}return o}equal(e,t){return xe([e,t],"equal"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n===s?1:0)}notEqual(e,t){return xe([e,t],"notEqual"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n!==s?1:0)}less(e,t){return xe([e,t],"less"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n<s?1:0)}lessEqual(e,t){return xe([e,t],"lessEqual"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n<=s?1:0)}greater(e,t){return xe([e,t],"greater"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n>s?1:0)}greaterEqual(e,t){return xe([e,t],"greaterEqual"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n>=s?1:0)}logicalAnd(e,t){return xe([e,t],"logicalAnd"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n&&s)}logicalOr(e,t){return xe([e,t],"logicalOr"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n||s)}select(e,t,n){xe([e,t,n],"select");const s=this.readSync(e.dataId),i=this.readSync(t.dataId),o=this.readSync(n.dataId),a=ct(t.shape,Nn(t.dtype,n.dtype)),c=this.readSync(a.dataId);let h=0;const d=e.rank===0||e.rank>1||t.rank===1?1:we(t.shape.slice(1));for(let m=0;m<s.length;m++)for(let y=0;y<d;y++)s[m]===1?c[h++]=i[m]:c[h++]=o[m];return a}where(e){xe([e],"where");const t=this.readSync(e.dataId);return jH(e.shape,t)}topk(e,t,n){xe(e,"topk");const s=this.readSync(e.dataId);return qH(s,e.shape,e.dtype,t,n)}min(e,t){xe(e,"min"),ts("min",t,e.rank);const[n,s]=Rn(e.shape,t),i=ct(n,e.dtype),o=we(s),a=this.readSync(i.dataId),c=this.readSync(e.dataId);for(let h=0;h<a.length;++h){const d=h*o;let m=c[d];for(let y=0;y<o;++y){const b=c[d+y];b<m&&(m=b)}a[h]=m}return i}minimum(e,t){return xe([e,t],"minimum"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>Math.min(n,s))}mod(e,t){return xe([e,t],"mod"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>{const i=n%s;return n<0&&s<0||n>=0&&s>=0?i:(i+s)%s})}maximum(e,t){return xe([e,t],"maximum"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>Math.max(n,s))}all(e,t){xe(e,"all"),ts("all",t,e.rank);const[n,s]=Rn(e.shape,t),i=ct(n,e.dtype),o=we(s),a=this.readSync(i.dataId),c=this.readSync(e.dataId);for(let h=0;h<a.length;++h){const d=h*o;let m=c[d];for(let y=0;y<o;++y){const b=c[d+y];m=m&&b}a[h]=m}return i}any(e,t){xe(e,"any"),ts("any",t,e.rank);const[n,s]=Rn(e.shape,t),i=ct(n,e.dtype),o=we(s),a=this.readSync(i.dataId),c=this.readSync(e.dataId);for(let h=0;h<a.length;++h){const d=h*o;let m=c[d];for(let y=0;y<o;++y){const b=c[d+y];m=m||b}a[h]=m}return i}squaredDifference(e,t){return xe([e,t],"squaredDifference"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>{const i=n-s;return i*i})}linear(e){return e}relu(e){xe(e,"relu");const t=ct(e.shape,e.dtype),n=this.readSync(t.dataId),s=this.readSync(e.dataId);for(let i=0;i<s.length;++i)n[i]=Math.max(0,s[i]);return t}relu6(e){xe(e,"relu");const t=ct(e.shape,e.dtype),n=this.readSync(t.dataId),s=this.readSync(e.dataId);for(let i=0;i<s.length;++i)n[i]=Math.min(Math.max(0,s[i]),6);return t}prelu(e,t){return xe([e,t],"prelu"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>n<0?s*n:n)}eluDer(e,t){xe([e,t],"eluDer");const n=new Float32Array(t.size),s=this.readSync(t.dataId),i=this.readSync(e.dataId);for(let o=0;o<s.length;++o){const a=s[o];a>=1?n[o]=i[o]:n[o]=i[o]*(a+1)}return this.makeOutput(n,t.shape,"float32")}atan2(e,t){return xe([e,t],"atan2"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>Math.atan2(n,s))}fusedConv2d({input:e,filter:t,convInfo:n,bias:s,activation:i,preluActivationWeights:o}){let a=this.conv2d(e,t,n);return s&&(a=be(a,s)),i&&(a=pS(this,a,i,o)),a}conv2d(e,t,n){xe([e,t],"conv2d");const s=n.filterHeight,i=n.filterWidth,o=n.dilationHeight,a=n.dilationWidth,c=n.padInfo.left,h=n.padInfo.top,d=n.dataFormat==="channelsLast",m=Ze(n.outShape,e.dtype),y=e.strides[0],b=d?e.strides[1]:e.strides[2],w=d?e.strides[2]:1,L=d?1:e.strides[1],T=m.strides[0],A=d?m.strides[1]:m.strides[2],N=d?m.strides[2]:1,E=d?1:m.strides[1],D=this.readSync(e.dataId),F=this.readSync(t.dataId),_=m.values;for(let B=0;B<n.batchSize;++B){const $=B*y,H=B*T;for(let q=0;q<n.outHeight;++q){const J=H+q*A,re=q*n.strideHeight-h;for(let ce=0;ce<s;ce++){const ue=re+ce*o;if(ue<0||ue>=n.inHeight)continue;const he=ce*t.strides[0],de=$+ue*b;for(let le=0;le<n.outWidth;++le){const ye=J+le*N,pe=le*n.strideWidth-c;for(let Ie=0;Ie<i;Ie++){const Se=pe+Ie*a;if(Se<0||Se>=n.inWidth)continue;const Ee=he+Ie*t.strides[1],We=de+Se*w;let Oe=Ee;for(let $e=0;$e<n.inChannels;++$e){const Ye=D[We+$e*L];for(let et=0;et<n.outChannels;++et)_[ye+et*E]+=Ye*F[Oe+et];Oe+=n.outChannels}}}}}}return m.toTensor()}conv3d(e,t,n){const s=n.filterDepth,i=n.filterHeight,o=n.filterWidth,a=n.dilationDepth,c=n.dilationHeight,h=n.dilationWidth,d=n.padInfo.front,m=n.padInfo.left,y=n.padInfo.top,b=Ze(n.outShape,e.dtype),w=this.readSync(e.dataId),L=this.readSync(t.dataId),T=b.values;for(let A=0;A<n.batchSize;++A){const N=A*e.strides[0],E=A*b.strides[0];for(let D=0;D<n.outDepth;++D){const F=E+D*b.strides[1],_=D*n.strideDepth-d;for(let B=0;B<s;B++){const $=_+B*a;if($<0||$>=n.inDepth)continue;const H=B*t.strides[0],q=N+$*e.strides[1];for(let J=0;J<n.outHeight;++J){const re=F+J*b.strides[2],ce=J*n.strideHeight-y;for(let ue=0;ue<i;ue++){const he=ce+ue*c;if(he<0||he>=n.inHeight)continue;const de=H+ue*t.strides[1],le=q+he*e.strides[2];for(let ye=0;ye<n.outWidth;++ye){const pe=re+ye*n.outChannels,Ie=ye*n.strideWidth-m;for(let Se=0;Se<o;Se++){const Ee=Ie+Se*h;if(Ee<0||Ee>=n.inWidth)continue;const We=de+Se*t.strides[2],Oe=le+Ee*n.inChannels;let $e=We;for(let Ye=0;Ye<n.inChannels;++Ye){const et=w[Oe+Ye];for(let bt=0;bt<n.outChannels;++bt)T[pe+bt]+=et*L[$e+bt];$e+=n.outChannels}}}}}}}}return b.toTensor()}conv2dDerInput(e,t,n){xe([e,t],"conv2dDerInput");const s=Ze(n.inShape,"float32"),i=s.values,o=this.readSync(e.dataId),a=this.readSync(t.dataId),[c,h,d]=t.strides,{batchSize:m,filterHeight:y,filterWidth:b,inChannels:w,inHeight:L,inWidth:T,outChannels:A,outHeight:N,outWidth:E,strideHeight:D,strideWidth:F,dataFormat:_}=n,B=y-1-n.padInfo.top,$=b-1-n.padInfo.left,H=_==="channelsLast",q=s.strides[0],J=H?s.strides[1]:s.strides[2],re=H?s.strides[2]:1,ce=H?1:s.strides[1],ue=e.strides[0],he=H?e.strides[1]:e.strides[2],de=H?e.strides[2]:1,le=H?1:e.strides[1];for(let ye=0;ye<m;++ye)for(let pe=0;pe<w;++pe)for(let Ie=0;Ie<L;++Ie){const Se=Ie-B,Ee=Math.max(0,Math.ceil(Se/D)),We=Math.min(N,(y+Se)/D);for(let Oe=0;Oe<T;++Oe){const $e=Oe-$,Ye=Math.max(0,Math.ceil($e/F)),et=Math.min(E,(b+$e)/F);let bt=0;for(let un=Ee;un<We;++un){const hs=un*D-Se;for(let Ht=Ye;Ht<et;++Ht){const $n=Ht*F-$e,pi=ue*ye+he*un+de*Ht,vs=c*(y-1-hs)+h*(b-1-$n)+d*pe;for(let us=0;us<A;++us){const Gs=o[pi+le*us],hu=a[vs+us];bt+=Gs*hu}}}const Jt=q*ye+J*Ie+re*Oe+ce*pe;i[Jt]=bt}}return s.toTensor()}conv3dDerInput(e,t,n){const s=Ze(n.inShape,"float32"),i=s.values,[o,a,c,h]=s.strides,d=this.readSync(e.dataId),[m,y,b,w]=e.strides,L=this.readSync(t.dataId),[T,A,N,E]=t.strides,{batchSize:D,filterDepth:F,filterHeight:_,filterWidth:B,inChannels:$,inDepth:H,inHeight:q,inWidth:J,outChannels:re,outDepth:ce,outHeight:ue,outWidth:he,strideDepth:de,strideHeight:le,strideWidth:ye}=n,pe=F-1-n.padInfo.front,Ie=_-1-n.padInfo.top,Se=B-1-n.padInfo.left;for(let Ee=0;Ee<D;++Ee)for(let We=0;We<$;++We)for(let Oe=0;Oe<H;++Oe){const $e=Oe-pe,Ye=Math.max(0,Math.ceil($e/de)),et=Math.min(ce,(F+$e)/de);for(let bt=0;bt<q;++bt){const Jt=bt-Ie,un=Math.max(0,Math.ceil(Jt/le)),hs=Math.min(ue,(_+Jt)/le);for(let Ht=0;Ht<J;++Ht){const $n=Ht-Se,pi=Math.max(0,Math.ceil($n/ye)),vs=Math.min(he,(B+$n)/ye);let us=0;for(let Gs=Ye;Gs<et;++Gs){const hu=Gs*de-$e;for(let yc=un;yc<hs;++yc){const bc=yc*le-Jt;for(let wc=pi;wc<vs;++wc){const _S=wc*ye-$n,WS=m*Ee+y*Gs+b*yc+w*wc,m7=T*(F-1-hu)+A*(_-1-bc)+N*(B-1-_S)+E*We;for(let bm=0;bm<re;++bm){const f7=d[WS+bm],g7=L[m7+bm];us+=f7*g7}}}}i[o*Ee+a*Oe+c*bt+h*Ht+We]=us}}}return s.toTensor()}conv2dDerFilter(e,t,n){xe([e,t],"conv2dDerFilter");const s=n.strideHeight,i=n.strideWidth,o=n.filterHeight,a=n.filterWidth,c=n.dataFormat==="channelsLast",h=Ze(n.filterShape,"float32"),d=n.padInfo.left,m=n.padInfo.top,y=this.bufferSync(e),b=this.bufferSync(t);for(let w=0;w<o;++w){const L=Math.max(0,Math.ceil((m-w)/s)),T=Math.min(n.outHeight,(n.inHeight+m-w)/s);for(let A=0;A<a;++A){const N=Math.max(0,Math.ceil((d-A)/i)),E=Math.min(n.outWidth,(n.inWidth+d-A)/i);for(let D=0;D<n.inChannels;++D)for(let F=0;F<n.outChannels;++F){let _=0;for(let B=0;B<n.batchSize;++B)for(let $=L;$<T;++$){const H=w+$*s-m;for(let q=N;q<E;++q){const J=A+q*i-d;c?_+=y.get(B,H,J,D)*b.get(B,$,q,F):_+=y.get(B,D,H,J)*b.get(B,F,$,q)}}h.set(_,w,A,D,F)}}}return h.toTensor()}conv3dDerFilter(e,t,n){const s=n.strideDepth,i=n.strideHeight,o=n.strideWidth,a=n.filterDepth,c=n.filterHeight,h=n.filterWidth,d=Ze(n.filterShape,"float32"),m=d.values,[y,b,w,L]=d.strides,T=this.readSync(t.dataId),[A,N,E,D]=t.strides,F=this.readSync(e.dataId),[_,B,$,H]=e.strides,q=n.padInfo.front,J=n.padInfo.left,re=n.padInfo.top;for(let ce=0;ce<a;++ce){const ue=Math.max(0,Math.ceil((q-ce)/s)),he=Math.min(n.outDepth,(n.inDepth+q-ce)/s),de=ce*y;for(let le=0;le<c;++le){const ye=Math.max(0,Math.ceil((re-le)/i)),pe=Math.min(n.outHeight,(n.inHeight+re-le)/i),Ie=le*b+de;for(let Se=0;Se<h;++Se){const Ee=Math.max(0,Math.ceil((J-Se)/o)),We=Math.min(n.outWidth,(n.inWidth+J-Se)/o),Oe=Se*w+Ie;for(let $e=0;$e<n.inChannels;++$e){const Ye=$e*L+Oe;for(let et=0;et<n.outChannels;++et){let bt=0;for(let Jt=0;Jt<n.batchSize;++Jt){const un=Jt*_,hs=Jt*A;for(let Ht=ue;Ht<he;++Ht){const $n=ce+Ht*s-q,pi=$n*B+un,vs=Ht*N+hs;for(let us=ye;us<pe;++us){const Gs=le+us*i-re,hu=Gs*$+pi,yc=us*E+vs;for(let bc=Ee;bc<We;++bc){const wc=Se+bc*o-J,_S=wc*H+hu,WS=bc*D+yc;bt+=F[_S+$e]*T[WS+et]}}}}m[Ye+et]=bt}}}}}return d.toTensor()}fusedDepthwiseConv2D({input:e,filter:t,convInfo:n,bias:s,activation:i,preluActivationWeights:o}){let a=this.depthwiseConv2D(e,t,n);return s&&(a=be(a,s)),i&&(a=pS(this,a,i,o)),a}depthwiseConv2D(e,t,n){xe([e,t],"depthwiseConv2D");const s=n.filterHeight,i=n.filterWidth,o=n.dilationHeight,a=n.dilationWidth,c=n.padInfo.left,h=n.padInfo.top,d=n.outChannels/n.inChannels,m=Ze(n.outShape,e.dtype),y=this.readSync(e.dataId),b=this.readSync(t.dataId),w=m.values;for(let L=0;L<n.batchSize;++L){const T=L*e.strides[0],A=L*m.strides[0];for(let N=0;N<n.outHeight;++N){const E=A+N*m.strides[1],D=N*n.strideHeight-c;for(let F=0;F<s;++F){const _=D+F*o;if(_<0||_>=n.inHeight)continue;const B=F*t.strides[0],$=T+_*e.strides[1];for(let H=0;H<n.outWidth;++H){const q=E+H*m.strides[2],J=H*n.strideWidth-h;for(let re=0;re<i;++re){const ce=J+re*a;if(ce<0||ce>=n.inWidth)continue;const ue=B+re*t.strides[1],he=$+ce*n.inChannels;let de=q,le=ue;for(let ye=0;ye<n.inChannels;++ye){const pe=y[he+ye];for(let Ie=0;Ie<d;++Ie)w[de+Ie]+=pe*b[le+Ie];de+=d,le+=d}}}}}}return m.toTensor()}depthwiseConv2DDerInput(e,t,n){xe([e,t],"depthwiseConv2DDerInput");const s=Ze(n.inShape,"float32"),i=s.values,[o,a,c]=s.strides,h=this.readSync(e.dataId),[d,m,y]=e.strides,b=this.readSync(t.dataId),[w,L,T]=t.strides,{batchSize:A,filterHeight:N,filterWidth:E,inChannels:D,inHeight:F,inWidth:_,outChannels:B,outHeight:$,outWidth:H,strideHeight:q,strideWidth:J}=n,re=N-1-n.padInfo.top,ce=E-1-n.padInfo.left,ue=B/D;for(let he=0;he<A;++he)for(let de=0;de<D;++de)for(let le=0;le<F;++le){const ye=le-re,pe=Math.max(0,Math.ceil(ye/q)),Ie=Math.min($,(N+ye)/q);for(let Se=0;Se<_;++Se){const Ee=Se-ce,We=Math.max(0,Math.ceil(Ee/J)),Oe=Math.min(H,(E+Ee)/J);let $e=0;for(let Ye=pe;Ye<Ie;++Ye){const et=Ye*q-ye;for(let bt=We;bt<Oe;++bt){const Jt=bt*J-Ee,un=d*he+m*Ye+y*bt,hs=w*(N-1-et)+L*(E-1-Jt)+T*de;for(let Ht=0;Ht<ue;++Ht){const $n=de*ue+Ht,pi=h[un+$n],vs=b[hs+Ht];$e+=pi*vs}}}i[o*he+a*le+c*Se+de]=$e}}return s.toTensor()}depthwiseConv2DDerFilter(e,t,n){xe([e,t],"depthwiseConv2DDerFilter");const s=n.strideHeight,i=n.strideWidth,o=n.filterHeight,a=n.filterWidth,c=Ze(n.filterShape,"float32"),h=n.padInfo.left,d=n.padInfo.top,m=n.outChannels/n.inChannels,y=this.bufferSync(e),b=this.bufferSync(t);for(let w=0;w<o;++w){const L=Math.max(0,Math.ceil((d-w)/s)),T=Math.min(n.outHeight,(n.inHeight+d-w)/s);for(let A=0;A<a;++A){const N=Math.max(0,Math.ceil((h-A)/i)),E=Math.min(n.outWidth,(n.inWidth+h-A)/i);for(let D=0;D<n.outChannels;++D){const F=Math.trunc(D/m),_=D%m;let B=0;for(let $=0;$<n.batchSize;++$)for(let H=L;H<T;++H){const q=w+H*s-d;for(let J=N;J<E;++J){const re=A+J*i-h;B+=y.get($,q,re,F)*b.get($,H,J,D)}}c.set(B,w,A,F,_)}}}return c.toTensor()}tile(e,t){return xe(e,"tile"),HH(this.bufferSync(e),t)}gather(e,t,n){xe([e,t],"gather");const s=e.shape.slice(),i=this.readSync(t.dataId);s[n]=i.length;const o=Ze(s,e.dtype),a=this.bufferSync(e);for(let c=0;c<o.size;++c){const h=o.indexToLoc(c),d=h.slice();d[n]=i[h[n]];const m=a.locToIndex(d);o.values[c]=a.values[m]}return o.toTensor()}batchToSpaceND(e,t,n){xe([e],"batchToSpaceND");const s=t.reduce((d,m)=>d*m),i=Ah(e.shape,t,s),o=vh(i.length,t.length),a=Nh(e.shape,t,s),c=sw(n,t.length),h=iw(a,n,t.length);return Me(e.reshape(i),o).reshape(a).slice(c,h)}pool3d(e,t,n){xe(e,"pool3d");const s=t.strideDepth,i=t.strideHeight,o=t.strideWidth,a=t.dilationDepth,c=t.dilationHeight,h=t.dilationWidth,d=t.effectiveFilterDepth,m=t.effectiveFilterHeight,y=t.effectiveFilterWidth,b=t.padInfo.front,w=t.padInfo.top,L=t.padInfo.left,T=n==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,A=this.readSync(e.dataId),N=Ze(t.outShape,e.dtype),E=N.values,D=t.outShape[1]*t.outShape[2]*t.outShape[3]*t.outShape[4],F=t.outShape[2]*t.outShape[3]*t.outShape[4],_=t.outShape[3]*t.outShape[4],B=t.outShape[4];for(let $=0;$<t.batchSize;++$){const H=$*D,q=$*e.strides[0];for(let J=0;J<t.inChannels;++J)for(let re=0;re<t.outDepth;++re){const ce=re*s-b;let ue=ce;for(;ue<0;)ue+=a;const he=Math.min(t.inDepth,d+ce),de=H+re*F;for(let le=0;le<t.outHeight;++le){const ye=le*i-w;let pe=ye;for(;pe<0;)pe+=c;const Ie=Math.min(t.inHeight,m+ye),Se=de+le*_;for(let Ee=0;Ee<t.outWidth;++Ee){const We=Ee*o-L;let Oe=We;for(;Oe<0;)Oe+=h;const $e=Math.min(t.inWidth,y+We),Ye=Se+Ee*B;let et=T,bt=0,Jt=0;for(let hs=ue;hs<he;hs+=a){const Ht=q+hs*e.strides[1];for(let $n=pe;$n<Ie;$n+=c){const pi=Ht+$n*e.strides[2];for(let vs=Oe;vs<$e;vs+=h){const us=pi+vs*e.strides[3],Gs=A[us+J];if(n==="max"&&Gs>et?et=Gs:n==="avg"&&(bt+=Gs,Jt++),isNaN(et))break}if(isNaN(et))break}if(isNaN(et))break}const un=Ye+J;E[un]=n==="avg"?bt/Jt:et}}}}return N.toTensor()}avgPool3d(e,t){return xe(e,"avgPool3d"),this.pool3d(e,t,"avg").toFloat()}avgPool3dBackprop(e,t,n){xe([e,t],"avgPool3dBackprop");const s=n.strideDepth,i=n.strideHeight,o=n.strideWidth,a=n.filterDepth,c=n.filterHeight,h=n.filterWidth,d=n.dilationDepth,m=n.dilationHeight,y=n.dilationWidth,b=n.effectiveFilterDepth,w=n.effectiveFilterHeight,L=n.effectiveFilterWidth,T=b-1-n.padInfo.front,A=L-1-n.padInfo.left,N=w-1-n.padInfo.top,E=Ze(t.shape,"float32"),D=1/(a*c*h),F=this.bufferSync(e);for(let _=0;_<n.batchSize;++_)for(let B=0;B<n.inChannels;++B)for(let $=0;$<n.inDepth;++$)for(let H=0;H<n.inHeight;++H)for(let q=0;q<n.inWidth;++q){const J=$-T,re=H-N,ce=q-A;let ue=0;for(let he=0;he<b;he+=d){const de=(J+he)/s;if(de<0||de>=n.outDepth||Math.floor(de)!==de)continue;for(let le=0;le<w;le+=m){const ye=(re+le)/i;if(ye<0||ye>=n.outHeight||Math.floor(ye)!==ye)continue;for(let pe=0;pe<L;pe+=y){const Ie=(ce+pe)/o;if(Ie<0||Ie>=n.outWidth||Math.floor(Ie)!==Ie)continue;const Se=F.get(_,de,ye,Ie,B);ue+=Se}}}E.set(ue*D,_,$,H,q,B)}return E.toTensor()}maxPool3d(e,t){return xe(e,"maxPool3d"),this.pool3d(e,t,"max").toFloat()}maxPool3dPositions(e,t){const n=Ze(t.outShape,"int32"),s=t.strideDepth,i=t.strideHeight,o=t.strideWidth,a=t.dilationDepth,c=t.dilationHeight,h=t.dilationWidth,d=t.effectiveFilterDepth,m=t.effectiveFilterHeight,y=t.effectiveFilterWidth,b=t.padInfo.front,w=t.padInfo.top,L=t.padInfo.left,T=this.bufferSync(e);for(let A=0;A<t.batchSize;++A)for(let N=0;N<t.inChannels;++N)for(let E=0;E<t.outDepth;++E){const D=E*s-b;let F=D;for(;F<0;)F+=a;const _=Math.min(t.inDepth,d+D);for(let B=0;B<t.outHeight;++B){const $=B*i-w;let H=$;for(;H<0;)H+=c;const q=Math.min(t.inHeight,m+$);for(let J=0;J<t.outWidth;++J){const re=J*o-L;let ce=re;for(;ce<0;)ce+=h;const ue=Math.min(t.inWidth,y+re);let he=Number.NEGATIVE_INFINITY,de=-1;for(let le=F;le<_;le+=a){const ye=le-D;for(let pe=H;pe<q;pe+=c){const Ie=pe-$;for(let Se=ce;Se<ue;Se+=h){const Ee=Se-re,We=T.get(A,le,pe,Se,N);We>=he&&(he=We,de=ye*m*y+Ie*m+Ee)}}}n.set(de,A,E,B,J,N)}}}return n.toTensor()}maxPool3dBackprop(e,t,n,s){xe([t,n],"maxPool3dBackprop");const i=this.maxPool3dPositions(t,s),o=s.strideDepth,a=s.strideHeight,c=s.strideWidth,h=s.dilationDepth,d=s.dilationHeight,m=s.dilationWidth,y=s.effectiveFilterDepth,b=s.effectiveFilterHeight,w=s.effectiveFilterWidth,L=y-1-s.padInfo.front,T=w-1-s.padInfo.left,A=b-1-s.padInfo.top,N=Ze(t.shape,"float32"),E=this.bufferSync(i),D=this.bufferSync(e);for(let F=0;F<s.batchSize;++F)for(let _=0;_<s.inChannels;++_)for(let B=0;B<s.inDepth;++B)for(let $=0;$<s.inHeight;++$)for(let H=0;H<s.inWidth;++H){const q=B-L,J=$-A,re=H-T;let ce=0;for(let ue=0;ue<y;ue+=h){const he=(q+ue)/o;if(he<0||he>=s.outDepth||Math.floor(he)!==he)continue;for(let de=0;de<b;de+=d){const le=(J+de)/a;if(le<0||le>=s.outHeight||Math.floor(le)!==le)continue;for(let ye=0;ye<w;ye+=m){const pe=(re+ye)/c;if(pe<0||pe>=s.outWidth||Math.floor(pe)!==pe)continue;const Ie=y*b*w-1-E.get(F,he,le,pe,_),Se=ue*b*w+de*w+ye,Ee=Ie===Se?1:0;if(Ee===0)continue;const We=D.get(F,he,le,pe,_);ce+=We*Ee}}}N.set(ce,F,B,$,H,_)}return N.toTensor()}resizeBilinear(e,t,n,s){xe(e,"resizeBilinear");const[i,o,a,c]=e.shape,h=this.readSync(e.dataId),d=new Float32Array(we([i,t,n,c])),m=[s&&t>1?o-1:o,s&&n>1?a-1:a],y=[s&&t>1?t-1:t,s&&n>1?n-1:n];let b=0;const w=m[0]/y[0],L=m[1]/y[1];for(let T=0;T<i;T++)for(let A=0;A<t;A++){const N=w*A,E=Math.floor(N),D=N-E,F=Math.min(o-1,Math.ceil(N)),_=T*e.strides[0]+E*e.strides[1],B=T*e.strides[0]+F*e.strides[1];for(let $=0;$<n;$++){const H=L*$,q=Math.floor(H),J=H-q,re=Math.min(a-1,Math.ceil(H)),ce=_+q*e.strides[2],ue=B+q*e.strides[2],he=_+re*e.strides[2],de=B+re*e.strides[2];for(let le=0;le<c;le++){const ye=h[ce+le],pe=h[ue+le],Ie=h[he+le],Se=h[de+le],Ee=ye+(Ie-ye)*J,We=pe+(Se-pe)*J,Oe=Ee+(We-Ee)*D;d[b++]=Oe}}}return en(d,[i,t,n,c])}resizeBilinearBackprop(e,t,n){xe([e,t],"resizeBilinearBackprop");const[s,i,o,a]=t.shape,[,c,h]=e.shape,d=new Float32Array(s*i*o*a),m=[n&&c>1?i-1:i,n&&h>1?o-1:o],y=[n&&c>1?c-1:c,n&&h>1?h-1:h],b=m[0]/y[0],w=m[1]/y[1],L=this.readSync(e.dataId);let T=0;for(let A=0;A<s;A++){const N=A*t.strides[0];for(let E=0;E<c;E++){const D=E*b,F=Math.floor(D),_=Math.min(Math.ceil(D),i-1),B=N+F*t.strides[1],$=N+_*t.strides[1],H=D-F,q=1-H;for(let J=0;J<h;J++){const re=J*w,ce=Math.floor(re),ue=Math.min(Math.ceil(re),o-1),he=re-ce,de=1-he,le=B+ce*t.strides[2],ye=B+ue*t.strides[2],pe=$+ce*t.strides[2],Ie=$+ue*t.strides[2],Se=q*de,Ee=q*he,We=H*de,Oe=H*he;for(let $e=0;$e<a;$e++){const Ye=L[T++];d[le+$e]+=Ye*Se,d[ye+$e]+=Ye*Ee,d[pe+$e]+=Ye*We,d[Ie+$e]+=Ye*Oe}}}}return Va(d,[s,o,i,a],t.dtype)}resizeNearestNeighbor(e,t,n,s){xe(e,"resizeNearestNeighbor");const[i,o,a,c]=e.shape,h=this.readSync(e.dataId),d=new Float32Array(i*t*n*c),m=[s&&t>1?o-1:o,s&&n>1?a-1:a],y=[s&&t>1?t-1:t,s&&n>1?n-1:n],b=m[0]/y[0],w=m[1]/y[1];let L=0;for(let T=0;T<i;T++){const A=T*e.strides[0];for(let N=0;N<t;N++){const E=b*N,D=Math.min(o-1,s?Math.round(E):Math.floor(E)),F=A+D*e.strides[1];for(let _=0;_<n;_++){const B=w*_,$=Math.min(a-1,s?Math.round(B):Math.floor(B)),H=F+$*e.strides[2];for(let q=0;q<c;q++){const J=h[H+q];d[L++]=J}}}}return en(d,[i,t,n,c],e.dtype)}resizeNearestNeighborBackprop(e,t,n){xe([e,t],"resizeNearestNeighborBackprop");const[s,i,o,a]=t.shape,[,c,h]=e.shape,d=new Float32Array(s*i*o*a),m=this.readSync(e.dataId),y=[n&&c>1?i-1:i,n&&h>1?o-1:o],b=[n&&c>1?c-1:c,n&&h>1?h-1:h],w=y[0]/b[0],L=y[1]/b[1],T=1/w,A=1/L,N=Math.ceil(T)*2+2,E=Math.ceil(A)*2+2;for(let D=0;D<s;D++){const F=D*t.strides[0];for(let _=0;_<i;_++){const B=F+_*t.strides[1],$=Math.floor(_*T),H=Math.floor($-N/2);for(let q=0;q<o;q++){const J=B+q*t.strides[2],re=Math.floor(q*A),ce=Math.floor(re-E/2);for(let ue=0;ue<a;ue++){let he=0;for(let de=0;de<N;de++){const le=de+H;if(le<0||le>=c)continue;const ye=F+le*e.strides[1],pe=le*w,Ie=Math.min(i-1,n?Math.round(pe):Math.floor(pe));if(_!==Ie)continue;for(let Se=0;Se<E;Se++){const Ee=Se+ce;if(Ee<0||Ee>=h)continue;const We=ye+Ee*e.strides[2],Oe=Ee*L,$e=Math.min(o-1,n?Math.round(Oe):Math.floor(Oe));q===$e&&(he+=m[We+ue])}}d[J+ue]=he}}}}return Va(d,t.shape,t.dtype)}localResponseNormalization4D(e,t,n,s,i){xe(e,"localResponseNormalization4D");const o=e.shape[3],a=o-1,c=this.readSync(e.dataId),h=e.size,d=new Float32Array(h);function m(y){const b=y%o;let w=y-b+Math.max(0,b-t);const L=y-b+Math.min(b+t,a);let T=0;for(;w<=L;w++){const A=c[w];T+=A*A}return T}for(let y=0;y<h;y++){const b=m(y),w=c[y]*Math.pow(n+s*b,-i);d[y]=w}return Va(d,e.shape)}LRNGrad(e,t,n,s,i,o,a){xe(e,"LRNGrad");const c=e.shape[3],h=this.readSync(e.dataId),d=this.readSync(t.dataId),m=this.readSync(n.dataId),y=new Float32Array(e.size),b=e.size;for(let w=0;w<b;w++){const L=w%c,T=w-L+Math.max(0,L-s),A=w-L+Math.min(c,L+s+1);let N=0;for(let E=T;E<A;E++)N+=Math.pow(d[E],2);N=o*N+i;for(let E=T;E<A;E++){let D=-2*o*a*d[E]*m[w]/N;w===E&&(D+=Math.pow(N,-a)),D*=h[w],y[E]+=D}}return Va(y,e.shape)}multinomial(e,t,n,s){xe(e,"multinomial");const i=t?e:Wo(e),o=i.shape[0],a=i.shape[1],c=ct([o,n],"int32"),h=this.readSync(c.dataId),d=this.readSync(i.dataId);for(let m=0;m<o;++m){const y=m*a,b=new Float32Array(a-1);b[0]=d[y];for(let T=1;T<b.length;++T)b[T]=b[T-1]+d[y+T];const w=Pa(s.toString()),L=m*n;for(let T=0;T<n;++T){const A=w();h[L+T]=b.length;for(let N=0;N<b.length;N++)if(A<b[N]){h[L+T]=N;break}}}return c}oneHot(e,t,n,s){xe(e,"oneHot");const i=new Float32Array(e.size*t);i.fill(s);const o=this.readSync(e.dataId);for(let a=0;a<e.size;++a)o[a]>=0&&o[a]<t&&(i[a*t+o[a]]=n);return Wr(i,[e.size,t],"int32")}nonMaxSuppression(e,t,n,s,i){xe(e,"nonMaxSuppression");const o=this.readSync(e.dataId),a=this.readSync(t.dataId);return VH(o,a,n,s,i)}depthToSpace(e,t,n){k(n==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${n}`),k(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`);const s=e.shape[0],i=e.shape[1],o=e.shape[2],a=e.shape[3],c=i*t,h=o*t,d=a/(t*t),m=this.readSync(e.dataId),y=new Float32Array(s*c*h*d);let b=0;for(let w=0;w<s;++w)for(let L=0;L<c;++L){const T=Math.floor(L/t),A=L%t;for(let N=0;N<h;++N){const E=Math.floor(N/t),D=N%t,F=(A*t+D)*d;for(let _=0;_<d;++_){const B=_+F,$=B+a*(E+o*(T+i*w));y[b++]=m[$]}}}return Va(y,[s,c,h,d])}broadcastedBinaryOp(e,t,n,s){const i=tt(e.shape,t.shape),o=Ze(i,n),a=this.readSync(e.dataId),c=this.readSync(t.dataId),h=Ro(e.shape,i),d=Ro(t.shape,i),m=o.values;if(h.length+d.length===0)for(let y=0;y<m.length;++y)m[y]=s(a[y%a.length],c[y%c.length]);else{const y=this.bufferSync(e),b=this.bufferSync(t);for(let w=0;w<m.length;++w){const L=o.indexToLoc(w),T=L.slice(-e.rank);h.forEach(D=>T[D]=0);const A=y.locToIndex(T),N=L.slice(-t.rank);d.forEach(D=>N[D]=0);const E=b.locToIndex(N);m[w]=s(a[A],c[E])}}return o.toTensor()}split(e,t,n){return YH(e,t,n)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}cropAndResize(e,t,n,s,i,o){const[a,c,h,d]=e.shape,m=t.shape[0],[y,b]=s,w=Ze([m,y,b,d],"float32"),L=this.readSync(t.dataId),T=this.readSync(n.dataId),A=this.readSync(e.dataId),N=e.strides,E=w.strides;for(let D=0;D<m;D++){const F=D*4,_=L[F],B=L[F+1],$=L[F+2],H=L[F+3],q=T[D];if(q>=a)continue;const J=y>1?($-_)*(c-1)/(y-1):0,re=b>1?(H-B)*(h-1)/(b-1):0;for(let ce=0;ce<y;ce++){const ue=y>1?_*(c-1)+ce*J:.5*(_+$)*(c-1);if(ue<0||ue>c-1){for(let he=0;he<b;he++)for(let de=0;de<d;de++){const le=de+he*E[2]+ce*E[1]+D*E[0];w.values[le]=o}continue}if(i==="bilinear"){const he=Math.floor(ue),de=Math.ceil(ue),le=ue-he;for(let ye=0;ye<b;ye++){const pe=b>1?B*(h-1)+ye*re:.5*(B+H)*(h-1);if(pe<0||pe>h-1){for(let We=0;We<d;We++){const Oe=We+ye*E[2]+ce*E[1]+D*E[0];w.values[Oe]=o}continue}const Ie=Math.floor(pe),Se=Math.ceil(pe),Ee=pe-Ie;for(let We=0;We<d;We++){let Oe=We+Ie*N[2]+he*N[1]+q*N[0];const $e=A[Oe];Oe=We+Se*N[2]+he*N[1]+q*N[0];const Ye=A[Oe];Oe=We+Ie*N[2]+de*N[1]+q*N[0];const et=A[Oe];Oe=We+Se*N[2]+de*N[1]+q*N[0];const bt=A[Oe],Jt=$e+(Ye-$e)*Ee,un=et+(bt-et)*Ee;Oe=We+ye*E[2]+ce*E[1]+D*E[0],w.values[Oe]=Jt+(un-Jt)*le}}}else for(let he=0;he<b;++he){const de=b>1?B*(h-1)+he*re:.5*(B+H)*(h-1);if(de<0||de>h-1){for(let pe=0;pe<d;pe++){const Ie=pe+he*E[2]+ce*E[1]+D*E[0];w.values[Ie]=o}continue}const le=Math.round(de),ye=Math.round(ue);for(let pe=0;pe<d;pe++){const Ie=pe+le*N[2]+ye*N[1]+q*N[0],Se=pe+he*E[2]+ce*E[1]+D*E[0];w.values[Se]=A[Ie]}}}}return w.toTensor()}sparseToDense(e,t,n,s){const{sliceRank:i,numUpdates:o,sliceSize:a,strides:c,outputSize:h}=Da(t,e,n),d=!1;return this.scatter(e,t,n,h,a,o,i,c,s,d)}gatherND(e,t){const n=t.shape,s=n[n.length-1],[i,o,a,c]=vd(e,t);if(o===0)return en([],i,e.dtype);const h=new vr([o,a],e.dtype),d=this.readSync(t.dataId),m=this.readSync(e.dataId);for(let y=0;y<o;y++){const b=[];let w=0;for(let L=0;L<s;L++){const T=d[y*s+L];w+=T*c[L],b.push(T)}if(w<0||w>=e.size/a)throw new Error(`Invalid indices: ${b} does not index into ${e.shape}`);for(let L=0;L<a;L++)h.values[y*a+L]=m[w*a+L]}return h.toTensor().reshape(i)}scatterND(e,t,n){const{sliceRank:s,numUpdates:i,sliceSize:o,strides:a,outputSize:c}=Da(t,e,n),h=Ne(0),d=!0;return this.scatter(e,t,n,c,o,i,s,a,h,d)}fill(e,t,n){n=n||Ta(t);const s=wo(n,we(e));return s.fill(t),_s().makeTensor(s,e,n,this)}onesLike(e){if(e.dtype==="string")throw new Error("onesLike is not supported for string tensors");return this.fill(e.shape,1,e.dtype)}zerosLike(e){const t=wo(e.dtype,we(e.shape));return this.makeOutput(t,e.shape,e.dtype)}linspace(e,t,n){return dw(e,t,n)}scatter(e,t,n,s,i,o,a,c,h,d){const m=[s/i,i],y=this.readSync(e.dataId),b=this.readSync(t.dataId);if(s===0)return en([],n,t.dtype);const w=new vr(m,t.dtype);w.values.fill(this.readSync(h.dataId)[0]);for(let L=0;L<o;L++){const T=[];let A=0;for(let N=0;N<a;N++){const E=y[L*a+N];T.push(E),A+=E*c[N]}if(A<0||A>=s/i)throw new Error(`Invalid indices: ${T} does not index into ${n}`);for(let N=0;N<i;N++)d?w.values[A*i+N]+=b[L*i+N]:w.values[A*i+N]=t.rank===0?b[0]:b[L*i+N]}return w.toTensor().reshape(n)}}function a0(e){const t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}const XH=e=>{const{x:t}=e.inputs,n=e.backend;let s=new Float32Array(we(t.shape));if(t.dtype!=="complex64"){const i=n.data.get(t.dataId).values;s=a0(i)}else{const i=n.data.get(t.dataId),o=i.complexTensorInfos.real,a=i.complexTensorInfos.imag,c=n.data.get(o.dataId).values,h=n.data.get(a.dataId).values;for(let d=0;d<c.length;d++){const m=c[d],y=h[d];s[d]=Math.hypot(m,y)}}return n.makeOutput(s,t.shape,"float32")},JH={kernelName:ge,backendName:"cpu",kernelFunc:XH};function Ho(e){return(t,n,s,i,o)=>{const a=tt(t,n),c=a.length,h=Ot(a),d=we(a),m=bn(o,d),y=t.length,b=n.length,w=Ot(t),L=Ot(n),T=Ro(t,a),A=Ro(n,a);if(T.length+A.length===0)for(let N=0;N<m.length;++N)m[N]=e(s[N%s.length],i[N%i.length]);else for(let N=0;N<m.length;++N){const E=va(N,c,h),D=E.slice(-y);T.forEach($=>D[$]=0);const F=ei(D,y,w),_=E.slice(-b);A.forEach($=>_[$]=0);const B=ei(_,b,L);m[N]=e(s[F],i[B])}return[m,a]}}function di(e){const{inputs:t,backend:n}=e,{real:s,imag:i}=t,o=n.data.get(s.dataId).values,a=n.data.get(i.dataId).values,c=n.makeTensorInfo(s.shape,"complex64"),h=n.data.get(c.dataId);return h.complexTensorInfos={real:n.makeTensorInfo(s.shape,"float32",o),imag:n.makeTensorInfo(i.shape,"float32",a)},c}const ZH={kernelName:Ug,backendName:"cpu",kernelFunc:di};function rc(e){const{inputs:t,backend:n}=e,{x:s}=t;return n.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const QH={kernelName:yl,backendName:"cpu",kernelFunc:rc};function eu(e){const{inputs:t,backend:n}=e,{input:s}=t,i=n.data.get(s.dataId).complexTensorInfos.real,o=n.data.get(i.dataId).values;return n.makeTensorInfo(i.shape,i.dtype,o)}const eq={kernelName:ly,backendName:"cpu",kernelFunc:eu};function tu(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{dtype:o}=s;if(o==="complex64"){if(i.dtype==="complex64")return rc({inputs:{x:i},backend:n});const a=ct(i.shape),c=tu({inputs:{x:i},backend:n,attrs:{dtype:"float32"}}),h=di({inputs:{real:c,imag:a},backend:n});return a.dispose(),n.disposeIntermediateTensorInfo(c),h}if(i.dtype==="complex64"){const a=eu({inputs:{input:i},backend:n}),c=tu({inputs:{x:a},backend:n,attrs:{dtype:o}});return n.disposeIntermediateTensorInfo(a),c}if(!Dy(i.dtype,o)){const a=rc({inputs:{x:i},backend:n});return{dataId:a.dataId,shape:a.shape,dtype:o}}if(o==="int32"){const a=n.data.get(i.dataId).values,c=Int32Array.from(a);return n.makeTensorInfo(i.shape,"int32",c)}if(o==="bool"){const a=n.data.get(i.dataId).values,c=Ar([0],i.dtype),[h,d]=Ho((m,y)=>m!==y?1:0)(i.shape,[],a,c,"bool");return n.makeTensorInfo(d,"bool",h)}throw new Error(`Error in Cast: failed to cast ${i.dtype} to ${o}`)}const tq={kernelName:al,backendName:"cpu",kernelFunc:tu};function oc(e,t,n,s){return n==null?({inputs:i,backend:o})=>{const{a,b:c}=i,h=o;xe([a,c],e);const d=h.data.get(a.dataId).values,m=h.data.get(c.dataId).values,y=s||a.dtype,[b,w]=t(a.shape,c.shape,d,m,y);return h.makeTensorInfo(w,y,b)}:({inputs:i,backend:o})=>{const{a,b:c}=i,h=o;if(a.dtype==="complex64"||c.dtype==="complex64"){const d=tu({inputs:{x:a},backend:h,attrs:{dtype:"complex64"}}),m=h.data.get(d.dataId),y=m.complexTensorInfos.real,b=m.complexTensorInfos.imag,w=h.data.get(y.dataId).values,L=h.data.get(b.dataId).values,T=tu({inputs:{x:c},backend:h,attrs:{dtype:"complex64"}}),A=h.data.get(T.dataId),N=A.complexTensorInfos.real,E=A.complexTensorInfos.imag,D=h.data.get(N.dataId).values,F=h.data.get(E.dataId).values,[_,B,$]=n(a.shape,c.shape,w,L,D,F),H=h.makeTensorInfo($,"float32",_),q=h.makeTensorInfo($,"float32",B),J=di({inputs:{real:H,imag:q},backend:h});return h.disposeIntermediateTensorInfo(d),h.disposeIntermediateTensorInfo(T),h.disposeIntermediateTensorInfo(H),h.disposeIntermediateTensorInfo(q),J}else{const d=h.data.get(a.dataId).values,m=h.data.get(c.dataId).values,y=s||a.dtype,[b,w]=t(a.shape,c.shape,d,m,y);return h.makeTensorInfo(w,y,b)}}}function mS(e){return(t,n,s,i,o,a)=>{const c=tt(t,n),h=we(c),d=c.length,m=Ot(c),y=bn("float32",h),b=bn("float32",h),w=Ro(t,c),L=Ro(n,c),T=er(s,i),A=er(o,a),N=t.length,E=Ot(t),D=n.length,F=Ot(n);if(w.length+L.length===0)for(let _=0;_<y.length;_++){const B=_%T.length,$=_%A.length,H=e(T[B*2],T[B*2+1],A[$*2],A[$*2+1]);y[_]=H.real,b[_]=H.imag}else for(let _=0;_<y.length;_++){const B=va(_,d,m),$=B.slice(-N);w.forEach(ce=>$[ce]=0);const H=ei($,N,E),q=B.slice(-D);L.forEach(ce=>q[ce]=0);const J=ei(q,D,F),re=e(T[H*2],T[H*2+1],A[J*2],A[J*2+1]);y[_]=re.real,b[_]=re.imag}return[y,b,c]}}const c0=Ho((e,t)=>e+t),nq=mS((e,t,n,s)=>({real:e+n,imag:t+s})),l0=oc(Te,c0,nq),sq={kernelName:Te,backendName:"cpu",kernelFunc:l0};function ac(e){return(t,n,s)=>{const i=bn(n,t.length);for(let o=0;o<t.length;++o)i[o]=e(t[o],s);return i}}function xt(e,t,n){return({inputs:s,attrs:i,backend:o})=>{const{x:a}=s;if(xe(a,e),a.dtype==="string"||n==="string")throw new Error("unaryKernelFunc does not support string input/output");const c=o,h=c.data.get(a.dataId).values,d=we(a.shape),m=n||a.dtype,y=wo(m,d);for(let b=0;b<d;++b)y[b]=t(h[b],i);return c.makeTensorInfo(a.shape,m,y)}}function cc(e,t,n){return({inputs:s,attrs:i,backend:o})=>{const{x:a}=s;if(xe(a,e),a.dtype==="string"||n==="string")throw new Error("unaryKernelFunc does not support string input/output");const c=o,h=c.data.get(a.dataId).values,d=n||a.dtype,m=t(h,d,i);return c.makeTensorInfo(a.shape,d,m)}}const h0=ac(e=>Math.ceil(e)),iq=cc(cl,h0),rq={kernelName:cl,backendName:"cpu",kernelFunc:iq};const u0=ac(e=>Math.exp(e)),oq=cc(pl,u0),aq={kernelName:pl,backendName:"cpu",kernelFunc:oq};const d0=ac(e=>Math.expm1(e)),cq=cc(ml,d0),lq={kernelName:ml,backendName:"cpu",kernelFunc:cq};const p0=ac(e=>Math.floor(e)),hq=cc(fl,p0),uq={kernelName:fl,backendName:"cpu",kernelFunc:hq};const m0=ac(e=>Math.log(e)),dq=cc(Sl,m0),pq={kernelName:Sl,backendName:"cpu",kernelFunc:dq};function f0(e,t,n,s){const i=bn(s,we(n));for(let o=0;o<i.length;++o){const a=o*t;let c=e[a];for(let h=0;h<t;++h){const d=e[a+h];d>c&&(c=d)}i[o]=c}return i}const g0=Ho((e,t)=>e*t),mq=mS((e,t,n,s)=>({real:e*n-t*s,imag:e*s+t*n})),y0=oc(Al,g0,mq),fq={kernelName:Al,backendName:"cpu",kernelFunc:y0};const b0=ac(e=>1/Math.sqrt(e)),gq=cc(Rl,b0),yq={kernelName:Rl,backendName:"cpu",kernelFunc:gq};function w0(e,t,n,s,i){const o=rb(s,t,n),a=we(n),c=Ot(s);if(o){const d=ob(t,c);return e.subarray(d,d+a)}const h=bn(i,a);for(let d=0;d<a;++d){const m=n.length,y=Ot(n),b=va(d,m,y),w=b.map((T,A)=>T+t[A]),L=ei(w,s.length,c);h[d]=e[L]}return h}function fS(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{begin:o,size:a}=s;xe(i,"slice");const[c,h]=Rd(i,o,a);ib(i,c,h);const d=n.data.get(i.dataId).values,m=w0(d,c,h,i.shape,i.dtype);return n.makeTensorInfo(h,i.dtype,m)}const bq={kernelName:rd,backendName:"cpu",kernelFunc:fS};const L0=Ho((e,t)=>e-t),wq=mS((e,t,n,s)=>({real:e-n,imag:t-s})),S0=oc(Wl,L0,wq),Lq={kernelName:Wl,backendName:"cpu",kernelFunc:S0};function gS(e,t,n,s,i){const o=t.length,a=we(t),c=Ot(t),h=Ot(i),d=bn(n,we(i));for(let m=0;m<a;++m){const y=va(m,o,c),b=new Array(y.length);for(let L=0;L<b.length;L++)b[L]=y[s[L]];const w=ei(b,o,h);d[w]=e[m]}return d}function I0(e,t,n,s){const i=gt(t,n)[0],o=[1,n[0],1];for(let L=0;L<i;L++)o[0]*=n[L];o[1]=n[i];for(let L=i+1;L<n.length;L++)o[2]*=n[L];const a={},c=new Int32Array(n[i]),h=new vr(o,s,e),d=[],m=o[0]===1&&o[2]===1;for(let L=0;L<n[i];L++){let T;if(m)T=e[L].toString();else{const A=[];for(let N=0;N<o[0];N++)for(let E=0;E<o[2];E++)A.push(h.get(N,L,E));T=A.join(",")}if(a[T]!==void 0)c[L]=a[T];else{const A=Object.keys(a).length;a[T]=A,c[L]=A,d.push(L)}}const y=o.slice();y[1]=Object.keys(a).length;const b=new vr(y,s);d.forEach((L,T)=>{for(let A=0;A<o[0];A++)for(let N=0;N<o[2];N++)b.set(h.get(A,L,N),A,T,N)});const w=n.slice();return w[i]=y[1],{outputValues:b.values,outputShape:w,indices:c}}var Sq=Object.freeze({__proto__:null,simpleAbsImpl:a0,addImpl:c0,ceilImpl:h0,expImpl:u0,expm1Impl:d0,floorImpl:p0,logImpl:m0,maxImpl:f0,multiplyImpl:g0,rsqrtImpl:b0,sliceImpl:w0,subImpl:L0,transposeImpl:gS,uniqueImpl:I0});const Iq="2.6.0";hb("cpu",()=>new KH,1);const xq=xt(fe,e=>Math.acos(e)),Tq={kernelName:fe,backendName:"cpu",kernelFunc:xq};const Aq=xt(Ae,e=>Math.acosh(e)),vq={kernelName:Ae,backendName:"cpu",kernelFunc:Aq};const Nq=xt(Dn,e=>Math.asin(e)),Cq={kernelName:Dn,backendName:"cpu",kernelFunc:Nq};const Rq=xt(An,e=>Math.asinh(e)),Oq={kernelName:An,backendName:"cpu",kernelFunc:Rq};const Eq=xt(vn,e=>Math.atan(e)),Dq={kernelName:vn,backendName:"cpu",kernelFunc:Eq};const kq=xt(Zs,e=>Math.atanh(e)),Fq={kernelName:Zs,backendName:"cpu",kernelFunc:kq};function yS(e,t,n,s,i,o){const a=i.strideHeight,c=i.strideWidth,h=i.dilationHeight,d=i.dilationWidth,m=i.effectiveFilterHeight,y=i.effectiveFilterWidth,b=i.padInfo.top,w=i.padInfo.left,L=o==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,T=Ze(i.outShape,n),A=T.values,N=i.outShape[1]*i.outShape[2]*i.outShape[3],E=i.outShape[2]*i.outShape[3],D=i.outShape[3];for(let F=0;F<i.batchSize;++F){const _=F*N,B=F*s[0];for(let $=0;$<i.inChannels;++$)for(let H=0;H<i.outHeight;++H){const q=H*a-b,J=Math.max(0,q),re=Math.min(i.inHeight,m+q),ce=_+H*E;for(let ue=0;ue<i.outWidth;++ue){const he=ue*c-w,de=Math.max(0,he),le=Math.min(i.inWidth,y+he);let ye=L,pe=0,Ie=0;for(let Ee=J;Ee<re;Ee+=h){const We=B+Ee*s[1];for(let Oe=de;Oe<le;Oe+=d){const $e=We+Oe*s[2],Ye=e[$e+$];o==="max"&&Ye>ye?ye=Ye:o==="avg"&&(pe+=Ye,Ie++)}if(isNaN(ye))break}const Se=ce+ue*D+$;A[Se]=o==="avg"?pe/Ie:ye}}}return T}function x0(e,t,n,s,i=!1,o=!1){const a=Ze(s.outShape,"int32"),c=s.strideHeight,h=s.strideWidth,d=s.dilationHeight,m=s.dilationWidth,y=s.effectiveFilterHeight,b=s.effectiveFilterWidth,w=s.padInfo.top,L=s.padInfo.left,T=Ze(t,n,e);for(let A=0;A<s.batchSize;++A)for(let N=0;N<s.inChannels;++N)for(let E=0;E<s.outHeight;++E){const D=E*c-w;let F=D;for(;F<0;)F+=d;const _=Math.min(s.inHeight,y+D);for(let B=0;B<s.outWidth;++B){const $=B*h-L;let H=$;for(;H<0;)H+=m;const q=Math.min(s.inWidth,b+$);let J=Number.NEGATIVE_INFINITY,re=-1;for(let ce=F;ce<_;ce+=d){const ue=ce-D;for(let he=H;he<q;he+=m){const de=he-$,le=T.get(A,ce,he,N);le>J&&(J=le,i?re=o?((A*s.inHeight+ce)*s.inWidth+he)*s.inChannels+N:(ce*s.inWidth+he)*s.inChannels+N:re=ue*b+de)}}a.set(re,A,E,B,N)}}return a}function _q(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;xe(i,"avgPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:h}=s,d=1;k(rn(a,d),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${d}'`);const m=Fn(i.shape,o,a,d,c,h);let y;if(m.filterWidth===1&&m.filterHeight===1&&ot(m.inShape,m.outShape))y=rc({inputs:{x:i},backend:n});else{const b=n.data.get(i.dataId).values,w=Ot(i.shape),L=yS(b,i.shape,i.dtype,w,m,"avg");y=n.makeTensorInfo(m.outShape,i.dtype,L.values)}return y}const Wq={kernelName:Qs,backendName:"cpu",kernelFunc:_q};function $q(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o}=t,a=o;xe([i,o],"avgPoolBackprop");const{filterSize:c,strides:h,pad:d}=s,m=Fn(a.shape,c,h,1,d),y=m.strideHeight,b=m.strideWidth,w=m.filterHeight,L=m.filterWidth,T=m.dilationHeight,A=m.dilationWidth,N=m.effectiveFilterHeight,E=m.effectiveFilterWidth,D=E-1-m.padInfo.left,F=N-1-m.padInfo.top,_=Ze(a.shape,"float32"),B=1/(w*L),$=n.data.get(i.dataId).values,H=Ze(i.shape,"float32",$);for(let q=0;q<m.batchSize;++q)for(let J=0;J<m.inChannels;++J)for(let re=0;re<m.inHeight;++re)for(let ce=0;ce<m.inWidth;++ce){const ue=re-F,he=ce-D;let de=0;for(let le=0;le<N;le+=T){const ye=(ue+le)/y;if(ye<0||ye>=m.outHeight||Math.floor(ye)!==ye)continue;for(let pe=0;pe<E;pe+=A){const Ie=(he+pe)/b;if(Ie<0||Ie>=m.outWidth||Math.floor(Ie)!==Ie)continue;const Se=H.get(q,ye,Ie,J);de+=Se}}_.set(de*B,q,re,ce,J)}return n.makeTensorInfo(_.shape,_.dtype,_.values)}const Uq={kernelName:ya,backendName:"cpu",kernelFunc:$q};function Bq(e){const{inputs:t,backend:n,attrs:s}=e,{x:i,scale:o,offset:a,mean:c,variance:h}=t;k(c.shape.length===h.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),k(a==null||c.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),k(o==null||c.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),xe([i,c,h,o,a],"batchNorm");let{varianceEpsilon:d}=s;d==null&&(d=.001);const m=n.data.get(i.dataId).values,y=n.data.get(c.dataId).values,b=n.data.get(h.dataId).values,w=o?n.data.get(o.dataId).values:new Float32Array([1]),L=a?n.data.get(a.dataId).values:new Float32Array([0]),T=new Float32Array(m.length),A=L.length,N=w.length,E=b.length,D=y.length;let F=0,_=0,B=0,$=0;for(let H=0;H<m.length;++H)T[H]=L[F++]+(m[H]-y[_++])*w[B++]/Math.sqrt(b[$++]+d),F>=A&&(F=0),_>=D&&(_=0),B>=N&&(B=0),$>=E&&($=0);return n.makeTensorInfo(i.shape,i.dtype,T)}const Mq={kernelName:gl,backendName:"cpu",kernelFunc:Bq};const Pq=xt(ll,(e,t)=>{const n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e}),zq={kernelName:ll,backendName:"cpu",kernelFunc:Pq};function im(e){const{inputs:t,backend:n}=e,{input:s}=t,i=n.data.get(s.dataId).complexTensorInfos.imag,o=n.data.get(i.dataId).values;return n.makeTensorInfo(i.shape,i.dtype,o)}const Gq={kernelName:Kg,backendName:"cpu",kernelFunc:im};function qr(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{shape:o}=s,a=we(i.shape),c=md(o,a),h=we(c);k(a===h,()=>`The new shape (${c}) has ${h} elements and the old shape (${i.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`),n.incRef(i.dataId);const d=n.data.get(i.dataId);if(d.complexTensorInfos!=null){const m=d.complexTensorInfos.real,y=d.complexTensorInfos.imag;m.shape=c,y.shape=c}return{dataId:i.dataId,shape:c,dtype:i.dtype}}const Vq={kernelName:Nl,backendName:"cpu",kernelFunc:qr};function nu(e){const{inputs:t,backend:n,attrs:s}=e,{axis:i}=s,o=gt(i,t[0].shape)[0];let a=Er(t.map(w=>w.shape),o);if(we(a)===0)return n.makeTensorInfo(a,t[0].dtype,[]);const c=t.filter(w=>we(w.shape)>0);if(c.length===1)return c[0];const h=c.map(w=>w.shape);if(xb(h,o),c[0].dtype==="complex64"){const w=c.map(E=>eu({inputs:{input:E},backend:n})),L=c.map(E=>im({inputs:{input:E},backend:n})),T=nu({inputs:w,backend:n,attrs:{axis:i}}),A=nu({inputs:L,backend:n,attrs:{axis:i}}),N=di({inputs:{real:T,imag:A},backend:n});return w.forEach(E=>n.disposeIntermediateTensorInfo(E)),L.forEach(E=>n.disposeIntermediateTensorInfo(E)),n.disposeIntermediateTensorInfo(T),n.disposeIntermediateTensorInfo(A),N}const d=c.map(w=>{const L=we(w.shape.slice(o)),T=[-1,L];return qr({inputs:{x:w},backend:n,attrs:{shape:T}})});a=Er(d.map(w=>w.shape),1);const m=bn(c[0].dtype,we(a));if(d[0].shape[0]===1){let w=0;d.forEach(L=>{const T=n.data.get(L.dataId).values,A=we(L.shape);m.set(T,w),w+=A})}else{let w=0;d.forEach(L=>{const T=n.data.get(L.dataId).values;let A=0;for(let N=0;N<L.shape[0];++N){const E=N*a[1]+w;for(let D=0;D<L.shape[1];++D)m[E+D]=T[A++]}w+=L.shape[1]})}const y=Er(c.map(w=>w.shape),o),b=n.makeTensorInfo(y,t[0].dtype,m);return d.forEach(w=>n.disposeIntermediateTensorInfo(w)),b}const Yq={kernelName:qu,backendName:"cpu",kernelFunc:nu};const Hq=xt(ba,e=>Math.cos(e)),qq={kernelName:ba,backendName:"cpu",kernelFunc:Hq};const jq=xt(hl,e=>Math.cosh(e)),Kq={kernelName:hl,backendName:"cpu",kernelFunc:jq};const Xq={kernelName:ju,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,filter:i}=e,{strides:o,pad:a,dilations:c}=n,h=t,d=h.data.get(s.dataId).values,m=s.shape.length,y=h.data.get(i.dataId).values,b=i.shape.length,{batchSize:w,inHeight:L,inWidth:T,inChannels:A,outHeight:N,outWidth:E,padInfo:D,strideHeight:F,strideWidth:_,filterHeight:B,filterWidth:$,dilationHeight:H,dilationWidth:q,outShape:J}=Fd(s.shape,i.shape,o,a,"NHWC",c),re=we(J),ce=J.length,ue=wo(s.dtype,re);for(let de=0;de<w;++de)for(let le=0;le<N;++le){const ye=le*F-D.top;for(let pe=0;pe<E;++pe){const Ie=pe*_-D.left;for(let Se=0;Se<A;++Se){let Ee=Number.MIN_SAFE_INTEGER;for(let Oe=0;Oe<B;++Oe){const $e=ye+Oe*H;if($e>=0&&$e<L)for(let Ye=0;Ye<$;++Ye){const et=Ie+Ye*q;if(et>=0&&et<T){const bt=ei([de,$e,et,Se],m,Ot(s.shape)),Jt=ei([Oe,Ye,Se],b,Ot(i.shape)),un=d[bt]+y[Jt];un>Ee&&(Ee=un)}}}const We=ei([de,le,pe,Se],ce,Ot(J));ue[We]=Ee}}}const he=h.write(Ar(ue,s.dtype),J,s.dtype);return{dataId:he,shape:J,dtype:s.dtype}}};const Jq={kernelName:Xu,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,filter:i,dy:o}=e,{strides:a,pad:c,dilations:h}=n,d=t,m=ys(s.shape,d.data.get(s.dataId).values),y=ys(i.shape,d.data.get(i.dataId).values),{batchSize:b,inHeight:w,inWidth:L,inChannels:T,outHeight:A,outWidth:N,padInfo:E,strideHeight:D,strideWidth:F,filterHeight:_,filterWidth:B,dilationHeight:$,dilationWidth:H,outShape:q}=Fd(s.shape,i.shape,a,c,"NHWC",h);k(o.rank===q.length,()=>`Error in ${Xu}, dy must have the same rank as output ${q.length}, but got ${o.rank}`);const J=ys(q,d.data.get(o.dataId).values),re=_y(i.shape,i.dtype);for(let ue=0;ue<b;++ue)for(let he=0;he<A;++he){const de=he*D-E.top;for(let le=0;le<N;++le){const ye=le*F-E.left;for(let pe=0;pe<T;++pe){let Ie=Number.MIN_SAFE_INTEGER,Se=0,Ee=0;for(let We=0;We<_;++We){const Oe=de+We*$;if(Oe>=0&&Oe<w)for(let $e=0;$e<B;++$e){const Ye=ye+$e*H;if(Ye>=0&&Ye<L){const et=m[ue][Oe][Ye][pe]+y[We][$e][pe];et>Ie&&(Ie=et,Se=We,Ee=$e)}}}re[Se][Ee][pe]+=J[ue][he][le][pe]}}}const ce=d.write(Ar(re,s.dtype),i.shape,i.dtype);return{dataId:ce,shape:i.shape,dtype:i.dtype}}};const Zq={kernelName:Ku,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,filter:i,dy:o}=e,{strides:a,pad:c,dilations:h}=n,d=t,m=ys(s.shape,d.data.get(s.dataId).values),y=ys(i.shape,d.data.get(i.dataId).values),{batchSize:b,inHeight:w,inWidth:L,inChannels:T,outHeight:A,outWidth:N,padInfo:E,strideHeight:D,strideWidth:F,filterHeight:_,filterWidth:B,dilationHeight:$,dilationWidth:H,outShape:q}=Fd(s.shape,i.shape,a,c,"NHWC",h);k(o.rank===q.length,()=>`Error in ${Ku}, dy must have the same rank as output ${q.length}, but got ${o.rank}`);const J=ys(q,d.data.get(o.dataId).values),re=_y(s.shape,s.dtype);for(let ue=0;ue<b;++ue)for(let he=0;he<A;++he){const de=he*D-E.top;for(let le=0;le<N;++le){const ye=le*F-E.left;for(let pe=0;pe<T;++pe){let Ie=Number.MIN_SAFE_INTEGER,Se=de<0?0:de,Ee=ye<0?0:ye;for(let We=0;We<_;++We){const Oe=de+We*$;if(Oe>=0&&Oe<w)for(let $e=0;$e<B;++$e){const Ye=ye+$e*H;if(Ye>=0&&Ye<L){const et=m[ue][Oe][Ye][pe]+y[We][$e][pe];et>Ie&&(Ie=et,Se=Oe,Ee=Ye)}}}re[ue][Se][Ee][pe]+=J[ue][he][le][pe]}}}const ce=d.write(Ar(re,s.dtype),s.shape,s.dtype);return{dataId:ce,shape:s.shape,dtype:s.dtype}}};const Qq=Ho((e,t)=>e/t),e4=oc(wa,Qq),bS={kernelName:wa,backendName:"cpu",kernelFunc:e4};const t4=xt(ul,e=>e>=0?e:Math.exp(e)-1),n4={kernelName:ul,backendName:"cpu",kernelFunc:t4};const s4=rw,i4=ow,r4=aw,o4=cw,a4=lw,c4=hw,l4=xt(dl,e=>{const t=Math.sign(e),n=Math.abs(e),s=1/(1+s4*n);return t*(1-((((c4*s+a4)*s+o4)*s+r4)*s+i4)*s*Math.exp(-n*n))}),h4={kernelName:dl,backendName:"cpu",kernelFunc:l4};function T0(e,t,n){const s=e.shape,i=s[0],o=s[1],a=n.data.get(e.dataId),c=a.complexTensorInfos.real,h=a.complexTensorInfos.imag,d=[i,o],m=we(d),y=bn("float32",m),b=bn("float32",m);for(let A=0;A<i;A++){const N=fS({inputs:{x:c},backend:n,attrs:{begin:[A,0],size:[1,o]}}),E=fS({inputs:{x:h},backend:n,attrs:{begin:[A,0],size:[1,o]}}),D=di({inputs:{real:N,imag:E},backend:n}),{real:F,imag:_}=u4(D,t,n),B=er(F,_);for(let $=0;$<o;$++){const H=uw(B,$);y[A*o+$]=H.real,b[A*o+$]=H.imag}n.disposeIntermediateTensorInfo(N),n.disposeIntermediateTensorInfo(E),n.disposeIntermediateTensorInfo(D)}const w=n.makeTensorInfo(d,"float32",y),L=n.makeTensorInfo(d,"float32",b),T=di({inputs:{real:w,imag:L},backend:n});return n.disposeIntermediateTensorInfo(w),n.disposeIntermediateTensorInfo(L),T}function u4(e,t,n){const s=we(e.shape),i=n.data.get(e.dataId),o=n.data.get(i.complexTensorInfos.real.dataId).values,a=n.data.get(i.complexTensorInfos.imag.dataId).values;if(d4(s)){const c=wS(o,a,s,t,n),h=[e.shape[0],e.shape[1]];if(t){const d=n.makeTensorInfo(h,"float32",c.real),m=n.makeTensorInfo(h,"float32",c.imag),y=n.makeTensorInfo([],"float32",zx(s,"float32")),b=rc({inputs:{x:y},backend:n}),w=bS.kernelFunc({inputs:{a:d,b:y},backend:n}),L=bS.kernelFunc({inputs:{a:m,b},backend:n}),T=n.data.get(w.dataId).values,A=n.data.get(L.dataId).values;return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(w),n.disposeIntermediateTensorInfo(L),{real:T,imag:A}}return c}else{const c=er(o,a),h=p4(c,s,t);return kA(h)}}function d4(e){return(e&e-1)===0}function wS(e,t,n,s,i){if(n===1)return{real:e,imag:t};const o=er(e,t),a=n/2,c=FA(o),h=c.real,d=c.imag,m=[h.length],y=i.makeTensorInfo(m,"float32",h),b=i.makeTensorInfo(m,"float32",d),w=di({inputs:{real:y,imag:b},backend:i}),L=_A(o),T=L.real,A=L.imag,N=[T.length],E=i.makeTensorInfo(N,"float32",T),D=i.makeTensorInfo(N,"float32",A),F=di({inputs:{real:E,imag:D},backend:i}),_=wS(h,d,a,s,i),B=_.real,$=_.imag,H=[B.length],q=i.makeTensorInfo(H,"float32",B),J=i.makeTensorInfo(H,"float32",$),re=di({inputs:{real:q,imag:J},backend:i}),ce=wS(T,A,a,s,i),ue=ce.real,he=ce.imag,de=[ue.length],le=i.makeTensorInfo(de,"float32",ue),ye=i.makeTensorInfo(de,"float32",he),pe=di({inputs:{real:le,imag:ye},backend:i}),Ie=$A(n,s),Se=[Ie.real.length],Ee=i.makeTensorInfo(Se,"float32",Ie.real),We=i.makeTensorInfo(Se,"float32",Ie.imag),Oe=di({inputs:{real:Ee,imag:We},backend:i}),$e=y0({inputs:{a:Oe,b:pe},backend:i}),Ye=l0({inputs:{a:re,b:$e},backend:i}),et=S0({inputs:{a:re,b:$e},backend:i}),bt=eu({inputs:{input:Ye},backend:i}),Jt=eu({inputs:{input:et},backend:i}),un=im({inputs:{input:Ye},backend:i}),hs=im({inputs:{input:et},backend:i}),Ht=nu({inputs:[bt,Jt],backend:i,attrs:{axis:0}}),$n=nu({inputs:[un,hs],backend:i,attrs:{axis:0}}),pi=i.data.get(Ht.dataId).values,vs=i.data.get($n.dataId).values;return i.disposeIntermediateTensorInfo(y),i.disposeIntermediateTensorInfo(b),i.disposeIntermediateTensorInfo(w),i.disposeIntermediateTensorInfo(E),i.disposeIntermediateTensorInfo(D),i.disposeIntermediateTensorInfo(F),i.disposeIntermediateTensorInfo(q),i.disposeIntermediateTensorInfo(J),i.disposeIntermediateTensorInfo(re),i.disposeIntermediateTensorInfo(le),i.disposeIntermediateTensorInfo(ye),i.disposeIntermediateTensorInfo(pe),i.disposeIntermediateTensorInfo(Ee),i.disposeIntermediateTensorInfo(We),i.disposeIntermediateTensorInfo(Oe),i.disposeIntermediateTensorInfo($e),i.disposeIntermediateTensorInfo(Ye),i.disposeIntermediateTensorInfo(et),i.disposeIntermediateTensorInfo(bt),i.disposeIntermediateTensorInfo(un),i.disposeIntermediateTensorInfo(Jt),i.disposeIntermediateTensorInfo(hs),i.disposeIntermediateTensorInfo(Ht),i.disposeIntermediateTensorInfo($n),{real:pi,imag:vs}}function p4(e,t,n){const s=new Float32Array(t*2);for(let i=0;i<t;i++){let o=0,a=0;for(let c=0;c<t;c++){const h=UA(i*c,t,n),d=uw(e,c);o+=d.real*h.real-d.imag*h.imag,a+=d.real*h.imag+d.imag*h.real}n&&(o/=t,a/=t),WA(s,o,a,i)}return s}function m4(e){const{inputs:t,backend:n}=e,{input:s}=t,i=we(s.shape),o=s.shape[s.shape.length-1],a=i/o,c=qr({inputs:{x:s},backend:n,attrs:{shape:[a,o]}}),h=T0(c,!1,n),d=qr({inputs:{x:h},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),d}const f4={kernelName:Vg,backendName:"cpu",kernelFunc:m4};const g4={kernelName:Ju,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,i=n,o=bn(s.dtype,we(s.shape)),[a,c,h,d]=s.shape,m=i.data.get(s.dataId).values;for(let b=0;b<a;b++){const w=b*h*c*d;for(let L=0;L<c;L++){const T=L*(h*d);for(let A=0;A<h;A++){const N=A*d;for(let E=0;E<d;E++){const D=[a,L,A,E],F=D[2],_=Math.round(h-F),B=w+T+N+E;let $=m[B];if(_>=0&&_<h){const H=_*d,q=w+T+H+E;$=m[q]}o[B]=$}}}}const y=i.write(o,s.shape,s.dtype);return{dataId:y,shape:s.shape,dtype:s.dtype}}};function y4(e){const{inputs:t,backend:n}=e,{input:s}=t,i=we(s.shape),o=s.shape[s.shape.length-1],a=i/o,c=qr({inputs:{x:s},backend:n,attrs:{shape:[a,o]}}),h=T0(c,!0,n),d=qr({inputs:{x:h},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),d}const b4={kernelName:jg,backendName:"cpu",kernelFunc:y4};const w4=xt(bl,e=>Number.isFinite(e)?1:0,"bool"),L4={kernelName:bl,backendName:"cpu",kernelFunc:w4};const S4=xt(wl,e=>Math.abs(e)===Infinity?1:0,"bool"),I4={kernelName:wl,backendName:"cpu",kernelFunc:S4};const x4=xt(Ll,e=>Number.isNaN(e)?1:0,"bool"),T4={kernelName:Ll,backendName:"cpu",kernelFunc:x4};const A4=xt(Il,e=>Math.log1p(e)),v4={kernelName:Il,backendName:"cpu",kernelFunc:A4};const N4=xt(Zu,e=>e?0:1,"bool"),C4={kernelName:Zu,backendName:"cpu",kernelFunc:N4};const R4={kernelName:xl,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{reductionIndices:i,keepDims:o}=t,a=n;let c=s.shape;const h=c.length,d=gt(i,c);let m=d;const y=kn(m,h);let b=a.data.get(s.dataId).values;if(y!=null){const D=new Array(h);for(let F=0;F<D.length;F++)D[F]=c[y[F]];b=gS(b,c,s.dtype,y,D),m=ws(m.length,h),c=D}xe(s,"max"),ts("max",m,h);const[w,L]=Rn(c,m),T=we(L),A=f0(b,T,w,s.dtype),N=a.write(A,w,s.dtype);let E=w;if(o){const D=On(w,d);E=D}return{dataId:N,shape:E,dtype:s.dtype}}};function O4(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;xe(i,"maxPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:h}=s,d=1;k(rn(a,d),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${d}'`);const m=Fn(i.shape,o,a,d,c,h);let y;if(m.filterWidth===1&&m.filterHeight===1&&ot(m.inShape,m.outShape))y=rc({inputs:{x:i},backend:n});else{const b=n.data.get(i.dataId).values,w=Ot(i.shape),L=yS(b,i.shape,i.dtype,w,m,"max");y=n.makeTensorInfo(m.outShape,i.dtype,L.values)}return y}const E4={kernelName:Tl,backendName:"cpu",kernelFunc:O4};function D4(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o,output:a}=t,c=o;xe([o,a],"maxPoolBackprop");const{filterSize:h,strides:d,pad:m,dimRoundingMode:y}=s,b=Fn(c.shape,h,d,1,m,y),w=n.data.get(c.dataId).values,L=Ze(b.outShape,c.dtype,x0(w,c.shape,c.dtype,b).values),T=b.strideHeight,A=b.strideWidth,N=b.dilationHeight,E=b.dilationWidth,D=b.effectiveFilterHeight,F=b.effectiveFilterWidth,_=F-1-b.padInfo.left,B=D-1-b.padInfo.top,$=Ze(c.shape,"float32"),H=n.data.get(i.dataId).values,q=Ze(i.shape,"float32",H);for(let J=0;J<b.batchSize;++J)for(let re=0;re<b.inChannels;++re)for(let ce=0;ce<b.inHeight;++ce)for(let ue=0;ue<b.inWidth;++ue){const he=ce-B,de=ue-_;let le=0;for(let ye=0;ye<D;ye+=N){const pe=(he+ye)/T;if(pe<0||pe>=b.outHeight||Math.floor(pe)!==pe)continue;for(let Ie=0;Ie<F;Ie+=E){const Se=(de+Ie)/A;if(Se<0||Se>=b.outWidth||Math.floor(Se)!==Se)continue;const Ee=D*F-1-L.get(J,pe,Se,re),We=ye*F+Ie,Oe=Ee===We?1:0;if(Oe===0)continue;const $e=q.get(J,pe,Se,re);le+=$e*Oe}}$.set(le,J,ce,ue,re)}return n.makeTensorInfo($.shape,$.dtype,$.values)}const k4={kernelName:Qu,backendName:"cpu",kernelFunc:D4};function F4(e,t,n,s,i){const o=Ot(t),a=yS(e,t,n,o,i,"max"),c=x0(e,t,n,i,!0,s);return[a.values,c.values]}const _4={kernelName:ed,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{filterSize:i,strides:o,pad:a,includeBatchInIndex:c}=t,h=n;xe(s,"MaxPoolWithArgmax");const d=h.data.get(s.dataId).values,m=Fn(s.shape,i,o,[1,1],a),[y,b]=F4(d,s.shape,s.dtype,c,m),w=h.write(y,m.outShape,s.dtype),L=h.write(b,m.outShape,s.dtype);return[{dataId:w,shape:m.outShape,dtype:s.dtype},{dataId:L,shape:m.outShape,dtype:"int32"}]}};const W4=dp,$4={kernelName:nd,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{boxes:s,scores:i}=e,{maxOutputSize:o,iouThreshold:a,scoreThreshold:c,padToMaxOutputSize:h}=n,d=t;xe(s,"NonMaxSuppressionPadded");const m=d.data.get(s.dataId).values,y=d.data.get(i.dataId).values,{selectedIndices:b,validOutputs:w}=W4(m,y,o,a,c,h);return[b,w]}};const U4=pp,B4={kernelName:sd,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{boxes:s,scores:i}=e,{maxOutputSize:o,iouThreshold:a,scoreThreshold:c,softNmsSigma:h}=n,d=t;xe(s,"NonMaxSuppressionWithScore");const m=d.data.get(s.dataId).values,y=d.data.get(i.dataId).values,b=o,w=a,L=c,T=h,{selectedIndices:A,selectedScores:N}=U4(m,y,b,w,L,T);return[A,N]}};const M4=Ho((e,t)=>e!==t?1:0),P4=oc(td,M4,null,"bool"),z4={kernelName:td,backendName:"cpu",kernelFunc:P4};function G4(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{paddings:o,constantValue:a}=s;xe(i,"pad");const c=o.map((E,D)=>E[0]+i.shape[D]+E[1]),h=o.map(E=>E[0]),d=n.data.get(i.dataId).values,m=we(i.shape),y=i.shape.length,b=Ot(i.shape),w=we(c),L=c.length,T=Ot(c),A=bn(i.dtype,w);a!==0&&A.fill(a);for(let E=0;E<m;E++){const D=va(E,y,b),F=D.map((B,$)=>B+h[$]),_=ei(F,L,T);A[_]=d[E]}const N=n.write(A,c,i.dtype);return{dataId:N,shape:c,dtype:i.dtype}}const A0={kernelName:id,backendName:"cpu",kernelFunc:G4};const V4=xt(vl,e=>1/e),Y4={kernelName:vl,backendName:"cpu",kernelFunc:V4};const H4={kernelName:hd,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,{radians:i,fillValue:o,center:a}=t,c=n,h=bn(s.dtype,we(s.shape)),[d,m,y,b]=s.shape,[w,L]=nw(a,m,y),T=255,A=Math.sin(i),N=Math.cos(i),E=c.data.get(s.dataId).values;for(let F=0;F<d;F++){const _=F*y*m*b;for(let B=0;B<m;B++){const $=B*(y*b);for(let H=0;H<y;H++){const q=H*b;for(let J=0;J<b;J++){const re=[d,B,H,J],ce=re[2],ue=re[1];let he=(ce-w)*N-(ue-L)*A,de=(ce-w)*A+(ue-L)*N;he=Math.round(he+w),de=Math.round(de+L);let le=o;if(typeof o!="number"&&(J===3?le=T:le=o[J]),he>=0&&he<y&&de>=0&&de<m){const pe=de*(y*b),Ie=he*b,Se=_+pe+Ie+J;le=E[Se]}const ye=_+$+q+J;h[ye]=le}}}}const D=c.write(h,s.shape,s.dtype);return{dataId:D,shape:s.shape,dtype:s.dtype}}};const q4=xt(Cl,e=>{const t=Math.floor(e);return e-t<.5?Math.floor(e):e-t>.5?Math.ceil(e):t%2===0?t:t+1}),j4={kernelName:Cl,backendName:"cpu",kernelFunc:q4};const K4=fp,X4=gp,J4=xt(Ol,e=>e>=0?X4*e:K4*(Math.exp(e)-1)),Z4={kernelName:Ol,backendName:"cpu",kernelFunc:J4};const Q4=xt(kl,e=>1/(1+Math.exp(-e))),ej={kernelName:kl,backendName:"cpu",kernelFunc:Q4};const tj=xt(Dl,e=>e<0?-1:e>0?1:0),nj={kernelName:Dl,backendName:"cpu",kernelFunc:tj};const sj=xt(La,e=>Math.sin(e)),ij={kernelName:La,backendName:"cpu",kernelFunc:sj};const rj=xt(El,e=>Math.sinh(e)),oj={kernelName:El,backendName:"cpu",kernelFunc:rj};const aj=11920928955078125e-23,v0=Math.log(aj)+2,cj=xt(Fl,e=>{const t=e>-v0,n=e<v0,s=Math.exp(e);let i;return n?i=s:t?i=e:i=Math.log(1+s),i}),lj={kernelName:Fl,backendName:"cpu",kernelFunc:cj};function N0(e){const{inputs:t,attrs:n,backend:s}=e,{x:i}=t,{perm:o}=n;xe(i,"transpose");const a=i.shape.length,c=new Array(a);for(let y=0;y<c.length;y++)c[y]=i.shape[o[y]];const h=s.data.get(i.dataId).values,d=gS(h,i.shape,i.dtype,o,c),m=s.write(d,c,i.dtype);return{dataId:m,shape:c,dtype:i.dtype}}const hj={kernelName:Ul,backendName:"cpu",kernelFunc:N0};function uj(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{blockShape:o,paddings:a}=s;xe([i],"spaceToBatchND");const c=we(o),h=[[0,0]];h.push(...a);for(let B=1+o.length;B<i.shape.length;++B)h.push([0,0]);const d=A0.kernelFunc({inputs:{x:i},backend:n,attrs:{paddings:h,constantValue:0}}),m=Ah(d.shape,o,c,!1),y=vh(m.length,o.length,!1),b=Nh(d.shape,o,c,!1),w={x:d},L={shape:m},T=qr({inputs:w,backend:n,attrs:L}),A={x:T},N={perm:y},E=N0({inputs:A,backend:n,attrs:N}),D={x:E},F={shape:b},_=qr({inputs:D,backend:n,attrs:F});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(T),n.disposeIntermediateTensorInfo(E),_}const dj={kernelName:od,backendName:"cpu",kernelFunc:uj};const pj=xt(_l,e=>Math.sqrt(e)),mj={kernelName:_l,backendName:"cpu",kernelFunc:pj};const fj={kernelName:ad,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{const{x:n}=e,s=t;xe(n,"square");const i=s.data.get(n.dataId).values,o=new Float32Array(i.length);for(let c=0;c<i.length;++c){const h=i[c];o[c]=h*h}const a=s.write(o,n.shape,n.dtype);return{dataId:a,shape:n.shape,dtype:n.dtype}}};const gj=Ho((e,t)=>{const n=e-t;return n*n}),yj=oc(Sa,gj),bj={kernelName:Sa,backendName:"cpu",kernelFunc:yj};const wj=xt(Bl,(e,t)=>{const n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),Lj={kernelName:Bl,backendName:"cpu",kernelFunc:wj};const Sj=xt(Ia,e=>Math.tan(e)),Ij={kernelName:Ia,backendName:"cpu",kernelFunc:Sj};const xj=xt($l,e=>Math.tanh(e)),Tj={kernelName:$l,backendName:"cpu",kernelFunc:xj};function Aj(e){const{inputs:t,attrs:n,backend:s}=e,{axis:i}=n,{x:o}=t;xe(o,"unique");const a=s.data.get(o.dataId).values,{outputValues:c,outputShape:h,indices:d}=I0(a,i,o.shape,o.dtype);return[s.makeTensorInfo(h,o.dtype,c),s.makeTensorInfo([d.length],"int32",d)]}const vj={kernelName:cd,backendName:"cpu",kernelFunc:Aj};const Nj=[JH,Tq,vq,sq,Cq,Oq,Dq,Fq,Wq,Uq,Mq,tq,rq,zq,ZH,Yq,qq,Kq,Xq,Zq,Jq,bS,n4,h4,aq,lq,f4,g4,uq,QH,b4,Gq,L4,I4,T4,pq,v4,C4,E4,k4,_4,R4,fq,$4,B4,z4,A0,eq,Y4,Vq,H4,j4,yq,Z4,ej,nj,ij,oj,bq,lj,dj,mj,fj,bj,Lj,Lq,Ij,Tj,hj,vj];for(const e of Nj)dd(e);const qo={},LS={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Cj(e,t){qo[e]=t}function Wi(e){if(!(e in qo)){const n=Oj(e);if(n!==null)qo[e]=n;else return console.log("Could not get context for WebGL version",e),null}const t=qo[e];return t.isContextLost()?(delete qo[e],Wi(e)):(t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.BLEND),t.disable(t.DITHER),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SAMPLE_COVERAGE),t.enable(t.SCISSOR_TEST),t.enable(t.CULL_FACE),t.cullFace(t.BACK),qo[e])}function Rj(e){if(typeof OffscreenCanvas!="undefined"&&e===2)return new OffscreenCanvas(300,150);if(typeof document!="undefined")return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}function Oj(e){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");const t=Rj(e);return t.addEventListener("webglcontextlost",n=>{n.preventDefault(),delete qo[e]},!1),e===1?t.getContext("webgl",LS)||t.getContext("experimental-webgl",LS):t.getContext("webgl2",LS)}var su;(function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"})(su||(su={}));var As;(function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"})(As||(As={}));var Sn;(function(e){e[e.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",e[e.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",e[e.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",e[e.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",e[e.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"})(Sn||(Sn={}));function iu(e,t){return[t,e]}function Ej(e,t){return e*t}function hee(e,t){return[t*4,e]}function ru(e){const t=we(e),n=Math.ceil(t/4);return pd(n)}function uee(e,t){if(e%t!==0)throw new Error(`unpackedSize (${e}) must be a multiple of ${t}`);return e/t}function dee(e,t,n){const s=e.length*n/4;if(t.length<s)throw new Error(`matrix length (${t.length}) must be >= ${s}`);let i=0;for(let o=0;o<e.length;o+=4)for(let a=0;a<n;a++)t[i++]=e[o+a]}function lc(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function Dj(e,t){const[n,s]=lc(e,t);return n*s*4}function SS(e,t){const n=e;let s,i,o,a,c,h,d,m,y,b;return C().getNumber("WEBGL_VERSION")===2?(s=n.R32F,i=n.R16F,o=n.RGBA16F,a=n.RGBA32F,c=n.RED,d=4,m=1,y=n.HALF_FLOAT,b=n.FLOAT):(s=e.RGBA,i=e.RGBA,o=e.RGBA,a=n.RGBA,c=e.RGBA,d=4,m=4,y=t!=null?t.HALF_FLOAT_OES:null,b=e.FLOAT),h=e.RGBA,{internalFormatFloat:s,internalFormatHalfFloat:i,internalFormatPackedHalfFloat:o,internalFormatPackedFloat:a,textureFormatFloat:c,downloadTextureFormat:h,downloadUnpackNumChannels:d,defaultNumChannels:m,textureTypeHalfFloat:y,textureTypeFloat:b}}function Re(e,t){const n=t();return C().getBool("DEBUG")&&kj(e),n}function kj(e){const t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+$j(e,t))}const Fj=596e-10,_j=65504;function Wj(e){return!!(C().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||Fj<Math.abs(e)&&Math.abs(e)<_j)}function $j(e,t){switch(t){case e.NO_ERROR:return"NO_ERROR";case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return`Unknown error code ${t}`}}function rm(e,t){return ar(e,()=>e.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function Uj(e,t){const n=ar(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(Re(e,()=>e.shaderSource(n,t)),Re(e,()=>e.compileShader(n)),e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw console.log(e.getShaderInfoLog(n)),new Error("Failed to compile vertex shader.");return n}function Bj(e,t){const n=ar(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(Re(e,()=>e.shaderSource(n,t)),Re(e,()=>e.compileShader(n)),e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw Pj(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}const Mj=/ERROR: [0-9]+:([0-9]+):/g;function Pj(e,t){const n=Mj.exec(t);if(n==null){console.log(`Couldn't parse line number in error: ${t}`),console.log(e);return}const s=+n[1],i=e.split(`
`),o=i.length.toString().length+2,a=i.map((y,b)=>bo((b+1).toString(),o)+y);let c=0;for(let y=0;y<a.length;y++)c=Math.max(a[y].length,c);const h=a.slice(0,s-1),d=a.slice(s-1,s),m=a.slice(s);console.log(h.join(`
`)),console.log(t.split(`
`)[0]),console.log(`%c ${bo(d[0],c)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(m.join(`
`))}function zj(e){return ar(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function Gj(e,t){if(Re(e,()=>e.linkProgram(t)),e.getProgramParameter(t,e.LINK_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function IS(e,t){if(Re(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function Vj(e,t){const n=ar(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Re(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),Re(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function Yj(e,t){const n=ar(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Re(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),Re(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function pee(){return C().getNumber("WEBGL_VERSION")===2?1:4}function Hj(e){return ar(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function qj(e,t){const n=C().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){const s=`[${e}x${t}]`;throw new Error("Requested texture size "+s+" is invalid.")}if(e>n||t>n){const s=`[${e}x${t}]`,i=`[${n}x${n}]`;throw new Error("Requested texture size "+s+" greater than WebGL maximum on this browser / GPU "+i+".")}}function jj(e){return ar(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function C0(e,t,n,s,i,o,a){const c=e.getAttribLocation(t,n);return c===-1?!1:(Re(e,()=>e.bindBuffer(e.ARRAY_BUFFER,s)),Re(e,()=>e.vertexAttribPointer(c,i,e.FLOAT,!1,o,a)),Re(e,()=>e.enableVertexAttribArray(c)),!0)}function Kj(e,t,n){O0(e,n),Re(e,()=>e.activeTexture(e.TEXTURE0+n)),Re(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function mee(e,t){O0(e,t),Re(e,()=>e.activeTexture(e.TEXTURE0+t)),Re(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function Xj(e,t,n){return ar(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function Jj(e,t,n){return e.getUniformLocation(t,n)}function Zj(e,t,n,s){Re(e,()=>Kj(e,t,s)),Re(e,()=>e.uniform1i(n,s))}function fee(e){Re(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),Re(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),Re(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function xS(e,t,n){Re(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),Re(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function R0(e,t){Re(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),Re(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function om(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Qj(e,t))}function Qj(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}function ar(e,t,n){const s=Re(e,()=>t());if(s==null)throw new Error(n);return s}function O0(e,t){const n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,s=t+e.TEXTURE0;if(s<e.TEXTURE0||s>n){const i=`[gl.TEXTURE0, gl.TEXTURE${n}]`;throw new Error(`textureUnit must be in ${i}.`)}}function hc(e,t=2){return we(e.slice(0,e.length-t))}function uc(e){if(e.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function TS(e){let t=[1,1,1];const n=e.length===0||e.length===1&&e[0]===1;return n||(t=[hc(e),...uc(e)]),t}function eK(e,t=!1){let n=C().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(n=n*2,e=e.map((i,o)=>o>=e.length-2?Oy(e[o]):e[o]),e.length===1&&(e=[2,e[0]])),e.length!==2){const i=Ir(e);e=i.newShape}let s=we(e);if(e.length<=1&&s<=n)return[1,s];if(e.length===2&&e[0]<=n&&e[1]<=n)return e;if(e.length===3&&e[0]*e[1]<=n&&e[2]<=n)return[e[0]*e[1],e[2]];if(e.length===3&&e[0]<=n&&e[1]*e[2]<=n)return[e[0],e[1]*e[2]];if(e.length===4&&e[0]*e[1]*e[2]<=n&&e[3]<=n)return[e[0]*e[1]*e[2],e[3]];if(e.length===4&&e[0]<=n&&e[1]*e[2]*e[3]<=n)return[e[0],e[1]*e[2]*e[3]];if(t){const i=hc(e);let o=2,a=2;return e.length&&([o,a]=uc(e)),s=i*(o/2)*(a/2),pd(s).map(c=>c*2)}return pd(s)}function am(e){return e%2===0}function cm(e,t){if(e=e.slice(-2),t=t.slice(-2),ot(e,t))return!0;if(!e.length||!t.length)return!0;if(e[0]===0||e[1]===0||t[0]===0||t[1]===0)return!0;if(e.length!==t.length){const n=e.slice(-1)[0],s=t.slice(-1)[0];if(n===s)return!0;if(am(n)&&am(s)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&am(e[0])&&am(t[0])}let lm,hm;function tK(e){if(lm==null){const t=Wi(e);lm=t.getParameter(t.MAX_TEXTURE_SIZE)}return lm}function gee(){lm=null}function yee(){hm=null}function nK(e){if(hm==null){const t=Wi(e);hm=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,hm)}function sK(e){if(e===0)return 0;let t;const n=Wi(e);return zs(n,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:zs(n,"EXT_disjoint_timer_query")?t=1:t=0,t}function zs(e,t){const n=e.getExtension(t);return n!=null}function E0(e){try{const t=Wi(e);if(t!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function iK(e){if(e===0)return!1;const t=Wi(e);if(e===1){if(!zs(t,"OES_texture_float"))return!1}else if(!zs(t,"EXT_color_buffer_float"))return!1;const n=AS(t);return n}function rK(e){if(e===0)return!1;const t=Wi(e);if(e===1){if(!zs(t,"OES_texture_float"))return!1;if(!zs(t,"WEBGL_color_buffer_float"))return!1}else{if(zs(t,"EXT_color_buffer_float"))return AS(t);const s="EXT_color_buffer_half_float";if(zs(t,s)){const i=t.getExtension(s);return oK(t,i)}return!1}const n=AS(t);return n}function AS(e){const t=SS(e),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n);const s=1,i=1;e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,s,i,0,t.textureFormatFloat,t.textureTypeFloat,null);const o=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,o),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);const a=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(o),a}function oK(e,t){const n=SS(e,t),s=e.createTexture();e.bindTexture(e.TEXTURE_2D,s);const i=1,o=1;e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,i,o,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);const a=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,a),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const c=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(s),e.deleteFramebuffer(a),c}function aK(e){if(e!==2)return!1;const t=Wi(e),n=t.fenceSync!=null;return n}function ou(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{n!=null&&k(n.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the WebGL backend.`)})}const Ge=C();Ge.registerFlag("HAS_WEBGL",()=>Ge.getNumber("WEBGL_VERSION")>0),Ge.registerFlag("WEBGL_VERSION",()=>E0(2)?2:E0(1)?1:0),Ge.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1),Ge.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>Ge.get("WEBGL_VERSION")===2),Ge.registerFlag("WEBGL_CPU_FORWARD",()=>!0),Ge.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1),Ge.registerFlag("WEBGL_PACK",()=>Ge.getBool("HAS_WEBGL")),Ge.registerFlag("WEBGL_PACK_NORMALIZATION",()=>Ge.getBool("WEBGL_PACK")),Ge.registerFlag("WEBGL_PACK_CLIP",()=>Ge.getBool("WEBGL_PACK")),Ge.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>!1),Ge.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>Ge.getBool("WEBGL_PACK")),Ge.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>Ge.getBool("WEBGL_PACK")),Ge.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>Ge.getBool("WEBGL_PACK")),Ge.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>Ge.getBool("WEBGL_PACK")),Ge.registerFlag("WEBGL_PACK_REDUCE",()=>Ge.getBool("WEBGL_PACK")),Ge.registerFlag("WEBGL_LAZILY_UNPACK",()=>Ge.getBool("WEBGL_PACK")),Ge.registerFlag("WEBGL_CONV_IM2COL",()=>Ge.getBool("WEBGL_PACK")),Ge.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>tK(Ge.getNumber("WEBGL_VERSION"))),Ge.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>nK(Ge.getNumber("WEBGL_VERSION"))),Ge.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{const e=Ge.getNumber("WEBGL_VERSION");return e===0?0:sK(e)}),Ge.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>Ge.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!Zx()),Ge.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>iK(Ge.getNumber("WEBGL_VERSION"))),Ge.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>Ge.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:Ge.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")),Ge.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>rK(Ge.getNumber("WEBGL_VERSION"))),Ge.registerFlag("WEBGL_FENCE_API_ENABLED",()=>aK(Ge.getNumber("WEBGL_VERSION"))),Ge.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>{const e=Ge.getBool("WEBGL_RENDER_FLOAT32_ENABLED");return e?4:0}),Ge.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",()=>-1,e=>{if(e<0&&e!==-1)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${e}.`)});const{simpleAbsImpl:cK,addImpl:lK,ceilImpl:hK,expImpl:uK,expm1Impl:dK,floorImpl:pK,logImpl:mK,maxImpl:fK,multiplyImpl:gK,rsqrtImpl:yK,sliceImpl:bK,subImpl:wK,transposeImpl:D0,uniqueImpl:LK}=Sq;class SK{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((i,o)=>`T${o}`);const n=[];this.variableNames.forEach(i=>{n.push(`float v${i} = get${i}AtOutCoords();`)});const s=this.variableNames.map(i=>`v${i}`).join(" + ");this.userCode=`
void main() {
${n.join(`
`)}
float result = ${s};
setOutput(result);
}
`}}class IK{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((i,o)=>`T${o}`);const n=[];this.variableNames.forEach(i=>{n.push(`vec4 v${i} = get${i}AtOutCoords();`)});const s=this.variableNames.map(i=>`v${i}`).join(" + ");this.userCode=`
void main() {
${n.join(`
`)}
vec4 result = ${s};
setOutput(result);
}
`}}class xK{constructor(e,t,n){this.variableNames=["A"];const{windowSize:s,batchSize:i,outSize:o}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[i,o];const a=t==="max"?">":"<",c=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${s};
int bestIndex = inOffset;
float bestValue = getA(batch, bestIndex);
for (int i = 0; i < ${s}; i++) {
int inIdx = ${c};
float candidate = getA(batch, inIdx);
if (candidate ${a} bestValue) {
bestValue = candidate;
bestIndex = inIdx;
}
}
setOutput(float(bestIndex));
}
`}}function k0(e,t){return["x","y","z","w","u","v"].slice(0,t).map(n=>`${e}.${n}`)}function ls(e,t){return t===1?[e]:k0(e,t)}function TK(e,t){if(e===1)return"rc";let n="";for(let s=0;s<e;s++)n+=t[s],s<e-1&&(n+=",");return n}function Wn(){let e,t,n,s,i,o,a,c,h,d;return C().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",n="out",s="in",i="texture",o="outputColor",a="out vec4 outputColor;",c=`
bool isnan_custom(float val) {
return (val > 0.0 || val < 0.0) ? false : val != 0.0;
}
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan_custom(val.x),
isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
}
#define isnan(value) isnan_custom(value)
`,h="",d=`
#define round(value) newRound(value)
int newRound(float value) {
return int(floor(value + 0.5));
}
ivec4 newRound(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
`):(e="",t="attribute",n="varying",s="varying",i="texture2D",o="gl_FragColor",a="",c=`
#define isnan(value) isnan_custom(value)
bool isnan_custom(float val) {
return (val > 0. || val < 1. || val == 0.) ? false : true;
}
bvec4 isnan_custom(vec4 val) {
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
}
`,h=`
uniform float INFINITY;
bool isinf(float val) {
return abs(val) == INFINITY;
}
bvec4 isinf(vec4 val) {
return equal(abs(val), vec4(INFINITY));
}
`,d=`
int round(float value) {
return int(floor(value + 0.5));
}
ivec4 round(vec4 value) {
return ivec4(floor(value + vec4(0.5)));
}
`),{version:e,attribute:t,varyingVs:n,varyingFs:s,texture2D:i,output:o,defineOutput:a,defineSpecialNaN:c,defineSpecialInf:h,defineRound:d}}function jo(e,t,n="index"){const s=Ot(t);return s.map((i,o)=>{const a=`int ${e[o]} = ${n} / ${i}`,c=o===s.length-1?`int ${e[o+1]} = ${n} - ${e[o]} * ${i}`:`index -= ${e[o]} * ${i}`;return`${a}; ${c};`}).join("")}function um(e){return e.length===1?`${e[0]}`:`vec${e.length}(${e.join(",")})`}function bee(e,t){if(e.length!==t.length)throw new Error(`Vectors to be dotted must be of the same length -got ${e.length} and ${t.length}`);const n=[],s=Math.floor(e.length/4),i=e.length%4;for(let o=0;o<s;o++){const a=e.slice(o*4,o*4+4),c=t.slice(o*4,o*4+4);n.push(`${um(a)}, ${um(c)}`)}if(i!==0){let o=e.slice(s*4),a=t.slice(s*4);o.length===1&&(o=o.map(c=>`float(${c})`),a=a.map(c=>`float(${c})`)),n.push(`${um(o)}, ${um(a)}`)}return n.map((o,a)=>`dot(${o})`).join("+")}function vS(e){const t=Ot(e).map(n=>n.toString());return`
int getFlatIndex(ivec3 coords) {
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
}
`}const F0=`
const float FLOAT_MAX = 1.70141184e38;
const float FLOAT_MIN = 1.17549435e-38;
lowp vec4 encode_float(highp float v) {
if (isnan(v)) {
return vec4(255, 255, 255, 255);
}
highp float av = abs(v);
if(av < FLOAT_MIN) {
return vec4(0.0, 0.0, 0.0, 0.0);
} else if(v > FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;
} else if(v < -FLOAT_MAX) {
return vec4(0.0, 0.0, 128.0, 255.0) / 255.0;
}
highp vec4 c = vec4(0,0,0,0);
highp float e = floor(log2(av));
highp float m = exp2(fract(log2(av))) - 1.0;
c[2] = floor(128.0 * m);
m -= c[2] / 128.0;
c[1] = floor(32768.0 * m);
m -= c[1] / 32768.0;
c[0] = floor(8388608.0 * m);
highp float ebias = e + 127.0;
c[3] = floor(ebias / 2.0);
ebias -= c[3] * 2.0;
c[2] += floor(ebias) * 128.0;
c[3] += 128.0 * step(0.0, -v);
return c / 255.0;
}
`;const{getBroadcastDims:_0}=pw;function AK(e,t,n,s){const i=[];e.forEach(L=>{const T=we(L.shapeInfo.logicalShape);L.shapeInfo.isUniform?i.push(`uniform float ${L.name}${T>1?`[${T}]`:""};`):(i.push(`uniform sampler2D ${L.name};`),i.push(`uniform int offset${L.name};`))});const o=i.join(`
`),a=e.map(L=>vK(L,t,s)).join(`
`),c=t.texShape,h=Wn(),d=RK(h);let m,y,b=DK(h);t.isPacked?(m=NK(t.logicalShape,c),y=EK(h)):(m=CK(t.logicalShape,c),y=OK(h)),s&&(b+=WK);const w=[b,d,y,o,m,a,n].join(`
`);return w}function dc(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return jK(e);case 1:return XK(e);case 2:return ZK(e);case 3:return e5(e);case 4:return n5(e);case 5:return s5(e);case 6:return i5(e);default:throw new Error(`${t.length}-D input sampling is not yet supported`)}}function W0(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return qK(e);case 1:return KK(e);case 2:return JK(e);case 3:return QK(e);default:return t5(e)}}function vK(e,t,n=!1){let s="";n?s+=W0(e):s+=dc(e);const i=e.shapeInfo.logicalShape,o=t.logicalShape;return i.length<=o.length&&(n?s+=r5(e,t):s+=o5(e,t)),s}function NK(e,t){switch(e.length){case 0:return $0();case 1:return $K(e,t);case 2:return YK(e,t);case 3:return BK(e,t);default:return PK(e,t)}}function CK(e,t){switch(e.length){case 0:return $0();case 1:return UK(e,t);case 2:return HK(e,t);case 3:return MK(e,t);case 4:return zK(e,t);case 5:return GK(e,t);case 6:return VK(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function RK(e){return`
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${e.texture2D}(textureSampler, uv).r;
}
`}function OK(e){return`
void setOutput(float val) {
${e.output} = vec4(val, 0, 0, 0);
}
`}function EK(e){return`
void setOutput(vec4 val) {
${e.output} = val;
}
`}function DK(e){const t=`${e.version}
precision highp float;
precision highp int;
precision highp sampler2D;
${e.varyingFs} vec2 resultUV;
${e.defineOutput}
const vec2 halfCR = vec2(0.5, 0.5);
struct ivec5
{
int x;
int y;
int z;
int w;
int u;
};
struct ivec6
{
int x;
int y;
int z;
int w;
int u;
int v;
};
uniform float NAN;
${e.defineSpecialNaN}
${e.defineSpecialInf}
${e.defineRound}
int imod(int x, int y) {
return x - y * (x / y);
}
int idiv(int a, int b, float sign) {
int res = a / b;
int mod = imod(a, b);
if (sign < 0. && mod != 0) {
res -= 1;
}
return res;
}
//Based on the work of Dave Hoskins
//https://www.shadertoy.com/view/4djSRW
#define HASHSCALE1 443.8975
float random(float seed){
vec2 p = resultUV * seed;
vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);
p3 += dot(p3, p3.yzx + 19.19);
return fract((p3.x + p3.y) * p3.z);
}
${kK}
${FK}
${_K}
`;return t}const kK=`
vec2 uvFromFlat(int texNumR, int texNumC, int index) {
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
vec2 packedUVfrom1D(int texNumR, int texNumC, int index) {
int texelIndex = index / 2;
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`,FK=`
vec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,
int texNumC, int row, int col) {
int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);
int texR = texelIndex / texNumC;
int texC = texelIndex - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`,_K=`
vec2 packedUVfrom3D(int texNumR, int texNumC,
int texelsInBatch, int texelsInLogicalRow, int b,
int row, int col) {
int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);
int texR = index / texNumC;
int texC = index - texR * texNumC;
return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);
}
`,WK=`
float getChannel(vec4 frag, vec2 innerDims) {
vec2 modCoord = mod(innerDims, 2.);
return modCoord.x == 0. ?
(modCoord.y == 0. ? frag.r : frag.g) :
(modCoord.y == 0. ? frag.b : frag.a);
}
float getChannel(vec4 frag, int dim) {
float modCoord = mod(float(dim), 2.);
return modCoord == 0. ? frag.r : frag.g;
}
`;function $0(){return`
int getOutputCoords() {
return 0;
}
`}function $K(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return n[0]===1?`
int getOutputCoords() {
return 2 * int(resultUV.x * ${n[1]}.0);
}
`:n[1]===1?`
int getOutputCoords() {
return 2 * int(resultUV.y * ${n[0]}.0);
}
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
return 2 * (resTexRC.x * ${n[1]} + resTexRC.y);
}
`}function UK(e,t){return t[0]===1?`
int getOutputCoords() {
return int(resultUV.x * ${t[1]}.0);
}
`:t[1]===1?`
int getOutputCoords() {
return int(resultUV.y * ${t[0]}.0);
}
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
return resTexRC.x * ${t[1]} + resTexRC.y;
}
`}function BK(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[2]/2),i=s*Math.ceil(e[1]/2);return`
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
int index = resTexRC.x * ${n[1]} + resTexRC.y;
int b = index / ${i};
index -= b * ${i};
int r = 2 * (index / ${s});
int c = imod(index, ${s}) * 2;
return ivec3(b, r, c);
}
`}function MK(e,t){const n=jo(["r","c","d"],e);return`
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${n}
return ivec3(r, c, d);
}
`}function PK(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[e.length-1]/2),i=s*Math.ceil(e[e.length-2]/2);let o=i,a="",c="b, r, c";for(let h=2;h<e.length-1;h++)o*=e[e.length-h-1],a=`
int b${h} = index / ${o};
index -= b${h} * ${o};
`+a,c=`b${h}, `+c;return`
ivec${e.length} getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
int index = resTexRC.x * ${n[1]} + resTexRC.y;
${a}
int b = index / ${i};
index -= b * ${i};
int r = 2 * (index / ${s});
int c = imod(index, ${s}) * 2;
return ivec${e.length}(${c});
}
`}function zK(e,t){const n=jo(["r","c","d","d2"],e);return`
ivec4 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${n}
return ivec4(r, c, d, d2);
}
`}function GK(e,t){const n=jo(["r","c","d","d2","d3"],e);return`
ivec5 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},
${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${n}
ivec5 outShape = ivec5(r, c, d, d2, d3);
return outShape;
}
`}function VK(e,t){const n=jo(["r","c","d","d2","d3","d4"],e);return`
ivec6 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
${n}
ivec6 result = ivec6(r, c, d, d2, d3, d4);
return result;
}
`}function YK(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(ot(e,t))return`
ivec2 getOutputCoords() {
return 2 * ivec2(resultUV.yx * vec2(${n[0]}, ${n[1]}));
}
`;const s=Math.ceil(e[1]/2);return`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${n[0]}, ${n[1]}));
int index = resTexRC.x * ${n[1]} + resTexRC.y;
int r = 2 * (index / ${s});
int c = imod(index, ${s}) * 2;
return ivec2(r, c);
}
`}function HK(e,t){return ot(e,t)?`
ivec2 getOutputCoords() {
return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
}
`:e[1]===1?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(index, 0);
}
`:e[0]===1?`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
return ivec2(0, index);
}
`:`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = resTexRC.x * ${t[1]} + resTexRC.y;
int r = index / ${e[1]};
int c = index - r * ${e[1]};
return ivec2(r, c);
}
`}function Ko(e){return`offset${e}`}function qK(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),s=Wn();return`
vec4 ${n}() {
return ${s.texture2D}(${t}, halfCR);
}
`}function jK(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`float ${n}() {return ${t};}`;const[s,i]=e.shapeInfo.texShape;if(s===1&&i===1)return`
float ${n}() {
return sampleTexture(${t}, halfCR);
}
`;const[o,a]=e.shapeInfo.texShape,c=Ko(t);return`
float ${n}() {
vec2 uv = uvFromFlat(${o}, ${a}, ${c});
return sampleTexture(${t}, uv);
}
`}function KK(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),s=e.shapeInfo.texShape,i=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],o=Wn();return`
vec4 ${n}(int index) {
vec2 uv = packedUVfrom1D(
${i[0]}, ${i[1]}, index);
return ${o.texture2D}(${t}, uv);
}
`}function XK(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`
float ${n}(int index) {
${pc(e)}
}
`;const s=e.shapeInfo.texShape,i=s[0],o=s[1];if(o===1&&i===1)return`
float ${n}(int index) {
return sampleTexture(${t}, halfCR);
}
`;const a=Ko(t);return o===1?`
float ${n}(int index) {
vec2 uv = vec2(0.5, (float(index + ${a}) + 0.5) / ${i}.0);
return sampleTexture(${t}, uv);
}
`:i===1?`
float ${n}(int index) {
vec2 uv = vec2((float(index + ${a}) + 0.5) / ${o}.0, 0.5);
return sampleTexture(${t}, uv);
}
`:`
float ${n}(int index) {
vec2 uv = uvFromFlat(${i}, ${o}, index + ${a});
return sampleTexture(${t}, uv);
}
`}function JK(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=e.shapeInfo.texShape,o=i[0],a=i[1],c=Wn();if(i!=null&&ot(t,i))return`
vec4 ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${a}.0, ${o}.0);
return ${c.texture2D}(${n}, uv);
}
`;const h=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],d=Math.ceil(t[1]/2);return`
vec4 ${s}(int row, int col) {
vec2 uv = packedUVfrom2D(${d}, ${h[0]}, ${h[1]}, row, col);
return ${c.texture2D}(${n}, uv);
}
`}function ZK(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=e.shapeInfo.texShape;if(i!=null&&ot(t,i)){const y=i[0],b=i[1];return`
float ${s}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${b}.0, ${y}.0);
return sampleTexture(${n}, uv);
}
`}const{newShape:o,keptDims:a}=Ir(t),c=o;if(c.length<t.length){const y=mc(e,c),b=["row","col"];return`
${dc(y)}
float ${s}(int row, int col) {
return ${s}(${fc(b,a)});
}
`}if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col) {
int index = round(dot(vec2(row, col), vec2(${t[1]}, 1)));
${pc(e)}
}
`;const h=i[0],d=i[1],m=Ko(n);return d===1?`
float ${s}(int row, int col) {
float index = dot(vec3(row, col, ${m}), vec3(${t[1]}, 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / ${h}.0);
return sampleTexture(${n}, uv);
}
`:h===1?`
float ${s}(int row, int col) {
float index = dot(vec3(row, col, ${m}), vec3(${t[1]}, 1, 1));
vec2 uv = vec2((index + 0.5) / ${d}.0, 0.5);
return sampleTexture(${n}, uv);
}
`:`
float ${s}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${t[1]} + col + ${m};
vec2 uv = uvFromFlat(${h}, ${d}, index);
return sampleTexture(${n}, uv);
}
`}function QK(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=e.shapeInfo.texShape,o=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)];if(t[0]===1){const y=t.slice(1),b=[1,2],w=mc(e,y),L=["b","row","col"];return`
${W0(w)}
vec4 ${s}(int b, int row, int col) {
return ${s}(${fc(L,b)});
}
`}const a=o[0],c=o[1],h=Math.ceil(t[2]/2),d=h*Math.ceil(t[1]/2),m=Wn();return`
vec4 ${s}(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
${a}, ${c}, ${d}, ${h}, b, row, col);
return ${m.texture2D}(${n}, uv);
}
`}function e5(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=t[1]*t[2],o=t[2],{newShape:a,keptDims:c}=Ir(t),h=a;if(h.length<t.length){const L=mc(e,h),T=["row","col","depth"];return`
${dc(L)}
float ${s}(int row, int col, int depth) {
return ${s}(${fc(T,c)});
}
`}if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col, int depth) {
int index = round(dot(vec3(row, col, depth),
vec3(${i}, ${o}, 1)));
${pc(e)}
}
`;const d=e.shapeInfo.texShape,m=d[0],y=d[1],b=e.shapeInfo.flatOffset;if(y===i&&b==null)return`
float ${s}(int row, int col, int depth) {
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(${o}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${y}.0, ${m}.0);
return sampleTexture(${n}, uv);
}
`;if(y===o&&b==null)return`
float ${s}(int row, int col, int depth) {
float texR = dot(vec2(row, col), vec2(${t[1]}, 1));
float texC = float(depth);
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${y}.0, ${m}.0);
return sampleTexture(${n}, uv);
}
`;const w=Ko(n);return`
float ${s}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${i} + col * ${o} + depth + ${w};
vec2 uv = uvFromFlat(${m}, ${y}, index);
return sampleTexture(${n}, uv);
}
`}function t5(e){const t=e.shapeInfo.logicalShape,n=t.length,s=e.name,i="get"+s.charAt(0).toUpperCase()+s.slice(1),o=e.shapeInfo.texShape,a=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],c=a[0],h=a[1],d=Math.ceil(t[n-1]/2);let m=d*Math.ceil(t[n-2]/2),y="int b, int row, int col",b=`b * ${m} + (row / 2) * ${d} + (col / 2)`;for(let L=2;L<n-1;L++)y=`int b${L}, `+y,m*=t[n-L-1],b=`b${L} * ${m} + `+b;const w=Wn();return`
vec4 ${i}(${y}) {
int index = ${b};
int texR = index / ${h};
int texC = index - texR * ${h};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${h}, ${c});
return ${w.texture2D}(${s}, uv);
}
`}function n5(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=t[3],o=t[2]*i,a=t[1]*o,{newShape:c,keptDims:h}=Ir(t);if(c.length<t.length){const L=mc(e,c),T=["row","col","depth","depth2"];return`
${dc(L)}
float ${s}(int row, int col, int depth, int depth2) {
return ${s}(${fc(T,h)});
}
`}if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col, int depth, int depth2) {
int index = round(dot(vec4(row, col, depth, depth2),
vec4(${a}, ${o}, ${i}, 1)));
${pc(e)}
}
`;const d=e.shapeInfo.flatOffset,m=e.shapeInfo.texShape,y=m[0],b=m[1];if(b===a&&d==null)return`
float ${s}(int row, int col, int depth, int depth2) {
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(${o}, ${i}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${b}.0, ${y}.0);
return sampleTexture(${n}, uv);
}
`;if(b===i&&d==null)return`
float ${s}(int row, int col, int depth, int depth2) {
float texR = dot(vec3(row, col, depth),
vec3(${t[1]*t[2]}, ${t[2]}, 1));
float texC = float(depth2);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${b}.0, ${y}.0);
return sampleTexture(${n}, uv);
}
`;const w=Ko(n);return`
float ${s}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${a} + col * ${o} +
depth * ${i} + depth2;
vec2 uv = uvFromFlat(${y}, ${b}, index + ${w});
return sampleTexture(${n}, uv);
}
`}function s5(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),i=t[4],o=t[3]*i,a=t[2]*o,c=t[1]*a,{newShape:h,keptDims:d}=Ir(t);if(h.length<t.length){const T=mc(e,h),A=["row","col","depth","depth2","depth3"];return`
${dc(T)}
float ${s}(int row, int col, int depth, int depth2, int depth3) {
return ${s}(${fc(A,d)});
}
`}if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col, int depth, int depth2, int depth3) {
float index = dot(
vec4(row, col, depth, depth2),
vec4(${c}, ${a}, ${o}, ${i})) +
depth3;
${pc(e)}
}
`;const m=e.shapeInfo.flatOffset,y=e.shapeInfo.texShape,b=y[0],w=y[1];if(w===c&&m==null)return`
float ${s}(int row, int col, int depth, int depth2, int depth3) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${a}, ${o}, ${i}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${w}.0, ${b}.0);
return sampleTexture(${n}, uv);
}
`;if(w===i&&m==null)return`
float ${s}(int row, int col, int depth, int depth2, int depth3) {
float texR = dot(
vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]},
${t[2]*t[3]}, ${t[3]}, 1));
int texC = depth3;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${w}.0, ${b}.0);
return sampleTexture(${n}, uv);
}
`;const L=Ko(n);return`
float ${s}(int row, int col, int depth, int depth2, int depth3) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${c} + col * ${a} + depth * ${o} +
depth2 * ${i} + depth3 + ${L};
vec2 uv = uvFromFlat(${b}, ${w}, index);
return sampleTexture(${n}, uv);
}
`}function i5(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:i,keptDims:o}=Ir(t);if(i.length<t.length){const A=mc(e,i),N=["row","col","depth","depth2","depth3","depth4"];return`
${dc(A)}
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
return ${s}(${fc(N,o)});
}
`}const a=t[5],c=t[4]*a,h=t[3]*c,d=t[2]*h,m=t[1]*d;if(e.shapeInfo.isUniform)return`
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int index = round(dot(
vec4(row, col, depth, depth2),
vec4(${m}, ${d}, ${h}, ${c})) +
dot(
vec2(depth3, depth4),
vec2(${a}, 1)));
${pc(e)}
}
`;const y=e.shapeInfo.flatOffset,b=e.shapeInfo.texShape,w=b[0],L=b[1];if(L===m&&y==null)return`
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${d}, ${h}, ${c}, ${a})) +
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${L}.0, ${w}.0);
return sampleTexture(${n}, uv);
}
`;if(L===a&&y==null)return`
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
float texR = dot(vec4(row, col, depth, depth2),
vec4(${t[1]*t[2]*t[3]*t[4]},
${t[2]*t[3]*t[4]},
${t[3]*t[4]},
${t[4]})) + float(depth3);
int texC = depth4;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${L}.0, ${w}.0);
return sampleTexture(${n}, uv);
}
`;const T=Ko(n);return`
float ${s}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${m} + col * ${d} + depth * ${h} +
depth2 * ${c} + depth3 * ${a} + depth4 + ${T};
vec2 uv = uvFromFlat(${w}, ${L}, index);
return sampleTexture(${n}, uv);
}
`}function pc(e){const t=e.name,n=we(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`
for (int i = 0; i < ${n}; i++) {
if (i == index) {
return ${t}[i];
}
}
`}function r5(e,t){const n=e.name,s=n.charAt(0).toUpperCase()+n.slice(1),i="get"+s+"AtOutCoords",o=e.shapeInfo.logicalShape.length,a=t.logicalShape.length,c=_0(e.shapeInfo.logicalShape,t.logicalShape),h=Et(a),d=a-o;let m;const y=["x","y","z","w","u","v"];o===0?m="":a<2&&c.length>=1?m="coords = 0;":m=c.map(E=>`coords.${y[E+d]} = 0;`).join(`
`);let b="";a<2&&o>0?b="coords":b=e.shapeInfo.logicalShape.map((E,D)=>`coords.${y[D+d]}`).join(", ");let w="return outputValue;";const L=we(e.shapeInfo.logicalShape),T=L===1,A=we(t.logicalShape),N=A===1;if(o===1&&!T&&!N)w=`
return vec4(outputValue.xy, outputValue.xy);
`;else if(T&&!N)a===1?w=`
return vec4(outputValue.x, outputValue.x, 0., 0.);
`:w=`
return vec4(outputValue.x);
`;else if(c.length){const E=o-2,D=o-1;c.indexOf(E)>-1&&c.indexOf(D)>-1?w="return vec4(outputValue.x);":c.indexOf(E)>-1?w="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":c.indexOf(D)>-1&&(w="return vec4(outputValue.xx, outputValue.zz);")}return`
vec4 ${i}() {
${h} coords = getOutputCoords();
${m}
vec4 outputValue = get${s}(${b});
${w}
}
`}function o5(e,t){const n=e.name,s=n.charAt(0).toUpperCase()+n.slice(1),i="get"+s+"AtOutCoords",o=t.texShape,a=e.shapeInfo.texShape,c=e.shapeInfo.logicalShape.length,h=t.logicalShape.length;if(!e.shapeInfo.isUniform&&c===h&&e.shapeInfo.flatOffset==null&&ot(a,o))return`
float ${i}() {
return sampleTexture(${n}, resultUV);
}
`;const d=Et(h),m=_0(e.shapeInfo.logicalShape,t.logicalShape),y=h-c;let b;const w=["x","y","z","w","u","v"];c===0?b="":h<2&&m.length>=1?b="coords = 0;":b=m.map(T=>`coords.${w[T+y]} = 0;`).join(`
`);let L="";return h<2&&c>0?L="coords":L=e.shapeInfo.logicalShape.map((T,A)=>`coords.${w[A+y]}`).join(", "),`
float ${i}() {
${d} coords = getOutputCoords();
${b}
return get${s}(${L});
}
`}function Et(e){if(e<=1)return"int";if(e===2)return"ivec2";if(e===3)return"ivec3";if(e===4)return"ivec4";if(e===5)return"ivec5";if(e===6)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function mc(e,t){const n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function fc(e,t){return t.map(n=>e[n]).join(", ")}class a5{constructor(e,t,n,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,k(e.length>2,()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`);const i=e[e.length-1],o=Math.ceil(i/t);this.outputShape=e.slice(0,-1),o>1&&this.outputShape.push(o),s||this.variableNames.push("bestIndicesA");const a=this.outputShape,c=a.length,h=Et(c),d=ls("coords",c);let m,y;if(o===1){y=c+1;const $=Et(y);m=`
${$} sourceLocR = ${$}(${d.join()}, 0);
++${d[c-1]};
${$} sourceLocG = ${$}(${d.join()}, 0);
++${d[c-2]};
${$} sourceLocA = ${$}(${d.join()}, 0);
--${d[c-1]};
${$} sourceLocB = ${$}(${d.join()}, 0);
--${d[c-2]};`}else y=c,m=`
${h} sourceLocR = coords;
++${d[c-1]};
${h} sourceLocG = coords;
++${d[c-2]};
${h} sourceLocA = coords;
--${d[c-1]};
${h} sourceLocB = coords;
--${d[c-2]};`;const b=["x","y","z","w","u","v"].slice(0,y),w="."+b[y-1],L=b.map($=>"int "+$),T=ls("sourceLocR",y-1).concat("inIdx.r"),A=ls("sourceLocG",y-1).concat("inIdx.g"),N=ls("sourceLocB",y-1).concat("inIdx.b"),E=ls("sourceLocA",y-1).concat("inIdx.a"),D=n==="max"?"greaterThan":"lessThan",F=s?"":`
inIdx = round(vec4(getBestIndicesAChannel(${T.join()}),
getBestIndicesAChannel(${A.join()}),
getBestIndicesAChannel(${N.join()}),
getBestIndicesAChannel(${E.join()})));`,_=`vec4(
getAChannel(${T.join()}),
hasNextCol ? getAChannel(${A.join()}) : 0.,
hasNextRow ? getAChannel(${N.join()}) : 0.,
hasNextRow && hasNextCol ? getAChannel(${E.join()}) : 0.)`,B=s?"":`
float getBestIndicesAChannel(${L.join()}) {
return getChannel(getBestIndicesA(${b.join()}),
vec2(${b.slice(-2).join()}));
}`;this.userCode=`
float getAChannel(${L.join()}) {
return getChannel(getA(${b.join()}),
vec2(${b.slice(-2).join()}));
}
${B}
void main() {
${h} coords = getOutputCoords();
bool hasNextCol = ${d[c-1]} < ${a[c-1]-1};
bool hasNextRow = ${d[c-2]} < ${a[c-2]-1};
${m}
ivec4 srcIdx = ivec4(sourceLocR${w}, sourceLocG${w},
sourceLocB${w}, sourceLocA${w}) * ${t};
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
vec4 bestValue = ${_};
for (int i = 0; i < ${t}; i++) {
inIdx = srcIdx;
${F}
vec4 candidate = ${_};
bvec4 nan = isnan(candidate);
bvec4 replace = bvec4(
vec4(${D}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
replace.y ? candidate.y : bestValue.y,
replace.z ? candidate.z : bestValue.z,
replace.w ? candidate.w : bestValue.w);
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
srcIdx++;
}
setOutput(bestIndex);
}
`}}class c5{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,i=e.strideWidth,o=e.dilationHeight,a=e.dilationWidth,c=e.effectiveFilterHeight,h=e.effectiveFilterWidth,d=c-1-e.padInfo.top,m=h-1-e.padInfo.left,y=1/(t*n);this.userCode=`
const ivec2 pads = ivec2(${d}, ${m});
const float avgMultiplier = float(${y});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${c};
wR += ${o}) {
float dyR = float(dyRCorner + wR) / ${s}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${h};
wC+= ${a}) {
float dyC = float(dyCCorner + wC) / ${i}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
dotProd += dyValue * avgMultiplier;
}
}
setOutput(dotProd);
}
`}}class l5{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,s=e.filterWidth,i=e.strideDepth,o=e.strideHeight,a=e.strideWidth,c=e.dilationDepth,h=e.dilationHeight,d=e.dilationWidth,m=e.effectiveFilterDepth,y=e.effectiveFilterHeight,b=e.effectiveFilterWidth,w=m-1-e.padInfo.front,L=y-1-e.padInfo.top,T=b-1-e.padInfo.left,A=1/(t*n*s);this.userCode=`
const ivec3 pads = ivec3(${w}, ${L}, ${T});
const float avgMultiplier = float(${A});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wD = 0; wD < ${m};
wD += ${c}) {
float dyD = float(dyDCorner + wD) / ${i}.0;
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < ${y};
wR += ${h}) {
float dyR = float(dyRCorner + wR) / ${o}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${b};
wC += ${d}) {
float dyC = float(dyCCorner + wC) / ${a}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
dotProd += dyValue * avgMultiplier;
}
}
}
setOutput(dotProd);
}
`}}const U0={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"};class B0{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=tt(t,n),this.userCode=`
float binaryOpComplex(
float areal, float aimag, float breal, float bimag) {
${e}
}
void main() {
float areal = getARealAtOutCoords();
float aimag = getAImagAtOutCoords();
float breal = getBRealAtOutCoords();
float bimag = getBImagAtOutCoords();
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
}
`}}const M0=`
if (isnan(a)) return a;
if (isnan(b)) return b;
`,NS="return a + b;",CS="return a - b;",P0="return a * b;",h5=`
float s = sign(a) * sign(b);
int ia = round(a);
int ib = round(b);
if (ib != 0) {
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
return float(idiv(ia, ib, s));
} else {
return NAN;
}
`,u5=`
if(a < 0.0 && floor(b) < b){
return NAN;
}
if (b == 0.0) {
return 1.0;
}
return (round(mod(b, 2.0)) != 1) ?
pow(abs(a), b) : sign(a) * pow(abs(a), b);
`,wee="return (a - b) * (a - b);",d5="return float(a == b);",p5="return float(a != b);",m5="return float(a < b);",f5="return float(a <= b);",g5="return float(a > b);",y5="return float(a >= b);",b5="return float(a >= 1.0 && b >= 1.0);",w5="return float(a >= 1.0 || b >= 1.0);",L5=M0+`
return max(a, b);
`,S5=M0+`
return min(a, b);
`,I5=`if (b == 0.0) return NAN;
return mod(a, b);`,x5="return (b >= 1.0) ? a : a * (b + 1.0);",z0="return (a < 0.) ? b * a : a;";class hn{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=tt(t,n),this.userCode=`
float binaryOperation(float a, float b) {
${e}
}
void main() {
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
}
`}}const dm=`
result.r = isNaN.r > 0. ? NAN : result.r;
result.g = isNaN.g > 0. ? NAN : result.g;
result.b = isNaN.b > 0. ? NAN : result.b;
result.a = isNaN.a > 0. ? NAN : result.a;
`,T5=`
ivec4 ia = round(a);
ivec4 ib = round(b);
bvec4 cond = notEqual(ib, ivec4(0));
ivec4 result = ivec4(0);
vec4 s = sign(a) * sign(b);
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
if (cond[0]) {
result[0] = idiv(ia[0], ib[0], s[0]);
}
if (cond[1]) {
result[1] = idiv(ia[1], ib[1], s[1]);
}
if (cond[2]) {
result[2] = idiv(ia[2], ib[2], s[2]);
}
if (cond[3]) {
result[3] = idiv(ia[3], ib[3], s[3]);
}
return vec4(result);
`,A5=`
// isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));
vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);
vec4 result = multiplier * pow(abs(a), b);
// Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
bvec4 isExpZero = equal(b, vec4(0.0));
result.r = isExpZero.r ? 1.0 : result.r;
result.g = isExpZero.g ? 1.0 : result.g;
result.b = isExpZero.b ? 1.0 : result.b;
result.a = isExpZero.a ? 1.0 : result.a;
vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));
`+dm+`
return result;
`,G0=`
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`,v5=`
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
`,N5=`
return vec4(equal(a, b));
`,C5=`
return vec4(notEqual(a, b));
`,R5=`
return vec4(lessThan(a, b));
`,O5=`
return vec4(lessThanEqual(a, b));
`,E5=`
return vec4(greaterThan(a, b));
`,D5=`
return vec4(greaterThanEqual(a, b));
`,k5=`
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
`,F5=`
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
`,_5=`
vec4 result = vec4(max(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+dm+`
return result;
`,W5=`
vec4 result = vec4(min(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+dm+`
return result;
`,$5=`
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
`+dm+`
return result;
`;class jr{constructor(e,t,n,s=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=tt(t,n);const i=this.outputShape.length;let o="";if(s)if(i===0||we(this.outputShape)===1)o=`
result.y = 0.;
result.z = 0.;
result.w = 0.;
`;else{const a=Et(i);if(o=`
${a} coords = getOutputCoords();
`,i===1)o+=`
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
result.z = 0.;
result.w = 0.;
`;else{const c=ls("coords",i);o+=`
bool nextRowOutOfBounds =
(${c[i-2]} + 1) >= ${this.outputShape[i-2]};
bool nextColOutOfBounds =
(${c[i-1]} + 1) >= ${this.outputShape[i-1]};
result.y = nextColOutOfBounds ? 0. : result.y;
result.z = nextRowOutOfBounds ? 0. : result.z;
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
`}}this.userCode=`
vec4 binaryOperation(vec4 a, vec4 b) {
${e}
}
void main() {
vec4 a = getAAtOutCoords();
vec4 b = getBAtOutCoords();
vec4 result = binaryOperation(a, b);
${o}
setOutput(result);
}
`}}class U5{constructor(e){this.variableNames=["A"],this.outputShape=e,this.userCode=`
uniform float minVal;
uniform float maxVal;
void main() {
float value = getAAtOutCoords();
if (isnan(value)) {
setOutput(value);
return;
}
setOutput(clamp(value, minVal, maxVal));
}
`}getCustomSetupFunc(e,t){return(n,s)=>{this.minLoc==null&&(this.minLoc=n.getUniformLocationNoThrow(s,"minVal"),this.maxLoc=n.getUniformLocationNoThrow(s,"maxVal")),n.gl.uniform1f(this.minLoc,e),n.gl.uniform1f(this.maxLoc,t)}}}class B5{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode=`
uniform float minVal;
uniform float maxVal;
void main() {
vec4 value = getAAtOutCoords();
if (any(isnan(value))) {
setOutput(value);
return;
}
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
}
`}getCustomSetupFunc(e,t){return(n,s)=>{this.minLoc==null&&(this.minLoc=n.getUniformLocationNoThrow(s,"minVal"),this.maxLoc=n.getUniformLocationNoThrow(s,"maxVal")),n.gl.uniform1f(this.minLoc,e),n.gl.uniform1f(this.maxLoc,t)}}}class M5{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode=`
void main() {
float re = abs(getRealAtOutCoords());
float im = abs(getImagAtOutCoords());
float mx = max(re, im);
// sadly the length function in glsl is not underflow-safe
// (at least not on Intel GPUs). So the safe solution is
// to ensure underflow-safety in all cases.
setOutput(
mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))
);
}
`}}class P5{constructor(e){this.outputShape=[],this.outputShape=Er(e,1),this.variableNames=e.map((o,a)=>`T${a}`);const t=new Array(e.length-1);t[0]=e[0][1];for(let o=1;o<t.length;o++)t[o]=t[o-1]+e[o][1];const n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let o=1;o<t.length;o++){const a=t[o-1];n.push(`else if (yC < ${t[o]}) setOutput(getT${o}(yR, yC-${a}));`)}const s=t.length,i=t[t.length-1];n.push(`else setOutput(getT${s}(yR, yC-${i}));`),this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int yR = coords.x;
int yC = coords.y;
${n.join(`
`)}
}
`}}class z5{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=Er(e,t);const n=this.outputShape,s=n.length,i=Et(s),o=ls("coords",s),a=["x","y","z","w","u","v"].slice(0,s);this.variableNames=e.map((L,T)=>`T${T}`);const c=new Array(e.length-1);c[0]=e[0][t];for(let L=1;L<c.length;L++)c[L]=c[L-1]+e[L][t];const h=a[t],d=a.slice(-2),m=a.join();let y=`if (${h} < ${c[0]}) {
return getChannel(
getT0(${m}), vec2(${d.join()}));
}`;for(let L=1;L<c.length;L++){const T=c[L-1];y+=`
if (${h} < ${c[L]} && ${h} >= ${c[L-1]}) {
return getChannel(
getT${L}(${pm(a,h,T)}),
vec2(${pm(d,h,T)}));
}`}const b=c.length,w=c[c.length-1];y+=`
return getChannel(
getT${b}(${pm(a,h,w)}),
vec2(${pm(d,h,w)}));`,this.userCode=`
float getValue(${a.map(L=>"int "+L)}) {
${y}
}
void main() {
${i} coords = getOutputCoords();
vec4 result = vec4(getValue(${o}), 0., 0., 0.);
${o[s-1]} = ${o[s-1]} + 1;
if (${o[s-1]} < ${n[s-1]}) {
result.g = getValue(${o});
}
${o[s-2]} = ${o[s-2]} + 1;
if (${o[s-2]} < ${n[s-2]}) {
result.a = getValue(${o});
}
${o[s-1]} = ${o[s-1]} - 1;
if (${o[s-2]} < ${n[s-2]} &&
${o[s-1]} < ${n[s-1]}) {
result.b = getValue(${o});
}
setOutput(result);
}
`}}function pm(e,t,n){const s=e.indexOf(t),i=e.map((o,a)=>a===s?`${o} - ${n}`:o);return i.join()}class G5{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,s=e.padInfo.top,i=e.padInfo.left,o=e.dataFormat==="channelsLast";this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int d2 = coords.w;
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${t} - ${s};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${n} - ${i};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
if (${o}) {
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
} else {
float dyValue = getDy(b, d2, yR, yC);
float xValue = getX(b, d1, xR, xC);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
`}}class V5{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,i=e.strideWidth,o=e.dataFormat==="channelsLast",a=t-1-e.padInfo.top,c=n-1-e.padInfo.left,h=o?1:2,d=o?2:3,m=o?3:1;this.userCode=`
const ivec2 pads = ivec2(${a}, ${c});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[${m}];
ivec2 dyCorner = ivec2(coords[${h}], coords[${d}]) - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${t}; wR++) {
float dyR = float(dyRCorner + wR) / ${s}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${t} - 1 - wR;
for (int wC = 0; wC < ${n}; wC++) {
float dyC = float(dyCCorner + wC) / ${i}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${n} - 1 - wC;
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
if (${o}) {
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
} else {
float xValue = getDy(batch, d2, idyR, idyC);
float wValue = getW(wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
`}}class Y5{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideDepth,n=e.strideHeight,s=e.strideWidth,i=e.padInfo.front,o=e.padInfo.top,a=e.padInfo.left;this.userCode=`
void main() {
ivec5 coords = getOutputCoords();
int wF = coords.x;
int wR = coords.y;
int wC = coords.z;
int d1 = coords.w;
int d2 = coords.u;
float dotProd = 0.0;
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yF = 0; yF < ${e.outDepth}; yF++) {
int xF = wF + yF * ${t} - ${i};
if (xF < 0 || xF >= ${e.inDepth}) {
continue;
}
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${n} - ${o};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${s} - ${a};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float dyValue = getDy(b, yF, yR, yC, d2);
float xValue = getX(b, xF, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
}
setOutput(dotProd);
}
`}}class H5{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,s=e.filterWidth,i=e.strideDepth,o=e.strideHeight,a=e.strideWidth,c=t-1-e.padInfo.front,h=n-1-e.padInfo.top,d=s-1-e.padInfo.left;this.userCode=`
const ivec3 pads = ivec3(${c}, ${h}, ${d});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d1 = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyFCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
float dotProd = 0.0;
for (int wF = 0; wF < ${t}; wF++) {
float dyF = float(dyFCorner + wF) / ${i}.0;
if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {
continue;
}
int idyF = int(dyF);
int wFPerm = ${t} - 1 - wF;
for (int wR = 0; wR < ${n}; wR++) {
float dyR = float(dyRCorner + wR) / ${o}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${n} - 1 - wR;
for (int wC = 0; wC < ${s}; wC++) {
float dyC = float(dyCCorner + wC) / ${a}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${s} - 1 - wC;
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
float xValue = getDy(batch, idyF, idyR, idyC, d2);
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
`}}class q5{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,s=e.padInfo.top,i=e.padInfo.left,o=e.outChannels/e.inChannels;this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int wR = coords.x;
int wC = coords.y;
int d1 = coords.z;
int dm = coords.w;
int d2 = d1 * ${o} + dm;
float dotProd = 0.0;
// TO DO: Vec4 over the batch size
for (int b = 0; b < ${e.batchSize}; b++) {
for (int yR = 0; yR < ${e.outHeight}; yR++) {
int xR = wR + yR * ${t} - ${s};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${n} - ${i};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float dyValue = getDy(b, yR, yC, d2);
float xValue = getX(b, xR, xC, d1);
dotProd += (xValue * dyValue);
}
}
}
setOutput(dotProd);
}
`}}class j5{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.top,a=n-1-e.padInfo.left,c=e.outChannels/e.inChannels;this.userCode=`
const ivec2 pads = ivec2(${o}, ${a});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[3];
ivec2 dyCorner = coords.yz - pads;
int dyRCorner = dyCorner.x;
int dyCCorner = dyCorner.y;
float dotProd = 0.0;
for (int wR = 0; wR < ${t}; wR++) {
float dyR = float(dyRCorner + wR) / ${s}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${t} - 1 - wR;
for (int wC = 0; wC < ${n}; wC++) {
float dyC = float(dyCCorner + wC) / ${i}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
int wCPerm = ${n} - 1 - wC;
// TO DO: Vec4 over the channelMul
for (int dm = 0; dm < ${c}; dm++) {
int d2 = d1 * ${c} + dm;
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, dm);
dotProd += xValue * wValue;
}
}
}
setOutput(dotProd);
}
`}}class V0{constructor(e,t=!1,n=null,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const i=e.padInfo.top,o=e.padInfo.left,a=e.strideHeight,c=e.strideWidth,h=e.dilationHeight,d=e.dilationWidth,m=e.filterHeight,y=e.filterWidth,b=Math.floor(e.inChannels/4)*4,w=e.inChannels%4,L=e.dataFormat==="channelsLast",T=L?1:2,A=L?2:3,N=L?3:1;let E="",D="";n&&(s?E=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${n}
}`:E=`
float activation(float x) {
${n}
}
`,D="result = activation(result);");const F=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${E}
const ivec2 strides = ivec2(${a}, ${c});
const ivec2 pads = ivec2(${i}, ${o});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d2 = coords[${N}];
ivec2 xRCCorner =
ivec2(coords[${T}], coords[${A}]) * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${m}; wR++) {
int xR = xRCorner + wR * ${h};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${y}; wC++) {
int xC = xCCorner + wC * ${d};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
for (int d1 = 0; d1 < ${b}; d1 += 4) {
vec4 wValues = vec4(
getW(wR, wC, d1, d2),
getW(wR, wC, d1 + 1, d2),
getW(wR, wC, d1 + 2, d2),
getW(wR, wC, d1 + 3, d2)
);
if (${L}) {
vec4 xValues = vec4(
getX(batch, xR, xC, d1),
getX(batch, xR, xC, d1 + 1),
getX(batch, xR, xC, d1 + 2),
getX(batch, xR, xC, d1 + 3)
);
dotProd += dot(xValues, wValues);
} else {
vec4 xValues = vec4(
getX(batch, d1, xR, xC),
getX(batch, d1 + 1, xR, xC),
getX(batch, d1 + 2, xR, xC),
getX(batch, d1 + 3, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
if (${w===1}) {
if (${L}) {
dotProd +=
getX(batch, xR, xC, ${b}) *
getW(wR, wC, ${b}, d2);
} else {
dotProd +=
getX(batch, ${b}, xR, xC) *
getW(wR, wC, ${b}, d2);
}
} else if (${w===2}) {
vec2 wValues = vec2(
getW(wR, wC, ${b}, d2),
getW(wR, wC, ${b} + 1, d2)
);
if (${L}) {
vec2 xValues = vec2(
getX(batch, xR, xC, ${b}),
getX(batch, xR, xC, ${b} + 1)
);
dotProd += dot(xValues, wValues);
} else {
vec2 xValues = vec2(
getX(batch, ${b}, xR, xC),
getX(batch, ${b} + 1, xR, xC)
);
dotProd += dot(xValues, wValues);
}
} else if (${w===3}) {
vec3 wValues = vec3(
getW(wR, wC, ${b}, d2),
getW(wR, wC, ${b} + 1, d2),
getW(wR, wC, ${b} + 2, d2)
);
if (${L}) {
vec3 xValues = vec3(
getX(batch, xR, xC, ${b}),
getX(batch, xR, xC, ${b} + 1),
getX(batch, xR, xC, ${b} + 2)
);
dotProd += dot(xValues, wValues);
} else {
vec3 xValues = vec3(
getX(batch, ${b}, xR, xC),
getX(batch, ${b} + 1, xR, xC),
getX(batch, ${b} + 2, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
}
}
float result = dotProd;
${F}
${D}
setOutput(result);
}
`}}class K5{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const t=e.padInfo.front,n=e.padInfo.top,s=e.padInfo.left,i=e.strideDepth,o=e.strideHeight,a=e.strideWidth,c=e.dilationDepth,h=e.dilationHeight,d=e.dilationWidth,m=e.filterDepth,y=e.filterHeight,b=e.filterWidth,w=Math.floor(e.inChannels/4)*4,L=e.inChannels%4;this.userCode=`
const ivec3 strides = ivec3(${i}, ${o}, ${a});
const ivec3 pads = ivec3(${t}, ${n}, ${s});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int d2 = coords.u;
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xFCorner = xFRCCorner.x;
int xRCorner = xFRCCorner.y;
int xCCorner = xFRCCorner.z;
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
// y(yF, yR, yC, d2). ? = to be determined. : = across all
// values in that axis.
float dotProd = 0.0;
for (int wF = 0; wF < ${m}; wF++) {
int xF = xFCorner + wF * ${c};
if (xF < 0 || xF >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${y}; wR++) {
int xR = xRCorner + wR * ${h};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${b}; wC++) {
int xC = xCCorner + wC * ${d};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
for (int d1 = 0; d1 < ${w}; d1 += 4) {
vec4 xValues = vec4(
getX(batch, xF, xR, xC, d1),
getX(batch, xF, xR, xC, d1 + 1),
getX(batch, xF, xR, xC, d1 + 2),
getX(batch, xF, xR, xC, d1 + 3)
);
vec4 wValues = vec4(
getW(wF, wR, wC, d1, d2),
getW(wF, wR, wC, d1 + 1, d2),
getW(wF, wR, wC, d1 + 2, d2),
getW(wF, wR, wC, d1 + 3, d2)
);
dotProd += dot(xValues, wValues);
}
if (${L===1}) {
dotProd +=
getX(batch, xF, xR, xC, ${w}) *
getW(wF, wR, wC, ${w}, d2);
} else if (${L===2}) {
vec2 xValues = vec2(
getX(batch, xF, xR, xC, ${w}),
getX(batch, xF, xR, xC, ${w} + 1)
);
vec2 wValues = vec2(
getW(wF, wR, wC, ${w}, d2),
getW(wF, wR, wC, ${w} + 1, d2)
);
dotProd += dot(xValues, wValues);
} else if (${L===3}) {
vec3 xValues = vec3(
getX(batch, xF, xR, xC, ${w}),
getX(batch, xF, xR, xC, ${w} + 1),
getX(batch, xF, xR, xC, ${w} + 2)
);
vec3 wValues = vec3(
getW(wF, wR, wC, ${w}, d2),
getW(wF, wR, wC, ${w} + 1, d2),
getW(wF, wR, wC, ${w} + 2, d2)
);
dotProd += dot(xValues, wValues);
}
}
}
}
setOutput(dotProd);
}
`}}class Y0{constructor(e,t=!1,n=null,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const i=e.inHeight,o=e.inWidth,a=e.padInfo.top,c=e.padInfo.left,h=e.strideHeight,d=e.strideWidth,m=e.dilationHeight,y=e.dilationWidth,b=e.filterHeight,w=e.filterWidth,L=e.outChannels/e.inChannels;let T="",A="";n&&(s?T=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${n}
}`:T=`
float activation(float x) {
${n}
}
`,A="result = activation(result);");const N=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${T}
const ivec2 strides = ivec2(${h}, ${d});
const ivec2 pads = ivec2(${a}, ${c});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${L};
int q = d2 - d1 * ${L};
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
for (int wR = 0; wR < ${b}; wR++) {
int xR = xRCorner + wR * ${m};
if (xR < 0 || xR >= ${i}) {
continue;
}
for (int wC = 0; wC < ${w}; wC++) {
int xC = xCCorner + wC * ${y};
if (xC < 0 || xC >= ${o}) {
continue;
}
float xVal = getX(batch, xR, xC, d1);
float wVal = getW(wR, wC, d1, q);
dotProd += xVal * wVal;
}
}
float result = dotProd;
${N}
${A}
setOutput(result);
}
`}}class H0{constructor(e,t=!1,n=null,s=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.outShape;const i=e.inHeight,o=e.inWidth,a=e.padInfo.top,c=e.padInfo.left,h=e.strideHeight,d=e.strideWidth,m=e.dilationHeight,y=e.dilationWidth,b=e.filterHeight,w=e.filterWidth,L=w;let T="int xR; int xC; int xCOffset;";for(let D=0;D<b;D++)for(let F=0;F<w;F++)T+=`
vec4 xTexelR${D}C${F*2} = vec4(0.);
vec4 wR${D}C${F} = vec4(0.);
vec4 xR${D}C${F} = vec4(0.);`;for(let D=0;D<b;D++)for(let F=0;F<L;F++){const _=F*2;if(T+=`
xR = xRCorner + ${D*m};
xC = xCCorner + ${_*y};
`,d===1){if(_<w&&(c%2===1?T+=`
xCOffset = xC + 1;
if(xR >= 0 && xR < ${i} && xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${_} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if(xCOffset + 1 >= ${o}) {
xTexelR${D}C${_}.zw = vec2(0.);
}
} else {
xTexelR${D}C${_} = vec4(0.);
}
xCOffset = xC + 1 - 2;
if(xR >= 0 && xR < ${i} && xCOffset >= 0 && xCOffset < ${o}) {
vec4 previous = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if(xCOffset + 1 >= ${o}) {
previous.zw = vec2(0.);
}
xR${D}C${_} = vec4(previous.zw, xTexelR${D}C${_}.xy);
} else {
xR${D}C${_} = vec4(0, 0, xTexelR${D}C${_}.xy);
}
`:T+=`
if(xR >= 0 && xR < ${i} && xC >= 0 && xC < ${o}) {
xTexelR${D}C${_} = getX(batch, xR, xC, d1);
} else {
xTexelR${D}C${_} = vec4(0.);
}
xR${D}C${_} = xTexelR${D}C${_};
`,_+1<w)){const B=c%2===0?Oy(y):y;y%2===0&&c%2===1||y%2!==0&&c%2!==1?(T+=`
xCOffset = xC + ${c%2} + ${B};
if(xR >= 0 && xR < ${i} &&
xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${_+2} = getX(batch, xR, xCOffset, d1);
}
`,y>1&&(T+=`
xCOffset -= 2;
if(xR >= 0 && xR < ${i} &&
xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${_} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${D}C${_} = vec4(0.);
}
`),T+=`
xR${D}C${_+1} = vec4(
xTexelR${D}C${_}.zw, xTexelR${D}C${_+2}.xy);
`):T+=`
xCOffset = xC + ${B};
if(xR >= 0 && xR < ${i} &&
xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${_+2} = getX(batch, xR, xCOffset, d1);
}
xR${D}C${_+1} = xTexelR${D}C${_+2};
`}}else _<w&&(T+=`
if(xR >= 0 && xR < ${i}) {
`,c%2===1?(T+=`
xCOffset = xC + 1 - ${d};
if(xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${_} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${D}C${_} = vec4(0.);
}
if(xC + 1 >= 0 && xC + 1 < ${o}) {
xTexelR${D}C${_+2} = getX(batch, xR, xC + 1, d1);
} else {
xTexelR${D}C${_+2} = vec4(0.);
}
xR${D}C${_} = vec4(
xTexelR${D}C${_}.zw, xTexelR${D}C${_+2}.zw);
`,_+1<w&&(T+=`
vec4 final = vec4(0.);
xCOffset = xC + 1 + ${d};
if(xCOffset >= 0 && xCOffset < ${o}) {
final = getX(batch, xR, xCOffset, d1);
}
xR${D}C${_+1} = vec4(xTexelR${D}C${_+2}.xy, final.xy);
`)):(T+=`
if(xC >= 0 && xC < ${o}) {
xTexelR${D}C${_} = getX(batch, xR, xC, d1);
} else {
xTexelR${D}C${_} = vec4(0.);
}
xCOffset = xC + ${d};
if(xCOffset >= 0 && xCOffset < ${o}) {
xTexelR${D}C${_+2} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${D}C${_+2} = vec4(0.);
}
xR${D}C${_} = vec4(
xTexelR${D}C${_}.xy, xTexelR${D}C${_+2}.xy);
`,_+1<w&&(T+=`
xR${D}C${_+1} = vec4(
xTexelR${D}C${_}.zw, xTexelR${D}C${_+2}.zw);
`)),T+="}");_<w&&(T+=`
vec4 wTexelR${D}C${_} = getW(${D}, ${_}, d1, q);
wR${D}C${_} = vec4(wTexelR${D}C${_}.xz, wTexelR${D}C${_}.xz);
`,_+1<w&&(T+=`
vec4 wTexelR${D}C${_+1} = getW(${D}, ${_+1}, d1, q);
wR${D}C${_+1} =
vec4(wTexelR${D}C${_+1}.xz, wTexelR${D}C${_+1}.xz);`))}for(let D=0;D<b;D++)for(let F=0;F<w;F++)T+=`dotProd += xR${D}C${F} * wR${D}C${F};`;let A="",N="";n&&(s?A=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${n}
}`:A=`vec4 activation(vec4 x) {
${n}
}`,N="result = activation(result);");const E=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${A}
const ivec2 strides = ivec2(${h}, ${d});
const ivec2 pads = ivec2(${a}, ${c});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2;
int q = 0;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
vec4 dotProd = vec4(0.);
${T}
vec4 result = dotProd;
${E}
${N}
setOutput(result);
}
`}}class X5{constructor(e,t,n,s,i){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[o,a,c,h]=e,[d]=t,[m,y]=n;this.outputShape=[d,m,y,h];const b=s==="bilinear"?1:0,[w,L]=[`${a-1}.0`,`${c-1}.0`],[T,A,N]=m>1?[`${(a-1)/(m-1)}`,"(y2-y1) * height_ratio",`y1*${w} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${w}`],[E,D,F]=y>1?[`${(c-1)/(y-1)}`,"(x2-x1) * width_ratio",`x1*${L} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${L}`];this.userCode=`
const float height_ratio = float(${T});
const float width_ratio = float(${E});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int y = coords[1];
int x = coords[2];
int d = coords[3];
// get box vals
float y1 = getBoxes(b,0);
float x1 = getBoxes(b,1);
float y2 = getBoxes(b,2);
float x2 = getBoxes(b,3);
// get image in batch index
int bInd = round(getBoxInd(b));
if(bInd < 0 || bInd >= ${o}) {
return;
}
float height_scale = ${A};
float width_scale = ${D};
float in_y = ${N};
if( in_y < 0.0 || in_y > ${w} ) {
setOutput(float(${i}));
return;
}
float in_x = ${F};
if( in_x < 0.0 || in_x > ${L} ) {
setOutput(float(${i}));
return;
}
vec2 sourceFracIndexCR = vec2(in_x,in_y);
if(${b} == 1) {
// Compute the four integer indices.
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
float top = topLeft + (topRight - topLeft) * fracCR.x;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
float newValue = top + (bottom - top) * fracCR.y;
setOutput(newValue);
} else {
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestCR = ivec2(floor(
sourceFracIndexCR + vec2(0.5,0.5)));
float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
setOutput(newValue);
}
}
`}}class q0{constructor(e,t,n){this.variableNames=["x"],this.outputShape=e;const s=e.length,i=t?"0.0":`getX(${j0(s,"coords")})`,o=e[e.length-1];let a="",c="";t?(a=n?`end != ${o-1}`:"end != 0",c=n?"end + 1":"end - 1"):(a=n?`end + pow2 < ${o}`:"end >= pow2",c=n?"end + pow2":"end - pow2"),this.userCode=`
uniform float index;
void main() {
${Et(s)} coords = getOutputCoords();
int end = ${K0(s,"coords")};
float val = ${i};
int pow2 = int(pow(2.0, index));
if (${a}) {
int idx = ${c};
${K0(s,"coords")} = idx;
val += getX(${j0(s,"coords")});
}
setOutput(val);
}
`}getCustomSetupFunc(e){return(t,n)=>{this.index==null&&(this.index=t.getUniformLocation(n,"index")),t.gl.uniform1f(this.index,e)}}}function j0(e,t){if(e===1)return`${t}`;if(e===2)return`${t}.x, ${t}.y`;if(e===3)return`${t}.x, ${t}.y, ${t}.z`;if(e===4)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw Error(`Cumulative sum for rank ${e} is not yet supported`)}function K0(e,t){if(e===1)return`${t}`;if(e===2)return`${t}.y`;if(e===3)return`${t}.z`;if(e===4)return`${t}.w`;throw Error(`Cumulative sum for rank ${e} is not yet supported`)}class J5{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=su.DENSE;const t=ru(e),n=Wn();this.outputShape=e,this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
${jo(["r","c","d"],e)}
return ivec3(r, c, d);
}
void main() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = 4 * (resTexRC.x * ${t[1]} + resTexRC.y);
vec4 result = vec4(0.);
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getA(rc.x, rc.y, rc.z);
}
${n.output} = result;
}
`}}class Z5{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=su.DENSE;const t=ru(e),n=Wn();this.outputShape=e,this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
${jo(["r","c","d"],e)}
return ivec3(r, c, d);
}
void main() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${t[0]}, ${t[1]}));
int index = 4 * (resTexRC.x * ${t[1]} + resTexRC.y);
vec4 result = vec4(0.);
for (int i=0; i<4; i++) {
int flatIndex = index + i;
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));
}
${n.output} = result;
}
`}}class Q5{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int h = ${this.getHeightCoordString()};
int w = ${this.getWidthCoordString()};
int d = ${this.getDepthCoordString()};
int in_h = h / ${t};
int offset_h = imod(h, ${t});
int in_w = w / ${t};
int offset_w = imod(w, ${t});
int offset_d = (offset_h * ${t} + offset_w) *
${this.getOutputDepthSize()};
int in_d = d + offset_d;
float result = ${this.getInputSamplingString()};
setOutput(result);
}
`}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}}class e8{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;
setOutput(val);
}
`}}class t8{constructor(e){this.variableNames=["A"],this.outTexUsage=As.DOWNLOAD;const t=Wn();this.outputShape=e,this.userCode=`
${F0}
void main() {
float x = getAAtOutCoords();
${t.output} = encode_float(x);
}
`}}class n8{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=As.DOWNLOAD;const t=Wn();this.outputShape=e,this.userCode=`
${F0}
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
${t.output} = encode_float(x);
}
`}}class s8{constructor(e,t,n=!1){this.variableNames=["A"];const s=Wn(),[i,o]=t;this.outputShape=e;let a="result";n&&(a="floor(result * 255. + 0.5)"),this.userCode=`
${vS(e)}
void main() {
ivec3 coords = getOutputCoords();
int flatIndex = getFlatIndex(coords);
int offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
int r = flatIndex / ${o};
int c = imod(flatIndex, ${o});
vec2 uv = (vec2(c, r) + halfCR) / vec2(${o}.0, ${i}.0);
vec4 values = ${s.texture2D}(A, uv);
float result;
if(offset == 0) {
result = values[0];
} else if(offset == 1) {
result = values[1];
} else if(offset == 2) {
result = values[2];
} else {
result = values[3];
}
${s.output} = vec4(${a}, 0., 0., 0.);
}
`}}class i8{constructor(e,t,n=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const s=Wn(),[i,o]=t;this.outputShape=e;let a="",c="result";n&&(c="floor(result * 255. + 0.5)");for(let h=0;h<=1;h++)for(let d=0;d<=1;d++){const m=h*2+d;a+=`
localCoords = coords;
if(localCoords[2] + ${d} < ${e[2]}) {
localCoords[2] += ${d};
if(localCoords[1] + ${h} < ${e[1]}) {
localCoords[1] += ${h};
flatIndex = getFlatIndex(localCoords);
offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
r = flatIndex / ${o};
c = imod(flatIndex, ${o});
uv = (vec2(c, r) + halfCR) / vec2(${o}.0, ${i}.0);
values = ${s.texture2D}(A, uv);
if(offset == 0) {
result[${m}] = values[0];
} else if(offset == 1) {
result[${m}] = values[1];
} else if(offset == 2) {
result[${m}] = values[2];
} else {
result[${m}] = values[3];
}
}
}
`}this.userCode=`
${vS(e)}
void main() {
ivec3 coords = getOutputCoords();
vec4 result = vec4(0.);
int flatIndex, r, c, offset;
ivec3 localCoords;
vec2 uv;
vec4 values;
${a}
${s.output} = ${c};
}
`}}const X0={REAL:"return real * expR - imag * expI;",IMAG:"return real * expI + imag * expR;"};class J0{constructor(e,t,n){this.variableNames=["real","imag"];const s=t[1];this.outputShape=t;const i=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,o=n?`${s}.0`:"1.0";this.userCode=`
const float exponentMultiplier = ${i};
float unaryOpComplex(float real, float expR, float imag, float expI) {
${e}
}
float mulMatDFT(int batch, int index) {
float indexRatio = float(index) / float(${s});
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio;
float result = 0.0;
for (int i = 0; i < ${s}; i++) {
// x = (-2|2 * PI / N) * index * i;
float x = exponentMultiplierTimesIndexRatio * float(i);
float expR = cos(x);
float expI = sin(x);
float real = getReal(batch, i);
float imag = getImag(batch, i);
result +=
unaryOpComplex(real, expR, imag, expI) / ${o};
}
return result;
}
void main() {
ivec2 coords = getOutputCoords();
setOutput(mulMatDFT(coords[0], coords[1]));
}
`}}class r8{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.outputShape=e,this.userCode=`
uniform float value;
void main() {
// Input can be obtained from uniform value.
setOutput(value);
}
`}getCustomSetupFunc(e){return(t,n)=>{this.valueLoc==null&&(this.valueLoc=t.getUniformLocationNoThrow(n,"value")),t.gl.uniform1f(this.valueLoc,e)}}}class o8{constructor(e,t,n){this.variableNames=["A","indices"];const s=e.slice();s[n]=t,this.outputShape=s,this.rank=s.length;const i=Et(this.rank),o=a8(e,n);this.userCode=`
void main() {
${i} resRC = getOutputCoords();
setOutput(getA(${o}));
}
`}}function a8(e,t){const n=e.length;if(n>4)throw Error(`Gather for rank ${n} is not yet supported`);if(n===1)return"int(getIndices(resRC))";const s=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[];for(let o=0;o<e.length;o++)o===t?i.push(`int(getIndices(${s[o]}))`):i.push(`${s[o]}`);return i.join()}class c8{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;const s=Et(t.length),i=Et(n.length),o=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
${s} strides = ${s}(${this.strides});
void main() {
${i} coords = getOutputCoords();
int flattenIndex = 0;
for (int j = 0; j < ${this.sliceDim}; j++) {
int index = round(getIndices(coords[0], j));
flattenIndex += index * ${o};
}
setOutput(getX(flattenIndex, coords[1]));
}
`}}function l8(e){const t=Wn(),n=`${t.version}
precision highp float;
${t.attribute} vec3 clipSpacePos;
${t.attribute} vec2 uv;
${t.varyingVs} vec2 resultUV;
void main() {
gl_Position = vec4(clipSpacePos, 1);
resultUV = uv;
}`;return Uj(e,n)}function h8(e){const t=new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]);return Vj(e,t)}function u8(e){const t=new Uint16Array([0,1,2,2,1,3]);return Yj(e,t)}function au(e,t,n,s,i,o){qj(t,n);const a=Hj(e),c=e.TEXTURE_2D;return Re(e,()=>e.bindTexture(c,a)),Re(e,()=>e.texParameteri(c,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),Re(e,()=>e.texParameteri(c,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),Re(e,()=>e.texParameteri(c,e.TEXTURE_MIN_FILTER,e.NEAREST)),Re(e,()=>e.texParameteri(c,e.TEXTURE_MAG_FILTER,e.NEAREST)),Re(e,()=>e.texImage2D(c,0,s,t,n,0,i,o,null)),Re(e,()=>e.bindTexture(e.TEXTURE_2D,null)),a}function Z0(e){return e.internalFormatFloat}function d8(e,t,n,s){const[i,o]=iu(t,n);return au(e,i,o,Z0(s),s.textureFormatFloat,e.FLOAT)}function Q0(e){return e.internalFormatHalfFloat}function p8(e,t,n,s){const[i,o]=iu(t,n);return au(e,i,o,Q0(s),s.textureFormatFloat,s.textureTypeHalfFloat)}function eC(e){return e.downloadTextureFormat}function m8(e,t,n,s){const[i,o]=iu(t,n);return au(e,i,o,eC(s),e.RGBA,e.UNSIGNED_BYTE)}function tC(e){return e.internalFormatPackedFloat}function f8(e,t,n,s){const[i,o]=lc(t,n);return au(e,i,o,tC(s),e.RGBA,e.FLOAT)}function nC(e){return e.internalFormatPackedHalfFloat}function g8(e,t,n,s){const[i,o]=lc(t,n);return au(e,i,o,nC(s),e.RGBA,s.textureTypeHalfFloat)}function y8(e,t,n){const s=0,i=3*4,o=3*4+2*4;Re(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n));const a=C0(e,t,"clipSpacePos",n,3,o,s);return a&&C0(e,t,"uv",n,2,o,i)}function b8(e,t,n,s,i,o){Re(e,()=>e.bindTexture(e.TEXTURE_2D,t));let a,c,h;i instanceof Uint8Array?(a=new Uint8Array(n*s*4),c=e.UNSIGNED_BYTE,h=e.RGBA):(a=new Float32Array(n*s*4),c=e.FLOAT,h=o.internalFormatPackedFloat),a.set(i),Re(e,()=>e.texImage2D(e.TEXTURE_2D,0,h,n,s,0,e.RGBA,c,a)),Re(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function w8(e,t,n){Re(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?Re(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):Re(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),Re(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function L8(e,t,n,s){const i=e.createBuffer();Re(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,i));const o=4,a=4,c=o*a*t*n;return Re(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,c,e.STREAM_READ)),Re(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),Re(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),i}function S8(e,t,n){const s=e,i=new Float32Array(n);return s.bindBuffer(s.PIXEL_PACK_BUFFER,t),s.getBufferSubData(s.PIXEL_PACK_BUFFER,0,i),s.bindBuffer(s.PIXEL_PACK_BUFFER,null),i}function I8(e,t,n,s){const[i,o]=iu(t,n),a=4,c=new Uint8Array(Ej(t*n,a));return Re(e,()=>e.readPixels(0,0,i,o,s.downloadTextureFormat,e.UNSIGNED_BYTE,c)),new Float32Array(c.buffer)}function x8(e,t,n,s,i,o,a,c){const h=e,d=new Float32Array(Dj(o,a));return h.bindBuffer(h.PIXEL_PACK_BUFFER,t),h.getBufferSubData(h.PIXEL_PACK_BUFFER,0,d),h.bindBuffer(h.PIXEL_PACK_BUFFER,null),d}function T8(e,t,n){const s=new Float32Array(t*n*4);return Re(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,s)),s}class A8{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];const t=C().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,Cj(t,e)):this.gl=Wi(t);let n="WEBGL_color_buffer_float";const s="EXT_color_buffer_half_float";if(C().getNumber("WEBGL_VERSION")===1){const i="OES_texture_float",o="OES_texture_half_float";if(this.textureFloatExtension=rm(this.gl,i),zs(this.gl,o))this.textureHalfFloatExtension=rm(this.gl,o);else if(C().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),zs(this.gl,s))this.colorBufferHalfFloatExtension=rm(this.gl,s);else if(C().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",zs(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else if(zs(this.gl,s))this.colorBufferHalfFloatExtension=this.gl.getExtension(s);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=h8(this.gl),this.indexBuffer=u8(this.gl),this.framebuffer=jj(this.gl),this.textureConfig=SS(this.gl,this.textureHalfFloatExtension)}get debug(){return C().getBool("DEBUG")}dispose(){if(this.disposed)return;this.program!=null&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),this.outputTexture!=null&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");const e=this.gl;Re(e,()=>e.finish()),Re(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),Re(e,()=>e.deleteFramebuffer(this.framebuffer)),Re(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),Re(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),Re(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),d8(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),p8(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),m8(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),w8(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,s){this.throwIfDisposed(),b8(this.gl,e,t,n,s,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),g8(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),f8(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(R0(this.gl,this.framebuffer),this.outputTexture=null),Re(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,()=>I8(this.gl,t,n,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,n,s,i,o){return x8(this.gl,e,t,n,s,i,o,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return S8(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);const s=L8(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),s}createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(C().getBool("WEBGL_FENCE_API_ENABLED")){const s=e,i=s.fenceSync(s.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{const o=s.clientWaitSync(i,0,0);return o===s.ALREADY_SIGNALED||o===s.CONDITION_SATISFIED},t=i}else C().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,C().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,()=>T8(this.gl,t,n))}createProgram(e){this.throwIfDisposed();const t=this.gl,n=Bj(t,e),s=l8(t),i=zj(t);return Re(t,()=>t.attachShader(i,s)),Re(t,()=>t.attachShader(i,n)),Gj(t,i),this.debug&&IS(t,i),this.vertexAttrsAreBound||(this.setProgram(i),this.vertexAttrsAreBound=y8(t,this.program,this.vertexBuffer)),i}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&Re(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&IS(this.gl,this.program),Re(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?Xj(this.gl,e,t):Jj(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),Re(this.gl,()=>this.gl.getAttribLocation(e,t))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),Zj(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();const[s,i]=lc(t,n);this.setOutputMatrixTextureDriver(e,s,i)}setOutputMatrixWriteRegion(e,t,n,s){this.setOutputMatrixWriteRegionDriver(n,e,s,t)}setOutputPackedMatrixWriteRegion(e,t,n,s){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&IS(this.gl,this.program),om(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const e=this.gl;this.debug&&this.debugValidate(),Re(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),Re(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=rm(this.gl,C().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(C().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){const n=this.gl,s=this.getQueryTimerExtensionWebGL2(),i=n.createQuery();return n.beginQuery(s.TIME_ELAPSED_EXT,i),i}const e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(C().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){const t=this.gl,n=this.getQueryTimerExtensionWebGL2();t.endQuery(n.TIME_ELAPSED_EXT);return}const e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await Ey(()=>this.disposed||this.isQueryAvailable(e,C().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,C().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(t===0)return null;if(t===2){const n=this.gl,s=n.getQueryParameter(e,n.QUERY_RESULT);return s/1e6}else{const n=this.getQueryTimerExtensionWebGL1(),s=n.getQueryObjectEXT(e,n.QUERY_RESULT_EXT);return s/1e6}}isQueryAvailable(e,t){if(t===0)return!0;if(t===2){const n=this.gl,s=this.getQueryTimerExtensionWebGL2(),i=n.getQueryParameter(e,n.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(s.GPU_DISJOINT_EXT)),i&&!this.disjoint}else{const n=this.getQueryTimerExtensionWebGL1(),s=n.getQueryObjectEXT(e,n.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),s&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){const e=v8(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=e;++t){const{resolveFn:n}=this.itemsToPoll[t];n()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){if(this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1)return;Ey(()=>(this.pollItems(),this.itemsToPoll.length===0))}bindTextureToFrameBuffer(e){this.throwIfDisposed(),xS(this.gl,e,this.framebuffer),this.debug&&om(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(xS(this.gl,this.outputTexture,this.framebuffer),this.debug&&om(this.gl)):R0(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);const n=t();return this.unbindTextureToFrameBuffer(),n}setOutputMatrixTextureDriver(e,t,n){this.throwIfDisposed();const s=this.gl;xS(s,e,this.framebuffer),this.debug&&om(s),this.outputTexture=e,Re(s,()=>s.viewport(0,0,t,n)),Re(s,()=>s.scissor(0,0,t,n))}setOutputMatrixWriteRegionDriver(e,t,n,s){this.throwIfDisposed(),Re(this.gl,()=>this.gl.scissor(e,t,n,s))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(this.program==null)throw new Error("No GPU program is currently set.")}}function v8(e){let t=0;for(;t<e.length;++t){const n=e[t]();if(!n)break}return t-1}function N8(e,t,n,s){const i=t.userCode,o=n.map((w,L)=>{const T={logicalShape:w.shape,texShape:w.isUniform?null:w.texData.texShape,isUniform:w.isUniform,isPacked:w.isUniform?!1:w.texData.isPacked,flatOffset:null};return w.texData!=null&&w.texData.slice!=null&&w.texData.slice.flatOffset>0&&(T.flatOffset=w.texData.slice.flatOffset),{name:t.variableNames[L],shapeInfo:T}}),a=o.map(w=>w.shapeInfo),c={logicalShape:s.shape,texShape:s.texData.texShape,isUniform:!1,isPacked:s.texData.isPacked,flatOffset:null},h=AK(o,c,i,t.packedInputs),d=e.createProgram(h);let m=null;const y=e.getUniformLocation(d,"NAN",!1);C().getNumber("WEBGL_VERSION")===1&&(m=e.getUniformLocation(d,"INFINITY",!1));const b={};for(let w=0;w<t.variableNames.length;w++){const L=t.variableNames[w],T=!1;b[L]=e.getUniformLocation(d,L,T),b[`offset${L}`]=e.getUniformLocation(d,`offset${L}`,T)}return{program:t,source:h,webGLProgram:d,uniformLocations:b,inShapeInfos:a,outShapeInfo:c,infLoc:m,nanLoc:y}}function sC(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);e.forEach((n,s)=>{const i=n.logicalShape,o=t[s],a=o.shape;if(!ot(i,a))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${i} and ${a} must match`);if(n.isUniform&&o.isUniform)return;const c=n.texShape,h=o.isUniform?null:o.texData.texShape;if(!ot(c,h))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${c} and ${h} must match`)})}function C8(e,t,n,s,i){sC(t.inShapeInfos,n),sC([t.outShapeInfo],[s]);const o=s.texData.texture,a=s.texData.texShape;s.texData.isPacked?e.setOutputPackedMatrixTexture(o,a[0],a[1]):e.setOutputMatrixTexture(o,a[0],a[1]),e.setProgram(t.webGLProgram),C().getNumber("WEBGL_VERSION")===1&&(t.infLoc!==null&&e.gl.uniform1f(t.infLoc,Infinity)),t.nanLoc!==null&&e.gl.uniform1f(t.nanLoc,NaN),n.forEach((c,h)=>{const d=t.program.variableNames[h],m=t.uniformLocations[d],y=t.uniformLocations[`offset${d}`];if(m==null)return;if(c.isUniform){if(we(c.shape)<2)e.gl.uniform1f(m,c.uniformValues[0]);else{let b=c.uniformValues;b instanceof Float32Array||(b=new Float32Array(b)),e.gl.uniform1fv(m,b)}return}c.texData.slice!=null&&y!=null&&e.gl.uniform1i(y,c.texData.slice.flatOffset),e.setInputMatrixTexture(c.texData.texture,m,h)}),i!=null&&i(e,t.webGLProgram),e.executeProgram()}function R8(e,t,n){let s="";t.concat(n).forEach(a=>{const c=a.texData!=null&&a.texData.slice!=null&&a.texData.slice.flatOffset>0,h=a.isUniform?"uniform":a.texData.texShape;s+=`${a.shape}_${h}_${c}`});const i=e.userCode;let o=e.constructor.name;return o+="_"+s+"_"+i,o}class O8{constructor(e,t,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;const{filterWidth:s,inChannels:i,strideWidth:o,strideHeight:a,padInfo:c,outWidth:h,dilationWidth:d,dilationHeight:m,dataFormat:y}=n,{left:b,top:w}=c,L=i*s,T=Wn(),A=y==="channelsLast",N=A?0:1,E=A?1:2;let D="";for(let F=0;F<=1;F++)for(let _=0;_<=1;_++)D+=`
blockIndex = rc.y + ${_};
pos = rc.x + ${F};
if(blockIndex < ${e[1]} && pos < ${e[0]}) {
offsetY = int(blockIndex / (${h})) * ${a} - ${w};
d0 = offsetY + ${m} * (pos / ${L});
if(d0 < ${t[N]} && d0 >= 0) {
offsetX = int(mod(float(blockIndex), ${h}.) * ${o}. - ${b}.);
d1 = offsetX + ${d} * (int(mod(float(pos), ${L}.) / ${i}.));
if(d1 < ${t[E]} && d1 >= 0) {
ch = int(mod(float(pos), ${i}.));
if (${A}) {
innerDims = vec2(d1, ch);
result[${F*2+_}] = getChannel(
getA(d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
result[${F*2+_}] = getChannel(
getA(ch, int(innerDims.x),
int(innerDims.y)), innerDims);
}
}
}
}
`;this.userCode=`
void main() {
ivec2 rc = getOutputCoords();
vec4 result = vec4(0);
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
vec2 innerDims;
${D}
${T.output} = result;
}
`}}class E8{constructor(e,t,n,s,i){this.variableNames=["x"],this.outputShape=[];const o=t,a=e[3]-1;this.outputShape=e;let c;const h=`float(${n}) + float(${s}) * sum`;i===.5?c=`inversesqrt(${h})`:i===1?c=`1.0/(${h})`:c=`exp(log(${h}) * float(-${i}));`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
int d = coords[3];
float x = getX(b, r, c, d);
float sum = 0.0;
for (int j = -${o}; j <= ${o}; j++) {
int idx = d + j;
if (idx >= 0 && idx <= ${a}) {
float z = getX(b, r, c, idx);
sum += z * z;
}
}
float val = x * ${c};
setOutput(val);
}
`}}class D8{constructor(e,t,n,s,i){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=s,this.beta=i,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int r = coords[1];
int c = coords[2];
float result = 0.0;
for (int d = 0; d < ${this.depth}; ++d) {
int depthBegin = int(max(0.0, float(d - ${t})));
int depthEnd = int(min(float(${this.depth}),
float(d + ${t} + 1)));
const int MIN_DEPTH_BEGIN = 0;
const int MAX_DEPTH_END = ${this.depth};
float norm = 0.0;
for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd) {
norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
}
else {
break;
}
}
norm = float(${s}) * norm + float(${n});
for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
if (k < depthBegin){
continue;
}
else if (k >= depthBegin && k < depthEnd){
float dyi = -2.0 * float(${s})
* float(${i})
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
/ norm;
if (k == d) {
dyi += pow(norm, -1.0 * ${i});
}
if (k == coords[3]) {
dyi *= getDy(b, r, c, d);
result += dyi;
}
}
else {
break;
}
}
}
setOutput(result);
}
`}}class k8{constructor(e,t,n,s,i){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;const o=t,a=e[3]-1;this.outputShape=e;let c;const h=`float(${n}) + float(${s}) * sum`;i===.5?c=`inversesqrt(${h})`:i===1?c=`1.0/(${h})`:c=`exp(log(${h}) * float(-${i}));`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords.x;
int r = coords.y;
int c = coords.z;
int d = coords.w;
bool hasNextCol = d < ${this.outputShape[3]};
bool hasNextRow = c < ${this.outputShape[2]};
vec4 sum = vec4(0.);
vec4 xFragAtOutputCoords = getX(b, r, c, d);
vec4 xAtOutputCoords = vec4(
getChannel(xFragAtOutputCoords, vec2(c, d)),
hasNextCol ?
getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
hasNextRow ?
getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
(hasNextRow && hasNextCol) ?
getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
);
int firstChannel = d - ${o};
vec2 cache = vec2(0.);
if(firstChannel >= 0){
vec4 firstChannelFrag = getX(b, r, c, firstChannel);
cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));
if(hasNextRow){
cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));
}
}
ivec2 depth = ivec2(d, d + 1);
for (int j = - ${o}; j <= ${o}; j++) {
ivec2 idx = depth + j;
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${a}));
bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
if(depthInRange || depthPlusOneInRange){
vec4 z = vec4(0.);
vec4 xFragAtCurrentDepth;
z.xz = cache.xy;
if(depthPlusOneInRange && hasNextCol){
xFragAtCurrentDepth = idx.y != d ?
getX(b, r, c, idx.y) : xFragAtOutputCoords;
z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
if(hasNextRow){
z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
}
}
cache.xy = z.yw;
sum += z * z;
}
}
vec4 result = xAtOutputCoords * ${c};
setOutput(result);
}
`}}class F8{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideHeight,n=e.strideWidth,s=e.dilationHeight,i=e.effectiveFilterHeight,o=e.effectiveFilterWidth,a=i-1-e.padInfo.top,c=o-1-e.padInfo.left,h=i*o-1;this.userCode=`
const ivec2 pads = ivec2(${a}, ${c});
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 dyRCCorner = coords.yz - pads;
int dyRCorner = dyRCCorner.x;
int dyCCorner = dyRCCorner.y;
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wR = 0; wR < ${i};
wR += ${s}) {
float dyR = float(dyRCorner + wR) / ${t}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${o}; wC++) {
float dyC = float(dyCCorner + wC) / ${n}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(b, idyR, idyC, d);
int maxPosValue = ${h} - int(getMaxPos(b, idyR, idyC, d));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue = wR * ${o} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
setOutput(dotProd);
}
`}}class _8{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideDepth,n=e.strideHeight,s=e.strideWidth,i=e.dilationDepth,o=e.dilationHeight,a=e.dilationWidth,c=e.effectiveFilterDepth,h=e.effectiveFilterHeight,d=e.effectiveFilterWidth,m=c-1-e.padInfo.front,y=h-1-e.padInfo.top,b=d-1-e.padInfo.left,w=c*h*d-1;this.userCode=`
const ivec3 pads = ivec3(${m}, ${y}, ${b});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
int dyDCorner = dyCorner.x;
int dyRCorner = dyCorner.y;
int dyCCorner = dyCorner.z;
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
// dx(xD, xR, xC, ch).
// ? = to be determined. : = across all values in that axis.
float dotProd = 0.0;
for (int wD = 0; wD < ${c};
wD += ${i}) {
float dyD = float(dyDCorner + wD) / ${t}.0;
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
continue;
}
int idyD = int(dyD);
for (int wR = 0; wR < ${h};
wR += ${o}) {
float dyR = float(dyRCorner + wR) / ${n}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
for (int wC = 0; wC < ${d};
wC += ${a}) {
float dyC = float(dyCCorner + wC) / ${s}.0;
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
fract(dyC) > 0.0) {
continue;
}
int idyC = int(dyC);
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
int maxPosValue = ${w} -
int(getMaxPos(batch, idyD, idyR, idyC, ch));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
wD * ${h} * ${d} +
wR * ${d} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
}
setOutput(dotProd);
}
`}}class RS{constructor(e,t,n=!1,s=!1,i=!1,o=null,a=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;const c=n?e[1]:e[2],h=Math.ceil(c/2),d=n?"i * 2, rc.y":"rc.y, i * 2",m=s?"rc.z, i * 2":"i * 2, rc.z",y=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],b=s?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let w="",L="";o&&(a?w=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${o}
}`:w=`vec4 activation(vec4 x) {
${o}
}`,L="result = activation(result);");const T=i?"result += getBiasAtOutCoords();":"";i&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${w}
const float sharedDimension = ${h}.0;
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
for (int i = 0; i < ${h}; i++) {
vec4 a = getMatrixA(rc.x, ${d});
vec4 b = getMatrixB(rc.x, ${m});
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
result += (${y[0]} * ${b[0]});
result += (${y[1]} * ${b[1]});
}
return result;
}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
${T}
${L}
setOutput(result);
}
`}}class W8{constructor(e,t,n){this.variableNames=["probs"],this.outputShape=[e,n],this.userCode=`
uniform float seed;
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
float r = random(seed);
float cdf = 0.0;
for (int i = 0; i < ${t-1}; i++) {
cdf += getProbs(batch, i);
if (r < cdf) {
setOutput(float(i));
return;
}
}
// If no other event happened, last event happened.
setOutput(float(${t-1}));
}
`}getCustomSetupFunc(e){return(t,n)=>{this.seedLoc==null&&(this.seedLoc=t.getUniformLocation(n,"seed")),t.gl.uniform1f(this.seedLoc,e)}}}class $8{constructor(e,t,n,s){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int index = round(getIndices(coords.x));
setOutput(mix(float(${s}), float(${n}),
float(index == coords.y)));
}
`}}class U8{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e;const t=e.length;if(t===0)this.userCode=`
void main() {
setOutput(vec4(getA(), 0., 0., 0.));
}
`;else{const n=ls("rc",t),s=Et(t),i=M8(t,e,n),o=P8(t,e[e.length-1],e[e.length-2],n),a=z8(e,n);this.userCode=`
void main() {
${s} rc = getOutputCoords();
if(${i}) {
setOutput(vec4(0));
} else {
${o}
setOutput(vec4(${a}));
}
}
`}}}function B8(e,t){const n=[];for(let s=0;s<=1;s++)for(let i=0;i<=1;i++){let o=`${s===0?"r":"rp1"}, ${i===0?"c":"cp1"}`;for(let a=2;a<e;a++)o=`${t[t.length-1-a]},`+o;n.push(o)}return n}function M8(e,t,n){if(e===1)return`rc > ${t[0]}`;let s="";for(let i=e-2;i<e;i++)s+=`${n[i]} >= ${t[i]}`,i<e-1&&(s+="||");return s}function P8(e,t,n,s){if(e===1)return"";const i=s.slice(-2);return`
int r = ${i[0]};
int c = ${i[1]};
int rp1 = r + 1;
int cp1 = c + 1;
bool cEdge = cp1 >= ${t};
bool rEdge = rp1 >= ${n};
`}function z8(e,t){const n=e.length,s=B8(n,t);return n===1?`getA(rc),
rc + 1 >= ${e[0]} ? 0. : getA(rc + 1),
0, 0`:`getA(${s[0]}),
cEdge ? 0. : getA(${s[1]}),
rEdge ? 0. : getA(${s[2]}),
rEdge || cEdge ? 0. : getA(${s[3]})`}class G8{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((h,d)=>h[0]+e[d]+h[1]);const s=e.length,i=Et(s),o=t.map(h=>h[0]).join(","),a=t.map((h,d)=>h[0]+e[d]).join(","),c=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s);if(s===1){this.userCode=`
int start = ${o};
int end = ${a};
void main() {
int outC = getOutputCoords();
if (outC < start || outC >= end) {
setOutput(float(${n}));
} else {
setOutput(getX(outC - start));
}
}
`;return}this.userCode=`
${i} start = ${i}(${o});
${i} end = ${i}(${a});
void main() {
${i} outC = getOutputCoords();
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
setOutput(float(${n}));
} else {
${i} coords = outC - start;
setOutput(getX(${c}));
}
}
`}}class V8{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((L,T)=>L[0]+e[T]+L[1]);const s=e.length,i=Et(s),o=t.map(L=>L[0]).join(","),a=t.map((L,T)=>L[0]+e[T]).join(","),c=ls("rc",s),h=ls("source",s),d=`${c[s-1]} < ${this.outputShape[s-1]}`,m=s===1?"source":`vec2(${h.slice(-2).join()})`,y=[`${i} rc = outputLoc;`,`${c[s-1]} += 1;
if(${d}) {
`,s===1?"":`}
rc = outputLoc;
${c[s-2]} += 1;
if(${c[s-2]} < ${this.outputShape[s-2]}) {`,s===1?"":` ${c[s-1]} += 1;
if(${d}) {`],b=s===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let w="";for(let L=0,T=s===1?2:4;L<T;L++)w+=`
${y[L]}
if (${b}) {
result[${L}] = float(${n});
} else {
${i} source = rc - start;
result[${L}] = getChannel(getX(${h.join()}), ${m});
}
`;w+=s===1?"} ":"}}",this.userCode=`
const ${i} start = ${i}(${o});
const ${i} end = ${i}(${a});
void main() {
${i} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${w}
setOutput(result);
}
`}}class cu{constructor(e,t,n,s=!1,i=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");const o=e.filterWidth,a=e.strideHeight,c=e.strideWidth,h=e.dilationHeight,d=e.dilationWidth,m=e.effectiveFilterHeight,y=e.effectiveFilterWidth,b=e.padInfo.top,w=e.padInfo.left;this.outputShape=e.outShape;const L=t==="avg",T=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,A=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let N="0.0";if(L||(N="-1.0 / 1e-20"),n){const $=">=";this.userCode=`
const ivec2 strides = ivec2(${a}, ${c});
const ivec2 pads = ivec2(${b}, ${w});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
float avgValue = 0.0;
for (int wR = 0; wR < ${m};
wR += ${h}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${y};
wC += ${d}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float value = getX(batch, xR, xC, d);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
if (value ${$} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${s?i?T:A:`wR * ${y} + wC`};
}
}
}
setOutput(float(minMaxPosition));
}
`;return}const E="max";let D=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(D="avgValue / count");const F=Math.floor(o/4)*4,_=o%4,B=`
if (${L}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${E}(values, minMaxValue);
}
`;this.userCode=`
const ivec2 strides = ivec2(${a}, ${c});
const ivec2 pads = ivec2(${b}, ${w});
const float initializationValue = ${N};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xR, int xC, int d) {
if (xC < 0 || xC >= ${e.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xR, xC, d);
}
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d = coords[3];
ivec2 xRCCorner = coords.yz * strides - pads;
int xRCorner = xRCCorner.x;
int xCCorner = xRCCorner.y;
// max/min x(?, ?, d) to get y(yR, yC, d).
// ? = to be determined
vec4 minMaxValue = vec4(${N});
float avgValue = 0.0;
count = 0.0;
for (int wR = 0; wR < ${m};
wR += ${h}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${F}; wC += 4) {
int xC = xCCorner + wC * ${d};
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${d}, d),
getValue(batch, xR, xC + 2 * ${d}, d),
getValue(batch, xR, xC + 3 * ${d}, d)
);
${B}
}
int xC = xCCorner + ${F};
if (${_===1}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
${B}
} else if (${_===2}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${d}, d),
initializationValue,
initializationValue
);
${B}
} else if (${_===3}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${d}, d),
getValue(batch, xR, xC + 2 * ${d}, d),
initializationValue
);
${B}
}
}
setOutput(${D});
}
`}}class OS{constructor(e,t,n,s=!1,i=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");const o=e.filterWidth,a=e.strideDepth,c=e.strideHeight,h=e.strideWidth,d=e.dilationDepth,m=e.dilationHeight,y=e.dilationWidth,b=e.effectiveFilterDepth,w=e.effectiveFilterHeight,L=e.effectiveFilterWidth,T=e.padInfo.front,A=e.padInfo.top,N=e.padInfo.left;this.outputShape=e.outShape;const E=t==="avg";let D="0.0";if(E||(D="-1.0 / 1e-20"),n){const q=">=";this.userCode=`
const ivec3 strides =
ivec3(${a}, ${c}, ${h});
const ivec3 pads = ivec3(${T}, ${A}, ${N});
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
// ? = to be determined
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
for (int wD = 0; wD < ${b};
wD += ${d}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${w};
wR += ${m}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${L};
wC += ${y}) {
int xC = xCCorner + wC;
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
float value = getX(batch, xD, xR, xC, ch);
// If a min / max value has already been found, use it. If not,
// use the current value.
float currMinMaxValue = mix(
value, minMaxValue, minMaxValueFound);
if (value ${q} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${s?i?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${w} * ${L} +
wR * ${L} + wC`};
}
}
}
}
setOutput(float(minMaxPosition));
}
`;return}const F="max";let _=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(_="avgValue / count");const B=Math.floor(o/4)*4,$=o%4,H=`
if (${E}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${F}(values, minMaxValue);
}
`;this.userCode=`
const ivec3 strides =
ivec3(${a}, ${c}, ${h});
const ivec3 pads = ivec3(${T}, ${A}, ${N});
const float initializationValue = ${D};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float count = 0.0;
float getValue(int batch, int xD, int xR, int xC, int ch) {
if (xC < 0 || xC >= ${e.inWidth}) {
return initializationValue;
}
count += 1.0;
return getX(batch, xD, xR, xC, ch);
}
void main() {
ivec5 coords = getOutputCoords();
int batch = coords.x;
int ch = coords.u;
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
int xDCorner = xCorner.x;
int xRCorner = xCorner.y;
int xCCorner = xCorner.z;
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
// ? = to be determined
vec4 minMaxValue = vec4(${D});
float avgValue = 0.0;
count = 0.0;
for (int wD = 0; wD < ${b};
wD += ${d}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${w};
wR += ${m}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${B}; wC += 4) {
int xC = xCCorner + wC * ${y};
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${y}, ch),
getValue(batch, xD, xR, xC + 2 * ${y}, ch),
getValue(batch, xD, xR, xC + 3 * ${y}, ch)
);
${H}
}
int xC = xCCorner + ${B};
if (${$===1}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
${H}
} else if (${$===2}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${y}, ch),
initializationValue,
initializationValue
);
${H}
} else if (${$===3}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${y}, ch),
getValue(batch, xD, xR, xC + 2 * ${y}, ch),
initializationValue
);
${H}
}
}
setOutput(${_});
}
}
`}}class iC{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:s,inSize:i,outSize:o}=e;this.outputShape=[s,o];let a="0.0",c="";t==="prod"?a="1.0":t==="min"?(a="1.0 / 1e-20",c="min"):t==="max"&&(a="-1.0 / 1e-20",c="max");let h=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?h="sumValue":t==="prod"?h="prodValue":t==="all"?h="allValue":t==="any"&&(h="anyValue");const d=Math.floor(n/4)*4,m=n%4;let y=`
if (${t==="sum"}) {
sumValue += dot(values, ones);
} else if (${t==="prod"}) {
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
prodValue *= tmp[0] * tmp[1];
} else {
minMaxValue = ${c}(values, minMaxValue);
}
`,b="vec4";t==="all"?(a="1.0",y=`
bool reducedAllValue = all(values);
float floatedReducedAllValue = float(reducedAllValue);
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
`,b="bvec4"):t==="any"&&(a="0.0",y=`
bool reducedAnyValue = any(values);
float floatedReducedAnyValue = float(reducedAnyValue);
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
`,b="bvec4");let w="";i%n>0&&(w=`
if (inIdx < 0 || inIdx >= ${i}) {
return initializationValue;
}
`),this.userCode=`
const float initializationValue = ${a};
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
float getValue(int batch, int inIdx) {
${w}
return getX(batch, inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = outIdx * ${n};
vec4 minMaxValue = vec4(${a});
float prodValue = 1.0;
float sumValue = 0.0;
float allValue = 1.0;
float anyValue = 0.0;
for (int i = 0; i < ${d}; i += 4) {
int inIdx = inOffset + i;
${b} values = ${b}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
${y}
}
int inIdx = inOffset + ${d};
if (${m===1}) {
${b} values = ${b}(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
${y}
} else if (${m===2}) {
${b} values = ${b}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
${y}
} else if (${m===3}) {
${b} values = ${b}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
${y}
}
setOutput(${h});
}
`}}class rC{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;let n="";for(let s=0;s<4;s++){let i="thisRC = rc;";s%2===1&&(i+="thisRC.z += 1;"),s>1&&(i+="thisRC.y += 1;"),n+=`
${i}
${s>0?"if(thisRC.y < rows && thisRC.z < cols){":""}
int flatIndex = getFlatIndex(thisRC);
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
result[${s}] =
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
${s>0?"}":""}
`}this.userCode=`
${Y8(t)}
${vS(e)}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0.);
ivec3 thisRC;
int rows = ${e[1]};
int cols = ${e[2]};
${n}
setOutput(result);
}
`}}function Y8(e){const t=jo(["r","c","d"],e);return`
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${t}
return ivec3(r, c, d);
}
`}class H8{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;const[,s,i]=t.shape,[,o,a]=e.shape,c=[n&&o>1?s-1:s,n&&a>1?i-1:i],h=[n&&o>1?o-1:o,n&&a>1?a-1:a],d=c[0]/h[0],m=c[1]/h[1],y=1/d,b=1/m,w=Math.ceil(y)*2+2,L=Math.ceil(b)*2+2;this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
const float heightScale = float(${d});
const float widthScale = float(${m});
const float invHeightScale = float(${y});
const float invWidthScale = float(${b});
const int winHeight = int(${w});
const int winWidth = int(${L});
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(startRLerp - float(winHeight / 2));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(startCLerp - float(winWidth / 2));
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${o}) {
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${a}) {
continue;
}
float dxR = float(dyR) * heightScale;
int topDxRIndex = int(floor(dxR));
int bottomDxRIndex = int(min(ceil(dxR), ${s-1}.0));
float dxRLerp = dxR - float(topDxRIndex);
float inverseDxRLerp = 1.0 - dxRLerp;
float dxC = float(dyC) * widthScale;
int leftDxCIndex = int(floor(dxC));
int rightDxCIndex = int(min(ceil(dxC), ${i-1}.0));
float dxCLerp = dxC - float(leftDxCIndex);
float inverseDxCLerp = 1.0 - dxCLerp;
if (r == topDxRIndex && c == leftDxCIndex) {
// topLeft
accumulator +=
getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;
}
if (r == topDxRIndex && c == rightDxCIndex) {
// topRight
accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;
}
if (r == bottomDxRIndex && c == leftDxCIndex) {
// bottomLeft
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;
}
if (r == bottomDxRIndex && c == rightDxCIndex) {
// bottomRight
accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;
}
}
}
// End loop over dy
setOutput(accumulator);
}
`}}class q8{constructor(e,t,n,s){this.variableNames=["A"],this.outputShape=[];const[i,o,a,c]=e;this.outputShape=[i,t,n,c];const h=[s&&t>1?o-1:o,s&&n>1?a-1:a],d=[s&&t>1?t-1:t,s&&n>1?n-1:n];this.userCode=`
const vec2 effectiveInputOverOutputRatioRC = vec2(
${h[0]/d[0]},
${h[1]/d[1]});
const vec2 inputShapeRC = vec2(${o}.0, ${a}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;
// Compute the four integer indices.
ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);
ivec2 sourceCeilRC = ivec2(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);
float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);
float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);
float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);
vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);
float top = topLeft + (topRight - topLeft) * fracRC.y;
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
float newValue = top + (bottom - top) * fracRC.x;
setOutput(newValue);
}
`}}class j8{constructor(e,t,n,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[i,o,a,c]=e;this.outputShape=[i,t,n,c];const h=[s&&t>1?o-1:o,s&&n>1?a-1:a],d=[s&&t>1?t-1:t,s&&n>1?n-1:n];this.userCode=`
const vec3 effectiveInputOverOutputRatioRC = vec3(
${h[0]/d[0]},
${h[1]/d[1]},
${h[1]/d[1]});
const vec3 inputShapeRC = vec3(${o}.0, ${a}.0,
${a}.0);
float getAValue(int b, int r, int c, int d) {
return getChannel(getA(b, r, c, d), vec2(c, d));
}
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
// Calculate values for next column in yRC.z.
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
// Fractional source index.
vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;
// Compute the four integer indices.
ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);
ivec3 sourceCeilRC = ivec3(
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
// Should we calculate next column and row elements in 2x2 packed cell.
bool hasNextCol = d < ${c-1};
bool hasNextRow = coords.z < ${n-1};
// In parallel, construct four corners for all four components in
// packed 2x2 cell.
vec4 topLeft = vec4(
getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);
vec4 bottomLeft = vec4(
getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);
vec4 topRight = vec4(
getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);
vec4 bottomRight = vec4(
getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)
: 0.0,
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)
: 0.0,
(hasNextRow && hasNextCol) ?
getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);
vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
vec4 top = mix(topLeft, topRight, fracRC.yyzz);
vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
vec4 newValue = mix(top, bottom, fracRC.x);
setOutput(newValue);
}
`}}class K8{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;const[,s,i]=t.shape,[,o,a]=e.shape,c=[n&&o>1?s-1:s,n&&a>1?i-1:i],h=[n&&o>1?o-1:o,n&&a>1?a-1:a],d=c[0]/h[0],m=c[1]/h[1],y=1/d,b=1/m,w=Math.ceil(y)*2+2,L=Math.ceil(b)*2+2;this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
int r = coords[1];
int c = coords[2];
float accumulator = 0.0;
const float heightScale = float(${d});
const float widthScale = float(${m});
const float invHeightScale = float(${y});
const float invWidthScale = float(${b});
const int winHeight = int(${w});
const int winWidth = int(${L});
// Compute bounds for where in dy we will look
float startRLerp = floor(float(r) * invHeightScale);
int startDyR = int(floor(startRLerp - float(winHeight / 2)));
float startCLerp = floor(float(c) * invWidthScale);
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
// Loop over dy
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
int dyR = dyROffset + startDyR;
// Guard against the window exceeding the bounds of dy
if (dyR < 0 || dyR >= ${o}) {
continue;
}
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
int dyC = dyCOffset + startDyC;
// Guard against the window exceeding the bounds of dy
if (dyC < 0 || dyC >= ${a}) {
continue;
}
float sourceFracRow =
float(${c[0]}) *
(float(dyR) / float(${h[0]}));
float sourceFracCol =
float(${c[1]}) *
(float(dyC) / float(${h[1]}));
int sourceNearestRow = int(min(
float(int(${s}) - 1),
${n} ? float(round(sourceFracRow)) :
float(floor(sourceFracRow))));
int sourceNearestCol = int(min(
float(int(${i}) - 1),
${n} ? float(round(sourceFracCol)) :
float(floor(sourceFracCol))));
if (r == sourceNearestRow && c == sourceNearestCol) {
accumulator += getDy(b, dyR, dyC, d);
}
}
}
// End loop over dy
setOutput(accumulator);
}
`}}class X8{constructor(e,t,n,s){this.variableNames=["A"],this.outputShape=[];const[i,o,a,c]=e;this.outputShape=[i,t,n,c];const h=[s&&t>1?o-1:o,s&&n>1?a-1:a],d=[s&&t>1?t-1:t,s&&n>1?n-1:n],m=s?"0.5":"0.0";this.userCode=`
const vec2 effectiveInputOverOutputRatioRC = vec2(
${h[0]/d[0]},
${h[1]/d[1]});
const vec2 inputShapeRC = vec2(${o}.0, ${a}.0);
void main() {
ivec4 coords = getOutputCoords();
int b = coords[0];
int d = coords[3];
ivec2 yRC = coords.yz;
// Fractional source index.
vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;
// Compute the coordinators of nearest neighbor point.
ivec2 sourceNearestRC = ivec2(
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${m})));
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
setOutput(newValue);
}
`}}class J8{constructor(e,t){this.variableNames=["x"];const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=e,n===1){this.userCode=`
void main() {
int coord = getOutputCoords();
setOutput(getX(${e[0]} - coord - 1));
}
`;return}const s=a=>t.indexOf(a)!==-1&&e[a]!==1?`${e[a]} - coords[${a}] - 1`:`coords[${a}]`,i=e.map((a,c)=>s(c)).join(","),o=Et(n);this.userCode=`
void main() {
${o} coords = getOutputCoords();
setOutput(getX(${i}));
}
`}}class Z8{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=e;const s=ls("rc",n),i=`${s[n-1]} + 1 < ${this.outputShape[n-1]}`,o=`${s[n-2]} + 1 < ${this.outputShape[n-2]}`,a=Et(n);n===1?this.userCode=`
void main(){
int rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = getChannel(getX(${e[0]} - rc - 1),
${e[0]} - rc - 1);
if(${i}){
result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),
${e[0]} - (rc + 1) - 1);
}
setOutput(result);
}
`:this.userCode=`
void main() {
${a} rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = ${c(s.slice())};
if(${i}){
result.g = ${h(s.slice())};
}
if(${o}) {
result.b = ${d(s.slice())};
if(${i}) {
result.a = ${m(s.slice())};
}
}
setOutput(result);
}
`;function c(w){return y(w)}function h(w){return w[n-1]="("+w[n-1]+" + 1)",y(w)}function d(w){return w[n-2]="("+w[n-2]+" + 1)",y(w)}function m(w){return w[n-1]="("+w[n-1]+" + 1)",w[n-2]="("+w[n-2]+" + 1)",y(w)}function y(w){const L=e.map((N,E)=>b(E,w)),T=L.join(","),A=L.slice(-2).join(",");return`getChannel(getX(${T}), vec2(${A}))`}function b(w,L){return t.indexOf(w)!==-1&&e[w]!==1?`${e[w]} - ${L[w]} - 1`:`${L[w]}`}}}class oC{constructor(e,t,n,s,i,o,a=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=o;const c=Et(i.length),h=Et(o.length);let d="";n===1?d="i":n===2&&(d="i, j");const m=`getIndices(${d})`;let y="";s===1?y="i":s===2&&(y="i, coords[1]");const b=`getUpdates(${y})`,w=t>1?"strides[j]":"strides";this.userCode=`
${c} strides = ${c}(${i});
void main() {
${h} coords = getOutputCoords();
float sum = 0.0;
bool found = false;
for (int i = 0; i < ${e}; i++) {
int flattenedIndex = 0;
for (int j = 0; j < ${t}; j++) {
int index = round(${m});
flattenedIndex += index * ${w};
}
if (flattenedIndex == coords[0]) {
sum += ${b};
found = true;
}
}
setOutput(mix(getDefaultValue(), sum, float(found)));
}
`}}class Q8{constructor(e,t){this.variableNames=["x","segmentIds"];const n=e.windowSize,s=e.batchSize,i=e.inSize,o=e.numSegments,a=o*Math.ceil(i/n);this.outputShape=[s,a];const c="0.0",h="sumValue",d=Math.floor(n/4)*4,m=n%4,y=`
sumValue += dot(values, segFilter);
`;let b="";i%n>0&&(b=`
if (inIdx < 0 || inIdx >= ${i}) {
return initializationValue;
}
`);let w="";i%n>0&&(w=`
if (inIdx < 0 || inIdx >= ${i}) {
return -1.0;
}
`),this.userCode=`
const float initializationValue = ${c};
float getValue(int batch, int inIdx) {
${b}
return getX(batch, inIdx);
}
float getSegmentIdAtIndex(int inIdx) {
${w}
return getSegmentIds(inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = int(floor(float(outIdx) / float(
${o})) * float(${n}));
int currentSeg = int(mod(float(outIdx), float(${o})));
float sumValue = 0.0;
for (int i = 0; i < ${d}; i += 4) {
int inIdx = inOffset + i;
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
);
${y}
}
int inIdx = inOffset + ${d};
if (${m===1}) {
vec4 values = vec4(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
0,
0,
0
);
${y}
} else if (${m===2}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
0,
0
);
${y}
} else if (${m===3}) {
vec4 values = vec4(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
vec4 segFilter = vec4(
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
0
);
${y}
}
setOutput(${h});
}
`}}class e6{constructor(e,t,n){this.variableNames=["c","a","b"],this.outputShape=t;let s,i;if(n>4)throw Error(`Where for rank ${n} is not yet supported`);if(n===1)i="resRC",s="resRC";else{const a=["resRC.x","resRC.y","resRC.z","resRC.w"],c=[],h=[];for(let d=0;d<t.length;d++)h.push(`${a[d]}`),d<e&&c.push(`${a[d]}`);s=c.join(),i=h.join()}const o=Et(n);this.userCode=`
void main() {
${o} resRC = getOutputCoords();
float cVal = getC(${s});
if (cVal >= 1.0) {
setOutput(getA(${i}));
} else {
setOutput(getB(${i}));
}
}
`}}class t6{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=Et(this.rank),n=`uniform int start[${this.rank}];`,s=n6(this.rank);let i;const o=e.map((a,c)=>`sourceLoc.${ES[c]} = start[${c}] + coords.${ES[c]};`);i=`
${t} sourceLoc;
${t} coords = getOutputCoords();
${o.join(`
`)}
`,this.userCode=`
${n}
void main() {
${i}
setOutput(getSource(${s}));
}
`}getCustomSetupFunc(e){if(e.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${e.length})`);return(t,n)=>{if(this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(n,"start"),this.startLoc==null))return;t.gl.uniform1iv(this.startLoc,e)}}}const ES=["x","y","z","w","u","v"];function n6(e){if(e===1)return"sourceLoc";if(e<=6)return ES.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}class s6{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;const t=Et(this.rank),n=ls("coords",this.rank),s=ls("sourceLoc",this.rank),i=this.rank===1?"sourceLoc":`vec2(${s.slice(-2).join()})`,o=`getChannel(getSource(${s.join()}), ${i})`,a=`
result.x = ${o};
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
++${s[this.rank-1]};
result.y = ${o};
--${s[this.rank-1]};
}
`,c=this.rank===1?"":`
--${n[this.rank-1]};
if (++${n[this.rank-2]} < ${e[this.rank-2]}) {
++${s[this.rank-2]};
result.z = ${o};
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
++${s[this.rank-1]};
result.w = ${o};
}
}
`,h=this.rank<=4?`sourceLoc = coords +
${t}(${e.map((d,m)=>`start[${m}]`).join()});`:e.map((d,m)=>`${s[m]} = ${n[m]} + start[${m}];`).join(`
`);this.userCode=`
uniform int start[${this.rank}];
void main() {
${t} coords = getOutputCoords();
${t} sourceLoc;
${h}
vec4 result = vec4(0.);
${a}
${c}
setOutput(result);
}
`}getCustomSetupFunc(e){if(e.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${e.length})`);return(t,n)=>{if(this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(n,"start"),this.startLoc==null))return;t.gl.uniform1iv(this.startLoc,e)}}}class i6{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const s=n.length,i=Et(n.length),o=Et(n.length);let a="";if(s===1)a="coords * strides + begin";else{let c=0;a=n.map((h,d)=>(c++,n.length===1?`coords * strides[${d}] + begin[${d}]`:`coords[${c-1}] * strides[${d}] + begin[${d}]`)).join(",")}this.userCode=`
${i} begin = ${i}(${e});
${i} strides = ${i}(${t});
void main() {
${o} coords = getOutputCoords();
setOutput(getX(${a}));
}
`}}class r6{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(e,t,n){const s=cC(t,n),i=lC(e,s,n);i in this.freeTextures||(this.freeTextures[i]=[]),i in this.usedTextures||(this.usedTextures[i]=[]);const o=aC(e,s,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[i].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=o,this.log();const c=this.freeTextures[i].shift();return this.usedTextures[i].push(c),c}let a;return s===Sn.PACKED_2X2_FLOAT32?a=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):s===Sn.PACKED_2X2_FLOAT16?a=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):s===Sn.UNPACKED_FLOAT32?a=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):s===Sn.UNPACKED_FLOAT16?a=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):s===Sn.PACKED_4X1_UNSIGNED_BYTE&&(a=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[i].push(a),this.numUsedTextures++,this._numBytesAllocated+=o,this.log(),a}releaseTexture(e,t,n,s){if(this.freeTextures==null)return;const i=cC(n,s),o=lC(t,i,s);o in this.freeTextures||(this.freeTextures[o]=[]);const a=aC(t,i,this.gpgpu.gl,this.gpgpu.textureConfig,s),c=C().get("WEBGL_DELETE_TEXTURE_THRESHOLD");c!==-1&&this._numBytesAllocated>c?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=a):(this.freeTextures[o].push(e),this.numFreeTextures++,this._numBytesFree+=a),this.numUsedTextures--;const h=this.usedTextures[o],d=h.indexOf(e);if(d<0)throw new Error("Cannot release a texture that was never provided by this texture manager");h.splice(d,1),this.log()}log(){if(!this.logEnabled)return;const e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);const t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures==null)return;for(const e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});for(const e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}function o6(e,t){const n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;throw new Error(`Unknown internal format ${t}`)}function aC(e,t,n,s,i){const o=a6(t,s);let a;if(i){const[h,d]=lc(e[0],e[1]);a=h*d}else{const[h,d]=iu(e[0],e[1]);a=h*d}const c=o6(n,o);return a*c}function a6(e,t){switch(e){case Sn.PACKED_2X2_FLOAT32:return tC(t);case Sn.PACKED_2X2_FLOAT16:return nC(t);case Sn.UNPACKED_FLOAT32:return Z0(t);case Sn.UNPACKED_FLOAT16:return Q0(t);case Sn.PACKED_4X1_UNSIGNED_BYTE:return eC(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function c6(e){return C().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Sn.PACKED_2X2_FLOAT32:Sn.UNPACKED_FLOAT32:e?Sn.PACKED_2X2_FLOAT16:Sn.UNPACKED_FLOAT16}function cC(e,t){if(e===As.UPLOAD)return Sn.PACKED_2X2_FLOAT32;if(e===As.RENDER||e==null)return c6(t);if(e===As.DOWNLOAD||e===As.PIXELS)return Sn.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function lC(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class l6{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let o=0;o<n.length;o++)n[o]=e[o]*t[o];this.outputShape=n,this.rank=n.length;const s=Et(this.rank),i=h6(e);this.userCode=`
void main() {
${s} resRC = getOutputCoords();
setOutput(getA(${i}));
}
`}}function h6(e){const t=e.length;if(t>5)throw Error(`Tile for rank ${t} is not yet supported`);if(t===1)return`imod(resRC, ${e[0]})`;const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],s=[];for(let i=0;i<e.length;i++)s.push(`imod(${n[i]}, ${e[i]})`);return s.join()}class st{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.userCode=`
float unaryOperation(float x) {
${t}
}
void main() {
float x = getAAtOutCoords();
float y = unaryOperation(x);
setOutput(y);
}
`}}const cr="if (isnan(x)) return x;",u6="return x;",hC="return abs(x);",uC=cr+`
return (x < 0.0) ? 0.0 : x;
`,dC=cr+`
return (x < 0.0) ? 0.0 : min(6.0, x);
`,pC="return (x >= 0.0) ? x : (exp(x) - 1.0);",d6=`
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
float scaleAlpha = ${fp};
float scale = ${gp};
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
`;function p6(e=0){return cr+`
return x > 0.0 ? 1.0 : float(${e});
`}const mC="return -x;",fC="return ceil(x);",gC="return floor(x);",m6=`
if (isnan(x)) { return 0.0; }
return sign(x);
`,f6="return float(isnan(x));",g6="return float(isinf(x));",y6="return float(!isnan(x) && !isinf(x));",b6=`
// OpenGL ES does not support round function.
// The algorithm is based on banker's rounding.
float base = floor(x);
if ((x - base) < 0.5) {
return floor(x);
} else if ((x - base) > 0.5) {
return ceil(x);
} else {
if (mod(base, 2.0) == 0.0) {
return base;
} else {
return base + 1.0;
}
}
`,yC="return exp(x);",bC="return exp(x) - 1.0;",w6=`if (x < 0.0) return NAN;
return log(x);`,L6="return log(1.0 + x);",S6="return sqrt(x);",I6="return inversesqrt(x);",x6="return 1.0 / (1.0 + exp(-1.0 * x));",T6=`
float epsilon = 1.1920928955078125e-7;
float threshold = log(epsilon) + 2.0;
bool too_large = x > -threshold;
bool too_small = x < threshold;
float result;
float exp_x = exp(x);
if (too_large){
result = x;
}
else if (too_small){
result = exp_x;
}
else{
result = log(exp_x + 1.0);
}
return result;
`,A6=cr+`
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
`,v6=cr+`
if (abs(x) > 1.) {
return NAN;
}
return acos(x);
`,N6=cr+`
return atan(x);
`,C6=`
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
`,R6=`
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
`,O6=`
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
`,E6=cr+"return log(x + sqrt(x * x + 1.0));",D6=cr+`
if (x < 1.0) return NAN;
return log(x + sqrt(x * x - 1.0));`,k6=cr+`
if ((x < -1.0) || (x > 1.0)) return NAN;
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,F6=`
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
float p = ${rw};
float a1 = ${ow};
float a2 = ${aw};
float a3 = ${cw};
float a4 = ${lw};
float a5 = ${hw};
float sign = sign(x);
x = abs(x);
float t = 1.0 / (1.0 + p * x);
return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));
`,_6="return 1.0 / x;",W6="return float(!(x >= 1.0));",$6="return float(int(x));",mm="return x;";const U6="return x;",B6=`
vec4 result = log(x);
vec4 isNaN = vec4(lessThan(x, vec4(0.0)));
result.r = isNaN.r == 1.0 ? NAN : result.r;
result.g = isNaN.g == 1.0 ? NAN : result.g;
result.b = isNaN.b == 1.0 ? NAN : result.b;
result.a = isNaN.a == 1.0 ? NAN : result.a;
return result;
`,wC=`
vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`,LC=`
vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));
bvec4 isNaN = isnan(x);
result.r = isNaN.r ? x.r : result.r;
result.g = isNaN.g ? x.g : result.g;
result.b = isNaN.b ? x.b : result.b;
result.a = isNaN.a ? x.a : result.a;
return result;
`,SC=`
vec4 result;
result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);
result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);
result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);
result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);
return result;
`;class lu{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode=`
vec4 unaryOperation(vec4 x) {
${t}
}
void main() {
vec4 x = getAAtOutCoords();
vec4 y = unaryOperation(x);
setOutput(y);
}
`}}class M6{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;const t=e.length,n=ls("rc",t),s=Et(t),i=TK(t,n),o=n.slice(-2),a=t<=1?"rc":`vec2(${o.join(",")})`;this.userCode=`
void main() {
${s} rc = getOutputCoords();
vec4 packedInput = getA(${i});
setOutput(getChannel(packedInput, ${a}));
}
`}}const{segment_util:IC}=pw,P6=mw,z6=fw,G6=gw,V6=ip,Y6=1e-7,H6=1e-4,fm={};function q6(e){return e in fm||(fm[e]={}),fm[e]}function gm(e,t=!1){if(e==="linear")return t?U6:u6;if(e==="relu")return t?wC:uC;if(e==="elu")return t?SC:pC;if(e==="relu6")return t?LC:dC;if(e==="prelu")return t?G0:z0;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}const j6=128,K6=600;function X6(){return C().global.screen==null?1024:C().global.screen.height*C().global.screen.width*window.devicePixelRatio*K6/1024/1024}const xC=1e3;class J6 extends g{constructor(e){super();if(this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.warnedAboutMemory=!1,this.warnedAboutCPUBackend=!1,this.pendingDeletes=0,this.disposed=!1,!C().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){const t=Wi(C().getNumber("WEBGL_VERSION"));this.binaryCache=q6(C().getNumber("WEBGL_VERSION")),this.gpgpu=new A8(t),this.canvas=t.canvas,this.gpgpuCreatedLocally=!0}else this.gpgpu=e,this.binaryCache={},this.gpgpuCreatedLocally=!1,this.canvas=e.gl.canvas;this.textureManager=new r6(this.gpgpu),this.numMBBeforeWarning=X6(),this.texData=new p(this,_s())}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(e,t,n){if((C().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||C().getBool("DEBUG"))&&this.checkNumericalProblems(e),n==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const s={};return this.texData.set(s,{shape:t,dtype:n,values:e,usage:As.UPLOAD,refCount:1}),s}incRef(e){const t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){const t=this.texData.get(e);t.refCount--}}move(e,t,n,s){if(C().getBool("DEBUG")&&this.checkNumericalProblems(t),s==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:s,values:t,usage:As.UPLOAD,refCount:1})}disposeIntermediateTensorInfo(e){const t=e.dataId;if(this.texData.has(t)){const n=this.texData.get(t);n.refCount--,n.refCount<1&&this.disposeData(t)}}readSync(e){const t=this.texData.get(e),{values:n,dtype:s,complexTensors:i,slice:o,shape:a,isPacked:c}=t;if(o!=null){let y;c?y=new lu(a,mm):y=new st(a,mm);const b=this.runWebGLProgram(y,[{dataId:e,shape:a,dtype:s}],s),w=this.readSync(b.dataId);return this.disposeIntermediateTensorInfo(b),w}if(n!=null)return this.convertAndCacheOnCPU(e);if(s==="string")return n;const h=this.activeTimers!=null;let d;h&&(d=Yn());let m;if(s==="complex64"){const y=i.real.dataSync(),b=i.imag.dataSync();m=er(y,b)}else m=this.getValuesFromTexture(e);return h&&(this.downloadWaitMs+=Yn()-d),this.convertAndCacheOnCPU(e,m)}async read(e){if(this.pendingRead.has(e)){const w=this.pendingRead.get(e);return new Promise(L=>w.push(L))}const t=this.texData.get(e),{values:n,shape:s,slice:i,dtype:o,complexTensors:a,isPacked:c}=t;if(i!=null){let w;c?w=new lu(s,mm):w=new st(s,mm);const L=this.runWebGLProgram(w,[{dataId:e,shape:s,dtype:o}],o),T=this.read(L.dataId);return this.disposeIntermediateTensorInfo(L),T}if(n!=null)return this.convertAndCacheOnCPU(e);if(!C().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&C().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let h=null,d;if(o!=="complex64"&&C().get("WEBGL_BUFFER_SUPPORTED")){d=this.decode(e);const w=this.texData.get(d.dataId);h=this.gpgpu.createBufferFromTexture(w.texture,...ru(s))}this.pendingRead.set(e,[]),o!=="complex64"&&await this.gpgpu.createAndWaitForFence();let m;if(o==="complex64"){const w=await Promise.all([a.real.data(),a.imag.data()]),L=w[0],T=w[1];m=er(L,T)}else if(h==null)m=this.getValuesFromTexture(e);else{const w=we(s);m=this.gpgpu.downloadFloat32MatrixFromBuffer(h,w)}d!=null&&this.disposeIntermediateTensorInfo(d);const y=this.convertAndCacheOnCPU(e,m),b=this.pendingRead.get(e);return this.pendingRead.delete(e),b.forEach(w=>w(y)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e),this.pendingDeletes--),y}checkNumericalProblems(e){if(e==null)return;for(let t=0;t<e.length;t++){const n=e[t];if(!Wj(n))throw C().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")?Error(`The value ${n} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`):Error(`The value ${n} cannot be represented on this device.`)}}getValuesFromTexture(e){const{shape:t,dtype:n,isPacked:s}=this.texData.get(e),i=we(t);if(C().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){const y=this.decode(e),b=this.texData.get(y.dataId),w=this.gpgpu.downloadMatrixFromPackedTexture(b.texture,...ru(t)).subarray(0,i);return this.disposeIntermediateTensorInfo(y),w}const o=C().getBool("WEBGL_PACK")&&s===!0,a=o?TS(t):t,c=o?new n8(a):new t8(a),h=this.runWebGLProgram(c,[{shape:a,dtype:n,dataId:e}],"float32"),d=this.texData.get(h.dataId),m=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(d.texture,d.texShape[0],d.texShape[1]).subarray(0,i);return this.disposeIntermediateTensorInfo(h),m}async time(e){const t=this.activeTimers,n=[];let s=!1;this.programTimersStack==null?(this.programTimersStack=n,s=!0):this.activeTimers.push(n),this.activeTimers=n,e();const i=qi(this.activeTimers.map(c=>c.query)).filter(c=>c!=null),o=qi(this.activeTimers.map(c=>c.name)).filter(c=>c!=null);this.activeTimers=t,s&&(this.programTimersStack=null);const a={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};if(C().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const c=await Promise.all(i);a.kernelMs=$x(c),a.getExtraProfileInfo=()=>c.map((h,d)=>({name:o[d],ms:h})).map(h=>`${h.name}: ${h.ms}`).join(", ")}else a.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,a}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return C().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:Yn(),endMs:null}}endTimer(e){return C().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=Yn(),e)}async getQueryTime(e){if(C().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);const t=e;return t.endMs-t.startMs}disposeData(e){if(this.pendingDisposal.has(e))return;if(this.pendingRead.has(e)){this.pendingDisposal.add(e),this.pendingDeletes++;return}if(!this.texData.has(e))return;this.releaseGPUData(e);const{complexTensors:t}=this.texData.get(e);t!=null&&(t.real.dispose(),t.imag.dispose()),this.texData.delete(e)}releaseGPUData(e){const{texture:t,dtype:n,texShape:s,usage:i,isPacked:o,slice:a}=this.texData.get(e),c=a&&a.origDataId||e,h=this.dataRefCount.get(c);h>1?this.dataRefCount.set(c,h-1):(this.dataRefCount.delete(c),t!=null&&(this.numBytesInGPU-=this.computeBytes(s,n),this.textureManager.releaseTexture(t,s,i,o)));const d=this.texData.get(e);d.texture=null,d.texShape=null,d.isPacked=!1,d.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture}getDataInfo(e){return this.texData.get(e)}getCPUBackend(){return C().getBool("WEBGL_CPU_FORWARD")?(this.cpuBackend==null&&(this.cpuBackend=_s().findBackend("cpu")),this.cpuBackend):null}shouldExecuteOnCPU(e,t=j6){const n=this.getCPUBackend();return!this.warnedAboutCPUBackend&&n==null&&(console.warn("Your application contains ops that are small enough to be executed on the CPU backend, however the CPU backend cannot be found. Consider importing the CPU backend (@tensorflow/tfjs-backend-cpu) for better performance."),this.warnedAboutCPUBackend=!0),n!=null&&e.every(s=>this.texData.get(s.dataId).texture==null&&we(s.shape)<t)}getGPGPUContext(){return this.gpgpu}complex(e,t){const n=this.makeOutput(e.shape,"complex64"),s=this.texData.get(n.dataId);return s.complexTensors={real:_s().keep(e.clone()),imag:_s().keep(t.clone())},n}real(e){const t=this.texData.get(e.dataId);return t.complexTensors.real.clone()}imag(e){const t=this.texData.get(e.dataId);return t.complexTensors.imag.clone()}slice(e,t,n){if(this.shouldExecuteOnCPU([e])){const o=bK(this.texData.get(e.dataId).values,t,n,e.shape,e.dtype);return this.makeOutput(n,e.dtype,o)}if(we(n)===0)return en([],n,e.dtype);const{isPacked:s}=this.texData.get(e.dataId),i=rb(e.shape,t,n);if(s||!i){const o=C().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new s6(n):new t6(n),a=o.getCustomSetupFunc(t);return this.compileAndRun(o,[e],null,a)}return this.uploadToGPU(e.dataId),this.shallowSlice(e,t,n)}shallowSlice(e,t,n){const s=this.texData.get(e.dataId),i=this.makeOutput(n,e.dtype),o=this.texData.get(i.dataId);Object.assign(o,s),o.shape=n,o.dtype=e.dtype;let a=ob(t,e.strides);s.slice&&(a+=s.slice.flatOffset),o.slice={flatOffset:a,origDataId:s.slice&&s.slice.origDataId||e.dataId};const c=this.dataRefCount.get(o.slice.origDataId)||1;return this.dataRefCount.set(o.slice.origDataId,c+1),i}stridedSlice(e,t,n,s){const i=this.tryRunOnCpuOrThrow([e],()=>this.cpuBackend.stridedSlice(e,t,n,s));if(i)return i;const o=Cd(t,n,s);if(o.some(c=>c===0))return en([],o);const a=new i6(t,s,o);return this.compileAndRun(a,[e])}reverse(e,t){const n=C().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Z8(e.shape,t):new J8(e.shape,t);return this.compileAndRun(n,[e])}concat(e,t){if(e[0].dtype==="complex64"){const a=e.map(h=>Do(h)),c=e.map(h=>$a(h));return Ti(this.concat(a,t),this.concat(c,t))}if(e.length===1)return e[0];if(e.length>C().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const a=Math.floor(e.length/2),c=this.concat(e.slice(0,a),t),h=this.concat(e.slice(a),t);return this.concat([c,h],t)}if(C().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].rank>1){const a=new z5(e.map(c=>c.shape),t);return this.compileAndRun(a,e)}const n=Er(e.map(a=>a.shape),t),s=e.map(a=>a.as2D(-1,we(a.shape.slice(t)))),i=new P5(s.map(a=>a.shape)),o=this.compileAndRun(i,s);return o.reshape(n)}neg(e){const t=this.tryRunOnCpuOrThrow([e],()=>this.cpuBackend.neg(e));if(t)return t;if(C().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,mC,e.dtype);const n=new st(e.shape,mC);return this.compileAndRun(n,[e])}batchMatMul(e,t,n,s){const i=n?e.shape[2]:e.shape[1],o=s?t.shape[1]:t.shape[2],a=n?e.shape[1]:e.shape[2],[c,,]=e.shape;if((i===1||o===1)&&a>xC){n&&(e=Me(e,[0,2,1])),s&&(t=Me(t,[0,2,1]));const m=o===1?e:e.as3D(c,a,1),y=o===1?2:1,b=o===1?t.as3D(c,1,a):t;return this.multiply(m,b).sum(y,!0)}const h=Nn(e.dtype,t.dtype),d=new RS(e.shape,[c,i,o],n,s);return this.compileAndRun(d,[e,t],h)}fusedBatchMatMul({a:e,b:t,transposeA:n,transposeB:s,bias:i,activation:o,preluActivationWeights:a}){const c=n?e.shape[2]:e.shape[1],h=s?t.shape[1]:t.shape[2],[d,,]=e.shape,m=Nn(e.dtype,t.dtype),y=i!=null,b=a!=null,w=o?gm(o,!0):null,L=new RS(e.shape,[d,c,h],n,s,y,w,b),T=[e,t];return i&&T.push(i),a&&T.push(a),this.compileAndRun(L,T,m)}multiply(e,t){if(e.dtype==="complex64"){const i=this.texData.get(e.dataId),o=this.texData.get(t.dataId),a=new B0(U0.REAL,e.shape,t.shape),c=new B0(U0.IMAG,e.shape,t.shape),h=[this.makeComplexComponentTensorInfo(e,i.complexTensors.real),this.makeComplexComponentTensorInfo(e,i.complexTensors.imag),this.makeComplexComponentTensorInfo(t,o.complexTensors.real),this.makeComplexComponentTensorInfo(t,o.complexTensors.imag)],d=this.compileAndRun(a,h),m=this.compileAndRun(c,h),y=this.complex(d,m);return d.dispose(),m.dispose(),y}const n=Nn(e.dtype,t.dtype);if(this.shouldExecuteOnCPU([e,t])){const i=this.texData.get(e.dataId),o=this.texData.get(t.dataId),[a,c]=gK(e.shape,t.shape,i.values,o.values,n);return this.makeOutput(c,n,a)}if(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,P0,e.dtype);const s=new hn(P0,e.shape,t.shape);return this.compileAndRun(s,[e,t],e.dtype)}localResponseNormalization4D(e,t,n,s,i){const o=C().getBool("WEBGL_PACK_NORMALIZATION")?new k8(e.shape,t,n,s,i):new E8(e.shape,t,n,s,i);return this.compileAndRun(o,[e])}LRNGrad(e,t,n,s,i,o,a){const c=new D8(t.shape,s,i,o,a);return this.compileAndRun(c,[t,n,e])}tile(e,t){if(e.dtype==="string"){const s=this.readSync(e.dataId),i=s.map(a=>zl(a)),o=Ze(e.shape,e.dtype,i);return z6(o,t)}const n=new l6(e.shape,t);return this.compileAndRun(n,[e])}pad(e,t,n){const s=C().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new V8(e.shape,t,n):new G8(e.shape,t,n);return this.compileAndRun(s,[e])}gather(e,t,n){const s=this.tryRunOnCpuOrThrow([e,t],()=>this.cpuBackend.gather(e,t,n));if(s)return s;const i=new o8(e.shape,t.size,n);return this.compileAndRun(i,[e,t])}batchToSpaceND(e,t,n){k(e.rank<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");const s=t.reduce((d,m)=>d*m),i=Ah(e.shape,t,s),o=vh(i.length,t.length),a=Nh(e.shape,t,s),c=sw(n,t.length),h=iw(a,n,t.length);return Me(e.reshape(i),o).reshape(a).slice(c,h)}spaceToBatchND(e,t,n){k(e.rank<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");const s=t.reduce((m,y)=>m*y),i=[[0,0]];i.push(...n);for(let m=1+t.length;m<e.shape.length;++m)i.push([0,0]);const o=e.pad(i),a=Ah(o.shape,t,s,!1),c=vh(a.length,t.length,!1),h=Nh(o.shape,t,s,!1),d=Me(o.reshape(a),c);return K(d,h)}reduce(e,t,n){const s=e.shape[0],i=e.shape[1],o=ah(i),a=Math.ceil(i/o),c={windowSize:o,inSize:i,batchSize:s,outSize:a},h=new iC(c,t),d=this.compileAndRun(h,[e],n);return d.shape[1]===1?d:this.reduce(d,t,n)}argReduce(e,t,n=null){let s=e.shape[0],i=e.shape[1];n!=null&&(s=n.shape[0],i=n.shape[1]);const o=ah(i),a={windowSize:o,inSize:i,batchSize:s,outSize:Math.ceil(i/o)},c=new xK(a,t,n==null),h=[e];n!=null&&h.push(n);const d=this.compileAndRun(c,h,"int32");return d.shape[1]===1?d:this.argReduce(e,t,d)}argReducePacked(e,t,n=null){const s=n!=null?n.shape:e.shape,i=s[s.length-1],o=ah(i),a=new a5(s,o,t,n==null),c=n==null?[e]:[e,n],h=this.compileAndRun(a,c,"int32");return h.rank===e.rank?this.argReducePacked(e,t,h):h}sum(e,t){ts("sum",t,e.rank);const[n,s]=Rn(e.shape,t),i=we(s),o=e.as2D(-1,i),a=bd(e.dtype);return this.reduce(o,"sum",a).reshape(n)}prod(e,t){const n=this.tryRunOnCpuOrThrow([e],()=>this.cpuBackend.prod(e,t));if(n)return n;const[s,i]=Rn(e.shape,t),o=we(i),a=e.as2D(-1,o),c=bd(e.dtype);return this.reduce(a,"prod",c).reshape(s)}unsortedSegmentSum(e,t,n){let s=0;const i=kn([s],e.rank);let o=e;i!=null&&(o=Me(e,i),s=ws(1,e.rank)[0]);const a=IC.computeOutShape(o.shape,s,n),c=we([o.shape[s]]),h=o.as2D(-1,c),d=bd(e.dtype);let m=this.segOpCompute(h,"unsortedSegmentSum",t,d,n).reshape(a);return i!=null&&(m=Me(m,Xl(i))),m}segOpCompute(e,t,n,s,i){const o=e.shape[0],a=e.shape[1],c=IC.segOpComputeOptimalWindowSize(a,i),h={windowSize:c,inSize:a,batchSize:o,numSegments:i},d=new Q8(h,t),m=this.compileAndRun(d,[e,n],s);return m.shape[1]===i?m:(n=ph(0,i).tile([a/c]),this.segOpCompute(m,t,n,s,i))}argMinMaxReduce(e,t,n){const s=[t];if(ts("arg"+n.charAt(0).toUpperCase()+n.slice(1),s,e.rank),!C().getBool("WEBGL_PACK_REDUCE")||e.rank<=2){const[i,o]=Rn(e.shape,s),a=we(o),c=e.as2D(-1,a);return this.argReduce(c,n).reshape(i)}return this.argReducePacked(e,n)}argMin(e,t){return this.argMinMaxReduce(e,t,"min")}argMax(e,t){return this.argMinMaxReduce(e,t,"max")}cumsum(e,t,n,s){if(t!==e.rank-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${e.rank-1} but got axis=${t}`);const i=e.shape[t];let o=e;for(let a=0;a<=Math.ceil(Math.log2(i))-1;a++){const c=new q0(e.shape,!1,s),h=c.getCustomSetupFunc(a),d=o;o=this.compileAndRun(c,[o],o.dtype,h),d.dispose()}if(n){const a=new q0(e.shape,n,s),c=o;o=this.compileAndRun(a,[o]),c.dispose()}return o}equal(e,t){if(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,N5,"bool");const n=new hn(d5,e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")}notEqual(e,t){if(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,C5,"bool");const n=new hn(p5,e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")}less(e,t){const n=this.tryRunOnCpuOrThrow([e,t],()=>this.cpuBackend.less(e,t));if(n)return n;if(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,R5,"bool");const s=new hn(m5,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}lessEqual(e,t){if(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,O5,"bool");const n=new hn(f5,e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")}greater(e,t){const n=this.tryRunOnCpuOrThrow([e,t],()=>this.cpuBackend.greater(e,t));if(n)return n;if(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,E5,"bool");const s=new hn(g5,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}greaterEqual(e,t){if(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,D5,"bool");const n=new hn(y5,e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")}logicalNot(e){const t=new st(e.shape,W6);return this.compileAndRun(t,[e])}logicalAnd(e,t){if(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,k5,"bool");const n=new hn(b5,e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")}logicalOr(e,t){if(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,F5,"bool");const n=new hn(w5,e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")}select(e,t,n){const s=new e6(e.rank,t.shape,t.rank);return this.compileAndRun(s,[e,t,n],Nn(t.dtype,n.dtype))}where(e){qa("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");const t=e.dataSync();return V6(e.shape,t)}topk(e,t,n){const s=e.dataSync();return G6(s,e.shape,e.dtype,t,n)}min(e,t){ts("min",t,e.rank);const[n,s]=Rn(e.shape,t),i=we(s),o=e.as2D(-1,i);return this.reduce(o,"min",o.dtype).reshape(n)}minimum(e,t){const n=this.tryRunOnCpuOrThrow([e,t],()=>this.cpuBackend.minimum(e,t));if(n)return n;const s=C().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new jr(W5,e.shape,t.shape):new hn(S5,e.shape,t.shape);return this.compileAndRun(s,[e,t])}mod(e,t){const n=C().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new jr($5,e.shape,t.shape):new hn(I5,e.shape,t.shape);return this.compileAndRun(n,[e,t])}maximum(e,t){const n=this.tryRunOnCpuOrThrow([e,t],()=>this.cpuBackend.maximum(e,t));if(n)return n;const s=C().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new jr(_5,e.shape,t.shape):new hn(L5,e.shape,t.shape);return this.compileAndRun(s,[e,t])}all(e,t){ts("all",t,e.rank);const[n,s]=Rn(e.shape,t),i=we(s),o=e.as2D(-1,i);return this.reduce(o,"all",o.dtype).reshape(n)}any(e,t){ts("any",t,e.rank);const[n,s]=Rn(e.shape,t),i=we(s),o=e.as2D(-1,i);return this.reduce(o,"any",o.dtype).reshape(n)}floorDiv(e,t){const n=h5,s="int32";if(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,T5,s);const i=new hn(n,e.shape,t.shape);return this.compileAndRun(i,[e,t],s)}add(e,t){if(e.dtype==="complex64"&&t.dtype==="complex64")return this.complexSeparableBinaryOp(e,t,NS);const n=Nn(e.dtype,t.dtype);if(this.shouldExecuteOnCPU([e,t])){const i=this.texData.get(e.dataId),o=this.texData.get(t.dataId),[a,c]=lK(e.shape,t.shape,i.values,o.values,n);return this.makeOutput(c,n,a)}if(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,NS,n);const s=new hn(NS,e.shape,t.shape);return this.compileAndRun(s,[e,t],n)}packedUnaryOp(e,t,n){const s=new lu(e.shape,t);return this.compileAndRun(s,[e],n)}packedBinaryOp(e,t,n,s,i=!1){const o=new jr(n,e.shape,t.shape,i);return this.compileAndRun(o,[e,t],s)}complexSeparableBinaryOp(e,t,n){const s=this.texData.get(e.dataId),i=this.texData.get(t.dataId),[o,a]=[[s.complexTensors.real,i.complexTensors.real],[s.complexTensors.imag,i.complexTensors.imag]].map(h=>{const[d,m]=h,y=this.makeComplexComponentTensorInfo(e,d),b=this.makeComplexComponentTensorInfo(t,m),w=new hn(n,e.shape,t.shape);return this.compileAndRun(w,[y,b],Nn(d.dtype,m.dtype))}),c=this.complex(o,a);return o.dispose(),a.dispose(),c}makeComplexComponentTensorInfo(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}addN(e){if(e.length===1)return e[0];if(e.length>C().get("WEBGL_MAX_TEXTURES_IN_SHADER")){const o=Math.floor(e.length/2),a=this.addN(e.slice(0,o)),c=this.addN(e.slice(o));return this.addN([a,c])}const t=e.map(o=>o.dtype).reduce((o,a)=>Nn(o,a)),n=e.map(o=>o.shape),s=C().getBool("WEBGL_PACK"),i=s?new IK(e[0].shape,n):new SK(e[0].shape,n);return this.compileAndRun(i,e,t)}subtract(e,t){if(e.dtype==="complex64"&&t.dtype==="complex64")return this.complexSeparableBinaryOp(e,t,CS);const n=Nn(e.dtype,t.dtype);if(this.shouldExecuteOnCPU([e,t])){const i=this.texData.get(e.dataId),o=this.texData.get(t.dataId),[a,c]=wK(e.shape,t.shape,i.values,o.values,n);return this.makeOutput(c,n,a)}if(C().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,CS,e.dtype);const s=new hn(CS,e.shape,t.shape);return this.compileAndRun(s,[e,t],n)}pow(e,t){const n=C().getBool("WEBGL_PACK_BINARY_OPERATIONS"),s=n?new jr(A5,e.shape,t.shape):new hn(u5,e.shape,t.shape),i=Nn(e.dtype,t.dtype);return this.compileAndRun(s,[e,t],i)}ceil(e){if(this.shouldExecuteOnCPU([e])){const n=hK(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}if(C().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,fC,e.dtype);const t=new st(e.shape,fC);return this.compileAndRun(t,[e])}floor(e){if(this.shouldExecuteOnCPU([e])){const n=pK(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}if(C().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,gC,e.dtype);const t=new st(e.shape,gC);return this.compileAndRun(t,[e])}sign(e){const t=new st(e.shape,m6);return this.compileAndRun(t,[e])}isNaN(e){const t=new st(e.shape,f6);return this.compileAndRun(t,[e],"bool")}isInf(e){const t=new st(e.shape,g6);return this.compileAndRun(t,[e],"bool")}isFinite(e){const t=new st(e.shape,y6);return this.compileAndRun(t,[e],"bool")}round(e){const t=new st(e.shape,b6);return this.compileAndRun(t,[e])}exp(e){if(this.shouldExecuteOnCPU([e])){const n=uK(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}if(C().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,yC,e.dtype);const t=new st(e.shape,yC);return this.compileAndRun(t,[e])}expm1(e){if(this.shouldExecuteOnCPU([e])){const n=dK(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}if(C().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,bC,e.dtype);const t=new st(e.shape,bC);return this.compileAndRun(t,[e])}softmax(e,t){const n=gt([t],e.shape),s=jn(e,n),i=On(s.shape,n),o=this.subtract(e,s.reshape(i)),a=this.exp(o),c=this.sum(a,n).reshape(i);return _e(a,c)}log(e){if(this.shouldExecuteOnCPU([e])){const n=mK(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}if(C().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,B6,e.dtype);const t=new st(e.shape,w6);return this.compileAndRun(t,[e])}log1p(e){const t=new st(e.shape,L6);return this.compileAndRun(t,[e])}sqrt(e){const t=new st(e.shape,S6);return this.compileAndRun(t,[e])}rsqrt(e){if(this.shouldExecuteOnCPU([e])){const n=yK(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}const t=new st(e.shape,I6);return this.compileAndRun(t,[e])}reciprocal(e){const t=new st(e.shape,_6);return this.compileAndRun(t,[e])}relu(e){let t;return C().getBool("WEBGL_PACK")?t=new lu(e.shape,wC):t=new st(e.shape,uC),this.compileAndRun(t,[e])}relu6(e){let t;return C().getBool("WEBGL_PACK")?t=new lu(e.shape,LC):t=new st(e.shape,dC),this.compileAndRun(t,[e])}prelu(e,t){const n=C().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new jr(G0,e.shape,t.shape):new hn(z0,e.shape,t.shape);return this.compileAndRun(n,[e,t])}elu(e){if(C().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,SC,e.dtype);const t=new st(e.shape,pC);return this.compileAndRun(t,[e])}eluDer(e,t){const n=C().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new jr(v5,e.shape,t.shape):new hn(x5,e.shape,t.shape);return this.compileAndRun(n,[e,t])}selu(e){const t=new st(e.shape,d6);return this.compileAndRun(t,[e])}int(e){const t=new st(e.shape,$6);return this.compileAndRun(t,[e],"int32")}clip(e,t,n){let s;C().getBool("WEBGL_PACK_CLIP")?s=new B5(e.shape):s=new U5(e.shape);const i=s.getCustomSetupFunc(t,n);return this.compileAndRun(s,[e],null,i)}abs(e){if(this.shouldExecuteOnCPU([e])&&e.dtype!=="complex64"){const n=cK(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,n)}if(C().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,hC,e.dtype);const t=new st(e.shape,hC);return this.compileAndRun(t,[e])}complexAbs(e){const t=this.texData.get(e.dataId),n=new M5(e.shape),s=[this.makeComplexComponentTensorInfo(e,t.complexTensors.real),this.makeComplexComponentTensorInfo(e,t.complexTensors.imag)];return this.compileAndRun(n,s)}sigmoid(e){const t=new st(e.shape,x6);return this.compileAndRun(t,[e])}softplus(e){const t=new st(e.shape,T6);return this.compileAndRun(t,[e])}asin(e){const t=new st(e.shape,A6);return this.compileAndRun(t,[e])}acos(e){const t=new st(e.shape,v6);return this.compileAndRun(t,[e])}atan(e){const t=new st(e.shape,N6);return this.compileAndRun(t,[e])}sinh(e){const t=new st(e.shape,C6);return this.compileAndRun(t,[e])}cosh(e){const t=new st(e.shape,R6);return this.compileAndRun(t,[e])}tanh(e){const t=new st(e.shape,O6);return this.compileAndRun(t,[e])}asinh(e){const t=new st(e.shape,E6);return this.compileAndRun(t,[e])}acosh(e){const t=new st(e.shape,D6);return this.compileAndRun(t,[e])}atanh(e){const t=new st(e.shape,k6);return this.compileAndRun(t,[e])}erf(e){const t=new st(e.shape,F6);return this.compileAndRun(t,[e])}step(e,t){const n=new st(e.shape,p6(t));return this.compileAndRun(n,[e])}conv2dByMatMul(e,t,n,s,i,o){const a=e.shape,c=this.texData.get(e.dataId),h=n.inChannels,d=a[0]*a[1]*a[2],m=n.outChannels,y=n.dataFormat==="channelsLast",b=!1,w=!1,L=(d===1||m===1)&&h>xC,T=a[2]%2!==0&&!!c.isPacked;if(L||!C().getBool("WEBGL_LAZILY_UNPACK")||!C().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!T){const B=y?a[0]*a[1]*a[2]:a[0]*a[2]*a[3],$=K(e,[1,B,n.inChannels]),H=K(t,[1,n.inChannels,n.outChannels]),q=this.fusedBatchMatMul({a:$,b:H,transposeA:b,transposeB:w,bias:s,activation:i,preluActivationWeights:o});return K(q,n.outShape)}const A=y?a[0]*a[1]*(a[2]+1):a[0]*a[2]*(a[3]+1),N={dataId:e.dataId,shape:[1,A,n.inChannels],dtype:e.dtype},E=c.shape;c.shape=c.shape.slice(),c.shape[c.shape.length-2]++,k(cm(c.shape,N.shape),()=>`packed reshape ${c.shape} to ${N.shape} isn't free`);const D=K(t,[1,n.inChannels,n.outChannels]),F=this.fusedBatchMatMul({a:N,b:D,transposeA:b,transposeB:w,bias:s,activation:i,preluActivationWeights:o}),_=this.texData.get(F.dataId);return k(_.isPacked,()=>"batchMatMul result is expected to be packed"),c.shape=E,_.shape=n.outShape,_s().makeTensorFromDataId(F.dataId,n.outShape,F.dtype)}conv2dWithIm2Row(e,t,n,s,i,o){const{filterWidth:a,filterHeight:c,inChannels:h,outWidth:d,outHeight:m,dataFormat:y}=n,b=y==="channelsLast",w=a*c*h,L=m*d,T=[w,L],A=!0,N=!1,E=e.squeeze([0]),D=t.reshape([1,w,-1]),F=new O8(T,E.shape,n),_=this.compileAndRun(F,[E]).reshape([1,T[0],T[1]]),B=s!=null,$=o!=null,H=i?gm(i,!0):null,q=new RS(_.shape,[1,L,n.outChannels],A,N,B,H,$),J=[_,D];s&&J.push(s),$&&J.push(o);const re=this.compileAndRun(q,J);return b?re.reshape([1,m,d,n.outChannels]):re.reshape([1,n.outChannels,m,d])}fusedConv2d({input:e,filter:t,convInfo:n,bias:s,activation:i,preluActivationWeights:o}){if(n.filterHeight===1&&n.filterWidth===1&&n.dilationHeight===1&&n.dilationWidth===1&&n.strideHeight===1&&n.strideWidth===1&&(n.padInfo.type==="SAME"||n.padInfo.type==="VALID"))return this.conv2dByMatMul(e,t,n,s,i,o);if(C().getBool("WEBGL_CONV_IM2COL")&&e.shape[0]===1)return this.conv2dWithIm2Row(e,t,n,s,i,o);const a=s!=null,c=o!=null,h=i?gm(i,!1):null,d=new V0(n,a,h,c),m=[e,t];return s&&m.push(s),o&&m.push(o),this.compileAndRun(d,m)}conv2d(e,t,n){if(n.filterHeight===1&&n.filterWidth===1&&n.dilationHeight===1&&n.dilationWidth===1&&n.strideHeight===1&&n.strideWidth===1&&(n.padInfo.type==="SAME"||n.padInfo.type==="VALID"))return this.conv2dByMatMul(e,t,n);if(C().getBool("WEBGL_CONV_IM2COL")&&e.shape[0]===1)return this.conv2dWithIm2Row(e,t,n);const s=new V0(n);return this.compileAndRun(s,[e,t])}conv2dDerInput(e,t,n){const s=new V5(n);return this.compileAndRun(s,[e,t])}conv2dDerFilter(e,t,n){const s=new G5(n);return this.compileAndRun(s,[e,t])}fusedDepthwiseConv2D({input:e,filter:t,convInfo:n,bias:s,activation:i,preluActivationWeights:o}){const a=C().getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels===1,c=i?gm(i,a):null,h=[e,t],d=s!=null,m=o!=null;d&&h.push(s),m&&h.push(o);let y;return a?(y=new H0(n,d,c,m),this.compileAndRun(y,h)):(y=new Y0(n,d,c,m),this.compileAndRun(y,h))}depthwiseConv2D(e,t,n){let s;return C().getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels===1?(s=new H0(n),this.compileAndRun(s,[e,t])):(s=new Y0(n),this.compileAndRun(s,[e,t]))}depthwiseConv2DDerInput(e,t,n){const s=new j5(n);return this.compileAndRun(s,[e,t])}depthwiseConv2DDerFilter(e,t,n){const s=new q5(n);return this.compileAndRun(s,[e,t])}conv3d(e,t,n){const s=new K5(n);return this.compileAndRun(s,[e,t])}conv3dDerInput(e,t,n){const s=new H5(n);return this.compileAndRun(s,[e,t])}conv3dDerFilter(e,t,n){const s=new Y5(n);return this.compileAndRun(s,[e,t])}cast(e,t){return BA(e,t,this)}unstack(e,t){const n=e.shape[t],s=new Array(e.rank-1);let i=0;for(let h=0;h<e.rank;h++)h!==t&&(s[i++]=e.shape[h]);const o=new Array(e.rank).fill(0),a=e.shape.slice();a[t]=1;const c=new Array(n);for(let h=0;h<c.length;h++)o[t]=h,c[h]=this.slice(e,o,a).reshape(s);return c}avgPool3d(e,t){const n=new OS(t,"avg",!1);return this.compileAndRun(n,[e],"float32")}avgPool3dBackprop(e,t,n){const s=new l5(n);return this.compileAndRun(s,[e],t.dtype)}maxPool3d(e,t){const n=new OS(t,"max",!1);return this.compileAndRun(n,[e],"float32")}maxPool3dBackprop(e,t,n,s){const i=!0,o=new OS(s,"max",i),a=this.compileAndRun(o,[t]),c=new _8(s),h=this.compileAndRun(c,[e,a],t.dtype);return a.dispose(),h}resizeBilinear(e,t,n,s){const i=C().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new j8(e.shape,t,n,s):new q8(e.shape,t,n,s);return this.compileAndRun(i,[e],"float32")}resizeBilinearBackprop(e,t,n){const s=new H8(e,t,n);return this.compileAndRun(s,[e])}resizeNearestNeighbor(e,t,n,s){const i=new X8(e.shape,t,n,s);return this.compileAndRun(i,[e])}resizeNearestNeighborBackprop(e,t,n){const s=new K8(e,t,n);return this.compileAndRun(s,[e])}multinomial(e,t,n,s){const i=t?e:Wo(e),o=i.shape[0],a=i.shape[1],c=new W8(o,a,n),h=c.getCustomSetupFunc(s);return this.compileAndRun(c,[i],"int32",h)}oneHot(e,t,n,s){const i=new $8(e.size,t,n,s);return this.compileAndRun(i,[e])}diag(e){const t=new e8(e.size);return this.compileAndRun(t,[e])}cropAndResize(e,t,n,s,i,o){const a=new X5(e.shape,t.shape,s,i,o);return this.compileAndRun(a,[e,t,n],"float32")}depthToSpace(e,t,n){k(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`);const s=e.shape[0],i=n==="NHWC"?e.shape[1]:e.shape[2],o=n==="NHWC"?e.shape[2]:e.shape[3],a=n==="NHWC"?e.shape[3]:e.shape[1],c=i*t,h=o*t,d=a/(t*t),m=n==="NHWC"?[s,c,h,d]:[s,d,c,h],y=new Q5(m,t,n);return this.compileAndRun(y,[e])}split(e,t,n){return P6(e,t,n)}scatterND(e,t,n){const{sliceRank:s,numUpdates:i,sliceSize:o,strides:a,outputSize:c}=Da(t,e,n),h=[c/o,o],d=e.reshape([i,s]),m=t.reshape([i,o]);if(c===0)return MA(en([]),n);const y=Ne(0),b=new oC(i,s,d.rank,m.rank,a,h),w=this.compileAndRun(b,[m,d,y]);return w.reshape(n)}sparseToDense(e,t,n,s){const{sliceRank:i,numUpdates:o,strides:a,outputSize:c}=Da(t,e,n),h=!1,d=new oC(o,i,e.rank,t.rank,a,[c,1],h),m=this.compileAndRun(d,[t,e,s]);return m.reshape(n)}fft(e){const t=!1;return this.fftImpl(e,t)}ifft(e){const t=!0;return this.fftImpl(e,t)}fftImpl(e,t){const n=this.texData.get(e.dataId),s=new J0(X0.REAL,e.shape,t),i=new J0(X0.IMAG,e.shape,t),o=[this.makeComplexComponentTensorInfo(e,n.complexTensors.real),this.makeComplexComponentTensorInfo(e,n.complexTensors.imag)],a=this.compileAndRun(s,o),c=this.compileAndRun(i,o),h=this.complex(a,c).as2D(e.shape[0],e.shape[1]);return a.dispose(),c.dispose(),h}gatherND(e,t){const n=t.shape,s=n[n.length-1],[i,o,a,c]=vd(e,t),h=t.reshape([o,s]),d=e.reshape([e.size/a,a]),m=new c8(s,c,[o,a]),y=this.compileAndRun(m,[d,h]);return y.reshape(i)}fill(e,t,n){if(n=n||Ta(t),n==="string"){const s=wo(n,we(e));return s.fill(t),_s().makeTensor(s,e,n,this)}else{const s=new r8(e,t),i=s.getCustomSetupFunc(t);return this.compileAndRun(s,[],n,i)}}onesLike(e){if(e.dtype==="string")throw new Error("onesLike is not supported under string dtype");return this.fill(e.shape,1,e.dtype)}zerosLike(e){return this.fill(e.shape,e.dtype==="string"?"":0,e.dtype)}linspace(e,t,n){return dw(e,t,n)}makeTensorInfo(e,t,n){const s=this.write(n,e,t);return this.texData.get(s).usage=null,{dataId:s,shape:e,dtype:t}}makeOutput(e,t,n){const{dataId:s}=this.makeTensorInfo(e,t,n);return _s().makeTensorFromDataId(s,e,t,this)}unpackTensor(e){const t=new M6(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new U8(e.shape),n=!0;return this.runWebGLProgram(t,[e],e.dtype,null,n)}packedReshape(e,t){const n=[hc(e.shape),...uc(e.shape)],s={dtype:e.dtype,shape:n,dataId:e.dataId},i=[hc(t),...uc(t)],o=new rC(i,n),a=!0,c=this.runWebGLProgram(o,[s],e.dtype,null,a);return{dataId:c.dataId,shape:t,dtype:c.dtype}}decode(e){const t=this.texData.get(e),{isPacked:n,shape:s,dtype:i}=t,o=TS(s);let a;n?a=new Z5(o):a=new J5(o);const c=!0,h=this.runWebGLProgram(a,[{shape:o,dtype:i,dataId:e}],i,null,c);return{dtype:i,shape:s,dataId:h.dataId}}runWebGLProgram(e,t,n,s,i=!1){const o=this.makeTensorInfo(e.outputShape,n),a=this.texData.get(o.dataId);if(e.packedOutput&&(a.isPacked=!0),e.outPackingScheme===su.DENSE){const L=ru(e.outputShape);a.texShape=L.map(T=>T*2)}if(e.outTexUsage!=null&&(a.usage=e.outTexUsage),we(o.shape)===0)return a.values=bn(o.dtype,0),o;const c=[],h=t.map(L=>{if(L.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let T=this.texData.get(L.dataId);if(T.texture==null){if(!e.packedInputs&&we(L.shape)<=C().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:L.shape,texData:null,isUniform:!0,uniformValues:T.values};e.packedInputs&&(T.isPacked=!0,T.shape=L.shape)}else if(!!T.isPacked!==!!e.packedInputs)L=T.isPacked?this.unpackTensor(L):this.packTensor(L),c.push(L),T=this.texData.get(L.dataId);else if(T.isPacked&&!cm(T.shape,L.shape)){const A=L,N=L.shape;L.shape=T.shape,L=this.packedReshape(L,N),c.push(L),T=this.texData.get(L.dataId),A.shape=N}return this.uploadToGPU(L.dataId),{shape:L.shape,texData:T,isUniform:!1}});this.uploadToGPU(o.dataId);const d={shape:o.shape,texData:a,isUniform:!1},m=R8(e,h,d),y=this.getAndSaveBinary(m,()=>N8(this.gpgpu,e,h,d)),b=this.activeTimers!=null;let w;if(b&&(w=this.startTimer()),C8(this.gpgpu,y,h,d,s),c.forEach(L=>this.disposeIntermediateTensorInfo(L)),b&&(w=this.endTimer(w),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(w)})),!C().getBool("WEBGL_LAZILY_UNPACK")&&a.isPacked&&i===!1){const L=this.unpackTensor(o);return this.disposeIntermediateTensorInfo(o),L}return o}compileAndRun(e,t,n,s,i=!1){n=n||t[0].dtype;const o=this.runWebGLProgram(e,t,n,s,i);return _s().makeTensorFromDataId(o.dataId,o.shape,o.dtype)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){if(this.disposed)return;if(!C().getBool("IS_TEST")){const e=Object.keys(this.binaryCache);e.forEach(t=>{this.gpgpu.deleteProgram(this.binaryCache[t].webGLProgram),delete this.binaryCache[t]})}this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement!="undefined"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0}floatPrecision(){return this.floatPrecisionValue==null&&(this.floatPrecisionValue=ee(()=>{if(!C().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=C().getBool("DEBUG");C().set("DEBUG",!1);const t=this.abs(Ne(1e-8)).dataSync()[0];if(C().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?Y6:H6}uploadToGPU(e){const t=this.texData.get(e),{shape:n,dtype:s,values:i,texture:o,usage:a,isPacked:c}=t;if(o!=null)return;const h=this.activeTimers!=null;let d;h&&(d=Yn());let m=t.texShape;if(m==null&&(m=eK(n,c),t.texShape=m),i!=null){const y=TS(n);let b,w=m[1],L=m[0];const T=i instanceof Uint8Array;c?([w,L]=lc(m[0],m[1]),b=new i8(y,[L,w],T)):b=new s8(y,[L,w],T);const A=this.makeTensorInfo([L,w],s);T?this.texData.get(A.dataId).usage=As.PIXELS:this.texData.get(A.dataId).usage=As.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(A.dataId),w,L,i);const N=!0,E=this.runWebGLProgram(b,[A],s,null,N),D=this.texData.get(E.dataId);t.texture=D.texture,t.texShape=D.texShape,t.isPacked=D.isPacked,t.usage=D.usage,this.disposeIntermediateTensorInfo(A),this.texData.delete(E.dataId),t.values=null,h&&(this.uploadWaitMs+=Yn()-d)}else{const y=this.acquireTexture(m,a,s,c);t.texture=y}}convertAndCacheOnCPU(e,t){const n=this.texData.get(e),{dtype:s}=n;return this.releaseGPUData(e),t!=null&&(n.values=Z6(t,s)),n.values}acquireTexture(e,t,n,s){if(this.numBytesInGPU+=this.computeBytes(e,n),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){const i=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${i} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,s)}computeBytes(e,t){return e[0]*e[1]*ky(t)}tryRunOnCpuOrThrow(e,t){if(this.shouldExecuteOnCPU(e))try{return t()}catch(n){if(C().getBool("IS_TEST"))throw new Error("CPU forwarding failed")}return null}}function Z6(e,t){if(t==="float32"||t==="complex64")return e;if(t==="int32"||t==="bool"){const n=t==="int32"?new Int32Array(e.length):new Uint8Array(e.length);for(let s=0;s<n.length;++s)n[s]=Math.round(e[s]);return n}else throw new Error(`Unknown dtype ${t}`)}const Q6="2.6.0";function eX(){C().set("WEBGL_FORCE_F16_TEXTURES",!0)}Gy()&&hb("webgl",()=>new J6,2);const Lee={forceHalfFloat:eX},TC="if (isnan(x)) return x;",tX=`
if (isnan(a)) return a;
if (isnan(b)) return b;
`,nX=`
result.r = isNaN.r > 0. ? NAN : result.r;
result.g = isNaN.g > 0. ? NAN : result.g;
result.b = isNaN.b > 0. ? NAN : result.b;
result.a = isNaN.a > 0. ? NAN : result.a;
`;function ym(e){return({inputs:t,backend:n})=>{const{x:s}=t,i=n,o=new st(s.shape,e);return i.runWebGLProgram(o,[s],s.dtype)}}function DS(e,t,n,s){return({inputs:i,backend:o})=>{const{a,b:c}=i,h=o,d=C().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new jr(t,a.shape,c.shape,!!n):new hn(e,a.shape,c.shape),m=s||a.dtype,y=h.runWebGLProgram(d,[a,c],m);return y}}const sX=tX+`
return atan(a, b);
`,iX=`
vec4 result = atan(a, b);
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+nX+`
return result;
`,rX=DS(sX,iX),oX={kernelName:Si,backendName:"webgl",kernelFunc:rX};function kS(e){const{inputs:t,backend:n}=e,{x:s}=t;return n.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const aX={kernelName:yl,backendName:"webgl",kernelFunc:kS};function cX(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;ou(i,"avgPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:h}=s,d=1;k(rn(a,d),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${d}'`);const m=Fn(i.shape,o,a,d,c,h);if(m.filterWidth===1&&m.filterHeight===1&&ot(m.inShape,m.outShape))return kS({inputs:{x:i},backend:n});const y=new cu(m,"avg",!1);return n.runWebGLProgram(y,[i],"float32")}const lX={kernelName:Qs,backendName:"webgl",kernelFunc:cX};function hX(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o}=t,a=o;ou([i,o],"avgPoolBackprop");const{filterSize:c,strides:h,pad:d}=s,m=Fn(a.shape,c,h,1,d),y=new c5(m);return n.runWebGLProgram(y,[i],a.dtype)}const uX={kernelName:ya,backendName:"webgl",kernelFunc:hX};class dX{constructor(e,t,n,s,i,o){this.outputShape=[],this.variableNames=["x","mean","variance"],tt(e,t),tt(e,n);let a="0.0";s!=null&&(tt(e,s),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let c="1.0";i!=null&&(tt(e,i),this.variableNames.push("scale"),c="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
void main() {
float x = getXAtOutCoords();
float mean = getMeanAtOutCoords();
float variance = getVarianceAtOutCoords();
float offset = ${a};
float scale = ${c};
float inv = scale * inversesqrt(variance + float(${o}));
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
}
`}}class pX{constructor(e,t,n,s,i,o){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],tt(e,t),tt(e,n);let a="vec4(0.0)";s!=null&&(tt(e,s),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let c="vec4(1.0)";i!=null&&(tt(e,i),this.variableNames.push("scale"),c="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
void main() {
vec4 offset = ${a};
vec4 scale = ${c};
vec4 x = getXAtOutCoords();
vec4 mean = getMeanAtOutCoords();
vec4 variance = getVarianceAtOutCoords();
vec4 inv = scale * inversesqrt(variance + vec4(${o}));
setOutput((x - mean) * inv + offset);
}
`}}const mX=({inputs:e,backend:t,attrs:n})=>{const{x:s,mean:i,variance:o,offset:a,scale:c}=e;k(i.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),k(a==null||i.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),k(c==null||i.shape.length===c.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:h}=n;h==null&&(h=.001);const d=[s,i,o];let m=null;a!=null&&(m=a.shape,d.push(a));let y=null;c!=null&&(y=c.shape,d.push(c));const b=C().getBool("WEBGL_PACK_NORMALIZATION")?new pX(s.shape,i.shape,o.shape,m,y,h):new dX(s.shape,i.shape,o.shape,m,y,h),w=t.runWebGLProgram(b,d,d[0].dtype);return w},fX={kernelName:gl,backendName:"webgl",kernelFunc:mX};const gX=TC+`
return cos(x);
`,yX=ym(gX),bX={kernelName:ba,backendName:"webgl",kernelFunc:yX};const wX=`
if (a == b) {
return 1.0;
};
return a / b;`,LX=`
// vec4 one = vec4(equal(a, b));
// return one + (vec4(1.0) - one) * a / b;
vec4 result = a / b;
if(a.x == b.x) {
result.x = 1.;
}
if(a.y == b.y) {
result.y = 1.;
}
if(a.z == b.z) {
result.z = 1.;
}
if(a.w == b.w) {
result.w = 1.;
}
return result;
`,SX=DS(wX,LX,!0),IX={kernelName:wa,backendName:"webgl",kernelFunc:SX};class xX{constructor(e){this.variableNames=["Image"],this.outputShape=[];const t=e[2];this.outputShape=e,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int coordX = ${t} - x;
float outputValue;
if(coordX >= 0 && coordX < ${t}) {
outputValue = getImage(coords[0], coords[1], coordX, coords[3]);
} else {
outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);
}
setOutput(outputValue);
}
`}}const TX={kernelName:Ju,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:n}=e,s=t,i=new xX(n.shape),o=s.runWebGLProgram(i,[n],n.dtype);return o}};class AX{constructor(e){this.variableNames=["A"];const t=Wn(),[n,s]=e;this.outputShape=e,this.userCode=`
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${s}.0, ${n}.0);
vec4 values = ${t.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
setOutput(floor(value * 255.0 + 0.5));
}
`}}class vX{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=Wn(),[n,s]=e;this.outputShape=e,this.userCode=`
void main() {
ivec3 coords = getOutputCoords();
int texR = coords[0];
int texC = coords[1];
int depth = coords[2];
vec4 result = vec4(0.);
for(int row=0; row<=1; row++) {
for(int col=0; col<=1; col++) {
texC = coords[1] + row;
depth = coords[2] + col;
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${s}.0, ${n}.0);
vec4 values = ${t.texture2D}(A, uv);
float value;
if (depth == 0) {
value = values.r;
} else if (depth == 1) {
value = values.g;
} else if (depth == 2) {
value = values.b;
} else if (depth == 3) {
value = values.a;
}
result[row * 2 + col] = floor(value * 255.0 + 0.5);
}
}
${t.output} = result;
}
`}}const NX={kernelName:ld,backendName:"webgl",kernelFunc:CX};let gc;function CX(e){const{inputs:t,backend:n,attrs:s}=e;let{pixels:i}=t;const{numChannels:o}=s,a=typeof HTMLVideoElement!="undefined"&&i instanceof HTMLVideoElement,c=typeof HTMLImageElement!="undefined"&&i instanceof HTMLImageElement,[h,d]=a?[i.videoWidth,i.videoHeight]:[i.width,i.height],m=[d,h],y=[d,h,o];(c||a)&&(gc==null&&(gc=document.createElement("canvas").getContext("2d")),gc.canvas.width=h,gc.canvas.height=d,gc.drawImage(i,0,0,h,d),i=gc.canvas);const b=n.makeTensorInfo(m,"int32");n.texData.get(b.dataId).usage=As.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(b.dataId),i);const w=C().getBool("WEBGL_PACK")?new vX(y):new AX(y),L=n.runWebGLProgram(w,[b],"int32");return n.disposeData(b.dataId),L}function RX(e){const t=[];for(;t.length===0||t[t.length-1].outSize!==1;){const n=t.length?t[t.length-1].outSize:e[1],s=ah(n);t.push({inSize:n,windowSize:s,outSize:Math.ceil(n/s)})}return t}function OX(e,t,n,s){const i=RX(e.shape);let o=e;for(let a=0;a<i.length;a++){const{inSize:c,windowSize:h,outSize:d}=i[a],m=new iC({windowSize:h,inSize:c,batchSize:e.shape[0],outSize:d},n),y=o;o=s.runWebGLProgram(m,[o],t),y.dataId!==e.dataId&&s.disposeData(y.dataId)}return o}function EX(e,t,n){const s=[hc(e.shape),...uc(e.shape)],i={dtype:e.dtype,shape:s,dataId:e.dataId},o=[hc(t),...uc(t)],a=new rC(o,s),c=!0,h=n.runWebGLProgram(a,[i],e.dtype,null,c);return{dataId:h.dataId,shape:t,dtype:h.dtype}}function FS(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{shape:o}=s,a=n,c=we(i.shape),h=md(o,c),d=we(h);k(c===d,()=>`The new shape (${h}) has ${d} elements and the old shape (${i.shape}) has ${c} elements. The new shape and old shape must have the same number of elements.`);const m=a.texData.get(i.dataId);return m.isPacked&&!cm(i.shape,h)&&!(m.texture!==null&&cm(m.shape,h))?EX(i,h,a):(a.incRef(i.dataId),{dataId:i.dataId,shape:h,dtype:i.dtype})}const DX={kernelName:Nl,backendName:"webgl",kernelFunc:FS};function kX(e,t,n,s){const i=we(t),o=we(e.shape),a=o/i,c=FS({inputs:{x:e},attrs:{shape:[a,i]},backend:s}),h=OX(c,e.dtype,"max",s),d=FS({inputs:{x:h},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(c),s.disposeIntermediateTensorInfo(h),d}class FX{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let o=0;o<n.length;o++)n[o]=e[t[o]];this.outputShape=n,this.rank=n.length;const s=Et(this.rank),i=_X(t);this.userCode=`
void main() {
${s} resRC = getOutputCoords();
setOutput(getA(${i}));
}
`}}function _X(e){const t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],s=new Array(t);for(let i=0;i<e.length;i++)s[e[i]]=n[i];return s.join()}class WX{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;const n=new Array(e.length);for(let d=0;d<n.length;d++)n[d]=e[t[d]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const s=Et(this.rank),i=k0("rc",this.rank),o=new Array(this.rank);for(let d=0;d<t.length;d++)o[t[d]]=i[d];const a=`vec2(${o.slice(-2).join()})`,c=`++${i[this.rank-1]} < ${n[this.rank-1]}`,h=`getChannel(getA(${o.join()}), ${a})`;this.userCode=`
void main() {
${s} rc = getOutputCoords();
vec4 result = vec4(0.);
result[0] = ${h};
if(${c}) {
result[1] = ${h};
}
--${i[this.rank-1]};
if(++${i[this.rank-2]} < ${n[this.rank-2]}) {
result[2] = ${h};
if(${c}) {
result[3] = ${h};
}
}
setOutput(result);
}
`}}function AC(e,t,n){const s=C().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new WX(e.shape,t):new FX(e.shape,t);return n.runWebGLProgram(s,[e],e.dtype)}const $X={kernelName:xl,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{reductionIndices:i,keepDims:o}=t,a=n,c=s.shape.length,h=gt(i,s.shape);let d=h;const m=kn(d,c),y=m!=null,b=a.shouldExecuteOnCPU([s]);let w=s;if(y){if(b){const E=a.texData.get(w.dataId),D=E.values,F=new Array(c);for(let $=0;$<F.length;$++)F[$]=s.shape[m[$]];const _=D0(D,s.shape,s.dtype,m,F);w=a.makeTensorInfo(F,s.dtype);const B=a.texData.get(w.dataId);B.values=_}else w=AC(s,m,a);d=ws(d.length,c)}ts("max",d,c);const[L,T]=Rn(w.shape,d);let A=L;o&&(A=On(L,h));let N;if(b){const E=a.texData.get(w.dataId),D=E.values,F=fK(D,we(T),A,s.dtype);N=a.makeTensorInfo(A,s.dtype);const _=a.texData.get(N.dataId);_.values=F}else N=kX(w,T,A,a);return y&&a.disposeIntermediateTensorInfo(w),N}};function UX(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;ou(i,"maxPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:h}=s,d=1;k(rn(a,d),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${d}'`);const m=Fn(i.shape,o,a,d,c,h);if(m.filterWidth===1&&m.filterHeight===1&&ot(m.inShape,m.outShape))return kS({inputs:{x:i},backend:n});const y=new cu(m,"max",!1);return n.runWebGLProgram(y,[i],i.dtype)}const BX={kernelName:Tl,backendName:"webgl",kernelFunc:UX};function MX(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o,output:a}=t,c=o;ou([o,a],"maxPoolBackprop");const{filterSize:h,strides:d,pad:m,dimRoundingMode:y}=s,b=Fn(c.shape,h,d,1,m,y),w=!0,L=new cu(b,"max",w),T=n.runWebGLProgram(L,[c],c.dtype),A=new F8(b),N=n.runWebGLProgram(A,[i,T],c.dtype);return n.disposeIntermediateTensorInfo(T),N}const PX={kernelName:Qu,backendName:"webgl",kernelFunc:MX};function zX(e,t,n,s){let i=new cu(n,"max",!1);const o=s.runWebGLProgram(i,[e],"float32");i=new cu(n,"max",!0,!0,t);const a=s.runWebGLProgram(i,[e],"float32");return[o,a]}const GX={kernelName:ed,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{filterSize:i,strides:o,pad:a,includeBatchInIndex:c}=t,h=n;k(s.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${s.shape.length}.`);const d=[1,1];k(rn(o,d),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${d}'`);const m=Fn(s.shape,i,o,d,a),[y,b]=zX(s,c,m,h);return[y,b]}};const VX={kernelName:iy,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{qa("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{boxes:s,scores:i}=e,{maxOutputSize:o,iouThreshold:a,scoreThreshold:c}=n,h=t,d=h.readSync(s.dataId),m=h.readSync(i.dataId),y=o,b=a,w=c;return up(d,m,y,b,w)}};const YX=dp,HX={kernelName:nd,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{qa("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{boxes:s,scores:i}=e,{maxOutputSize:o,iouThreshold:a,scoreThreshold:c,padToMaxOutputSize:h}=n,d=t,m=d.readSync(s.dataId),y=d.readSync(i.dataId),{selectedIndices:b,validOutputs:w}=YX(m,y,o,a,c,h);return[b,w]}};const qX=pp,jX={kernelName:sd,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{qa("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{boxes:s,scores:i}=e,{maxOutputSize:o,iouThreshold:a,scoreThreshold:c,softNmsSigma:h}=n,d=t,m=d.readSync(s.dataId),y=d.readSync(i.dataId),b=o,w=a,L=c,T=h,{selectedIndices:A,selectedScores:N}=qX(m,y,b,w,L,T);return[A,N]}};class KX{constructor(e,t,n,s){this.variableNames=["Image"],this.outputShape=[];const i=e[1],o=e[2],a=Math.sin(t).toFixed(3),c=Math.cos(t).toFixed(3);this.outputShape=e;const[h,d]=nw(s,i,o),m=h.toFixed(3),y=d.toFixed(3);let b="";typeof n=="number"?b=`float outputValue = ${n.toFixed(2)};`:b=`
vec3 fill = vec3(${n.join(",")});
float outputValue = fill[coords[3]];`,this.userCode=`
void main() {
ivec4 coords = getOutputCoords();
int x = coords[2];
int y = coords[1];
float coordXFloat = (float(x) - ${m}) * ${c} - (float(y) - ${y}) * ${a};
float coordYFloat = (float(x) - ${m}) * ${a} + (float(y) - ${y}) * ${c};
int coordX = int(round(coordXFloat + ${m}));
int coordY = int(round(coordYFloat + ${y}));
${b}
if(coordX >= 0 && coordX < ${o} && coordY >= 0 && coordY < ${i}) {
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
}
setOutput(outputValue);
}
`}}const XX={kernelName:hd,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,{radians:i,fillValue:o,center:a}=t,c=n,h=new KX(s.shape,i,o,a),d=c.runWebGLProgram(h,[s],s.dtype);return d}};const JX=TC+`
return sin(x);
`,ZX=ym(JX),QX={kernelName:La,backendName:"webgl",kernelFunc:ZX};const e7="return x * x;",t7=ym(e7),n7={kernelName:ad,backendName:"webgl",kernelFunc:t7};const vC="return (a - b) * (a - b);",s7=DS(vC,vC),i7={kernelName:Sa,backendName:"webgl",kernelFunc:s7};const r7="return tan(x);",o7=ym(r7),a7={kernelName:Ia,backendName:"webgl",kernelFunc:o7};const c7={kernelName:Ul,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{perm:i}=t,o=n,a=s.shape.length,c=new Array(a);for(let d=0;d<c.length;d++)c[d]=s.shape[i[d]];let h;if(o.shouldExecuteOnCPU([s])){const d=o.texData.get(s.dataId),m=d.values,y=D0(m,s.shape,s.dtype,i,c);h=o.makeTensorInfo(c,s.dtype);const b=o.texData.get(h.dataId);b.values=y}else h=AC(s,i,o);return h}};function l7(e){const{inputs:t,attrs:n,backend:s}=e,{axis:i}=n,{x:o}=t;ou(o,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const a=s.readSync(o.dataId),{outputValues:c,outputShape:h,indices:d}=LK(a,i,o.shape,o.dtype);return[s.makeTensorInfo(h,o.dtype,c),s.makeTensorInfo([d.length],"int32",d)]}const h7={kernelName:cd,backendName:"webgl",kernelFunc:l7};const u7=[oX,lX,uX,fX,bX,IX,TX,NX,aX,$X,BX,PX,GX,VX,HX,jX,DX,XX,QX,n7,i7,a7,c7,h7];for(const e of u7)dd(e);const d7="2.6.0";const p7={"tfjs-core":OT,"tfjs-backend-cpu":Iq,"tfjs-backend-webgl":Q6,"tfjs-data":o0,"tfjs-layers":zp,"tfjs-converter":UN,tfjs:d7};r.Abs=ge,r.Acos=fe,r.Acosh=Ae,r.AdadeltaOptimizer=wh,r.AdagradOptimizer=Lh,r.AdamOptimizer=Sh,r.AdamaxOptimizer=Ih,r.Add=Te,r.AddN=Ve,r.All=rt,r.Any=Ct,r.ArgMax=Ut,r.ArgMin=Kt,r.Asin=Dn,r.Asinh=An,r.Atan=vn,r.Atan2=Si,r.Atanh=Zs,r.AvgPool=Qs,r.AvgPool3D=ol,r.AvgPool3DBackprop=ax,r.AvgPoolBackprop=ya,r.BatchMatMul=_g,r.BatchToSpaceND=Wg,r.BroadcastTo=$g,r.Callback=xN,r.CallbackList=yv,r.Cast=al,r.Ceil=cl,r.ClipByValue=ll,r.Complex=Ug,r.Concat=qu,r.Conv2D=Bg,r.Conv2DBackpropFilter=cx,r.Conv2DBackpropInput=Mg,r.Conv3D=Pg,r.Conv3DBackpropFilterV2=lx,r.Conv3DBackpropInputV2=hx,r.Cos=ba,r.Cosh=hl,r.CropAndResize=ux,r.Cumsum=zg,r.CustomCallback=wv,r.DataStorage=p,r.DepthToSpace=dx,r.DepthwiseConv2dNative=Gg,r.DepthwiseConv2dNativeBackpropFilter=px,r.DepthwiseConv2dNativeBackpropInput=mx,r.Diag=fx,r.Dilation2D=ju,r.Dilation2DBackpropFilter=Xu,r.Dilation2DBackpropInput=Ku,r.Div=wa,r.EarlyStopping=AN,r.Elu=ul,r.EluGrad=gx,r.Environment=S,r.Equal=yx,r.Erf=dl,r.Exp=pl,r.Expm1=ml,r.FFT=Vg,r.Fill=bx,r.FlipLeftRight=Ju,r.Floor=fl,r.FloorDiv=Yg,r.FromPixels=ld,r.FusedBatchNorm=gl,r.FusedConv2D=Ty,r.FusedDepthwiseConv2D=Ay,r.GatherNd=wx,r.GatherV2=Hg,r.GraphModel=$N,r.Greater=Lx,r.GreaterEqual=qg,r.History=bv,r.IFFT=jg,r.Identity=yl,r.Imag=Kg,r.InputSpec=mn,r.IsFinite=bl,r.IsInf=wl,r.IsNan=Ll,r.KernelBackend=g,r.LRN=Jg,r.LRNBackprop=vx,r.LayerVariable=ai,r.LayersModel=ir,r.Less=Sx,r.LessEqual=Ix,r.LinSpace=xx,r.Log=Sl,r.Log1p=Il,r.LogSoftmax=Xg,r.LogicalAnd=Tx,r.LogicalNot=Zu,r.LogicalOr=Ax,r.Max=xl,r.MaxPool=Tl,r.MaxPool3D=Qg,r.MaxPool3DBackprop=Nx,r.MaxPoolBackprop=Qu,r.MaxPoolWithArgmax=ed,r.Maximum=Zg,r.Mean=YD,r.Min=ey,r.Minimum=ty,r.Mod=ny,r.MomentumOptimizer=xh,r.Multiply=Al,r.Negate=sy,r.NonMaxSuppressionV3=iy,r.NonMaxSuppressionV4=nd,r.NonMaxSuppressionV5=sd,r.NotEqual=td,r.OP_SCOPE_SUFFIX=tT,r.OneHot=oy,r.OnesLike=ry,r.Optimizer=Qi,r.PadV2=id,r.Pool=HD,r.Pow=ay,r.Prelu=cy,r.Prod=Cx,r.RMSPropOptimizer=Th,r.RNN=_i,r.Range=Rx,r.Real=ly,r.Reciprocal=vl,r.Relu=hy,r.Relu6=py,r.Reshape=Nl,r.ResizeBilinear=dy,r.ResizeBilinearGrad=Ex,r.ResizeNearestNeighbor=uy,r.ResizeNearestNeighborGrad=Ox,r.Reverse=my,r.RotateWithOffset=hd,r.Round=Cl,r.Rsqrt=Rl,r.SGDOptimizer=Ha,r.ScatterNd=Dx,r.SelectV2=fy,r.Selu=Ol,r.Sequential=ec,r.Sigmoid=kl,r.Sign=Dl,r.Sin=La,r.Sinh=El,r.Slice=rd,r.Softmax=by,r.Softplus=Fl,r.SpaceToBatchND=od,r.SparseToDense=kx,r.SplitV=yy,r.Sqrt=_l,r.Square=ad,r.SquaredDifference=Sa,r.Step=Bl,r.StridedSlice=Fx,r.Sub=Wl,r.Sum=gy,r.SymbolicTensor=ci,r.Tan=Ia,r.Tanh=$l,r.Tensor=Q,r.TensorBuffer=vr,r.Tile=wy,r.TopK=_x,r.Transpose=Ul,r.Unique=cd,r.Unpack=Ly,r.UnsortedSegmentSum=Sy,r.Variable=Hl,r.ZerosLike=Iy,r._FusedMatMul=xy,r.abs=sn,r.acos=ub,r.acosh=db,r.add=be,r.addN=kT,r.addStrict=lA,r.all=kd,r.any=Jl,r.argMax=Zl,r.argMin=mb,r.asin=fb,r.asinh=gb,r.atan=yb,r.atan2=bb,r.atanh=wb,r.avgPool=nh,r.avgPool3d=Ib,r.backend=DT,r.backend_util=pw,r.basicLSTMCell=g_,r.batchNorm=No,r.batchNorm2d=_T,r.batchNorm3d=WT,r.batchNorm4d=$T,r.batchToSpaceND=sh,r.booleanMaskAsync=NU,r.broadcastTo=ih,r.browser=wF,r.buffer=Ze,r.callbacks=KV,r.cast=ve,r.ceil=Tb,r.clipByValue=Hn,r.clone=Rr,r.complex=Ti,r.concat=Pt,r.concat1d=UT,r.concat2d=BT,r.concat3d=MT,r.concat4d=PT,r.constraints=Lz,r.conv1d=$d,r.conv2d=Xi,r.conv2dTranspose=Ud,r.conv3d=vb,r.conv3dTranspose=$_,r.copyRegisteredKernels=KD,r.cos=rh,r.cosh=Bd,r.cosineWindow=Zb,r.cumsum=Md,r.customGrad=Ci,r.data=GH,r.deprecationWarn=nn,r.depthToSpace=Nb,r.depthwiseConv2d=Co,r.deregisterOp=JV,r.device_util=wk,r.diag=V_,r.dilation2d=Cb,r.disableDeprecationWarnings=DF,r.dispose=He,r.disposeVariables=kF,r.div=_e,r.divNoNan=Rb,r.divStrict=hA,r.dot=GT,r.dropout=SA,r.elu=Oo,r.enableDebugMode=EF,r.enableProdMode=OF,r.enclosingPowerOfTwo=IA,r.engine=_s,r.env=C,r.equal=ti,r.equalStrict=sA,r.erf=Ob,r.exp=Ls,r.expandDims=qn,r.expm1=Eb,r.eye=Pd,r.fft=fh,r.fill=oh,r.findBackend=BF,r.findBackendFactory=MF,r.floor=_a,r.floorDiv=Dd,r.fused=oB,r.gather=Wa,r.gatherND=LA,r.gather_util=LF,r.getBackend=$F,r.getGradient=Ny,r.getKernel=vy,r.getKernelsForBackend=ud,r.grad=IW,r.grads=xW,r.greater=Ss,r.greaterEqual=Ji,r.greaterEqualStrict=iA,r.greaterStrict=rA,r.ifft=za,r.imag=$a,r.image=$r,r.inTopKAsync=QU,r.initializers=n3,r.input=Gv,r.io=lF,r.irfft=np,r.isFinite=YT,r.isInf=HT,r.isNaN=qT,r.keep=Cn,r.kernel_impls=fM,r.layers=vV,r.leakyRelu=zd,r.less=ch,r.lessEqual=kr,r.lessEqualStrict=oA,r.lessStrict=aA,r.linalg=DA,r.linspace=jT,r.loadGraphModel=aH,r.loadLayersModel=iG,r.localResponseNormalization=kb,r.log=ns,r.log1p=Gd,r.logSigmoid=KT,r.logSoftmax=Yd,r.logSumExp=_b,r.logicalAnd=$s,r.logicalNot=lh,r.logicalOr=Hd,r.logicalXor=XT,r.losses=dM,r.matMul=at,r.math=gF,r.max=jn,r.maxPool=hh,r.maxPool3d=Wb,r.maxPoolWithArgmax=JT,r.maximum=Ws,r.maximumStrict=uA,r.mean=Gt,r.memory=Ed,r.metrics=zV,r.min=Ba,r.minimum=Eo,r.minimumStrict=dA,r.mod=qd,r.modStrict=pA,r.model=nG,r.models=GV,r.moments=jd,r.movingAverage=YU,r.mul=X,r.mulStrict=mA,r.multiRNNCell=jW,r.multinomial=ZT,r.neg=zt,r.nextFrame=mp,r.norm=rp,r.notEqual=Fr,r.notEqualStrict=cA,r.oneHot=To,r.ones=ni,r.onesLike=En,r.op=P,r.outerProduct=e$,r.pad=Ri,r.pad1d=s$,r.pad2d=r$,r.pad3d=a$,r.pad4d=l$,r.pool=QT,r.pow=si,r.powStrict=fA,r.prelu=dh,r.print=hT,r.prod=Kd,r.profile=FF,r.rand=b$,r.randomGamma=D$,r.randomNormal=Bb,r.randomUniform=_o,r.range=ph,r.ready=WF,r.real=Do,r.reciprocal=Mb,r.registerBackend=hb,r.registerCallbackConstructor=rG,r.registerGradient=Wx,r.registerKernel=dd,r.registerOp=XV,r.regularizers=qV,r.relu=Oi,r.relu6=Pb,r.removeBackend=UF,r.reshape=K,r.reverse=Is,r.reverse1d=M$,r.reverse2d=z$,r.reverse3d=V$,r.reverse4d=H$,r.rfft=gh,r.round=zb,r.rsqrt=Xd,r.scalar=Ne,r.scatterND=wA,r.scatter_util=SF,r.selu=Jd,r.separableConv2d=Gb,r.sequential=sG,r.serialization=IF,r.setBackend=ET,r.setPlatform=PF,r.setdiff1dAsync=eA,r.sigmoid=Ni,r.sign=Vb,r.signal=uM,r.sin=Zd,r.sinh=Qd,r.slice=nt,r.slice1d=ep,r.slice2d=Yb,r.slice3d=tp,r.slice4d=mh,r.slice_util=CT,r.softmax=Wo,r.softplus=Ua,r.spaceToBatchND=uh,r.sparseToDense=Jb,r.spectral=hM,r.split=is,r.sqrt=Ln,r.square=wt,r.squaredDifference=yh,r.squaredDifferenceStrict=gA,r.squeeze=_r,r.stack=rs,r.step=Ga,r.stridedSlice=Hb,r.sub=Ce,r.subStrict=yA,r.sum=Ue,r.sumOutType=bd,r.tan=qb,r.tanh=Fa,r.tensor=en,r.tensor1d=ss,r.tensor2d=Wr,r.tensor3d=yT,r.tensor4d=Va,r.tensor5d=bU,r.tensor6d=wU,r.tensor_util=fk,r.test_util=RF,r.tidy=ee,r.tile=Dr,r.time=_F,r.topk=jb,r.train=Uo,r.transpose=Me,r.truncatedNormal=bh,r.unique=sp,r.unregisterGradient=jD,r.unregisterKernel=qD,r.unsortedSegmentSum=Kb,r.unstack=Ei,r.upcastType=Nn,r.util=nk,r.valueAndGrad=TW,r.valueAndGrads=AW,r.variable=nA,r.variableGrads=Fb,r.version=p7,r.version_converter=UN,r.version_core=OT,r.version_layers=zp,r.where=_n,r.whereAsync=Xb,r.zeros=ct,r.zerosLike=Qe,Object.defineProperty(r,"__esModule",{value:!0})})});var DC=Lm((L7,EC)=>{uu(L7,{isNodejs:()=>S7});function S7(){return typeof global=="object"&&!0&&typeof EC!="undefined"&&typeof process!="undefined"&&!!process.version}});var g2=Lm(I7=>{uu(I7,{AgeGenderNet:()=>jm,BoundingBox:()=>Oc,Box:()=>At,ComposableTask:()=>Hs,ComputeAllFaceDescriptorsTask:()=>Kr,ComputeFaceDescriptorsTaskBase:()=>Wm,ComputeSingleFaceDescriptorTask:()=>Xr,DetectAllFaceLandmarksTask:()=>Fm,DetectAllFacesTask:()=>pu,DetectFaceLandmarksTaskBase:()=>km,DetectFacesTaskBase:()=>Em,DetectSingleFaceLandmarksTask:()=>_m,DetectSingleFaceTask:()=>Dm,Dimensions:()=>Zn,FACE_EXPRESSION_LABELS:()=>Bm,FaceDetection:()=>Wt,FaceDetectionNet:()=>BC,FaceExpressionNet:()=>Mm,FaceExpressions:()=>Qr,FaceLandmark68Net:()=>Ac,FaceLandmark68TinyNet:()=>Um,FaceLandmarkNet:()=>h2,FaceLandmarks:()=>Ns,FaceLandmarks5:()=>f2,FaceLandmarks68:()=>Rc,FaceMatch:()=>Lu,FaceMatcher:()=>GS,FaceRecognitionNet:()=>Tc,Gender:()=>Ui,LabeledBox:()=>wu,LabeledFaceDescriptors:()=>so,NetInput:()=>hr,NeuralNetwork:()=>In,ObjectDetection:()=>ta,Point:()=>qe,PredictedBox:()=>m2,Rect:()=>Cc,SsdMobilenetv1:()=>Xo,SsdMobilenetv1Options:()=>Vs,TinyFaceDetector:()=>Ic,TinyFaceDetectorOptions:()=>vm,TinyYolov2:()=>Sc,TinyYolov2Options:()=>$i,TinyYolov2SizeType:()=>Am,allFaces:()=>o2,allFacesSsdMobilenetv1:()=>zS,allFacesTinyYolov2:()=>r2,awaitMediaLoaded:()=>qm,bufferToImage:()=>Hm,computeFaceDescriptor:()=>YC,createCanvas:()=>ea,createCanvasFromMedia:()=>Nc,createFaceDetectionNet:()=>UC,createFaceRecognitionNet:()=>l2,createSsdMobilenetv1:()=>$S,createTinyFaceDetector:()=>$C,createTinyYolov2:()=>WC,detectAllFaces:()=>du,detectFaceLandmarks:()=>MS,detectFaceLandmarksTiny:()=>VC,detectLandmarks:()=>s2,detectSingleFace:()=>i2,draw:()=>Im,env:()=>mt,euclideanDistance:()=>Pm,extendWithAge:()=>yu,extendWithFaceDescriptor:()=>gu,extendWithFaceDetection:()=>Zr,extendWithFaceExpressions:()=>fu,extendWithFaceLandmarks:()=>Jo,extendWithGender:()=>mu,extractFaceTensors:()=>Qo,extractFaces:()=>Zo,fetchImage:()=>p2,fetchJson:()=>Ym,fetchNetWeights:()=>d2,fetchOrThrow:()=>no,getContext2dOrThrow:()=>Un,getMediaDimensions:()=>to,imageTensorToCanvas:()=>Vm,imageToSquare:()=>Gm,inverseSigmoid:()=>PC,iou:()=>Om,isMediaElement:()=>bu,isMediaLoaded:()=>vc,isWithAge:()=>c2,isWithFaceDetection:()=>mi,isWithFaceExpressions:()=>$m,isWithFaceLandmarks:()=>Jr,isWithGender:()=>a2,loadAgeGenderModel:()=>e2,loadFaceDetectionModel:()=>t2,loadFaceExpressionModel:()=>QC,loadFaceLandmarkModel:()=>XC,loadFaceLandmarkTinyModel:()=>JC,loadFaceRecognitionModel:()=>ZC,loadSsdMobilenetv1Model:()=>PS,loadTinyFaceDetectorModel:()=>jC,loadTinyYolov2Model:()=>KC,loadWeightMap:()=>zm,locateFaces:()=>n2,matchDimensions:()=>u2,minBbox:()=>Rm,nets:()=>ht,nonMaxSuppression:()=>Cm,normalize:()=>Ys,padToSquare:()=>Nm,predictAgeAndGender:()=>qC,recognizeFaceExpressions:()=>HC,resizeResults:()=>US,resolveInput:()=>eo,shuffleArray:()=>MC,sigmoid:()=>xc,ssdMobilenetv1:()=>BS,tf:()=>kC,tinyFaceDetector:()=>zC,tinyYolov2:()=>GC,toNetInput:()=>Tt,utils:()=>xm,validateConfig:()=>Tm,version:()=>_C});const kC=Xe(Je()),x7=typeof process!="undefined",T7=typeof navigator!="undefined"&&typeof navigator.userAgent!="undefined",_C={faceapi:FC,node:x7,browser:T7}});function ur(r,l,u=!1){if(r.beginPath(),l.slice(1).forEach(({x:p,y:g},f)=>{const I=l[f];r.moveTo(I.x,I.y),r.lineTo(p,g)}),u){const p=l[l.length-1],g=l[0];if(!p||!g)return;r.moveTo(p.x,p.y),r.lineTo(g.x,g.y)}r.stroke()}class Zn{constructor(r,l){if(!fi(r)||!fi(l))throw new Error(`Dimensions.constructor - expected width and height to be valid numbers, instead have ${JSON.stringify({width:r,height:l})}`);this._width=r,this._height=l}get width(){return this._width}get height(){return this._height}reverse(){return new Zn(1/this.width,1/this.height)}}const xm={};uu(xm,{computeReshapedDimensions:()=>HS,getCenterPoint:()=>ia,isDimensions:()=>Xm,isEven:()=>Km,isFloat:()=>YS,isTensor:()=>na,isTensor1D:()=>A7,isTensor2D:()=>VS,isTensor3D:()=>dr,isTensor4D:()=>Cs,isValidNumber:()=>fi,isValidProbablitiy:()=>Ec,range:()=>Bi,round:()=>sa});const y2=Xe(Je());function na(r,l){return r instanceof y2.Tensor&&r.shape.length===l}function A7(r){return na(r,1)}function VS(r){return na(r,2)}function dr(r){return na(r,3)}function Cs(r){return na(r,4)}function YS(r){return r%1!==0}function Km(r){return r%2===0}function sa(r,l=2){const u=Math.pow(10,l);return Math.floor(r*u)/u}function Xm(r){return r&&r.width&&r.height}function HS({width:r,height:l},u){const p=u/Math.max(l,r);return new Zn(Math.round(r*p),Math.round(l*p))}function ia(r){return r.reduce((l,u)=>l.add(u),new qe(0,0)).div(new qe(r.length,r.length))}function Bi(r,l,u){return Array(r).fill(0).map((p,g)=>l+g*u)}function fi(r){return!!r&&r!==Infinity&&r!==-Infinity&&!isNaN(r)||r===0}function Ec(r){return fi(r)&&0<=r&&r<=1}class qe{constructor(r,l){this._x=r,this._y=l}get x(){return this._x}get y(){return this._y}add(r){return new qe(this.x+r.x,this.y+r.y)}sub(r){return new qe(this.x-r.x,this.y-r.y)}mul(r){return new qe(this.x*r.x,this.y*r.y)}div(r){return new qe(this.x/r.x,this.y/r.y)}abs(){return new qe(Math.abs(this.x),Math.abs(this.y))}magnitude(){return Math.sqrt(Math.pow(this.x,2)+Math.pow(this.y,2))}floor(){return new qe(Math.floor(this.x),Math.floor(this.y))}}class At{static isRect(r){return!!r&&[r.x,r.y,r.width,r.height].every(fi)}static assertIsValidBox(r,l,u=!1){if(!At.isRect(r))throw new Error(`${l} - invalid box: ${JSON.stringify(r)}, expected object with properties x, y, width, height`);if(!u&&(r.width<0||r.height<0))throw new Error(`${l} - width (${r.width}) and height (${r.height}) must be positive numbers`)}constructor(r,l=!0){const u=r||{},p=[u.left,u.top,u.right,u.bottom].every(fi),g=[u.x,u.y,u.width,u.height].every(fi);if(!g&&!p)throw new Error(`Box.constructor - expected box to be IBoundingBox | IRect, instead have ${JSON.stringify(u)}`);const[f,I,S,x]=g?[u.x,u.y,u.width,u.height]:[u.left,u.top,u.right-u.left,u.bottom-u.top];At.assertIsValidBox({x:f,y:I,width:S,height:x},"Box.constructor",l),this._x=f,this._y=I,this._width=S,this._height=x}get x(){return this._x}get y(){return this._y}get width(){return this._width}get height(){return this._height}get left(){return this.x}get top(){return this.y}get right(){return this.x+this.width}get bottom(){return this.y+this.height}get area(){return this.width*this.height}get topLeft(){return new qe(this.left,this.top)}get topRight(){return new qe(this.right,this.top)}get bottomLeft(){return new qe(this.left,this.bottom)}get bottomRight(){return new qe(this.right,this.bottom)}round(){const[r,l,u,p]=[this.x,this.y,this.width,this.height].map(g=>Math.round(g));return new At({x:r,y:l,width:u,height:p})}floor(){const[r,l,u,p]=[this.x,this.y,this.width,this.height].map(g=>Math.floor(g));return new At({x:r,y:l,width:u,height:p})}toSquare(){let{x:r,y:l,width:u,height:p}=this;const g=Math.abs(u-p);return u<p&&(r-=g/2,u+=g),p<u&&(l-=g/2,p+=g),new At({x:r,y:l,width:u,height:p})}rescale(r){const l=Xm(r)?r.width:r,u=Xm(r)?r.height:r;return new At({x:this.x*l,y:this.y*u,width:this.width*l,height:this.height*u})}pad(r,l){let[u,p,g,f]=[this.x-r/2,this.y-l/2,this.width+r,this.height+l];return new At({x:u,y:p,width:g,height:f})}clipAtImageBorders(r,l){const{x:u,y:p,right:g,bottom:f}=this,I=Math.max(u,0),S=Math.max(p,0),x=g-I,v=f-S,O=Math.min(x,r-I),C=Math.min(v,l-S);return new At({x:I,y:S,width:O,height:C}).floor()}shift(r,l){const{width:u,height:p}=this,g=this.x+r,f=this.y+l;return new At({x:g,y:f,width:u,height:p})}padAtBorders(r,l){const u=this.width+1,p=this.height+1;let g=1,f=1,I=u,S=p,x=this.left,v=this.top,O=this.right,C=this.bottom;return O>l&&(I=-O+l+u,O=l),C>r&&(S=-C+r+p,C=r),x<1&&(S=2-x,x=1),v<1&&(S=2-v,v=1),{dy:f,edy:S,dx:g,edx:I,y:v,ey:C,x,ex:O,w:u,h:p}}calibrate(r){return new At({left:this.left+r.left*this.width,top:this.top+r.top*this.height,right:this.right+r.right*this.width,bottom:this.bottom+r.bottom*this.height}).toSquare().round()}}class Oc extends At{constructor(r,l,u,p,g=!1){super({left:r,top:l,right:u,bottom:p},g)}}class ta{constructor(r,l,u,p,g){this._imageDims=new Zn(g.width,g.height),this._score=r,this._classScore=l,this._className=u,this._box=new At(p).rescale(this._imageDims)}get score(){return this._score}get classScore(){return this._classScore}get className(){return this._className}get box(){return this._box}get imageDims(){return this._imageDims}get imageWidth(){return this.imageDims.width}get imageHeight(){return this.imageDims.height}get relativeBox(){return new At(this._box).rescale(this.imageDims.reverse())}forSize(r,l){return new ta(this.score,this.classScore,this.className,this.relativeBox,{width:r,height:l})}}class Wt extends ta{constructor(r,l,u){super(r,r,"",l,u)}forSize(r,l){const{score:u,relativeBox:p,imageDims:g}=super.forSize(r,l);return new Wt(u,p,g)}}function Om(r,l,u=!0){const p=Math.max(0,Math.min(r.right,l.right)-Math.max(r.left,l.left)),g=Math.max(0,Math.min(r.bottom,l.bottom)-Math.max(r.top,l.top)),f=p*g;return u?f/(r.area+l.area-f):f/Math.min(r.area,l.area)}function Rm(r){const l=r.map(S=>S.x),u=r.map(S=>S.y),p=l.reduce((S,x)=>x<S?x:S,Infinity),g=u.reduce((S,x)=>x<S?x:S,Infinity),f=l.reduce((S,x)=>S<x?x:S,0),I=u.reduce((S,x)=>S<x?x:S,0);return new Oc(p,g,f,I)}function Cm(r,l,u,p=!0){let g=l.map((I,S)=>({score:I,boxIndex:S})).sort((I,S)=>I.score-S.score).map(I=>I.boxIndex);const f=[];for(;g.length>0;){const I=g.pop();f.push(I);const S=g,x=[];for(let v=0;v<S.length;v++){const O=S[v],C=r[I],U=r[O];x.push(Om(C,U,p))}g=g.filter((v,O)=>x[O]<=u)}return f}const Mi=Xe(Je());function Ys(r,l){return Mi.tidy(()=>{const[u,p,g]=l,f=Mi.fill([...r.shape.slice(0,3),1],u,"float32"),I=Mi.fill([...r.shape.slice(0,3),1],p,"float32"),S=Mi.fill([...r.shape.slice(0,3),1],g,"float32"),x=Mi.concat([f,I,S],3);return Mi.sub(r,x)})}const io=Xe(Je());function Nm(r,l=!1){return io.tidy(()=>{const[u,p]=r.shape.slice(1);if(u===p)return r;const g=Math.abs(u-p),f=Math.round(g*(l?.5:1)),I=u>p?2:1,S=U=>{const G=r.shape.slice();return G[I]=U,io.fill(G,0,"float32")},x=S(f),v=g-x.shape[I],O=l&&v?S(v):null,C=[O,r,x].filter(U=>!!U).map(U=>io.cast(U,"float32"));return io.concat(C,I)})}function MC(r){const l=r.slice();for(let u=l.length-1;u>0;u--){const p=Math.floor(Math.random()*(u+1)),g=l[u];l[u]=l[p],l[p]=g}return l}function xc(r){return 1/(1+Math.exp(-r))}function PC(r){return Math.log(r/(1-r))}class Cc extends At{constructor(r,l,u,p,g=!1){super({x:r,y:l,width:u,height:p},g)}}const v7=.5,N7=.43,C7=.45;class Ns{constructor(r,l,u=new qe(0,0)){const{width:p,height:g}=l;this._imgDims=new Zn(p,g),this._shift=u,this._positions=r.map(f=>f.mul(new qe(p,g)).add(u))}get shift(){return new qe(this._shift.x,this._shift.y)}get imageWidth(){return this._imgDims.width}get imageHeight(){return this._imgDims.height}get positions(){return this._positions}get relativePositions(){return this._positions.map(r=>r.sub(this._shift).div(new qe(this.imageWidth,this.imageHeight)))}forSize(r,l){return new this.constructor(this.relativePositions,{width:r,height:l})}shiftBy(r,l){return new this.constructor(this.relativePositions,this._imgDims,new qe(r,l))}shiftByPoint(r){return this.shiftBy(r.x,r.y)}align(r,l={}){if(r){const g=r instanceof Wt?r.box.floor():new At(r);return this.shiftBy(g.x,g.y).align(null,l)}const{useDlibAlignment:u,minBoxPadding:p}=Object.assign({},{useDlibAlignment:!1,minBoxPadding:.2},l);return u?this.alignDlib():this.alignMinBbox(p)}alignDlib(){const r=this.getRefPointsForAlignment(),[l,u,p]=r,g=O=>p.sub(O).magnitude(),f=(g(l)+g(u))/2,I=Math.floor(f/C7),S=ia(r),x=Math.floor(Math.max(0,S.x-v7*I)),v=Math.floor(Math.max(0,S.y-N7*I));return new Cc(x,v,Math.min(I,this.imageWidth+x),Math.min(I,this.imageHeight+v))}alignMinBbox(r){const l=Rm(this.positions);return l.pad(l.width*r,l.height*r)}getRefPointsForAlignment(){throw new Error("getRefPointsForAlignment not implemented by base class")}}class f2 extends Ns{getRefPointsForAlignment(){const r=this.positions;return[r[0],r[1],ia([r[3],r[4]])]}}class Rc extends Ns{getJawOutline(){return this.positions.slice(0,17)}getLeftEyeBrow(){return this.positions.slice(17,22)}getRightEyeBrow(){return this.positions.slice(22,27)}getNose(){return this.positions.slice(27,36)}getLeftEye(){return this.positions.slice(36,42)}getRightEye(){return this.positions.slice(42,48)}getMouth(){return this.positions.slice(48,68)}getRefPointsForAlignment(){return[this.getLeftEye(),this.getRightEye(),this.getMouth()].map(ia)}}class Lu{constructor(r,l){this._label=r,this._distance=l}get label(){return this._label}get distance(){return this._distance}toString(r=!0){return`${this.label}${r?` (${sa(this.distance)})`:""}`}}class wu extends At{static assertIsValidLabeledBox(r,l){if(At.assertIsValidBox(r,l),!fi(r.label))throw new Error(`${l} - expected property label (${r.label}) to be a number`)}constructor(r,l){super(r);this._label=l}get label(){return this._label}}class so{constructor(r,l){if(!(typeof r=="string"))throw new Error("LabeledFaceDescriptors - constructor expected label to be a string");if(!Array.isArray(l)||l.some(u=>!(u instanceof Float32Array)))throw new Error("LabeledFaceDescriptors - constructor expected descriptors to be an array of Float32Array");this._label=r,this._descriptors=l}get label(){return this._label}get descriptors(){return this._descriptors}toJSON(){return{label:this.label,descriptors:this.descriptors.map(r=>Array.from(r))}}static fromJSON(r){const l=r.descriptors.map(u=>new Float32Array(u));return new so(r.label,l)}}class m2 extends wu{static assertIsValidPredictedBox(r,l){if(wu.assertIsValidLabeledBox(r,l),!Ec(r.score)||!Ec(r.classScore))throw new Error(`${l} - expected properties score (${r.score}) and (${r.classScore}) to be a number between [0, 1]`)}constructor(r,l,u,p){super(r,l);this._score=u,this._classScore=p}get score(){return this._score}get classScore(){return this._classScore}}function mi(r){return r.detection instanceof Wt}function Zr(r,l){const u={detection:l};return Object.assign({},r,u)}function qS(){const r=window.fetch||function(){throw new Error("fetch - missing fetch implementation for browser environment")},l=function(){throw new Error("readFile - filesystem not available for browser environment")};return{Canvas:HTMLCanvasElement,CanvasRenderingContext2D,Image:HTMLImageElement,ImageData,Video:HTMLVideoElement,createCanvasElement:()=>document.createElement("canvas"),createImageElement:()=>document.createElement("img"),fetch:r,readFile:l}}function Jm(r){let l="";if(!r)try{r=require("fs")}catch(p){l=p.toString()}const u=r?function(p){return new Promise((g,f)=>{r.readFile(p,function(I,S){return I?f(I):g(S)})})}:function(){throw new Error(`readFile - failed to require fs in nodejs environment with error: ${l}`)};return{readFile:u}}function jS(){const r=global.Canvas||global.HTMLCanvasElement,l=global.Image||global.HTMLImageElement,u=function(){if(r)return new r;throw new Error("createCanvasElement - missing Canvas implementation for nodejs environment")},p=function(){if(l)return new l;throw new Error("createImageElement - missing Image implementation for nodejs environment")},g=global.fetch||function(){throw new Error("fetch - missing fetch implementation for nodejs environment")},f=Jm();return{Canvas:r||class{},CanvasRenderingContext2D:global.CanvasRenderingContext2D||class{},Image:l||class{},ImageData:global.ImageData||class{},Video:global.HTMLVideoElement||class{},createCanvasElement:u,createImageElement:p,fetch:g,...f}}function KS(){return typeof window=="object"&&typeof document!="undefined"&&typeof HTMLImageElement!="undefined"&&typeof HTMLCanvasElement!="undefined"&&typeof HTMLVideoElement!="undefined"&&typeof ImageData!="undefined"&&typeof CanvasRenderingContext2D!="undefined"}const XS=Xe(DC());let gn;function R7(){if(!gn)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return gn}function JS(r){gn=r}function ZS(){if(KS())return JS(qS());if(XS.isNodejs())return JS(jS())}function O7(r){if(gn||ZS(),!gn)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");const{Canvas:l=gn.Canvas,Image:u=gn.Image}=r;gn.Canvas=l,gn.Image=u,gn.createCanvasElement=r.createCanvasElement||(()=>new l),gn.createImageElement=r.createImageElement||(()=>new u),gn.ImageData=r.ImageData||gn.ImageData,gn.Video=r.Video||gn.Video,gn.fetch=r.fetch||gn.fetch,gn.readFile=r.readFile||gn.readFile}const mt={getEnv:R7,setEnv:JS,initialize:ZS,createBrowserEnv:qS,createFileSystem:Jm,createNodejsEnv:jS,monkeyPatch:O7,isBrowser:KS,isNodejs:XS.isNodejs};ZS();function eo(r){return!mt.isNodejs()&&typeof r=="string"?document.getElementById(r):r}function Un(r){const{Canvas:l,CanvasRenderingContext2D:u}=mt.getEnv();if(r instanceof u)return r;const p=eo(r);if(!(p instanceof l))throw new Error("resolveContext2d - expected canvas to be of instance of Canvas");const g=p.getContext("2d");if(!g)throw new Error("resolveContext2d - canvas 2d context is null");return g}var Pi;(function(r){r.TOP_LEFT="TOP_LEFT",r.TOP_RIGHT="TOP_RIGHT",r.BOTTOM_LEFT="BOTTOM_LEFT",r.BOTTOM_RIGHT="BOTTOM_RIGHT"})(Pi||(Pi={}));class Zm{constructor(r={}){const{anchorPosition:l,backgroundColor:u,fontColor:p,fontSize:g,fontStyle:f,padding:I}=r;this.anchorPosition=l||Pi.TOP_LEFT,this.backgroundColor=u||"rgba(0, 0, 0, 0.5)",this.fontColor=p||"rgba(255, 255, 255, 1)",this.fontSize=g||14,this.fontStyle=f||"Georgia",this.padding=I||4}}class Dc{constructor(r,l,u={}){this.text=typeof r=="string"?[r]:r instanceof Dc?r.text:r,this.anchor=l,this.options=new Zm(u)}measureWidth(r){const{padding:l}=this.options;return this.text.map(u=>r.measureText(u).width).reduce((u,p)=>u<p?p:u,0)+2*l}measureHeight(){const{fontSize:r,padding:l}=this.options;return this.text.length*r+2*l}getUpperLeft(r,l){const{anchorPosition:u}=this.options,p=u===Pi.BOTTOM_RIGHT||u===Pi.TOP_RIGHT,g=u===Pi.BOTTOM_LEFT||u===Pi.BOTTOM_RIGHT,f=this.measureWidth(r),I=this.measureHeight(),S=p?this.anchor.x-f:this.anchor.x,x=g?this.anchor.y-I:this.anchor.y;if(l){const{width:v,height:O}=l,C=Math.max(Math.min(S,v-f),0),U=Math.max(Math.min(x,O-I),0);return{x:C,y:U}}return{x:S,y:x}}draw(r){const l=eo(r),u=Un(l),{backgroundColor:p,fontColor:g,fontSize:f,fontStyle:I,padding:S}=this.options;u.font=`${f}px ${I}`;const x=this.measureWidth(u),v=this.measureHeight();u.fillStyle=p;const O=this.getUpperLeft(u,l);u.fillRect(O.x,O.y,x,v),u.fillStyle=g,this.text.forEach((C,U)=>{const G=S+O.x,ne=S+O.y+(U+1)*f;u.fillText(C,G,ne)})}}class b2{constructor(r={}){const{boxColor:l,lineWidth:u,label:p,drawLabelOptions:g}=r;this.boxColor=l||"rgba(0, 0, 255, 1)",this.lineWidth=u||2,this.label=p;const f={anchorPosition:Pi.BOTTOM_LEFT,backgroundColor:this.boxColor};this.drawLabelOptions=new Zm(Object.assign({},f,g))}}class QS{constructor(r,l={}){this.box=new At(r),this.options=new b2(l)}draw(r){const l=Un(r),{boxColor:u,lineWidth:p}=this.options,{x:g,y:f,width:I,height:S}=this.box;l.strokeStyle=u,l.lineWidth=p,l.strokeRect(g,f,I,S);const{label:x}=this.options;x&&new Dc([x],{x:g-p/2,y:f},this.options.drawLabelOptions).draw(r)}}function E7(r,l){const u=Array.isArray(l)?l:[l];u.forEach(p=>{const g=p instanceof Wt?p.score:mi(p)?p.detection.score:void 0,f=p instanceof Wt?p.box:mi(p)?p.detection.box:new At(p),I=g?`${sa(g)}`:void 0;new QS(f,{label:I}).draw(r)})}function vc(r){const{Image:l,Video:u}=mt.getEnv();return r instanceof l&&r.complete||r instanceof u&&r.readyState>=3}function qm(r){return new Promise((l,u)=>{if(r instanceof mt.getEnv().Canvas||vc(r))return l(null);function p(f){if(!f.currentTarget)return;f.currentTarget.removeEventListener("load",p),f.currentTarget.removeEventListener("error",g),l(f)}function g(f){if(!f.currentTarget)return;f.currentTarget.removeEventListener("load",p),f.currentTarget.removeEventListener("error",g),u(f)}r.addEventListener("load",p),r.addEventListener("error",g)})}function Hm(r){return new Promise((l,u)=>{if(!(r instanceof Blob))return u("bufferToImage - expected buf to be of type: Blob");const p=new FileReader;p.onload=()=>{if(typeof p.result!="string")return u("bufferToImage - expected reader.result to be a string, in onload");const g=mt.getEnv().createImageElement();g.onload=()=>l(g),g.onerror=u,g.src=p.result},p.onerror=u,p.readAsDataURL(r)})}function to(r){const{Image:l,Video:u}=mt.getEnv();return r instanceof l?new Zn(r.naturalWidth,r.naturalHeight):r instanceof u?new Zn(r.videoWidth,r.videoHeight):new Zn(r.width,r.height)}function ea({width:r,height:l}){const{createCanvasElement:u}=mt.getEnv(),p=u();return p.width=r,p.height=l,p}function Nc(r,l){const{ImageData:u}=mt.getEnv();if(!(r instanceof u)&&!vc(r))throw new Error("createCanvasFromMedia - media has not finished loading yet");const{width:p,height:g}=l||to(r),f=ea({width:p,height:g});return r instanceof u?Un(f).putImageData(r,0,0):Un(f).drawImage(r,0,0,p,g),f}const Qm=Xe(Je());async function Vm(r,l){const u=l||mt.getEnv().createCanvasElement(),[p,g,f]=r.shape.slice(Cs(r)?1:0),I=Qm.tidy(()=>r.as3D(p,g,f).toInt());return await Qm.browser.toPixels(I,u),I.dispose(),u}function bu(r){const{Image:l,Canvas:u,Video:p}=mt.getEnv();return r instanceof l||r instanceof u||r instanceof p}const D7=1e-7,k7=1e-4;class w2{time(r){return se("time")}read(r){return se("read")}readSync(r){return se("readSync")}numDataIds(){return se("numDataIds")}disposeData(r){return se("disposeData")}write(r,l,u){return se("write")}move(r,l,u,p){return se("move")}memory(){return se("memory")}floatPrecision(){return se("floatPrecision")}epsilon(){return this.floatPrecision()===32?D7:k7}batchMatMul(r,l,u,p){return se("batchMatMul")}fusedBatchMatMul({a:r,b:l,transposeA:u,transposeB:p,bias:g,activation:f,preluActivationWeights:I}){return se("fusedBatchMatMul")}slice(r,l,u){return se("slice")}stridedSlice(r,l,u,p){return se("stridedSlice")}unstack(r,l){return se("unstack")}reverse(r,l){return se("reverse")}concat(r,l){return se("concat")}neg(r){return se("neg")}add(r,l){return se("add")}addN(r){return se("addN")}subtract(r,l){return se("subtract")}multiply(r,l){return se("multiply")}realDivide(r,l){return se("realDivide")}floorDiv(r,l){return se("floorDiv")}sum(r,l){return se("sum")}prod(r,l){return se("prod")}unsortedSegmentSum(r,l,u){return se("unsortedSegmentSum")}argMin(r,l){return se("argMin")}argMax(r,l){return se("argMax")}equal(r,l){return se("equal")}notEqual(r,l){return se("notEqual")}less(r,l){return se("less")}lessEqual(r,l){return se("lessEqual")}greater(r,l){return se("greater")}greaterEqual(r,l){return se("greaterEqual")}logicalNot(r){return se("logicalNot")}logicalAnd(r,l){return se("logicalAnd")}logicalOr(r,l){return se("logicalOr")}where(r){return se("where")}select(r,l,u){return se("select")}topk(r,l,u){return se("topk")}min(r,l){return se("min")}minimum(r,l){return se("minimum")}mod(r,l){return se("mod")}max(r,l){return se("max")}maximum(r,l){return se("maximum")}all(r,l){return se("all")}any(r,l){return se("any")}squaredDifference(r,l){return se("squaredDifference")}ceil(r){return se("ceil")}floor(r){return se("floor")}round(r){return se("round")}sign(r){return se("sign")}isNaN(r){return se("isNaN")}isInf(r){return se("isInf")}isFinite(r){return se("isFinite")}pow(r,l){return se("pow")}exp(r){return se("exp")}expm1(r){return se("expm1")}softmax(r,l){return se("softmax")}log(r){return se("log")}log1p(r){return se("log1p")}sqrt(r){return se("sqrt")}rsqrt(r){return se("rsqrt")}square(r){return se("square")}reciprocal(r){return se("reciprocal")}relu(r){return se("relu")}relu6(r){return se("relu6")}prelu(r,l){return se("prelu")}elu(r){return se("elu")}eluDer(r,l){return se("eluDer")}selu(r){return se("selu")}int(r){return se("int")}clip(r,l,u){return se("clip")}abs(r){return se("abs")}complexAbs(r){return se("complexAbs")}sigmoid(r){return se("sigmoid")}softplus(r){return se("softplus")}sin(r){return se("sin")}cos(r){return se("cos")}tan(r){return se("tan")}asin(r){return se("asin")}acos(r){return se("acos")}atan(r){return se("atan")}atan2(r,l){return se("atan2")}sinh(r){return se("sinh")}cosh(r){return se("cosh")}tanh(r){return se("tanh")}asinh(r){return se("asinh")}acosh(r){return se("acosh")}atanh(r){return se("atanh")}erf(r){return se("erf")}step(r,l){return se("step")}fusedConv2d({input:r,filter:l,convInfo:u,bias:p,activation:g,preluActivationWeights:f}){return se("fusedConv2d")}conv2d(r,l,u){return se("conv2d")}conv2dDerInput(r,l,u){return se("conv2dDerInput")}conv2dDerFilter(r,l,u){return se("conv2dDerFilter")}fusedDepthwiseConv2D({input:r,filter:l,convInfo:u,bias:p,activation:g,preluActivationWeights:f}){return se("fusedDepthwiseConv2D")}depthwiseConv2D(r,l,u){return se("depthwiseConv2D")}depthwiseConv2DDerInput(r,l,u){return se("depthwiseConv2DDerInput")}depthwiseConv2DDerFilter(r,l,u){return se("depthwiseConv2DDerFilter")}conv3d(r,l,u){return se("conv3d")}conv3dDerInput(r,l,u){return se("conv3dDerInput")}conv3dDerFilter(r,l,u){return se("conv3dDerFilter")}maxPool(r,l){return se("maxPool")}maxPoolBackprop(r,l,u,p){return se("maxPoolBackprop")}avgPool(r,l){return se("avgPool")}avgPoolBackprop(r,l,u){return se("avgPoolBackprop")}avgPool3d(r,l){return se("avgPool3d")}avgPool3dBackprop(r,l,u){return se("avgPool3dBackprop")}maxPool3d(r,l){return se("maxPool3d")}maxPool3dBackprop(r,l,u,p){return se("maxPool3dBackprop")}reshape(r,l){return se("reshape")}cast(r,l){return se("cast")}tile(r,l){return se("tile")}pad(r,l,u){return se("pad")}transpose(r,l){return se("transpose")}gather(r,l,u){return se("gather")}gatherND(r,l){return se("gatherND")}scatterND(r,l,u){return se("scatterND")}batchToSpaceND(r,l,u){return se("batchToSpaceND")}spaceToBatchND(r,l,u){return se("spaceToBatchND")}resizeBilinear(r,l,u,p){return se("resizeBilinear")}resizeBilinearBackprop(r,l,u){return se("resizeBilinearBackprop")}resizeNearestNeighbor(r,l,u,p){return se("resizeNearestNeighbor")}resizeNearestNeighborBackprop(r,l,u){return se("resizeNearestNeighborBackprop")}batchNorm(r,l,u,p,g,f){return se("batchNorm")}localResponseNormalization4D(r,l,u,p,g){return se("localResponseNormalization4D")}LRNGrad(r,l,u,p,g,f,I){return se("LRNGrad")}multinomial(r,l,u,p){return se("multinomial")}oneHot(r,l,u,p){return se("oneHot")}cumsum(r,l,u,p){return se("cumsum")}nonMaxSuppression(r,l,u,p,g){return se("nonMaxSuppression")}fft(r){return se("fft")}ifft(r){return se("ifft")}complex(r,l){return se("complex")}real(r){return se("real")}imag(r){return se("imag")}cropAndResize(r,l,u,p,g,f){return se("cropAndResize")}depthToSpace(r,l,u){return se("depthToSpace")}split(r,l,u){return se("split")}sparseToDense(r,l,u,p){return se("sparseToDense")}diag(r){return se("diag")}fill(r,l,u){return se("fill")}onesLike(r){return se("onesLike")}zerosLike(r){return se("zerosLike")}linspace(r,l,u){return se("linspace")}dispose(){return se("dispose")}}function se(r){throw new Error(`'${r}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}const L2="tfjsflags";class S2{constructor(r){this.global=r,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}setPlatform(r,l){this.platform!=null&&console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${l}.`),this.platformName=r,this.platform=l}registerFlag(r,l,u){if(this.flagRegistry[r]={evaluationFn:l,setHook:u},this.urlFlags[r]!=null){const p=this.urlFlags[r];console.warn(`Setting feature override from URL ${r}: ${p}.`),this.set(r,p)}}async getAsync(r){return r in this.flags?this.flags[r]:(this.flags[r]=await this.evaluateFlag(r),this.flags[r])}get(r){if(r in this.flags)return this.flags[r];const l=this.evaluateFlag(r);if(l instanceof Promise)throw new Error(`Flag ${r} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[r]=l,this.flags[r]}getNumber(r){return this.get(r)}getBool(r){return this.get(r)}getFlags(){return this.flags}get features(){return this.flags}set(r,l){if(this.flagRegistry[r]==null)throw new Error(`Cannot set flag ${r} as it has not been registered.`);this.flags[r]=l,this.flagRegistry[r].setHook!=null&&this.flagRegistry[r].setHook(l)}evaluateFlag(r){if(this.flagRegistry[r]==null)throw new Error(`Cannot evaluate flag '${r}': no evaluation function found.`);return this.flagRegistry[r].evaluationFn()}setFlags(r){this.flags=Object.assign({},r)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(typeof this.global=="undefined"||typeof this.global.location=="undefined"||typeof this.global.location.search=="undefined")return;const r=F7(this.global.location.search);if(L2 in r){const l=r[L2].split(",");l.forEach(u=>{const[p,g]=u.split(":");this.urlFlags[p]=_7(p,g)})}}}function F7(r){const l={};return r.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(u,...p)=>(W7(l,p[0],p[1]),p.join("="))),l}function W7(r,l,u){r[decodeURIComponent(l)]=decodeURIComponent(u||"")}function _7(r,l){if(l=l.toLowerCase(),l==="true"||l==="false")return l==="true";if(`${+l}`===l)return+l;throw new Error(`Could not parse value flag value ${l} for flag ${r}.`)}function Rs(){return I2}let I2=null;function x2(r){I2=r}let eI;function tI(){if(eI==null){let r;if(typeof window!="undefined")r=window;else if(typeof global!="undefined")r=global;else if(typeof process!="undefined")r=process;else if(typeof self!="undefined")r=self;else throw new Error("Could not find a global object");eI=r}return eI}function $7(){const r=tI();return r._tfGlobals==null&&(r._tfGlobals=new Map),r._tfGlobals}function nI(r,l){const u=$7();if(u.has(r))return u.get(r);{const p=l();return u.set(r,p),u.get(r)}}const ef="Abs",T2="Acos",A2="Acosh",kc="Add",v2="AddN",N2="ArgMax",C2="ArgMin",R2="Asin",O2="Asinh",E2="Atan",D2="Atanh",k2="Atan2",F2="AvgPool",_2="AvgPoolBackprop",W2="AvgPool3D",$2="AvgPool3DBackprop",tf="BatchMatMul",nf="BatchToSpaceND",sf="BroadcastTo",Fc="Cast",U2="Ceil",B2="ClipByValue",M2="Complex",rf="Concat",of="Conv2D",P2="Conv2DBackpropFilter",af="Conv2DBackpropInput",z2="Conv3D",G2="Conv3DBackpropFilterV2",V2="Conv3DBackpropInputV2",cf="Cos",lf="Cosh",hf="Cumsum",Y2="CropAndResize",H2="DepthwiseConv2dNative",q2="DepthwiseConv2dNativeBackpropFilter",j2="DepthwiseConv2dNativeBackpropInput",K2="Dilation2D",X2="Dilation2DBackpropInput",J2="Dilation2DBackpropFilter",uf="Div",Z2="Elu",Q2="EluGrad",eR="Erf",tR="Equal",df="Exp",nR="Expm1",sR="FFT",iR="Fill",rR="FlipLeftRight",pf="Floor",mf="FloorDiv",oR="FusedBatchNorm",ff="GatherV2",aR="Greater",gf="GreaterEqual",yf="Identity",cR="IFFT",lR="Imag",hR="IsFinite",uR="IsInf",dR="IsNan",pR="Less",mR="LessEqual",bf="Log",wf="Log1p",fR="LogicalAnd",gR="LogicalNot",yR="LogSoftmax",bR="LRN",wR="LRNBackprop",Lf="Max",Sf="Maximum",LR="MaxPool",SR="MaxPoolBackprop",IR="MaxPool3D",xR="MaxPool3DBackprop",If="Min",xf="Minimum",TR="Mod",Tf="Multiply",Af="Negate",AR="NotEqual",vR="NonMaxSuppressionV3",NR="NonMaxSuppressionV4",CR="NonMaxSuppressionV5",RR="OnesLike",OR="OneHot",vf="PadV2",Nf="Pow",ER="Prelu",DR="Range",kR="Real",FR="Reciprocal",Cf="Relu",Rf="Reshape",Of="ResizeNearestNeighbor",_R="ResizeNearestNeighborGrad",Ef="ResizeBilinear",WR="ResizeBilinearGrad",$R="Relu6",Df="Reverse",UR="Round",kf="Rsqrt",Ff="SelectV2",BR="Selu",_f="Slice",Wf="Sin",$f="Sinh",MR="Sign",Uf="Sigmoid",PR="Softplus",Bf="Sqrt",Mf="Sum",Pf="SpaceToBatchND",zf="SplitV",zR="Softmax",Gf="SquaredDifference",GR="Square",Vf="Sub",VR="Tan",YR="Tanh",Yf="Tile",Hf="Transpose",qf="Unpack",jf="UnsortedSegmentSum",Kf="ZerosLike",Xf="Step",sI="FromPixels",HR="RotateWithOffset";const qR=nI("kernelRegistry",()=>new Map),iI=nI("gradRegistry",()=>new Map);function Jf(r,l){const u=U7(r,l);return qR.get(u)}function rI(r){return iI.get(r)}function oI(r){const l=qR.entries(),u=[];for(;;){const{done:p,value:g}=l.next();if(p)break;const[f,I]=g,[S]=f.split("_");S===r&&u.push(I)}return u}function jR(r){const{kernelName:l}=r;iI.has(l)&&(Rs().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${l}'`)),iI.set(l,r)}function U7(r,l){return`${l}_${r}`}function Z(r,l){if(!r)throw new Error(typeof l=="string"?l:l())}function Zt(r,l,u=""){Z(ra(r,l),()=>u+` Shapes ${r} and ${l} must match`)}function _c(r){Z(r!=null,()=>"The input to the tensor constructor must be a non-null value.")}function Wc(r,l=[],u=!1){if(l==null&&(l=[]),Array.isArray(r)||Os(r)&&!u)for(let p=0;p<r.length;++p)Wc(r[p],l,u);else l.push(r);return l}function qt(r){if(r.length===0)return 1;let l=r[0];for(let u=1;u<r.length;u++)l*=r[u];return l}function ra(r,l){if(r===l)return!0;if(r==null||l==null)return!1;if(r.length!==l.length)return!1;for(let u=0;u<r.length;u++)if(r[u]!==l[u])return!1;return!0}function Qt(r){return r%1===0}function $c(r,l){return l<=r.length?r:r+" ".repeat(l-r.length)}function KR(r,l){let u=1,p=-1;for(let f=0;f<r.length;++f)if(r[f]>=0)u*=r[f];else if(r[f]===-1){if(p!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${p} and dim ${f}`);p=f}else if(r[f]<0)throw Error(`Shapes can not be < 0. Found ${r[f]} at dim ${f}`);if(p===-1){if(l>0&&l!==u)throw Error(`Size(${l}) must match the product of shape ${r}`);return r}if(u===0)throw Error(`Cannot infer the missing size in [${r}] when there are 0 elements`);if(l%u!==0)throw Error(`The implicit shape can't be a fractional number. Got ${l} / ${u}`);const g=r.slice();return g[p]=l/u,g}function ut(r,l){const u=l.length;return r=r==null?l.map((p,g)=>g):[].concat(r),Z(r.every(p=>p>=-u&&p<u),()=>`All values in axis param must be in range [-${u}, ${u}) but got axis ${r}`),Z(r.every(p=>Qt(p)),()=>`All values in axis param must be integers but got axis ${r}`),r.map(p=>p<0?u+p:p)}function XR(r,l){const u=[],p=[],g=l!=null&&Array.isArray(l)&&l.length===0,f=l==null||g?null:ut(l,r).sort();let I=0;for(let S=0;S<r.length;++S){if(f!=null){if(f[I]===S&&r[S]!==1)throw new Error(`Can't squeeze axis ${S} since its dim '${r[S]}' is not 1`);(f[I]==null||f[I]>S)&&r[S]===1&&(u.push(r[S]),p.push(S)),f[I]<=S&&I++}r[S]!==1&&(u.push(r[S]),p.push(S))}return{newShape:u,keptDims:p}}function JR(r,l){let u=null;if(r==null||r==="float32")u=new Float32Array(l);else if(r==="int32")u=new Int32Array(l);else if(r==="bool")u=new Uint8Array(l);else if(r==="string")u=new Array(l);else throw new Error(`Unknown data type ${r}`);return u}function B7(r,l){for(let u=0;u<r.length;u++){const p=r[u];if(isNaN(p)||!isFinite(p))throw Error(`A tensor of type ${l} being uploaded contains ${p}.`)}}function ZR(r){return r==="bool"||r==="complex64"||r==="float32"||r==="int32"||r==="string"}function Os(r){return r instanceof Float32Array||r instanceof Int32Array||r instanceof Uint8Array}function QR(r){if(r==="float32"||r==="int32")return 4;if(r==="complex64")return 8;if(r==="bool")return 1;throw new Error(`Unknown dtype ${r}`)}function eO(r){if(r==null)return 0;let l=0;return r.forEach(u=>l+=u.length),l}function Su(r){return typeof r=="string"||r instanceof String}function M7(r){return typeof r=="boolean"}function P7(r){return typeof r=="number"}function Iu(r){return Array.isArray(r)?Iu(r[0]):r instanceof Float32Array?"float32":r instanceof Int32Array||r instanceof Uint8Array?"int32":P7(r)?"float32":Su(r)?"string":M7(r)?"bool":"float32"}function aI(r){return!!(r&&r.constructor&&r.call&&r.apply)}function xu(r){const l=r.length;if(l<2)return[];const u=new Array(l-1);u[l-2]=r[l-1];for(let p=l-3;p>=0;--p)u[p]=u[p+1]*r[p+1];return u}function Zf(r,l){if(l==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(r)&&(r=Wc(r)),Rs().getBool("DEBUG")&&B7(r,l),z7(r,l))return r;if(l==null||l==="float32"||l==="complex64")return new Float32Array(r);if(l==="int32")return new Int32Array(r);if(l==="bool"){const u=new Uint8Array(r.length);for(let p=0;p<u.length;++p)Math.round(r[p])!==0&&(u[p]=1);return u}else throw new Error(`Unknown data type ${l}`)}function tO(r,l,u){const p=new Array;if(l.length===1){const g=l[0];for(let f=0;f<g;f++)p[f]=u[r+f]}else{const g=l[0],f=l.slice(1),I=f.reduce((S,x)=>S*x);for(let S=0;S<g;S++)p[S]=tO(r+S*I,f,u)}return p}function cI(r,l){if(r.length===0)return l[0];const u=r.reduce((p,g)=>p*g);if(u===0)return[];if(u!==l.length)throw new Error(`[${r}] does not match the input size ${l.length}.`);return tO(0,r,l)}function z7(r,l){return r instanceof Float32Array&&l==="float32"||r instanceof Int32Array&&l==="int32"||r instanceof Uint8Array&&l==="bool"}function Qf(r,l){const u=oa(r,l);for(let p=0;p<u.length;p++)u[p]=1;return u}function oa(r,l){if(l==null||l==="float32"||l==="complex64")return new Float32Array(r);if(l==="int32")return new Int32Array(r);if(l==="bool")return new Uint8Array(r);throw new Error(`Unknown data type ${l}`)}function lI(){return Rs().platform.now()}function eg(r){r.forEach(l=>{Z(Number.isInteger(l)&&l>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${r}].`)})}function nO(r,l="utf-8"){return l=l||"utf-8",Rs().platform.encode(r,l)}function hI(r,l="utf-8"){return l=l||"utf-8",Rs().platform.decode(r,l)}class sO{constructor(r,l){this.backendTimer=r,this.logger=l,l==null&&(this.logger=new V7)}profileKernel(r,l,u){let p;const g=()=>{p=u()},f=this.backendTimer.time(g);for(let S=0;S<p.length;S++){const x=p[S];x.data().then(v=>{G7(v,x.dtype,r)})}const I={kernelName:r,outputs:p,inputs:l,timeMs:f.then(S=>S.kernelMs),extraInfo:f.then(S=>S.getExtraProfileInfo!=null?S.getExtraProfileInfo():"")};return I}logKernelProfile(r){const{kernelName:l,outputs:u,timeMs:p,inputs:g,extraInfo:f}=r;u.forEach(I=>{Promise.all([I.data(),p,f]).then(S=>{this.logger.logKernelProfile(l,I,S[0],S[1],g,S[2])})})}}function G7(r,l,u){if(l!=="float32")return!1;for(let p=0;p<r.length;p++){const g=r[p];if(isNaN(g)||!isFinite(g))return console.warn(`Found ${g} in the result of '${u}'`),!0}return!1}class V7{logKernelProfile(r,l,u,p,g,f){const I=typeof p=="number"?$c(`${p}ms`,9):p.error,S=$c(r,25),x=l.rank,v=l.size,O=$c(l.shape.toString(),14);let C="";for(const U in g){const G=g[U];if(G!=null){const ne=G.shape||l.shape,te=ne.length;C+=`${U}: ${te}D ${te>0?ne:""} `}}console.log(`%c${S} %c${I} %c${x}D ${O} %c${v} %c${C} %c${f}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function iO(r,l,u){const p={},g={};for(let x=0;x<l.length;x++)p[l[x].id]=!0;for(let x=0;x<r.length;x++){const v=r[x],O=v.inputs;for(const C in O){const U=O[C];let G=!1;for(let ne=0;ne<l.length;ne++)if(p[U.id]){v.outputs.forEach(te=>p[te.id]=!0),G=!0,g[v.id]=!0;break}if(G)break}}const f={};f[u.id]=!0;const I={};for(let x=r.length-1;x>=0;x--){const v=r[x],O=v.inputs;for(let C=0;C<v.outputs.length;C++)if(f[v.outputs[C].id]){for(const U in O)f[O[U].id]=!0,I[v.id]=!0;break}}const S=[];for(let x=0;x<r.length;x++){const v=r[x];if(g[v.id]&&I[v.id]){const O={};for(const U in v.inputs){const G=v.inputs[U];p[G.id]&&(O[U]=G)}const C=Object.assign({},v);C.inputs=O,C.outputs=v.outputs,S.push(C)}}return S}function rO(r,l,u,p){for(let g=l.length-1;g>=0;g--){const f=l[g],I=[];if(f.outputs.forEach(x=>{const v=r[x.id];v!=null?I.push(v):I.push(null)}),f.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${f.kernelName}.`);const S=f.gradient(I);for(const x in f.inputs){if(!(x in S))throw new Error(`Cannot backprop through input ${x}. Available gradients found: ${Object.keys(S)}.`);const v=u(()=>S[x]());if(v.dtype!=="float32")throw new Error(`Error in gradient for op ${f.kernelName}. The gradient of input ${x} must have 'float32' dtype, but has '${v.dtype}'`);const O=f.inputs[x];if(!ra(v.shape,O.shape))throw new Error(`Error in gradient for op ${f.kernelName}. The gradient of input '${x}' has shape '${v.shape}', which does not match the shape of the input '${O.shape}'`);if(r[O.id]==null)r[O.id]=v;else{const C=r[O.id];r[O.id]=p(C,v),C.dispose()}}}}const oO=20,Tu=3,uI=7;function aO(r,l,u,p){const g=xu(l),f=Y7(r,l,u,g),I=l.length,S=tg(r,l,u,g,f),x=["Tensor"];return p&&(x.push(` dtype: ${u}`),x.push(` rank: ${I}`),x.push(` shape: [${l}]`),x.push(" values:")),x.push(S.map(v=>" "+v).join(`
`)),x.join(`
`)}function Y7(r,l,u,p){const g=qt(l),f=p[p.length-1],I=new Array(f).fill(0),S=l.length,x=u==="complex64"?vu(r):r;if(S>1)for(let v=0;v<g/f;v++){const O=v*f;for(let C=0;C<f;C++)I[C]=Math.max(I[C],Au(x[O+C],0,u).length)}return I}function Au(r,l,u){let p;return Array.isArray(r)?p=`${parseFloat(r[0].toFixed(uI))} + ${parseFloat(r[1].toFixed(uI))}j`:Su(r)?p=`'${r}'`:u==="bool"?p=cO(r):p=parseFloat(r.toFixed(uI)).toString(),$c(p,l)}function cO(r){return r===0?"false":"true"}function tg(r,l,u,p,g,f=!0){const I=u==="complex64"?2:1,S=l[0],x=l.length;if(x===0){if(u==="complex64"){const te=vu(r);return[Au(te[0],0,u)]}return u==="bool"?[cO(r[0])]:[r[0].toString()]}if(x===1){if(S>oO){const oe=Tu*I;let ge=Array.from(r.slice(0,oe)),fe=Array.from(r.slice((S-Tu)*I,S*I));return u==="complex64"&&(ge=vu(ge),fe=vu(fe)),["["+ge.map((Ae,Te)=>Au(Ae,g[Te],u)).join(", ")+", ..., "+fe.map((Ae,Te)=>Au(Ae,g[S-Tu+Te],u)).join(", ")+"]"]}const te=u==="complex64"?vu(r):Array.from(r);return["["+te.map((oe,ge)=>Au(oe,g[ge],u)).join(", ")+"]"]}const v=l.slice(1),O=p.slice(1),C=p[0]*I,U=[];if(S>oO){for(let te=0;te<Tu;te++){const oe=te*C,ge=oe+C;U.push(...tg(r.slice(oe,ge),v,u,O,g,!1))}U.push("...");for(let te=S-Tu;te<S;te++){const oe=te*C,ge=oe+C;U.push(...tg(r.slice(oe,ge),v,u,O,g,te===S-1))}}else for(let te=0;te<S;te++){const oe=te*C,ge=oe+C;U.push(...tg(r.slice(oe,ge),v,u,O,g,te===S-1))}const G=x===2?",":"";U[0]="["+U[0]+G;for(let te=1;te<U.length-1;te++)U[te]=" "+U[te]+G;let ne=`,
`;for(let te=2;te<x;te++)ne+=`
`;return U[U.length-1]=" "+U[U.length-1]+"]"+(f?"":ne),U}function vu(r){const l=[];for(let u=0;u<r.length;u+=2)l.push([r[u],r[u+1]]);return l}class lO{constructor(r,l,u){if(this.dtype=l,this.shape=r.slice(),this.size=qt(r),u!=null){const p=u.length;Z(p===this.size,()=>`Length of values '${p}' does not match the size inferred by the shape '${this.size}'.`)}if(l==="complex64")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=u||JR(l,this.size),this.strides=xu(r)}set(r,...l){l.length===0&&(l=[0]),Z(l.length===this.rank,()=>`The number of provided coordinates (${l.length}) must match the rank (${this.rank})`);const u=this.locToIndex(l);this.values[u]=r}get(...r){r.length===0&&(r=[0]);let l=0;for(const p of r){if(p<0||p>=this.shape[l]){const g=`Requested out of range element at ${r}. Buffer shape=${this.shape}`;throw new Error(g)}l++}let u=r[r.length-1];for(let p=0;p<r.length-1;++p)u+=this.strides[p]*r[p];return this.values[u]}locToIndex(r){if(this.rank===0)return 0;if(this.rank===1)return r[0];let l=r[r.length-1];for(let u=0;u<r.length-1;++u)l+=this.strides[u]*r[u];return l}indexToLoc(r){if(this.rank===0)return[];if(this.rank===1)return[r];const l=new Array(this.shape.length);for(let u=0;u<l.length-1;++u)l[u]=Math.floor(r/this.strides[u]),r-=l[u]*this.strides[u];return l[l.length-1]=r,l}get rank(){return this.shape.length}toTensor(){return zi().makeTensor(this.values,this.shape,this.dtype)}}let zi=null,Uc=null,H7=null;function hO(r){zi=r}function uO(r){Uc=r}function dO(r){H7=r}class xn{constructor(r,l,u,p){this.kept=!1,this.isDisposedInternal=!1,this.shape=r.slice(),this.dtype=l||"float32",this.size=qt(r),this.strides=xu(r),this.dataId=u,this.id=p,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const r=await this.data();return Uc.buffer(this.shape,this.dtype,r)}bufferSync(){return Uc.buffer(this.shape,this.dtype,this.dataSync())}async array(){const r=await this.data();return cI(this.shape,r)}arraySync(){return cI(this.shape,this.dataSync())}async data(){this.throwIfDisposed();const r=zi().read(this.dataId);if(this.dtype==="string"){const l=await r;try{return l.map(u=>hI(u))}catch(u){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return r}dataSync(){this.throwIfDisposed();const r=zi().readSync(this.dataId);if(this.dtype==="string")try{return r.map(l=>hI(l))}catch(l){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return r}async bytes(){this.throwIfDisposed();const r=await zi().read(this.dataId);return this.dtype==="string"?r:new Uint8Array(r.buffer)}dispose(){if(this.isDisposed)return;zi().disposeTensor(this),this.isDisposedInternal=!0}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(r=!1){return Uc.print(this,r)}clone(){return this.throwIfDisposed(),Uc.clone(this)}toString(r=!1){const l=this.dataSync();return aO(l,this.shape,this.dtype,r)}cast(r){return this.throwIfDisposed(),Uc.cast(this,r)}variable(r=!0,l,u){return this.throwIfDisposed(),zi().makeVariable(this,r,l,u)}}Object.defineProperty(xn,Symbol.hasInstance,{value:r=>!!r&&r.data!=null&&r.dataSync!=null&&r.throwIfDisposed!=null});class ng extends xn{constructor(r,l,u,p){super(r.shape,r.dtype,r.dataId,p);this.trainable=l,this.name=u}assign(r){if(r.dtype!==this.dtype)throw new Error(`dtype of the new value (${r.dtype}) and previous value (${this.dtype}) must match`);if(!ra(r.shape,this.shape))throw new Error(`shape of the new value (${r.shape}) and previous value (${this.shape}) must match`);zi().disposeTensor(this),this.dataId=r.dataId,zi().incRef(this,null)}dispose(){zi().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(ng,Symbol.hasInstance,{value:r=>r instanceof xn&&r.assign!=null&&r.assign instanceof Function});var pO;(function(r){r.R0="R0",r.R1="R1",r.R2="R2",r.R3="R3",r.R4="R4",r.R5="R5",r.R6="R6"})(pO||(pO={}));var dI;(function(r){r.float32="float32",r.int32="int32",r.bool="int32",r.complex64="complex64"})(dI||(dI={}));var pI;(function(r){r.float32="float32",r.int32="int32",r.bool="bool",r.complex64="complex64"})(pI||(pI={}));var mI;(function(r){r.float32="float32",r.int32="float32",r.bool="float32",r.complex64="complex64"})(mI||(mI={}));var fI;(function(r){r.float32="complex64",r.int32="complex64",r.bool="complex64",r.complex64="complex64"})(fI||(fI={}));const q7={float32:mI,int32:dI,bool:pI,complex64:fI};function mO(r,l){if(r==="string"||l==="string"){if(r==="string"&&l==="string")return"string";throw new Error(`Can not upcast ${r} with ${l}`)}return q7[r][l]}function ft(r,l){if(r.dtype===l.dtype)return[r,l];const u=mO(r.dtype,l.dtype);return[r.cast(u),l.cast(u)]}function sg(r){const l=[],u=new Set;return fO(r,l,u),l}function fO(r,l,u){if(r==null)return;if(r instanceof xn){l.push(r);return}if(!j7(r))return;const p=r;for(const g in p){const f=p[g];u.has(f)||(u.add(f),fO(f,l,u))}}function j7(r){return Array.isArray(r)||typeof r=="object"}class gO{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}}dispose(){for(const r in this.registeredVariables)this.registeredVariables[r].dispose()}}class Nu{constructor(r){this.ENV=r,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new gO}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;const r=this.getSortedBackends();for(let l=0;l<r.length;l++){const u=r[l],p=await this.initializeBackend(u).success;if(p){await this.setBackend(u);return}}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(this.pendingBackendInit!=null)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(this.backendInstance==null){const{name:r,asyncInit:l}=this.initializeBackendsAndReturnBest();if(l)throw new Error(`The highest priority backend '${r}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(r)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(r){if(!(r in this.registry))if(r in this.registryFactory){const{asyncInit:l}=this.initializeBackend(r);if(l)return null}else return null;return this.registry[r]}findBackendFactory(r){return r in this.registryFactory?this.registryFactory[r].factory:null}registerBackend(r,l,u=1){return r in this.registryFactory?(console.warn(`${r} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[r]={factory:l,priority:u},!0)}async setBackend(r){if(this.registryFactory[r]==null)throw new Error(`Backend name '${r}' not found in registry`);if(this.backendName=r,this.registry[r]==null){this.backendInstance=null;const{success:l,asyncInit:u}=this.initializeBackend(r),p=u?await l:l;if(!p)return!1}return this.backendInstance=this.registry[r],this.setupRegisteredKernels(),this.profiler=new sO(this.backendInstance),!0}setupRegisteredKernels(){const r=oI(this.backendName);r.forEach(l=>{l.setupFunc!=null&&l.setupFunc(this.backendInstance)})}disposeRegisteredKernels(r){const l=oI(r);l.forEach(u=>{u.disposeFunc!=null&&u.disposeFunc(this.registry[r])})}initializeBackend(r){const l=this.registryFactory[r];if(l==null)throw new Error(`Cannot initialize backend ${r}, no registration found.`);try{const u=l.factory();if(u&&!(u instanceof w2)&&typeof u.then=="function"){const p=++this.pendingBackendInitId,g=u.then(f=>p<this.pendingBackendInitId?!1:(this.registry[r]=f,this.pendingBackendInit=null,!0)).catch(f=>(p<this.pendingBackendInitId||(this.pendingBackendInit=null,console.warn(`Initialization of backend ${r} failed`),console.warn(f.stack||f.message)),!1));return this.pendingBackendInit=g,{success:g,asyncInit:!0}}else return this.registry[r]=u,{success:!0,asyncInit:!1}}catch(u){return console.warn(`Initialization of backend ${r} failed`),console.warn(u.stack||u.message),{success:!1,asyncInit:!1}}}removeBackend(r){if(!(r in this.registryFactory))throw new Error(`${r} backend not found in registry`);this.backendName===r&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,r in this.registry&&(this.disposeRegisteredKernels(r),this.registry[r].dispose(),delete this.registry[r]),delete this.registryFactory[r],this.backendName===r&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(Object.keys(this.registryFactory).length===0)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((r,l)=>this.registryFactory[l].priority-this.registryFactory[r].priority)}initializeBackendsAndReturnBest(){const r=this.getSortedBackends();for(let l=0;l<r.length;l++){const u=r[l],{success:p,asyncInit:g}=this.initializeBackend(u);if(g||p)return{name:u,asyncInit:g}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(r,l){const u=this.state.tensorInfo.get(l),p=u.backend,g=this.readSync(l);p.disposeData(l),u.backend=r,r.move(l,g,u.shape,u.dtype),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(r,l){let u=null;if(l==null){if(typeof r!="function")throw new Error("Please provide a function to tidy()");l=r}else{if(typeof r!="string"&&!(r instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof l!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");u=r}let p;return this.scopedRun(()=>this.startScope(u),()=>this.endScope(p),()=>(p=l(),p instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),p))}scopedRun(r,l,u){r();try{const p=u();return l(),p}catch(p){throw l(),p}}nextTensorId(){return Nu.nextTensorId++}nextVariableId(){return Nu.nextVariableId++}clone(r){const l=this.makeTensorFromDataId(r.dataId,r.shape,r.dtype),u={x:r},p=f=>({x:()=>{const I="float32",S={x:f},x={dtype:I};return Y.runKernelFunc(v=>v.cast(f,I),S,null,Fc,x)}}),g=[];return this.addTapeNode(this.state.activeScope.name,u,[l],p,g,{}),l}runKernel(r,l,u,p,g){const f=null,I=null;return this.runKernelFunc(f,l,I,r,u,p,g)}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(r,l,u){const p=this.backend.numDataIds();let g=0;u.forEach(S=>{g+=S.dtype==="complex64"?3:1});const f=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],I=p-l-g-f;if(I>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${I} data ids) after running '${r}'`)}runKernelFunc(r,l,u,p,g,f,I){let S,x=[];const v=this.isTapeOn();p==null&&(p=this.state.activeScope!=null?this.state.activeScope.name:"");const O=this.state.numBytes,C=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let U;const G=Jf(p,this.backendName);let ne;if(G!=null)U=()=>{const oe=this.backend.numDataIds();ne=G.kernelFunc({inputs:l,attrs:g,backend:this.backend});const ge=Array.isArray(ne)?ne:[ne];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(p,oe,ge);const fe=ge.map(({dataId:Ae,shape:Te,dtype:Ve})=>this.makeTensorFromDataId(Ae,Te,Ve));if(v){let Ae=this.getTensorsForGradient(p,l,fe);if(Ae==null){I==null&&(I=[]);const Te=fe.filter((Ve,rt)=>I[rt]);Ae=(f||[]).slice().concat(Te)}x=this.saveTensorsForBackwardMode(Ae)}return fe};else{const oe=ge=>{if(!v)return;x=ge.map(fe=>this.keep(this.clone(fe)))};U=()=>{const ge=this.backend.numDataIds();ne=this.tidy(()=>r(this.backend,oe));const fe=Array.isArray(ne)?ne:[ne];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(p,ge,fe),fe}}let te;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?S=U():(te=this.profiler.profileKernel(p,l,()=>U()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(te),S=te.outputs)}),v&&this.addTapeNode(p,l,S,u,x,g),this.state.profiling&&this.state.activeProfile.kernels.push({name:p,bytesAdded:this.state.numBytes-O,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-C,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(l).map(oe=>l[oe]!=null?l[oe].shape:null),outputShapes:S.map(oe=>oe.shape),kernelTimeMs:te.timeMs,extraInfo:te.extraInfo}),Array.isArray(ne)?S:S[0]}saveTensorsForBackwardMode(r){const l=r.map(u=>this.keep(this.clone(u)));return l}getTensorsForGradient(r,l,u){const p=rI(r);if(p!=null){const g=p.inputsToSave||[],f=p.outputsToSave||[];let I;p.saveAllInputs?(Z(Array.isArray(l),()=>"saveAllInputs is true, expected inputs to be an array."),I=Object.keys(l).map(x=>l[x])):I=g.map(x=>l[x]);const S=u.filter((x,v)=>f[v]);return I.concat(S)}return null}makeTensor(r,l,u,p){if(r==null)throw new Error("Values passed to engine.makeTensor() are null");u=u||"float32",p=p||this.backend;let g=r;u==="string"&&Su(r[0])&&(g=r.map(S=>nO(S)));const f=p.write(g,l,u),I=new xn(l,u,f,this.nextTensorId());if(this.incRef(I,p),u==="string"){const S=this.state.tensorInfo.get(f),x=eO(g);this.state.numBytes+=x-S.bytes,S.bytes=x}return I}makeTensorFromDataId(r,l,u,p){u=u||"float32";const g=new xn(l,u,r,this.nextTensorId());return this.incRef(g,p),g}makeVariable(r,l=!0,u,p){u=u||this.nextVariableId().toString(),p!=null&&p!==r.dtype&&(r=r.cast(p));const g=new ng(r,l,u,this.nextTensorId());if(this.state.registeredVariables[g.name]!=null)throw new Error(`Variable with name ${g.name} was already registered`);return this.state.registeredVariables[g.name]=g,this.incRef(g,this.backend),g}incRef(r,l){const u=this.state.tensorInfo.has(r.dataId)?this.state.tensorInfo.get(r.dataId).refCount:0;if(this.state.numTensors++,r.dtype==="string"&&this.state.numStringTensors++,u===0){this.state.numDataBuffers++;let p=0;r.dtype!=="complex64"&&r.dtype!=="string"&&(p=r.size*QR(r.dtype)),this.state.tensorInfo.set(r.dataId,{backend:l||this.backend,dtype:r.dtype,shape:r.shape,bytes:p,refCount:0}),this.state.numBytes+=p}this.state.tensorInfo.get(r.dataId).refCount++,r instanceof ng||this.track(r)}disposeTensor(r){if(!this.state.tensorInfo.has(r.dataId))return;this.state.numTensors--,r.dtype==="string"&&this.state.numStringTensors--;const l=this.state.tensorInfo.get(r.dataId),u=l.refCount;u<=1?(r.dtype!=="complex64"&&(this.state.numBytes-=l.bytes),this.state.numDataBuffers--,l.backend.disposeData(r.dataId),this.state.tensorInfo.delete(r.dataId)):this.state.tensorInfo.get(r.dataId).refCount--}disposeVariables(){for(const r in this.state.registeredVariables){const l=this.state.registeredVariables[r];this.disposeVariable(l)}}disposeVariable(r){this.disposeTensor(r),this.state.registeredVariables[r.name]!=null&&delete this.state.registeredVariables[r.name]}memory(){const r=this.backend.memory();return r.numTensors=this.state.numTensors,r.numDataBuffers=this.state.numDataBuffers,r.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(r.unreliable=!0,r.reasons==null&&(r.reasons=[]),r.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),r}async profile(r){this.state.profiling=!0;const l=this.state.numBytes,u=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await r(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(p=>p.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-l,this.state.activeProfile.newTensors=this.state.numTensors-u;for(const p of this.state.activeProfile.kernels)p.kernelTimeMs=await p.kernelTimeMs,p.extraInfo=await p.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(r,l,u,p,g,f){const I={id:this.state.nextTapeNodeId++,kernelName:r,inputs:l,outputs:u,saved:g},S=rI(r);S!=null&&(p=S.gradFunc),p!=null&&(I.gradient=x=>(x=x.map((v,O)=>{if(v==null){const C=u[O],U=oa(C.size,C.dtype);return this.makeTensor(U,C.shape,C.dtype)}return v}),p(x.length>1?x:x[0],g,f))),this.state.activeTape.push(I)}keep(r){return r.kept=!0,r}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(r){const l={track:[],name:"unnamed scope",id:this.state.nextScopeId++};r&&(l.name=r),this.state.scopeStack.push(l),this.state.activeScope=l}endScope(r){const l=sg(r),u=new Set(l.map(g=>g.id));for(let g=0;g<this.state.activeScope.track.length;g++){const f=this.state.activeScope.track[g];!f.kept&&!u.has(f.id)&&f.dispose()}const p=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],l.forEach(g=>{!g.kept&&g.scopeId===p.id&&this.track(g)})}gradients(r,l,u,p=!1){if(Z(l.length>0,()=>"gradients() received an empty list of xs."),u!=null&&u.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${u.dtype}'`);const g=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",r));Z(g instanceof xn,()=>"The result y returned by f() must be a tensor.");const f=iO(this.state.activeTape,l,g);if(!p&&f.length===0&&l.length>0)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 I={};I[g.id]=u==null?K7(g.shape):u,rO(I,f,x=>this.tidy(x),X7);const S=l.map(x=>I[x.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(x=>{for(const v of x.saved)v.dispose()}),this.state.activeTape=null),{value:g,grads:S}})}customGrad(r){return Z(aI(r),()=>"The f passed in customGrad(f) must be a function."),(...l)=>{Z(l.every(g=>g instanceof xn),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let u;const p={};return l.forEach((g,f)=>{p[f]=g}),this.runKernelFunc((g,f)=>(u=r(...l,f),Z(u.value instanceof xn,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),Z(aI(u.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),u.value),p,(g,f)=>{const I=u.gradFunc(g,f),S=Array.isArray(I)?I:[I];Z(S.length===l.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(...)."),Z(S.every(v=>v instanceof xn),()=>"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 x={};return S.forEach((v,O)=>{x[O]=()=>v}),x})}}readSync(r){const l=this.state.tensorInfo.get(r);return l.backend.readSync(r)}read(r){const l=this.state.tensorInfo.get(r);return l.backend.read(r)}async time(r){const l=lI(),u=await this.backend.time(r);return u.wallMs=lI()-l,u}track(r){return this.state.activeScope!=null&&(r.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(r)),r}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new gO;for(const r in this.registry)this.disposeRegisteredKernels(r),this.registry[r].dispose(),delete this.registry[r];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}Nu.nextTensorId=0;Nu.nextVariableId=0;function K7(r){const l=Qf(qt(r),"float32");return Y.makeTensor(l,r,"float32")}function gI(){const r=tI();if(r._tfengine==null){const l=new S2(r);r._tfengine=new Nu(l)}return x2(r._tfengine.ENV),hO(()=>r._tfengine),r._tfengine}const Y=gI();function X7(r,l){const u={a:r,b:l};return Y.runKernelFunc((p,g)=>{const f=p.add(r,l);return g([r,l]),f},u,null,kc)}function yO(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}const pr=Rs();pr.registerFlag("DEBUG",()=>!1,r=>{r&&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.")});pr.registerFlag("IS_BROWSER",()=>yO());pr.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");pr.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));pr.registerFlag("PROD",()=>!1);pr.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>pr.getBool("DEBUG"));pr.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);pr.registerFlag("IS_TEST",()=>!1);function mr(r,l){let u=r;if(Os(r))return l==="string"?[]:[r.length];if(!Array.isArray(r))return[];const p=[];for(;Array.isArray(u)||Os(u)&&l!=="string";)p.push(u.length),u=u[0];return Array.isArray(r)&&Rs().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&bO(r,p,[]),p}function bO(r,l,u){if(u=u||[],!Array.isArray(r)&&!Os(r)){Z(l.length===0,()=>`Element arr[${u.join("][")}] is a primitive, but should be an array/TypedArray of ${l[0]} elements`);return}Z(l.length>0,()=>`Element arr[${u.join("][")}] should be a primitive, but is an array of ${r.length} elements`),Z(r.length===l[0],()=>`Element arr[${u.join("][")}] should have ${l[0]} elements, but has ${r.length} elements`);const p=l.slice(1);for(let g=0;g<r.length;++g)bO(r[g],p,u.concat(g))}function wO(r,l,u,p){if(r==null)return;if(r!=="numeric"&&r!==l||r==="numeric"&&l==="string")throw new Error(`Argument '${u}' passed to '${p}' must be ${r} tensor, but got ${l} tensor`)}function M(r,l,u,p="numeric"){if(r instanceof xn)return wO(p,r.dtype,l,u),r;let g=Iu(r);if(g!=="string"&&["bool","int32","float32"].indexOf(p)>=0&&(g=p),wO(p,g,l,u),r==null||!Os(r)&&!Array.isArray(r)&&typeof r!="number"&&typeof r!="boolean"&&typeof r!="string"){const x=r==null?"null":r.constructor.name;throw new Error(`Argument '${l}' passed to '${u}' must be a Tensor or TensorLike, but got '${x}'`)}const f=mr(r,g);!Os(r)&&!Array.isArray(r)&&(r=[r]);const I=!0,S=g!=="string"?Zf(r,g):Wc(r,[],I);return Y.makeTensor(S,f,g)}function ig(r,l,u,p="numeric"){if(!Array.isArray(r))throw new Error(`Argument ${l} passed to ${u} must be a \`Tensor[]\` or \`TensorLike[]\``);const g=r;return g.map((f,I)=>M(f,`${l}[${I}]`,u),p)}const LO="__op";function z(r){const l=Object.keys(r);if(l.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${l.length} keys.`);let u=l[0];const p=r[u];u.endsWith("_")&&(u=u.substring(0,u.length-1)),u=u+LO;const g=(...f)=>{Y.startScope(u);try{const I=p(...f);return I instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),Y.endScope(I),I}catch(I){throw Y.endScope(null),I}};return Object.defineProperty(g,"name",{value:u,configurable:!0}),g}function J7(r,l){const u=M(r,"real","complex"),p=M(l,"imag","complex");Zt(u.shape,p.shape,`real and imag shapes, ${u.shape} and ${p.shape}, must match in call to tf.complex().`);const g=I=>I.complex(u,p),f={real:u,imag:p};return Y.runKernelFunc(g,f,null,M2)}const Gi=z({complex_:J7});function Vi(r,l,u,p){if(p==null&&(p=Iu(r)),p==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!Os(r)&&!Array.isArray(r)&&typeof r!="number"&&typeof r!="boolean"&&typeof r!="string")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(l!=null){eg(l);const g=qt(l),f=qt(u);Z(g===f,()=>`Based on the provided shape, [${l}], the tensor should have ${g} values but has ${f}`);for(let I=0;I<u.length;++I){const S=u[I],x=I===u.length-1?S!==qt(l.slice(I)):!0;Z(u[I]===l[I]||!x,()=>`Error creating a new Tensor. Inferred shape (${u}) does not match the provided shape (${l}). `)}}return!Os(r)&&!Array.isArray(r)&&(r=[r]),l=l||u,r=p!=="string"?Zf(r,p):Wc(r,[],!0),Y.makeTensor(r,l,p)}function yI(r,l,u){const p=mr(r,u);return Vi(r,l,p,u)}function Cu(r,l="float32",u){return l=l||"float32",eg(r),new lO(r,l,u)}function Z7(r,l){const u=M(r,"x","cast");if(!ZR(l))throw new Error(`Failed to cast to unknown dtype ${l}`);if(l==="string"&&u.dtype!=="string"||l!=="string"&&u.dtype==="string")throw new Error("Only strings can be casted to strings");const p={x:u},g={dtype:l};return Y.runKernelFunc(f=>f.cast(u,l),p,null,Fc,g)}const Le=z({cast_:Z7});function Q7(r){const l=M(r,"x","clone",null),u=()=>Y.makeTensorFromDataId(l.dataId,l.shape,l.dtype),p={x:l};return Y.runKernelFunc(u,p,null,yf)}const gi=z({clone_:Q7});function bI(r,l=!1){console.log(r.toString(l))}gI();const eJ={buffer:Cu,cast:Le,clone:gi,print:bI};uO(eJ);function tJ(r,l){const u=M(r,"x","reshape",null),p={x:u},g={shape:l},f=(I,S)=>(l=KR(l,u.size),Z(u.size===qt(l),()=>"new shape and old shape must have the same number of elements."),S([u]),I.reshape(u,l));return Y.runKernelFunc(f,p,null,Rf,g)}const ie=z({reshape_:tJ});function nJ(r,l,u=!1,p=!1){let g=M(r,"a","matMul"),f=M(l,"b","matMul");[g,f]=ft(g,f),Z(g.rank>=2&&f.rank>=2&&g.rank===f.rank,()=>`Error in matMul: inputs must have the same rank of at least 2, got ranks ${g.rank} and ${f.rank}.`);const I=u?g.shape[g.rank-2]:g.shape[g.rank-1],S=p?f.shape[f.rank-1]:f.shape[f.rank-2],x=u?g.shape[g.rank-1]:g.shape[g.rank-2],v=p?f.shape[f.rank-2]:f.shape[f.rank-1],O=g.shape.slice(0,-2),C=f.shape.slice(0,-2),U=qt(O),G=qt(C);Z(ra(O,C),()=>`Error in matMul: outer dimensions (${O}) and (${C}) of Tensors with shapes ${g.shape} and ${f.shape} must match.`),Z(I===S,()=>`Error in matMul: inner shapes (${I}) and (${S}) of Tensors with shapes ${g.shape} and ${f.shape} and transposeA=${u} and transposeB=${p} must match.`);const ne=g.shape.slice(0,-2).concat([x,v]),te=u?ie(g,[U,I,x]):ie(g,[U,x,I]),oe=p?ie(f,[G,v,S]):ie(f,[G,S,v]),ge=(Ve,rt)=>(rt([te,oe]),Ve.batchMatMul(te,oe,u,p)),fe={a:te,b:oe},Ae={transposeA:u,transposeB:p},Te=Y.runKernelFunc(ge,fe,null,tf,Ae);return ie(Te,ne)}const dn=z({matMul_:nJ});function sJ(r,l){const u=M(r,"x","transpose");if(l==null&&(l=u.shape.map((f,I)=>I).reverse()),Z(u.rank===l.length,()=>`Error in transpose: rank of input ${u.rank} must match length of perm ${l}.`),l.forEach(f=>{Z(f>=0&&f<u.rank,()=>`All entries in 'perm' must be between 0 and ${u.rank-1} but got ${l}`)}),u.rank<=1)return u.clone();const p={x:u},g={perm:l};return Y.runKernelFunc(f=>f.transpose(u,l),p,null,Hf,g)}const $t=z({transpose_:sJ});function wI(r,l,u){if(_c(r),l!=null&&l.length!==3)throw new Error("tensor3d() requires shape to have three numbers");const p=mr(r,u);if(p.length!==3&&p.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(p.length===1&&l==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Vi(r,l,p,u)}const LI={};uu(LI,{fromPixels:()=>oJ,toPixels:()=>rJ});let Bc;function iJ(r,l=3){if(l>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(r==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let u=!1,p=!1,g=!1,f=!1,I=!1;if(r.data instanceof Uint8Array)u=!0;else if(typeof ImageData!="undefined"&&r instanceof ImageData)p=!0;else if(typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement)g=!0;else if(typeof HTMLImageElement!="undefined"&&r instanceof HTMLImageElement)f=!0;else if(r.getContext!=null)I=!0;else 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 ${r.constructor.name}`);if(g){const G=2;if(g&&r.readyState<G)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.")}const S=Jf(sI,Y.backendName);if(S!=null){const G={pixels:r},ne={numChannels:l};return Y.runKernel(sI,G,ne)}const[x,v]=g?[r.videoWidth,r.videoHeight]:[r.width,r.height];let O;I?O=r.getContext("2d").getImageData(0,0,x,v).data:p||u?O=r.data:(f||g)&&(Bc==null&&(Bc=document.createElement("canvas").getContext("2d")),Bc.canvas.width=x,Bc.canvas.height=v,Bc.drawImage(r,0,0,x,v),O=Bc.getImageData(0,0,x,v).data);let C;if(l===4)C=new Int32Array(O);else{const G=x*v;C=new Int32Array(G*l);for(let ne=0;ne<G;ne++)for(let te=0;te<l;++te)C[ne*l+te]=O[ne*4+te]}const U=[v,x,l];return wI(C,U,"int32")}async function rJ(r,l){let u=M(r,"img","toPixels");if(!(r instanceof xn)){const v=u;u=Le(v,"int32"),v.dispose()}if(u.rank!==2&&u.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${u.rank}.`);const[p,g]=u.shape.slice(0,2),f=u.rank===2?1:u.shape[2];if(f>4||f===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${f}`);if(u.dtype!=="float32"&&u.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${u.dtype}. Please use float32 or int32 tensors.`);const I=await u.data(),S=u.dtype==="float32"?255:1,x=new Uint8ClampedArray(g*p*4);for(let v=0;v<p*g;++v){const O=[0,0,0,255];for(let U=0;U<f;U++){const G=I[v*f+U];if(u.dtype==="float32"){if(G<0||G>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${G}.`)}else if(u.dtype==="int32"&&(G<0||G>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${G}.`);f===1?(O[0]=G*S,O[1]=G*S,O[2]=G*S):O[U]=G*S}const C=v*4;x[C+0]=Math.round(O[0]),x[C+1]=Math.round(O[1]),x[C+2]=Math.round(O[2]),x[C+3]=Math.round(O[3])}if(l!=null){l.width=g,l.height=p;const v=l.getContext("2d"),O=new ImageData(x,g,p);v.putImageData(O,0,0)}return u!==r&&u.dispose(),x}const oJ=z({fromPixels_:iJ});function SO(r,l,u){const p=r.shape.length;Z(p===l.length,()=>`Error in slice${p}D: Length of begin ${l} must match the rank of the array (${p}).`),Z(p===u.length,()=>`Error in slice${p}D: Length of size ${u} must match the rank of the array (${p}).`);for(let g=0;g<p;++g)Z(l[g]+u[g]<=r.shape[g],()=>`Error in slice${p}D: begin[${g}] + size[${g}] (${l[g]+u[g]}) would overflow input.shape[${g}] (${r.shape[g]})`)}function rg(r,l,u){let p;const g=r.shape.length;typeof l=="number"?p=[l,...new Array(g-1).fill(0)]:l.length<g?p=l.concat(new Array(g-l.length).fill(0)):p=l.slice(),p.forEach(I=>{Z(I!==-1,()=>"slice() does not support negative begin indexing.")});let f;return u==null?f=new Array(g).fill(-1):typeof u=="number"?f=[u,...new Array(g-1).fill(-1)]:u.length<g?f=u.concat(new Array(g-u.length).fill(-1)):f=u,f=f.map((I,S)=>I>=0?I:(Z(I===-1,()=>`Negative size values should be exactly -1 but got ${I} for the slice() size at index ${S}.`),r.shape[S]-p[S])),[p,f]}function aJ(r){Rs().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(r+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}dO(aJ);function IO(r,l){return Y.tidy(r,l)}function xO(r){const l=sg(r);l.forEach(u=>u.dispose())}function cJ(r,l){let u=M(r,"a","add"),p=M(l,"b","add");[u,p]=ft(u,p);const g=(I,S)=>{const x=I.add(u,p);return S([u,p]),x},f={a:u,b:p};return Y.runKernelFunc(g,f,null,kc)}const Lt=z({add_:cJ});function lJ(r,l){let u=M(r,"a","floorDiv"),p=M(l,"b","floorDiv");[u,p]=ft(u,p);const g=(I,S)=>{const x=I.floorDiv(u,p);return S([u,p]),x},f={a:u,b:p};return Y.runKernelFunc(g,f,null,mf)}const SI=z({floorDiv_:lJ});function hJ(r,l){let u=M(r,"a","div"),p=M(l,"b","div");if([u,p]=ft(u,p),u.dtype==="int32"&&p.dtype==="int32")return SI(u,p);const g=(S,x)=>{const v=S.realDivide(u,p);return x([u,p]),v},f={a:u,b:p},I={};return Y.runKernelFunc(g,f,null,uf,I)}const Pe=z({div_:hJ});function uJ(r,l){let u=M(r,"a","mul"),p=M(l,"b","mul");[u,p]=ft(u,p);const g=(I,S)=>{const x=I.multiply(u,p);return S([u,p]),x},f={a:u,b:p};return Y.runKernelFunc(g,f,null,Tf)}const ae=z({mul_:uJ});function dJ(r){const l=M(r,"x","abs"),u={x:l};return Y.runKernelFunc((p,g)=>(g([l]),l.dtype==="complex64"?p.complexAbs(l):p.abs(l)),u,null,ef)}const Bn=z({abs_:dJ});function pJ(r,l){for(let u=0;u<r.length;++u)if(r[r.length-u-1]!==l-1-u)return!1;return!0}function mJ(r,l,u){const p=r.length+l.length,g=[];let f=0,I=0;for(let S=0;S<p;S++)u.indexOf(S)===-1?g.push(r[f++]):g.push(l[I++]);return g}function TO(r,l){const u=[],p=r.length;for(let f=0;f<p;f++)l.indexOf(f)===-1&&u.push(r[f]);const g=l.map(f=>r[f]);return[u,g]}function Qn(r,l){const u=l.map(p=>1);return mJ(r,u,l)}function ds(r,l){if(pJ(r,l))return null;const u=[];for(let p=0;p<l;++p)r.indexOf(p)===-1&&u.push(p);return r.forEach(p=>u.push(p)),u}function Mc(r){return r.map((l,u)=>[u,l]).sort((l,u)=>l[1]-u[1]).map(l=>l[0])}function ro(r,l){const u=[];for(let p=l-r;p<l;++p)u.push(p);return u}function ag(r,l,u,p,g,f,I="channelsLast"){const[S,x]=og(l);let v;if(I==="channelsLast")v=[S,x,r[3],r[3]];else if(I==="channelsFirst")v=[S,x,r[1],r[1]];else throw new Error(`Unknown dataFormat ${I}`);return fr(r,v,u,p,g,f,!1,I)}function cg(r,l,u,p,g,f,I="NDHWC"){const[S,x,v]=II(l);let O,C;if(I==="NDHWC")C="channelsLast",O=[S,x,v,r[4],r[4]];else if(I==="NCDHW")C="channelsFirst",O=[S,x,v,r[1],r[1]];else throw new Error(`Unknown dataFormat ${I}`);return Ru(r,O,u,p,g,!1,C,f)}function fr(r,l,u,p,g,f,I=!1,S="channelsLast"){let[x,v,O,C]=[-1,-1,-1,-1];if(S==="channelsLast")[x,v,O,C]=r;else if(S==="channelsFirst")[x,C,v,O]=r;else throw new Error(`Unknown dataFormat ${S}`);const[U,G,,ne]=l,[te,oe]=og(u),[ge,fe]=og(p),Ae=Pc(U,ge),Te=Pc(G,fe),{padInfo:Ve,outHeight:rt,outWidth:Ct}=fJ(g,v,O,te,oe,Ae,Te,f,S),Ut=I?ne*C:ne;let Kt;return S==="channelsFirst"?Kt=[x,Ut,rt,Ct]:S==="channelsLast"&&(Kt=[x,rt,Ct,Ut]),{batchSize:x,dataFormat:S,inHeight:v,inWidth:O,inChannels:C,outHeight:rt,outWidth:Ct,outChannels:Ut,padInfo:Ve,strideHeight:te,strideWidth:oe,filterHeight:U,filterWidth:G,effectiveFilterHeight:Ae,effectiveFilterWidth:Te,dilationHeight:ge,dilationWidth:fe,inShape:r,outShape:Kt,filterShape:l}}function Ru(r,l,u,p,g,f=!1,I="channelsLast",S){let[x,v,O,C,U]=[-1,-1,-1,-1,-1];if(I==="channelsLast")[x,v,O,C,U]=r;else if(I==="channelsFirst")[x,U,v,O,C]=r;else throw new Error(`Unknown dataFormat ${I}`);const[G,ne,te,,oe]=l,[ge,fe,Ae]=II(u),[Te,Ve,rt]=II(p),Ct=Pc(G,Te),Ut=Pc(ne,Ve),Kt=Pc(te,rt),{padInfo:Dn,outDepth:An,outHeight:vn,outWidth:Zs}=gJ(g,v,O,C,ge,fe,Ae,Ct,Ut,Kt,S),Si=f?oe*U:oe;let Qs;return I==="channelsFirst"?Qs=[x,Si,An,vn,Zs]:I==="channelsLast"&&(Qs=[x,An,vn,Zs,Si]),{batchSize:x,dataFormat:I,inDepth:v,inHeight:O,inWidth:C,inChannels:U,outDepth:An,outHeight:vn,outWidth:Zs,outChannels:Si,padInfo:Dn,strideDepth:ge,strideHeight:fe,strideWidth:Ae,filterDepth:G,filterHeight:ne,filterWidth:te,effectiveFilterDepth:Ct,effectiveFilterHeight:Ut,effectiveFilterWidth:Kt,dilationDepth:Te,dilationHeight:Ve,dilationWidth:rt,inShape:r,outShape:Qs,filterShape:l}}function yJ(r,l,u,p,g){p==null&&(p=AO(r,l,u));const f=r[0],I=r[1],S=aa((f-l+2*p)/u+1,g);Z(Qt(S),()=>`The output # of rows (${S}) must be an integer. Change the stride and/or zero pad parameters`);const x=aa((I-l+2*p)/u+1,g);return Z(Qt(x),()=>`The output # of columns (${x}) must be an integer. Change the stride and/or zero pad parameters`),[S,x]}function bJ(r,l,u,p,g,f){g==null&&(g=AO(r,l,p));const I=r[0],S=r[1],x=r[2],v=aa((I-l+2*g)/p+1,f);Z(Qt(v),()=>`The output # of depths (${v}) must be an integer. Change the stride and/or zero pad parameters`);const O=aa((S-l+2*g)/p+1,f);Z(Qt(O),()=>`The output # of rows (${O}) must be an integer. Change the stride and/or zero pad parameters`);const C=aa((x-l+2*g)/p+1,f);return Z(Qt(C),()=>`The output # of columns (${C}) must be an integer. Change the stride and/or zero pad parameters`),[v,O,C,u]}function AO(r,l,u,p=1){const g=Pc(l,p);return Math.floor((r[0]*(u-1)-u+g)/2)}function og(r){return typeof r=="number"?[r,r,r]:r.length===2?[r[0],r[1],1]:r}function II(r){return typeof r=="number"?[r,r,r]:r}function Pc(r,l){return l<=1?r:r+(r-1)*(l-1)}function fJ(r,l,u,p,g,f,I,S,x){let v,O,C;if(typeof r=="number"){const U=r===0?"VALID":"NUMBER";v={top:r,bottom:r,left:r,right:r,type:U};const G=yJ([l,u],f,p,r,S);O=G[0],C=G[1]}else if(r==="same"){O=Math.ceil(l/p),C=Math.ceil(u/g);const U=Math.max(0,(O-1)*p+f-l),G=Math.max(0,(C-1)*g+I-u),ne=Math.floor(U/2),te=U-ne,oe=Math.floor(G/2),ge=G-oe;v={top:ne,bottom:te,left:oe,right:ge,type:"SAME"}}else if(r==="valid")v={top:0,bottom:0,left:0,right:0,type:"VALID"},O=Math.ceil((l-f+1)/p),C=Math.ceil((u-I+1)/g);else if(typeof r=="object"){const U=x==="channelsLast"?r[1][0]:r[2][0],G=x==="channelsLast"?r[1][1]:r[2][1],ne=x==="channelsLast"?r[2][0]:r[3][0],te=x==="channelsLast"?r[2][1]:r[3][1],oe=U===0&&G===0&&ne===0&&te===0?"VALID":"EXPLICIT";v={top:U,bottom:G,left:ne,right:te,type:oe},O=aa((l-f+U+G)/p+1,S),C=aa((u-I+ne+te)/g+1,S)}else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:v,outHeight:O,outWidth:C}}function gJ(r,l,u,p,g,f,I,S,x,v,O){let C,U,G,ne;if(typeof r=="number"){const te=r===0?"VALID":"NUMBER";C={top:r,bottom:r,left:r,right:r,front:r,back:r,type:te};const oe=bJ([l,u,p,1],S,1,g,r,O);U=oe[0],G=oe[1],ne=oe[2]}else if(r==="same"){U=Math.ceil(l/g),G=Math.ceil(u/f),ne=Math.ceil(p/I);const te=(U-1)*g+S-l,oe=(G-1)*f+x-u,ge=(ne-1)*I+v-p,fe=Math.floor(te/2),Ae=te-fe,Te=Math.floor(oe/2),Ve=oe-Te,rt=Math.floor(ge/2),Ct=ge-rt;C={top:Te,bottom:Ve,left:rt,right:Ct,front:fe,back:Ae,type:"SAME"}}else if(r==="valid")C={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},U=Math.ceil((l-S+1)/g),G=Math.ceil((u-x+1)/f),ne=Math.ceil((p-v+1)/I);else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:C,outDepth:U,outHeight:G,outWidth:ne}}function aa(r,l){if(!l)return r;switch(l){case"round":return Math.round(r);case"ceil":return Math.ceil(r);case"floor":return Math.floor(r);default:throw new Error(`Unknown roundingMode ${l}`)}}function oo(r){const[l,u,p]=og(r);return l===1&&u===1&&p===1}function ao(r,l){return oo(r)||oo(l)}function zc(r){if(r==="NHWC")return"channelsLast";if(r==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${r}`)}function vO(r,l){const u=r[0].length;r.forEach((g,f)=>{Z(g.length===u,()=>`Error in concat${u}D: rank of tensors[${f}] must be the same as the rank of the rest (${u})`)}),Z(l>=0&&l<u,()=>`Error in concat${u}D: axis must be between 0 and ${u-1}.`);const p=r[0];r.forEach((g,f)=>{for(let I=0;I<u;I++)Z(I===l||g[I]===p[I],()=>`Error in concat${u}D: Shape of tensors[${f}] (${g}) does not match the shape of the rest (${p}) along the non-concatenated axis ${f}.`)})}function NO(r,l){const u=r[0].slice();for(let p=1;p<r.length;p++)u[l]+=r[p][l];return u}function wJ(r,l=0){Z(r.length>=1,()=>"Pass at least one tensor to concat");let u=ig(r,"tensors","concat");u[0].dtype==="complex64"&&u.forEach(I=>{if(I.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
with dtype ${I.dtype}. `)});const p=(I,S)=>{const x=ut(l,u[0].shape)[0],v=NO(u.map(U=>U.shape),x);if(qt(v)===0)return yI([],v);if(u=u.filter(U=>U.size>0),u.length===1)return u[0];const O=u.map(U=>U.shape);vO(O,x);const C=I.concat(u,x);return S(u),C},g=u,f={axis:l};return Y.runKernelFunc(p,g,null,rf,f)}const yn=z({concat_:wJ});function LJ(r){const l=M(r,"x","sigmoid"),u={x:l};return Y.runKernelFunc((p,g)=>{const f=p.sigmoid(l);return g([f]),f},u,null,Uf)}const xI=z({sigmoid_:LJ});function SJ(r,l,u){const p=M(r,"x","slice");if(p.rank===0)throw new Error("Slicing scalar is not possible");const g=(S,x)=>{const[v,O]=rg(p,l,u);return SO(p,v,O),x([p]),S.slice(p,v,O)},f={x:p},I={begin:l,size:u};return Y.runKernelFunc(g,f,null,_f,I)}const vt=z({slice_:SJ});function IJ(r,l,u){const p=M(r,"x","batchToSpaceND"),g=l.reduce((x,v)=>x*v);Z(p.rank>=1+l.length,()=>`input rank is ${p.rank} but should be > than blockShape.length ${l.length}`),Z(u.length===l.length,()=>`crops.length is ${u.length} but should be equal to blockShape.length ${l.length}`),Z(p.shape[0]%g===0,()=>`input tensor batch is ${p.shape[0]} but is not divisible by the product of the elements of blockShape ${l.join(" * ")} === ${g}`);const f=x=>x.batchToSpaceND(p,l,u),I={x:p},S={blockShape:l,crops:u};return Y.runKernelFunc(f,I,null,nf,S)}const TI=z({batchToSpaceND_:IJ});function xJ(r,l){let u=M(r,"broadcastTo","x");const p=u.shape;if(l.some(O=>!(O>0)||O%1!==0))throw new Error(`broadcastTo(): Invalid broadcast shape [${l}].`);if(l.length<u.rank)throw new Error(`broadcastTo(): shape.length=${l.length} < input.rank=${u.rank}.`);if(l.length>u.rank){const O=u.shape.slice();for(;O.length<l.length;)O.unshift(1);u=ie(u,O)}const g=u.shape,f=Array.from(l);for(let O=l.length-1;O>=0;O--)if(g[O]===l[O])f[O]=1;else if(u.shape[O]!==1)throw new Error(`broadcastTo(): [${p}] cannot be broadcast to [${l}].`);const I=f.map((O,C)=>O>1?C:-1).filter(O=>O>=0);if(I.length===0)return gi(u);const S=O=>O.tile(u,f),x={x:u},v={shape:l,inputShape:g};return Y.runKernelFunc(S,x,null,sf,v)}const lg=z({broadcastTo_:xJ});function TJ(r,l,u,p,g="NHWC",f=[1,1],I){const S=M(r,"x","conv2d"),x=M(l,"filter","conv2d");let v=S,O=!1;S.rank===3&&(O=!0,v=ie(S,[1,S.shape[0],S.shape[1],S.shape[2]])),Z(v.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${v.rank}.`),Z(x.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${x.rank}.`),I!=null&&Z(Qt(p),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${I} but got pad ${p}.`);const C=g==="NHWC"?v.shape[3]:v.shape[1];Z(C===x.shape[2],()=>`Error in conv2d: depth of input (${C}) must match input depth for filter ${x.shape[2]}.`),Z(ao(u,f),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${u} and dilations '${f}'`);const U=(oe,ge)=>{const fe=zc(g),Ae=fr(v.shape,x.shape,u,f,p,I,!1,fe),Te=oe.conv2d(v,x,Ae);return ge([v,x]),Te},G={x:v,filter:x},ne={strides:u,pad:p,dataFormat:g,dilations:f,dimRoundingMode:I},te=Y.runKernelFunc(U,G,null,of,ne);return O?ie(te,[te.shape[1],te.shape[2],te.shape[3]]):te}const AI=z({conv2d_:TJ});function AJ(r,l,u,p,g,f="NHWC",I){Z(r.length===l.rank,()=>`Length of inShape (${r.length}) and rank of dy (${l.rank}) must match`);let S=r,x=l,v=!1;l.rank===3&&(v=!0,x=ie(l,[1,l.shape[0],l.shape[1],l.shape[2]]),S=[1,r[0],r[1],r[2]]),Z(S.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${S.length}.`),Z(x.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${x.rank}`),Z(u.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${u.rank}`);const O=f==="NHWC"?S[3]:S[1],C=f==="NHWC"?x.shape[3]:x.shape[1];Z(O===u.shape[2],()=>`Error in conv2dDerInput: depth of input (${O}) must match input depth for filter ${u.shape[2]}.`),Z(C===u.shape[3],()=>`Error in conv2dDerInput: depth of output (${C}) must match output depth for filter ${u.shape[3]}.`),I!=null&&Z(Qt(g),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${I} but got pad ${g}.`);const U=(oe,ge)=>{const fe=1,Ae=zc(f),Te=fr(S,u.shape,p,fe,g,I,!1,Ae),Ve=oe.conv2dDerInput(x,u,Te);return ge([x,u]),Ve},G={dy:x,filter:u},ne={strides:p,pad:g,dataFormat:f,dimRoundingMode:I,inputShape:S},te=Y.runKernelFunc(U,G,null,af,ne);return v?ie(te,[te.shape[1],te.shape[2],te.shape[3]]):te}const CO=z({conv2DBackpropInput_:AJ});function vJ(r,l,u,p,g){Z(r.length===l.rank,()=>`Length of inShape (${r.length}) and rank of dy (${l.rank}) must match`);let f=r,I=l,S=!1;l.rank===4&&(S=!0,I=ie(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),f=[1,r[0],r[1],r[2],r[3]]);const x=f[4],v=I.shape[4];Z(f.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${f.length}.`),Z(I.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${I.rank}`),Z(u.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${u.rank}`),Z(x===u.shape[3],()=>`Error in conv3dDerInput: depth of input (${x}) must match input depth for filter ${u.shape[3]}.`),Z(v===u.shape[4],()=>`Error in conv3dDerInput: depth of output (${v}) must match output depth for filter ${u.shape[4]}.`);const O=ne=>{const te=1,oe=Ru(f,u.shape,p,te,g);return ne.conv3dDerInput(I,u,oe)},C={dy:I},U={pad:g},G=Y.runKernelFunc(O,C,null,V2,U);return S?ie(G,[G.shape[1],G.shape[2],G.shape[3],G.shape[4]]):G}const RO=z({conv3DBackpropInput_:vJ});function NJ(r){const l=M(r,"x","cos"),u={x:l};return Y.runKernelFunc((p,g)=>{const f=p.cos(l);return g([l]),f},u,null,cf)}const Ou=z({cos_:NJ});function CJ(r){const l=M(r,"x","cosh"),u={x:l};return Y.runKernelFunc((p,g)=>{const f=p.cosh(l);return g([l]),f},u,null,lf)}const vI=z({cosh_:CJ});function RJ(r,l=0,u=!1,p=!1){const g=M(r,"x","cumsum"),f=(x,v)=>{const O=ds([l],g.rank);let C=g;O!=null&&(C=$t(g,O));const U=ro(1,g.rank)[0];let G=x.cumsum(C,U,u,p);if(v([g]),O!=null){const ne=Mc(O);G=$t(G,ne)}return G},I={x:g},S={axis:l,exclusive:u,reverse:p};return Y.runKernelFunc(f,I,null,hf,S)}const NI=z({cumsum_:RJ});function Nt(r,l){const u=[];for(let p=0;p<l.length;p++){const g=r[r.length-p-1],f=l.length-p-1,I=l[f];(g==null||g===1&&I>1)&&u.unshift(f)}return u}function it(r,l){const u=[],p=Math.max(r.length,l.length);for(let g=0;g<p;g++){let f=r[r.length-g-1];f==null&&(f=1);let I=l[l.length-g-1];if(I==null&&(I=1),f===1)u.unshift(I);else if(I===1)u.unshift(f);else if(f!==I){const S=`Operands could not be broadcast together with shapes ${r} and ${l}.`;throw Error(S)}else u.unshift(f)}return u}function OJ(r,l){let u=M(r,"a","equal"),p=M(l,"b","equal");[u,p]=ft(u,p),it(u.shape,p.shape);const g=I=>I.equal(u,p),f={a:u,b:p};return Y.runKernelFunc(g,f,null,tR)}const CI=z({equal_:OJ});function EJ(r,l,u){const p=M(l,"a","where"),g=M(u,"b","where"),f=M(r,"condition","where","bool"),I=it(p.shape,g.shape),S=lg(p,I),x=lg(g,I);f.rank===1&&Z(f.shape[0]===p.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),f.rank!==1&&Zt(f.shape,x.shape,"Error in where: ");const v=(C,U)=>{const G=C.select(f,S,x);return U([f]),G},O={condition:f,t:S,e:x};return Y.runKernelFunc(v,O,null,Ff)}const Mn=z({where_:EJ});function DJ(r){const l=M(r,"x","zerosLike"),u={x:l};return Y.runKernelFunc(p=>p.zerosLike(l),u,null,Kf)}const je=z({zerosLike_:DJ});function kJ(r){const l=M(r,"x","exp"),u={x:l};return Y.runKernelFunc((p,g)=>{const f=p.exp(l);return g([f]),f},u,null,df)}const Pn=z({exp_:kJ});function FJ(r,l=0){const u=null,p=M(r,"x","expandDims",u);Z(l<=p.rank,()=>"Axis must be <= rank of the tensor");const g=p.shape.slice();return l<0&&(Z(-(p.rank+1)<=l,()=>`Axis must be in the interval [${-(p.rank+1)}, ${p.rank}]`),l=p.rank+l+1),g.splice(l,0,1),ie(p,g)}const Es=z({expandDims_:FJ});function _J(r,l){const u=null,p=M(r,"x","tile",u);Z(p.rank===l.length,()=>`Error in transpose: rank of input ${p.rank} must match length of reps ${l}.`);const g=(x,v)=>{const O=x.tile(p,l);return v([p]),O},f=[p],I={x:p},S={reps:l};return Y.runKernelFunc(g,I,null,Yf,S,f)}const ca=z({tile_:_J});function WJ(r,l,u,p="float32"){l==null&&(l=r);const g=Cu([r,l],p),f=r<=l?r:l;for(let S=0;S<f;++S)g.set(1,S,S);const I=ie(g.toTensor(),[r,l]);if(u==null)return I;if(u.length===1)return ca(Es(I,0),[u[0],1,1]);if(u.length===2)return ca(Es(Es(I,0),0),[u[0],u[1],1,1]);if(u.length===3)return ca(Es(Es(Es(I,0),0),0),[u[0],u[1],u[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${u.length}D.`)}const RI=z({eye_:WJ});function OI(r,l,u){const p={shape:r,value:l,dtype:u};return Y.runKernelFunc(g=>g.fill(r,l,u),{},null,iR,p)}function $J(r){const l=M(r,"x","floor"),u={x:l};return Y.runKernelFunc(p=>p.floor(l),u,null,pf)}const EI=z({floor_:$J});function OO(r,l,u){const p=r.shape[u],g=[];let f=1,I=1;for(let S=0;S<u;S++)g.push(r.shape[S]),f*=r.shape[S];for(let S=0;S<l.rank;S++)g.push(l.shape[S]);for(let S=u+1;S<r.rank;S++)g.push(r.shape[S]),I*=r.shape[S];return{batchSize:f,sliceSize:I,dimSize:p,outputShape:g}}function UJ(r,l,u=0){const p=M(r,"x","gather"),g=M(l,"indices","gather","int32"),f={x:p,indices:g},I={axis:u},S=(x,v)=>{const O=ut(u,p.shape)[0],C=OO(p,g,O),U=x.gather(p,ie(g,[g.size]),O);return v([p,g]),ie(U,C.outputShape)};return Y.runKernelFunc(S,f,null,ff,I)}const DI=z({gather_:UJ});function BJ(r,l){let u=M(r,"a","greater"),p=M(l,"b","greater");[u,p]=ft(u,p),it(u.shape,p.shape);const g=I=>I.greater(u,p),f={a:u,b:p};return Y.runKernelFunc(g,f,null,aR)}const yi=z({greater_:BJ});function MJ(r,l){let u=M(r,"a","greaterEqual"),p=M(l,"b","greaterEqual");[u,p]=ft(u,p),it(u.shape,p.shape);const g=(I,S)=>{const x=I.greaterEqual(u,p);return S([u,p]),x},f={a:u,b:p};return Y.runKernelFunc(g,f,null,gf)}const gr=z({greaterEqual_:MJ});function PJ(r){const l=M(r,"input","imag"),u=g=>g.imag(l),p={input:l};return Y.runKernelFunc(u,p,null,lR)}const Eu=z({imag_:PJ});function zJ(r,l){let u=M(r,"a","maximum"),p=M(l,"b","maximum");[u,p]=ft(u,p),u.dtype==="bool"&&(u=Le(u,"int32"),p=Le(p,"int32")),it(u.shape,p.shape);const g=(I,S)=>{const x=I.maximum(u,p);return S([u,p]),x},f={a:u,b:p};return Y.runKernelFunc(g,f,null,Sf)}const kI=z({maximum_:zJ});function ke(r,l){if((Os(r)&&l!=="string"||Array.isArray(r))&&l!=="complex64")throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if(l==="string"&&Os(r)&&!(r instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");const u=[],p=[];return Vi(r,u,p,l)}function GJ(r,l){let u=M(r,"a","less"),p=M(l,"b","less");[u,p]=ft(u,p),it(u.shape,p.shape);const g=I=>I.less(u,p),f={a:u,b:p};return Y.runKernelFunc(g,f,null,pR)}const FI=z({less_:GJ});function VJ(r,l){let u=M(r,"a","lessEqual"),p=M(l,"b","lessEqual");[u,p]=ft(u,p),it(u.shape,p.shape);const g=(I,S)=>{const x=I.lessEqual(u,p);return S([u,p]),x},f={a:u,b:p};return Y.runKernelFunc(g,f,null,mR)}const yr=z({lessEqual_:VJ});function YJ(r){const l=M(r,"x","log"),u={x:l};return Y.runKernelFunc((p,g)=>{const f=p.log(l);return g([l]),f},u,null,bf)}const co=z({log_:YJ});function HJ(r){const l=M(r,"x","log1p"),u={x:l};return Y.runKernelFunc((p,g)=>{const f=p.log1p(l);return g([l]),f},u,null,wf)}const _I=z({log1p_:HJ});function hg(r){return Y.customGrad(r)}function qJ(r){const l=M(r,"x","neg"),u={x:l};return Y.runKernelFunc(p=>p.neg(l),u,null,Af)}const yt=z({neg_:qJ});function jJ(r,l=null,u=!1){const p=M(r,"x","max"),g=(S,x)=>{const v=ut(l,p.shape);let O=v;const C=ds(O,p.rank);let U=p;C!=null&&(U=$t(p,C),O=ro(O.length,U.rank));const G=S.max(U,O);C!=null&&U.dispose();let ne=G;if(u){const te=Qn(ne.shape,ut(l,p.shape));ne=ie(ne,te),G.dispose()}return x([p,ne]),ne},f={x:p},I={reductionIndices:l,keepDims:u};return Y.runKernelFunc(g,f,null,Lf,I)}const la=z({max_:jJ});function KJ(r,l){let u=M(r,"a","sub"),p=M(l,"b","sub");[u,p]=ft(u,p);const g=(I,S)=>{const x=I.subtract(u,p);return S([u,p]),x},f={a:u,b:p};return Y.runKernelFunc(g,f,null,Vf)}const Be=z({sub_:KJ});function XJ(r,l=null,u=!1){let p=M(r,"x","sum");p.dtype==="bool"&&(p=Le(p,"int32"));const g=(S,x)=>{x([p]);const v=ut(l,p.shape),O=ds(v,p.rank);let C=v,U=p;O!=null&&(U=$t(p,O),C=ro(C.length,p.rank));let G=S.sum(U,C);if(u){const ne=Qn(G.shape,v);G=ie(G,ne)}return G},f={x:p},I={axis:l,keepDims:u};return Y.runKernelFunc(g,f,null,Mf,I)}const Fe=z({sum_:XJ});function JJ(r,l=null,u=!1){const p=M(r,"x","logSumExp"),g=ut(l,p.shape),f=la(p,g,!0),I=Be(p,f),S=Pn(I),x=Fe(S,g),v=co(x),O=Lt(ie(f,v.shape),v);if(u){const C=Qn(O.shape,g);return ie(O,C)}return O}const WI=z({logSumExp_:JJ});function ZJ(r,l){const u=M(r,"a","logicalAnd","bool"),p=M(l,"b","logicalAnd","bool");it(u.shape,p.shape);const g={a:u,b:p};return Y.runKernelFunc(f=>f.logicalAnd(u,p),g,null,fR)}const ha=z({logicalAnd_:ZJ});function QJ(r){const l=M(r,"x","logicalNot","bool"),u={x:l};return Y.runKernelFunc(p=>p.logicalNot(l),u,null,gR)}const $I=z({logicalNot_:QJ});function Ds(r,l="float32"){if(l==="complex64"){const p=Ds(r,"float32"),g=Ds(r,"float32");return Gi(p,g)}const u=oa(qt(r),l);return Y.makeTensor(u,r,l)}function Yi(r,l="float32"){if(l==="complex64"){const p=Yi(r,"float32"),g=Ds(r,"float32");return Gi(p,g)}const u=Qf(qt(r),l);return Y.makeTensor(u,r,l)}function e9(r,l=null,u=!1){const p=M(r,"x","mean"),g=ut(l,p.shape),f=TO(p.shape,g),I=f[1],S=qt(I),x=hg(v=>{const O=ke(S),C=O.dtype===v.dtype?v:Le(v,O.dtype),U=Pe(C,O),G=Fe(U,l,u),ne=te=>{const oe=v.shape.slice();g.forEach(Ae=>{oe[Ae]=1});const ge=ie(te,oe),fe=Pe(ae(ge,Yi(v.shape,"float32")),S);return fe};return{value:G,gradFunc:ne}});return x(p)}const UI=z({mean_:e9});function t9(r,l=null,u=!1){const p=M(r,"x","min"),g=(S,x)=>{const v=ut(l,p.shape);let O=v;const C=ds(O,p.rank);let U=p;C!=null&&(U=$t(p,C),O=ro(O.length,p.rank));const G=S.min(U,O);C!=null&&U.dispose();let ne=G;if(u){const te=Qn(ne.shape,v);ne=ie(G,te),G.dispose()}return x([p,ne]),ne},f={x:p},I={axis:l,keepDims:u};return Y.runKernelFunc(g,f,null,If,I)}const ug=z({min_:t9});function n9(r,l){let u=M(r,"a","minimum"),p=M(l,"b","minimum");[u,p]=ft(u,p),u.dtype==="bool"&&(u=Le(u,"int32"),p=Le(p,"int32")),it(u.shape,p.shape);const g=(I,S)=>{const x=I.minimum(u,p);return S([u,p]),x},f={a:u,b:p};return Y.runKernelFunc(g,f,null,xf)}const BI=z({minimum_:n9});function s9(r){const l=M(r,"x","square"),u={},p=[l],g=[];return Y.runKernelFunc((f,I)=>(I([l]),f.square(l)),{x:l},null,"Square",u,p,g)}const dt=z({square_:s9});function i9(r,l){let u=M(r,"a","notEqual"),p=M(l,"b","notEqual");[u,p]=ft(u,p),it(u.shape,p.shape);const g=I=>I.notEqual(u,p),f={a:u,b:p};return Y.runKernelFunc(g,f,null,AR)}const MI=z({notEqual_:i9});function r9(r){const l=M(r,"input","real"),u=g=>g.real(l),p={input:l};return Y.runKernelFunc(u,p,null,kR)}const Gc=z({real_:r9});function o9(r,l,u=0){const p=M(r,"x","pad");if(p.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const g=(S,x)=>(x([p]),S.pad(p,l,u)),f={paddings:l,constantValue:u},I={x:p};return Y.runKernelFunc(g,I,null,vf,f)}const PI=z({pad_:o9});function a9(r,l,u){const p=M(r,"x","spaceToBatchND");Z(p.rank>=1+l.length,()=>`input rank ${p.rank} should be > than [blockShape] ${l.length}`),Z(u.length===l.length,()=>`paddings.shape[0] ${u.length} must be equal to [blockShape] ${l.length}`),Z(p.shape.reduce((S,x,v)=>v>0&&v<=l.length?S&&(x+u[v-1][0]+u[v-1][1])%l[v-1]===0:S,!0),()=>`input spatial dimensions ${p.shape.slice(1)} with paddings ${u.toString()} must be divisible by blockShapes ${l.toString()}`);const g=S=>S.spaceToBatchND(p,l,u),f={x:p},I={blockShape:l,paddings:u};return Y.runKernelFunc(g,f,null,Pf,I)}const zI=z({spaceToBatchND_:a9});function c9(r,l){let u=M(r,"base","pow"),p=M(l,"exp","pow");[u,p]=ft(u,p);const g={a:u,b:p},f=(I,S)=>{const x=I.pow(u,p);return S([u,p,x]),x};return Y.runKernelFunc(f,g,null,Nf)}const ua=z({pow_:c9});function lo(r,l){_c(r);const u=mr(r,l);if(u.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");const p=null;return Vi(r,p,u,l)}function dg(r,l,u=1,p="float32"){if(u===0)throw new Error("Cannot have a step of zero");const g=()=>{const I=r===l,S=r<l&&u<0,x=l<r&&u>1;if(I||S||x)return Ds([0],p);const v=Math.abs(Math.ceil((l-r)/u)),O=oa(v,p);l<r&&u===1&&(u=-1),O[0]=r;for(let C=1;C<O.length;C++)O[C]=O[C-1]+u;return lo(O,p)},f={start:r,stop:l,step:u,dtype:p};return Y.runKernelFunc(g,{},null,DR,f)}function l9(r){const l=M(r,"x","relu"),u=(g,f)=>(f([l]),l.dtype==="bool"?Le(l,"int32"):g.relu(l)),p={x:l};return Y.runKernelFunc(u,p,null,Cf)}const Du=z({relu_:l9});function h9(r,l){const u=M(r,"x","reverse"),p=I=>{const S=ut(l,u.shape);if(u.rank===0)return gi(u);const x=I.reverse(u,S);return ie(x,u.shape)},g={x:u},f={dims:l};return Y.runKernelFunc(p,g,null,Df,f)}const Vc=z({reverse_:h9});function u9(r){const l=M(r,"x","rsqrt"),u={x:l};return Y.runKernelFunc((p,g)=>{const f=p.rsqrt(l);return g([l]),f},u,null,kf)}const GI=z({rsqrt_:u9});function d9(r){const l=M(r,"x","sin"),u={x:l};return Y.runKernelFunc((p,g)=>{const f=p.sin(l);return g([l]),f},u,null,Wf)}const VI=z({sin_:d9});function p9(r){const l=M(r,"x","sinh"),u={x:l};return Y.runKernelFunc((p,g)=>{const f=p.sinh(l);return g([l]),f},u,null,$f)}const YI=z({sinh_:p9});function m9(r){Z(r.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${r.dtype}.`);const l={input:r};return Y.runKernelFunc(u=>{const p=r.shape[r.shape.length-1],g=r.size/p,f=r.as2D(g,p),I=u.fft(f);return I.reshape(r.shape)},l,null,sR)}const ku=z({fft_:m9});function f9(r){Z(r.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${r.dtype}.`);const l={input:r};return Y.runKernelFunc(u=>{const p=r.shape[r.shape.length-1],g=r.size/p,f=ie(r,[g,p]),I=u.ifft(f);return ie(I,r.shape)},l,null,cR)}const Yc=z({ifft_:f9});function g9(r){const l=r.shape[r.shape.length-1],u=r.size/l;let p;if(l<=2){const g=ie(r,[u,l]);p=Yc(g)}else{const g=[u,2*(l-1)],f=ie(Gc(r),[u,l]),I=ie(Eu(r),[u,l]),S=Vc(vt(f,[0,1],[u,l-2]),1),x=ae(Vc(vt(I,[0,1],[u,l-2]),1),ke(-1)),v=yn([f,S],1),O=yn([I,x],1),C=ie(Gi(v,O),[g[0],g[1]]);p=Yc(C)}if(p=Gc(p),r.rank===3&&r.shape[0]!==0){const g=p,f=r.shape[0];p=ie(p,[f,p.shape[0]/f,p.shape[1]]),g.dispose()}return p}const HI=z({irfft_:g9});function EO(r,l,u=0){let p=[];if(typeof l=="number")Z(r.shape[u]%l===0,()=>"Number of splits must evenly divide the axis."),p=new Array(l).fill(r.shape[u]/l);else{const g=l.reduce((I,S)=>(S===-1&&(I+=1),I),0);Z(g<=1,()=>"There should be only one negative value in split array.");const f=l.indexOf(-1);if(f!==-1){const I=l.reduce((S,x)=>x>0?S+x:S);l[f]=r.shape[u]-I}Z(r.shape[u]===l.reduce((I,S)=>I+S),()=>"The sum of sizes must match the size of the axis dimension."),p=l}return p}function y9(r,l,u=0){const p=M(r,"x","split"),g=(S,x)=>{const v=ut(u,p.shape)[0],O=EO(p,l,v);return S.split(p,O,v)},f={x:p},I={numOrSizeSplits:l,axis:u};return Y.runKernelFunc(g,f,null,zf,I)}const ho=z({split_:y9});function b9(r,l){Z(r.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${r.dtype}`);let u=r.shape[r.shape.length-1];const p=r.size/u;let g;if(l!=null&&l<u){const ne=r.shape.map(oe=>0),te=r.shape.map(oe=>oe);te[r.shape.length-1]=l,g=vt(r,ne,te),u=l}else if(l!=null&&l>u){const ne=r.shape.map(te=>te);ne[r.shape.length-1]=l-u,g=yn([r,Ds(ne)],r.shape.length-1),u=l}else g=r;const f=je(g),I=ie(Gi(g,f),[p,u]),S=ku(I),x=Math.floor(u/2)+1,v=Gc(S),O=Eu(S),C=ho(v,[x,u-x],v.shape.length-1),U=ho(O,[x,u-x],O.shape.length-1),G=g.shape.slice();return G[g.shape.length-1]=x,ie(Gi(C[0],U[0]),G)}const Fu=z({rfft_:b9});function w9(r){const l=M(r,"x","sqrt"),u={x:l};return Y.runKernelFunc((p,g)=>{const f=p.sqrt(l);return g([l]),f},u,null,Bf)}const ps=z({sqrt_:w9});function L9(r,l){let u=M(r,"a","squaredDifference"),p=M(l,"b","squaredDifference");[u,p]=ft(u,p),it(u.shape,p.shape);const g=(S,x)=>{const v=S.squaredDifference(u,p);return x([u,p]),v},f={a:u,b:p},I={};return Y.runKernelFunc(g,f,null,Gf,I)}const qI=z({squaredDifference_:L9});function S9(r,l){const u=M(r,"x","squeeze");return ie(u,XR(u.shape,l).newShape)}const jI=z({squeeze_:S9});function I9(r,l=0){const u=ig(r,"tensors","stack");if(Z(u.length>=1,()=>"Pass at least one tensor to tf.stack"),u.length===1)return Es(u[0],l);const p=u[0].rank,g=u[0].shape,f=u[0].dtype;Z(l<=p,()=>"Axis must be <= rank of the tensor"),u.forEach(S=>{Zt(g,S.shape,"All tensors passed to stack must have matching shapes"),Z(f===S.dtype,()=>"All tensors passed to stack must have matching dtypes")});const I=u.map(S=>Es(S,l));return yn(I,l)}const qs=z({stack_:I9});function x9(r,l=0){const u=M(r,"x","step"),p={x:u},g={alpha:l};return Y.runKernelFunc(f=>f.step(u,l),p,null,Xf,g)}const da=z({step_:x9});function pa(r,l,u){if(_c(r),l!=null&&l.length!==2)throw new Error("tensor2d() requires shape to have two numbers");const p=mr(r,u);if(p.length!==2&&p.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(p.length===1&&l==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Vi(r,l,p,u)}function T9(r,l,u){const p=M(r,"x","unsortedSegmentSum"),g=M(l,"segmentIds","unsortedSegmentSum","int32");Z(Qt(u),()=>"numSegments must be of dtype int");const f={x:p,segmentIds:g},I={numSegments:u},S=(x,v)=>{const O=x.unsortedSegmentSum(p,g,u);return v([g]),O};return Y.runKernelFunc(S,f,null,jf,I)}const KI=z({unsortedSegmentSum_:T9});function A9(r,l=0){const u=M(r,"x","unstack");Z(l>=-u.shape.length&&l<u.shape.length,()=>`Axis = ${l} is not in [-${u.shape.length}, ${u.shape.length})`),l<0&&(l+=u.shape.length);const p={value:u},g={axis:l},f=I=>I.unstack(u,l);return Y.runKernelFunc(f,p,null,qf,g)}const _u=z({unstack_:A9});function v9(r,l="euclidean",u=null,p=!1){r=M(r,"x","norm");const g=DO(r,l,u);let f=g.shape;if(p){const I=ut(u,r.shape);f=Qn(g.shape,I)}return ie(g,f)}function DO(r,l,u=null){if(r.rank===0)return Bn(r);if(r.rank!==1&&u===null)return DO(ie(r,[-1]),l,u);if(r.rank===1||typeof u=="number"||Array.isArray(u)&&u.length===1){if(l===1)return Fe(Bn(r),u);if(l===Infinity)return la(Bn(r),u);if(l===-Infinity)return ug(Bn(r),u);if(l==="euclidean"||l===2)return ps(Fe(ua(Bn(r),ke(2,"int32")),u));throw new Error(`Error in norm: invalid ord value: ${l}`)}if(Array.isArray(u)&&u.length===2){if(l===1)return la(Fe(Bn(r),u[0]),u[1]-1);if(l===Infinity)return la(Fe(Bn(r),u[1]),u[0]);if(l===-Infinity)return ug(Fe(Bn(r),u[1]),u[0]);if(l==="fro"||l==="euclidean")return ps(Fe(dt(r),u));throw new Error(`Error in norm: invalid ord value: ${l}`)}throw new Error(`Error in norm: invalid axis: ${u}`)}const pg=z({norm_:v9});function kO(r){return Math.floor(Math.pow(2,Math.ceil(Math.log(r)/Math.log(2))))}function mg(r,l,u){const p=1-r%2,g=new Float32Array(r);for(let f=0;f<r;++f){const I=2*Math.PI*f/(r+p-1);g[f]=l-u*Math.cos(I)}return lo(g,"float32")}function N9(r,l,u,p,g,f="NHWC",I){let S=r;r.rank===3&&(S=ie(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let x=l;x.rank===3&&(x=ie(l,[1,l.shape[0],l.shape[1],l.shape[2]])),Z(S.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${S.shape}.`),Z(x.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${x.shape}.`),Z(u.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${u}.`);const v=f==="NHWC"?S.shape[3]:S.shape[1],O=f==="NHWC"?x.shape[3]:x.shape[1];Z(v===u[2],()=>`Error in conv2dDerFilter: depth of input ${v}) must match input depth in filter (${u[2]}.`),Z(O===u[3],()=>`Error in conv2dDerFilter: depth of dy (${O}) must match output depth for filter (${u[3]}).`),I!=null&&Z(Qt(g),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${I} but got pad ${g}.`);const C=ne=>{const te=1,oe=zc(f),ge=fr(S.shape,u,p,te,g,I,!1,oe);return ne.conv2dDerFilter(S,x,ge)},U={x:S,dy:x},G={strides:p,pad:g,dataFormat:f,dimRoundingMode:I};return Y.runKernelFunc(C,U,null,P2,G)}const fg=z({conv2DBackpropFilter_:N9});function C9(r,l,u,p){let g=r;r.rank===3&&(g=ie(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let f=l;f.rank===3&&(f=ie(l,[1,l.shape[0],l.shape[1],l.shape[2]]));const I=x=>x.depthwiseConv2DDerFilter(g,f,p),S={x:g,dy:f};return Y.runKernelFunc(I,S,null,q2)}const FO=z({depthwiseConv2dNativeBackpropFilter_:C9});function R9(r,l,u,p){let g=l,f=!1;l.rank===3&&(f=!0,g=ie(l,[1,l.shape[0],l.shape[1],l.shape[2]]));const I=v=>v.depthwiseConv2DDerInput(g,u,p),S={dy:g},x=Y.runKernelFunc(I,S,null,j2);return f?ie(x,[x.shape[1],x.shape[2],x.shape[3]]):x}const _O=z({depthwiseConv2dNativeBackpropInput_:R9});function O9(r){return mg(r,.54,.46)}const WO=z({hammingWindow_:O9});function E9(r){return mg(r,.5,.5)}const gg=z({hannWindow_:E9});function D9(r,l,u,p=!1,g=0){let f=0;const I=[];for(;f+l<=r.size;)I.push(vt(r,f,l)),f+=u;if(p)for(;f<r.size;){const S=f+l-r.size,x=yn([vt(r,f,l-S),OI([S],g)]);I.push(x),f+=u}return I.length===0?pa([],[0,l]):ie(yn(I),[I.length,l])}const yg=z({frame_:D9});function k9(r,l,u,p,g=gg){p==null&&(p=kO(l));const f=yg(r,l,u),I=ae(f,g(l)),S=[];for(let x=0;x<f.shape[0];x++)S.push(Fu(vt(I,[x,0],[1,l]),p));return yn(S)}const $O=z({stft_:k9});function F9(r,l,u,p,g,f){const I=M(r,"image","cropAndResize"),S=M(l,"boxes","cropAndResize","float32"),x=M(u,"boxInd","cropAndResize","int32");g=g||"bilinear",f=f||0;const v=S.shape[0];Z(I.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${I.rank}.`),Z(S.rank===2&&S.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${v},4] but had shape ${S.shape}.`),Z(x.rank===1&&x.shape[0]===v,()=>`Error in cropAndResize: boxInd must be have size [${v}] but had shape ${S.shape}.`),Z(p.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${p.length}.`),Z(p[0]>=1&&p[1]>=1,()=>`cropSize must be atleast [1,1], but was ${p}`),Z(g==="bilinear"||g==="nearest",()=>`method must be bilinear or nearest, but was ${g}`);const O=ne=>ne.cropAndResize(I,S,x,p,g,f),C={image:I,boxes:S,boxInd:x},U={method:g,extrapolationValue:f,cropSize:p},G=Y.runKernelFunc(O,C,null,Y2,U);return G}const UO=z({cropAndResize_:F9});function _9(r){const l=M(r,"image","flipLeftRight","float32");Z(l.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${l.rank}.`);const u={image:l},p=Y.runKernel(rR,u,{});return p}const BO=z({flipLeftRight_:_9});function W9(r,l,u=0,p=.5){const g=M(r,"image","rotateWithOffset","float32");Z(g.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${g.rank}.`);const f={image:g},I={radians:l,fillValue:u,center:p},S=Y.runKernel(HR,f,I);return S}const MO=z({rotateWithOffset_:W9});function js(r,l,u,p,g,f){p==null&&(p=.5),g==null&&(g=Number.NEGATIVE_INFINITY),f==null&&(f=0);const I=r.shape[0];return u=Math.min(u,I),Z(0<=p&&p<=1,()=>`iouThreshold must be in [0, 1], but was '${p}'`),Z(r.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${r.rank}'`),Z(r.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${r.shape[1]}`),Z(l.rank===1,()=>"scores must be a 1D tensor"),Z(l.shape[0]===I,()=>`scores has incompatible shape with boxes. Expected ${I}, but was ${l.shape[0]}`),Z(0<=f&&f<=1,()=>`softNmsSigma must be in [0, 1], but was '${f}'`),{maxOutputSize:u,iouThreshold:p,scoreThreshold:g,softNmsSigma:f}}function $9(r,l,u,p=.5,g=Number.NEGATIVE_INFINITY){const f=M(r,"boxes","nonMaxSuppression"),I=M(l,"scores","nonMaxSuppression"),S=js(f,I,u,p,g);u=S.maxOutputSize,p=S.iouThreshold,g=S.scoreThreshold;const x={maxOutputSize:u,iouThreshold:p,scoreThreshold:g};return Y.runKernelFunc(v=>v.nonMaxSuppression(f,I,u,p,g),{boxes:f,scores:I},null,vR,x)}const PO=z({nonMaxSuppression_:$9});function zO(r,l,u){const p=U9(r,l,u),g=p<0?-(p+1):p;r.splice(g,0,l)}function U9(r,l,u){return M9(r,l,u||B9)}function B9(r,l){return r>l?1:r<l?-1:0}function M9(r,l,u){let p=0,g=r.length,f=0,I=!1;for(;p<g;){f=p+(g-p>>>1);const S=u(l,r[f]);S>0?p=f+1:(g=f,I=!S)}return I?p:-p-1}function GO(r,l,u,p,g){return XI(r,l,u,p,g,0).selectedIndices}function VO(r,l,u,p,g,f){return XI(r,l,u,p,g,0,!1,f,!0)}function YO(r,l,u,p,g,f){return XI(r,l,u,p,g,f,!0)}function XI(r,l,u,p,g,f,I=!1,S=!1,x=!1){const v=[];for(let oe=0;oe<l.length;oe++)l[oe]>g&&v.push({score:l[oe],boxIndex:oe,suppressBeginIndex:0});v.sort(HO);const O=f>0?-.5/f:0,C=[],U=[];for(;C.length<u&&v.length>0;){const oe=v.pop(),{score:ge,boxIndex:fe,suppressBeginIndex:Ae}=oe;if(ge<g)break;let Te=!1;for(let Ve=C.length-1;Ve>=Ae;--Ve){const rt=P9(r,fe,C[Ve]);if(rt>=p){Te=!0;break}if(oe.score=oe.score*z9(p,O,rt),oe.score<=g)break}oe.suppressBeginIndex=C.length,Te||(oe.score===ge?(C.push(fe),U.push(oe.score)):oe.score>g&&zO(v,oe,HO))}const G=C.length,ne=u-G;S&&ne>0&&(C.push(...new Array(ne).fill(0)),U.push(...new Array(ne).fill(0)));const te={selectedIndices:lo(C,"int32")};return I&&(te.selectedScores=lo(U,"float32")),x&&(te.validOutputs=ke(G,"int32")),te}function P9(r,l,u){const p=r.subarray(l*4,l*4+4),g=r.subarray(u*4,u*4+4),f=Math.min(p[0],p[2]),I=Math.min(p[1],p[3]),S=Math.max(p[0],p[2]),x=Math.max(p[1],p[3]),v=Math.min(g[0],g[2]),O=Math.min(g[1],g[3]),C=Math.max(g[0],g[2]),U=Math.max(g[1],g[3]),G=(S-f)*(x-I),ne=(C-v)*(U-O);if(G<=0||ne<=0)return 0;const te=Math.max(f,v),oe=Math.max(I,O),ge=Math.min(S,C),fe=Math.min(x,U),Ae=Math.max(ge-te,0)*Math.max(fe-oe,0);return Ae/(G+ne-Ae)}function z9(r,l,u){const p=Math.exp(l*u*u);return u<=r?p:0}function HO(r,l){return r.score-l.score||r.score===l.score&&l.boxIndex-r.boxIndex}async function G9(r,l,u,p=.5,g=Number.NEGATIVE_INFINITY){const f=M(r,"boxes","nonMaxSuppressionAsync"),I=M(l,"scores","nonMaxSuppressionAsync"),S=js(f,I,u,p,g);u=S.maxOutputSize,p=S.iouThreshold,g=S.scoreThreshold;const x=await Promise.all([f.data(),I.data()]),v=x[0],O=x[1],C=GO(v,O,u,p,g);return f!==r&&f.dispose(),I!==l&&I.dispose(),C}const qO=G9;function V9(r,l,u,p=.5,g=Number.NEGATIVE_INFINITY,f=0){const I=M(r,"boxes","nonMaxSuppression"),S=M(l,"scores","nonMaxSuppression"),x=js(I,S,u,p,g,f);u=x.maxOutputSize,p=x.iouThreshold,g=x.scoreThreshold,f=x.softNmsSigma;const v={boxes:I,scores:S},O={maxOutputSize:u,iouThreshold:p,scoreThreshold:g,softNmsSigma:f},C=Y.runKernel(CR,v,O);return{selectedIndices:C[0],selectedScores:C[1]}}const jO=z({nonMaxSuppressionWithScore_:V9});async function Y9(r,l,u,p=.5,g=Number.NEGATIVE_INFINITY,f=0){const I=M(r,"boxes","nonMaxSuppressionAsync"),S=M(l,"scores","nonMaxSuppressionAsync"),x=js(I,S,u,p,g,f);u=x.maxOutputSize,p=x.iouThreshold,g=x.scoreThreshold,f=x.softNmsSigma;const v=await Promise.all([I.data(),S.data()]),O=v[0],C=v[1],U=YO(O,C,u,p,g,f);return I!==r&&I.dispose(),S!==l&&S.dispose(),U}const KO=Y9;function H9(r,l,u,p=.5,g=Number.NEGATIVE_INFINITY,f=!1){const I=M(r,"boxes","nonMaxSuppression"),S=M(l,"scores","nonMaxSuppression"),x=js(I,S,u,p,g,null),v=x.maxOutputSize,O=x.iouThreshold,C=x.scoreThreshold,U={boxes:I,scores:S},G={maxOutputSize:v,iouThreshold:O,scoreThreshold:C,padToMaxOutputSize:f},ne=Y.runKernel(NR,U,G);return{selectedIndices:ne[0],validOutputs:ne[1]}}const XO=z({nonMaxSuppressionPadded_:H9});async function q9(r,l,u,p=.5,g=Number.NEGATIVE_INFINITY,f=!1){const I=M(r,"boxes","nonMaxSuppressionAsync"),S=M(l,"scores","nonMaxSuppressionAsync"),x=js(I,S,u,p,g,null),v=x.maxOutputSize,O=x.iouThreshold,C=x.scoreThreshold,[U,G]=await Promise.all([I.data(),S.data()]),ne=VO(U,G,v,O,C,f);return I!==r&&I.dispose(),S!==l&&S.dispose(),ne}const JO=q9;function j9(r,l,u=!1){const p=M(r,"images","resizeBilinear");Z(p.rank===3||p.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${p.rank}.`),Z(l.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${l}.`);let g=p,f=!1;p.rank===3&&(f=!0,g=ie(p,[1,p.shape[0],p.shape[1],p.shape[2]]));const[I,S]=l,x=(U,G)=>(G([g]),U.resizeBilinear(g,I,S,u)),v={images:g},O={alignCorners:u,size:l},C=Y.runKernelFunc(x,v,null,Ef,O);return f?ie(C,[C.shape[1],C.shape[2],C.shape[3]]):C}const ZO=z({resizeBilinear_:j9});function K9(r,l,u=!1){const p=M(r,"images","resizeNearestNeighbor");Z(p.rank===3||p.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${p.rank}.`),Z(l.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${l}.`),Z(p.dtype==="float32"||p.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype");let g=p,f=!1;p.rank===3&&(f=!0,g=ie(p,[1,p.shape[0],p.shape[1],p.shape[2]]));const[I,S]=l,x={images:g},v={alignCorners:u,size:l},O=(U,G)=>(G([g]),U.resizeNearestNeighbor(g,I,S,u)),C=Y.runKernelFunc(O,x,null,Of,v);return f?ie(C,[C.shape[1],C.shape[2],C.shape[3]]):C}const QO=z({resizeNearestNeighbor_:K9});function X9(r,l,u){Z(l%1===0,()=>`bandPart(): numLower must be an integer, got ${l}.`),Z(u%1===0,()=>`bandPart(): numUpper must be an integer, got ${u}.`);const p=M(r,"a","bandPart");Z(p.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${p.rank}.`);const g=p.shape,[f,I]=p.shape.slice(-2);if(!(l<=f))throw new Error(`bandPart(): numLower (${l}) must not be greater than the number of rows (${f}).`);if(!(u<=I))throw new Error(`bandPart(): numUpper (${u}) must not be greater than the number of columns (${I}).`);l<0&&(l=f),u<0&&(u=I);const S=ie(dg(0,f,1,"int32"),[-1,1]),x=dg(0,I,1,"int32"),v=Be(S,x),O=ha(yr(v,ke(+l,"int32")),gr(v,ke(-u,"int32"))),C=Ds([f,I],p.dtype);return ie(qs(_u(ie(p,[-1,f,I])).map(U=>Mn(O,U,C))),g)}const e1=z({bandPart_:X9});function J9(r){let l;if(Array.isArray(r)){l=!1,Z(r!=null&&r.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");const g=r[0].shape[0];for(let f=1;f<r.length;++f)Z(r[f].shape[0]===g,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${r[f].shape[0]} vs. ${g})`)}else l=!0,r=ho(r,r.shape[0],0).map(g=>jI(g,[0]));Z(r.length<=r[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${r.length}) exceeds number of dimensions (${r[0].shape[0]}).`);const u=[],p=r;for(let g=0;g<r.length;++g)u.push(Y.tidy(()=>{let f=p[g];if(g>0)for(let I=0;I<g;++I){const S=ae(Fe(ae(u[I],f)),u[I]);f=Be(f,S)}return Pe(f,pg(f,"euclidean"))}));return l?qs(u,0):u}const t1=z({gramSchmidt_:J9});function Z9(r,l=!1){if(Z(r.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${r.rank}`),r.rank===2)return n1(r,l);{const u=r.shape.slice(0,r.shape.length-2).reduce((x,v)=>x*v),p=_u(ie(r,[u,r.shape[r.shape.length-2],r.shape[r.shape.length-1]]),0),g=[],f=[];p.forEach(x=>{const[v,O]=n1(x,l);g.push(v),f.push(O)});const I=ie(qs(g,0),r.shape),S=ie(qs(f,0),r.shape);return[I,S]}}function n1(r,l=!1){return Y.tidy(()=>{Z(r.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${r.shape.length}D Tensor.`);const u=r.shape[0],p=r.shape[1];let g=RI(u),f=gi(r);const I=pa([[1]],[1,1]);let S=gi(I);const x=u>=p?p:u;for(let v=0;v<x;++v){const O=f,C=S,U=g;[S,f,g]=Y.tidy(()=>{const G=vt(f,[v,v],[u-v,1]),ne=pg(G),te=vt(f,[v,v],[1,1]),oe=Mn(yi(te,0),pa([[-1]]),pa([[1]])),ge=Be(te,ae(oe,ne)),fe=Pe(G,ge);fe.shape[0]===1?S=gi(I):S=yn([I,vt(fe,[1,0],[fe.shape[0]-1,fe.shape[1]])],0);const Ae=yt(Pe(dn(oe,ge),ne)),Te=vt(f,[v,0],[u-v,p]),Ve=ae(Ae,S),rt=$t(S);if(v===0)f=Be(Te,dn(Ve,dn(rt,Te)));else{const Kt=Be(Te,dn(Ve,dn(rt,Te)));f=yn([vt(f,[0,0],[v,p]),Kt],0)}const Ct=$t(Ve),Ut=vt(g,[0,v],[u,g.shape[1]-v]);if(v===0)g=Be(Ut,dn(dn(Ut,S),Ct));else{const Kt=Be(Ut,dn(dn(Ut,S),Ct));g=yn([vt(g,[0,0],[u,v]),Kt],1)}return[S,f,g]}),xO([O,C,U])}return!l&&u>p&&(g=vt(g,[0,0],[u,p]),f=vt(f,[0,0],[p,p])),[g,f]})}const s1=z({qr_:Z9});var jt;(function(r){r[r.NONE=0]="NONE",r[r.MEAN=1]="MEAN",r[r.SUM=2]="SUM",r[r.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"})(jt||(jt={}));function Q9(r,l,u=jt.SUM_BY_NONZERO_WEIGHTS){const p=M(r,"losses","computeWeightedLoss");let g=null;l!=null&&(g=M(l,"weights","computeWeightedLoss"));const f=g==null?p:ae(p,g);if(u===jt.NONE)return f;if(u===jt.SUM)return Fe(f);if(u===jt.MEAN){if(g==null)return UI(f);{const I=p.size/g.size,S=Pe(Fe(f),Fe(g));return I>1?Pe(S,ke(I)):S}}if(u===jt.SUM_BY_NONZERO_WEIGHTS){if(g==null)return Pe(Fe(f),ke(p.size));{const I=ae(g,Yi(p.shape)),S=Le(Fe(MI(I,ke(0))),"float32");return Pe(Fe(f),S)}}throw Error(`Unknown reduction: ${u}`)}const Tn=z({computeWeightedLoss_:Q9});function eZ(r,l,u,p=jt.SUM_BY_NONZERO_WEIGHTS){const g=M(r,"labels","absoluteDifference"),f=M(l,"predictions","absoluteDifference");let I=null;u!=null&&(I=M(u,"weights","absoluteDifference")),Zt(g.shape,f.shape,"Error in absoluteDifference: ");const S=Bn(Be(g,f));return Tn(S,I,p)}const i1=z({absoluteDifference_:eZ});function tZ(r,l,u,p,g=jt.SUM_BY_NONZERO_WEIGHTS){const f=M(r,"labels","cosineDistance"),I=M(l,"predictions","cosineDistance");let S=null;p!=null&&(S=M(p,"weights","cosineDistance")),Zt(f.shape,I.shape,"Error in cosineDistance: ");const x=ke(1),v=Be(x,Fe(ae(f,I),u,!0));return Tn(v,S,g)}const r1=z({cosineDistance_:tZ});function nZ(r,l,u,p=jt.SUM_BY_NONZERO_WEIGHTS){let g=M(r,"labels","hingeLoss");const f=M(l,"predictions","hingeLoss");let I=null;u!=null&&(I=M(u,"weights","hingeLoss")),Zt(g.shape,f.shape,"Error in hingeLoss: ");const S=ke(1);g=Be(ae(ke(2),g),S);const x=Du(Be(S,ae(g,f)));return Tn(x,I,p)}const o1=z({hingeLoss_:nZ});function sZ(r,l,u,p=1,g=jt.SUM_BY_NONZERO_WEIGHTS){const f=M(r,"labels","huberLoss"),I=M(l,"predictions","huberLoss");let S=null;u!=null&&(S=M(u,"weights","huberLoss")),Zt(f.shape,I.shape,"Error in huberLoss: ");const x=ke(p),v=Bn(Be(I,f)),O=BI(v,x),C=Be(v,O),U=Lt(ae(ke(.5),dt(O)),ae(x,C));return Tn(U,S,g)}const a1=z({huberLoss_:sZ});function iZ(r,l,u,p=1e-7,g=jt.SUM_BY_NONZERO_WEIGHTS){const f=M(r,"labels","logLoss"),I=M(l,"predictions","logLoss");let S=null;u!=null&&(S=M(u,"weights","logLoss")),Zt(f.shape,I.shape,"Error in logLoss: ");const x=ke(1),v=ke(p),O=yt(ae(f,co(Lt(I,v)))),C=ae(Be(x,f),co(Lt(Be(x,I),v))),U=Be(O,C);return Tn(U,S,g)}const c1=z({logLoss_:iZ});function rZ(r,l,u,p=jt.SUM_BY_NONZERO_WEIGHTS){const g=M(r,"labels","meanSquaredError"),f=M(l,"predictions","meanSquaredError");let I=null;u!=null&&(I=M(u,"weights","meanSquaredError")),Zt(g.shape,f.shape,"Error in meanSquaredError: ");const S=qI(g,f);return Tn(S,I,p)}const l1=z({meanSquaredError_:rZ});function oZ(r,l){const u=M(r,"labels","sigmoidCrossEntropyWithLogits"),p=M(l,"logits","sigmoidCrossEntropyWithLogits");Zt(u.shape,p.shape,"Error in sigmoidCrossEntropyWithLogits: ");const g=Du(p),f=ae(p,u),I=_I(Pn(yt(Bn(p))));return Lt(Be(g,f),I)}function aZ(r,l,u,p=0,g=jt.SUM_BY_NONZERO_WEIGHTS){let f=M(r,"multiClassLabels","sigmoidCrossEntropy");const I=M(l,"logits","sigmoidCrossEntropy");let S=null;if(u!=null&&(S=M(u,"weights","sigmoidCrossEntropy")),Zt(f.shape,I.shape,"Error in sigmoidCrossEntropy: "),p>0){const v=ke(p),O=ke(1),C=ke(.5);f=Lt(ae(f,Be(O,v)),ae(C,v))}const x=oZ(f,I);return Tn(x,S,g)}const h1=z({sigmoidCrossEntropy_:aZ});function cZ(r,l,u=-1){if(u===-1&&(u=l.rank-1),u!==l.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${l.rank} and dim was ${u}`);const p=hg((g,f,I)=>{const S=!0,x=WI(f,[u],S),v=Be(Le(f,"float32"),x);I([g,v]);const O=yt(ae(v,g)),C=Fe(O,[u]),U=(G,ne)=>{const[te,oe]=ne,ge=Qn(G.shape,[u]);return[ae(ie(G,ge),Be(Le(te,"float32"),Pn(oe))),ae(ie(G,ge),Be(Pn(oe),Le(te,"float32")))]};return{value:C,gradFunc:U}});return p(r,l)}function lZ(r,l,u,p=0,g=jt.SUM_BY_NONZERO_WEIGHTS){let f=M(r,"onehotLabels","softmaxCrossEntropy");const I=M(l,"logits","softmaxCrossEntropy");let S=null;if(u!=null&&(S=M(u,"weights","softmaxCrossEntropy")),Zt(f.shape,I.shape,"Error in softmaxCrossEntropy: "),p>0){const v=ke(p),O=ke(1),C=ke(f.shape[1]);f=Lt(ae(f,Be(O,v)),Pe(v,C))}const x=cZ(f,I);return Tn(x,S,g)}const u1=z({softmaxCrossEntropy_:lZ});const zTe={fft:ku,ifft:Yc,rfft:Fu,irfft:HI},qTe={hammingWindow:WO,hannWindow:gg,frame:yg,stft:$O},d1={flipLeftRight:BO,resizeNearestNeighbor:QO,resizeBilinear:ZO,rotateWithOffset:MO,cropAndResize:UO,nonMaxSuppression:PO,nonMaxSuppressionAsync:qO,nonMaxSuppressionWithScore:jO,nonMaxSuppressionWithScoreAsync:KO,nonMaxSuppressionPadded:XO,nonMaxSuppressionPaddedAsync:JO},cAe={bandPart:e1,gramSchmidt:t1,qr:s1},bAe={absoluteDifference:i1,computeWeightedLoss:Tn,cosineDistance:r1,hingeLoss:o1,huberLoss:a1,logLoss:c1,meanSquaredError:l1,sigmoidCrossEntropy:h1,softmaxCrossEntropy:u1};const p1=1.7580993408473768,m1=1.0507009873554805;const f1={kernelName:ef,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>ae(r,da(Le(u,"float32"),-1))}}};const g1={kernelName:T2,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>{const p=dt(Le(u,"float32")),g=ps(Be(ke(1),p));return yt(Pe(r,g))}}}};const y1={kernelName:A2,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>{const p=ps(Be(dt(Le(u,"float32")),1));return Pe(r,p)}}}};const b1={kernelName:kc,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,p]=l,g=it(u.shape,p.shape),f=()=>{let S=r;const x=Nt(u.shape,g);return x.length>0&&(S=Fe(S,x)),ie(S,u.shape)},I=()=>{let S=r;const x=Nt(p.shape,g);return x.length>0&&(S=Fe(S,x)),ie(S,p.shape)};return{a:f,b:I}}};const w1={kernelName:v2,saveAllInputs:!0,gradFunc:(r,l)=>{const u={};return l.forEach((p,g)=>{u[g]=()=>r.clone()}),u}};const L1={kernelName:N2,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>je(u)}}};const S1={kernelName:C2,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>je(u)}}};const I1={kernelName:R2,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Pe(r,ps(Be(ke(1),dt(Le(u,"float32")))))}}};const x1={kernelName:O2,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>{const p=ps(Lt(ke(1),dt(Le(u,"float32"))));return Pe(r,p)}}}};const T1={kernelName:k2,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,p]=l,g=it(u.shape,p.shape),f=()=>{const S=Lt(dt(u),dt(p));let x=ae(r,Pe(p,S));const v=Nt(u.shape,g);return v.length>0&&(x=Fe(x,v)),ie(x,u.shape)},I=()=>{const S=Lt(dt(u),dt(p));let x=yt(ae(r,Pe(u,S)));const v=Nt(p.shape,g);return v.length>0&&(x=Fe(x,v)),ie(x,p.shape)};return{a:f,b:I}}};const A1={kernelName:E2,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Pe(r,Lt(dt(Le(u,"float32")),1))}}};const v1={kernelName:D2,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Pe(r,Be(ke(1),dt(Le(u,"float32"))))}}};function hZ(r,l,u,p,g=[1,1,1],f,I){const S=M(r,"dy","avgPool3dBackprop"),x=M(l,"input","avgPool3dBackprop");let v=S,O=x,C=!1;x.rank===4&&(C=!0,v=ie(S,[1,S.shape[0],S.shape[1],S.shape[2],S.shape[3]]),O=ie(x,[1,x.shape[0],x.shape[1],x.shape[2],x.shape[3]])),Z(v.rank===5,()=>`Error in avgPool3dBackprop: dy must be rank 5 but got rank ${v.rank}.`),Z(O.rank===5,()=>`Error in avgPool3dBackprop: input must be rank 5 but got rank ${O.rank}.`),Z(ao(p,g),()=>`Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides ${p} and dilations '${g}'`),I!=null&&Z(Qt(f),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${I} but got pad ${f}.`);const U=oe=>{const ge=cg(O.shape,u,p,g,f,I);return oe.avgPool3dBackprop(v,O,ge)},G={dy:v,input:O},ne={filterSize:u,strides:p,dilations:g,pad:f,dimRoundingMode:I},te=Y.runKernelFunc(U,G,null,$2,ne);return C?ie(te,[te.shape[1],te.shape[2],te.shape[3],te.shape[4]]):te}const N1=z({avgPool3dBackprop_:hZ});const C1={kernelName:W2,inputsToSave:["x"],gradFunc:(r,l,u)=>{const[p]=l,{filterSize:g,strides:f,dilations:I,pad:S,dimRoundingMode:x}=u,v=I==null?[1,1,1]:I;return{x:()=>N1(r,p,g,f,v,S,x)}}};function uZ(r,l,u,p,g){const f=M(r,"dy","avgPoolBackprop"),I=M(l,"input","avgPoolBackprop");Z(I.rank===f.rank,()=>`Rank of input (${I.rank}) does not match rank of dy (${f.rank})`);let S=I,x=f,v=!1;I.rank===3&&(v=!0,S=ie(I,[1,I.shape[0],I.shape[1],I.shape[2]]),x=ie(f,[1,f.shape[0],f.shape[1],f.shape[2]])),Z(x.rank===4,()=>`Error in avgPoolBackprop: dy must be rank 4 but got rank ${x.rank}.`),Z(S.rank===4,()=>`Error in avgPoolBackprop: input must be rank 4 but got rank ${S.rank}.`);const O=ne=>{const te=ag(S.shape,u,p,1,g);return ne.avgPoolBackprop(x,S,te)},C={dy:x,input:S},U={filterSize:u,strides:p,pad:g},G=Y.runKernelFunc(O,C,null,_2,U);return v?ie(G,[G.shape[1],G.shape[2],G.shape[3]]):G}const R1=z({avgPoolBackprop_:uZ});const O1={kernelName:F2,inputsToSave:["x"],gradFunc:(r,l,u)=>{const[p]=l,{filterSize:g,strides:f,pad:I}=u;return{x:()=>R1(r,p,g,f,I)}}};const E1={kernelName:tf,inputsToSave:["a","b"],gradFunc:(r,l,u)=>{const[p,g]=l,{transposeA:f,transposeB:I}=u;return!f&&!I?{a:()=>dn(r,g,!1,!0),b:()=>dn(p,r,!0,!1)}:!f&&I?{a:()=>dn(r,g,!1,!1),b:()=>dn(r,p,!0,!1)}:f&&!I?{a:()=>dn(g,r,!1,!0),b:()=>dn(p,r,!1,!1)}:{a:()=>dn(g,r,!0,!0),b:()=>dn(r,p,!0,!0)}}};const D1={kernelName:nf,gradFunc:(r,l,u)=>{const{blockShape:p,crops:g}=u;return{x:()=>zI(r,p,g)}}};const k1={kernelName:sf,gradFunc:(r,l,u)=>{const p=u,g=p.inputShape,f=p.shape,I=Array.from(f);for(let x=g.length-1;x>=0;x--)if(g[x]===f[x])I[x]=1;else if(g[x]!==1)throw new Error(`broadcastTo(): [${g}] cannot be broadcast to [${f}].`);const S=[];for(let x=0;x<I.length;x++)I[x]>1&&S.push(x);return{x:()=>Fe(r,S,!0)}}};const F1={kernelName:Fc,gradFunc:r=>({x:()=>r.clone()})};const _1={kernelName:U2,gradFunc:r=>({x:()=>je(r)})};const W1={kernelName:B2,inputsToSave:["x"],gradFunc:(r,l,u)=>{const[p]=l,{clipValueMin:g,clipValueMax:f}=u;return{x:()=>Mn(ha(gr(p,g),yr(p,f)),r,je(r))}}};const $1={kernelName:rf,saveAllInputs:!0,gradFunc:(r,l,u)=>{const p=l.map(x=>x.shape),{axis:g}=u,f=ut(g,l[0].shape)[0],I=p.map(x=>x[f]),S=ho(r,I,f);return S.map(x=>()=>x)}};const U1={kernelName:of,inputsToSave:["x","filter"],gradFunc:(r,l,u)=>{const[p,g]=l,{dilations:f,strides:I,pad:S,dataFormat:x}=u;return Z(oo(f),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${f}'`),{x:()=>CO(p.shape,r,g,I,S,x),filter:()=>fg(p,r,g.shape,I,S,x)}}};const B1={kernelName:af,inputsToSave:["dy","filter"],gradFunc:(r,l,u)=>{const[p,g]=l,{strides:f,pad:I,dataFormat:S,dimRoundingMode:x}=u;return{dy:()=>AI(r,g,f,I,S,1,x),filter:()=>fg(r,p,g.shape,f,I,S,x)}}};function dZ(r,l,u,p,g){let f=r;r.rank===4&&(f=ie(r,[1,r.shape[0],r.shape[1],r.shape[2],r.shape[3]]));let I=l;I.rank===4&&(I=ie(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]])),Z(f.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${f.shape}.`),Z(I.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${I.shape}.`),Z(u.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${u}.`),Z(f.shape[4]===u[3],()=>`Error in conv3dDerFilter: depth of input ${f.shape[4]}) must match input depth in filter (${u[3]}.`),Z(I.shape[4]===u[4],()=>`Error in conv3dDerFilter: depth of dy (${I.shape[4]}) must match output depth for filter (${u[4]}).`);const S=O=>{const C=1,U=Ru(f.shape,u,p,C,g);return O.conv3dDerFilter(f,I,U)},x={x:f,y:I},v={strides:p,pad:g};return Y.runKernelFunc(S,x,null,G2,v)}const M1=z({conv3DBackpropFilter_:dZ});const P1={kernelName:z2,inputsToSave:["x","filter"],gradFunc:(r,l,u)=>{const{dilations:p,strides:g,pad:f}=u;Z(oo(p),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${p}'`);const[I,S]=l;return{x:()=>RO(I.shape,r,S,g,f),filter:()=>M1(I,r,S.shape,g,f)}}};const z1={kernelName:cf,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>ae(yt(VI(Le(u,"float32"))),r)}}};const G1={kernelName:lf,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>ae(YI(Le(u,"float32")),r)}}};const V1={kernelName:hf,inputsToSave:["x"],gradFunc:(r,l,u)=>{const[p]=l,{axis:g,exclusive:f,reverse:I}=u;return{x:()=>{const S=ds([g],p.rank);let x=NI(r,g,f,!I);return S!=null&&(x=$t(x,S)),x}}}};const Y1={kernelName:H2,inputsToSave:["x","filter"],gradFunc:(r,l,u)=>{const{dilations:p,strides:g,pad:f,dimRoundingMode:I}=u,S=p==null?[1,1]:p;Z(oo(S),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${S}'`);const[x,v]=l;Z(x.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${x.rank}.`),Z(v.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${v.rank}.`),Z(x.shape[3]===v.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${x.shape[3]}) must match the inChannels dimension in filter ${v.shape[2]}.`),Z(ao(g,S),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${g} and dilations '${S}'.`),I!=null&&Z(Qt(f),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${I} but got pad ${f}.`);const O=fr(x.shape,v.shape,g,S,f,I,!0);return{x:()=>_O(x.shape,r,v,O),filter:()=>FO(x,r,v.shape,O)}}};const H1={kernelName:K2,inputsToSave:["x","filter"],gradFunc:(r,l,u)=>{const[p,g]=l,f={x:p,filter:g,dy:r},I={x:p,filter:g,dy:r};return{x:()=>Y.runKernel(X2,f,u),filter:()=>Y.runKernel(J2,I,u)}}};const q1={kernelName:uf,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,p]=l,g=it(u.shape,p.shape),f=()=>{const S=Pe(r,Le(p,"float32")),x=Nt(u.shape,g);return x.length>0?ie(Fe(S,x),u.shape):S},I=()=>{let S=ae(r,Le(u,"float32"));const x=Nt(p.shape,g);x.length>0&&(S=ie(Fe(S,x),p.shape));const v=dt(p);return yt(Pe(S,Le(v,"float32")))};return{a:f,b:I}}};const j1={kernelName:Z2,outputsToSave:[!0],gradFunc:(r,l)=>{const[u]=l,p=f=>f.eluDer(r,u),g={dy:r,y:u};return{x:()=>Y.runKernelFunc(p,g,null,Q2)}}};const K1={kernelName:eR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l,p=ae(Pn(yt(dt(u))),2/Math.sqrt(Math.PI));return{x:()=>ae(r,p)}}};const X1={kernelName:df,outputsToSave:[!0],gradFunc:(r,l)=>{const[u]=l;return{x:()=>ae(r,u)}}};const J1={kernelName:nR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>ae(r,Pn(u))}}};const Z1={kernelName:pf,gradFunc:r=>({x:()=>je(r)})};const Q1={kernelName:mf,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,p]=l,g=it(u.shape,p.shape),f=()=>{const S=Pe(r,Le(p,"float32")),x=Nt(u.shape,g);return x.length>0?ie(Fe(S,x),u.shape):S},I=()=>{let S=ae(r,Le(u,"float32"));const x=Nt(p.shape,g);x.length>0&&(S=ie(Fe(S,x),p.shape));const v=dt(p);return yt(Pe(S,Le(v,"float32")))};return{a:f,b:I}}};const eE={kernelName:oR,inputsToSave:["x","mean","variance","scale"],gradFunc:(r,l,u)=>{const{varianceEpsilon:p}=u,[g,f,I,S]=l,x=S==null?ke(1):S,v=Nt(f.shape,g.shape),O=[];if(f.rank===1){for(let Te=0;Te<g.shape.length-1;++Te)O.push(g.shape[Te]);O.push(1)}const C=Be(g,f),U=ae(r,x),G=GI(Lt(I,ke(p))),ne=ae(ae(ae(G,G),G),ke(-.5)),te=()=>f.rank===1?ie(ae(ae(r,ca(ie(G,[1,1,1,f.shape[0]]),O)),x),g.shape):ie(ae(ae(r,G),x),g.shape),oe=()=>{let Te=ae(ae(G,ke(-1)),U);return f.rank===1&&(Te=Fe(Te,v)),ie(Te,f.shape)},ge=()=>{let Te=ae(ae(ne,C),U);return f.rank===1&&(Te=Fe(Te,v)),ie(Te,f.shape)},fe=()=>{const Te=ae(C,G);let Ve=ae(r,Te);return f.rank===1&&(Ve=Fe(Ve,v)),ie(Ve,f.shape)},Ae=()=>{let Te=r;return f.rank===1&&(Te=Fe(Te,v)),ie(Te,f.shape)};return{x:te,mean:oe,variance:ge,scale:fe,offset:Ae}}};const sE={kernelName:ff,inputsToSave:["x","indices"],gradFunc:(r,l,u)=>{const[p,g]=l,{axis:f}=u,I=ut(f,p.shape)[0],S=()=>{const x=p.shape,v=g.size,O=x.slice(0,I),C=O.length,U=x.slice(f,x.length).slice(1),G=U.length,ne=tE(0,C),te=tE(C+1,C+1+G),oe=nE([O,[v],U]),ge=ie(r,oe),fe=ie(g,[v]),Ae=nE([[C],ne,te]),Te=$t(ge,Ae);let Ve=KI(Te,fe,p.shape[I]);const rt=Mc(Ae);return Ve=$t(Ve,rt),Ve};return{x:S,indices:()=>g}}};function tE(r,l){const u=[];for(let p=r;p<l;++p)u.push(p);return u}function nE(r){const l=[];for(let u=0;u<r.length;++u)for(let p=0;p<r[u].length;++p)l.push(r[u][p]);return l}const iE={kernelName:gf,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,p]=l;return{a:()=>je(u),b:()=>je(p)}}};const rE={kernelName:yf,gradFunc:r=>({x:()=>Le(r,"float32")})};const oE={kernelName:hR,gradFunc:r=>({x:()=>je(r)})};const aE={kernelName:uR,gradFunc:r=>({x:()=>je(r)})};const cE={kernelName:dR,gradFunc:r=>({x:()=>je(r)})};const lE={kernelName:wf,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Pe(r,Lt(u,1))}}};const hE={kernelName:bf,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Pe(r,Le(u,"float32"))}}};const uE={kernelName:yR,inputsToSave:[],outputsToSave:[!0],gradFunc:(r,l,u)=>{const[p]=l,{axis:g}=u;return{logits:()=>{const f=!0,I=Pn(p);return Be(r,ae(Fe(r,g,f),I))}}}};function pZ(r,l,u,p=5,g=1,f=1,I=.5){const S=O=>O.LRNGrad(u,r,l,p,g,f,I),x={x:r,y:l,dy:u},v={depthRadius:p,bias:g,alpha:f,beta:I};return Y.runKernelFunc(S,x,null,wR,v)}const dE=z({localResponseNormalizationBackprop_:pZ});const pE={kernelName:bR,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,l,u)=>{const[p,g]=l,{depthRadius:f,bias:I,alpha:S,beta:x}=u;return{x:()=>dE(p,g,r,f,I,S,x)}}};function bg(r,l,u,p,g){return l.rank<u.rank&&(l=ie(l,Qn(l.shape,p))),r.rank<u.rank&&(r=ie(r,Qn(r.shape,p))),{x:()=>{const f=ae(r,Le(CI(u,l),r.dtype));return g==null?f:$t(f,g)}}}const JI={kernelName:Lf,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,l,u)=>{const p=u,{reductionIndices:g}=p,[f,I]=l,S=ut(g,f.shape),x=ds(S,f.rank),v=bg(r,I,f,S,x);return{x:()=>{let O=v.x();return x!=null&&(O=$t(O)),O}}}};const mE={kernelName:Sf,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,p]=l,g=()=>ae(r,Le(gr(u,p),"float32")),f=()=>ae(r,Le(FI(u,p),"float32"));return{a:g,b:f}}};function mZ(r,l,u,p,g,f=[1,1,1],I,S){const x=M(r,"dy","maxPool3dBackprop"),v=M(l,"input","maxPool3dBackprop"),O=M(u,"output","maxPool3dBackprop");let C=x,U=v,G=O,ne=!1;v.rank===4&&(ne=!0,C=ie(x,[1,x.shape[0],x.shape[1],x.shape[2],x.shape[3]]),U=ie(v,[1,v.shape[0],v.shape[1],v.shape[2],v.shape[3]]),G=ie(O,[1,O.shape[0],O.shape[1],O.shape[2],O.shape[3]])),Z(C.rank===5,()=>`Error in maxPool3dBackprop: dy must be rank 5 but got rank ${C.rank}.`),Z(U.rank===5,()=>`Error in maxPool3dBackprop: input must be rank 5 but got rank ${U.rank}.`),Z(G.rank===5,()=>`Error in maxPool3dBackprop: output must be rank 5 but got rank ${G.rank}.`),Z(ao(g,f),()=>`Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides ${g} and dilations '${f}'`),S!=null&&Z(Qt(I),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${S} but got pad ${I}.`);const te=Ae=>{const Te=cg(U.shape,p,g,f,I,S);return Ae.maxPool3dBackprop(C,U,G,Te)},oe={dy:C,input:U,output:G},ge={filterSize:p,strides:g,dilations:f,pad:I,dimRoundingMode:S},fe=Y.runKernelFunc(te,oe,null,xR,ge);return ne?ie(fe,[fe.shape[1],fe.shape[2],fe.shape[3],fe.shape[4]]):fe}const fE=z({maxPool3dBackprop_:mZ});const gE={kernelName:IR,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,l,u)=>{const[p,g]=l,{filterSize:f,strides:I,dilations:S,pad:x,dimRoundingMode:v}=u,O=S==null?[1,1,1]:S;return{x:()=>fE(r,p,g,f,I,O,x,v)}}};function fZ(r,l,u,p,g,f,I){const S=M(r,"dy","maxPoolBackprop"),x=M(l,"input","maxPoolBackprop"),v=M(u,"output","maxPoolBackprop");Z(x.rank===S.rank,()=>`Rank of input (${x.rank}) does not match rank of dy (${S.rank})`),Z(S.rank===4,()=>`Error in maxPoolBackprop: dy must be rank 4 but got rank ${S.rank}.`),Z(x.rank===4,()=>`Error in maxPoolBackprop: input must be rank 4 but got rank ${x.rank}.`),I!=null&&Z(Qt(f),()=>`Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode ${I} but got pad ${f}.`);const O=G=>{const ne=ag(x.shape,p,g,1,f,I);return G.maxPoolBackprop(S,x,v,ne)},C={dy:S,input:x,output:v},U={filterSize:p,strides:g,pad:f,dimRoundingMode:I};return Y.runKernelFunc(O,C,null,SR,U)}const yE=z({maxPoolBackprop_:fZ});const bE={kernelName:LR,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,l,u)=>{const[p,g]=l,{filterSize:f,strides:I,pad:S}=u;return{x:()=>yE(r,p,g,f,I,S)}}};const wE={kernelName:If,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,l,u)=>{const p=u,{axis:g}=p,[f,I]=l,S=ut(g,f.shape),x=ds(S,f.rank),v=bg(r,I,f,S,x);return{x:()=>{let O=v.x();return x!=null&&(O=$t(O)),O}}}};const LE={kernelName:xf,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,p]=l,g=()=>ae(r,Le(yr(u,p),"float32")),f=()=>ae(r,Le(yi(u,p),"float32"));return{a:g,b:f}}};const SE={kernelName:TR,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,p]=l,g=it(u.shape,p.shape),f=()=>{const S=Nt(u.shape,g);return S.length>0?ie(Fe(r,S),u.shape):r},I=()=>{const S=ae(r,yt(EI(Pe(u,p)))),x=Nt(p.shape,g);return x.length>0?ie(Fe(S,x),p.shape):S};return{a:f,b:I}}};const IE={kernelName:Tf,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,p]=l,g=it(u.shape,p.shape),f=()=>{const S=ae(r,Le(p,"float32")),x=Nt(u.shape,g);return x.length>0?ie(Fe(S,x),u.shape):S},I=()=>{const S=ae(r,Le(u,"float32")),x=Nt(p.shape,g);return x.length>0?ie(Fe(S,x),p.shape):S};return{a:f,b:I}}};const xE={kernelName:Af,gradFunc:r=>({x:()=>yt(r)})};const TE={kernelName:OR,inputsToSave:["indices"],gradFunc:(r,l)=>{const u=l[0];return{indices:()=>Ds(u.shape,"float32")}}};const AE={kernelName:RR,gradFunc:r=>({x:()=>je(r)})};const ZI={kernelName:vf,inputsToSave:["x"],gradFunc:(r,l,u)=>{const p=l[0],{paddings:g}=u,f=g.map(I=>I[0]);return{x:()=>vt(r,f,p.shape)}}};const vE={kernelName:Nf,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(r,l)=>{const[u,p,g]=l,f=u,I=p,S=it(f.shape,I.shape),x=()=>{const O=Le(I,"float32");let C=ae(r,ae(O,ua(f,Be(O,ke(1)))));const U=Nt(f.shape,S);return U.length>0&&(C=Fe(C,U)),ie(C,f.shape)},v=()=>{const O=yi(f,0),C=Mn(O,co(f),je(f));let U=ae(r,ae(g,C));const G=Nt(I.shape,S);return G.length>0&&(U=Fe(U,G)),ie(U,I.shape)};return{a:x,b:v}}};const NE={kernelName:ER,inputsToSave:["x","alpha"],gradFunc:(r,l)=>{const[u,p]=l,g=yi(u,0);return{x:()=>Mn(g,r,ae(r,p)),alpha:()=>{let f=Mn(g,je(r),ae(r,u));const I=Nt(p.shape,r.shape);return I.length>0&&(f=Fe(f,I)),ie(f,p.shape)}}}};const CE={kernelName:FR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Pe(r,yt(dt(u)))}}};const RE={kernelName:$R,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l,p=ae(yr(u,6),da(u));return{x:()=>ae(r,Le(p,"float32"))}}};const OE={kernelName:Cf,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>ae(r,Le(da(u),"float32"))}}};const EE={kernelName:Rf,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>ie(r,u.shape)}}};const DE={kernelName:Ef,inputsToSave:["images"],gradFunc:(r,l,u)=>{const[p]=l,g=S=>{const{alignCorners:x}=u;return S.resizeBilinearBackprop(r,p,x)},f={images:p},I=()=>Y.runKernelFunc(g,f,null,WR,u);return{images:I}}};const kE={kernelName:Of,inputsToSave:["images"],gradFunc:(r,l,u)=>{const[p]=l,g=S=>{const{alignCorners:x}=u;return S.resizeNearestNeighborBackprop(r,p,x)},f={images:p},I=()=>Y.runKernelFunc(g,f,null,_R,u);return{images:I}}};const FE={kernelName:Df,gradFunc:(r,l,u)=>{const{dims:p}=u,g=ut(p,r.shape);return{x:()=>Vc(r,g)}}};const _E={kernelName:UR,gradFunc:r=>({x:()=>je(r)})};const WE={kernelName:kf,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>yt(Pe(r,ae(ua(u,1.5),2)))}}};const $E={kernelName:Ff,inputsToSave:["condition"],gradFunc:(r,l)=>{const[u]=l;return{condition:()=>Le(je(u),"float32"),t:()=>ae(r,Le(u,r.dtype)),e:()=>ae(r,Le($I(u),r.dtype))}}};const UE={kernelName:BR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>{const p=yi(u,ke(0)),g=ke(p1),f=ke(m1),I=ae(r,f),S=ae(ae(r,g),Pn(Le(u,"float32")));return Mn(p,I,S)}}}};const BE={kernelName:Uf,outputsToSave:[!0],gradFunc:(r,l)=>{const[u]=l;return{x:()=>ae(r,ae(u,Be(ke(1),u)))}}};const ME={kernelName:MR,gradFunc:r=>({x:()=>je(r)})};const PE={kernelName:Wf,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>ae(Ou(Le(u,"float32")),r)}}};const zE={kernelName:$f,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>ae(vI(Le(u,"float32")),r)}}};const GE={kernelName:_f,inputsToSave:["x"],gradFunc:(r,l,u)=>{const[p]=l,{begin:g,size:f}=u,I=p.shape,[S,x]=rg(p,g,f),v=[];for(let O=0;O<r.rank;O++)v.push([S[O],I[O]-S[O]-x[O]]);return{x:()=>PI(r,v)}}};const VE={kernelName:zR,outputsToSave:[!0],gradFunc:(r,l,u)=>{const[p]=l,{dim:g}=u,f=!0,I=ae(r,p);return{logits:()=>Be(I,ae(Fe(I,[g],f),p))}}};const YE={kernelName:PR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>ae(r,xI(u))}}};const QI={kernelName:Pf,gradFunc:(r,l,u)=>{const{blockShape:p,paddings:g}=u;return{x:()=>TI(r,p,g)}}};const ex={kernelName:zf,gradFunc:(r,l,u)=>{const{axis:p}=u;return{x:()=>yn(r,p)}}};const HE={kernelName:Bf,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Pe(r,ae(ps(Le(u,"float32")),2))}}};const qE={kernelName:GR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>ae(r,ae(Le(u,"float32"),2))}}};const jE={kernelName:Gf,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,p]=l,g=ke(2),f=()=>ae(r,ae(g,Be(u,p))),I=()=>ae(r,ae(g,Be(p,u)));return{a:f,b:I}}};const KE={kernelName:Xf,gradFunc:r=>({x:()=>je(r)})};const XE={kernelName:Vf,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,p]=l,g=it(u.shape,p.shape),f=()=>{let S=r;const x=Nt(u.shape,g);return x.length>0&&(S=Fe(S,x)),ie(S,u.shape)},I=()=>{let S=r;const x=Nt(p.shape,g);return x.length>0&&(S=Fe(S,x)),ie(yt(S),p.shape)};return{a:f,b:I}}};const JE={kernelName:Mf,inputsToSave:["x"],gradFunc:(r,l,u)=>{const[p]=l,g=p.shape.slice(),{axis:f}=u,I=ut(f,p.shape);I.forEach(v=>{g[v]=1});const S=ie(r,g),x=ae(S,Yi(p.shape,"float32"));return{x:()=>x}}};const ZE={kernelName:VR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Pe(r,dt(Ou(u)))}}};const QE={kernelName:YR,outputsToSave:[!0],gradFunc:(r,l)=>{const[u]=l;return{x:()=>ae(Be(ke(1),dt(u)),r)}}};const eD={kernelName:Yf,inputsToSave:["x"],gradFunc:(r,l,u)=>{const[p]=l,{reps:g}=u,f=()=>{let I=je(p);if(p.rank===1)for(let S=0;S<g[0];++S)I=Lt(I,vt(r,[S*p.shape[0]],[p.shape[0]]));else if(p.rank===2)for(let S=0;S<g[0];++S)for(let x=0;x<g[1];++x)I=Lt(I,vt(r,[S*p.shape[0],x*p.shape[1]],[p.shape[0],p.shape[1]]));else if(p.rank===3)for(let S=0;S<g[0];++S)for(let x=0;x<g[1];++x)for(let v=0;v<g[2];++v)I=Lt(I,vt(r,[S*p.shape[0],x*p.shape[1],v*p.shape[2]],[p.shape[0],p.shape[1],p.shape[2]]));else if(p.rank===4)for(let S=0;S<g[0];++S)for(let x=0;x<g[1];++x)for(let v=0;v<g[2];++v)for(let O=0;O<g[3];++O)I=Lt(I,vt(r,[S*p.shape[0],x*p.shape[1],v*p.shape[2],O*p.shape[3]],[p.shape[0],p.shape[1],p.shape[2],p.shape[3]]));else throw new Error(`Gradient for tile operation is not implemented for rank-${p.rank} tensors yet.`);return I};return{x:f}}};const tD={kernelName:Hf,gradFunc:(r,l,u)=>{const p=u,{perm:g}=p,f=Mc(g);return{x:()=>$t(r,f)}}};const nD={kernelName:qf,gradFunc:(r,l,u)=>{const p=u,{axis:g}=p;return{value:()=>qs(r,g)}}};const sD={kernelName:jf,inputsToSave:["segmentIds"],gradFunc:(r,l)=>{const[u]=l,p=()=>gZ(r,u);return{x:p}}};function gZ(r,l){const u=kI(l,je(l)),p=DI(r,u);let g=gr(l,ke(0,"int32"));const f=p.rank-g.rank;for(let S=0;S<f;++S)g=Es(g,S+1);g=ha(g,Yi(p.shape,"bool"));const I=je(p);return Mn(g,p,I)}const iD={kernelName:Kf,gradFunc:r=>({x:()=>je(r)})};const yZ=[f1,g1,y1,b1,w1,L1,S1,I1,x1,T1,A1,v1,C1,O1,E1,D1,k1,F1,_1,W1,$1,B1,U1,P1,z1,G1,V1,Y1,H1,q1,j1,K1,X1,J1,Q1,Z1,eE,sE,iE,rE,oE,aE,cE,lE,hE,uE,pE,JI,JI,mE,gE,bE,wE,LE,SE,IE,xE,TE,AE,ZI,ZI,vE,NE,CE,RE,OE,EE,DE,kE,FE,_E,WE,$E,UE,BE,ME,PE,zE,GE,VE,YE,QI,QI,ex,ex,HE,jE,qE,KE,XE,JE,ZE,QE,eD,tD,nD,sD,iD];for(const r of yZ)jR(r);function Gm(r,l,u=!1){const{Image:p,Canvas:g}=mt.getEnv();if(!(r instanceof p||r instanceof g))throw new Error("imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement");const f=to(r),I=l/Math.max(f.height,f.width),S=I*f.width,x=I*f.height,v=ea({width:l,height:l}),O=r instanceof g?r:Nc(r),C=Math.abs(S-x)/2,U=u&&S<x?C:0,G=u&&x<S?C:0;return Un(v).drawImage(O,U,G,S,x),v}class hr{constructor(r,l=!1){this._imageTensors=[];this._canvases=[];this._treatAsBatchInput=!1;this._inputDimensions=[];if(!Array.isArray(r))throw new Error(`NetInput.constructor - expected inputs to be an Array of TResolvedNetInput or to be instanceof tf.Tensor4D, instead have ${r}`);this._treatAsBatchInput=l,this._batchSize=r.length,r.forEach((u,p)=>{if(dr(u)){this._imageTensors[p]=u,this._inputDimensions[p]=u.shape;return}if(Cs(u)){const f=u.shape[0];if(f!==1)throw new Error(`NetInput - tf.Tensor4D with batchSize ${f} passed, but not supported in input array`);this._imageTensors[p]=u,this._inputDimensions[p]=u.shape.slice(1);return}const g=u instanceof mt.getEnv().Canvas?u:Nc(u);this._canvases[p]=g,this._inputDimensions[p]=[g.height,g.width,3]})}get imageTensors(){return this._imageTensors}get canvases(){return this._canvases}get isBatchInput(){return this.batchSize>1||this._treatAsBatchInput}get batchSize(){return this._batchSize}get inputDimensions(){return this._inputDimensions}get inputSize(){return this._inputSize}get reshapedInputDimensions(){return Bi(this.batchSize,0,1).map((r,l)=>this.getReshapedInputDimensions(l))}getInput(r){return this.canvases[r]||this.imageTensors[r]}getInputDimensions(r){return this._inputDimensions[r]}getInputHeight(r){return this._inputDimensions[r][0]}getInputWidth(r){return this._inputDimensions[r][1]}getReshapedInputDimensions(r){if(typeof this.inputSize!="number")throw new Error("getReshapedInputDimensions - inputSize not set, toBatchTensor has not been called yet");const l=this.getInputWidth(r),u=this.getInputHeight(r);return HS({width:l,height:u},this.inputSize)}toBatchTensor(r,l=!0){return this._inputSize=r,IO(()=>{const u=Bi(this.batchSize,0,1).map(g=>{const f=this.getInput(g);if(f instanceof xn){let I=Cs(f)?f:f.expandDims();return I=Nm(I,l),(I.shape[1]!==r||I.shape[2]!==r)&&(I=d1.resizeBilinear(I,[r,r])),I.as3D(r,r,3)}if(f instanceof mt.getEnv().Canvas)return LI.fromPixels(Gm(f,r,l));throw new Error(`toBatchTensor - at batchIdx ${g}, expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have ${f}`)}),p=qs(u.map(g=>Le(g,"float32"))).as4D(this.batchSize,r,r,3);return p})}}async function Tt(r){if(r instanceof hr)return r;let l=Array.isArray(r)?r:[r];if(!l.length)throw new Error("toNetInput - empty array passed as input");const u=g=>Array.isArray(r)?` at input index ${g}:`:"",p=l.map(eo);return p.forEach((g,f)=>{if(!bu(g)&&!dr(g)&&!Cs(g))throw typeof l[f]=="string"?new Error(`toNetInput -${u(f)} string passed, but could not resolve HTMLElement for element id ${l[f]}`):new Error(`toNetInput -${u(f)} expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id`);if(Cs(g)){const I=g.shape[0];if(I!==1)throw new Error(`toNetInput -${u(f)} tf.Tensor4D with batchSize ${I} passed, but not supported in input array`)}}),await Promise.all(p.map(g=>bu(g)&&qm(g))),new hr(p,Array.isArray(r))}async function Zo(r,l){const{Canvas:u}=mt.getEnv();let p=r;if(!(r instanceof u)){const I=await Tt(r);if(I.batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");const S=I.getInput(0);p=S instanceof u?S:await Vm(S)}const g=Un(p),f=l.map(I=>I instanceof Wt?I.forSize(p.width,p.height).box.floor():I).map(I=>I.clipAtImageBorders(p.width,p.height));return f.map(({x:I,y:S,width:x,height:v})=>{const O=ea({width:x,height:v});return Un(O).putImageData(g.getImageData(I,S,x,v),0,0),O})}const wg=Xe(Je());async function Qo(r,l){if(!dr(r)&&!Cs(r))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(Cs(r)&&r.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return wg.tidy(()=>{const[u,p,g]=r.shape.slice(Cs(r)?1:0),f=l.map(S=>S instanceof Wt?S.forSize(p,u).box:S).map(S=>S.clipAtImageBorders(p,u)),I=f.map(({x:S,y:x,width:v,height:O})=>wg.slice3d(r.as3D(u,p,g),[x,S,0],[O,v,g]));return I})}async function no(r,l){const u=mt.getEnv().fetch,p=await u(r,l);if(!(p.status<400))throw new Error(`failed to fetch: (${p.status}) ${p.statusText}, from url: ${p.url}`);return p}async function p2(r){const l=await no(r),u=await l.blob();if(!u.type.startsWith("image/"))throw new Error(`fetchImage - expected blob type to be of type image/*, instead have: ${u.type}, for url: ${l.url}`);return Hm(u)}async function Ym(r){return(await no(r)).json()}async function d2(r){return new Float32Array(await(await no(r)).arrayBuffer())}function Lg(r,l){const u=`${l}-weights_manifest.json`;if(!r)return{modelBaseUri:"",manifestUri:u};if(r==="/")return{modelBaseUri:"/",manifestUri:`/${u}`};const p=r.startsWith("http://")?"http://":r.startsWith("https://")?"https://":"";r=r.replace(p,"");const g=r.split("/").filter(S=>S),f=r.endsWith(".json")?g[g.length-1]:u;let I=p+(r.endsWith(".json")?g.slice(0,g.length-1):g).join("/");return I=r.startsWith("/")?`/${I}`:I,{modelBaseUri:I,manifestUri:I==="/"?`/${f}`:`${I}/${f}`}}const rD=Xe(Je());async function zm(r,l){const{manifestUri:u,modelBaseUri:p}=Lg(r,l);let g=await Ym(u);return rD.io.loadWeights(g,p)}function u2(r,l,u=!1){const{width:p,height:g}=u?to(l):l;return r.width=p,r.height=g,{width:p,height:g}}const br=Xe(Je());class In{constructor(r){this._name=r;this._params=void 0;this._paramMappings=[]}get params(){return this._params}get paramMappings(){return this._paramMappings}get isLoaded(){return!!this.params}getParamFromPath(r){const{obj:l,objProp:u}=this.traversePropertyPath(r);return l[u]}reassignParamFromPath(r,l){const{obj:u,objProp:p}=this.traversePropertyPath(r);u[p].dispose(),u[p]=l}getParamList(){return this._paramMappings.map(({paramPath:r})=>({path:r,tensor:this.getParamFromPath(r)}))}getTrainableParams(){return this.getParamList().filter(r=>r.tensor instanceof br.Variable)}getFrozenParams(){return this.getParamList().filter(r=>!(r.tensor instanceof br.Variable))}variable(){this.getFrozenParams().forEach(({path:r,tensor:l})=>{this.reassignParamFromPath(r,l.variable())})}freeze(){this.getTrainableParams().forEach(({path:r,tensor:l})=>{const u=br.tensor(l.dataSync());l.dispose(),this.reassignParamFromPath(r,u)})}dispose(r=!0){this.getParamList().forEach(l=>{if(r&&l.tensor.isDisposed)throw new Error(`param tensor has already been disposed for path ${l.path}`);l.tensor.dispose()}),this._params=void 0}serializeParams(){return new Float32Array(this.getParamList().map(({tensor:r})=>Array.from(r.dataSync())).reduce((r,l)=>r.concat(l)))}async load(r){if(r instanceof Float32Array){this.extractWeights(r);return}await this.loadFromUri(r)}async loadFromUri(r){if(r&&typeof r!="string")throw new Error(`${this._name}.loadFromUri - expected model uri`);const l=await zm(r,this.getDefaultModelName());this.loadFromWeightMap(l)}async loadFromDisk(r){if(r&&typeof r!="string")throw new Error(`${this._name}.loadFromDisk - expected model file path`);const{readFile:l}=mt.getEnv(),{manifestUri:u,modelBaseUri:p}=Lg(r,this.getDefaultModelName()),g=x=>Promise.all(x.map(v=>l(v).then(O=>O.buffer))),f=br.io.weightsLoaderFactory(g),I=JSON.parse((await l(u)).toString()),S=await f(I,p);this.loadFromWeightMap(S)}loadFromWeightMap(r){const{paramMappings:l,params:u}=this.extractParamsFromWeigthMap(r);this._paramMappings=l,this._params=u}extractWeights(r){const{paramMappings:l,params:u}=this.extractParams(r);this._paramMappings=l,this._params=u}traversePropertyPath(r){if(!this.params)throw new Error("traversePropertyPath - model has no loaded params");const l=r.split("/").reduce((g,f)=>{if(!g.nextObj.hasOwnProperty(f))throw new Error(`traversePropertyPath - object does not have property ${f}, for path ${r}`);return{obj:g.nextObj,objProp:f,nextObj:g.nextObj[f]}},{nextObj:this.params}),{obj:u,objProp:p}=l;if(!u||!p||!(u[p]instanceof br.Tensor))throw new Error(`traversePropertyPath - parameter is not a tensor, for path ${r}`);return{obj:u,objProp:p}}}const Hc=Xe(Je());function es(r,l,u){return Hc.tidy(()=>{let p=Hc.separableConv2d(r,l.depthwise_filter,l.pointwise_filter,u,"same");return p=Hc.add(p,l.bias),p})}const Dt=Xe(Je());function Sg(r,l,u=!1){return Dt.tidy(()=>{const p=Dt.relu(u?Dt.add(Dt.conv2d(r,l.conv0.filters,[2,2],"same"),l.conv0.bias):es(r,l.conv0,[2,2])),g=es(p,l.conv1,[1,1]),f=Dt.relu(Dt.add(p,g)),I=es(f,l.conv2,[1,1]);return Dt.relu(Dt.add(p,Dt.add(g,I)))})}function Wu(r,l,u=!1,p=!0){return Dt.tidy(()=>{const g=Dt.relu(u?Dt.add(Dt.conv2d(r,l.conv0.filters,p?[2,2]:[1,1],"same"),l.conv0.bias):es(r,l.conv0,p?[2,2]:[1,1])),f=es(g,l.conv1,[1,1]),I=Dt.relu(Dt.add(g,f)),S=es(I,l.conv2,[1,1]),x=Dt.relu(Dt.add(g,Dt.add(f,S))),v=es(x,l.conv3,[1,1]);return Dt.relu(Dt.add(g,Dt.add(f,Dt.add(S,v))))})}const uo=Xe(Je());function ma(r,l,u="same",p=!1){return uo.tidy(()=>{const g=uo.add(uo.conv2d(r,l.filters,[1,1],u),l.bias);return p?uo.relu(g):g})}function zn(r,l){Object.keys(r).forEach(u=>{l.some(p=>p.originalPath===u)||r[u].dispose()})}const Ig=Xe(Je());function qc(r,l){return function(u,p,g,f){const I=Ig.tensor4d(r(u*p*g*g),[g,g,u,p]),S=Ig.tensor1d(r(p));return l.push({paramPath:`${f}/filters`},{paramPath:`${f}/bias`}),{filters:I,bias:S}}}const xg=Xe(Je());function Tg(r,l){return function(u,p,g){const f=xg.tensor2d(r(u*p),[u,p]),I=xg.tensor1d(r(p));return l.push({paramPath:`${g}/weights`},{paramPath:`${g}/bias`}),{weights:f,bias:I}}}class tx{constructor(r,l,u){this.depthwise_filter=r;this.pointwise_filter=l;this.bias=u}}const $u=Xe(Je());function jc(r,l){return function(u,p,g){const f=$u.tensor4d(r(3*3*u),[3,3,u,1]),I=$u.tensor4d(r(u*p),[1,1,u,p]),S=$u.tensor1d(r(p));return l.push({paramPath:`${g}/depthwise_filter`},{paramPath:`${g}/pointwise_filter`},{paramPath:`${g}/bias`}),new tx(f,I,S)}}function Kc(r){return function(l){const u=r(`${l}/depthwise_filter`,4),p=r(`${l}/pointwise_filter`,4),g=r(`${l}/bias`,1);return new tx(u,p,g)}}function ms(r,l){return function(u,p,g){const f=r[u];if(!na(f,p))throw new Error(`expected weightMap[${u}] to be a Tensor${p}D, instead have ${f}`);return l.push({originalPath:u,paramPath:g||u}),f}}function Gn(r){let l=r;function u(g){const f=l.slice(0,g);return l=l.slice(g),f}function p(){return l}return{extractWeights:u,getRemainingWeights:p}}function Ag(r,l){const u=qc(r,l),p=jc(r,l);function g(I,S,x,v=!1){const O=v?u(I,S,3,`${x}/conv0`):p(I,S,`${x}/conv0`),C=p(S,S,`${x}/conv1`),U=p(S,S,`${x}/conv2`);return{conv0:O,conv1:C,conv2:U}}function f(I,S,x,v=!1){const{conv0:O,conv1:C,conv2:U}=g(I,S,x,v),G=p(S,S,`${x}/conv3`);return{conv0:O,conv1:C,conv2:U,conv3:G}}return{extractDenseBlock3Params:g,extractDenseBlock4Params:f}}function oD(r){const l=[],{extractWeights:u,getRemainingWeights:p}=Gn(r),{extractDenseBlock4Params:g}=Ag(u,l),f=g(3,32,"dense0",!0),I=g(32,64,"dense1"),S=g(64,128,"dense2"),x=g(128,256,"dense3");if(p().length!==0)throw new Error(`weights remaing after extract: ${p().length}`);return{paramMappings:l,params:{dense0:f,dense1:I,dense2:S,dense3:x}}}function vg(r){return function(l){const u=r(`${l}/filters`,4),p=r(`${l}/bias`,1);return{filters:u,bias:p}}}function Ng(r,l){const u=ms(r,l),p=vg(u),g=Kc(u);function f(S,x=!1){const v=x?p(`${S}/conv0`):g(`${S}/conv0`),O=g(`${S}/conv1`),C=g(`${S}/conv2`);return{conv0:v,conv1:O,conv2:C}}function I(S,x=!1){const v=x?p(`${S}/conv0`):g(`${S}/conv0`),O=g(`${S}/conv1`),C=g(`${S}/conv2`),U=g(`${S}/conv3`);return{conv0:v,conv1:O,conv2:C,conv3:U}}return{extractDenseBlock3Params:f,extractDenseBlock4Params:I}}function aD(r){const l=[],{extractDenseBlock4Params:u}=Ng(r,l),p={dense0:u("dense0",!0),dense1:u("dense1"),dense2:u("dense2"),dense3:u("dense3")};return zn(r,l),{params:p,paramMappings:l}}const po=Xe(Je());class Cg extends In{constructor(){super("FaceFeatureExtractor")}forwardInput(r){const{params:l}=this;if(!l)throw new Error("FaceFeatureExtractor - load model before inference");return po.tidy(()=>{const u=po.cast(r.toBatchTensor(112,!0),"float32"),p=[122.782,117.001,104.298],g=Ys(u,p).div(po.scalar(255));let f=Wu(g,l.dense0,!0);return f=Wu(f,l.dense1),f=Wu(f,l.dense2),f=Wu(f,l.dense3),f=po.avgPool(f,[7,7],[2,2],"valid"),f})}async forward(r){return this.forwardInput(await Tt(r))}getDefaultModelName(){return"face_feature_extractor_model"}extractParamsFromWeigthMap(r){return aD(r)}extractParams(r){return oD(r)}}const Xc=Xe(Je());function Uu(r,l){return Xc.tidy(()=>Xc.add(Xc.matMul(r,l.weights),l.bias))}function cD(r,l,u){const p=[],{extractWeights:g,getRemainingWeights:f}=Gn(r),I=Tg(g,p),S=I(l,u,"fc");if(f().length!==0)throw new Error(`weights remaing after extract: ${f().length}`);return{paramMappings:p,params:{fc:S}}}function lD(r){const l=[],u=ms(r,l);function p(f){const I=u(`${f}/weights`,2),S=u(`${f}/bias`,1);return{weights:I,bias:S}}const g={fc:p("fc")};return zn(r,l),{params:g,paramMappings:l}}function Rg(r){const l={},u={};return Object.keys(r).forEach(p=>{const g=p.startsWith("fc")?u:l;g[p]=r[p]}),{featureExtractorMap:l,classifierMap:u}}const hD=Xe(Je());class Og extends In{constructor(r,l){super(r);this._faceFeatureExtractor=l}get faceFeatureExtractor(){return this._faceFeatureExtractor}runNet(r){const{params:l}=this;if(!l)throw new Error(`${this._name} - load model before inference`);return hD.tidy(()=>{const u=r instanceof hr?this.faceFeatureExtractor.forwardInput(r):r;return Uu(u.as2D(u.shape[0],-1),l.fc)})}dispose(r=!0){this.faceFeatureExtractor.dispose(r),super.dispose(r)}loadClassifierParams(r){const{params:l,paramMappings:u}=this.extractClassifierParams(r);this._params=l,this._paramMappings=u}extractClassifierParams(r){return cD(r,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())}extractParamsFromWeigthMap(r){const{featureExtractorMap:l,classifierMap:u}=Rg(r);return this.faceFeatureExtractor.loadFromWeightMap(l),lD(u)}extractParams(r){const l=this.getClassifierChannelsIn(),u=this.getClassifierChannelsOut(),p=u*l+u,g=r.slice(0,r.length-p),f=r.slice(r.length-p);return this.faceFeatureExtractor.extractWeights(g),this.extractClassifierParams(f)}}const Bm=["neutral","happy","sad","angry","fearful","disgusted","surprised"];class Qr{constructor(r){if(r.length!==7)throw new Error(`FaceExpressions.constructor - expected probabilities.length to be 7, have: ${r.length}`);Bm.forEach((l,u)=>{this[l]=r[u]})}asSortedArray(){return Bm.map(r=>({expression:r,probability:this[r]})).sort((r,l)=>l.probability-r.probability)}}const Jc=Xe(Je());class Mm extends Og{constructor(r=new Cg){super("FaceExpressionNet",r)}forwardInput(r){return Jc.tidy(()=>Jc.softmax(this.runNet(r)))}async forward(r){return this.forwardInput(await Tt(r))}async predictExpressions(r){const l=await Tt(r),u=await this.forwardInput(l),p=await Promise.all(Jc.unstack(u).map(async f=>{const I=await f.data();return f.dispose(),I}));u.dispose();const g=p.map(f=>new Qr(f));return l.isBatchInput?g:g[0]}getDefaultModelName(){return"face_expression_model"}getClassifierChannelsIn(){return 256}getClassifierChannelsOut(){return 7}}function $m(r){return r.expressions instanceof Qr}function fu(r,l){const u={expressions:l};return Object.assign({},r,u)}function bZ(r,l,u=.1,p){const g=Array.isArray(l)?l:[l];g.forEach(f=>{const I=f instanceof Qr?f:$m(f)?f.expressions:void 0;if(!I)throw new Error("drawFaceExpressions - expected faceExpressions to be FaceExpressions | WithFaceExpressions<{}> or array thereof");const S=I.asSortedArray(),x=S.filter(C=>C.probability>u),v=mi(f)?f.detection.box.bottomLeft:p||new qe(0,0),O=new Dc(x.map(C=>`${C.expression} (${sa(C.probability)})`),v);O.draw(r)})}function Jr(r){return mi(r)&&r.landmarks instanceof Ns&&r.unshiftedLandmarks instanceof Ns&&r.alignedRect instanceof Wt}function Jo(r,l){const{box:u}=r.detection,p=l.shiftBy(u.x,u.y),g=p.align(),{imageDims:f}=r.detection,I=new Wt(r.detection.score,g.rescale(f.reverse()),f),S={landmarks:p,unshiftedLandmarks:l,alignedRect:I};return Object.assign({},r,S)}class uD{constructor(r={}){const{drawLines:l=!0,drawPoints:u=!0,lineWidth:p,lineColor:g,pointSize:f,pointColor:I}=r;this.drawLines=l,this.drawPoints=u,this.lineWidth=p||1,this.pointSize=f||2,this.lineColor=g||"rgba(0, 255, 255, 1)",this.pointColor=I||"rgba(255, 0, 255, 1)"}}class dD{constructor(r,l={}){this.faceLandmarks=r,this.options=new uD(l)}draw(r){const l=Un(r),{drawLines:u,drawPoints:p,lineWidth:g,lineColor:f,pointSize:I,pointColor:S}=this.options;if(u&&this.faceLandmarks instanceof Rc&&(l.strokeStyle=f,l.lineWidth=g,ur(l,this.faceLandmarks.getJawOutline()),ur(l,this.faceLandmarks.getLeftEyeBrow()),ur(l,this.faceLandmarks.getRightEyeBrow()),ur(l,this.faceLandmarks.getNose()),ur(l,this.faceLandmarks.getLeftEye(),!0),ur(l,this.faceLandmarks.getRightEye(),!0),ur(l,this.faceLandmarks.getMouth(),!0)),p){l.strokeStyle=S,l.fillStyle=S;const x=v=>{l.beginPath(),l.arc(v.x,v.y,I,0,2*Math.PI),l.fill()};this.faceLandmarks.positions.forEach(x)}}}function wZ(r,l){const u=Array.isArray(l)?l:[l];u.forEach(p=>{const g=p instanceof Ns?p:Jr(p)?p.landmarks:void 0;if(!g)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof");new dD(g).draw(r)})}const Im={};uu(Im,{AnchorPosition:()=>Pi,DrawBox:()=>QS,DrawBoxOptions:()=>b2,DrawFaceLandmarks:()=>dD,DrawFaceLandmarksOptions:()=>uD,DrawTextField:()=>Dc,DrawTextFieldOptions:()=>Zm,drawContour:()=>ur,drawDetections:()=>E7,drawFaceExpressions:()=>bZ,drawFaceLandmarks:()=>wZ});function LZ(r,l){const u=qc(r,l),p=jc(r,l);function g(I,S,x){const v=p(I,S,`${x}/separable_conv0`),O=p(S,S,`${x}/separable_conv1`),C=u(I,S,1,`${x}/expansion_conv`);return{separable_conv0:v,separable_conv1:O,expansion_conv:C}}function f(I,S){const x=p(I,I,`${S}/separable_conv0`),v=p(I,I,`${S}/separable_conv1`),O=p(I,I,`${S}/separable_conv2`);return{separable_conv0:x,separable_conv1:v,separable_conv2:O}}return{extractConvParams:u,extractSeparableConvParams:p,extractReductionBlockParams:g,extractMainBlockParams:f}}function pD(r,l){const u=[],{extractWeights:p,getRemainingWeights:g}=Gn(r),{extractConvParams:f,extractSeparableConvParams:I,extractReductionBlockParams:S,extractMainBlockParams:x}=LZ(p,u),v=f(3,32,3,"entry_flow/conv_in"),O=S(32,64,"entry_flow/reduction_block_0"),C=S(64,128,"entry_flow/reduction_block_1"),U={conv_in:v,reduction_block_0:O,reduction_block_1:C},G={};Bi(l,0,1).forEach(ge=>{G[`main_block_${ge}`]=x(128,`middle_flow/main_block_${ge}`)});const ne=S(128,256,"exit_flow/reduction_block"),te=I(256,512,"exit_flow/separable_conv"),oe={reduction_block:ne,separable_conv:te};if(g().length!==0)throw new Error(`weights remaing after extract: ${g().length}`);return{paramMappings:u,params:{entry_flow:U,middle_flow:G,exit_flow:oe}}}function SZ(r,l){const u=ms(r,l),p=vg(u),g=Kc(u);function f(S){const x=g(`${S}/separable_conv0`),v=g(`${S}/separable_conv1`),O=p(`${S}/expansion_conv`);return{separable_conv0:x,separable_conv1:v,expansion_conv:O}}function I(S){const x=g(`${S}/separable_conv0`),v=g(`${S}/separable_conv1`),O=g(`${S}/separable_conv2`);return{separable_conv0:x,separable_conv1:v,separable_conv2:O}}return{extractConvParams:p,extractSeparableConvParams:g,extractReductionBlockParams:f,extractMainBlockParams:I}}function mD(r,l){const u=[],{extractConvParams:p,extractSeparableConvParams:g,extractReductionBlockParams:f,extractMainBlockParams:I}=SZ(r,u),S=p("entry_flow/conv_in"),x=f("entry_flow/reduction_block_0"),v=f("entry_flow/reduction_block_1"),O={conv_in:S,reduction_block_0:x,reduction_block_1:v},C={};Bi(l,0,1).forEach(te=>{C[`main_block_${te}`]=I(`middle_flow/main_block_${te}`)});const U=f("exit_flow/reduction_block"),G=g("exit_flow/separable_conv"),ne={reduction_block:U,separable_conv:G};return zn(r,u),{params:{entry_flow:O,middle_flow:C,exit_flow:ne},paramMappings:u}}const tn=Xe(Je());function fD(r,l,u){return tn.add(tn.conv2d(r,l.filters,u,"same"),l.bias)}function nx(r,l,u=!0){let p=u?tn.relu(r):r;return p=es(p,l.separable_conv0,[1,1]),p=es(tn.relu(p),l.separable_conv1,[1,1]),p=tn.maxPool(p,[3,3],[2,2],"same"),p=tn.add(p,fD(r,l.expansion_conv,[2,2])),p}function IZ(r,l){let u=es(tn.relu(r),l.separable_conv0,[1,1]);return u=es(tn.relu(u),l.separable_conv1,[1,1]),u=es(tn.relu(u),l.separable_conv2,[1,1]),u=tn.add(u,r),u}class gD extends In{constructor(r){super("TinyXception");this._numMainBlocks=r}forwardInput(r){const{params:l}=this;if(!l)throw new Error("TinyXception - load model before inference");return tn.tidy(()=>{const u=tn.cast(r.toBatchTensor(112,!0),"float32"),p=[122.782,117.001,104.298],g=Ys(u,p).div(tn.scalar(256));let f=tn.relu(fD(g,l.entry_flow.conv_in,[2,2]));return f=nx(f,l.entry_flow.reduction_block_0,!1),f=nx(f,l.entry_flow.reduction_block_1),Bi(this._numMainBlocks,0,1).forEach(I=>{f=IZ(f,l.middle_flow[`main_block_${I}`])}),f=nx(f,l.exit_flow.reduction_block),f=tn.relu(es(f,l.exit_flow.separable_conv,[1,1])),f})}async forward(r){return this.forwardInput(await Tt(r))}getDefaultModelName(){return"tiny_xception_model"}extractParamsFromWeigthMap(r){return mD(r,this._numMainBlocks)}extractParams(r){return pD(r,this._numMainBlocks)}}function yD(r){const l=[],{extractWeights:u,getRemainingWeights:p}=Gn(r),g=Tg(u,l),f=g(512,1,"fc/age"),I=g(512,2,"fc/gender");if(p().length!==0)throw new Error(`weights remaing after extract: ${p().length}`);return{paramMappings:l,params:{fc:{age:f,gender:I}}}}function bD(r){const l=[],u=ms(r,l);function p(f){const I=u(`${f}/weights`,2),S=u(`${f}/bias`,1);return{weights:I,bias:S}}const g={fc:{age:p("fc/age"),gender:p("fc/gender")}};return zn(r,l),{params:g,paramMappings:l}}var Ui;(function(r){r.FEMALE="female",r.MALE="male"})(Ui||(Ui={}));const Hi=Xe(Je());class jm extends In{constructor(r=new gD(2)){super("AgeGenderNet");this._faceFeatureExtractor=r}get faceFeatureExtractor(){return this._faceFeatureExtractor}runNet(r){const{params:l}=this;if(!l)throw new Error(`${this._name} - load model before inference`);return Hi.tidy(()=>{const u=r instanceof hr?this.faceFeatureExtractor.forwardInput(r):r,p=Hi.avgPool(u,[7,7],[2,2],"valid").as2D(u.shape[0],-1),g=Uu(p,l.fc.age).as1D(),f=Uu(p,l.fc.gender);return{age:g,gender:f}})}forwardInput(r){return Hi.tidy(()=>{const{age:l,gender:u}=this.runNet(r);return{age:l,gender:Hi.softmax(u)}})}async forward(r){return this.forwardInput(await Tt(r))}async predictAgeAndGender(r){const l=await Tt(r),u=await this.forwardInput(l),p=Hi.unstack(u.age),g=Hi.unstack(u.gender),f=p.map((S,x)=>({ageTensor:S,genderTensor:g[x]})),I=await Promise.all(f.map(async({ageTensor:S,genderTensor:x})=>{const v=(await S.data())[0],O=(await x.data())[0],C=O>.5,U=C?Ui.MALE:Ui.FEMALE,G=C?O:1-O;return S.dispose(),x.dispose(),{age:v,gender:U,genderProbability:G}}));return u.age.dispose(),u.gender.dispose(),l.isBatchInput?I:I[0]}getDefaultModelName(){return"age_gender_model"}dispose(r=!0){this.faceFeatureExtractor.dispose(r),super.dispose(r)}loadClassifierParams(r){const{params:l,paramMappings:u}=this.extractClassifierParams(r);this._params=l,this._paramMappings=u}extractClassifierParams(r){return yD(r)}extractParamsFromWeigthMap(r){const{featureExtractorMap:l,classifierMap:u}=Rg(r);return this.faceFeatureExtractor.loadFromWeightMap(l),bD(u)}extractParams(r){const l=512*1+1+(512*2+2),u=r.slice(0,r.length-l),p=r.slice(r.length-l);return this.faceFeatureExtractor.extractWeights(u),this.extractClassifierParams(p)}}const fs=Xe(Je());class Eg extends Og{postProcess(r,l,u){const p=u.map(({width:f,height:I})=>{const S=l/Math.max(I,f);return{width:f*S,height:I*S}}),g=p.length;return fs.tidy(()=>{const f=(O,C)=>fs.stack([fs.fill([68],O,"float32"),fs.fill([68],C,"float32")],1).as2D(1,136).as1D(),I=(O,C)=>{const{width:U,height:G}=p[O];return C(U,G)?Math.abs(U-G)/2:0},S=O=>I(O,(C,U)=>C<U),x=O=>I(O,(C,U)=>U<C),v=r.mul(fs.fill([g,136],l,"float32")).sub(fs.stack(Array.from(Array(g),(O,C)=>f(S(C),x(C))))).div(fs.stack(Array.from(Array(g),(O,C)=>f(p[C].width,p[C].height))));return v})}forwardInput(r){return fs.tidy(()=>{const l=this.runNet(r);return this.postProcess(l,r.inputSize,r.inputDimensions.map(([u,p])=>({height:u,width:p})))})}async forward(r){return this.forwardInput(await Tt(r))}async detectLandmarks(r){const l=await Tt(r),u=fs.tidy(()=>fs.unstack(this.forwardInput(l))),p=await Promise.all(u.map(async(g,f)=>{const I=Array.from(await g.data()),S=I.filter((v,O)=>Km(O)),x=I.filter((v,O)=>!Km(O));return new Rc(Array(68).fill(0).map((v,O)=>new qe(S[O],x[O])),{height:l.getInputHeight(f),width:l.getInputWidth(f)})}));return u.forEach(g=>g.dispose()),l.isBatchInput?p:p[0]}getClassifierChannelsOut(){return 136}}class Ac extends Eg{constructor(r=new Cg){super("FaceLandmark68Net",r)}getDefaultModelName(){return"face_landmark_68_model"}getClassifierChannelsIn(){return 256}}function wD(r){const l=[],{extractDenseBlock3Params:u}=Ng(r,l),p={dense0:u("dense0",!0),dense1:u("dense1"),dense2:u("dense2")};return zn(r,l),{params:p,paramMappings:l}}function LD(r){const l=[],{extractWeights:u,getRemainingWeights:p}=Gn(r),{extractDenseBlock3Params:g}=Ag(u,l),f=g(3,32,"dense0",!0),I=g(32,64,"dense1"),S=g(64,128,"dense2");if(p().length!==0)throw new Error(`weights remaing after extract: ${p().length}`);return{paramMappings:l,params:{dense0:f,dense1:I,dense2:S}}}const mo=Xe(Je());class SD extends In{constructor(){super("TinyFaceFeatureExtractor")}forwardInput(r){const{params:l}=this;if(!l)throw new Error("TinyFaceFeatureExtractor - load model before inference");return mo.tidy(()=>{const u=mo.cast(r.toBatchTensor(112,!0),"float32"),p=[122.782,117.001,104.298],g=Ys(u,p).div(mo.scalar(255));let f=Sg(g,l.dense0,!0);return f=Sg(f,l.dense1),f=Sg(f,l.dense2),f=mo.avgPool(f,[14,14],[2,2],"valid"),f})}async forward(r){return this.forwardInput(await Tt(r))}getDefaultModelName(){return"face_feature_extractor_tiny_model"}extractParamsFromWeigthMap(r){return wD(r)}extractParams(r){return LD(r)}}class Um extends Eg{constructor(r=new SD){super("FaceLandmark68TinyNet",r)}getDefaultModelName(){return"face_landmark_68_tiny_model"}getClassifierChannelsIn(){return 128}}class h2 extends Ac{}const Dg=Xe(Je());function ID(r,l){return Dg.add(Dg.mul(r,l.weights),l.biases)}const Zc=Xe(Je());function sx(r,l,u,p,g="same"){const{filters:f,bias:I}=l.conv;let S=Zc.conv2d(r,f,u,g);return S=Zc.add(S,I),S=ID(S,l.scale),p?Zc.relu(S):S}function xD(r,l){return sx(r,l,[1,1],!0)}function ix(r,l){return sx(r,l,[1,1],!1)}function kg(r,l){return sx(r,l,[2,2],!0,"valid")}const gs=Xe(Je());function xZ(r,l){function u(S,x,v){const O=r(S),C=O.length/(x*v*v);if(YS(C))throw new Error(`depth has to be an integer: ${C}, weights.length: ${O.length}, numFilters: ${x}, filterSize: ${v}`);return gs.tidy(()=>gs.transpose(gs.tensor4d(O,[x,C,v,v]),[2,3,1,0]))}function p(S,x,v,O){const C=u(S,x,v),U=gs.tensor1d(r(x));return l.push({paramPath:`${O}/filters`},{paramPath:`${O}/bias`}),{filters:C,bias:U}}function g(S,x){const v=gs.tensor1d(r(S)),O=gs.tensor1d(r(S));return l.push({paramPath:`${x}/weights`},{paramPath:`${x}/biases`}),{weights:v,biases:O}}function f(S,x,v,O){const C=p(S,x,v,`${O}/conv`),U=g(x,`${O}/scale`);return{conv:C,scale:U}}function I(S,x,v,O,C=!1){const U=f((C?.5:1)*S,x,v,`${O}/conv1`),G=f(S,x,v,`${O}/conv2`);return{conv1:U,conv2:G}}return{extractConvLayerParams:f,extractResidualLayerParams:I}}function TD(r){const{extractWeights:l,getRemainingWeights:u}=Gn(r),p=[],{extractConvLayerParams:g,extractResidualLayerParams:f}=xZ(l,p),I=g(4704,32,7,"conv32_down"),S=f(9216,32,3,"conv32_1"),x=f(9216,32,3,"conv32_2"),v=f(9216,32,3,"conv32_3"),O=f(36864,64,3,"conv64_down",!0),C=f(36864,64,3,"conv64_1"),U=f(36864,64,3,"conv64_2"),G=f(36864,64,3,"conv64_3"),ne=f(147456,128,3,"conv128_down",!0),te=f(147456,128,3,"conv128_1"),oe=f(147456,128,3,"conv128_2"),ge=f(589824,256,3,"conv256_down",!0),fe=f(589824,256,3,"conv256_1"),Ae=f(589824,256,3,"conv256_2"),Te=f(589824,256,3,"conv256_down_out"),Ve=gs.tidy(()=>gs.transpose(gs.tensor2d(l(256*128),[128,256]),[1,0]));if(p.push({paramPath:"fc"}),u().length!==0)throw new Error(`weights remaing after extract: ${u().length}`);const rt={conv32_down:I,conv32_1:S,conv32_2:x,conv32_3:v,conv64_down:O,conv64_1:C,conv64_2:U,conv64_3:G,conv128_down:ne,conv128_1:te,conv128_2:oe,conv256_down:ge,conv256_1:fe,conv256_2:Ae,conv256_down_out:Te,fc:Ve};return{params:rt,paramMappings:p}}function TZ(r,l){const u=ms(r,l);function p(I){const S=u(`${I}/scale/weights`,1),x=u(`${I}/scale/biases`,1);return{weights:S,biases:x}}function g(I){const S=u(`${I}/conv/filters`,4),x=u(`${I}/conv/bias`,1),v=p(I);return{conv:{filters:S,bias:x},scale:v}}function f(I){return{conv1:g(`${I}/conv1`),conv2:g(`${I}/conv2`)}}return{extractConvLayerParams:g,extractResidualLayerParams:f}}function AD(r){const l=[],{extractConvLayerParams:u,extractResidualLayerParams:p}=TZ(r,l),g=u("conv32_down"),f=p("conv32_1"),I=p("conv32_2"),S=p("conv32_3"),x=p("conv64_down"),v=p("conv64_1"),O=p("conv64_2"),C=p("conv64_3"),U=p("conv128_down"),G=p("conv128_1"),ne=p("conv128_2"),te=p("conv256_down"),oe=p("conv256_1"),ge=p("conv256_2"),fe=p("conv256_down_out"),Ae=r.fc;if(l.push({originalPath:"fc",paramPath:"fc"}),!VS(Ae))throw new Error(`expected weightMap[fc] to be a Tensor2D, instead have ${Ae}`);const Te={conv32_down:g,conv32_1:f,conv32_2:I,conv32_3:S,conv64_down:x,conv64_1:v,conv64_2:O,conv64_3:C,conv128_down:U,conv128_1:G,conv128_2:ne,conv256_down:te,conv256_1:oe,conv256_2:ge,conv256_down_out:fe,fc:Ae};return zn(r,l),{params:Te,paramMappings:l}}const Vn=Xe(Je());function bi(r,l){let u=xD(r,l.conv1);return u=ix(u,l.conv2),u=Vn.add(u,r),u=Vn.relu(u),u}function Bu(r,l){let u=kg(r,l.conv1);u=ix(u,l.conv2);let p=Vn.avgPool(r,2,2,"valid");const g=Vn.zeros(p.shape),f=p.shape[3]!==u.shape[3],I=p.shape[1]!==u.shape[1]||p.shape[2]!==u.shape[2];if(I){const S=[...u.shape];S[1]=1;const x=Vn.zeros(S);u=Vn.concat([u,x],1);const v=[...u.shape];v[2]=1;const O=Vn.zeros(v);u=Vn.concat([u,O],2)}return p=f?Vn.concat([p,g],3):p,u=Vn.add(p,u),u=Vn.relu(u),u}const ks=Xe(Je());class Tc extends In{constructor(){super("FaceRecognitionNet")}forwardInput(r){const{params:l}=this;if(!l)throw new Error("FaceRecognitionNet - load model before inference");return ks.tidy(()=>{const u=ks.cast(r.toBatchTensor(150,!0),"float32"),p=[122.782,117.001,104.298],g=Ys(u,p).div(ks.scalar(256));let f=kg(g,l.conv32_down);f=ks.maxPool(f,3,2,"valid"),f=bi(f,l.conv32_1),f=bi(f,l.conv32_2),f=bi(f,l.conv32_3),f=Bu(f,l.conv64_down),f=bi(f,l.conv64_1),f=bi(f,l.conv64_2),f=bi(f,l.conv64_3),f=Bu(f,l.conv128_down),f=bi(f,l.conv128_1),f=bi(f,l.conv128_2),f=Bu(f,l.conv256_down),f=bi(f,l.conv256_1),f=bi(f,l.conv256_2),f=Bu(f,l.conv256_down_out);const I=f.mean([1,2]),S=ks.matMul(I,l.fc);return S})}async forward(r){return this.forwardInput(await Tt(r))}async computeFaceDescriptor(r){const l=await Tt(r),u=ks.tidy(()=>ks.unstack(this.forwardInput(l))),p=await Promise.all(u.map(g=>g.data()));return u.forEach(g=>g.dispose()),l.isBatchInput?p:p[0]}getDefaultModelName(){return"face_recognition_model"}extractParamsFromWeigthMap(r){return AD(r)}extractParams(r){return TD(r)}}function l2(r){const l=new Tc;return l.extractWeights(r),l}function gu(r,l){const u={descriptor:l};return Object.assign({},r,u)}function c2(r){return typeof r.age=="number"}function yu(r,l){const u={age:l};return Object.assign({},r,u)}function a2(r){return(r.gender===Ui.MALE||r.gender===Ui.FEMALE)&&Ec(r.genderProbability)}function mu(r,l,u){const p={gender:l,genderProbability:u};return Object.assign({},r,p)}const wi=Xe(Je());function AZ(r,l){function u(x,v){const O=wi.tensor4d(r(3*3*x),[3,3,x,1]),C=wi.tensor1d(r(x)),U=wi.tensor1d(r(x)),G=wi.tensor1d(r(x)),ne=wi.tensor1d(r(x));return l.push({paramPath:`${v}/filters`},{paramPath:`${v}/batch_norm_scale`},{paramPath:`${v}/batch_norm_offset`},{paramPath:`${v}/batch_norm_mean`},{paramPath:`${v}/batch_norm_variance`}),{filters:O,batch_norm_scale:C,batch_norm_offset:U,batch_norm_mean:G,batch_norm_variance:ne}}function p(x,v,O,C,U){const G=wi.tensor4d(r(x*v*O*O),[O,O,x,v]),ne=wi.tensor1d(r(v));return l.push({paramPath:`${C}/filters`},{paramPath:`${C}/${U?"batch_norm_offset":"bias"}`}),{filters:G,bias:ne}}function g(x,v,O,C){const{filters:U,bias:G}=p(x,v,O,C,!0);return{filters:U,batch_norm_offset:G}}function f(x,v,O){const C=u(x,`${O}/depthwise_conv`),U=g(x,v,1,`${O}/pointwise_conv`);return{depthwise_conv:C,pointwise_conv:U}}function I(){const x=g(3,32,3,"mobilenetv1/conv_0"),v=f(32,64,"mobilenetv1/conv_1"),O=f(64,128,"mobilenetv1/conv_2"),C=f(128,128,"mobilenetv1/conv_3"),U=f(128,256,"mobilenetv1/conv_4"),G=f(256,256,"mobilenetv1/conv_5"),ne=f(256,512,"mobilenetv1/conv_6"),te=f(512,512,"mobilenetv1/conv_7"),oe=f(512,512,"mobilenetv1/conv_8"),ge=f(512,512,"mobilenetv1/conv_9"),fe=f(512,512,"mobilenetv1/conv_10"),Ae=f(512,512,"mobilenetv1/conv_11"),Te=f(512,1024,"mobilenetv1/conv_12"),Ve=f(1024,1024,"mobilenetv1/conv_13");return{conv_0:x,conv_1:v,conv_2:O,conv_3:C,conv_4:U,conv_5:G,conv_6:ne,conv_7:te,conv_8:oe,conv_9:ge,conv_10:fe,conv_11:Ae,conv_12:Te,conv_13:Ve}}function S(){const x=g(1024,256,1,"prediction_layer/conv_0"),v=g(256,512,3,"prediction_layer/conv_1"),O=g(512,128,1,"prediction_layer/conv_2"),C=g(128,256,3,"prediction_layer/conv_3"),U=g(256,128,1,"prediction_layer/conv_4"),G=g(128,256,3,"prediction_layer/conv_5"),ne=g(256,64,1,"prediction_layer/conv_6"),te=g(64,128,3,"prediction_layer/conv_7"),oe=p(512,12,1,"prediction_layer/box_predictor_0/box_encoding_predictor"),ge=p(512,9,1,"prediction_layer/box_predictor_0/class_predictor"),fe=p(1024,24,1,"prediction_layer/box_predictor_1/box_encoding_predictor"),Ae=p(1024,18,1,"prediction_layer/box_predictor_1/class_predictor"),Te=p(512,24,1,"prediction_layer/box_predictor_2/box_encoding_predictor"),Ve=p(512,18,1,"prediction_layer/box_predictor_2/class_predictor"),rt=p(256,24,1,"prediction_layer/box_predictor_3/box_encoding_predictor"),Ct=p(256,18,1,"prediction_layer/box_predictor_3/class_predictor"),Ut=p(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),Kt=p(256,18,1,"prediction_layer/box_predictor_4/class_predictor"),Dn=p(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),An=p(128,18,1,"prediction_layer/box_predictor_5/class_predictor"),vn={box_encoding_predictor:oe,class_predictor:ge},Zs={box_encoding_predictor:fe,class_predictor:Ae},Si={box_encoding_predictor:Te,class_predictor:Ve},Qs={box_encoding_predictor:rt,class_predictor:Ct},ya={box_encoding_predictor:Ut,class_predictor:Kt},ol={box_encoding_predictor:Dn,class_predictor:An};return{conv_0:x,conv_1:v,conv_2:O,conv_3:C,conv_4:U,conv_5:G,conv_6:ne,conv_7:te,box_predictor_0:vn,box_predictor_1:Zs,box_predictor_2:Si,box_predictor_3:Qs,box_predictor_4:ya,box_predictor_5:ol}}return{extractMobilenetV1Params:I,extractPredictionLayerParams:S}}function vD(r){const l=[],{extractWeights:u,getRemainingWeights:p}=Gn(r),{extractMobilenetV1Params:g,extractPredictionLayerParams:f}=AZ(u,l),I=g(),S=f(),x=wi.tensor3d(u(5118*4),[1,5118,4]),v={extra_dim:x};if(l.push({paramPath:"output_layer/extra_dim"}),p().length!==0)throw new Error(`weights remaing after extract: ${p().length}`);return{params:{mobilenetv1:I,prediction_layer:S,output_layer:v},paramMappings:l}}function vZ(r,l){const u=ms(r,l);function p(v,O,C){const U=u(`${v}/Conv2d_${O}_pointwise/weights`,4,`${C}/filters`),G=u(`${v}/Conv2d_${O}_pointwise/convolution_bn_offset`,1,`${C}/batch_norm_offset`);return{filters:U,batch_norm_offset:G}}function g(v){const O=`mobilenetv1/conv_${v}`,C=`MobilenetV1/Conv2d_${v}_depthwise`,U=`${O}/depthwise_conv`,G=`${O}/pointwise_conv`,ne=u(`${C}/depthwise_weights`,4,`${U}/filters`),te=u(`${C}/BatchNorm/gamma`,1,`${U}/batch_norm_scale`),oe=u(`${C}/BatchNorm/beta`,1,`${U}/batch_norm_offset`),ge=u(`${C}/BatchNorm/moving_mean`,1,`${U}/batch_norm_mean`),fe=u(`${C}/BatchNorm/moving_variance`,1,`${U}/batch_norm_variance`);return{depthwise_conv:{filters:ne,batch_norm_scale:te,batch_norm_offset:oe,batch_norm_mean:ge,batch_norm_variance:fe},pointwise_conv:p("MobilenetV1",v,G)}}function f(){return{conv_0:p("MobilenetV1",0,"mobilenetv1/conv_0"),conv_1:g(1),conv_2:g(2),conv_3:g(3),conv_4:g(4),conv_5:g(5),conv_6:g(6),conv_7:g(7),conv_8:g(8),conv_9:g(9),conv_10:g(10),conv_11:g(11),conv_12:g(12),conv_13:g(13)}}function I(v,O){const C=u(`${v}/weights`,4,`${O}/filters`),U=u(`${v}/biases`,1,`${O}/bias`);return{filters:C,bias:U}}function S(v){const O=I(`Prediction/BoxPredictor_${v}/BoxEncodingPredictor`,`prediction_layer/box_predictor_${v}/box_encoding_predictor`),C=I(`Prediction/BoxPredictor_${v}/ClassPredictor`,`prediction_layer/box_predictor_${v}/class_predictor`);return{box_encoding_predictor:O,class_predictor:C}}function x(){return{conv_0:p("Prediction",0,"prediction_layer/conv_0"),conv_1:p("Prediction",1,"prediction_layer/conv_1"),conv_2:p("Prediction",2,"prediction_layer/conv_2"),conv_3:p("Prediction",3,"prediction_layer/conv_3"),conv_4:p("Prediction",4,"prediction_layer/conv_4"),conv_5:p("Prediction",5,"prediction_layer/conv_5"),conv_6:p("Prediction",6,"prediction_layer/conv_6"),conv_7:p("Prediction",7,"prediction_layer/conv_7"),box_predictor_0:S(0),box_predictor_1:S(1),box_predictor_2:S(2),box_predictor_3:S(3),box_predictor_4:S(4),box_predictor_5:S(5)}}return{extractMobilenetV1Params:f,extractPredictionLayerParams:x}}function ND(r){const l=[],{extractMobilenetV1Params:u,extractPredictionLayerParams:p}=vZ(r,l),g=r["Output/extra_dim"];if(l.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!dr(g))throw new Error(`expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have ${g}`);const f={mobilenetv1:u(),prediction_layer:p(),output_layer:{extra_dim:g}};return zn(r,l),{params:f,paramMappings:l}}const fo=Xe(Je());function Ks(r,l,u){return fo.tidy(()=>{let p=fo.conv2d(r,l.filters,u,"same");return p=fo.add(p,l.batch_norm_offset),fo.clipByValue(p,0,6)})}const wr=Xe(Je()),NZ=.0010000000474974513;function CZ(r,l,u){return wr.tidy(()=>{let p=wr.depthwiseConv2d(r,l.filters,u,"same");return p=wr.batchNorm(p,l.batch_norm_mean,l.batch_norm_variance,l.batch_norm_offset,l.batch_norm_scale,NZ),wr.clipByValue(p,0,6)})}function RZ(r){return[2,4,6,12].some(l=>l===r)?[2,2]:[1,1]}function CD(r,l){return wr.tidy(()=>{let u,p=Ks(r,l.conv_0,[2,2]);const g=[l.conv_1,l.conv_2,l.conv_3,l.conv_4,l.conv_5,l.conv_6,l.conv_7,l.conv_8,l.conv_9,l.conv_10,l.conv_11,l.conv_12,l.conv_13];if(g.forEach((f,I)=>{const S=I+1,x=RZ(S);p=CZ(p,f.depthwise_conv,x),p=Ks(p,f.pointwise_conv,[1,1]),S===11&&(u=p)}),u===null)throw new Error("mobileNetV1 - output of conv layer 11 is null");return{out:p,conv11:u}})}function RD(r,l,u,p,g){const f=r.shape[0],I=Math.min(u,f),S=l.map((O,C)=>({score:O,boxIndex:C})).filter(O=>O.score>g).sort((O,C)=>C.score-O.score),x=O=>O<=p?1:0,v=[];return S.forEach(O=>{if(v.length>=I)return;const C=O.score;for(let U=v.length-1;U>=0;--U){const G=OZ(r,O.boxIndex,v[U]);if(G===0)continue;if(O.score*=x(G),O.score<=g)break}C===O.score&&v.push(O.boxIndex)}),v}function OZ(r,l,u){const p=r.arraySync(),g=Math.min(p[l][0],p[l][2]),f=Math.min(p[l][1],p[l][3]),I=Math.max(p[l][0],p[l][2]),S=Math.max(p[l][1],p[l][3]),x=Math.min(p[u][0],p[u][2]),v=Math.min(p[u][1],p[u][3]),O=Math.max(p[u][0],p[u][2]),C=Math.max(p[u][1],p[u][3]),U=(I-g)*(S-f),G=(O-x)*(C-v);if(U<=0||G<=0)return 0;const ne=Math.max(g,x),te=Math.max(f,v),oe=Math.min(I,O),ge=Math.min(S,C),fe=Math.max(oe-ne,0)*Math.max(ge-te,0);return fe/(U+G-fe)}const De=Xe(Je());function EZ(r){const l=De.unstack(De.transpose(r,[1,0])),u=[De.sub(l[2],l[0]),De.sub(l[3],l[1])],p=[De.add(l[0],De.div(u[0],De.scalar(2))),De.add(l[1],De.div(u[1],De.scalar(2)))];return{sizes:u,centers:p}}function DZ(r,l){const{sizes:u,centers:p}=EZ(r),g=De.unstack(De.transpose(l,[1,0])),f=De.div(De.mul(De.exp(De.div(g[2],De.scalar(5))),u[0]),De.scalar(2)),I=De.add(De.mul(De.div(g[0],De.scalar(10)),u[0]),p[0]),S=De.div(De.mul(De.exp(De.div(g[3],De.scalar(5))),u[1]),De.scalar(2)),x=De.add(De.mul(De.div(g[1],De.scalar(10)),u[1]),p[1]);return De.transpose(De.stack([De.sub(I,f),De.sub(x,S),De.add(I,f),De.add(x,S)]),[1,0])}function OD(r,l,u){return De.tidy(()=>{const p=r.shape[0];let g=DZ(De.reshape(De.tile(u.extra_dim,[p,1,1]),[-1,4]),De.reshape(r,[-1,4]));g=De.reshape(g,[p,g.shape[0]/p,4]);const f=De.sigmoid(De.slice(l,[0,0,1],[-1,-1,-1]));let I=De.slice(f,[0,0,0],[-1,-1,1]);I=De.reshape(I,[p,I.shape[1]]);const S=De.unstack(g),x=De.unstack(I);return{boxes:S,scores:x}})}const Mu=Xe(Je());function fa(r,l){return Mu.tidy(()=>{const u=r.shape[0],p=Mu.reshape(ma(r,l.box_encoding_predictor),[u,-1,1,4]),g=Mu.reshape(ma(r,l.class_predictor),[u,-1,3]);return{boxPredictionEncoding:p,classPrediction:g}})}const Pu=Xe(Je());function ED(r,l,u){return Pu.tidy(()=>{const p=Ks(r,u.conv_0,[1,1]),g=Ks(p,u.conv_1,[2,2]),f=Ks(g,u.conv_2,[1,1]),I=Ks(f,u.conv_3,[2,2]),S=Ks(I,u.conv_4,[1,1]),x=Ks(S,u.conv_5,[2,2]),v=Ks(x,u.conv_6,[1,1]),O=Ks(v,u.conv_7,[2,2]),C=fa(l,u.box_predictor_0),U=fa(r,u.box_predictor_1),G=fa(g,u.box_predictor_2),ne=fa(I,u.box_predictor_3),te=fa(x,u.box_predictor_4),oe=fa(O,u.box_predictor_5),ge=Pu.concat([C.boxPredictionEncoding,U.boxPredictionEncoding,G.boxPredictionEncoding,ne.boxPredictionEncoding,te.boxPredictionEncoding,oe.boxPredictionEncoding],1),fe=Pu.concat([C.classPrediction,U.classPrediction,G.classPrediction,ne.classPrediction,te.classPrediction,oe.classPrediction],1);return{boxPredictions:ge,classPredictions:fe}})}class Vs{constructor({minConfidence:r,maxResults:l}={}){this._name="SsdMobilenetv1Options";if(this._minConfidence=r||.5,this._maxResults=l||100,typeof this._minConfidence!="number"||this._minConfidence<=0||this._minConfidence>=1)throw new Error(`${this._name} - expected minConfidence to be a number between 0 and 1`);if(typeof this._maxResults!="number")throw new Error(`${this._name} - expected maxResults to be a number`)}get minConfidence(){return this._minConfidence}get maxResults(){return this._maxResults}}const Li=Xe(Je());class Xo extends In{constructor(){super("SsdMobilenetv1")}forwardInput(r){const{params:l}=this;if(!l)throw new Error("SsdMobilenetv1 - load model before inference");return Li.tidy(()=>{const u=Li.cast(r.toBatchTensor(512,!1),"float32"),p=Li.sub(Li.mul(u,Li.scalar(.007843137718737125)),Li.scalar(1)),g=CD(p,l.mobilenetv1),{boxPredictions:f,classPredictions:I}=ED(g.out,g.conv11,l.prediction_layer);return OD(f,I,l.output_layer)})}async forward(r){return this.forwardInput(await Tt(r))}async locateFaces(r,l={}){const{maxResults:u,minConfidence:p}=new Vs(l),g=await Tt(r),{boxes:f,scores:I}=this.forwardInput(g),S=f[0],x=I[0];for(let fe=1;fe<f.length;fe++)f[fe].dispose(),I[fe].dispose();const v=Array.from(await x.data()),O=.5,C=RD(S,v,u,O,p),U=g.getReshapedInputDimensions(0),G=g.inputSize,ne=G/U.width,te=G/U.height,oe=S.arraySync(),ge=C.map(fe=>{const[Ae,Te]=[Math.max(0,oe[fe][0]),Math.min(1,oe[fe][2])].map(Ct=>Ct*te),[Ve,rt]=[Math.max(0,oe[fe][1]),Math.min(1,oe[fe][3])].map(Ct=>Ct*ne);return new Wt(v[fe],new Cc(Ve,Ae,rt-Ve,Te-Ae),{height:g.getInputHeight(0),width:g.getInputWidth(0)})});return S.dispose(),x.dispose(),ge}getDefaultModelName(){return"ssd_mobilenetv1_model"}extractParamsFromWeigthMap(r){return ND(r)}extractParams(r){return vD(r)}}function $S(r){const l=new Xo;return l.extractWeights(r),l}function UC(r){return $S(r)}class BC extends Xo{}const DD=.4,kD=[new qe(.738768,.874946),new qe(2.42204,2.65704),new qe(4.30971,7.04493),new qe(10.246,4.59428),new qe(12.6868,11.8741)],FD=[new qe(1.603231,2.094468),new qe(6.041143,7.080126),new qe(2.882459,3.518061),new qe(4.266906,5.178857),new qe(9.041765,10.66308)],_D=[117.001,114.697,97.404],WD="tiny_yolov2_model",$D="tiny_yolov2_separable_conv_model";const Fg=r=>typeof r=="number";function Tm(r){if(!r)throw new Error(`invalid config: ${r}`);if(typeof r.withSeparableConvs!="boolean")throw new Error(`config.withSeparableConvs has to be a boolean, have: ${r.withSeparableConvs}`);if(!Fg(r.iouThreshold)||r.iouThreshold<0||r.iouThreshold>1)throw new Error(`config.iouThreshold has to be a number between [0, 1], have: ${r.iouThreshold}`);if(!Array.isArray(r.classes)||!r.classes.length||!r.classes.every(l=>typeof l=="string"))throw new Error(`config.classes has to be an array class names: string[], have: ${JSON.stringify(r.classes)}`);if(!Array.isArray(r.anchors)||!r.anchors.length||!r.anchors.map(l=>l||{}).every(l=>Fg(l.x)&&Fg(l.y)))throw new Error(`config.anchors has to be an array of { x: number, y: number }, have: ${JSON.stringify(r.anchors)}`);if(r.meanRgb&&(!Array.isArray(r.meanRgb)||r.meanRgb.length!==3||!r.meanRgb.every(Fg)))throw new Error(`config.meanRgb has to be an array of shape [number, number, number], have: ${JSON.stringify(r.meanRgb)}`)}const Xs=Xe(Je());function Qc(r){return Xs.tidy(()=>{const l=Xs.mul(r,Xs.scalar(.10000000149011612));return Xs.add(Xs.relu(Xs.sub(r,l)),l)})}const Js=Xe(Je());function Lr(r,l){return Js.tidy(()=>{let u=Js.pad(r,[[0,0],[1,1],[1,1],[0,0]]);return u=Js.conv2d(u,l.conv.filters,[1,1],"valid"),u=Js.sub(u,l.bn.sub),u=Js.mul(u,l.bn.truediv),u=Js.add(u,l.conv.bias),Qc(u)})}const go=Xe(Je());function Sr(r,l){return go.tidy(()=>{let u=go.pad(r,[[0,0],[1,1],[1,1],[0,0]]);return u=go.separableConv2d(u,l.depthwise_filter,l.pointwise_filter,[1,1],"valid"),u=go.add(u,l.bias),Qc(u)})}const rx=Xe(Je());function kZ(r,l){const u=qc(r,l);function p(I,S){const x=rx.tensor1d(r(I)),v=rx.tensor1d(r(I));return l.push({paramPath:`${S}/sub`},{paramPath:`${S}/truediv`}),{sub:x,truediv:v}}function g(I,S,x){const v=u(I,S,3,`${x}/conv`),O=p(S,`${x}/bn`);return{conv:v,bn:O}}const f=jc(r,l);return{extractConvParams:u,extractConvWithBatchNormParams:g,extractSeparableConvParams:f}}function UD(r,l,u,p){const{extractWeights:g,getRemainingWeights:f}=Gn(r),I=[],{extractConvParams:S,extractConvWithBatchNormParams:x,extractSeparableConvParams:v}=kZ(g,I);let O;if(l.withSeparableConvs){const[C,U,G,ne,te,oe,ge,fe,Ae]=p,Te=l.isFirstLayerConv2d?S(C,U,3,"conv0"):v(C,U,"conv0"),Ve=v(U,G,"conv1"),rt=v(G,ne,"conv2"),Ct=v(ne,te,"conv3"),Ut=v(te,oe,"conv4"),Kt=v(oe,ge,"conv5"),Dn=fe?v(ge,fe,"conv6"):void 0,An=Ae?v(fe,Ae,"conv7"):void 0,vn=S(Ae||fe||ge,5*u,1,"conv8");O={conv0:Te,conv1:Ve,conv2:rt,conv3:Ct,conv4:Ut,conv5:Kt,conv6:Dn,conv7:An,conv8:vn}}else{const[C,U,G,ne,te,oe,ge,fe,Ae]=p,Te=x(C,U,"conv0"),Ve=x(U,G,"conv1"),rt=x(G,ne,"conv2"),Ct=x(ne,te,"conv3"),Ut=x(te,oe,"conv4"),Kt=x(oe,ge,"conv5"),Dn=x(ge,fe,"conv6"),An=x(fe,Ae,"conv7"),vn=S(Ae,5*u,1,"conv8");O={conv0:Te,conv1:Ve,conv2:rt,conv3:Ct,conv4:Ut,conv5:Kt,conv6:Dn,conv7:An,conv8:vn}}if(f().length!==0)throw new Error(`weights remaing after extract: ${f().length}`);return{params:O,paramMappings:I}}function FZ(r,l){const u=ms(r,l);function p(S){const x=u(`${S}/sub`,1),v=u(`${S}/truediv`,1);return{sub:x,truediv:v}}function g(S){const x=u(`${S}/filters`,4),v=u(`${S}/bias`,1);return{filters:x,bias:v}}function f(S){const x=g(`${S}/conv`),v=p(`${S}/bn`);return{conv:x,bn:v}}const I=Kc(u);return{extractConvParams:g,extractConvWithBatchNormParams:f,extractSeparableConvParams:I}}function BD(r,l){const u=[],{extractConvParams:p,extractConvWithBatchNormParams:g,extractSeparableConvParams:f}=FZ(r,u);let I;if(l.withSeparableConvs){const S=l.filterSizes&&l.filterSizes.length||9;I={conv0:l.isFirstLayerConv2d?p("conv0"):f("conv0"),conv1:f("conv1"),conv2:f("conv2"),conv3:f("conv3"),conv4:f("conv4"),conv5:f("conv5"),conv6:S>7?f("conv6"):void 0,conv7:S>8?f("conv7"):void 0,conv8:p("conv8")}}else I={conv0:g("conv0"),conv1:g("conv1"),conv2:g("conv2"),conv3:g("conv3"),conv4:g("conv4"),conv5:g("conv5"),conv6:g("conv6"),conv7:g("conv7"),conv8:p("conv8")};return zn(r,u),{params:I,paramMappings:u}}var Am;(function(r){r[r.XS=224]="XS",r[r.SM=320]="SM",r[r.MD=416]="MD",r[r.LG=608]="LG"})(Am||(Am={}));class $i{constructor({inputSize:r,scoreThreshold:l}={}){this._name="TinyYolov2Options";if(this._inputSize=r||416,this._scoreThreshold=l||.5,typeof this._inputSize!="number"||this._inputSize%32!==0)throw new Error(`${this._name} - expected inputSize to be a number divisible by 32`);if(typeof this._scoreThreshold!="number"||this._scoreThreshold<=0||this._scoreThreshold>=1)throw new Error(`${this._name} - expected scoreThreshold to be a number between 0 and 1`)}get inputSize(){return this._inputSize}get scoreThreshold(){return this._scoreThreshold}}const kt=Xe(Je());class el extends In{constructor(r){super("TinyYolov2");Tm(r),this._config=r}get config(){return this._config}get withClassScores(){return this.config.withClassScores||this.config.classes.length>1}get boxEncodingSize(){return 5+(this.withClassScores?this.config.classes.length:0)}runTinyYolov2(r,l){let u=Lr(r,l.conv0);return u=kt.maxPool(u,[2,2],[2,2],"same"),u=Lr(u,l.conv1),u=kt.maxPool(u,[2,2],[2,2],"same"),u=Lr(u,l.conv2),u=kt.maxPool(u,[2,2],[2,2],"same"),u=Lr(u,l.conv3),u=kt.maxPool(u,[2,2],[2,2],"same"),u=Lr(u,l.conv4),u=kt.maxPool(u,[2,2],[2,2],"same"),u=Lr(u,l.conv5),u=kt.maxPool(u,[2,2],[1,1],"same"),u=Lr(u,l.conv6),u=Lr(u,l.conv7),ma(u,l.conv8,"valid",!1)}runMobilenet(r,l){let u=this.config.isFirstLayerConv2d?Qc(ma(r,l.conv0,"valid",!1)):Sr(r,l.conv0);return u=kt.maxPool(u,[2,2],[2,2],"same"),u=Sr(u,l.conv1),u=kt.maxPool(u,[2,2],[2,2],"same"),u=Sr(u,l.conv2),u=kt.maxPool(u,[2,2],[2,2],"same"),u=Sr(u,l.conv3),u=kt.maxPool(u,[2,2],[2,2],"same"),u=Sr(u,l.conv4),u=kt.maxPool(u,[2,2],[2,2],"same"),u=Sr(u,l.conv5),u=kt.maxPool(u,[2,2],[1,1],"same"),u=l.conv6?Sr(u,l.conv6):u,u=l.conv7?Sr(u,l.conv7):u,ma(u,l.conv8,"valid",!1)}forwardInput(r,l){const{params:u}=this;if(!u)throw new Error("TinyYolov2 - load model before inference");return kt.tidy(()=>{let p=kt.cast(r.toBatchTensor(l,!1),"float32");return p=this.config.meanRgb?Ys(p,this.config.meanRgb):p,p=p.div(kt.scalar(256)),this.config.withSeparableConvs?this.runMobilenet(p,u):this.runTinyYolov2(p,u)})}async forward(r,l){return await this.forwardInput(await Tt(r),l)}async detect(r,l={}){const{inputSize:u,scoreThreshold:p}=new $i(l),g=await Tt(r),f=await this.forwardInput(g,u),I=kt.tidy(()=>kt.unstack(f)[0].expandDims()),S={width:g.getInputWidth(0),height:g.getInputHeight(0)},x=await this.extractBoxes(I,g.getReshapedInputDimensions(0),p);f.dispose(),I.dispose();const v=x.map(te=>te.box),O=x.map(te=>te.score),C=x.map(te=>te.classScore),U=x.map(te=>this.config.classes[te.label]),G=Cm(v.map(te=>te.rescale(u)),O,this.config.iouThreshold,!0),ne=G.map(te=>new ta(O[te],C[te],U[te],v[te],S));return ne}getDefaultModelName(){return""}extractParamsFromWeigthMap(r){return BD(r,this.config)}extractParams(r){const l=this.config.filterSizes||el.DEFAULT_FILTER_SIZES,u=l?l.length:void 0;if(u!==7&&u!==8&&u!==9)throw new Error(`TinyYolov2 - expected 7 | 8 | 9 convolutional filters, but found ${u} filterSizes in config`);return UD(r,this.config,this.boxEncodingSize,l)}async extractBoxes(r,l,u){const{width:p,height:g}=l,f=Math.max(p,g),I=f/p,S=f/g,x=r.shape[1],v=this.config.anchors.length,[O,C,U]=kt.tidy(()=>{const oe=r.reshape([x,x,v,this.boxEncodingSize]),ge=oe.slice([0,0,0,0],[x,x,v,4]),fe=oe.slice([0,0,0,4],[x,x,v,1]),Ae=this.withClassScores?kt.softmax(oe.slice([0,0,0,5],[x,x,v,this.config.classes.length]),3):kt.scalar(0);return[ge,fe,Ae]}),G=[],ne=await C.array(),te=await O.array();for(let oe=0;oe<x;oe++)for(let ge=0;ge<x;ge++)for(let fe=0;fe<v;fe++){const Ae=xc(ne[oe][ge][fe][0]);if(!u||Ae>u){const Te=(ge+xc(te[oe][ge][fe][0]))/x*I,Ve=(oe+xc(te[oe][ge][fe][1]))/x*S,rt=Math.exp(te[oe][ge][fe][2])*this.config.anchors[fe].x/x*I,Ct=Math.exp(te[oe][ge][fe][3])*this.config.anchors[fe].y/x*S,Ut=Te-rt/2,Kt=Ve-Ct/2,Dn={row:oe,col:ge,anchor:fe},{classScore:An,label:vn}=this.withClassScores?await this.extractPredictedClass(U,Dn):{classScore:1,label:0};G.push({box:new Oc(Ut,Kt,Ut+rt,Kt+Ct),score:Ae,classScore:Ae*An,label:vn,...Dn})}}return O.dispose(),C.dispose(),U.dispose(),G}async extractPredictedClass(r,l){const{row:u,col:p,anchor:g}=l,f=await r.array();return Array(this.config.classes.length).fill(0).map((I,S)=>f[u][p][g][S]).map((I,S)=>({classScore:I,label:S})).reduce((I,S)=>I.classScore>S.classScore?I:S)}}el.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024];class Sc extends el{constructor(r=!0){const l=Object.assign({},{withSeparableConvs:r,iouThreshold:DD,classes:["face"]},r?{anchors:FD,meanRgb:_D}:{anchors:kD,withClassScores:!0});super(l)}get withSeparableConvs(){return this.config.withSeparableConvs}get anchors(){return this.config.anchors}async locateFaces(r,l){const u=await this.detect(r,l);return u.map(p=>new Wt(p.score,p.relativeBox,{width:p.imageWidth,height:p.imageHeight}))}getDefaultModelName(){return this.withSeparableConvs?$D:WD}extractParamsFromWeigthMap(r){return super.extractParamsFromWeigthMap(r)}}function WC(r,l=!0){const u=new Sc(l);return u.extractWeights(r),u}class vm extends $i{constructor(){super(...arguments);this._name="TinyFaceDetectorOptions"}}class Hs{async then(r){return r(await this.run())}async run(){throw new Error("ComposableTask - run is not implemented")}}const ox=Xe(Je());async function ga(r,l,u,p,g=({alignedRect:f})=>f){const f=r.map(x=>Jr(x)?g(x):x.detection),I=p||(l instanceof ox.Tensor?await Qo(l,f):await Zo(l,f)),S=await u(I);return I.forEach(x=>x instanceof ox.Tensor&&x.dispose()),S}async function tl(r,l,u,p,g){return ga([r],l,async f=>u(f[0]),p,g)}const MD=.4,PD=[new qe(1.603231,2.094468),new qe(6.041143,7.080126),new qe(2.882459,3.518061),new qe(4.266906,5.178857),new qe(9.041765,10.66308)],zD=[117.001,114.697,97.404];class Ic extends el{constructor(){const r={withSeparableConvs:!0,iouThreshold:MD,classes:["face"],anchors:PD,meanRgb:zD,isFirstLayerConv2d:!0,filterSizes:[3,16,32,64,128,256,512]};super(r)}get anchors(){return this.config.anchors}async locateFaces(r,l){const u=await this.detect(r,l);return u.map(p=>new Wt(p.score,p.relativeBox,{width:p.imageWidth,height:p.imageHeight}))}getDefaultModelName(){return"tiny_face_detector_model"}extractParamsFromWeigthMap(r){return super.extractParamsFromWeigthMap(r)}}const ht={ssdMobilenetv1:new Xo,tinyFaceDetector:new Ic,tinyYolov2:new Sc,faceLandmark68Net:new Ac,faceLandmark68TinyNet:new Um,faceRecognitionNet:new Tc,faceExpressionNet:new Mm,ageGenderNet:new jm},BS=(r,l)=>ht.ssdMobilenetv1.locateFaces(r,l),zC=(r,l)=>ht.tinyFaceDetector.locateFaces(r,l),GC=(r,l)=>ht.tinyYolov2.locateFaces(r,l),MS=r=>ht.faceLandmark68Net.detectLandmarks(r),VC=r=>ht.faceLandmark68TinyNet.detectLandmarks(r),YC=r=>ht.faceRecognitionNet.computeFaceDescriptor(r),HC=r=>ht.faceExpressionNet.predictExpressions(r),qC=r=>ht.ageGenderNet.predictAgeAndGender(r),PS=r=>ht.ssdMobilenetv1.load(r),jC=r=>ht.tinyFaceDetector.load(r),KC=r=>ht.tinyYolov2.load(r),XC=r=>ht.faceLandmark68Net.load(r),JC=r=>ht.faceLandmark68TinyNet.load(r),ZC=r=>ht.faceRecognitionNet.load(r),QC=r=>ht.faceExpressionNet.load(r),e2=r=>ht.ageGenderNet.load(r),t2=PS,n2=BS,s2=MS;class GD extends Hs{constructor(r,l,u){super();this.parentTask=r;this.input=l;this.extractedFaces=u}}class Vu extends GD{async run(){const r=await this.parentTask,l=await ga(r,this.input,async u=>await Promise.all(u.map(p=>ht.faceExpressionNet.predictExpressions(p))),this.extractedFaces);return r.map((u,p)=>fu(u,l[p]))}withAgeAndGender(){return new zu(this,this.input)}}class Yu extends GD{async run(){const r=await this.parentTask;if(!r)return;const l=await tl(r,this.input,u=>ht.faceExpressionNet.predictExpressions(u),this.extractedFaces);return fu(r,l)}withAgeAndGender(){return new Gu(this,this.input)}}class il extends Vu{withAgeAndGender(){return new nl(this,this.input)}withFaceDescriptors(){return new Kr(this,this.input)}}class rl extends Yu{withAgeAndGender(){return new sl(this,this.input)}withFaceDescriptor(){return new Xr(this,this.input)}}class VD extends Hs{constructor(r,l,u){super();this.parentTask=r;this.input=l;this.extractedFaces=u}}class zu extends VD{async run(){const r=await this.parentTask,l=await ga(r,this.input,async u=>await Promise.all(u.map(p=>ht.ageGenderNet.predictAgeAndGender(p))),this.extractedFaces);return r.map((u,p)=>{const{age:g,gender:f,genderProbability:I}=l[p];return yu(mu(u,f,I),g)})}withFaceExpressions(){return new Vu(this,this.input)}}class Gu extends VD{async run(){const r=await this.parentTask;if(!r)return;const{age:l,gender:u,genderProbability:p}=await tl(r,this.input,g=>ht.ageGenderNet.predictAgeAndGender(g),this.extractedFaces);return yu(mu(r,u,p),l)}withFaceExpressions(){return new Yu(this,this.input)}}class nl extends zu{withFaceExpressions(){return new il(this,this.input)}withFaceDescriptors(){return new Kr(this,this.input)}}class sl extends Gu{withFaceExpressions(){return new rl(this,this.input)}withFaceDescriptor(){return new Xr(this,this.input)}}class Wm extends Hs{constructor(r,l){super();this.parentTask=r;this.input=l}}class Kr extends Wm{async run(){const r=await this.parentTask,l=await ga(r,this.input,u=>Promise.all(u.map(p=>ht.faceRecognitionNet.computeFaceDescriptor(p))),null,u=>u.landmarks.align(null,{useDlibAlignment:!0}));return l.map((u,p)=>gu(r[p],u))}withFaceExpressions(){return new il(this,this.input)}withAgeAndGender(){return new nl(this,this.input)}}class Xr extends Wm{async run(){const r=await this.parentTask;if(!r)return;const l=await tl(r,this.input,u=>ht.faceRecognitionNet.computeFaceDescriptor(u),null,u=>u.landmarks.align(null,{useDlibAlignment:!0}));return gu(r,l)}withFaceExpressions(){return new rl(this,this.input)}withAgeAndGender(){return new sl(this,this.input)}}const Hu=Xe(Je());class km extends Hs{constructor(r,l,u){super();this.parentTask=r;this.input=l;this.useTinyLandmarkNet=u}get landmarkNet(){return this.useTinyLandmarkNet?ht.faceLandmark68TinyNet:ht.faceLandmark68Net}}class Fm extends km{async run(){const r=await this.parentTask,l=r.map(g=>g.detection),u=this.input instanceof Hu.Tensor?await Qo(this.input,l):await Zo(this.input,l),p=await Promise.all(u.map(g=>this.landmarkNet.detectLandmarks(g)));return u.forEach(g=>g instanceof Hu.Tensor&&g.dispose()),r.map((g,f)=>Jo(g,p[f]))}withFaceExpressions(){return new il(this,this.input)}withAgeAndGender(){return new nl(this,this.input)}withFaceDescriptors(){return new Kr(this,this.input)}}class _m extends km{async run(){const r=await this.parentTask;if(!r)return;const{detection:l}=r,u=this.input instanceof Hu.Tensor?await Qo(this.input,[l]):await Zo(this.input,[l]),p=await this.landmarkNet.detectLandmarks(u[0]);return u.forEach(g=>g instanceof Hu.Tensor&&g.dispose()),Jo(r,p)}withFaceExpressions(){return new rl(this,this.input)}withAgeAndGender(){return new sl(this,this.input)}withFaceDescriptor(){return new Xr(this,this.input)}}class Em extends Hs{constructor(r,l=new Vs){super();this.input=r;this.options=l}}class pu extends Em{async run(){const{input:r,options:l}=this,u=l instanceof vm?p=>ht.tinyFaceDetector.locateFaces(p,l):l instanceof Vs?p=>ht.ssdMobilenetv1.locateFaces(p,l):l instanceof $i?p=>ht.tinyYolov2.locateFaces(p,l):null;if(!u)throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | MtcnnOptions | TinyYolov2Options");return u(r)}runAndExtendWithFaceDetections(){return new Promise(async r=>{const l=await this.run();return r(l.map(u=>Zr({},u)))})}withFaceLandmarks(r=!1){return new Fm(this.runAndExtendWithFaceDetections(),this.input,r)}withFaceExpressions(){return new Vu(this.runAndExtendWithFaceDetections(),this.input)}withAgeAndGender(){return new zu(this.runAndExtendWithFaceDetections(),this.input)}}class Dm extends Em{async run(){const r=await new pu(this.input,this.options);let l=r[0];return r.forEach(u=>{u.score>l.score&&(l=u)}),l}runAndExtendWithFaceDetection(){return new Promise(async r=>{const l=await this.run();return r(l?Zr({},l):void 0)})}withFaceLandmarks(r=!1){return new _m(this.runAndExtendWithFaceDetection(),this.input,r)}withFaceExpressions(){return new Yu(this.runAndExtendWithFaceDetection(),this.input)}withAgeAndGender(){return new Gu(this.runAndExtendWithFaceDetection(),this.input)}}function i2(r,l=new Vs){return new Dm(r,l)}function du(r,l=new Vs){return new pu(r,l)}async function zS(r,l){return console.warn("allFacesSsdMobilenetv1 is deprecated and will be removed soon, use the high level api instead"),await du(r,new Vs(l?{minConfidence:l}:{})).withFaceLandmarks().withFaceDescriptors()}async function r2(r,l={}){return console.warn("allFacesTinyYolov2 is deprecated and will be removed soon, use the high level api instead"),await du(r,new $i(l)).withFaceLandmarks().withFaceDescriptors()}const o2=zS;function Pm(r,l){if(r.length!==l.length)throw new Error("euclideanDistance: arr1.length !== arr2.length");const u=Array.from(r),p=Array.from(l);return Math.sqrt(u.map((g,f)=>g-p[f]).reduce((g,f)=>g+Math.pow(f,2),0))}class GS{constructor(r,l=.6){this._distanceThreshold=l;const u=Array.isArray(r)?r:[r];if(!u.length)throw new Error("FaceRecognizer.constructor - expected atleast one input");let p=1;const g=()=>`person ${p++}`;this._labeledDescriptors=u.map(f=>{if(f instanceof so)return f;if(f instanceof Float32Array)return new so(g(),[f]);if(f.descriptor&&f.descriptor instanceof Float32Array)return new so(g(),[f.descriptor]);throw new Error("FaceRecognizer.constructor - expected inputs to be of type LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array | Array<LabeledFaceDescriptors | WithFaceDescriptor<any> | Float32Array>")})}get labeledDescriptors(){return this._labeledDescriptors}get distanceThreshold(){return this._distanceThreshold}computeMeanDistance(r,l){return l.map(u=>Pm(u,r)).reduce((u,p)=>u+p,0)/(l.length||1)}matchDescriptor(r){return this.labeledDescriptors.map(({descriptors:l,label:u})=>new Lu(u,this.computeMeanDistance(r,l))).reduce((l,u)=>l.distance<u.distance?l:u)}findBestMatch(r){const l=this.matchDescriptor(r);return l.distance<this.distanceThreshold?l:new Lu("unknown",l.distance)}toJSON(){return{distanceThreshold:this.distanceThreshold,labeledDescriptors:this.labeledDescriptors.map(r=>r.toJSON())}}static fromJSON(r){const l=r.labeledDescriptors.map(u=>so.fromJSON(u));return new GS(l,r.distanceThreshold)}}function $C(r){const l=new Ic;return l.extractWeights(r),l}function US(r,l){const{width:u,height:p}=new Zn(l.width,l.height);if(u<=0||p<=0)throw new Error(`resizeResults - invalid dimensions: ${JSON.stringify({width:u,height:p})}`);if(Array.isArray(r))return r.map(g=>US(g,{width:u,height:p}));if(Jr(r)){const g=r.detection.forSize(u,p),f=r.unshiftedLandmarks.forSize(g.box.width,g.box.height);return Jo(Zr(r,g),f)}return mi(r)?Zr(r,r.detection.forSize(u,p)):r instanceof Ns||r instanceof Wt?r.forSize(u,p):r}var FC="0.8.3";return g2();})();
/**
* @license
* Copyright 2017 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* @license
* Copyright 2018 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
/**
* @license
* Copyright 2019 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google Inc. 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.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/**
* @license
* Copyright 2020 Google LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =============================================================================
*/
/** @license See the LICENSE file. */
//# sourceMappingURL=face-api.js.map