4122 lines
1.1 MiB
4122 lines
1.1 MiB
var faceapi=(()=>{var Xm=Object.defineProperty,s9=Object.prototype.hasOwnProperty,Jm=(r,l)=>()=>(l||(l={exports:{}},r(l.exports,l)),l.exports),s2=r=>Xm(r,"__esModule",{value:!0}),vu=(r,l)=>{s2(r);for(var u in l)Xm(r,u,{get:l[u],enumerable:!0})},i9=(r,l)=>{if(s2(r),typeof l=="object"||typeof l=="function")for(let u in l)!s9.call(r,u)&&u!=="default"&&Xm(r,u,{get:()=>l[u],enumerable:!0});return r},Ze=r=>r&&r.__esModule?r:i9(Xm({},"default",{value:r,enumerable:!0}),r);var r2=Jm((Ec,i2)=>{"use strict";var r9=function(){if(typeof self!="undefined")return self;if(typeof window!="undefined")return window;if(typeof gr!="undefined")return gr;throw new Error("unable to locate global object")},gr=r9();i2.exports=Ec=gr.fetch;gr.fetch&&(Ec.default=gr.fetch.bind(gr));Ec.Headers=gr.Headers;Ec.Request=gr.Request;Ec.Response=gr.Response});var Qe=Jm((Zm,o2)=>{(function(r,l){typeof Zm=="object"&&typeof o2!="undefined"?l(Zm):typeof define=="function"&&define.amd?define(["exports"],l):(r=r||self,l(r.tf=r.tf||{}))})(Zm,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 y{time(e){return g("time")}read(e){return g("read")}readSync(e){return g("readSync")}numDataIds(){return g("numDataIds")}disposeData(e){return g("disposeData")}write(e,t,n){return g("write")}move(e,t,n,s){return g("move")}memory(){return g("memory")}floatPrecision(){return g("floatPrecision")}epsilon(){return this.floatPrecision()===32?l:u}batchMatMul(e,t,n,s){return g("batchMatMul")}fusedBatchMatMul({a:e,b:t,transposeA:n,transposeB:s,bias:i,activation:o,preluActivationWeights:a}){return g("fusedBatchMatMul")}slice(e,t,n){return g("slice")}stridedSlice(e,t,n,s){return g("stridedSlice")}unstack(e,t){return g("unstack")}reverse(e,t){return g("reverse")}concat(e,t){return g("concat")}neg(e){return g("neg")}add(e,t){return g("add")}addN(e){return g("addN")}subtract(e,t){return g("subtract")}multiply(e,t){return g("multiply")}realDivide(e,t){return g("realDivide")}floorDiv(e,t){return g("floorDiv")}sum(e,t){return g("sum")}prod(e,t){return g("prod")}unsortedSegmentSum(e,t,n){return g("unsortedSegmentSum")}argMin(e,t){return g("argMin")}argMax(e,t){return g("argMax")}equal(e,t){return g("equal")}notEqual(e,t){return g("notEqual")}less(e,t){return g("less")}lessEqual(e,t){return g("lessEqual")}greater(e,t){return g("greater")}greaterEqual(e,t){return g("greaterEqual")}logicalNot(e){return g("logicalNot")}logicalAnd(e,t){return g("logicalAnd")}logicalOr(e,t){return g("logicalOr")}where(e){return g("where")}select(e,t,n){return g("select")}topk(e,t,n){return g("topk")}min(e,t){return g("min")}minimum(e,t){return g("minimum")}mod(e,t){return g("mod")}max(e,t){return g("max")}maximum(e,t){return g("maximum")}all(e,t){return g("all")}any(e,t){return g("any")}squaredDifference(e,t){return g("squaredDifference")}ceil(e){return g("ceil")}floor(e){return g("floor")}round(e){return g("round")}sign(e){return g("sign")}isNaN(e){return g("isNaN")}isInf(e){return g("isInf")}isFinite(e){return g("isFinite")}pow(e,t){return g("pow")}exp(e){return g("exp")}expm1(e){return g("expm1")}softmax(e,t){return g("softmax")}log(e){return g("log")}log1p(e){return g("log1p")}sqrt(e){return g("sqrt")}rsqrt(e){return g("rsqrt")}square(e){return g("square")}reciprocal(e){return g("reciprocal")}relu(e){return g("relu")}relu6(e){return g("relu6")}prelu(e,t){return g("prelu")}elu(e){return g("elu")}eluDer(e,t){return g("eluDer")}selu(e){return g("selu")}int(e){return g("int")}clip(e,t,n){return g("clip")}abs(e){return g("abs")}complexAbs(e){return g("complexAbs")}sigmoid(e){return g("sigmoid")}softplus(e){return g("softplus")}sin(e){return g("sin")}cos(e){return g("cos")}tan(e){return g("tan")}asin(e){return g("asin")}acos(e){return g("acos")}atan(e){return g("atan")}atan2(e,t){return g("atan2")}sinh(e){return g("sinh")}cosh(e){return g("cosh")}tanh(e){return g("tanh")}asinh(e){return g("asinh")}acosh(e){return g("acosh")}atanh(e){return g("atanh")}erf(e){return g("erf")}step(e,t){return g("step")}fusedConv2d({input:e,filter:t,convInfo:n,bias:s,activation:i,preluActivationWeights:o}){return g("fusedConv2d")}conv2d(e,t,n){return g("conv2d")}conv2dDerInput(e,t,n){return g("conv2dDerInput")}conv2dDerFilter(e,t,n){return g("conv2dDerFilter")}fusedDepthwiseConv2D({input:e,filter:t,convInfo:n,bias:s,activation:i,preluActivationWeights:o}){return g("fusedDepthwiseConv2D")}depthwiseConv2D(e,t,n){return g("depthwiseConv2D")}depthwiseConv2DDerInput(e,t,n){return g("depthwiseConv2DDerInput")}depthwiseConv2DDerFilter(e,t,n){return g("depthwiseConv2DDerFilter")}conv3d(e,t,n){return g("conv3d")}conv3dDerInput(e,t,n){return g("conv3dDerInput")}conv3dDerFilter(e,t,n){return g("conv3dDerFilter")}maxPool(e,t){return g("maxPool")}maxPoolBackprop(e,t,n,s){return g("maxPoolBackprop")}avgPool(e,t){return g("avgPool")}avgPoolBackprop(e,t,n){return g("avgPoolBackprop")}avgPool3d(e,t){return g("avgPool3d")}avgPool3dBackprop(e,t,n){return g("avgPool3dBackprop")}maxPool3d(e,t){return g("maxPool3d")}maxPool3dBackprop(e,t,n,s){return g("maxPool3dBackprop")}reshape(e,t){return g("reshape")}cast(e,t){return g("cast")}tile(e,t){return g("tile")}pad(e,t,n){return g("pad")}transpose(e,t){return g("transpose")}gather(e,t,n){return g("gather")}gatherND(e,t){return g("gatherND")}scatterND(e,t,n){return g("scatterND")}batchToSpaceND(e,t,n){return g("batchToSpaceND")}spaceToBatchND(e,t,n){return g("spaceToBatchND")}resizeBilinear(e,t,n,s){return g("resizeBilinear")}resizeBilinearBackprop(e,t,n){return g("resizeBilinearBackprop")}resizeNearestNeighbor(e,t,n,s){return g("resizeNearestNeighbor")}resizeNearestNeighborBackprop(e,t,n){return g("resizeNearestNeighborBackprop")}batchNorm(e,t,n,s,i,o){return g("batchNorm")}localResponseNormalization4D(e,t,n,s,i){return g("localResponseNormalization4D")}LRNGrad(e,t,n,s,i,o,a){return g("LRNGrad")}multinomial(e,t,n,s){return g("multinomial")}oneHot(e,t,n,s){return g("oneHot")}cumsum(e,t,n,s){return g("cumsum")}nonMaxSuppression(e,t,n,s,i){return g("nonMaxSuppression")}fft(e){return g("fft")}ifft(e){return g("ifft")}complex(e,t){return g("complex")}real(e){return g("real")}imag(e){return g("imag")}cropAndResize(e,t,n,s,i,o){return g("cropAndResize")}depthToSpace(e,t,n){return g("depthToSpace")}split(e,t,n){return g("split")}sparseToDense(e,t,n,s){return g("sparseToDense")}diag(e){return g("diag")}fill(e,t,n){return g("fill")}onesLike(e){return g("onesLike")}zerosLike(e){return g("zerosLike")}linspace(e,t,n){return g("linspace")}dispose(){return g("dispose")}}function g(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function I(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 S(e,t,n){return Math.max(e,Math.min(t,n))}function T(e){return e%2===0?e:e+1}function C(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function D(e,t){const n=Math.random();return t*n+(1-n)*e}function _(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 A(e,t){if(!e)throw new Error(typeof t=="string"?t:t())}function B(e,t,n=""){A(ae(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function ne(e){A(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function te(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||hn(e)&&!n)for(let s=0;s<e.length;++s)te(e[s],t,n);else t.push(e);return t}function P(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 ge(e){return e.length===0}function ae(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 Le(e){return e%1===0}function ve(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 Ve(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function at(e){const t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return I(t),t}function pt(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function $t(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 Gt(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 qe(e,t){const n=t.length;return e=e==null?t.map((s,i)=>i):[].concat(e),A(e.every(s=>s>=-n&&s<n),()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),A(e.every(s=>Le(s)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(s=>s<0?n+s:s)}function ln(e,t){const n=[],s=[],i=t!=null&&Array.isArray(t)&&t.length===0,o=t==null||i?null:qe(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 bt(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 ws(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 Cr(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 Rr(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function Ta(e,t){return t==="complex64"||(t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64")?!1:!(t==="bool"&&e==="bool")}function hn(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function py(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 Rx(e){if(e==null)return 0;let t=0;return e.forEach(n=>t+=n.length),t}function qi(e){return typeof e=="string"||e instanceof String}function Ox(e){return typeof e=="boolean"}function ld(e){return typeof e=="number"}function Aa(e){return Array.isArray(e)?Aa(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":ld(e)?"float32":qi(e)?"string":Ox(e)?"bool":"float32"}function Or(e){return!!(e&&e.constructor&&e.call&&e.apply)}function hd(e,t){for(let n=t;n<e;++n)if(e%n===0)return n;return e}function je(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 Ex(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]=Ex(e+c*a,o,n)}return s}function Ls(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 Ex(0,e,t)}function my(e,t){const n=va(e,t);for(let s=0;s<n.length;s++)n[s]=1;return n}function va(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 fy(e,t){const n=e.reduce((s,i)=>s*i,1);if(t==null||t==="float32")return Ls(e,new Float32Array(n));if(t==="int32")return Ls(e,new Int32Array(n));if(t==="bool")return Ls(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function gy(e){e.forEach(t=>{A(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function Ws(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 vo(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}function No(e){return e&&e.then&&typeof e.then=="function"}const Dx="tfjsflags";class kx{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(No(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}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=Ak(this.global.location.search);if(Dx in e){const t=e[Dx].split(",");t.forEach(n=>{const[s,i]=n.split(":");this.urlFlags[s]=Nk(s,i)})}}}function Ak(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...s)=>(vk(t,s[0],s[1]),s.join("="))),t}function vk(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function Nk(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 oe(){return r.ENV}r.ENV=null;function Ck(e){r.ENV=e}let yy;function Fx(){if(yy==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");yy=e}return yy}function Rk(){const e=Fx();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function _x(e,t){const n=Rk();if(n.has(e))return n.get(e);{const s=t();return n.set(e,s),n.get(e)}}const ud="Abs",gl="Acos",yl="Acosh",Co="Add",by="AddN",Wx="All",$x="Any",wy="ArgMax",Ly="ArgMin",bl="Asin",wl="Asinh",Ll="Atan",Sl="Atanh",dd="Atan2",Il="AvgPool",pd="AvgPoolBackprop",Sy="AvgPool3D",Ux="AvgPool3DBackprop",md="BatchMatMul",Iy="BatchToSpaceND",xy="BroadcastTo",Na="Cast",xl="Ceil",Tl="ClipByValue",fd="Complex",Al="Concat",gd="Conv2D",Ty="Conv2DBackpropFilter",yd="Conv2DBackpropInput",bd="Conv3D",Ay="Conv3DBackpropFilterV2",vy="Conv3DBackpropInputV2",Ca="Cos",vl="Cosh",Ny="Cumsum",Bx="CropAndResize",Mx="DepthToSpace",wd="DepthwiseConv2dNative",Cy="DepthwiseConv2dNativeBackpropFilter",Ry="DepthwiseConv2dNativeBackpropInput",Px="Diag",Ld="Dilation2D",Sd="Dilation2DBackpropInput",Id="Dilation2DBackpropFilter",Ra="Div",Nl="Elu",zx="EluGrad",Cl="Erf",Vx="Equal",Rl="Exp",Ol="Expm1",xd="FFT",Oy="Fill",Td="FlipLeftRight",El="Floor",Ey="FloorDiv",Dl="FusedBatchNorm",Dy="GatherV2",Gx="GatherNd",Yx="Greater",ky="GreaterEqual",kl="Identity",Ad="IFFT",vd="Imag",Fl="IsFinite",_l="IsInf",Wl="IsNan",Hx="Less",qx="LessEqual",jx="LinSpace",$l="Log",Ul="Log1p",Kx="LogicalAnd",Nd="LogicalNot",Xx="LogicalOr",Fy="LogSoftmax",_y="LRN",Jx="LRNBackprop",Bl="Max",Wy="Maximum",Ml="MaxPool",Cd="MaxPoolBackprop",$y="MaxPool3D",Zx="MaxPool3DBackprop",Rd="MaxPoolWithArgmax",Uy="Mean",By="Min",My="Minimum",Pl="MirrorPad",Py="Mod",Oa="Multiply",zy="Negate",zl="NotEqual",Vy="NonMaxSuppressionV3",Od="NonMaxSuppressionV4",Ed="NonMaxSuppressionV5",Gy="OnesLike",Yy="OneHot",Dd="PadV2",Ok="Pool",Hy="Pow",kd="Prelu",Qx="Prod",eT="Range",Fd="Real",Vl="Reciprocal",Gl="Relu",Yl="Reshape",qy="ResizeNearestNeighbor",tT="ResizeNearestNeighborGrad",jy="ResizeBilinear",nT="ResizeBilinearGrad",Hl="Relu6",Ky="Reverse",ql="Round",jl="Rsqrt",sT="ScatterNd",Xy="SelectV2",Kl="Selu",_d="Slice",Ea="Sin",Xl="Sinh",Jl="Sign",Zl="Sigmoid",Ql="Softplus",eh="Sqrt",Jy="Sum",Wd="SpaceToBatchND",Zy="SplitV",Qy="Softmax",Da="SquaredDifference",$d="Square",ka="Sub",iT="SparseToDense",rT="StridedSlice",Fa="Tan",th="Tanh",eb="Tile",oT="TopK",nh="Transpose",Ud="Unique",tb="Unpack",nb="UnsortedSegmentSum",sb="ZerosLike",sh="Step",Bd="FromPixels",Md="RotateWithOffset",Pd="_FusedMatMul",zd="FusedConv2D",Vd="FusedDepthwiseConv2D";const _a=_x("kernelRegistry",()=>new Map),ih=_x("gradRegistry",()=>new Map);function ib(e,t){const n=ob(e,t);return _a.get(n)}function rb(e){return ih.get(e)}function Gd(e){const t=_a.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 Yd(e){const{kernelName:t,backendName:n}=e,s=ob(t,n);_a.has(s)&&console.warn(`The kernel '${t}' for backend '${n}' is already registered`),_a.set(s,e)}function aT(e){const{kernelName:t}=e;ih.has(t)&&(oe().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${t}'`)),ih.set(t,e)}function Ek(e,t){const n=ob(e,t);if(!_a.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);_a.delete(n)}function Dk(e){if(!ih.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);ih.delete(e)}function kk(e,t){const n=Gd(e);n.forEach(s=>{const i=Object.assign({},s,{backendName:t});Yd(i)})}function ob(e,t){return`${t}_${e}`}function cT(e,t){return t==="string"?Hd(e):Er([e],t)}function Fk(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function Er(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=te(e)),oe().getBool("DEBUG")&&Cr(e,t),Fk(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 Kn(){return oe().platform.now()}function lT(e,t){return oe().platform.fetch(e,t)}function Hd(e,t="utf-8"){return t=t||"utf-8",oe().platform.encode(e,t)}function rh(e,t="utf-8"){return t=t||"utf-8",oe().platform.decode(e,t)}var _k=Object.freeze({__proto__:null,createScalarValue:cT,toTypedArray:Er,now:Kn,fetch:lT,encodeString:Hd,decodeString:rh,shuffle:I,clamp:S,nearestLargerEven:T,sum:C,randUniform:D,distSquared:_,assert:A,assertShapesMatch:B,assertNonNull:ne,flatten:te,sizeFromShape:P,isScalarShape:ge,arraysEqual:ae,isInt:Le,tanh:ve,sizeToSquarishShape:Ve,createShuffledIndices:at,rightPad:pt,repeatedTry:$t,inferFromImplicitShape:Gt,parseAxisParam:qe,squeezeShape:ln,getTypedArrayFromDType:bt,getArrayFromDType:ws,checkConversionForErrors:Cr,isValidDtype:Rr,hasEncodingLoss:Ta,isTypedArray:hn,bytesPerElement:py,bytesFromStringArray:Rx,isString:qi,isBoolean:Ox,isNumber:ld,inferDtype:Aa,isFunction:Or,nearestDivisor:hd,computeStrides:je,toNestedArray:Ls,makeOnesTypedArray:my,makeZerosTypedArray:va,makeZerosNestedTypedArray:fy,assertNonNegativeIntegerDimensions:gy,locToIndex:Ws,indexToLoc:vo,isPromise:No});class Wk{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new Uk)}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=>{$k(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 $k(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 Uk{logKernelProfile(e,t,n,s,i,o){const a=typeof s=="number"?pt(`${s}ms`,9):s.error,c=pt(e,25),h=t.rank,d=t.size,m=pt(t.shape.toString(),14);let f="";for(const b in i){const w=i[b];if(w!=null){const L=w.shape||t.shape,x=L.length;f+=`${b}: ${x}D ${x>0?L:""} `}}console.log(`%c${c} %c${a} %c${h}D ${m} %c${d} %c${f} %c${o}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function Bk(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 f in m){const b=m[f];let w=!1;for(let L=0;L<t.length;L++)if(s[b.id]){d.outputs.forEach(x=>s[x.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 f=0;f<d.outputs.length;f++)if(o[d.outputs[f].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 f=Object.assign({},d);f.inputs=m,f.outputs=d.outputs,c.push(f)}}return c}function Mk(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(!ae(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 f=e[m.id];e[m.id]=s(f,d),f.dispose()}}}}const hT=20,oh=3,ab=7;function Pk(e,t,n,s){const i=je(t),o=zk(e,t,n,i),a=t.length,c=qd(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 zk(e,t,n,s){const i=P(t),o=s[s.length-1],a=new Array(o).fill(0),c=t.length,h=n==="complex64"?ch(e):e;if(c>1)for(let d=0;d<i/o;d++){const m=d*o;for(let f=0;f<o;f++)a[f]=Math.max(a[f],ah(h[m+f],0,n).length)}return a}function ah(e,t,n){let s;return Array.isArray(e)?s=`${parseFloat(e[0].toFixed(ab))} + ${parseFloat(e[1].toFixed(ab))}j`:qi(e)?s=`'${e}'`:n==="bool"?s=uT(e):s=parseFloat(e.toFixed(ab)).toString(),pt(s,t)}function uT(e){return e===0?"false":"true"}function qd(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 x=ch(e);return[ah(x[0],0,n)]}return n==="bool"?[uT(e[0])]:[e[0].toString()]}if(h===1){if(c>hT){const v=oh*a;let N=Array.from(e.slice(0,v)),O=Array.from(e.slice((c-oh)*a,c*a));return n==="complex64"&&(N=ch(N),O=ch(O)),["["+N.map((E,k)=>ah(E,i[k],n)).join(", ")+", ..., "+O.map((E,k)=>ah(E,i[c-oh+k],n)).join(", ")+"]"]}const x=n==="complex64"?ch(e):Array.from(e);return["["+x.map((v,N)=>ah(v,i[N],n)).join(", ")+"]"]}const d=t.slice(1),m=s.slice(1),f=s[0]*a,b=[];if(c>hT){for(let x=0;x<oh;x++){const v=x*f,N=v+f;b.push(...qd(e.slice(v,N),d,n,m,i,!1))}b.push("...");for(let x=c-oh;x<c;x++){const v=x*f,N=v+f;b.push(...qd(e.slice(v,N),d,n,m,i,x===c-1))}}else for(let x=0;x<c;x++){const v=x*f,N=v+f;b.push(...qd(e.slice(v,N),d,n,m,i,x===c-1))}const w=h===2?",":"";b[0]="["+b[0]+w;for(let x=1;x<b.length-1;x++)b[x]=" "+b[x]+w;let L=`,
|
|
`;for(let x=2;x<h;x++)L+=`
|
|
`;return b[b.length-1]=" "+b[b.length-1]+"]"+(o?"":L),b}function ch(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class an{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=P(e),n!=null){const s=n.length;A(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||ws(t,this.size),this.strides=je(e)}set(e,...t){t.length===0&&(t=[0]),A(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,Wa=null,dT=null;function Vk(e){Ii=e}function Gk(e){Wa=e}function Yk(e){dT=e}class ee{constructor(e,t,n,s){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=P(e),this.strides=je(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 Wa.buffer(this.shape,this.dtype,e)}bufferSync(){return Wa.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return Ls(this.shape,e)}arraySync(){return Ls(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=>rh(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=>rh(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 Wa.print(this,e)}clone(){return this.throwIfDisposed(),Wa.clone(this)}toString(e=!1){const t=this.dataSync();return Pk(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Wa.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Ii().makeVariable(this,e,t,n)}}Object.defineProperty(ee,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});class lh extends ee{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(!ae(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(lh,Symbol.hasInstance,{value:e=>e instanceof ee&&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 cb;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(cb||(cb={}));var lb;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(lb||(lb={}));var hb;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(hb||(hb={}));var ub;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(ub||(ub={}));const Hk={float32:hb,int32:cb,bool:lb,complex64:ub};function $n(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return Hk[e][t]}function jd(e){return $n(e,"int32")}function Yt(e,t){if(e.dtype===t.dtype)return[e,t];const n=$n(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function pT(e,t){A(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function Kd(e,t){return t.some(n=>n.id===e.id)}function ji(e){const t=[],n=new Set;return mT(e,t,n),t}function mT(e,t,n){if(e==null)return;if(e instanceof ee){t.push(e);return}if(!qk(e))return;const s=e;for(const i in s){const o=s[i];n.has(o)||(n.add(o),mT(o,t,n))}}function qk(e){return Array.isArray(e)||typeof e=="object"}var jk=Object.freeze({__proto__:null,makeTypesMatch:Yt,assertTypesMatch:pT,isTensorInList:Kd,getTensorsInContainer:ji});class fT{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 hh{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new fT}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 Wk(this.backendInstance),!0}setupRegisteredKernels(){const e=Gd(this.backendName);e.forEach(t=>{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){const t=Gd(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 y)&&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 hh.nextTensorId++}nextVariableId(){return hh.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 G.runKernelFunc(d=>d.cast(o,a),c,null,Na,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,f=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let b;const w=ib(s,this.backendName);let L;if(w!=null)b=()=>{const v=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,v,N);const O=N.map(({dataId:E,shape:k,dtype:F})=>this.makeTensorFromDataId(E,k,F));if(d){let E=this.getTensorsForGradient(s,t,O);if(E==null){a==null&&(a=[]);const k=O.filter((F,U)=>a[U]);E=(o||[]).slice().concat(k)}h=this.saveTensorsForBackwardMode(E)}return O};else{const v=N=>{if(!d)return;h=N.map(O=>this.keep(this.clone(O)))};b=()=>{const N=this.backend.numDataIds();L=this.tidy(()=>e(this.backend,v));const O=Array.isArray(L)?L:[L];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(s,N,O),O}}let x;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?c=b():(x=this.profiler.profileKernel(s,t,()=>b()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(x),c=x.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-f,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(t).map(v=>t[v]!=null?t[v].shape:null),outputShapes:c.map(v=>v.shape),kernelTimeMs:x.timeMs,extraInfo:x.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=rb(e);if(s!=null){const i=s.inputsToSave||[],o=s.outputsToSave||[];let a;s.saveAllInputs?(A(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"&&qi(e[0])&&(i=e.map(c=>Hd(c)));const o=s.write(i,t,n),a=new ee(t,n,o,this.nextTensorId());if(this.incRef(a,s),n==="string"){const c=this.state.tensorInfo.get(o),h=Rx(i);this.state.numBytes+=h-c.bytes,c.bytes=h}return a}makeTensorFromDataId(e,t,n,s){n=n||"float32";const i=new ee(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 lh(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*py(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 lh||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=rb(e);c!=null&&(s=c.gradFunc),s!=null&&(a.gradient=h=>(h=h.map((d,m)=>{if(d==null){const f=n[m],b=va(f.size,f.dtype);return this.makeTensor(b,f.shape,f.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(A(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));A(i instanceof ee,()=>"The result y returned by f() must be a tensor.");const o=Bk(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?Kk(i.shape):n,Mk(a,o,h=>this.tidy(h),Xk);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 A(Or(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{A(t.every(i=>i instanceof ee),()=>"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),A(n.value instanceof ee,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),A(Or(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];A(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(...)."),A(c.every(d=>d instanceof ee),()=>"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=Kn(),n=await this.backend.time(e);return n.wallMs=Kn()-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 fT;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}}hh.nextTensorId=0,hh.nextVariableId=0;function Kk(e){const t=my(P(e),"float32");return G.makeTensor(t,e,"float32")}function gT(){const e=Fx();if(e._tfengine==null){const t=new kx(e);e._tfengine=new hh(t)}return Ck(e._tfengine.ENV),Vk(()=>e._tfengine),e._tfengine}const G=gT();function Xk(e,t){const n={a:e,b:t};return G.runKernelFunc((s,i)=>{const o=s.add(e,t);return i([e,t]),o},n,null,Co)}function Jk(){return typeof navigator!="undefined"&&navigator!=null}function yT(){if(Jk()){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 db(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var Zk=Object.freeze({__proto__:null,isMobile:yT,isBrowser:db});const Ki=oe();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",()=>db()),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(hn(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];const s=[];for(;Array.isArray(n)||hn(n)&&t!=="string";)s.push(n.length),n=n[0];return Array.isArray(e)&&oe().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&bT(e,s,[]),s}function bT(e,t,n){if(n=n||[],!Array.isArray(e)&&!hn(e)){A(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}A(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),A(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)bT(e[i],s,n.concat(i))}function wT(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 ee)return wT(s,e.dtype,t,n),e;let i=Aa(e);if(i!=="string"&&["bool","int32","float32"].indexOf(s)>=0&&(i=s),wT(s,i,t,n),e==null||!hn(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);!hn(e)&&!Array.isArray(e)&&(e=[e]);const a=!0,c=i!=="string"?Er(e,i):te(e,[],a);return G.makeTensor(c,o,i)}function uh(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 LT="__op";function z(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+LT;const i=(...o)=>{G.startScope(n);try{const a=s(...o);return No(a)&&console.error("Cannot return a Promise inside of tidy."),G.endScope(a),a}catch(a){throw G.endScope(null),a}};return Object.defineProperty(i,"name",{value:n,configurable:!0}),i}function Qk(e,t){const n=W(e,"real","complex"),s=W(t,"imag","complex");B(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 G.runKernelFunc(i,o,null,fd)}const Xi=z({complex_:Qk});function Dr(e,t,n,s){if(s==null&&(s=Aa(e)),s==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!hn(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){gy(t);const i=P(t),o=P(n);A(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!==P(t.slice(a)):!0;A(n[a]===t[a]||!h,()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return!hn(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=s!=="string"?Er(e,s):te(e,[],!0),G.makeTensor(e,t,s)}function sn(e,t,n){const s=xi(e,n);return Dr(e,t,s,n)}const pb={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};const Xd=4;async function mb(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 f=>{const b=await h.bytes(),w=b.reduce((v,N)=>v+N.length,0)+Xd*b.length,L=new Uint8Array(w);let x=0;for(let v=0;v<b.length;v++){const N=b[v],O=new Uint8Array(new Uint32Array([N.length]).buffer);L.set(O,x),x+=Xd,L.set(N,x),x+=N.length}f(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:eF(o),specs:n}}function Jd(e,t){const n={};let s,i=0;for(const o of t){const a=o.name,c=o.dtype,h=o.shape,d=P(h);let m;if("quantization"in o){const f=o.quantization;if(f.dtype==="uint8"||f.dtype==="uint16"){if(!("min"in f&&"scale"in f))throw new Error(`Weight ${o.name} with quantization ${f.dtype} doesn't have corresponding metadata min and scale.`)}else if(f.dtype==="float16"){if(c!=="float32")throw new Error(`Weight ${o.name} is quantized with ${f.dtype} which only supports weights of type float32 not ${c}.`)}else throw new Error(`Weight ${o.name} has unknown quantization dtype ${f.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);const b=pb[f.dtype],w=e.slice(i,i+d*b),L=f.dtype==="uint8"?new Uint8Array(w):new Uint16Array(w);if(c==="float32")if(f.dtype==="uint8"||f.dtype==="uint16"){m=new Float32Array(L.length);for(let x=0;x<L.length;x++){const v=L[x];m[x]=v*f.scale+f.min}}else if(f.dtype==="float16")s===void 0&&(s=oF()),m=s(L);else throw new Error(`Unsupported quantization type ${f.dtype} for weight type float32.`);else if(c==="int32"){if(f.dtype!=="uint8"&&f.dtype!=="uint16")throw new Error(`Unsupported quantization type ${f.dtype} for weight type int32.`);m=new Int32Array(L.length);for(let x=0;x<L.length;x++){const v=L[x];m[x]=Math.round(v*f.scale+f.min)}}else throw new Error(`Unsupported dtype in weight '${a}': ${c}`);i+=d*b}else if(c==="string"){const f=P(o.shape);m=[];for(let b=0;b<f;b++){const w=new Uint32Array(e.slice(i,i+Xd))[0];i+=Xd;const L=new Uint8Array(e.slice(i,i+w));m.push(L),i+=w}}else{const f=pb[c],b=e.slice(i,i+d*f);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 x=sn(w,h,"float32"),v=sn(L,h,"float32");n[a]=Xi(x,v),x.dispose(),v.dispose()}else throw new Error(`Unsupported dtype in weight '${a}': ${c}`);i+=d*f}c!=="complex64"&&(n[a]=sn(m,h,c))}return n}function eF(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 fb=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function ST(e){return fb?Buffer.byteLength(e):new Blob([e]).size}function tF(e){if(fb)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 nF(e){if(fb){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 Zd(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 IT(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 dh(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:ST(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:ST(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function sF(){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 iF(){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 rF(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function oF(){const e=sF(),t=iF(),n=rF();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 en{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return en.instance==null&&(en.instance=new en),en.instance}static registerSaveRouter(e){en.getInstance().saveRouters.push(e)}static registerLoadRouter(e){en.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return en.getHandlers(e,"save")}static getLoadHandlers(e,t){return en.getHandlers(e,"load",t)}static getHandlers(e,t,n){const s=[],i=t==="load"?en.getInstance().loadRouters:en.getInstance().saveRouters;return i.forEach(o=>{const a=o(e,n);a!==null&&s.push(a)}),s}}const aF=e=>en.registerSaveRouter(e),cF=e=>en.registerLoadRouter(e),gb=e=>en.getSaveHandlers(e),yb=(e,t)=>en.getLoadHandlers(e,t);const Qd="tensorflowjs",bb=1,Ro="models_store",kr="model_info_store";async function Lee(){const e=wb();return new Promise((t,n)=>{const s=e.deleteDatabase(Qd);s.onsuccess=()=>t(),s.onerror=i=>n(i)})}function wb(){if(!oe().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 Lb(e){const t=e.result;t.createObjectStore(Ro,{keyPath:"modelPath"}),t.createObjectStore(kr,{keyPath:"modelPath"})}class Oo{constructor(e){if(this.indexedDB=wb(),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(Qd,bb);i.onupgradeneeded=()=>Lb(i),i.onsuccess=()=>{const o=i.result;if(t==null){const a=o.transaction(Ro,"readonly"),c=a.objectStore(Ro),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=dh(t),c=o.transaction(kr,"readwrite");let h=c.objectStore(kr);const d=h.put({modelPath:this.modelPath,modelArtifactsInfo:a});let m;d.onsuccess=()=>{m=o.transaction(Ro,"readwrite");const f=m.objectStore(Ro),b=f.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:a});b.onsuccess=()=>n({modelArtifactsInfo:a}),b.onerror=w=>{h=c.objectStore(kr);const L=h.delete(this.modelPath);L.onsuccess=()=>(o.close(),s(b.error)),L.onerror=x=>(o.close(),s(b.error))}},d.onerror=f=>(o.close(),s(d.error)),c.oncomplete=()=>{m==null?o.close():m.oncomplete=()=>o.close()}}},i.onerror=o=>s(i.error)})}}Oo.URL_SCHEME="indexeddb://";const xT=e=>oe().getBool("IS_BROWSER")&&(!Array.isArray(e)&&e.startsWith(Oo.URL_SCHEME))?lF(e.slice(Oo.URL_SCHEME.length)):null;en.registerSaveRouter(xT),en.registerLoadRouter(xT);function lF(e){return new Oo(e)}function hF(e){return e.startsWith(Oo.URL_SCHEME)?e.slice(Oo.URL_SCHEME.length):e}class uF{constructor(){this.indexedDB=wb()}async listModels(){return new Promise((e,t)=>{const n=this.indexedDB.open(Qd,bb);n.onupgradeneeded=()=>Lb(n),n.onsuccess=()=>{const s=n.result,i=s.transaction(kr,"readonly"),o=i.objectStore(kr),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=hF(e),new Promise((t,n)=>{const s=this.indexedDB.open(Qd,bb);s.onupgradeneeded=()=>Lb(s),s.onsuccess=()=>{const i=s.result,o=i.transaction(kr,"readwrite"),a=o.objectStore(kr),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(Ro,"readwrite");const f=h.objectStore(Ro),b=f.delete(e);b.onsuccess=()=>t(c.result.modelArtifactsInfo),b.onerror=w=>n(c.error)};d.onsuccess=m,d.onerror=f=>(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 Ti="/",Eo="tensorflowjs_models",TT="info",dF="model_topology",pF="weight_specs",mF="weight_data",fF="model_metadata";function See(){if(!oe().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=Eo+Ti;if(s.startsWith(i)&&s.length>i.length){e.removeItem(s);const o=vT(s);t.indexOf(o)===-1&&t.push(o)}}return t}function AT(e){return{info:[Eo,e,TT].join(Ti),topology:[Eo,e,dF].join(Ti),weightSpecs:[Eo,e,pF].join(Ti),weightData:[Eo,e,mF].join(Ti),modelMetadata:[Eo,e,fF].join(Ti)}}function vT(e){const t=e.split(Ti);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Ti)}function gF(e){return e.startsWith(Do.URL_SCHEME)?e.slice(Do.URL_SCHEME.length):e}class Do{constructor(e){if(!oe().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=AT(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=dh(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,tF(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=nF(o),t}}Do.URL_SCHEME="localstorage://";const NT=e=>oe().getBool("IS_BROWSER")&&(!Array.isArray(e)&&e.startsWith(Do.URL_SCHEME))?yF(e.slice(Do.URL_SCHEME.length)):null;en.registerSaveRouter(NT),en.registerLoadRouter(NT);function yF(e){return new Do(e)}class bF{constructor(){A(oe().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),A(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){const e={},t=Eo+Ti,n=Ti+TT;for(let s=0;s<this.LS.length;++s){const i=this.LS.key(s);if(i.startsWith(t)&&i.endsWith(n)){const o=vT(i);e[o]=JSON.parse(this.LS.getItem(i))}}return e}async removeModel(e){e=gF(e);const t=AT(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 $a="://";class Ss{constructor(){this.managers={}}static getInstance(){return Ss.instance==null&&(Ss.instance=new Ss),Ss.instance}static registerManager(e,t){A(e!=null,()=>"scheme must not be undefined or null."),e.endsWith($a)&&(e=e.slice(0,e.indexOf($a))),A(e.length>0,()=>"scheme must not be an empty string.");const n=Ss.getInstance();A(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 ep(e){if(e.indexOf($a)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Ss.getSchemes().join(",")}`);return{scheme:e.split($a)[0],path:e.split($a)[1]}}async function CT(e,t,n=!1){A(e!==t,()=>`Old path and new path are the same: '${e}'`);const s=en.getLoadHandlers(e);A(s.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),A(s.length<2,()=>`Copying failed because more than one (${s.length}) load handlers for source URL ${e}.`);const i=s[0],o=en.getSaveHandlers(t);A(o.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),A(o.length<2,()=>`Copying failed because more than one (${s.length}) save handlers for destination URL ${t}.`);const a=o[0],c=ep(e).scheme,h=ep(e).path,d=c===ep(e).scheme,m=await i.load();n&&d&&await Ss.getManager(c).removeModel(h);const f=await a.save(m);return n&&!d&&await Ss.getManager(c).removeModel(h),f.modelArtifactsInfo}async function wF(){const e=Ss.getSchemes(),t={};for(const n of e){const s=await Ss.getManager(n).listModels();for(const i in s){const o=n+$a+i;t[o]=s[i]}}return t}async function LF(e){const t=ep(e),n=Ss.getManager(t.scheme);return n.removeModel(t.path)}async function SF(e,t){const n=!1;return CT(e,t,n)}async function IF(e,t){const n=!0;return CT(e,t,n)}class xF{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(oe().get("IS_BROWSER")){oe().setPlatform("browser",new xF);try{Ss.registerManager(Do.URL_SCHEME,new bF)}catch(e){}try{Ss.registerManager(Oo.URL_SCHEME,new uF)}catch(e){}}const TF={importFetch:()=>r2()};let Ua;function Iee(){Ua=null}function xee(e){Ua=e}function Tee(){return Ua}class AF{constructor(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return oe().global.fetch!=null?oe().global.fetch(e,t):(Ua==null&&(Ua=TF.importFetch()),Ua(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)}}oe().get("IS_NODE")&&oe().setPlatform("node",new AF);function wt(e,t="float32",n){return t=t||"float32",gy(e),new an(e,t,n)}function vF(e,t){const n=W(e,"x","cast");if(!Rr(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 G.runKernelFunc(o=>o.cast(n,t),s,null,Na,i)}const Ae=z({cast_:vF});function NF(e){const t=W(e,"x","clone",null),n=()=>G.makeTensorFromDataId(t.dataId,t.shape,t.dtype),s={x:t};return G.runKernelFunc(n,s,null,kl)}const Fr=z({clone_:NF});function RT(e,t=!1){console.log(e.toString(t))}gT();const CF={buffer:wt,cast:Ae,clone:Fr,print:RT};Gk(CF);const RF="model",OF=".json",EF=".weights.bin";function OT(e){return new Promise(t=>setTimeout(t)).then(e)}class Ba{constructor(e){if(!oe().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Ba.URL_SCHEME)&&(e=e.slice(Ba.URL_SCHEME.length)),(e==null||e.length===0)&&(e=RF),this.modelTopologyFileName=e+OF,this.weightDataFileName=e+EF}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 OT(()=>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 OT(()=>a.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:dh(e)}}}}Ba.URL_SCHEME="downloads://";class DF{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=[],f=[],b=[];h.forEach(w=>{w.paths.forEach(L=>{f.push(L),b.push(null)}),m.push(...w.weights)}),h.forEach(w=>{w.paths.forEach(L=>{const x=new FileReader;x.onload=v=>{const N=v.target.result,O=f.indexOf(L);b[O]=N,b.indexOf(null)===-1&&n({modelTopology:c,weightSpecs:m,weightData:Zd(b),format:a.format,generatedBy:a.generatedBy,convertedBy:a.convertedBy,userDefinedMetadata:a.userDefinedMetadata})},x.onerror=v=>s(`Failed to weights data from file of path '${L}'.`),x.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=>IT(o.name)),i={};for(const o of e)o.paths.forEach(a=>{const c=IT(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 kF=e=>oe().getBool("IS_BROWSER")&&(!Array.isArray(e)&&e.startsWith(Ba.URL_SCHEME))?FF(e.slice(Ba.URL_SCHEME.length)):null;en.registerSaveRouter(kF);function FF(e="model"){return new Ba(e)}function _F(e){return new DF(e)}function ET(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){A(h!=null&&Array.isArray(h)&&h.length>0,()=>"promises must be a none empty array")}function c(h,d){A(h>=0&&h<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${h}`),A(d>=0&&d<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${d}`),A(d>=h,()=>`startFraction must be no more than endFraction, but got startFraction ${h} and endFraction ${d}`)}return Promise.all(e.map(o))}async function DT(e,t){t==null&&(t={});const n=t.fetchFunc==null?oe().platform.fetch:t.fetchFunc,s=e.map(f=>n(f,t.requestInit,{isBinary:!0})),i=0,o=.5,a=t.onProgress==null?await Promise.all(s):await ET(s,t.onProgress,i,o),c=a.map(f=>f.arrayBuffer()),h=.5,d=1,m=t.onProgress==null?await Promise.all(c):await ET(c,t.onProgress,h,d);return m}async function kT(e,t="",n,s){const i=a=>DT(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 x=0;w.weights.forEach(v=>{const N="quantization"in v?v.quantization.dtype:v.dtype,O=pb[N]*P(v.shape),E=()=>{i[L]=!0,o[L]==null&&(o[L]=[]),o[L].push({manifestEntry:v,groupOffset:x,sizeBytes:O})};s!=null?s.forEach((k,F)=>{k===v.name&&(E(),a[F]=!0)}):E(),c.push(v.name),x+=O})}),!a.every(w=>w)){const w=s.filter((L,x)=>!a[x]);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,x)=>(L&&w.push(x),w),[]),d=[];h.forEach(w=>{t[w].paths.forEach(L=>{const x=n+(n.endsWith("/")?"":"/")+L;d.push(x)})});const m=await e(d),f={};let b=0;return h.forEach(w=>{const L=t[w].paths.length;let x=0;for(let k=0;k<L;k++)x+=m[b+k].byteLength;const v=new ArrayBuffer(x),N=new Uint8Array(v);let O=0;for(let k=0;k<L;k++){const F=new Uint8Array(m[b+k]);N.set(F,O),O+=F.byteLength}const E=o[w];E.forEach(k=>{const F=v.slice(k.groupOffset,k.groupOffset+k.sizeBytes),U=Jd(F,[k.manifestEntry]);for(const $ in U)f[$]=U[$]}),b+=L}),f}}const WF="application/octet-stream",$F="application/json";class Sb{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?(A(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=oe().platform.fetch,A(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&A(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:$F}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:WF}),"model.weights.bin");const i=await this.fetch(this.path,t);if(i.ok)return{modelArtifactsInfo:dh(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},f=t.modelInitializer;return f&&(m.modelInitializer=f),m}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,s]=UF(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 DT(a,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[o,Zd(h)]}}Sb.URL_SCHEME_REGEX=/^https?:\/\//;function UF(e){const t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),s=e.substring(0,t),i=n>t?e.substring(n):"";return[s+"/",i]}function Ib(e){return e.match(Sb.URL_SCHEME_REGEX)!=null}const _T=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(s=>Ib(s)):n=Ib(e),n)return xb(e,t)}return null};en.registerSaveRouter(_T),en.registerLoadRouter(_T);function xb(e,t){return new Sb(e,t)}function tp(e,t){return xb(e,t)}class Tb{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}}class BF{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}}function MF(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 PF(e){return new BF(e)}var zF=Object.freeze({__proto__:null,browserFiles:_F,browserHTTPRequest:tp,concatenateArrayBuffers:Zd,decodeWeights:Jd,encodeWeights:mb,fromMemory:MF,getLoadHandlers:yb,getModelArtifactsInfoForJSON:dh,getSaveHandlers:gb,http:xb,isHTTPScheme:Ib,loadWeights:kT,registerLoadRouter:cF,registerSaveRouter:aF,weightsLoaderFactory:FT,withSaveHandler:PF,copyModel:SF,listModels:wF,moveModel:IF,removeModel:LF});function VF(e,t){const n=W(e,"x","reshape",null),s={x:n},i={shape:t},o=(a,c)=>(t=Gt(t,n.size),A(n.size===P(t),()=>"new shape and old shape must have the same number of elements."),c([n]),a.reshape(n,t));return G.runKernelFunc(o,s,null,Yl,i)}const K=z({reshape_:VF});function GF(e,t,n=!1,s=!1){let i=W(e,"a","matMul"),o=W(t,"b","matMul");[i,o]=Yt(i,o);const a=(d,m)=>{m([i,o]);const f=n?i.shape[i.rank-2]:i.shape[i.rank-1],b=s?o.shape[o.rank-1]:o.shape[o.rank-2],w=n?i.shape[i.rank-1]:i.shape[i.rank-2],L=s?o.shape[o.rank-2]:o.shape[o.rank-1],x=i.shape.slice(0,-2),v=o.shape.slice(0,-2),N=P(x),O=P(v),E=N===O||N===1||O===1;A(i.rank>=2&&o.rank>=2&&E,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${x}) and (${v}).`),A(f===b,()=>`Error in matMul: inner shapes (${f}) and (${b}) of Tensors with shapes ${i.shape} and ${o.shape} and transposeA=${n} and transposeB=${s} must match.`);const k=N>O?x:v,F=k.concat([w,L]),U=n?K(i,[N,f,w]):K(i,[N,w,f]),$=s?K(o,[O,L,b]):K(o,[O,b,L]),Y=d.batchMatMul(U,$,n,s);return K(Y,F)},c={a:i,b:o},h={transposeA:n,transposeB:s};return G.runKernelFunc(a,c,null,md,h)}const ct=z({matMul_:GF});function YF(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 G.runKernelFunc(a,c,null,Yy,h)}const ko=z({oneHot_:YF});function HF(e,t){const n=W(e,"x","transpose");if(t==null&&(t=n.shape.map((o,a)=>a).reverse()),A(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(o=>{A(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 G.runKernelFunc(o=>o.transpose(n,t),s,null,nh,i)}const Ye=z({transpose_:HF});function qF(e,t,n){const s=W(e,"labels","confusionMatrix"),i=W(t,"predictions","confusionMatrix");A(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),A(s.rank===1,()=>`Expected the rank of labels to be 1, but got ${s.rank}`),A(i.rank===1,()=>`Expected the rank of predictions to be 1, but got ${i.rank}`),A(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.`),A(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);const o=ko(Ae(s,"int32"),n),a=ko(Ae(i,"int32"),n),c=Ye(o),h=ct(c,a);return Ae(h,"int32")}const jF=z({confusionMatrix_:qF});var KF=Object.freeze({__proto__:null,confusionMatrix:jF});function WT(e,t,n){if(ne(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 Dr(e,t,s,n)}let Ma;function XF(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=ib(Bd,G.backendName);if(c!=null){const w={pixels:e},L={numChannels:t};return G.runKernel(Bd,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)&&(Ma==null&&(Ma=document.createElement("canvas").getContext("2d")),Ma.canvas.width=h,Ma.canvas.height=d,Ma.drawImage(e,0,0,h,d),m=Ma.getImageData(0,0,h,d).data);let f;if(t===4)f=new Int32Array(m);else{const w=h*d;f=new Int32Array(w*t);for(let L=0;L<w;L++)for(let x=0;x<t;++x)f[L*t+x]=m[L*4+x]}const b=[d,h,t];return WT(f,b,"int32")}async function JF(e,t){let n=W(e,"img","toPixels");if(!(e instanceof ee)){const d=n;n=Ae(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 f=d*4;h[f+0]=Math.round(m[0]),h[f+1]=Math.round(m[1]),h[f+2]=Math.round(m[2]),h[f+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 $T=z({fromPixels_:XF});var ZF=Object.freeze({__proto__:null,toPixels:JF,fromPixels:$T});function np(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=[...je(e.shape).map(d=>d/c),1].slice(0,s);return[a,i,c,h]}var QF=Object.freeze({__proto__:null,prepareAndValidate:np});function Ab(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 vb(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}`)}Ab(n,t,e)}function Pa(e,t,n){const s=t.shape.length,i=s>1?t.shape[s-1]:1,o=n.length;let a=1;for(let f=i;f<o;++f)a*=n[f];const c=i<1?1:i,h=P(t.shape)/c,d=[...je(n.slice(0,i)),1],m=P(n);return{sliceRank:i,numUpdates:h,sliceSize:a,strides:d,outputSize:m}}var e_=Object.freeze({__proto__:null,validateUpdateShape:Ab,validateInput:vb,calculateShapes:Pa});function Nb(e,t,n){const s=e.shape.length;A(s===t.length,()=>`Error in slice${s}D: Length of begin ${t} must match the rank of the array (${s}).`),A(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)A(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 sp(e){const t=[];let n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function ip(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 UT(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 BT(e,t,n){return n<=e?n:n-(t-1)}function MT(e,t){const n=[];for(let s=0;s<e;s++)n.push(t+s);return n}function PT(e,t,n,s,i,o,a,c,h){const d=e.length;let m=new Array(d),f=new Array(d),b=new Array(d);if(t.length&&n>0){const w=t[0],L=n+1;m=zT(a,w,L,s,e),f=VT(c,w,L,i,e),b=UT(o,w,L,e)}else for(let w=0;w<d;w++)m[w]=YT(a,s,o,e,w,h),f[w]=HT(c,i,o,e,w,h),b[w]=GT(o,w,h);return{begin:m,end:f,strides:b}}function zT(e,t,n,s,i){const o=[...i],a=MT(n,t);for(let c=0;c<o.length;c++)if(a.indexOf(c)>-1)o[c]=0;else{const h=BT(t,n,c);let d=s[h];e&1<<h&&(d=0),o[c]=d}return o}function VT(e,t,n,s,i){const o=[...i],a=MT(n,t);for(let c=0;c<o.length;c++)if(a.indexOf(c)>-1)o[c]=Number.MAX_SAFE_INTEGER;else{const h=BT(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]=S(0,o[c],i[c])}return o}function GT(e,t,n){let s=e[t];return(n&1<<t||s==null)&&(s=1),s}function YT(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=S(0,a,h-1),a}function HT(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=S(0,a,h):a=S(-1,a,h-1),a}function Cb(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 Rb(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 rp(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=>{A(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:(A(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 qT=Object.freeze({__proto__:null,assertParamsValid:Nb,maskToAxes:sp,computeOutShape:ip,stridesWithElidedDims:UT,getNormalizedAxes:PT,startIndicesWithElidedDims:zT,stopIndicesWithElidedDims:VT,stridesForAxis:GT,startForAxis:YT,stopForAxis:HT,isSliceContinous:Cb,computeFlatOffset:Rb,parseSliceParams:rp});class Fo{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class $s{constructor(){this.classNameMap={}}static getMap(){return $s.instance==null&&($s.instance=new $s),$s.instance}static register(e){$s.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function fe(e){A(e.className!=null,()=>"Class being registered does not have the static className property defined."),A(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),A(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),$s.register(e)}var t_=Object.freeze({__proto__:null,Serializable:Fo,SerializationMap:$s,registerClass:fe});const n_=.001,jT=.1;function s_(e,t,n){return n==null&&(n=op()),Ob(e,t,(s,i)=>Db(s,i,n))}function op(){return G.backend.floatPrecision()===32?n_:jT}function Ob(e,t,n){let s=!0;if((hn(e)||hn(t))&&(s=!1),hn(e)&&hn(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(!ae(a,c))throw new Error(`Arrays have different shapes. Actual: [${a}]. Expected: [${c}]`)}const i=hn(e)?e:te(e),o=hn(t)?t:te(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 i_(e,t){e().then(()=>t.fail(),()=>t())}function r_(e,t){const n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return qi(e)||qi(e[0])||qi(t)||qi(t[0])?Ob(e,n,(s,i)=>s==i):Ob(e,t,(s,i)=>Db(s,i,0))}function Eb(e,t,n){if(n==null&&(n=op()),!Db(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function Db(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function o_(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 a_(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}var c_=Object.freeze({__proto__:null,TEST_EPSILON_FLOAT16:jT,expectArraysClose:s_,testEpsilon:op,expectPromiseToFail:i_,expectArraysEqual:r_,expectNumbersClose:Eb,expectValuesInRange:o_,expectArrayBuffersEqual:a_});const KT="2.7.0";function l_(){oe().set("PROD",!0)}function h_(){oe().set("DEBUG",!0)}function u_(){oe().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function un(e){oe().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}Yk(un);function d_(){G.disposeVariables()}function Ji(){return G}function ap(){return G.memory()}function p_(e){return G.profile(e)}function Q(e,t){return G.tidy(e,t)}function He(e){const t=ji(e);t.forEach(n=>n.dispose())}function bn(e){return G.keep(e)}function m_(e){return G.time(e)}function XT(e){return G.setBackend(e)}function f_(){return G.ready()}function g_(){return G.backendName}function y_(e){G.removeBackend(e)}function b_(e){return G.findBackend(e)}function w_(e){return G.findBackendFactory(e)}function kb(e,t,n=1){return G.registerBackend(e,t,n)}function JT(){return G.backend}function L_(e,t){oe().setPlatform(e,t)}function S_(e,t){let n=W(e,"a","add"),s=W(t,"b","add");[n,s]=Yt(n,s);const i=(a,c)=>{const h=a.add(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,Co)}const be=z({add_:S_});function I_(e,t){let n=W(e,"a","floorDiv"),s=W(t,"b","floorDiv");[n,s]=Yt(n,s);const i=(a,c)=>{const h=a.floorDiv(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,Ey)}const cp=z({floorDiv_:I_});function x_(e,t){let n=W(e,"a","div"),s=W(t,"b","div");if([n,s]=Yt(n,s),n.dtype==="int32"&&s.dtype==="int32")return cp(n,s);const i=(c,h)=>{const d=c.realDivide(n,s);return h([n,s]),d},o={a:n,b:s},a={};return G.runKernelFunc(i,o,null,Ra,a)}const We=z({div_:x_});function T_(e,t){let n=W(e,"a","mul"),s=W(t,"b","mul");[n,s]=Yt(n,s);const i=(a,c)=>{const h=a.multiply(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,Oa)}const X=z({mul_:T_});function A_(e){const t=W(e,"x","abs"),n={x:t};return G.runKernelFunc((s,i)=>(i([t]),t.dtype==="complex64"?s.complexAbs(t):s.abs(t)),n,null,ud)}const dn=z({abs_:A_});function v_(e){const t=W(e,"x","acos"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.acos(t);return i([t]),o},n,null,gl)}const Fb=z({acos_:v_});function N_(e){const t=W(e,"x","acosh"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.acosh(t);return i([t]),o},n,null,yl)}const _b=z({acosh_:N_});function C_(e){A(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),A(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(!ae(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 G.runKernelFunc(s,i,null,by)}const ZT=z({addN_:C_});function Wb(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function QT(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 An(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 vn(e,t){const n=t.map(s=>1);return QT(e,n,t)}function Xn(e,t,n){A(Wb(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function Jn(e,t){if(Wb(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 ph(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function cs(e,t){const n=[];for(let s=t-e;s<t;++s)n.push(s);return n}function R_(e,t=null,n=!1){let s=W(e,"x","all","bool");const i=c=>{const h=qe(t,s.shape);let d=h;const m=Jn(d,s.rank);m!=null&&(s=Ye(s,m),d=cs(d.length,s.rank));const f=c.all(s,d);if(n){const b=vn(f.shape,h);return K(f,b)}return f},o={x:s},a={axis:t,keepDims:n};return G.runKernelFunc(i,o,null,Wx,a)}const lp=z({all_:R_});function O_(e,t=null,n=!1){let s=W(e,"x","any","bool");const i=c=>{const h=qe(t,s.shape);let d=h;const m=Jn(d,s.rank);m!=null&&(s=Ye(s,m),d=cs(d.length,s.rank));const f=c.any(s,d);if(n){const b=vn(f.shape,h);return K(f,b)}return f},o={x:s},a={axis:t,keepDims:n};return G.runKernelFunc(i,o,null,$x,a)}const mh=z({any_:O_});function E_(e,t=0){let n=W(e,"x","argMax");const s=(a,c)=>{c([n]);let h=qe(t,n.shape);const d=Jn(h,n.rank);return d!=null&&(n=Ye(n,d),h=cs(h.length,n.rank)),a.argMax(n,h[0])},i={x:n},o={axis:t};return G.runKernelFunc(s,i,null,wy,o)}const fh=z({argMax_:E_});function D_(e,t=0){let n=W(e,"x","argMin");const s=(a,c)=>{c([n]),t==null&&(t=0);let h=qe(t,n.shape);const d=Jn(h,n.rank);return d!=null&&(n=Ye(n,d),h=cs(h.length,n.rank)),a.argMin(n,h[0])},i={x:n},o={axis:t};return G.runKernelFunc(s,i,null,Ly,o)}const $b=z({argMin_:D_});function k_(e){const t=W(e,"x","asin"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.asin(t);return i([t]),o},n,null,bl)}const Ub=z({asin_:k_});function F_(e){const t=W(e,"x","asinh"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.asinh(t);return i([t]),o},n,null,wl)}const Bb=z({asinh_:F_});function __(e){const t=W(e,"x","atan"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.atan(t);return i([t]),o},n,null,Ll)}const Mb=z({atan_:__});function W_(e,t){let n=W(e,"a","atan2"),s=W(t,"b","atan2");[n,s]=Yt(n,s);const i=(a,c)=>{const h=a.atan2(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,dd)}const Pb=z({atan2_:W_});function $_(e){const t=W(e,"x","atanh"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.atanh(t);return i([t]),o},n,null,Sl)}const zb=z({atanh_:$_});function hp(e,t,n,s,i="NHWC",o){const a=e[3],c=[...t,a],h=$r(i);return Fn(e,c,n,o,s,null,null,h)}function Un(e,t,n,s,i,o,a="channelsLast"){const[c,h]=up(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 Fn(e,d,n,s,i,o,!1,a)}function gh(e,t,n,s,i,o,a="NDHWC"){const[c,h,d]=Gb(t);let m,f;if(a==="NDHWC")f="channelsLast",m=[c,h,d,e[4],e[4]];else if(a==="NCDHW")f="channelsFirst",m=[c,h,d,e[1],e[1]];else throw new Error(`Unknown dataFormat ${a}`);return _r(e,m,n,s,i,!1,f,o)}function Fn(e,t,n,s,i,o,a=!1,c="channelsLast"){let[h,d,m,f]=[-1,-1,-1,-1];if(c==="channelsLast")[h,d,m,f]=e;else if(c==="channelsFirst")[h,f,d,m]=e;else throw new Error(`Unknown dataFormat ${c}`);const[b,w,,L]=t,[x,v]=up(n),[N,O]=up(s),E=za(b,N),k=za(w,O),{padInfo:F,outHeight:U,outWidth:$}=M_(i,d,m,x,v,E,k,o,c),Y=a?L*f:L;let j;return c==="channelsFirst"?j=[h,Y,U,$]:c==="channelsLast"&&(j=[h,U,$,Y]),{batchSize:h,dataFormat:c,inHeight:d,inWidth:m,inChannels:f,outHeight:U,outWidth:$,outChannels:Y,padInfo:F,strideHeight:x,strideWidth:v,filterHeight:b,filterWidth:w,effectiveFilterHeight:E,effectiveFilterWidth:k,dilationHeight:N,dilationWidth:O,inShape:e,outShape:j,filterShape:t}}function _r(e,t,n,s,i,o=!1,a="channelsLast",c){let[h,d,m,f,b]=[-1,-1,-1,-1,-1];if(a==="channelsLast")[h,d,m,f,b]=e;else if(a==="channelsFirst")[h,b,d,m,f]=e;else throw new Error(`Unknown dataFormat ${a}`);const[w,L,x,,v]=t,[N,O,E]=Gb(n),[k,F,U]=Gb(s),$=za(w,k),Y=za(L,F),j=za(x,U),{padInfo:Z,outDepth:ie,outHeight:de,outWidth:he}=P_(i,d,m,f,N,O,E,$,Y,j,c),ue=o?v*b:v;let me;return a==="channelsFirst"?me=[h,ue,ie,de,he]:a==="channelsLast"&&(me=[h,ie,de,he,ue]),{batchSize:h,dataFormat:a,inDepth:d,inHeight:m,inWidth:f,inChannels:b,outDepth:ie,outHeight:de,outWidth:he,outChannels:ue,padInfo:Z,strideDepth:N,strideHeight:O,strideWidth:E,filterDepth:w,filterHeight:L,filterWidth:x,effectiveFilterDepth:$,effectiveFilterHeight:Y,effectiveFilterWidth:j,dilationDepth:k,dilationHeight:F,dilationWidth:U,inShape:e,outShape:me,filterShape:t}}function U_(e,t,n,s,i){s==null&&(s=Vb(e,t,n));const o=e[0],a=e[1],c=_o((o-t+2*s)/n+1,i);A(Le(c),()=>`The output # of rows (${c}) must be an integer. Change the stride and/or zero pad parameters`);const h=_o((a-t+2*s)/n+1,i);return A(Le(h),()=>`The output # of columns (${h}) must be an integer. Change the stride and/or zero pad parameters`),[c,h]}function B_(e,t,n,s,i,o){i==null&&(i=Vb(e,t,s));const a=e[0],c=e[1],h=e[2],d=_o((a-t+2*i)/s+1,o);A(Le(d),()=>`The output # of depths (${d}) must be an integer. Change the stride and/or zero pad parameters`);const m=_o((c-t+2*i)/s+1,o);A(Le(m),()=>`The output # of rows (${m}) must be an integer. Change the stride and/or zero pad parameters`);const f=_o((h-t+2*i)/s+1,o);return A(Le(f),()=>`The output # of columns (${f}) must be an integer. Change the stride and/or zero pad parameters`),[d,m,f,n]}function Vb(e,t,n,s=1){const i=za(t,s);return Math.floor((e[0]*(n-1)-n+i)/2)}function up(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function Gb(e){return typeof e=="number"?[e,e,e]:e}function za(e,t){return t<=1?e:e+(e-1)*(t-1)}function M_(e,t,n,s,i,o,a,c,h){let d,m,f;if(typeof e=="number"){const b=e===0?"VALID":"NUMBER";d={top:e,bottom:e,left:e,right:e,type:b};const w=U_([t,n],o,s,e,c);m=w[0],f=w[1]}else if(e==="same"){m=Math.ceil(t/s),f=Math.ceil(n/i);const b=Math.max(0,(m-1)*s+o-t),w=Math.max(0,(f-1)*i+a-n),L=Math.floor(b/2),x=b-L,v=Math.floor(w/2),N=w-v;d={top:L,bottom:x,left:v,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),f=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],x=h==="channelsLast"?e[2][1]:e[3][1],v=b===0&&w===0&&L===0&&x===0?"VALID":"EXPLICIT";d={top:b,bottom:w,left:L,right:x,type:v},m=_o((t-o+b+w)/s+1,c),f=_o((n-a+L+x)/i+1,c)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:d,outHeight:m,outWidth:f}}function P_(e,t,n,s,i,o,a,c,h,d,m){let f,b,w,L;if(typeof e=="number"){const x=e===0?"VALID":"NUMBER";f={top:e,bottom:e,left:e,right:e,front:e,back:e,type:x};const v=B_([t,n,s,1],c,1,i,e,m);b=v[0],w=v[1],L=v[2]}else if(e==="same"){b=Math.ceil(t/i),w=Math.ceil(n/o),L=Math.ceil(s/a);const x=(b-1)*i+c-t,v=(w-1)*o+h-n,N=(L-1)*a+d-s,O=Math.floor(x/2),E=x-O,k=Math.floor(v/2),F=v-k,U=Math.floor(N/2),$=N-U;f={top:k,bottom:F,left:U,right:$,front:O,back:E,type:"SAME"}}else if(e==="valid")f={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:f,outDepth:b,outHeight:w,outWidth:L}}function _o(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 Wr(e){const[t,n,s]=up(e);return t===1&&n===1&&s===1}function cn(e,t){return Wr(e)||Wr(t)}function $r(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function z_(e,t,n,s,i){const o=W(e,"x","avgPool","float32"),a=1;A(cn(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]])),A(c.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${c.rank}.`),i!=null&&A(Le(s),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);const d=(w,L)=>{const x=Un(c.shape,t,n,1,s,i);return L([c]),x.filterWidth===1&&x.filterHeight===1&&ae(x.inShape,x.outShape)?c.clone():w.avgPool(c,x)},m={x:c},f={filterSize:t,strides:n,pad:s,dimRoundingMode:i};let b=G.runKernelFunc(d,m,null,Il,f);return b=Ae(b,o.dtype),h?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const yh=z({avgPool_:z_});function V_(e,t,n,s,i,o="NDHWC",a){a==null?a=[1,1,1]:un("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]])),A(h.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${h.rank}.`),A(o==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${o}`),A(cn(n,a),()=>`Error in avgPool3d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),i!=null&&A(Le(s),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);const m=(L,x)=>{a==null&&(a=[1,1,1]);const v=gh(h.shape,t,n,a,s,i,o);return x([h]),L.avgPool3d(h,v)},f={x:h},b={filterSize:t,strides:n,pad:s,dimRoundingMode:i,dataFormat:o,dilations:a};let w=G.runKernelFunc(m,f,null,Sy,b);return w=Ae(w,h.dtype),d?K(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}const Yb=z({avgPool3d_:V_});function dp(e,t){const n=e[0].length;e.forEach((i,o)=>{A(i.length===n,()=>`Error in concat${n}D: rank of tensors[${o}] must be the same as the rank of the rest (${n})`)}),A(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++)A(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 Zi(e,t){const n=e[0].slice();for(let s=1;s<e.length;s++)n[t]+=e[s][t];return n}function G_(e,t=0){A(e.length>=1,()=>"Pass at least one tensor to concat");let n=uh(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=qe(t,n[0].shape)[0],d=Zi(n.map(b=>b.shape),h);if(P(d)===0)return sn([],d);if(n=n.filter(b=>b.size>0),n.length===1)return n[0];const m=n.map(b=>b.shape);dp(m,h);const f=a.concat(n,h);return c(n),f},i=n,o={axis:t};return G.runKernelFunc(s,i,null,Al,o)}const Ht=z({concat_:G_});function Y_(e){const t=W(e,"x","sigmoid"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.sigmoid(t);return i([o]),o},n,null,Zl)}const Ai=z({sigmoid_:Y_});function H_(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]=rp(s,t,n);return Nb(s,d,m),h([s]),c.slice(s,d,m)},o={x:s},a={begin:t,size:n};return G.runKernelFunc(i,o,null,_d,a)}const tt=z({slice_:H_});function q_(e){const t=W(e,"x","tanh"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.tanh(t);return i([o]),o},n,null,th)}const Va=z({tanh_:q_});function j_(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"),f=W(o,"h","basicLSTMCell"),b=Ht([d,f],1),w=ct(b,c),L=be(w,h),x=L.shape[0],v=L.shape[1]/4,N=[x,v],O=tt(L,[0,0],N),E=tt(L,[0,v],N),k=tt(L,[0,v*2],N),F=tt(L,[0,v*3],N),U=be(X(Ai(O),Va(E)),X(m,Ai(be(a,k)))),$=X(Va(U),Ai(F));return[U,$]}const K_=z({basicLSTMCell_:j_});function X_(e,t,n){const s=W(e,"x","batchToSpaceND"),i=t.reduce((h,d)=>h*d);A(s.rank>=1+t.length,()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`),A(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),A(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 G.runKernelFunc(o,a,null,Iy,c)}const bh=z({batchToSpaceND_:X_});function J_(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 Z_(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")),A(c.rank===h.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),A(m==null||c.rank===m.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),A(d==null||c.rank===d.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const f=J_(a),b=(v,N)=>(N([f,c,h,d]),v.batchNorm(f,pp(c),pp(h),pp(m),pp(d),o)),w={x:f,scale:d,offset:m,mean:c,variance:h},L={varianceEpsilon:o},x=G.runKernelFunc(b,w,null,Dl,L);return K(x,a.shape)}function pp(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 Wo=z({batchNorm_:Z_});function Q_(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")),A(a.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${a.rank}.`),A(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${c.rank}.`),A(h.rank===2||h.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${h.rank}.`),d!=null&&A(d.rank===2||d.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${d.rank}.`),m!=null&&A(m.rank===2||m.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${m.rank}.`),Wo(a,c,h,m,d,o)}const eA=z({batchNorm2d_:Q_});function eW(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")),A(a.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${a.rank}.`),A(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${c.rank}.`),A(h.rank===3||h.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${h.rank}.`),d!=null&&A(d.rank===3||d.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${d.rank}.`),m!=null&&A(m.rank===3||m.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${m.rank}.`),Wo(a,c,h,m,d,o)}const tA=z({batchNorm3d_:eW});function tW(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")),A(a.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${a.rank}.`),A(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${c.rank}.`),A(h.rank===4||h.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${h.rank}.`),d!=null&&A(d.rank===4||d.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${d.rank}.`),m!=null&&A(m.rank===4||m.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${m.rank}.`),Wo(a,c,h,m,d,o)}const nA=z({batchNorm4d_:tW});function nW(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,f)=>m>1?f:-1).filter(m=>m>=0);if(a.length===0)return Fr(n);const c=m=>m.tile(n,o),h={x:n},d={shape:t,inputShape:i};return G.runKernelFunc(c,h,null,xy,d)}const wh=z({broadcastTo_:nW});function sW(e){const t=W(e,"x","ceil"),n={x:t};return G.runKernelFunc(s=>s.ceil(t),n,null,xl)}const Hb=z({ceil_:sW});function iW(e,t,n){const s=W(e,"x","clipByValue");A(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 G.runKernelFunc((a,c)=>{const h=a.clip(s,t,n);return c([s]),h},i,null,Tl,o)}const Zn=z({clipByValue_:iW});function rW(e){return Ht(e,0)}const sA=z({concat1d_:rW});function oW(e,t){return Ht(e,t)}const iA=z({concat2d_:oW});function aW(e,t){return Ht(e,t)}const rA=z({concat3d_:aW});function cW(e,t){return Ht(e,t)}const oA=z({concat4d_:cW});function lW(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]])),A(d.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${d.rank}.`),A(h.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${h.rank}.`),a!=null&&A(Le(s),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`);const f=i==="NHWC"?d.shape[3]:d.shape[1];A(f===h.shape[2],()=>`Error in conv2d: depth of input (${f}) must match input depth for filter ${h.shape[2]}.`),A(cn(n,o),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`);const b=(v,N)=>{const O=$r(i),E=Fn(d.shape,h.shape,n,o,s,a,!1,O),k=v.conv2d(d,h,E);return N([d,h]),k},w={x:d,filter:h},L={strides:n,pad:s,dataFormat:i,dilations:o,dimRoundingMode:a},x=G.runKernelFunc(b,w,null,gd,L);return m?K(x,[x.shape[1],x.shape[2],x.shape[3]]):x}const Qi=z({conv2d_:lW});function hW(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]])),A(d.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${d.rank}.`),A(h.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${h.rank}.`),a!=null&&A(Le(s),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`),A(d.shape[2]===h.shape[1],()=>`Error in conv1d: depth of input (${d.shape[2]}) must match input depth for filter ${h.shape[1]}.`),A(cn(n,o),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${o}'`),A(i==="NWC",()=>`Error in conv1d: got dataFormat of ${i} but only NWC is currently supported.`);const f=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],x="NHWC",v=Qi(b,f,w,s,x,L,a);return m?K(v,[v.shape[2],v.shape[3]]):K(v,[v.shape[0],v.shape[2],v.shape[3]])}const mp=z({conv1d_:hW});function uW(e,t,n,s,i,o="NHWC",a){A(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]]),A(c.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${c.length}.`),A(h.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${h.rank}`),A(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);const m=o==="NHWC"?c[3]:c[1],f=o==="NHWC"?h.shape[3]:h.shape[1];A(m===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${m}) must match input depth for filter ${n.shape[2]}.`),A(f===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${f}) must match output depth for filter ${n.shape[3]}.`),a!=null&&A(Le(i),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${a} but got pad ${i}.`);const b=(v,N)=>{const O=1,E=$r(o),k=Fn(c,n.shape,s,O,i,a,!1,E),F=v.conv2dDerInput(h,n,k);return N([h,n]),F},w={dy:h,filter:n},L={strides:s,pad:i,dataFormat:o,dimRoundingMode:a,inputShape:c},x=G.runKernelFunc(b,w,null,yd,L);return d?K(x,[x.shape[1],x.shape[2],x.shape[3]]):x}const qb=z({conv2DBackpropInput_:uW});function dW(e,t,n,s,i,o){const a=W(e,"x","conv2dTranspose"),c=W(t,"filter","conv2dTranspose");return qb(n,a,c,s,i,"NHWC",o)}const fp=z({conv2dTranspose_:dW});function pW(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]])),A(h.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${h.rank}.`),A(c.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${c.rank}.`),A(h.shape[4]===c.shape[3],()=>`Error in conv3d: depth of input (${h.shape[4]}) must match input depth for filter ${c.shape[3]}.`),A(cn(n,o),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),A(i==="NDHWC",()=>`Error in conv3d: got dataFormat of ${i} but only NDHWC is currently supported.`);const m=(L,x)=>{const v=_r(h.shape,c.shape,n,o,s),N=L.conv3d(h,c,v);return x([h,c]),N},f={x:h,filter:c},b={strides:n,pad:s,dataFormat:i,dilations:o},w=G.runKernelFunc(m,f,null,bd,b);return d?K(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}const jb=z({conv3d_:pW});function mW(e,t,n,s,i){A(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];A(o.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${o.length}.`),A(a.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${a.rank}`),A(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),A(h===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${h}) must match input depth for filter ${n.shape[3]}.`),A(d===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${d}) must match output depth for filter ${n.shape[4]}.`);const m=L=>{const x=1,v=_r(o,n.shape,s,x,i);return L.conv3dDerInput(a,n,v)},f={dy:a,filter:n},b={pad:i,strides:s,inputShape:o},w=G.runKernelFunc(m,f,null,vy,b);return c?K(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}const aA=z({conv3DBackpropInput_:mW});function fW(e,t,n,s,i){const o=W(e,"x","conv3dTranspose"),a=W(t,"filter","conv3dTranspose");return aA(n,o,a,s,i)}const gW=z({conv3dTranspose_:fW});function yW(e){const t=W(e,"x","cos"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.cos(t);return i([t]),o},n,null,Ca)}const Lh=z({cos_:yW});function bW(e){const t=W(e,"x","cosh"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.cosh(t);return i([t]),o},n,null,vl)}const gp=z({cosh_:bW});function wW(e,t=0,n=!1,s=!1){const i=W(e,"x","cumsum"),o=(h,d)=>{const m=Jn([t],i.rank);let f=i;m!=null&&(f=Ye(i,m));const b=cs(1,i.rank)[0];let w=h.cumsum(f,b,n,s);if(d([i]),m!=null){const L=ph(m);w=Ye(w,L)}return w},a={x:i},c={axis:t,exclusive:n,reverse:s};return G.runKernelFunc(o,a,null,Ny,c)}const yp=z({cumsum_:wW});function LW(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];A(i*t>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${i} and ${t} for depthToSpace with input shape
|
|
${s.shape}`),A(o*t>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${o} and ${t} for depthToSpace with input shape
|
|
${s.shape}`),A(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 G.runKernelFunc(c,h,null,Mx,d)}const Kb=z({depthToSpace_:LW});function SW(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]])),A(d.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${d.rank}.`),A(h.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${h.rank}.`),A(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&&A(Le(s),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`);const f=(x,v)=>{o==null&&(o=[1,1]),A(cn(n,o),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`);const N=Fn(d.shape,h.shape,n,o,s,a,!0),O=x.depthwiseConv2D(d,h,N);return v([d,h]),O},b={x:d,filter:h},w={strides:n,pad:s,dataFormat:i,dilations:o,dimRoundingMode:a},L=G.runKernelFunc(f,b,null,wd,w);return m?K(L,[L.shape[1],L.shape[2],L.shape[3]]):L}const $o=z({depthwiseConv2d_:SW});function IW(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 G.runKernelFunc(n,s,null,Px)}const xW=z({diag_:IW});function TW(e,t,n,s,i=[1,1],o="NHWC"){const a=W(e,"x","dilation2d"),c=W(t,"filter","dilation2d");A(a.rank===3||a.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${a.rank}.`),A(c.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${c.rank}.`),A(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},f={strides:n,pad:s,dilations:i},b=G.runKernel(Ld,m,f);return d?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const Xb=z({dilation2d_:TW});function Uo(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 pn(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 nt(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 AW(e,t){let n=W(e,"a","equal"),s=W(t,"b","equal");[n,s]=Yt(n,s),nt(n.shape,s.shape);const i=a=>a.equal(n,s),o={a:n,b:s};return G.runKernelFunc(i,o,null,Vx)}const Qs=z({equal_:AW});function vW(e,t,n){const s=W(t,"a","where"),i=W(n,"b","where"),o=W(e,"condition","where","bool"),a=nt(s.shape,i.shape),c=wh(s,a),h=wh(i,a);o.rank===1&&A(o.shape[0]===s.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),o.rank!==1&&B(o.shape,h.shape,"Error in where: ");const d=(f,b)=>{const w=f.select(o,c,h);return b([o]),w},m={condition:o,t:c,e:h};return G.runKernelFunc(d,m,null,Xy)}const Bn=z({where_:vW});function NW(e){const t=W(e,"x","zerosLike"),n={x:t};return G.runKernelFunc(s=>s.zerosLike(t),n,null,sb)}const et=z({zerosLike_:NW});function CW(e,t){let n=W(e,"a","div"),s=W(t,"b","div");[n,s]=Yt(n,s);const i=We(n,s),o=et(i),a=Qs(s,o);return Bn(a,o,i)}const Jb=z({divNoNan_:CW});function RW(e,t){const n=W(e,"t1","dot"),s=W(t,"t2","dot");A((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(A(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=ct(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=ct(a,c);return K(h,[h.size])}else if(n.rank===2&&s.rank===1){const a=K(s,[-1,1]),c=ct(n,a);return K(c,[c.size])}else{const a=K(s,[s.shape[0],s.shape[1]]),c=ct(n,a);return c}}const cA=z({dot_:RW});function OW(e){const t=W(e,"x","elu"),n=(i,o)=>{const a=i.elu(t);return o([a]),a},s={x:t};return G.runKernelFunc(n,s,null,Nl)}const Ga=z({elu_:OW});function EW(e){let t=W(e,"x","erf");A(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=Ae(t,"float32"));const n={x:t};return G.runKernelFunc((s,i)=>{const o=s.erf(t);return i([t]),o},n,null,Cl)}const Zb=z({erf_:EW});function DW(e){const t=W(e,"x","exp"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.exp(t);return i([o]),o},n,null,Rl)}const Is=z({exp_:DW});function kW(e,t=0){const n=null,s=W(e,"x","expandDims",n);A(t<=s.rank,()=>"Axis must be <= rank of the tensor");const i=s.shape.slice();return t<0&&(A(-(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=z({expandDims_:kW});function FW(e){const t=W(e,"x","expm1"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.expm1(t);return i([t]),o},n,null,Ol)}const Qb=z({expm1_:FW});function _W(e,t){const n=null,s=W(e,"x","tile",n);A(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 G.runKernelFunc(i,a,null,eb,c,o)}const Ur=z({tile_:_W});function WW(e,t,n,s="float32"){t==null&&(t=e);const i=wt([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 Ur(Qn(a,0),[n[0],1,1]);if(n.length===2)return Ur(Qn(Qn(a,0),0),[n[0],n[1],1,1]);if(n.length===3)return Ur(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 bp=z({eye_:WW});function Ya(e,t,n){const s={shape:e,value:t,dtype:n};return G.runKernelFunc(i=>i.fill(e,t,n),{},null,Oy,s)}function $W(e){const t=W(e,"x","floor"),n={x:t};return G.runKernelFunc(s=>s.floor(t),n,null,El)}const Ha=z({floor_:$W});const ew=30;function Sh(e){return e<=ew?e:hd(e,Math.floor(Math.sqrt(e)))}function UW(e,t){let n=!1,s;for(e<=ew?(s=e,n=!0):s=hd(e,Math.floor(Math.sqrt(e)));!n;)s>t||s===e?n=!0:s=hd(e,s+1);return s}function BW(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 lA(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 MW=Object.freeze({__proto__:null,segOpComputeOptimalWindowSize:UW,computeOutShape:BW,collectGatherOpShapeInfo:lA});function PW(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=qe(n,s.shape)[0],f=lA(s,i,m),b=h.gather(s,K(i,[i.size]),m);return d([s,i]),K(b,f.outputShape)};return G.runKernelFunc(c,o,null,Dy,a)}const qa=z({gather_:PW});function zW(e,t){let n=W(e,"a","greater"),s=W(t,"b","greater");[n,s]=Yt(n,s),nt(n.shape,s.shape);const i=a=>a.greater(n,s),o={a:n,b:s};return G.runKernelFunc(i,o,null,Yx)}const xs=z({greater_:zW});function VW(e,t){let n=W(e,"a","greaterEqual"),s=W(t,"b","greaterEqual");[n,s]=Yt(n,s),nt(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 G.runKernelFunc(i,o,null,ky)}const er=z({greaterEqual_:VW});function GW(e){const t=W(e,"input","imag"),n=i=>i.imag(t),s={input:t};return G.runKernelFunc(n,s,null,vd)}const Ih=z({imag_:GW});function YW(e){const t=W(e,"x","isFinite"),n={x:t};return G.runKernelFunc(s=>s.isFinite(t),n,null,Fl)}const hA=z({isFinite_:YW});function HW(e){const t=W(e,"x","isInf"),n={x:t};return G.runKernelFunc(s=>s.isInf(t),n,null,_l)}const uA=z({isInf_:HW});function qW(e){const t=W(e,"x","isNaN"),n={x:t};return G.runKernelFunc(s=>s.isNaN(t),n,null,Wl)}const dA=z({isNaN_:qW});function jW(e,t){let n=W(e,"a","maximum"),s=W(t,"b","maximum");[n,s]=Yt(n,s),n.dtype==="bool"&&(n=Ae(n,"int32"),s=Ae(s,"int32")),nt(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 G.runKernelFunc(i,o,null,Wy)}const Us=z({maximum_:jW});function Ce(e,t){if((hn(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"&&hn(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");const n=[],s=[];return Dr(e,n,s,t)}function KW(e,t=.2){const n=W(e,"x","leakyRelu");return Us(X(Ce(t),n),n)}const wp=z({leakyRelu_:KW});function XW(e,t){let n=W(e,"a","less"),s=W(t,"b","less");[n,s]=Yt(n,s),nt(n.shape,s.shape);const i=a=>a.less(n,s),o={a:n,b:s};return G.runKernelFunc(i,o,null,Hx)}const xh=z({less_:XW});function JW(e,t){let n=W(e,"a","lessEqual"),s=W(t,"b","lessEqual");[n,s]=Yt(n,s),nt(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 G.runKernelFunc(i,o,null,qx)}const Br=z({lessEqual_:JW});function pA(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 G.runKernelFunc(i=>i.linspace(e,t,n),{},null,jx,s)}function ZW(e,t=5,n=1,s=1,i=.5){const o=W(e,"x","localResponseNormalization");A(o.rank===4||o.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
|
|
rank ${o.rank}.`),A(Le(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},f=G.runKernelFunc(h,d,null,_y,m);return c?K(f,[f.shape[1],f.shape[2],f.shape[3]]):f}const tw=z({localResponseNormalization_:ZW});function QW(e){const t=W(e,"x","log"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.log(t);return i([t]),o},n,null,$l)}const ls=z({log_:QW});function e$(e){const t=W(e,"x","log1p"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.log1p(t);return i([t]),o},n,null,Ul)}const Lp=z({log1p_:e$});function t$(e){return A(Or(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 G.tidy(()=>{const{value:o,grads:a}=G.gradients(()=>e(s),[s],i);return i!=null&&B(o.shape,i.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Sp(a),a[0]})}}function n$(e){return A(Or(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{A(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");const s=uh(t,"args","tf.grads",null),i=n!=null?W(n,"dy","tf.grads"):null;return G.tidy(()=>{const{value:o,grads:a}=G.gradients(()=>e(...s),s,i);return i!=null&&B(o.shape,i.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Sp(a),a})}}function s$(e){return A(Or(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{A(t instanceof ee,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),A(n==null||n instanceof ee,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");const{grads:s,value:i}=G.gradients(()=>e(t),[t],n);return Sp(s),{grad:s[0],value:i}}}function i$(e){return A(Or(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{A(Array.isArray(t)&&t.every(i=>i instanceof ee),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),A(n==null||n instanceof ee,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");const s=G.gradients(()=>e(...t),t,n);return n!=null&&B(s.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Sp(s.grads),s}}function nw(e,t){A(Or(e),()=>"The f passed in variableGrads(f) must be a function"),A(t==null||Array.isArray(t)&&t.every(d=>d instanceof lh),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const n=t!=null;if(!n){t=[];for(const d in G.registeredVariables)t.push(G.registeredVariables[d])}const s=n?t.filter(d=>!d.trainable):null,i=t.length;t=t.filter(d=>d.trainable),A(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}=G.gradients(e,t,null,o);A(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()."),A(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 vi(e){return G.customGrad(e)}function Sp(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 r$(e){const t=W(e,"x","neg"),n={x:t};return G.runKernelFunc(s=>s.neg(t),n,null,zy)}const qt=z({neg_:r$});function o$(e){const t=W(e,"x","softplus"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.softplus(t);return i([t]),o},n,null,Ql)}const ja=z({softplus_:o$});function a$(e){const t=W(e,"x","logSigmoid"),n=vi(s=>{const i=qt(ja(qt(s))),o=a=>{const c=X(a,Ai(qt(s)));return c};return{value:i,gradFunc:o}});return n(t)}const mA=z({logSigmoid_:a$});function c$(e,t=null,n=!1){const s=W(e,"x","max"),i=(c,h)=>{const d=qe(t,s.shape);let m=d;const f=Jn(m,s.rank);let b=s;f!=null&&(b=Ye(s,f),m=cs(m.length,b.rank));const w=c.max(b,m);f!=null&&b.dispose();let L=w;if(n){const x=vn(L.shape,qe(t,s.shape));L=K(L,x),w.dispose()}return h([s,L]),L},o={x:s},a={reductionIndices:t,keepDims:n};return G.runKernelFunc(i,o,null,Bl,a)}const es=z({max_:c$});function l$(e,t){let n=W(e,"a","sub"),s=W(t,"b","sub");[n,s]=Yt(n,s);const i=(a,c)=>{const h=a.subtract(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,ka)}const Re=z({sub_:l$});function h$(e,t=null,n=!1){let s=W(e,"x","sum");s.dtype==="bool"&&(s=Ae(s,"int32"));const i=(c,h)=>{h([s]);const d=qe(t,s.shape),m=Jn(d,s.rank);let f=d,b=s;m!=null&&(b=Ye(s,m),f=cs(f.length,s.rank));let w=c.sum(b,f);if(n){const L=vn(w.shape,d);w=K(w,L)}return w},o={x:s},a={axis:t,keepDims:n};return G.runKernelFunc(i,o,null,Jy,a)}const $e=z({sum_:h$});function u$(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=es(e,t,!0),m=Re(e,d),f=Re(Ae(m,"float32"),ls($e(Is(m),t,h)));return c([f]),f},i={logits:n},o={axis:t};return G.runKernelFunc(s,i,null,Fy,o)}const Ip=z({logSoftmax_:u$});function d$(e,t=null,n=!1){const s=W(e,"x","logSumExp"),i=qe(t,s.shape),o=es(s,i,!0),a=Re(s,o),c=Is(a),h=$e(c,i),d=ls(h),m=be(K(o,d.shape),d);if(n){const f=vn(m.shape,i);return K(m,f)}return m}const sw=z({logSumExp_:d$});function p$(e,t){const n=W(e,"a","logicalAnd","bool"),s=W(t,"b","logicalAnd","bool");nt(n.shape,s.shape);const i={a:n,b:s};return G.runKernelFunc(o=>o.logicalAnd(n,s),i,null,Kx)}const Bs=z({logicalAnd_:p$});function m$(e){const t=W(e,"x","logicalNot","bool"),n={x:t};return G.runKernelFunc(s=>s.logicalNot(t),n,null,Nd)}const Th=z({logicalNot_:m$});function f$(e,t){const n=W(e,"a","logicalOr","bool"),s=W(t,"b","logicalOr","bool");nt(n.shape,s.shape);const i={a:n,b:s};return G.runKernelFunc(o=>o.logicalOr(n,s),i,null,Xx)}const xp=z({logicalOr_:f$});function g$(e,t){const n=W(e,"a","logicalXor","bool"),s=W(t,"b","logicalXor","bool");return nt(n.shape,s.shape),Bs(xp(e,t),Th(Bs(e,t)))}const fA=z({logicalXor_:g$});function y$(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]])),A(c.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${c.rank}.`),A(cn(n,a),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),i!=null&&A(Le(s),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);const d=(w,L)=>{const x=Un(c.shape,t,n,1,s,i);let v;return x.filterWidth===1&&x.filterHeight===1&&ae(x.inShape,x.outShape)?v=c.clone():v=w.maxPool(c,x),L([c,v]),v},m={x:c},f={filterSize:t,strides:n,pad:s,dimRoundingMode:i},b=G.runKernelFunc(d,m,null,Ml,f);return h?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const Ah=z({maxPool_:y$});function b$(e,t=[1,1,1],n,s,i,o="NDHWC",a){a==null?a=[1,1,1]:un("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]])),A(h.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${h.rank}.`),A(o==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${o}`),A(cn(n,a),()=>`Error in maxPool3d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),i!=null&&A(Le(s),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);const m=(L,x)=>{a==null&&(a=[1,1,1]);const v=gh(h.shape,t,n,a,s,i,o),N=L.maxPool3d(h,v);return x([h,N]),N},f={x:h},b={filterSize:t,strides:n,pad:s,dimRoundingMode:i,dataFormat:o,dilations:a},w=G.runKernelFunc(m,f,null,$y,b);return d?K(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}const iw=z({maxPool3d_:b$});function w$(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=G.runKernel(Rd,a,c);return{result:h[0],indexes:h[1]}}const gA=z({maxPoolWithArgmax_:w$});function dt(e,t="float32"){if(t==="complex64"){const s=dt(e,"float32"),i=dt(e,"float32");return Xi(s,i)}const n=va(P(e),t);return G.makeTensor(n,e,t)}function ei(e,t="float32"){if(t==="complex64"){const s=ei(e,"float32"),i=dt(e,"float32");return Xi(s,i)}const n=my(P(e),t);return G.makeTensor(n,e,t)}function L$(e,t=null,n=!1){const s=W(e,"x","mean"),i=qe(t,s.shape),o=An(s.shape,i),a=o[1],c=P(a),h={x:s},d={axis:t,keepDims:n},m=()=>{const b=Ce(c),w=b.dtype===s.dtype?s:Ae(s,b.dtype),L=We(w,b);return $e(L,t,n)},f=vi(b=>{const w=G.runKernelFunc(m,h,null,Uy,d),L=x=>{const v=b.shape.slice();i.forEach(E=>{v[E]=1});const N=K(x,v),O=We(X(N,ei(b.shape,"float32")),c);return O};return{value:w,gradFunc:L}});return f(s)}const jt=z({mean_:L$});function S$(e,t=null,n=!1){const s=W(e,"x","min"),i=(c,h)=>{const d=qe(t,s.shape);let m=d;const f=Jn(m,s.rank);let b=s;f!=null&&(b=Ye(s,f),m=cs(m.length,s.rank));const w=c.min(b,m);f!=null&&b.dispose();let L=w;if(n){const x=vn(L.shape,d);L=K(w,x),w.dispose()}return h([s,L]),L},o={x:s},a={axis:t,keepDims:n};return G.runKernelFunc(i,o,null,By,a)}const Ka=z({min_:S$});function I$(e,t){let n=W(e,"a","minimum"),s=W(t,"b","minimum");[n,s]=Yt(n,s),n.dtype==="bool"&&(n=Ae(n,"int32"),s=Ae(s,"int32")),nt(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 G.runKernelFunc(i,o,null,My)}const Bo=z({minimum_:I$});function x$(e,t,n){A(n==="reflect"||n==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);const s=W(e,"x","mirrorPad");if(s.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");A(t.length===s.rank,()=>`Padding doesn't match input. Must be ${s.rank}. Got ${t.length}.`);const i=n==="reflect"?1:0;for(let c=0;c<s.rank;c++)A(t[c].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),A(t[c][0]>=0&&t[c][0]<=s.shape[c]-i&&t[c][1]>=0&&t[c][1]<=s.shape[c]-i,()=>`Padding in dimension ${c} cannot be greater than or equal to ${s.shape[c]-i} or less than 0 for input of shape ${s.shape}`);const o={paddings:t,mode:n},a={x:s};return G.runKernel(Pl,a,o)}const rw=z({mirrorPad_:x$});function T$(e,t){let n=W(e,"a","mod"),s=W(t,"b","mod");[n,s]=Yt(n,s);const i=(a,c)=>{const h=a.mod(n,s);return c([n,s]),h},o={a:n,b:s};return G.runKernelFunc(i,o,null,Py)}const Tp=z({mod_:T$});function A$(e){const t=W(e,"x","square"),n={},s=[t],i=[];return G.runKernelFunc((o,a)=>(a([t]),o.square(t)),{x:t},null,"Square",n,s,i)}const At=z({square_:A$});function v$(e,t=null,n=!1){e=W(e,"x","moments");const s=qe(t,e.shape),i=jt(e,s,n);let o=i.shape;n||(o=vn(i.shape,s));const a=At(Re(Ae(e,"float32"),K(i,o))),c=jt(a,s,n);return{mean:i,variance:c}}const Ap=z({moments_:v$});function N$(e,t,n,s){const i=W(t,"data","multiRNNCell"),o=uh(n,"c","multiRNNCell"),a=uh(s,"h","multiRNNCell");let c=i;const h=[];for(let f=0;f<e.length;f++){const b=e[f](c,o[f],a[f]);h.push(b[0]),h.push(b[1]),c=b[1]}const d=[],m=[];for(let f=0;f<h.length;f+=2)d.push(h[f]),m.push(h[f+1]);return[d,m]}const C$=z({multiRNNCell_:N$});function R$(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=G.runKernelFunc(d=>d.multinomial(c,s,t,n),{logits2D:c});return a===1?K(h,[h.size]):h}const yA=z({multinomial_:R$});function O$(e,t){let n=W(e,"a","notEqual"),s=W(t,"b","notEqual");[n,s]=Yt(n,s),nt(n.shape,s.shape);const i=a=>a.notEqual(n,s),o={a:n,b:s};return G.runKernelFunc(i,o,null,zl)}const Mr=z({notEqual_:O$});function E$(e){const t=W(e,"input","real"),n=i=>i.real(t),s={input:t};return G.runKernelFunc(n,s,null,Fd)}const Xa=z({real_:E$});function D$(e){const t=W(e,"x","onesLike"),n=(i,o)=>{if(t.dtype==="complex64"){const a=_n(Xa(t)),c=et(Ih(t));return Xi(a,c)}return i.onesLike(t)},s={x:t};return G.runKernelFunc(n,s,null,Gy)}const _n=z({onesLike_:D$});function k$(e,t){const n=W(e,"v1","outerProduct"),s=W(t,"v2","outerProduct");A(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 ct(i,o)}const F$=z({outerProduct_:k$});function _$(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 G.runKernelFunc(i,a,null,Dd,o)}const Ni=z({pad_:_$});function W$(e,t,n=0){return A(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),Ni(e,[t],n)}const $$=z({pad1d_:W$});function U$(e,t,n=0){return A(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Ni(e,t,n)}const B$=z({pad2d_:U$});function M$(e,t,n=0){return A(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."),Ni(e,t,n)}const P$=z({pad3d_:M$});function z$(e,t,n=0){return A(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."),Ni(e,t,n)}const V$=z({pad4d_:z$});function G$(e,t,n){const s=W(e,"x","spaceToBatchND");A(s.rank>=1+t.length,()=>`input rank ${s.rank} should be > than [blockShape] ${t.length}`),A(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),A(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 G.runKernelFunc(i,o,null,Wd,a)}const vh=z({spaceToBatchND_:G$});function Y$(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]])),A(cn(o,i),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${o} and dilations '${i}'`);const d=Un(c.shape,t,o,i,s),m=[d.dilationHeight,d.dilationWidth];let f;s==="same"?f=q$([d.filterHeight,d.filterWidth],m):f=[[0,0],[0,0]];const b=m[0]===1&&m[1]===1,[w,L]=H$([d.inHeight,d.inWidth],m,f),x=b?s:"valid",v=b?c:vh(c,m,w),N=n==="avg"?()=>yh(v,t,o,x):()=>Ah(v,t,o,x),O=N(),E=b?O:bh(O,m,L);return h?K(E,[E.shape[1],E.shape[2],E.shape[3]]):E}function H$(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,f)=>(m-o[f]%m)%m),c=i.map((m,f)=>m+a[f]),h=t.map((m,f)=>[s[f],c[f]]),d=t.map((m,f)=>[0,a[f]]);return[h,d]}function q$(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 bA=z({pool_:Y$});function j$(e,t){let n=W(e,"base","pow"),s=W(t,"exp","pow");[n,s]=Yt(n,s);const i={a:n,b:s},o=(a,c)=>{const h=a.pow(n,s);return c([n,s,h]),h};return G.runKernelFunc(o,i,null,Hy)}const ti=z({pow_:j$});function K$(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 G.runKernelFunc(i,o,null,kd)}const Nh=z({prelu_:K$});function X$(e,t=null,n=!1){let s=W(e,"x","prod");s.dtype==="bool"&&(s=Ae(s,"int32"));const i=c=>{const h=qe(t,s.shape),d=Jn(h,s.rank);let m=h,f=s;d!=null&&(f=Ye(s,d),m=cs(m.length,s.rank));let b=c.prod(f,m);if(n){const w=vn(b.shape,h);b=K(b,w)}return b},o={x:s},a={axis:t,keepDims:n};return G.runKernelFunc(i,o,null,Qx,a)}const vp=z({prod_:X$});function J$(e,t,n){const s=P(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 G.makeTensor(i,e,n)}const Z$=z({rand_:J$});var Ja=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function Aee(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Mo(e,t){return t={exports:{}},e(t,t.exports),t.exports}function vee(e){return e&&e.default||e}function Nee(){throw new Error("Dynamic requires are not currently supported by @rollup/plugin-commonjs")}var Q$=Mo(function(e){(function(t,n,s){function i(h){var d=this,m=c();d.next=function(){var f=2091639*d.s0+d.c*23283064365386963e-26;return d.s0=d.s1,d.s1=d.s2,d.s2=f-(d.c=f|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),f=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,f&&(typeof f=="object"&&o(f,m),b.state=function(){return o(m,{})}),b}function c(){var h=4022871197,d=function(m){m=m.toString();for(var f=0;f<m.length;f++){h+=m.charCodeAt(f);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})(Ja,e,!1)}),eU=Mo(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 f=h.x^h.x<<11;return h.x=h.y,h.y=h.z,h.z=h.w,h.w^=h.w>>>19^f^f>>>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,f=function(){return(d.next()>>>0)/4294967296};return f.double=function(){do var b=d.next()>>>11,w=(d.next()>>>0)/4294967296,L=(b+w)/(1<<21);while(L===0);return L},f.int32=d.next,f.quick=f,m&&(typeof m=="object"&&o(m,d),f.state=function(){return o(d,{})}),f}n&&n.exports?n.exports=a:s&&s.amd?s(function(){return a}):this.xor128=a})(Ja,e,!1)}),tU=Mo(function(e){(function(t,n,s){function i(c){var h=this,d="";h.next=function(){var f=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^(f^f<<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,f=function(){return(d.next()>>>0)/4294967296};return f.double=function(){do var b=d.next()>>>11,w=(d.next()>>>0)/4294967296,L=(b+w)/(1<<21);while(L===0);return L},f.int32=d.next,f.quick=f,m&&(typeof m=="object"&&o(m,d),f.state=function(){return o(d,{})}),f}n&&n.exports?n.exports=a:s&&s.amd?s(function(){return a}):this.xorwow=a})(Ja,e,!1)}),nU=Mo(function(e){(function(t,n,s){function i(c){var h=this;h.next=function(){var m=h.x,f=h.i,b,w,L;return b=m[f],b^=b>>>7,w=b^b<<24,b=m[f+1&7],w^=b^b>>>10,b=m[f+3&7],w^=b^b>>>3,b=m[f+4&7],w^=b^b<<7,b=m[f+7&7],b=b^b<<13,w^=b^b<<9,m[f]=w,h.i=f+1&7,w};function d(m,f){var b,w,L=[];if(f===(f|0))w=L[0]=f;else for(f=""+f,b=0;b<f.length;++b)L[b&7]=L[b&7]<<15^f.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,f=function(){return(d.next()>>>0)/4294967296};return f.double=function(){do var b=d.next()>>>11,w=(d.next()>>>0)/4294967296,L=(b+w)/(1<<21);while(L===0);return L},f.int32=d.next,f.quick=f,m&&(m.x&&o(m,d),f.state=function(){return o(d,{})}),f}n&&n.exports?n.exports=a:s&&s.amd?s(function(){return a}):this.xorshift7=a})(Ja,e,!1)}),sU=Mo(function(e){(function(t,n,s){function i(c){var h=this;h.next=function(){var m=h.w,f=h.X,b=h.i,w,L;return h.w=m=m+1640531527|0,L=f[b+34&127],w=f[b=b+1&127],L^=L<<13,w^=w<<17,L^=L>>>15,w^=w>>>12,L=f[b]=L^w,h.i=b,L+(m^m>>>16)|0};function d(m,f){var b,w,L,x,v,N=[],O=128;for(f===(f|0)?(w=f,f=null):(f=f+"\0",w=0,O=Math.max(O,f.length)),L=0,x=-32;x<O;++x)f&&(w^=f.charCodeAt((x+32)%f.length)),x===0&&(v=w),w^=w<<10,w^=w>>>15,w^=w<<4,w^=w>>>13,x>=0&&(v=v+1640531527|0,b=N[x&127]^=w+v,L=b==0?L+1:0);for(L>=128&&(N[(f&&f.length||0)&127]=-1),L=127,x=4*128;x>0;--x)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=v,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,f=function(){return(d.next()>>>0)/4294967296};return f.double=function(){do var b=d.next()>>>11,w=(d.next()>>>0)/4294967296,L=(b+w)/(1<<21);while(L===0);return L},f.int32=d.next,f.quick=f,m&&(m.X&&o(m,d),f.state=function(){return o(d,{})}),f}n&&n.exports?n.exports=a:s&&s.amd?s(function(){return a}):this.xor4096=a})(Ja,e,!1)}),iU=Mo(function(e){(function(t,n,s){function i(c){var h=this,d="";h.next=function(){var f=h.b,b=h.c,w=h.d,L=h.a;return f=f<<25^f>>>7^b,b=b-w|0,w=w<<24^w>>>8^L,L=L-f|0,h.b=f=f<<20^f>>>12^b,h.c=b=b-w|0,h.d=w<<16^b>>>16^L,h.a=L-f|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,f=function(){return(d.next()>>>0)/4294967296};return f.double=function(){do var b=d.next()>>>11,w=(d.next()>>>0)/4294967296,L=(b+w)/(1<<21);while(L===0);return L},f.int32=d.next,f.quick=f,m&&(typeof m=="object"&&o(m,d),f.state=function(){return o(d,{})}),f}n&&n.exports?n.exports=a:s&&s.amd?s(function(){return a}):this.tychei=a})(Ja,e,!1)}),Po=Mo(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,f=i-1,b;function w(k,F,U){var $=[];F=F==!0?{entropy:!0}:F||{};var Y=N(v(F.entropy?[k,E(t)]:k==null?O():k,3),$),j=new L($),Z=function(){for(var ie=j.g(o),de=h,he=0;ie<d;)ie=(ie+he)*i,de*=i,he=j.g(1);for(;ie>=m;)ie/=2,de/=2,he>>>=1;return(ie+he)/de};return Z.int32=function(){return j.g(4)|0},Z.quick=function(){return j.g(4)/4294967296},Z.double=Z,N(E(j.S),t),(F.pass||U||function(ie,de,he,ue){return ue&&(ue.S&&x(ue,j),ie.state=function(){return x(j,{})}),he?(n[c]=ie,de):ie})(Z,Y,"global"in F?F.global:this==n,F.state)}n["seed"+c]=w;function L(k){var F,U=k.length,$=this,Y=0,j=$.i=$.j=0,Z=$.S=[];for(U||(k=[U++]);Y<i;)Z[Y]=Y++;for(Y=0;Y<i;Y++)Z[Y]=Z[j=f&j+k[Y%U]+(F=Z[Y])],Z[j]=F;($.g=function(ie){for(var de,he=0,ue=$.i,me=$.j,ce=$.S;ie--;)de=ce[ue=f&ue+1],he=he*i+ce[f&(ce[ue]=ce[me=f&me+de])+(ce[me]=de)];return $.i=ue,$.j=me,he})(i)}function x(k,F){return F.i=k.i,F.j=k.j,F.S=k.S.slice(),F}function v(k,F){var U=[],$=typeof k,Y;if(F&&$=="object")for(Y in k)try{U.push(v(k[Y],F-1))}catch(j){}return U.length?U:$=="string"?k:k+"\0"}function N(k,F){for(var U=k+"",$,Y=0;Y<U.length;)F[f&Y]=f&($^=F[f&Y]*19)+U.charCodeAt(Y++);return E(F)}function O(){try{var k;return b&&(k=b.randomBytes)?k=k(i):(k=new Uint8Array(i),(s.crypto||s.msCrypto).getRandomValues(k)),E(k)}catch($){var F=s.navigator,U=F&&F.plugins;return[+new Date,s,U,s.screen,E(t)]}}function E(k){return String.fromCharCode.apply(0,k)}if(N(n.random(),t),e.exports){e.exports=w;try{b=require("crypto")}catch(k){}}})([],Math)});Po.alea=Q$,Po.xor128=eU,Po.xorwow=tU,Po.xorshift7=nU,Po.xor4096=sU,Po.tychei=iU;var rU=Po,Za=rU.alea;class ow{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=Za(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 oU{constructor(e,t,n,s){this.alpha=e,this.beta=1/t,this.dtype=n;const i=s||Math.random();this.randu=Za(i.toString()),this.randn=new ow(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 aU{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=Za(s)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}function Cee(e){const t=e.length,n=hU(e),s=lU(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 Ree(e,t,n,s){s==null&&(s=op());const i=aw(e);Eb(i,t,s),Eb(cU(e,i),n,s)}function aw(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t/e.length}function cU(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 lU(e){const t=aw(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 hU(e){const t=aw(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 uU(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 oU(t,n,s,i),a=wt(e,s);for(let c=0;c<a.values.length;c++)a.values[c]=o.nextValue();return a.toTensor()}const dU=z({randomGamma_:uU});function pU(e,t=0,n=1,s,i){if(s!=null&&s==="bool")throw new Error(`Unsupported data type ${s}`);const o=new ow(t,n,s,!1,i),a=wt(e,s);for(let c=0;c<a.values.length;c++)a.values[c]=o.nextValue();return a.toTensor()}const cw=z({randomNormal_:pU});function mU(e,t=0,n=1,s="float32",i){const o=wt(e,s),a=new aU(t,n,null,i);for(let c=0;c<o.values.length;c++)o.values[c]=a.nextValue();return o.toTensor()}const zo=z({randomUniform_:mU});function hs(e,t){ne(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 Dr(e,s,n,t)}function Ch(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 dt([0],s);const d=Math.abs(Math.ceil((t-e)/n)),m=va(d,s);t<e&&n===1&&(n=-1),m[0]=e;for(let f=1;f<m.length;f++)m[f]=m[f-1]+n;return hs(m,s)},o={start:e,stop:t,step:n,dtype:s};return G.runKernelFunc(i,{},null,eT,o)}function fU(e){const t=W(e,"x","reciprocal"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.reciprocal(t);return i([t]),o},n,null,Vl)}const lw=z({reciprocal_:fU});function gU(e){const t=W(e,"x","relu"),n=(i,o)=>(o([t]),t.dtype==="bool"?Ae(t,"int32"):i.relu(t)),s={x:t};return G.runKernelFunc(n,s,null,Gl)}const Ci=z({relu_:gU});function yU(e){const t=W(e,"x","relu6"),n=(i,o)=>(o([t]),t.dtype==="bool"?Ae(t,"int32"):i.relu6(t)),s={x:t};return G.runKernelFunc(n,s,null,Hl)}const hw=z({relu6_:yU});function bU(e,t){const n=W(e,"x","reverse"),s=a=>{const c=qe(t,n.shape);if(n.rank===0)return Fr(n);const h=a.reverse(n,c);return K(h,n.shape)},i={x:n},o={dims:t};return G.runKernelFunc(s,i,null,Ky,o)}const Ts=z({reverse_:bU});function wU(e){const t=W(e,"x","reverse");return A(t.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),Ts(t,0)}const LU=z({reverse1d_:wU});function SU(e,t){const n=W(e,"x","reverse");return A(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),Ts(n,t)}const IU=z({reverse2d_:SU});function xU(e,t){const n=W(e,"x","reverse");return A(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),Ts(n,t)}const TU=z({reverse3d_:xU});function AU(e,t){const n=W(e,"x","reverse");return A(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),Ts(n,t)}const vU=z({reverse4d_:AU});function NU(e){const t=W(e,"x","round"),n={x:t};return G.runKernelFunc(s=>s.round(t),n,null,ql)}const uw=z({round_:NU});function CU(e){const t=W(e,"x","rsqrt"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.rsqrt(t);return i([t]),o},n,null,jl)}const Np=z({rsqrt_:CU});function RU(e){const t=W(e,"x","selu"),n=(i,o)=>{const a=i.selu(t);return o([t]),a},s={x:t};return G.runKernelFunc(n,s,null,Kl)}const Cp=z({selu_:RU});function OU(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,f=!1;if(c.rank===3&&(f=!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");A(m.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${m.rank}.`),A(h.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${h.rank}.`),A(d.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${h.rank}.`),A(d.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${d.shape[0]}.`),A(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];A(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=$o(m,h,s,i,a,o),x=1,v=Qi(L,d,x,"valid",a);return f?K(v,[v.shape[1],v.shape[2],v.shape[3]]):v}const dw=z({separableConv2d_:OU});async function EU(e,t){const n=W(e,"x","setdiff1d"),s=W(t,"y","setdiff1d");A(n.dtype===s.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${s.dtype}).`),A(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),A(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 an([c],n.dtype),d=new an([c],"int32");for(let m=0,f=0;m<i.length;m++)a.has(i[m])||(h.values[f]=i[m],d.values[f]=m,f++);return[h.toTensor(),d.toTensor()]}const wA=EU;function DU(e){const t=W(e,"x","sign"),n={x:t};return G.runKernelFunc(s=>s.sign(t),n,null,Jl)}const pw=z({sign_:DU});function kU(e){const t=W(e,"x","sin"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.sin(t);return i([t]),o},n,null,Ea)}const Rp=z({sin_:kU});function FU(e){const t=W(e,"x","sinh"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.sinh(t);return i([t]),o},n,null,Xl)}const Op=z({sinh_:FU});function _U(e,t,n){const s=W(e,"x","slice1d");return A(s.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`),tt(s,[t],[n])}const Ep=z({slice1d_:_U});function WU(e,t,n){const s=W(e,"x","slice2d");return A(s.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`),tt(s,t,n)}const mw=z({slice2d_:WU});function $U(e,t,n){const s=W(e,"x","slice3d");return A(s.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`),tt(s,t,n)}const Dp=z({slice3d_:$U});function UU(e,t,n){const s=W(e,"x","slice4d");return A(s.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`),tt(s,t,n)}const Rh=z({slice4d_:UU});function BU(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 G.runKernelFunc((o,a)=>{const c=o.softmax(n,t);return a([c]),c},s,null,Qy,i)}const Vo=z({softmax_:BU});function MU(e){A(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);const t={input:e};return G.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,xd)}const Oh=z({fft_:MU});function PU(e){A(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);const t={input:e};return G.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,Ad)}const Qa=z({ifft_:PU});function zU(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=Qa(i)}else{const i=[n,2*(t-1)],o=K(Xa(e),[n,t]),a=K(Ih(e),[n,t]),c=Ts(tt(o,[0,1],[n,t-2]),1),h=X(Ts(tt(a,[0,1],[n,t-2]),1),Ce(-1)),d=Ht([o,c],1),m=Ht([a,h],1),f=K(Xi(d,m),[i[0],i[1]]);s=Qa(f)}if(s=Xa(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 kp=z({irfft_:zU});function LA(e,t,n=0){let s=[];if(typeof t=="number")A(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);A(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}A(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 VU(e,t,n=0){const s=W(e,"x","split"),i=(c,h)=>{const d=qe(n,s.shape)[0],m=LA(s,t,d);return c.split(s,m,d)},o={x:s},a={numOrSizeSplits:t,axis:n};return G.runKernelFunc(i,o,null,Zy,a)}const us=z({split_:VU});function GU(e,t){A(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(v=>0),x=e.shape.map(v=>v);x[e.shape.length-1]=t,i=tt(e,L,x),n=t}else if(t!=null&&t>n){const L=e.shape.map(x=>x);L[e.shape.length-1]=t-n,i=Ht([e,dt(L)],e.shape.length-1),n=t}else i=e;const o=et(i),a=K(Xi(i,o),[s,n]),c=Oh(a),h=Math.floor(n/2)+1,d=Xa(c),m=Ih(c),f=us(d,[h,n-h],d.shape.length-1),b=us(m,[h,n-h],m.shape.length-1),w=i.shape.slice();return w[i.shape.length-1]=h,K(Xi(f[0],b[0]),w)}const Eh=z({rfft_:GU});function YU(e){const t=W(e,"x","sqrt"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.sqrt(t);return i([t]),o},n,null,eh)}const Nn=z({sqrt_:YU});function HU(e,t){let n=W(e,"a","squaredDifference"),s=W(t,"b","squaredDifference");[n,s]=Yt(n,s),nt(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 G.runKernelFunc(i,o,null,Da,a)}const Dh=z({squaredDifference_:HU});function qU(e,t){const n=W(e,"x","squeeze");return K(n,ln(n.shape,t).newShape)}const Pr=z({squeeze_:qU});function jU(e,t=0){const n=uh(e,"tensors","stack");if(A(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;A(t<=s,()=>"Axis must be <= rank of the tensor"),n.forEach(c=>{B(i,c.shape,"All tensors passed to stack must have matching shapes"),A(o===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});const a=n.map(c=>Qn(c,t));return Ht(a,t)}const ts=z({stack_:jU});function KU(e,t=0){const n=W(e,"x","step"),s={x:n},i={alpha:t};return G.runKernelFunc(o=>o.step(n,t),s,null,sh,i)}const ec=z({step_:KU});function XU(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=sp(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 x=d.rank-t.length,v=sp(c),N=d.shape.slice();v.forEach(Z=>{t[Z]=0,n[Z]=1,N.splice(Z,0,1)}),d=K(d,N);const{begin:O,end:E,strides:k}=PT(d.shape,L,x,t,n,s,i,o,a);t=O,n=E,s=k;const F=sp(h);F.forEach(Z=>{n[Z]=t[Z]+1,s[Z]=1});const U=ip(t,n,s),$=U.filter((Z,ie)=>F.indexOf(ie)===-1),Y=s.every(Z=>Z===1);if(Y)return K(tt(d,t,U),$);const j=w.stridedSlice(d,t,n,s);return K(j,$)},f={x:d},b={begin:t,end:n,strides:s,beginMask:i,endMask:o,ellipsisMask:a,newAxisMask:c,shrinkAxisMask:h};return G.runKernelFunc(m,f,null,rT,b)}const fw=z({stridedSlice_:XU});function JU(e){const t=W(e,"x","tan"),n={x:t};return G.runKernelFunc((s,i)=>{const o=s.tan(t);return i([t]),o},n,null,Fa)}const gw=z({tan_:JU});function zr(e,t,n){if(ne(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 Dr(e,t,s,n)}function tc(e,t,n){if(ne(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 Dr(e,t,s,n)}function ZU(e,t,n){if(ne(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 Dr(e,t,s,n)}function QU(e,t,n){if(ne(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,Dr(e,t,s,n)}function eB(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]=G.runKernelFunc(d=>d.topk(s,t,n),o,null,oT,a);return{values:c,indices:h}}const yw=z({topk_:eB});function tB(e,t=0,n=1,s,i){if(s!=null&&s==="bool")throw new Error("Unsupported data type $ { dtype }");const o=new ow(t,n,s,!0,i),a=wt(e,s);for(let c=0;c<a.values.length;c++)a.values[c]=o.nextValue();return a.toTensor()}const kh=z({truncatedNormal_:tB});function nB(e,t=0){const n=W(e,"x","unique",null);A(n.rank>0,()=>"The input tensor must be at least 1D");const s={x:n},i={axis:t},[o,a]=G.runKernel(Ud,s,i);return{values:o,indices:a}}const Fp=z({unique_:nB});function sB(e,t,n){const s=W(e,"x","unsortedSegmentSum"),i=W(t,"segmentIds","unsortedSegmentSum","int32");A(Le(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 G.runKernelFunc(c,o,null,nb,a)}const bw=z({unsortedSegmentSum_:sB});function iB(e,t=0){const n=W(e,"x","unstack");A(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 G.runKernelFunc(o,s,null,tb,i)}const ni=z({unstack_:iB});function SA(e,t=!0,n,s){return G.makeVariable(e,t,n,s)}function _p(e,t){const n=[];for(let o=0;o<t.length;o++)t[o]&&n.push(o);const s=wt(e,"int32"),i=wt([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 rB(e){const t=W(e,"condition","whereAsync","bool"),n=await t.data(),s=_p(t.shape,n);return e!==t&&t.dispose(),s}const ww=rB;async function oB(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;A(a>0,()=>"mask cannot be scalar"),B(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 x=o;x<o+a;x++)h*=c[x];const d=c.slice(0,o).concat([h],c.slice(o+a)),m=K(s,d),f=K(i,[-1]),b=await ww(f),w=Pr(b,[1]),L=qa(m,w,o);return e!==s&&s.dispose(),t!==i&&i.dispose(),w.dispose(),m.dispose(),f.dispose(),b.dispose(),L}const aB=oB;function cB(e,t){un("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 B(n.shape,s.shape,"Error in notEqualStrict: "),Mr(n,s)}function lB(e,t){un("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 B(n.shape,s.shape,"Error in lessStrict: "),xh(n,s)}function hB(e,t){un("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 B(n.shape,s.shape,"Error in equalStrict: "),Qs(n,s)}function uB(e,t){un("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 B(n.shape,s.shape,"Error in lessEqualStrict: "),Br(n,s)}function dB(e,t){un("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 B(n.shape,s.shape,"Error in greaterStrict: "),xs(n,s)}function pB(e,t){un("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 B(n.shape,s.shape,"Error in greaterEqualStrict: "),er(n,s)}const IA=z({equalStrict_:hB}),xA=z({greaterEqualStrict_:pB}),TA=z({greaterStrict_:dB}),AA=z({lessEqualStrict_:uB}),vA=z({lessStrict_:lB}),NA=z({notEqualStrict_:cB});function mB(e,t){un("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 B(n.shape,s.shape,"Error in addStrict: "),be(n,s)}function fB(e,t){un("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 B(n.shape,s.shape,"Error in subStrict: "),Re(n,s)}function gB(e,t){return un("strict variants of ops have been deprecated and will be removed in future"),B(e.shape,t.shape,"Error in powStrict: "),ti(e,t)}function yB(e,t){un("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 B(n.shape,s.shape,"Error in multiplyStrict: "),X(n,s)}function bB(e,t){un("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 B(n.shape,s.shape,"Error in divideStrict: "),We(n,s)}function wB(e,t){un("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 B(n.shape,s.shape,"Error in modStrict: "),Tp(n,s)}function LB(e,t){un("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 B(n.shape,s.shape,"Error in minimumStrict: "),Bo(n,s)}function SB(e,t){un("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 B(n.shape,s.shape,"Error in maximumStrict: "),Us(n,s)}function IB(e,t){un("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 B(n.shape,s.shape,"Error in squaredDifferenceStrict: "),Dh(n,s)}const CA=z({addStrict_:mB}),RA=z({divStrict_:bB}),OA=z({maximumStrict_:SB}),EA=z({minimumStrict_:LB}),DA=z({modStrict_:wB}),kA=z({mulStrict_:yB}),FA=z({powStrict_:gB}),_A=z({squaredDifferenceStrict_:IB}),WA=z({subStrict_:fB});function xB(e,t="euclidean",n=null,s=!1){e=W(e,"x","norm");const i=$A(e,t,n);let o=i.shape;if(s){const a=qe(n,e.shape);o=vn(i.shape,a)}return K(i,o)}function $A(e,t,n=null){if(e.rank===0)return dn(e);if(e.rank!==1&&n===null)return $A(K(e,[-1]),t,n);if(e.rank===1||typeof n=="number"||Array.isArray(n)&&n.length===1){if(t===1)return $e(dn(e),n);if(t===Infinity)return es(dn(e),n);if(t===-Infinity)return Ka(dn(e),n);if(t==="euclidean"||t===2)return Nn($e(ti(dn(e),Ce(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&n.length===2){if(t===1)return es($e(dn(e),n[0]),n[1]-1);if(t===Infinity)return es($e(dn(e),n[1]),n[0]);if(t===-Infinity)return Ka($e(dn(e),n[1]),n[0]);if(t==="fro"||t==="euclidean")return Nn($e(At(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const Wp=z({norm_:xB});function TB(e,t,n,s,i=!0){const o=W(e,"v","movingAverage"),a=W(t,"x","movingAverage"),c=W(n,"decay","movingAverage");pT(o,a),A(ae(o.shape,a.shape),()=>"Shape mismatch in v and x");const h=Ce(1),d=Re(h,c);let m=X(Re(a,o),d);if(i){A(s!=null,()=>"When using zeroDebias: true, step is required.");const f=W(s,"step","movingAverage");m=We(m,Re(h,ti(c,f)))}return be(o,m)}const AB=z({movingAverage_:TB});function vB(e,t,n){const s=W(e,"indices","scatterND","int32"),i=W(t,"updates","scatterND");vb(i,s,n);const o=h=>h.scatterND(s,i,n),a={indices:s,updates:i},c={shape:n};return G.runKernelFunc(o,a,null,sT,c)}const UA=z({scatterND_:vB});function NB(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 CB(e,t,n,s=0){const i=W(e,"sparseIndices","sparseToDense","int32"),o=W(t,"sparseValues","sparseToDense"),a=W(s,"defaultValue","sparseToDense",o.dtype);NB(i,o,n,a);const c={sparseIndices:i,sparseValues:o,defaultValue:a},h={outputShape:n};return G.runKernelFunc(d=>d.sparseToDense(i,o,n,a),c,null,iT,h)}const Lw=z({sparseToDense_:CB});function RB(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 G.runKernelFunc(i,o,null,Gx)}const BA=z({gatherND_:RB});function OB(e,t){if(t==null)return e.shape.slice();if(ae(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 EB(e,t,n,s){const i=W(e,"x","dropout");if(A(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.`),A(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof ee?i.clone():i;const o=OB(i,n),a=1-t,c=We(Ha(be(zo(o,0,1,"float32",s),a)),a);return X(i,c)}const MA=z({dropout_:EB});function PA(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function Sw(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 hs(i,"float32")}async function DB(e,t,n=1){const s=W(e,"predictions","inTopK"),i=W(t,"targets","inTopK");A(s.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${s.rank}`),A(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}`),B(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];A(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=bt("bool",h);for(let f=0;f<h;f++){const b=f*d,w=a.subarray(b,b+d),L=[];for(let x=0;x<w.length;x++)L.push({value:w[x],index:x});L.sort((x,v)=>v.value-x.value),m[f]=0;for(let x=0;x<n;x++)if(L[x].index===c[f]){m[f]=1;break}}return e!==s&&s.dispose(),t!==i&&i.dispose(),sn(m,i.shape,"bool")}const kB=DB;function FB(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]])),A(c.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${c.shape}.`),A(h.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${h.shape}.`),A(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];A(d===n[2],()=>`Error in conv2dDerFilter: depth of input ${d}) must match input depth in filter (${n[2]}.`),A(m===n[3],()=>`Error in conv2dDerFilter: depth of dy (${m}) must match output depth for filter (${n[3]}).`),a!=null&&A(Le(i),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${a} but got pad ${i}.`);const f=L=>{const x=1,v=$r(o),N=Fn(c.shape,n,s,x,i,a,!1,v);return L.conv2dDerFilter(c,h,N)},b={x:c,dy:h},w={strides:s,pad:i,dataFormat:o,dimRoundingMode:a,filterShape:n};return G.runKernelFunc(f,b,null,Ty,w)}const Iw=z({conv2DBackpropFilter_:FB});function $p(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return X(e,ec(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Up(e,t){let n=t;const s=pn(e.shape,t.shape);return s.length>0&&(n=$e(n,s)),K(n,e.shape)}function Bp(e,t,n){if(t==="linear")return e;if(t==="relu")return Ci(e);if(t==="elu")return Ga(e);if(t==="relu6")return hw(e);if(t==="prelu")return Nh(e,n);throw new Error(`Unknown fused activation ${t}.`)}const Mp=(e,t)=>{const n=e>0;return!n||t==="linear"};function _B({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",Mp(G.state.gradientDepth,h)===!1){let F=Qi(e,t,n,s,i,o,a);return c!=null&&(F=be(F,c)),Bp(F,h,d)}const m=W(e,"x","conv2d"),f=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]])),A(b.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${b.rank}.`),A(f.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${f.rank}.`),a!=null&&A(Le(s),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`),A(b.shape[3]===f.shape[2],()=>`Error in conv2d: depth of input (${b.shape[3]}) must match input depth for filter ${f.shape[2]}.`),A(cn(n,o),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),A(i==="NHWC",()=>`Error in conv2d: got dataFormat of ${i} but only NHWC is currently supported.`);const L=Fn(b.shape,f.shape,n,o,s,a);let x;c!=null&&(x=W(c,"bias","fused conv2d"),[x]=Yt(x,m),nt(L.outShape,x.shape));let v;d!=null&&(v=W(d,"prelu weights","fused conv2d"));const N=(F,U)=>{const[$,Y,j,Z]=U,ie=$p(F,j,h);A(Wr(o),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${o}'`);const de=qb(Y.shape,ie,$,n,s),he=Iw(Y,ie,$.shape,n,s),ue=[de,he];if(Z!=null){const me=Up(Z,ie);ue.push(me)}return ue},O=F=>{const U=F.fusedConv2d({input:b,filter:f,convInfo:L,bias:x,activation:h,preluActivationWeights:v});return U},E={x:b,filter:f,bias:x,preluActivationWeights:v},k={strides:n,pad:s,dataFormat:i,dilations:o,dimRoundingMode:a,activation:h};if(c==null){const F=vi((U,$,Y)=>{let j=G.runKernelFunc(O,E,null,zd,k);return Y([$,U,j]),w&&(j=K(j,[j.shape[1],j.shape[2],j.shape[3]])),{value:j,gradFunc:N}});return F(b,f)}else{const F=vi((U,$,Y,j)=>{let Z=G.runKernelFunc(O,E,null,zd,k);return j([$,U,Z,Y]),w&&(Z=K(Z,[Z.shape[1],Z.shape[2],Z.shape[3]])),{value:Z,gradFunc:N}});return F(b,f,x)}}const xw=z({fusedConv2d_:_B});function WB(e,t,n,s,i,o=[1,1],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]]));const d=b=>{const w=Fn(e.shape,n,s,o,i,a,!0);return b.depthwiseConv2DDerFilter(c,h,w)},m={x:c,dy:h},f={strides:s,pad:i,dimRoundingMode:a,dilations:o,filterShape:n};return G.runKernelFunc(d,m,null,Cy,f)}const zA=z({depthwiseConv2dNativeBackpropFilter_:WB});function $B(e,t,n,s,i,o=[1,1],a){let c=t,h=!1;t.rank===3&&(h=!0,c=K(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const d=w=>{const L=Fn(e,n.shape,s,o,i,a,!0);return w.depthwiseConv2DDerInput(c,n,L)},m={dy:c,filter:n},f={strides:s,pad:i,dimRoundingMode:a,dilations:o,inputShape:e},b=G.runKernelFunc(d,m,null,Ry,f);return h?K(b,[b.shape[1],b.shape[2],b.shape[3]]):b}const VA=z({depthwiseConv2dNativeBackpropInput_:$B});function UB({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(Mp(G.state.gradientDepth,h)===!1){let F=$o(e,t,n,s,i,o,a);return c!=null&&(F=be(F,c)),Bp(F,h,d)}const m=W(e,"x","depthwiseConv2d"),f=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]])),A(b.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${b.rank}.`),A(f.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${f.rank}.`),A(b.shape[3]===f.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${b.shape[3]}) must match the inChannels dimension in filter ${f.shape[2]}.`),o==null&&(o=[1,1]),A(cn(n,o),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),a!=null&&A(Le(s),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${a} but got pad ${s}.`);const L=Fn(b.shape,f.shape,n,o,s,a,!0);let x;c!=null&&(x=W(c,"bias","fused conv2d"),[x]=Yt(x,m),nt(L.outShape,x.shape));let v;d!=null&&(v=W(d,"prelu weights","fused depthwiseConv2d"));const N=(F,U)=>{A(Wr(o),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`);const[$,Y,j,Z]=U,ie=$p(F,j,h),de=VA(Y.shape,ie,$,n,s,o,a),he=zA(Y,ie,$.shape,n,s,o,a);if(Z!=null){const ue=Up(x,ie);return[de,he,ue]}return[de,he]},O=F=>{const U=F.fusedDepthwiseConv2D({input:b,filter:f,convInfo:L,bias:x,activation:h,preluActivationWeights:v});return U},E={x:b,filter:f,bias:x,preluActivationWeights:v},k={strides:n,pad:s,dataFormat:i,dilations:o,dimRoundingMode:a,activation:h};if(c==null){const F=vi((U,$,Y)=>{let j=G.runKernelFunc(O,E,null,Vd,k);return Y([$,U,j]),w&&(j=K(j,[j.shape[1],j.shape[2],j.shape[3]])),{value:j,gradFunc:N}});return F(b,f)}else{const F=vi((U,$,Y,j)=>{let Z=G.runKernelFunc(O,E,null,Vd,k);return j([$,U,Z,Y]),w&&(Z=K(Z,[Z.shape[1],Z.shape[2],Z.shape[3]])),{value:Z,gradFunc:N}});return F(b,f,x)}}const GA=z({fusedDepthwiseConv2d_:UB});function BB({a:e,b:t,transposeA:n=!1,transposeB:s=!1,bias:i,activation:o="linear",preluActivationWeights:a}){if(Mp(G.state.gradientDepth,o)===!1){let Z=ct(e,t,n,s);return i!=null&&(Z=be(Z,i)),Bp(Z,o,a)}let c=W(e,"a","fused matMul"),h=W(t,"b","fused matMul");[c,h]=Yt(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],f=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),x=P(w),v=P(L);A(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}.`),A(ae(w,L),()=>`Error in fused matMul: outer dimensions (${w}) and (${L}) of Tensors with shapes ${c.shape} and ${h.shape} must match.`),A(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([f,b]),O=n?K(c,[x,d,f]):K(c,[x,f,d]),E=s?K(h,[v,b,m]):K(h,[v,m,b]);let k;i!=null&&(k=W(i,"bias","fused matMul"),[k]=Yt(k,c),nt(N,k.shape));let F;a!=null&&(F=W(a,"prelu weights","fused matMul"));const U=(Z,ie)=>{const[de,he,ue,me]=ie,ce=$p(K(Z,ue.shape),ue,o);let ye,pe;if(!n&&!s?(ye=ct(ce,he,!1,!0),pe=ct(de,ce,!0,!1)):!n&&s?(ye=ct(ce,he,!1,!1),pe=ct(ce,de,!0,!1)):n&&!s?(ye=ct(he,ce,!1,!0),pe=ct(de,ce,!1,!1)):(ye=ct(he,ce,!0,!0),pe=ct(ce,de,!0,!0)),i!=null){const we=Up(me,ce);return[ye,pe,we]}else return[ye,pe]},$=Z=>{const ie=Z.fusedBatchMatMul({a:O,b:E,transposeA:n,transposeB:s,bias:k,activation:o,preluActivationWeights:F});return ie},Y={a:O,b:E,bias:k,preluActivationWeights:F},j={transposeA:n,transposeB:s,activation:o};if(i==null){const Z=vi((ie,de,he)=>{const ue=G.runKernelFunc($,Y,null,Pd,j);return he([ie,de,ue]),{value:K(ue,N),gradFunc:U}});return Z(O,E)}else{const Z=vi((ie,de,he,ue)=>{const me=G.runKernelFunc($,Y,null,Pd,j);return ue([ie,de,me,he]),{value:K(me,N),gradFunc:U}});return Z(O,E,k)}}const Pp=z({fusedMatMul_:BB});var MB=Object.freeze({__proto__:null,conv2d:xw,depthwiseConv2d:GA,matMul:Pp});function PB(e){return Sw(e,.54,.46)}const zB=z({hammingWindow_:PB});function VB(e){return Sw(e,.5,.5)}const YA=z({hannWindow_:VB});function GB(e,t,n,s=!1,i=0){let o=0;const a=[];for(;o+t<=e.size;)a.push(tt(e,o,t)),o+=n;if(s)for(;o<e.size;){const c=o+t-e.size,h=Ht([tt(e,o,t-c),Ya([c],i)]);a.push(h),o+=n}return a.length===0?zr([],[0,t]):K(Ht(a),[a.length,t])}const HA=z({frame_:GB});function YB(e,t,n,s,i=YA){s==null&&(s=PA(t));const o=HA(e,t,n),a=X(o,i(t)),c=[];for(let h=0;h<o.shape[0];h++)c.push(Eh(tt(a,[h,0],[1,t]),s));return Ht(c)}const HB=z({stft_:YB});function qB(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];A(a.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${a.rank}.`),A(c.rank===2&&c.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${d},4] but had shape ${c.shape}.`),A(h.rank===1&&h.shape[0]===d,()=>`Error in cropAndResize: boxInd must be have size [${d}] but had shape ${c.shape}.`),A(s.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`),A(s[0]>=1&&s[1]>=1,()=>`cropSize must be atleast [1,1], but was ${s}`),A(i==="bilinear"||i==="nearest",()=>`method must be bilinear or nearest, but was ${i}`);const m=L=>L.cropAndResize(a,c,h,s,i,o),f={image:a,boxes:c,boxInd:h},b={method:i,extrapolationValue:o,cropSize:s},w=G.runKernelFunc(m,f,null,Bx,b);return w}const jB=z({cropAndResize_:qB});function KB(e){const t=W(e,"image","flipLeftRight","float32");A(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);const n={image:t},s=G.runKernel(Td,n,{});return s}const XB=z({flipLeftRight_:KB});function JB(e,t,n=0,s=.5){const i=W(e,"image","rotateWithOffset","float32");A(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=G.runKernel(Md,o,a);return c}const ZB=z({rotateWithOffset_:JB});function nc(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),A(0<=s&&s<=1,()=>`iouThreshold must be in [0, 1], but was '${s}'`),A(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),A(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),A(t.rank===1,()=>"scores must be a 1D tensor"),A(t.shape[0]===a,()=>`scores has incompatible shape with boxes. Expected ${a}, but was ${t.shape[0]}`),A(0<=o&&o<=1,()=>`softNmsSigma must be in [0, 1], but was '${o}'`),{maxOutputSize:n,iouThreshold:s,scoreThreshold:i,softNmsSigma:o}}function QB(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY){const o=W(e,"boxes","nonMaxSuppression"),a=W(t,"scores","nonMaxSuppression"),c=nc(o,a,n,s,i);n=c.maxOutputSize,s=c.iouThreshold,i=c.scoreThreshold;const h={maxOutputSize:n,iouThreshold:s,scoreThreshold:i};return G.runKernelFunc(d=>d.nonMaxSuppression(o,a,n,s,i),{boxes:o,scores:a},null,Vy,h)}const eM=z({nonMaxSuppression_:QB});function tM(e,t,n){const s=nM(e,t,n),i=s<0?-(s+1):s;e.splice(i,0,t)}function nM(e,t,n){return iM(e,t,n||sM)}function sM(e,t){return e>t?1:e<t?-1:0}function iM(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 zp(e,t,n,s,i){return Tw(e,t,n,s,i,0).selectedIndices}function Vp(e,t,n,s,i,o){return Tw(e,t,n,s,i,0,!1,o,!0)}function Gp(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 v=0;v<t.length;v++)t[v]>i&&d.push({score:t[v],boxIndex:v,suppressBeginIndex:0});d.sort(qA);const m=o>0?-.5/o:0,f=[],b=[];for(;f.length<n&&d.length>0;){const v=d.pop(),{score:N,boxIndex:O,suppressBeginIndex:E}=v;if(N<i)break;let k=!1;for(let F=f.length-1;F>=E;--F){const U=rM(e,O,f[F]);if(U>=s){k=!0;break}if(v.score=v.score*oM(s,m,U),v.score<=i)break}v.suppressBeginIndex=f.length,k||(v.score===N?(f.push(O),b.push(v.score)):v.score>i&&tM(d,v,qA))}const w=f.length,L=n-w;c&&L>0&&(f.push(...new Array(L).fill(0)),b.push(...new Array(L).fill(0)));const x={selectedIndices:hs(f,"int32")};return a&&(x.selectedScores=hs(b,"float32")),h&&(x.validOutputs=Ce(w,"int32")),x}function rM(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]),f=Math.max(i[0],i[2]),b=Math.max(i[1],i[3]),w=(c-o)*(h-a),L=(f-d)*(b-m);if(w<=0||L<=0)return 0;const x=Math.max(o,d),v=Math.max(a,m),N=Math.min(c,f),O=Math.min(h,b),E=Math.max(N-x,0)*Math.max(O-v,0);return E/(w+L-E)}function oM(e,t,n){const s=Math.exp(t*n*n);return n<=e?s:0}function qA(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function aM(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY){const o=W(e,"boxes","nonMaxSuppressionAsync"),a=W(t,"scores","nonMaxSuppressionAsync"),c=nc(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],f=zp(d,m,n,s,i);return o!==e&&o.dispose(),a!==t&&a.dispose(),f}const cM=aM;function lM(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY,o=0){const a=W(e,"boxes","nonMaxSuppression"),c=W(t,"scores","nonMaxSuppression"),h=nc(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},f=G.runKernel(Ed,d,m);return{selectedIndices:f[0],selectedScores:f[1]}}const hM=z({nonMaxSuppressionWithScore_:lM});async function uM(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY,o=0){const a=W(e,"boxes","nonMaxSuppressionAsync"),c=W(t,"scores","nonMaxSuppressionAsync"),h=nc(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],f=d[1],b=Gp(m,f,n,s,i,o);return a!==e&&a.dispose(),c!==t&&c.dispose(),b}const dM=uM;function pM(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY,o=!1){const a=W(e,"boxes","nonMaxSuppression"),c=W(t,"scores","nonMaxSuppression"),h=nc(a,c,n,s,i,null),d=h.maxOutputSize,m=h.iouThreshold,f=h.scoreThreshold,b={boxes:a,scores:c},w={maxOutputSize:d,iouThreshold:m,scoreThreshold:f,padToMaxOutputSize:o},L=G.runKernel(Od,b,w);return{selectedIndices:L[0],validOutputs:L[1]}}const mM=z({nonMaxSuppressionPadded_:pM});async function fM(e,t,n,s=.5,i=Number.NEGATIVE_INFINITY,o=!1){const a=W(e,"boxes","nonMaxSuppressionAsync"),c=W(t,"scores","nonMaxSuppressionAsync"),h=nc(a,c,n,s,i,null),d=h.maxOutputSize,m=h.iouThreshold,f=h.scoreThreshold,[b,w]=await Promise.all([a.data(),c.data()]),L=Vp(b,w,d,m,f,o);return a!==e&&a.dispose(),c!==t&&c.dispose(),L}const gM=fM;function yM(e,t,n=!1){const s=W(e,"images","resizeBilinear");A(s.rank===3||s.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${s.rank}.`),A(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},f=G.runKernelFunc(h,d,null,jy,m);return o?K(f,[f.shape[1],f.shape[2],f.shape[3]]):f}const jA=z({resizeBilinear_:yM});function bM(e,t,n=!1){const s=W(e,"images","resizeNearestNeighbor");A(s.rank===3||s.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${s.rank}.`),A(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),A(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)),f=G.runKernelFunc(m,h,null,qy,d);return o?K(f,[f.shape[1],f.shape[2],f.shape[3]]):f}const KA=z({resizeNearestNeighbor_:bM});function wM(e,t,n){A(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),A(n%1===0,()=>`bandPart(): numUpper must be an integer, got ${n}.`);const s=W(e,"a","bandPart");A(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(Ch(0,o,1,"int32"),[-1,1]),h=Ch(0,a,1,"int32"),d=Re(c,h),m=Bs(Br(d,Ce(+t,"int32")),er(d,Ce(-n,"int32"))),f=dt([o,a],s.dtype);return K(ts(ni(K(s,[-1,o,a])).map(b=>Bn(m,b,f))),i)}const LM=z({bandPart_:wM});function SM(e){let t;if(Array.isArray(e)){t=!1,A(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)A(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=us(e,e.shape[0],0).map(i=>Pr(i,[0]));A(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(G.tidy(()=>{let o=s[i];if(i>0)for(let a=0;a<i;++a){const c=X($e(X(n[a],o)),n[a]);o=Re(o,c)}return We(o,Wp(o,"euclidean"))}));return t?ts(n,0):n}const IM=z({gramSchmidt_:SM});function xM(e,t=!1){if(A(e.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return XA(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce((h,d)=>h*d),s=ni(K(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),i=[],o=[];s.forEach(h=>{const[d,m]=XA(h,t);i.push(d),o.push(m)});const a=K(ts(i,0),e.shape),c=K(ts(o,0),e.shape);return[a,c]}}function XA(e,t=!1){return G.tidy(()=>{A(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=bp(n),o=Fr(e);const a=zr([[1]],[1,1]);let c=Fr(a);const h=n>=s?s:n;for(let d=0;d<h;++d){const m=o,f=c,b=i;[c,o,i]=G.tidy(()=>{const w=tt(o,[d,d],[n-d,1]),L=Wp(w),x=tt(o,[d,d],[1,1]),v=Bn(xs(x,0),zr([[-1]]),zr([[1]])),N=Re(x,X(v,L)),O=We(w,N);O.shape[0]===1?c=Fr(a):c=Ht([a,tt(O,[1,0],[O.shape[0]-1,O.shape[1]])],0);const E=qt(We(ct(v,N),L)),k=tt(o,[d,0],[n-d,s]),F=X(E,c),U=Ye(c);if(d===0)o=Re(k,ct(F,ct(U,k)));else{const j=Re(k,ct(F,ct(U,k)));o=Ht([tt(o,[0,0],[d,s]),j],0)}const $=Ye(F),Y=tt(i,[0,d],[n,i.shape[1]-d]);if(d===0)i=Re(Y,ct(ct(Y,c),$));else{const j=Re(Y,ct(ct(Y,c),$));i=Ht([tt(i,[0,0],[n,d]),j],1)}return[c,o,i]}),He([m,f,b])}return!t&&n>s&&(i=tt(i,[0,0],[n,s]),o=tt(o,[0,0],[s,s])),[i,o]})}const TM=z({qr_:xM});(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 AM(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 $e(o);if(n===r.Reduction.MEAN){if(i==null)return jt(o);{const a=s.size/i.size,c=We($e(o),$e(i));return a>1?We(c,Ce(a)):c}}if(n===r.Reduction.SUM_BY_NONZERO_WEIGHTS){if(i==null)return We($e(o),Ce(s.size));{const a=X(i,ei(s.shape)),c=Ae($e(Mr(a,Ce(0))),"float32");return We($e(o),c)}}throw Error(`Unknown reduction: ${n}`)}const tr=z({computeWeightedLoss_:AM});function vM(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")),B(i.shape,o.shape,"Error in absoluteDifference: ");const c=dn(Re(i,o));return tr(c,a,s)}const NM=z({absoluteDifference_:vM});function CM(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")),B(o.shape,a.shape,"Error in cosineDistance: ");const h=Ce(1),d=Re(h,$e(X(o,a),n,!0));return tr(d,c,i)}const RM=z({cosineDistance_:CM});function OM(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")),B(i.shape,o.shape,"Error in hingeLoss: ");const c=Ce(1);i=Re(X(Ce(2),i),c);const h=Ci(Re(c,X(i,o)));return tr(h,a,s)}const EM=z({hingeLoss_:OM});function DM(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")),B(o.shape,a.shape,"Error in huberLoss: ");const h=Ce(s),d=dn(Re(a,o)),m=Bo(d,h),f=Re(d,m),b=be(X(Ce(.5),At(m)),X(h,f));return tr(b,c,i)}const kM=z({huberLoss_:DM});function FM(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")),B(o.shape,a.shape,"Error in logLoss: ");const h=Ce(1),d=Ce(s),m=qt(X(o,ls(be(a,d)))),f=X(Re(h,o),ls(be(Re(h,a),d))),b=Re(m,f);return tr(b,c,i)}const _M=z({logLoss_:FM});function WM(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")),B(i.shape,o.shape,"Error in meanSquaredError: ");const c=Dh(i,o);return tr(c,a,s)}const $M=z({meanSquaredError_:WM});function UM(e,t){const n=W(e,"labels","sigmoidCrossEntropyWithLogits"),s=W(t,"logits","sigmoidCrossEntropyWithLogits");B(n.shape,s.shape,"Error in sigmoidCrossEntropyWithLogits: ");const i=Ci(s),o=X(s,n),a=Lp(Is(qt(dn(s))));return be(Re(i,o),a)}function BM(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")),B(o.shape,a.shape,"Error in sigmoidCrossEntropy: "),s>0){const d=Ce(s),m=Ce(1),f=Ce(.5);o=be(X(o,Re(m,d)),X(f,d))}const h=UM(o,a);return tr(h,c,i)}const MM=z({sigmoidCrossEntropy_:BM});function PM(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=vi((i,o,a)=>{const c=!0,h=sw(o,[n],c),d=Re(Ae(o,"float32"),h);a([i,d]);const m=qt(X(d,i)),f=$e(m,[n]),b=(w,L)=>{const[x,v]=L,N=vn(w.shape,[n]);return[X(K(w,N),Re(Ae(x,"float32"),Is(v))),X(K(w,N),Re(Is(v),Ae(x,"float32")))]};return{value:f,gradFunc:b}});return s(e,t)}function zM(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")),B(o.shape,a.shape,"Error in softmaxCrossEntropy: "),s>0){const d=Ce(s),m=Ce(1),f=Ce(o.shape[1]);o=be(X(o,Re(m,d)),We(d,f))}const h=PM(o,a);return tr(h,c,i)}const VM=z({softmaxCrossEntropy_:zM});const GM={fft:Oh,ifft:Qa,rfft:Eh,irfft:kp},YM={hammingWindow:zB,hannWindow:YA,frame:HA,stft:HB},Vr={flipLeftRight:XB,resizeNearestNeighbor:KA,resizeBilinear:jA,rotateWithOffset:ZB,cropAndResize:jB,nonMaxSuppression:eM,nonMaxSuppressionAsync:cM,nonMaxSuppressionWithScore:hM,nonMaxSuppressionWithScoreAsync:dM,nonMaxSuppressionPadded:mM,nonMaxSuppressionPaddedAsync:gM},JA={bandPart:LM,gramSchmidt:IM,qr:TM},HM={absoluteDifference:NM,computeWeightedLoss:tr,cosineDistance:RM,hingeLoss:EM,huberLoss:kM,logLoss:_M,meanSquaredError:$M,sigmoidCrossEntropy:MM,softmaxCrossEntropy:VM};class nr extends Fo{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 nw(e,t)}dispose(){this.iterations_!=null&&He(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Ce(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(nr,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});class Fh extends nr{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=G.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,s)=>{const i=G.registeredVariables[n],o=!1;this.accumulatedGrads[s]==null&&(this.accumulatedGrads[s]={originalName:`${n}/accum_grad`,variable:Q(()=>et(i).variable(o))}),this.accumulatedUpdates[s]==null&&(this.accumulatedUpdates[s]={originalName:`${n}/accum_var`,variable:Q(()=>et(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;Q(()=>{const d=be(X(c,this.rho),X(At(a),1-this.rho)),m=X(We(Nn(be(h,this.epsilon)),Nn(be(c,this.epsilon))),a),f=be(X(h,this.rho),X(At(m),1-this.rho));c.assign(d),h.assign(f);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)}}Fh.className="Adadelta",fe(Fh);class _h extends nr{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=G.registeredVariables[n];if(this.accumulatedGrads[s]==null){const c=!1;this.accumulatedGrads[s]={originalName:`${n}/accumulator`,variable:Q(()=>Ya(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;Q(()=>{const c=be(a,At(o));a.assign(c);const h=be(X(We(o,Nn(be(c,G.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)}}_h.className="Adagrad",fe(_h);class Wh extends nr{constructor(e,t,n,s=null){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],Q(()=>{this.accBeta1=Ce(t).variable(),this.accBeta2=Ce(n).variable()}),s==null&&(this.epsilon=G.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);Q(()=>{const n=Re(1,this.accBeta1),s=Re(1,this.accBeta2);t.forEach((i,o)=>{const a=G.registeredVariables[i],c=!1;this.accumulatedFirstMoment[o]==null&&(this.accumulatedFirstMoment[o]={originalName:`${i}/m`,variable:Q(()=>et(a).variable(c))}),this.accumulatedSecondMoment[o]==null&&(this.accumulatedSecondMoment[o]={originalName:`${i}/v`,variable:Q(()=>et(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,f=be(X(d,this.beta1),X(h,1-this.beta1)),b=be(X(m,this.beta2),X(At(h),1-this.beta2)),w=We(f,n),L=We(b,s);d.assign(f),m.assign(b);const x=be(X(We(w,be(Nn(L),this.epsilon)),-this.learningRate),a);a.assign(x)}),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),Q(()=>{this.accBeta1.assign(ti(this.beta1,this.iterations_+1)),this.accBeta2.assign(ti(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)}}Wh.className="Adam",fe(Wh);class $h extends nr{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=[],Q(()=>{this.iteration=Ce(0).variable(),this.accBeta1=Ce(t).variable()}),s==null&&(this.epsilon=G.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);Q(()=>{const n=Re(1,this.accBeta1),s=We(-this.learningRate,be(X(this.iteration,this.decay),1));t.forEach((i,o)=>{const a=G.registeredVariables[i],c=!1;this.accumulatedFirstMoment[o]==null&&(this.accumulatedFirstMoment[o]={originalName:`${i}/m`,variable:et(a).variable(c)}),this.accumulatedWeightedInfNorm[o]==null&&(this.accumulatedWeightedInfNorm[o]={originalName:`${i}/v`,variable:et(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,f=be(X(d,this.beta1),X(h,1-this.beta1)),b=X(m,this.beta2),w=dn(h),L=Us(b,w);d.assign(f),m.assign(L);const x=be(X(We(s,n),We(f,be(L,this.epsilon))),a);a.assign(x)}),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)}}$h.className="Adamax",fe($h);class sc extends nr{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=G.registeredVariables[n];Q(()=>{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=bn(Ce(-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)}}sc.className="SGD",fe(sc);class Uh extends sc{constructor(e,t,n=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Ce(this.momentum)}applyGradients(e){const t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);t.forEach((n,s)=>{const i=G.registeredVariables[n];if(this.accumulations[s]==null){const c=!1;this.accumulations[s]={originalName:`${n}/momentum`,variable:Q(()=>et(i).variable(c))}}const o=this.accumulations[s].variable,a=Array.isArray(e)?e[s].tensor:e[n];if(a==null)return;Q(()=>{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)}}Uh.className="Momentum",fe(Uh);class Bh extends nr{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=G.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=G.registeredVariables[n],o=!1;this.accumulatedMeanSquares[s]==null&&(this.accumulatedMeanSquares[s]={originalName:`${n}/rms`,variable:Q(()=>et(i).variable(o))}),this.accumulatedMoments[s]==null&&(this.accumulatedMoments[s]={originalName:`${n}/momentum`,variable:Q(()=>et(i).variable(o))}),this.accumulatedMeanGrads[s]==null&&this.centered&&(this.accumulatedMeanGrads[s]={originalName:`${n}/mg`,variable:Q(()=>et(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;Q(()=>{const d=be(X(c,this.decay),X(At(a),1-this.decay));if(this.centered){const m=this.accumulatedMeanGrads[s].variable,f=be(X(m,this.decay),X(a,1-this.decay)),b=We(X(a,this.learningRate),Nn(Re(d,be(At(f),this.epsilon)))),w=be(X(h,this.momentum),b);c.assign(d),m.assign(f),h.assign(w);const L=Re(i,w);i.assign(L)}else{const m=be(X(c,this.decay),X(At(a),1-this.decay)),f=be(X(h,this.momentum),We(X(a,this.learningRate),Nn(be(m,this.epsilon))));c.assign(m),h.assign(f);const b=Re(i,f);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)}}Bh.className="RMSProp",fe(Bh);class Go{static sgd(e){return new sc(e)}static momentum(e,t,n=!1){return new Uh(e,t,n)}static rmsprop(e,t=.9,n=0,s=null,i=!1){return new Bh(e,t,n,s,i)}static adam(e=.001,t=.9,n=.999,s=null){return new Wh(e,t,n,s)}static adadelta(e=.001,t=.95,n=null){return new Fh(e,t,n)}static adamax(e=.002,t=.9,n=.999,s=null,i=0){return new $h(e,t,n,s,i)}static adagrad(e,t=.1){return new _h(e,t)}}const Yo={sgd:Go.sgd,momentum:Go.momentum,adadelta:Go.adadelta,adagrad:Go.adagrad,rmsprop:Go.rmsprop,adamax:Go.adamax,adam:Go.adam};const qM=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function Yp(){return new Promise(e=>qM(()=>e()))}function Aw(e,t,n){const s=n*(typeof e=="number"?e:e[0]),i=t*(typeof e=="number"?e:e[1]);return[s,i]}function Mh(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 Ph(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 zh(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 vw(e,t){const n=[0];for(let s=0;s<t;++s)n.push(e[s][0]);return n}function Nw(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 Hp=1.7580993408473768,qp=1.0507009873554805;const Cw=.3275911,Rw=.254829592,Ow=-.284496736,Ew=1.421413741,Dw=-1.453152027,kw=1.061405429;function ic(...e){oe().getBool("IS_TEST")||console.warn(...e)}function jM(...e){oe().getBool("IS_TEST")||console.log(...e)}function sr(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 ZA(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 QA(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 ev(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 Fw(e,t){const n=e[t*2],s=e[t*2+1];return{real:n,imag:s}}function tv(e,t,n,s){e[s*2]=t,e[s*2+1]=n}function nv(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 sv(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 KM(e,t,n){if(t==="complex64"){if(e.dtype==="complex64")return e.clone();const s=dt(e.shape),i=Ae(e,"float32"),o=n.complex(i,s);return s.dispose(),i.dispose(),o}if(!Ta(e.dtype,t))return G.makeTensorFromDataId(e.dataId,e.shape,t);if(e.dtype==="complex64"){const s=n.real(e),i=Ae(s,t);return s.dispose(),i}if(t==="int32")return n.int(e);if(t==="bool"){const s=Ce(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 iv(e,t){return G.makeTensorFromDataId(e.dataId,t,e.dtype)}function _w(e,t,n){const s=(t-e)/(n-1),i=va(n,"float32");i[0]=e;for(let o=1;o<i.length;o++)i[o]=i[o-1]+s;return hs(i,"float32")}var Ww=Object.freeze({__proto__:null,slice_util:qT,segment_util:MW,castTensor:KM,reshapeTensor:iv,linspaceImpl:_w,upcastType:$n,axesAreInnerMostDims:Wb,combineLocations:QT,computeOutAndReduceShapes:An,expandShapeToKeepDim:vn,assertAxesAreInnerMostDims:Xn,getAxesPermutation:Jn,getUndoAxesPermutation:ph,getInnerMostAxes:cs,getBroadcastDims:Uo,getReductionAxes:pn,assertAndGetBroadcastShape:nt,assertParamsConsistent:dp,computeOutShape:Zi,computeDilation2DInfo:hp,computePool2DInfo:Un,computePool3DInfo:gh,computeConv2DInfo:Fn,computeConv3DInfo:_r,computeDefaultPad:Vb,tupleValuesAreOne:Wr,eitherStridesOrDilationsAreOne:cn,convertConv2DDataFormat:$r,getFusedDyActivation:$p,getFusedBiasGradient:Up,applyActivation:Bp,shouldFuse:Mp,PARALLELIZE_THRESHOLD:ew,computeOptimalWindowSize:Sh,getImageCenter:Aw,getReshaped:Mh,getPermuted:Ph,getReshapedPermuted:zh,getSliceBeginCoords:vw,getSliceSize:Nw,prepareAndValidate:np,validateUpdateShape:Ab,validateInput:vb,calculateShapes:Pa,SELU_SCALEALPHA:Hp,SELU_SCALE:qp,ERF_P:Cw,ERF_A1:Rw,ERF_A2:Ow,ERF_A3:Ew,ERF_A4:Dw,ERF_A5:kw,warn:ic,log:jM,mergeRealAndImagArrays:sr,splitRealAndImagArrays:ZA,complexWithEvenIndex:QA,complexWithOddIndex:ev,getComplexWithIndex:Fw,assignToTypedArray:tv,exponents:nv,exponent:sv,prepareSplitSize:LA});function $w(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=tt(e,s,a);return s[n]+=o,c})}function Uw(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=wt(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 Bw(e,t,n,s,i){const o=t[t.length-1],[a,c]=[e.length/o,o],h=bt(n,a*s),d=bt("int32",a*s);for(let f=0;f<a;f++){const b=f*c,w=e.subarray(b,b+c),L=[];for(let O=0;O<w.length;O++)L.push({value:w[O],index:O});L.sort((O,E)=>E.value-O.value);const x=f*s,v=h.subarray(x,x+s),N=d.subarray(x,x+s);for(let O=0;O<s;O++)v[O]=L[O].value,N[O]=L[O].index}const m=t.slice();return m[m.length-1]=s,[sn(h,m,n),sn(d,m,"int32")]}var XM=Object.freeze({__proto__:null,nonMaxSuppressionV3Impl:zp,nonMaxSuppressionV4Impl:Vp,nonMaxSuppressionV5Impl:Gp,split:$w,tile:Uw,topkImpl:Bw,whereImpl:_p});const JM={kernelName:ud,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,ec(Ae(n,"float32"),-1))}}};const ZM={kernelName:gl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const s=At(Ae(n,"float32")),i=Nn(Re(Ce(1),s));return qt(We(e,i))}}}};const QM={kernelName:yl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const s=Nn(Re(At(Ae(n,"float32")),1));return We(e,s)}}}};const eP={kernelName:Co,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=nt(n.shape,s.shape),o=()=>{let c=e;const h=pn(n.shape,i);return h.length>0&&(c=$e(c,h)),K(c,n.shape)},a=()=>{let c=e;const h=pn(s.shape,i);return h.length>0&&(c=$e(c,h)),K(c,s.shape)};return{a:o,b:a}}};const tP={kernelName:by,saveAllInputs:!0,gradFunc:(e,t)=>{const n={};return t.forEach((s,i)=>{n[i]=()=>e.clone()}),n}};const nP={kernelName:wy,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>et(n)}}};const sP={kernelName:Ly,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>et(n)}}};const iP={kernelName:bl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>We(e,Nn(Re(Ce(1),At(Ae(n,"float32")))))}}};const rP={kernelName:wl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const s=Nn(be(Ce(1),At(Ae(n,"float32"))));return We(e,s)}}}};const oP={kernelName:dd,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=nt(n.shape,s.shape),o=()=>{const c=be(At(n),At(s));let h=X(e,We(s,c));const d=pn(n.shape,i);return d.length>0&&(h=$e(h,d)),K(h,n.shape)},a=()=>{const c=be(At(n),At(s));let h=qt(X(e,We(n,c)));const d=pn(s.shape,i);return d.length>0&&(h=$e(h,d)),K(h,s.shape)};return{a:o,b:a}}};const aP={kernelName:Ll,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>We(e,be(At(Ae(n,"float32")),1))}}};const cP={kernelName:Sl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>We(e,Re(Ce(1),At(Ae(n,"float32"))))}}};function lP(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,f=!1;h.rank===4&&(f=!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]])),A(d.rank===5,()=>`Error in avgPool3dBackprop: dy must be rank 5 but got rank ${d.rank}.`),A(m.rank===5,()=>`Error in avgPool3dBackprop: input must be rank 5 but got rank ${m.rank}.`),A(cn(s,i),()=>`Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides ${s} and dilations '${i}'`),a!=null&&A(Le(o),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);const b=v=>{const N=gh(m.shape,n,s,i,o,a);return v.avgPool3dBackprop(d,m,N)},w={dy:d,input:m},L={filterSize:n,strides:s,dilations:i,pad:o,dimRoundingMode:a},x=G.runKernelFunc(b,w,null,Ux,L);return f?K(x,[x.shape[1],x.shape[2],x.shape[3],x.shape[4]]):x}const hP=z({avgPool3dBackprop_:lP});const uP={kernelName:Sy,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:()=>hP(e,s,i,o,d,c,h)}}};function dP(e,t,n,s,i){const o=W(e,"dy","avgPoolBackprop"),a=W(t,"input","avgPoolBackprop");A(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]])),A(h.rank===4,()=>`Error in avgPoolBackprop: dy must be rank 4 but got rank ${h.rank}.`),A(c.rank===4,()=>`Error in avgPoolBackprop: input must be rank 4 but got rank ${c.rank}.`);const m=L=>{const x=Un(c.shape,n,s,1,i);return L.avgPoolBackprop(h,c,x)},f={dy:h,input:c},b={filterSize:n,strides:s,pad:i},w=G.runKernelFunc(m,f,null,pd,b);return d?K(w,[w.shape[1],w.shape[2],w.shape[3]]):w}const pP=z({avgPoolBackprop_:dP});const mP={kernelName:Il,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{filterSize:i,strides:o,pad:a}=n;return{x:()=>pP(e,s,i,o,a)}}};const fP={kernelName:md,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{const[s,i]=t,{transposeA:o,transposeB:a}=n;return!o&&!a?{a:()=>ct(e,i,!1,!0),b:()=>ct(s,e,!0,!1)}:!o&&a?{a:()=>ct(e,i,!1,!1),b:()=>ct(e,s,!0,!1)}:o&&!a?{a:()=>ct(i,e,!1,!0),b:()=>ct(s,e,!1,!1)}:{a:()=>ct(i,e,!0,!0),b:()=>ct(e,s,!0,!0)}}};const gP={kernelName:Iy,gradFunc:(e,t,n)=>{const{blockShape:s,crops:i}=n;return{x:()=>vh(e,s,i)}}};const yP={kernelName:xy,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:()=>$e(e,c,!0)}}};const bP={kernelName:Na,gradFunc:e=>({x:()=>e.clone()})};const wP={kernelName:xl,gradFunc:e=>({x:()=>et(e)})};const LP={kernelName:Tl,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{clipValueMin:i,clipValueMax:o}=n;return{x:()=>Bn(Bs(er(s,i),Br(s,o)),e,et(e))}}};const SP={kernelName:Al,saveAllInputs:!0,gradFunc:(e,t,n)=>{const s=t.map(h=>h.shape),{axis:i}=n,o=qe(i,t[0].shape)[0],a=s.map(h=>h[o]),c=us(e,a,o);return c.map(h=>()=>h)}};const IP={kernelName:gd,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[s,i]=t,{dilations:o,strides:a,pad:c,dataFormat:h}=n;return A(Wr(o),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${o}'`),{x:()=>qb(s.shape,e,i,a,c,h),filter:()=>Iw(s,e,i.shape,a,c,h)}}};const xP={kernelName:yd,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{const[s,i]=t,{strides:o,pad:a,dataFormat:c,dimRoundingMode:h}=n;return{dy:()=>Qi(e,i,o,a,c,1,h),filter:()=>Iw(e,s,i.shape,o,a,c,h)}}};function TP(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]])),A(o.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${o.shape}.`),A(a.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${a.shape}.`),A(n.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`),A(o.shape[4]===n[3],()=>`Error in conv3dDerFilter: depth of input ${o.shape[4]}) must match input depth in filter (${n[3]}.`),A(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 f=1,b=_r(o.shape,n,s,f,i);return m.conv3dDerFilter(o,a,b)},h={x:o,dy:a},d={strides:s,pad:i,filterShape:n};return G.runKernelFunc(c,h,null,Ay,d)}const AP=z({conv3DBackpropFilter_:TP});const vP={kernelName:bd,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:s,strides:i,pad:o}=n;A(Wr(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:()=>aA(a.shape,e,c,i,o),filter:()=>AP(a,e,c.shape,i,o)}}};const NP={kernelName:Ca,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(qt(Rp(Ae(n,"float32"))),e)}}};const CP={kernelName:vl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(Op(Ae(n,"float32")),e)}}};const RP={kernelName:Ny,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{axis:i,exclusive:o,reverse:a}=n;return{x:()=>{const c=Jn([i],s.rank);let h=yp(e,i,o,!a);return c!=null&&(h=Ye(h,c)),h}}}};const OP={kernelName:wd,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:s,strides:i,pad:o,dimRoundingMode:a}=n,c=s==null?[1,1]:s;A(Wr(c),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${c}'`);const[h,d]=t;return A(h.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${h.rank}.`),A(d.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${d.rank}.`),A(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]}.`),A(cn(i,c),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${c}'.`),a!=null&&A(Le(o),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`),{x:()=>VA(h.shape,e,d,i,o,s,a),filter:()=>zA(h,e,d.shape,i,o,s,a)}}};const EP={kernelName:Ld,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:()=>G.runKernel(Sd,o,n),filter:()=>G.runKernel(Id,a,n)}}};const DP={kernelName:Ra,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=nt(n.shape,s.shape),o=()=>{const c=We(e,Ae(s,"float32")),h=pn(n.shape,i);return h.length>0?K($e(c,h),n.shape):c},a=()=>{let c=X(e,Ae(n,"float32"));const h=pn(s.shape,i);h.length>0&&(c=K($e(c,h),s.shape));const d=At(s);return qt(We(c,Ae(d,"float32")))};return{a:o,b:a}}};const kP={kernelName:Nl,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t,s=o=>o.eluDer(e,n),i={dy:e,y:n};return{x:()=>G.runKernelFunc(s,i,null,zx)}}};const FP={kernelName:Cl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,s=X(Is(qt(At(n))),2/Math.sqrt(Math.PI));return{x:()=>X(e,s)}}};const _P={kernelName:Rl,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,n)}}};const WP={kernelName:Ol,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,Is(n))}}};const $P={kernelName:El,gradFunc:e=>({x:()=>et(e)})};const UP={kernelName:Ey,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=nt(n.shape,s.shape),o=()=>{const c=We(e,Ae(s,"float32")),h=pn(n.shape,i);return h.length>0?K($e(c,h),n.shape):c},a=()=>{let c=X(e,Ae(n,"float32"));const h=pn(s.shape,i);h.length>0&&(c=K($e(c,h),s.shape));const d=At(s);return qt(We(c,Ae(d,"float32")))};return{a:o,b:a}}};const BP={kernelName:Dl,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{const{varianceEpsilon:s}=n,[i,o,a,c]=t,h=c==null?Ce(1):c,d=pn(o.shape,i.shape),m=[];if(o.rank===1){for(let k=0;k<i.shape.length-1;++k)m.push(i.shape[k]);m.push(1)}const f=Re(i,o),b=X(e,h),w=Np(be(a,Ce(s))),L=X(X(X(w,w),w),Ce(-.5)),x=()=>o.rank===1?K(X(X(e,Ur(K(w,[1,1,1,o.shape[0]]),m)),h),i.shape):K(X(X(e,w),h),i.shape),v=()=>{let k=X(X(w,Ce(-1)),b);return o.rank===1&&(k=$e(k,d)),K(k,o.shape)},N=()=>{let k=X(X(L,f),b);return o.rank===1&&(k=$e(k,d)),K(k,o.shape)},O=()=>{const k=X(f,w);let F=X(e,k);return o.rank===1&&(F=$e(F,d)),K(F,o.shape)},E=()=>{let k=e;return o.rank===1&&(k=$e(k,d)),K(k,o.shape)};return{x,mean:v,variance:N,scale:O,offset:E}}};const MP={kernelName:Dy,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{const[s,i]=t,{axis:o}=n,a=qe(o,s.shape)[0],c=()=>{const h=s.shape,d=i.size,m=h.slice(0,a),f=m.length,b=h.slice(o,h.length).slice(1),w=b.length,L=rv(0,f),x=rv(f+1,f+1+w),v=ov([m,[d],b]),N=K(e,v),O=K(i,[d]),E=ov([[f],L,x]),k=Ye(N,E);let F=bw(k,O,s.shape[a]);const U=ph(E);return F=Ye(F,U),F};return{x:c,indices:()=>i}}};function rv(e,t){const n=[];for(let s=e;s<t;++s)n.push(s);return n}function ov(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 PP={kernelName:ky,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t;return{a:()=>et(n),b:()=>et(s)}}};const zP={kernelName:kl,gradFunc:e=>({x:()=>Ae(e,"float32")})};const VP={kernelName:Fl,gradFunc:e=>({x:()=>et(e)})};const GP={kernelName:_l,gradFunc:e=>({x:()=>et(e)})};const YP={kernelName:Wl,gradFunc:e=>({x:()=>et(e)})};const HP={kernelName:Ul,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>We(e,be(n,1))}}};const qP={kernelName:$l,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>We(e,Ae(n,"float32"))}}};const jP={kernelName:Fy,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s]=t,{axis:i}=n;return{logits:()=>{const o=!0,a=Is(s);return Re(e,X($e(e,i,o),a))}}}};function KP(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 G.runKernelFunc(c,h,null,Jx,d)}const XP=z({localResponseNormalizationBackprop_:KP});const JP={kernelName:_y,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,i]=t,{depthRadius:o,bias:a,alpha:c,beta:h}=n;return{x:()=>XP(s,i,e,o,a,c,h)}}};function av(e,t,n,s){return t.rank<n.rank&&(t=K(t,vn(t.shape,s))),e.rank<n.rank&&(e=K(e,vn(e.shape,s))),{x:()=>{const i=X(e,Ae(Qs(n,t),e.dtype));return i}}}const cv={kernelName:Bl,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const s=n,{reductionIndices:i}=s,o=t[0],a=t[1],c=qe(i,o.shape),h=av(e,a,o,c);return{x:()=>h.x()}}};const ZP={kernelName:Wy,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=()=>X(e,Ae(er(n,s),"float32")),o=()=>X(e,Ae(xh(n,s),"float32"));return{a:i,b:o}}};function QP(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 f=h,b=d,w=m,L=!1;d.rank===4&&(L=!0,f=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]])),A(f.rank===5,()=>`Error in maxPool3dBackprop: dy must be rank 5 but got rank ${f.rank}.`),A(b.rank===5,()=>`Error in maxPool3dBackprop: input must be rank 5 but got rank ${b.rank}.`),A(w.rank===5,()=>`Error in maxPool3dBackprop: output must be rank 5 but got rank ${w.rank}.`),A(cn(i,o),()=>`Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides ${i} and dilations '${o}'`),c!=null&&A(Le(a),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${c} but got pad ${a}.`);const x=E=>{const k=gh(b.shape,s,i,o,a,c);return E.maxPool3dBackprop(f,b,w,k)},v={dy:f,input:b,output:w},N={filterSize:s,strides:i,dilations:o,pad:a,dimRoundingMode:c},O=G.runKernelFunc(x,v,null,Zx,N);return L?K(O,[O.shape[1],O.shape[2],O.shape[3],O.shape[4]]):O}const ez=z({maxPool3dBackprop_:QP});const tz={kernelName:$y,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:()=>ez(e,s,i,o,a,m,h,d)}}};function nz(e,t,n,s,i,o,a){const c=W(e,"dy","maxPoolBackprop"),h=W(t,"input","maxPoolBackprop"),d=W(n,"output","maxPoolBackprop");A(h.rank===c.rank,()=>`Rank of input (${h.rank}) does not match rank of dy (${c.rank})`),A(c.rank===4,()=>`Error in maxPoolBackprop: dy must be rank 4 but got rank ${c.rank}.`),A(h.rank===4,()=>`Error in maxPoolBackprop: input must be rank 4 but got rank ${h.rank}.`),a!=null&&A(Le(o),()=>`Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);const m=w=>{const L=Un(h.shape,s,i,1,o,a);return w.maxPoolBackprop(c,h,d,L)},f={dy:c,input:h,output:d},b={filterSize:s,strides:i,pad:o,dimRoundingMode:a};return G.runKernelFunc(m,f,null,Cd,b)}const sz=z({maxPoolBackprop_:nz});const iz={kernelName:Ml,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,i]=t,{filterSize:o,strides:a,pad:c}=n;return{x:()=>sz(e,s,i,o,a,c)}}};const rz={kernelName:By,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const s=n,{axis:i}=s,[o,a]=t,c=qe(i,o.shape),h=av(e,a,o,c);return{x:()=>h.x()}}};const oz={kernelName:My,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=()=>X(e,Ae(Br(n,s),"float32")),o=()=>X(e,Ae(xs(n,s),"float32"));return{a:i,b:o}}};const az={kernelName:Pl,inputsToSave:["x"],gradFunc:(e,t,n)=>{const s=t[0],{paddings:i}=n,o=i.map(a=>a[0]);return{x:()=>tt(e,o,s.shape)}}};const cz={kernelName:Py,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=nt(n.shape,s.shape),o=()=>{const c=pn(n.shape,i);return c.length>0?K($e(e,c),n.shape):e},a=()=>{const c=X(e,qt(Ha(We(n,s)))),h=pn(s.shape,i);return h.length>0?K($e(c,h),s.shape):c};return{a:o,b:a}}};const lz={kernelName:Oa,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=nt(n.shape,s.shape),o=()=>{const c=X(e,Ae(s,"float32")),h=pn(n.shape,i);return h.length>0?K($e(c,h),n.shape):c},a=()=>{const c=X(e,Ae(n,"float32")),h=pn(s.shape,i);return h.length>0?K($e(c,h),s.shape):c};return{a:o,b:a}}};const hz={kernelName:zy,gradFunc:e=>({x:()=>qt(e)})};const uz={kernelName:Yy,inputsToSave:["indices"],gradFunc:(e,t)=>{const n=t[0];return{indices:()=>dt(n.shape,"float32")}}};const dz={kernelName:Gy,gradFunc:e=>({x:()=>et(e)})};const lv={kernelName:Dd,inputsToSave:["x"],gradFunc:(e,t,n)=>{const s=t[0],{paddings:i}=n,o=i.map(a=>a[0]);return{x:()=>tt(e,o,s.shape)}}};const pz={kernelName:Hy,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[n,s,i]=t,o=n,a=s,c=nt(o.shape,a.shape),h=()=>{const m=Ae(a,"float32");let f=X(e,X(m,ti(o,Re(m,Ce(1)))));const b=pn(o.shape,c);return b.length>0&&(f=$e(f,b)),K(f,o.shape)},d=()=>{const m=xs(o,0),f=Bn(m,ls(o),et(o));let b=X(e,X(i,f));const w=pn(a.shape,c);return w.length>0&&(b=$e(b,w)),K(b,a.shape)};return{a:h,b:d}}};const mz={kernelName:kd,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[n,s]=t,i=xs(n,0);return{x:()=>Bn(i,e,X(e,s)),alpha:()=>{let o=Bn(i,et(e),X(e,n));const a=pn(s.shape,e.shape);return a.length>0&&(o=$e(o,a)),K(o,s.shape)}}}};const fz={kernelName:Vl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>We(e,qt(At(n)))}}};const gz={kernelName:Hl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,s=X(Br(n,6),ec(n));return{x:()=>X(e,Ae(s,"float32"))}}};const yz={kernelName:Gl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,Ae(ec(n),"float32"))}}};const bz={kernelName:Yl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>K(e,n.shape)}}};const wz={kernelName:jy,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=()=>G.runKernelFunc(i,o,null,nT,n);return{images:a}}};const Lz={kernelName:qy,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=()=>G.runKernelFunc(i,o,null,tT,n);return{images:a}}};const Sz={kernelName:Ky,gradFunc:(e,t,n)=>{const{dims:s}=n,i=qe(s,e.shape);return{x:()=>Ts(e,i)}}};const Iz={kernelName:ql,gradFunc:e=>({x:()=>et(e)})};const xz={kernelName:jl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>qt(We(e,X(ti(n,1.5),2)))}}};const Tz={kernelName:Xy,inputsToSave:["condition"],gradFunc:(e,t)=>{const[n]=t;return{condition:()=>Ae(et(n),"float32"),t:()=>X(e,Ae(n,e.dtype)),e:()=>X(e,Ae(Th(n),e.dtype))}}};const Az={kernelName:Kl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const s=xs(n,Ce(0)),i=Ce(Hp),o=Ce(qp),a=X(e,o),c=X(X(e,i),Is(Ae(n,"float32")));return Bn(s,a,c)}}}};const vz={kernelName:Zl,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,X(n,Re(Ce(1),n)))}}};const Nz={kernelName:Jl,gradFunc:e=>({x:()=>et(e)})};const Cz={kernelName:Ea,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(Lh(Ae(n,"float32")),e)}}};const Rz={kernelName:Xl,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(gp(Ae(n,"float32")),e)}}};const Oz={kernelName:_d,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{begin:i,size:o}=n,a=s.shape,[c,h]=rp(s,i,o),d=[];for(let m=0;m<e.rank;m++)d.push([c[m],a[m]-c[m]-h[m]]);return{x:()=>Ni(e,d)}}};const Ez={kernelName:Qy,outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s]=t,{dim:i}=n,o=!0,a=X(e,s);return{logits:()=>Re(a,X($e(a,[i],o),s))}}};const Dz={kernelName:Ql,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,Ai(n))}}};const hv={kernelName:Wd,gradFunc:(e,t,n)=>{const{blockShape:s,paddings:i}=n;return{x:()=>bh(e,s,i)}}};const uv={kernelName:Zy,gradFunc:(e,t,n)=>{const{axis:s}=n;return{x:()=>Ht(e,s)}}};const kz={kernelName:eh,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>We(e,X(Nn(Ae(n,"float32")),2))}}};const Fz={kernelName:$d,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(e,X(Ae(n,"float32"),2))}}};const _z={kernelName:Da,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=Ce(2),o=()=>X(e,X(i,Re(n,s))),a=()=>X(e,X(i,Re(s,n)));return{a:o,b:a}}};const Wz={kernelName:sh,gradFunc:e=>({x:()=>et(e)})};const $z={kernelName:ka,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,i=nt(n.shape,s.shape),o=()=>{let c=e;const h=pn(n.shape,i);return h.length>0&&(c=$e(c,h)),K(c,n.shape)},a=()=>{let c=e;const h=pn(s.shape,i);return h.length>0&&(c=$e(c,h)),K(qt(c),s.shape)};return{a:o,b:a}}};const Uz={kernelName:Jy,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,i=s.shape.slice(),{axis:o}=n,a=qe(o,s.shape);a.forEach(d=>{i[d]=1});const c=K(e,i),h=X(c,ei(s.shape,"float32"));return{x:()=>h}}};const Bz={kernelName:Fa,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>We(e,At(Lh(n)))}}};const Mz={kernelName:th,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>X(Re(Ce(1),At(n)),e)}}};const Pz={kernelName:eb,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{reps:i}=n,o=()=>{let a=et(s);if(s.rank===1)for(let c=0;c<i[0];++c)a=be(a,tt(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,tt(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,tt(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,tt(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 zz={kernelName:nh,gradFunc:(e,t,n)=>{const s=n,{perm:i}=s,o=ph(i);return{x:()=>Ye(e,o)}}};const Vz={kernelName:tb,gradFunc:(e,t,n)=>{const s=n,{axis:i}=s;return{value:()=>ts(e,i)}}};const Gz={kernelName:nb,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[n]=t,s=()=>Yz(e,n);return{x:s}}};function Yz(e,t){const n=Us(t,et(t)),s=qa(e,n);let i=er(t,Ce(0,"int32"));const o=s.rank-i.rank;for(let c=0;c<o;++c)i=Qn(i,c+1);i=Bs(i,ei(s.shape,"bool"));const a=et(s);return Bn(i,s,a)}const Hz={kernelName:sb,gradFunc:e=>({x:()=>et(e)})};const qz=[JM,ZM,QM,eP,tP,nP,sP,iP,rP,oP,aP,cP,uP,mP,fP,gP,yP,bP,wP,LP,SP,xP,IP,vP,NP,CP,RP,OP,EP,DP,kP,FP,_P,WP,UP,$P,BP,MP,PP,zP,VP,GP,YP,HP,qP,jP,JP,cv,cv,ZP,tz,iz,rz,oz,az,cz,lz,hz,uz,dz,lv,lv,pz,mz,fz,gz,yz,bz,wz,Lz,Sz,Iz,xz,Tz,Az,vz,Nz,Cz,Rz,Oz,Ez,Dz,hv,hv,uv,uv,kz,_z,Fz,Wz,$z,Uz,Bz,Mz,Pz,zz,Vz,Gz,Hz];for(const e of qz)aT(e);ee.prototype.abs=function(){return this.throwIfDisposed(),dn(this)};ee.prototype.acos=function(){return this.throwIfDisposed(),Fb(this)};ee.prototype.acosh=function(){return this.throwIfDisposed(),_b(this)};ee.prototype.addStrict=function(e){return this.throwIfDisposed(),CA(this,e)};ee.prototype.add=function(e){return this.throwIfDisposed(),be(this,e)};ee.prototype.all=function(e,t){return this.throwIfDisposed(),lp(this,e,t)};ee.prototype.any=function(e,t){return this.throwIfDisposed(),mh(this,e,t)};ee.prototype.argMax=function(e){return this.throwIfDisposed(),fh(this,e)};ee.prototype.argMin=function(e){return this.throwIfDisposed(),$b(this,e)};ee.prototype.asScalar=function(){return this.throwIfDisposed(),A(this.size===1,()=>"The array must have only 1 element."),K(this,[])};ee.prototype.asType=function(e){return this.throwIfDisposed(),Ae(this,e)};ee.prototype.as1D=function(){return this.throwIfDisposed(),K(this,[this.size])};ee.prototype.as2D=function(e,t){return this.throwIfDisposed(),K(this,[e,t])};ee.prototype.as3D=function(e,t,n){return this.throwIfDisposed(),K(this,[e,t,n])};ee.prototype.as4D=function(e,t,n,s){return this.throwIfDisposed(),K(this,[e,t,n,s])};ee.prototype.as5D=function(e,t,n,s,i){return this.throwIfDisposed(),K(this,[e,t,n,s,i])};ee.prototype.asin=function(){return this.throwIfDisposed(),Ub(this)};ee.prototype.asinh=function(){return this.throwIfDisposed(),Bb(this)};ee.prototype.atan=function(){return this.throwIfDisposed(),Mb(this)};ee.prototype.atan2=function(e){return this.throwIfDisposed(),Pb(this,e)};ee.prototype.atanh=function(){return this.throwIfDisposed(),zb(this)};ee.prototype.avgPool=function(e,t,n,s){return this.throwIfDisposed(),yh(this,e,t,n,s)};ee.prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),bh(this,e,t)};ee.prototype.batchNorm=function(e,t,n,s,i){return this.throwIfDisposed(),Wo(this,e,t,n,s,i)};ee.prototype.broadcastTo=function(e){return this.throwIfDisposed(),wh(this,e)};ee.prototype.cast=function(e){return this.throwIfDisposed(),Ae(this,e)};ee.prototype.ceil=function(){return this.throwIfDisposed(),Hb(this)};ee.prototype.clipByValue=function(e,t){return this.throwIfDisposed(),Zn(this,e,t)};ee.prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof ee&&(e=[e]),Ht([this,...e],t)};ee.prototype.conv1d=function(e,t,n,s,i,o){return this.throwIfDisposed(),mp(this,e,t,n,s,i,o)};ee.prototype.conv2dTranspose=function(e,t,n,s,i){return this.throwIfDisposed(),fp(this,e,t,n,s,i)};ee.prototype.conv2d=function(e,t,n,s,i,o){return this.throwIfDisposed(),Qi(this,e,t,n,s,i,o)};ee.prototype.cos=function(){return this.throwIfDisposed(),Lh(this)};ee.prototype.cosh=function(){return this.throwIfDisposed(),gp(this)};ee.prototype.cumsum=function(e,t,n){return this.throwIfDisposed(),yp(this,e,t,n)};ee.prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),Kb(this,e,t)};ee.prototype.depthwiseConv2D=function(e,t,n,s,i,o){return un("depthwiseConv2D is deprecated, use depthwiseConv2d instead"),this.throwIfDisposed(),$o(this,e,t,n,s,i,o)};ee.prototype.depthwiseConv2d=function(e,t,n,s,i,o){return this.throwIfDisposed(),$o(this,e,t,n,s,i,o)};ee.prototype.dilation2d=function(e,t,n,s,i){return this.throwIfDisposed(),Xb(this,e,t,n,s,i)};ee.prototype.divNoNan=function(e){return this.throwIfDisposed(),Jb(this,e)};ee.prototype.divStrict=function(e){return this.throwIfDisposed(),RA(this,e)};ee.prototype.div=function(e){return this.throwIfDisposed(),We(this,e)};ee.prototype.dot=function(e){return this.throwIfDisposed(),cA(this,e)};ee.prototype.elu=function(){return this.throwIfDisposed(),Ga(this)};ee.prototype.equalStrict=function(e){return this.throwIfDisposed(),IA(this,e)};ee.prototype.equal=function(e){return this.throwIfDisposed(),Qs(this,e)};ee.prototype.erf=function(){return this.throwIfDisposed(),Zb(this)};ee.prototype.exp=function(){return this.throwIfDisposed(),Is(this)};ee.prototype.expandDims=function(e){return this.throwIfDisposed(),Qn(this,e)};ee.prototype.expm1=function(){return this.throwIfDisposed(),Qb(this)};ee.prototype.fft=function(){return this.throwIfDisposed(),Oh(this)};ee.prototype.flatten=function(){return this.throwIfDisposed(),K(this,[this.size])};ee.prototype.floor=function(){return this.throwIfDisposed(),Ha(this)};ee.prototype.floorDiv=function(e){return this.throwIfDisposed(),cp(this,e)};ee.prototype.gather=function(e,t){return this.throwIfDisposed(),qa(this,e,t)};ee.prototype.greaterEqualStrict=function(e){return this.throwIfDisposed(),xA(this,e)};ee.prototype.greaterEqual=function(e){return this.throwIfDisposed(),er(this,e)};ee.prototype.greaterStrict=function(e){return this.throwIfDisposed(),TA(this,e)};ee.prototype.greater=function(e){return this.throwIfDisposed(),xs(this,e)};ee.prototype.ifft=function(){return this.throwIfDisposed(),Qa(this)};ee.prototype.irfft=function(){return this.throwIfDisposed(),kp(this)};ee.prototype.isFinite=function(){return this.throwIfDisposed(),hA(this)};ee.prototype.isInf=function(){return this.throwIfDisposed(),uA(this)};ee.prototype.isNaN=function(){return this.throwIfDisposed(),dA(this)};ee.prototype.leakyRelu=function(e){return this.throwIfDisposed(),wp(this,e)};ee.prototype.lessEqualStrict=function(e){return this.throwIfDisposed(),AA(this,e)};ee.prototype.lessEqual=function(e){return this.throwIfDisposed(),Br(this,e)};ee.prototype.lessStrict=function(e){return this.throwIfDisposed(),vA(this,e)};ee.prototype.less=function(e){return this.throwIfDisposed(),xh(this,e)};ee.prototype.localResponseNormalization=function(e,t,n,s){return this.throwIfDisposed(),tw(this,e,t,n,s)};ee.prototype.logSigmoid=function(){return this.throwIfDisposed(),mA(this)};ee.prototype.logSoftmax=function(e){return this.throwIfDisposed(),Ip(this,e)};ee.prototype.logSumExp=function(e,t){return this.throwIfDisposed(),sw(this,e,t)};ee.prototype.log=function(){return this.throwIfDisposed(),ls(this)};ee.prototype.log1p=function(){return this.throwIfDisposed(),Lp(this)};ee.prototype.logicalAnd=function(e){return this.throwIfDisposed(),Bs(this,e)};ee.prototype.logicalNot=function(){return this.throwIfDisposed(),Th(this)};ee.prototype.logicalOr=function(e){return this.throwIfDisposed(),xp(this,e)};ee.prototype.logicalXor=function(e){return this.throwIfDisposed(),fA(this,e)};ee.prototype.matMul=function(e,t,n){return this.throwIfDisposed(),ct(this,e,t,n)};ee.prototype.maxPool=function(e,t,n,s){return this.throwIfDisposed(),Ah(this,e,t,n,s)};ee.prototype.max=function(e,t){return this.throwIfDisposed(),es(this,e,t)};ee.prototype.maximumStrict=function(e){return this.throwIfDisposed(),OA(this,e)};ee.prototype.maximum=function(e){return this.throwIfDisposed(),Us(this,e)};ee.prototype.mean=function(e,t){return this.throwIfDisposed(),jt(this,e,t)};ee.prototype.min=function(e,t){return this.throwIfDisposed(),Ka(this,e,t)};ee.prototype.minimumStrict=function(e){return this.throwIfDisposed(),EA(this,e)};ee.prototype.minimum=function(e){return this.throwIfDisposed(),Bo(this,e)};ee.prototype.mirrorPad=function(e,t){return this.throwIfDisposed(),rw(this,e,t)};ee.prototype.modStrict=function(e){return this.throwIfDisposed(),DA(this,e)};ee.prototype.mod=function(e){return this.throwIfDisposed(),Tp(this,e)};ee.prototype.mulStrict=function(e){return this.throwIfDisposed(),kA(this,e)};ee.prototype.mul=function(e){return this.throwIfDisposed(),X(this,e)};ee.prototype.neg=function(){return this.throwIfDisposed(),qt(this)};ee.prototype.norm=function(e,t,n){return this.throwIfDisposed(),Wp(this,e,t,n)};ee.prototype.notEqualStrict=function(e){return this.throwIfDisposed(),NA(this,e)};ee.prototype.notEqual=function(e){return this.throwIfDisposed(),Mr(this,e)};ee.prototype.oneHot=function(e,t=1,n=0){return this.throwIfDisposed(),ko(this,e,t,n)};ee.prototype.onesLike=function(){return this.throwIfDisposed(),_n(this)};ee.prototype.pad=function(e,t){return this.throwIfDisposed(),Ni(this,e,t)};ee.prototype.pool=function(e,t,n,s,i){return this.throwIfDisposed(),bA(this,e,t,n,s,i)};ee.prototype.powStrict=function(e){return this.throwIfDisposed(),FA(this,e)};ee.prototype.pow=function(e){return this.throwIfDisposed(),ti(this,e)};ee.prototype.prelu=function(e){return this.throwIfDisposed(),Nh(this,e)};ee.prototype.prod=function(e,t){return this.throwIfDisposed(),vp(this,e,t)};ee.prototype.reciprocal=function(){return this.throwIfDisposed(),lw(this)};ee.prototype.relu=function(){return this.throwIfDisposed(),Ci(this)};ee.prototype.relu6=function(){return this.throwIfDisposed(),hw(this)};ee.prototype.reshapeAs=function(e){return this.throwIfDisposed(),K(this,e.shape)};ee.prototype.reshape=function(e){return this.throwIfDisposed(),K(this,e)};ee.prototype.resizeBilinear=function(e,t){return this.throwIfDisposed(),jA(this,e,t)};ee.prototype.resizeNearestNeighbor=function(e,t){return this.throwIfDisposed(),KA(this,e,t)};ee.prototype.reverse=function(e){return this.throwIfDisposed(),Ts(this,e)};ee.prototype.rfft=function(){return this.throwIfDisposed(),Eh(this)};ee.prototype.round=function(){return this.throwIfDisposed(),uw(this)};ee.prototype.rsqrt=function(){return this.throwIfDisposed(),Np(this)};ee.prototype.selu=function(){return this.throwIfDisposed(),Cp(this)};ee.prototype.separableConv2d=function(e,t,n,s,i,o){return this.throwIfDisposed(),dw(this,e,t,n,s,i,o)};ee.prototype.sigmoid=function(){return this.throwIfDisposed(),Ai(this)};ee.prototype.sign=function(){return this.throwIfDisposed(),pw(this)};ee.prototype.sin=function(){return this.throwIfDisposed(),Rp(this)};ee.prototype.sinh=function(){return this.throwIfDisposed(),Op(this)};ee.prototype.slice=function(e,t){return this.throwIfDisposed(),tt(this,e,t)};ee.prototype.softmax=function(e){return this.throwIfDisposed(),Vo(this,e)};ee.prototype.softplus=function(){return this.throwIfDisposed(),ja(this)};ee.prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),vh(this,e,t)};ee.prototype.split=function(e,t){return this.throwIfDisposed(),us(this,e,t)};ee.prototype.sqrt=function(){return this.throwIfDisposed(),Nn(this)};ee.prototype.square=function(){return this.throwIfDisposed(),At(this)};ee.prototype.squaredDifference=function(e){return this.throwIfDisposed(),Dh(this,e)};ee.prototype.squaredDifferenceStrict=function(e){return this.throwIfDisposed(),_A(this,e)};ee.prototype.squeeze=function(e){return this.throwIfDisposed(),Pr(this,e)};ee.prototype.stack=function(e,t){this.throwIfDisposed();const n=e instanceof ee?[this,e]:[this,...e];return ts(n,t)};ee.prototype.step=function(e){return this.throwIfDisposed(),ec(this,e)};ee.prototype.stridedSlice=function(e,t,n,s,i,o,a,c){return this.throwIfDisposed(),fw(this,e,t,n,s,i,o,a,c)};ee.prototype.subStrict=function(e){return this.throwIfDisposed(),WA(this,e)};ee.prototype.sub=function(e){return this.throwIfDisposed(),Re(this,e)};ee.prototype.sum=function(e,t){return this.throwIfDisposed(),$e(this,e,t)};ee.prototype.tan=function(){return this.throwIfDisposed(),gw(this)};ee.prototype.tanh=function(){return this.throwIfDisposed(),Va(this)};ee.prototype.tile=function(e){return this.throwIfDisposed(),Ur(this,e)};ee.prototype.toBool=function(){return this.throwIfDisposed(),Ae(this,"bool")};ee.prototype.toFloat=function(){return this.throwIfDisposed(),Ae(this,"float32")};ee.prototype.toInt=function(){return this.throwIfDisposed(),Ae(this,"int32")};ee.prototype.topk=function(e,t){return this.throwIfDisposed(),yw(this,e,t)};ee.prototype.transpose=function(e){return this.throwIfDisposed(),Ye(this,e)};ee.prototype.unique=function(e){return this.throwIfDisposed(),Fp(this,e)};ee.prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),bw(this,e,t)};ee.prototype.unstack=function(e){return this.throwIfDisposed(),ni(this,e)};ee.prototype.where=function(e,t){return this.throwIfDisposed(),Bn(e,this,t)};ee.prototype.zerosLike=function(){return this.throwIfDisposed(),et(this)};let jp;function mn(){return jp==null&&(jp=JT().epsilon()),jp}function Oee(e){jp=e}function si(){return"channelsLast"}class ir extends Error{constructor(e){super(e);Object.setPrototypeOf(this,ir.prototype)}}class ii extends Error{constructor(e){super(e);Object.setPrototypeOf(this,ii.prototype)}}class q extends Error{constructor(e){super(e);Object.setPrototypeOf(this,q.prototype)}}class Pe extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Pe.prototype)}}class dv extends Error{constructor(e){super(e);Object.setPrototypeOf(this,dv.prototype)}}class jz extends Error{constructor(e){super(e);Object.setPrototypeOf(this,jz.prototype)}}function Ho(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 As(e,t){if(!e)throw new dv(t)}function pv(e,t){let n=0;for(const s of e)s===t&&n++;return n}function ns(e){return e.length===1?e[0]:e}function kt(e){return Array.isArray(e)?e:[e]}function Eee(e){const t=kt(e);let n="";for(const s of t){if(s.id==null)throw new q(`Object ${s} passed to objectListUid without an id`);n!==""&&(n=n+", "),n=`${n}${Math.abs(s.id)}`}return n}function rr(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 qo(e){return e.length<=1||e.indexOf("_")===-1?e:e.replace(/[_]+(\w|$)/g,(t,n)=>n.toUpperCase())}let Ms={};function Mw(e){if(e==null)return null;const t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function Pw(e){if(e==null||typeof e!="object")return;if(Array.isArray(e))e.forEach(t=>Pw(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:Pw(s))}}}function Vh(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 Ms)a=Ms[o];else if(a=t[o],a==null)throw new q(`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 q(`${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 Ms?[c,h]=Ms.className:a in t&&([c,h]=t[a]),c==null)throw new q(`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(Ms))d[w]=Ms[w];for(const w of Object.keys(n))d[w]=n[w];const m=o.config;m.customObjects=d;const f=Object.assign({},Ms);for(const w of Object.keys(n))Ms[w]=n[w];Pw(o.config);const b=h(c,o.config,n,i);return Ms=Object.assign({},f),b}else{const d=Object.assign({},Ms);for(const f of Object.keys(n))Ms[f]=n[f];const m=new c(o.config);return Ms=Object.assign({},d),m}}}function Kz(e,t){return e<t?-1:e>t?1:0}function Kp(e,t){return-1*Kz(e,t)}function Dee(e){switch(e){case"float32":return"float32";default:throw new q(`Invalid dtype: ${e}`)}}function kee(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 Gr(e){if(e==null)return e;const t=[];for(const n of e)t.indexOf(n)===-1&&t.push(n);return t}function Xz(e){if(e==null)throw new q(`Invalid value in obj: ${JSON.stringify(e)}`);for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function rc(e,t,n){if(n==null)return;if(e.indexOf(n)<0)throw new q(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function zw(e,t,n=0,s=Infinity){return As(n>=0),As(s>=n),Array.isArray(e)&&e.length>=n&&e.length<=s&&e.every(i=>typeof i===t)}function wn(e,t){Array.isArray(e)?(A(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,s)=>wn(n,`element ${s+1} of ${t}`))):A(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${mv(e)}.`)}function mv(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>mv(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function Jz(e,t){let n=Kn(),s;const i=(...o)=>{const a=Kn();return a-n<t||(n=a,s=e(...o)),s};return i}function fv(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function Fee(...e){As(e.length>0,"arrayOfValues is empty");for(const t of e)As(Array.isArray(t),"one of the values is not an array"),As(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 Vw(e,t){return Q(()=>Nn($e(X(e,e),t,!0)))}class Gh extends Fo{getConfig(){return{}}}class Gw extends Gh{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 Q(()=>{const t=Vw(e,this.axis),n=Zn(t,0,this.maxValue);return X(e,We(n,be(mn(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}Gw.className="MaxNorm",fe(Gw);class Yw extends Gh{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return Q(()=>We(e,be(mn(),Vw(e,this.axis))))}getConfig(){return{axis:this.axis}}}Yw.className="UnitNorm",fe(Yw);class Hw extends Gh{apply(e){return Ci(e)}}Hw.className="NonNeg",fe(Hw);class qw extends Gh{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 Q(()=>{const t=Vw(e,this.axis),n=be(X(this.rate,Zn(t,this.minValue,this.maxValue)),X(1-this.rate,t));return X(e,We(n,be(mn(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}qw.className="MinMaxNorm",fe(qw);const gv={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function fn(e){return Mw(e)}function yv(e,t={}){return Vh(e,$s.getMap().classNameMap,t,"constraint")}function gn(e){if(e==null)return null;if(typeof e=="string"){const t=e in gv?gv[e]:e,n={className:t,config:{}};return yv(n)}else return e instanceof Gh?e:yv(e)}function Zz(e){return new Gw(e)}function Qz(e){return new Yw(e)}function e3(){return new Hw}function t3(e){return new qw(e)}var n3=Object.freeze({__proto__:null,maxNorm:Zz,unitNorm:Qz,nonNeg:e3,minMaxNorm:t3});const s3=["channelsFirst","channelsLast"],i3=["valid","same","causal"],r3=["max","avg"],o3=["sum","mul","concat","ave"],_ee=["temporal"];const oc=new Map;function Kt(e){rc(s3,"DataFormat",e)}function vs(e){rc(i3,"PaddingMode",e)}function bv(e){rc(r3,"PoolMode",e)}const Yh=[],wv="/";function jo(e,t){Yh.push(e);try{const n=t();return Yh.pop(),n}catch(n){throw Yh.pop(),n}}function a3(){return Yh.length===0?"":Yh.join(wv)+wv}function Lv(e){if(!Iv(e))throw new Error("Not a valid tensor name: '"+e+"'");return a3()+e}function Sv(e){if(!Iv(e))throw new Error("Not a valid tensor name: '"+e+"'");oc.has(e)||oc.set(e,0);const t=oc.get(e);if(oc.set(e,oc.get(e)+1),t>0){const n=`${e}_${t}`;return oc.set(n,1),n}else return e}const c3=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function Iv(e){return!!e.match(c3)}function l3(e){return e===parseInt(e.toString(),10)}function Yr(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 Xp(e){return e=Array.isArray(e)?new Float32Array(e):e,hs(e)}function ac(e){return Ka(Xp(e)).dataSync()[0]}function Hr(e){return es(Xp(e)).dataSync()[0]}function h3(e){return $e(Xp(e)).dataSync()[0]}function u3(e){return h3(e)/e.length}function Wee(e){const t=Re(Xp(e),Ce(u3(e))),n=$e(X(t,t)).dataSync()[0];return n/e.length}function $ee(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 ri(e,t){if(t<e)throw new q(`end (${t}) < begin (${e}) is forbidden.`);const n=[];for(let s=e;s<t;++s)n.push(s);return n}let xv="webgl";function Uee(e){XT(e),xv=e}function Bee(){return xv}function Mee(){return!1}function Pee(e){const t=e.shape;return t.length>0?t.reduce((n,s)=>n*s):1}function Hh(e,t){return e.asType(t)}function qh(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 d3(e,t){return Q(()=>{if(e.shape.length!==2)throw new q(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);const n=qh(e,1);return Xw(n,[1,t,1])})}function p3(e){const t=[Yr(e.shape)];return e.reshape(t)}function m3(e){if(e.rank<=1)throw new q(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);const t=[e.shape[0],Yr(e.shape,1)];return e.reshape(t)}function Ko(e,t,n){return Q(()=>{switch(e.rank){case 1:return Ep(e,t,n);case 2:return mw(e,[t,0],[n,e.shape[1]]);case 3:return Dp(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return Rh(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return tt(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return tt(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 q(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function jw(e,t,n){return Q(()=>{switch(e.rank){case 1:return Ep(e,t,n);case 2:return mw(e,[0,t],[e.shape[0],n]);case 3:return Dp(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return Rh(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new q(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Jp(e,t,n,s){return Q(()=>{switch(e.rank){case 1:return Ep(e,t,n);case 2:switch(s){case 1:return Ko(e,t,n);case 2:return jw(e,t,n);default:throw new q(`The axis is not within the rank of the tensor ${s}`)}case 3:switch(s){case 1:return Ko(e,t,n);case 2:return Dp(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return jw(e,t,n);default:throw new q(`The axis is not within the rank of the tensor ${s}`)}case 4:switch(s){case 1:return Ko(e,t,n);case 2:return Rh(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return Rh(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return jw(e,t,n);default:throw new q(`The axis is not within the rank of the tensor ${s}`)}default:throw new q(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Kw(e,t=-1){let n;return t<0&&(n=e[0].rank,n!==0?t=n:t=0),t===e[0].rank&&(t=-1),Ht(e,t)}function Tv(e,t){switch(e.rank){case 1:return sA([e,t]);case 2:return iA([e,t],0);case 3:return rA([e,t],0);case 4:return oA([e,t],0);default:throw new q(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function Xw(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new q(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return Ur(e,t)}function Zp(e,t=0,n=1,s,i){return cw(e,t,n,s,i)}function Ri(e,t,n,s){if(e.rank<2||t.rank<2)throw new Pe(`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 Pe(`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 Pp({a:e,b:t,transposeA:i,transposeB:o,bias:s?Jw(e.rank,s,si()):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,x)=>x===0?t.rank-2:x<=t.rank-2?x-1:x);t=t.transpose(m).reshape([h,-1]);const f=[...i,...d],b=!1,w=!1;return Pp({a:e,b:t,transposeA:b,transposeB:w,bias:s?Jw(e.rank,s,si()):null,activation:n}).reshape(f)}}function zee(e){return Q(()=>{const t=et(e),n=_n(e);return Bn(Qs(e,t),t,Bn(xs(e,et(e)),n,X(-1,n)))})}function Vee(e,t){return Q(()=>{if(e.rank!==1)throw new Error("Only 1D one-hot tensors are supported in the deeplearn backend, at present.");return e=e.toInt(),ko(e,t).toFloat()})}function Av(e,t,n){return Q(()=>(Array.isArray(t)?t=hs(t,"int32"):t=t.toInt(),qa(e,t,n)))}function jh(e){return X(e,e)}function Gee(e,t){return Q(()=>{if(typeof t=="number"&&(t=Ce(Math.round(t),"int32")),t.dtype!=="int32")throw new Pe(`Non-int32 dtype (${t.dtype}) is not supported by pow() yet`);return ti(e,t)})}function Jw(e,t,n){const s=t.shape;if(t.rank!==1&&t.rank!==e)throw new q(`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 q(`Unsupported input rank by biasAdd: ${t.rank}`)}function Oi(e,t,n){return Q(()=>(n==null&&(n=si()),Kt(n),e.add(Jw(e.rank,t,n))))}function f3(e,t=1){if(t!==1)throw new Pe(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return Ga(e)}function g3(e){return Q(()=>We(e,dn(e).add(1)))}function vv(e,t,n,s){return Q(()=>MA(e,t,n,s))}function y3(e){return Q(()=>{const t=be(.5,X(.2,e));return Zn(t,0,1)})}function Kh(e,t,n=!1){return n?e():t()}const b3=["fanIn","fanOut","fanAvg"],w3=["normal","uniform","truncatedNormal"],Yee=["Zeros","Ones","Constant","RandomNormal","RandomUniform","TruncatedNormal","VarianceScaling","Orthogonal","Identity"];function L3(e){rc(b3,"FanMode",e)}function S3(e){rc(w3,"Distribution",e)}class Ps extends Fo{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class Zw extends Ps{apply(e,t){return dt(e,t)}}Zw.className="Zeros",fe(Zw);class Qp extends Ps{apply(e,t){return ei(e,t)}}Qp.className="Ones",fe(Qp);class Qw extends Ps{constructor(e){super();if(typeof e!="object")throw new q(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new q(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return Q(()=>X(Ce(this.value),ei(e,t)))}getConfig(){return{value:this.value}}}Qw.className="Constant",fe(Qw);class eL extends Ps{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 zo(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}eL.className="RandomUniform",fe(eL);class tL extends Ps{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 Pe(`randomNormal does not support dType ${t}.`);return Zp(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}tL.className="RandomNormal",fe(tL);class nL extends Ps{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 Pe(`truncatedNormal does not support dType ${t}.`);return kh(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}nL.className="TruncatedNormal",fe(nL);class sL extends Ps{constructor(e){super();this.gain=e.gain!=null?e.gain:1}apply(e,t){return Q(()=>{if(e.length!==2||e[0]!==e[1])throw new q("Identity matrix initializer can only be used for 2D square matrices.");return X(this.gain,bp(e[0]))})}getConfig(){return{gain:this.gain}}}sL.className="Identity",fe(sL);function I3(e,t="channelsLast"){let n,s;if(Kt(t),e.length===2)n=e[0],s=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){const i=Yr(e,2);n=e[1]*i,s=e[0]*i}else if(t==="channelsLast"){const i=Yr(e,0,e.length-2);n=e[e.length-2]*i,s=e[e.length-1]*i}}else{const i=Yr(e);n=Math.sqrt(i),s=Math.sqrt(i)}return[n,s]}class ss extends Ps{constructor(e){super();if(e.scale<0)throw new q(`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,L3(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,S3(this.distribution),this.seed=e.seed}apply(e,t){const n=I3(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 Pe(`${this.getClassName()} does not support dType ${t}.`);return kh(e,0,a,t,this.seed)}else{const a=Math.sqrt(3*o);return zo(e,-a,a,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}ss.className="VarianceScaling",fe(ss);class em extends ss{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return ss.className}}em.className="GlorotUniform",fe(em);class tm extends ss{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return ss.className}}tm.className="GlorotNormal",fe(tm);class nm extends ss{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return ss.className}}nm.className="HeNormal",fe(nm);class sm extends ss{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return ss.className}}sm.className="HeUniform",fe(sm);class im extends ss{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return ss.className}}im.className="LeCunNormal",fe(im);class rm extends ss{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return ss.className}}rm.className="LeCunNormal",fe(rm);class iL extends Ps{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 Pe("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return Q(()=>{if(e.length<2)throw new Pe("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=Zp(n,0,1,"float32");let i=JA.gramSchmidt(s);return e[0]>e[1]&&(i=i.transpose()),X(this.gain,i)})}getConfig(){return{gain:this.gain,seed:this.seed}}}iL.className="Orthogonal",fe(iL);const Nv={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 Cv(e,t={}){return Vh(e,$s.getMap().classNameMap,t,"initializer")}function Xt(e){return Mw(e)}function Pt(e){if(typeof e=="string"){const t=e in Nv?Nv[e]:e;if(t==="GlorotNormal")return new tm;if(t==="GlorotUniform")return new em;if(t==="HeNormal")return new nm;if(t==="HeUniform")return new sm;if(t==="LeCunNormal")return new im;if(t==="LeCunUniform")return new rm;{const n={};return n.className=t,n.config={},Cv(n)}}else return e instanceof Ps?e:Cv(e)}function x3(){return new Zw}function T3(){return new Qp}function A3(e){return new Qw(e)}function v3(e){return new eL(e)}function N3(e){return new tL(e)}function C3(e){return new nL(e)}function R3(e){return new sL(e)}function O3(e){return new ss(e)}function E3(e){return new em(e)}function D3(e){return new tm(e)}function k3(e){return new nm(e)}function F3(e){return new sm(e)}function _3(e){return new im(e)}function W3(e){return new rm(e)}function $3(e){return new iL(e)}var U3=Object.freeze({__proto__:null,zeros:x3,ones:T3,constant:A3,randomUniform:v3,randomNormal:N3,truncatedNormal:C3,identity:R3,varianceScaling:O3,glorotUniform:E3,glorotNormal:D3,heNormal:k3,heUniform:F3,leCunNormal:_3,leCunUniform:W3,orthogonal:$3});let B3=0;function Rv(){return B3++}const om={};function am(e=""){return e in om||(om[e]=0),om[e]+=1,e+om[e].toString()}function rL(e){return Array.isArray(e)&&Array.isArray(e[0])}function cm(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function Je(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new q(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function Nt(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(e.length===1)return e=e,e[0];throw new q(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function lm(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 Ov="Variable";class oi{constructor(e,t="float32",n=Ov,s=!0,i=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=Rv(),n=n==null?Ov:n,this.originalName=Lv(n),this.name=Sv(this.originalName),this.trainable_=s,this.constraint=i,this.val=SA(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),M3(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 M3(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function Hee(e,t,n,s){return new oi(e,t,n,!0,s)}function qee(e,t,n){return new oi(dt(e),t,n)}function jee(e,t,n){return new oi(et(e),t,n)}function Kee(e,t,n){const s=ei(e);return new oi(s,t,n)}function Xee(e,t,n){const s=_n(e);return new oi(s,t,n)}function Jee(e,t,n){return new oi(bp(e),t,n)}function Zee(e,t,n,s,i,o="randomUniform"){return new oi(zo(e,t,n,s),s,o)}function Qee(e,t=0,n=1,s,i,o="truncatedNormal"){if(s=s||"float32",s!=="float32"&&s!=="int32")throw new Pe(`randomNormal does not support dType ${s}.`);return new oi(kh(e,t,n,s,i),s,o)}function ete(e,t=0,n=1,s,i,o="randomNormal"){if(s=s||"float32",s!=="float32"&&s!=="int32")throw new Pe(`randomNormalVariable does not support dType ${s}.`);return new oi(cw(e,t,n,s,i),s,o)}function tte(e,t){return e.write(t)}function nte(e,t){return e.write(be(e.read(),t))}function ste(e,t){return e.write(Re(e.read(),t))}function oL(e){return e.map(t=>t.read())}function aL(e){e.forEach(t=>{const n=t[0];n.write(t[1])})}function ite(e,t){const n=t.map(i=>i.read()),s=nw(e,n);return t.map(i=>s.grads[i.name])}class Ln{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 ai{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=Rv(),o!=null&&(this.originalName=Lv(o),this.name=Sv(this.originalName)),this.rank=t.length}}let P3=0;class hm{constructor(e,t){this.callArgs=t,this.id=P3++,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 z3=0;class lt extends Fo{constructor(e={}){super();this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=z3++,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=rr(n)+"_"+am(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 ii(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new q(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return ns(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return ns(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new ir(`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 ir(`Layer ${this.name} is not connected, no input to return.`);return ns(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new ir(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new ir(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return ns(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=kt(e),this.inputSpec==null||this.inputSpec.length===0)return;const t=kt(this.inputSpec);if(e.length!==t.length)throw new q(`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 q(`Input ${n} is incompatible with layer ${this.name}: expected ndim=${i.ndim}, found ndim=${o}`);if(i.maxNDim!=null&&o>i.maxNDim)throw new q(`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 q(`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 q(`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 q(`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 q(`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=kt(e);let s=!0;for(const o of n)if(!(o instanceof ai)){s=!1;break}let i=!0;for(const o of n)if(o instanceof ai){i=!1;break}if(s===i)throw new q("Arguments to apply() must be all SymbolicTensors or all Tensors");return jo(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);const o=[];for(const a of kt(e))o.push(a.shape);this.build(ns(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=kt(o),c=[];for(let h of a)n.indexOf(h)!==-1&&(h=h.clone()),c.push(h);if(o=ns(c),this.activityRegularizer!=null)throw new Pe("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return o}else{const o=V3(e),a=this.computeOutputShape(o);let c;const h=G3(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 ai(h,d,this,kt(e),t,this.name,m)):c=new ai(h,a,this,kt(e),t,this.name),this.addInboundNode(e,c,null,null,o,a,t),this._refCount++,this.activityRegularizer!=null)throw new Pe("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 ir(`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 ir(`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 ii(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return lm(this.weights)}build(e){this.built=!0}getWeights(e=!1){return oL(e?this.trainableWeights:this.weights)}setWeights(e){Q(()=>{const t=this.weights;if(t.length!==e.length)throw new q(`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=oL(t);for(let i=0;i<s.length;++i){const o=s[i],a=t[i],c=e[i];if(!ae(o.shape,c.shape))throw new q(`Layer weight shape ${o.shape} not compatible with provided weight shape ${c.shape}`);n.push([a,c])}aL(n)})}addWeight(e,t,n,s,i,o,a){if(this._addedWeightNames.indexOf(e)!==-1)throw new q(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),n==null&&(n="float32"),this.fastWeightInitDuringBuild&&(s=Pt("zeros"));const c=s.apply(t,n),h=new oi(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=kt(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=kt(e);t=kt(t),n=kt(n),s=kt(s),i=cm(i),o=cm(o);const h=[],d=[],m=[];for(const f of c)h.push(f.sourceLayer),d.push(f.nodeIndex),m.push(f.tensorIndex);new hm({outboundLayer:this,inboundLayers:h,nodeIndices:d,tensorIndices:m,inputTensors:c,outputTensors:t,inputMasks:n,outputMasks:s,inputShapes:i,outputShapes:o},a);for(let f=0;f<t.length;f++)t[f].sourceLayer=this,t[f].nodeIndex=this.inboundNodes.length-1,t[f].tensorIndex=f}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 V3(e){e=kt(e);const t=[];for(const n of e)t.push(n.shape);return ns(t)}function G3(e){return"float32"}function Ev(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=Ev(a,c,h);for(const m of d)i.indexOf(m)===-1&&i.push(m)}return i}}}class cc extends lt{constructor(e){super({dtype:e.dtype,name:e.name!=null?e.name:am("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 q("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 q("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(e.batchSize!=null)throw new q("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 ai(this.dtype,this.batchInputShape,this,[],{},this.name);s.nodeIndex=0,s.tensorIndex=0,new hm({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[s],outputTensors:[s],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new q(`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}}}cc.className="InputLayer",fe(cc);function Dv(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 q("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 cc({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}),i=s.inboundNodes[0].outputTensors;return i[0]}async function qr(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 kv(e){if(e==null)return;for(const t in e){const n=e[t];typeof n!="number"&&n.dispose()}}var Fv;(function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"})(Fv||(Fv={}));const Y3=125;class lc{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 _v{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 lc{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=Q(()=>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:Q(()=>{const s=X(We(1,this.seen),this.totals[n]);t[n]=s,this.totals[n].dispose(),bn(t[n])})}}}class Wv extends lc{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 $v extends lc{constructor(e,t){super();if(this.currentEpoch=0,this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=Y3),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");ld(this.yieldEvery)&&(this.maybeWait=Jz(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 qr(n),s.push(this.yield(e,t,n))),s.push(Yp()),await Promise.all(s)}async onEpochBegin(e,t){this.currentEpoch=e,this.epochBegin!=null&&(await qr(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){const n=[];this.epochEnd!=null&&(await qr(t),n.push(this.epochEnd(e,t))),this.yieldEvery==="epoch"&&n.push(Yp()),await Promise.all(n)}async onBatchBegin(e,t){this.batchBegin!=null&&(await qr(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){const n=[];this.batchEnd!=null&&(await qr(t),n.push(this.batchEnd(e,t))),this.yieldEvery==="batch"?n.push(Yp()):ld(this.yieldEvery)&&n.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(n)}async onTrainBegin(e){this.trainBegin!=null&&(await qr(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await qr(e),await this.trainEnd(e))}}function Uv(e,t){if(e==null&&(e={}),e instanceof lc)return[e];if(Array.isArray(e)&&e[0]instanceof lc)return e;const n=kt(e);return n.map(s=>new $v(s,t))}class zs{constructor(){}static registerCallbackConstructor(e,t){A(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),zs.checkForDuplicate(t),zs.constructors[e]==null&&(zs.constructors[e]=[]),zs.constructors[e].push(t)}static checkForDuplicate(e){for(const t in zs.constructors){const n=zs.constructors[+t];n.forEach(s=>{if(s===e)throw new q("Duplicate callback constructor.")})}}static clear(){zs.constructors={}}static createCallbacks(e){const t=[];for(const n in zs.constructors){const s=+n;e>=s&&t.push(...zs.constructors[s])}return t.map(n=>new n)}}zs.constructors={};function Bv(e,t,n,s,i,o,a,c,h){const d=new Wv,m=[new H3,...zs.createCallbacks(t)];e!=null&&m.push(...e),m.push(d);const f=new _v(m);return f.setParams({epochs:n,initialEpoch:s,samples:i,steps:o,batchSize:a,verbose:t,doValidation:c,metrics:h}),{callbackList:f,history:d}}function ci(e,t={},n=!1){return Vh(e,$s.getMap().classNameMap,t,"layer",n)}function um(e,t){return Q(()=>{e.dtype!=="float32"&&(e=e.asType("float32"));const n=$e(jh(e),t,!0),s=Ya(n.shape,mn()),i=Nn(Us(n,s));return We(e,i)})}function or(e,t){return Q(()=>jt(jh(Re(t,e)),-1))}function hc(e,t){return Q(()=>jt(dn(Re(t,e)),-1))}function jr(e,t){return Q(()=>{const n=Re(e,t),s=Zn(dn(e),mn(),Number.MAX_VALUE),i=dn(We(n,s));return X(100,jt(i,-1))})}function cL(e,t){return Q(()=>{const n=Zn(t,mn(),Number.MAX_VALUE),s=ls(be(1,n)),i=Zn(e,mn(),Number.MAX_VALUE),o=ls(be(1,i));return jt(jh(Re(s,o)),-1)})}function q3(e,t){return Q(()=>{const n=Us(0,Re(1,X(e,t)));return jt(jh(n),-1)})}function j3(e,t){return Q(()=>{const n=Us(0,Re(1,X(e,t)));return jt(n,-1)})}function K3(e,t){return Q(()=>{const n=$e(X(e,t),-1),s=es(X(Re(1,e),t),-1);return Us(0,be(1,Re(s,n)))})}function X3(e,t){return Q(()=>{const n=Math.log(2),s=Re(t,e),i=Re(be(s,ja(X(-2,s))),n);return jt(i,-1)})}function Xh(e,t,n=!1){return Q(()=>{if(n)t=Vo(t);else{const s=$e(t,t.shape.length-1,!0);t=We(t,s)}return t=Zn(t,mn(),1-mn()),qt($e(X(e.toFloat(),ls(t)),t.shape.length-1))})}function dm(e,t,n=!1){return Q(()=>{const s=Ha(p3(e)).toInt();t=Zn(t,mn(),1-mn());const i=t.shape,o=ko(s,i[i.length-1]).reshape(i);return Xh(o,t,n)})}function J3(e,t){if(!ae(e.shape,t.shape))throw new q(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return Q(()=>{const n=t.relu(),s=t.abs().neg();return n.sub(t.mul(e)).add(s.exp().log1p())})}function pm(e,t){return Q(()=>{let n;return n=Zn(t,mn(),1-mn()),n=ls(We(n,Re(1,n))),jt(J3(e,n),-1)})}function lL(e,t){return Q(()=>{const n=Zn(e,mn(),1),s=Zn(t,mn(),1);return $e(X(e,ls(We(n,s))),-1)})}function Z3(e,t){return Q(()=>{const n=ls(be(mn(),t));return jt(Re(t,X(e,n)),-1)})}function mm(e,t){return Q(()=>{const n=um(e,-1),s=um(t,-1),i=X(n,s);return qt($e(i,-1))})}const rte=or,ote=or,ate=hc,cte=hc,lte=jr,hte=jr,ute=cL,dte=cL,pte=lL,mte=lL,fte=mm,fm={meanSquaredError:or,meanAbsoluteError:hc,meanAbsolutePercentageError:jr,meanSquaredLogarithmicError:cL,squaredHinge:q3,hinge:j3,categoricalHinge:K3,logcosh:X3,categoricalCrossentropy:Xh,sparseCategoricalCrossentropy:dm,binaryCrossentropy:pm,kullbackLeiblerDivergence:lL,poisson:Z3,cosineProximity:mm};function hL(e){if(typeof e=="string"){if(e in fm)return fm[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 q(t)}else return e}function uL(e,t){return Q(()=>{const n=X(.5,_n(t)),s=Hh(xs(t,n),e.dtype);return jt(Qs(e,s),-1)})}function dL(e,t){return Q(()=>Hh(Qs(fh(e,-1),fh(t,-1)),"float32"))}function Mv(e,t){return Q(()=>Bs(e.equal(1),t.equal(1)).sum().cast("float32"))}function Q3(e,t){return Q(()=>Bs(e.equal(1),t.equal(0)).sum().cast("float32"))}function eV(e,t){return Q(()=>Bs(e.equal(0),t.equal(1)).sum().cast("float32"))}function Pv(e,t){return Q(()=>{const n=Mv(e,t),s=eV(e,t),i=n.add(s);return Bn(xs(i,0),n.div(i),0).cast("float32")})}function tV(e,t){return Q(()=>{const n=Mv(e,t),s=Q3(e,t),i=n.add(s);return Bn(xs(i,0),n.div(i),0).cast("float32")})}function zv(e,t){return pm(e,t)}function Vv(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)),Qs(e,t).asType("float32")}function gte(e,t){throw new Pe}function yte(e,t){throw new Pe}const nV=or,sV=or,iV=hc,rV=hc,oV=jr,aV=jr,pL=Xh,cV=mm,Gv=dm,gm={binaryAccuracy:uL,categoricalAccuracy:dL,precision:Pv,categoricalCrossentropy:pL,sparseCategoricalCrossentropy:Gv,mse:nV,MSE:sV,mae:iV,MAE:rV,mape:oV,MAPE:aV,cosine:cV};function lV(e){if(typeof e=="string"&&e in gm)return gm[e];if(typeof e!="string"&&e!=null)return e;throw new q(`Unknown metric ${e}`)}function ym(e){if(As(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(const n of Object.keys(fm))if(fm[n]===e){t=n;break}if(t!==void 0)return t;for(const n of Object.keys(gm))if(gm[n]===e){t=n;break}return t!==void 0?t:e.name}}function hV(e){const t={Adagrad:()=>Yo.adagrad(.01),Adadelta:()=>Yo.adadelta(1,.95,mn()),Adam:()=>Yo.adam(.001,.9,.999,mn()),Adamax:()=>Yo.adamax(.002,.9,.999,mn(),0),RMSProp:()=>Yo.rmsprop(.001,.9,0,mn()),SGD:()=>Yo.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 q(`Unknown Optimizer ${e}`)}const Yv=1*1024*1024;function Hv(e,t,n=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!mL(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>Yv&&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 <= ${Yv}.`)}}function mL(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(!mL(e[n]))return!1}return!0}else if(Array.isArray(e)){for(const t of e)if(!mL(t))return!1;return!0}else return!1;else{const t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function uV(e,t,n,s=console.log){const i=pV(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)),bm(o,n,s),s("=".repeat(t));const c=e.layers;for(let m=0;m<c.length;++m)i?mV(c[m],n,s):fV(c[m],n,a,s),s((m===c.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();const h=dV(e),d=lm(e.nonTrainableWeights);s(`Total params: ${h+d}`),s(`Trainable params: ${h}`),s(`Non-trainable params: ${d}`),s("_".repeat(t))}function dV(e){let t;return e.collectedTrainableWeights!=null?t=lm(e.collectedTrainableWeights):t=lm(e.trainableWeights),t}function pV(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 bm(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 mV(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()];bm(a,t,n)}function fV(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 f=0;f<m.inboundLayers.length;++f){const b=m.inboundLayers[f].name,w=m.nodeIndices[f],L=m.tensorIndices[f];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];bm(d,t,s);for(let m=1;m<o.length;++m)bm(["","","",o[m]],t,s)}function qv(e,t,n){return(e==="inboundNodes"||e==="outputLayers"||e==="inputLayers")&&t===0&&typeof n=="string"}function Jh(e,t){if(e===null)return null;if(typeof e=="string")return qo(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];qv(t,i,o)?n.push(o):n.push(Jh(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=qo(s);n[o]=Jh(i,o)}}return n}}function fL(e,t){if(e==null)return null;if(typeof e=="string")return rr(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];qv(t,i,o)?n.push(o):n.push(fL(o,t))}return n}else{const n={};for(const s of Object.keys(e)){const i=e[s],o=rr(s);(s==="name"||s==="className")&&typeof i=="string"?n[o]=i:n[o]=fL(i,s)}return n}}const wm="2.7.0";function gV(e,t){if(e.dtype==null||e.dtype===t.dtype)return t;try{return Ae(t,e.dtype)}catch(n){throw new q(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}class Xo{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof Xo)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]=gV(e,t),this.name2Id[e.name]=e.id,n!=null&&(this.id2Mask[e.id]=n);else throw new q(`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 ai){if(this.id2Value[e.id]==null)throw new q(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}else{const t=this.name2Id[e];if(t==null)throw new q(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof ai){if(this.id2Value[e.id]==null)throw new q(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}else{const t=this.name2Id[e];if(t==null)throw new q(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){this.id2Mask!=null&&He(this.id2Mask)}}const gL={},jv={};function Zh(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 f,b;if(gL[m]==null){const L=yV(a,t);f=L.sorted,b=L.recipientCounts,gL[m]=f,jv[m]=b}f=gL[m],b={},i||Object.assign(b,jv[m]);const w=new Xo(t);for(let L=0;L<f.length;++L){if(s!=null){const j=ap().numTensors;j>s.maxNumTensors&&(s.maxNumTensors=j),j<s.minNumTensors&&(s.minNumTensors=j)}const x=f[L],v=x.sourceLayer;if(v instanceof cc)continue;const N=[],O=[],E=[];let k=!1;for(const j of x.inputs){const Z=w.getValue(j),ie=w.getMask(j);N.push(Z),O.push(ie),ie!=null&&(k=!0),i||(b[j.name]--,b[j.name]===0&&!t.hasKey(j)&&c.indexOf(j.name)===-1&&!Z.isDisposed&&j.sourceLayer.stateful!==!0&&E.push(Z))}k&&(n=n||{},n.mask=O[0]);const F=kt(v.apply(N,n));let U=null;v.supportsMasking&&(U=v.computeMask(N,O));const $=wV(x),Y=Array.isArray($)?$:[$];for(let j=0;j<Y.length;++j){w.hasKey(Y[j])||w.add(Y[j],F[j],Array.isArray(U)?U[0]:U);const Z=c.indexOf(Y[j].name);Z!==-1&&(h[Z]=F[j])}i||He(E)}return w.disposeMasks(),o?h:h[0]}function yV(e,t){A(e!=null&&e.length>0,()=>"Expected at least one fetch, got none");let n=[],s={};if(e.length===1){const i=Kv(e[0],t);n=i.sorted,s=i.recipientMap}else{const i=new Set;for(const o of e){const{sorted:a,recipientMap:c}=Kv(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:bV(s)}}function bV(e){const t={};for(const n in e)t[n]=e[n].size;return t}function Kv(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 wV(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 Ei extends lt{constructor(e){super({});if(this.containerNodes=new Set,this.name=e.name,this.name==null){const N=this.getClassName().toLowerCase();this.name=am(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],Gr(this.inputs).length!==this.inputs.length)throw new q(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(N=>N.name)}`);Gr(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 O=N.sourceLayer,E=N.nodeIndex,k=N.tensorIndex;this.outputLayers.push(O),this.outputLayersNodeIndices.push(E),this.outputLayersTensorIndices.push(k)}for(const N of this.inputs){const O=N.sourceLayer,E=N.nodeIndex,k=N.tensorIndex;As(E===0,"input layer has >1 nodes"),As(k===0,"input layer has >1 tensors"),this.inputLayers.push(O),this.inputLayersNodeIndices.push(E),this.inputLayersTensorIndices.push(k)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let N=0;N<this.inputLayers.length;N++){const O=this.inputLayers[N];if(!(O instanceof cc))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${N} (0-based) originates from layer type ${O.getClassName()}.`);this.inputNames.push(O.name),this.feedInputShapes.push(O.batchInputShape),this.feedInputNames.push(O.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,O,E,k,F,U)=>{(k==null||F==null||U==null)&&(k=N.sourceLayer,F=N.nodeIndex,U=N.tensorIndex);const $=k.inboundNodes[F];if(E.indexOf($)!==-1)throw new ii(`The tensor ${N.name} at layer "${k.name}" is part of a cycle.`);if(O.indexOf($)!==-1)return;this.containerNodes.add(Ei.nodeKey(k,F)),k.id in o||(o[k.id]=Object.keys(o).length),E.indexOf($)===-1&&E.push($);const Y=$.inboundLayers.length;for(let j=0;j<Y;j++){const Z=$.inputTensors[j],ie=$.inboundLayers[j],de=$.nodeIndices[j],he=$.tensorIndices[j];c(Z,O,E,ie,de,he)}for(O.push($);E.indexOf($)>=0;)E.splice(E.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 O=t[N.id];const E=s[N.outboundLayer.id]==null?0:s[N.outboundLayer.id];O=Math.max(O,E),s[N.outboundLayer.id]=O,i[N.outboundLayer.id]=N.outboundLayer,t[N.id]=O;for(let k=0;k<N.inboundLayers.length;k++){const F=N.inboundLayers[k],U=N.nodeIndices[k],$=F.inboundNodes[U],Y=t[$.id]==null?0:t[$.id];t[$.id]=Math.max(O+1,Y),n[$.id]=$}}const f={};for(const N in t){const O=t[N];O in f||(f[O]=[]),f[O].push(n[N])}const b={};for(const N in s){const O=s[N];O in b||(b[O]=[]),b[O].push(i[N])}let w=Object.keys(b).map(N=>parseInt(N,10)).sort(Kp);this.layers=[];for(const N of w){const O=b[N];O.sort((E,k)=>{const F=o[E.id],U=o[k.id];return F<U?-1:F>U?1:0});for(const E of O)E instanceof Ei&&this.internalContainerRefs.push(E),this.layers.push(E)}this.layersByDepth=b,w=Object.keys(f).map(N=>parseInt(N,10)).sort(Kp);const L=this.inputs.slice(),x=[];for(const N of w)for(const O of f[N]){const E=O.outboundLayer;if(E!=null){for(const k of O.inputTensors)if(L.indexOf(k)===-1)throw new ii(`Graph disconnected: cannot obtain value for tensor ${k} at layer "${E.name}". The following previous layers were accessed without issue: ${x}`);for(const k of O.outputTensors)L.push(k);x.push(E.name)}}this.nodesByDepth=f;const v=this.layers.map(N=>N.name);for(const N of v){const O=v.filter(E=>E===N).length;if(O!==1)throw new ii(`The name "${N}" is used ${O} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(v))}this.outboundNodes=[],this.inboundNodes=[],new hm({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 q("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 q(`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 q(`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 q(`${o.length} of ${s} weights are not set: ${o}`)}aL(i)}updatedConfig(){const e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${wm}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){const n=fL(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return Q(()=>{e=kt(e);const n=new Xo;for(let s=0;s<this.inputs.length;++s)n.add(this.inputs[s],e[s]);return Zh(this.outputs,n,t)})}computeMask(e,t){return Q(()=>{e=kt(e);let n;return t==null?n=Ho(null,e.length):n=kt(t),this.runInternalGraph(e,n)[1]})}computeOutputShape(e){const t=cm(e);if(t.length!==this.inputLayers.length)throw new q(`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(Kp);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 x=h.inboundLayers[L],v=h.nodeIndices[L],N=h.tensorIndices[L],O=`${x.name}_${v}_${N}`,E=n[O];m.push(E)}const f=d.computeOutputShape(ns(m)),b=cm(f),w=d.inboundNodes.indexOf(h);for(let L=0;L<b.length;L++){const x=`${d.name}_${w}_${L}`;n[x]=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];As(c in n),i.push(n[c])}return ns(i)}runInternalGraph(e,t){t==null&&(t=Ho(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(Kp);for(const c of s){const h=this.nodesByDepth[c];for(const d of h){const m=d.outboundLayer,f=d.inputTensors,b=d.outputTensors,w=new Array;for(const L of f)L.id in n&&w.push(n[L.id]);if(w.length===f.length){let L={},x,v,N,O;if(d.callArgs!=null&&(L=d.callArgs),w.length===1){const[E,k]=w[0];L.mask==null&&(L.mask=k),N=kt(m.call(E,L)),O=kt(m.computeMask(E,k)),x=[E],v=[k]}else x=w.map(E=>E[0]),v=w.map(E=>E[1]),L.mask==null&&(L.mask=v),N=kt(m.call(x,L)),O=kt(m.computeMask(x,v));if(m.activityRegularizer)throw new Pe("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let E=0;E<b.length;++E){const k=b[E],F=N[E],U=O[E];n[k.id]=[F,U]}}}}const i=[],o=[],a=[];for(const c of this.outputs){As(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 Ei?1:0;for(let i=0;i<s.inboundNodes.length;i++){const o=Ei.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 q(`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 q("Provide either a layer name or layer index");for(const n of this.layers)if(n.name===e)return n;throw new q(`No such layer: ${e}`)}calculateLosses(){return Q(()=>{const e=[];for(const t of this.layers)for(let n=0;n<t.inboundNodes.length;++n){const s=Ei.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 f=o.inboundNodes[m],b=Ei.nodeKey(o,m);let w={};if(this.containerNodes.has(b)){if(f.callArgs)try{JSON.stringify(f.callArgs),w=f.callArgs}catch(L){console.warn(`Layer ${o.name} was passed non-serializable keyword arguments: ${f.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),w={}}if(f.inboundLayers.length>0){const L=[];for(let x=0;x<f.inboundLayers.length;x++){const v=f.inboundLayers[x],N=f.nodeIndices[x],O=f.tensorIndices[x],E=Ei.nodeKey(v,N);let k=t[E];k==null&&(k=0),L.push([v.name,k,O,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=Ei.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=Ei.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(x,v){x.name in o?o[x.name].push(v):o[x.name]=[v]}function c(x,v){const N=[];let O;for(const E of v){const k=E[0],F=E[1],U=E[2];if(O=E[3]==null?{}:E[3],!(k in i)){a(x,v);return}const $=i[k];if($.inboundNodes.length<=F){a(x,v);return}const Y=$.inboundNodes[F];N.push(Y.outputTensors[U])}N.length>0&&x.apply(ns(N),O)}function h(x){const v=x.name,N=ci(x,t.customObjects!=null?t.customObjects:{});N.setFastWeightInitDuringBuild(s),i[v]=N;const O=x.inboundNodes;O.forEach(E=>{if(!(E instanceof Array))throw new q(`Corrupted configuration, expected array for nodeData: ${E}`);a(N,E)})}const d=t.name,m=t.layers;for(const x of m)h(x);for(;!Xz(o);)for(const x of m){const v=i[x.name];if(v.name in o){const N=o[v.name];delete o[v.name];for(const O of N)c(v,O)}}const f=[],b=[],w=t.inputLayers;for(const x of w){const v=x[0],N=x[1],O=x[2];As(v in i);const E=i[v],k=E.inboundNodes[N].outputTensors;f.push(k[O])}const L=t.outputLayers;for(const x of L){const v=x[0],N=x[1],O=x[2];As(v in i);const E=i[v],k=E.inboundNodes[N].outputTensors;b.push(k[O])}return new e({inputs:f,outputs:b,name:d})}get stateful(){if(this._stateful)throw new q("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(){Q(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}}function Xv(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 Jv(e,t){return Xv(e,t,"classWeight")}function bte(e,t){return Xv(e,t,"sampleWeight")}async function Zv(e,t,n,s){if(t!=null||s!=null)throw new Error("Support sampleWeight is not implemented yet");if(n!=null){const i=Q(()=>{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])}),hs(a,"float32")}else return null}function LV(e,t){return X(e,t)}const SV=32;function Qv(e,t){let n,s;const i=t;n=i.xs,s=i.ys,A(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=eN("input",e.inputNames,n),a=eN("output",e.outputNames,s),c=o[0].shape[0];A(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)})`),A(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++)A(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++)A(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 eN(e,t,n){if(n instanceof ee)return[n];if(Array.isArray(n))return A(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 q(`The feature data generated by the dataset lacks the required ${e} key '${i}'.`);s.push(n[i])}return s}}function IV(e){if(e.length===3)throw new Pe("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}async function xV(e,t,n){const s=n.batchesPerEpoch!=null;if(A(e.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),A(n!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),A(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}`),A(!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}`),A(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(tN(n.validationData))A(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 v=IV(n.validationData);o=v.xs,a=v.ys}const c=e.makeTrainFunction(),h=e.getDedupedMetricsNames();let d;i?d=h.slice().concat(h.map(v=>"val_"+v)):d=h.slice();const m=Uv(n.callbacks,n.yieldEvery),f=n.verbose==null?1:n.verbose,{callbackList:b,history:w}=Bv(m,f,n.epochs,null,null,TV(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,x=await t.iterator();for(;L<n.epochs;){const v={};await b.onEpochBegin(L);let N=0,O=0;for(s||(x=await t.iterator());s?N<n.batchesPerEpoch:!0;){const E=await x.next();if(s&&E.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(E.value!=null){const{xs:k,ys:F}=Qv(e,E.value),U={};U.batch=O,U.size=k[0].shape[0],await b.onBatchBegin(O,U);const $=[];if(n.classWeight!=null){const Z=Jv(n.classWeight,e.outputNames);for(let ie=0;ie<Z.length;++ie)$.push(await Zv(F[ie],null,Z[ie]))}const Y=k.concat(F).concat($),j=c(Y);He(Y);for(let Z=0;Z<h.length;++Z){const ie=h[Z],de=j[Z];U[ie]=de,bn(de)}await b.onBatchEnd(O,U),kv(U),O++,N++}if(s?N>=n.batchesPerEpoch:E.done){if(i){let k;tN(n.validationData)?k=kt(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):k=kt(e.evaluate(o,a,{batchSize:n.validationBatchSize==null?SV:n.validationBatchSize,verbose:0}));for(let F=0;F<e.metricsNames.length;++F)v[`val_${e.metricsNames[F]}`]=k[F]}break}if(e.stopTraining_)break}if(await b.onEpochEnd(L,v),L++,e.stopTraining_)break}return await b.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}function TV(e,t){let n=null;return t.batchesPerEpoch!=null?n=t.batchesPerEpoch:Number.isFinite(e.size)&&(n=e.size),n}function tN(e){return typeof e.iterator=="function"}function AV(e){return typeof e.next=="function"}async function vV(e,t,n){n=n||{};const s=n.batches!=null,i=e.testFunction;let o=[];if(n.verbose>0)throw new Pe("Verbose mode is not implemented yet.");A(!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=AV(t)?t:await t.iterator();let c=0,h=0;for(;s?h<n.batches:!0;){const d=await a.next();if(o=Q(()=>{if(d.value){const{xs:m,ys:f}=Qv(e,d.value),b=m.concat(f),w=Q(()=>i(b));if(He(b),h===0)for(let x=0;x<w.length;++x)o.push(Ce(0));const L=b[0].shape[0];for(let x=0;x<w.length;++x){const v=w[x],N=o[x];o[x]=Q(()=>be(o[x],X(L,v))),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]=We(o[d],c),He(m)}return ns(o)}function yL(e){A(e>0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function Qh(e,t,n){return e==null?[null]:Array.isArray(e)?e.map(s=>Ko(s,t,n-t)):Ko(e,t,n-t)}function bL(e,t){return Q(()=>e==null?null:Array.isArray(e)?e.map(n=>bL(n,t)):Av(e,t.dtype==="int32"?t:t.toInt()))}function wL(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 NV(e,t,n,s,i,o,a,c,h,d,m,f,b,w,L){i==null&&(i=32),o==null&&(o=1),m==null&&(m=!0),b==null&&(b=0);let x=!1;if(h!=null&&d!=null&&(x=!0),L!=null&&(x=!0,w==null))throw new q("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");const v=e.checkNumSamples(n,i,w,"steps_per_epoch");let N;v!=null&&(N=ri(0,v)),a==null&&(a=1);const{callbackList:O,history:E}=Bv(c,a,o,b,v,w,i,x,f);O.setModel(e),e.history=E,await O.onTrainBegin(),e.stopTraining_=!1;for(let k=b;k<o;++k){await O.onEpochBegin(k);const F={};if(w!=null)throw new Pe("stepsPerEpoch mode is not implemented yet.");{if(m==="batch")throw new Pe("batch shuffling is not implemneted yet");m&&I(N);const U=hs(N),$=wL(v,i);for(let Y=0;Y<$.length;++Y){const j={};if(await O.onBatchBegin(Y,j),Q(()=>{const Z=$[Y][0],ie=$[Y][1],de=Ko(U,Z,ie-Z);j.batch=Y,j.size=ie-Z;const he=bL(n,de),ue=t(he);for(let me=0;me<s.length;++me){const ce=s[me],ye=ue[me];j[ce]=ye,bn(ye)}if(Y===$.length-1&&x){const me=e.testLoop(h,d,i);for(let ce=0;ce<s.length;++ce){const ye=s[ce],pe=me[ce];bn(pe),F["val_"+ye]=pe}}}),await O.onBatchEnd(Y,j),kv(j),e.stopTraining_)break}U.dispose()}if(await O.onEpochEnd(k,F),e.stopTraining_)break}return await O.onTrainEnd(),await e.history.syncData(),e.history}async function CV(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 f=s.batchSize==null?32:s.batchSize;yL(f);const b=!1,w=await e.standardizeUserData(t,n,s.sampleWeight,s.classWeight,b,f);i=w[0],o=w[1],m=w[2];let L=!1,x;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 Pe("validationData including sample weights is not supported yet."):new q(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${s.validationData} is invalid.`);const $=!0,Y=await e.standardizeUserData(a,c,null,null,$,f);h=Y[0],d=Y[1],x=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)),Y=i[0].shape[0];h=Qh(i,$,Y),i=Qh(i,0,$),d=Qh(o,$,Y),o=Qh(o,0,$),x=h.concat(d)}else s.validationSteps!=null&&(L=!0);const v=i.concat(o).concat(m);e.checkTrainableWeightsConsistency();const N=e.makeTrainFunction(),O=e.getDedupedMetricsNames();let E,k;L?(e.makeTestFunction(),E=e.testFunction,k=O.slice().concat(O.map($=>"val_"+$))):(E=null,x=[],k=O.slice());const F=Uv(s.callbacks,s.yieldEvery),U=await NV(e,N,v,O,f,s.epochs,s.verbose,F,E,x,s.shuffle,k,s.initialEpoch,null,null);return U}finally{e.isTraining=!1,Jo(i,t),Jo(o,n),Jo(h,a),Jo(d,c),m!=null&&He(m)}}function nN(e){const t=[];e instanceof ee&&(e=[e]);for(let n=0;n<e.length;++n){const s=e[n];if(s.rank===1)t.push(qh(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 Jo(e,t){if(e==null)return;const n=[];if(t instanceof ee)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 ee)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 RV(e){return e instanceof ee}function LL(e){return Array.isArray(e)}function sN(e){return!RV(e)&&!LL(e)}function iN(e,t,n,s=!0,i=""){if(t==null||t.length===0){if(e!=null){let a=!1;if(LL(e)&&e.length>0)a=!0;else if(sN(e)){for(const c in e)if(e.hasOwnProperty(c)){a=!0;break}}else a=!0;if(a)throw new q(`Error when checking model ${i} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(a=>null);let o;if(sN(e)){e=e,o=[];for(const a of t){if(e[a]==null)throw new q(`No data provided for "${a}". Need data for each key in: ${t}`);o.push(e[a])}}else if(LL(e)){if(e=e,e.length!==t.length)throw new q(`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 q(`The model ${i} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);o=[e]}if(o=nN(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 q(`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 q(`Error when checking ${i}: expected ${t[a]} to have shape [${n[a]}], but got array with shape [${c.shape}].`)}}return o}function OV(e,t,n){const s=Gr(e.map(o=>o.shape[0]));s.sort();const i=Gr(t.map(o=>o.shape[0]));if(i.sort(),s.length>1)throw new q(`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 q(`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&&!ae(s,i))throw new q(`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 EV(e,t,n){const s=[or,pm,Xh];for(let i=0;i<e.length;++i){const o=e[i],a=t[i],c=n[i];if(a==null)continue;if(a===Xh&&o.shape[o.shape.length-1]===1)throw new q(`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 f=h[m],b=d[m];if(b!=null&&f!==b)throw new q(`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 rN(e,t,n,s=!0,i=""){let o;if(Array.isArray(e)){if(e.length!==t.length)throw new q(`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 q(`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 q(`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 q(`Error when checking ${i}: expected ${t[a]} to have shape ${JSON.stringify(n[a])} but got array with shape ${JSON.stringify(c.shape)}.`)}}}function DV(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 kV="layers-model";class ar extends Ei{constructor(e){super(e);this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new q("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).");uV(this,e,t,n)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=hV(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof nr))throw new q("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 q(`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(hL(e.loss[o]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new q(`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=>hL(a))}else{const o=hL(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=[],jo("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=DV(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])};jo("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,f,b;for(const w of h){if(typeof w=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(w)!==-1){const x=this.internalOutputShapes[o];x[x.length-1]===1||this.lossFunctions[o]===pm?["accuracy","acc"].indexOf(w)!==-1?f=uL:["crossentropy","ce"].indexOf(w)!==-1&&(f=zv):this.lossFunctions[o]===dm?["accuracy","acc"].indexOf(w)!==-1?f=Vv:["crossentropy","ce"].indexOf(w)!==-1&&(f=Gv):["accuracy","acc"].indexOf(w)!==-1?f=dL:["crossentropy","ce"].indexOf(w)!==-1&&(f=pL);let v;["accuracy","acc"].indexOf(w)!==-1?v="acc":["crossentropy","ce"].indexOf(w)!==-1&&(v="ce"),b=f,m=d+v}else{const x=lV(w);b=x,m=d+ym(w)}let L;jo(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;yL(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 ns(h)}finally{Jo(o[0],e),Jo(o[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),vV(this,e,t)}checkNumSamples(e,t,n,s="steps"){let i;if(n!=null){if(i=null,t!=null)throw new q(`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 q(`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 q("`outputs` is an empty Array, which is not allowed.");const n=Array.isArray(t),s=n?t:[t],i=this.retrieveSymbolicTensors(s),o=new Xo;if(e instanceof ee&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new q(`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 q(`No value is provided for the model's input ${c.name}`);o.add(c,h)}const a=Zh(i,o);return n?a:a[0]}retrieveSymbolicTensors(e){const t=Ho(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 q(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(s)}`)}return t}predictLoop(e,t=32,n=!1){return Q(()=>{const s=this.checkNumSamples(e);if(n)throw new Pe("Verbose predictLoop() is not implemented yet.");const i=wL(s,t),o=this.outputs.map(a=>[]);for(let a=0;a<i.length;++a){const c=Q(()=>{const h=i[a][0],d=i[a][1],m=Qh(e,h,d),f=[];if(Array.isArray(m))for(let w=0;w<m.length;++w)f.push({key:this.inputs[w],value:m[w]});else f.push({key:this.inputs[0],value:m});const b=new Xo(f);return Zh(this.outputs,b)});c.forEach((h,d)=>o[d].push(h))}return ns(o.map(a=>Ht(a,0)))})}predict(e,t={}){const n=nN(e);rN(n,this.inputNames,this.feedInputShapes,!1);try{const s=t.batchSize==null?32:t.batchSize;return yL(s),this.predictLoop(n,s)}finally{Jo(n,e)}}predictOnBatch(e){rN(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 ii("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===dm?i.push(a.slice(0,a.length-1).concat([1])):i.push(a)}if(e=iN(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=iN(t,this.feedOutputNames,i,!1,"target"),OV(e,t,null),EV(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&s!=null&&s>0&&e[0].shape[0]%s!==0)throw new q(`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=Jv(s,this.outputNames);h=[];for(let m=0;m<d.length;++m)h.push(await Zv(c[m],null,d[m]))}return[a,c,h]}testLoop(e,t,n,s=0,i){return Q(()=>{const o=this.checkNumSamples(t,n,i,"steps"),a=[];if(s>0)throw new Pe("Verbose mode is not implemented yet.");if(i!=null)throw new Pe("steps mode in testLoop() is not implemented yet");{const c=wL(o,n),h=hs(ri(0,o));for(let d=0;d<c.length;++d){const m=c[d][0],f=c[d][1],b=Ko(h,m,f-m),w=bL(t,b),L=e(w);if(d===0)for(let x=0;x<L.length;++x)a.push(Ce(0));for(let x=0;x<L.length;++x){const v=L[x];a[x]=be(a[x],X(f-m,v))}}for(let d=0;d<a.length;++d)a[d]=We(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(pv(e,s)>1){const o=pv(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 f=new Xo(m),b=Zh(this.outputs,f,{training:!0});let w;for(let L=0;L<this.lossFunctions.length;++L){const x=this.lossFunctions[L];let v=x(s[L],b[L]);i[L]!=null&&(v=LV(v,i[L]));const N=jt(v);t.push(N),L===0?w=v:w=be(w,v)}for(let L=0;L<this.metricsTensors.length;++L){let x;if(this.outputs.length>1&&L<this.outputs.length)x=t[L];else{const v=this.metricsTensors[L][0],N=this.metricsTensors[L][1];x=jt(v(s[N],b[N]))}bn(x),o.push(x)}return w=jt(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=>Q(()=>{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 Xo(o),c=Zh(this.outputs,a);for(let h=0;h<this.lossFunctions.length;++h){const d=this.lossFunctions[h],m=jt(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],f=jt(d(i[m],c[m]));t.push(f)}return t})}async fit(e,t,n={}){return CV(this,e,t,n)}async fitDataset(e,t){return xV(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),ns(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=ap().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-ap().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=rr(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=>rr(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]=rr(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[rr(ym(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>rr(ym(e)));{const e={};for(const t in this.metrics)e[t]=rr(ym(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=Jh(e.optimizer_config),n=ci(t);let s;if(typeof e.loss=="string")s=qo(e.loss);else if(Array.isArray(e.loss))s=e.loss.map(o=>qo(o));else if(e.loss!=null){s={};for(const o in e.loss)s[o]=qo(e.loss[o])}let i;if(Array.isArray(e.metrics))i=e.metrics.map(o=>qo(o));else if(e.metrics!=null){i={};for(const o in e.metrics)i[o]=qo(e.metrics[o])}this.compile({loss:s,metrics:i,optimizer:n})}async save(e,t){if(typeof e=="string"){const h=gb(e);if(h.length===0)throw new q(`Cannot find any save handlers for URL '${e}'`);if(h.length>1)throw new q(`Found more than one (${h.length}) save handlers for URL '${e}'`);e=h[0]}if(e.save==null)throw new q("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const n=await mb(this.getNamedWeights(t)),s=!1,i=null,o=this.toJSON(i,s),a={modelTopology:o,format:kV,generatedBy:`TensorFlow.js tfjs-layers v${wm}`,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 mb(await this.optimizer.getWeights(),h);n.specs.push(...m),n.data=Zd([n.data,d])}if(this.userDefinedMetadata!=null){const h=!0;Hv(this.userDefinedMetadata,this.name,h),a.userDefinedMetadata=this.userDefinedMetadata}return a.weightData=n.data,a.weightSpecs=n.specs,e.save(a)}setUserDefinedMetadata(e){Hv(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}ar.className="Model",fe(ar);class oN extends ar{}oN.className="Functional",fe(oN);async function FV(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let n=e.modelTopology;n.model_config!=null&&(n=n.model_config);const s=Jh(n),i=ci(s,t);if(e.weightsManifest!=null){const o=await kT(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 _V(e,t){if(t==null&&(t={}),typeof e=="string"){const n=yb(e,t);if(n.length===0)n.push(tp(e,t));else if(n.length>1)throw new q(`Found more than one (${n.length}) load handlers for URL '${e}'`);e=n[0]}return WV(e,void 0,t)}async function WV(e,t,n){if(n==null&&(n={}),e.load==null)throw new q("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=ci(Jh(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 q("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");const{modelWeights:d,optimizerWeights:m}=$V(s.weightData,s.weightSpecs);c.loadWeights(d,o),c.optimizer!=null&&m.length>0&&await c.optimizer.setWeights(m),He(d),He(m.map(f=>f.tensor))}return c}function $V(e,t){const n=Jd(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 uc extends ar{constructor(e){super({inputs:[],outputs:[]});if(e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:am("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 q(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const t=e instanceof uc||e instanceof ar;let n;if(t){if(n=e,n.outputs.length!==1)throw new q("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 q("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 q("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const s=Dv({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 q(`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 q("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=Ev(this.outputs[0])}this.inboundNodes=[],new hm({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Ho(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(Nt(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 ar({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 ii("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 ii("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 ii("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 ii("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 q("Legacy serialization format not supported yet.");i=t}else A(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 uc))throw new Pe(`Sequential.fromConfig called on non-Sequential input: ${a}`);for(const c of i){const h=void 0,d=ci(c,h,s);s&&d.setFastWeightInitDuringBuild(!0),a.add(d)}return a}set stopTraining(e){if(this.model==null)throw new q("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 q("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}}}uc.className="Sequential",fe(uc);function UV(e){return new ar(e)}function BV(e){return new uc(e)}function MV(e,t){return t==null&&(t={}),_V(e,t)}function aN(e){return Dv(e)}function PV(e,t){zs.registerCallbackConstructor(e,t)}class ds extends Fo{getConfig(){return{}}}class cN extends ds{apply(e,t=1){return f3(e,t)}}cN.className="elu",fe(cN);class lN extends ds{apply(e){return Cp(e)}}lN.className="selu",fe(lN);class hN extends ds{apply(e){return Ci(e)}}hN.className="relu",fe(hN);class uN extends ds{apply(e){return Q(()=>Bo(6,Ci(e)))}}uN.className="relu6",fe(uN);class dN extends ds{apply(e){return e}}dN.className="linear",fe(dN);class pN extends ds{apply(e){return Ai(e)}}pN.className="sigmoid",fe(pN);class mN extends ds{apply(e){return y3(e)}}mN.className="hardSigmoid",fe(mN);class fN extends ds{apply(e){return ja(e)}}fN.className="softplus",fe(fN);class gN extends ds{apply(e){return g3(e)}}gN.className="softsign",fe(gN);class yN extends ds{apply(e){return Va(e)}}yN.className="tanh",fe(yN);class SL extends ds{apply(e,t=-1){return Vo(e,t)}}SL.className="softmax",fe(SL);class bN extends ds{apply(e,t=-1){return Ip(e,t)}}bN.className="logSoftmax",fe(bN);class wN extends ds{apply(e,t=1){return Q(()=>Ai(e.mul(t)).mul(e))}}wN.className="swish",fe(wN);function Kr(e){return e.getClassName()}function IL(e,t={}){return Vh(e,$s.getMap().classNameMap,t,"activation")}function Xr(e){if(e==null){const t={};return t.className="linear",t.config={},IL(t)}if(typeof e=="string"){const t={};return t.className=e,t.config={},IL(t)}else return e instanceof ds?e:IL(e)}function xL(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 LN extends Fo{}class eu extends LN{constructor(e){super();xL(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 Q(()=>{let t=dt([1]);return this.hasL1&&(t=be(t,$e(X(this.l1,dn(e))))),this.hasL2&&(t=be(t,$e(X(this.l2,jh(e))))),t.asScalar()})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}}eu.className="L1L2",fe(eu);function zV(e){return xL(e),new eu({l1:e!=null?e.l1:null,l2:0})}function VV(e){return xL(e),new eu({l2:e!=null?e.l2:null,l1:0})}const SN={l1l2:"L1L2"};function Ct(e){return Mw(e)}function IN(e,t={}){return Vh(e,$s.getMap().classNameMap,t,"regularizer")}function zt(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 LN?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=Je(e);let n=Ci(e);return this.maxValue!=null&&(n=Zn(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",fe(TL);class AL 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=Je(e);return wp(n,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}AL.className="LeakyReLU",fe(AL);class vL extends lt{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=Pt(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=zt(e.alphaRegularizer),this.alphaConstraint=gn(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 q(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=Nt(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 Ln({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=Je(e),Nh(e,this.alpha.read())}getConfig(){const e={alphaInitializer:Xt(this.alphaInitializer),alphaRegularizer:Ct(this.alphaRegularizer),alphaConstraint:fn(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}}vL.className="PReLU",fe(vL);class NL 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 Pe(`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=Je(e);return Ga(n)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}NL.className="ELU",fe(NL);class CL 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=Je(e);return n.mul(Hh(n.greater(this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){const e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}}CL.className="ThresholdedReLU",fe(CL);class RL extends lt{constructor(e){super(e==null?{}:e);this.DEFAULT_AXIS=1,e==null&&(e={}),this.softmax=new SL().apply,this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis}call(e,t){const n=Je(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}}RL.className="Softmax",fe(RL);function dc(e,t,n){if(typeof e=="number")return Ho(e,t);if(e.length!==t)throw new q(`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(!l3(i))throw new q(`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 li(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 Lm(e,t,n,s){if(e==null)return null;if(s==="valid")e=e*t+Hr([n-t,0]);else if(s==="same")e=e*t;else throw new q(`Unsupport padding mode: ${s}.`);return e}function OL(e,t){return Q(()=>(Kt(t),t==="channelsFirst"?Ye(e,[0,2,3,1]):e))}function xN(e,t){return Q(()=>(Kt(t),t==="channelsFirst"?Ye(e,[0,2,3,4,1]):e))}function TN(e,t,n,s=1,i="valid",o,a=1){return Q(()=>{if(o==null&&(o=si()),Kt(o),e.shape.length!==3)throw new q(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new q(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(n!=null&&n.shape.length!==1)throw new q(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(o==="channelsFirst"&&(e=Ye(e,[0,2,1])),i==="causal")throw new Pe("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let c=mp(e,t,s,i==="same"?"same":"valid","NWC",a);return n!=null&&(c=Oi(c,n)),c})}function wte(e,t,n=1,s="valid",i,o=1){return Q(()=>(Kt(i),TN(e,t,null,n,s,i,o)))}function Lte(e,t,n=[1,1],s="valid",i,o){return Q(()=>(Kt(i),EL(e,t,null,n,s,i,o)))}function EL(e,t,n,s=[1,1],i="valid",o,a,c=null){return Q(()=>{if(o==null&&(o=si()),Kt(o),e.rank!==3&&e.rank!==4)throw new q(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new q(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let h=OL(e,o);if(i==="causal")throw new Pe("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return h=xw({x:h,filter:t,strides:s,pad:i==="same"?"same":"valid",dilations:a,dataFormat:"NHWC",bias:n,activation:c}),o==="channelsFirst"&&(h=Ye(h,[0,3,1,2])),h})}function Ste(e,t,n=[1,1,1],s="valid",i,o){return Q(()=>(Kt(i),AN(e,t,null,n,s,i,o)))}function AN(e,t,n,s=[1,1,1],i="valid",o,a){return Q(()=>{if(o==null&&(o=si()),Kt(o),e.rank!==4&&e.rank!==5)throw new q(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new q(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let c=xN(e,o);if(i==="causal")throw new Pe("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return c=jb(c,t,s,i==="same"?"same":"valid","NDHWC",a),n!=null&&(c=Oi(c,n)),o==="channelsFirst"&&(c=Ye(c,[0,4,1,2,3])),c})}class DL extends lt{constructor(e,t){super(t);if(this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",DL.verifyArgs(t),this.rank=e,wn(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new Pe(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=dc(t.kernelSize,e,"kernelSize"),this.strides=dc(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,vs(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,Kt(this.dataFormat),this.activation=Xr(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=Pt(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=gn(t.biasConstraint),this.biasRegularizer=zt(t.biasRegularizer),this.activityRegularizer=zt(t.activityRegularizer),this.dilationRate=dc(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new q(`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 q(`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 q(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(As("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!zw(e.kernelSize,"number",1,3))throw new q(`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:Kr(this.activation),useBias:this.useBias,biasInitializer:Xt(this.biasInitializer),biasRegularizer:Ct(this.biasRegularizer),activityRegularizer:Ct(this.activityRegularizer),biasConstraint:fn(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class tu extends DL{constructor(e,t){super(e,t);this.kernel=null,tu.verifyArgs(t),this.filters=t.filters,wn(this.filters,"filters"),this.kernelInitializer=Pt(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=gn(t.kernelConstraint),this.kernelRegularizer=zt(t.kernelRegularizer)}build(e){e=Nt(e);const t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new q(`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 Q(()=>{e=Je(e);let n;const s=this.bias==null?null:this.bias.read(),i=fv(this.activation.getClassName());if(i!=null&&this.rank===2)n=EL(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate,i);else{if(this.rank===1)n=TN(e,this.kernel.read(),s,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)n=EL(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 Pe("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(n=this.activation.apply(n))}return n})}computeOutputShape(e){e=Nt(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=li(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:Xt(this.kernelInitializer),kernelRegularizer:Ct(this.kernelRegularizer),kernelConstraint:fn(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 q(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}}class nu extends tu{constructor(e){super(2,e);nu.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!zw(e.kernelSize,"number",1,2))throw new q(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}nu.className="Conv2D",fe(nu);class Sm extends tu{constructor(e){super(3,e);Sm.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 q(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}Sm.className="Conv3D",fe(Sm);class kL extends nu{constructor(e){super(e);if(this.inputSpec=[new Ln({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new q(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=Nt(e),e.length!==4)throw new q("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 q("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 Ln({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return Q(()=>{let n=Je(e);if(n.shape.length!==4)throw new q(`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],f=this.strides[0],b=this.strides[1],w=Lm(c,f,d,this.padding),L=Lm(h,b,m,this.padding),x=[i,w,L,this.filters];this.dataFormat!=="channelsLast"&&(n=Ye(n,[0,2,3,1]));let v=fp(n,this.kernel.read(),x,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(v=Ye(v,[0,3,1,2])),this.bias!=null&&(v=Oi(v,this.bias.read(),this.dataFormat)),this.activation!=null&&(v=this.activation.apply(v)),v})}computeOutputShape(e){e=Nt(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]=Lm(t[s],c,o,this.padding),t[i]=Lm(t[i],h,a,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}kL.className="Conv2DTranspose",fe(kL);class vN extends tu{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 q("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new q("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 q(`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=Pt(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=zt(t.depthwiseRegularizer),this.depthwiseConstraint=gn(t.depthwiseConstraint),this.pointwiseInitializer=Pt(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=zt(t.pointwiseRegularizer),this.pointwiseConstraint=gn(t.pointwiseConstraint)}build(e){if(e=Nt(e),e.length<this.rank+2)throw new q(`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 q(`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 Ln({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return Q(()=>{e=Je(e);let n;if(this.rank===1)throw new Pe("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=Ye(e,[0,2,3,1])),n=dw(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(n=Oi(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),this.dataFormat==="channelsFirst"&&(n=Ye(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=Xt(this.depthwiseInitializer),e.pointwiseInitializer=Xt(this.pointwiseInitializer),e.depthwiseRegularizer=Ct(this.depthwiseRegularizer),e.pointwiseRegularizer=Ct(this.pointwiseRegularizer),e.depthwiseConstraint=fn(this.depthwiseConstraint),e.pointwiseConstraint=fn(this.pointwiseConstraint),e}}vN.className="SeparableConv";class FL extends vN{constructor(e){super(2,e)}}FL.className="SeparableConv2D",fe(FL);class Im extends tu{constructor(e){super(1,e);Im.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"&&!zw(e.kernelSize,"number",1,1))throw new q(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}Im.className="Conv1D",fe(Im);class _L 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 Q(()=>{if(e=Je(e),this.dataFormat==="channelsLast"){const n=Jp(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Jp(n,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{const n=Jp(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Jp(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}}_L.className="Cropping2D",fe(_L);class WL 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 Q(()=>{let n=Je(e);const s=n.shape;if(this.dataFormat==="channelsFirst"){n=Ye(n,[0,2,3,1]);const i=this.size[0]*s[2],o=this.size[1]*s[3],a=n.resizeNearestNeighbor([i,o]);return Ye(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}}WL.className="UpSampling2D",fe(WL);function GV(e,t,n=[1,1],s="valid",i,o){return Q(()=>{i==null&&(i=si()),Kt(i);let a=OL(e,i);if(e.rank!==4)throw new q(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new q(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return a=$o(a,t,n,s==="same"?"same":"valid","NHWC",o),i==="channelsFirst"&&(a=Ye(a,[0,3,1,2])),a})}class $L extends DL{constructor(e){super(2,e);this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=Pt(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=gn(e.depthwiseConstraint),this.depthwiseRegularizer=zt(e.depthwiseRegularizer)}build(e){if(e=Nt(e),e.length<4)throw new q(`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 q(`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 Q(()=>{e=Je(e);let n=GV(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(n=Oi(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),n})}computeOutputShape(e){e=Nt(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=li(t,this.kernelSize[0],this.padding,this.strides[0]),o=li(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=Xt(this.depthwiseInitializer),e.depthwiseRegularizer=Ct(this.depthwiseRegularizer),e.depthwiseConstraint=fn(this.depthwiseRegularizer),e}}$L.className="DepthwiseConv2D",fe($L);function NN(e,t,n,s){if(Array.isArray(e)){if(t!=null||n!=null)throw new q("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 CN(e,t,n,s=!1,i,o,a=!1,c=!1){return Q(()=>{const h=t.shape.length;if(h<3)throw new q(`Input should be at least 3D, but is ${h}D.`);const d=[1,0].concat(ri(2,h));if(t=Ye(t,d),o!=null)throw new Pe("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=Ye(i,d)),s&&(t=Ts(t,0),i!=null&&(i=Ts(i,0)));const m=[];let f,b=n;const w=t.shape[0],L=ni(t);let x;i!=null&&(x=ni(i));for(let N=0;N<w;++N){const O=L[N],E=Q(()=>e(O,b));if(i==null)f=E[0],b=E[1];else{const k=Q(()=>{const F=x[N],U=_n(F).sub(F),$=E[0].mul(F).add(b[0].mul(U)),Y=b.map((j,Z)=>E[1][Z].mul(F).add(j.mul(U)));return{output:$,newStates:Y}});f=k.output,b=k.newStates}c&&m.push(f)}let v;if(c){const N=1;v=ts(m,N)}return[f,v,b]})}class Di extends lt{constructor(e){super(e);let t;if(e.cell==null)throw new q("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new Am({cells:e.cell}):t=e.cell,t.stateSize==null)throw new q("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 Ln({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 ri(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){rL(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 Q(()=>{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 Pe("Constants support is not implemented in RNN yet.");rL(e)&&(e=e[0]),e=e;const n=this.stateful?e[0]:null,s=e.slice(2);this.inputSpec[0]=new Ln({shape:[n,null,...s]});const i=[e[0]].concat(e.slice(2));if(t!=null)throw new Pe("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(!ae(this.stateSpec.map(a=>a.shape[a.shape.length-1]),o))throw new q(`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 Ln({shape:[null,a]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){Q(()=>{if(!this.stateful)throw new ir("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape[0];if(n==null)throw new q("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=>dt([n,s])):this.states_=[dt([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=>dt([n,s])):this.states_[0]=dt([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new q(`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(!ae(i.shape,a))throw new q(`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=>bn(s.clone()))})}apply(e,t){let n=t==null?null:t.initialState,s=t==null?null:t.constants;t==null&&(t={});const i=NN(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 Ln({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 ai;if(c){const h=[e].concat(o),d=this.inputSpec.concat(a),m=this.inputSpec;this.inputSpec=d;const f=super.apply(h,t);return this.inputSpec=m,f}else return super.apply(e,t)}call(e,t){return Q(()=>{const n=t==null?null:t.mask,s=t==null?null:t.training;let i=t==null?null:t.initialState;e=Je(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 q(`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 x=this.cell.call([w].concat(L),a);return[x[0],x.slice(1)]},h=CN(c,e,i,this.goBackwards,n,null,this.unroll,this.returnSequences),d=h[0],m=h[1],f=h[2];this.stateful&&this.resetStates(f,s);const b=this.returnSequences?m:d;return this.returnState?[b].concat(f):b})}getInitialState(e){return Q(()=>{let t=dt(e.shape);return t=$e(t,[1,2]),t=qh(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(n=>n>1?Xw(t,[1,n]):t):this.cell.stateSize>1?[Xw(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()===Di.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign({},n,e,t)}static fromConfig(e,t,n={}){const s=t.cell,i=ci(s,n);return new e(Object.assign(t,{cell:i}))}}Di.className="RNN",fe(Di);class pc extends lt{}class xm extends pc{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,wn(this.units,"units"),this.activation=Xr(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Pt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Pt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Pt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=zt(e.kernelRegularizer),this.recurrentRegularizer=zt(e.recurrentRegularizer),this.biasRegularizer=zt(e.biasRegularizer),this.kernelConstraint=gn(e.kernelConstraint),this.recurrentConstraint=gn(e.recurrentConstraint),this.biasConstraint=gn(e.biasConstraint),this.dropout=ac([1,Hr([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=ac([1,Hr([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Nt(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 Q(()=>{if(e=e,e.length!==2)throw new q(`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=Jr({ones:()=>_n(e),rate:this.dropout,training:s})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Jr({ones:()=>_n(n),rate:this.recurrentDropout,training:s}));let i;const o=this.dropoutMask,a=this.recurrentDropoutMask;o!=null?i=Ri(X(e,o),this.kernel.read()):i=Ri(e,this.kernel.read()),this.bias!=null&&(i=Oi(i,this.bias.read())),a!=null&&(n=X(n,a));let c=be(i,Ri(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:Kr(this.activation),useBias:this.useBias,kernelInitializer:Xt(this.kernelInitializer),recurrentInitializer:Xt(this.recurrentInitializer),biasInitializer:Xt(this.biasInitializer),kernelRegularizer:Ct(this.kernelRegularizer),recurrentRegularizer:Ct(this.recurrentRegularizer),biasRegularizer:Ct(this.biasRegularizer),activityRegularizer:Ct(this.activityRegularizer),kernelConstraint:fn(this.kernelConstraint),recurrentConstraint:fn(this.recurrentConstraint),biasConstraint:fn(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign({},e,t)}}xm.className="SimpleRNNCell",fe(xm);class UL extends Di{constructor(e){e.cell=new xm(e),super(e)}call(e,t){return Q(()=>{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)}}UL.className="SimpleRNN",fe(UL);class Tm extends pc{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 q("GRUCell does not support reset_after parameter set to true.");this.units=e.units,wn(this.units,"units"),this.activation=Xr(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Xr(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Pt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Pt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Pt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=zt(e.kernelRegularizer),this.recurrentRegularizer=zt(e.recurrentRegularizer),this.biasRegularizer=zt(e.biasRegularizer),this.kernelConstraint=gn(e.kernelConstraint),this.recurrentConstraint=gn(e.recurrentConstraint),this.biasConstraint=gn(e.biasConstraint),this.dropout=ac([1,Hr([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=ac([1,Hr([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Nt(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 Q(()=>{if(e=e,e.length!==2)throw new q(`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=Jr({ones:()=>_n(e),rate:this.dropout,training:n,count:3})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Jr({ones:()=>_n(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=Ri(e,this.kernel.read());this.useBias&&(d=Oi(d,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(s=X(s,o[0]));const m=this.recurrentKernel.read(),[f,b]=us(m,[2*this.units,this.units],m.rank-1),w=Ri(s,f),[L,x,v]=us(d,3,d.rank-1),[N,O]=us(w,2,w.rank-1);a=this.recurrentActivation.apply(be(L,N)),c=this.recurrentActivation.apply(be(x,O));const E=Ri(X(c,s),b);h=this.activation.apply(be(v,E));const k=be(X(a,s),X(be(1,qt(a)),h));return[k,k]})}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Kr(this.activation),recurrentActivation:Kr(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Xt(this.kernelInitializer),recurrentInitializer:Xt(this.recurrentInitializer),biasInitializer:Xt(this.biasInitializer),kernelRegularizer:Ct(this.kernelRegularizer),recurrentRegularizer:Ct(this.recurrentRegularizer),biasRegularizer:Ct(this.biasRegularizer),activityRegularizer:Ct(this.activityRegularizer),kernelConstraint:fn(this.kernelConstraint),recurrentConstraint:fn(this.recurrentConstraint),biasConstraint:fn(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign({},e,t)}}Tm.className="GRUCell",fe(Tm);class BL extends Di{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 Tm(e),super(e)}call(e,t){return Q(()=>{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)}}BL.className="GRU",fe(BL);class su extends pc{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,wn(this.units,"units"),this.activation=Xr(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Xr(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Pt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Pt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Pt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=zt(e.kernelRegularizer),this.recurrentRegularizer=zt(e.recurrentRegularizer),this.biasRegularizer=zt(e.biasRegularizer),this.kernelConstraint=gn(e.kernelConstraint),this.recurrentConstraint=gn(e.recurrentConstraint),this.biasConstraint=gn(e.biasConstraint),this.dropout=ac([1,Hr([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=ac([1,Hr([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=Nt(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 Ps{apply(c,h){const d=i.apply([o]),m=new Qp().apply([o]),f=i.apply([o*2]);return Tv(Tv(d,m),f)}},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 Q(()=>{const n=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new q(`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=Jr({ones:()=>_n(e),rate:this.dropout,training:n,count:4})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Jr({ones:()=>_n(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 f=Ri(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(s=X(s,a[0])),f=be(f,Ri(s,this.recurrentKernel.read())),this.useBias&&(f=Oi(f,this.bias.read()));const[b,w,L,x]=us(f,4,f.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(x);const v=X(m,this.activation.apply(d));return[v,v,d]})}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Kr(this.activation),recurrentActivation:Kr(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Xt(this.kernelInitializer),recurrentInitializer:Xt(this.recurrentInitializer),biasInitializer:Xt(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Ct(this.kernelRegularizer),recurrentRegularizer:Ct(this.recurrentRegularizer),biasRegularizer:Ct(this.biasRegularizer),activityRegularizer:Ct(this.activityRegularizer),kernelConstraint:fn(this.kernelConstraint),recurrentConstraint:fn(this.recurrentConstraint),biasConstraint:fn(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign({},e,t)}}su.className="LSTMCell",fe(su);class ML extends Di{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 su(e),super(e)}call(e,t){return Q(()=>{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)}}ML.className="LSTM",fe(ML);class Am extends pc{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 Q(()=>{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){rL(e)&&(e=e[0]),e=e;let t;this.cells.forEach((n,s)=>{jo(`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(ci(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 oL(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]])}aL(t)}}Am.className="StackedRNNCells",fe(Am);function Jr(e){const{ones:t,rate:n,training:s=!1,count:i=1}=e,o=()=>vv(t(),n),a=()=>Kh(o,t,s);if(!i||i<=1)return bn(a().clone());const c=Array(i).fill(void 0).map(a);return c.map(h=>bn(h.clone()))}var YV=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 Ite extends pc{}class RN extends Di{constructor(e){if(e.unroll)throw new Pe("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Pe("It is not possible at the moment to stack convolutional cells.");super(e);this.inputSpec=[new Ln({ndim:5})]}call(e,t){return Q(()=>{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 q("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 Q(()=>{const{stateSize:t}=this.cell,n=e.shape,s=this.computeSingleOutputShape(n),i=[s[0],...s.slice(2)],o=dt(i);return Array.isArray(t)?Array(t.length).fill(o):[o]})}resetStates(e,t=!1){Q(()=>{if(!this.stateful)throw new ir("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 q("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(()=>dt(i)):this.states_=[dt(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(()=>dt(i)):this.states_[0]=dt(i);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new q(`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(!ae(c.shape,h))throw new q(`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=>bn(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=li(h,s[0],i,o[0],a[0]),f=li(d,s[1],i,o[1],a[1]),b=[...e.slice(0,2),...c?[n,m,f]:[m,f,n]];return b}}RN.className="ConvRNN2D";class vm extends su{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,wn(this.filters,"filters"),this.kernelSize=dc(n,2,"kernelSize"),this.kernelSize.forEach(c=>wn(c,"kernelSize")),this.strides=dc(s||1,2,"strides"),this.strides.forEach(c=>wn(c,"strides")),this.padding=i||"valid",vs(this.padding),this.dataFormat=o||"channelsLast",Kt(this.dataFormat),this.dilationRate=dc(a||1,2,"dilationRate"),this.dilationRate.forEach(c=>wn(c,"dilationRate"))}build(e){var t;e=Nt(e);const n=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[n]==null)throw new q(`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 Ps{apply(f,b){const w=h.apply([d]),L=ei([d]),x=h.apply([d*2]);return Kw([w,L,x])}},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 Q(()=>{if(e.length!==3)throw new q(`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=Jr({ones:()=>_n(s),rate:this.dropout,training:n,count:a}));const c=this.dropoutMask,h=(we,Se,xe)=>!Se||!Se[xe]?we:X(Se[xe],we);let d=h(s,c,0),m=h(s,c,1),f=h(s,c,2),b=h(s,c,3);0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Jr({ones:()=>_n(i),rate:this.recurrentDropout,training:n,count:a}));const w=this.recurrentDropoutMask;let L=h(i,w,0),x=h(i,w,1),v=h(i,w,2),N=h(i,w,3);const O=3,[E,k,F,U]=us(this.kernel.read(),a,O),[$,Y,j,Z]=this.useBias?us(this.bias.read(),a):[null,null,null,null];d=this.inputConv(d,E,$,this.padding),m=this.inputConv(m,k,Y,this.padding),f=this.inputConv(f,F,j,this.padding),b=this.inputConv(b,U,Z,this.padding);const[ie,de,he,ue]=us(this.recurrentKernel.read(),a,O);L=this.recurrentConv(L,ie),x=this.recurrentConv(x,de),v=this.recurrentConv(v,he),N=this.recurrentConv(N,ue);const me=this.recurrentActivation.apply(be(d,L)),ce=this.recurrentActivation.apply(be(m,x)),ye=be(X(ce,o),X(me,this.activation.apply(be(f,v)))),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=YV(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=Qi(e,t,this.strides,s||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return n?Oi(i,n,this.dataFormat):i}recurrentConv(e,t){const n=1;return Qi(e,t,n,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}}vm.className="ConvLSTM2DCell",fe(vm);class PL extends RN{constructor(e){const t=new vm(e);super(Object.assign({},e,{cell:t}))}static fromConfig(e,t){return new e(t)}}PL.className="ConvLSTM2D",fe(PL);class Nm 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 Q(()=>{this.invokeCallHook(e,t);const n=Je(e);if(0<this.rate&&this.rate<1){const s=t.training==null?!1:t.training,i=this.getNoiseShape(n),o=Kh(()=>vv(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()}}Nm.className="Dropout",fe(Nm);class zL extends Nm{constructor(e){super(e);this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}zL.className="SpatialDropout1D",fe(zL);class VL 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,wn(this.units,"units"),this.activation=Xr(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=Pt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=Pt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=gn(e.kernelConstraint),this.biasConstraint=gn(e.biasConstraint),this.kernelRegularizer=zt(e.kernelRegularizer),this.biasRegularizer=zt(e.biasRegularizer),this.activityRegularizer=zt(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=Nt(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=Nt(e);const t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return Q(()=>{this.invokeCallHook(e,t);const n=Je(e),s=fv(this.activation.getClassName());let i;return s!=null?i=Ri(n,this.kernel.read(),s,this.bias?this.bias.read():null):(i=Ri(n,this.kernel.read()),this.bias!=null&&(i=Oi(i,this.bias.read())),this.activation!=null&&(i=this.activation.apply(i))),i})}getConfig(){const e={units:this.units,activation:Kr(this.activation),useBias:this.useBias,kernelInitializer:Xt(this.kernelInitializer),biasInitializer:Xt(this.biasInitializer),kernelRegularizer:Ct(this.kernelRegularizer),biasRegularizer:Ct(this.biasRegularizer),activityRegularizer:Ct(this.activityRegularizer),kernelConstraint:fn(this.kernelConstraint),biasConstraint:fn(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}VL.className="Dense",fe(VL);class GL extends lt{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=Nt(e);for(const t of e.slice(1))if(t==null)throw new q(`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],Yr(e,1)]}call(e,t){return Q(()=>{this.invokeCallHook(e,t);let n=Je(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 m3(n)})}getConfig(){const e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);const t=super.getConfig();return Object.assign(e,t),e}}GL.className="Flatten",fe(GL);class YL extends lt{constructor(e){super(e);this.supportsMasking=!0,this.activation=Xr(e.activation)}call(e,t){return Q(()=>{this.invokeCallHook(e,t);const n=Je(e);return this.activation.apply(n)})}getConfig(){const e={activation:Kr(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}YL.className="Activation",fe(YL);class HL 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 Q(()=>(e=Je(e),d3(e,this.n)))}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}HL.className="RepeatVector",fe(HL);class qL 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 q("Can only specifiy one unknown dimension.");else i*=h}const a=Yr(e);if(o!==null){if(i===0||a%i!==0)throw new q(n);s[o]=a/i}else if(a!==i)throw new q(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 Q(()=>{this.invokeCallHook(e,t);const n=Je(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}}qL.className="Reshape",fe(qL);class jL 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=ri(1,e.dims.length+1);if(!ae(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 Ln({ndim:this.dims.length+1})]}computeOutputShape(e){e=Nt(e);const t=e.slice();return this.dims.forEach((n,s)=>{t[s+1]=e[n]}),t}call(e,t){return Ye(Je(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}}jL.className="Permute",fe(jL);class KL 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=Je(e),s=-1;return mh(Mr(n,this.maskValue),s)}call(e,t){return Q(()=>{this.invokeCallHook(e,t);const n=Je(e),s=-1,i=!0,o=mh(Mr(n,this.maskValue),s,i),a=n.mul(o.asType(n.dtype));return a})}}KL.className="Masking",fe(KL);class XL 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(kt(e.inputLength))}this.inputDim=e.inputDim,wn(this.inputDim,"inputDim"),this.outputDim=e.outputDim,wn(this.outputDim,"outputDim"),this.embeddingsInitializer=Pt(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=zt(e.embeddingsRegularizer),this.activityRegularizer=zt(e.activityRegularizer),this.embeddingsConstraint=gn(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 Q(()=>this.maskZero?(e=Je(e),Mr(e,et(e))):null)}computeOutputShape(e){if(e=Nt(e),this.inputLength==null)return[...e,this.outputDim];const t=kt(this.inputLength);if(t.length!==e.length-1)throw new q(`"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 q(`"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 Q(()=>{this.invokeCallHook(e,t);let n=Je(e);n.dtype!=="int32"&&(n=Hh(n,"int32"));const s=Av(this.embeddings.read(),n.as1D());return s.reshape(Nt(this.computeOutputShape(n.shape)))})}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Xt(this.embeddingsInitializer),embeddingsRegularizer:Ct(this.embeddingsRegularizer),activityRegularizer:Ct(this.activityRegularizer),embeddingsConstraint:fn(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}}XL.className="Embedding",fe(XL);class Zo extends lt{constructor(e){super(e||{});this.supportsMasking=!0}mergeFunction(e){throw new Pe}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 q("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=[Nt(e)]),e=e,e.length<2)throw new q(`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=Gr(t),t.length>1)throw new q(`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&&Gr(s).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return Q(()=>{if(e=e,this.reshapeRequired){const n=[],s=e.map(i=>i.rank);if(s.indexOf(null)===-1){const i=Hr(s);for(let o of e){const a=o.rank;for(let c=0;c<i-a;++c)o=qh(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],f=d.slice(1).concat([m]);let b=c.reshape([m].concat(Yr(d.slice(1))));b=Ye(b,[1,0]),b=b.reshape(f),n.push(b),i=!0}else if(h>1){const d=ri(1,h).concat([0]);n.push(Ye(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=Ye(o.reshape([-1,d]),[1,0]).reshape(m)}else if(a>1){const c=[a-1].concat(ri(0,a-1));o=Ye(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=Gr(n),n.length===1?t=n.concat(t):t=[null].concat(t),t}computeMask(e,t){return Q(()=>{if(t==null)return null;if(!Array.isArray(t))throw new q("`mask` should be an Array");if(!Array.isArray(e))throw new q("`inputs` should be an Array");if(t.length!==e.length)throw new q(`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=Bs(n,t[s]);return n})}}class iu extends Zo{constructor(e){super(e)}mergeFunction(e){return Q(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=be(t,e[n]);return t})}}iu.className="Add",fe(iu);function xte(e){if(Array.isArray(e)){const t=new iu({});return t.apply(e)}else return new iu(e)}class ru extends Zo{constructor(e){super(e)}mergeFunction(e){return Q(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=X(t,e[n]);return t})}}ru.className="Multiply",fe(ru);function Tte(e){if(Array.isArray(e)){const t=new ru({});return t.apply(e)}else return new ru(e)}class ou extends Zo{constructor(e){super(e)}mergeFunction(e){return Q(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=be(t,e[n]);return X(1/e.length,t)})}}ou.className="Average",fe(ou);function Ate(e){if(Array.isArray(e)){const t=new ou({});return t.apply(e)}else return new ou(e)}class au extends Zo{constructor(e){super(e)}mergeFunction(e){return Q(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=Us(t,e[n]);return t})}}au.className="Maximum",fe(au);function vte(e){if(Array.isArray(e)){const t=new au({});return t.apply(e)}else return new au(e)}class cu extends Zo{constructor(e){super(e)}mergeFunction(e){return Q(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=Bo(t,e[n]);return t})}}cu.className="Minimum",fe(cu);function Nte(e){if(Array.isArray(e)){const t=new cu({});return t.apply(e)}else return new cu(e)}class lu extends Zo{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 q("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(ae(a,i)){o=!0;break}o||n.push(i)}if(n.length>1)throw new q("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return Q(()=>Kw(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new q("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 q("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new q("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new q(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return Q(()=>{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(_n(e[o]).asType("bool")):t[o].rank<e[o].rank?s.push(Qn(t[o],-1)):s.push(t[o]);const i=Ht(s,this.axis);return lp(i,-1,!1)})}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}lu.className="Concatenate",fe(lu);function Cte(e){if(Array.isArray(e)){const t=new lu({});return t.apply(e)}else return new lu(e)}function hu(e,t){for(;e<0;)e+=t;return e}function HV(e,t,n){if(e.shape.length>3||t.shape.length>3)throw new Pe("batchDot is not implemented for tensors of 4D or higher rank yet");if(A(e.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`),A(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 Pe("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 Q(()=>{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 JL extends Zo{constructor(e){super(e);this.axes=e.axes,this.normalize=e.normalize==null?!1:e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){A(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 Pe("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 q(`Dimension incompatibility: ${t[s[0]]} !== ${n[s[1]]}`)}mergeFunction(e){if(e.length!==2)throw new q(`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)=>hu(i,e[o].shape.length)):s=[hu(this.axes,t.shape.length),hu(this.axes,n.shape.length)],this.normalize&&(t=um(t,s[0]),n=um(n,s[1])),HV(t,n,s)}interpretAxes(e,t){let n;return Array.isArray(this.axes)?n=this.axes:n=[hu(this.axes,e.length),hu(this.axes,t.length)],n}computeOutputShape(e){A(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 Pe("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}}JL.className="Dot",fe(JL);class ZL 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 Q(()=>{this.invokeCallHook(e,t);const n=Je(e),s=()=>Zp(n.shape,0,this.stddev).add(n),i=Kh(s,()=>n,t.training||!1);return i})}}ZL.className="GaussianNoise",fe(ZL);class QL 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 Q(()=>{this.invokeCallHook(e,t);const n=Je(e);if(this.rate>0&&this.rate<1){const s=()=>{const i=Math.sqrt(this.rate/(1-this.rate));return n.mul(Zp(n.shape,1,i))};return Kh(s,()=>n,t.training||!1)}return n})}}QL.className="GaussianDropout",fe(QL);class eS extends lt{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Je(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 Q(()=>{if(this.rate<1&&this.rate>0){const n=this._getNoiseShape(e),s=()=>{const i=Je(e),o=1.6732632423543772,a=1.0507009873554805,c=-o*a;let h=er(zo(n),this.rate);h=Hh(h,"float32");const d=((1-this.rate)*(1+this.rate*c**2))**-.5,m=-d*c*this.rate,f=i.mul(h).add(h.add(-1).mul(c));return f.mul(d).add(m)};return Kh(s,()=>Je(e),t.training||!1)}return e})}}eS.className="AlphaDropout",fe(eS);function uu(e,t,n,s,i,o=.001){let a;if(e.rank===2)a=eA(e,t,n,s,i,o);else if(e.rank===3)a=tA(e,t,n,s,i,o);else if(e.rank===4)a=nA(e,t,n,s,i,o);else throw new Pe(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return a}function qV(e,t,n,s,i=.001){return Q(()=>{const o=Ap(e,s),a=o.mean,c=o.variance,h=uu(e,a,c,n,t,i);return[h,a,c]})}function jV(e,t,n,s,i=.001){return Q(()=>{const o=Ap(e,s),a=o.mean,c=o.variance,h=[];for(const L of ri(0,e.rank))s.indexOf(L)!==-1?h.push(1):h.push(e.shape[L]);const d=a.reshape(h),m=c.reshape(h),f=t==null?null:t.reshape(h),b=n==null?null:n.reshape(h),w=uu(e,d,m,b,f,i);return[w,a,c]})}function KV(e,t,n,s,i=.001){return ae(s.slice().sort(),ri(0,e.rank-1))?qV(e,t,n,s,i):jV(e,t,n,s,i)}class tS 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=Pt(e.betaInitializer||"zeros"),this.gammaInitializer=Pt(e.gammaInitializer||"ones"),this.movingMeanInitializer=Pt(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=Pt(e.movingVarianceInitializer||"ones"),this.betaConstraint=gn(e.betaConstraint),this.gammaConstraint=gn(e.gammaConstraint),this.betaRegularizer=zt(e.betaRegularizer),this.gammaRegularizer=zt(e.gammaRegularizer)}build(e){e=Nt(e);const t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(n==null)throw new q(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Ln({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 Q(()=>{const n=t.training==null?!1:t.training,s=Je(e),i=s.shape,o=i.length,a=ri(0,o),c=this.axis>=0?this.axis:this.axis+o;a.splice(c,1);const h=Ho(1,o);h[c]=i[c];const d=a.slice();d.sort();const m=!ae(d,ri(0,o).slice(0,o-1)),f=()=>{if(m){const N=this.movingMean.read().reshape(h),O=this.movingVariance.read().reshape(h),E=this.center?this.beta.read().reshape(h):null,k=this.scale?this.gamma.read().reshape(h):null;return uu(s,N,O,E,k,this.epsilon)}else return uu(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 f();const[b,w,L]=KV(s,this.gamma.read(),this.beta.read(),a,this.epsilon),x=(N,O,E)=>{Q(()=>{const k=1-E,F=N.read(),U=F.sub(O).mul(k);N.write(F.sub(U))})},v=()=>{x(this.movingMean,w,this.momentum),x(this.movingVariance,L,this.momentum)};return v(),b})}getConfig(){const e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Xt(this.betaInitializer),gammaInitializer:Xt(this.gammaInitializer),movingMeanInitializer:Xt(this.movingMeanInitializer),movingVarianceInitializer:Xt(this.movingVarianceInitializer),betaRegularizer:Ct(this.betaRegularizer),gammaRegularizer:Ct(this.gammaRegularizer),betaConstraint:fn(this.betaConstraint),gammaConstraint:fn(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}}tS.className="BatchNormalization",fe(tS);class nS 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=Pt(e.betaInitializer||"zeros"),this.gammaInitializer=Pt(e.gammaInitializer||"ones"),this.betaRegularizer=zt(e.betaRegularizer),this.gammaRegularizer=zt(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=Nt(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!==Gr(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=Je(e),s=n.shape,i=s.length;return Q(()=>{const o=!0;let{mean:a,variance:c}=Ap(n,this.axis,o);const h=Ho(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()),f=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),f=f.tile(w),uu(n,a,c,f,m,this.epsilon)})}getConfig(){const e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Xt(this.betaInitializer),gammaInitializer:Xt(this.gammaInitializer),betaRegularizer:Ct(this.betaRegularizer),gammaRegularizer:Ct(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}}nS.className="LayerNormalization",fe(nS);function Rte(e,t){return Q(()=>{if(e.rank!==3)throw new q(`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 q(`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 Ni(e,n)})}function XV(e,t,n){return Q(()=>{if(e.rank!==4)throw new q(`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 q("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(n==null&&(n=si()),n!=="channelsLast"&&n!=="channelsFirst")throw new q(`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]],Ni(e,s)})}class sS extends lt{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?si():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 q(`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 q(`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 q(`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 Ln({ndim:4})]}computeOutputShape(e){e=Nt(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 Q(()=>XV(Je(e),this.padding,this.dataFormat))}getConfig(){const e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}sS.className="ZeroPadding2D",fe(sS);function Cm(e,t,n,s,i,o){return Q(()=>{Kt(i),bv(o),vs(s),n==null&&(n=[1,1]),s==null&&(s="valid"),i==null&&(i=si()),o==null&&(o="max"),e=OL(e,i);let a;const c=s==="same"?"same":"valid";return o==="max"?a=Ah(e,t,n,c):a=yh(e,t,n,c),i==="channelsFirst"&&(a=Ye(a,[0,3,1,2])),a})}function ON(e,t,n,s,i,o){return Q(()=>{Kt(i),bv(o),vs(s),n==null&&(n=[1,1,1]),s==null&&(s="valid"),i==null&&(i=si()),o==null&&(o="max"),e=xN(e,i);let a;const c=s==="same"?"same":"valid";return o==="max"?a=iw(e,t,n,c):a=Yb(e,t,n,c),i==="channelsFirst"&&(a=Ye(a,[0,4,1,2,3])),a})}class EN 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 q(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(wn(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 q(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);wn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,vs(this.padding),this.inputSpec=[new Ln({ndim:3})]}computeOutputShape(e){e=Nt(e);const t=li(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return Q(()=>{this.invokeCallHook(e,t),e=qh(Je(e),2);const n=this.poolingFunction(Je(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Pr(n,[2])})}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class iS extends EN{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return Kt(i),vs(s),Cm(e,t,n,s,i,"max")}}iS.className="MaxPooling1D",fe(iS);class rS extends EN{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return Kt(i),vs(s),Cm(e,t,n,s,i,"avg")}}rS.className="AveragePooling1D",fe(rS);class DN 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 q(`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];wn(this.poolSize,"poolSize"),wn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Kt(this.dataFormat),vs(this.padding),this.inputSpec=[new Ln({ndim:4})]}computeOutputShape(e){e=Nt(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=li(t,this.poolSize[0],this.padding,this.strides[0]),n=li(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 Q(()=>(this.invokeCallHook(e,t),this.poolingFunction(Je(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 oS extends DN{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return Kt(i),vs(s),Cm(e,t,n,s,i,"max")}}oS.className="MaxPooling2D",fe(oS);class aS extends DN{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return Kt(i),vs(s),Cm(e,t,n,s,i,"avg")}}aS.className="AveragePooling2D",fe(aS);class kN 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 q(`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];wn(this.poolSize,"poolSize"),wn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Kt(this.dataFormat),vs(this.padding),this.inputSpec=[new Ln({ndim:5})]}computeOutputShape(e){e=Nt(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=li(t,this.poolSize[0],this.padding,this.strides[0]),n=li(n,this.poolSize[1],this.padding,this.strides[1]),s=li(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 Q(()=>(this.invokeCallHook(e,t),this.poolingFunction(Je(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 cS extends kN{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return Kt(i),vs(s),ON(e,t,n,s,i,"max")}}cS.className="MaxPooling3D",fe(cS);class lS extends kN{constructor(e){super(e)}poolingFunction(e,t,n,s,i){return Kt(i),vs(s),ON(e,t,n,s,i,"avg")}}lS.className="AveragePooling3D",fe(lS);class FN extends lt{constructor(e){super(e);this.inputSpec=[new Ln({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Pe}}class hS extends FN{constructor(e){super(e||{})}call(e,t){return Q(()=>{const n=Je(e);return jt(n,1)})}}hS.className="GlobalAveragePooling1D",fe(hS);class uS extends FN{constructor(e){super(e||{})}call(e,t){return Q(()=>{const n=Je(e);return es(n,1)})}}uS.className="GlobalMaxPooling1D",fe(uS);class _N extends lt{constructor(e){super(e);this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Kt(this.dataFormat),this.inputSpec=[new Ln({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Pe}getConfig(){const e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class dS extends _N{call(e,t){return Q(()=>{const n=Je(e);return this.dataFormat==="channelsLast"?jt(n,[1,2]):jt(n,[2,3])})}}dS.className="GlobalAveragePooling2D",fe(dS);class pS extends _N{call(e,t){return Q(()=>{const n=Je(e);return this.dataFormat==="channelsLast"?es(n,[1,2]):es(n,[2,3])})}}pS.className="GlobalMaxPooling2D",fe(pS);class WN 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=ci(s,n);delete t.layer;const o={layer:i};return Object.assign(o,t),new e(o)}}class mS extends WN{constructor(e){super(e);this.supportsMasking=!0}build(e){if(e=Nt(e),e.length<3)throw new q(`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=Nt(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 Q(()=>{e=Je(e);const n=(o,a)=>{const c=Je(this.layer.call(o,t));return[c,[]]},s=CN(n,e,[],!1,null,null,!1,!0),i=s[1];return i})}}mS.className="TimeDistributed",fe(mS);function JV(e){rc(o3,"BidirectionalMergeMode",e)}const ZV="concat";class fS extends WN{constructor(e){super(e);const t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=ci(n),t.goBackwards=!(t.goBackwards===!0);const s={};if(s.className=e.layer.getClassName(),s.config=t,this.backwardLayer=ci(s),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?ZV:e.mergeMode,JV(this.mergeMode),e.weights)throw new Pe("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()):ns(s)}apply(e,t){let n=t==null?null:t.initialState,s=t==null?null:t.constants;t==null&&(t={});const i=NN(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 q("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 Ln({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 Pe("Support for constants in Bidirectional layers is not implemented yet.");const c=o[0]instanceof ai;for(const h of o)if(h instanceof ai!==c)throw new q("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 f=super.apply(h,t);return this.inputSpec=m,f}else return super.apply(e,t)}call(e,t){return Q(()=>{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=Ts(i,1));let a;return this.mergeMode==="concat"?a=Kw([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){jo(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),jo(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=ci(t.layer);if(delete t.layer,t.numConstants!=null)throw new Pe("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const s=t;return s.layer=n,new e(s)}}fS.className="Bidirectional",fe(fS);function QV(e){return new cc(e)}function eG(e){return new NL(e)}function tG(e){return new TL(e)}function nG(e){return new AL(e)}function sG(e){return new vL(e)}function iG(e){return new RL(e)}function rG(e){return new CL(e)}function oG(e){return new Im(e)}function aG(e){return new nu(e)}function cG(e){return new kL(e)}function lG(e){return new Sm(e)}function hG(e){return new FL(e)}function uG(e){return new _L(e)}function dG(e){return new WL(e)}function pG(e){return new $L(e)}function mG(e){return new YL(e)}function fG(e){return new VL(e)}function gG(e){return new Nm(e)}function yG(e){return new zL(e)}function bG(e){return new GL(e)}function wG(e){return new HL(e)}function LG(e){return new qL(e)}function SG(e){return new jL(e)}function IG(e){return new XL(e)}function xG(e){return new iu(e)}function TG(e){return new ou(e)}function AG(e){return new lu(e)}function vG(e){return new au(e)}function NG(e){return new cu(e)}function CG(e){return new ru(e)}function RG(e){return new JL(e)}function OG(e){return new tS(e)}function EG(e){return new nS(e)}function DG(e){return new sS(e)}function gS(e){return new rS(e)}function kG(e){return gS(e)}function FG(e){return gS(e)}function yS(e){return new aS(e)}function _G(e){return yS(e)}function WG(e){return yS(e)}function bS(e){return new lS(e)}function $G(e){return bS(e)}function UG(e){return bS(e)}function BG(e){return new hS(e)}function MG(e){return new dS(e)}function $N(e){return new uS(e)}function UN(e){return new pS(e)}function BN(e){return new iS(e)}function MN(e){return new oS(e)}function PG(e){return new cS(e)}function zG(e){return new BL(e)}function VG(e){return new Tm(e)}function GG(e){return new ML(e)}function YG(e){return new su(e)}function HG(e){return new UL(e)}function qG(e){return new xm(e)}function jG(e){return new PL(e)}function KG(e){return new vm(e)}function XG(e){return new Di(e)}function JG(e){return new Am(e)}function ZG(e){return new fS(e)}function QG(e){return new mS(e)}const eY=$N,tY=UN,nY=BN,sY=MN;function iY(e){return new ZL(e)}function rY(e){return new QL(e)}function oY(e){return new eS(e)}function aY(e){return new KL(e)}var cY=Object.freeze({__proto__:null,inputLayer:QV,elu:eG,reLU:tG,leakyReLU:nG,prelu:sG,softmax:iG,thresholdedReLU:rG,conv1d:oG,conv2d:aG,conv2dTranspose:cG,conv3d:lG,separableConv2d:hG,cropping2D:uG,upSampling2d:dG,depthwiseConv2d:pG,activation:mG,dense:fG,dropout:gG,spatialDropout1d:yG,flatten:bG,repeatVector:wG,reshape:LG,permute:SG,embedding:IG,add:xG,average:TG,concatenate:AG,maximum:vG,minimum:NG,multiply:CG,dot:RG,batchNormalization:OG,layerNormalization:EG,zeroPadding2d:DG,averagePooling1d:gS,avgPool1d:kG,avgPooling1d:FG,averagePooling2d:yS,avgPool2d:_G,avgPooling2d:WG,averagePooling3d:bS,avgPool3d:$G,avgPooling3d:UG,globalAveragePooling1d:BG,globalAveragePooling2d:MG,globalMaxPooling1d:$N,globalMaxPooling2d:UN,maxPooling1d:BN,maxPooling2d:MN,maxPooling3d:PG,gru:zG,gruCell:VG,lstm:GG,lstmCell:YG,simpleRNN:HG,simpleRNNCell:qG,convLstm2d:jG,convLstm2dCell:KG,rnn:XG,stackedRNNCells:JG,bidirectional:ZG,timeDistributed:QG,globalMaxPool1d:eY,globalMaxPool2d:tY,maxPool1d:nY,maxPool2d:sY,Layer:lt,RNN:Di,RNNCell:pc,input:aN,gaussianNoise:iY,gaussianDropout:rY,alphaDropout:oY,masking:aY});function lY(e,t){return uL(e,t)}function hY(e,t){return zv(e,t)}function uY(e,t){return Vv(e,t)}function dY(e,t){return dL(e,t)}function pY(e,t){return pL(e,t)}function mY(e,t){return Pv(e,t)}function fY(e,t){return tV(e,t)}function gY(e,t){return mm(e,t)}function yY(e,t){return hc(e,t)}function bY(e,t){return jr(e,t)}function wY(e,t){return jr(e,t)}function LY(e,t){return jr(e,t)}function SY(e,t){return or(e,t)}function IY(e,t){return or(e,t)}function xY(e,t){return or(e,t)}var TY=Object.freeze({__proto__:null,binaryAccuracy:lY,binaryCrossentropy:hY,sparseCategoricalAccuracy:uY,categoricalAccuracy:dY,categoricalCrossentropy:pY,precision:mY,recall:fY,cosineProximity:gY,meanAbsoluteError:yY,meanAbsolutePercentageError:bY,MAPE:wY,mape:LY,meanSquaredError:SY,MSE:IY,mse:xY});var AY=Object.freeze({__proto__:null,modelFromJSON:FV});function vY(e){return new eu(e)}function NY(e){return zV(e)}function CY(e){return VV(e)}var RY=Object.freeze({__proto__:null,l1l2:vY,l1:NY,l2:CY});class PN extends lc{constructor(){super(...arguments);this.model=null}setModel(e){if(!(e instanceof ar))throw new Error("model must be a LayersModel, not some other Container");this.model=e}}function Rm(e,t){return e<t}function zN(e,t){return e>t}class VN extends PN{constructor(e){super();if(e==null&&(e={}),e.restoreBestWeights)throw new Pe("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=Rm:this.mode==="max"?this.monitorFunc=zN:this.monitor.indexOf("acc")!==-1?this.monitorFunc=zN:this.monitorFunc=Rm,this.monitorFunc===Rm&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Rm?Infinity:-Infinity}async onEpochEnd(e,t){await qr(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 OY(e){return new VN(e)}const EY={earlyStopping:OY};var hi;(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"})(hi||(hi={}));var GN;(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={}))})(GN||(GN={}));const wS={};function DY(e,t){const n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};wS[e]=n}function YN(e){return wS[e]}function kY(e){delete wS[e]}function R(e,t,n,s,i){const o=t.inputParams[e];if(o&&o.inputIndexStart!==void 0){const c=o.inputIndexStart,h=o.inputIndexEnd===0?void 0:o.inputIndexEnd===void 0?c+1:o.inputIndexEnd;if(o.type==="tensor")return is(t.inputNames[o.inputIndexStart],n,s,i);if(o.type==="tensors"){const f=t.inputNames.slice(c,h);return f.map(b=>is(b,n,s,i))}const d=is(t.inputNames.slice(c)[0],n,s,i),m=d.dataSync();return o.type==="number"?m[0]:Ls(d.shape,m)}const a=t.attrParams[e];return a&&a.value}function is(e,t,n,s){const[i,o]=ps(e);if(s!=null){const c=s.getHashTableHandleByName(i);if(c!=null)return c}const a=n.currentContextIds.find(c=>!!t[Om(i,c)]);return a!==void 0?t[Om(i,a)][o]:void 0}function FY(e,t,n){return t[Om(e,n.currentContextId)]}function cr(e,t){const[n,s]=ps(e);return[Om(n,t&&t.currentContextId),s]}function Om(e,t){return t?`${e}-${t}`:e}function ps(e){const t=e.split(":");if(t.length===1)return[e,0];const n=t[0];return[n,Number(t[t.length-1])]}function Ote(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 lr(e){return e.kept?e:Fr(e)}const _Y=[{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 WY=Object.freeze({__proto__:null,json:_Y});const $Y=[{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 UY=Object.freeze({__proto__:null,json:$Y});const BY=[{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 MY=Object.freeze({__proto__:null,json:BY});const PY=[{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 zY=Object.freeze({__proto__:null,json:PY});const VY=[{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 GY=Object.freeze({__proto__:null,json:VY});const YY=[{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:YY});const qY=[{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 jY=Object.freeze({__proto__:null,json:qY});const KY=[{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 XY=Object.freeze({__proto__:null,json:KY});const JY=[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]}];var ZY=Object.freeze({__proto__:null,json:JY});const QY=[{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 eH=Object.freeze({__proto__:null,json:QY});const tH=[{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 nH=Object.freeze({__proto__:null,json:tH});const sH=[{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 iH=Object.freeze({__proto__:null,json:sH});const rH=[{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 oH=Object.freeze({__proto__:null,json:rH});const aH=[{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 cH=Object.freeze({__proto__:null,json:aH});const lH=[{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 hH=Object.freeze({__proto__:null,json:lH});const uH=[{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 dH=Object.freeze({__proto__:null,json:uH});const pH=[{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:"MirrorPad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"mode",name:"mode",type:"string"}]},{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 mH=Object.freeze({__proto__:null,json:pH});class HN{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[WY,UY,MY,zY,GY,HY,jY,nH,eH,XY,iH,oH,cH,hH,dH,mH,ZY],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,x)=>(L[x.name]=this.mapNode(x),x.op.startsWith("Placeholder")?s.push(L[x.name]):x.op==="Const"?i.push(L[x.name]):(x.input==null||x.input.length===0)&&o.push(L[x.name]),L),{});let c=[];const h=[];let d={},m={};t!=null&&(d=this.mapSignatureEntries(t.inputs),m=this.mapSignatureEntries(t.outputs));const f=Object.keys(a);f.forEach(L=>{const x=a[L];x.inputNames.forEach(v=>{const[N]=cr(v);x.inputs.push(a[N]),a[N].children.push(x)})}),Object.keys(m).length===0?f.forEach(L=>{const x=a[L];x.children.length===0&&h.push(x)}):Object.keys(m).forEach(L=>{const[x]=cr(L),v=a[x];v!=null&&(v.signatureKey=m[L],h.push(v))}),Object.keys(d).length>0?Object.keys(d).forEach(L=>{const[x]=cr(L),v=a[x];v&&(v.signatureKey=d[L],c.push(v))}):c=s;let b={};e.library!=null&&e.library.function!=null&&(b=e.library.function.reduce((L,x)=>(L[x.signature.name]=this.mapFunction(x),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=YN(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=LS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=LS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"string[]":a=CS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=CS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"number":a=IS(e.attr,i.tfName,i.defaultValue||0),a===void 0&&!!i.tfDeprecatedName&&(a=IS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"number[]":a=NS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=NS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"bool":a=SS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=SS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"bool[]":a=OS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=OS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"shape":a=vS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=vS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"shape[]":a=RS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=RS(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=AS(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=AS(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"func":a=jN(e.attr,i.tfName,i.defaultValue),a===void 0&&!!i.tfDeprecatedName&&(a=jN(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,f)=>(m[f.name]=this.mapNode(f),f.op==="Const"&&s.push(m[f.name]),m),{}));const o=[],a=[];e.signature.inputArg.forEach(m=>{const[f]=cr(m.name),b={name:f,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:xS(m.type),type:"dtype"}},children:[]};b.signatureKey=m.name,o.push(b),i[f]=b});const c=Object.keys(i);c.forEach(m=>{const f=i[m];f.inputNames.forEach(b=>{const[w]=cr(b);f.inputs.push(i[w]),i[w].children.push(f)})});const h=e.ret;e.signature.outputArg.forEach(m=>{const[f,b]=cr(h[m.name]),w=i[f];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 fH(e){const t=oe().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 qN(e,t){const n=Array.isArray(e)?String.fromCharCode.apply(null,e):fH(e);return t?n:n.toLowerCase()}function LS(e,t,n,s=!1){const i=e[t];return i!=null?qN(i.s,s):n}function SS(e,t,n){const s=e[t];return s?s.b:n}function IS(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 xS(e){typeof e=="string"&&(e=hi[e]);switch(e){case hi.DT_FLOAT:return"float32";case hi.DT_INT32:case hi.DT_INT64:case hi.DT_INT8:case hi.DT_UINT8:return"int32";case hi.DT_BOOL:return"bool";case hi.DT_DOUBLE:return"float32";case hi.DT_STRING:return"string";default:return null}}function jN(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?xS(s.type):n}function AS(e,t,n){const s=e[t];return s&&s.list&&s.list.type?s.list.type.map(i=>xS(i)):n}function KN(e){return e.unknownRank?void 0:e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function vS(e,t,n){const s=e[t];return s&&s.shape?KN(s.shape):n}function NS(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 CS(e,t,n,s=!1){const i=e[t];return i&&i.list&&i.list.s?i.list.s.map(o=>qN(o,s)):n}function RS(e,t,n){const s=e[t];return s&&s.list&&s.list.shape?s.list.shape.map(i=>KN(i)):n}function OS(e,t,n){const s=e[t];return s&&s.list&&s.list.b?s.list.b:n}class gH{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 is(e,this.tensorMap,this.context)}getAttr(e,t){const n=this.node.rawAttrs[e];if(n.tensor!=null)return is(e,this.tensorMap,this.context);if(n.i!=null||n.f!=null)return IS(this.node.rawAttrs,e,t);if(n.s!=null)return LS(this.node.rawAttrs,e,t);if(n.b!=null)return SS(this.node.rawAttrs,e,t);if(n.shape!=null)return vS(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 NS(this.node.rawAttrs,e,t);if(n.list.s!=null)return CS(this.node.rawAttrs,e,t);if(n.list.shape!=null)return RS(this.node.rawAttrs,e,t);if(n.list.b!=null)return OS(this.node.rawAttrs,e,t);if(n.list.type!=null)return AS(this.node.rawAttrs,e,t)}return t}}const yH=(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[ZT(R("tensors",e,t,n))];case"FloorMod":case"Mod":return[Tp(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[We(R("a",e,t,n),R("b",e,t,n))];case"DivNoNan":return[Jb(R("a",e,t,n),R("b",e,t,n))];case"FloorDiv":return[cp(R("a",e,t,n),R("b",e,t,n))];case"Sub":return[Re(R("a",e,t,n),R("b",e,t,n))];case"Minimum":return[Bo(R("a",e,t,n),R("b",e,t,n))];case"Maximum":return[Us(R("a",e,t,n),R("b",e,t,n))];case"Pow":return[ti(R("a",e,t,n),R("b",e,t,n))];case"SquaredDifference":return[Dh(R("a",e,t,n),R("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Ete="arithmetic";const bH=(e,t,n)=>{switch(e.op){case"Abs":case"ComplexAbs":return[dn(R("x",e,t,n))];case"Acos":return[Fb(R("x",e,t,n))];case"Acosh":return[_b(R("x",e,t,n))];case"Asin":return[Ub(R("x",e,t,n))];case"Asinh":return[Bb(R("x",e,t,n))];case"Atan":return[Mb(R("x",e,t,n))];case"Atan2":return[Pb(R("x",e,t,n),R("y",e,t,n))];case"Atanh":return[zb(R("x",e,t,n))];case"Ceil":return[Hb(R("x",e,t,n))];case"Complex":return[Xi(R("real",e,t,n),R("imag",e,t,n))];case"Cos":return[Lh(R("x",e,t,n))];case"Cosh":return[gp(R("x",e,t,n))];case"Elu":return[Ga(R("x",e,t,n))];case"Erf":return[Zb(R("x",e,t,n))];case"Exp":return[Is(R("x",e,t,n))];case"Expm1":return[Qb(R("x",e,t,n))];case"Floor":return[Ha(R("x",e,t,n))];case"Log":return[ls(R("x",e,t,n))];case"Log1p":return[Lp(R("x",e,t,n))];case"Imag":return[Ih(R("x",e,t,n))];case"Neg":return[qt(R("x",e,t,n))];case"Reciprocal":return[lw(R("x",e,t,n))];case"Real":return[Xa(R("x",e,t,n))];case"Relu":return[Ci(R("x",e,t,n))];case"Round":return[uw(R("x",e,t,n))];case"Selu":return[Cp(R("x",e,t,n))];case"Sigmoid":return[Ai(R("x",e,t,n))];case"Sin":return[Rp(R("x",e,t,n))];case"Sign":return[pw(R("x",e,t,n))];case"Sinh":return[Op(R("x",e,t,n))];case"Softplus":return[ja(R("x",e,t,n))];case"Sqrt":return[Nn(R("x",e,t,n))];case"Square":return[At(R("x",e,t,n))];case"Tanh":return[Va(R("x",e,t,n))];case"Tan":return[gw(R("x",e,t,n))];case"Relu6":case"ClipByValue":return[Zn(R("x",e,t,n),R("clipValueMin",e,t,n),R("clipValueMax",e,t,n))];case"Rsqrt":return[Np(is(e.inputNames[0],t,n))];case"Prod":return[vp(R("x",e,t,n),R("axes",e,t,n))];case"LeakyRelu":return[wp(R("x",e,t,n),R("alpha",e,t,n))];case"Prelu":return[Nh(R("x",e,t,n),R("alpha",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Dte="basic_math";function Vs(e,t,n=""){A(wH(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function wH(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 LH{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=Ce(0),bn(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),Vs(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,bn(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 sn([],[0].concat(this.elementShape));const n=this.readMany(e);return Vs(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),ts(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 sn([],[0].concat(this.elementShape));const t=[];for(let s=0;s<this.size();s++)t.push(s);const n=this.readMany(t);return Vs(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),Ht(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,ni(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=[];Q(()=>{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(tt(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 du{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}`);Vs(t,i.shape,"TensorList shape mismatch: "),bn(i)}),this.idTensor=Ce(0),this.maxNumElements=s,bn(this.idTensor)}get id(){return this.idTensor.id}copy(){return new du([...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 Vs(e,this.elementShape,"TensorList shape mismatch: "),Q(()=>{const s=this.tensors.map(i=>K(i,e));return ts(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 Vs(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(Vs(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");bn(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 Vs(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.`);Vs(this.elementShape,t.shape,"TensorList shape mismatch: "),bn(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 Vs(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size()),e.length===0?sn([],[0].concat(this.elementShape)):Q(()=>{const s=e.map(i=>K(this.tensors[i],n));return ts(s,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);return Vs(this.elementShape,t,"TensorList shape mismatch: "),this.size()===0?sn([],[0].concat(this.elementShape)):Q(()=>{const n=this.tensors.map(s=>K(s,t));return Ht(n,0)})}}function SH(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);Vs(i,t,"TensorList shape mismatch: ");const o=ni(e);return new du(o,t,s)}function IH(e,t,n){return new du([],e,t,n)}function xH(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 du([],n,e.dtype,s),a=ni(e,0);return t.forEach((c,h)=>{o.setItem(c,a[h])}),o}function TH(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=Q(()=>{const h=[];e=K(e,[1,s,o]);for(let d=0;d<t.length;++d){const m=d===0?0:i[d-1],f=[0,m,0],b=[1,t[d],o];h[d]=K(tt(e,f,b),n)}return e.dispose(),h}),c=new du([],n,e.dtype,t.length);for(let h=0;h<a.length;h++)c.setItem(h,a[h]);return c}const AH=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 f=d.map(w=>w.id);m.forEach(w=>{!w.kept&&c.indexOf(w.id)===-1&&f.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&&f.indexOf(w.id)===-1&&w.dispose()})}return d}case"LoopCond":{const s=R("pred",e,t,n);return[lr(s)]}case"Switch":{const s=R("pred",e,t,n);let i=R("data",e,t,n);return i.kept||(i=lr(i)),(await s.data())[0]?[void 0,i]:[i,void 0]}case"Merge":{const s=e.inputNames.find(i=>is(i,t,n)!==void 0);if(s){const i=is(s,t,n);return[lr(i)]}return}case"Enter":{const s=R("frameName",e,t,n),i=R("tensor",e,t,n);return n.enterFrame(s),[lr(i)]}case"Exit":{const s=R("tensor",e,t,n);return n.exitFrame(),[lr(s)]}case"NextIteration":{const s=R("tensor",e,t,n);return n.nextIteration(),[lr(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 LH(d,i,s,o,h,a,c);return n.addTensorArray(m),[m.idTensor,Ce(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[Ce(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=xH(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=IH(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=SH(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=TH(s,o,i);return n.addTensorList(a),[a.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},kte="control";function XN(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),f=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:f,dilations:b,biasArg:w,preluArg:L,activationFunc:i}}const vH=(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[mp(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[Qi(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}=XN(e,t,n);return[xw({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}=XN(e,t,n);return[GA({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[fp(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[$o(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[jb(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[yh(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[Ah(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}=gA(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[Yb(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[iw(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[Xb(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`)}},Fte="convolution";const NH=(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[Ya(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[pA(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[yA(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[ko(s,i,o,a)]}case"Ones":return[ei(R("shape",e,t,n),R("dtype",e,t,n))];case"OnesLike":return[_n(R("x",e,t,n))];case"RandomUniform":return[zo(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[Ch(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[kh(s,i,o,R("dtype",e,t,n),a)]}case"Zeros":return[dt(R("shape",e,t,n),R("dtype",e,t,n))];case"ZerosLike":return[et(R("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},_te="creation";function ES(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 CH=async(e,t,n)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:s,scores:i,maxOutputSize:o,iouThreshold:a,scoreThreshold:c,softNmsSigma:h}=ES(e,t,n),d=await Vr.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}=ES(e,t,n),h=R("padToMaxOutputSize",e,t,n),d=await Vr.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}=ES(e,t,n);return[await Vr.nonMaxSuppressionAsync(s,i,o,a,c)]}case"Where":{const s=Ae(R("condition",e,t,n),"bool"),i=[await ww(s)];return s.dispose(),i}case"ListDiff":return wA(R("x",e,t,n),R("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}},Wte="dynamic";const RH=(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=yw(s,i,o);return[a.values,a.indices]}case"Unique":{const s=R("x",e,t,n),i=Fp(s);return[i.values,i.indices]}case"UniqueV2":{const s=R("x",e,t,n),i=R("axis",e,t,n),o=Fp(s,i);return[o.values,o.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},$te="evaluation";const OH=(e,t,n)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const s=R("default",e,t,n);return[is(e.name,t,n)||s];case"Placeholder":return[is(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{const d=R("x",e,t,n);return[lr(d)]}case"IdentityN":return R("x",e,t,n).map(d=>lr(d));case"Snapshot":const i=R("x",e,t,n);return[lr(i)];case"Shape":return[hs(R("x",e,t,n).shape,"int32")];case"ShapeN":return R("x",e,t,n).map(d=>hs(d.shape));case"Size":return[Ce(R("x",e,t,n).size,"int32")];case"Rank":return[Ce(R("x",e,t,n).rank,"int32")];case"NoOp":return[Ce(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`)}},Ute="graph";class EH{constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=Ce(0),this.tensorMap=new Map,bn(this.handle)}get id(){return this.handle.id}clearAndClose(){this.tensorMap.forEach(e=>e.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}async import(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return this.tensorMap.forEach(s=>s.dispose()),this.tensorMap.clear(),Q(()=>{const s=ni(t),i=n.length,o=s.length;A(i===o,()=>`The number of elements doesn't match, keys has ${i} elements, the values has ${o} elements.`);for(let a=0;a<i;a++){const c=n[a],h=s[a];bn(h),this.tensorMap.set(c,h)}return this.handle})}async find(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return Q(()=>{const s=[];for(let i=0;i<n.length;i++){const o=n[i],a=this.findWithDefault(o,t);s.push(a)}return ts(s)})}findWithDefault(e,t){const n=this.tensorMap.get(e);return n!=null?n:t}checkKeyAndValueTensor(e,t){if(e.dtype!==this.keyDType)throw new Error(`Expect key dtype ${this.keyDType}, but got ${e.dtype}`);if(t.dtype!==this.valueDType)throw new Error(`Expect value dtype ${this.valueDType}, but got ${t.dtype}`)}}const DH=async(e,t,n,s)=>{switch(e.op){case"HashTable":case"HashTableV2":{const i=R("keyDType",e,t,n),o=R("valueDType",e,t,n),a=new EH(i,o);return s.addHashTable(e.name,a),[a.handle]}case"LookupTableImport":case"LookupTableImportV2":{const i=R("tableHandle",e,t,n,s),o=R("keys",e,t,n),a=R("values",e,t,n),c=s.getHashTableById(i.id);return[await c.import(o,a)]}case"LookupTableFind":case"LookupTableFindV2":{const i=R("tableHandle",e,t,n,s),o=R("keys",e,t,n),a=R("defaultValue",e,t,n),c=s.getHashTableById(i.id);return[await c.find(o,a)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Bte="hash_table";const kH=(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[Vr.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[Vr.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[Vr.cropAndResize(s,i,o,a,c,h)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Mte="image";const FH=(e,t,n)=>{switch(e.op){case"Equal":return[Qs(R("a",e,t,n),R("b",e,t,n))];case"NotEqual":return[Mr(R("a",e,t,n),R("b",e,t,n))];case"Greater":return[xs(R("a",e,t,n),R("b",e,t,n))];case"GreaterEqual":return[er(R("a",e,t,n),R("b",e,t,n))];case"Less":return[xh(R("a",e,t,n),R("b",e,t,n))];case"LessEqual":return[Br(R("a",e,t,n),R("b",e,t,n))];case"LogicalAnd":return[Bs(R("a",e,t,n),R("b",e,t,n))];case"LogicalNot":return[Th(R("a",e,t,n))];case"LogicalOr":return[xp(R("a",e,t,n),R("b",e,t,n))];case"Select":case"SelectV2":return[Bn(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`)}},Pte="logical";const _H=(e,t,n)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[ct(R("a",e,t,n),R("b",e,t,n),R("transposeA",e,t,n),R("transposeB",e,t,n))];case"Transpose":return[Ye(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[Pp({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`)}},zte="matrices";const WH=(e,t,n)=>{switch(e.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[Wo(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[Wo(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[tw(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[Vo(R("x",e,t,n))];case"LogSoftmax":return[Ip(R("x",e,t,n))];case"SparseToDense":return[Lw(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`)}},Vte="normalization";const $H=(e,t,n)=>{switch(e.op){case"Max":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[es(R("x",e,t,n),s,i)]}case"Mean":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[jt(R("x",e,t,n),s,i)]}case"Min":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[Ka(R("x",e,t,n),s,i)]}case"Sum":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[$e(R("x",e,t,n),s,i)]}case"All":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[lp(R("x",e,t,n),s,i)]}case"Any":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[mh(R("x",e,t,n),s,i)]}case"ArgMax":{const s=R("axis",e,t,n);return[fh(R("x",e,t,n),s)]}case"ArgMin":{const s=R("axis",e,t,n);return[$b(R("x",e,t,n),s)]}case"Prod":{const s=R("axis",e,t,n),i=R("keepDims",e,t,n);return[vp(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[yp(R("x",e,t,n),s,i,o)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Gte="reduction";const UH=(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),[Ht(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[qa(i,Ae(o,"int32"),s)]}case"ReverseV2":case"Reverse":{const s=R("axis",e,t,n),i=R("x",e,t,n);return[Ts(i,s)]}case"Slice":{const s=R("begin",e,t,n),i=R("size",e,t,n);return[tt(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),f=R("x",e,t,n);return[fw(f,s,i,o,a,c,h,d,m)]}case"Pack":return Q(()=>{const s=R("axis",e,t,n),i=R("tensors",e,t,n),o=i[0].shape,a=Pr(i[0]).shape,c=i.map(h=>{const d=ae(h.shape,o);if(!d&&!ae(Pr(h).shape,a))throw new Error("the input tensors shape does not match");return d?h:K(h,o)});return[ts(c,s)]});case"Unpack":{const s=R("axis",e,t,n),i=R("tensor",e,t,n);return ni(i,s)}case"Tile":{const s=R("reps",e,t,n);return[Ur(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 us(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[UA(s,i,o)]}case"GatherNd":{const s=R("x",e,t,n),i=R("indices",e,t,n);return[BA(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[Lw(s,o,i,o.dtype===a.dtype?a:Ae(a,o.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Yte="slice_join";const BH=(e,t,n)=>{switch(e.op){case"FFT":return[Oh(R("x",e,t,n))];case"IFFT":return[Qa(R("x",e,t,n))];case"RFFT":return[Eh(R("x",e,t,n))];case"IRFFT":return[kp(R("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Hte="spectral";const MH=(e,t,n)=>{switch(e.op){case"Cast":return[Ae(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[Pr(R("x",e,t,n),s)]}case"Reshape":return[K(R("x",e,t,n),R("shape",e,t,n))];case"MirrorPad":return[rw(R("x",e,t,n),R("padding",e,t,n),R("mode",e,t,n))];case"PadV2":case"Pad":return[Ni(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[vh(R("x",e,t,n),s,i)]}case"BatchToSpaceND":{const s=R("blockShape",e,t,n),i=R("crops",e,t,n);return[bh(R("x",e,t,n),s,i)]}case"DepthToSpace":{const s=R("blockSize",e,t,n),i=R("dataFormat",e,t,n).toUpperCase();return[Kb(R("x",e,t,n),s,i)]}case"BroadcastTo":return[wh(R("x",e,t,n),R("shape",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},qte="transformation";function JN(e,t,n,s){const i=((o,a,c)=>{switch(o.category){case"arithmetic":return Q(()=>yH(o,a,c));case"basic_math":return Q(()=>bH(o,a,c));case"control":return AH(o,a,c);case"convolution":return Q(()=>vH(o,a,c));case"creation":return Q(()=>NH(o,a,c));case"dynamic":return CH(o,a,c);case"evaluation":return Q(()=>RH(o,a,c));case"image":return Q(()=>kH(o,a,c));case"graph":return Q(()=>OH(o,a,c));case"logical":return Q(()=>FH(o,a,c));case"matrices":return Q(()=>_H(o,a,c));case"normalization":return Q(()=>WH(o,a,c));case"reduction":return Q(()=>$H(o,a,c));case"slice_join":return Q(()=>UH(o,a,c));case"spectral":return Q(()=>BH(o,a,c));case"transformation":return Q(()=>MH(o,a,c));case"hash_table":return DH(o,a,c,s);case"custom":const h=YN(o.op);if(h&&h.customExecutor)return h.customExecutor(new gH(o,a,c));throw TypeError(`Custom op ${o.op} is not registered.`);default:throw TypeError(`Unknown op '${o.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 No(i)?i.then(o=>[].concat(o)):[].concat(i)}class ZN{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 QN(e,t,n,s){const i=new Set,o=[];let a=null,c=null;const h=new Set,d=Object.keys(e).map(b=>ps(b)[0]);let m=[];s!=null&&(m=s.map(b=>ps(b.name)[0]));const f=[...t];for(;f.length>0;){const b=f.pop();if((e0(b)||YH(b)||HH(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),f.push(w)})}return{inputs:e,outputs:t,usedNodes:i,missingInputs:o,dynamicNode:a,syncInputs:c}}function PH(e,t,n){const{usedNodes:s,inputs:i}=n,o=[],a=Object.keys(i).map(m=>ps(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(f=>{!h.has(f.name)&&s.has(f.name)&&f.inputs.every(b=>h.has(b.name))&&o.push(f)})}return d}const zH=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],VH=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],GH=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2"];function e0(e){return zH.indexOf(e.op)>=0}function YH(e){return VH.indexOf(e.op)>=0}function HH(e){return GH.indexOf(e.op)>=0}class DS{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 DS(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}set resourceManager(e){this._resourceManager=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=QN(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 PH(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[ps(m)[0]]),i=t.map(m=>ps(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 Q(()=>{const m=new ZN(this.weightMap,h,d,this.functionExecutorMap),f=Object.assign({},this.weightMap);Object.keys(e).forEach(L=>{const[x,v]=ps(L),N=[];N[v]=e[L],f[x]=N});const b=this.getFrozenTensorIds(f),w={};for(let L=0;L<c.length;L++){const x=c[L];if(!f[x.name]){const v=JN(x,f,m,this._resourceManager);if(No(v))throw new Error(`The execution of the op '${x.op}' returned a promise. Please use model.executeAsync() instead.`);f[x.name]=v,this.checkTensorForDisposal(x.name,x,f,m,b,i,w)}}return this.parent==null&&m.dispose(b),t.map(L=>is(L,f,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=FY(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 ZN(this.weightMap,s,i,this.functionExecutorMap),a=await this.executeWithControlFlow(e,o,t,n),c=t.map(f=>is(f,a,o)),h=c.map(f=>f.id),d=Object.keys(e).map(f=>e[f].id),m=new Set([...h,...d,...this.weightIds]);return Object.keys(a).forEach(f=>{const b=a[f];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(O=>this.graph.nodes[ps(O)[0]]),a=n.map(O=>ps(O)[0]);let c=a.map(O=>this.graph.nodes[O]);c.length===0&&(c=this._outputs);const{usedNodes:h,missingInputs:d,dynamicNode:m,syncInputs:f}=QN(e,c,this.weightMap,this._initNodes),b=[...o,...this.graph.weights,...this._initNodes||[]].map(O=>({node:O,contexts:t.currentContext})),w=Object.assign({},this.weightMap);Object.keys(e).forEach(O=>{const[E,k]=ps(O),F=[];F[k]=e[O],w[E]=F});const L={},x=this.getFrozenTensorIds(w),v={};for(;b.length>0;){const O=this.processStack(o,b,t,w,v,x,a,L,h);await Promise.all(O)}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(O=>!e0(O)&&!is(O.name,w,t)).map(O=>O.name);if(N.length>0){let O="";throw m!=null&&(O=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${f}]`),new Error(`Cannot compute the outputs [${N}] from the provided inputs [${i}]. Consider providing the following inputs: [${d}]. ${O}`)}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 f="";if(m.node.op==="Enter"&&R("isConstant",m.node,s,n)&&([f]=cr(m.node.name,n)),s[m.node.name]==null){const b=JN(m.node,s,n,this._resourceManager);f||([f]=cr(m.node.name,n));const w=n.currentContext;No(b)?d.push(b.then(L=>(s[f]=L,n.currentContext=w,this.checkTensorForDisposal(f,m.node,s,n,o,a,c),this.processChildNodes(m.node,t,n,s,i,h),L))):(s[f]=b,this.checkTensorForDisposal(f,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]=cr(a.name,n);if(i[c]||!o.has(a.name))return;a.op==="Merge"?a.inputNames.some(h=>!!is(h,s,n))&&(i[c]=!0,t.push({contexts:n.currentContext,node:a})):a.inputNames.every(h=>!!is(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]=ps(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);A(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&&A(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]=ps(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]=ps(t);if(!this.graph.nodes[n])throw new Error(`The output '${t}' is not found in the graph`)})}}class qH{constructor(e={},t={}){this.hashTableNameToHandle=e,this.hashTableMap=t}addHashTable(e,t){this.hashTableNameToHandle[e]=t.handle,this.hashTableMap[t.id]=t}getHashTableHandleByName(e){return this.hashTableNameToHandle[e]}getHashTableById(e){return this.hashTableMap[e]}dispose(){for(const e in this.hashTableMap)this.hashTableMap[e].clearAndClose(),delete this.hashTableMap[e];for(const e in this.hashTableNameToHandle)this.hashTableNameToHandle[e].dispose(),delete this.hashTableNameToHandle[e]}}const jH="?tfjs-format=file",KH="model.json";class t0{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={}),this.resourceManager=new qH}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=tp(e,this.loadOptions);else{const t=yb(e,this.loadOptions);if(t.length===0)t.push(tp(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=Jd(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new DS(HN.Instance.transformGraph(t,n)),this.executor.weightMap=this.convertTensorMapToTensorsMap(s),this.executor.resourceManager=this.resourceManager,e.modelInitializer!=null){const i=HN.Instance.transformGraph(e.modelInitializer);this.initializer=new DS(i),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializer.executeAsync({},[])}return!0}async save(e,t){if(typeof e=="string"){const n=gb(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 ee)&&!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(),this.resourceManager.dispose()}}async function XH(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}${KH}${jH}`));const n=new t0(e,t);return await n.load(),n}const n0="2.7.0";function JH(e,t){return Dm(e,t)}function Dm(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(mc(e)){const o=Array.isArray(e)?[]:{};s.add(e);for(const a in e){const c=e[a],h=Dm(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 ZH(e,t=i0){return s0(e,t)}function s0(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(mc(s)){const o=Array.isArray(s)?[]:{};n.add(s);for(const a in s){const c=e.map(d=>d[a]),h=s0(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 i0(e){return e===null?null:mc(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function r0(e,t){const n=new Map;Dm(e,t,n);for(const i of Array.from(n.keys())){const o=n.get(i);if(No(o)){const a=await o;n.set(i,a)}}const s=Dm(e,t,n);return s}function mc(e){return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof ee))}function QH(e){return e==null||eq(e)||Array.isArray(e)||typeof e=="object"&&e instanceof ee||hn(e)}function eq(e){return e===null||typeof e!="object"&&typeof e!="function"}function tq(e){return JH(e,nq)}function nq(e){return e instanceof ee?{value:e.clone(),recurse:!1}:mc(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}class o0{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 kS extends o0{constructor(){super(kS.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}}kS.INITIAL_CAPACITY=32;function a0(e){return new iq(e)}function jte(e){let t=e;return pu(()=>({value:t++,done:!1}))}function pu(e){return new rq(e)}function c0(e,t){return new h0(e,t)}function Kte(e,t,n){return c0(pu(e).take(t),n)}function sq(e,t=Zr.FAIL){return new mq(e,t)}class Sn{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 dq(this,e)}filter(e){return new hq(this,e)}map(e){return new uq(this,e)}mapAsync(e){return new l0(this,e)}serialMapAsync(e){return new l0(this,e).serial()}flatmap(e){return new pq(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 lq(this,e,t)}columnMajorBatch(e,t=!0,n=i0){const s=this.rowMajorBatch(e,t);return s.map(i=>ZH(i,n))}concatenate(e,t){return new h0(a0([this,e]),t)}take(e){return e<0||e==null?this:new cq(this,e)}skip(e){return e<0||e==null?this:new aq(this,e)}prefetch(e){return new u0(this,e)}shuffle(e,t){return new fq(this,e,t)}serial(){return new oq(this)}}class iq extends Sn{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:tq(e),done:!1}}}class rq extends Sn{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 oq extends Sn{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 aq extends Sn{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 cq extends Sn{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 lq extends Sn{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 hq extends Sn{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 uq extends Sn{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)Kd(i,s)||i.dispose();return{value:n,done:!1}}}class dq extends Sn{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 l0 extends Sn{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)Kd(i,s)||i.dispose();return{value:n,done:!1}}}class FS extends Sn{constructor(){super();this.outputQueue=new kS,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 pq extends FS{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)Kd(i,s)||i.dispose();return!0}}class h0 extends Sn{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 Zr;(function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"})(Zr||(Zr={}));class mq extends Sn{constructor(e,t=Zr.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 Sn){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 r0(this.iterators,s);if(t===n)return{value:null,done:!0};if(n>0)switch(this.mismatchMode){case Zr.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case Zr.SHORTEST:return{value:null,done:!0};case Zr.LONGEST:default:}return this.count++,{value:i,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}}class u0 extends Sn{constructor(e,t){super();this.upstream=e,this.bufferSize=t,this.buffer=new o0(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 fq extends u0{constructor(e,t,n){super(e,t);this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=Za(n||Kn().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 fc{constructor(){this.size=null}batch(e,t=!0){const n=this;A(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),ms(async()=>(await n.iterator()).columnMajorBatch(e,t,bq),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,ms(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){const t=this;let n;return this.size===Infinity?n=Infinity:n=null,ms(async()=>(await t.iterator()).filter(s=>Q(()=>e(s))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){const t=this;return ms(async()=>(await t.iterator()).map(n=>Q(()=>e(n))),this.size)}mapAsync(e){const t=this;return ms(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 ms(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,ms(async()=>{const s=pu(async()=>({value:await t.iterator(),done:!1}));return c0(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,ms(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=Za(t||Kn().toString());return ms(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,ms(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()}}fc.MAX_BUFFER_SIZE=1e4;function ms(e,t=null){return new class extends fc{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function gq(e){return ms(async()=>a0(e),e.length)}function yq(e){if(!mc(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 ms(async()=>{const n=await r0(e,s=>{if(s instanceof fc)return{value:s.iterator(),recurse:!1};if(mc(s))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return sq(n,Zr.SHORTEST)},t)}function bq(e){if(e===null)return null;const t=e[0];if(QH(t)){const n=wq(e);return{value:n,recurse:!1}}return{value:null,recurse:!0}}function wq(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof ee?ts(e):sn(e)}class d0 extends fc{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 km='"',mu=Symbol("out"),p0=Symbol("field"),Fm=Symbol("quote"),_S=Symbol("quoteafterquote"),m0=Symbol("quoteinquote");class f0 extends fc{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 d0(e),t||(t={}),this.hasHeader=!(t.hasHeader===!1),this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(A(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&&A(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(A(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=mu;for(let a=0;a<i;a++)switch(o){case mu:switch(e.charAt(a)){case km:s=a+1,o=Fm;break;case this.delimiter:if(s=a+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),o=mu;break;default:o=p0,s=a;break}break;case p0:switch(e.charAt(a)){case this.delimiter:n.push(e.substring(s,a)),o=mu,s=a+1;break;default:}break;case Fm:switch(e.charAt(a)){case km:o=_S;break;default:}break;case _S:switch(e.charAt(a)){case this.delimiter:n.push(e.substring(s,a-1)),o=mu,s=a+1;break;case km:o=Fm;break;default:o=m0;break}break;case m0:switch(e.charAt(a)){case km:o=Fm;break;default:}break;default:}if(o===_S?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 g0 extends Sn{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(oe().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");const t=new g0(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(P(t));return n.set(e,n.length-e.length),sn(n,t)}}class y0 extends Sn{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=hs([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=zr([o,i,c,a],[1,4])}else this.cropBox=zr([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(oe().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 y0(e,t);return await n.start(),n}async start(){this.webcamConfig.facingMode&&A(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=$T(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 Q(()=>{const t=e.toFloat().expandDims(0);let n;n=Vr.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 b0{}class w0 extends Sn{split(e){return new Lq(this,e)}}class Lq extends w0{constructor(e,t){super();this.upstream=e,this.impl=new Sq(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class Sq extends FS{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 Iq extends Sn{decodeUTF8(){return new xq(this)}}class xq extends w0{constructor(e){super();this.upstream=e,this.impl=new Tq(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class Tq extends FS{constructor(e){super();if(this.upstream=e,oe().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 oe().get("IS_BROWSER")?n=this.decoder.decode(t,{stream:!0}):n=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0}}class L0 extends Iq{constructor(e,t={}){super();this.file=e,this.options=t,A(e instanceof Uint8Array||(oe().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 Aq(e,t={}){let n,s;typeof e=="string"?n=e:(n=e.url,s=vq(e));const i=await lT(n,s);if(i.ok){const o=new Uint8Array(await i.arrayBuffer());return new L0(o,t)}else throw new Error(i.statusText)}const vq=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 b0{constructor(e,t={}){super();this.input=e,this.options=t}async iterator(){if(S0(this.input)&&oe().get("IS_NODE")){const e=require("fs");this.input=e.readFileSync(this.input.substr(7))}return new L0(this.input,this.options)}}class x0 extends b0{constructor(e,t={}){super();this.url=e,this.fileOptions=t}async iterator(){return S0(this.url)?new I0(this.url,this.fileOptions).iterator():Aq(this.url,this.fileOptions)}}function Nq(e,t={}){return new f0(new x0(e),t)}function Cq(e){const t=pu(e);return ms(async()=>t)}function Rq(e){return ms(async()=>{const t=await e();return pu(()=>t.next())})}async function Oq(e,t){return y0.create(e,t)}async function Eq(e){return g0.create(e)}const T0="2.7.0";var Dq=Object.freeze({__proto__:null,array:gq,Dataset:fc,zip:yq,CSVDataset:f0,TextLineDataset:d0,csv:Nq,func:Cq,generator:Rq,microphone:Eq,webcam:Oq,FileDataSource:I0,URLDataSource:x0,version_data:T0});function Te(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{n!=null&&A(n.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}const kq=zp,Fq=$w,_q=Uw,Wq=Bw,$q=_p;class Uq extends y{constructor(){super();this.blockSize=48,this.firstUse=!0,this.data=new p(this,Ji())}write(e,t,n){this.firstUse&&(this.firstUse=!1,oe().get("IS_NODE")&&ic(`
|
|
============================
|
|
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){let s;if(t==="string"&&n!=null&&n.length>0&&qi(n[0])){const i=n.map(o=>Hd(o));s=this.write(i,e,t)}else 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 sr(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=>rh(s))}catch(s){throw new Error("Failed to decode encoded string bytes into utf-8")}return wt(e.shape,e.dtype,n)}makeOutput(e,t,n){const s=this.write(e,t,n);return Ji().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=Kn();e();const n=Kn()-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){Te(e,"stridedSlice");const i=ip(t,n,s);if(i.some(c=>c===0))return sn([],i);const o=wt(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=wt([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]=tt(e,o,a).reshape(s);return c}reverse(e,t){Te(e,"reverse");const n=wt(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 Te(e,"neg"),X(Ce(-1),e)}addN(e){Te(e,"addN");const t=e.map(i=>this.readSync(i.dataId)),n=wt(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=qe([t],e.shape),s=es(e,n),i=vn(s.shape,n),o=Re(e,s.reshape(i)),a=Is(o),c=this.sum(a,n).reshape(i);return We(a,c)}pow(e,t){return Te([e,t],"pow"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>Math.pow(n,s))}floorDiv(e,t){Te([e,t],"floorDiv");const n=(i,o)=>Math.floor(i/o),s="int32";return this.broadcastedBinaryOp(e,t,s,n)}sum(e,t){Te(e,"sum"),Xn("sum",t,e.rank);const[n,s]=An(e.shape,t),i=$n(e.dtype,"int32"),o=dt(n,i),a=P(s),c=this.readSync(o.dataId),h=this.readSync(e.dataId);for(let d=0;d<c.length;++d){const m=d*a;let f=0;for(let b=0;b<a;++b)f+=h[m+b];c[d]=f}return o}prod(e,t){Te(e,"sum");const[n,s]=An(e.shape,t),i=$n(e.dtype,"int32"),o=dt(n,i),a=P(s),c=this.readSync(o.dataId),h=this.readSync(e.dataId);for(let d=0;d<c.length;++d){const m=d*a;let f=1;for(let b=0;b<a;++b)f*=h[m+b];c[d]=f}return o}unsortedSegmentSum(e,t,n){Te(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=Ce(o,"int32"),c=Qs(a,t).asType("float32"),h=c.mul(e).sum(0);s.push(h)}return ts(s)}argMin(e,t){Te(e,"argMin");const n=[t];Xn("argMin",n,e.rank);const[s,i]=An(e.shape,n),o=dt(s,"int32"),a=P(i),c=this.readSync(o.dataId),h=this.readSync(e.dataId);for(let d=0;d<c.length;++d){const m=d*a;let f=h[m],b=0;for(let w=0;w<a;++w){const L=h[m+w];L<f&&(f=L,b=w)}c[d]=b}return o}argMax(e,t){Te(e,"argMax");const n=[t];Xn("argMax",n,e.rank);const[s,i]=An(e.shape,n),o=dt(s,"int32"),a=P(i),c=this.readSync(o.dataId),h=this.readSync(e.dataId);for(let d=0;d<c.length;++d){const m=d*a;let f=h[m],b=0;for(let w=0;w<a;++w){const L=h[m+w];L>f&&(f=L,b=w)}c[d]=b}return o}cumsum(e,t,n,s){if(Te(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=$n(e.dtype,"int32"),o=dt(e.shape,i),a=this.readSync(o.dataId),c=this.readSync(e.dataId),h=e.shape[e.rank-1],d=s?(m,f)=>m+h-f-1:(m,f)=>m+f;for(let m=0;m<c.length;m+=h)for(let f=0;f<h;f++){const b=d(m,f);if(f===0)a[b]=n?0:c[b];else{const w=d(m,f-1);a[b]=n?c[w]+a[w]:c[b]+a[w]}}return o}equal(e,t){return Te([e,t],"equal"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n===s?1:0)}notEqual(e,t){return Te([e,t],"notEqual"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n!==s?1:0)}less(e,t){return Te([e,t],"less"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n<s?1:0)}lessEqual(e,t){return Te([e,t],"lessEqual"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n<=s?1:0)}greater(e,t){return Te([e,t],"greater"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n>s?1:0)}greaterEqual(e,t){return Te([e,t],"greaterEqual"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n>=s?1:0)}logicalAnd(e,t){return Te([e,t],"logicalAnd"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n&&s)}logicalOr(e,t){return Te([e,t],"logicalOr"),this.broadcastedBinaryOp(e,t,"bool",(n,s)=>n||s)}select(e,t,n){Te([e,t,n],"select");const s=this.readSync(e.dataId),i=this.readSync(t.dataId),o=this.readSync(n.dataId),a=dt(t.shape,$n(t.dtype,n.dtype)),c=this.readSync(a.dataId);let h=0;const d=e.rank===0||e.rank>1||t.rank===1?1:P(t.shape.slice(1));for(let m=0;m<s.length;m++)for(let f=0;f<d;f++)s[m]===1?c[h++]=i[m]:c[h++]=o[m];return a}where(e){Te([e],"where");const t=this.readSync(e.dataId);return $q(e.shape,t)}topk(e,t,n){Te(e,"topk");const s=this.readSync(e.dataId);return Wq(s,e.shape,e.dtype,t,n)}min(e,t){Te(e,"min"),Xn("min",t,e.rank);const[n,s]=An(e.shape,t),i=dt(n,e.dtype),o=P(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 f=0;f<o;++f){const b=c[d+f];b<m&&(m=b)}a[h]=m}return i}minimum(e,t){return Te([e,t],"minimum"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>Math.min(n,s))}mod(e,t){return Te([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 Te([e,t],"maximum"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>Math.max(n,s))}all(e,t){Te(e,"all"),Xn("all",t,e.rank);const[n,s]=An(e.shape,t),i=dt(n,e.dtype),o=P(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 f=0;f<o;++f){const b=c[d+f];m=m&&b}a[h]=m}return i}any(e,t){Te(e,"any"),Xn("any",t,e.rank);const[n,s]=An(e.shape,t),i=dt(n,e.dtype),o=P(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 f=0;f<o;++f){const b=c[d+f];m=m||b}a[h]=m}return i}squaredDifference(e,t){return Te([e,t],"squaredDifference"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>{const i=n-s;return i*i})}eluDer(e,t){Te([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 Te([e,t],"atan2"),this.broadcastedBinaryOp(e,t,e.dtype,(n,s)=>Math.atan2(n,s))}tile(e,t){return Te(e,"tile"),_q(this.bufferSync(e),t)}gather(e,t,n){Te([e,t],"gather");const s=e.shape.slice(),i=this.readSync(t.dataId);s[n]=i.length;const o=wt(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){Te([e],"batchToSpaceND");const s=t.reduce((d,m)=>d*m),i=Mh(e.shape,t,s),o=Ph(i.length,t.length),a=zh(e.shape,t,s),c=vw(n,t.length),h=Nw(a,n,t.length);return Ye(e.reshape(i),o).reshape(a).slice(c,h)}pool3d(e,t,n){Te(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,f=t.effectiveFilterWidth,b=t.padInfo.front,w=t.padInfo.top,L=t.padInfo.left,x=n==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,v=this.readSync(e.dataId),N=wt(t.outShape,e.dtype),O=N.values,E=t.outShape[1]*t.outShape[2]*t.outShape[3]*t.outShape[4],k=t.outShape[2]*t.outShape[3]*t.outShape[4],F=t.outShape[3]*t.outShape[4],U=t.outShape[4];for(let $=0;$<t.batchSize;++$){const Y=$*E,j=$*e.strides[0];for(let Z=0;Z<t.inChannels;++Z)for(let ie=0;ie<t.outDepth;++ie){const de=ie*s-b;let he=de;for(;he<0;)he+=a;const ue=Math.min(t.inDepth,d+de),me=Y+ie*k;for(let ce=0;ce<t.outHeight;++ce){const ye=ce*i-w;let pe=ye;for(;pe<0;)pe+=c;const we=Math.min(t.inHeight,m+ye),Se=me+ce*F;for(let xe=0;xe<t.outWidth;++xe){const Oe=xe*o-L;let Ne=Oe;for(;Ne<0;)Ne+=h;const De=Math.min(t.inWidth,f+Oe),Ue=Se+xe*U;let ze=x,ht=0,it=0;for(let mt=he;mt<ue;mt+=a){const ut=j+mt*e.strides[1];for(let Ft=pe;Ft<we;Ft+=c){const rn=ut+Ft*e.strides[2];for(let Ut=Ne;Ut<De;Ut+=h){const _t=rn+Ut*e.strides[3],Wt=v[_t+Z];if(n==="max"&&Wt>ze?ze=Wt:n==="avg"&&(ht+=Wt,it++),isNaN(ze))break}if(isNaN(ze))break}if(isNaN(ze))break}const rt=Ue+Z;O[rt]=n==="avg"?ht/it:ze}}}}return N.toTensor()}avgPool3d(e,t){return Te(e,"avgPool3d"),this.pool3d(e,t,"avg").toFloat()}avgPool3dBackprop(e,t,n){Te([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,f=n.dilationWidth,b=n.effectiveFilterDepth,w=n.effectiveFilterHeight,L=n.effectiveFilterWidth,x=b-1-n.padInfo.front,v=L-1-n.padInfo.left,N=w-1-n.padInfo.top,O=wt(t.shape,"float32"),E=1/(a*c*h),k=this.bufferSync(e);for(let F=0;F<n.batchSize;++F)for(let U=0;U<n.inChannels;++U)for(let $=0;$<n.inDepth;++$)for(let Y=0;Y<n.inHeight;++Y)for(let j=0;j<n.inWidth;++j){const Z=$-x,ie=Y-N,de=j-v;let he=0;for(let ue=0;ue<b;ue+=d){const me=(Z+ue)/s;if(me<0||me>=n.outDepth||Math.floor(me)!==me)continue;for(let ce=0;ce<w;ce+=m){const ye=(ie+ce)/i;if(ye<0||ye>=n.outHeight||Math.floor(ye)!==ye)continue;for(let pe=0;pe<L;pe+=f){const we=(de+pe)/o;if(we<0||we>=n.outWidth||Math.floor(we)!==we)continue;const Se=k.get(F,me,ye,we,U);he+=Se}}}O.set(he*E,F,$,Y,j,U)}return O.toTensor()}maxPool3d(e,t){return Te(e,"maxPool3d"),this.pool3d(e,t,"max").toFloat()}maxPool3dPositions(e,t){const n=wt(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,f=t.effectiveFilterWidth,b=t.padInfo.front,w=t.padInfo.top,L=t.padInfo.left,x=this.bufferSync(e);for(let v=0;v<t.batchSize;++v)for(let N=0;N<t.inChannels;++N)for(let O=0;O<t.outDepth;++O){const E=O*s-b;let k=E;for(;k<0;)k+=a;const F=Math.min(t.inDepth,d+E);for(let U=0;U<t.outHeight;++U){const $=U*i-w;let Y=$;for(;Y<0;)Y+=c;const j=Math.min(t.inHeight,m+$);for(let Z=0;Z<t.outWidth;++Z){const ie=Z*o-L;let de=ie;for(;de<0;)de+=h;const he=Math.min(t.inWidth,f+ie);let ue=Number.NEGATIVE_INFINITY,me=-1;for(let ce=k;ce<F;ce+=a){const ye=ce-E;for(let pe=Y;pe<j;pe+=c){const we=pe-$;for(let Se=de;Se<he;Se+=h){const xe=Se-ie,Oe=x.get(v,ce,pe,Se,N);Oe>=ue&&(ue=Oe,me=ye*m*f+we*m+xe)}}}n.set(me,v,O,U,Z,N)}}}return n.toTensor()}maxPool3dBackprop(e,t,n,s){Te([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,f=s.effectiveFilterDepth,b=s.effectiveFilterHeight,w=s.effectiveFilterWidth,L=f-1-s.padInfo.front,x=w-1-s.padInfo.left,v=b-1-s.padInfo.top,N=wt(t.shape,"float32"),O=this.bufferSync(i),E=this.bufferSync(e);for(let k=0;k<s.batchSize;++k)for(let F=0;F<s.inChannels;++F)for(let U=0;U<s.inDepth;++U)for(let $=0;$<s.inHeight;++$)for(let Y=0;Y<s.inWidth;++Y){const j=U-L,Z=$-v,ie=Y-x;let de=0;for(let he=0;he<f;he+=h){const ue=(j+he)/o;if(ue<0||ue>=s.outDepth||Math.floor(ue)!==ue)continue;for(let me=0;me<b;me+=d){const ce=(Z+me)/a;if(ce<0||ce>=s.outHeight||Math.floor(ce)!==ce)continue;for(let ye=0;ye<w;ye+=m){const pe=(ie+ye)/c;if(pe<0||pe>=s.outWidth||Math.floor(pe)!==pe)continue;const we=f*b*w-1-O.get(k,ue,ce,pe,F),Se=he*b*w+me*w+ye,xe=we===Se?1:0;if(xe===0)continue;const Oe=E.get(k,ue,ce,pe,F);de+=Oe*xe}}}N.set(de,k,U,$,Y,F)}return N.toTensor()}resizeBilinear(e,t,n,s){Te(e,"resizeBilinear");const[i,o,a,c]=e.shape,h=this.readSync(e.dataId),d=new Float32Array(P([i,t,n,c])),m=[s&&t>1?o-1:o,s&&n>1?a-1:a],f=[s&&t>1?t-1:t,s&&n>1?n-1:n];let b=0;const w=m[0]/f[0],L=m[1]/f[1];for(let x=0;x<i;x++)for(let v=0;v<t;v++){const N=w*v,O=Math.floor(N),E=N-O,k=Math.min(o-1,Math.ceil(N)),F=x*e.strides[0]+O*e.strides[1],U=x*e.strides[0]+k*e.strides[1];for(let $=0;$<n;$++){const Y=L*$,j=Math.floor(Y),Z=Y-j,ie=Math.min(a-1,Math.ceil(Y)),de=F+j*e.strides[2],he=U+j*e.strides[2],ue=F+ie*e.strides[2],me=U+ie*e.strides[2];for(let ce=0;ce<c;ce++){const ye=h[de+ce],pe=h[he+ce],we=h[ue+ce],Se=h[me+ce],xe=ye+(we-ye)*Z,Oe=pe+(Se-pe)*Z,Ne=xe+(Oe-xe)*E;d[b++]=Ne}}}return sn(d,[i,t,n,c])}resizeBilinearBackprop(e,t,n){Te([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],f=[n&&c>1?c-1:c,n&&h>1?h-1:h],b=m[0]/f[0],w=m[1]/f[1],L=this.readSync(e.dataId);let x=0;for(let v=0;v<s;v++){const N=v*t.strides[0];for(let O=0;O<c;O++){const E=O*b,k=Math.floor(E),F=Math.min(Math.ceil(E),i-1),U=N+k*t.strides[1],$=N+F*t.strides[1],Y=E-k,j=1-Y;for(let Z=0;Z<h;Z++){const ie=Z*w,de=Math.floor(ie),he=Math.min(Math.ceil(ie),o-1),ue=ie-de,me=1-ue,ce=U+de*t.strides[2],ye=U+he*t.strides[2],pe=$+de*t.strides[2],we=$+he*t.strides[2],Se=j*me,xe=j*ue,Oe=Y*me,Ne=Y*ue;for(let De=0;De<a;De++){const Ue=L[x++];d[ce+De]+=Ue*Se,d[ye+De]+=Ue*xe,d[pe+De]+=Ue*Oe,d[we+De]+=Ue*Ne}}}}return tc(d,[s,o,i,a],t.dtype)}resizeNearestNeighbor(e,t,n,s){Te(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],f=[s&&t>1?t-1:t,s&&n>1?n-1:n],b=m[0]/f[0],w=m[1]/f[1];let L=0;for(let x=0;x<i;x++){const v=x*e.strides[0];for(let N=0;N<t;N++){const O=b*N,E=Math.min(o-1,s?Math.round(O):Math.floor(O)),k=v+E*e.strides[1];for(let F=0;F<n;F++){const U=w*F,$=Math.min(a-1,s?Math.round(U):Math.floor(U)),Y=k+$*e.strides[2];for(let j=0;j<c;j++){const Z=h[Y+j];d[L++]=Z}}}}return sn(d,[i,t,n,c],e.dtype)}resizeNearestNeighborBackprop(e,t,n){Te([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),f=[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=f[0]/b[0],L=f[1]/b[1],x=1/w,v=1/L,N=Math.ceil(x)*2+2,O=Math.ceil(v)*2+2;for(let E=0;E<s;E++){const k=E*t.strides[0];for(let F=0;F<i;F++){const U=k+F*t.strides[1],$=Math.floor(F*x),Y=Math.floor($-N/2);for(let j=0;j<o;j++){const Z=U+j*t.strides[2],ie=Math.floor(j*v),de=Math.floor(ie-O/2);for(let he=0;he<a;he++){let ue=0;for(let me=0;me<N;me++){const ce=me+Y;if(ce<0||ce>=c)continue;const ye=k+ce*e.strides[1],pe=ce*w,we=Math.min(i-1,n?Math.round(pe):Math.floor(pe));if(F!==we)continue;for(let Se=0;Se<O;Se++){const xe=Se+de;if(xe<0||xe>=h)continue;const Oe=ye+xe*e.strides[2],Ne=xe*L,De=Math.min(o-1,n?Math.round(Ne):Math.floor(Ne));j===De&&(ue+=m[Oe+he])}}d[Z+he]=ue}}}}return tc(d,t.shape,t.dtype)}localResponseNormalization4D(e,t,n,s,i){Te(e,"localResponseNormalization4D");const o=e.shape[3],a=o-1,c=this.readSync(e.dataId),h=e.size,d=new Float32Array(h);function m(f){const b=f%o;let w=f-b+Math.max(0,b-t);const L=f-b+Math.min(b+t,a);let x=0;for(;w<=L;w++){const v=c[w];x+=v*v}return x}for(let f=0;f<h;f++){const b=m(f),w=c[f]*Math.pow(n+s*b,-i);d[f]=w}return tc(d,e.shape)}LRNGrad(e,t,n,s,i,o,a){Te(e,"LRNGrad");const c=e.shape[3],h=this.readSync(e.dataId),d=this.readSync(t.dataId),m=this.readSync(n.dataId),f=new Float32Array(e.size),b=e.size;for(let w=0;w<b;w++){const L=w%c,x=w-L+Math.max(0,L-s),v=w-L+Math.min(c,L+s+1);let N=0;for(let O=x;O<v;O++)N+=Math.pow(d[O],2);N=o*N+i;for(let O=x;O<v;O++){let E=-2*o*a*d[O]*m[w]/N;w===O&&(E+=Math.pow(N,-a)),E*=h[w],f[O]+=E}}return tc(f,e.shape)}multinomial(e,t,n,s){Te(e,"multinomial");const i=t?e:Vo(e),o=i.shape[0],a=i.shape[1],c=dt([o,n],"int32"),h=this.readSync(c.dataId),d=this.readSync(i.dataId);for(let m=0;m<o;++m){const f=m*a,b=new Float32Array(a-1);b[0]=d[f];for(let x=1;x<b.length;++x)b[x]=b[x-1]+d[f+x];const w=Za(s.toString()),L=m*n;for(let x=0;x<n;++x){const v=w();h[L+x]=b.length;for(let N=0;N<b.length;N++)if(v<b[N]){h[L+x]=N;break}}}return c}oneHot(e,t,n,s){Te(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 zr(i,[e.size,t],"int32")}nonMaxSuppression(e,t,n,s,i){Te(e,"nonMaxSuppression");const o=this.readSync(e.dataId),a=this.readSync(t.dataId);return kq(o,a,n,s,i)}depthToSpace(e,t,n){A(n==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${n}`),A(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),f=new Float32Array(s*c*h*d);let b=0;for(let w=0;w<s;++w)for(let L=0;L<c;++L){const x=Math.floor(L/t),v=L%t;for(let N=0;N<h;++N){const O=Math.floor(N/t),E=N%t,k=(v*t+E)*d;for(let F=0;F<d;++F){const U=F+k,$=U+a*(O+o*(x+i*w));f[b++]=m[$]}}}return tc(f,[s,c,h,d])}broadcastedBinaryOp(e,t,n,s){const i=nt(e.shape,t.shape),o=wt(i,n),a=this.readSync(e.dataId),c=this.readSync(t.dataId),h=Uo(e.shape,i),d=Uo(t.shape,i),m=o.values;if(h.length+d.length===0)for(let f=0;f<m.length;++f)m[f]=s(a[f%a.length],c[f%c.length]);else{const f=this.bufferSync(e),b=this.bufferSync(t);for(let w=0;w<m.length;++w){const L=o.indexToLoc(w),x=L.slice(-e.rank);h.forEach(E=>x[E]=0);const v=f.locToIndex(x),N=L.slice(-t.rank);d.forEach(E=>N[E]=0);const O=b.locToIndex(N);m[w]=s(a[v],c[O])}}return o.toTensor()}split(e,t,n){return Fq(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],[f,b]=s,w=wt([m,f,b,d],"float32"),L=this.readSync(t.dataId),x=this.readSync(n.dataId),v=this.readSync(e.dataId),N=e.strides,O=w.strides;for(let E=0;E<m;E++){const k=E*4,F=L[k],U=L[k+1],$=L[k+2],Y=L[k+3],j=x[E];if(j>=a)continue;const Z=f>1?($-F)*(c-1)/(f-1):0,ie=b>1?(Y-U)*(h-1)/(b-1):0;for(let de=0;de<f;de++){const he=f>1?F*(c-1)+de*Z:.5*(F+$)*(c-1);if(he<0||he>c-1){for(let ue=0;ue<b;ue++)for(let me=0;me<d;me++){const ce=me+ue*O[2]+de*O[1]+E*O[0];w.values[ce]=o}continue}if(i==="bilinear"){const ue=Math.floor(he),me=Math.ceil(he),ce=he-ue;for(let ye=0;ye<b;ye++){const pe=b>1?U*(h-1)+ye*ie:.5*(U+Y)*(h-1);if(pe<0||pe>h-1){for(let Oe=0;Oe<d;Oe++){const Ne=Oe+ye*O[2]+de*O[1]+E*O[0];w.values[Ne]=o}continue}const we=Math.floor(pe),Se=Math.ceil(pe),xe=pe-we;for(let Oe=0;Oe<d;Oe++){let Ne=Oe+we*N[2]+ue*N[1]+j*N[0];const De=v[Ne];Ne=Oe+Se*N[2]+ue*N[1]+j*N[0];const Ue=v[Ne];Ne=Oe+we*N[2]+me*N[1]+j*N[0];const ze=v[Ne];Ne=Oe+Se*N[2]+me*N[1]+j*N[0];const ht=v[Ne],it=De+(Ue-De)*xe,rt=ze+(ht-ze)*xe;Ne=Oe+ye*O[2]+de*O[1]+E*O[0],w.values[Ne]=it+(rt-it)*ce}}}else for(let ue=0;ue<b;++ue){const me=b>1?U*(h-1)+ue*ie:.5*(U+Y)*(h-1);if(me<0||me>h-1){for(let pe=0;pe<d;pe++){const we=pe+ue*O[2]+de*O[1]+E*O[0];w.values[we]=o}continue}const ce=Math.round(me),ye=Math.round(he);for(let pe=0;pe<d;pe++){const we=pe+ce*N[2]+ye*N[1]+j*N[0],Se=pe+ue*O[2]+de*O[1]+E*O[0];w.values[Se]=v[we]}}}}return w.toTensor()}sparseToDense(e,t,n,s){const{sliceRank:i,numUpdates:o,sliceSize:a,strides:c,outputSize:h}=Pa(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]=np(e,t);if(o===0)return sn([],i,e.dtype);const h=new an([o,a],e.dtype),d=this.readSync(t.dataId),m=this.readSync(e.dataId);for(let f=0;f<o;f++){const b=[];let w=0;for(let L=0;L<s;L++){const x=d[f*s+L];w+=x*c[L],b.push(x)}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[f*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}=Pa(t,e,n),h=Ce(0),d=!0;return this.scatter(e,t,n,c,o,i,s,a,h,d)}onesLike(e){if(e.dtype==="string")throw new Error("onesLike is not supported for string tensors");return Ya(e.shape,1,e.dtype)}zerosLike(e){const t=ws(e.dtype,P(e.shape));return this.makeOutput(t,e.shape,e.dtype)}linspace(e,t,n){return _w(e,t,n)}scatter(e,t,n,s,i,o,a,c,h,d){const m=[s/i,i],f=this.readSync(e.dataId),b=this.readSync(t.dataId);if(s===0)return sn([],n,t.dtype);const w=new an(m,t.dtype);w.values.fill(this.readSync(h.dataId)[0]);for(let L=0;L<o;L++){const x=[];let v=0;for(let N=0;N<a;N++){const O=f[L*a+N];x.push(O),v+=O*c[N]}if(v<0||v>=s/i)throw new Error(`Invalid indices: ${x} does not index into ${n}`);for(let N=0;N<i;N++)d?w.values[v*i+N]+=b[L*i+N]:w.values[v*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 Bq=e=>{const{x:t}=e.inputs,n=e.backend;let s=new Float32Array(P(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],f=h[d];s[d]=Math.hypot(m,f)}}return n.makeOutput(s,t.shape,"float32")},Mq={kernelName:ud,backendName:"cpu",kernelFunc:Bq};function Qr(e){return(t,n,s,i,o)=>{const a=nt(t,n),c=a.length,h=je(a),d=P(a),m=bt(o,d),f=t.length,b=n.length,w=je(t),L=je(n),x=Uo(t,a),v=Uo(n,a);if(x.length+v.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 O=vo(N,c,h),E=O.slice(-f);x.forEach($=>E[$]=0);const k=Ws(E,f,w),F=O.slice(-b);v.forEach($=>F[$]=0);const U=Ws(F,b,L);m[N]=e(s[k],i[U])}return[m,a]}}function ui(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 Pq={kernelName:fd,backendName:"cpu",kernelFunc:ui};function Qo(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 zq={kernelName:kl,backendName:"cpu",kernelFunc:Qo};function fu(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 Vq={kernelName:Fd,backendName:"cpu",kernelFunc:fu};function gu(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{dtype:o}=s;if(o==="complex64"){if(i.dtype==="complex64")return Qo({inputs:{x:i},backend:n});const a=dt(i.shape),c=gu({inputs:{x:i},backend:n,attrs:{dtype:"float32"}}),h=ui({inputs:{real:c,imag:a},backend:n});return a.dispose(),n.disposeIntermediateTensorInfo(c),h}if(i.dtype==="complex64"){const a=fu({inputs:{input:i},backend:n}),c=gu({inputs:{x:a},backend:n,attrs:{dtype:o}});return n.disposeIntermediateTensorInfo(a),c}if(!Ta(i.dtype,o)){const a=Qo({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=Er([0],i.dtype),[h,d]=Qr((m,f)=>m!==f?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 Gq={kernelName:Na,backendName:"cpu",kernelFunc:gu};function gc(e,t,n,s){return n==null?({inputs:i,backend:o})=>{const{a,b:c}=i,h=o;Te([a,c],e);const d=h.data.get(a.dataId).values,m=h.data.get(c.dataId).values,f=s||a.dtype,[b,w]=t(a.shape,c.shape,d,m,f);return h.makeTensorInfo(w,f,b)}:({inputs:i,backend:o})=>{const{a,b:c}=i,h=o;if(a.dtype==="complex64"||c.dtype==="complex64"){const d=gu({inputs:{x:a},backend:h,attrs:{dtype:"complex64"}}),m=h.data.get(d.dataId),f=m.complexTensorInfos.real,b=m.complexTensorInfos.imag,w=h.data.get(f.dataId).values,L=h.data.get(b.dataId).values,x=gu({inputs:{x:c},backend:h,attrs:{dtype:"complex64"}}),v=h.data.get(x.dataId),N=v.complexTensorInfos.real,O=v.complexTensorInfos.imag,E=h.data.get(N.dataId).values,k=h.data.get(O.dataId).values,[F,U,$]=n(a.shape,c.shape,w,L,E,k),Y=h.makeTensorInfo($,"float32",F),j=h.makeTensorInfo($,"float32",U),Z=ui({inputs:{real:Y,imag:j},backend:h});return h.disposeIntermediateTensorInfo(d),h.disposeIntermediateTensorInfo(x),h.disposeIntermediateTensorInfo(Y),h.disposeIntermediateTensorInfo(j),Z}else{const d=h.data.get(a.dataId).values,m=h.data.get(c.dataId).values,f=s||a.dtype,[b,w]=t(a.shape,c.shape,d,m,f);return h.makeTensorInfo(w,f,b)}}}function WS(e){return(t,n,s,i,o,a)=>{const c=nt(t,n),h=P(c),d=c.length,m=je(c),f=bt("float32",h),b=bt("float32",h),w=Uo(t,c),L=Uo(n,c),x=sr(s,i),v=sr(o,a),N=t.length,O=je(t),E=n.length,k=je(n);if(w.length+L.length===0)for(let F=0;F<f.length;F++){const U=F%x.length,$=F%v.length,Y=e(x[U*2],x[U*2+1],v[$*2],v[$*2+1]);f[F]=Y.real,b[F]=Y.imag}else for(let F=0;F<f.length;F++){const U=vo(F,d,m),$=U.slice(-N);w.forEach(de=>$[de]=0);const Y=Ws($,N,O),j=U.slice(-E);L.forEach(de=>j[de]=0);const Z=Ws(j,E,k),ie=e(x[Y*2],x[Y*2+1],v[Z*2],v[Z*2+1]);f[F]=ie.real,b[F]=ie.imag}return[f,b,c]}}const v0=Qr((e,t)=>e+t),Yq=WS((e,t,n,s)=>({real:e+n,imag:t+s})),yu=gc(Co,v0,Yq),Hq={kernelName:Co,backendName:"cpu",kernelFunc:yu};function yc(e){return(t,n,s)=>{const i=bt(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(Te(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=P(a.shape),m=n||a.dtype,f=ws(m,d);for(let b=0;b<d;++b)f[b]=t(h[b],i);return c.makeTensorInfo(a.shape,m,f)}}function bc(e,t,n){return({inputs:s,attrs:i,backend:o})=>{const{x:a}=s;if(Te(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 N0=yc(e=>Math.ceil(e)),qq=bc(xl,N0),jq={kernelName:xl,backendName:"cpu",kernelFunc:qq};const C0=yc(e=>Math.exp(e)),Kq=bc(Rl,C0),Xq={kernelName:Rl,backendName:"cpu",kernelFunc:Kq};const R0=yc(e=>Math.expm1(e)),Jq=bc(Ol,R0),Zq={kernelName:Ol,backendName:"cpu",kernelFunc:Jq};const O0=yc(e=>Math.floor(e)),Qq=bc(El,O0),e4={kernelName:El,backendName:"cpu",kernelFunc:Qq};const E0=yc(e=>Math.log(e)),t4=bc($l,E0),n4={kernelName:$l,backendName:"cpu",kernelFunc:t4};function D0(e,t,n,s){const i=bt(s,P(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 k0=Qr((e,t)=>e*t),s4=WS((e,t,n,s)=>({real:e*n-t*s,imag:e*s+t*n})),F0=gc(Oa,k0,s4),i4={kernelName:Oa,backendName:"cpu",kernelFunc:F0};const _0=Qr((e,t)=>e!==t?1:0),r4=gc(zl,_0,null,"bool"),o4={kernelName:zl,backendName:"cpu",kernelFunc:r4};const W0=yc(e=>1/Math.sqrt(e)),a4=bc(jl,W0),c4={kernelName:jl,backendName:"cpu",kernelFunc:a4};function $0(e,t,n,s,i){const o=Cb(s,t,n),a=P(n),c=je(s);if(o){const d=Rb(t,c);return e.subarray(d,d+a)}const h=bt(i,a);for(let d=0;d<a;++d){const m=n.length,f=je(n),b=vo(d,m,f),w=b.map((x,v)=>x+t[v]),L=Ws(w,s.length,c);h[d]=e[L]}return h}function $S(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{begin:o,size:a}=s;Te(i,"slice");const[c,h]=rp(i,o,a);Nb(i,c,h);const d=n.data.get(i.dataId).values,m=$0(d,c,h,i.shape,i.dtype);return n.makeTensorInfo(h,i.dtype,m)}const l4={kernelName:_d,backendName:"cpu",kernelFunc:$S};const U0=Qr((e,t)=>{const n=e-t;return n*n}),h4=gc(Da,U0),u4={kernelName:Da,backendName:"cpu",kernelFunc:h4};const B0=Qr((e,t)=>e-t),d4=WS((e,t,n,s)=>({real:e-n,imag:t-s})),M0=gc(ka,B0,d4),p4={kernelName:ka,backendName:"cpu",kernelFunc:M0};function US(e,t,n,s,i){const o=t.length,a=P(t),c=je(t),h=je(i),d=bt(n,P(i));for(let m=0;m<a;++m){const f=vo(m,o,c),b=new Array(f.length);for(let L=0;L<b.length;L++)b[L]=f[s[L]];const w=Ws(b,o,h);d[w]=e[m]}return d}function P0(e,t,n,s){const i=qe(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 an(o,s,e),d=[],m=o[0]===1&&o[2]===1;for(let L=0;L<n[i];L++){let x;if(m)x=e[L].toString();else{const v=[];for(let N=0;N<o[0];N++)for(let O=0;O<o[2];O++)v.push(h.get(N,L,O));x=v.join(",")}if(a[x]!==void 0)c[L]=a[x];else{const v=Object.keys(a).length;a[x]=v,c[L]=v,d.push(L)}}const f=o.slice();f[1]=Object.keys(a).length;const b=new an(f,s);d.forEach((L,x)=>{for(let v=0;v<o[0];v++)for(let N=0;N<o[2];N++)b.set(h.get(v,L,N),v,x,N)});const w=n.slice();return w[i]=f[1],{outputValues:b.values,outputShape:w,indices:c}}var m4=Object.freeze({__proto__:null,simpleAbsImpl:A0,addImpl:v0,ceilImpl:N0,expImpl:C0,expm1Impl:R0,floorImpl:O0,logImpl:E0,maxImpl:D0,multiplyImpl:k0,notEqualImpl:_0,rsqrtImpl:W0,sliceImpl:$0,squaredDifferenceImpl:U0,subImpl:B0,transposeImpl:US,uniqueImpl:P0});const f4="2.7.0";kb("cpu",()=>new Uq,1);const z0=xt(Nl,e=>e>=0?e:Math.exp(e)-1),g4={kernelName:Nl,backendName:"cpu",kernelFunc:z0};const y4=Qr((e,t)=>e<0?t*e:e);function V0(e){const{inputs:t,backend:n}=e,{x:s,alpha:i}=t;Te([s,i],"prelu");const o=n.data.get(s.dataId).values,a=n.data.get(i.dataId).values,[c,h]=y4(s.shape,i.shape,o,a,s.dtype);return n.makeTensorInfo(h,s.dtype,c)}const b4={kernelName:kd,backendName:"cpu",kernelFunc:V0};const G0=xt(Gl,e=>Math.max(0,e)),w4={kernelName:Gl,backendName:"cpu",kernelFunc:G0};const Y0=xt(Hl,e=>Math.min(Math.max(0,e),6)),L4={kernelName:Hl,backendName:"cpu",kernelFunc:Y0};function BS(e,t,n,s){if(n==="linear")return Qo({inputs:{x:t},backend:e});if(n==="relu")return G0({inputs:{x:t},backend:e});if(n==="elu")return z0({inputs:{x:t},backend:e});if(n==="relu6")return Y0({inputs:{x:t},backend:e});if(n==="prelu")return V0({inputs:{x:t,alpha:s},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function ki(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{shape:o}=s,a=P(i.shape),c=Gt(o,a),h=P(c);A(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,f=d.complexTensorInfos.imag;m.shape=c,f.shape=c}return{dataId:i.dataId,shape:c,dtype:i.dtype}}const S4={kernelName:Yl,backendName:"cpu",kernelFunc:ki};function H0(e){const{inputs:t,backend:n,attrs:s}=e,{a:i,b:o}=t,{transposeA:a,transposeB:c}=s;Te([i,o],"matMul");const h=i.shape.length,d=o.shape.length,m=a?i.shape[h-2]:i.shape[h-1],f=c?o.shape[d-1]:o.shape[d-2],b=a?i.shape[h-1]:i.shape[h-2],w=c?o.shape[d-2]:o.shape[d-1],L=i.shape.slice(0,-2),x=o.shape.slice(0,-2),v=P(L),N=P(x),O=v===N||v===1||N===1;A(h>=2&&d>=2&&O,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${L}) and (${x}).`);const E=v>N?i.shape.slice(0,-2):o.shape.slice(0,-2),k=E.concat([b,w]);A(m===f,()=>`Error in matMul: inner shapes (${m}) and (${f}) of Tensors with shapes ${i.shape} and ${o.shape} and transposeA=${a} and transposeB=${c} must match.`);const F=a?[v,m,b]:[v,b,m],U=c?[N,w,f]:[N,f,w],$=ki({inputs:{x:i},backend:n,attrs:{shape:F}}),Y=ki({inputs:{x:o},backend:n,attrs:{shape:U}}),j=a?$.shape[1]:$.shape[2],Z=a?$.shape[2]:$.shape[1],ie=c?Y.shape[1]:Y.shape[2],de=Math.max(v,N),he=n.data.get($.dataId).values,ue=n.data.get(Y.dataId).values,me=je($.shape),ce=je(Y.shape),[ye,pe,we]=a?[me[0],1,me[1]]:[me[0],me[1],1],[Se,xe,Oe]=c?[1,ce[1],ce[0]]:[ce[1],1,ce[0]],Ne=Z*ie,De=wt([de,Z,ie],$.dtype),Ue=De.values,ze=n.blockSize;for(let ht=0;ht<de;ht++)for(let it=0;it<Z;it+=ze)for(let rt=0;rt<ie;rt+=ze)for(let mt=0;mt<j;mt+=ze){const ut=Math.min(it+ze,Z),Ft=Math.min(rt+ze,ie),rn=Math.min(mt+ze,j);for(let Ut=it;Ut<ut;Ut++)for(let _t=rt;_t<Ft;_t++){let Wt=0;for(let Jt=mt;Jt<rn;Jt++){const Rn=Math.min(ht,v-1)*ye,fr=Math.min(ht,N-1)*Oe,On=he[Rn+Ut*pe+Jt*we],di=ue[Jt*Se+_t*xe+fr];Wt+=On*di}Ue[ht*Ne+(Ut*ie+_t)]+=Wt}}return n.disposeIntermediateTensorInfo($),n.disposeIntermediateTensorInfo(Y),n.makeTensorInfo(k,De.dtype,De.values)}const I4={kernelName:md,backendName:"cpu",kernelFunc:H0};function x4(e){const{inputs:t,backend:n,attrs:s}=e,{a:i,b:o,bias:a,preluActivationWeights:c}=t,{transposeA:h,transposeB:d,activation:m}=s;let f,b,w;const L=[],x=H0({inputs:{a:i,b:o},attrs:{transposeA:h,transposeB:d},backend:n});f=x,a&&(b=yu({inputs:{a:f,b:a},backend:n}),L.push(f),f=b),m&&(w=BS(n,f,m,c),L.push(f),f=w);for(const v of L)n.disposeIntermediateTensorInfo(v);return f}const T4={kernelName:Pd,backendName:"cpu",kernelFunc:x4};const A4=xt(gl,e=>Math.acos(e)),v4={kernelName:gl,backendName:"cpu",kernelFunc:A4};const N4=xt(yl,e=>Math.acosh(e)),C4={kernelName:yl,backendName:"cpu",kernelFunc:N4};const R4=xt(bl,e=>Math.asin(e)),O4={kernelName:bl,backendName:"cpu",kernelFunc:R4};const E4=xt(wl,e=>Math.asinh(e)),D4={kernelName:wl,backendName:"cpu",kernelFunc:E4};const k4=xt(Ll,e=>Math.atan(e)),F4={kernelName:Ll,backendName:"cpu",kernelFunc:k4};const _4=xt(Sl,e=>Math.atanh(e)),W4={kernelName:Sl,backendName:"cpu",kernelFunc:_4};function MS(e,t,n,s,i,o){const a=i.strideHeight,c=i.strideWidth,h=i.dilationHeight,d=i.dilationWidth,m=i.effectiveFilterHeight,f=i.effectiveFilterWidth,b=i.padInfo.top,w=i.padInfo.left,L=o==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=wt(i.outShape,n),v=x.values,N=i.outShape[1]*i.outShape[2]*i.outShape[3],O=i.outShape[2]*i.outShape[3],E=i.outShape[3];for(let k=0;k<i.batchSize;++k){const F=k*N,U=k*s[0];for(let $=0;$<i.inChannels;++$)for(let Y=0;Y<i.outHeight;++Y){const j=Y*a-b,Z=Math.max(0,j),ie=Math.min(i.inHeight,m+j),de=F+Y*O;for(let he=0;he<i.outWidth;++he){const ue=he*c-w,me=Math.max(0,ue),ce=Math.min(i.inWidth,f+ue);let ye=L,pe=0,we=0;for(let xe=Z;xe<ie;xe+=h){const Oe=U+xe*s[1];for(let Ne=me;Ne<ce;Ne+=d){const De=Oe+Ne*s[2],Ue=e[De+$];o==="max"&&Ue>ye?ye=Ue:o==="avg"&&(pe+=Ue,we++)}if(isNaN(ye))break}const Se=de+he*E+$;v[Se]=o==="avg"?pe/we:ye}}}return x}function q0(e,t,n,s,i=!1,o=!1){const a=wt(s.outShape,"int32"),c=s.strideHeight,h=s.strideWidth,d=s.dilationHeight,m=s.dilationWidth,f=s.effectiveFilterHeight,b=s.effectiveFilterWidth,w=s.padInfo.top,L=s.padInfo.left,x=wt(t,n,e);for(let v=0;v<s.batchSize;++v)for(let N=0;N<s.inChannels;++N)for(let O=0;O<s.outHeight;++O){const E=O*c-w;let k=E;for(;k<0;)k+=d;const F=Math.min(s.inHeight,f+E);for(let U=0;U<s.outWidth;++U){const $=U*h-L;let Y=$;for(;Y<0;)Y+=m;const j=Math.min(s.inWidth,b+$);let Z=Number.NEGATIVE_INFINITY,ie=-1;for(let de=k;de<F;de+=d){const he=de-E;for(let ue=Y;ue<j;ue+=m){const me=ue-$,ce=x.get(v,de,ue,N);ce>Z&&(Z=ce,i?ie=o?((v*s.inHeight+de)*s.inWidth+ue)*s.inChannels+N:(de*s.inWidth+ue)*s.inChannels+N:ie=he*b+me)}}a.set(ie,v,O,U,N)}}return a}function $4(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;Te(i,"avgPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:h}=s,d=1;A(cn(a,d),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${d}'`);const m=Un(i.shape,o,a,d,c,h);let f;if(m.filterWidth===1&&m.filterHeight===1&&ae(m.inShape,m.outShape))f=Qo({inputs:{x:i},backend:n});else{const b=n.data.get(i.dataId).values,w=je(i.shape),L=MS(b,i.shape,i.dtype,w,m,"avg");f=n.makeTensorInfo(m.outShape,i.dtype,L.values)}return f}const U4={kernelName:Il,backendName:"cpu",kernelFunc:$4};function B4(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o}=t,a=o;Te([i,o],"avgPoolBackprop");const{filterSize:c,strides:h,pad:d}=s,m=Un(a.shape,c,h,1,d),f=m.strideHeight,b=m.strideWidth,w=m.filterHeight,L=m.filterWidth,x=m.dilationHeight,v=m.dilationWidth,N=m.effectiveFilterHeight,O=m.effectiveFilterWidth,E=O-1-m.padInfo.left,k=N-1-m.padInfo.top,F=wt(a.shape,"float32"),U=1/(w*L),$=n.data.get(i.dataId).values,Y=wt(i.shape,"float32",$);for(let j=0;j<m.batchSize;++j)for(let Z=0;Z<m.inChannels;++Z)for(let ie=0;ie<m.inHeight;++ie)for(let de=0;de<m.inWidth;++de){const he=ie-k,ue=de-E;let me=0;for(let ce=0;ce<N;ce+=x){const ye=(he+ce)/f;if(ye<0||ye>=m.outHeight||Math.floor(ye)!==ye)continue;for(let pe=0;pe<O;pe+=v){const we=(ue+pe)/b;if(we<0||we>=m.outWidth||Math.floor(we)!==we)continue;const Se=Y.get(j,ye,we,Z);me+=Se}}F.set(me*U,j,ie,de,Z)}return n.makeTensorInfo(F.shape,F.dtype,F.values)}const M4={kernelName:pd,backendName:"cpu",kernelFunc:B4};function P4(e){const{inputs:t,backend:n,attrs:s}=e,{x:i,scale:o,offset:a,mean:c,variance:h}=t;A(c.shape.length===h.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),A(a==null||c.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),A(o==null||c.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),Te([i,c,h,o,a],"batchNorm");let{varianceEpsilon:d}=s;d==null&&(d=.001);const m=n.data.get(i.dataId).values,f=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]),x=new Float32Array(m.length),v=L.length,N=w.length,O=b.length,E=f.length;let k=0,F=0,U=0,$=0;for(let Y=0;Y<m.length;++Y)x[Y]=L[k++]+(m[Y]-f[F++])*w[U++]/Math.sqrt(b[$++]+d),k>=v&&(k=0),F>=E&&(F=0),U>=N&&(U=0),$>=O&&($=0);return n.makeTensorInfo(i.shape,i.dtype,x)}const z4={kernelName:Dl,backendName:"cpu",kernelFunc:P4};const V4=xt(Tl,(e,t)=>{const n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e}),G4={kernelName:Tl,backendName:"cpu",kernelFunc:V4};function _m(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 Y4={kernelName:vd,backendName:"cpu",kernelFunc:_m};function bu(e){const{inputs:t,backend:n,attrs:s}=e,{axis:i}=s,o=qe(i,t[0].shape)[0];let a=Zi(t.map(w=>w.shape),o);if(P(a)===0)return n.makeTensorInfo(a,t[0].dtype,[]);const c=t.filter(w=>P(w.shape)>0);if(c.length===1)return c[0];const h=c.map(w=>w.shape);if(dp(h,o),c[0].dtype==="complex64"){const w=c.map(O=>fu({inputs:{input:O},backend:n})),L=c.map(O=>_m({inputs:{input:O},backend:n})),x=bu({inputs:w,backend:n,attrs:{axis:o}}),v=bu({inputs:L,backend:n,attrs:{axis:o}}),N=ui({inputs:{real:x,imag:v},backend:n});return w.forEach(O=>n.disposeIntermediateTensorInfo(O)),L.forEach(O=>n.disposeIntermediateTensorInfo(O)),n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(v),N}const d=c.map(w=>{const L=P(w.shape.slice(o)),x=[-1,L];return ki({inputs:{x:w},backend:n,attrs:{shape:x}})});a=Zi(d.map(w=>w.shape),1);const m=bt(c[0].dtype,P(a));if(d[0].shape[0]===1){let w=0;d.forEach(L=>{const x=n.data.get(L.dataId).values,v=P(L.shape);m.set(x,w),w+=v})}else{let w=0;d.forEach(L=>{const x=n.data.get(L.dataId).values;let v=0;for(let N=0;N<L.shape[0];++N){const O=N*a[1]+w;for(let E=0;E<L.shape[1];++E)m[O+E]=x[v++]}w+=L.shape[1]})}const f=Zi(c.map(w=>w.shape),o),b=n.makeTensorInfo(f,t[0].dtype,m);return d.forEach(w=>n.disposeIntermediateTensorInfo(w)),b}const H4={kernelName:Al,backendName:"cpu",kernelFunc:bu};function j0(e){const{inputs:t,backend:n,attrs:s}=e,{x:i,filter:o}=t,{strides:a,pad:c,dataFormat:h,dilations:d,dimRoundingMode:m}=s;Te([i,o],"conv2d");const f=$r(h),b=Fn(i.shape,o.shape,a,d,c,m,!1,f),w=b.filterHeight,L=b.filterWidth,x=b.dilationHeight,v=b.dilationWidth,N=b.padInfo.left,O=b.padInfo.top,E=b.dataFormat==="channelsLast",k=new an(b.outShape,i.dtype),F=je(i.shape),U=je(o.shape),$=F[0],Y=E?F[1]:F[2],j=E?F[2]:1,Z=E?1:F[1],ie=k.strides[0],de=E?k.strides[1]:k.strides[2],he=E?k.strides[2]:1,ue=E?1:k.strides[1],me=n.data.get(i.dataId).values,ce=n.data.get(o.dataId).values,ye=k.values;for(let pe=0;pe<b.batchSize;++pe){const we=pe*$,Se=pe*ie;for(let xe=0;xe<b.outHeight;++xe){const Oe=Se+xe*de,Ne=xe*b.strideHeight-O;for(let De=0;De<w;++De){const Ue=Ne+De*x;if(Ue<0||Ue>=b.inHeight)continue;const ze=De*U[0],ht=we+Ue*Y;for(let it=0;it<b.outWidth;++it){const rt=Oe+it*he,mt=it*b.strideWidth-N;for(let ut=0;ut<L;++ut){const Ft=mt+ut*v;if(Ft<0||Ft>=b.inWidth)continue;const rn=ze+ut*U[1],Ut=ht+Ft*j;let _t=rn;for(let Wt=0;Wt<b.inChannels;++Wt){const Jt=me[Ut+Wt*Z];for(let Rn=0;Rn<b.outChannels;++Rn)ye[rt+Rn*ue]+=Jt*ce[_t+Rn];_t+=b.outChannels}}}}}}return n.makeTensorInfo(k.shape,k.dtype,ye)}const q4={kernelName:gd,backendName:"cpu",kernelFunc:j0};function j4(e){const{inputs:t,backend:n,attrs:s}=e,{x:i,dy:o}=t,{strides:a,pad:c,dataFormat:h,dimRoundingMode:d,filterShape:m}=s;Te([i,o],"conv2dBackpropFilter");const f=$r(h),b=Fn(i.shape,m,a,1,c,d,!1,f),{strideHeight:w,strideWidth:L,filterHeight:x,filterWidth:v}=b,N=b.dataFormat==="channelsLast",O=new an(b.filterShape,"float32"),E=b.padInfo.left,k=b.padInfo.top,F=n.data.get(i.dataId).values,U=n.data.get(o.dataId).values,$=new an(i.shape,i.dtype,F),Y=new an(o.shape,o.dtype,U);for(let j=0;j<x;++j){const Z=Math.max(0,Math.ceil((k-j)/w)),ie=Math.min(b.outHeight,(b.inHeight+k-j)/w);for(let de=0;de<v;++de){const he=Math.max(0,Math.ceil((E-de)/L)),ue=Math.min(b.outWidth,(b.inWidth+E-de)/L);for(let me=0;me<b.inChannels;++me)for(let ce=0;ce<b.outChannels;++ce){let ye=0;for(let pe=0;pe<b.batchSize;++pe)for(let we=Z;we<ie;++we){const Se=j+we*w-k;for(let xe=he;xe<ue;++xe){const Oe=de+xe*L-E;N?ye+=$.get(pe,Se,Oe,me)*Y.get(pe,we,xe,ce):ye+=$.get(pe,me,Se,Oe)*Y.get(pe,ce,we,xe)}}O.set(ye,j,de,me,ce)}}}return n.makeTensorInfo(O.shape,O.dtype,O.values)}const K4={kernelName:Ty,backendName:"cpu",kernelFunc:j4};function X4(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,filter:o}=t,{inputShape:a,strides:c,pad:h,dataFormat:d,dimRoundingMode:m}=s;Te([i,o],"conv2dBackpropInput");const f=je(o.shape),b=je(i.shape);let w=$r(d);const L=Fn(a,o.shape,c,1,h,m,!1,w),x=new an(L.inShape,"float32"),v=x.values,N=n.data.get(i.dataId).values,O=n.data.get(o.dataId).values,[E,k,F]=f,{batchSize:U,filterHeight:$,filterWidth:Y,inChannels:j,inHeight:Z,inWidth:ie,outChannels:de,outHeight:he,outWidth:ue,strideHeight:me,strideWidth:ce}=L;w=L.dataFormat;const ye=$-1-L.padInfo.top,pe=Y-1-L.padInfo.left,we=w==="channelsLast",Se=x.strides[0],xe=we?x.strides[1]:x.strides[2],Oe=we?x.strides[2]:1,Ne=we?1:x.strides[1],De=b[0],Ue=we?b[1]:b[2],ze=we?b[2]:1,ht=we?1:b[1];for(let it=0;it<U;++it)for(let rt=0;rt<j;++rt)for(let mt=0;mt<Z;++mt){const ut=mt-ye,Ft=Math.max(0,Math.ceil(ut/me)),rn=Math.min(he,($+ut)/me);for(let Ut=0;Ut<ie;++Ut){const _t=Ut-pe,Wt=Math.max(0,Math.ceil(_t/ce)),Jt=Math.min(ue,(Y+_t)/ce);let Rn=0;for(let On=Ft;On<rn;++On){const di=On*me-ut;for(let Cs=Wt;Cs<Jt;++Cs){const na=Cs*ce-_t,pi=De*it+Ue*On+ze*Cs,_i=E*($-1-di)+k*(Y-1-na)+F*rt;for(let to=0;to<de;++to){const no=N[pi+ht*to],so=O[_i+to];Rn+=no*so}}}const fr=Se*it+xe*mt+Oe*Ut+Ne*rt;v[fr]=Rn}}return n.makeTensorInfo(x.shape,x.dtype,x.values)}const J4={kernelName:yd,backendName:"cpu",kernelFunc:X4};function Z4(e){const{inputs:t,backend:n,attrs:s}=e,{x:i,filter:o}=t,{strides:a,pad:c,dilations:h}=s;Te([i,o],"conv3d");const d=_r(i.shape,o.shape,a,h,c),{filterDepth:m,filterHeight:f,filterWidth:b,dilationDepth:w,dilationHeight:L,dilationWidth:x,padInfo:v}=d,N=v.front,O=v.left,E=v.top,k=new an(d.outShape,i.dtype),F=n.data.get(i.dataId).values,U=n.data.get(o.dataId).values,$=k.values,Y=je(i.shape),j=je(o.shape);for(let Z=0;Z<d.batchSize;++Z){const ie=Z*Y[0],de=Z*k.strides[0];for(let he=0;he<d.outDepth;++he){const ue=de+he*k.strides[1],me=he*d.strideDepth-N;for(let ce=0;ce<m;++ce){const ye=me+ce*w;if(ye<0||ye>=d.inDepth)continue;const pe=ce*j[0],we=ie+ye*Y[1];for(let Se=0;Se<d.outHeight;++Se){const xe=ue+Se*k.strides[2],Oe=Se*d.strideHeight-E;for(let Ne=0;Ne<f;++Ne){const De=Oe+Ne*L;if(De<0||De>=d.inHeight)continue;const Ue=pe+Ne*j[1],ze=we+De*Y[2];for(let ht=0;ht<d.outWidth;++ht){const it=xe+ht*d.outChannels,rt=ht*d.strideWidth-O;for(let mt=0;mt<b;++mt){const ut=rt+mt*x;if(ut<0||ut>=d.inWidth)continue;const Ft=Ue+mt*j[2],rn=ze+ut*d.inChannels;let Ut=Ft;for(let _t=0;_t<d.inChannels;++_t){const Wt=F[rn+_t];for(let Jt=0;Jt<d.outChannels;++Jt)$[it+Jt]+=Wt*U[Ut+Jt];Ut+=d.outChannels}}}}}}}}return n.makeTensorInfo(k.shape,k.dtype,k.values)}const Q4={kernelName:bd,backendName:"cpu",kernelFunc:Z4};function ej(e){const{inputs:t,backend:n,attrs:s}=e,{x:i,dy:o}=t,{strides:a,pad:c,filterShape:h}=s;Te([i,o],"conv3dBackpropFilterV2");const d=je(i.shape),m=je(o.shape),f=_r(i.shape,h,a,1,c),b=f.strideDepth,w=f.strideHeight,L=f.strideWidth,x=f.filterDepth,v=f.filterHeight,N=f.filterWidth,O=new an(f.filterShape,"float32"),E=O.values,[k,F,U,$]=O.strides,Y=n.data.get(o.dataId).values,[j,Z,ie,de]=m,he=n.data.get(i.dataId).values,[ue,me,ce,ye]=d,pe=f.padInfo.front,we=f.padInfo.left,Se=f.padInfo.top;for(let xe=0;xe<x;++xe){const Oe=Math.max(0,Math.ceil((pe-xe)/b)),Ne=Math.min(f.outDepth,(f.inDepth+pe-xe)/b),De=xe*k;for(let Ue=0;Ue<v;++Ue){const ze=Math.max(0,Math.ceil((Se-Ue)/w)),ht=Math.min(f.outHeight,(f.inHeight+Se-Ue)/w),it=Ue*F+De;for(let rt=0;rt<N;++rt){const mt=Math.max(0,Math.ceil((we-rt)/L)),ut=Math.min(f.outWidth,(f.inWidth+we-rt)/L),Ft=rt*U+it;for(let rn=0;rn<f.inChannels;++rn){const Ut=rn*$+Ft;for(let _t=0;_t<f.outChannels;++_t){let Wt=0;for(let Jt=0;Jt<f.batchSize;++Jt){const Rn=Jt*ue,fr=Jt*j;for(let On=Oe;On<Ne;++On){const di=xe+On*b-pe,Cs=di*me+Rn,na=On*Z+fr;for(let pi=ze;pi<ht;++pi){const _i=Ue+pi*w-Se,to=_i*ce+Cs,no=pi*ie+na;for(let so=mt;so<ut;++so){const Oc=rt+so*L-we,sI=Oc*ye+to,iI=so*de+no;Wt+=he[sI+rn]*Y[iI+_t]}}}}E[Ut+_t]=Wt}}}}}return n.makeTensorInfo(O.shape,O.dtype,O.values)}const tj={kernelName:Ay,backendName:"cpu",kernelFunc:ej};function nj(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,filter:o}=t,{pad:a,strides:c,inputShape:h}=s;Te([i],"conv3dBackpropInputV2");const d=je(i.shape),m=je(o.shape),f=_r(h,o.shape,c,1,a),b=new an(f.inShape,"float32"),w=b.values,[L,x,v,N]=b.strides,O=n.data.get(i.dataId).values,[E,k,F,U]=d,$=n.data.get(o.dataId).values,[Y,j,Z,ie]=m,{batchSize:de,filterDepth:he,filterHeight:ue,filterWidth:me,inChannels:ce,inDepth:ye,inHeight:pe,inWidth:we,outChannels:Se,outDepth:xe,outHeight:Oe,outWidth:Ne,strideDepth:De,strideHeight:Ue,strideWidth:ze}=f,ht=he-1-f.padInfo.front,it=ue-1-f.padInfo.top,rt=me-1-f.padInfo.left;for(let mt=0;mt<de;++mt)for(let ut=0;ut<ce;++ut)for(let Ft=0;Ft<ye;++Ft){const rn=Ft-ht,Ut=Math.max(0,Math.ceil(rn/De)),_t=Math.min(xe,(he+rn)/De);for(let Wt=0;Wt<pe;++Wt){const Jt=Wt-it,Rn=Math.max(0,Math.ceil(Jt/Ue)),fr=Math.min(Oe,(ue+Jt)/Ue);for(let On=0;On<we;++On){const di=On-rt,Cs=Math.max(0,Math.ceil(di/ze)),na=Math.min(Ne,(me+di)/ze);let pi=0;for(let _i=Ut;_i<_t;++_i){const to=_i*De-rn;for(let no=Rn;no<fr;++no){const so=no*Ue-Jt;for(let Oc=Cs;Oc<na;++Oc){const sI=Oc*ze-di,iI=E*mt+k*_i+F*no+U*Oc,e9=Y*(he-1-to)+j*(ue-1-so)+Z*(me-1-sI)+ie*ut;for(let Km=0;Km<Se;++Km){const t9=O[iI+Km],n9=$[e9+Km];pi+=t9*n9}}}}w[L*mt+x*Ft+v*Wt+N*On+ut]=pi}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}const sj={kernelName:vy,backendName:"cpu",kernelFunc:nj};const ij=xt(Ca,e=>Math.cos(e)),rj={kernelName:Ca,backendName:"cpu",kernelFunc:ij};const oj=xt(vl,e=>Math.cosh(e)),aj={kernelName:vl,backendName:"cpu",kernelFunc:oj};function K0(e){const{inputs:t,backend:n,attrs:s}=e,{x:i,filter:o}=t,{strides:a,pad:c,dilations:h,dimRoundingMode:d}=s;Te([i,o],"depthwiseConv2DNative");const m=je(i.shape),f=je(o.shape);let b=h;b==null&&(b=[1,1]),A(cn(a,b),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${b}'`);const w=Fn(i.shape,o.shape,a,b,c,d,!0),{filterHeight:L,filterWidth:x,dilationHeight:v,dilationWidth:N,padInfo:O}=w,E=O.left,k=O.top,F=w.outChannels/w.inChannels,U=new an(w.outShape,i.dtype),$=n.data.get(i.dataId).values,Y=n.data.get(o.dataId).values,j=U.values;for(let Z=0;Z<w.batchSize;++Z){const ie=Z*m[0],de=Z*U.strides[0];for(let he=0;he<w.outHeight;++he){const ue=de+he*U.strides[1],me=he*w.strideHeight-E;for(let ce=0;ce<L;++ce){const ye=me+ce*v;if(ye<0||ye>=w.inHeight)continue;const pe=ce*f[0],we=ie+ye*m[1];for(let Se=0;Se<w.outWidth;++Se){const xe=ue+Se*U.strides[2],Oe=Se*w.strideWidth-k;for(let Ne=0;Ne<x;++Ne){const De=Oe+Ne*N;if(De<0||De>=w.inWidth)continue;const Ue=pe+Ne*f[1],ze=we+De*w.inChannels;let ht=xe,it=Ue;for(let rt=0;rt<w.inChannels;++rt){const mt=$[ze+rt];for(let ut=0;ut<F;++ut)j[ht+ut]+=mt*Y[it+ut];ht+=F,it+=F}}}}}}return n.makeTensorInfo(U.shape,U.dtype,U.values)}const cj={kernelName:wd,backendName:"cpu",kernelFunc:K0};function lj(e){const{inputs:t,backend:n,attrs:s}=e,{x:i,dy:o}=t,{strides:a,dilations:c,pad:h,dimRoundingMode:d,filterShape:m}=s;Te([i,o],"depthwiseConv2dNativeBackpropFilter");const f=Fn(i.shape,m,a,c,h,d,!0),{strideHeight:b,strideWidth:w,filterHeight:L,filterWidth:x}=f,v=new an(f.filterShape,"float32"),N=f.padInfo.left,O=f.padInfo.top,E=f.outChannels/f.inChannels,k=n.data.get(i.dataId).values,F=new an(i.shape,i.dtype,k),U=n.data.get(o.dataId).values,$=new an(o.shape,o.dtype,U);for(let Y=0;Y<L;++Y){const j=Math.max(0,Math.ceil((O-Y)/b)),Z=Math.min(f.outHeight,(f.inHeight+O-Y)/b);for(let ie=0;ie<x;++ie){const de=Math.max(0,Math.ceil((N-ie)/w)),he=Math.min(f.outWidth,(f.inWidth+N-ie)/w);for(let ue=0;ue<f.outChannels;++ue){const me=Math.trunc(ue/E),ce=ue%E;let ye=0;for(let pe=0;pe<f.batchSize;++pe)for(let we=j;we<Z;++we){const Se=Y+we*b-O;for(let xe=de;xe<he;++xe){const Oe=ie+xe*w-N;ye+=F.get(pe,Se,Oe,me)*$.get(pe,we,xe,ue)}}v.set(ye,Y,ie,me,ce)}}}return n.makeTensorInfo(v.shape,v.dtype,v.values)}const hj={kernelName:Cy,backendName:"cpu",kernelFunc:lj};function uj(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,filter:o}=t,{strides:a,dilations:c,pad:h,dimRoundingMode:d,inputShape:m}=s;Te([i,o],"depthwiseConv2DNativeBackpropInput");const f=je(i.shape),b=je(o.shape),w=Fn(m,o.shape,a,c,h,d,!0),L=new an(w.inShape,"float32"),x=L.values,[v,N,O]=L.strides,E=n.data.get(i.dataId).values,[k,F,U]=f,$=n.data.get(o.dataId).values,[Y,j,Z]=b,{batchSize:ie,filterHeight:de,filterWidth:he,inChannels:ue,inHeight:me,inWidth:ce,outChannels:ye,outHeight:pe,outWidth:we,strideHeight:Se,strideWidth:xe}=w,Oe=de-1-w.padInfo.top,Ne=he-1-w.padInfo.left,De=ye/ue;for(let Ue=0;Ue<ie;++Ue)for(let ze=0;ze<ue;++ze)for(let ht=0;ht<me;++ht){const it=ht-Oe,rt=Math.max(0,Math.ceil(it/Se)),mt=Math.min(pe,(de+it)/Se);for(let ut=0;ut<ce;++ut){const Ft=ut-Ne,rn=Math.max(0,Math.ceil(Ft/xe)),Ut=Math.min(we,(he+Ft)/xe);let _t=0;for(let Wt=rt;Wt<mt;++Wt){const Jt=Wt*Se-it;for(let Rn=rn;Rn<Ut;++Rn){const fr=Rn*xe-Ft,On=k*Ue+F*Wt+U*Rn,di=Y*(de-1-Jt)+j*(he-1-fr)+Z*ze;for(let Cs=0;Cs<De;++Cs){const na=ze*De+Cs,pi=E[On+na],_i=$[di+Cs];_t+=pi*_i}}}x[v*Ue+N*ht+O*ut+ze]=_t}}return n.makeTensorInfo(L.shape,L.dtype,L.values)}const dj={kernelName:Ry,backendName:"cpu",kernelFunc:uj};const pj={kernelName:Ld,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,f=h.data.get(i.dataId).values,b=i.shape.length,{batchSize:w,inHeight:L,inWidth:x,inChannels:v,outHeight:N,outWidth:O,padInfo:E,strideHeight:k,strideWidth:F,filterHeight:U,filterWidth:$,dilationHeight:Y,dilationWidth:j,outShape:Z}=hp(s.shape,i.shape,o,a,"NHWC",c),ie=P(Z),de=Z.length,he=ws(s.dtype,ie);for(let me=0;me<w;++me)for(let ce=0;ce<N;++ce){const ye=ce*k-E.top;for(let pe=0;pe<O;++pe){const we=pe*F-E.left;for(let Se=0;Se<v;++Se){let xe=Number.MIN_SAFE_INTEGER;for(let Ne=0;Ne<U;++Ne){const De=ye+Ne*Y;if(De>=0&&De<L)for(let Ue=0;Ue<$;++Ue){const ze=we+Ue*j;if(ze>=0&&ze<x){const ht=Ws([me,De,ze,Se],m,je(s.shape)),it=Ws([Ne,Ue,Se],b,je(i.shape)),rt=d[ht]+f[it];rt>xe&&(xe=rt)}}}const Oe=Ws([me,ce,pe,Se],de,je(Z));he[Oe]=xe}}}const ue=h.write(Er(he,s.dtype),Z,s.dtype);return{dataId:ue,shape:Z,dtype:s.dtype}}};const mj={kernelName:Id,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=Ls(s.shape,d.data.get(s.dataId).values),f=Ls(i.shape,d.data.get(i.dataId).values),{batchSize:b,inHeight:w,inWidth:L,inChannels:x,outHeight:v,outWidth:N,padInfo:O,strideHeight:E,strideWidth:k,filterHeight:F,filterWidth:U,dilationHeight:$,dilationWidth:Y,outShape:j}=hp(s.shape,i.shape,a,c,"NHWC",h);A(o.rank===j.length,()=>`Error in ${Id}, dy must have the same rank as output ${j.length}, but got ${o.rank}`);const Z=Ls(j,d.data.get(o.dataId).values),ie=fy(i.shape,i.dtype);for(let he=0;he<b;++he)for(let ue=0;ue<v;++ue){const me=ue*E-O.top;for(let ce=0;ce<N;++ce){const ye=ce*k-O.left;for(let pe=0;pe<x;++pe){let we=Number.MIN_SAFE_INTEGER,Se=0,xe=0;for(let Oe=0;Oe<F;++Oe){const Ne=me+Oe*$;if(Ne>=0&&Ne<w)for(let De=0;De<U;++De){const Ue=ye+De*Y;if(Ue>=0&&Ue<L){const ze=m[he][Ne][Ue][pe]+f[Oe][De][pe];ze>we&&(we=ze,Se=Oe,xe=De)}}}ie[Se][xe][pe]+=Z[he][ue][ce][pe]}}}const de=d.write(Er(ie,s.dtype),i.shape,i.dtype);return{dataId:de,shape:i.shape,dtype:i.dtype}}};const fj={kernelName:Sd,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=Ls(s.shape,d.data.get(s.dataId).values),f=Ls(i.shape,d.data.get(i.dataId).values),{batchSize:b,inHeight:w,inWidth:L,inChannels:x,outHeight:v,outWidth:N,padInfo:O,strideHeight:E,strideWidth:k,filterHeight:F,filterWidth:U,dilationHeight:$,dilationWidth:Y,outShape:j}=hp(s.shape,i.shape,a,c,"NHWC",h);A(o.rank===j.length,()=>`Error in ${Sd}, dy must have the same rank as output ${j.length}, but got ${o.rank}`);const Z=Ls(j,d.data.get(o.dataId).values),ie=fy(s.shape,s.dtype);for(let he=0;he<b;++he)for(let ue=0;ue<v;++ue){const me=ue*E-O.top;for(let ce=0;ce<N;++ce){const ye=ce*k-O.left;for(let pe=0;pe<x;++pe){let we=Number.MIN_SAFE_INTEGER,Se=me<0?0:me,xe=ye<0?0:ye;for(let Oe=0;Oe<F;++Oe){const Ne=me+Oe*$;if(Ne>=0&&Ne<w)for(let De=0;De<U;++De){const Ue=ye+De*Y;if(Ue>=0&&Ue<L){const ze=m[he][Ne][Ue][pe]+f[Oe][De][pe];ze>we&&(we=ze,Se=Ne,xe=Ue)}}}ie[he][Se][xe][pe]+=Z[he][ue][ce][pe]}}}const de=d.write(Er(ie,s.dtype),s.shape,s.dtype);return{dataId:de,shape:s.shape,dtype:s.dtype}}};const gj=Qr((e,t)=>e/t),yj=gc(Ra,gj),PS={kernelName:Ra,backendName:"cpu",kernelFunc:yj};const bj=Cw,wj=Rw,Lj=Ow,Sj=Ew,Ij=Dw,xj=kw,Tj=xt(Cl,e=>{const t=Math.sign(e),n=Math.abs(e),s=1/(1+bj*n);return t*(1-((((xj*s+Ij)*s+Sj)*s+Lj)*s+wj)*s*Math.exp(-n*n))}),Aj={kernelName:Cl,backendName:"cpu",kernelFunc:Tj};function X0(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=P(d),f=bt("float32",m),b=bt("float32",m);for(let v=0;v<i;v++){const N=$S({inputs:{x:c},backend:n,attrs:{begin:[v,0],size:[1,o]}}),O=$S({inputs:{x:h},backend:n,attrs:{begin:[v,0],size:[1,o]}}),E=ui({inputs:{real:N,imag:O},backend:n}),{real:k,imag:F}=vj(E,t,n),U=sr(k,F);for(let $=0;$<o;$++){const Y=Fw(U,$);f[v*o+$]=Y.real,b[v*o+$]=Y.imag}n.disposeIntermediateTensorInfo(N),n.disposeIntermediateTensorInfo(O),n.disposeIntermediateTensorInfo(E)}const w=n.makeTensorInfo(d,"float32",f),L=n.makeTensorInfo(d,"float32",b),x=ui({inputs:{real:w,imag:L},backend:n});return n.disposeIntermediateTensorInfo(w),n.disposeIntermediateTensorInfo(L),x}function vj(e,t,n){const s=P(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(Nj(s)){const c=zS(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),f=n.makeTensorInfo([],"float32",cT(s,"float32")),b=Qo({inputs:{x:f},backend:n}),w=PS.kernelFunc({inputs:{a:d,b:f},backend:n}),L=PS.kernelFunc({inputs:{a:m,b},backend:n}),x=n.data.get(w.dataId).values,v=n.data.get(L.dataId).values;return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(w),n.disposeIntermediateTensorInfo(L),{real:x,imag:v}}return c}else{const c=sr(o,a),h=Cj(c,s,t);return ZA(h)}}function Nj(e){return(e&e-1)===0}function zS(e,t,n,s,i){if(n===1)return{real:e,imag:t};const o=sr(e,t),a=n/2,c=QA(o),h=c.real,d=c.imag,m=[h.length],f=i.makeTensorInfo(m,"float32",h),b=i.makeTensorInfo(m,"float32",d),w=ui({inputs:{real:f,imag:b},backend:i}),L=ev(o),x=L.real,v=L.imag,N=[x.length],O=i.makeTensorInfo(N,"float32",x),E=i.makeTensorInfo(N,"float32",v),k=ui({inputs:{real:O,imag:E},backend:i}),F=zS(h,d,a,s,i),U=F.real,$=F.imag,Y=[U.length],j=i.makeTensorInfo(Y,"float32",U),Z=i.makeTensorInfo(Y,"float32",$),ie=ui({inputs:{real:j,imag:Z},backend:i}),de=zS(x,v,a,s,i),he=de.real,ue=de.imag,me=[he.length],ce=i.makeTensorInfo(me,"float32",he),ye=i.makeTensorInfo(me,"float32",ue),pe=ui({inputs:{real:ce,imag:ye},backend:i}),we=nv(n,s),Se=[we.real.length],xe=i.makeTensorInfo(Se,"float32",we.real),Oe=i.makeTensorInfo(Se,"float32",we.imag),Ne=ui({inputs:{real:xe,imag:Oe},backend:i}),De=F0({inputs:{a:Ne,b:pe},backend:i}),Ue=yu({inputs:{a:ie,b:De},backend:i}),ze=M0({inputs:{a:ie,b:De},backend:i}),ht=fu({inputs:{input:Ue},backend:i}),it=fu({inputs:{input:ze},backend:i}),rt=_m({inputs:{input:Ue},backend:i}),mt=_m({inputs:{input:ze},backend:i}),ut=bu({inputs:[ht,it],backend:i,attrs:{axis:0}}),Ft=bu({inputs:[rt,mt],backend:i,attrs:{axis:0}}),rn=i.data.get(ut.dataId).values,Ut=i.data.get(Ft.dataId).values;return i.disposeIntermediateTensorInfo(f),i.disposeIntermediateTensorInfo(b),i.disposeIntermediateTensorInfo(w),i.disposeIntermediateTensorInfo(O),i.disposeIntermediateTensorInfo(E),i.disposeIntermediateTensorInfo(k),i.disposeIntermediateTensorInfo(j),i.disposeIntermediateTensorInfo(Z),i.disposeIntermediateTensorInfo(ie),i.disposeIntermediateTensorInfo(ce),i.disposeIntermediateTensorInfo(ye),i.disposeIntermediateTensorInfo(pe),i.disposeIntermediateTensorInfo(xe),i.disposeIntermediateTensorInfo(Oe),i.disposeIntermediateTensorInfo(Ne),i.disposeIntermediateTensorInfo(De),i.disposeIntermediateTensorInfo(Ue),i.disposeIntermediateTensorInfo(ze),i.disposeIntermediateTensorInfo(ht),i.disposeIntermediateTensorInfo(rt),i.disposeIntermediateTensorInfo(it),i.disposeIntermediateTensorInfo(mt),i.disposeIntermediateTensorInfo(ut),i.disposeIntermediateTensorInfo(Ft),{real:rn,imag:Ut}}function Cj(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=sv(i*c,t,n),d=Fw(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),tv(s,o,a,i)}return s}function Rj(e){const{inputs:t,backend:n}=e,{input:s}=t,i=P(s.shape),o=s.shape[s.shape.length-1],a=i/o,c=ki({inputs:{x:s},backend:n,attrs:{shape:[a,o]}}),h=X0(c,!1,n),d=ki({inputs:{x:h},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),d}const Oj={kernelName:xd,backendName:"cpu",kernelFunc:Rj};function Ej(e){const{backend:t,attrs:n}=e,{shape:s,value:i,dtype:o}=n,a=o||Aa(i),c=ws(a,P(s));return kj(c,i,a),t.makeTensorInfo(s,a,c)}const Dj={kernelName:Oy,backendName:"cpu",kernelFunc:Ej};function kj(e,t,n){n==="string",e.fill(t)}const Fj={kernelName:Td,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,i=n,o=bt(s.dtype,P(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 x=L*(h*d);for(let v=0;v<h;v++){const N=v*d;for(let O=0;O<d;O++){const E=[a,L,v,O],k=E[2],F=Math.round(h-k),U=w+x+N+O;let $=m[U];if(F>=0&&F<h){const Y=F*d,j=w+x+Y+O;$=m[j]}o[U]=$}}}}const f=i.write(o,s.shape,s.dtype);return{dataId:f,shape:s.shape,dtype:s.dtype}}};function _j(e){const{inputs:t,backend:n,attrs:s}=e,{x:i,filter:o,bias:a,preluActivationWeights:c}=t,{strides:h,pad:d,dataFormat:m,dilations:f,dimRoundingMode:b,activation:w}=s;let L=j0({inputs:{x:i,filter:o},backend:n,attrs:{strides:h,pad:d,dataFormat:m,dilations:f,dimRoundingMode:b}});if(a){const x=L;L=yu({inputs:{a:L,b:a},backend:n}),n.disposeIntermediateTensorInfo(x)}if(w){const x=L;L=BS(n,L,w,c),n.disposeIntermediateTensorInfo(x)}return L}const Wj={kernelName:zd,backendName:"cpu",kernelFunc:_j};function $j(e){const{inputs:t,backend:n,attrs:s}=e,{x:i,filter:o,bias:a,preluActivationWeights:c}=t,{strides:h,pad:d,dataFormat:m,dilations:f,dimRoundingMode:b,activation:w}=s;let L=K0({inputs:{x:i,filter:o},backend:n,attrs:{strides:h,pad:d,dataFormat:m,dilations:f,dimRoundingMode:b}});if(a){const x=L;L=yu({inputs:{a:L,b:a},backend:n}),n.disposeIntermediateTensorInfo(x)}if(w){const x=L;L=BS(n,L,w,c),n.disposeIntermediateTensorInfo(x)}return L}const Uj={kernelName:Vd,backendName:"cpu",kernelFunc:$j};function Bj(e){const{inputs:t,backend:n}=e,{input:s}=t,i=P(s.shape),o=s.shape[s.shape.length-1],a=i/o,c=ki({inputs:{x:s},backend:n,attrs:{shape:[a,o]}}),h=X0(c,!0,n),d=ki({inputs:{x:h},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),d}const Mj={kernelName:Ad,backendName:"cpu",kernelFunc:Bj};const Pj=xt(Fl,e=>Number.isFinite(e)?1:0,"bool"),zj={kernelName:Fl,backendName:"cpu",kernelFunc:Pj};const Vj=xt(_l,e=>Math.abs(e)===Infinity?1:0,"bool"),Gj={kernelName:_l,backendName:"cpu",kernelFunc:Vj};const Yj=xt(Wl,e=>Number.isNaN(e)?1:0,"bool"),Hj={kernelName:Wl,backendName:"cpu",kernelFunc:Yj};const qj=xt(Ul,e=>Math.log1p(e)),jj={kernelName:Ul,backendName:"cpu",kernelFunc:qj};const Kj=xt(Nd,e=>e?0:1,"bool"),Xj={kernelName:Nd,backendName:"cpu",kernelFunc:Kj};const Jj={kernelName:Bl,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=qe(i,c);let m=d;const f=Jn(m,h);let b=a.data.get(s.dataId).values;if(f!=null){const E=new Array(h);for(let k=0;k<E.length;k++)E[k]=c[f[k]];b=US(b,c,s.dtype,f,E),m=cs(m.length,h),c=E}Te(s,"max"),Xn("max",m,h);const[w,L]=An(c,m),x=P(L),v=D0(b,x,w,s.dtype),N=a.write(v,w,s.dtype);let O=w;if(o){const E=vn(w,d);O=E}return{dataId:N,shape:O,dtype:s.dtype}}};function Zj(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;Te(i,"maxPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:h}=s,d=1;A(cn(a,d),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${d}'`);const m=Un(i.shape,o,a,d,c,h);let f;if(m.filterWidth===1&&m.filterHeight===1&&ae(m.inShape,m.outShape))f=Qo({inputs:{x:i},backend:n});else{const b=n.data.get(i.dataId).values,w=je(i.shape),L=MS(b,i.shape,i.dtype,w,m,"max");f=n.makeTensorInfo(m.outShape,i.dtype,L.values)}return f}const Qj={kernelName:Ml,backendName:"cpu",kernelFunc:Zj};function eK(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o,output:a}=t,c=o;Te([o,a],"maxPoolBackprop");const{filterSize:h,strides:d,pad:m,dimRoundingMode:f}=s,b=Un(c.shape,h,d,1,m,f),w=n.data.get(c.dataId).values,L=wt(b.outShape,c.dtype,q0(w,c.shape,c.dtype,b).values),x=b.strideHeight,v=b.strideWidth,N=b.dilationHeight,O=b.dilationWidth,E=b.effectiveFilterHeight,k=b.effectiveFilterWidth,F=k-1-b.padInfo.left,U=E-1-b.padInfo.top,$=wt(c.shape,"float32"),Y=n.data.get(i.dataId).values,j=wt(i.shape,"float32",Y);for(let Z=0;Z<b.batchSize;++Z)for(let ie=0;ie<b.inChannels;++ie)for(let de=0;de<b.inHeight;++de)for(let he=0;he<b.inWidth;++he){const ue=de-U,me=he-F;let ce=0;for(let ye=0;ye<E;ye+=N){const pe=(ue+ye)/x;if(pe<0||pe>=b.outHeight||Math.floor(pe)!==pe)continue;for(let we=0;we<k;we+=O){const Se=(me+we)/v;if(Se<0||Se>=b.outWidth||Math.floor(Se)!==Se)continue;const xe=E*k-1-L.get(Z,pe,Se,ie),Oe=ye*k+we,Ne=xe===Oe?1:0;if(Ne===0)continue;const De=j.get(Z,pe,Se,ie);ce+=De*Ne}}$.set(ce,Z,de,he,ie)}return n.makeTensorInfo($.shape,$.dtype,$.values)}const tK={kernelName:Cd,backendName:"cpu",kernelFunc:eK};function nK(e,t,n,s,i){const o=je(t),a=MS(e,t,n,o,i,"max"),c=q0(e,t,n,i,!0,s);return[a.values,c.values]}const sK={kernelName:Rd,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{filterSize:i,strides:o,pad:a,includeBatchInIndex:c}=t,h=n;Te(s,"MaxPoolWithArgmax");const d=h.data.get(s.dataId).values,m=Un(s.shape,i,o,[1,1],a),[f,b]=nK(d,s.shape,s.dtype,c,m),w=h.write(f,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"}]}};function iK(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{paddings:o,mode:a}=s;Te(i,"mirrorPad");const c=o.map((E,k)=>E[0]+i.shape[k]+E[1]),h=o.map(E=>E[0]),d=o.map((E,k)=>E[0]+i.shape[k]),m=a==="reflect"?0:1,f=n.data.get(i.dataId).values,b=i.shape.length,w=je(i.shape),L=P(c),x=c.length,v=je(c),N=bt(i.dtype,L);for(let E=0;E<L;E++){let k=vo(E,x,v);for(let U=0;U<x;U++)k[U]<h[U]?k[U]=h[U]*2-k[U]-m:k[U]>=d[U]&&(k[U]=(d[U]-1)*2-k[U]+m);k=k.map((U,$)=>U-h[$]);const F=Ws(k,b,w);N[E]=f[F]}const O=n.write(N,c,i.dtype);return{dataId:O,shape:c,dtype:i.dtype}}const rK={kernelName:Pl,backendName:"cpu",kernelFunc:iK};const oK=Vp,aK={kernelName:Od,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;Te(s,"NonMaxSuppressionPadded");const m=d.data.get(s.dataId).values,f=d.data.get(i.dataId).values,{selectedIndices:b,validOutputs:w}=oK(m,f,o,a,c,h);return[b,w]}};const cK=Gp,lK={kernelName:Ed,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;Te(s,"NonMaxSuppressionWithScore");const m=d.data.get(s.dataId).values,f=d.data.get(i.dataId).values,b=o,w=a,L=c,x=h,{selectedIndices:v,selectedScores:N}=cK(m,f,b,w,L,x);return[v,N]}};function hK(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{paddings:o,constantValue:a}=s;Te(i,"pad");const c=o.map((O,E)=>O[0]+i.shape[E]+O[1]),h=o.map(O=>O[0]),d=n.data.get(i.dataId).values,m=P(i.shape),f=i.shape.length,b=je(i.shape),w=P(c),L=c.length,x=je(c),v=bt(i.dtype,w);a!==0&&v.fill(a);for(let O=0;O<m;O++){const E=vo(O,f,b),k=E.map((U,$)=>U+h[$]),F=Ws(k,L,x);v[F]=d[O]}const N=n.write(v,c,i.dtype);return{dataId:N,shape:c,dtype:i.dtype}}const J0={kernelName:Dd,backendName:"cpu",kernelFunc:hK};const uK=xt(Vl,e=>1/e),dK={kernelName:Vl,backendName:"cpu",kernelFunc:uK};const pK={kernelName:Md,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,{radians:i,fillValue:o,center:a}=t,c=n,h=bt(s.dtype,P(s.shape)),[d,m,f,b]=s.shape,[w,L]=Aw(a,m,f),x=255,v=Math.sin(i),N=Math.cos(i),O=c.data.get(s.dataId).values;for(let k=0;k<d;k++){const F=k*f*m*b;for(let U=0;U<m;U++){const $=U*(f*b);for(let Y=0;Y<f;Y++){const j=Y*b;for(let Z=0;Z<b;Z++){const ie=[d,U,Y,Z],de=ie[2],he=ie[1];let ue=(de-w)*N-(he-L)*v,me=(de-w)*v+(he-L)*N;ue=Math.round(ue+w),me=Math.round(me+L);let ce=o;if(typeof o!="number"&&(Z===3?ce=x:ce=o[Z]),ue>=0&&ue<f&&me>=0&&me<m){const pe=me*(f*b),we=ue*b,Se=F+pe+we+Z;ce=O[Se]}const ye=F+$+j+Z;h[ye]=ce}}}}const E=c.write(h,s.shape,s.dtype);return{dataId:E,shape:s.shape,dtype:s.dtype}}};const mK=xt(ql,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}),fK={kernelName:ql,backendName:"cpu",kernelFunc:mK};const gK=Hp,yK=qp,bK=xt(Kl,e=>e>=0?yK*e:gK*(Math.exp(e)-1)),wK={kernelName:Kl,backendName:"cpu",kernelFunc:bK};const LK=xt(Zl,e=>1/(1+Math.exp(-e))),SK={kernelName:Zl,backendName:"cpu",kernelFunc:LK};const IK=xt(Jl,e=>e<0?-1:e>0?1:0),xK={kernelName:Jl,backendName:"cpu",kernelFunc:IK};const TK=xt(Ea,e=>Math.sin(e)),AK={kernelName:Ea,backendName:"cpu",kernelFunc:TK};const vK=xt(Xl,e=>Math.sinh(e)),NK={kernelName:Xl,backendName:"cpu",kernelFunc:vK};const CK=11920928955078125e-23,Z0=Math.log(CK)+2,RK=xt(Ql,e=>{const t=e>-Z0,n=e<Z0,s=Math.exp(e);let i;return n?i=s:t?i=e:i=Math.log(1+s),i}),OK={kernelName:Ql,backendName:"cpu",kernelFunc:RK};function Q0(e){const{inputs:t,attrs:n,backend:s}=e,{x:i}=t,{perm:o}=n;Te(i,"transpose");const a=i.shape.length,c=new Array(a);for(let f=0;f<c.length;f++)c[f]=i.shape[o[f]];const h=s.data.get(i.dataId).values,d=US(h,i.shape,i.dtype,o,c),m=s.write(d,c,i.dtype);return{dataId:m,shape:c,dtype:i.dtype}}const EK={kernelName:nh,backendName:"cpu",kernelFunc:Q0};function DK(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{blockShape:o,paddings:a}=s;Te([i],"spaceToBatchND");const c=P(o),h=[[0,0]];h.push(...a);for(let U=1+o.length;U<i.shape.length;++U)h.push([0,0]);const d=J0.kernelFunc({inputs:{x:i},backend:n,attrs:{paddings:h,constantValue:0}}),m=Mh(d.shape,o,c,!1),f=Ph(m.length,o.length,!1),b=zh(d.shape,o,c,!1),w={x:d},L={shape:m},x=ki({inputs:w,backend:n,attrs:L}),v={x},N={perm:f},O=Q0({inputs:v,backend:n,attrs:N}),E={x:O},k={shape:b},F=ki({inputs:E,backend:n,attrs:k});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(O),F}const kK={kernelName:Wd,backendName:"cpu",kernelFunc:DK};const FK=xt(eh,e=>Math.sqrt(e)),_K={kernelName:eh,backendName:"cpu",kernelFunc:FK};const WK={kernelName:$d,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{const{x:n}=e,s=t;Te(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 $K=xt(sh,(e,t)=>{const n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),UK={kernelName:sh,backendName:"cpu",kernelFunc:$K};const BK=xt(Fa,e=>Math.tan(e)),MK={kernelName:Fa,backendName:"cpu",kernelFunc:BK};const PK=xt(th,e=>Math.tanh(e)),zK={kernelName:th,backendName:"cpu",kernelFunc:PK};function VK(e){const{inputs:t,attrs:n,backend:s}=e,{axis:i}=n,{x:o}=t;Te(o,"unique");const a=s.data.get(o.dataId).values,{outputValues:c,outputShape:h,indices:d}=P0(a,i,o.shape,o.dtype);return[s.makeTensorInfo(h,o.dtype,c),s.makeTensorInfo([d.length],"int32",d)]}const GK={kernelName:Ud,backendName:"cpu",kernelFunc:VK};const YK=[T4,Mq,v4,C4,Hq,O4,D4,F4,W4,U4,M4,I4,z4,Gq,jq,G4,Pq,H4,K4,J4,q4,tj,sj,Q4,rj,aj,cj,hj,dj,pj,fj,mj,PS,g4,Aj,Xq,Zq,Oj,Dj,Fj,e4,Wj,Uj,zq,Mj,Y4,zj,Gj,Hj,n4,jj,Xj,Qj,tK,sK,Jj,rK,i4,aK,lK,o4,J0,b4,Vq,dK,w4,L4,S4,pK,fK,c4,wK,SK,xK,AK,NK,l4,OK,kK,_K,WK,u4,UK,p4,MK,zK,EK,GK];for(const e of YK)Yd(e);const eo={},VS={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Xte(e){delete eo[e]}function HK(e,t){eo[e]=t}function Fi(e){if(!(e in eo)){const n=jK(e);if(n!==null)eo[e]=n;else return console.log("Could not get context for WebGL version",e),null}const t=eo[e];return t.isContextLost()?(delete eo[e],Fi(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),eo[e])}function qK(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 jK(e){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");const t=qK(e);return t.addEventListener("webglcontextlost",n=>{n.preventDefault(),delete eo[e]},!1),e===1?t.getContext("webgl",VS)||t.getContext("experimental-webgl",VS):t.getContext("webgl2",VS)}var wu;(function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"})(wu||(wu={}));var Ns;(function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"})(Ns||(Ns={}));var Cn;(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"})(Cn||(Cn={}));function Lu(e,t){return[t,e]}function KK(e,t){return e*t}function Jte(e,t){return[t*4,e]}function Su(e){const t=P(e),n=Math.ceil(t/4);return Ve(n)}function Zte(e,t){if(e%t!==0)throw new Error(`unpackedSize (${e}) must be a multiple of ${t}`);return e/t}function Qte(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 wc(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function XK(e,t){const[n,s]=wc(e,t);return n*s*4}function GS(e,t){const n=e;let s,i,o,a,c,h,d,m,f,b;return oe().getNumber("WEBGL_VERSION")===2?(s=n.R32F,i=n.R16F,o=n.RGBA16F,a=n.RGBA32F,c=n.RED,d=4,m=1,f=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,f=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:f,textureTypeFloat:b}}function Ee(e,t){const n=t();return oe().getBool("DEBUG")&&JK(e),n}function JK(e){const t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+t5(e,t))}const ZK=596e-10,QK=65504;function e5(e){return!!(oe().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||ZK<Math.abs(e)&&Math.abs(e)<QK)}function t5(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 Wm(e,t){return hr(e,()=>e.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function n5(e,t){const n=hr(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(Ee(e,()=>e.shaderSource(n,t)),Ee(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 s5(e,t){const n=hr(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(Ee(e,()=>e.shaderSource(n,t)),Ee(e,()=>e.compileShader(n)),e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw r5(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}const i5=/ERROR: [0-9]+:([0-9]+):/g;function r5(e,t){const n=i5.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((f,b)=>pt((b+1).toString(),o)+f);let c=0;for(let f=0;f<a.length;f++)c=Math.max(a[f].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 ${pt(d[0],c)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(m.join(`
|
|
`))}function o5(e){return hr(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function a5(e,t){if(Ee(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 YS(e,t){if(Ee(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function c5(e,t){const n=hr(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Ee(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),Ee(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function l5(e,t){const n=hr(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return Ee(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),Ee(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function ene(){return oe().getNumber("WEBGL_VERSION")===2?1:4}function h5(e){return hr(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function u5(e,t){const n=oe().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 d5(e){return hr(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function eC(e,t,n,s,i,o,a){const c=e.getAttribLocation(t,n);return c===-1?!1:(Ee(e,()=>e.bindBuffer(e.ARRAY_BUFFER,s)),Ee(e,()=>e.vertexAttribPointer(c,i,e.FLOAT,!1,o,a)),Ee(e,()=>e.enableVertexAttribArray(c)),!0)}function p5(e,t,n){nC(e,n),Ee(e,()=>e.activeTexture(e.TEXTURE0+n)),Ee(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function tne(e,t){nC(e,t),Ee(e,()=>e.activeTexture(e.TEXTURE0+t)),Ee(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function m5(e,t,n){return hr(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function f5(e,t,n){return e.getUniformLocation(t,n)}function g5(e,t,n,s){Ee(e,()=>p5(e,t,s)),Ee(e,()=>e.uniform1i(n,s))}function nne(e){Ee(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),Ee(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),Ee(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function HS(e,t,n){Ee(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),Ee(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function tC(e,t){Ee(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),Ee(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function $m(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+y5(e,t))}function y5(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 hr(e,t,n){const s=Ee(e,()=>t());if(s==null)throw new Error(n);return s}function nC(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 Lc(e,t=2){return P(e.slice(0,e.length-t))}function Sc(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 qS(e){let t=[1,1,1];const n=e.length===0||e.length===1&&e[0]===1;return n||(t=[Lc(e),...Sc(e)]),t}function b5(e,t=!1){let n=oe().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(n=n*2,e=e.map((i,o)=>o>=e.length-2?T(e[o]):e[o]),e.length===1&&(e=[2,e[0]])),e.length!==2){const i=ln(e);e=i.newShape}let s=P(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=Lc(e);let o=2,a=2;return e.length&&([o,a]=Sc(e)),s=i*(o/2)*(a/2),Ve(s).map(c=>c*2)}return Ve(s)}function Um(e){return e%2===0}function Bm(e,t){if(e=e.slice(-2),t=t.slice(-2),ae(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(Um(n)&&Um(s)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&Um(e[0])&&Um(t[0])}let Mm,Pm;function w5(e){if(Mm==null){const t=Fi(e);Mm=t.getParameter(t.MAX_TEXTURE_SIZE)}return Mm}function sne(){Mm=null}function ine(){Pm=null}function L5(e){if(Pm==null){const t=Fi(e);Pm=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Pm)}function S5(e){if(e===0)return 0;let t;const n=Fi(e);return Gs(n,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:Gs(n,"EXT_disjoint_timer_query")?t=1:t=0,t}function Gs(e,t){const n=e.getExtension(t);return n!=null}function sC(e){try{const t=Fi(e);if(t!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function I5(e){if(e===0)return!1;const t=Fi(e);if(e===1){if(!Gs(t,"OES_texture_float"))return!1}else if(!Gs(t,"EXT_color_buffer_float"))return!1;const n=jS(t);return n}function x5(e){if(e===0)return!1;const t=Fi(e);if(e===1){if(!Gs(t,"OES_texture_float"))return!1;if(!Gs(t,"WEBGL_color_buffer_float"))return!1}else{if(Gs(t,"EXT_color_buffer_float"))return jS(t);const s="EXT_color_buffer_half_float";if(Gs(t,s)){const i=t.getExtension(s);return T5(t,i)}return!1}const n=jS(t);return n}function jS(e){const t=GS(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 T5(e,t){const n=GS(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 A5(e){if(e!==2)return!1;const t=Fi(e),n=t.fenceSync!=null;return n}function Iu(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{n!=null&&A(n.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the WebGL backend.`)})}const Ge=oe();Ge.registerFlag("HAS_WEBGL",()=>Ge.getNumber("WEBGL_VERSION")>0),Ge.registerFlag("WEBGL_VERSION",()=>sC(2)?2:sC(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",()=>w5(Ge.getNumber("WEBGL_VERSION"))),Ge.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>L5(Ge.getNumber("WEBGL_VERSION"))),Ge.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{const e=Ge.getNumber("WEBGL_VERSION");return e===0?0:S5(e)}),Ge.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>Ge.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!yT()),Ge.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>I5(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",()=>x5(Ge.getNumber("WEBGL_VERSION"))),Ge.registerFlag("WEBGL_FENCE_API_ENABLED",()=>A5(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:v5,addImpl:N5,ceilImpl:C5,expImpl:R5,expm1Impl:O5,floorImpl:E5,logImpl:D5,maxImpl:k5,multiplyImpl:F5,rsqrtImpl:_5,sliceImpl:W5,subImpl:$5,transposeImpl:KS,uniqueImpl:U5}=m4;class B5{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 M5{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 P5{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 iC(e,t){return["x","y","z","w","u","v"].slice(0,t).map(n=>`${e}.${n}`)}function Mn(e,t){return t===1?[e]:iC(e,t)}function z5(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 Pn(){let e,t,n,s,i,o,a,c,h,d;return oe().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 ea(e,t,n="index"){const s=je(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 zm(e){return e.length===1?`${e[0]}`:`vec${e.length}(${e.join(",")})`}function rne(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(`${zm(a)}, ${zm(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(`${zm(o)}, ${zm(a)}`)}return n.map((o,a)=>`dot(${o})`).join("+")}function XS(e){const t=je(e).map(n=>n.toString());return`
|
|
int getFlatIndex(ivec3 coords) {
|
|
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
|
|
}
|
|
`}const rC=`
|
|
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:oC}=Ww;function V5(e,t,n,s){const i=[];e.forEach(L=>{const x=P(L.shapeInfo.logicalShape);L.shapeInfo.isUniform?i.push(`uniform float ${L.name}${x>1?`[${x}]`:""};`):(i.push(`uniform sampler2D ${L.name};`),i.push(`uniform int offset${L.name};`))});const o=i.join(`
|
|
`),a=e.map(L=>G5(L,t,s)).join(`
|
|
`),c=t.texShape,h=Pn(),d=q5(h);let m,f,b=X5(h);t.isPacked?(m=Y5(t.logicalShape,c),f=K5(h)):(m=H5(t.logicalShape,c),f=j5(h)),s&&(b+=e8);const w=[b,d,f,o,m,a,n].join(`
|
|
`);return w}function Ic(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return d8(e);case 1:return m8(e);case 2:return g8(e);case 3:return b8(e);case 4:return L8(e);case 5:return S8(e);case 6:return I8(e);default:throw new Error(`${t.length}-D input sampling is not yet supported`)}}function aC(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return u8(e);case 1:return p8(e);case 2:return f8(e);case 3:return y8(e);default:return w8(e)}}function G5(e,t,n=!1){let s="";n?s+=aC(e):s+=Ic(e);const i=e.shapeInfo.logicalShape,o=t.logicalShape;return i.length<=o.length&&(n?s+=x8(e,t):s+=T8(e,t)),s}function Y5(e,t){switch(e.length){case 0:return cC();case 1:return t8(e,t);case 2:return l8(e,t);case 3:return s8(e,t);default:return r8(e,t)}}function H5(e,t){switch(e.length){case 0:return cC();case 1:return n8(e,t);case 2:return h8(e,t);case 3:return i8(e,t);case 4:return o8(e,t);case 5:return a8(e,t);case 6:return c8(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function q5(e){return`
|
|
float sampleTexture(sampler2D textureSampler, vec2 uv) {
|
|
return ${e.texture2D}(textureSampler, uv).r;
|
|
}
|
|
`}function j5(e){return`
|
|
void setOutput(float val) {
|
|
${e.output} = vec4(val, 0, 0, 0);
|
|
}
|
|
`}function K5(e){return`
|
|
void setOutput(vec4 val) {
|
|
${e.output} = val;
|
|
}
|
|
`}function X5(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);
|
|
}
|
|
|
|
${J5}
|
|
${Z5}
|
|
${Q5}
|
|
`;return t}const J5=`
|
|
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);
|
|
}
|
|
`,Z5=`
|
|
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);
|
|
}
|
|
`,Q5=`
|
|
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);
|
|
}
|
|
`,e8=`
|
|
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 cC(){return`
|
|
int getOutputCoords() {
|
|
return 0;
|
|
}
|
|
`}function t8(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 n8(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 s8(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 i8(e,t){const n=ea(["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 r8(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 o8(e,t){const n=ea(["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 a8(e,t){const n=ea(["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 c8(e,t){const n=ea(["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 l8(e,t){const n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(ae(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 h8(e,t){return ae(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 ta(e){return`offset${e}`}function u8(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),s=Pn();return`
|
|
vec4 ${n}() {
|
|
return ${s.texture2D}(${t}, halfCR);
|
|
}
|
|
`}function d8(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=ta(t);return`
|
|
float ${n}() {
|
|
vec2 uv = uvFromFlat(${o}, ${a}, ${c});
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function p8(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=Pn();return`
|
|
vec4 ${n}(int index) {
|
|
vec2 uv = packedUVfrom1D(
|
|
${i[0]}, ${i[1]}, index);
|
|
return ${o.texture2D}(${t}, uv);
|
|
}
|
|
`}function m8(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`
|
|
float ${n}(int index) {
|
|
${xc(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=ta(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 f8(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=Pn();if(i!=null&&ae(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 g8(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&&ae(t,i)){const f=i[0],b=i[1];return`
|
|
float ${s}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${b}.0, ${f}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}const{newShape:o,keptDims:a}=ln(t),c=o;if(c.length<t.length){const f=Tc(e,c),b=["row","col"];return`
|
|
${Ic(f)}
|
|
float ${s}(int row, int col) {
|
|
return ${s}(${Ac(b,a)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${s}(int row, int col) {
|
|
int index = round(dot(vec2(row, col), vec2(${t[1]}, 1)));
|
|
${xc(e)}
|
|
}
|
|
`;const h=i[0],d=i[1],m=ta(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 y8(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 f=t.slice(1),b=[1,2],w=Tc(e,f),L=["b","row","col"];return`
|
|
${aC(w)}
|
|
vec4 ${s}(int b, int row, int col) {
|
|
return ${s}(${Ac(L,b)});
|
|
}
|
|
`}const a=o[0],c=o[1],h=Math.ceil(t[2]/2),d=h*Math.ceil(t[1]/2),m=Pn();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 b8(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}=ln(t),h=a;if(h.length<t.length){const L=Tc(e,h),x=["row","col","depth"];return`
|
|
${Ic(L)}
|
|
float ${s}(int row, int col, int depth) {
|
|
return ${s}(${Ac(x,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)));
|
|
${xc(e)}
|
|
}
|
|
`;const d=e.shapeInfo.texShape,m=d[0],f=d[1],b=e.shapeInfo.flatOffset;if(f===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(${f}.0, ${m}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;if(f===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(${f}.0, ${m}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;const w=ta(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}, ${f}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function w8(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),f="int b, int row, int col",b=`b * ${m} + (row / 2) * ${d} + (col / 2)`;for(let L=2;L<n-1;L++)f=`int b${L}, `+f,m*=t[n-L-1],b=`b${L} * ${m} + `+b;const w=Pn();return`
|
|
vec4 ${i}(${f}) {
|
|
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 L8(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}=ln(t);if(c.length<t.length){const L=Tc(e,c),x=["row","col","depth","depth2"];return`
|
|
${Ic(L)}
|
|
float ${s}(int row, int col, int depth, int depth2) {
|
|
return ${s}(${Ac(x,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)));
|
|
${xc(e)}
|
|
}
|
|
`;const d=e.shapeInfo.flatOffset,m=e.shapeInfo.texShape,f=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, ${f}.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, ${f}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;const w=ta(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(${f}, ${b}, index + ${w});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function S8(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}=ln(t);if(h.length<t.length){const x=Tc(e,h),v=["row","col","depth","depth2","depth3"];return`
|
|
${Ic(x)}
|
|
float ${s}(int row, int col, int depth, int depth2, int depth3) {
|
|
return ${s}(${Ac(v,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;
|
|
${xc(e)}
|
|
}
|
|
`;const m=e.shapeInfo.flatOffset,f=e.shapeInfo.texShape,b=f[0],w=f[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=ta(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 I8(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:i,keptDims:o}=ln(t);if(i.length<t.length){const v=Tc(e,i),N=["row","col","depth","depth2","depth3","depth4"];return`
|
|
${Ic(v)}
|
|
float ${s}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
return ${s}(${Ac(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)));
|
|
${xc(e)}
|
|
}
|
|
`;const f=e.shapeInfo.flatOffset,b=e.shapeInfo.texShape,w=b[0],L=b[1];if(L===m&&f==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&&f==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 x=ta(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 + ${x};
|
|
vec2 uv = uvFromFlat(${w}, ${L}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function xc(e){const t=e.name,n=P(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`
|
|
for (int i = 0; i < ${n}; i++) {
|
|
if (i == index) {
|
|
return ${t}[i];
|
|
}
|
|
}
|
|
`}function x8(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=oC(e.shapeInfo.logicalShape,t.logicalShape),h=Rt(a),d=a-o;let m;const f=["x","y","z","w","u","v"];o===0?m="":a<2&&c.length>=1?m="coords = 0;":m=c.map(O=>`coords.${f[O+d]} = 0;`).join(`
|
|
`);let b="";a<2&&o>0?b="coords":b=e.shapeInfo.logicalShape.map((O,E)=>`coords.${f[E+d]}`).join(", ");let w="return outputValue;";const L=P(e.shapeInfo.logicalShape),x=L===1,v=P(t.logicalShape),N=v===1;if(o===1&&!x&&!N)w=`
|
|
return vec4(outputValue.xy, outputValue.xy);
|
|
`;else if(x&&!N)a===1?w=`
|
|
return vec4(outputValue.x, outputValue.x, 0., 0.);
|
|
`:w=`
|
|
return vec4(outputValue.x);
|
|
`;else if(c.length){const O=o-2,E=o-1;c.indexOf(O)>-1&&c.indexOf(E)>-1?w="return vec4(outputValue.x);":c.indexOf(O)>-1?w="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":c.indexOf(E)>-1&&(w="return vec4(outputValue.xx, outputValue.zz);")}return`
|
|
vec4 ${i}() {
|
|
${h} coords = getOutputCoords();
|
|
${m}
|
|
vec4 outputValue = get${s}(${b});
|
|
${w}
|
|
}
|
|
`}function T8(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&&ae(a,o))return`
|
|
float ${i}() {
|
|
return sampleTexture(${n}, resultUV);
|
|
}
|
|
`;const d=Rt(h),m=oC(e.shapeInfo.logicalShape,t.logicalShape),f=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(x=>`coords.${w[x+f]} = 0;`).join(`
|
|
`);let L="";return h<2&&c>0?L="coords":L=e.shapeInfo.logicalShape.map((x,v)=>`coords.${w[v+f]}`).join(", "),`
|
|
float ${i}() {
|
|
${d} coords = getOutputCoords();
|
|
${b}
|
|
return get${s}(${L});
|
|
}
|
|
`}function Rt(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 Tc(e,t){const n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function Ac(e,t){return t.map(n=>e[n]).join(", ")}class A8{constructor(e,t,n,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,A(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=Rt(c),d=Mn("coords",c);let m,f;if(o===1){f=c+1;const $=Rt(f);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 f=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,f),w="."+b[f-1],L=b.map($=>"int "+$),x=Mn("sourceLocR",f-1).concat("inIdx.r"),v=Mn("sourceLocG",f-1).concat("inIdx.g"),N=Mn("sourceLocB",f-1).concat("inIdx.b"),O=Mn("sourceLocA",f-1).concat("inIdx.a"),E=n==="max"?"greaterThan":"lessThan",k=s?"":`
|
|
inIdx = round(vec4(getBestIndicesAChannel(${x.join()}),
|
|
getBestIndicesAChannel(${v.join()}),
|
|
getBestIndicesAChannel(${N.join()}),
|
|
getBestIndicesAChannel(${O.join()})));`,F=`vec4(
|
|
getAChannel(${x.join()}),
|
|
hasNextCol ? getAChannel(${v.join()}) : 0.,
|
|
hasNextRow ? getAChannel(${N.join()}) : 0.,
|
|
hasNextRow && hasNextCol ? getAChannel(${O.join()}) : 0.)`,U=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()}));
|
|
}
|
|
${U}
|
|
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 = ${F};
|
|
|
|
for (int i = 0; i < ${t}; i++) {
|
|
inIdx = srcIdx;
|
|
${k}
|
|
vec4 candidate = ${F};
|
|
bvec4 nan = isnan(candidate);
|
|
bvec4 replace = bvec4(
|
|
vec4(${E}(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 v8{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,f=1/(t*n);this.userCode=`
|
|
const ivec2 pads = ivec2(${d}, ${m});
|
|
const float avgMultiplier = float(${f});
|
|
|
|
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 N8{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,f=e.effectiveFilterHeight,b=e.effectiveFilterWidth,w=m-1-e.padInfo.front,L=f-1-e.padInfo.top,x=b-1-e.padInfo.left,v=1/(t*n*s);this.userCode=`
|
|
const ivec3 pads = ivec3(${w}, ${L}, ${x});
|
|
const float avgMultiplier = float(${v});
|
|
|
|
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 < ${f};
|
|
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 lC=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,C8=`
|
|
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;
|
|
}
|
|
`,R8=`
|
|
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);
|
|
`,one="return (a - b) * (a - b);",O8="return float(a == b);",E8="return float(a < b);",D8="return float(a <= b);",k8="return float(a > b);",F8="return float(a >= b);",_8="return float(a >= 1.0 && b >= 1.0);",W8="return float(a >= 1.0 || b >= 1.0);",$8=lC+`
|
|
return max(a, b);
|
|
`,U8=lC+`
|
|
return min(a, b);
|
|
`,B8=`if (b == 0.0) return NAN;
|
|
return mod(a, b);`,M8="return (b >= 1.0) ? a : a * (b + 1.0);",hC="return (a < 0.) ? b * a : a;";class Wn{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=nt(t,n),this.userCode=`
|
|
float binaryOperation(float a, float b) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
float a = getAAtOutCoords();
|
|
float b = getBAtOutCoords();
|
|
setOutput(binaryOperation(a, b));
|
|
}
|
|
`}}const Vm=`
|
|
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;
|
|
`,P8=`
|
|
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);
|
|
`,z8=`
|
|
// 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));
|
|
`+Vm+`
|
|
return result;
|
|
`,uC=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`,V8=`
|
|
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
|
|
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
|
|
`,G8=`
|
|
return vec4(equal(a, b));
|
|
`,ane=`
|
|
return vec4(notEqual(a, b));
|
|
`,Y8=`
|
|
return vec4(lessThan(a, b));
|
|
`,H8=`
|
|
return vec4(lessThanEqual(a, b));
|
|
`,q8=`
|
|
return vec4(greaterThan(a, b));
|
|
`,j8=`
|
|
return vec4(greaterThanEqual(a, b));
|
|
`,K8=`
|
|
return vec4(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) *
|
|
vec4(greaterThanEqual(b, vec4(1.0))));
|
|
`,X8=`
|
|
return min(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) +
|
|
vec4(greaterThanEqual(b, vec4(1.0))),
|
|
vec4(1.0));
|
|
`,J8=`
|
|
vec4 result = vec4(max(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+Vm+`
|
|
return result;
|
|
`,Z8=`
|
|
vec4 result = vec4(min(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+Vm+`
|
|
return result;
|
|
`,Q8=`
|
|
vec4 result = mod(a, b);
|
|
vec4 isNaN = vec4(equal(b, vec4(0.0)));
|
|
`+Vm+`
|
|
return result;
|
|
`;class ur{constructor(e,t,n,s=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=nt(t,n);const i=this.outputShape.length;let o="";if(s)if(i===0||P(this.outputShape)===1)o=`
|
|
result.y = 0.;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else{const a=Rt(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=Mn("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 e6{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 t6{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 n6{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 s6{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 i6{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 r6{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 o6{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 a6{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 c6{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 dC{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,f=e.filterWidth,b=Math.floor(e.inChannels/4)*4,w=e.inChannels%4,L=e.dataFormat==="channelsLast",x=L?1:2,v=L?2:3,N=L?3:1;let O="",E="";n&&(s?O=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:O=`
|
|
float activation(float x) {
|
|
${n}
|
|
}
|
|
`,E="result = activation(result);");const k=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
|
|
${O}
|
|
|
|
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[${x}], coords[${v}]) * 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 < ${f}; 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;
|
|
${k}
|
|
${E}
|
|
setOutput(result);
|
|
}
|
|
`}}class l6{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,f=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 < ${f}; 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 pC{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,f=e.dilationWidth,b=e.filterHeight,w=e.filterWidth,L=e.outChannels/e.inChannels;let x="",v="";n&&(s?x=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:x=`
|
|
float activation(float x) {
|
|
${n}
|
|
}
|
|
`,v="result = activation(result);");const N=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
|
|
${x}
|
|
|
|
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 * ${f};
|
|
|
|
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}
|
|
${v}
|
|
setOutput(result);
|
|
}
|
|
`}}class mC{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,f=e.dilationWidth,b=e.filterHeight,w=e.filterWidth,L=w;let x="int xR; int xC; int xCOffset;";for(let E=0;E<b;E++)for(let k=0;k<w;k++)x+=`
|
|
vec4 xTexelR${E}C${k*2} = vec4(0.);
|
|
vec4 wR${E}C${k} = vec4(0.);
|
|
vec4 xR${E}C${k} = vec4(0.);`;for(let E=0;E<b;E++)for(let k=0;k<L;k++){const F=k*2;if(x+=`
|
|
xR = xRCorner + ${E*m};
|
|
xC = xCCorner + ${F*f};
|
|
`,d===1){if(F<w&&(c%2===1?x+=`
|
|
xCOffset = xC + 1;
|
|
if(xR >= 0 && xR < ${i} && xCOffset >= 0 && xCOffset < ${o}) {
|
|
xTexelR${E}C${F} = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if(xCOffset + 1 >= ${o}) {
|
|
xTexelR${E}C${F}.zw = vec2(0.);
|
|
}
|
|
} else {
|
|
xTexelR${E}C${F} = 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${E}C${F} = vec4(previous.zw, xTexelR${E}C${F}.xy);
|
|
} else {
|
|
xR${E}C${F} = vec4(0, 0, xTexelR${E}C${F}.xy);
|
|
}
|
|
`:x+=`
|
|
if(xR >= 0 && xR < ${i} && xC >= 0 && xC < ${o}) {
|
|
xTexelR${E}C${F} = getX(batch, xR, xC, d1);
|
|
} else {
|
|
xTexelR${E}C${F} = vec4(0.);
|
|
}
|
|
|
|
xR${E}C${F} = xTexelR${E}C${F};
|
|
`,F+1<w)){const U=c%2===0?T(f):f;f%2===0&&c%2===1||f%2!==0&&c%2!==1?(x+=`
|
|
xCOffset = xC + ${c%2} + ${U};
|
|
|
|
if(xR >= 0 && xR < ${i} &&
|
|
xCOffset >= 0 && xCOffset < ${o}) {
|
|
xTexelR${E}C${F+2} = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
`,f>1&&(x+=`
|
|
xCOffset -= 2;
|
|
if(xR >= 0 && xR < ${i} &&
|
|
xCOffset >= 0 && xCOffset < ${o}) {
|
|
xTexelR${E}C${F} = getX(batch, xR, xCOffset, d1);
|
|
} else {
|
|
xTexelR${E}C${F} = vec4(0.);
|
|
}
|
|
`),x+=`
|
|
xR${E}C${F+1} = vec4(
|
|
xTexelR${E}C${F}.zw, xTexelR${E}C${F+2}.xy);
|
|
`):x+=`
|
|
xCOffset = xC + ${U};
|
|
|
|
if(xR >= 0 && xR < ${i} &&
|
|
xCOffset >= 0 && xCOffset < ${o}) {
|
|
xTexelR${E}C${F+2} = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
|
|
xR${E}C${F+1} = xTexelR${E}C${F+2};
|
|
`}}else F<w&&(x+=`
|
|
if(xR >= 0 && xR < ${i}) {
|
|
`,c%2===1?(x+=`
|
|
xCOffset = xC + 1 - ${d};
|
|
if(xCOffset >= 0 && xCOffset < ${o}) {
|
|
xTexelR${E}C${F} = getX(batch, xR, xCOffset, d1);
|
|
} else {
|
|
xTexelR${E}C${F} = vec4(0.);
|
|
}
|
|
|
|
if(xC + 1 >= 0 && xC + 1 < ${o}) {
|
|
xTexelR${E}C${F+2} = getX(batch, xR, xC + 1, d1);
|
|
} else {
|
|
xTexelR${E}C${F+2} = vec4(0.);
|
|
}
|
|
|
|
xR${E}C${F} = vec4(
|
|
xTexelR${E}C${F}.zw, xTexelR${E}C${F+2}.zw);
|
|
`,F+1<w&&(x+=`
|
|
vec4 final = vec4(0.);
|
|
xCOffset = xC + 1 + ${d};
|
|
if(xCOffset >= 0 && xCOffset < ${o}) {
|
|
final = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
xR${E}C${F+1} = vec4(xTexelR${E}C${F+2}.xy, final.xy);
|
|
`)):(x+=`
|
|
if(xC >= 0 && xC < ${o}) {
|
|
xTexelR${E}C${F} = getX(batch, xR, xC, d1);
|
|
} else {
|
|
xTexelR${E}C${F} = vec4(0.);
|
|
}
|
|
|
|
xCOffset = xC + ${d};
|
|
if(xCOffset >= 0 && xCOffset < ${o}) {
|
|
xTexelR${E}C${F+2} = getX(batch, xR, xCOffset, d1);
|
|
} else {
|
|
xTexelR${E}C${F+2} = vec4(0.);
|
|
}
|
|
|
|
xR${E}C${F} = vec4(
|
|
xTexelR${E}C${F}.xy, xTexelR${E}C${F+2}.xy);
|
|
`,F+1<w&&(x+=`
|
|
xR${E}C${F+1} = vec4(
|
|
xTexelR${E}C${F}.zw, xTexelR${E}C${F+2}.zw);
|
|
`)),x+="}");F<w&&(x+=`
|
|
vec4 wTexelR${E}C${F} = getW(${E}, ${F}, d1, q);
|
|
wR${E}C${F} = vec4(wTexelR${E}C${F}.xz, wTexelR${E}C${F}.xz);
|
|
`,F+1<w&&(x+=`
|
|
vec4 wTexelR${E}C${F+1} = getW(${E}, ${F+1}, d1, q);
|
|
wR${E}C${F+1} =
|
|
vec4(wTexelR${E}C${F+1}.xz, wTexelR${E}C${F+1}.xz);`))}for(let E=0;E<b;E++)for(let k=0;k<w;k++)x+=`dotProd += xR${E}C${k} * wR${E}C${k};`;let v="",N="";n&&(s?v=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:v=`vec4 activation(vec4 x) {
|
|
${n}
|
|
}`,N="result = activation(result);");const O=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),this.userCode=`
|
|
${v}
|
|
|
|
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.);
|
|
|
|
${x}
|
|
|
|
vec4 result = dotProd;
|
|
${O}
|
|
${N}
|
|
setOutput(result);
|
|
}
|
|
`}}class h6{constructor(e,t,n,s,i){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[o,a,c,h]=e,[d]=t,[m,f]=n;this.outputShape=[d,m,f,h];const b=s==="bilinear"?1:0,[w,L]=[`${a-1}.0`,`${c-1}.0`],[x,v,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}`],[O,E,k]=f>1?[`${(c-1)/(f-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(${x});
|
|
const float width_ratio = float(${O});
|
|
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 = ${v};
|
|
float width_scale = ${E};
|
|
|
|
float in_y = ${N};
|
|
if( in_y < 0.0 || in_y > ${w} ) {
|
|
setOutput(float(${i}));
|
|
return;
|
|
}
|
|
float in_x = ${k};
|
|
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 fC{constructor(e,t,n){this.variableNames=["x"],this.outputShape=e;const s=e.length,i=t?"0.0":`getX(${gC(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() {
|
|
${Rt(s)} coords = getOutputCoords();
|
|
int end = ${yC(s,"coords")};
|
|
float val = ${i};
|
|
int pow2 = int(pow(2.0, index));
|
|
if (${a}) {
|
|
int idx = ${c};
|
|
${yC(s,"coords")} = idx;
|
|
val += getX(${gC(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 gC(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 yC(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 u6{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=wu.DENSE;const t=Su(e),n=Pn();this.outputShape=e,this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${ea(["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 d6{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=wu.DENSE;const t=Su(e),n=Pn();this.outputShape=e,this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${ea(["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 p6{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 m6{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 f6{constructor(e){this.variableNames=["A"],this.outTexUsage=Ns.DOWNLOAD;const t=Pn();this.outputShape=e,this.userCode=`
|
|
${rC}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}}class g6{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Ns.DOWNLOAD;const t=Pn();this.outputShape=e,this.userCode=`
|
|
${rC}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}}class y6{constructor(e,t,n=!1){this.variableNames=["A"];const s=Pn(),[i,o]=t;this.outputShape=e;let a="result";n&&(a="floor(result * 255. + 0.5)"),this.userCode=`
|
|
${XS(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 b6{constructor(e,t,n=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const s=Pn(),[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=`
|
|
${XS(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};
|
|
}
|
|
`}}class w6{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 L6{constructor(e,t,n){this.variableNames=["A","indices"];const s=e.slice();s[n]=t,this.outputShape=s,this.rank=s.length;const i=Rt(this.rank),o=S6(e,n);this.userCode=`
|
|
void main() {
|
|
${i} resRC = getOutputCoords();
|
|
setOutput(getA(${o}));
|
|
}
|
|
`}}function S6(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 I6{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;const s=Rt(t.length),i=Rt(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 x6(e){const t=Pn(),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 n5(e,n)}function T6(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 c5(e,t)}function A6(e){const t=new Uint16Array([0,1,2,2,1,3]);return l5(e,t)}function xu(e,t,n,s,i,o){u5(t,n);const a=h5(e),c=e.TEXTURE_2D;return Ee(e,()=>e.bindTexture(c,a)),Ee(e,()=>e.texParameteri(c,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),Ee(e,()=>e.texParameteri(c,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),Ee(e,()=>e.texParameteri(c,e.TEXTURE_MIN_FILTER,e.NEAREST)),Ee(e,()=>e.texParameteri(c,e.TEXTURE_MAG_FILTER,e.NEAREST)),Ee(e,()=>e.texImage2D(c,0,s,t,n,0,i,o,null)),Ee(e,()=>e.bindTexture(e.TEXTURE_2D,null)),a}function bC(e){return e.internalFormatFloat}function v6(e,t,n,s){const[i,o]=Lu(t,n);return xu(e,i,o,bC(s),s.textureFormatFloat,e.FLOAT)}function wC(e){return e.internalFormatHalfFloat}function N6(e,t,n,s){const[i,o]=Lu(t,n);return xu(e,i,o,wC(s),s.textureFormatFloat,s.textureTypeHalfFloat)}function LC(e){return e.downloadTextureFormat}function C6(e,t,n,s){const[i,o]=Lu(t,n);return xu(e,i,o,LC(s),e.RGBA,e.UNSIGNED_BYTE)}function SC(e){return e.internalFormatPackedFloat}function R6(e,t,n,s){const[i,o]=wc(t,n);return xu(e,i,o,SC(s),e.RGBA,e.FLOAT)}function IC(e){return e.internalFormatPackedHalfFloat}function O6(e,t,n,s){const[i,o]=wc(t,n);return xu(e,i,o,IC(s),e.RGBA,s.textureTypeHalfFloat)}function E6(e,t,n){const s=0,i=3*4,o=3*4+2*4;Ee(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n));const a=eC(e,t,"clipSpacePos",n,3,o,s);return a&&eC(e,t,"uv",n,2,o,i)}function D6(e,t,n,s,i,o){Ee(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),Ee(e,()=>e.texImage2D(e.TEXTURE_2D,0,h,n,s,0,e.RGBA,c,a)),Ee(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function k6(e,t,n){Ee(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?Ee(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):Ee(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),Ee(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function F6(e,t,n,s){const i=e.createBuffer();Ee(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,i));const o=4,a=4,c=o*a*t*n;return Ee(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,c,e.STREAM_READ)),Ee(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),Ee(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),i}function _6(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 W6(e,t,n,s){const[i,o]=Lu(t,n),a=4,c=new Uint8Array(KK(t*n,a));return Ee(e,()=>e.readPixels(0,0,i,o,s.downloadTextureFormat,e.UNSIGNED_BYTE,c)),new Float32Array(c.buffer)}function $6(e,t,n,s,i,o,a,c){const h=e,d=new Float32Array(XK(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 U6(e,t,n){const s=new Float32Array(t*n*4);return Ee(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,s)),s}class B6{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];const t=oe().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,HK(t,e)):this.gl=Fi(t);let n="WEBGL_color_buffer_float";const s="EXT_color_buffer_half_float";if(oe().getNumber("WEBGL_VERSION")===1){const i="OES_texture_float",o="OES_texture_half_float";if(this.textureFloatExtension=Wm(this.gl,i),Gs(this.gl,o))this.textureHalfFloatExtension=Wm(this.gl,o);else if(oe().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),Gs(this.gl,s))this.colorBufferHalfFloatExtension=Wm(this.gl,s);else if(oe().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",Gs(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else if(Gs(this.gl,s))this.colorBufferHalfFloatExtension=this.gl.getExtension(s);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=T6(this.gl),this.indexBuffer=A6(this.gl),this.framebuffer=d5(this.gl),this.textureConfig=GS(this.gl,this.textureHalfFloatExtension)}get debug(){return oe().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;Ee(e,()=>e.finish()),Ee(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),Ee(e,()=>e.deleteFramebuffer(this.framebuffer)),Ee(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),Ee(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),Ee(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),v6(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),N6(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),C6(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),k6(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,s){this.throwIfDisposed(),D6(this.gl,e,t,n,s,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),O6(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),R6(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(tC(this.gl,this.framebuffer),this.outputTexture=null),Ee(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,()=>W6(this.gl,t,n,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,n,s,i,o){return $6(this.gl,e,t,n,s,i,o,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return _6(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);const s=F6(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(oe().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 oe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,oe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,()=>U6(this.gl,t,n))}createProgram(e){this.throwIfDisposed();const t=this.gl,n=s5(t,e),s=x6(t),i=o5(t);return Ee(t,()=>t.attachShader(i,s)),Ee(t,()=>t.attachShader(i,n)),a5(t,i),this.debug&&YS(t,i),this.vertexAttrsAreBound||(this.setProgram(i),this.vertexAttrsAreBound=E6(t,this.program,this.vertexBuffer)),i}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&Ee(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&YS(this.gl,this.program),Ee(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?m5(this.gl,e,t):f5(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),Ee(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(),g5(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();const[s,i]=wc(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&&YS(this.gl,this.program),$m(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const e=this.gl;this.debug&&this.debugValidate(),Ee(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),Ee(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=Wm(this.gl,oe().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(oe().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(oe().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 $t(()=>this.disposed||this.isQueryAvailable(e,oe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,oe().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=M6(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;$t(()=>(this.pollItems(),this.itemsToPoll.length===0))}bindTextureToFrameBuffer(e){this.throwIfDisposed(),HS(this.gl,e,this.framebuffer),this.debug&&$m(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(HS(this.gl,this.outputTexture,this.framebuffer),this.debug&&$m(this.gl)):tC(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;HS(s,e,this.framebuffer),this.debug&&$m(s),this.outputTexture=e,Ee(s,()=>s.viewport(0,0,t,n)),Ee(s,()=>s.scissor(0,0,t,n))}setOutputMatrixWriteRegionDriver(e,t,n,s){this.throwIfDisposed(),Ee(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 M6(e){let t=0;for(;t<e.length;++t){const n=e[t]();if(!n)break}return t-1}function P6(e,t,n,s){const i=t.userCode,o=n.map((w,L)=>{const x={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&&(x.flatOffset=w.texData.slice.flatOffset),{name:t.variableNames[L],shapeInfo:x}}),a=o.map(w=>w.shapeInfo),c={logicalShape:s.shape,texShape:s.texData.texShape,isUniform:!1,isPacked:s.texData.isPacked,flatOffset:null},h=V5(o,c,i,t.packedInputs),d=e.createProgram(h);let m=null;const f=e.getUniformLocation(d,"NAN",!1);oe().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],x=!1;b[L]=e.getUniformLocation(d,L,x),b[`offset${L}`]=e.getUniformLocation(d,`offset${L}`,x)}return{program:t,source:h,webGLProgram:d,uniformLocations:b,inShapeInfos:a,outShapeInfo:c,infLoc:m,nanLoc:f}}function xC(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(!ae(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(!ae(c,h))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${c} and ${h} must match`)})}function z6(e,t,n,s,i){xC(t.inShapeInfos,n),xC([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),oe().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],f=t.uniformLocations[`offset${d}`];if(m==null)return;if(c.isUniform){if(P(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&&f!=null&&e.gl.uniform1i(f,c.texData.slice.flatOffset),e.setInputMatrixTexture(c.texData.texture,m,h)}),i!=null&&i(e,t.webGLProgram),e.executeProgram()}function V6(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 G6{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:f}=n,{left:b,top:w}=c,L=i*s,x=Pn(),v=f==="channelsLast",N=v?0:1,O=v?1:2;let E="";for(let k=0;k<=1;k++)for(let F=0;F<=1;F++)E+=`
|
|
blockIndex = rc.y + ${F};
|
|
pos = rc.x + ${k};
|
|
|
|
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[O]} && d1 >= 0) {
|
|
|
|
ch = int(mod(float(pos), ${i}.));
|
|
|
|
if (${v}) {
|
|
innerDims = vec2(d1, ch);
|
|
result[${k*2+F}] = getChannel(
|
|
getA(d0, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
} else {
|
|
innerDims = vec2(d0, d1);
|
|
result[${k*2+F}] = 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;
|
|
|
|
${E}
|
|
|
|
${x.output} = result;
|
|
}
|
|
`}}class Y6{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 H6{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 q6{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 j6{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 K6{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,f=h-1-e.padInfo.top,b=d-1-e.padInfo.left,w=c*h*d-1;this.userCode=`
|
|
const ivec3 pads = ivec3(${m}, ${f}, ${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 JS{constructor(e,t,n,s=!1,i=!1,o=!1,a=null,c=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n;const h=s?e[1]:e[2],d=Math.ceil(h/2),m=s?"i * 2, rc.y":"rc.y, i * 2",f=i?"rc.z, i * 2":"i * 2, rc.z",b=s?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],w=i?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let L="",x="";a&&(c?L=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${a}
|
|
}`:L=`vec4 activation(vec4 x) {
|
|
${a}
|
|
}`,x="result = activation(result);");const v=o?"result += getBiasAtOutCoords();":"";o&&this.variableNames.push("bias"),c&&this.variableNames.push("preluActivationWeights");let N="rc.x",O="rc.x";e[0]<t[0]?N=`int(min(float(rc.x), ${e[0]-1}.))`:t[0]<e[0]&&(O=`int(min(float(rc.x), ${t[0]-1}.))`),this.userCode=`
|
|
${L}
|
|
|
|
const float sharedDimension = ${d}.0;
|
|
|
|
vec4 dot2x2ARowBCol(ivec3 rc) {
|
|
vec4 result = vec4(0);
|
|
for (int i = 0; i < ${d}; i++) {
|
|
int batchA = ${N};
|
|
int batchB = ${O};
|
|
vec4 a = getMatrixA(batchA, ${m});
|
|
vec4 b = getMatrixB(batchB, ${f});
|
|
|
|
// These swizzled products need to be separately added.
|
|
// See: https://github.com/tensorflow/tfjs/issues/1735
|
|
result += (${b[0]} * ${w[0]});
|
|
result += (${b[1]} * ${w[1]});
|
|
}
|
|
return result;
|
|
}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
vec4 result = dot2x2ARowBCol(rc);
|
|
|
|
${v}
|
|
|
|
${x}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}}class X6{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 J6{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 Z6{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=Mn("rc",t),s=Rt(t),i=eX(t,e,n),o=tX(t,e[e.length-1],e[e.length-2],n),a=nX(e,n);this.userCode=`
|
|
void main() {
|
|
${s} rc = getOutputCoords();
|
|
|
|
if(${i}) {
|
|
setOutput(vec4(0));
|
|
} else {
|
|
${o}
|
|
|
|
setOutput(vec4(${a}));
|
|
}
|
|
}
|
|
`}}}function Q6(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 eX(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 tX(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 nX(e,t){const n=e.length,s=Q6(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 sX{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((h,d)=>h[0]+e[d]+h[1]);const s=e.length,i=Rt(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 iX{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((L,x)=>L[0]+e[x]+L[1]);const s=e.length,i=Rt(s),o=t.map(L=>L[0]).join(","),a=t.map((L,x)=>L[0]+e[x]).join(","),c=Mn("rc",s),h=Mn("source",s),d=`${c[s-1]} < ${this.outputShape[s-1]}`,m=s===1?"source":`vec2(${h.slice(-2).join()})`,f=[`${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,x=s===1?2:4;L<x;L++)w+=`
|
|
${f[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 Tu{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,f=e.effectiveFilterWidth,b=e.padInfo.top,w=e.padInfo.left;this.outputShape=e.outShape;const L=t==="avg",x=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,v=`(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 < ${f};
|
|
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?x:v:`wR * ${f} + wC`};
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;return}const O="max";let E=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(E="avgValue / count");const k=Math.floor(o/4)*4,F=o%4,U=`
|
|
if (${L}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${O}(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 < ${k}; 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)
|
|
);
|
|
|
|
${U}
|
|
}
|
|
|
|
int xC = xCCorner + ${k};
|
|
if (${F===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${U}
|
|
} else if (${F===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${d}, d),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${U}
|
|
} else if (${F===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${d}, d),
|
|
getValue(batch, xR, xC + 2 * ${d}, d),
|
|
initializationValue
|
|
);
|
|
|
|
${U}
|
|
}
|
|
}
|
|
setOutput(${E});
|
|
}
|
|
`}}class ZS{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,f=e.dilationWidth,b=e.effectiveFilterDepth,w=e.effectiveFilterHeight,L=e.effectiveFilterWidth,x=e.padInfo.front,v=e.padInfo.top,N=e.padInfo.left;this.outputShape=e.outShape;const O=t==="avg";let E="0.0";if(O||(E="-1.0 / 1e-20"),n){const j=">=";this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${a}, ${c}, ${h});
|
|
const ivec3 pads = ivec3(${x}, ${v}, ${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 += ${f}) {
|
|
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 ${j} 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 k="max";let F=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(F="avgValue / count");const U=Math.floor(o/4)*4,$=o%4,Y=`
|
|
if (${O}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${k}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${a}, ${c}, ${h});
|
|
const ivec3 pads = ivec3(${x}, ${v}, ${N});
|
|
const float initializationValue = ${E};
|
|
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(${E});
|
|
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 < ${U}; wC += 4) {
|
|
int xC = xCCorner + wC * ${f};
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${f}, ch),
|
|
getValue(batch, xD, xR, xC + 2 * ${f}, ch),
|
|
getValue(batch, xD, xR, xC + 3 * ${f}, ch)
|
|
);
|
|
|
|
${Y}
|
|
}
|
|
|
|
int xC = xCCorner + ${U};
|
|
if (${$===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${Y}
|
|
} else if (${$===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${f}, ch),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${Y}
|
|
} else if (${$===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${f}, ch),
|
|
getValue(batch, xD, xR, xC + 2 * ${f}, ch),
|
|
initializationValue
|
|
);
|
|
|
|
${Y}
|
|
}
|
|
}
|
|
setOutput(${F});
|
|
}
|
|
}
|
|
`}}class TC{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 f=`
|
|
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",f=`
|
|
bool reducedAllValue = all(values);
|
|
float floatedReducedAllValue = float(reducedAllValue);
|
|
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
|
|
`,b="bvec4"):t==="any"&&(a="0.0",f=`
|
|
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)
|
|
);
|
|
|
|
${f}
|
|
}
|
|
|
|
int inIdx = inOffset + ${d};
|
|
if (${m===1}) {
|
|
${b} values = ${b}(
|
|
getValue(batch, inIdx),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${f}
|
|
} else if (${m===2}) {
|
|
${b} values = ${b}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${f}
|
|
} else if (${m===3}) {
|
|
${b} values = ${b}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
initializationValue
|
|
);
|
|
|
|
${f}
|
|
}
|
|
setOutput(${h});
|
|
}
|
|
`}}class AC{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=`
|
|
${rX(t)}
|
|
${XS(e)}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
ivec3 thisRC;
|
|
int rows = ${e[1]};
|
|
int cols = ${e[2]};
|
|
|
|
${n}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}}function rX(e){const t=ea(["r","c","d"],e);return`
|
|
ivec3 inputCoordsFromReshapedOutCoords(int index) {
|
|
${t}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}class oX{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],f=1/d,b=1/m,w=Math.ceil(f)*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(${f});
|
|
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 aX{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 cX{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 lX{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],f=1/d,b=1/m,w=Math.ceil(f)*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(${f});
|
|
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 hX{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 uX{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=Rt(n);this.userCode=`
|
|
void main() {
|
|
${o} coords = getOutputCoords();
|
|
setOutput(getX(${i}));
|
|
}
|
|
`}}class dX{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=Mn("rc",n),i=`${s[n-1]} + 1 < ${this.outputShape[n-1]}`,o=`${s[n-2]} + 1 < ${this.outputShape[n-2]}`,a=Rt(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 f(w)}function h(w){return w[n-1]="("+w[n-1]+" + 1)",f(w)}function d(w){return w[n-2]="("+w[n-2]+" + 1)",f(w)}function m(w){return w[n-1]="("+w[n-1]+" + 1)",w[n-2]="("+w[n-2]+" + 1)",f(w)}function f(w){const L=e.map((N,O)=>b(O,w)),x=L.join(","),v=L.slice(-2).join(",");return`getChannel(getX(${x}), vec2(${v}))`}function b(w,L){return t.indexOf(w)!==-1&&e[w]!==1?`${e[w]} - ${L[w]} - 1`:`${L[w]}`}}}class vC{constructor(e,t,n,s,i,o,a=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=o;const c=Rt(i.length),h=Rt(o.length);let d="";n===1?d="i":n===2&&(d="i, j");const m=`getIndices(${d})`;let f="";s===1?f="i":s===2&&(f="i, coords[1]");const b=`getUpdates(${f})`,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 pX{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,f=`
|
|
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
|
|
);
|
|
|
|
${f}
|
|
}
|
|
|
|
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
|
|
);
|
|
|
|
${f}
|
|
} 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
|
|
);
|
|
|
|
${f}
|
|
} 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
|
|
);
|
|
|
|
${f}
|
|
}
|
|
setOutput(${h});
|
|
}
|
|
`}}class mX{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=Rt(n);this.userCode=`
|
|
void main() {
|
|
${o} resRC = getOutputCoords();
|
|
float cVal = getC(${s});
|
|
if (cVal >= 1.0) {
|
|
setOutput(getA(${i}));
|
|
} else {
|
|
setOutput(getB(${i}));
|
|
}
|
|
}
|
|
`}}class fX{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=Rt(this.rank),n=`uniform int start[${this.rank}];`,s=gX(this.rank);let i;const o=e.map((a,c)=>`sourceLoc.${QS[c]} = start[${c}] + coords.${QS[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 QS=["x","y","z","w","u","v"];function gX(e){if(e===1)return"sourceLoc";if(e<=6)return QS.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}class yX{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;const t=Rt(this.rank),n=Mn("coords",this.rank),s=Mn("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 bX{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const s=n.length,i=Rt(n.length),o=Rt(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 wX{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=RC(e,s,n);i in this.freeTextures||(this.freeTextures[i]=[]),i in this.usedTextures||(this.usedTextures[i]=[]);const o=NC(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===Cn.PACKED_2X2_FLOAT32?a=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):s===Cn.PACKED_2X2_FLOAT16?a=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):s===Cn.UNPACKED_FLOAT32?a=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):s===Cn.UNPACKED_FLOAT16?a=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):s===Cn.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=RC(t,i,s);o in this.freeTextures||(this.freeTextures[o]=[]);const a=NC(t,i,this.gpgpu.gl,this.gpgpu.textureConfig,s),c=oe().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 LX(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 NC(e,t,n,s,i){const o=SX(t,s);let a;if(i){const[h,d]=wc(e[0],e[1]);a=h*d}else{const[h,d]=Lu(e[0],e[1]);a=h*d}const c=LX(n,o);return a*c}function SX(e,t){switch(e){case Cn.PACKED_2X2_FLOAT32:return SC(t);case Cn.PACKED_2X2_FLOAT16:return IC(t);case Cn.UNPACKED_FLOAT32:return bC(t);case Cn.UNPACKED_FLOAT16:return wC(t);case Cn.PACKED_4X1_UNSIGNED_BYTE:return LC(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function IX(e){return oe().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Cn.PACKED_2X2_FLOAT32:Cn.UNPACKED_FLOAT32:e?Cn.PACKED_2X2_FLOAT16:Cn.UNPACKED_FLOAT16}function CC(e,t){if(e===Ns.UPLOAD)return Cn.PACKED_2X2_FLOAT32;if(e===Ns.RENDER||e==null)return IX(t);if(e===Ns.DOWNLOAD||e===Ns.PIXELS)return Cn.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function RC(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class xX{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=Rt(this.rank),i=TX(e);this.userCode=`
|
|
void main() {
|
|
${s} resRC = getOutputCoords();
|
|
setOutput(getA(${i}));
|
|
}
|
|
`}}function TX(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 dr="if (isnan(x)) return x;",AX="return x;",OC="return abs(x);",EC=dr+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,DC=dr+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,kC="return (x >= 0.0) ? x : (exp(x) - 1.0);",vX=`
|
|
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
|
|
// see: https://arxiv.org/abs/1706.02515
|
|
float scaleAlpha = ${Hp};
|
|
float scale = ${qp};
|
|
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
|
|
`;function NX(e=0){return dr+`
|
|
return x > 0.0 ? 1.0 : float(${e});
|
|
`}const FC="return -x;",_C="return ceil(x);",WC="return floor(x);",CX=`
|
|
if (isnan(x)) { return 0.0; }
|
|
return sign(x);
|
|
`,RX="return float(isnan(x));",OX="return float(isinf(x));",EX="return float(!isnan(x) && !isinf(x));",DX=`
|
|
// 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;
|
|
}
|
|
}
|
|
`,$C="return exp(x);",UC="return exp(x) - 1.0;",kX=`if (x < 0.0) return NAN;
|
|
return log(x);`,FX="return log(1.0 + x);",_X="return sqrt(x);",WX="return inversesqrt(x);",$X="return 1.0 / (1.0 + exp(-1.0 * x));",UX=`
|
|
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;
|
|
`,BX=dr+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return asin(x);
|
|
`,MX=dr+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return acos(x);
|
|
`,PX=dr+`
|
|
return atan(x);
|
|
`,zX=`
|
|
float e2x = exp(x);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`,VX=`
|
|
float e2x = exp(-x);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`,GX=`
|
|
float e2x = exp(-2.0 * abs(x));
|
|
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
|
|
`,YX=dr+"return log(x + sqrt(x * x + 1.0));",HX=dr+`
|
|
if (x < 1.0) return NAN;
|
|
return log(x + sqrt(x * x - 1.0));`,qX=dr+`
|
|
if ((x < -1.0) || (x > 1.0)) return NAN;
|
|
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,jX=`
|
|
// Error function is calculated approximately with elementary function.
|
|
// See "Handbook of Mathematical Functions with Formulas,
|
|
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
|
|
float p = ${Cw};
|
|
float a1 = ${Rw};
|
|
float a2 = ${Ow};
|
|
float a3 = ${Ew};
|
|
float a4 = ${Dw};
|
|
float a5 = ${kw};
|
|
|
|
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));
|
|
`,KX="return 1.0 / x;",XX="return float(!(x >= 1.0));",Gm="return x;";const JX="return x;",ZX=`
|
|
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;
|
|
`,BC=`
|
|
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;
|
|
`,MC=`
|
|
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;
|
|
`,PC=`
|
|
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 Au{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 QX{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;const t=e.length,n=Mn("rc",t),s=Rt(t),i=z5(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:zC}=Ww,e7=$w,t7=Uw,n7=Bw,s7=_p,i7=1e-7,r7=1e-4,Ym={};function o7(e){return e in Ym||(Ym[e]={}),Ym[e]}function Hm(e,t=!1){if(e==="linear")return t?JX:AX;if(e==="relu")return t?BC:EC;if(e==="elu")return t?PC:kC;if(e==="relu6")return t?MC:DC;if(e==="prelu")return t?uC:hC;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}const a7=128,c7=600;function l7(){return oe().global.screen==null?1024:oe().global.screen.height*oe().global.screen.width*window.devicePixelRatio*c7/1024/1024}const VC=1e3;class h7 extends y{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,!oe().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){const t=Fi(oe().getNumber("WEBGL_VERSION"));this.binaryCache=o7(oe().getNumber("WEBGL_VERSION")),this.gpgpu=new B6(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 wX(this.gpgpu),this.numMBBeforeWarning=l7(),this.texData=new p(this,Ji())}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(e,t,n){if((oe().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||oe().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:Ns.UPLOAD,refCount:1,complexParentRefCount:0}),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(oe().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:Ns.UPLOAD,refCount:1,complexParentRefCount:0})}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,complexTensorInfos:i,slice:o,shape:a,isPacked:c}=t;if(o!=null){let f;c?f=new Au(a,Gm):f=new st(a,Gm);const b=this.runWebGLProgram(f,[{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=Kn());let m;if(s==="complex64"){const f=this.readSync(i.real.dataId),b=this.readSync(i.imag.dataId);m=sr(f,b)}else m=this.getValuesFromTexture(e);return h&&(this.downloadWaitMs+=Kn()-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,complexTensorInfos:a,isPacked:c}=t;if(i!=null){let w;c?w=new Au(s,Gm):w=new st(s,Gm);const L=this.runWebGLProgram(w,[{dataId:e,shape:s,dtype:o}],o),x=this.read(L.dataId);return this.disposeIntermediateTensorInfo(L),x}if(n!=null)return this.convertAndCacheOnCPU(e);if(!oe().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&oe().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"&&oe().get("WEBGL_BUFFER_SUPPORTED")){d=this.decode(e);const w=this.texData.get(d.dataId);h=this.gpgpu.createBufferFromTexture(w.texture,...Su(s))}this.pendingRead.set(e,[]),o!=="complex64"&&await this.gpgpu.createAndWaitForFence();let m;if(o==="complex64"){const w=await Promise.all([this.read(a.real.dataId),this.read(a.imag.dataId)]),L=w[0],x=w[1];m=sr(L,x)}else if(h==null)m=this.getValuesFromTexture(e);else{const w=P(s);m=this.gpgpu.downloadFloat32MatrixFromBuffer(h,w)}d!=null&&this.disposeIntermediateTensorInfo(d);const f=this.convertAndCacheOnCPU(e,m),b=this.pendingRead.get(e);return this.pendingRead.delete(e),b.forEach(w=>w(f)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e),this.pendingDeletes--),f}checkNumericalProblems(e){if(e==null)return;for(let t=0;t<e.length;t++){const n=e[t];if(!e5(n))throw oe().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=P(t);if(oe().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){const f=this.decode(e),b=this.texData.get(f.dataId),w=this.gpgpu.downloadMatrixFromPackedTexture(b.texture,...Su(t)).subarray(0,i);return this.disposeIntermediateTensorInfo(f),w}const o=oe().getBool("WEBGL_PACK")&&s===!0,a=o?qS(t):t,c=o?new g6(a):new f6(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=te(this.activeTimers.map(c=>c.query)).filter(c=>c!=null),o=te(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(oe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const c=await Promise.all(i);a.kernelMs=C(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 oe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:Kn(),endMs:null}}endTimer(e){return oe().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=Kn(),e)}async getQueryTime(e){if(oe().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;if(this.texData.get(e).complexParentRefCount>0){this.texData.get(e).refCount--;return}this.releaseGPUData(e);const{complexTensorInfos:t}=this.texData.get(e);t!=null&&(this.texData.get(t.real.dataId).complexParentRefCount--,this.disposeIntermediateTensorInfo(t.real),this.texData.get(t.imag.dataId).complexParentRefCount--,this.disposeIntermediateTensorInfo(t.imag)),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 oe().getBool("WEBGL_CPU_FORWARD")?(this.cpuBackend==null&&(this.cpuBackend=Ji().findBackend("cpu")),this.cpuBackend):null}shouldExecuteOnCPU(e,t=a7){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&&P(s.shape)<t)}getGPGPUContext(){return this.gpgpu}slice(e,t,n){if(this.shouldExecuteOnCPU([e])){const o=W5(this.texData.get(e.dataId).values,t,n,e.shape,e.dtype);return this.makeOutput(n,e.dtype,o)}if(P(n)===0)return sn([],n,e.dtype);const{isPacked:s}=this.texData.get(e.dataId),i=Cb(e.shape,t,n);if(s||!i){const o=oe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new yX(n):new fX(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=Rb(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=ip(t,n,s);if(o.some(c=>c===0))return sn([],o);const a=new bX(t,s,o);return this.compileAndRun(a,[e])}reverse(e,t){const n=oe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new dX(e.shape,t):new uX(e.shape,t);return this.compileAndRun(n,[e])}neg(e){const t=this.tryRunOnCpuOrThrow([e],()=>this.cpuBackend.neg(e));if(t)return t;if(oe().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,FC,e.dtype);const n=new st(e.shape,FC);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=Math.max(e.shape[0],t.shape[0]);if((i===1||o===1)&&a>VC){n&&(e=Ye(e,[0,2,1])),s&&(t=Ye(t,[0,2,1]));const m=o===1?e:e.as3D(c,a,1),f=o===1?2:1,b=o===1?t.as3D(c,1,a):t,w=X(m,b);return w.sum(f,!0)}const h=$n(e.dtype,t.dtype),d=new JS(e.shape,t.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=Math.max(e.shape[0],t.shape[0]),m=$n(e.dtype,t.dtype),f=i!=null,b=a!=null,w=o?Hm(o,!0):null,L=new JS(e.shape,t.shape,[d,c,h],n,s,f,w,b),x=[e,t];return i&&x.push(i),a&&x.push(a),this.compileAndRun(L,x,m)}localResponseNormalization4D(e,t,n,s,i){const o=oe().getBool("WEBGL_PACK_NORMALIZATION")?new q6(e.shape,t,n,s,i):new Y6(e.shape,t,n,s,i);return this.compileAndRun(o,[e])}LRNGrad(e,t,n,s,i,o,a){const c=new H6(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=>rh(a)),o=wt(e.shape,e.dtype,i);return t7(o,t)}const n=new xX(e.shape,t);return this.compileAndRun(n,[e])}pad(e,t,n){const s=oe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new iX(e.shape,t,n):new sX(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 L6(e.shape,t.size,n);return this.compileAndRun(i,[e,t])}batchToSpaceND(e,t,n){A(e.rank<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");const s=t.reduce((d,m)=>d*m),i=Mh(e.shape,t,s),o=Ph(i.length,t.length),a=zh(e.shape,t,s),c=vw(n,t.length),h=Nw(a,n,t.length);return Ye(e.reshape(i),o).reshape(a).slice(c,h)}spaceToBatchND(e,t,n){A(e.rank<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");const s=t.reduce((m,f)=>m*f),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=Mh(o.shape,t,s,!1),c=Ph(a.length,t.length,!1),h=zh(o.shape,t,s,!1),d=Ye(o.reshape(a),c);return K(d,h)}reduce(e,t,n){const s=e.shape[0],i=e.shape[1],o=Sh(i),a=Math.ceil(i/o),c={windowSize:o,inSize:i,batchSize:s,outSize:a},h=new TC(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=Sh(i),a={windowSize:o,inSize:i,batchSize:s,outSize:Math.ceil(i/o)},c=new P5(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=Sh(i),a=new A8(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){Xn("sum",t,e.rank);const[n,s]=An(e.shape,t),i=P(s),o=e.as2D(-1,i),a=jd(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]=An(e.shape,t),o=P(i),a=e.as2D(-1,o),c=jd(e.dtype);return this.reduce(a,"prod",c).reshape(s)}unsortedSegmentSum(e,t,n){let s=0;const i=Jn([s],e.rank);let o=e;i!=null&&(o=Ye(e,i),s=cs(1,e.rank)[0]);const a=zC.computeOutShape(o.shape,s,n),c=P([o.shape[s]]),h=o.as2D(-1,c),d=jd(e.dtype);let m=this.segOpCompute(h,"unsortedSegmentSum",t,d,n).reshape(a);return i!=null&&(m=Ye(m,ph(i))),m}segOpCompute(e,t,n,s,i){const o=e.shape[0],a=e.shape[1],c=zC.segOpComputeOptimalWindowSize(a,i),h={windowSize:c,inSize:a,batchSize:o,numSegments:i},d=new pX(h,t),m=this.compileAndRun(d,[e,n],s);return m.shape[1]===i?m:(n=Ch(0,i).tile([a/c]),this.segOpCompute(m,t,n,s,i))}argMinMaxReduce(e,t,n){const s=[t];if(Xn("arg"+n.charAt(0).toUpperCase()+n.slice(1),s,e.rank),!oe().getBool("WEBGL_PACK_REDUCE")||e.rank<=2){const[i,o]=An(e.shape,s),a=P(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 fC(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 fC(e.shape,n,s),c=o;o=this.compileAndRun(a,[o]),c.dispose()}return o}equal(e,t){if(oe().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,G8,"bool");const n=new Wn(O8,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(oe().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,Y8,"bool");const s=new Wn(E8,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}lessEqual(e,t){if(oe().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,H8,"bool");const n=new Wn(D8,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(oe().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,q8,"bool");const s=new Wn(k8,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}greaterEqual(e,t){if(oe().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,j8,"bool");const n=new Wn(F8,e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")}logicalNot(e){const t=new st(e.shape,XX);return this.compileAndRun(t,[e])}logicalAnd(e,t){if(oe().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,K8,"bool");const n=new Wn(_8,e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")}logicalOr(e,t){if(oe().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,X8,"bool");const n=new Wn(W8,e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")}select(e,t,n){const s=new mX(e.rank,t.shape,t.rank);return this.compileAndRun(s,[e,t,n],$n(t.dtype,n.dtype))}where(e){ic("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");const t=e.dataSync();return s7(e.shape,t)}topk(e,t,n){const s=e.dataSync();return n7(s,e.shape,e.dtype,t,n)}min(e,t){Xn("min",t,e.rank);const[n,s]=An(e.shape,t),i=P(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=oe().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ur(Z8,e.shape,t.shape):new Wn(U8,e.shape,t.shape);return this.compileAndRun(s,[e,t])}mod(e,t){const n=oe().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ur(Q8,e.shape,t.shape):new Wn(B8,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=oe().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ur(J8,e.shape,t.shape):new Wn($8,e.shape,t.shape);return this.compileAndRun(s,[e,t])}all(e,t){Xn("all",t,e.rank);const[n,s]=An(e.shape,t),i=P(s),o=e.as2D(-1,i);return this.reduce(o,"all",o.dtype).reshape(n)}any(e,t){Xn("any",t,e.rank);const[n,s]=An(e.shape,t),i=P(s),o=e.as2D(-1,i);return this.reduce(o,"any",o.dtype).reshape(n)}floorDiv(e,t){const n=C8,s="int32";if(oe().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,P8,s);const i=new Wn(n,e.shape,t.shape);return this.compileAndRun(i,[e,t],s)}packedUnaryOp(e,t,n){const s=new Au(e.shape,t);return this.compileAndRun(s,[e],n)}packedBinaryOp(e,t,n,s,i=!1){const o=new ur(n,e.shape,t.shape,i);return this.compileAndRun(o,[e,t],s)}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>oe().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)=>$n(o,a)),n=e.map(o=>o.shape),s=oe().getBool("WEBGL_PACK"),i=s?new M5(e[0].shape,n):new B5(e[0].shape,n);return this.compileAndRun(i,e,t)}pow(e,t){const n=oe().getBool("WEBGL_PACK_BINARY_OPERATIONS"),s=n?new ur(z8,e.shape,t.shape):new Wn(R8,e.shape,t.shape),i=$n(e.dtype,t.dtype);return this.compileAndRun(s,[e,t],i)}ceil(e){if(this.shouldExecuteOnCPU([e])){const n=C5(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}if(oe().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,_C,e.dtype);const t=new st(e.shape,_C);return this.compileAndRun(t,[e])}floor(e){if(this.shouldExecuteOnCPU([e])){const n=E5(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}if(oe().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,WC,e.dtype);const t=new st(e.shape,WC);return this.compileAndRun(t,[e])}sign(e){const t=new st(e.shape,CX);return this.compileAndRun(t,[e])}isNaN(e){const t=new st(e.shape,RX);return this.compileAndRun(t,[e],"bool")}isInf(e){const t=new st(e.shape,OX);return this.compileAndRun(t,[e],"bool")}isFinite(e){const t=new st(e.shape,EX);return this.compileAndRun(t,[e],"bool")}round(e){const t=new st(e.shape,DX);return this.compileAndRun(t,[e])}exp(e){if(this.shouldExecuteOnCPU([e])){const n=R5(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}if(oe().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,$C,e.dtype);const t=new st(e.shape,$C);return this.compileAndRun(t,[e])}expm1(e){if(this.shouldExecuteOnCPU([e])){const n=O5(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}if(oe().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,UC,e.dtype);const t=new st(e.shape,UC);return this.compileAndRun(t,[e])}softmax(e,t){const n=qe([t],e.shape),s=es(e,n),i=vn(s.shape,n),o=Re(e,s.reshape(i)),a=this.exp(o),c=this.sum(a,n).reshape(i);return We(a,c)}log(e){if(this.shouldExecuteOnCPU([e])){const n=D5(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}if(oe().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,ZX,e.dtype);const t=new st(e.shape,kX);return this.compileAndRun(t,[e])}log1p(e){const t=new st(e.shape,FX);return this.compileAndRun(t,[e])}sqrt(e){const t=new st(e.shape,_X);return this.compileAndRun(t,[e])}rsqrt(e){if(this.shouldExecuteOnCPU([e])){const n=_5(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,n)}const t=new st(e.shape,WX);return this.compileAndRun(t,[e])}reciprocal(e){const t=new st(e.shape,KX);return this.compileAndRun(t,[e])}relu(e){let t;return oe().getBool("WEBGL_PACK")?t=new Au(e.shape,BC):t=new st(e.shape,EC),this.compileAndRun(t,[e])}relu6(e){let t;return oe().getBool("WEBGL_PACK")?t=new Au(e.shape,MC):t=new st(e.shape,DC),this.compileAndRun(t,[e])}prelu(e,t){const n=oe().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ur(uC,e.shape,t.shape):new Wn(hC,e.shape,t.shape);return this.compileAndRun(n,[e,t])}elu(e){if(oe().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,PC,e.dtype);const t=new st(e.shape,kC);return this.compileAndRun(t,[e])}eluDer(e,t){const n=oe().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ur(V8,e.shape,t.shape):new Wn(M8,e.shape,t.shape);return this.compileAndRun(n,[e,t])}selu(e){const t=new st(e.shape,vX);return this.compileAndRun(t,[e])}clip(e,t,n){let s;oe().getBool("WEBGL_PACK_CLIP")?s=new t6(e.shape):s=new e6(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=v5(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,n)}if(oe().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,OC,e.dtype);const t=new st(e.shape,OC);return this.compileAndRun(t,[e])}complexAbs(e){const t=this.texData.get(e.dataId),n=new n6(e.shape),s=[this.makeComplexComponentTensorInfo(e,t.complexTensorInfos.real),this.makeComplexComponentTensorInfo(e,t.complexTensorInfos.imag)];return this.compileAndRun(n,s)}sigmoid(e){const t=new st(e.shape,$X);return this.compileAndRun(t,[e])}softplus(e){const t=new st(e.shape,UX);return this.compileAndRun(t,[e])}asin(e){const t=new st(e.shape,BX);return this.compileAndRun(t,[e])}acos(e){const t=new st(e.shape,MX);return this.compileAndRun(t,[e])}atan(e){const t=new st(e.shape,PX);return this.compileAndRun(t,[e])}sinh(e){const t=new st(e.shape,zX);return this.compileAndRun(t,[e])}cosh(e){const t=new st(e.shape,VX);return this.compileAndRun(t,[e])}tanh(e){const t=new st(e.shape,GX);return this.compileAndRun(t,[e])}asinh(e){const t=new st(e.shape,YX);return this.compileAndRun(t,[e])}acosh(e){const t=new st(e.shape,HX);return this.compileAndRun(t,[e])}atanh(e){const t=new st(e.shape,qX);return this.compileAndRun(t,[e])}erf(e){const t=new st(e.shape,jX);return this.compileAndRun(t,[e])}step(e,t){const n=new st(e.shape,NX(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,f=n.dataFormat==="channelsLast",b=!1,w=!1,L=(d===1||m===1)&&h>VC,x=a[2]%2!==0&&!!c.isPacked;if(L||!oe().getBool("WEBGL_LAZILY_UNPACK")||!oe().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!x){const U=f?a[0]*a[1]*a[2]:a[0]*a[2]*a[3],$=K(e,[1,U,n.inChannels]),Y=K(t,[1,n.inChannels,n.outChannels]),j=this.fusedBatchMatMul({a:$,b:Y,transposeA:b,transposeB:w,bias:s,activation:i,preluActivationWeights:o});return K(j,n.outShape)}const v=f?a[0]*a[1]*(a[2]+1):a[0]*a[2]*(a[3]+1),N={dataId:e.dataId,shape:[1,v,n.inChannels],dtype:e.dtype},O=c.shape;c.shape=c.shape.slice(),c.shape[c.shape.length-2]++,A(Bm(c.shape,N.shape),()=>`packed reshape ${c.shape} to ${N.shape} isn't free`);const E=K(t,[1,n.inChannels,n.outChannels]),k=this.fusedBatchMatMul({a:N,b:E,transposeA:b,transposeB:w,bias:s,activation:i,preluActivationWeights:o}),F=this.texData.get(k.dataId);return A(F.isPacked,()=>"batchMatMul result is expected to be packed"),c.shape=O,F.shape=n.outShape,Ji().makeTensorFromDataId(k.dataId,n.outShape,k.dtype)}conv2dWithIm2Row(e,t,n,s,i,o){const{filterWidth:a,filterHeight:c,inChannels:h,outWidth:d,outHeight:m,dataFormat:f}=n,b=f==="channelsLast",w=a*c*h,L=m*d,x=[w,L],v=!0,N=!1,O=e.squeeze([0]),E=t.reshape([1,w,-1]),k=new G6(x,O.shape,n),F=this.compileAndRun(k,[O]).reshape([1,x[0],x[1]]),U=s!=null,$=o!=null,Y=i?Hm(i,!0):null,j=new JS(F.shape,E.shape,[1,L,n.outChannels],v,N,U,Y,$),Z=[F,E];s&&Z.push(s),$&&Z.push(o);const ie=this.compileAndRun(j,Z);return b?ie.reshape([1,m,d,n.outChannels]):ie.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(oe().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?Hm(i,!1):null,d=new dC(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(oe().getBool("WEBGL_CONV_IM2COL")&&e.shape[0]===1)return this.conv2dWithIm2Row(e,t,n);const s=new dC(n);return this.compileAndRun(s,[e,t])}conv2dDerInput(e,t,n){const s=new i6(n);return this.compileAndRun(s,[e,t])}conv2dDerFilter(e,t,n){const s=new s6(n);return this.compileAndRun(s,[e,t])}fusedDepthwiseConv2D({input:e,filter:t,convInfo:n,bias:s,activation:i,preluActivationWeights:o}){const a=oe().getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels===1,c=i?Hm(i,a):null,h=[e,t],d=s!=null,m=o!=null;d&&h.push(s),m&&h.push(o);let f;return a?(f=new mC(n,d,c,m),this.compileAndRun(f,h)):(f=new pC(n,d,c,m),this.compileAndRun(f,h))}depthwiseConv2D(e,t,n){let s;return oe().getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels===1?(s=new mC(n),this.compileAndRun(s,[e,t])):(s=new pC(n),this.compileAndRun(s,[e,t]))}depthwiseConv2DDerInput(e,t,n){const s=new c6(n);return this.compileAndRun(s,[e,t])}depthwiseConv2DDerFilter(e,t,n){const s=new a6(n);return this.compileAndRun(s,[e,t])}conv3d(e,t,n){const s=new l6(n);return this.compileAndRun(s,[e,t])}conv3dDerInput(e,t,n){const s=new o6(n);return this.compileAndRun(s,[e,t])}conv3dDerFilter(e,t,n){const s=new r6(n);return this.compileAndRun(s,[e,t])}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 ZS(t,"avg",!1);return this.compileAndRun(n,[e],"float32")}avgPool3dBackprop(e,t,n){const s=new N8(n);return this.compileAndRun(s,[e],t.dtype)}maxPool3d(e,t){const n=new ZS(t,"max",!1);return this.compileAndRun(n,[e],"float32")}maxPool3dBackprop(e,t,n,s){const i=!0,o=new ZS(s,"max",i),a=this.compileAndRun(o,[t]),c=new K6(s),h=this.compileAndRun(c,[e,a],t.dtype);return a.dispose(),h}resizeBilinear(e,t,n,s){const i=oe().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new cX(e.shape,t,n,s):new aX(e.shape,t,n,s);return this.compileAndRun(i,[e],"float32")}resizeBilinearBackprop(e,t,n){const s=new oX(e,t,n);return this.compileAndRun(s,[e])}resizeNearestNeighbor(e,t,n,s){const i=new hX(e.shape,t,n,s);return this.compileAndRun(i,[e])}resizeNearestNeighborBackprop(e,t,n){const s=new lX(e,t,n);return this.compileAndRun(s,[e])}multinomial(e,t,n,s){const i=t?e:Vo(e),o=i.shape[0],a=i.shape[1],c=new X6(o,a,n),h=c.getCustomSetupFunc(s);return this.compileAndRun(c,[i],"int32",h)}oneHot(e,t,n,s){const i=new J6(e.size,t,n,s);return this.compileAndRun(i,[e])}diag(e){const t=new m6(e.size);return this.compileAndRun(t,[e])}cropAndResize(e,t,n,s,i,o){const a=new h6(e.shape,t.shape,s,i,o);return this.compileAndRun(a,[e,t,n],"float32")}depthToSpace(e,t,n){A(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],f=new p6(m,t,n);return this.compileAndRun(f,[e])}split(e,t,n){return e7(e,t,n)}scatterND(e,t,n){const{sliceRank:s,numUpdates:i,sliceSize:o,strides:a,outputSize:c}=Pa(t,e,n),h=[c/o,o],d=e.reshape([i,s]),m=t.reshape([i,o]);if(c===0)return iv(sn([]),n);const f=Ce(0),b=new vC(i,s,d.rank,m.rank,a,h),w=this.compileAndRun(b,[m,d,f]);return w.reshape(n)}sparseToDense(e,t,n,s){const{sliceRank:i,numUpdates:o,strides:a,outputSize:c}=Pa(t,e,n),h=!1,d=new vC(o,i,e.rank,t.rank,a,[c,1],h),m=this.compileAndRun(d,[t,e,s]);return m.reshape(n)}gatherND(e,t){const n=t.shape,s=n[n.length-1],[i,o,a,c]=np(e,t),h=t.reshape([o,s]),d=e.reshape([e.size/a,a]),m=new I6(s,c,[o,a]),f=this.compileAndRun(m,[d,h]);return f.reshape(i)}fill(e,t,n){if(n=n||Aa(t),n==="string"){const s=ws(n,P(e));return s.fill(t),Ji().makeTensor(s,e,n,this)}else{const s=new w6(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 _w(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 Ji().makeTensorFromDataId(s,e,t,this)}unpackTensor(e){const t=new QX(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new Z6(e.shape),n=!0;return this.runWebGLProgram(t,[e],e.dtype,null,n)}packedReshape(e,t){const n=[Lc(e.shape),...Sc(e.shape)],s={dtype:e.dtype,shape:n,dataId:e.dataId},i=[Lc(t),...Sc(t)],o=new AC(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=qS(s);let a;n?a=new d6(o):a=new u6(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===wu.DENSE){const L=Su(e.outputShape);a.texShape=L.map(x=>x*2)}if(e.outTexUsage!=null&&(a.usage=e.outTexUsage),P(o.shape)===0)return a.values=bt(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 x=this.texData.get(L.dataId);if(x.texture==null){if(!e.packedInputs&&P(L.shape)<=oe().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:L.shape,texData:null,isUniform:!0,uniformValues:x.values};e.packedInputs&&(x.isPacked=!0,x.shape=L.shape)}else if(!!x.isPacked!==!!e.packedInputs)L=x.isPacked?this.unpackTensor(L):this.packTensor(L),c.push(L),x=this.texData.get(L.dataId);else if(x.isPacked&&!Bm(x.shape,L.shape)){const v=L,N=L.shape;L.shape=x.shape,L=this.packedReshape(L,N),c.push(L),x=this.texData.get(L.dataId),v.shape=N}return this.uploadToGPU(L.dataId),{shape:L.shape,texData:x,isUniform:!1}});this.uploadToGPU(o.dataId);const d={shape:o.shape,texData:a,isUniform:!1},m=V6(e,h,d),f=this.getAndSaveBinary(m,()=>P6(this.gpgpu,e,h,d)),b=this.activeTimers!=null;let w;if(b&&(w=this.startTimer()),z6(this.gpgpu,f,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)})),!oe().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 Ji().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(!oe().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=Q(()=>{if(!oe().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=oe().getBool("DEBUG");oe().set("DEBUG",!1);const t=this.abs(Ce(1e-8)).dataSync()[0];if(oe().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?i7:r7}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=Kn());let m=t.texShape;if(m==null&&(m=b5(n,c),t.texShape=m),i!=null){const f=qS(n);let b,w=m[1],L=m[0];const x=i instanceof Uint8Array;c?([w,L]=wc(m[0],m[1]),b=new b6(f,[L,w],x)):b=new y6(f,[L,w],x);const v=this.makeTensorInfo([L,w],s);x?this.texData.get(v.dataId).usage=Ns.PIXELS:this.texData.get(v.dataId).usage=Ns.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(v.dataId),w,L,i);const N=!0,O=this.runWebGLProgram(b,[v],s,null,N),E=this.texData.get(O.dataId);t.texture=E.texture,t.texShape=E.texShape,t.isPacked=E.isPacked,t.usage=E.usage,this.disposeIntermediateTensorInfo(v),this.texData.delete(O.dataId),t.values=null,h&&(this.uploadWaitMs+=Kn()-d)}else{const f=this.acquireTexture(m,a,s,c);t.texture=f}}convertAndCacheOnCPU(e,t){const n=this.texData.get(e),{dtype:s}=n;return this.releaseGPUData(e),t!=null&&(n.values=u7(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]*py(t)}tryRunOnCpuOrThrow(e,t){if(this.shouldExecuteOnCPU(e))try{return t()}catch(n){if(oe().getBool("IS_TEST"))throw new Error("CPU forwarding failed")}return null}}function u7(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 d7="2.7.0";function p7(){oe().set("WEBGL_FORCE_F16_TEXTURES",!0)}db()&&kb("webgl",()=>new h7,2);const cne={forceHalfFloat:p7};function pr(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 m7={kernelName:kl,backendName:"webgl",kernelFunc:pr};function vc(e){const{inputs:t,backend:n}=e,{real:s,imag:i}=t,o=n.makeTensorInfo(s.shape,"complex64"),a=n.texData.get(o.dataId),c=pr({inputs:{x:s},backend:n}),h=n.texData.get(c.dataId);h.complexParentRefCount++;const d=pr({inputs:{x:i},backend:n}),m=n.texData.get(d.dataId);return m.complexParentRefCount++,a.complexTensorInfos={real:c,imag:d},o}const f7={kernelName:fd,backendName:"webgl",kernelFunc:vc};const GC="if (isnan(x)) return x;",g7=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,y7=`
|
|
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 qm(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 Nc({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:s=!1,cpuKernelImpl:i,dtype:o}){return({inputs:a,backend:c})=>{const{a:h,b:d}=a,m=c;if(s&&h.dtype==="complex64"){const L=m.texData.get(h.dataId),x=m.texData.get(d.dataId),[v,N]=[[L.complexTensorInfos.real,x.complexTensorInfos.real],[L.complexTensorInfos.imag,x.complexTensorInfos.imag]].map(E=>{const[k,F]=E,U={dataId:k.dataId,dtype:k.dtype,shape:h.shape},$={dataId:F.dataId,dtype:F.dtype,shape:d.shape},Y=new Wn(e,h.shape,d.shape);return m.runWebGLProgram(Y,[U,$],$n(k.dtype,F.dtype))}),O=vc({inputs:{real:v,imag:N},backend:m});return m.disposeIntermediateTensorInfo(v),m.disposeIntermediateTensorInfo(N),O}const f=o||$n(h.dtype,d.dtype);if(m.shouldExecuteOnCPU([h,d])&&i!=null){const L=m.texData.get(h.dataId),x=m.texData.get(d.dataId),[v,N]=i(h.shape,d.shape,L.values,x.values,f),O=m.makeTensorInfo(N,f),E=m.texData.get(O.dataId);return E.values=v,O}const b=oe().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null;let w;return b?w=new ur(t,h.shape,d.shape,n):w=new Wn(e,h.shape,d.shape),m.runWebGLProgram(w,[h,d],f)}}const YC="return a + b;",b7=Nc({opSnippet:YC,packedOpSnippet:YC,supportsComplex:!0,cpuKernelImpl:N5}),w7={kernelName:Co,backendName:"webgl",kernelFunc:b7};const L7=g7+`
|
|
return atan(a, b);
|
|
`,S7=`
|
|
vec4 result = atan(a, b);
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+y7+`
|
|
return result;
|
|
`,I7=Nc({opSnippet:L7,packedOpSnippet:S7}),x7={kernelName:dd,backendName:"webgl",kernelFunc:I7};function T7(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;Iu(i,"avgPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:h}=s,d=1;A(cn(a,d),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${d}'`);const m=Un(i.shape,o,a,d,c,h);if(m.filterWidth===1&&m.filterHeight===1&&ae(m.inShape,m.outShape))return pr({inputs:{x:i},backend:n});const f=new Tu(m,"avg",!1);return n.runWebGLProgram(f,[i],"float32")}const A7={kernelName:Il,backendName:"webgl",kernelFunc:T7};function v7(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o}=t,a=o;Iu([i,o],"avgPoolBackprop");const{filterSize:c,strides:h,pad:d}=s,m=Un(a.shape,c,h,1,d),f=new v8(m);return n.runWebGLProgram(f,[i],a.dtype)}const N7={kernelName:pd,backendName:"webgl",kernelFunc:v7};class C7{constructor(e,t,n,s,i,o){this.outputShape=[],this.variableNames=["x","mean","variance"],nt(e,t),nt(e,n);let a="0.0";s!=null&&(nt(e,s),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let c="1.0";i!=null&&(nt(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 R7{constructor(e,t,n,s,i,o){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],nt(e,t),nt(e,n);let a="vec4(0.0)";s!=null&&(nt(e,s),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let c="vec4(1.0)";i!=null&&(nt(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 O7=({inputs:e,backend:t,attrs:n})=>{const{x:s,mean:i,variance:o,offset:a,scale:c}=e;A(i.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),A(a==null||i.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),A(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 f=null;c!=null&&(f=c.shape,d.push(c));const b=oe().getBool("WEBGL_PACK_NORMALIZATION")?new R7(s.shape,i.shape,o.shape,m,f,h):new C7(s.shape,i.shape,o.shape,m,f,h),w=t.runWebGLProgram(b,d,d[0].dtype);return w},E7={kernelName:Dl,backendName:"webgl",kernelFunc:O7};const D7="return float(a != b);",HC=Nc({opSnippet:D7,dtype:"bool"}),k7={kernelName:zl,backendName:"webgl",kernelFunc:HC};function eI(e){const{inputs:t,backend:n}=e,{input:s}=t,i=n.texData.get(s.dataId);return pr({inputs:{x:i.complexTensorInfos.real},backend:n})}const F7={kernelName:Fd,backendName:"webgl",kernelFunc:eI};const _7="return float(int(x));";function W7(e,t){const n=new st(e.shape,_7),s=t.runWebGLProgram(n,[e],"int32");return{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}function tI(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{dtype:o}=s;if(o==="complex64"){if(i.dtype==="complex64")return pr({inputs:{x:i},backend:n});const a=dt(i.shape),c=tI({inputs:{x:i},backend:n,attrs:{dtype:"float32"}}),h=vc({inputs:{real:c,imag:a},backend:n});return a.dispose(),n.disposeIntermediateTensorInfo(c),h}if(i.dtype==="complex64"){const a=eI({inputs:{input:i},backend:n}),c=tI({inputs:{x:a},backend:n,attrs:{dtype:o}});return n.disposeIntermediateTensorInfo(a),c}if(!Ta(i.dtype,o)){const a=pr({inputs:{x:i},backend:n});return{dataId:a.dataId,shape:a.shape,dtype:o}}if(o==="int32")return W7(i,n);if(o==="bool"){const a=n.makeTensorInfo([],"bool",bt("bool",1)),c={a:i,b:a},h=HC({inputs:c,backend:n});return n.disposeIntermediateTensorInfo(a),h}throw new Error(`Error in Cast: failed to cast ${i.dtype} to ${o}`)}const $7={kernelName:Na,backendName:"webgl",kernelFunc:tI};class U7{constructor(e){this.outputShape=[],this.outputShape=Zi(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 B7{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=Zi(e,t);const n=this.outputShape,s=n.length,i=Rt(s),o=Mn("coords",s),a=["x","y","z","w","u","v"].slice(0,s);this.variableNames=e.map((L,x)=>`T${x}`);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 f=`if (${h} < ${c[0]}) {
|
|
return getChannel(
|
|
getT0(${m}), vec2(${d.join()}));
|
|
}`;for(let L=1;L<c.length;L++){const x=c[L-1];f+=`
|
|
if (${h} < ${c[L]} && ${h} >= ${c[L-1]}) {
|
|
return getChannel(
|
|
getT${L}(${jm(a,h,x)}),
|
|
vec2(${jm(d,h,x)}));
|
|
}`}const b=c.length,w=c[c.length-1];f+=`
|
|
return getChannel(
|
|
getT${b}(${jm(a,h,w)}),
|
|
vec2(${jm(d,h,w)}));`,this.userCode=`
|
|
float getValue(${a.map(L=>"int "+L)}) {
|
|
${f}
|
|
}
|
|
|
|
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 jm(e,t,n){const s=e.indexOf(t),i=e.map((o,a)=>a===s?`${o} - ${n}`:o);return i.join()}function qC(e){const{inputs:t,backend:n}=e,{input:s}=t,i=n.texData.get(s.dataId);return pr({inputs:{x:i.complexTensorInfos.imag},backend:n})}const M7={kernelName:vd,backendName:"webgl",kernelFunc:qC};function P7(e,t,n){const s=[Lc(e.shape),...Sc(e.shape)],i={dtype:e.dtype,shape:s,dataId:e.dataId},o=[Lc(t),...Sc(t)],a=new AC(o,s),c=!0,h=n.runWebGLProgram(a,[i],e.dtype,null,c);return{dataId:h.dataId,shape:t,dtype:h.dtype}}function mr(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t,{shape:o}=s,a=n,c=P(i.shape),h=Gt(o,c),d=P(h);A(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&&!Bm(i.shape,h)&&!(m.texture!==null&&Bm(m.shape,h))?P7(i,h,a):(a.incRef(i.dataId),{dataId:i.dataId,shape:h,dtype:i.dtype})}const z7={kernelName:Yl,backendName:"webgl",kernelFunc:mr};function Cc(e,t,n){const s=e[0].dtype;if(s==="complex64"){const d=e.map(L=>eI({inputs:{input:L},backend:n})),m=e.map(L=>qC({inputs:{input:L},backend:n})),f=Cc(d,t,n),b=Cc(m,t,n),w=vc({inputs:{real:f,imag:b},backend:n});return d.forEach(L=>n.disposeIntermediateTensorInfo(L)),m.forEach(L=>n.disposeIntermediateTensorInfo(L)),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(b),w}if(e.length>oe().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const d=Math.floor(e.length/2),m=Cc(e.slice(0,d),t,n),f=Cc(e.slice(d),t,n),b=Cc([m,f],t,n);return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(f),b}if(oe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){const d=new B7(e.map(m=>m.shape),t);return n.runWebGLProgram(d,e,s)}const i=Zi(e.map(d=>d.shape),t),o=e.map(d=>mr({inputs:{x:d},attrs:{shape:[-1,P(d.shape.slice(t))]},backend:n})),a=new U7(o.map(d=>d.shape)),c=n.runWebGLProgram(a,o,s);o.forEach(d=>n.disposeIntermediateTensorInfo(d));const h=mr({inputs:{x:c},attrs:{shape:i},backend:n});return n.disposeIntermediateTensorInfo(c),h}function V7(e){const{inputs:t,backend:n,attrs:s}=e,{axis:i}=s,o=qe(i,t[0].shape)[0],a=Zi(t.map(d=>d.shape),o);if(P(a)===0)return n.makeTensorInfo(a,t[0].dtype,[]);const c=t.filter(d=>P(d.shape)>0);if(c.length===1)return c[0];const h=c.map(d=>d.shape);return dp(h,o),Cc(c,o,n)}const G7={kernelName:Al,backendName:"webgl",kernelFunc:V7};const Y7=GC+`
|
|
return cos(x);
|
|
`,H7=qm(Y7),q7={kernelName:Ca,backendName:"webgl",kernelFunc:H7};const j7=`
|
|
if (a == b) {
|
|
return 1.0;
|
|
};
|
|
return a / b;`,K7=`
|
|
// 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;
|
|
`,X7=Nc({opSnippet:j7,packedOpSnippet:K7,checkOutOfBounds:!0}),J7={kernelName:Ra,backendName:"webgl",kernelFunc:X7};class jC{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";let a;if(e==="real")a="return real * expR - imag * expI;";else if(e==="imag")a="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);this.userCode=`
|
|
const float exponentMultiplier = ${i};
|
|
|
|
float unaryOpComplex(float real, float expR, float imag, float expI) {
|
|
${a}
|
|
}
|
|
|
|
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]));
|
|
}
|
|
`}}function KC(e,t,n){const s=n.texData.get(e.dataId),i=P(e.shape),o=e.shape[e.shape.length-1],a=i/o,c=mr({inputs:{x:e},backend:n,attrs:{shape:[a,o]}}),h=c.shape,d=new jC("real",h,t),m=new jC("imag",h,t),f=[{dataId:s.complexTensorInfos.real.dataId,dtype:s.complexTensorInfos.real.dtype,shape:h},{dataId:s.complexTensorInfos.imag.dataId,dtype:s.complexTensorInfos.imag.dtype,shape:h}],b=n.runWebGLProgram(d,f,"float32"),w=n.runWebGLProgram(m,f,"float32"),L=vc({inputs:{real:b,imag:w},backend:n});n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(w);const x=mr({inputs:{x:L},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(x),x}function Z7(e){const{inputs:t,backend:n}=e,{input:s}=t;return KC(s,!1,n)}const Q7={kernelName:xd,backendName:"webgl",kernelFunc:Z7};class eJ{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 tJ={kernelName:Td,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:n}=e,s=t,i=new eJ(n.shape),o=s.runWebGLProgram(i,[n],n.dtype);return o}};class nJ{constructor(e){this.variableNames=["A"];const t=Pn(),[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 sJ{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=Pn(),[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 iJ={kernelName:Bd,backendName:"webgl",kernelFunc:rJ};let Rc;function rJ(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],f=[d,h,o];(c||a)&&(Rc==null&&(Rc=document.createElement("canvas").getContext("2d")),Rc.canvas.width=h,Rc.canvas.height=d,Rc.drawImage(i,0,0,h,d),i=Rc.canvas);const b=n.makeTensorInfo(m,"int32");n.texData.get(b.dataId).usage=Ns.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(b.dataId),i);const w=oe().getBool("WEBGL_PACK")?new sJ(f):new nJ(f),L=n.runWebGLProgram(w,[b],"int32");return n.disposeData(b.dataId),L}function oJ(e){const{inputs:t,backend:n}=e,{input:s}=t;return KC(s,!0,n)}const aJ={kernelName:Ad,backendName:"webgl",kernelFunc:oJ};class XC{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:s,inSize:i,outSize:o}=e;this.outputShape=[s,o];const a=Math.floor(n/4)*4,c=n%4;let h="sumValue += dot(values, ones);";if(t!=null){const m=1/t;h=`sumValue += dot(values * ${Le(m)?m.toPrecision(2):m}, ones);`}let d="";i%n>0&&(d=`
|
|
if (inIdx < 0 || inIdx >= ${i}) {
|
|
return 0.0;
|
|
}
|
|
`),this.userCode=`
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${d}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * ${n};
|
|
|
|
float sumValue = 0.0;
|
|
|
|
for (int i = 0; i < ${a}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
${h}
|
|
}
|
|
|
|
int inIdx = inOffset + ${a};
|
|
if (${c===1}) {
|
|
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
|
|
|
|
${h}
|
|
} else if (${c===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1), 0.0, 0.0);
|
|
|
|
${h}
|
|
} else if (${c===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2), 0.0);
|
|
|
|
${h}
|
|
}
|
|
setOutput(sumValue);
|
|
}
|
|
`}}function cJ(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=Sh(n);t.push({inSize:n,windowSize:s,outSize:Math.ceil(n/s)})}return t}function JC(e,t,n,s){const i=cJ(e.shape);let o=e;for(let a=0;a<i.length;a++){const{inSize:c,windowSize:h,outSize:d}=i[a];let m,f;n==="mean"?m=a===0?new XC({windowSize:h,inSize:c,batchSize:e.shape[0],outSize:d},c):new XC({windowSize:h,inSize:c,batchSize:e.shape[0],outSize:d}):m=new TC({windowSize:h,inSize:c,batchSize:e.shape[0],outSize:d},n),f=o,o=s.runWebGLProgram(m,[o],t),f.dataId!==e.dataId&&s.disposeIntermediateTensorInfo(f)}return o}function lJ(e,t,n,s){const i=P(t),o=P(e.shape),a=o/i,c=mr({inputs:{x:e},attrs:{shape:[a,i]},backend:s}),h=JC(c,e.dtype,"max",s),d=mr({inputs:{x:h},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(c),s.disposeIntermediateTensorInfo(h),d}class hJ{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=Rt(this.rank),i=uJ(t);this.userCode=`
|
|
void main() {
|
|
${s} resRC = getOutputCoords();
|
|
setOutput(getA(${i}));
|
|
}
|
|
`}}function uJ(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 dJ{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=Rt(this.rank),i=iC("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 nI(e,t,n){const s=oe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new dJ(e.shape,t):new hJ(e.shape,t);return n.runWebGLProgram(s,[e],e.dtype)}const pJ={kernelName:Bl,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=qe(i,s.shape);let d=h;const m=Jn(d,c),f=m!=null,b=a.shouldExecuteOnCPU([s]);let w=s;if(f){if(b){const O=a.texData.get(w.dataId),E=O.values,k=new Array(c);for(let $=0;$<k.length;$++)k[$]=s.shape[m[$]];const F=KS(E,s.shape,s.dtype,m,k);w=a.makeTensorInfo(k,s.dtype);const U=a.texData.get(w.dataId);U.values=F}else w=nI(s,m,a);d=cs(d.length,c)}Xn("max",d,c);const[L,x]=An(w.shape,d);let v=L;o&&(v=vn(L,h));let N;if(b){const O=a.texData.get(w.dataId),E=O.values,k=k5(E,P(x),v,s.dtype);N=a.makeTensorInfo(v,s.dtype);const F=a.texData.get(N.dataId);F.values=k}else N=lJ(w,x,v,a);return f&&a.disposeIntermediateTensorInfo(w),N}};function mJ(e){const{inputs:t,backend:n,attrs:s}=e,{x:i}=t;Iu(i,"maxPool");const{filterSize:o,strides:a,pad:c,dimRoundingMode:h}=s,d=1;A(cn(a,d),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${d}'`);const m=Un(i.shape,o,a,d,c,h);if(m.filterWidth===1&&m.filterHeight===1&&ae(m.inShape,m.outShape))return pr({inputs:{x:i},backend:n});const f=new Tu(m,"max",!1);return n.runWebGLProgram(f,[i],i.dtype)}const fJ={kernelName:Ml,backendName:"webgl",kernelFunc:mJ};function gJ(e){const{inputs:t,backend:n,attrs:s}=e,{dy:i,input:o,output:a}=t,c=o;Iu([o,a],"maxPoolBackprop");const{filterSize:h,strides:d,pad:m,dimRoundingMode:f}=s,b=Un(c.shape,h,d,1,m,f),w=!0,L=new Tu(b,"max",w),x=n.runWebGLProgram(L,[c],c.dtype),v=new j6(b),N=n.runWebGLProgram(v,[i,x],c.dtype);return n.disposeIntermediateTensorInfo(x),N}const yJ={kernelName:Cd,backendName:"webgl",kernelFunc:gJ};function bJ(e,t,n,s){let i=new Tu(n,"max",!1);const o=s.runWebGLProgram(i,[e],"float32");i=new Tu(n,"max",!0,!0,t);const a=s.runWebGLProgram(i,[e],"float32");return[o,a]}const wJ={kernelName:Rd,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{filterSize:i,strides:o,pad:a,includeBatchInIndex:c}=t,h=n;A(s.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${s.shape.length}.`);const d=[1,1];A(cn(o,d),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${d}'`);const m=Un(s.shape,i,o,d,a),[f,b]=bJ(s,c,m,h);return[f,b]}};function LJ(e,t,n,s){const i=P(t),o=P(e.shape),a=o/i,c=mr({inputs:{x:e},attrs:{shape:[a,i]},backend:s}),h=JC(c,"float32","mean",s),d=mr({inputs:{x:h},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(c),s.disposeIntermediateTensorInfo(h),d}const SJ={kernelName:Uy,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{keepDims:i,axis:o}=t,a=n,c=s.shape.length,h=qe(o,s.shape);let d=h;const m=Jn(d,c),f=m!=null,b=a.shouldExecuteOnCPU([s]),w=[];let L=s;if(f){if(b){const E=a.texData.get(L.dataId),k=E.values,F=new Array(c);for(let Y=0;Y<F.length;Y++)F[Y]=s.shape[m[Y]];const U=KS(k,s.shape,s.dtype,m,F);L=a.makeTensorInfo(F,s.dtype);const $=a.texData.get(L.dataId);$.values=U}else L=nI(s,m,a);w.push(L),d=cs(d.length,c)}Xn("sum",d,c);const[x,v]=An(L.shape,d);let N=x;i&&(N=vn(x,h));const O=LJ(L,v,N,a);for(const E of w)a.disposeIntermediateTensorInfo(E);return O}};class IJ{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((d,m)=>d[0]+e[m]+d[1]);const s=e.length,i=Rt(s),o=t.map(d=>d[0]).join(","),a=t.map((d,m)=>d[0]+e[m]).join(","),c=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s),h=n==="reflect"?0:1;if(s===1){this.userCode=`
|
|
int start = ${o};
|
|
int end = ${a};
|
|
|
|
void main() {
|
|
int outC = getOutputCoords();
|
|
if (outC < start) {
|
|
outC = start * 2 - outC - ${h};
|
|
} else if(outC >= end) {
|
|
outC = (end - 1) * 2 - outC + ${h};
|
|
}
|
|
setOutput(getX(outC - start));
|
|
}
|
|
`;return}this.userCode=`
|
|
${i} start = ${i}(${o});
|
|
${i} end = ${i}(${a});
|
|
|
|
void main() {
|
|
${i} outC = getOutputCoords();
|
|
for (int i = 0; i < ${s}; i++) {
|
|
if (outC[i] < start[i]) {
|
|
outC[i] = start[i] * 2 - outC[i] - ${h};
|
|
} else if(outC[i] >= end[i]) {
|
|
outC[i] = (end[i] - 1) * 2 - outC[i] + ${h};
|
|
}
|
|
}
|
|
${i} coords = outC - start;
|
|
setOutput(getX(${c}));
|
|
}
|
|
`}}class xJ{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((w,L)=>w[0]+e[L]+w[1]);const s=e.length,i=Rt(s),o=t.map(w=>w[0]).join(","),a=t.map((w,L)=>w[0]+e[L]).join(","),c=Mn("rc",s),h=Mn("source",s),d=`${c[s-1]} < ${this.outputShape[s-1]}`,m=s===1?"source":`vec2(${h.slice(-2).join()})`,f=n==="reflect"?0:1;let b="";if(s===1){const w=`
|
|
${i} source = rc;
|
|
if (source < start) {
|
|
source = start * 2 - source - ${f};
|
|
} else if (source >= end) {
|
|
source = (end - 1) * 2 - source + ${f};
|
|
}
|
|
source -= start;
|
|
`;b=`
|
|
${i} rc = outputLoc;
|
|
${w}
|
|
result[0] = getChannel(getX(${h.join()}), ${m});
|
|
${c[s-1]} += 1;
|
|
if(${d}) {
|
|
${w}
|
|
result[1] = getChannel(getX(${h.join()}), ${m});
|
|
}
|
|
`}else{const w=`
|
|
${i} source = rc;
|
|
${i} lt = ${i}(lessThan(source, start));
|
|
${i} gte = ${i}(greaterThanEqual(source, end));
|
|
${i} orig = 1 - (lt + gte);
|
|
source = orig * source +
|
|
lt * (start * 2 - source - ${f}) +
|
|
gte * ((end - 1) * 2 - source + ${f});
|
|
source -= start;
|
|
`;b=`
|
|
${i} rc = outputLoc;
|
|
${w}
|
|
result[0] = getChannel(getX(${h.join()}), ${m});
|
|
${c[s-1]} += 1;
|
|
if(${d}) {
|
|
${w}
|
|
result[1] = getChannel(getX(${h.join()}), ${m});
|
|
}
|
|
rc = outputLoc;
|
|
${c[s-2]} += 1;
|
|
if(${c[s-2]} < ${this.outputShape[s-2]}) {
|
|
${w}
|
|
result[2] = getChannel(getX(${h.join()}), ${m});
|
|
${c[s-1]} += 1;
|
|
if(${d}) {
|
|
${w}
|
|
result[3] = getChannel(getX(${h.join()}), ${m});
|
|
}
|
|
}
|
|
`}this.userCode=`
|
|
const ${i} start = ${i}(${o});
|
|
const ${i} end = ${i}(${a});
|
|
|
|
void main() {
|
|
${i} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${b}
|
|
setOutput(result);
|
|
}
|
|
`}}const TJ=({inputs:e,backend:t,attrs:n})=>{const{x:s}=e,{paddings:i,mode:o}=n,a=oe().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new xJ(s.shape,i,o):new IJ(s.shape,i,o),c=t.runWebGLProgram(a,[s],s.dtype);return c},AJ={kernelName:Pl,backendName:"webgl",kernelFunc:TJ};const ZC={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"};class QC{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=nt(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 e2="return a * b;";function vJ(e){const{inputs:t,backend:n}=e,{a:s,b:i}=t,o=$n(s.dtype,i.dtype);if(s.dtype==="complex64"){const c=n.texData.get(s.dataId),h=n.texData.get(i.dataId),d=new QC(ZC.REAL,s.shape,i.shape),m=new QC(ZC.IMAG,s.shape,i.shape),f=[{dataId:c.complexTensorInfos.real.dataId,dtype:c.complexTensorInfos.real.dtype,shape:s.shape},{dataId:c.complexTensorInfos.imag.dataId,dtype:c.complexTensorInfos.imag.dtype,shape:s.shape},{dataId:h.complexTensorInfos.real.dataId,dtype:h.complexTensorInfos.real.dtype,shape:i.shape},{dataId:h.complexTensorInfos.imag.dataId,dtype:h.complexTensorInfos.imag.dtype,shape:i.shape}],b=n.runWebGLProgram(d,f,"float32"),w=n.runWebGLProgram(m,f,"float32"),L=vc({inputs:{real:b,imag:w},backend:n});return n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(w),L}if(n.shouldExecuteOnCPU([s,i])){const c=n.texData.get(s.dataId),h=n.texData.get(i.dataId),[d,m]=F5(s.shape,i.shape,c.values,h.values,o),f=n.makeTensorInfo(m,o),b=n.texData.get(f.dataId);return b.values=d,f}let a;return oe().getBool("WEBGL_PACK_BINARY_OPERATIONS")?a=new ur(e2,s.shape,i.shape):a=new Wn(e2,s.shape,i.shape),n.runWebGLProgram(a,[s,i],o)}const NJ={kernelName:Oa,backendName:"webgl",kernelFunc:vJ};const CJ={kernelName:Vy,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{ic("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),f=o,b=a,w=c;return zp(d,m,f,b,w)}};const RJ=Vp,OJ={kernelName:Od,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{ic("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),f=d.readSync(i.dataId),{selectedIndices:b,validOutputs:w}=RJ(m,f,o,a,c,h);return[b,w]}};const EJ=Gp,DJ={kernelName:Ed,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{ic("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),f=d.readSync(i.dataId),b=o,w=a,L=c,x=h,{selectedIndices:v,selectedScores:N}=EJ(m,f,b,w,L,x);return[v,N]}};class kJ{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]=Aw(s,i,o),m=h.toFixed(3),f=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) - ${f}) * ${a};
|
|
float coordYFloat = (float(x) - ${m}) * ${a} + (float(y) - ${f}) * ${c};
|
|
int coordX = int(round(coordXFloat + ${m}));
|
|
int coordY = int(round(coordYFloat + ${f}));
|
|
${b}
|
|
if(coordX >= 0 && coordX < ${o} && coordY >= 0 && coordY < ${i}) {
|
|
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
|
|
}
|
|
setOutput(outputValue);
|
|
}
|
|
`}}const FJ={kernelName:Md,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,{radians:i,fillValue:o,center:a}=t,c=n,h=new kJ(s.shape,i,o,a),d=c.runWebGLProgram(h,[s],s.dtype);return d}};const _J=GC+`
|
|
return sin(x);
|
|
`,WJ=qm(_J),$J={kernelName:Ea,backendName:"webgl",kernelFunc:WJ};const UJ="return x * x;",BJ=qm(UJ),MJ={kernelName:$d,backendName:"webgl",kernelFunc:BJ};const t2="return (a - b) * (a - b);",PJ=Nc({opSnippet:t2,packedOpSnippet:t2}),zJ={kernelName:Da,backendName:"webgl",kernelFunc:PJ};const n2="return a - b;",VJ=Nc({opSnippet:n2,packedOpSnippet:n2,supportsComplex:!0,cpuKernelImpl:$5}),GJ={kernelName:ka,backendName:"webgl",kernelFunc:VJ};const YJ="return tan(x);",HJ=qm(YJ),qJ={kernelName:Fa,backendName:"webgl",kernelFunc:HJ};const jJ={kernelName:nh,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,f=KS(m,s.shape,s.dtype,i,c);h=o.makeTensorInfo(c,s.dtype);const b=o.texData.get(h.dataId);b.values=f}else h=nI(s,i,o);return h}};function KJ(e){const{inputs:t,attrs:n,backend:s}=e,{axis:i}=n,{x:o}=t;Iu(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}=U5(a,i,o.shape,o.dtype);return[s.makeTensorInfo(h,o.dtype,c),s.makeTensorInfo([d.length],"int32",d)]}const XJ={kernelName:Ud,backendName:"webgl",kernelFunc:KJ};const JJ=[w7,x7,A7,N7,E7,$7,f7,G7,q7,J7,Q7,tJ,iJ,m7,aJ,M7,pJ,fJ,yJ,wJ,SJ,AJ,NJ,CJ,OJ,DJ,k7,F7,z7,FJ,$J,MJ,GJ,zJ,qJ,jJ,XJ];for(const e of JJ)Yd(e);const ZJ="2.7.0";const QJ={"tfjs-core":KT,"tfjs-backend-cpu":f4,"tfjs-backend-webgl":d7,"tfjs-data":T0,"tfjs-layers":wm,"tfjs-converter":n0,tfjs:ZJ};r.Abs=ud,r.Acos=gl,r.Acosh=yl,r.AdadeltaOptimizer=Fh,r.AdagradOptimizer=_h,r.AdamOptimizer=Wh,r.AdamaxOptimizer=$h,r.Add=Co,r.AddN=by,r.All=Wx,r.Any=$x,r.ArgMax=wy,r.ArgMin=Ly,r.Asin=bl,r.Asinh=wl,r.Atan=Ll,r.Atan2=dd,r.Atanh=Sl,r.AvgPool=Il,r.AvgPool3D=Sy,r.AvgPool3DBackprop=Ux,r.AvgPoolBackprop=pd,r.BatchMatMul=md,r.BatchToSpaceND=Iy,r.BroadcastTo=xy,r.Callback=PN,r.CallbackList=_v,r.Cast=Na,r.Ceil=xl,r.ClipByValue=Tl,r.Complex=fd,r.Concat=Al,r.Conv2D=gd,r.Conv2DBackpropFilter=Ty,r.Conv2DBackpropInput=yd,r.Conv3D=bd,r.Conv3DBackpropFilterV2=Ay,r.Conv3DBackpropInputV2=vy,r.Cos=Ca,r.Cosh=vl,r.CropAndResize=Bx,r.Cumsum=Ny,r.CustomCallback=$v,r.DataStorage=p,r.DepthToSpace=Mx,r.DepthwiseConv2dNative=wd,r.DepthwiseConv2dNativeBackpropFilter=Cy,r.DepthwiseConv2dNativeBackpropInput=Ry,r.Diag=Px,r.Dilation2D=Ld,r.Dilation2DBackpropFilter=Id,r.Dilation2DBackpropInput=Sd,r.Div=Ra,r.EarlyStopping=VN,r.Elu=Nl,r.EluGrad=zx,r.Environment=kx,r.Equal=Vx,r.Erf=Cl,r.Exp=Rl,r.Expm1=Ol,r.FFT=xd,r.Fill=Oy,r.FlipLeftRight=Td,r.Floor=El,r.FloorDiv=Ey,r.FromPixels=Bd,r.FusedBatchNorm=Dl,r.FusedConv2D=zd,r.FusedDepthwiseConv2D=Vd,r.GatherNd=Gx,r.GatherV2=Dy,r.GraphModel=t0,r.Greater=Yx,r.GreaterEqual=ky,r.History=Wv,r.IFFT=Ad,r.Identity=kl,r.Imag=vd,r.InputSpec=Ln,r.IsFinite=Fl,r.IsInf=_l,r.IsNan=Wl,r.KernelBackend=y,r.LRN=_y,r.LRNBackprop=Jx,r.LayerVariable=oi,r.LayersModel=ar,r.Less=Hx,r.LessEqual=qx,r.LinSpace=jx,r.Log=$l,r.Log1p=Ul,r.LogSoftmax=Fy,r.LogicalAnd=Kx,r.LogicalNot=Nd,r.LogicalOr=Xx,r.Max=Bl,r.MaxPool=Ml,r.MaxPool3D=$y,r.MaxPool3DBackprop=Zx,r.MaxPoolBackprop=Cd,r.MaxPoolWithArgmax=Rd,r.Maximum=Wy,r.Mean=Uy,r.Min=By,r.Minimum=My,r.MirrorPad=Pl,r.Mod=Py,r.MomentumOptimizer=Uh,r.Multiply=Oa,r.Negate=zy,r.NonMaxSuppressionV3=Vy,r.NonMaxSuppressionV4=Od,r.NonMaxSuppressionV5=Ed,r.NotEqual=zl,r.OP_SCOPE_SUFFIX=LT,r.OneHot=Yy,r.OnesLike=Gy,r.Optimizer=nr,r.PadV2=Dd,r.Pool=Ok,r.Pow=Hy,r.Prelu=kd,r.Prod=Qx,r.RMSPropOptimizer=Bh,r.RNN=Di,r.Range=eT,r.Real=Fd,r.Reciprocal=Vl,r.Relu=Gl,r.Relu6=Hl,r.Reshape=Yl,r.ResizeBilinear=jy,r.ResizeBilinearGrad=nT,r.ResizeNearestNeighbor=qy,r.ResizeNearestNeighborGrad=tT,r.Reverse=Ky,r.RotateWithOffset=Md,r.Round=ql,r.Rsqrt=jl,r.SGDOptimizer=sc,r.ScatterNd=sT,r.SelectV2=Xy,r.Selu=Kl,r.Sequential=uc,r.Sigmoid=Zl,r.Sign=Jl,r.Sin=Ea,r.Sinh=Xl,r.Slice=_d,r.Softmax=Qy,r.Softplus=Ql,r.SpaceToBatchND=Wd,r.SparseToDense=iT,r.SplitV=Zy,r.Sqrt=eh,r.Square=$d,r.SquaredDifference=Da,r.Step=sh,r.StridedSlice=rT,r.Sub=ka,r.Sum=Jy,r.SymbolicTensor=ai,r.Tan=Fa,r.Tanh=th,r.Tensor=ee,r.TensorBuffer=an,r.Tile=eb,r.TopK=oT,r.Transpose=nh,r.Unique=Ud,r.Unpack=tb,r.UnsortedSegmentSum=nb,r.Variable=lh,r.ZerosLike=sb,r._FusedMatMul=Pd,r.abs=dn,r.acos=Fb,r.acosh=_b,r.add=be,r.addN=ZT,r.addStrict=CA,r.all=lp,r.any=mh,r.argMax=fh,r.argMin=$b,r.asin=Ub,r.asinh=Bb,r.atan=Mb,r.atan2=Pb,r.atanh=zb,r.avgPool=yh,r.avgPool3d=Yb,r.backend=JT,r.backend_util=Ww,r.basicLSTMCell=K_,r.batchNorm=Wo,r.batchNorm2d=eA,r.batchNorm3d=tA,r.batchNorm4d=nA,r.batchToSpaceND=bh,r.booleanMaskAsync=aB,r.broadcastTo=wh,r.browser=ZF,r.buffer=wt,r.callbacks=EY,r.cast=Ae,r.ceil=Hb,r.clipByValue=Zn,r.clone=Fr,r.complex=Xi,r.concat=Ht,r.concat1d=sA,r.concat2d=iA,r.concat3d=rA,r.concat4d=oA,r.constraints=n3,r.conv1d=mp,r.conv2d=Qi,r.conv2dTranspose=fp,r.conv3d=jb,r.conv3dTranspose=gW,r.copyRegisteredKernels=kk,r.cos=Lh,r.cosh=gp,r.cosineWindow=Sw,r.cumsum=yp,r.customGrad=vi,r.data=Dq,r.deprecationWarn=un,r.depthToSpace=Kb,r.depthwiseConv2d=$o,r.deregisterOp=kY,r.device_util=Zk,r.diag=xW,r.dilation2d=Xb,r.disableDeprecationWarnings=u_,r.dispose=He,r.disposeVariables=d_,r.div=We,r.divNoNan=Jb,r.divStrict=RA,r.dot=cA,r.dropout=MA,r.elu=Ga,r.enableDebugMode=h_,r.enableProdMode=l_,r.enclosingPowerOfTwo=PA,r.engine=Ji,r.env=oe,r.equal=Qs,r.equalStrict=IA,r.erf=Zb,r.exp=Is,r.expandDims=Qn,r.expm1=Qb,r.eye=bp,r.fft=Oh,r.fill=Ya,r.findBackend=b_,r.findBackendFactory=w_,r.floor=Ha,r.floorDiv=cp,r.fused=MB,r.gather=qa,r.gatherND=BA,r.gather_util=QF,r.getBackend=g_,r.getGradient=rb,r.getKernel=ib,r.getKernelsForBackend=Gd,r.grad=t$,r.grads=n$,r.greater=xs,r.greaterEqual=er,r.greaterEqualStrict=xA,r.greaterStrict=TA,r.ifft=Qa,r.imag=Ih,r.image=Vr,r.inTopKAsync=kB,r.initializers=U3,r.input=aN,r.io=zF,r.irfft=kp,r.isFinite=hA,r.isInf=uA,r.isNaN=dA,r.keep=bn,r.kernel_impls=XM,r.layers=cY,r.leakyRelu=wp,r.less=xh,r.lessEqual=Br,r.lessEqualStrict=AA,r.lessStrict=vA,r.linalg=JA,r.linspace=pA,r.loadGraphModel=XH,r.loadLayersModel=MV,r.localResponseNormalization=tw,r.log=ls,r.log1p=Lp,r.logSigmoid=mA,r.logSoftmax=Ip,r.logSumExp=sw,r.logicalAnd=Bs,r.logicalNot=Th,r.logicalOr=xp,r.logicalXor=fA,r.losses=HM,r.matMul=ct,r.math=KF,r.max=es,r.maxPool=Ah,r.maxPool3d=iw,r.maxPoolWithArgmax=gA,r.maximum=Us,r.maximumStrict=OA,r.mean=jt,r.memory=ap,r.metrics=TY,r.min=Ka,r.minimum=Bo,r.minimumStrict=EA,r.mirrorPad=rw,r.mod=Tp,r.modStrict=DA,r.model=UV,r.models=AY,r.moments=Ap,r.movingAverage=AB,r.mul=X,r.mulStrict=kA,r.multiRNNCell=C$,r.multinomial=yA,r.neg=qt,r.nextFrame=Yp,r.norm=Wp,r.notEqual=Mr,r.notEqualStrict=NA,r.oneHot=ko,r.ones=ei,r.onesLike=_n,r.op=z,r.outerProduct=F$,r.pad=Ni,r.pad1d=$$,r.pad2d=B$,r.pad3d=P$,r.pad4d=V$,r.pool=bA,r.pow=ti,r.powStrict=FA,r.prelu=Nh,r.print=RT,r.prod=vp,r.profile=p_,r.rand=Z$,r.randomGamma=dU,r.randomNormal=cw,r.randomUniform=zo,r.range=Ch,r.ready=f_,r.real=Xa,r.reciprocal=lw,r.registerBackend=kb,r.registerCallbackConstructor=PV,r.registerGradient=aT,r.registerKernel=Yd,r.registerOp=DY,r.regularizers=RY,r.relu=Ci,r.relu6=hw,r.removeBackend=y_,r.reshape=K,r.reverse=Ts,r.reverse1d=LU,r.reverse2d=IU,r.reverse3d=TU,r.reverse4d=vU,r.rfft=Eh,r.round=uw,r.rsqrt=Np,r.scalar=Ce,r.scatterND=UA,r.scatter_util=e_,r.selu=Cp,r.separableConv2d=dw,r.sequential=BV,r.serialization=t_,r.setBackend=XT,r.setPlatform=L_,r.setdiff1dAsync=wA,r.sigmoid=Ai,r.sign=pw,r.signal=YM,r.sin=Rp,r.sinh=Op,r.slice=tt,r.slice1d=Ep,r.slice2d=mw,r.slice3d=Dp,r.slice4d=Rh,r.slice_util=qT,r.softmax=Vo,r.softplus=ja,r.spaceToBatchND=vh,r.sparseToDense=Lw,r.spectral=GM,r.split=us,r.sqrt=Nn,r.square=At,r.squaredDifference=Dh,r.squaredDifferenceStrict=_A,r.squeeze=Pr,r.stack=ts,r.step=ec,r.stridedSlice=fw,r.sub=Re,r.subStrict=WA,r.sum=$e,r.sumOutType=jd,r.tan=gw,r.tanh=Va,r.tensor=sn,r.tensor1d=hs,r.tensor2d=zr,r.tensor3d=WT,r.tensor4d=tc,r.tensor5d=ZU,r.tensor6d=QU,r.tensor_util=jk,r.test_util=c_,r.tidy=Q,r.tile=Ur,r.time=m_,r.topk=yw,r.train=Yo,r.transpose=Ye,r.truncatedNormal=kh,r.unique=Fp,r.unregisterGradient=Dk,r.unregisterKernel=Ek,r.unsortedSegmentSum=bw,r.unstack=ni,r.upcastType=$n,r.util=_k,r.valueAndGrad=s$,r.valueAndGrads=i$,r.variable=SA,r.variableGrads=nw,r.version=QJ,r.version_converter=n0,r.version_core=KT,r.version_layers=wm,r.where=Bn,r.whereAsync=ww,r.zeros=dt,r.zerosLike=et,Object.defineProperty(r,"__esModule",{value:!0})})});var c2=Jm((o9,a2)=>{vu(o9,{isNodejs:()=>a9});function a9(){return typeof global=="object"&&!0&&typeof a2!="undefined"&&typeof process!="undefined"&&!!process.version}});var H2=Jm(c9=>{vu(c9,{AgeGenderNet:()=>vf,BoundingBox:()=>Pc,Box:()=>Et,ComposableTask:()=>qs,ComputeAllFaceDescriptorsTask:()=>io,ComputeFaceDescriptorsTaskBase:()=>mf,ComputeSingleFaceDescriptorTask:()=>ro,DetectAllFaceLandmarksTask:()=>df,DetectAllFacesTask:()=>Cu,DetectFaceLandmarksTaskBase:()=>uf,DetectFacesTaskBase:()=>lf,DetectSingleFaceLandmarksTask:()=>pf,DetectSingleFaceTask:()=>hf,Dimensions:()=>rs,FACE_EXPRESSION_LABELS:()=>yf,FaceDetection:()=>Vt,FaceDetectionNet:()=>f2,FaceExpressionNet:()=>bf,FaceExpressions:()=>co,FaceLandmark68Net:()=>Wc,FaceLandmark68TinyNet:()=>gf,FaceLandmarkNet:()=>M2,FaceLandmarks:()=>Rs,FaceLandmarks5:()=>Y2,FaceLandmarks68:()=>Mc,FaceMatch:()=>_u,FaceMatcher:()=>uI,FaceRecognitionNet:()=>_c,Gender:()=>$i,LabeledBox:()=>Fu,LabeledFaceDescriptors:()=>po,NetInput:()=>yr,NeuralNetwork:()=>En,ObjectDetection:()=>ca,Point:()=>Ke,PredictedBox:()=>G2,Rect:()=>Bc,SsdMobilenetv1:()=>sa,SsdMobilenetv1Options:()=>Ys,TinyFaceDetector:()=>kc,TinyFaceDetectorOptions:()=>sf,TinyYolov2:()=>Dc,TinyYolov2Options:()=>Wi,TinyYolov2SizeType:()=>nf,allFaces:()=>W2,allFacesSsdMobilenetv1:()=>hI,allFacesTinyYolov2:()=>_2,awaitMediaLoaded:()=>Af,bufferToImage:()=>Tf,computeFaceDescriptor:()=>S2,createCanvas:()=>aa,createCanvasFromMedia:()=>Uc,createFaceDetectionNet:()=>m2,createFaceRecognitionNet:()=>B2,createSsdMobilenetv1:()=>rI,createTinyFaceDetector:()=>p2,createTinyYolov2:()=>d2,detectAllFaces:()=>Nu,detectFaceLandmarks:()=>cI,detectFaceLandmarksTiny:()=>L2,detectLandmarks:()=>k2,detectSingleFace:()=>F2,draw:()=>Qm,env:()=>Lt,euclideanDistance:()=>wf,extendWithAge:()=>Du,extendWithFaceDescriptor:()=>Eu,extendWithFaceDetection:()=>ao,extendWithFaceExpressions:()=>Ou,extendWithFaceLandmarks:()=>ia,extendWithGender:()=>Ru,extractFaceTensors:()=>oa,extractFaces:()=>ra,fetchImage:()=>V2,fetchJson:()=>xf,fetchNetWeights:()=>z2,fetchOrThrow:()=>uo,getContext2dOrThrow:()=>zn,getMediaDimensions:()=>ho,imageTensorToCanvas:()=>If,imageToSquare:()=>Sf,inverseSigmoid:()=>y2,iou:()=>cf,isMediaElement:()=>ku,isMediaLoaded:()=>$c,isWithAge:()=>U2,isWithFaceDetection:()=>mi,isWithFaceExpressions:()=>ff,isWithFaceLandmarks:()=>oo,isWithGender:()=>$2,loadAgeGenderModel:()=>O2,loadFaceDetectionModel:()=>E2,loadFaceExpressionModel:()=>R2,loadFaceLandmarkModel:()=>v2,loadFaceLandmarkTinyModel:()=>N2,loadFaceRecognitionModel:()=>C2,loadSsdMobilenetv1Model:()=>lI,loadTinyFaceDetectorModel:()=>T2,loadTinyYolov2Model:()=>A2,loadWeightMap:()=>Lf,locateFaces:()=>D2,matchDimensions:()=>P2,minBbox:()=>af,nets:()=>ft,nonMaxSuppression:()=>of,normalize:()=>Hs,padToSquare:()=>rf,predictAgeAndGender:()=>x2,recognizeFaceExpressions:()=>I2,resizeResults:()=>oI,resolveInput:()=>lo,shuffleArray:()=>g2,sigmoid:()=>Fc,ssdMobilenetv1:()=>aI,tf:()=>l2,tinyFaceDetector:()=>b2,tinyYolov2:()=>w2,toNetInput:()=>Ot,utils:()=>ef,validateConfig:()=>tf,version:()=>u2});const l2=Ze(Qe()),l9=typeof process!="undefined",h9=typeof navigator!="undefined"&&typeof navigator.userAgent!="undefined",u2={faceapi:h2,node:l9,browser:h9}});function br(r,l,u=!1){if(r.beginPath(),l.slice(1).forEach(({x:p,y},g)=>{const I=l[g];r.moveTo(I.x,I.y),r.lineTo(p,y)}),u){const p=l[l.length-1],y=l[0];if(!p||!y)return;r.moveTo(p.x,p.y),r.lineTo(y.x,y.y)}r.stroke()}class rs{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 rs(1/this.width,1/this.height)}}const ef={};vu(ef,{computeReshapedDimensions:()=>mI,getCenterPoint:()=>ua,isDimensions:()=>Cf,isEven:()=>Nf,isFloat:()=>pI,isTensor:()=>la,isTensor1D:()=>u9,isTensor2D:()=>dI,isTensor3D:()=>wr,isTensor4D:()=>Os,isValidNumber:()=>fi,isValidProbablitiy:()=>zc,range:()=>Ui,round:()=>ha});const q2=Ze(Qe());function la(r,l){return r instanceof q2.Tensor&&r.shape.length===l}function u9(r){return la(r,1)}function dI(r){return la(r,2)}function wr(r){return la(r,3)}function Os(r){return la(r,4)}function pI(r){return r%1!==0}function Nf(r){return r%2===0}function ha(r,l=2){const u=Math.pow(10,l);return Math.floor(r*u)/u}function Cf(r){return r&&r.width&&r.height}function mI({width:r,height:l},u){const p=u/Math.max(l,r);return new rs(Math.round(r*p),Math.round(l*p))}function ua(r){return r.reduce((l,u)=>l.add(u),new Ke(0,0)).div(new Ke(r.length,r.length))}function Ui(r,l,u){return Array(r).fill(0).map((p,y)=>l+y*u)}function fi(r){return!!r&&r!==Infinity&&r!==-Infinity&&!isNaN(r)||r===0}function zc(r){return fi(r)&&0<=r&&r<=1}class Ke{constructor(r,l){this._x=r,this._y=l}get x(){return this._x}get y(){return this._y}add(r){return new Ke(this.x+r.x,this.y+r.y)}sub(r){return new Ke(this.x-r.x,this.y-r.y)}mul(r){return new Ke(this.x*r.x,this.y*r.y)}div(r){return new Ke(this.x/r.x,this.y/r.y)}abs(){return new Ke(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 Ke(Math.floor(this.x),Math.floor(this.y))}}class Et{static isRect(r){return!!r&&[r.x,r.y,r.width,r.height].every(fi)}static assertIsValidBox(r,l,u=!1){if(!Et.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),y=[u.x,u.y,u.width,u.height].every(fi);if(!y&&!p)throw new Error(`Box.constructor - expected box to be IBoundingBox | IRect, instead have ${JSON.stringify(u)}`);const[g,I,S,T]=y?[u.x,u.y,u.width,u.height]:[u.left,u.top,u.right-u.left,u.bottom-u.top];Et.assertIsValidBox({x:g,y:I,width:S,height:T},"Box.constructor",l),this._x=g,this._y=I,this._width=S,this._height=T}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 Ke(this.left,this.top)}get topRight(){return new Ke(this.right,this.top)}get bottomLeft(){return new Ke(this.left,this.bottom)}get bottomRight(){return new Ke(this.right,this.bottom)}round(){const[r,l,u,p]=[this.x,this.y,this.width,this.height].map(y=>Math.round(y));return new Et({x:r,y:l,width:u,height:p})}floor(){const[r,l,u,p]=[this.x,this.y,this.width,this.height].map(y=>Math.floor(y));return new Et({x:r,y:l,width:u,height:p})}toSquare(){let{x:r,y:l,width:u,height:p}=this;const y=Math.abs(u-p);return u<p&&(r-=y/2,u+=y),p<u&&(l-=y/2,p+=y),new Et({x:r,y:l,width:u,height:p})}rescale(r){const l=Cf(r)?r.width:r,u=Cf(r)?r.height:r;return new Et({x:this.x*l,y:this.y*u,width:this.width*l,height:this.height*u})}pad(r,l){let[u,p,y,g]=[this.x-r/2,this.y-l/2,this.width+r,this.height+l];return new Et({x:u,y:p,width:y,height:g})}clipAtImageBorders(r,l){const{x:u,y:p,right:y,bottom:g}=this,I=Math.max(u,0),S=Math.max(p,0),T=y-I,C=g-S,D=Math.min(T,r-I),_=Math.min(C,l-S);return new Et({x:I,y:S,width:D,height:_}).floor()}shift(r,l){const{width:u,height:p}=this,y=this.x+r,g=this.y+l;return new Et({x:y,y:g,width:u,height:p})}padAtBorders(r,l){const u=this.width+1,p=this.height+1;let y=1,g=1,I=u,S=p,T=this.left,C=this.top,D=this.right,_=this.bottom;return D>l&&(I=-D+l+u,D=l),_>r&&(S=-_+r+p,_=r),T<1&&(S=2-T,T=1),C<1&&(S=2-C,C=1),{dy:g,edy:S,dx:y,edx:I,y:C,ey:_,x:T,ex:D,w:u,h:p}}calibrate(r){return new Et({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 Pc extends Et{constructor(r,l,u,p,y=!1){super({left:r,top:l,right:u,bottom:p},y)}}class ca{constructor(r,l,u,p,y){this._imageDims=new rs(y.width,y.height),this._score=r,this._classScore=l,this._className=u,this._box=new Et(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 Et(this._box).rescale(this.imageDims.reverse())}forSize(r,l){return new ca(this.score,this.classScore,this.className,this.relativeBox,{width:r,height:l})}}class Vt extends ca{constructor(r,l,u){super(r,r,"",l,u)}forSize(r,l){const{score:u,relativeBox:p,imageDims:y}=super.forSize(r,l);return new Vt(u,p,y)}}function cf(r,l,u=!0){const p=Math.max(0,Math.min(r.right,l.right)-Math.max(r.left,l.left)),y=Math.max(0,Math.min(r.bottom,l.bottom)-Math.max(r.top,l.top)),g=p*y;return u?g/(r.area+l.area-g):g/Math.min(r.area,l.area)}function af(r){const l=r.map(S=>S.x),u=r.map(S=>S.y),p=l.reduce((S,T)=>T<S?T:S,Infinity),y=u.reduce((S,T)=>T<S?T:S,Infinity),g=l.reduce((S,T)=>S<T?T:S,0),I=u.reduce((S,T)=>S<T?T:S,0);return new Pc(p,y,g,I)}function of(r,l,u,p=!0){let y=l.map((I,S)=>({score:I,boxIndex:S})).sort((I,S)=>I.score-S.score).map(I=>I.boxIndex);const g=[];for(;y.length>0;){const I=y.pop();g.push(I);const S=y,T=[];for(let C=0;C<S.length;C++){const D=S[C],_=r[I],A=r[D];T.push(cf(_,A,p))}y=y.filter((C,D)=>T[D]<=u)}return g}const Bi=Ze(Qe());function Hs(r,l){return Bi.tidy(()=>{const[u,p,y]=l,g=Bi.fill([...r.shape.slice(0,3),1],u,"float32"),I=Bi.fill([...r.shape.slice(0,3),1],p,"float32"),S=Bi.fill([...r.shape.slice(0,3),1],y,"float32"),T=Bi.concat([g,I,S],3);return Bi.sub(r,T)})}const mo=Ze(Qe());function rf(r,l=!1){return mo.tidy(()=>{const[u,p]=r.shape.slice(1);if(u===p)return r;const y=Math.abs(u-p),g=Math.round(y*(l?.5:1)),I=u>p?2:1,S=A=>{const B=r.shape.slice();return B[I]=A,mo.fill(B,0,"float32")},T=S(g),C=y-T.shape[I],D=l&&C?S(C):null,_=[D,r,T].filter(A=>!!A).map(A=>mo.cast(A,"float32"));return mo.concat(_,I)})}function g2(r){const l=r.slice();for(let u=l.length-1;u>0;u--){const p=Math.floor(Math.random()*(u+1)),y=l[u];l[u]=l[p],l[p]=y}return l}function Fc(r){return 1/(1+Math.exp(-r))}function y2(r){return Math.log(r/(1-r))}class Bc extends Et{constructor(r,l,u,p,y=!1){super({x:r,y:l,width:u,height:p},y)}}const d9=.5,p9=.43,m9=.45;class Rs{constructor(r,l,u=new Ke(0,0)){const{width:p,height:y}=l;this._imgDims=new rs(p,y),this._shift=u,this._positions=r.map(g=>g.mul(new Ke(p,y)).add(u))}get shift(){return new Ke(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 Ke(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 Ke(r,l))}shiftByPoint(r){return this.shiftBy(r.x,r.y)}align(r,l={}){if(r){const y=r instanceof Vt?r.box.floor():new Et(r);return this.shiftBy(y.x,y.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,y=D=>p.sub(D).magnitude(),g=(y(l)+y(u))/2,I=Math.floor(g/m9),S=ua(r),T=Math.floor(Math.max(0,S.x-d9*I)),C=Math.floor(Math.max(0,S.y-p9*I));return new Bc(T,C,Math.min(I,this.imageWidth+T),Math.min(I,this.imageHeight+C))}alignMinBbox(r){const l=af(this.positions);return l.pad(l.width*r,l.height*r)}getRefPointsForAlignment(){throw new Error("getRefPointsForAlignment not implemented by base class")}}class Y2 extends Rs{getRefPointsForAlignment(){const r=this.positions;return[r[0],r[1],ua([r[3],r[4]])]}}class Mc extends Rs{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(ua)}}class _u{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?` (${ha(this.distance)})`:""}`}}class Fu extends Et{static assertIsValidLabeledBox(r,l){if(Et.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 po{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 po(r.label,l)}}class G2 extends Fu{static assertIsValidPredictedBox(r,l){if(Fu.assertIsValidLabeledBox(r,l),!zc(r.score)||!zc(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 Vt}function ao(r,l){const u={detection:l};return Object.assign({},r,u)}function fI(){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 Rf(r){let l="";if(!r)try{r=require("fs")}catch(p){l=p.toString()}const u=r?function(p){return new Promise((y,g)=>{r.readFile(p,function(I,S){return I?g(I):y(S)})})}:function(){throw new Error(`readFile - failed to require fs in nodejs environment with error: ${l}`)};return{readFile:u}}function gI(){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")},y=global.fetch||function(){throw new Error("fetch - missing fetch implementation for nodejs environment")},g=Rf();return{Canvas:r||class{},CanvasRenderingContext2D:global.CanvasRenderingContext2D||class{},Image:l||class{},ImageData:global.ImageData||class{},Video:global.HTMLVideoElement||class{},createCanvasElement:u,createImageElement:p,fetch:y,...g}}function yI(){return typeof window=="object"&&typeof document!="undefined"&&typeof HTMLImageElement!="undefined"&&typeof HTMLCanvasElement!="undefined"&&typeof HTMLVideoElement!="undefined"&&typeof ImageData!="undefined"&&typeof CanvasRenderingContext2D!="undefined"}const bI=Ze(c2());let In;function f9(){if(!In)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return In}function wI(r){In=r}function LI(){if(yI())return wI(fI());if(bI.isNodejs())return wI(gI())}function g9(r){if(In||LI(),!In)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");const{Canvas:l=In.Canvas,Image:u=In.Image}=r;In.Canvas=l,In.Image=u,In.createCanvasElement=r.createCanvasElement||(()=>new l),In.createImageElement=r.createImageElement||(()=>new u),In.ImageData=r.ImageData||In.ImageData,In.Video=r.Video||In.Video,In.fetch=r.fetch||In.fetch,In.readFile=r.readFile||In.readFile}const Lt={getEnv:f9,setEnv:wI,initialize:LI,createBrowserEnv:fI,createFileSystem:Rf,createNodejsEnv:gI,monkeyPatch:g9,isBrowser:yI,isNodejs:bI.isNodejs};LI();function lo(r){return!Lt.isNodejs()&&typeof r=="string"?document.getElementById(r):r}function zn(r){const{Canvas:l,CanvasRenderingContext2D:u}=Lt.getEnv();if(r instanceof u)return r;const p=lo(r);if(!(p instanceof l))throw new Error("resolveContext2d - expected canvas to be of instance of Canvas");const y=p.getContext("2d");if(!y)throw new Error("resolveContext2d - canvas 2d context is null");return y}var Mi;(function(r){r.TOP_LEFT="TOP_LEFT",r.TOP_RIGHT="TOP_RIGHT",r.BOTTOM_LEFT="BOTTOM_LEFT",r.BOTTOM_RIGHT="BOTTOM_RIGHT"})(Mi||(Mi={}));class Of{constructor(r={}){const{anchorPosition:l,backgroundColor:u,fontColor:p,fontSize:y,fontStyle:g,padding:I}=r;this.anchorPosition=l||Mi.TOP_LEFT,this.backgroundColor=u||"rgba(0, 0, 0, 0.5)",this.fontColor=p||"rgba(255, 255, 255, 1)",this.fontSize=y||14,this.fontStyle=g||"Georgia",this.padding=I||4}}class Vc{constructor(r,l,u={}){this.text=typeof r=="string"?[r]:r instanceof Vc?r.text:r,this.anchor=l,this.options=new Of(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===Mi.BOTTOM_RIGHT||u===Mi.TOP_RIGHT,y=u===Mi.BOTTOM_LEFT||u===Mi.BOTTOM_RIGHT,g=this.measureWidth(r),I=this.measureHeight(),S=p?this.anchor.x-g:this.anchor.x,T=y?this.anchor.y-I:this.anchor.y;if(l){const{width:C,height:D}=l,_=Math.max(Math.min(S,C-g),0),A=Math.max(Math.min(T,D-I),0);return{x:_,y:A}}return{x:S,y:T}}draw(r){const l=lo(r),u=zn(l),{backgroundColor:p,fontColor:y,fontSize:g,fontStyle:I,padding:S}=this.options;u.font=`${g}px ${I}`;const T=this.measureWidth(u),C=this.measureHeight();u.fillStyle=p;const D=this.getUpperLeft(u,l);u.fillRect(D.x,D.y,T,C),u.fillStyle=y,this.text.forEach((_,A)=>{const B=S+D.x,ne=S+D.y+(A+1)*g;u.fillText(_,B,ne)})}}class j2{constructor(r={}){const{boxColor:l,lineWidth:u,label:p,drawLabelOptions:y}=r;this.boxColor=l||"rgba(0, 0, 255, 1)",this.lineWidth=u||2,this.label=p;const g={anchorPosition:Mi.BOTTOM_LEFT,backgroundColor:this.boxColor};this.drawLabelOptions=new Of(Object.assign({},g,y))}}class SI{constructor(r,l={}){this.box=new Et(r),this.options=new j2(l)}draw(r){const l=zn(r),{boxColor:u,lineWidth:p}=this.options,{x:y,y:g,width:I,height:S}=this.box;l.strokeStyle=u,l.lineWidth=p,l.strokeRect(y,g,I,S);const{label:T}=this.options;T&&new Vc([T],{x:y-p/2,y:g},this.options.drawLabelOptions).draw(r)}}function y9(r,l){const u=Array.isArray(l)?l:[l];u.forEach(p=>{const y=p instanceof Vt?p.score:mi(p)?p.detection.score:void 0,g=p instanceof Vt?p.box:mi(p)?p.detection.box:new Et(p),I=y?`${ha(y)}`:void 0;new SI(g,{label:I}).draw(r)})}function $c(r){const{Image:l,Video:u}=Lt.getEnv();return r instanceof l&&r.complete||r instanceof u&&r.readyState>=3}function Af(r){return new Promise((l,u)=>{if(r instanceof Lt.getEnv().Canvas||$c(r))return l(null);function p(g){if(!g.currentTarget)return;g.currentTarget.removeEventListener("load",p),g.currentTarget.removeEventListener("error",y),l(g)}function y(g){if(!g.currentTarget)return;g.currentTarget.removeEventListener("load",p),g.currentTarget.removeEventListener("error",y),u(g)}r.addEventListener("load",p),r.addEventListener("error",y)})}function Tf(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 y=Lt.getEnv().createImageElement();y.onload=()=>l(y),y.onerror=u,y.src=p.result},p.onerror=u,p.readAsDataURL(r)})}function ho(r){const{Image:l,Video:u}=Lt.getEnv();return r instanceof l?new rs(r.naturalWidth,r.naturalHeight):r instanceof u?new rs(r.videoWidth,r.videoHeight):new rs(r.width,r.height)}function aa({width:r,height:l}){const{createCanvasElement:u}=Lt.getEnv(),p=u();return p.width=r,p.height=l,p}function Uc(r,l){const{ImageData:u}=Lt.getEnv();if(!(r instanceof u)&&!$c(r))throw new Error("createCanvasFromMedia - media has not finished loading yet");const{width:p,height:y}=l||ho(r),g=aa({width:p,height:y});return r instanceof u?zn(g).putImageData(r,0,0):zn(g).drawImage(r,0,0,p,y),g}const Ef=Ze(Qe());async function If(r,l){const u=l||Lt.getEnv().createCanvasElement(),[p,y,g]=r.shape.slice(Os(r)?1:0),I=Ef.tidy(()=>r.as3D(p,y,g).toInt());return await Ef.browser.toPixels(I,u),I.dispose(),u}function ku(r){const{Image:l,Canvas:u,Video:p}=Lt.getEnv();return r instanceof l||r instanceof u||r instanceof p}const b9=1e-7,w9=1e-4;class K2{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?b9:w9}batchMatMul(r,l,u,p){return se("batchMatMul")}fusedBatchMatMul({a:r,b:l,transposeA:u,transposeB:p,bias:y,activation:g,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:y,preluActivationWeights:g}){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:y,preluActivationWeights:g}){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,y,g){return se("batchNorm")}localResponseNormalization4D(r,l,u,p,y){return se("localResponseNormalization4D")}LRNGrad(r,l,u,p,y,g,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,y){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,y,g){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`)}function J(r,l){if(!r)throw new Error(typeof l=="string"?l:l())}function tn(r,l,u=""){J(Wu(r,l),()=>u+` Shapes ${r} and ${l} must match`)}function Gc(r){J(r!=null,()=>"The input to the tensor constructor must be a non-null value.")}function da(r,l=[],u=!1){if(l==null&&(l=[]),Array.isArray(r)||Es(r)&&!u)for(let p=0;p<r.length;++p)da(r[p],l,u);else l.push(r);return l}function Zt(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 Wu(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 nn(r){return r%1===0}function Yc(r,l){return l<=r.length?r:r+" ".repeat(l-r.length)}function X2(r,l){let u=1,p=-1;for(let g=0;g<r.length;++g)if(r[g]>=0)u*=r[g];else if(r[g]===-1){if(p!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${p} and dim ${g}`);p=g}else if(r[g]<0)throw Error(`Shapes can not be < 0. Found ${r[g]} at dim ${g}`);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 y=r.slice();return y[p]=l/u,y}function gt(r,l){const u=l.length;return r=r==null?l.map((p,y)=>y):[].concat(r),J(r.every(p=>p>=-u&&p<u),()=>`All values in axis param must be in range [-${u}, ${u}) but got axis ${r}`),J(r.every(p=>nn(p)),()=>`All values in axis param must be integers but got axis ${r}`),r.map(p=>p<0?u+p:p)}function J2(r,l){const u=[],p=[],y=l!=null&&Array.isArray(l)&&l.length===0,g=l==null||y?null:gt(l,r).sort();let I=0;for(let S=0;S<r.length;++S){if(g!=null){if(g[I]===S&&r[S]!==1)throw new Error(`Can't squeeze axis ${S} since its dim '${r[S]}' is not 1`);(g[I]==null||g[I]>S)&&r[S]===1&&(u.push(r[S]),p.push(S)),g[I]<=S&&I++}r[S]!==1&&(u.push(r[S]),p.push(S))}return{newShape:u,keptDims:p}}function Z2(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 Q2(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 eR(r){return r==="bool"||r==="complex64"||r==="float32"||r==="int32"||r==="string"}function Es(r){return r instanceof Float32Array||r instanceof Int32Array||r instanceof Uint8Array}function tR(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 nR(r){if(r==null)return 0;let l=0;return r.forEach(u=>l+=u.length),l}function $u(r){return typeof r=="string"||r instanceof String}function L9(r){return typeof r=="boolean"}function S9(r){return typeof r=="number"}function Uu(r){return Array.isArray(r)?Uu(r[0]):r instanceof Float32Array?"float32":r instanceof Int32Array||r instanceof Uint8Array?"int32":S9(r)?"float32":$u(r)?"string":L9(r)?"bool":"float32"}function II(r){return!!(r&&r.constructor&&r.call&&r.apply)}function Bu(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 sR(r,l,u){const p=new Array;if(l.length===1){const y=l[0];for(let g=0;g<y;g++)p[g]=u[r+g]}else{const y=l[0],g=l.slice(1),I=g.reduce((S,T)=>S*T);for(let S=0;S<y;S++)p[S]=sR(r+S*I,g,u)}return p}function xI(r,l){if(r.length===0)return l[0];const u=r.reduce((p,y)=>p*y);if(u===0)return[];if(u!==l.length)throw new Error(`[${r}] does not match the input size ${l.length}.`);return sR(0,r,l)}function Df(r,l){const u=pa(r,l);for(let p=0;p<u.length;p++)u[p]=1;return u}function pa(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 kf(r){r.forEach(l=>{J(Number.isInteger(l)&&l>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${r}].`)})}function Ff(r){return r&&r.then&&typeof r.then=="function"}const iR="tfjsflags";class rR{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(Ff(l))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=I9(this.global.location.search);if(iR in r){const l=r[iR].split(",");l.forEach(u=>{const[p,y]=u.split(":");this.urlFlags[p]=x9(p,y)})}}}function I9(r){const l={};return r.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(u,...p)=>(T9(l,p[0],p[1]),p.join("="))),l}function T9(r,l,u){r[decodeURIComponent(l)]=decodeURIComponent(u||"")}function x9(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 Ds(){return oR}let oR=null;function aR(r){oR=r}let TI;function AI(){if(TI==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");TI=r}return TI}function A9(){const r=AI();return r._tfGlobals==null&&(r._tfGlobals=new Map),r._tfGlobals}function vI(r,l){const u=A9();if(u.has(r))return u.get(r);{const p=l();return u.set(r,p),u.get(r)}}const _f="Abs",cR="Acos",lR="Acosh",Hc="Add",hR="AddN",uR="ArgMax",dR="ArgMin",pR="Asin",mR="Asinh",fR="Atan",gR="Atanh",yR="Atan2",bR="AvgPool",wR="AvgPoolBackprop",LR="AvgPool3D",SR="AvgPool3DBackprop",Wf="BatchMatMul",$f="BatchToSpaceND",Uf="BroadcastTo",qc="Cast",IR="Ceil",xR="ClipByValue",TR="Complex",Bf="Concat",Mf="Conv2D",AR="Conv2DBackpropFilter",Pf="Conv2DBackpropInput",vR="Conv3D",NR="Conv3DBackpropFilterV2",CR="Conv3DBackpropInputV2",zf="Cos",Vf="Cosh",Gf="Cumsum",RR="CropAndResize",OR="DepthwiseConv2dNative",ER="DepthwiseConv2dNativeBackpropFilter",DR="DepthwiseConv2dNativeBackpropInput",kR="Dilation2D",FR="Dilation2DBackpropInput",_R="Dilation2DBackpropFilter",Yf="Div",WR="Elu",$R="EluGrad",UR="Erf",BR="Equal",Hf="Exp",MR="Expm1",PR="FFT",zR="Fill",VR="FlipLeftRight",qf="Floor",jf="FloorDiv",GR="FusedBatchNorm",Kf="GatherV2",YR="Greater",Xf="GreaterEqual",Jf="Identity",HR="IFFT",qR="Imag",jR="IsFinite",KR="IsInf",XR="IsNan",JR="Less",ZR="LessEqual",Zf="Log",Qf="Log1p",QR="LogicalAnd",eO="LogicalNot",tO="LogSoftmax",nO="LRN",sO="LRNBackprop",eg="Max",tg="Maximum",iO="MaxPool",rO="MaxPoolBackprop",oO="MaxPool3D",aO="MaxPool3DBackprop",cO="Mean",ng="Min",sg="Minimum",lO="MirrorPad",hO="Mod",ig="Multiply",rg="Negate",uO="NotEqual",dO="NonMaxSuppressionV3",pO="NonMaxSuppressionV4",mO="NonMaxSuppressionV5",fO="OnesLike",gO="OneHot",og="PadV2",ag="Pow",yO="Prelu",bO="Range",wO="Real",LO="Reciprocal",cg="Relu",lg="Reshape",hg="ResizeNearestNeighbor",SO="ResizeNearestNeighborGrad",ug="ResizeBilinear",IO="ResizeBilinearGrad",xO="Relu6",dg="Reverse",TO="Round",pg="Rsqrt",mg="SelectV2",AO="Selu",fg="Slice",gg="Sin",yg="Sinh",vO="Sign",bg="Sigmoid",NO="Softplus",wg="Sqrt",Lg="Sum",Sg="SpaceToBatchND",Ig="SplitV",CO="Softmax",xg="SquaredDifference",RO="Square",Tg="Sub",OO="Tan",EO="Tanh",Ag="Tile",vg="Transpose",Ng="Unpack",Cg="UnsortedSegmentSum",Rg="ZerosLike",Og="Step",NI="FromPixels",DO="RotateWithOffset";const kO=vI("kernelRegistry",()=>new Map),CI=vI("gradRegistry",()=>new Map);function Eg(r,l){const u=v9(r,l);return kO.get(u)}function RI(r){return CI.get(r)}function OI(r){const l=kO.entries(),u=[];for(;;){const{done:p,value:y}=l.next();if(p)break;const[g,I]=y,[S]=g.split("_");S===r&&u.push(I)}return u}function FO(r){const{kernelName:l}=r;CI.has(l)&&(Ds().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${l}'`)),CI.set(l,r)}function v9(r,l){return`${l}_${r}`}function N9(r,l){return r instanceof Float32Array&&l==="float32"||r instanceof Int32Array&&l==="int32"||r instanceof Uint8Array&&l==="bool"}function Dg(r,l){if(l==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(r)&&(r=da(r)),Ds().getBool("DEBUG")&&Q2(r,l),N9(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 EI(){return Ds().platform.now()}function _O(r,l="utf-8"){return l=l||"utf-8",Ds().platform.encode(r,l)}function DI(r,l="utf-8"){return l=l||"utf-8",Ds().platform.decode(r,l)}class WO{constructor(r,l){this.backendTimer=r,this.logger=l,l==null&&(this.logger=new R9)}profileKernel(r,l,u){let p;const y=()=>{p=u()},g=this.backendTimer.time(y);for(let S=0;S<p.length;S++){const T=p[S];T.data().then(C=>{C9(C,T.dtype,r)})}const I={kernelName:r,outputs:p,inputs:l,timeMs:g.then(S=>S.kernelMs),extraInfo:g.then(S=>S.getExtraProfileInfo!=null?S.getExtraProfileInfo():"")};return I}logKernelProfile(r){const{kernelName:l,outputs:u,timeMs:p,inputs:y,extraInfo:g}=r;u.forEach(I=>{Promise.all([I.data(),p,g]).then(S=>{this.logger.logKernelProfile(l,I,S[0],S[1],y,S[2])})})}}function C9(r,l,u){if(l!=="float32")return!1;for(let p=0;p<r.length;p++){const y=r[p];if(isNaN(y)||!isFinite(y))return console.warn(`Found ${y} in the result of '${u}'`),!0}return!1}class R9{logKernelProfile(r,l,u,p,y,g){const I=typeof p=="number"?Yc(`${p}ms`,9):p.error,S=Yc(r,25),T=l.rank,C=l.size,D=Yc(l.shape.toString(),14);let _="";for(const A in y){const B=y[A];if(B!=null){const ne=B.shape||l.shape,te=ne.length;_+=`${A}: ${te}D ${te>0?ne:""} `}}console.log(`%c${S} %c${I} %c${T}D ${D} %c${C} %c${_} %c${g}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function $O(r,l,u){const p={},y={};for(let T=0;T<l.length;T++)p[l[T].id]=!0;for(let T=0;T<r.length;T++){const C=r[T],D=C.inputs;for(const _ in D){const A=D[_];let B=!1;for(let ne=0;ne<l.length;ne++)if(p[A.id]){C.outputs.forEach(te=>p[te.id]=!0),B=!0,y[C.id]=!0;break}if(B)break}}const g={};g[u.id]=!0;const I={};for(let T=r.length-1;T>=0;T--){const C=r[T],D=C.inputs;for(let _=0;_<C.outputs.length;_++)if(g[C.outputs[_].id]){for(const A in D)g[D[A].id]=!0,I[C.id]=!0;break}}const S=[];for(let T=0;T<r.length;T++){const C=r[T];if(y[C.id]&&I[C.id]){const D={};for(const A in C.inputs){const B=C.inputs[A];p[B.id]&&(D[A]=B)}const _=Object.assign({},C);_.inputs=D,_.outputs=C.outputs,S.push(_)}}return S}function UO(r,l,u,p){for(let y=l.length-1;y>=0;y--){const g=l[y],I=[];if(g.outputs.forEach(T=>{const C=r[T.id];C!=null?I.push(C):I.push(null)}),g.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${g.kernelName}.`);const S=g.gradient(I);for(const T in g.inputs){if(!(T in S))throw new Error(`Cannot backprop through input ${T}. Available gradients found: ${Object.keys(S)}.`);const C=u(()=>S[T]());if(C.dtype!=="float32")throw new Error(`Error in gradient for op ${g.kernelName}. The gradient of input ${T} must have 'float32' dtype, but has '${C.dtype}'`);const D=g.inputs[T];if(!Wu(C.shape,D.shape))throw new Error(`Error in gradient for op ${g.kernelName}. The gradient of input '${T}' has shape '${C.shape}', which does not match the shape of the input '${D.shape}'`);if(r[D.id]==null)r[D.id]=C;else{const _=r[D.id];r[D.id]=p(_,C),_.dispose()}}}}const BO=20,Mu=3,kI=7;function MO(r,l,u,p){const y=Bu(l),g=O9(r,l,u,y),I=l.length,S=kg(r,l,u,y,g),T=["Tensor"];return p&&(T.push(` dtype: ${u}`),T.push(` rank: ${I}`),T.push(` shape: [${l}]`),T.push(" values:")),T.push(S.map(C=>" "+C).join(`
|
|
`)),T.join(`
|
|
`)}function O9(r,l,u,p){const y=Zt(l),g=p[p.length-1],I=new Array(g).fill(0),S=l.length,T=u==="complex64"?zu(r):r;if(S>1)for(let C=0;C<y/g;C++){const D=C*g;for(let _=0;_<g;_++)I[_]=Math.max(I[_],Pu(T[D+_],0,u).length)}return I}function Pu(r,l,u){let p;return Array.isArray(r)?p=`${parseFloat(r[0].toFixed(kI))} + ${parseFloat(r[1].toFixed(kI))}j`:$u(r)?p=`'${r}'`:u==="bool"?p=PO(r):p=parseFloat(r.toFixed(kI)).toString(),Yc(p,l)}function PO(r){return r===0?"false":"true"}function kg(r,l,u,p,y,g=!0){const I=u==="complex64"?2:1,S=l[0],T=l.length;if(T===0){if(u==="complex64"){const te=zu(r);return[Pu(te[0],0,u)]}return u==="bool"?[PO(r[0])]:[r[0].toString()]}if(T===1){if(S>BO){const P=Mu*I;let ge=Array.from(r.slice(0,P)),ae=Array.from(r.slice((S-Mu)*I,S*I));return u==="complex64"&&(ge=zu(ge),ae=zu(ae)),["["+ge.map((Le,ve)=>Pu(Le,y[ve],u)).join(", ")+", ..., "+ae.map((Le,ve)=>Pu(Le,y[S-Mu+ve],u)).join(", ")+"]"]}const te=u==="complex64"?zu(r):Array.from(r);return["["+te.map((P,ge)=>Pu(P,y[ge],u)).join(", ")+"]"]}const C=l.slice(1),D=p.slice(1),_=p[0]*I,A=[];if(S>BO){for(let te=0;te<Mu;te++){const P=te*_,ge=P+_;A.push(...kg(r.slice(P,ge),C,u,D,y,!1))}A.push("...");for(let te=S-Mu;te<S;te++){const P=te*_,ge=P+_;A.push(...kg(r.slice(P,ge),C,u,D,y,te===S-1))}}else for(let te=0;te<S;te++){const P=te*_,ge=P+_;A.push(...kg(r.slice(P,ge),C,u,D,y,te===S-1))}const B=T===2?",":"";A[0]="["+A[0]+B;for(let te=1;te<A.length-1;te++)A[te]=" "+A[te]+B;let ne=`,
|
|
`;for(let te=2;te<T;te++)ne+=`
|
|
`;return A[A.length-1]=" "+A[A.length-1]+"]"+(g?"":ne),A}function zu(r){const l=[];for(let u=0;u<r.length;u+=2)l.push([r[u],r[u+1]]);return l}class zO{constructor(r,l,u){if(this.dtype=l,this.shape=r.slice(),this.size=Zt(r),u!=null){const p=u.length;J(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||Z2(l,this.size),this.strides=Bu(r)}set(r,...l){l.length===0&&(l=[0]),J(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 y=`Requested out of range element at ${r}. Buffer shape=${this.shape}`;throw new Error(y)}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 Pi().makeTensor(this.values,this.shape,this.dtype)}}let Pi=null,jc=null,E9=null;function VO(r){Pi=r}function GO(r){jc=r}function YO(r){E9=r}class Dn{constructor(r,l,u,p){this.kept=!1,this.isDisposedInternal=!1,this.shape=r.slice(),this.dtype=l||"float32",this.size=Zt(r),this.strides=Bu(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 jc.buffer(this.shape,this.dtype,r)}bufferSync(){return jc.buffer(this.shape,this.dtype,this.dataSync())}async array(){const r=await this.data();return xI(this.shape,r)}arraySync(){return xI(this.shape,this.dataSync())}async data(){this.throwIfDisposed();const r=Pi().read(this.dataId);if(this.dtype==="string"){const l=await r;try{return l.map(u=>DI(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=Pi().readSync(this.dataId);if(this.dtype==="string")try{return r.map(l=>DI(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 Pi().read(this.dataId);return this.dtype==="string"?r:new Uint8Array(r.buffer)}dispose(){if(this.isDisposed)return;Pi().disposeTensor(this),this.isDisposedInternal=!0}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(r=!1){return jc.print(this,r)}clone(){return this.throwIfDisposed(),jc.clone(this)}toString(r=!1){const l=this.dataSync();return MO(l,this.shape,this.dtype,r)}cast(r){return this.throwIfDisposed(),jc.cast(this,r)}variable(r=!0,l,u){return this.throwIfDisposed(),Pi().makeVariable(this,r,l,u)}}Object.defineProperty(Dn,Symbol.hasInstance,{value:r=>!!r&&r.data!=null&&r.dataSync!=null&&r.throwIfDisposed!=null});class Fg extends Dn{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(!Wu(r.shape,this.shape))throw new Error(`shape of the new value (${r.shape}) and previous value (${this.shape}) must match`);Pi().disposeTensor(this),this.dataId=r.dataId,Pi().incRef(this,null)}dispose(){Pi().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(Fg,Symbol.hasInstance,{value:r=>r instanceof Dn&&r.assign!=null&&r.assign instanceof Function});var HO;(function(r){r.R0="R0",r.R1="R1",r.R2="R2",r.R3="R3",r.R4="R4",r.R5="R5",r.R6="R6"})(HO||(HO={}));var FI;(function(r){r.float32="float32",r.int32="int32",r.bool="int32",r.complex64="complex64"})(FI||(FI={}));var _I;(function(r){r.float32="float32",r.int32="int32",r.bool="bool",r.complex64="complex64"})(_I||(_I={}));var WI;(function(r){r.float32="float32",r.int32="float32",r.bool="float32",r.complex64="complex64"})(WI||(WI={}));var $I;(function(r){r.float32="complex64",r.int32="complex64",r.bool="complex64",r.complex64="complex64"})($I||($I={}));const D9={float32:WI,int32:FI,bool:_I,complex64:$I};function qO(r,l){if(r==="string"||l==="string"){if(r==="string"&&l==="string")return"string";throw new Error(`Can not upcast ${r} with ${l}`)}return D9[r][l]}function St(r,l){if(r.dtype===l.dtype)return[r,l];const u=qO(r.dtype,l.dtype);return[r.cast(u),l.cast(u)]}function _g(r){const l=[],u=new Set;return jO(r,l,u),l}function jO(r,l,u){if(r==null)return;if(r instanceof Dn){l.push(r);return}if(!k9(r))return;const p=r;for(const y in p){const g=p[y];u.has(g)||(u.add(g),jO(g,l,u))}}function k9(r){return Array.isArray(r)||typeof r=="object"}class KO{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 Vu{constructor(r){this.ENV=r,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new KO}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 WO(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 K2)&&typeof u.then=="function"){const p=++this.pendingBackendInitId,y=u.then(g=>p<this.pendingBackendInitId?!1:(this.registry[r]=g,this.pendingBackendInit=null,!0)).catch(g=>(p<this.pendingBackendInitId||(this.pendingBackendInit=null,console.warn(`Initialization of backend ${r} failed`),console.warn(g.stack||g.message)),!1));return this.pendingBackendInit=y,{success:y,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:y}=this.initializeBackend(u);if(y||p)return{name:u,asyncInit:y}}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,y=this.readSync(l);p.disposeData(l),u.backend=r,r.move(l,y,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 Vu.nextTensorId++}nextVariableId(){return Vu.nextVariableId++}clone(r){const l=this.makeTensorFromDataId(r.dataId,r.shape,r.dtype),u={x:r},p=g=>({x:()=>{const I="float32",S={x:g},T={dtype:I};return H.runKernelFunc(C=>C.cast(g,I),S,null,qc,T)}}),y=[];return this.addTapeNode(this.state.activeScope.name,u,[l],p,y,{}),l}runKernel(r,l,u,p,y){const g=null,I=null;return this.runKernelFunc(g,l,I,r,u,p,y)}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(r,l,u){const p=this.backend.numDataIds();let y=0;u.forEach(S=>{y+=S.dtype==="complex64"?3:1});const g=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],I=p-l-y-g;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,y,g,I){let S,T=[];const C=this.isTapeOn();p==null&&(p=this.state.activeScope!=null?this.state.activeScope.name:"");const D=this.state.numBytes,_=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let A;const B=Eg(p,this.backendName);let ne;if(B!=null)A=()=>{const P=this.backend.numDataIds();ne=B.kernelFunc({inputs:l,attrs:y,backend:this.backend});const ge=Array.isArray(ne)?ne:[ne];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(p,P,ge);const ae=ge.map(({dataId:Le,shape:ve,dtype:Ve})=>this.makeTensorFromDataId(Le,ve,Ve));if(C){let Le=this.getTensorsForGradient(p,l,ae);if(Le==null){I==null&&(I=[]);const ve=ae.filter((Ve,at)=>I[at]);Le=(g||[]).slice().concat(ve)}T=this.saveTensorsForBackwardMode(Le)}return ae};else{const P=ge=>{if(!C)return;T=ge.map(ae=>this.keep(this.clone(ae)))};A=()=>{const ge=this.backend.numDataIds();ne=this.tidy(()=>r(this.backend,P));const ae=Array.isArray(ne)?ne:[ne];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(p,ge,ae),ae}}let te;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?S=A():(te=this.profiler.profileKernel(p,l,()=>A()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(te),S=te.outputs)}),C&&this.addTapeNode(p,l,S,u,T,y),this.state.profiling&&this.state.activeProfile.kernels.push({name:p,bytesAdded:this.state.numBytes-D,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-_,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(l).map(P=>l[P]!=null?l[P].shape:null),outputShapes:S.map(P=>P.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 y=p.inputsToSave||[],g=p.outputsToSave||[];let I;p.saveAllInputs?(J(Array.isArray(l),()=>"saveAllInputs is true, expected inputs to be an array."),I=Object.keys(l).map(T=>l[T])):I=y.map(T=>l[T]);const S=u.filter((T,C)=>g[C]);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 y=r;u==="string"&&$u(r[0])&&(y=r.map(S=>_O(S)));const g=p.write(y,l,u),I=new Dn(l,u,g,this.nextTensorId());if(this.incRef(I,p),u==="string"){const S=this.state.tensorInfo.get(g),T=nR(y);this.state.numBytes+=T-S.bytes,S.bytes=T}return I}makeTensorFromDataId(r,l,u,p){u=u||"float32";const y=new Dn(l,u,r,this.nextTensorId());return this.incRef(y,p),y}makeVariable(r,l=!0,u,p){u=u||this.nextVariableId().toString(),p!=null&&p!==r.dtype&&(r=r.cast(p));const y=new Fg(r,l,u,this.nextTensorId());if(this.state.registeredVariables[y.name]!=null)throw new Error(`Variable with name ${y.name} was already registered`);return this.state.registeredVariables[y.name]=y,this.incRef(y,this.backend),y}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*tR(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 Fg||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,y,g){const I={id:this.state.nextTapeNodeId++,kernelName:r,inputs:l,outputs:u,saved:y},S=RI(r);S!=null&&(p=S.gradFunc),p!=null&&(I.gradient=T=>(T=T.map((C,D)=>{if(C==null){const _=u[D],A=pa(_.size,_.dtype);return this.makeTensor(A,_.shape,_.dtype)}return C}),p(T.length>1?T:T[0],y,g))),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=_g(r),u=new Set(l.map(y=>y.id));for(let y=0;y<this.state.activeScope.track.length;y++){const g=this.state.activeScope.track[y];!g.kept&&!u.has(g.id)&&g.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(y=>{!y.kept&&y.scopeId===p.id&&this.track(y)})}gradients(r,l,u,p=!1){if(J(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 y=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",r));J(y instanceof Dn,()=>"The result y returned by f() must be a tensor.");const g=$O(this.state.activeTape,l,y);if(!p&&g.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[y.id]=u==null?F9(y.shape):u,UO(I,g,T=>this.tidy(T),_9);const S=l.map(T=>I[T.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(T=>{for(const C of T.saved)C.dispose()}),this.state.activeTape=null),{value:y,grads:S}})}customGrad(r){return J(II(r),()=>"The f passed in customGrad(f) must be a function."),(...l)=>{J(l.every(y=>y instanceof Dn),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let u;const p={};return l.forEach((y,g)=>{p[g]=y}),this.runKernelFunc((y,g)=>(u=r(...l,g),J(u.value instanceof Dn,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),J(II(u.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),u.value),p,(y,g)=>{const I=u.gradFunc(y,g),S=Array.isArray(I)?I:[I];J(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(...)."),J(S.every(C=>C instanceof Dn),()=>"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 T={};return S.forEach((C,D)=>{T[D]=()=>C}),T})}}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=EI(),u=await this.backend.time(r);return u.wallMs=EI()-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 KO;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}}Vu.nextTensorId=0;Vu.nextVariableId=0;function F9(r){const l=Df(Zt(r),"float32");return H.makeTensor(l,r,"float32")}function UI(){const r=AI();if(r._tfengine==null){const l=new rR(r);r._tfengine=new Vu(l)}return aR(r._tfengine.ENV),VO(()=>r._tfengine),r._tfengine}const H=UI();function _9(r,l){const u={a:r,b:l};return H.runKernelFunc((p,y)=>{const g=p.add(r,l);return y([r,l]),g},u,null,Hc)}function XO(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}const Lr=Ds();Lr.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.")});Lr.registerFlag("IS_BROWSER",()=>XO());Lr.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Lr.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Lr.registerFlag("PROD",()=>!1);Lr.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Lr.getBool("DEBUG"));Lr.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Lr.registerFlag("IS_TEST",()=>!1);function Sr(r,l){let u=r;if(Es(r))return l==="string"?[]:[r.length];if(!Array.isArray(r))return[];const p=[];for(;Array.isArray(u)||Es(u)&&l!=="string";)p.push(u.length),u=u[0];return Array.isArray(r)&&Ds().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&JO(r,p,[]),p}function JO(r,l,u){if(u=u||[],!Array.isArray(r)&&!Es(r)){J(l.length===0,()=>`Element arr[${u.join("][")}] is a primitive, but should be an array/TypedArray of ${l[0]} elements`);return}J(l.length>0,()=>`Element arr[${u.join("][")}] should be a primitive, but is an array of ${r.length} elements`),J(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 y=0;y<r.length;++y)JO(r[y],p,u.concat(y))}function ZO(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 Dn)return ZO(p,r.dtype,l,u),r;let y=Uu(r);if(y!=="string"&&["bool","int32","float32"].indexOf(p)>=0&&(y=p),ZO(p,y,l,u),r==null||!Es(r)&&!Array.isArray(r)&&typeof r!="number"&&typeof r!="boolean"&&typeof r!="string"){const T=r==null?"null":r.constructor.name;throw new Error(`Argument '${l}' passed to '${u}' must be a Tensor or TensorLike, but got '${T}'`)}const g=Sr(r,y);!Es(r)&&!Array.isArray(r)&&(r=[r]);const I=!0,S=y!=="string"?Dg(r,y):da(r,[],I);return H.makeTensor(S,g,y)}function Wg(r,l,u,p="numeric"){if(!Array.isArray(r))throw new Error(`Argument ${l} passed to ${u} must be a \`Tensor[]\` or \`TensorLike[]\``);const y=r;return y.map((g,I)=>M(g,`${l}[${I}]`,u),p)}const QO="__op";function V(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+QO;const y=(...g)=>{H.startScope(u);try{const I=p(...g);return Ff(I)&&console.error("Cannot return a Promise inside of tidy."),H.endScope(I),I}catch(I){throw H.endScope(null),I}};return Object.defineProperty(y,"name",{value:u,configurable:!0}),y}function W9(r,l){const u=M(r,"real","complex"),p=M(l,"imag","complex");tn(u.shape,p.shape,`real and imag shapes, ${u.shape} and ${p.shape}, must match in call to tf.complex().`);const y=I=>I.complex(u,p),g={real:u,imag:p};return H.runKernelFunc(y,g,null,TR)}const zi=V({complex_:W9});function Vi(r,l,u,p){if(p==null&&(p=Uu(r)),p==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!Es(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){kf(l);const y=Zt(l),g=Zt(u);J(y===g,()=>`Based on the provided shape, [${l}], the tensor should have ${y} values but has ${g}`);for(let I=0;I<u.length;++I){const S=u[I],T=I===u.length-1?S!==Zt(l.slice(I)):!0;J(u[I]===l[I]||!T,()=>`Error creating a new Tensor. Inferred shape (${u}) does not match the provided shape (${l}). `)}}return!Es(r)&&!Array.isArray(r)&&(r=[r]),l=l||u,r=p!=="string"?Dg(r,p):da(r,[],!0),H.makeTensor(r,l,p)}function BI(r,l,u){const p=Sr(r,u);return Vi(r,l,p,u)}function Gu(r,l="float32",u){return l=l||"float32",kf(r),new zO(r,l,u)}function $9(r,l){const u=M(r,"x","cast");if(!eR(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},y={dtype:l};return H.runKernelFunc(g=>g.cast(u,l),p,null,qc,y)}const Ie=V({cast_:$9});function U9(r){const l=M(r,"x","clone",null),u=()=>H.makeTensorFromDataId(l.dataId,l.shape,l.dtype),p={x:l};return H.runKernelFunc(u,p,null,Jf)}const gi=V({clone_:U9});function MI(r,l=!1){console.log(r.toString(l))}UI();const B9={buffer:Gu,cast:Ie,clone:gi,print:MI};GO(B9);function M9(r,l){const u=M(r,"x","reshape",null),p={x:u},y={shape:l},g=(I,S)=>(l=X2(l,u.size),J(u.size===Zt(l),()=>"new shape and old shape must have the same number of elements."),S([u]),I.reshape(u,l));return H.runKernelFunc(g,p,null,lg,y)}const re=V({reshape_:M9});function P9(r,l,u=!1,p=!1){let y=M(r,"a","matMul"),g=M(l,"b","matMul");[y,g]=St(y,g);const I=(C,D)=>{D([y,g]);const _=u?y.shape[y.rank-2]:y.shape[y.rank-1],A=p?g.shape[g.rank-1]:g.shape[g.rank-2],B=u?y.shape[y.rank-1]:y.shape[y.rank-2],ne=p?g.shape[g.rank-2]:g.shape[g.rank-1],te=y.shape.slice(0,-2),P=g.shape.slice(0,-2),ge=Zt(te),ae=Zt(P),Le=ge===ae||ge===1||ae===1;J(y.rank>=2&&g.rank>=2&&Le,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${te}) and (${P}).`),J(_===A,()=>`Error in matMul: inner shapes (${_}) and (${A}) of Tensors with shapes ${y.shape} and ${g.shape} and transposeA=${u} and transposeB=${p} must match.`);const ve=ge>ae?te:P,Ve=ve.concat([B,ne]),at=u?re(y,[ge,_,B]):re(y,[ge,B,_]),pt=p?re(g,[ae,ne,A]):re(g,[ae,A,ne]),$t=C.batchMatMul(at,pt,u,p);return re($t,Ve)},S={a:y,b:g},T={transposeA:u,transposeB:p};return H.runKernelFunc(I,S,null,Wf,T)}const yn=V({matMul_:P9});function z9(r,l){const u=M(r,"x","transpose");if(l==null&&(l=u.shape.map((g,I)=>I).reverse()),J(u.rank===l.length,()=>`Error in transpose: rank of input ${u.rank} must match length of perm ${l}.`),l.forEach(g=>{J(g>=0&&g<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},y={perm:l};return H.runKernelFunc(g=>g.transpose(u,l),p,null,vg,y)}const xn=V({transpose_:z9});function PI(r,l,u){if(Gc(r),l!=null&&l.length!==3)throw new Error("tensor3d() requires shape to have three numbers");const p=Sr(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 zI={};vu(zI,{fromPixels:()=>Y9,toPixels:()=>G9});let Kc;function V9(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,y=!1,g=!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)y=!0;else if(typeof HTMLImageElement!="undefined"&&r instanceof HTMLImageElement)g=!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(y){const B=2;if(y&&r.readyState<B)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.")}const S=Eg(NI,H.backendName);if(S!=null){const B={pixels:r},ne={numChannels:l};return H.runKernel(NI,B,ne)}const[T,C]=y?[r.videoWidth,r.videoHeight]:[r.width,r.height];let D;I?D=r.getContext("2d").getImageData(0,0,T,C).data:p||u?D=r.data:(g||y)&&(Kc==null&&(Kc=document.createElement("canvas").getContext("2d")),Kc.canvas.width=T,Kc.canvas.height=C,Kc.drawImage(r,0,0,T,C),D=Kc.getImageData(0,0,T,C).data);let _;if(l===4)_=new Int32Array(D);else{const B=T*C;_=new Int32Array(B*l);for(let ne=0;ne<B;ne++)for(let te=0;te<l;++te)_[ne*l+te]=D[ne*4+te]}const A=[C,T,l];return PI(_,A,"int32")}async function G9(r,l){let u=M(r,"img","toPixels");if(!(r instanceof Dn)){const C=u;u=Ie(C,"int32"),C.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,y]=u.shape.slice(0,2),g=u.rank===2?1:u.shape[2];if(g>4||g===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${g}`);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,T=new Uint8ClampedArray(y*p*4);for(let C=0;C<p*y;++C){const D=[0,0,0,255];for(let A=0;A<g;A++){const B=I[C*g+A];if(u.dtype==="float32"){if(B<0||B>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${B}.`)}else if(u.dtype==="int32"&&(B<0||B>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${B}.`);g===1?(D[0]=B*S,D[1]=B*S,D[2]=B*S):D[A]=B*S}const _=C*4;T[_+0]=Math.round(D[0]),T[_+1]=Math.round(D[1]),T[_+2]=Math.round(D[2]),T[_+3]=Math.round(D[3])}if(l!=null){l.width=y,l.height=p;const C=l.getContext("2d"),D=new ImageData(T,y,p);C.putImageData(D,0,0)}return u!==r&&u.dispose(),T}const Y9=V({fromPixels_:V9});function e1(r,l,u){const p=r.shape.length;J(p===l.length,()=>`Error in slice${p}D: Length of begin ${l} must match the rank of the array (${p}).`),J(p===u.length,()=>`Error in slice${p}D: Length of size ${u} must match the rank of the array (${p}).`);for(let y=0;y<p;++y)J(l[y]+u[y]<=r.shape[y],()=>`Error in slice${p}D: begin[${y}] + size[${y}] (${l[y]+u[y]}) would overflow input.shape[${y}] (${r.shape[y]})`)}function $g(r,l,u){let p;const y=r.shape.length;typeof l=="number"?p=[l,...new Array(y-1).fill(0)]:l.length<y?p=l.concat(new Array(y-l.length).fill(0)):p=l.slice(),p.forEach(I=>{J(I!==-1,()=>"slice() does not support negative begin indexing.")});let g;return u==null?g=new Array(y).fill(-1):typeof u=="number"?g=[u,...new Array(y-1).fill(-1)]:u.length<y?g=u.concat(new Array(y-u.length).fill(-1)):g=u,g=g.map((I,S)=>I>=0?I:(J(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,g]}function H9(r){Ds().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(r+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}YO(H9);function t1(r,l){return H.tidy(r,l)}function n1(r){const l=_g(r);l.forEach(u=>u.dispose())}function q9(r,l){let u=M(r,"a","add"),p=M(l,"b","add");[u,p]=St(u,p);const y=(I,S)=>{const T=I.add(u,p);return S([u,p]),T},g={a:u,b:p};return H.runKernelFunc(y,g,null,Hc)}const vt=V({add_:q9});function j9(r,l){let u=M(r,"a","floorDiv"),p=M(l,"b","floorDiv");[u,p]=St(u,p);const y=(I,S)=>{const T=I.floorDiv(u,p);return S([u,p]),T},g={a:u,b:p};return H.runKernelFunc(y,g,null,jf)}const VI=V({floorDiv_:j9});function K9(r,l){let u=M(r,"a","div"),p=M(l,"b","div");if([u,p]=St(u,p),u.dtype==="int32"&&p.dtype==="int32")return VI(u,p);const y=(S,T)=>{const C=S.realDivide(u,p);return T([u,p]),C},g={a:u,b:p},I={};return H.runKernelFunc(y,g,null,Yf,I)}const Me=V({div_:K9});function X9(r,l){let u=M(r,"a","mul"),p=M(l,"b","mul");[u,p]=St(u,p);const y=(I,S)=>{const T=I.multiply(u,p);return S([u,p]),T},g={a:u,b:p};return H.runKernelFunc(y,g,null,ig)}const le=V({mul_:X9});function J9(r){const l=M(r,"x","abs"),u={x:l};return H.runKernelFunc((p,y)=>(y([l]),l.dtype==="complex64"?p.complexAbs(l):p.abs(l)),u,null,_f)}const Vn=V({abs_:J9});function Z9(r,l){for(let u=0;u<r.length;++u)if(r[r.length-u-1]!==l-1-u)return!1;return!0}function Q9(r,l,u){const p=r.length+l.length,y=[];let g=0,I=0;for(let S=0;S<p;S++)u.indexOf(S)===-1?y.push(r[g++]):y.push(l[I++]);return y}function s1(r,l){const u=[],p=r.length;for(let g=0;g<p;g++)l.indexOf(g)===-1&&u.push(r[g]);const y=l.map(g=>r[g]);return[u,y]}function os(r,l){const u=l.map(p=>1);return Q9(r,u,l)}function Gi(r,l){if(Z9(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 Xc(r){return r.map((l,u)=>[u,l]).sort((l,u)=>l[1]-u[1]).map(l=>l[0])}function fo(r,l){const u=[];for(let p=l-r;p<l;++p)u.push(p);return u}function Bg(r,l,u,p,y,g,I="channelsLast"){const[S,T]=Ug(l);let C;if(I==="channelsLast")C=[S,T,r[3],r[3]];else if(I==="channelsFirst")C=[S,T,r[1],r[1]];else throw new Error(`Unknown dataFormat ${I}`);return yi(r,C,u,p,y,g,!1,I)}function Mg(r,l,u,p,y,g,I="NDHWC"){const[S,T,C]=GI(l);let D,_;if(I==="NDHWC")_="channelsLast",D=[S,T,C,r[4],r[4]];else if(I==="NCDHW")_="channelsFirst",D=[S,T,C,r[1],r[1]];else throw new Error(`Unknown dataFormat ${I}`);return Yu(r,D,u,p,y,!1,_,g)}function yi(r,l,u,p,y,g,I=!1,S="channelsLast"){let[T,C,D,_]=[-1,-1,-1,-1];if(S==="channelsLast")[T,C,D,_]=r;else if(S==="channelsFirst")[T,_,C,D]=r;else throw new Error(`Unknown dataFormat ${S}`);const[A,B,,ne]=l,[te,P]=Ug(u),[ge,ae]=Ug(p),Le=Jc(A,ge),ve=Jc(B,ae),{padInfo:Ve,outHeight:at,outWidth:pt}=eZ(y,C,D,te,P,Le,ve,g,S),$t=I?ne*_:ne;let Gt;return S==="channelsFirst"?Gt=[T,$t,at,pt]:S==="channelsLast"&&(Gt=[T,at,pt,$t]),{batchSize:T,dataFormat:S,inHeight:C,inWidth:D,inChannels:_,outHeight:at,outWidth:pt,outChannels:$t,padInfo:Ve,strideHeight:te,strideWidth:P,filterHeight:A,filterWidth:B,effectiveFilterHeight:Le,effectiveFilterWidth:ve,dilationHeight:ge,dilationWidth:ae,inShape:r,outShape:Gt,filterShape:l}}function Yu(r,l,u,p,y,g=!1,I="channelsLast",S){let[T,C,D,_,A]=[-1,-1,-1,-1,-1];if(I==="channelsLast")[T,C,D,_,A]=r;else if(I==="channelsFirst")[T,A,C,D,_]=r;else throw new Error(`Unknown dataFormat ${I}`);const[B,ne,te,,P]=l,[ge,ae,Le]=GI(u),[ve,Ve,at]=GI(p),pt=Jc(B,ve),$t=Jc(ne,Ve),Gt=Jc(te,at),{padInfo:qe,outDepth:ln,outHeight:bt,outWidth:ws}=tZ(y,C,D,_,ge,ae,Le,pt,$t,Gt,S),Cr=g?P*A:P;let Rr;return I==="channelsFirst"?Rr=[T,Cr,ln,bt,ws]:I==="channelsLast"&&(Rr=[T,ln,bt,ws,Cr]),{batchSize:T,dataFormat:I,inDepth:C,inHeight:D,inWidth:_,inChannels:A,outDepth:ln,outHeight:bt,outWidth:ws,outChannels:Cr,padInfo:qe,strideDepth:ge,strideHeight:ae,strideWidth:Le,filterDepth:B,filterHeight:ne,filterWidth:te,effectiveFilterDepth:pt,effectiveFilterHeight:$t,effectiveFilterWidth:Gt,dilationDepth:ve,dilationHeight:Ve,dilationWidth:at,inShape:r,outShape:Rr,filterShape:l}}function nZ(r,l,u,p,y){p==null&&(p=i1(r,l,u));const g=r[0],I=r[1],S=ma((g-l+2*p)/u+1,y);J(nn(S),()=>`The output # of rows (${S}) must be an integer. Change the stride and/or zero pad parameters`);const T=ma((I-l+2*p)/u+1,y);return J(nn(T),()=>`The output # of columns (${T}) must be an integer. Change the stride and/or zero pad parameters`),[S,T]}function sZ(r,l,u,p,y,g){y==null&&(y=i1(r,l,p));const I=r[0],S=r[1],T=r[2],C=ma((I-l+2*y)/p+1,g);J(nn(C),()=>`The output # of depths (${C}) must be an integer. Change the stride and/or zero pad parameters`);const D=ma((S-l+2*y)/p+1,g);J(nn(D),()=>`The output # of rows (${D}) must be an integer. Change the stride and/or zero pad parameters`);const _=ma((T-l+2*y)/p+1,g);return J(nn(_),()=>`The output # of columns (${_}) must be an integer. Change the stride and/or zero pad parameters`),[C,D,_,u]}function i1(r,l,u,p=1){const y=Jc(l,p);return Math.floor((r[0]*(u-1)-u+y)/2)}function Ug(r){return typeof r=="number"?[r,r,r]:r.length===2?[r[0],r[1],1]:r}function GI(r){return typeof r=="number"?[r,r,r]:r}function Jc(r,l){return l<=1?r:r+(r-1)*(l-1)}function eZ(r,l,u,p,y,g,I,S,T){let C,D,_;if(typeof r=="number"){const A=r===0?"VALID":"NUMBER";C={top:r,bottom:r,left:r,right:r,type:A};const B=nZ([l,u],g,p,r,S);D=B[0],_=B[1]}else if(r==="same"){D=Math.ceil(l/p),_=Math.ceil(u/y);const A=Math.max(0,(D-1)*p+g-l),B=Math.max(0,(_-1)*y+I-u),ne=Math.floor(A/2),te=A-ne,P=Math.floor(B/2),ge=B-P;C={top:ne,bottom:te,left:P,right:ge,type:"SAME"}}else if(r==="valid")C={top:0,bottom:0,left:0,right:0,type:"VALID"},D=Math.ceil((l-g+1)/p),_=Math.ceil((u-I+1)/y);else if(typeof r=="object"){const A=T==="channelsLast"?r[1][0]:r[2][0],B=T==="channelsLast"?r[1][1]:r[2][1],ne=T==="channelsLast"?r[2][0]:r[3][0],te=T==="channelsLast"?r[2][1]:r[3][1],P=A===0&&B===0&&ne===0&&te===0?"VALID":"EXPLICIT";C={top:A,bottom:B,left:ne,right:te,type:P},D=ma((l-g+A+B)/p+1,S),_=ma((u-I+ne+te)/y+1,S)}else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:C,outHeight:D,outWidth:_}}function tZ(r,l,u,p,y,g,I,S,T,C,D){let _,A,B,ne;if(typeof r=="number"){const te=r===0?"VALID":"NUMBER";_={top:r,bottom:r,left:r,right:r,front:r,back:r,type:te};const P=sZ([l,u,p,1],S,1,y,r,D);A=P[0],B=P[1],ne=P[2]}else if(r==="same"){A=Math.ceil(l/y),B=Math.ceil(u/g),ne=Math.ceil(p/I);const te=(A-1)*y+S-l,P=(B-1)*g+T-u,ge=(ne-1)*I+C-p,ae=Math.floor(te/2),Le=te-ae,ve=Math.floor(P/2),Ve=P-ve,at=Math.floor(ge/2),pt=ge-at;_={top:ve,bottom:Ve,left:at,right:pt,front:ae,back:Le,type:"SAME"}}else if(r==="valid")_={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},A=Math.ceil((l-S+1)/y),B=Math.ceil((u-T+1)/g),ne=Math.ceil((p-C+1)/I);else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:_,outDepth:A,outHeight:B,outWidth:ne}}function ma(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 go(r){const[l,u,p]=Ug(r);return l===1&&u===1&&p===1}function yo(r,l){return go(r)||go(l)}function Zc(r){if(r==="NHWC")return"channelsLast";if(r==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${r}`)}function r1(r,l){const u=r[0].length;r.forEach((y,g)=>{J(y.length===u,()=>`Error in concat${u}D: rank of tensors[${g}] must be the same as the rank of the rest (${u})`)}),J(l>=0&&l<u,()=>`Error in concat${u}D: axis must be between 0 and ${u-1}.`);const p=r[0];r.forEach((y,g)=>{for(let I=0;I<u;I++)J(I===l||y[I]===p[I],()=>`Error in concat${u}D: Shape of tensors[${g}] (${y}) does not match the shape of the rest (${p}) along the non-concatenated axis ${g}.`)})}function o1(r,l){const u=r[0].slice();for(let p=1;p<r.length;p++)u[l]+=r[p][l];return u}function iZ(r,l=0){J(r.length>=1,()=>"Pass at least one tensor to concat");let u=Wg(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 T=gt(l,u[0].shape)[0],C=o1(u.map(A=>A.shape),T);if(Zt(C)===0)return BI([],C);if(u=u.filter(A=>A.size>0),u.length===1)return u[0];const D=u.map(A=>A.shape);r1(D,T);const _=I.concat(u,T);return S(u),_},y=u,g={axis:l};return H.runKernelFunc(p,y,null,Bf,g)}const Tn=V({concat_:iZ});function rZ(r){const l=M(r,"x","sigmoid"),u={x:l};return H.runKernelFunc((p,y)=>{const g=p.sigmoid(l);return y([g]),g},u,null,bg)}const YI=V({sigmoid_:rZ});function oZ(r,l,u){const p=M(r,"x","slice");if(p.rank===0)throw new Error("Slicing scalar is not possible");const y=(S,T)=>{const[C,D]=$g(p,l,u);return e1(p,C,D),T([p]),S.slice(p,C,D)},g={x:p},I={begin:l,size:u};return H.runKernelFunc(y,g,null,fg,I)}const Tt=V({slice_:oZ});function aZ(r,l,u){const p=M(r,"x","batchToSpaceND"),y=l.reduce((T,C)=>T*C);J(p.rank>=1+l.length,()=>`input rank is ${p.rank} but should be > than blockShape.length ${l.length}`),J(u.length===l.length,()=>`crops.length is ${u.length} but should be equal to blockShape.length ${l.length}`),J(p.shape[0]%y===0,()=>`input tensor batch is ${p.shape[0]} but is not divisible by the product of the elements of blockShape ${l.join(" * ")} === ${y}`);const g=T=>T.batchToSpaceND(p,l,u),I={x:p},S={blockShape:l,crops:u};return H.runKernelFunc(g,I,null,$f,S)}const HI=V({batchToSpaceND_:aZ});function cZ(r,l){let u=M(r,"broadcastTo","x");const p=u.shape;if(l.some(D=>!(D>0)||D%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 D=u.shape.slice();for(;D.length<l.length;)D.unshift(1);u=re(u,D)}const y=u.shape,g=Array.from(l);for(let D=l.length-1;D>=0;D--)if(y[D]===l[D])g[D]=1;else if(u.shape[D]!==1)throw new Error(`broadcastTo(): [${p}] cannot be broadcast to [${l}].`);const I=g.map((D,_)=>D>1?_:-1).filter(D=>D>=0);if(I.length===0)return gi(u);const S=D=>D.tile(u,g),T={x:u},C={shape:l,inputShape:y};return H.runKernelFunc(S,T,null,Uf,C)}const Pg=V({broadcastTo_:cZ});function lZ(r,l,u,p,y="NHWC",g=[1,1],I){const S=M(r,"x","conv2d"),T=M(l,"filter","conv2d");let C=S,D=!1;S.rank===3&&(D=!0,C=re(S,[1,S.shape[0],S.shape[1],S.shape[2]])),J(C.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${C.rank}.`),J(T.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${T.rank}.`),I!=null&&J(nn(p),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${I} but got pad ${p}.`);const _=y==="NHWC"?C.shape[3]:C.shape[1];J(_===T.shape[2],()=>`Error in conv2d: depth of input (${_}) must match input depth for filter ${T.shape[2]}.`),J(yo(u,g),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${u} and dilations '${g}'`);const A=(P,ge)=>{const ae=Zc(y),Le=yi(C.shape,T.shape,u,g,p,I,!1,ae),ve=P.conv2d(C,T,Le);return ge([C,T]),ve},B={x:C,filter:T},ne={strides:u,pad:p,dataFormat:y,dilations:g,dimRoundingMode:I},te=H.runKernelFunc(A,B,null,Mf,ne);return D?re(te,[te.shape[1],te.shape[2],te.shape[3]]):te}const qI=V({conv2d_:lZ});function hZ(r,l,u,p,y,g="NHWC",I){J(r.length===l.rank,()=>`Length of inShape (${r.length}) and rank of dy (${l.rank}) must match`);let S=r,T=l,C=!1;l.rank===3&&(C=!0,T=re(l,[1,l.shape[0],l.shape[1],l.shape[2]]),S=[1,r[0],r[1],r[2]]),J(S.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${S.length}.`),J(T.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${T.rank}`),J(u.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${u.rank}`);const D=g==="NHWC"?S[3]:S[1],_=g==="NHWC"?T.shape[3]:T.shape[1];J(D===u.shape[2],()=>`Error in conv2dDerInput: depth of input (${D}) must match input depth for filter ${u.shape[2]}.`),J(_===u.shape[3],()=>`Error in conv2dDerInput: depth of output (${_}) must match output depth for filter ${u.shape[3]}.`),I!=null&&J(nn(y),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${I} but got pad ${y}.`);const A=(P,ge)=>{const ae=1,Le=Zc(g),ve=yi(S,u.shape,p,ae,y,I,!1,Le),Ve=P.conv2dDerInput(T,u,ve);return ge([T,u]),Ve},B={dy:T,filter:u},ne={strides:p,pad:y,dataFormat:g,dimRoundingMode:I,inputShape:S},te=H.runKernelFunc(A,B,null,Pf,ne);return C?re(te,[te.shape[1],te.shape[2],te.shape[3]]):te}const a1=V({conv2DBackpropInput_:hZ});function uZ(r,l,u,p,y){J(r.length===l.rank,()=>`Length of inShape (${r.length}) and rank of dy (${l.rank}) must match`);let g=r,I=l,S=!1;l.rank===4&&(S=!0,I=re(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),g=[1,r[0],r[1],r[2],r[3]]);const T=g[4],C=I.shape[4];J(g.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${g.length}.`),J(I.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${I.rank}`),J(u.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${u.rank}`),J(T===u.shape[3],()=>`Error in conv3dDerInput: depth of input (${T}) must match input depth for filter ${u.shape[3]}.`),J(C===u.shape[4],()=>`Error in conv3dDerInput: depth of output (${C}) must match output depth for filter ${u.shape[4]}.`);const D=ne=>{const te=1,P=Yu(g,u.shape,p,te,y);return ne.conv3dDerInput(I,u,P)},_={dy:I,filter:u},A={pad:y,strides:p,inputShape:g},B=H.runKernelFunc(D,_,null,CR,A);return S?re(B,[B.shape[1],B.shape[2],B.shape[3],B.shape[4]]):B}const c1=V({conv3DBackpropInput_:uZ});function dZ(r){const l=M(r,"x","cos"),u={x:l};return H.runKernelFunc((p,y)=>{const g=p.cos(l);return y([l]),g},u,null,zf)}const Hu=V({cos_:dZ});function pZ(r){const l=M(r,"x","cosh"),u={x:l};return H.runKernelFunc((p,y)=>{const g=p.cosh(l);return y([l]),g},u,null,Vf)}const jI=V({cosh_:pZ});function mZ(r,l=0,u=!1,p=!1){const y=M(r,"x","cumsum"),g=(T,C)=>{const D=Gi([l],y.rank);let _=y;D!=null&&(_=xn(y,D));const A=fo(1,y.rank)[0];let B=T.cumsum(_,A,u,p);if(C([y]),D!=null){const ne=Xc(D);B=xn(B,ne)}return B},I={x:y},S={axis:l,exclusive:u,reverse:p};return H.runKernelFunc(g,I,null,Gf,S)}const KI=V({cumsum_:mZ});function Dt(r,l){const u=[];for(let p=0;p<l.length;p++){const y=r[r.length-p-1],g=l.length-p-1,I=l[g];(y==null||y===1&&I>1)&&u.unshift(g)}return u}function ot(r,l){const u=[],p=Math.max(r.length,l.length);for(let y=0;y<p;y++){let g=r[r.length-y-1];g==null&&(g=1);let I=l[l.length-y-1];if(I==null&&(I=1),g===1)u.unshift(I);else if(I===1)u.unshift(g);else if(g!==I){const S=`Operands could not be broadcast together with shapes ${r} and ${l}.`;throw Error(S)}else u.unshift(g)}return u}function fZ(r,l){let u=M(r,"a","equal"),p=M(l,"b","equal");[u,p]=St(u,p),ot(u.shape,p.shape);const y=I=>I.equal(u,p),g={a:u,b:p};return H.runKernelFunc(y,g,null,BR)}const XI=V({equal_:fZ});function gZ(r,l,u){const p=M(l,"a","where"),y=M(u,"b","where"),g=M(r,"condition","where","bool"),I=ot(p.shape,y.shape),S=Pg(p,I),T=Pg(y,I);g.rank===1&&J(g.shape[0]===p.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),g.rank!==1&&tn(g.shape,T.shape,"Error in where: ");const C=(_,A)=>{const B=_.select(g,S,T);return A([g]),B},D={condition:g,t:S,e:T};return H.runKernelFunc(C,D,null,mg)}const Gn=V({where_:gZ});function yZ(r){const l=M(r,"x","zerosLike"),u={x:l};return H.runKernelFunc(p=>p.zerosLike(l),u,null,Rg)}const Xe=V({zerosLike_:yZ});function bZ(r){const l=M(r,"x","exp"),u={x:l};return H.runKernelFunc((p,y)=>{const g=p.exp(l);return y([g]),g},u,null,Hf)}const Yn=V({exp_:bZ});function wZ(r,l=0){const u=null,p=M(r,"x","expandDims",u);J(l<=p.rank,()=>"Axis must be <= rank of the tensor");const y=p.shape.slice();return l<0&&(J(-(p.rank+1)<=l,()=>`Axis must be in the interval [${-(p.rank+1)}, ${p.rank}]`),l=p.rank+l+1),y.splice(l,0,1),re(p,y)}const ks=V({expandDims_:wZ});function LZ(r,l){const u=null,p=M(r,"x","tile",u);J(p.rank===l.length,()=>`Error in transpose: rank of input ${p.rank} must match length of reps ${l}.`);const y=(T,C)=>{const D=T.tile(p,l);return C([p]),D},g=[p],I={x:p},S={reps:l};return H.runKernelFunc(y,I,null,Ag,S,g)}const fa=V({tile_:LZ});function SZ(r,l,u,p="float32"){l==null&&(l=r);const y=Gu([r,l],p),g=r<=l?r:l;for(let S=0;S<g;++S)y.set(1,S,S);const I=re(y.toTensor(),[r,l]);if(u==null)return I;if(u.length===1)return fa(ks(I,0),[u[0],1,1]);if(u.length===2)return fa(ks(ks(I,0),0),[u[0],u[1],1,1]);if(u.length===3)return fa(ks(ks(ks(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 JI=V({eye_:SZ});function ZI(r,l,u){const p={shape:r,value:l,dtype:u};return H.runKernelFunc(y=>y.fill(r,l,u),{},null,zR,p)}function IZ(r){const l=M(r,"x","floor"),u={x:l};return H.runKernelFunc(p=>p.floor(l),u,null,qf)}const QI=V({floor_:IZ});function l1(r,l,u){const p=r.shape[u],y=[];let g=1,I=1;for(let S=0;S<u;S++)y.push(r.shape[S]),g*=r.shape[S];for(let S=0;S<l.rank;S++)y.push(l.shape[S]);for(let S=u+1;S<r.rank;S++)y.push(r.shape[S]),I*=r.shape[S];return{batchSize:g,sliceSize:I,dimSize:p,outputShape:y}}function xZ(r,l,u=0){const p=M(r,"x","gather"),y=M(l,"indices","gather","int32"),g={x:p,indices:y},I={axis:u},S=(T,C)=>{const D=gt(u,p.shape)[0],_=l1(p,y,D),A=T.gather(p,re(y,[y.size]),D);return C([p,y]),re(A,_.outputShape)};return H.runKernelFunc(S,g,null,Kf,I)}const ex=V({gather_:xZ});function TZ(r,l){let u=M(r,"a","greater"),p=M(l,"b","greater");[u,p]=St(u,p),ot(u.shape,p.shape);const y=I=>I.greater(u,p),g={a:u,b:p};return H.runKernelFunc(y,g,null,YR)}const bi=V({greater_:TZ});function AZ(r,l){let u=M(r,"a","greaterEqual"),p=M(l,"b","greaterEqual");[u,p]=St(u,p),ot(u.shape,p.shape);const y=(I,S)=>{const T=I.greaterEqual(u,p);return S([u,p]),T},g={a:u,b:p};return H.runKernelFunc(y,g,null,Xf)}const Ir=V({greaterEqual_:AZ});function vZ(r){const l=M(r,"input","imag"),u=y=>y.imag(l),p={input:l};return H.runKernelFunc(u,p,null,qR)}const qu=V({imag_:vZ});function NZ(r,l){let u=M(r,"a","maximum"),p=M(l,"b","maximum");[u,p]=St(u,p),u.dtype==="bool"&&(u=Ie(u,"int32"),p=Ie(p,"int32")),ot(u.shape,p.shape);const y=(I,S)=>{const T=I.maximum(u,p);return S([u,p]),T},g={a:u,b:p};return H.runKernelFunc(y,g,null,tg)}const tx=V({maximum_:NZ});function Fe(r,l){if((Es(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"&&Es(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 CZ(r,l){let u=M(r,"a","less"),p=M(l,"b","less");[u,p]=St(u,p),ot(u.shape,p.shape);const y=I=>I.less(u,p),g={a:u,b:p};return H.runKernelFunc(y,g,null,JR)}const nx=V({less_:CZ});function RZ(r,l){let u=M(r,"a","lessEqual"),p=M(l,"b","lessEqual");[u,p]=St(u,p),ot(u.shape,p.shape);const y=(I,S)=>{const T=I.lessEqual(u,p);return S([u,p]),T},g={a:u,b:p};return H.runKernelFunc(y,g,null,ZR)}const xr=V({lessEqual_:RZ});function OZ(r){const l=M(r,"x","log"),u={x:l};return H.runKernelFunc((p,y)=>{const g=p.log(l);return y([l]),g},u,null,Zf)}const bo=V({log_:OZ});function EZ(r){const l=M(r,"x","log1p"),u={x:l};return H.runKernelFunc((p,y)=>{const g=p.log1p(l);return y([l]),g},u,null,Qf)}const sx=V({log1p_:EZ});function zg(r){return H.customGrad(r)}function DZ(r){const l=M(r,"x","neg"),u={x:l};return H.runKernelFunc(p=>p.neg(l),u,null,rg)}const It=V({neg_:DZ});function kZ(r,l=null,u=!1){const p=M(r,"x","max"),y=(S,T)=>{const C=gt(l,p.shape);let D=C;const _=Gi(D,p.rank);let A=p;_!=null&&(A=xn(p,_),D=fo(D.length,A.rank));const B=S.max(A,D);_!=null&&A.dispose();let ne=B;if(u){const te=os(ne.shape,gt(l,p.shape));ne=re(ne,te),B.dispose()}return T([p,ne]),ne},g={x:p},I={reductionIndices:l,keepDims:u};return H.runKernelFunc(y,g,null,eg,I)}const ga=V({max_:kZ});function FZ(r,l){let u=M(r,"a","sub"),p=M(l,"b","sub");[u,p]=St(u,p);const y=(I,S)=>{const T=I.subtract(u,p);return S([u,p]),T},g={a:u,b:p};return H.runKernelFunc(y,g,null,Tg)}const Be=V({sub_:FZ});function _Z(r,l=null,u=!1){let p=M(r,"x","sum");p.dtype==="bool"&&(p=Ie(p,"int32"));const y=(S,T)=>{T([p]);const C=gt(l,p.shape),D=Gi(C,p.rank);let _=C,A=p;D!=null&&(A=xn(p,D),_=fo(_.length,p.rank));let B=S.sum(A,_);if(u){const ne=os(B.shape,C);B=re(B,ne)}return B},g={x:p},I={axis:l,keepDims:u};return H.runKernelFunc(y,g,null,Lg,I)}const _e=V({sum_:_Z});function WZ(r,l=null,u=!1){const p=M(r,"x","logSumExp"),y=gt(l,p.shape),g=ga(p,y,!0),I=Be(p,g),S=Yn(I),T=_e(S,y),C=bo(T),D=vt(re(g,C.shape),C);if(u){const _=os(D.shape,y);return re(D,_)}return D}const ix=V({logSumExp_:WZ});function $Z(r,l){const u=M(r,"a","logicalAnd","bool"),p=M(l,"b","logicalAnd","bool");ot(u.shape,p.shape);const y={a:u,b:p};return H.runKernelFunc(g=>g.logicalAnd(u,p),y,null,QR)}const ya=V({logicalAnd_:$Z});function UZ(r){const l=M(r,"x","logicalNot","bool"),u={x:l};return H.runKernelFunc(p=>p.logicalNot(l),u,null,eO)}const rx=V({logicalNot_:UZ});function Fs(r,l="float32"){if(l==="complex64"){const p=Fs(r,"float32"),y=Fs(r,"float32");return zi(p,y)}const u=pa(Zt(r),l);return H.makeTensor(u,r,l)}function Yi(r,l="float32"){if(l==="complex64"){const p=Yi(r,"float32"),y=Fs(r,"float32");return zi(p,y)}const u=Df(Zt(r),l);return H.makeTensor(u,r,l)}function BZ(r,l=null,u=!1){const p=M(r,"x","mean"),y=gt(l,p.shape),g=s1(p.shape,y),I=g[1],S=Zt(I),T={x:p},C={axis:l,keepDims:u},D=()=>{const A=Fe(S),B=A.dtype===p.dtype?p:Ie(p,A.dtype),ne=Me(B,A);return _e(ne,l,u)},_=zg(A=>{const B=H.runKernelFunc(D,T,null,cO,C),ne=te=>{const P=A.shape.slice();y.forEach(Le=>{P[Le]=1});const ge=re(te,P),ae=Me(le(ge,Yi(A.shape,"float32")),S);return ae};return{value:B,gradFunc:ne}});return _(p)}const ox=V({mean_:BZ});function MZ(r,l=null,u=!1){const p=M(r,"x","min"),y=(S,T)=>{const C=gt(l,p.shape);let D=C;const _=Gi(D,p.rank);let A=p;_!=null&&(A=xn(p,_),D=fo(D.length,p.rank));const B=S.min(A,D);_!=null&&A.dispose();let ne=B;if(u){const te=os(ne.shape,C);ne=re(B,te),B.dispose()}return T([p,ne]),ne},g={x:p},I={axis:l,keepDims:u};return H.runKernelFunc(y,g,null,ng,I)}const Vg=V({min_:MZ});function PZ(r,l){let u=M(r,"a","minimum"),p=M(l,"b","minimum");[u,p]=St(u,p),u.dtype==="bool"&&(u=Ie(u,"int32"),p=Ie(p,"int32")),ot(u.shape,p.shape);const y=(I,S)=>{const T=I.minimum(u,p);return S([u,p]),T},g={a:u,b:p};return H.runKernelFunc(y,g,null,sg)}const ax=V({minimum_:PZ});function zZ(r){const l=M(r,"x","square"),u={},p=[l],y=[];return H.runKernelFunc((g,I)=>(I([l]),g.square(l)),{x:l},null,"Square",u,p,y)}const yt=V({square_:zZ});function VZ(r,l){let u=M(r,"a","notEqual"),p=M(l,"b","notEqual");[u,p]=St(u,p),ot(u.shape,p.shape);const y=I=>I.notEqual(u,p),g={a:u,b:p};return H.runKernelFunc(y,g,null,uO)}const cx=V({notEqual_:VZ});function GZ(r){const l=M(r,"input","real"),u=y=>y.real(l),p={input:l};return H.runKernelFunc(u,p,null,wO)}const Qc=V({real_:GZ});function YZ(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 y=(S,T)=>(T([p]),S.pad(p,l,u)),g={paddings:l,constantValue:u},I={x:p};return H.runKernelFunc(y,I,null,og,g)}const lx=V({pad_:YZ});function HZ(r,l,u){const p=M(r,"x","spaceToBatchND");J(p.rank>=1+l.length,()=>`input rank ${p.rank} should be > than [blockShape] ${l.length}`),J(u.length===l.length,()=>`paddings.shape[0] ${u.length} must be equal to [blockShape] ${l.length}`),J(p.shape.reduce((S,T,C)=>C>0&&C<=l.length?S&&(T+u[C-1][0]+u[C-1][1])%l[C-1]===0:S,!0),()=>`input spatial dimensions ${p.shape.slice(1)} with paddings ${u.toString()} must be divisible by blockShapes ${l.toString()}`);const y=S=>S.spaceToBatchND(p,l,u),g={x:p},I={blockShape:l,paddings:u};return H.runKernelFunc(y,g,null,Sg,I)}const hx=V({spaceToBatchND_:HZ});function qZ(r,l){let u=M(r,"base","pow"),p=M(l,"exp","pow");[u,p]=St(u,p);const y={a:u,b:p},g=(I,S)=>{const T=I.pow(u,p);return S([u,p,T]),T};return H.runKernelFunc(g,y,null,ag)}const ba=V({pow_:qZ});function wo(r,l){Gc(r);const u=Sr(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 Gg(r,l,u=1,p="float32"){if(u===0)throw new Error("Cannot have a step of zero");const y=()=>{const I=r===l,S=r<l&&u<0,T=l<r&&u>1;if(I||S||T)return Fs([0],p);const C=Math.abs(Math.ceil((l-r)/u)),D=pa(C,p);l<r&&u===1&&(u=-1),D[0]=r;for(let _=1;_<D.length;_++)D[_]=D[_-1]+u;return wo(D,p)},g={start:r,stop:l,step:u,dtype:p};return H.runKernelFunc(y,{},null,bO,g)}function jZ(r){const l=M(r,"x","relu"),u=(y,g)=>(g([l]),l.dtype==="bool"?Ie(l,"int32"):y.relu(l)),p={x:l};return H.runKernelFunc(u,p,null,cg)}const ju=V({relu_:jZ});function KZ(r,l){const u=M(r,"x","reverse"),p=I=>{const S=gt(l,u.shape);if(u.rank===0)return gi(u);const T=I.reverse(u,S);return re(T,u.shape)},y={x:u},g={dims:l};return H.runKernelFunc(p,y,null,dg,g)}const el=V({reverse_:KZ});function XZ(r){const l=M(r,"x","rsqrt"),u={x:l};return H.runKernelFunc((p,y)=>{const g=p.rsqrt(l);return y([l]),g},u,null,pg)}const ux=V({rsqrt_:XZ});function JZ(r){const l=M(r,"x","sin"),u={x:l};return H.runKernelFunc((p,y)=>{const g=p.sin(l);return y([l]),g},u,null,gg)}const dx=V({sin_:JZ});function ZZ(r){const l=M(r,"x","sinh"),u={x:l};return H.runKernelFunc((p,y)=>{const g=p.sinh(l);return y([l]),g},u,null,yg)}const px=V({sinh_:ZZ});function QZ(r){J(r.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${r.dtype}.`);const l={input:r};return H.runKernelFunc(u=>{const p=r.shape[r.shape.length-1],y=r.size/p,g=r.as2D(y,p),I=u.fft(g);return I.reshape(r.shape)},l,null,PR)}const Ku=V({fft_:QZ});function eQ(r){J(r.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${r.dtype}.`);const l={input:r};return H.runKernelFunc(u=>{const p=r.shape[r.shape.length-1],y=r.size/p,g=re(r,[y,p]),I=u.ifft(g);return re(I,r.shape)},l,null,HR)}const tl=V({ifft_:eQ});function tQ(r){const l=r.shape[r.shape.length-1],u=r.size/l;let p;if(l<=2){const y=re(r,[u,l]);p=tl(y)}else{const y=[u,2*(l-1)],g=re(Qc(r),[u,l]),I=re(qu(r),[u,l]),S=el(Tt(g,[0,1],[u,l-2]),1),T=le(el(Tt(I,[0,1],[u,l-2]),1),Fe(-1)),C=Tn([g,S],1),D=Tn([I,T],1),_=re(zi(C,D),[y[0],y[1]]);p=tl(_)}if(p=Qc(p),r.rank===3&&r.shape[0]!==0){const y=p,g=r.shape[0];p=re(p,[g,p.shape[0]/g,p.shape[1]]),y.dispose()}return p}const mx=V({irfft_:tQ});function h1(r,l,u=0){let p=[];if(typeof l=="number")J(r.shape[u]%l===0,()=>"Number of splits must evenly divide the axis."),p=new Array(l).fill(r.shape[u]/l);else{const y=l.reduce((I,S)=>(S===-1&&(I+=1),I),0);J(y<=1,()=>"There should be only one negative value in split array.");const g=l.indexOf(-1);if(g!==-1){const I=l.reduce((S,T)=>T>0?S+T:S);l[g]=r.shape[u]-I}J(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 nQ(r,l,u=0){const p=M(r,"x","split"),y=(S,T)=>{const C=gt(u,p.shape)[0],D=h1(p,l,C);return S.split(p,D,C)},g={x:p},I={numOrSizeSplits:l,axis:u};return H.runKernelFunc(y,g,null,Ig,I)}const Lo=V({split_:nQ});function sQ(r,l){J(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 y;if(l!=null&&l<u){const ne=r.shape.map(P=>0),te=r.shape.map(P=>P);te[r.shape.length-1]=l,y=Tt(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,y=Tn([r,Fs(ne)],r.shape.length-1),u=l}else y=r;const g=Xe(y),I=re(zi(y,g),[p,u]),S=Ku(I),T=Math.floor(u/2)+1,C=Qc(S),D=qu(S),_=Lo(C,[T,u-T],C.shape.length-1),A=Lo(D,[T,u-T],D.shape.length-1),B=y.shape.slice();return B[y.shape.length-1]=T,re(zi(_[0],A[0]),B)}const Xu=V({rfft_:sQ});function iQ(r){const l=M(r,"x","sqrt"),u={x:l};return H.runKernelFunc((p,y)=>{const g=p.sqrt(l);return y([l]),g},u,null,wg)}const fs=V({sqrt_:iQ});function rQ(r,l){let u=M(r,"a","squaredDifference"),p=M(l,"b","squaredDifference");[u,p]=St(u,p),ot(u.shape,p.shape);const y=(S,T)=>{const C=S.squaredDifference(u,p);return T([u,p]),C},g={a:u,b:p},I={};return H.runKernelFunc(y,g,null,xg,I)}const fx=V({squaredDifference_:rQ});function oQ(r,l){const u=M(r,"x","squeeze");return re(u,J2(u.shape,l).newShape)}const gx=V({squeeze_:oQ});function aQ(r,l=0){const u=Wg(r,"tensors","stack");if(J(u.length>=1,()=>"Pass at least one tensor to tf.stack"),u.length===1)return ks(u[0],l);const p=u[0].rank,y=u[0].shape,g=u[0].dtype;J(l<=p,()=>"Axis must be <= rank of the tensor"),u.forEach(S=>{tn(y,S.shape,"All tensors passed to stack must have matching shapes"),J(g===S.dtype,()=>"All tensors passed to stack must have matching dtypes")});const I=u.map(S=>ks(S,l));return Tn(I,l)}const js=V({stack_:aQ});function cQ(r,l=0){const u=M(r,"x","step"),p={x:u},y={alpha:l};return H.runKernelFunc(g=>g.step(u,l),p,null,Og,y)}const wa=V({step_:cQ});function La(r,l,u){if(Gc(r),l!=null&&l.length!==2)throw new Error("tensor2d() requires shape to have two numbers");const p=Sr(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 lQ(r,l,u){const p=M(r,"x","unsortedSegmentSum"),y=M(l,"segmentIds","unsortedSegmentSum","int32");J(nn(u),()=>"numSegments must be of dtype int");const g={x:p,segmentIds:y},I={numSegments:u},S=(T,C)=>{const D=T.unsortedSegmentSum(p,y,u);return C([y]),D};return H.runKernelFunc(S,g,null,Cg,I)}const yx=V({unsortedSegmentSum_:lQ});function hQ(r,l=0){const u=M(r,"x","unstack");J(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},y={axis:l},g=I=>I.unstack(u,l);return H.runKernelFunc(g,p,null,Ng,y)}const Ju=V({unstack_:hQ});function uQ(r,l="euclidean",u=null,p=!1){r=M(r,"x","norm");const y=u1(r,l,u);let g=y.shape;if(p){const I=gt(u,r.shape);g=os(y.shape,I)}return re(y,g)}function u1(r,l,u=null){if(r.rank===0)return Vn(r);if(r.rank!==1&&u===null)return u1(re(r,[-1]),l,u);if(r.rank===1||typeof u=="number"||Array.isArray(u)&&u.length===1){if(l===1)return _e(Vn(r),u);if(l===Infinity)return ga(Vn(r),u);if(l===-Infinity)return Vg(Vn(r),u);if(l==="euclidean"||l===2)return fs(_e(ba(Vn(r),Fe(2,"int32")),u));throw new Error(`Error in norm: invalid ord value: ${l}`)}if(Array.isArray(u)&&u.length===2){if(l===1)return ga(_e(Vn(r),u[0]),u[1]-1);if(l===Infinity)return ga(_e(Vn(r),u[1]),u[0]);if(l===-Infinity)return Vg(_e(Vn(r),u[1]),u[0]);if(l==="fro"||l==="euclidean")return fs(_e(yt(r),u));throw new Error(`Error in norm: invalid ord value: ${l}`)}throw new Error(`Error in norm: invalid axis: ${u}`)}const Yg=V({norm_:uQ});function d1(r){return Math.floor(Math.pow(2,Math.ceil(Math.log(r)/Math.log(2))))}function Hg(r,l,u){const p=1-r%2,y=new Float32Array(r);for(let g=0;g<r;++g){const I=2*Math.PI*g/(r+p-1);y[g]=l-u*Math.cos(I)}return wo(y,"float32")}function dQ(r,l,u,p,y,g="NHWC",I){let S=r;r.rank===3&&(S=re(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let T=l;T.rank===3&&(T=re(l,[1,l.shape[0],l.shape[1],l.shape[2]])),J(S.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${S.shape}.`),J(T.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${T.shape}.`),J(u.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${u}.`);const C=g==="NHWC"?S.shape[3]:S.shape[1],D=g==="NHWC"?T.shape[3]:T.shape[1];J(C===u[2],()=>`Error in conv2dDerFilter: depth of input ${C}) must match input depth in filter (${u[2]}.`),J(D===u[3],()=>`Error in conv2dDerFilter: depth of dy (${D}) must match output depth for filter (${u[3]}).`),I!=null&&J(nn(y),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${I} but got pad ${y}.`);const _=ne=>{const te=1,P=Zc(g),ge=yi(S.shape,u,p,te,y,I,!1,P);return ne.conv2dDerFilter(S,T,ge)},A={x:S,dy:T},B={strides:p,pad:y,dataFormat:g,dimRoundingMode:I,filterShape:u};return H.runKernelFunc(_,A,null,AR,B)}const qg=V({conv2DBackpropFilter_:dQ});function pQ(r,l,u,p,y,g=[1,1],I){let S=r;r.rank===3&&(S=re(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let T=l;T.rank===3&&(T=re(l,[1,l.shape[0],l.shape[1],l.shape[2]]));const C=A=>{const B=yi(r.shape,u,p,g,y,I,!0);return A.depthwiseConv2DDerFilter(S,T,B)},D={x:S,dy:T},_={strides:p,pad:y,dimRoundingMode:I,dilations:g,filterShape:u};return H.runKernelFunc(C,D,null,ER,_)}const p1=V({depthwiseConv2dNativeBackpropFilter_:pQ});function mQ(r,l,u,p,y,g=[1,1],I){let S=l,T=!1;l.rank===3&&(T=!0,S=re(l,[1,l.shape[0],l.shape[1],l.shape[2]]));const C=B=>{const ne=yi(r,u.shape,p,g,y,I,!0);return B.depthwiseConv2DDerInput(S,u,ne)},D={dy:S,filter:u},_={strides:p,pad:y,dimRoundingMode:I,dilations:g,inputShape:r},A=H.runKernelFunc(C,D,null,DR,_);return T?re(A,[A.shape[1],A.shape[2],A.shape[3]]):A}const m1=V({depthwiseConv2dNativeBackpropInput_:mQ});function fQ(r){return Hg(r,.54,.46)}const f1=V({hammingWindow_:fQ});function gQ(r){return Hg(r,.5,.5)}const jg=V({hannWindow_:gQ});function yQ(r,l,u,p=!1,y=0){let g=0;const I=[];for(;g+l<=r.size;)I.push(Tt(r,g,l)),g+=u;if(p)for(;g<r.size;){const S=g+l-r.size,T=Tn([Tt(r,g,l-S),ZI([S],y)]);I.push(T),g+=u}return I.length===0?La([],[0,l]):re(Tn(I),[I.length,l])}const Kg=V({frame_:yQ});function bQ(r,l,u,p,y=jg){p==null&&(p=d1(l));const g=Kg(r,l,u),I=le(g,y(l)),S=[];for(let T=0;T<g.shape[0];T++)S.push(Xu(Tt(I,[T,0],[1,l]),p));return Tn(S)}const g1=V({stft_:bQ});function wQ(r,l,u,p,y,g){const I=M(r,"image","cropAndResize"),S=M(l,"boxes","cropAndResize","float32"),T=M(u,"boxInd","cropAndResize","int32");y=y||"bilinear",g=g||0;const C=S.shape[0];J(I.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${I.rank}.`),J(S.rank===2&&S.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${C},4] but had shape ${S.shape}.`),J(T.rank===1&&T.shape[0]===C,()=>`Error in cropAndResize: boxInd must be have size [${C}] but had shape ${S.shape}.`),J(p.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${p.length}.`),J(p[0]>=1&&p[1]>=1,()=>`cropSize must be atleast [1,1], but was ${p}`),J(y==="bilinear"||y==="nearest",()=>`method must be bilinear or nearest, but was ${y}`);const D=ne=>ne.cropAndResize(I,S,T,p,y,g),_={image:I,boxes:S,boxInd:T},A={method:y,extrapolationValue:g,cropSize:p},B=H.runKernelFunc(D,_,null,RR,A);return B}const y1=V({cropAndResize_:wQ});function LQ(r){const l=M(r,"image","flipLeftRight","float32");J(l.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${l.rank}.`);const u={image:l},p=H.runKernel(VR,u,{});return p}const b1=V({flipLeftRight_:LQ});function SQ(r,l,u=0,p=.5){const y=M(r,"image","rotateWithOffset","float32");J(y.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${y.rank}.`);const g={image:y},I={radians:l,fillValue:u,center:p},S=H.runKernel(DO,g,I);return S}const w1=V({rotateWithOffset_:SQ});function Ks(r,l,u,p,y,g){p==null&&(p=.5),y==null&&(y=Number.NEGATIVE_INFINITY),g==null&&(g=0);const I=r.shape[0];return u=Math.min(u,I),J(0<=p&&p<=1,()=>`iouThreshold must be in [0, 1], but was '${p}'`),J(r.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${r.rank}'`),J(r.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${r.shape[1]}`),J(l.rank===1,()=>"scores must be a 1D tensor"),J(l.shape[0]===I,()=>`scores has incompatible shape with boxes. Expected ${I}, but was ${l.shape[0]}`),J(0<=g&&g<=1,()=>`softNmsSigma must be in [0, 1], but was '${g}'`),{maxOutputSize:u,iouThreshold:p,scoreThreshold:y,softNmsSigma:g}}function IQ(r,l,u,p=.5,y=Number.NEGATIVE_INFINITY){const g=M(r,"boxes","nonMaxSuppression"),I=M(l,"scores","nonMaxSuppression"),S=Ks(g,I,u,p,y);u=S.maxOutputSize,p=S.iouThreshold,y=S.scoreThreshold;const T={maxOutputSize:u,iouThreshold:p,scoreThreshold:y};return H.runKernelFunc(C=>C.nonMaxSuppression(g,I,u,p,y),{boxes:g,scores:I},null,dO,T)}const L1=V({nonMaxSuppression_:IQ});function S1(r,l,u){const p=xQ(r,l,u),y=p<0?-(p+1):p;r.splice(y,0,l)}function xQ(r,l,u){return AQ(r,l,u||TQ)}function TQ(r,l){return r>l?1:r<l?-1:0}function AQ(r,l,u){let p=0,y=r.length,g=0,I=!1;for(;p<y;){g=p+(y-p>>>1);const S=u(l,r[g]);S>0?p=g+1:(y=g,I=!S)}return I?p:-p-1}function I1(r,l,u,p,y){return bx(r,l,u,p,y,0).selectedIndices}function x1(r,l,u,p,y,g){return bx(r,l,u,p,y,0,!1,g,!0)}function T1(r,l,u,p,y,g){return bx(r,l,u,p,y,g,!0)}function bx(r,l,u,p,y,g,I=!1,S=!1,T=!1){const C=[];for(let P=0;P<l.length;P++)l[P]>y&&C.push({score:l[P],boxIndex:P,suppressBeginIndex:0});C.sort(A1);const D=g>0?-.5/g:0,_=[],A=[];for(;_.length<u&&C.length>0;){const P=C.pop(),{score:ge,boxIndex:ae,suppressBeginIndex:Le}=P;if(ge<y)break;let ve=!1;for(let Ve=_.length-1;Ve>=Le;--Ve){const at=vQ(r,ae,_[Ve]);if(at>=p){ve=!0;break}if(P.score=P.score*NQ(p,D,at),P.score<=y)break}P.suppressBeginIndex=_.length,ve||(P.score===ge?(_.push(ae),A.push(P.score)):P.score>y&&S1(C,P,A1))}const B=_.length,ne=u-B;S&&ne>0&&(_.push(...new Array(ne).fill(0)),A.push(...new Array(ne).fill(0)));const te={selectedIndices:wo(_,"int32")};return I&&(te.selectedScores=wo(A,"float32")),T&&(te.validOutputs=Fe(B,"int32")),te}function vQ(r,l,u){const p=r.subarray(l*4,l*4+4),y=r.subarray(u*4,u*4+4),g=Math.min(p[0],p[2]),I=Math.min(p[1],p[3]),S=Math.max(p[0],p[2]),T=Math.max(p[1],p[3]),C=Math.min(y[0],y[2]),D=Math.min(y[1],y[3]),_=Math.max(y[0],y[2]),A=Math.max(y[1],y[3]),B=(S-g)*(T-I),ne=(_-C)*(A-D);if(B<=0||ne<=0)return 0;const te=Math.max(g,C),P=Math.max(I,D),ge=Math.min(S,_),ae=Math.min(T,A),Le=Math.max(ge-te,0)*Math.max(ae-P,0);return Le/(B+ne-Le)}function NQ(r,l,u){const p=Math.exp(l*u*u);return u<=r?p:0}function A1(r,l){return r.score-l.score||r.score===l.score&&l.boxIndex-r.boxIndex}async function CQ(r,l,u,p=.5,y=Number.NEGATIVE_INFINITY){const g=M(r,"boxes","nonMaxSuppressionAsync"),I=M(l,"scores","nonMaxSuppressionAsync"),S=Ks(g,I,u,p,y);u=S.maxOutputSize,p=S.iouThreshold,y=S.scoreThreshold;const T=await Promise.all([g.data(),I.data()]),C=T[0],D=T[1],_=I1(C,D,u,p,y);return g!==r&&g.dispose(),I!==l&&I.dispose(),_}const v1=CQ;function RQ(r,l,u,p=.5,y=Number.NEGATIVE_INFINITY,g=0){const I=M(r,"boxes","nonMaxSuppression"),S=M(l,"scores","nonMaxSuppression"),T=Ks(I,S,u,p,y,g);u=T.maxOutputSize,p=T.iouThreshold,y=T.scoreThreshold,g=T.softNmsSigma;const C={boxes:I,scores:S},D={maxOutputSize:u,iouThreshold:p,scoreThreshold:y,softNmsSigma:g},_=H.runKernel(mO,C,D);return{selectedIndices:_[0],selectedScores:_[1]}}const N1=V({nonMaxSuppressionWithScore_:RQ});async function OQ(r,l,u,p=.5,y=Number.NEGATIVE_INFINITY,g=0){const I=M(r,"boxes","nonMaxSuppressionAsync"),S=M(l,"scores","nonMaxSuppressionAsync"),T=Ks(I,S,u,p,y,g);u=T.maxOutputSize,p=T.iouThreshold,y=T.scoreThreshold,g=T.softNmsSigma;const C=await Promise.all([I.data(),S.data()]),D=C[0],_=C[1],A=T1(D,_,u,p,y,g);return I!==r&&I.dispose(),S!==l&&S.dispose(),A}const C1=OQ;function EQ(r,l,u,p=.5,y=Number.NEGATIVE_INFINITY,g=!1){const I=M(r,"boxes","nonMaxSuppression"),S=M(l,"scores","nonMaxSuppression"),T=Ks(I,S,u,p,y,null),C=T.maxOutputSize,D=T.iouThreshold,_=T.scoreThreshold,A={boxes:I,scores:S},B={maxOutputSize:C,iouThreshold:D,scoreThreshold:_,padToMaxOutputSize:g},ne=H.runKernel(pO,A,B);return{selectedIndices:ne[0],validOutputs:ne[1]}}const R1=V({nonMaxSuppressionPadded_:EQ});async function DQ(r,l,u,p=.5,y=Number.NEGATIVE_INFINITY,g=!1){const I=M(r,"boxes","nonMaxSuppressionAsync"),S=M(l,"scores","nonMaxSuppressionAsync"),T=Ks(I,S,u,p,y,null),C=T.maxOutputSize,D=T.iouThreshold,_=T.scoreThreshold,[A,B]=await Promise.all([I.data(),S.data()]),ne=x1(A,B,C,D,_,g);return I!==r&&I.dispose(),S!==l&&S.dispose(),ne}const O1=DQ;function kQ(r,l,u=!1){const p=M(r,"images","resizeBilinear");J(p.rank===3||p.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${p.rank}.`),J(l.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${l}.`);let y=p,g=!1;p.rank===3&&(g=!0,y=re(p,[1,p.shape[0],p.shape[1],p.shape[2]]));const[I,S]=l,T=(A,B)=>(B([y]),A.resizeBilinear(y,I,S,u)),C={images:y},D={alignCorners:u,size:l},_=H.runKernelFunc(T,C,null,ug,D);return g?re(_,[_.shape[1],_.shape[2],_.shape[3]]):_}const E1=V({resizeBilinear_:kQ});function FQ(r,l,u=!1){const p=M(r,"images","resizeNearestNeighbor");J(p.rank===3||p.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${p.rank}.`),J(l.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${l}.`),J(p.dtype==="float32"||p.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype");let y=p,g=!1;p.rank===3&&(g=!0,y=re(p,[1,p.shape[0],p.shape[1],p.shape[2]]));const[I,S]=l,T={images:y},C={alignCorners:u,size:l},D=(A,B)=>(B([y]),A.resizeNearestNeighbor(y,I,S,u)),_=H.runKernelFunc(D,T,null,hg,C);return g?re(_,[_.shape[1],_.shape[2],_.shape[3]]):_}const D1=V({resizeNearestNeighbor_:FQ});function _Q(r,l,u){J(l%1===0,()=>`bandPart(): numLower must be an integer, got ${l}.`),J(u%1===0,()=>`bandPart(): numUpper must be an integer, got ${u}.`);const p=M(r,"a","bandPart");J(p.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${p.rank}.`);const y=p.shape,[g,I]=p.shape.slice(-2);if(!(l<=g))throw new Error(`bandPart(): numLower (${l}) must not be greater than the number of rows (${g}).`);if(!(u<=I))throw new Error(`bandPart(): numUpper (${u}) must not be greater than the number of columns (${I}).`);l<0&&(l=g),u<0&&(u=I);const S=re(Gg(0,g,1,"int32"),[-1,1]),T=Gg(0,I,1,"int32"),C=Be(S,T),D=ya(xr(C,Fe(+l,"int32")),Ir(C,Fe(-u,"int32"))),_=Fs([g,I],p.dtype);return re(js(Ju(re(p,[-1,g,I])).map(A=>Gn(D,A,_))),y)}const k1=V({bandPart_:_Q});function WQ(r){let l;if(Array.isArray(r)){l=!1,J(r!=null&&r.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");const y=r[0].shape[0];for(let g=1;g<r.length;++g)J(r[g].shape[0]===y,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${r[g].shape[0]} vs. ${y})`)}else l=!0,r=Lo(r,r.shape[0],0).map(y=>gx(y,[0]));J(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 y=0;y<r.length;++y)u.push(H.tidy(()=>{let g=p[y];if(y>0)for(let I=0;I<y;++I){const S=le(_e(le(u[I],g)),u[I]);g=Be(g,S)}return Me(g,Yg(g,"euclidean"))}));return l?js(u,0):u}const F1=V({gramSchmidt_:WQ});function $Q(r,l=!1){if(J(r.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${r.rank}`),r.rank===2)return _1(r,l);{const u=r.shape.slice(0,r.shape.length-2).reduce((T,C)=>T*C),p=Ju(re(r,[u,r.shape[r.shape.length-2],r.shape[r.shape.length-1]]),0),y=[],g=[];p.forEach(T=>{const[C,D]=_1(T,l);y.push(C),g.push(D)});const I=re(js(y,0),r.shape),S=re(js(g,0),r.shape);return[I,S]}}function _1(r,l=!1){return H.tidy(()=>{J(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 y=JI(u),g=gi(r);const I=La([[1]],[1,1]);let S=gi(I);const T=u>=p?p:u;for(let C=0;C<T;++C){const D=g,_=S,A=y;[S,g,y]=H.tidy(()=>{const B=Tt(g,[C,C],[u-C,1]),ne=Yg(B),te=Tt(g,[C,C],[1,1]),P=Gn(bi(te,0),La([[-1]]),La([[1]])),ge=Be(te,le(P,ne)),ae=Me(B,ge);ae.shape[0]===1?S=gi(I):S=Tn([I,Tt(ae,[1,0],[ae.shape[0]-1,ae.shape[1]])],0);const Le=It(Me(yn(P,ge),ne)),ve=Tt(g,[C,0],[u-C,p]),Ve=le(Le,S),at=xn(S);if(C===0)g=Be(ve,yn(Ve,yn(at,ve)));else{const Gt=Be(ve,yn(Ve,yn(at,ve)));g=Tn([Tt(g,[0,0],[C,p]),Gt],0)}const pt=xn(Ve),$t=Tt(y,[0,C],[u,y.shape[1]-C]);if(C===0)y=Be($t,yn(yn($t,S),pt));else{const Gt=Be($t,yn(yn($t,S),pt));y=Tn([Tt(y,[0,0],[u,C]),Gt],1)}return[S,g,y]}),n1([D,_,A])}return!l&&u>p&&(y=Tt(y,[0,0],[u,p]),g=Tt(g,[0,0],[p,p])),[y,g]})}const W1=V({qr_:$Q});var Qt;(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"})(Qt||(Qt={}));function UQ(r,l,u=Qt.SUM_BY_NONZERO_WEIGHTS){const p=M(r,"losses","computeWeightedLoss");let y=null;l!=null&&(y=M(l,"weights","computeWeightedLoss"));const g=y==null?p:le(p,y);if(u===Qt.NONE)return g;if(u===Qt.SUM)return _e(g);if(u===Qt.MEAN){if(y==null)return ox(g);{const I=p.size/y.size,S=Me(_e(g),_e(y));return I>1?Me(S,Fe(I)):S}}if(u===Qt.SUM_BY_NONZERO_WEIGHTS){if(y==null)return Me(_e(g),Fe(p.size));{const I=le(y,Yi(p.shape)),S=Ie(_e(cx(I,Fe(0))),"float32");return Me(_e(g),S)}}throw Error(`Unknown reduction: ${u}`)}const kn=V({computeWeightedLoss_:UQ});function BQ(r,l,u,p=Qt.SUM_BY_NONZERO_WEIGHTS){const y=M(r,"labels","absoluteDifference"),g=M(l,"predictions","absoluteDifference");let I=null;u!=null&&(I=M(u,"weights","absoluteDifference")),tn(y.shape,g.shape,"Error in absoluteDifference: ");const S=Vn(Be(y,g));return kn(S,I,p)}const $1=V({absoluteDifference_:BQ});function MQ(r,l,u,p,y=Qt.SUM_BY_NONZERO_WEIGHTS){const g=M(r,"labels","cosineDistance"),I=M(l,"predictions","cosineDistance");let S=null;p!=null&&(S=M(p,"weights","cosineDistance")),tn(g.shape,I.shape,"Error in cosineDistance: ");const T=Fe(1),C=Be(T,_e(le(g,I),u,!0));return kn(C,S,y)}const U1=V({cosineDistance_:MQ});function PQ(r,l,u,p=Qt.SUM_BY_NONZERO_WEIGHTS){let y=M(r,"labels","hingeLoss");const g=M(l,"predictions","hingeLoss");let I=null;u!=null&&(I=M(u,"weights","hingeLoss")),tn(y.shape,g.shape,"Error in hingeLoss: ");const S=Fe(1);y=Be(le(Fe(2),y),S);const T=ju(Be(S,le(y,g)));return kn(T,I,p)}const B1=V({hingeLoss_:PQ});function zQ(r,l,u,p=1,y=Qt.SUM_BY_NONZERO_WEIGHTS){const g=M(r,"labels","huberLoss"),I=M(l,"predictions","huberLoss");let S=null;u!=null&&(S=M(u,"weights","huberLoss")),tn(g.shape,I.shape,"Error in huberLoss: ");const T=Fe(p),C=Vn(Be(I,g)),D=ax(C,T),_=Be(C,D),A=vt(le(Fe(.5),yt(D)),le(T,_));return kn(A,S,y)}const M1=V({huberLoss_:zQ});function VQ(r,l,u,p=1e-7,y=Qt.SUM_BY_NONZERO_WEIGHTS){const g=M(r,"labels","logLoss"),I=M(l,"predictions","logLoss");let S=null;u!=null&&(S=M(u,"weights","logLoss")),tn(g.shape,I.shape,"Error in logLoss: ");const T=Fe(1),C=Fe(p),D=It(le(g,bo(vt(I,C)))),_=le(Be(T,g),bo(vt(Be(T,I),C))),A=Be(D,_);return kn(A,S,y)}const P1=V({logLoss_:VQ});function GQ(r,l,u,p=Qt.SUM_BY_NONZERO_WEIGHTS){const y=M(r,"labels","meanSquaredError"),g=M(l,"predictions","meanSquaredError");let I=null;u!=null&&(I=M(u,"weights","meanSquaredError")),tn(y.shape,g.shape,"Error in meanSquaredError: ");const S=fx(y,g);return kn(S,I,p)}const z1=V({meanSquaredError_:GQ});function YQ(r,l){const u=M(r,"labels","sigmoidCrossEntropyWithLogits"),p=M(l,"logits","sigmoidCrossEntropyWithLogits");tn(u.shape,p.shape,"Error in sigmoidCrossEntropyWithLogits: ");const y=ju(p),g=le(p,u),I=sx(Yn(It(Vn(p))));return vt(Be(y,g),I)}function HQ(r,l,u,p=0,y=Qt.SUM_BY_NONZERO_WEIGHTS){let g=M(r,"multiClassLabels","sigmoidCrossEntropy");const I=M(l,"logits","sigmoidCrossEntropy");let S=null;if(u!=null&&(S=M(u,"weights","sigmoidCrossEntropy")),tn(g.shape,I.shape,"Error in sigmoidCrossEntropy: "),p>0){const C=Fe(p),D=Fe(1),_=Fe(.5);g=vt(le(g,Be(D,C)),le(_,C))}const T=YQ(g,I);return kn(T,S,y)}const V1=V({sigmoidCrossEntropy_:HQ});function qQ(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=zg((y,g,I)=>{const S=!0,T=ix(g,[u],S),C=Be(Ie(g,"float32"),T);I([y,C]);const D=It(le(C,y)),_=_e(D,[u]),A=(B,ne)=>{const[te,P]=ne,ge=os(B.shape,[u]);return[le(re(B,ge),Be(Ie(te,"float32"),Yn(P))),le(re(B,ge),Be(Yn(P),Ie(te,"float32")))]};return{value:_,gradFunc:A}});return p(r,l)}function jQ(r,l,u,p=0,y=Qt.SUM_BY_NONZERO_WEIGHTS){let g=M(r,"onehotLabels","softmaxCrossEntropy");const I=M(l,"logits","softmaxCrossEntropy");let S=null;if(u!=null&&(S=M(u,"weights","softmaxCrossEntropy")),tn(g.shape,I.shape,"Error in softmaxCrossEntropy: "),p>0){const C=Fe(p),D=Fe(1),_=Fe(g.shape[1]);g=vt(le(g,Be(D,C)),Me(C,_))}const T=qQ(g,I);return kn(T,S,y)}const G1=V({softmaxCrossEntropy_:jQ});const Vve={fft:Ku,ifft:tl,rfft:Xu,irfft:mx},jve={hammingWindow:f1,hannWindow:jg,frame:Kg,stft:g1},Y1={flipLeftRight:b1,resizeNearestNeighbor:D1,resizeBilinear:E1,rotateWithOffset:w1,cropAndResize:y1,nonMaxSuppression:L1,nonMaxSuppressionAsync:v1,nonMaxSuppressionWithScore:N1,nonMaxSuppressionWithScoreAsync:C1,nonMaxSuppressionPadded:R1,nonMaxSuppressionPaddedAsync:O1},lNe={bandPart:k1,gramSchmidt:F1,qr:W1},wNe={absoluteDifference:$1,computeWeightedLoss:kn,cosineDistance:U1,hingeLoss:B1,huberLoss:M1,logLoss:P1,meanSquaredError:z1,sigmoidCrossEntropy:V1,softmaxCrossEntropy:G1};const H1=1.7580993408473768,q1=1.0507009873554805;const j1={kernelName:_f,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(r,wa(Ie(u,"float32"),-1))}}};const K1={kernelName:cR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>{const p=yt(Ie(u,"float32")),y=fs(Be(Fe(1),p));return It(Me(r,y))}}}};const X1={kernelName:lR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>{const p=fs(Be(yt(Ie(u,"float32")),1));return Me(r,p)}}}};const J1={kernelName:Hc,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,p]=l,y=ot(u.shape,p.shape),g=()=>{let S=r;const T=Dt(u.shape,y);return T.length>0&&(S=_e(S,T)),re(S,u.shape)},I=()=>{let S=r;const T=Dt(p.shape,y);return T.length>0&&(S=_e(S,T)),re(S,p.shape)};return{a:g,b:I}}};const Z1={kernelName:hR,saveAllInputs:!0,gradFunc:(r,l)=>{const u={};return l.forEach((p,y)=>{u[y]=()=>r.clone()}),u}};const Q1={kernelName:uR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Xe(u)}}};const eE={kernelName:dR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Xe(u)}}};const tE={kernelName:pR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Me(r,fs(Be(Fe(1),yt(Ie(u,"float32")))))}}};const nE={kernelName:mR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>{const p=fs(vt(Fe(1),yt(Ie(u,"float32"))));return Me(r,p)}}}};const sE={kernelName:yR,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,p]=l,y=ot(u.shape,p.shape),g=()=>{const S=vt(yt(u),yt(p));let T=le(r,Me(p,S));const C=Dt(u.shape,y);return C.length>0&&(T=_e(T,C)),re(T,u.shape)},I=()=>{const S=vt(yt(u),yt(p));let T=It(le(r,Me(u,S)));const C=Dt(p.shape,y);return C.length>0&&(T=_e(T,C)),re(T,p.shape)};return{a:g,b:I}}};const iE={kernelName:fR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Me(r,vt(yt(Ie(u,"float32")),1))}}};const rE={kernelName:gR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Me(r,Be(Fe(1),yt(Ie(u,"float32"))))}}};function KQ(r,l,u,p,y=[1,1,1],g,I){const S=M(r,"dy","avgPool3dBackprop"),T=M(l,"input","avgPool3dBackprop");let C=S,D=T,_=!1;T.rank===4&&(_=!0,C=re(S,[1,S.shape[0],S.shape[1],S.shape[2],S.shape[3]]),D=re(T,[1,T.shape[0],T.shape[1],T.shape[2],T.shape[3]])),J(C.rank===5,()=>`Error in avgPool3dBackprop: dy must be rank 5 but got rank ${C.rank}.`),J(D.rank===5,()=>`Error in avgPool3dBackprop: input must be rank 5 but got rank ${D.rank}.`),J(yo(p,y),()=>`Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides ${p} and dilations '${y}'`),I!=null&&J(nn(g),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${I} but got pad ${g}.`);const A=P=>{const ge=Mg(D.shape,u,p,y,g,I);return P.avgPool3dBackprop(C,D,ge)},B={dy:C,input:D},ne={filterSize:u,strides:p,dilations:y,pad:g,dimRoundingMode:I},te=H.runKernelFunc(A,B,null,SR,ne);return _?re(te,[te.shape[1],te.shape[2],te.shape[3],te.shape[4]]):te}const oE=V({avgPool3dBackprop_:KQ});const aE={kernelName:LR,inputsToSave:["x"],gradFunc:(r,l,u)=>{const[p]=l,{filterSize:y,strides:g,dilations:I,pad:S,dimRoundingMode:T}=u,C=I==null?[1,1,1]:I;return{x:()=>oE(r,p,y,g,C,S,T)}}};function XQ(r,l,u,p,y){const g=M(r,"dy","avgPoolBackprop"),I=M(l,"input","avgPoolBackprop");J(I.rank===g.rank,()=>`Rank of input (${I.rank}) does not match rank of dy (${g.rank})`);let S=I,T=g,C=!1;I.rank===3&&(C=!0,S=re(I,[1,I.shape[0],I.shape[1],I.shape[2]]),T=re(g,[1,g.shape[0],g.shape[1],g.shape[2]])),J(T.rank===4,()=>`Error in avgPoolBackprop: dy must be rank 4 but got rank ${T.rank}.`),J(S.rank===4,()=>`Error in avgPoolBackprop: input must be rank 4 but got rank ${S.rank}.`);const D=ne=>{const te=Bg(S.shape,u,p,1,y);return ne.avgPoolBackprop(T,S,te)},_={dy:T,input:S},A={filterSize:u,strides:p,pad:y},B=H.runKernelFunc(D,_,null,wR,A);return C?re(B,[B.shape[1],B.shape[2],B.shape[3]]):B}const cE=V({avgPoolBackprop_:XQ});const lE={kernelName:bR,inputsToSave:["x"],gradFunc:(r,l,u)=>{const[p]=l,{filterSize:y,strides:g,pad:I}=u;return{x:()=>cE(r,p,y,g,I)}}};const hE={kernelName:Wf,inputsToSave:["a","b"],gradFunc:(r,l,u)=>{const[p,y]=l,{transposeA:g,transposeB:I}=u;return!g&&!I?{a:()=>yn(r,y,!1,!0),b:()=>yn(p,r,!0,!1)}:!g&&I?{a:()=>yn(r,y,!1,!1),b:()=>yn(r,p,!0,!1)}:g&&!I?{a:()=>yn(y,r,!1,!0),b:()=>yn(p,r,!1,!1)}:{a:()=>yn(y,r,!0,!0),b:()=>yn(r,p,!0,!0)}}};const uE={kernelName:$f,gradFunc:(r,l,u)=>{const{blockShape:p,crops:y}=u;return{x:()=>hx(r,p,y)}}};const dE={kernelName:Uf,gradFunc:(r,l,u)=>{const p=u,y=p.inputShape,g=p.shape,I=Array.from(g);for(let T=y.length-1;T>=0;T--)if(y[T]===g[T])I[T]=1;else if(y[T]!==1)throw new Error(`broadcastTo(): [${y}] cannot be broadcast to [${g}].`);const S=[];for(let T=0;T<I.length;T++)I[T]>1&&S.push(T);return{x:()=>_e(r,S,!0)}}};const pE={kernelName:qc,gradFunc:r=>({x:()=>r.clone()})};const mE={kernelName:IR,gradFunc:r=>({x:()=>Xe(r)})};const fE={kernelName:xR,inputsToSave:["x"],gradFunc:(r,l,u)=>{const[p]=l,{clipValueMin:y,clipValueMax:g}=u;return{x:()=>Gn(ya(Ir(p,y),xr(p,g)),r,Xe(r))}}};const gE={kernelName:Bf,saveAllInputs:!0,gradFunc:(r,l,u)=>{const p=l.map(T=>T.shape),{axis:y}=u,g=gt(y,l[0].shape)[0],I=p.map(T=>T[g]),S=Lo(r,I,g);return S.map(T=>()=>T)}};const yE={kernelName:Mf,inputsToSave:["x","filter"],gradFunc:(r,l,u)=>{const[p,y]=l,{dilations:g,strides:I,pad:S,dataFormat:T}=u;return J(go(g),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${g}'`),{x:()=>a1(p.shape,r,y,I,S,T),filter:()=>qg(p,r,y.shape,I,S,T)}}};const bE={kernelName:Pf,inputsToSave:["dy","filter"],gradFunc:(r,l,u)=>{const[p,y]=l,{strides:g,pad:I,dataFormat:S,dimRoundingMode:T}=u;return{dy:()=>qI(r,y,g,I,S,1,T),filter:()=>qg(r,p,y.shape,g,I,S,T)}}};function JQ(r,l,u,p,y){let g=r;r.rank===4&&(g=re(r,[1,r.shape[0],r.shape[1],r.shape[2],r.shape[3]]));let I=l;I.rank===4&&(I=re(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]])),J(g.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${g.shape}.`),J(I.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${I.shape}.`),J(u.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${u}.`),J(g.shape[4]===u[3],()=>`Error in conv3dDerFilter: depth of input ${g.shape[4]}) must match input depth in filter (${u[3]}.`),J(I.shape[4]===u[4],()=>`Error in conv3dDerFilter: depth of dy (${I.shape[4]}) must match output depth for filter (${u[4]}).`);const S=D=>{const _=1,A=Yu(g.shape,u,p,_,y);return D.conv3dDerFilter(g,I,A)},T={x:g,dy:I},C={strides:p,pad:y,filterShape:u};return H.runKernelFunc(S,T,null,NR,C)}const wE=V({conv3DBackpropFilter_:JQ});const LE={kernelName:vR,inputsToSave:["x","filter"],gradFunc:(r,l,u)=>{const{dilations:p,strides:y,pad:g}=u;J(go(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:()=>c1(I.shape,r,S,y,g),filter:()=>wE(I,r,S.shape,y,g)}}};const SE={kernelName:zf,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(It(dx(Ie(u,"float32"))),r)}}};const IE={kernelName:Vf,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(px(Ie(u,"float32")),r)}}};const xE={kernelName:Gf,inputsToSave:["x"],gradFunc:(r,l,u)=>{const[p]=l,{axis:y,exclusive:g,reverse:I}=u;return{x:()=>{const S=Gi([y],p.rank);let T=KI(r,y,g,!I);return S!=null&&(T=xn(T,S)),T}}}};const TE={kernelName:OR,inputsToSave:["x","filter"],gradFunc:(r,l,u)=>{const{dilations:p,strides:y,pad:g,dimRoundingMode:I}=u,S=p==null?[1,1]:p;J(go(S),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${S}'`);const[T,C]=l;return J(T.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${T.rank}.`),J(C.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${C.rank}.`),J(T.shape[3]===C.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${T.shape[3]}) must match the inChannels dimension in filter ${C.shape[2]}.`),J(yo(y,S),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${y} and dilations '${S}'.`),I!=null&&J(nn(g),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${I} but got pad ${g}.`),{x:()=>m1(T.shape,r,C,y,g,p,I),filter:()=>p1(T,r,C.shape,y,g,p,I)}}};const AE={kernelName:kR,inputsToSave:["x","filter"],gradFunc:(r,l,u)=>{const[p,y]=l,g={x:p,filter:y,dy:r},I={x:p,filter:y,dy:r};return{x:()=>H.runKernel(FR,g,u),filter:()=>H.runKernel(_R,I,u)}}};const vE={kernelName:Yf,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,p]=l,y=ot(u.shape,p.shape),g=()=>{const S=Me(r,Ie(p,"float32")),T=Dt(u.shape,y);return T.length>0?re(_e(S,T),u.shape):S},I=()=>{let S=le(r,Ie(u,"float32"));const T=Dt(p.shape,y);T.length>0&&(S=re(_e(S,T),p.shape));const C=yt(p);return It(Me(S,Ie(C,"float32")))};return{a:g,b:I}}};const NE={kernelName:WR,outputsToSave:[!0],gradFunc:(r,l)=>{const[u]=l,p=g=>g.eluDer(r,u),y={dy:r,y:u};return{x:()=>H.runKernelFunc(p,y,null,$R)}}};const CE={kernelName:UR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l,p=le(Yn(It(yt(u))),2/Math.sqrt(Math.PI));return{x:()=>le(r,p)}}};const RE={kernelName:Hf,outputsToSave:[!0],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(r,u)}}};const OE={kernelName:MR,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(r,Yn(u))}}};const EE={kernelName:qf,gradFunc:r=>({x:()=>Xe(r)})};const DE={kernelName:jf,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,p]=l,y=ot(u.shape,p.shape),g=()=>{const S=Me(r,Ie(p,"float32")),T=Dt(u.shape,y);return T.length>0?re(_e(S,T),u.shape):S},I=()=>{let S=le(r,Ie(u,"float32"));const T=Dt(p.shape,y);T.length>0&&(S=re(_e(S,T),p.shape));const C=yt(p);return It(Me(S,Ie(C,"float32")))};return{a:g,b:I}}};const kE={kernelName:GR,inputsToSave:["x","mean","variance","scale"],gradFunc:(r,l,u)=>{const{varianceEpsilon:p}=u,[y,g,I,S]=l,T=S==null?Fe(1):S,C=Dt(g.shape,y.shape),D=[];if(g.rank===1){for(let ve=0;ve<y.shape.length-1;++ve)D.push(y.shape[ve]);D.push(1)}const _=Be(y,g),A=le(r,T),B=ux(vt(I,Fe(p))),ne=le(le(le(B,B),B),Fe(-.5)),te=()=>g.rank===1?re(le(le(r,fa(re(B,[1,1,1,g.shape[0]]),D)),T),y.shape):re(le(le(r,B),T),y.shape),P=()=>{let ve=le(le(B,Fe(-1)),A);return g.rank===1&&(ve=_e(ve,C)),re(ve,g.shape)},ge=()=>{let ve=le(le(ne,_),A);return g.rank===1&&(ve=_e(ve,C)),re(ve,g.shape)},ae=()=>{const ve=le(_,B);let Ve=le(r,ve);return g.rank===1&&(Ve=_e(Ve,C)),re(Ve,g.shape)},Le=()=>{let ve=r;return g.rank===1&&(ve=_e(ve,C)),re(ve,g.shape)};return{x:te,mean:P,variance:ge,scale:ae,offset:Le}}};const WE={kernelName:Kf,inputsToSave:["x","indices"],gradFunc:(r,l,u)=>{const[p,y]=l,{axis:g}=u,I=gt(g,p.shape)[0],S=()=>{const T=p.shape,C=y.size,D=T.slice(0,I),_=D.length,A=T.slice(g,T.length).slice(1),B=A.length,ne=FE(0,_),te=FE(_+1,_+1+B),P=_E([D,[C],A]),ge=re(r,P),ae=re(y,[C]),Le=_E([[_],ne,te]),ve=xn(ge,Le);let Ve=yx(ve,ae,p.shape[I]);const at=Xc(Le);return Ve=xn(Ve,at),Ve};return{x:S,indices:()=>y}}};function FE(r,l){const u=[];for(let p=r;p<l;++p)u.push(p);return u}function _E(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 $E={kernelName:Xf,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,p]=l;return{a:()=>Xe(u),b:()=>Xe(p)}}};const UE={kernelName:Jf,gradFunc:r=>({x:()=>Ie(r,"float32")})};const BE={kernelName:jR,gradFunc:r=>({x:()=>Xe(r)})};const ME={kernelName:KR,gradFunc:r=>({x:()=>Xe(r)})};const PE={kernelName:XR,gradFunc:r=>({x:()=>Xe(r)})};const zE={kernelName:Qf,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Me(r,vt(u,1))}}};const VE={kernelName:Zf,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Me(r,Ie(u,"float32"))}}};const GE={kernelName:tO,inputsToSave:[],outputsToSave:[!0],gradFunc:(r,l,u)=>{const[p]=l,{axis:y}=u;return{logits:()=>{const g=!0,I=Yn(p);return Be(r,le(_e(r,y,g),I))}}}};function ZQ(r,l,u,p=5,y=1,g=1,I=.5){const S=D=>D.LRNGrad(u,r,l,p,y,g,I),T={x:r,y:l,dy:u},C={depthRadius:p,bias:y,alpha:g,beta:I};return H.runKernelFunc(S,T,null,sO,C)}const YE=V({localResponseNormalizationBackprop_:ZQ});const HE={kernelName:nO,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,l,u)=>{const[p,y]=l,{depthRadius:g,bias:I,alpha:S,beta:T}=u;return{x:()=>YE(p,y,r,g,I,S,T)}}};function Xg(r,l,u,p){return l.rank<u.rank&&(l=re(l,os(l.shape,p))),r.rank<u.rank&&(r=re(r,os(r.shape,p))),{x:()=>{const y=le(r,Ie(XI(u,l),r.dtype));return y}}}const wx={kernelName:eg,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,l,u)=>{const p=u,{reductionIndices:y}=p,g=l[0],I=l[1],S=gt(y,g.shape),T=Xg(r,I,g,S);return{x:()=>T.x()}}};const qE={kernelName:tg,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,p]=l,y=()=>le(r,Ie(Ir(u,p),"float32")),g=()=>le(r,Ie(nx(u,p),"float32"));return{a:y,b:g}}};function QQ(r,l,u,p,y,g=[1,1,1],I,S){const T=M(r,"dy","maxPool3dBackprop"),C=M(l,"input","maxPool3dBackprop"),D=M(u,"output","maxPool3dBackprop");let _=T,A=C,B=D,ne=!1;C.rank===4&&(ne=!0,_=re(T,[1,T.shape[0],T.shape[1],T.shape[2],T.shape[3]]),A=re(C,[1,C.shape[0],C.shape[1],C.shape[2],C.shape[3]]),B=re(D,[1,D.shape[0],D.shape[1],D.shape[2],D.shape[3]])),J(_.rank===5,()=>`Error in maxPool3dBackprop: dy must be rank 5 but got rank ${_.rank}.`),J(A.rank===5,()=>`Error in maxPool3dBackprop: input must be rank 5 but got rank ${A.rank}.`),J(B.rank===5,()=>`Error in maxPool3dBackprop: output must be rank 5 but got rank ${B.rank}.`),J(yo(y,g),()=>`Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides ${y} and dilations '${g}'`),S!=null&&J(nn(I),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${S} but got pad ${I}.`);const te=Le=>{const ve=Mg(A.shape,p,y,g,I,S);return Le.maxPool3dBackprop(_,A,B,ve)},P={dy:_,input:A,output:B},ge={filterSize:p,strides:y,dilations:g,pad:I,dimRoundingMode:S},ae=H.runKernelFunc(te,P,null,aO,ge);return ne?re(ae,[ae.shape[1],ae.shape[2],ae.shape[3],ae.shape[4]]):ae}const jE=V({maxPool3dBackprop_:QQ});const KE={kernelName:oO,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,l,u)=>{const[p,y]=l,{filterSize:g,strides:I,dilations:S,pad:T,dimRoundingMode:C}=u,D=S==null?[1,1,1]:S;return{x:()=>jE(r,p,y,g,I,D,T,C)}}};function eee(r,l,u,p,y,g,I){const S=M(r,"dy","maxPoolBackprop"),T=M(l,"input","maxPoolBackprop"),C=M(u,"output","maxPoolBackprop");J(T.rank===S.rank,()=>`Rank of input (${T.rank}) does not match rank of dy (${S.rank})`),J(S.rank===4,()=>`Error in maxPoolBackprop: dy must be rank 4 but got rank ${S.rank}.`),J(T.rank===4,()=>`Error in maxPoolBackprop: input must be rank 4 but got rank ${T.rank}.`),I!=null&&J(nn(g),()=>`Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode ${I} but got pad ${g}.`);const D=B=>{const ne=Bg(T.shape,p,y,1,g,I);return B.maxPoolBackprop(S,T,C,ne)},_={dy:S,input:T,output:C},A={filterSize:p,strides:y,pad:g,dimRoundingMode:I};return H.runKernelFunc(D,_,null,rO,A)}const XE=V({maxPoolBackprop_:eee});const JE={kernelName:iO,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,l,u)=>{const[p,y]=l,{filterSize:g,strides:I,pad:S}=u;return{x:()=>XE(r,p,y,g,I,S)}}};const ZE={kernelName:ng,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,l,u)=>{const p=u,{axis:y}=p,[g,I]=l,S=gt(y,g.shape),T=Xg(r,I,g,S);return{x:()=>T.x()}}};const QE={kernelName:sg,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,p]=l,y=()=>le(r,Ie(xr(u,p),"float32")),g=()=>le(r,Ie(bi(u,p),"float32"));return{a:y,b:g}}};const eD={kernelName:lO,inputsToSave:["x"],gradFunc:(r,l,u)=>{const p=l[0],{paddings:y}=u,g=y.map(I=>I[0]);return{x:()=>Tt(r,g,p.shape)}}};const tD={kernelName:hO,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,p]=l,y=ot(u.shape,p.shape),g=()=>{const S=Dt(u.shape,y);return S.length>0?re(_e(r,S),u.shape):r},I=()=>{const S=le(r,It(QI(Me(u,p)))),T=Dt(p.shape,y);return T.length>0?re(_e(S,T),p.shape):S};return{a:g,b:I}}};const nD={kernelName:ig,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,p]=l,y=ot(u.shape,p.shape),g=()=>{const S=le(r,Ie(p,"float32")),T=Dt(u.shape,y);return T.length>0?re(_e(S,T),u.shape):S},I=()=>{const S=le(r,Ie(u,"float32")),T=Dt(p.shape,y);return T.length>0?re(_e(S,T),p.shape):S};return{a:g,b:I}}};const sD={kernelName:rg,gradFunc:r=>({x:()=>It(r)})};const iD={kernelName:gO,inputsToSave:["indices"],gradFunc:(r,l)=>{const u=l[0];return{indices:()=>Fs(u.shape,"float32")}}};const rD={kernelName:fO,gradFunc:r=>({x:()=>Xe(r)})};const Lx={kernelName:og,inputsToSave:["x"],gradFunc:(r,l,u)=>{const p=l[0],{paddings:y}=u,g=y.map(I=>I[0]);return{x:()=>Tt(r,g,p.shape)}}};const oD={kernelName:ag,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(r,l)=>{const[u,p,y]=l,g=u,I=p,S=ot(g.shape,I.shape),T=()=>{const D=Ie(I,"float32");let _=le(r,le(D,ba(g,Be(D,Fe(1)))));const A=Dt(g.shape,S);return A.length>0&&(_=_e(_,A)),re(_,g.shape)},C=()=>{const D=bi(g,0),_=Gn(D,bo(g),Xe(g));let A=le(r,le(y,_));const B=Dt(I.shape,S);return B.length>0&&(A=_e(A,B)),re(A,I.shape)};return{a:T,b:C}}};const aD={kernelName:yO,inputsToSave:["x","alpha"],gradFunc:(r,l)=>{const[u,p]=l,y=bi(u,0);return{x:()=>Gn(y,r,le(r,p)),alpha:()=>{let g=Gn(y,Xe(r),le(r,u));const I=Dt(p.shape,r.shape);return I.length>0&&(g=_e(g,I)),re(g,p.shape)}}}};const cD={kernelName:LO,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Me(r,It(yt(u)))}}};const lD={kernelName:xO,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l,p=le(xr(u,6),wa(u));return{x:()=>le(r,Ie(p,"float32"))}}};const hD={kernelName:cg,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(r,Ie(wa(u),"float32"))}}};const uD={kernelName:lg,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>re(r,u.shape)}}};const dD={kernelName:ug,inputsToSave:["images"],gradFunc:(r,l,u)=>{const[p]=l,y=S=>{const{alignCorners:T}=u;return S.resizeBilinearBackprop(r,p,T)},g={images:p},I=()=>H.runKernelFunc(y,g,null,IO,u);return{images:I}}};const pD={kernelName:hg,inputsToSave:["images"],gradFunc:(r,l,u)=>{const[p]=l,y=S=>{const{alignCorners:T}=u;return S.resizeNearestNeighborBackprop(r,p,T)},g={images:p},I=()=>H.runKernelFunc(y,g,null,SO,u);return{images:I}}};const mD={kernelName:dg,gradFunc:(r,l,u)=>{const{dims:p}=u,y=gt(p,r.shape);return{x:()=>el(r,y)}}};const fD={kernelName:TO,gradFunc:r=>({x:()=>Xe(r)})};const gD={kernelName:pg,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>It(Me(r,le(ba(u,1.5),2)))}}};const yD={kernelName:mg,inputsToSave:["condition"],gradFunc:(r,l)=>{const[u]=l;return{condition:()=>Ie(Xe(u),"float32"),t:()=>le(r,Ie(u,r.dtype)),e:()=>le(r,Ie(rx(u),r.dtype))}}};const bD={kernelName:AO,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>{const p=bi(u,Fe(0)),y=Fe(H1),g=Fe(q1),I=le(r,g),S=le(le(r,y),Yn(Ie(u,"float32")));return Gn(p,I,S)}}}};const wD={kernelName:bg,outputsToSave:[!0],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(r,le(u,Be(Fe(1),u)))}}};const LD={kernelName:vO,gradFunc:r=>({x:()=>Xe(r)})};const SD={kernelName:gg,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(Hu(Ie(u,"float32")),r)}}};const ID={kernelName:yg,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(jI(Ie(u,"float32")),r)}}};const xD={kernelName:fg,inputsToSave:["x"],gradFunc:(r,l,u)=>{const[p]=l,{begin:y,size:g}=u,I=p.shape,[S,T]=$g(p,y,g),C=[];for(let D=0;D<r.rank;D++)C.push([S[D],I[D]-S[D]-T[D]]);return{x:()=>lx(r,C)}}};const TD={kernelName:CO,outputsToSave:[!0],gradFunc:(r,l,u)=>{const[p]=l,{dim:y}=u,g=!0,I=le(r,p);return{logits:()=>Be(I,le(_e(I,[y],g),p))}}};const AD={kernelName:NO,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(r,YI(u))}}};const Sx={kernelName:Sg,gradFunc:(r,l,u)=>{const{blockShape:p,paddings:y}=u;return{x:()=>HI(r,p,y)}}};const Ix={kernelName:Ig,gradFunc:(r,l,u)=>{const{axis:p}=u;return{x:()=>Tn(r,p)}}};const vD={kernelName:wg,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Me(r,le(fs(Ie(u,"float32")),2))}}};const ND={kernelName:RO,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(r,le(Ie(u,"float32"),2))}}};const CD={kernelName:xg,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,p]=l,y=Fe(2),g=()=>le(r,le(y,Be(u,p))),I=()=>le(r,le(y,Be(p,u)));return{a:g,b:I}}};const RD={kernelName:Og,gradFunc:r=>({x:()=>Xe(r)})};const OD={kernelName:Tg,inputsToSave:["a","b"],gradFunc:(r,l)=>{const[u,p]=l,y=ot(u.shape,p.shape),g=()=>{let S=r;const T=Dt(u.shape,y);return T.length>0&&(S=_e(S,T)),re(S,u.shape)},I=()=>{let S=r;const T=Dt(p.shape,y);return T.length>0&&(S=_e(S,T)),re(It(S),p.shape)};return{a:g,b:I}}};const ED={kernelName:Lg,inputsToSave:["x"],gradFunc:(r,l,u)=>{const[p]=l,y=p.shape.slice(),{axis:g}=u,I=gt(g,p.shape);I.forEach(C=>{y[C]=1});const S=re(r,y),T=le(S,Yi(p.shape,"float32"));return{x:()=>T}}};const DD={kernelName:OO,inputsToSave:["x"],gradFunc:(r,l)=>{const[u]=l;return{x:()=>Me(r,yt(Hu(u)))}}};const kD={kernelName:EO,outputsToSave:[!0],gradFunc:(r,l)=>{const[u]=l;return{x:()=>le(Be(Fe(1),yt(u)),r)}}};const FD={kernelName:Ag,inputsToSave:["x"],gradFunc:(r,l,u)=>{const[p]=l,{reps:y}=u,g=()=>{let I=Xe(p);if(p.rank===1)for(let S=0;S<y[0];++S)I=vt(I,Tt(r,[S*p.shape[0]],[p.shape[0]]));else if(p.rank===2)for(let S=0;S<y[0];++S)for(let T=0;T<y[1];++T)I=vt(I,Tt(r,[S*p.shape[0],T*p.shape[1]],[p.shape[0],p.shape[1]]));else if(p.rank===3)for(let S=0;S<y[0];++S)for(let T=0;T<y[1];++T)for(let C=0;C<y[2];++C)I=vt(I,Tt(r,[S*p.shape[0],T*p.shape[1],C*p.shape[2]],[p.shape[0],p.shape[1],p.shape[2]]));else if(p.rank===4)for(let S=0;S<y[0];++S)for(let T=0;T<y[1];++T)for(let C=0;C<y[2];++C)for(let D=0;D<y[3];++D)I=vt(I,Tt(r,[S*p.shape[0],T*p.shape[1],C*p.shape[2],D*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:g}}};const _D={kernelName:vg,gradFunc:(r,l,u)=>{const p=u,{perm:y}=p,g=Xc(y);return{x:()=>xn(r,g)}}};const WD={kernelName:Ng,gradFunc:(r,l,u)=>{const p=u,{axis:y}=p;return{value:()=>js(r,y)}}};const $D={kernelName:Cg,inputsToSave:["segmentIds"],gradFunc:(r,l)=>{const[u]=l,p=()=>tee(r,u);return{x:p}}};function tee(r,l){const u=tx(l,Xe(l)),p=ex(r,u);let y=Ir(l,Fe(0,"int32"));const g=p.rank-y.rank;for(let S=0;S<g;++S)y=ks(y,S+1);y=ya(y,Yi(p.shape,"bool"));const I=Xe(p);return Gn(y,p,I)}const UD={kernelName:Rg,gradFunc:r=>({x:()=>Xe(r)})};const nee=[j1,K1,X1,J1,Z1,Q1,eE,tE,nE,sE,iE,rE,aE,lE,hE,uE,dE,pE,mE,fE,gE,bE,yE,LE,SE,IE,xE,TE,AE,vE,NE,CE,RE,OE,DE,EE,kE,WE,$E,UE,BE,ME,PE,zE,VE,GE,HE,wx,wx,qE,KE,JE,ZE,QE,eD,tD,nD,sD,iD,rD,Lx,Lx,oD,aD,cD,lD,hD,uD,dD,pD,mD,fD,gD,yD,bD,wD,LD,SD,ID,xD,TD,AD,Sx,Sx,Ix,Ix,vD,CD,ND,RD,OD,ED,DD,kD,FD,_D,WD,$D,UD];for(const r of nee)FO(r);function Sf(r,l,u=!1){const{Image:p,Canvas:y}=Lt.getEnv();if(!(r instanceof p||r instanceof y))throw new Error("imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement");const g=ho(r),I=l/Math.max(g.height,g.width),S=I*g.width,T=I*g.height,C=aa({width:l,height:l}),D=r instanceof y?r:Uc(r),_=Math.abs(S-T)/2,A=u&&S<T?_:0,B=u&&T<S?_:0;return zn(C).drawImage(D,A,B,S,T),C}class yr{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(wr(u)){this._imageTensors[p]=u,this._inputDimensions[p]=u.shape;return}if(Os(u)){const g=u.shape[0];if(g!==1)throw new Error(`NetInput - tf.Tensor4D with batchSize ${g} passed, but not supported in input array`);this._imageTensors[p]=u,this._inputDimensions[p]=u.shape.slice(1);return}const y=u instanceof Lt.getEnv().Canvas?u:Uc(u);this._canvases[p]=y,this._inputDimensions[p]=[y.height,y.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 Ui(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 mI({width:l,height:u},this.inputSize)}toBatchTensor(r,l=!0){return this._inputSize=r,t1(()=>{const u=Ui(this.batchSize,0,1).map(y=>{const g=this.getInput(y);if(g instanceof Dn){let I=Os(g)?g:g.expandDims();return I=rf(I,l),(I.shape[1]!==r||I.shape[2]!==r)&&(I=Y1.resizeBilinear(I,[r,r])),I.as3D(r,r,3)}if(g instanceof Lt.getEnv().Canvas)return zI.fromPixels(Sf(g,r,l));throw new Error(`toBatchTensor - at batchIdx ${y}, expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have ${g}`)}),p=js(u.map(y=>Ie(y,"float32"))).as4D(this.batchSize,r,r,3);return p})}}async function Ot(r){if(r instanceof yr)return r;let l=Array.isArray(r)?r:[r];if(!l.length)throw new Error("toNetInput - empty array passed as input");const u=y=>Array.isArray(r)?` at input index ${y}:`:"",p=l.map(lo);return p.forEach((y,g)=>{if(!ku(y)&&!wr(y)&&!Os(y))throw typeof l[g]=="string"?new Error(`toNetInput -${u(g)} string passed, but could not resolve HTMLElement for element id ${l[g]}`):new Error(`toNetInput -${u(g)} expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id`);if(Os(y)){const I=y.shape[0];if(I!==1)throw new Error(`toNetInput -${u(g)} tf.Tensor4D with batchSize ${I} passed, but not supported in input array`)}}),await Promise.all(p.map(y=>ku(y)&&Af(y))),new yr(p,Array.isArray(r))}async function ra(r,l){const{Canvas:u}=Lt.getEnv();let p=r;if(!(r instanceof u)){const I=await Ot(r);if(I.batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");const S=I.getInput(0);p=S instanceof u?S:await If(S)}const y=zn(p),g=l.map(I=>I instanceof Vt?I.forSize(p.width,p.height).box.floor():I).map(I=>I.clipAtImageBorders(p.width,p.height));return g.map(({x:I,y:S,width:T,height:C})=>{const D=aa({width:T,height:C});return zn(D).putImageData(y.getImageData(I,S,T,C),0,0),D})}const Jg=Ze(Qe());async function oa(r,l){if(!wr(r)&&!Os(r))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(Os(r)&&r.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return Jg.tidy(()=>{const[u,p,y]=r.shape.slice(Os(r)?1:0),g=l.map(S=>S instanceof Vt?S.forSize(p,u).box:S).map(S=>S.clipAtImageBorders(p,u)),I=g.map(({x:S,y:T,width:C,height:D})=>Jg.slice3d(r.as3D(u,p,y),[T,S,0],[D,C,y]));return I})}async function uo(r,l){const u=Lt.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 V2(r){const l=await uo(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 Tf(u)}async function xf(r){return(await uo(r)).json()}async function z2(r){return new Float32Array(await(await uo(r)).arrayBuffer())}function Zg(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 y=r.split("/").filter(S=>S),g=r.endsWith(".json")?y[y.length-1]:u;let I=p+(r.endsWith(".json")?y.slice(0,y.length-1):y).join("/");return I=r.startsWith("/")?`/${I}`:I,{modelBaseUri:I,manifestUri:I==="/"?`/${g}`:`${I}/${g}`}}const BD=Ze(Qe());async function Lf(r,l){const{manifestUri:u,modelBaseUri:p}=Zg(r,l);let y=await xf(u);return BD.io.loadWeights(y,p)}function P2(r,l,u=!1){const{width:p,height:y}=u?ho(l):l;return r.width=p,r.height=y,{width:p,height:y}}const Tr=Ze(Qe());class En{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 Tr.Variable)}getFrozenParams(){return this.getParamList().filter(r=>!(r.tensor instanceof Tr.Variable))}variable(){this.getFrozenParams().forEach(({path:r,tensor:l})=>{this.reassignParamFromPath(r,l.variable())})}freeze(){this.getTrainableParams().forEach(({path:r,tensor:l})=>{const u=Tr.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 Lf(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}=Lt.getEnv(),{manifestUri:u,modelBaseUri:p}=Zg(r,this.getDefaultModelName()),y=T=>Promise.all(T.map(C=>l(C).then(D=>D.buffer))),g=Tr.io.weightsLoaderFactory(y),I=JSON.parse((await l(u)).toString()),S=await g(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((y,g)=>{if(!y.nextObj.hasOwnProperty(g))throw new Error(`traversePropertyPath - object does not have property ${g}, for path ${r}`);return{obj:y.nextObj,objProp:g,nextObj:y.nextObj[g]}},{nextObj:this.params}),{obj:u,objProp:p}=l;if(!u||!p||!(u[p]instanceof Tr.Tensor))throw new Error(`traversePropertyPath - parameter is not a tensor, for path ${r}`);return{obj:u,objProp:p}}}const nl=Ze(Qe());function as(r,l,u){return nl.tidy(()=>{let p=nl.separableConv2d(r,l.depthwise_filter,l.pointwise_filter,u,"same");return p=nl.add(p,l.bias),p})}const Bt=Ze(Qe());function Qg(r,l,u=!1){return Bt.tidy(()=>{const p=Bt.relu(u?Bt.add(Bt.conv2d(r,l.conv0.filters,[2,2],"same"),l.conv0.bias):as(r,l.conv0,[2,2])),y=as(p,l.conv1,[1,1]),g=Bt.relu(Bt.add(p,y)),I=as(g,l.conv2,[1,1]);return Bt.relu(Bt.add(p,Bt.add(y,I)))})}function Zu(r,l,u=!1,p=!0){return Bt.tidy(()=>{const y=Bt.relu(u?Bt.add(Bt.conv2d(r,l.conv0.filters,p?[2,2]:[1,1],"same"),l.conv0.bias):as(r,l.conv0,p?[2,2]:[1,1])),g=as(y,l.conv1,[1,1]),I=Bt.relu(Bt.add(y,g)),S=as(I,l.conv2,[1,1]),T=Bt.relu(Bt.add(y,Bt.add(g,S))),C=as(T,l.conv3,[1,1]);return Bt.relu(Bt.add(y,Bt.add(g,Bt.add(S,C))))})}const So=Ze(Qe());function Sa(r,l,u="same",p=!1){return So.tidy(()=>{const y=So.add(So.conv2d(r,l.filters,[1,1],u),l.bias);return p?So.relu(y):y})}function Hn(r,l){Object.keys(r).forEach(u=>{l.some(p=>p.originalPath===u)||r[u].dispose()})}const ey=Ze(Qe());function sl(r,l){return function(u,p,y,g){const I=ey.tensor4d(r(u*p*y*y),[y,y,u,p]),S=ey.tensor1d(r(p));return l.push({paramPath:`${g}/filters`},{paramPath:`${g}/bias`}),{filters:I,bias:S}}}const ty=Ze(Qe());function ny(r,l){return function(u,p,y){const g=ty.tensor2d(r(u*p),[u,p]),I=ty.tensor1d(r(p));return l.push({paramPath:`${y}/weights`},{paramPath:`${y}/bias`}),{weights:g,bias:I}}}class xx{constructor(r,l,u){this.depthwise_filter=r;this.pointwise_filter=l;this.bias=u}}const Qu=Ze(Qe());function il(r,l){return function(u,p,y){const g=Qu.tensor4d(r(3*3*u),[3,3,u,1]),I=Qu.tensor4d(r(u*p),[1,1,u,p]),S=Qu.tensor1d(r(p));return l.push({paramPath:`${y}/depthwise_filter`},{paramPath:`${y}/pointwise_filter`},{paramPath:`${y}/bias`}),new xx(g,I,S)}}function rl(r){return function(l){const u=r(`${l}/depthwise_filter`,4),p=r(`${l}/pointwise_filter`,4),y=r(`${l}/bias`,1);return new xx(u,p,y)}}function gs(r,l){return function(u,p,y){const g=r[u];if(!la(g,p))throw new Error(`expected weightMap[${u}] to be a Tensor${p}D, instead have ${g}`);return l.push({originalPath:u,paramPath:y||u}),g}}function qn(r){let l=r;function u(y){const g=l.slice(0,y);return l=l.slice(y),g}function p(){return l}return{extractWeights:u,getRemainingWeights:p}}function sy(r,l){const u=sl(r,l),p=il(r,l);function y(I,S,T,C=!1){const D=C?u(I,S,3,`${T}/conv0`):p(I,S,`${T}/conv0`),_=p(S,S,`${T}/conv1`),A=p(S,S,`${T}/conv2`);return{conv0:D,conv1:_,conv2:A}}function g(I,S,T,C=!1){const{conv0:D,conv1:_,conv2:A}=y(I,S,T,C),B=p(S,S,`${T}/conv3`);return{conv0:D,conv1:_,conv2:A,conv3:B}}return{extractDenseBlock3Params:y,extractDenseBlock4Params:g}}function MD(r){const l=[],{extractWeights:u,getRemainingWeights:p}=qn(r),{extractDenseBlock4Params:y}=sy(u,l),g=y(3,32,"dense0",!0),I=y(32,64,"dense1"),S=y(64,128,"dense2"),T=y(128,256,"dense3");if(p().length!==0)throw new Error(`weights remaing after extract: ${p().length}`);return{paramMappings:l,params:{dense0:g,dense1:I,dense2:S,dense3:T}}}function iy(r){return function(l){const u=r(`${l}/filters`,4),p=r(`${l}/bias`,1);return{filters:u,bias:p}}}function ry(r,l){const u=gs(r,l),p=iy(u),y=rl(u);function g(S,T=!1){const C=T?p(`${S}/conv0`):y(`${S}/conv0`),D=y(`${S}/conv1`),_=y(`${S}/conv2`);return{conv0:C,conv1:D,conv2:_}}function I(S,T=!1){const C=T?p(`${S}/conv0`):y(`${S}/conv0`),D=y(`${S}/conv1`),_=y(`${S}/conv2`),A=y(`${S}/conv3`);return{conv0:C,conv1:D,conv2:_,conv3:A}}return{extractDenseBlock3Params:g,extractDenseBlock4Params:I}}function PD(r){const l=[],{extractDenseBlock4Params:u}=ry(r,l),p={dense0:u("dense0",!0),dense1:u("dense1"),dense2:u("dense2"),dense3:u("dense3")};return Hn(r,l),{params:p,paramMappings:l}}const Io=Ze(Qe());class oy extends En{constructor(){super("FaceFeatureExtractor")}forwardInput(r){const{params:l}=this;if(!l)throw new Error("FaceFeatureExtractor - load model before inference");return Io.tidy(()=>{const u=Io.cast(r.toBatchTensor(112,!0),"float32"),p=[122.782,117.001,104.298],y=Hs(u,p).div(Io.scalar(255));let g=Zu(y,l.dense0,!0);return g=Zu(g,l.dense1),g=Zu(g,l.dense2),g=Zu(g,l.dense3),g=Io.avgPool(g,[7,7],[2,2],"valid"),g})}async forward(r){return this.forwardInput(await Ot(r))}getDefaultModelName(){return"face_feature_extractor_model"}extractParamsFromWeigthMap(r){return PD(r)}extractParams(r){return MD(r)}}const ol=Ze(Qe());function ed(r,l){return ol.tidy(()=>ol.add(ol.matMul(r,l.weights),l.bias))}function zD(r,l,u){const p=[],{extractWeights:y,getRemainingWeights:g}=qn(r),I=ny(y,p),S=I(l,u,"fc");if(g().length!==0)throw new Error(`weights remaing after extract: ${g().length}`);return{paramMappings:p,params:{fc:S}}}function VD(r){const l=[],u=gs(r,l);function p(g){const I=u(`${g}/weights`,2),S=u(`${g}/bias`,1);return{weights:I,bias:S}}const y={fc:p("fc")};return Hn(r,l),{params:y,paramMappings:l}}function ay(r){const l={},u={};return Object.keys(r).forEach(p=>{const y=p.startsWith("fc")?u:l;y[p]=r[p]}),{featureExtractorMap:l,classifierMap:u}}const GD=Ze(Qe());class cy extends En{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 GD.tidy(()=>{const u=r instanceof yr?this.faceFeatureExtractor.forwardInput(r):r;return ed(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 zD(r,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())}extractParamsFromWeigthMap(r){const{featureExtractorMap:l,classifierMap:u}=ay(r);return this.faceFeatureExtractor.loadFromWeightMap(l),VD(u)}extractParams(r){const l=this.getClassifierChannelsIn(),u=this.getClassifierChannelsOut(),p=u*l+u,y=r.slice(0,r.length-p),g=r.slice(r.length-p);return this.faceFeatureExtractor.extractWeights(y),this.extractClassifierParams(g)}}const yf=["neutral","happy","sad","angry","fearful","disgusted","surprised"];class co{constructor(r){if(r.length!==7)throw new Error(`FaceExpressions.constructor - expected probabilities.length to be 7, have: ${r.length}`);yf.forEach((l,u)=>{this[l]=r[u]})}asSortedArray(){return yf.map(r=>({expression:r,probability:this[r]})).sort((r,l)=>l.probability-r.probability)}}const al=Ze(Qe());class bf extends cy{constructor(r=new oy){super("FaceExpressionNet",r)}forwardInput(r){return al.tidy(()=>al.softmax(this.runNet(r)))}async forward(r){return this.forwardInput(await Ot(r))}async predictExpressions(r){const l=await Ot(r),u=await this.forwardInput(l),p=await Promise.all(al.unstack(u).map(async g=>{const I=await g.data();return g.dispose(),I}));u.dispose();const y=p.map(g=>new co(g));return l.isBatchInput?y:y[0]}getDefaultModelName(){return"face_expression_model"}getClassifierChannelsIn(){return 256}getClassifierChannelsOut(){return 7}}function ff(r){return r.expressions instanceof co}function Ou(r,l){const u={expressions:l};return Object.assign({},r,u)}function see(r,l,u=.1,p){const y=Array.isArray(l)?l:[l];y.forEach(g=>{const I=g instanceof co?g:ff(g)?g.expressions:void 0;if(!I)throw new Error("drawFaceExpressions - expected faceExpressions to be FaceExpressions | WithFaceExpressions<{}> or array thereof");const S=I.asSortedArray(),T=S.filter(_=>_.probability>u),C=mi(g)?g.detection.box.bottomLeft:p||new Ke(0,0),D=new Vc(T.map(_=>`${_.expression} (${ha(_.probability)})`),C);D.draw(r)})}function oo(r){return mi(r)&&r.landmarks instanceof Rs&&r.unshiftedLandmarks instanceof Rs&&r.alignedRect instanceof Vt}function ia(r,l){const{box:u}=r.detection,p=l.shiftBy(u.x,u.y),y=p.align(),{imageDims:g}=r.detection,I=new Vt(r.detection.score,y.rescale(g.reverse()),g),S={landmarks:p,unshiftedLandmarks:l,alignedRect:I};return Object.assign({},r,S)}class YD{constructor(r={}){const{drawLines:l=!0,drawPoints:u=!0,lineWidth:p,lineColor:y,pointSize:g,pointColor:I}=r;this.drawLines=l,this.drawPoints=u,this.lineWidth=p||1,this.pointSize=g||2,this.lineColor=y||"rgba(0, 255, 255, 1)",this.pointColor=I||"rgba(255, 0, 255, 1)"}}class HD{constructor(r,l={}){this.faceLandmarks=r,this.options=new YD(l)}draw(r){const l=zn(r),{drawLines:u,drawPoints:p,lineWidth:y,lineColor:g,pointSize:I,pointColor:S}=this.options;if(u&&this.faceLandmarks instanceof Mc&&(l.strokeStyle=g,l.lineWidth=y,br(l,this.faceLandmarks.getJawOutline()),br(l,this.faceLandmarks.getLeftEyeBrow()),br(l,this.faceLandmarks.getRightEyeBrow()),br(l,this.faceLandmarks.getNose()),br(l,this.faceLandmarks.getLeftEye(),!0),br(l,this.faceLandmarks.getRightEye(),!0),br(l,this.faceLandmarks.getMouth(),!0)),p){l.strokeStyle=S,l.fillStyle=S;const T=C=>{l.beginPath(),l.arc(C.x,C.y,I,0,2*Math.PI),l.fill()};this.faceLandmarks.positions.forEach(T)}}}function iee(r,l){const u=Array.isArray(l)?l:[l];u.forEach(p=>{const y=p instanceof Rs?p:oo(p)?p.landmarks:void 0;if(!y)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof");new HD(y).draw(r)})}const Qm={};vu(Qm,{AnchorPosition:()=>Mi,DrawBox:()=>SI,DrawBoxOptions:()=>j2,DrawFaceLandmarks:()=>HD,DrawFaceLandmarksOptions:()=>YD,DrawTextField:()=>Vc,DrawTextFieldOptions:()=>Of,drawContour:()=>br,drawDetections:()=>y9,drawFaceExpressions:()=>see,drawFaceLandmarks:()=>iee});function ree(r,l){const u=sl(r,l),p=il(r,l);function y(I,S,T){const C=p(I,S,`${T}/separable_conv0`),D=p(S,S,`${T}/separable_conv1`),_=u(I,S,1,`${T}/expansion_conv`);return{separable_conv0:C,separable_conv1:D,expansion_conv:_}}function g(I,S){const T=p(I,I,`${S}/separable_conv0`),C=p(I,I,`${S}/separable_conv1`),D=p(I,I,`${S}/separable_conv2`);return{separable_conv0:T,separable_conv1:C,separable_conv2:D}}return{extractConvParams:u,extractSeparableConvParams:p,extractReductionBlockParams:y,extractMainBlockParams:g}}function qD(r,l){const u=[],{extractWeights:p,getRemainingWeights:y}=qn(r),{extractConvParams:g,extractSeparableConvParams:I,extractReductionBlockParams:S,extractMainBlockParams:T}=ree(p,u),C=g(3,32,3,"entry_flow/conv_in"),D=S(32,64,"entry_flow/reduction_block_0"),_=S(64,128,"entry_flow/reduction_block_1"),A={conv_in:C,reduction_block_0:D,reduction_block_1:_},B={};Ui(l,0,1).forEach(ge=>{B[`main_block_${ge}`]=T(128,`middle_flow/main_block_${ge}`)});const ne=S(128,256,"exit_flow/reduction_block"),te=I(256,512,"exit_flow/separable_conv"),P={reduction_block:ne,separable_conv:te};if(y().length!==0)throw new Error(`weights remaing after extract: ${y().length}`);return{paramMappings:u,params:{entry_flow:A,middle_flow:B,exit_flow:P}}}function oee(r,l){const u=gs(r,l),p=iy(u),y=rl(u);function g(S){const T=y(`${S}/separable_conv0`),C=y(`${S}/separable_conv1`),D=p(`${S}/expansion_conv`);return{separable_conv0:T,separable_conv1:C,expansion_conv:D}}function I(S){const T=y(`${S}/separable_conv0`),C=y(`${S}/separable_conv1`),D=y(`${S}/separable_conv2`);return{separable_conv0:T,separable_conv1:C,separable_conv2:D}}return{extractConvParams:p,extractSeparableConvParams:y,extractReductionBlockParams:g,extractMainBlockParams:I}}function jD(r,l){const u=[],{extractConvParams:p,extractSeparableConvParams:y,extractReductionBlockParams:g,extractMainBlockParams:I}=oee(r,u),S=p("entry_flow/conv_in"),T=g("entry_flow/reduction_block_0"),C=g("entry_flow/reduction_block_1"),D={conv_in:S,reduction_block_0:T,reduction_block_1:C},_={};Ui(l,0,1).forEach(te=>{_[`main_block_${te}`]=I(`middle_flow/main_block_${te}`)});const A=g("exit_flow/reduction_block"),B=y("exit_flow/separable_conv"),ne={reduction_block:A,separable_conv:B};return Hn(r,u),{params:{entry_flow:D,middle_flow:_,exit_flow:ne},paramMappings:u}}const on=Ze(Qe());function KD(r,l,u){return on.add(on.conv2d(r,l.filters,u,"same"),l.bias)}function Tx(r,l,u=!0){let p=u?on.relu(r):r;return p=as(p,l.separable_conv0,[1,1]),p=as(on.relu(p),l.separable_conv1,[1,1]),p=on.maxPool(p,[3,3],[2,2],"same"),p=on.add(p,KD(r,l.expansion_conv,[2,2])),p}function aee(r,l){let u=as(on.relu(r),l.separable_conv0,[1,1]);return u=as(on.relu(u),l.separable_conv1,[1,1]),u=as(on.relu(u),l.separable_conv2,[1,1]),u=on.add(u,r),u}class XD extends En{constructor(r){super("TinyXception");this._numMainBlocks=r}forwardInput(r){const{params:l}=this;if(!l)throw new Error("TinyXception - load model before inference");return on.tidy(()=>{const u=on.cast(r.toBatchTensor(112,!0),"float32"),p=[122.782,117.001,104.298],y=Hs(u,p).div(on.scalar(256));let g=on.relu(KD(y,l.entry_flow.conv_in,[2,2]));return g=Tx(g,l.entry_flow.reduction_block_0,!1),g=Tx(g,l.entry_flow.reduction_block_1),Ui(this._numMainBlocks,0,1).forEach(I=>{g=aee(g,l.middle_flow[`main_block_${I}`])}),g=Tx(g,l.exit_flow.reduction_block),g=on.relu(as(g,l.exit_flow.separable_conv,[1,1])),g})}async forward(r){return this.forwardInput(await Ot(r))}getDefaultModelName(){return"tiny_xception_model"}extractParamsFromWeigthMap(r){return jD(r,this._numMainBlocks)}extractParams(r){return qD(r,this._numMainBlocks)}}function JD(r){const l=[],{extractWeights:u,getRemainingWeights:p}=qn(r),y=ny(u,l),g=y(512,1,"fc/age"),I=y(512,2,"fc/gender");if(p().length!==0)throw new Error(`weights remaing after extract: ${p().length}`);return{paramMappings:l,params:{fc:{age:g,gender:I}}}}function ZD(r){const l=[],u=gs(r,l);function p(g){const I=u(`${g}/weights`,2),S=u(`${g}/bias`,1);return{weights:I,bias:S}}const y={fc:{age:p("fc/age"),gender:p("fc/gender")}};return Hn(r,l),{params:y,paramMappings:l}}var $i;(function(r){r.FEMALE="female",r.MALE="male"})($i||($i={}));const Hi=Ze(Qe());class vf extends En{constructor(r=new XD(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 yr?this.faceFeatureExtractor.forwardInput(r):r,p=Hi.avgPool(u,[7,7],[2,2],"valid").as2D(u.shape[0],-1),y=ed(p,l.fc.age).as1D(),g=ed(p,l.fc.gender);return{age:y,gender:g}})}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 Ot(r))}async predictAgeAndGender(r){const l=await Ot(r),u=await this.forwardInput(l),p=Hi.unstack(u.age),y=Hi.unstack(u.gender),g=p.map((S,T)=>({ageTensor:S,genderTensor:y[T]})),I=await Promise.all(g.map(async({ageTensor:S,genderTensor:T})=>{const C=(await S.data())[0],D=(await T.data())[0],_=D>.5,A=_?$i.MALE:$i.FEMALE,B=_?D:1-D;return S.dispose(),T.dispose(),{age:C,gender:A,genderProbability:B}}));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 JD(r)}extractParamsFromWeigthMap(r){const{featureExtractorMap:l,classifierMap:u}=ay(r);return this.faceFeatureExtractor.loadFromWeightMap(l),ZD(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 ys=Ze(Qe());class ly extends cy{postProcess(r,l,u){const p=u.map(({width:g,height:I})=>{const S=l/Math.max(I,g);return{width:g*S,height:I*S}}),y=p.length;return ys.tidy(()=>{const g=(D,_)=>ys.stack([ys.fill([68],D,"float32"),ys.fill([68],_,"float32")],1).as2D(1,136).as1D(),I=(D,_)=>{const{width:A,height:B}=p[D];return _(A,B)?Math.abs(A-B)/2:0},S=D=>I(D,(_,A)=>_<A),T=D=>I(D,(_,A)=>A<_),C=r.mul(ys.fill([y,136],l,"float32")).sub(ys.stack(Array.from(Array(y),(D,_)=>g(S(_),T(_))))).div(ys.stack(Array.from(Array(y),(D,_)=>g(p[_].width,p[_].height))));return C})}forwardInput(r){return ys.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 Ot(r))}async detectLandmarks(r){const l=await Ot(r),u=ys.tidy(()=>ys.unstack(this.forwardInput(l))),p=await Promise.all(u.map(async(y,g)=>{const I=Array.from(await y.data()),S=I.filter((C,D)=>Nf(D)),T=I.filter((C,D)=>!Nf(D));return new Mc(Array(68).fill(0).map((C,D)=>new Ke(S[D],T[D])),{height:l.getInputHeight(g),width:l.getInputWidth(g)})}));return u.forEach(y=>y.dispose()),l.isBatchInput?p:p[0]}getClassifierChannelsOut(){return 136}}class Wc extends ly{constructor(r=new oy){super("FaceLandmark68Net",r)}getDefaultModelName(){return"face_landmark_68_model"}getClassifierChannelsIn(){return 256}}function QD(r){const l=[],{extractDenseBlock3Params:u}=ry(r,l),p={dense0:u("dense0",!0),dense1:u("dense1"),dense2:u("dense2")};return Hn(r,l),{params:p,paramMappings:l}}function ek(r){const l=[],{extractWeights:u,getRemainingWeights:p}=qn(r),{extractDenseBlock3Params:y}=sy(u,l),g=y(3,32,"dense0",!0),I=y(32,64,"dense1"),S=y(64,128,"dense2");if(p().length!==0)throw new Error(`weights remaing after extract: ${p().length}`);return{paramMappings:l,params:{dense0:g,dense1:I,dense2:S}}}const xo=Ze(Qe());class tk extends En{constructor(){super("TinyFaceFeatureExtractor")}forwardInput(r){const{params:l}=this;if(!l)throw new Error("TinyFaceFeatureExtractor - load model before inference");return xo.tidy(()=>{const u=xo.cast(r.toBatchTensor(112,!0),"float32"),p=[122.782,117.001,104.298],y=Hs(u,p).div(xo.scalar(255));let g=Qg(y,l.dense0,!0);return g=Qg(g,l.dense1),g=Qg(g,l.dense2),g=xo.avgPool(g,[14,14],[2,2],"valid"),g})}async forward(r){return this.forwardInput(await Ot(r))}getDefaultModelName(){return"face_feature_extractor_tiny_model"}extractParamsFromWeigthMap(r){return QD(r)}extractParams(r){return ek(r)}}class gf extends ly{constructor(r=new tk){super("FaceLandmark68TinyNet",r)}getDefaultModelName(){return"face_landmark_68_tiny_model"}getClassifierChannelsIn(){return 128}}class M2 extends Wc{}const hy=Ze(Qe());function nk(r,l){return hy.add(hy.mul(r,l.weights),l.biases)}const cl=Ze(Qe());function Ax(r,l,u,p,y="same"){const{filters:g,bias:I}=l.conv;let S=cl.conv2d(r,g,u,y);return S=cl.add(S,I),S=nk(S,l.scale),p?cl.relu(S):S}function sk(r,l){return Ax(r,l,[1,1],!0)}function vx(r,l){return Ax(r,l,[1,1],!1)}function uy(r,l){return Ax(r,l,[2,2],!0,"valid")}const bs=Ze(Qe());function cee(r,l){function u(S,T,C){const D=r(S),_=D.length/(T*C*C);if(pI(_))throw new Error(`depth has to be an integer: ${_}, weights.length: ${D.length}, numFilters: ${T}, filterSize: ${C}`);return bs.tidy(()=>bs.transpose(bs.tensor4d(D,[T,_,C,C]),[2,3,1,0]))}function p(S,T,C,D){const _=u(S,T,C),A=bs.tensor1d(r(T));return l.push({paramPath:`${D}/filters`},{paramPath:`${D}/bias`}),{filters:_,bias:A}}function y(S,T){const C=bs.tensor1d(r(S)),D=bs.tensor1d(r(S));return l.push({paramPath:`${T}/weights`},{paramPath:`${T}/biases`}),{weights:C,biases:D}}function g(S,T,C,D){const _=p(S,T,C,`${D}/conv`),A=y(T,`${D}/scale`);return{conv:_,scale:A}}function I(S,T,C,D,_=!1){const A=g((_?.5:1)*S,T,C,`${D}/conv1`),B=g(S,T,C,`${D}/conv2`);return{conv1:A,conv2:B}}return{extractConvLayerParams:g,extractResidualLayerParams:I}}function ik(r){const{extractWeights:l,getRemainingWeights:u}=qn(r),p=[],{extractConvLayerParams:y,extractResidualLayerParams:g}=cee(l,p),I=y(4704,32,7,"conv32_down"),S=g(9216,32,3,"conv32_1"),T=g(9216,32,3,"conv32_2"),C=g(9216,32,3,"conv32_3"),D=g(36864,64,3,"conv64_down",!0),_=g(36864,64,3,"conv64_1"),A=g(36864,64,3,"conv64_2"),B=g(36864,64,3,"conv64_3"),ne=g(147456,128,3,"conv128_down",!0),te=g(147456,128,3,"conv128_1"),P=g(147456,128,3,"conv128_2"),ge=g(589824,256,3,"conv256_down",!0),ae=g(589824,256,3,"conv256_1"),Le=g(589824,256,3,"conv256_2"),ve=g(589824,256,3,"conv256_down_out"),Ve=bs.tidy(()=>bs.transpose(bs.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 at={conv32_down:I,conv32_1:S,conv32_2:T,conv32_3:C,conv64_down:D,conv64_1:_,conv64_2:A,conv64_3:B,conv128_down:ne,conv128_1:te,conv128_2:P,conv256_down:ge,conv256_1:ae,conv256_2:Le,conv256_down_out:ve,fc:Ve};return{params:at,paramMappings:p}}function lee(r,l){const u=gs(r,l);function p(I){const S=u(`${I}/scale/weights`,1),T=u(`${I}/scale/biases`,1);return{weights:S,biases:T}}function y(I){const S=u(`${I}/conv/filters`,4),T=u(`${I}/conv/bias`,1),C=p(I);return{conv:{filters:S,bias:T},scale:C}}function g(I){return{conv1:y(`${I}/conv1`),conv2:y(`${I}/conv2`)}}return{extractConvLayerParams:y,extractResidualLayerParams:g}}function rk(r){const l=[],{extractConvLayerParams:u,extractResidualLayerParams:p}=lee(r,l),y=u("conv32_down"),g=p("conv32_1"),I=p("conv32_2"),S=p("conv32_3"),T=p("conv64_down"),C=p("conv64_1"),D=p("conv64_2"),_=p("conv64_3"),A=p("conv128_down"),B=p("conv128_1"),ne=p("conv128_2"),te=p("conv256_down"),P=p("conv256_1"),ge=p("conv256_2"),ae=p("conv256_down_out"),Le=r.fc;if(l.push({originalPath:"fc",paramPath:"fc"}),!dI(Le))throw new Error(`expected weightMap[fc] to be a Tensor2D, instead have ${Le}`);const ve={conv32_down:y,conv32_1:g,conv32_2:I,conv32_3:S,conv64_down:T,conv64_1:C,conv64_2:D,conv64_3:_,conv128_down:A,conv128_1:B,conv128_2:ne,conv256_down:te,conv256_1:P,conv256_2:ge,conv256_down_out:ae,fc:Le};return Hn(r,l),{params:ve,paramMappings:l}}const jn=Ze(Qe());function wi(r,l){let u=sk(r,l.conv1);return u=vx(u,l.conv2),u=jn.add(u,r),u=jn.relu(u),u}function td(r,l){let u=uy(r,l.conv1);u=vx(u,l.conv2);let p=jn.avgPool(r,2,2,"valid");const y=jn.zeros(p.shape),g=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 T=jn.zeros(S);u=jn.concat([u,T],1);const C=[...u.shape];C[2]=1;const D=jn.zeros(C);u=jn.concat([u,D],2)}return p=g?jn.concat([p,y],3):p,u=jn.add(p,u),u=jn.relu(u),u}const _s=Ze(Qe());class _c extends En{constructor(){super("FaceRecognitionNet")}forwardInput(r){const{params:l}=this;if(!l)throw new Error("FaceRecognitionNet - load model before inference");return _s.tidy(()=>{const u=_s.cast(r.toBatchTensor(150,!0),"float32"),p=[122.782,117.001,104.298],y=Hs(u,p).div(_s.scalar(256));let g=uy(y,l.conv32_down);g=_s.maxPool(g,3,2,"valid"),g=wi(g,l.conv32_1),g=wi(g,l.conv32_2),g=wi(g,l.conv32_3),g=td(g,l.conv64_down),g=wi(g,l.conv64_1),g=wi(g,l.conv64_2),g=wi(g,l.conv64_3),g=td(g,l.conv128_down),g=wi(g,l.conv128_1),g=wi(g,l.conv128_2),g=td(g,l.conv256_down),g=wi(g,l.conv256_1),g=wi(g,l.conv256_2),g=td(g,l.conv256_down_out);const I=g.mean([1,2]),S=_s.matMul(I,l.fc);return S})}async forward(r){return this.forwardInput(await Ot(r))}async computeFaceDescriptor(r){const l=await Ot(r),u=_s.tidy(()=>_s.unstack(this.forwardInput(l))),p=await Promise.all(u.map(y=>y.data()));return u.forEach(y=>y.dispose()),l.isBatchInput?p:p[0]}getDefaultModelName(){return"face_recognition_model"}extractParamsFromWeigthMap(r){return rk(r)}extractParams(r){return ik(r)}}function B2(r){const l=new _c;return l.extractWeights(r),l}function Eu(r,l){const u={descriptor:l};return Object.assign({},r,u)}function U2(r){return typeof r.age=="number"}function Du(r,l){const u={age:l};return Object.assign({},r,u)}function $2(r){return(r.gender===$i.MALE||r.gender===$i.FEMALE)&&zc(r.genderProbability)}function Ru(r,l,u){const p={gender:l,genderProbability:u};return Object.assign({},r,p)}const Li=Ze(Qe());function hee(r,l){function u(T,C){const D=Li.tensor4d(r(3*3*T),[3,3,T,1]),_=Li.tensor1d(r(T)),A=Li.tensor1d(r(T)),B=Li.tensor1d(r(T)),ne=Li.tensor1d(r(T));return l.push({paramPath:`${C}/filters`},{paramPath:`${C}/batch_norm_scale`},{paramPath:`${C}/batch_norm_offset`},{paramPath:`${C}/batch_norm_mean`},{paramPath:`${C}/batch_norm_variance`}),{filters:D,batch_norm_scale:_,batch_norm_offset:A,batch_norm_mean:B,batch_norm_variance:ne}}function p(T,C,D,_,A){const B=Li.tensor4d(r(T*C*D*D),[D,D,T,C]),ne=Li.tensor1d(r(C));return l.push({paramPath:`${_}/filters`},{paramPath:`${_}/${A?"batch_norm_offset":"bias"}`}),{filters:B,bias:ne}}function y(T,C,D,_){const{filters:A,bias:B}=p(T,C,D,_,!0);return{filters:A,batch_norm_offset:B}}function g(T,C,D){const _=u(T,`${D}/depthwise_conv`),A=y(T,C,1,`${D}/pointwise_conv`);return{depthwise_conv:_,pointwise_conv:A}}function I(){const T=y(3,32,3,"mobilenetv1/conv_0"),C=g(32,64,"mobilenetv1/conv_1"),D=g(64,128,"mobilenetv1/conv_2"),_=g(128,128,"mobilenetv1/conv_3"),A=g(128,256,"mobilenetv1/conv_4"),B=g(256,256,"mobilenetv1/conv_5"),ne=g(256,512,"mobilenetv1/conv_6"),te=g(512,512,"mobilenetv1/conv_7"),P=g(512,512,"mobilenetv1/conv_8"),ge=g(512,512,"mobilenetv1/conv_9"),ae=g(512,512,"mobilenetv1/conv_10"),Le=g(512,512,"mobilenetv1/conv_11"),ve=g(512,1024,"mobilenetv1/conv_12"),Ve=g(1024,1024,"mobilenetv1/conv_13");return{conv_0:T,conv_1:C,conv_2:D,conv_3:_,conv_4:A,conv_5:B,conv_6:ne,conv_7:te,conv_8:P,conv_9:ge,conv_10:ae,conv_11:Le,conv_12:ve,conv_13:Ve}}function S(){const T=y(1024,256,1,"prediction_layer/conv_0"),C=y(256,512,3,"prediction_layer/conv_1"),D=y(512,128,1,"prediction_layer/conv_2"),_=y(128,256,3,"prediction_layer/conv_3"),A=y(256,128,1,"prediction_layer/conv_4"),B=y(128,256,3,"prediction_layer/conv_5"),ne=y(256,64,1,"prediction_layer/conv_6"),te=y(64,128,3,"prediction_layer/conv_7"),P=p(512,12,1,"prediction_layer/box_predictor_0/box_encoding_predictor"),ge=p(512,9,1,"prediction_layer/box_predictor_0/class_predictor"),ae=p(1024,24,1,"prediction_layer/box_predictor_1/box_encoding_predictor"),Le=p(1024,18,1,"prediction_layer/box_predictor_1/class_predictor"),ve=p(512,24,1,"prediction_layer/box_predictor_2/box_encoding_predictor"),Ve=p(512,18,1,"prediction_layer/box_predictor_2/class_predictor"),at=p(256,24,1,"prediction_layer/box_predictor_3/box_encoding_predictor"),pt=p(256,18,1,"prediction_layer/box_predictor_3/class_predictor"),$t=p(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),Gt=p(256,18,1,"prediction_layer/box_predictor_4/class_predictor"),qe=p(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),ln=p(128,18,1,"prediction_layer/box_predictor_5/class_predictor"),bt={box_encoding_predictor:P,class_predictor:ge},ws={box_encoding_predictor:ae,class_predictor:Le},Cr={box_encoding_predictor:ve,class_predictor:Ve},Rr={box_encoding_predictor:at,class_predictor:pt},Ta={box_encoding_predictor:$t,class_predictor:Gt},hn={box_encoding_predictor:qe,class_predictor:ln};return{conv_0:T,conv_1:C,conv_2:D,conv_3:_,conv_4:A,conv_5:B,conv_6:ne,conv_7:te,box_predictor_0:bt,box_predictor_1:ws,box_predictor_2:Cr,box_predictor_3:Rr,box_predictor_4:Ta,box_predictor_5:hn}}return{extractMobilenetV1Params:I,extractPredictionLayerParams:S}}function ok(r){const l=[],{extractWeights:u,getRemainingWeights:p}=qn(r),{extractMobilenetV1Params:y,extractPredictionLayerParams:g}=hee(u,l),I=y(),S=g(),T=Li.tensor3d(u(5118*4),[1,5118,4]),C={extra_dim:T};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:C},paramMappings:l}}function uee(r,l){const u=gs(r,l);function p(C,D,_){const A=u(`${C}/Conv2d_${D}_pointwise/weights`,4,`${_}/filters`),B=u(`${C}/Conv2d_${D}_pointwise/convolution_bn_offset`,1,`${_}/batch_norm_offset`);return{filters:A,batch_norm_offset:B}}function y(C){const D=`mobilenetv1/conv_${C}`,_=`MobilenetV1/Conv2d_${C}_depthwise`,A=`${D}/depthwise_conv`,B=`${D}/pointwise_conv`,ne=u(`${_}/depthwise_weights`,4,`${A}/filters`),te=u(`${_}/BatchNorm/gamma`,1,`${A}/batch_norm_scale`),P=u(`${_}/BatchNorm/beta`,1,`${A}/batch_norm_offset`),ge=u(`${_}/BatchNorm/moving_mean`,1,`${A}/batch_norm_mean`),ae=u(`${_}/BatchNorm/moving_variance`,1,`${A}/batch_norm_variance`);return{depthwise_conv:{filters:ne,batch_norm_scale:te,batch_norm_offset:P,batch_norm_mean:ge,batch_norm_variance:ae},pointwise_conv:p("MobilenetV1",C,B)}}function g(){return{conv_0:p("MobilenetV1",0,"mobilenetv1/conv_0"),conv_1:y(1),conv_2:y(2),conv_3:y(3),conv_4:y(4),conv_5:y(5),conv_6:y(6),conv_7:y(7),conv_8:y(8),conv_9:y(9),conv_10:y(10),conv_11:y(11),conv_12:y(12),conv_13:y(13)}}function I(C,D){const _=u(`${C}/weights`,4,`${D}/filters`),A=u(`${C}/biases`,1,`${D}/bias`);return{filters:_,bias:A}}function S(C){const D=I(`Prediction/BoxPredictor_${C}/BoxEncodingPredictor`,`prediction_layer/box_predictor_${C}/box_encoding_predictor`),_=I(`Prediction/BoxPredictor_${C}/ClassPredictor`,`prediction_layer/box_predictor_${C}/class_predictor`);return{box_encoding_predictor:D,class_predictor:_}}function T(){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:g,extractPredictionLayerParams:T}}function ak(r){const l=[],{extractMobilenetV1Params:u,extractPredictionLayerParams:p}=uee(r,l),y=r["Output/extra_dim"];if(l.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!wr(y))throw new Error(`expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have ${y}`);const g={mobilenetv1:u(),prediction_layer:p(),output_layer:{extra_dim:y}};return Hn(r,l),{params:g,paramMappings:l}}const To=Ze(Qe());function Xs(r,l,u){return To.tidy(()=>{let p=To.conv2d(r,l.filters,u,"same");return p=To.add(p,l.batch_norm_offset),To.clipByValue(p,0,6)})}const Ar=Ze(Qe()),dee=.0010000000474974513;function pee(r,l,u){return Ar.tidy(()=>{let p=Ar.depthwiseConv2d(r,l.filters,u,"same");return p=Ar.batchNorm(p,l.batch_norm_mean,l.batch_norm_variance,l.batch_norm_offset,l.batch_norm_scale,dee),Ar.clipByValue(p,0,6)})}function mee(r){return[2,4,6,12].some(l=>l===r)?[2,2]:[1,1]}function ck(r,l){return Ar.tidy(()=>{let u,p=Xs(r,l.conv_0,[2,2]);const y=[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(y.forEach((g,I)=>{const S=I+1,T=mee(S);p=pee(p,g.depthwise_conv,T),p=Xs(p,g.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 lk(r,l,u,p,y){const g=r.shape[0],I=Math.min(u,g),S=l.map((D,_)=>({score:D,boxIndex:_})).filter(D=>D.score>y).sort((D,_)=>_.score-D.score),T=D=>D<=p?1:0,C=[];return S.forEach(D=>{if(C.length>=I)return;const _=D.score;for(let A=C.length-1;A>=0;--A){const B=fee(r,D.boxIndex,C[A]);if(B===0)continue;if(D.score*=T(B),D.score<=y)break}_===D.score&&C.push(D.boxIndex)}),C}function fee(r,l,u){const p=r.arraySync(),y=Math.min(p[l][0],p[l][2]),g=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]),T=Math.min(p[u][0],p[u][2]),C=Math.min(p[u][1],p[u][3]),D=Math.max(p[u][0],p[u][2]),_=Math.max(p[u][1],p[u][3]),A=(I-y)*(S-g),B=(D-T)*(_-C);if(A<=0||B<=0)return 0;const ne=Math.max(y,T),te=Math.max(g,C),P=Math.min(I,D),ge=Math.min(S,_),ae=Math.max(P-ne,0)*Math.max(ge-te,0);return ae/(A+B-ae)}const ke=Ze(Qe());function gee(r){const l=ke.unstack(ke.transpose(r,[1,0])),u=[ke.sub(l[2],l[0]),ke.sub(l[3],l[1])],p=[ke.add(l[0],ke.div(u[0],ke.scalar(2))),ke.add(l[1],ke.div(u[1],ke.scalar(2)))];return{sizes:u,centers:p}}function yee(r,l){const{sizes:u,centers:p}=gee(r),y=ke.unstack(ke.transpose(l,[1,0])),g=ke.div(ke.mul(ke.exp(ke.div(y[2],ke.scalar(5))),u[0]),ke.scalar(2)),I=ke.add(ke.mul(ke.div(y[0],ke.scalar(10)),u[0]),p[0]),S=ke.div(ke.mul(ke.exp(ke.div(y[3],ke.scalar(5))),u[1]),ke.scalar(2)),T=ke.add(ke.mul(ke.div(y[1],ke.scalar(10)),u[1]),p[1]);return ke.transpose(ke.stack([ke.sub(I,g),ke.sub(T,S),ke.add(I,g),ke.add(T,S)]),[1,0])}function hk(r,l,u){return ke.tidy(()=>{const p=r.shape[0];let y=yee(ke.reshape(ke.tile(u.extra_dim,[p,1,1]),[-1,4]),ke.reshape(r,[-1,4]));y=ke.reshape(y,[p,y.shape[0]/p,4]);const g=ke.sigmoid(ke.slice(l,[0,0,1],[-1,-1,-1]));let I=ke.slice(g,[0,0,0],[-1,-1,1]);I=ke.reshape(I,[p,I.shape[1]]);const S=ke.unstack(y),T=ke.unstack(I);return{boxes:S,scores:T}})}const nd=Ze(Qe());function Ia(r,l){return nd.tidy(()=>{const u=r.shape[0],p=nd.reshape(Sa(r,l.box_encoding_predictor),[u,-1,1,4]),y=nd.reshape(Sa(r,l.class_predictor),[u,-1,3]);return{boxPredictionEncoding:p,classPrediction:y}})}const sd=Ze(Qe());function uk(r,l,u){return sd.tidy(()=>{const p=Xs(r,u.conv_0,[1,1]),y=Xs(p,u.conv_1,[2,2]),g=Xs(y,u.conv_2,[1,1]),I=Xs(g,u.conv_3,[2,2]),S=Xs(I,u.conv_4,[1,1]),T=Xs(S,u.conv_5,[2,2]),C=Xs(T,u.conv_6,[1,1]),D=Xs(C,u.conv_7,[2,2]),_=Ia(l,u.box_predictor_0),A=Ia(r,u.box_predictor_1),B=Ia(y,u.box_predictor_2),ne=Ia(I,u.box_predictor_3),te=Ia(T,u.box_predictor_4),P=Ia(D,u.box_predictor_5),ge=sd.concat([_.boxPredictionEncoding,A.boxPredictionEncoding,B.boxPredictionEncoding,ne.boxPredictionEncoding,te.boxPredictionEncoding,P.boxPredictionEncoding],1),ae=sd.concat([_.classPrediction,A.classPrediction,B.classPrediction,ne.classPrediction,te.classPrediction,P.classPrediction],1);return{boxPredictions:ge,classPredictions:ae}})}class Ys{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 Si=Ze(Qe());class sa extends En{constructor(){super("SsdMobilenetv1")}forwardInput(r){const{params:l}=this;if(!l)throw new Error("SsdMobilenetv1 - load model before inference");return Si.tidy(()=>{const u=Si.cast(r.toBatchTensor(512,!1),"float32"),p=Si.sub(Si.mul(u,Si.scalar(.007843137718737125)),Si.scalar(1)),y=ck(p,l.mobilenetv1),{boxPredictions:g,classPredictions:I}=uk(y.out,y.conv11,l.prediction_layer);return hk(g,I,l.output_layer)})}async forward(r){return this.forwardInput(await Ot(r))}async locateFaces(r,l={}){const{maxResults:u,minConfidence:p}=new Ys(l),y=await Ot(r),{boxes:g,scores:I}=this.forwardInput(y),S=g[0],T=I[0];for(let ae=1;ae<g.length;ae++)g[ae].dispose(),I[ae].dispose();const C=Array.from(await T.data()),D=.5,_=lk(S,C,u,D,p),A=y.getReshapedInputDimensions(0),B=y.inputSize,ne=B/A.width,te=B/A.height,P=S.arraySync(),ge=_.map(ae=>{const[Le,ve]=[Math.max(0,P[ae][0]),Math.min(1,P[ae][2])].map(pt=>pt*te),[Ve,at]=[Math.max(0,P[ae][1]),Math.min(1,P[ae][3])].map(pt=>pt*ne);return new Vt(C[ae],new Bc(Ve,Le,at-Ve,ve-Le),{height:y.getInputHeight(0),width:y.getInputWidth(0)})});return S.dispose(),T.dispose(),ge}getDefaultModelName(){return"ssd_mobilenetv1_model"}extractParamsFromWeigthMap(r){return ak(r)}extractParams(r){return ok(r)}}function rI(r){const l=new sa;return l.extractWeights(r),l}function m2(r){return rI(r)}class f2 extends sa{}const dk=.4,pk=[new Ke(.738768,.874946),new Ke(2.42204,2.65704),new Ke(4.30971,7.04493),new Ke(10.246,4.59428),new Ke(12.6868,11.8741)],mk=[new Ke(1.603231,2.094468),new Ke(6.041143,7.080126),new Ke(2.882459,3.518061),new Ke(4.266906,5.178857),new Ke(9.041765,10.66308)],fk=[117.001,114.697,97.404],gk="tiny_yolov2_model",yk="tiny_yolov2_separable_conv_model";const dy=r=>typeof r=="number";function tf(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(!dy(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=>dy(l.x)&&dy(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(dy)))throw new Error(`config.meanRgb has to be an array of shape [number, number, number], have: ${JSON.stringify(r.meanRgb)}`)}const Js=Ze(Qe());function ll(r){return Js.tidy(()=>{const l=Js.mul(r,Js.scalar(.10000000149011612));return Js.add(Js.relu(Js.sub(r,l)),l)})}const Zs=Ze(Qe());function vr(r,l){return Zs.tidy(()=>{let u=Zs.pad(r,[[0,0],[1,1],[1,1],[0,0]]);return u=Zs.conv2d(u,l.conv.filters,[1,1],"valid"),u=Zs.sub(u,l.bn.sub),u=Zs.mul(u,l.bn.truediv),u=Zs.add(u,l.conv.bias),ll(u)})}const Ao=Ze(Qe());function Nr(r,l){return Ao.tidy(()=>{let u=Ao.pad(r,[[0,0],[1,1],[1,1],[0,0]]);return u=Ao.separableConv2d(u,l.depthwise_filter,l.pointwise_filter,[1,1],"valid"),u=Ao.add(u,l.bias),ll(u)})}const Nx=Ze(Qe());function bee(r,l){const u=sl(r,l);function p(I,S){const T=Nx.tensor1d(r(I)),C=Nx.tensor1d(r(I));return l.push({paramPath:`${S}/sub`},{paramPath:`${S}/truediv`}),{sub:T,truediv:C}}function y(I,S,T){const C=u(I,S,3,`${T}/conv`),D=p(S,`${T}/bn`);return{conv:C,bn:D}}const g=il(r,l);return{extractConvParams:u,extractConvWithBatchNormParams:y,extractSeparableConvParams:g}}function bk(r,l,u,p){const{extractWeights:y,getRemainingWeights:g}=qn(r),I=[],{extractConvParams:S,extractConvWithBatchNormParams:T,extractSeparableConvParams:C}=bee(y,I);let D;if(l.withSeparableConvs){const[_,A,B,ne,te,P,ge,ae,Le]=p,ve=l.isFirstLayerConv2d?S(_,A,3,"conv0"):C(_,A,"conv0"),Ve=C(A,B,"conv1"),at=C(B,ne,"conv2"),pt=C(ne,te,"conv3"),$t=C(te,P,"conv4"),Gt=C(P,ge,"conv5"),qe=ae?C(ge,ae,"conv6"):void 0,ln=Le?C(ae,Le,"conv7"):void 0,bt=S(Le||ae||ge,5*u,1,"conv8");D={conv0:ve,conv1:Ve,conv2:at,conv3:pt,conv4:$t,conv5:Gt,conv6:qe,conv7:ln,conv8:bt}}else{const[_,A,B,ne,te,P,ge,ae,Le]=p,ve=T(_,A,"conv0"),Ve=T(A,B,"conv1"),at=T(B,ne,"conv2"),pt=T(ne,te,"conv3"),$t=T(te,P,"conv4"),Gt=T(P,ge,"conv5"),qe=T(ge,ae,"conv6"),ln=T(ae,Le,"conv7"),bt=S(Le,5*u,1,"conv8");D={conv0:ve,conv1:Ve,conv2:at,conv3:pt,conv4:$t,conv5:Gt,conv6:qe,conv7:ln,conv8:bt}}if(g().length!==0)throw new Error(`weights remaing after extract: ${g().length}`);return{params:D,paramMappings:I}}function wee(r,l){const u=gs(r,l);function p(S){const T=u(`${S}/sub`,1),C=u(`${S}/truediv`,1);return{sub:T,truediv:C}}function y(S){const T=u(`${S}/filters`,4),C=u(`${S}/bias`,1);return{filters:T,bias:C}}function g(S){const T=y(`${S}/conv`),C=p(`${S}/bn`);return{conv:T,bn:C}}const I=rl(u);return{extractConvParams:y,extractConvWithBatchNormParams:g,extractSeparableConvParams:I}}function wk(r,l){const u=[],{extractConvParams:p,extractConvWithBatchNormParams:y,extractSeparableConvParams:g}=wee(r,u);let I;if(l.withSeparableConvs){const S=l.filterSizes&&l.filterSizes.length||9;I={conv0:l.isFirstLayerConv2d?p("conv0"):g("conv0"),conv1:g("conv1"),conv2:g("conv2"),conv3:g("conv3"),conv4:g("conv4"),conv5:g("conv5"),conv6:S>7?g("conv6"):void 0,conv7:S>8?g("conv7"):void 0,conv8:p("conv8")}}else I={conv0:y("conv0"),conv1:y("conv1"),conv2:y("conv2"),conv3:y("conv3"),conv4:y("conv4"),conv5:y("conv5"),conv6:y("conv6"),conv7:y("conv7"),conv8:p("conv8")};return Hn(r,u),{params:I,paramMappings:u}}var nf;(function(r){r[r.XS=224]="XS",r[r.SM=320]="SM",r[r.MD=416]="MD",r[r.LG=608]="LG"})(nf||(nf={}));class Wi{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 Mt=Ze(Qe());class hl extends En{constructor(r){super("TinyYolov2");tf(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=vr(r,l.conv0);return u=Mt.maxPool(u,[2,2],[2,2],"same"),u=vr(u,l.conv1),u=Mt.maxPool(u,[2,2],[2,2],"same"),u=vr(u,l.conv2),u=Mt.maxPool(u,[2,2],[2,2],"same"),u=vr(u,l.conv3),u=Mt.maxPool(u,[2,2],[2,2],"same"),u=vr(u,l.conv4),u=Mt.maxPool(u,[2,2],[2,2],"same"),u=vr(u,l.conv5),u=Mt.maxPool(u,[2,2],[1,1],"same"),u=vr(u,l.conv6),u=vr(u,l.conv7),Sa(u,l.conv8,"valid",!1)}runMobilenet(r,l){let u=this.config.isFirstLayerConv2d?ll(Sa(r,l.conv0,"valid",!1)):Nr(r,l.conv0);return u=Mt.maxPool(u,[2,2],[2,2],"same"),u=Nr(u,l.conv1),u=Mt.maxPool(u,[2,2],[2,2],"same"),u=Nr(u,l.conv2),u=Mt.maxPool(u,[2,2],[2,2],"same"),u=Nr(u,l.conv3),u=Mt.maxPool(u,[2,2],[2,2],"same"),u=Nr(u,l.conv4),u=Mt.maxPool(u,[2,2],[2,2],"same"),u=Nr(u,l.conv5),u=Mt.maxPool(u,[2,2],[1,1],"same"),u=l.conv6?Nr(u,l.conv6):u,u=l.conv7?Nr(u,l.conv7):u,Sa(u,l.conv8,"valid",!1)}forwardInput(r,l){const{params:u}=this;if(!u)throw new Error("TinyYolov2 - load model before inference");return Mt.tidy(()=>{let p=Mt.cast(r.toBatchTensor(l,!1),"float32");return p=this.config.meanRgb?Hs(p,this.config.meanRgb):p,p=p.div(Mt.scalar(256)),this.config.withSeparableConvs?this.runMobilenet(p,u):this.runTinyYolov2(p,u)})}async forward(r,l){return await this.forwardInput(await Ot(r),l)}async detect(r,l={}){const{inputSize:u,scoreThreshold:p}=new Wi(l),y=await Ot(r),g=await this.forwardInput(y,u),I=Mt.tidy(()=>Mt.unstack(g)[0].expandDims()),S={width:y.getInputWidth(0),height:y.getInputHeight(0)},T=await this.extractBoxes(I,y.getReshapedInputDimensions(0),p);g.dispose(),I.dispose();const C=T.map(te=>te.box),D=T.map(te=>te.score),_=T.map(te=>te.classScore),A=T.map(te=>this.config.classes[te.label]),B=of(C.map(te=>te.rescale(u)),D,this.config.iouThreshold,!0),ne=B.map(te=>new ca(D[te],_[te],A[te],C[te],S));return ne}getDefaultModelName(){return""}extractParamsFromWeigthMap(r){return wk(r,this.config)}extractParams(r){const l=this.config.filterSizes||hl.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 bk(r,this.config,this.boxEncodingSize,l)}async extractBoxes(r,l,u){const{width:p,height:y}=l,g=Math.max(p,y),I=g/p,S=g/y,T=r.shape[1],C=this.config.anchors.length,[D,_,A]=Mt.tidy(()=>{const P=r.reshape([T,T,C,this.boxEncodingSize]),ge=P.slice([0,0,0,0],[T,T,C,4]),ae=P.slice([0,0,0,4],[T,T,C,1]),Le=this.withClassScores?Mt.softmax(P.slice([0,0,0,5],[T,T,C,this.config.classes.length]),3):Mt.scalar(0);return[ge,ae,Le]}),B=[],ne=await _.array(),te=await D.array();for(let P=0;P<T;P++)for(let ge=0;ge<T;ge++)for(let ae=0;ae<C;ae++){const Le=Fc(ne[P][ge][ae][0]);if(!u||Le>u){const ve=(ge+Fc(te[P][ge][ae][0]))/T*I,Ve=(P+Fc(te[P][ge][ae][1]))/T*S,at=Math.exp(te[P][ge][ae][2])*this.config.anchors[ae].x/T*I,pt=Math.exp(te[P][ge][ae][3])*this.config.anchors[ae].y/T*S,$t=ve-at/2,Gt=Ve-pt/2,qe={row:P,col:ge,anchor:ae},{classScore:ln,label:bt}=this.withClassScores?await this.extractPredictedClass(A,qe):{classScore:1,label:0};B.push({box:new Pc($t,Gt,$t+at,Gt+pt),score:Le,classScore:Le*ln,label:bt,...qe})}}return D.dispose(),_.dispose(),A.dispose(),B}async extractPredictedClass(r,l){const{row:u,col:p,anchor:y}=l,g=await r.array();return Array(this.config.classes.length).fill(0).map((I,S)=>g[u][p][y][S]).map((I,S)=>({classScore:I,label:S})).reduce((I,S)=>I.classScore>S.classScore?I:S)}}hl.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024];class Dc extends hl{constructor(r=!0){const l=Object.assign({},{withSeparableConvs:r,iouThreshold:dk,classes:["face"]},r?{anchors:mk,meanRgb:fk}:{anchors:pk,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 Vt(p.score,p.relativeBox,{width:p.imageWidth,height:p.imageHeight}))}getDefaultModelName(){return this.withSeparableConvs?yk:gk}extractParamsFromWeigthMap(r){return super.extractParamsFromWeigthMap(r)}}function d2(r,l=!0){const u=new Dc(l);return u.extractWeights(r),u}class sf extends Wi{constructor(){super(...arguments);this._name="TinyFaceDetectorOptions"}}class qs{async then(r){return r(await this.run())}async run(){throw new Error("ComposableTask - run is not implemented")}}const Cx=Ze(Qe());async function xa(r,l,u,p,y=({alignedRect:g})=>g){const g=r.map(T=>oo(T)?y(T):T.detection),I=p||(l instanceof Cx.Tensor?await oa(l,g):await ra(l,g)),S=await u(I);return I.forEach(T=>T instanceof Cx.Tensor&&T.dispose()),S}async function ul(r,l,u,p,y){return xa([r],l,async g=>u(g[0]),p,y)}const Lk=.4,Sk=[new Ke(1.603231,2.094468),new Ke(6.041143,7.080126),new Ke(2.882459,3.518061),new Ke(4.266906,5.178857),new Ke(9.041765,10.66308)],Ik=[117.001,114.697,97.404];class kc extends hl{constructor(){const r={withSeparableConvs:!0,iouThreshold:Lk,classes:["face"],anchors:Sk,meanRgb:Ik,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 Vt(p.score,p.relativeBox,{width:p.imageWidth,height:p.imageHeight}))}getDefaultModelName(){return"tiny_face_detector_model"}extractParamsFromWeigthMap(r){return super.extractParamsFromWeigthMap(r)}}const ft={ssdMobilenetv1:new sa,tinyFaceDetector:new kc,tinyYolov2:new Dc,faceLandmark68Net:new Wc,faceLandmark68TinyNet:new gf,faceRecognitionNet:new _c,faceExpressionNet:new bf,ageGenderNet:new vf},aI=(r,l)=>ft.ssdMobilenetv1.locateFaces(r,l),b2=(r,l)=>ft.tinyFaceDetector.locateFaces(r,l),w2=(r,l)=>ft.tinyYolov2.locateFaces(r,l),cI=r=>ft.faceLandmark68Net.detectLandmarks(r),L2=r=>ft.faceLandmark68TinyNet.detectLandmarks(r),S2=r=>ft.faceRecognitionNet.computeFaceDescriptor(r),I2=r=>ft.faceExpressionNet.predictExpressions(r),x2=r=>ft.ageGenderNet.predictAgeAndGender(r),lI=r=>ft.ssdMobilenetv1.load(r),T2=r=>ft.tinyFaceDetector.load(r),A2=r=>ft.tinyYolov2.load(r),v2=r=>ft.faceLandmark68Net.load(r),N2=r=>ft.faceLandmark68TinyNet.load(r),C2=r=>ft.faceRecognitionNet.load(r),R2=r=>ft.faceExpressionNet.load(r),O2=r=>ft.ageGenderNet.load(r),E2=lI,D2=aI,k2=cI;class xk extends qs{constructor(r,l,u){super();this.parentTask=r;this.input=l;this.extractedFaces=u}}class od extends xk{async run(){const r=await this.parentTask,l=await xa(r,this.input,async u=>await Promise.all(u.map(p=>ft.faceExpressionNet.predictExpressions(p))),this.extractedFaces);return r.map((u,p)=>Ou(u,l[p]))}withAgeAndGender(){return new id(this,this.input)}}class ad extends xk{async run(){const r=await this.parentTask;if(!r)return;const l=await ul(r,this.input,u=>ft.faceExpressionNet.predictExpressions(u),this.extractedFaces);return Ou(r,l)}withAgeAndGender(){return new rd(this,this.input)}}class ml extends od{withAgeAndGender(){return new dl(this,this.input)}withFaceDescriptors(){return new io(this,this.input)}}class fl extends ad{withAgeAndGender(){return new pl(this,this.input)}withFaceDescriptor(){return new ro(this,this.input)}}class Tk extends qs{constructor(r,l,u){super();this.parentTask=r;this.input=l;this.extractedFaces=u}}class id extends Tk{async run(){const r=await this.parentTask,l=await xa(r,this.input,async u=>await Promise.all(u.map(p=>ft.ageGenderNet.predictAgeAndGender(p))),this.extractedFaces);return r.map((u,p)=>{const{age:y,gender:g,genderProbability:I}=l[p];return Du(Ru(u,g,I),y)})}withFaceExpressions(){return new od(this,this.input)}}class rd extends Tk{async run(){const r=await this.parentTask;if(!r)return;const{age:l,gender:u,genderProbability:p}=await ul(r,this.input,y=>ft.ageGenderNet.predictAgeAndGender(y),this.extractedFaces);return Du(Ru(r,u,p),l)}withFaceExpressions(){return new ad(this,this.input)}}class dl extends id{withFaceExpressions(){return new ml(this,this.input)}withFaceDescriptors(){return new io(this,this.input)}}class pl extends rd{withFaceExpressions(){return new fl(this,this.input)}withFaceDescriptor(){return new ro(this,this.input)}}class mf extends qs{constructor(r,l){super();this.parentTask=r;this.input=l}}class io extends mf{async run(){const r=await this.parentTask,l=await xa(r,this.input,u=>Promise.all(u.map(p=>ft.faceRecognitionNet.computeFaceDescriptor(p))),null,u=>u.landmarks.align(null,{useDlibAlignment:!0}));return l.map((u,p)=>Eu(r[p],u))}withFaceExpressions(){return new ml(this,this.input)}withAgeAndGender(){return new dl(this,this.input)}}class ro extends mf{async run(){const r=await this.parentTask;if(!r)return;const l=await ul(r,this.input,u=>ft.faceRecognitionNet.computeFaceDescriptor(u),null,u=>u.landmarks.align(null,{useDlibAlignment:!0}));return Eu(r,l)}withFaceExpressions(){return new fl(this,this.input)}withAgeAndGender(){return new pl(this,this.input)}}const cd=Ze(Qe());class uf extends qs{constructor(r,l,u){super();this.parentTask=r;this.input=l;this.useTinyLandmarkNet=u}get landmarkNet(){return this.useTinyLandmarkNet?ft.faceLandmark68TinyNet:ft.faceLandmark68Net}}class df extends uf{async run(){const r=await this.parentTask,l=r.map(y=>y.detection),u=this.input instanceof cd.Tensor?await oa(this.input,l):await ra(this.input,l),p=await Promise.all(u.map(y=>this.landmarkNet.detectLandmarks(y)));return u.forEach(y=>y instanceof cd.Tensor&&y.dispose()),r.map((y,g)=>ia(y,p[g]))}withFaceExpressions(){return new ml(this,this.input)}withAgeAndGender(){return new dl(this,this.input)}withFaceDescriptors(){return new io(this,this.input)}}class pf extends uf{async run(){const r=await this.parentTask;if(!r)return;const{detection:l}=r,u=this.input instanceof cd.Tensor?await oa(this.input,[l]):await ra(this.input,[l]),p=await this.landmarkNet.detectLandmarks(u[0]);return u.forEach(y=>y instanceof cd.Tensor&&y.dispose()),ia(r,p)}withFaceExpressions(){return new fl(this,this.input)}withAgeAndGender(){return new pl(this,this.input)}withFaceDescriptor(){return new ro(this,this.input)}}class lf extends qs{constructor(r,l=new Ys){super();this.input=r;this.options=l}}class Cu extends lf{async run(){const{input:r,options:l}=this,u=l instanceof sf?p=>ft.tinyFaceDetector.locateFaces(p,l):l instanceof Ys?p=>ft.ssdMobilenetv1.locateFaces(p,l):l instanceof Wi?p=>ft.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=>ao({},u)))})}withFaceLandmarks(r=!1){return new df(this.runAndExtendWithFaceDetections(),this.input,r)}withFaceExpressions(){return new od(this.runAndExtendWithFaceDetections(),this.input)}withAgeAndGender(){return new id(this.runAndExtendWithFaceDetections(),this.input)}}class hf extends lf{async run(){const r=await new Cu(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?ao({},l):void 0)})}withFaceLandmarks(r=!1){return new pf(this.runAndExtendWithFaceDetection(),this.input,r)}withFaceExpressions(){return new ad(this.runAndExtendWithFaceDetection(),this.input)}withAgeAndGender(){return new rd(this.runAndExtendWithFaceDetection(),this.input)}}function F2(r,l=new Ys){return new hf(r,l)}function Nu(r,l=new Ys){return new Cu(r,l)}async function hI(r,l){return console.warn("allFacesSsdMobilenetv1 is deprecated and will be removed soon, use the high level api instead"),await Nu(r,new Ys(l?{minConfidence:l}:{})).withFaceLandmarks().withFaceDescriptors()}async function _2(r,l={}){return console.warn("allFacesTinyYolov2 is deprecated and will be removed soon, use the high level api instead"),await Nu(r,new Wi(l)).withFaceLandmarks().withFaceDescriptors()}const W2=hI;function wf(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((y,g)=>y-p[g]).reduce((y,g)=>y+Math.pow(g,2),0))}class uI{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 y=()=>`person ${p++}`;this._labeledDescriptors=u.map(g=>{if(g instanceof po)return g;if(g instanceof Float32Array)return new po(y(),[g]);if(g.descriptor&&g.descriptor instanceof Float32Array)return new po(y(),[g.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=>wf(u,r)).reduce((u,p)=>u+p,0)/(l.length||1)}matchDescriptor(r){return this.labeledDescriptors.map(({descriptors:l,label:u})=>new _u(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 _u("unknown",l.distance)}toJSON(){return{distanceThreshold:this.distanceThreshold,labeledDescriptors:this.labeledDescriptors.map(r=>r.toJSON())}}static fromJSON(r){const l=r.labeledDescriptors.map(u=>po.fromJSON(u));return new uI(l,r.distanceThreshold)}}function p2(r){const l=new kc;return l.extractWeights(r),l}function oI(r,l){const{width:u,height:p}=new rs(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(y=>oI(y,{width:u,height:p}));if(oo(r)){const y=r.detection.forSize(u,p),g=r.unshiftedLandmarks.forSize(y.box.width,y.box.height);return ia(ao(r,y),g)}return mi(r)?ao(r,r.detection.forSize(u,p)):r instanceof Rs||r instanceof Vt?r.forSize(u,p):r}var h2="0.8.5";return H2();})();
|
|
/**
|
|
* @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
|