face-api/dist/face-api.esm.js

3977 lines
935 KiB
JavaScript

var zu=Object.defineProperty,fE=Object.prototype.hasOwnProperty,ln=(e,t)=>()=>(t||(t={exports:{}},e(t.exports,t)),t.exports),pL=e=>zu(e,"__esModule",{value:!0}),Ee=(e,t)=>{pL(e);for(var s in t)zu(e,s,{get:t[s],enumerable:!0})},gE=(e,t)=>{if(pL(e),typeof t=="object"||typeof t=="function")for(let s in t)!fE.call(e,s)&&s!=="default"&&zu(e,s,{get:()=>t[s],enumerable:!0});return e},mc=e=>e&&e.__esModule?e:gE(zu({},"default",{value:e,enumerable:!0}),e);var hL=ln((uL,cg)=>{(function(e,t,s){function n(a){var l=this,c=o();l.next=function(){var p=2091639*l.s0+l.c*23283064365386963e-26;return l.s0=l.s1,l.s1=l.s2,l.s2=p-(l.c=p|0)},l.c=1,l.s0=c(" "),l.s1=c(" "),l.s2=c(" "),l.s0-=c(a),l.s0<0&&(l.s0+=1),l.s1-=c(a),l.s1<0&&(l.s1+=1),l.s2-=c(a),l.s2<0&&(l.s2+=1),c=null}function i(a,l){return l.c=a.c,l.s0=a.s0,l.s1=a.s1,l.s2=a.s2,l}function r(a,l){var c=new n(a),p=l&&l.state,u=c.next;return u.int32=function(){return c.next()*4294967296|0},u.double=function(){return u()+(u()*2097152|0)*11102230246251565e-32},u.quick=u,p&&(typeof p=="object"&&i(p,c),u.state=function(){return i(c,{})}),u}function o(){var a=4022871197,l=function(c){c=c.toString();for(var p=0;p<c.length;p++){a+=c.charCodeAt(p);var u=.02519603282416938*a;a=u>>>0,u-=a,u*=a,a=u>>>0,u-=a,a+=u*4294967296}return(a>>>0)*23283064365386963e-26};return l}t&&t.exports?t.exports=r:s&&s.amd?s(function(){return r}):this.alea=r})(uL,typeof cg=="object"&&cg,typeof define=="function"&&define)});var mL=ln((dL,pg)=>{(function(e,t,s){function n(o){var a=this,l="";a.x=0,a.y=0,a.z=0,a.w=0,a.next=function(){var p=a.x^a.x<<11;return a.x=a.y,a.y=a.z,a.z=a.w,a.w^=a.w>>>19^p^p>>>8},o===(o|0)?a.x=o:l+=o;for(var c=0;c<l.length+64;c++)a.x^=l.charCodeAt(c)|0,a.next()}function i(o,a){return a.x=o.x,a.y=o.y,a.z=o.z,a.w=o.w,a}function r(o,a){var l=new n(o),c=a&&a.state,p=function(){return(l.next()>>>0)/4294967296};return p.double=function(){do var u=l.next()>>>11,h=(l.next()>>>0)/4294967296,d=(u+h)/(1<<21);while(d===0);return d},p.int32=l.next,p.quick=p,c&&(typeof c=="object"&&i(c,l),p.state=function(){return i(l,{})}),p}t&&t.exports?t.exports=r:s&&s.amd?s(function(){return r}):this.xor128=r})(dL,typeof pg=="object"&&pg,typeof define=="function"&&define)});var gL=ln((fL,ug)=>{(function(e,t,s){function n(o){var a=this,l="";a.next=function(){var p=a.x^a.x>>>2;return a.x=a.y,a.y=a.z,a.z=a.w,a.w=a.v,(a.d=a.d+362437|0)+(a.v=a.v^a.v<<4^(p^p<<1))|0},a.x=0,a.y=0,a.z=0,a.w=0,a.v=0,o===(o|0)?a.x=o:l+=o;for(var c=0;c<l.length+64;c++)a.x^=l.charCodeAt(c)|0,c==l.length&&(a.d=a.x<<10^a.x>>>4),a.next()}function i(o,a){return a.x=o.x,a.y=o.y,a.z=o.z,a.w=o.w,a.v=o.v,a.d=o.d,a}function r(o,a){var l=new n(o),c=a&&a.state,p=function(){return(l.next()>>>0)/4294967296};return p.double=function(){do var u=l.next()>>>11,h=(l.next()>>>0)/4294967296,d=(u+h)/(1<<21);while(d===0);return d},p.int32=l.next,p.quick=p,c&&(typeof c=="object"&&i(c,l),p.state=function(){return i(l,{})}),p}t&&t.exports?t.exports=r:s&&s.amd?s(function(){return r}):this.xorwow=r})(fL,typeof ug=="object"&&ug,typeof define=="function"&&define)});var bL=ln((yL,hg)=>{(function(e,t,s){function n(o){var a=this;a.next=function(){var c=a.x,p=a.i,u,h,d;return u=c[p],u^=u>>>7,h=u^u<<24,u=c[p+1&7],h^=u^u>>>10,u=c[p+3&7],h^=u^u>>>3,u=c[p+4&7],h^=u^u<<7,u=c[p+7&7],u=u^u<<13,h^=u^u<<9,c[p]=h,a.i=p+1&7,h};function l(c,p){var u,h,d=[];if(p===(p|0))h=d[0]=p;else for(p=""+p,u=0;u<p.length;++u)d[u&7]=d[u&7]<<15^p.charCodeAt(u)+d[u+1&7]<<13;for(;d.length<8;)d.push(0);for(u=0;u<8&&d[u]===0;++u);for(u==8?h=d[7]=-1:h=d[u],c.x=d,c.i=0,u=256;u>0;--u)c.next()}l(a,o)}function i(o,a){return a.x=o.x.slice(),a.i=o.i,a}function r(o,a){o==null&&(o=+new Date);var l=new n(o),c=a&&a.state,p=function(){return(l.next()>>>0)/4294967296};return p.double=function(){do var u=l.next()>>>11,h=(l.next()>>>0)/4294967296,d=(u+h)/(1<<21);while(d===0);return d},p.int32=l.next,p.quick=p,c&&(c.x&&i(c,l),p.state=function(){return i(l,{})}),p}t&&t.exports?t.exports=r:s&&s.amd?s(function(){return r}):this.xorshift7=r})(yL,typeof hg=="object"&&hg,typeof define=="function"&&define)});var xL=ln((wL,dg)=>{(function(e,t,s){function n(o){var a=this;a.next=function(){var c=a.w,p=a.X,u=a.i,h,d;return a.w=c=c+1640531527|0,d=p[u+34&127],h=p[u=u+1&127],d^=d<<13,h^=h<<17,d^=d>>>15,h^=h>>>12,d=p[u]=d^h,a.i=u,d+(c^c>>>16)|0};function l(c,p){var u,h,d,m,f,g=[],y=128;for(p===(p|0)?(h=p,p=null):(p=p+"\0",h=0,y=Math.max(y,p.length)),d=0,m=-32;m<y;++m)p&&(h^=p.charCodeAt((m+32)%p.length)),m===0&&(f=h),h^=h<<10,h^=h>>>15,h^=h<<4,h^=h>>>13,m>=0&&(f=f+1640531527|0,u=g[m&127]^=h+f,d=u==0?d+1:0);for(d>=128&&(g[(p&&p.length||0)&127]=-1),d=127,m=4*128;m>0;--m)h=g[d+34&127],u=g[d=d+1&127],h^=h<<13,u^=u<<17,h^=h>>>15,u^=u>>>12,g[d]=h^u;c.w=f,c.X=g,c.i=d}l(a,o)}function i(o,a){return a.i=o.i,a.w=o.w,a.X=o.X.slice(),a}function r(o,a){o==null&&(o=+new Date);var l=new n(o),c=a&&a.state,p=function(){return(l.next()>>>0)/4294967296};return p.double=function(){do var u=l.next()>>>11,h=(l.next()>>>0)/4294967296,d=(u+h)/(1<<21);while(d===0);return d},p.int32=l.next,p.quick=p,c&&(c.X&&i(c,l),p.state=function(){return i(l,{})}),p}t&&t.exports?t.exports=r:s&&s.amd?s(function(){return r}):this.xor4096=r})(wL,typeof dg=="object"&&dg,typeof define=="function"&&define)});var SL=ln((LL,mg)=>{(function(e,t,s){function n(o){var a=this,l="";a.next=function(){var p=a.b,u=a.c,h=a.d,d=a.a;return p=p<<25^p>>>7^u,u=u-h|0,h=h<<24^h>>>8^d,d=d-p|0,a.b=p=p<<20^p>>>12^u,a.c=u=u-h|0,a.d=h<<16^u>>>16^d,a.a=d-p|0},a.a=0,a.b=0,a.c=2654435769|0,a.d=1367130551,o===Math.floor(o)?(a.a=o/4294967296|0,a.b=o|0):l+=o;for(var c=0;c<l.length+20;c++)a.b^=l.charCodeAt(c)|0,a.next()}function i(o,a){return a.a=o.a,a.b=o.b,a.c=o.c,a.d=o.d,a}function r(o,a){var l=new n(o),c=a&&a.state,p=function(){return(l.next()>>>0)/4294967296};return p.double=function(){do var u=l.next()>>>11,h=(l.next()>>>0)/4294967296,d=(u+h)/(1<<21);while(d===0);return d},p.int32=l.next,p.quick=p,c&&(typeof c=="object"&&i(c,l),p.state=function(){return i(l,{})}),p}t&&t.exports?t.exports=r:s&&s.amd?s(function(){return r}):this.tychei=r})(LL,typeof mg=="object"&&mg,typeof define=="function"&&define)});var IL=ln(()=>{});var vL=ln((JG,Pu)=>{(function(e,t){var s=this,n=256,i=6,r=52,o="random",a=t.pow(n,i),l=t.pow(2,r),c=l*2,p=n-1,u;function h(x,T,A){var _=[];T=T==!0?{entropy:!0}:T||{};var E=g(f(T.entropy?[x,w(e)]:x??y(),3),_),F=new d(_),D=function(){for(var M=F.g(i),P=a,B=0;M<l;)M=(M+B)*n,P*=n,B=F.g(1);for(;M>=c;)M/=2,P/=2,B>>>=1;return(M+B)/P};return D.int32=function(){return F.g(4)|0},D.quick=function(){return F.g(4)/4294967296},D.double=D,g(w(F.S),e),(T.pass||A||function(M,P,B,Y){return Y&&(Y.S&&m(Y,F),M.state=function(){return m(F,{})}),B?(t[o]=M,P):M})(D,E,"global"in T?T.global:this==t,T.state)}t["seed"+o]=h;function d(x){var T,A=x.length,_=this,E=0,F=_.i=_.j=0,D=_.S=[];for(A||(x=[A++]);E<n;)D[E]=E++;for(E=0;E<n;E++)D[E]=D[F=p&F+x[E%A]+(T=D[E])],D[F]=T;(_.g=function(M){for(var P,B=0,Y=_.i,q=_.j,K=_.S;M--;)P=K[Y=p&Y+1],B=B*n+K[p&(K[Y]=K[q=p&q+P])+(K[q]=P)];return _.i=Y,_.j=q,B})(n)}function m(x,T){return T.i=x.i,T.j=x.j,T.S=x.S.slice(),T}function f(x,T){var A=[],_=typeof x,E;if(T&&_=="object")for(E in x)try{A.push(f(x[E],T-1))}catch(F){}return A.length?A:_=="string"?x:x+"\0"}function g(x,T){for(var A=x+"",_,E=0;E<A.length;)T[p&E]=p&(_^=T[p&E]*19)+A.charCodeAt(E++);return w(T)}function y(){try{var x;return u&&(x=u.randomBytes)?x=x(n):(x=new Uint8Array(n),(s.crypto||s.msCrypto).getRandomValues(x)),w(x)}catch(_){var T=s.navigator,A=T&&T.plugins;return[+new Date,s,A,s.screen,w(e)]}}function w(x){return String.fromCharCode.apply(0,x)}if(g(t.random(),e),typeof Pu=="object"&&Pu.exports){Pu.exports=h;try{u=IL()}catch(x){}}else typeof define=="function"&&define.amd&&define(function(){return h})})([],Math)});var fc=ln((ZG,TL)=>{var yE=hL(),bE=mL(),wE=gL(),xE=bL(),LE=xL(),SE=SL(),fo=vL();fo.alea=yE;fo.xor128=bE;fo.xorwow=wE;fo.xorshift7=xE;fo.xor4096=LE;fo.tychei=SE;TL.exports=fo});var AL=ln(()=>{});var NL=ln(()=>{});var RL=ln((IE,CL)=>{Ee(IE,{isNodejs:()=>vE});function vE(){return typeof global=="object"&&!0&&typeof CL!="undefined"&&typeof process!="undefined"&&!!process.version}});const TE=1e-7,AE=1e-4;class gc{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 go{time(e){return z("time")}read(e){return z("read")}readSync(e){return z("readSync")}numDataIds(){return z("numDataIds")}disposeData(e){return z("disposeData")}write(e,t,s){return z("write")}move(e,t,s,n){return z("move")}memory(){return z("memory")}floatPrecision(){return z("floatPrecision")}epsilon(){return this.floatPrecision()===32?TE:AE}batchMatMul(e,t,s,n){return z("batchMatMul")}fusedBatchMatMul({a:e,b:t,transposeA:s,transposeB:n,bias:i,activation:r,preluActivationWeights:o}){return z("fusedBatchMatMul")}slice(e,t,s){return z("slice")}stridedSlice(e,t,s,n){return z("stridedSlice")}unstack(e,t){return z("unstack")}reverse(e,t){return z("reverse")}concat(e,t){return z("concat")}neg(e){return z("neg")}add(e,t){return z("add")}addN(e){return z("addN")}subtract(e,t){return z("subtract")}multiply(e,t){return z("multiply")}realDivide(e,t){return z("realDivide")}floorDiv(e,t){return z("floorDiv")}sum(e,t){return z("sum")}prod(e,t){return z("prod")}unsortedSegmentSum(e,t,s){return z("unsortedSegmentSum")}argMin(e,t){return z("argMin")}argMax(e,t){return z("argMax")}equal(e,t){return z("equal")}notEqual(e,t){return z("notEqual")}less(e,t){return z("less")}lessEqual(e,t){return z("lessEqual")}greater(e,t){return z("greater")}greaterEqual(e,t){return z("greaterEqual")}logicalNot(e){return z("logicalNot")}logicalAnd(e,t){return z("logicalAnd")}logicalOr(e,t){return z("logicalOr")}where(e){return z("where")}select(e,t,s){return z("select")}topk(e,t,s){return z("topk")}min(e,t){return z("min")}minimum(e,t){return z("minimum")}mod(e,t){return z("mod")}max(e,t){return z("max")}maximum(e,t){return z("maximum")}all(e,t){return z("all")}any(e,t){return z("any")}squaredDifference(e,t){return z("squaredDifference")}ceil(e){return z("ceil")}floor(e){return z("floor")}round(e){return z("round")}sign(e){return z("sign")}isNaN(e){return z("isNaN")}isInf(e){return z("isInf")}isFinite(e){return z("isFinite")}pow(e,t){return z("pow")}exp(e){return z("exp")}expm1(e){return z("expm1")}softmax(e,t){return z("softmax")}log(e){return z("log")}log1p(e){return z("log1p")}sqrt(e){return z("sqrt")}rsqrt(e){return z("rsqrt")}square(e){return z("square")}reciprocal(e){return z("reciprocal")}relu(e){return z("relu")}relu6(e){return z("relu6")}prelu(e,t){return z("prelu")}elu(e){return z("elu")}eluDer(e,t){return z("eluDer")}selu(e){return z("selu")}int(e){return z("int")}clip(e,t,s){return z("clip")}abs(e){return z("abs")}complexAbs(e){return z("complexAbs")}sigmoid(e){return z("sigmoid")}softplus(e){return z("softplus")}sin(e){return z("sin")}cos(e){return z("cos")}tan(e){return z("tan")}asin(e){return z("asin")}acos(e){return z("acos")}atan(e){return z("atan")}atan2(e,t){return z("atan2")}sinh(e){return z("sinh")}cosh(e){return z("cosh")}tanh(e){return z("tanh")}asinh(e){return z("asinh")}acosh(e){return z("acosh")}atanh(e){return z("atanh")}erf(e){return z("erf")}step(e,t){return z("step")}fusedConv2d({input:e,filter:t,convInfo:s,bias:n,activation:i,preluActivationWeights:r}){return z("fusedConv2d")}conv2d(e,t,s){return z("conv2d")}conv2dDerInput(e,t,s){return z("conv2dDerInput")}conv2dDerFilter(e,t,s){return z("conv2dDerFilter")}fusedDepthwiseConv2D({input:e,filter:t,convInfo:s,bias:n,activation:i,preluActivationWeights:r}){return z("fusedDepthwiseConv2D")}depthwiseConv2D(e,t,s){return z("depthwiseConv2D")}depthwiseConv2DDerInput(e,t,s){return z("depthwiseConv2DDerInput")}depthwiseConv2DDerFilter(e,t,s){return z("depthwiseConv2DDerFilter")}conv3d(e,t,s){return z("conv3d")}conv3dDerInput(e,t,s){return z("conv3dDerInput")}conv3dDerFilter(e,t,s){return z("conv3dDerFilter")}maxPool(e,t){return z("maxPool")}maxPoolBackprop(e,t,s,n){return z("maxPoolBackprop")}avgPool(e,t){return z("avgPool")}avgPoolBackprop(e,t,s){return z("avgPoolBackprop")}avgPool3d(e,t){return z("avgPool3d")}avgPool3dBackprop(e,t,s){return z("avgPool3dBackprop")}maxPool3d(e,t){return z("maxPool3d")}maxPool3dBackprop(e,t,s,n){return z("maxPool3dBackprop")}reshape(e,t){return z("reshape")}cast(e,t){return z("cast")}tile(e,t){return z("tile")}pad(e,t,s){return z("pad")}transpose(e,t){return z("transpose")}gather(e,t,s){return z("gather")}gatherND(e,t){return z("gatherND")}scatterND(e,t,s){return z("scatterND")}batchToSpaceND(e,t,s){return z("batchToSpaceND")}spaceToBatchND(e,t,s){return z("spaceToBatchND")}resizeBilinear(e,t,s,n){return z("resizeBilinear")}resizeBilinearBackprop(e,t,s){return z("resizeBilinearBackprop")}resizeNearestNeighbor(e,t,s,n){return z("resizeNearestNeighbor")}resizeNearestNeighborBackprop(e,t,s){return z("resizeNearestNeighborBackprop")}batchNorm(e,t,s,n,i,r){return z("batchNorm")}localResponseNormalization4D(e,t,s,n,i){return z("localResponseNormalization4D")}LRNGrad(e,t,s,n,i,r,o){return z("LRNGrad")}multinomial(e,t,s,n){return z("multinomial")}oneHot(e,t,s,n){return z("oneHot")}cumsum(e,t,s,n){return z("cumsum")}nonMaxSuppression(e,t,s,n,i){return z("nonMaxSuppression")}fft(e){return z("fft")}ifft(e){return z("ifft")}complex(e,t){return z("complex")}real(e){return z("real")}imag(e){return z("imag")}cropAndResize(e,t,s,n,i,r){return z("cropAndResize")}depthToSpace(e,t,s){return z("depthToSpace")}split(e,t,s){return z("split")}sparseToDense(e,t,s,n){return z("sparseToDense")}diag(e){return z("diag")}fill(e,t,s){return z("fill")}onesLike(e){return z("onesLike")}zerosLike(e){return z("zerosLike")}linspace(e,t,s){return z("linspace")}dispose(){return z("dispose")}}function z(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}const OL="tfjsflags";class fg{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,s){if(this.flagRegistry[e]={evaluationFn:t,setHook:s},this.urlFlags[e]!=null){const n=this.urlFlags[e];console.warn(`Setting feature override from URL ${e}: ${n}.`),this.set(e,n)}}async getAsync(e){return e in this.flags?this.flags[e]:(this.flags[e]=await this.evaluateFlag(e),this.flags[e])}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(t instanceof Promise)throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(this.flagRegistry[e]==null)throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,this.flagRegistry[e].setHook!=null&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(this.flagRegistry[e]==null)throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(typeof this.global=="undefined"||typeof this.global.location=="undefined"||typeof this.global.location.search=="undefined")return;const e=NE(this.global.location.search);if(OL in e){const t=e[OL].split(",");t.forEach(s=>{const[n,i]=s.split(":");this.urlFlags[n]=CE(n,i)})}}}function NE(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(s,...n)=>(RE(t,n[0],n[1]),n.join("="))),t}function RE(e,t,s){e[decodeURIComponent(t)]=decodeURIComponent(s||"")}function CE(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 W(){return gg}let gg=null;function EL(e){gg=e}let yg;function bg(){if(yg==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");yg=e}return yg}function OE(){const e=bg();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function wg(e,t){const s=OE();if(s.has(e))return s.get(e);{const n=t();return s.set(e,n),s.get(e)}}const yo="Abs",nr="Acos",ir="Acosh",Kn="Add",yc="AddN",xg="All",Lg="Any",bc="ArgMax",wc="ArgMin",rr="Asin",or="Asinh",ar="Atan",lr="Atanh",bo="Atan2",Si="AvgPool",wo="AvgPoolBackprop",xc="AvgPool3D",Sg="AvgPool3DBackprop",Lc="BatchMatMul",Sc="BatchToSpaceND",Ic="BroadcastTo",Ii="Cast",cr="Ceil",pr="ClipByValue",vc="Complex",xo="Concat",Tc="Conv2D",Ig="Conv2DBackpropFilter",Ac="Conv2DBackpropInput",Nc="Conv3D",vg="Conv3DBackpropFilterV2",Tg="Conv3DBackpropInputV2",Xn="Cos",ur="Cosh",Cc="Cumsum",Ag="CropAndResize",Ng="DepthToSpace",Rc="DepthwiseConv2dNative",Cg="DepthwiseConv2dNativeBackpropFilter",Rg="DepthwiseConv2dNativeBackpropInput",Og="Diag",Lo="Dilation2D",Oa="Dilation2DBackpropInput",Ea="Dilation2DBackpropFilter",Jn="Div",hr="Elu",Eg="EluGrad",dr="Erf",_g="Equal",mr="Exp",fr="Expm1",Oc="FFT",kg="Fill",So="FlipLeftRight",gr="Floor",Ec="FloorDiv",vi="FusedBatchNorm",_c="GatherV2",Dg="GatherNd",Fg="Greater",kc="GreaterEqual",Ti="Identity",Dc="IFFT",Fc="Imag",yr="IsFinite",br="IsInf",wr="IsNan",Mg="Less",Ug="LessEqual",$g="LinSpace",xr="Log",Lr="Log1p",Wg="LogicalAnd",_a="LogicalNot",zg="LogicalOr",Mc="LogSoftmax",Uc="LRN",Pg="LRNBackprop",Ai="Max",$c="Maximum",Ni="MaxPool",Io="MaxPoolBackprop",Wc="MaxPool3D",Bg="MaxPool3DBackprop",vo="MaxPoolWithArgmax",EE="Mean",zc="Min",Pc="Minimum",Bc="Mod",Sr="Multiply",jc="Negate",ka="NotEqual",Vc="NonMaxSuppressionV3",To="NonMaxSuppressionV4",Ao="NonMaxSuppressionV5",Gc="OnesLike",qc="OneHot",No="PadV2",_E="Pool",Hc="Pow",Yc="Prelu",jg="Prod",Vg="Range",Kc="Real",Ir="Reciprocal",Xc="Relu",Ci="Reshape",Jc="ResizeNearestNeighbor",Gg="ResizeNearestNeighborGrad",Zc="ResizeBilinear",qg="ResizeBilinearGrad",Qc="Relu6",ep="Reverse",vr="Round",Tr="Rsqrt",Hg="ScatterNd",tp="SelectV2",Ar="Selu",Co="Slice",Zn="Sin",Nr="Sinh",Cr="Sign",Rr="Sigmoid",Or="Softplus",Er="Sqrt",sp="Sum",Ro="SpaceToBatchND",np="SplitV",ip="Softmax",Qn="SquaredDifference",Oo="Square",_r="Sub",Yg="SparseToDense",Kg="StridedSlice",ei="Tan",kr="Tanh",rp="Tile",Xg="TopK",Ri="Transpose",Eo="Unique",op="Unpack",ap="UnsortedSegmentSum",lp="ZerosLike",Dr="Step",Da="FromPixels",_o="RotateWithOffset",Bu="_FusedMatMul",ju="FusedConv2D",Vu="FusedDepthwiseConv2D";const Fa=wg("kernelRegistry",()=>new Map),cp=wg("gradRegistry",()=>new Map);function pp(e,t){const s=Jg(e,t);return Fa.get(s)}function Gu(e){return cp.get(e)}function up(e){const t=Fa.entries(),s=[];for(;;){const{done:n,value:i}=t.next();if(n)break;const[r,o]=i,[a]=r.split("_");a===e&&s.push(o)}return s}function Ma(e){const{kernelName:t,backendName:s}=e,n=Jg(t,s);Fa.has(n)&&console.warn(`The kernel '${t}' for backend '${s}' is already registered`),Fa.set(n,e)}function Zg(e){const{kernelName:t}=e;cp.has(t)&&(W().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${t}'`)),cp.set(t,e)}function kE(e,t){const s=Jg(e,t);if(!Fa.has(s))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);Fa.delete(s)}function DE(e){if(!cp.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);cp.delete(e)}function FE(e,t){const s=up(e);s.forEach(n=>{const i=Object.assign({},n,{backendName:t});Ma(i)})}function Jg(e,t){return`${t}_${e}`}const N={};Ee(N,{arraysEqual:()=>Nt,assert:()=>I,assertNonNegativeIntegerDimensions:()=>dp,assertNonNull:()=>qs,assertShapesMatch:()=>Se,bytesFromStringArray:()=>ry,bytesPerElement:()=>iy,checkConversionForErrors:()=>kL,clamp:()=>Ua,computeStrides:()=>ni,createScalarValue:()=>GE,createShuffledIndices:()=>jE,decodeString:()=>Yu,distSquared:()=>WE,encodeString:()=>qu,fetch:()=>YE,flatten:()=>ti,getArrayFromDType:()=>ty,getTypedArrayFromDType:()=>$a,hasEncodingLoss:()=>ny,indexToLoc:()=>XE,inferDtype:()=>Wa,inferFromImplicitShape:()=>Qg,isBoolean:()=>DL,isFunction:()=>si,isInt:()=>ke,isNumber:()=>FL,isScalarShape:()=>zE,isString:()=>kn,isTypedArray:()=>Dt,isValidDtype:()=>sy,locToIndex:()=>KE,makeOnesTypedArray:()=>hp,makeZerosNestedTypedArray:()=>HE,makeZerosTypedArray:()=>ii,nearestDivisor:()=>za,nearestLargerEven:()=>ME,now:()=>Hu,parseAxisParam:()=>Ne,randUniform:()=>$E,repeatedTry:()=>VE,rightPad:()=>ko,shuffle:()=>_L,sizeFromShape:()=>We,sizeToSquarishShape:()=>BE,squeezeShape:()=>ey,sum:()=>UE,tanh:()=>PE,toNestedArray:()=>Do,toTypedArray:()=>Pa});function _L(e){let t=e.length,s=0,n=0;for(;t>0;)n=Math.random()*t|0,t--,s=e[t],e[t]=e[n],e[n]=s}function Ua(e,t,s){return Math.max(e,Math.min(t,s))}function ME(e){return e%2===0?e:e+1}function UE(e){let t=0;for(let s=0;s<e.length;s++)t+=e[s];return t}function $E(e,t){const s=Math.random();return t*s+(1-s)*e}function WE(e,t){let s=0;for(let n=0;n<e.length;n++){const i=Number(e[n])-Number(t[n]);s+=i*i}return s}function I(e,t){if(!e)throw new Error(typeof t=="string"?t:t())}function Se(e,t,s=""){I(Nt(e,t),()=>s+` Shapes ${e} and ${t} must match`)}function qs(e){I(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function ti(e,t=[],s=!1){if(t==null&&(t=[]),Array.isArray(e)||Dt(e)&&!s)for(let n=0;n<e.length;++n)ti(e[n],t,s);else t.push(e);return t}function We(e){if(e.length===0)return 1;let t=e[0];for(let s=1;s<e.length;s++)t*=e[s];return t}function zE(e){return e.length===0}function Nt(e,t){if(e===t)return!0;if(e==null||t==null)return!1;if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(e[s]!==t[s])return!1;return!0}function ke(e){return e%1===0}function PE(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 BE(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function jE(e){const t=new Uint32Array(e);for(let s=0;s<e;++s)t[s]=s;return _L(t),t}function ko(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function VE(e,t=n=>0,s){return new Promise((n,i)=>{let r=0;const o=()=>{if(e()){n();return}r++;const a=t(r);if(s!=null&&r>=s){i();return}setTimeout(o,a)};o()})}function Qg(e,t){let s=1,n=-1;for(let r=0;r<e.length;++r)if(e[r]>=0)s*=e[r];else if(e[r]===-1){if(n!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${n} and dim ${r}`);n=r}else if(e[r]<0)throw Error(`Shapes can not be < 0. Found ${e[r]} at dim ${r}`);if(n===-1){if(t>0&&t!==s)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(s===0)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%s!==0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${s}`);const i=e.slice();return i[n]=t/s,i}function Ne(e,t){const s=t.length;return e=e==null?t.map((n,i)=>i):[].concat(e),I(e.every(n=>n>=-s&&n<s),()=>`All values in axis param must be in range [-${s}, ${s}) but got axis ${e}`),I(e.every(n=>ke(n)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(n=>n<0?s+n:n)}function ey(e,t){const s=[],n=[],i=t!=null&&Array.isArray(t)&&t.length===0,r=t==null||i?null:Ne(t,e).sort();let o=0;for(let a=0;a<e.length;++a){if(r!=null){if(r[o]===a&&e[a]!==1)throw new Error(`Can't squeeze axis ${a} since its dim '${e[a]}' is not 1`);(r[o]==null||r[o]>a)&&e[a]===1&&(s.push(e[a]),n.push(a)),r[o]<=a&&o++}e[a]!==1&&(s.push(e[a]),n.push(a))}return{newShape:s,keptDims:n}}function $a(e,t){let s=null;if(e==null||e==="float32")s=new Float32Array(t);else if(e==="int32")s=new Int32Array(t);else if(e==="bool")s=new Uint8Array(t);else throw new Error(`Unknown data type ${e}`);return s}function ty(e,t){let s=null;if(e==null||e==="float32")s=new Float32Array(t);else if(e==="int32")s=new Int32Array(t);else if(e==="bool")s=new Uint8Array(t);else if(e==="string")s=new Array(t);else throw new Error(`Unknown data type ${e}`);return s}function kL(e,t){for(let s=0;s<e.length;s++){const n=e[s];if(isNaN(n)||!isFinite(n))throw Error(`A tensor of type ${t} being uploaded contains ${n}.`)}}function sy(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function ny(e,t){return t==="complex64"||(t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64")?!1:!(t==="bool"&&e==="bool")}function Dt(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function iy(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 ry(e){if(e==null)return 0;let t=0;return e.forEach(s=>t+=s.length),t}function kn(e){return typeof e=="string"||e instanceof String}function DL(e){return typeof e=="boolean"}function FL(e){return typeof e=="number"}function Wa(e){return Array.isArray(e)?Wa(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":FL(e)?"float32":kn(e)?"string":DL(e)?"bool":"float32"}function si(e){return!!(e&&e.constructor&&e.call&&e.apply)}function za(e,t){for(let s=t;s<e;++s)if(e%s===0)return s;return e}function ni(e){const t=e.length;if(t<2)return[];const s=new Array(t-1);s[t-2]=e[t-1];for(let n=t-3;n>=0;--n)s[n]=s[n+1]*e[n+1];return s}function GE(e,t){return t==="string"?qu(e):Pa([e],t)}function Pa(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=ti(e)),W().getBool("DEBUG")&&kL(e,t),qE(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 s=new Uint8Array(e.length);for(let n=0;n<s.length;++n)Math.round(e[n])!==0&&(s[n]=1);return s}else throw new Error(`Unknown data type ${t}`)}function ML(e,t,s){const n=new Array;if(t.length===1){const i=t[0];for(let r=0;r<i;r++)n[r]=s[e+r]}else{const i=t[0],r=t.slice(1),o=r.reduce((a,l)=>a*l);for(let a=0;a<i;a++)n[a]=ML(e+a*o,r,s)}return n}function Do(e,t){if(e.length===0)return t[0];const s=e.reduce((n,i)=>n*i);if(s===0)return[];if(s!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}.`);return ML(0,e,t)}function qE(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function hp(e,t){const s=ii(e,t);for(let n=0;n<s.length;n++)s[n]=1;return s}function ii(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 HE(e,t){const s=e.reduce((n,i)=>n*i,1);if(t==null||t==="float32")return Do(e,new Float32Array(s));if(t==="int32")return Do(e,new Int32Array(s));if(t==="bool")return Do(e,new Uint8Array(s));throw new Error(`Unknown data type ${t}`)}function Hu(){return W().platform.now()}function dp(e){e.forEach(t=>{I(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function YE(e,t){return W().platform.fetch(e,t)}function qu(e,t="utf-8"){return t=t||"utf-8",W().platform.encode(e,t)}function Yu(e,t="utf-8"){return t=t||"utf-8",W().platform.decode(e,t)}function KE(e,t,s){if(t===0)return 0;if(t===1)return e[0];let n=e[e.length-1];for(let i=0;i<e.length-1;++i)n+=s[i]*e[i];return n}function XE(e,t,s){if(t===0)return[];if(t===1)return[e];const n=new Array(t);for(let i=0;i<n.length-1;++i)n[i]=Math.floor(e/s[i]),e-=n[i]*s[i];return n[n.length-1]=e,n}class UL{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new ZE)}profileKernel(e,t,s){let n;const i=()=>{n=s()},r=this.backendTimer.time(i);for(let a=0;a<n.length;a++){const l=n[a];l.data().then(c=>{JE(c,l.dtype,e)})}const o={kernelName:e,outputs:n,inputs:t,timeMs:r.then(a=>a.kernelMs),extraInfo:r.then(a=>a.getExtraProfileInfo!=null?a.getExtraProfileInfo():"")};return o}logKernelProfile(e){const{kernelName:t,outputs:s,timeMs:n,inputs:i,extraInfo:r}=e;s.forEach(o=>{Promise.all([o.data(),n,r]).then(a=>{this.logger.logKernelProfile(t,o,a[0],a[1],i,a[2])})})}}function JE(e,t,s){if(t!=="float32")return!1;for(let n=0;n<e.length;n++){const i=e[n];if(isNaN(i)||!isFinite(i))return console.warn(`Found ${i} in the result of '${s}'`),!0}return!1}class ZE{logKernelProfile(e,t,s,n,i,r){const o=typeof n=="number"?ko(`${n}ms`,9):n.error,a=ko(e,25),l=t.rank,c=t.size,p=ko(t.shape.toString(),14);let u="";for(const h in i){const d=i[h];if(d!=null){const m=d.shape||t.shape,f=m.length;u+=`${h}: ${f}D ${f>0?m:""} `}}console.log(`%c${a} %c${o} %c${l}D ${p} %c${c} %c${u} %c${r}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function $L(e,t,s){const n={},i={};for(let l=0;l<t.length;l++)n[t[l].id]=!0;for(let l=0;l<e.length;l++){const c=e[l],p=c.inputs;for(const u in p){const h=p[u];let d=!1;for(let m=0;m<t.length;m++)if(n[h.id]){c.outputs.forEach(f=>n[f.id]=!0),d=!0,i[c.id]=!0;break}if(d)break}}const r={};r[s.id]=!0;const o={};for(let l=e.length-1;l>=0;l--){const c=e[l],p=c.inputs;for(let u=0;u<c.outputs.length;u++)if(r[c.outputs[u].id]){for(const h in p)r[p[h].id]=!0,o[c.id]=!0;break}}const a=[];for(let l=0;l<e.length;l++){const c=e[l];if(i[c.id]&&o[c.id]){const p={};for(const h in c.inputs){const d=c.inputs[h];n[d.id]&&(p[h]=d)}const u=Object.assign({},c);u.inputs=p,u.outputs=c.outputs,a.push(u)}}return a}function WL(e,t,s,n){for(let i=t.length-1;i>=0;i--){const r=t[i],o=[];if(r.outputs.forEach(l=>{const c=e[l.id];c!=null?o.push(c):o.push(null)}),r.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${r.kernelName}.`);const a=r.gradient(o);for(const l in r.inputs){if(!(l in a))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(a)}.`);const c=s(()=>a[l]());if(c.dtype!=="float32")throw new Error(`Error in gradient for op ${r.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${c.dtype}'`);const p=r.inputs[l];if(!Nt(c.shape,p.shape))throw new Error(`Error in gradient for op ${r.kernelName}. The gradient of input '${l}' has shape '${c.shape}', which does not match the shape of the input '${p.shape}'`);if(e[p.id]==null)e[p.id]=c;else{const u=e[p.id];e[p.id]=n(u,c),u.dispose()}}}}const zL=20,mp=3,oy=7;function PL(e,t,s,n){const i=ni(t),r=QE(e,t,s,i),o=t.length,a=Ku(e,t,s,i,r),l=["Tensor"];return n&&(l.push(` dtype: ${s}`),l.push(` rank: ${o}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(a.map(c=>" "+c).join(`
`)),l.join(`
`)}function QE(e,t,s,n){const i=We(t),r=n[n.length-1],o=new Array(r).fill(0),a=t.length,l=s==="complex64"?gp(e):e;if(a>1)for(let c=0;c<i/r;c++){const p=c*r;for(let u=0;u<r;u++)o[u]=Math.max(o[u],fp(l[p+u],0,s).length)}return o}function fp(e,t,s){let n;return Array.isArray(e)?n=`${parseFloat(e[0].toFixed(oy))} + ${parseFloat(e[1].toFixed(oy))}j`:kn(e)?n=`'${e}'`:s==="bool"?n=BL(e):n=parseFloat(e.toFixed(oy)).toString(),ko(n,t)}function BL(e){return e===0?"false":"true"}function Ku(e,t,s,n,i,r=!0){const o=s==="complex64"?2:1,a=t[0],l=t.length;if(l===0){if(s==="complex64"){const f=gp(e);return[fp(f[0],0,s)]}return s==="bool"?[BL(e[0])]:[e[0].toString()]}if(l===1){if(a>zL){const g=mp*o;let y=Array.from(e.slice(0,g)),w=Array.from(e.slice((a-mp)*o,a*o));return s==="complex64"&&(y=gp(y),w=gp(w)),["["+y.map((x,T)=>fp(x,i[T],s)).join(", ")+", ..., "+w.map((x,T)=>fp(x,i[a-mp+T],s)).join(", ")+"]"]}const f=s==="complex64"?gp(e):Array.from(e);return["["+f.map((g,y)=>fp(g,i[y],s)).join(", ")+"]"]}const c=t.slice(1),p=n.slice(1),u=n[0]*o,h=[];if(a>zL){for(let f=0;f<mp;f++){const g=f*u,y=g+u;h.push(...Ku(e.slice(g,y),c,s,p,i,!1))}h.push("...");for(let f=a-mp;f<a;f++){const g=f*u,y=g+u;h.push(...Ku(e.slice(g,y),c,s,p,i,f===a-1))}}else for(let f=0;f<a;f++){const g=f*u,y=g+u;h.push(...Ku(e.slice(g,y),c,s,p,i,f===a-1))}const d=l===2?",":"";h[0]="["+h[0]+d;for(let f=1;f<h.length-1;f++)h[f]=" "+h[f]+d;let m=`,
`;for(let f=2;f<l;f++)m+=`
`;return h[h.length-1]=" "+h[h.length-1]+"]"+(r?"":m),h}function gp(e){const t=[];for(let s=0;s<e.length;s+=2)t.push([e[s],e[s+1]]);return t}class cn{constructor(e,t,s){if(this.dtype=t,this.shape=e.slice(),this.size=We(e),s!=null){const n=s.length;I(n===this.size,()=>`Length of values '${n}' 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=s||ty(t,this.size),this.strides=ni(e)}set(e,...t){t.length===0&&(t=[0]),I(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);const s=this.locToIndex(t);this.values[s]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(const n of e){if(n<0||n>=this.shape[t]){const i=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(i)}t++}let s=e[e.length-1];for(let n=0;n<e.length-1;++n)s+=this.strides[n]*e[n];return this.values[s]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let s=0;s<e.length-1;++s)t+=this.strides[s]*e[s];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];const t=new Array(this.shape.length);for(let s=0;s<t.length-1;++s)t[s]=Math.floor(e/this.strides[s]),e-=t[s]*this.strides[s];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return ri().makeTensor(this.values,this.shape,this.dtype)}}let ri=null,Ba=null,e_=null;function jL(e){ri=e}function VL(e){Ba=e}function GL(e){e_=e}class me{constructor(e,t,s,n){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=We(e),this.strides=ni(e),this.dataId=s,this.id=n,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return Ba.buffer(this.shape,this.dtype,e)}bufferSync(){return Ba.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return Do(this.shape,e)}arraySync(){return Do(this.shape,this.dataSync())}async data(){this.throwIfDisposed();const e=ri().read(this.dataId);if(this.dtype==="string"){const t=await e;try{return t.map(s=>Yu(s))}catch(s){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=ri().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Yu(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 ri().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){if(this.isDisposed)return;ri().disposeTensor(this),this.isDisposedInternal=!0}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Ba.print(this,e)}clone(){return this.throwIfDisposed(),Ba.clone(this)}toString(e=!1){const t=this.dataSync();return PL(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Ba.cast(this,e)}variable(e=!0,t,s){return this.throwIfDisposed(),ri().makeVariable(this,e,t,s)}}Object.defineProperty(me,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});class oi extends me{constructor(e,t,s,n){super(e.shape,e.dtype,e.dataId,n);this.trainable=t,this.name=s}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(!Nt(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);ri().disposeTensor(this),this.dataId=e.dataId,ri().incRef(this,null)}dispose(){ri().disposeVariable(this),this.isDisposedInternal=!0}}Object.defineProperty(oi,Symbol.hasInstance,{value:e=>e instanceof me&&e.assign!=null&&e.assign instanceof Function});var ay;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(ay||(ay={}));var ly;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(ly||(ly={}));var cy;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(cy||(cy={}));var py;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(py||(py={}));var uy;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(uy||(uy={}));const t_={float32:py,int32:ly,bool:cy,complex64:uy};function Ft(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return t_[e][t]}function yp(e){return Ft(e,"int32")}const pn={};Ee(pn,{assertTypesMatch:()=>hy,getTensorsInContainer:()=>bp,isTensorInList:()=>s_,makeTypesMatch:()=>Ce});function Ce(e,t){if(e.dtype===t.dtype)return[e,t];const s=Ft(e.dtype,t.dtype);return[e.cast(s),t.cast(s)]}function hy(e,t){I(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function s_(e,t){return t.some(s=>s.id===e.id)}function bp(e){const t=[],s=new Set;return qL(e,t,s),t}function qL(e,t,s){if(e==null)return;if(e instanceof me){t.push(e);return}if(!n_(e))return;const n=e;for(const i in n){const r=n[i];s.has(r)||(s.add(r),qL(r,t,s))}}function n_(e){return Array.isArray(e)||typeof e=="object"}class HL{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 wp{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new HL}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 s=e[t],n=await this.initializeBackend(s).success;if(n){await this.setBackend(s);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,s=1){return e in this.registryFactory?(console.warn(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:s},!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:s}=this.initializeBackend(e),n=s?await t:t;if(!n)return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new UL(this.backendInstance),!0}setupRegisteredKernels(){const e=up(this.backendName);e.forEach(t=>{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){const t=up(e);t.forEach(s=>{s.disposeFunc!=null&&s.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 s=t.factory();if(s&&!(s instanceof go)&&typeof s.then=="function"){const n=++this.pendingBackendInitId,i=s.then(r=>n<this.pendingBackendInitId?!1:(this.registry[e]=r,this.pendingBackendInit=null,!0)).catch(r=>(n<this.pendingBackendInitId||(this.pendingBackendInit=null,console.warn(`Initialization of backend ${e} failed`),console.warn(r.stack||r.message)),!1));return this.pendingBackendInit=i,{success:i,asyncInit:!0}}else return this.registry[e]=s,{success:!0,asyncInit:!1}}catch(s){return console.warn(`Initialization of backend ${e} failed`),console.warn(s.stack||s.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 s=e[t],{success:n,asyncInit:i}=this.initializeBackend(s);if(i||n)return{name:s,asyncInit:i}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const s=this.state.tensorInfo.get(t),n=s.backend,i=this.readSync(t);n.disposeData(t),s.backend=e,e.move(t,i,s.shape,s.dtype),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let s=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");s=e}let n;return this.scopedRun(()=>this.startScope(s),()=>this.endScope(n),()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n))}scopedRun(e,t,s){e();try{const n=s();return t(),n}catch(n){throw t(),n}}nextTensorId(){return wp.nextTensorId++}nextVariableId(){return wp.nextVariableId++}clone(e){const t=this.makeTensorFromDataId(e.dataId,e.shape,e.dtype),s={x:e},n=r=>({x:()=>{const o="float32",a={x:r},l={dtype:o};return v.runKernelFunc(c=>c.cast(r,o),a,null,Ii,l)}}),i=[];return this.addTapeNode(this.state.activeScope.name,s,[t],n,i,{}),t}runKernel(e,t,s,n,i){const r=null,o=null;return this.runKernelFunc(r,t,o,e,s,n,i)}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,s){const n=this.backend.numDataIds();let i=0;s.forEach(a=>{i+=a.dtype==="complex64"?3:1});const r=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],o=n-t-i-r;if(o>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${o} data ids) after running '${e}'`)}runKernelFunc(e,t,s,n,i,r,o){let a,l=[];const c=this.isTapeOn();n==null&&(n=this.state.activeScope!=null?this.state.activeScope.name:"");const p=this.state.numBytes,u=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let h;const d=pp(n,this.backendName);let m;if(d!=null)h=()=>{const g=this.backend.numDataIds();m=d.kernelFunc({inputs:t,attrs:i,backend:this.backend});const y=Array.isArray(m)?m:[m];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(n,g,y);const w=y.map(({dataId:x,shape:T,dtype:A})=>this.makeTensorFromDataId(x,T,A));if(c){let x=this.getTensorsForGradient(n,t,w);if(x==null){o==null&&(o=[]);const T=w.filter((A,_)=>o[_]);x=(r||[]).slice().concat(T)}l=this.saveTensorsForBackwardMode(x)}return w};else{const g=y=>{if(!c)return;l=y.map(w=>this.keep(this.clone(w)))};h=()=>{const y=this.backend.numDataIds();m=this.tidy(()=>e(this.backend,g));const w=Array.isArray(m)?m:[m];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(n,y,w),w}}let f;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?a=h():(f=this.profiler.profileKernel(n,t,()=>h()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(f),a=f.outputs)}),c&&this.addTapeNode(n,t,a,s,l,i),this.state.profiling&&this.state.activeProfile.kernels.push({name:n,bytesAdded:this.state.numBytes-p,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-u,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(t).map(g=>t[g]!=null?t[g].shape:null),outputShapes:a.map(g=>g.shape),kernelTimeMs:f.timeMs,extraInfo:f.extraInfo}),Array.isArray(m)?a:a[0]}saveTensorsForBackwardMode(e){const t=e.map(s=>this.keep(this.clone(s)));return t}getTensorsForGradient(e,t,s){const n=Gu(e);if(n!=null){const i=n.inputsToSave||[],r=n.outputsToSave||[];let o;n.saveAllInputs?(I(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),o=Object.keys(t).map(l=>t[l])):o=i.map(l=>t[l]);const a=s.filter((l,c)=>r[c]);return o.concat(a)}return null}makeTensor(e,t,s,n){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");s=s||"float32",n=n||this.backend;let i=e;s==="string"&&kn(e[0])&&(i=e.map(a=>qu(a)));const r=n.write(i,t,s),o=new me(t,s,r,this.nextTensorId());if(this.incRef(o,n),s==="string"){const a=this.state.tensorInfo.get(r),l=ry(i);this.state.numBytes+=l-a.bytes,a.bytes=l}return o}makeTensorFromDataId(e,t,s,n){s=s||"float32";const i=new me(t,s,e,this.nextTensorId());return this.incRef(i,n),i}makeVariable(e,t=!0,s,n){s=s||this.nextVariableId().toString(),n!=null&&n!==e.dtype&&(e=e.cast(n));const i=new oi(e,t,s,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 s=this.state.tensorInfo.has(e.dataId)?this.state.tensorInfo.get(e.dataId).refCount:0;if(this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++,s===0){this.state.numDataBuffers++;let n=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(n=e.size*iy(e.dtype)),this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n,refCount:0}),this.state.numBytes+=n}this.state.tensorInfo.get(e.dataId).refCount++,e instanceof oi||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),s=t.refCount;s<=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,s=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(n=>n.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-s;for(const n of this.state.activeProfile.kernels)n.kernelTimeMs=await n.kernelTimeMs,n.extraInfo=await n.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,s,n,i,r){const o={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:s,saved:i},a=Gu(e);a!=null&&(n=a.gradFunc),n!=null&&(o.gradient=l=>(l=l.map((c,p)=>{if(c==null){const u=s[p],h=ii(u.size,u.dtype);return this.makeTensor(h,u.shape,u.dtype)}return c}),n(l.length>1?l:l[0],i,r))),this.state.activeTape.push(o)}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=bp(e),s=new Set(t.map(i=>i.id));for(let i=0;i<this.state.activeScope.track.length;i++){const r=this.state.activeScope.track[i];!r.kept&&!s.has(r.id)&&r.dispose()}const n=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===n.id&&this.track(i)})}gradients(e,t,s,n=!1){if(I(t.length>0,()=>"gradients() received an empty list of xs."),s!=null&&s.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${s.dtype}'`);const i=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));I(i instanceof me,()=>"The result y returned by f() must be a tensor.");const r=$L(this.state.activeTape,t,i);if(!n&&r.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 o={};o[i.id]=s??i_(i.shape),WL(o,r,l=>this.tidy(l),r_);const a=t.map(l=>o[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(const c of l.saved)c.dispose()}),this.state.activeTape=null),{value:i,grads:a}})}customGrad(e){return I(si(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{I(t.every(i=>i instanceof me),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let s;const n={};return t.forEach((i,r)=>{n[r]=i}),this.runKernelFunc((i,r)=>(s=e(...t,r),I(s.value instanceof me,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),I(si(s.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),s.value),n,(i,r)=>{const o=s.gradFunc(i,r),a=Array.isArray(o)?o:[o];I(a.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),I(a.every(c=>c instanceof me),()=>"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 l={};return a.forEach((c,p)=>{l[p]=()=>c}),l})}}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=Hu(),s=await this.backend.time(e);return s.wallMs=Hu()-t,s}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 HL;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}}wp.nextTensorId=0;wp.nextVariableId=0;function i_(e){const t=hp(We(e),"float32");return v.makeTensor(t,e,"float32")}function dy(){const e=bg();if(e._tfengine==null){const t=new fg(e);e._tfengine=new wp(t)}return EL(e._tfengine.ENV),jL(()=>e._tfengine),e._tfengine}const v=dy();function r_(e,t){const s={a:e,b:t};return v.runKernelFunc((n,i)=>{const r=n.add(e,t);return i([e,t]),r},s,null,Kn)}const ja={};Ee(ja,{isBrowser:()=>my,isMobile:()=>a_});function o_(){return typeof navigator!="undefined"&&navigator!=null}function a_(){if(o_()){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 my(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}const Oi=W();Oi.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.")});Oi.registerFlag("IS_BROWSER",()=>my());Oi.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Oi.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Oi.registerFlag("PROD",()=>!1);Oi.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Oi.getBool("DEBUG"));Oi.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Oi.registerFlag("IS_TEST",()=>!1);function Zt(e,t){let s=e;if(Dt(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];const n=[];for(;Array.isArray(s)||Dt(s)&&t!=="string";)n.push(s.length),s=s[0];return Array.isArray(e)&&W().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&YL(e,n,[]),n}function YL(e,t,s){if(s=s||[],!Array.isArray(e)&&!Dt(e)){I(t.length===0,()=>`Element arr[${s.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}I(t.length>0,()=>`Element arr[${s.join("][")}] should be a primitive, but is an array of ${e.length} elements`),I(e.length===t[0],()=>`Element arr[${s.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);const n=t.slice(1);for(let i=0;i<e.length;++i)YL(e[i],n,s.concat(i))}function KL(e,t,s,n){if(e==null)return;if(e!=="numeric"&&e!==t||e==="numeric"&&t==="string")throw new Error(`Argument '${s}' passed to '${n}' must be ${e} tensor, but got ${t} tensor`)}function b(e,t,s,n="numeric"){if(e instanceof me)return KL(n,e.dtype,t,s),e;let i=Wa(e);if(i!=="string"&&["bool","int32","float32"].indexOf(n)>=0&&(i=n),KL(n,i,t,s),e==null||!Dt(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){const l=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${s}' must be a Tensor or TensorLike, but got '${l}'`)}const r=Zt(e,i);!Dt(e)&&!Array.isArray(e)&&(e=[e]);const o=!0,a=i!=="string"?Pa(e,i):ti(e,[],o);return v.makeTensor(a,r,i)}function Ei(e,t,s,n="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${s} must be a \`Tensor[]\` or \`TensorLike[]\``);const i=e;return i.map((r,o)=>b(r,`${t}[${o}]`,s),n)}const fy="__op";function S(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 s=t[0];const n=e[s];s.endsWith("_")&&(s=s.substring(0,s.length-1)),s=s+fy;const i=(...r)=>{v.startScope(s);try{const o=n(...r);return o instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),v.endScope(o),o}catch(o){throw v.endScope(null),o}};return Object.defineProperty(i,"name",{value:s,configurable:!0}),i}function l_(e,t){const s=b(e,"real","complex"),n=b(t,"imag","complex");Se(s.shape,n.shape,`real and imag shapes, ${s.shape} and ${n.shape}, must match in call to tf.complex().`);const i=o=>o.complex(s,n),r={real:s,imag:n};return v.runKernelFunc(i,r,null,vc)}const Gt=S({complex_:l_});function us(e,t,s,n){if(n==null&&(n=Wa(e)),n==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!Dt(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){dp(t);const i=We(t),r=We(s);I(i===r,()=>`Based on the provided shape, [${t}], the tensor should have ${i} values but has ${r}`);for(let o=0;o<s.length;++o){const a=s[o],l=o===s.length-1?a!==We(t.slice(o)):!0;I(s[o]===t[o]||!l,()=>`Error creating a new Tensor. Inferred shape (${s}) does not match the provided shape (${t}). `)}}return!Dt(e)&&!Array.isArray(e)&&(e=[e]),t=t||s,e=n!=="string"?Pa(e,n):ti(e,[],!0),v.makeTensor(e,t,n)}function ze(e,t,s){const n=Zt(e,s);return us(e,t,n,s)}const xp={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};const Xu=4;async function p_(e,t){const s=[],n=[],i=Array.isArray(e)?e.map(o=>o.name):Object.keys(e);for(let o=0;o<i.length;++o){const a=i[o],l=Array.isArray(e)?e[o].tensor:e[a];if(l.dtype!=="float32"&&l.dtype!=="int32"&&l.dtype!=="bool"&&l.dtype!=="string"&&l.dtype!=="complex64")throw new Error(`Unsupported dtype in weight '${a}': ${l.dtype}`);const c={name:a,shape:l.shape,dtype:l.dtype};if(l.dtype==="string"){const p=new Promise(async u=>{const h=await l.bytes(),d=h.reduce((g,y)=>g+y.length,0)+Xu*h.length,m=new Uint8Array(d);let f=0;for(let g=0;g<h.length;g++){const y=h[g],w=new Uint8Array(new Uint32Array([y.length]).buffer);m.set(w,f),f+=Xu,m.set(y,f),f+=y.length}u(m)});n.push(p)}else n.push(l.data());t!=null&&(c.group=t),s.push(c)}const r=await Promise.all(n);return{data:c_(r),specs:s}}function gy(e,t){const s={};let n,i=0;for(const r of t){const o=r.name,a=r.dtype,l=r.shape,c=We(l);let p;if("quantization"in r){const u=r.quantization;if(u.dtype==="uint8"||u.dtype==="uint16"){if(!("min"in u&&"scale"in u))throw new Error(`Weight ${r.name} with quantization ${u.dtype} doesn't have corresponding metadata min and scale.`)}else if(u.dtype==="float16"){if(a!=="float32")throw new Error(`Weight ${r.name} is quantized with ${u.dtype} which only supports weights of type float32 not ${a}.`)}else throw new Error(`Weight ${r.name} has unknown quantization dtype ${u.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);const h=xp[u.dtype],d=e.slice(i,i+c*h),m=u.dtype==="uint8"?new Uint8Array(d):new Uint16Array(d);if(a==="float32")if(u.dtype==="uint8"||u.dtype==="uint16"){p=new Float32Array(m.length);for(let f=0;f<m.length;f++){const g=m[f];p[f]=g*u.scale+u.min}}else if(u.dtype==="float16")n===void 0&&(n=u_()),p=n(m);else throw new Error(`Unsupported quantization type ${u.dtype} for weight type float32.`);else if(a==="int32"){if(u.dtype!=="uint8"&&u.dtype!=="uint16")throw new Error(`Unsupported quantization type ${u.dtype} for weight type int32.`);p=new Int32Array(m.length);for(let f=0;f<m.length;f++){const g=m[f];p[f]=Math.round(g*u.scale+u.min)}}else throw new Error(`Unsupported dtype in weight '${o}': ${a}`);i+=c*h}else if(a==="string"){const u=We(r.shape);p=[];for(let h=0;h<u;h++){const d=new Uint32Array(e.slice(i,i+Xu))[0];i+=Xu;const m=new Uint8Array(e.slice(i,i+d));p.push(m),i+=d}}else{const u=xp[a],h=e.slice(i,i+c*u);if(a==="float32")p=new Float32Array(h);else if(a==="int32")p=new Int32Array(h);else if(a==="bool")p=new Uint8Array(h);else if(a==="complex64"){p=new Float32Array(h);const d=new Float32Array(p.length/2),m=new Float32Array(p.length/2);for(let y=0;y<d.length;y++)d[y]=p[y*2],m[y]=p[y*2+1];const f=ze(d,l,"float32"),g=ze(m,l,"float32");s[o]=Gt(f,g)}else throw new Error(`Unsupported dtype in weight '${o}': ${a}`);i+=c*u}a!=="complex64"&&(s[o]=ze(p,l,a))}return s}function c_(e){if(e===null)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0;const s=[];e.forEach(r=>{if(t+=r.byteLength,s.push(r.byteLength===r.buffer.byteLength?r:new r.constructor(r)),!(r instanceof Float32Array||r instanceof Int32Array||r instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${r.constructor.name}`)});const n=new Uint8Array(t);let i=0;return s.forEach(r=>{n.set(new Uint8Array(r.buffer),i),i+=r.byteLength}),n.buffer}const h_=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function XL(e){return h_?Buffer.byteLength(e):new Blob([e]).size}function Lp(e){if(e.length===1)return e[0];let t=0;e.forEach(i=>{t+=i.byteLength});const s=new Uint8Array(t);let n=0;return e.forEach(i=>{s.set(new Uint8Array(i),n),n+=i.byteLength}),s.buffer}function yy(e){const t="/";for(e=e.trim();e.endsWith(t);)e=e.slice(0,e.length-1);const s=e.split(t);return s[s.length-1]}function Sp(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:XL(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:XL(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function d_(){const e=s=>{let n=s<<13,i=0;for(;(n&8388608)===0;)i-=8388608,n<<=1;return n&=~8388608,i+=947912704,n|i},t=new Uint32Array(2048);t[0]=0;for(let s=1;s<1024;s++)t[s]=e(s);for(let s=1024;s<2048;s++)t[s]=939524096+(s-1024<<13);return t}function m_(){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 f_(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function u_(){const e=d_(),t=m_(),s=f_();return n=>{const i=new ArrayBuffer(4*n.length),r=new Uint32Array(i);for(let o=0;o<n.length;o++){const a=n[o],l=e[s[a>>10]+(a&1023)]+t[a>>10];r[o]=l}return new Float32Array(i)}}class Ct{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Ct.instance==null&&(Ct.instance=new Ct),Ct.instance}static registerSaveRouter(e){Ct.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Ct.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Ct.getHandlers(e,"save")}static getLoadHandlers(e,t){return Ct.getHandlers(e,"load",t)}static getHandlers(e,t,s){const n=[],i=t==="load"?Ct.getInstance().loadRouters:Ct.getInstance().saveRouters;return i.forEach(r=>{const o=r(e,s);o!==null&&n.push(o)}),n}}const g_=e=>Ct.registerSaveRouter(e),y_=e=>Ct.registerLoadRouter(e),b_=e=>Ct.getSaveHandlers(e),w_=(e,t)=>Ct.getLoadHandlers(e,t);const Va="://";class Dn{constructor(){this.managers={}}static getInstance(){return Dn.instance==null&&(Dn.instance=new Dn),Dn.instance}static registerManager(e,t){I(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(Va)&&(e=e.slice(0,e.indexOf(Va))),I(e.length>0,()=>"scheme must not be an empty string.");const s=Dn.getInstance();I(s.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),s.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 Ju(e){if(e.indexOf(Va)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Dn.getSchemes().join(",")}`);return{scheme:e.split(Va)[0],path:e.split(Va)[1]}}async function JL(e,t,s=!1){I(e!==t,()=>`Old path and new path are the same: '${e}'`);const n=Ct.getLoadHandlers(e);I(n.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),I(n.length<2,()=>`Copying failed because more than one (${n.length}) load handlers for source URL ${e}.`);const i=n[0],r=Ct.getSaveHandlers(t);I(r.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),I(r.length<2,()=>`Copying failed because more than one (${n.length}) save handlers for destination URL ${t}.`);const o=r[0],a=Ju(e).scheme,l=Ju(e).path,c=a===Ju(e).scheme,p=await i.load();s&&c&&await Dn.getManager(a).removeModel(l);const u=await o.save(p);return s&&!c&&await Dn.getManager(a).removeModel(l),u.modelArtifactsInfo}async function ZL(){const e=Dn.getSchemes(),t={};for(const s of e){const n=await Dn.getManager(s).listModels();for(const i in n){const r=s+Va+i;t[r]=n[i]}}return t}async function QL(e){const t=Ju(e),s=Dn.getManager(t.scheme);return s.removeModel(t.path)}async function eS(e,t){const s=!1;return JL(e,t,s)}async function tS(e,t){const s=!0;return JL(e,t,s)}function ge(e,t="float32",s){return t=t||"float32",dp(e),new cn(e,t,s)}function x_(e,t){const s=b(e,"x","cast");if(!sy(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&s.dtype!=="string"||t!=="string"&&s.dtype==="string")throw new Error("Only strings can be casted to strings");const n={x:s},i={dtype:t};return v.runKernelFunc(r=>r.cast(s,t),n,null,Ii,i)}const G=S({cast_:x_});function L_(e){const t=b(e,"x","clone",null),s=()=>v.makeTensorFromDataId(t.dataId,t.shape,t.dtype),n={x:t};return v.runKernelFunc(s,n,null,Ti)}const Ds=S({clone_:L_});function Zu(e,t=!1){console.log(e.toString(t))}dy();const S_={buffer:ge,cast:G,clone:Ds,print:Zu};VL(S_);const I_="model",v_=".json",T_=".weights.bin";function sS(e){return new Promise(t=>setTimeout(t)).then(e)}class Ga{constructor(e){if(!W().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Ga.URL_SCHEME)&&(e=e.slice(Ga.URL_SCHEME.length)),(e==null||e.length===0)&&(e=I_),this.modelTopologyFileName=e+v_,this.weightDataFileName=e+T_}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 s=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:s},i=window.URL.createObjectURL(new Blob([JSON.stringify(n)],{type:"application/json"})),r=this.jsonAnchor==null?document.createElement("a"):this.jsonAnchor;if(r.download=this.modelTopologyFileName,r.href=i,await sS(()=>r.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){const o=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;o.download=this.weightDataFileName,o.href=t,await sS(()=>o.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Sp(e)}}}}Ga.URL_SCHEME="downloads://";class A_{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((s,n)=>{const i=new FileReader;i.onload=r=>{const o=JSON.parse(r.target.result),a=o.modelTopology;if(a==null){n(new Error(`modelTopology field is missing from file ${e.name}`));return}t.length===0&&s({modelTopology:a});const l=o.weightsManifest;if(l==null){n(new Error(`weightManifest field is missing from file ${e.name}`));return}let c;try{c=this.checkManifestAndWeightFiles(l,t)}catch(d){n(d);return}const p=[],u=[],h=[];l.forEach(d=>{d.paths.forEach(m=>{u.push(m),h.push(null)}),p.push(...d.weights)}),l.forEach(d=>{d.paths.forEach(m=>{const f=new FileReader;f.onload=g=>{const y=g.target.result,w=u.indexOf(m);h[w]=y,h.indexOf(null)===-1&&s({modelTopology:a,weightSpecs:p,weightData:Lp(h),format:o.format,generatedBy:o.generatedBy,convertedBy:o.convertedBy,userDefinedMetadata:o.userDefinedMetadata})},f.onerror=g=>n(`Failed to weights data from file of path '${m}'.`),f.readAsArrayBuffer(c[m])})})},i.onerror=r=>n(`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 s=[],n=t.map(r=>yy(r.name)),i={};for(const r of e)r.paths.forEach(o=>{const a=yy(o);if(s.indexOf(a)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${a}'`);if(s.push(a),n.indexOf(a)===-1)throw new Error(`Weight file with basename '${a}' is not provided.`);i[o]=t[n.indexOf(a)]});if(s.length!==t.length)throw new Error(`Mismatch in the number of files in weights manifest (${s.length}) and the number of weight files provided (${t.length}).`);return i}}const C_=e=>W().getBool("IS_BROWSER")&&(!Array.isArray(e)&&e.startsWith(Ga.URL_SCHEME))?N_(e.slice(Ga.URL_SCHEME.length)):null;Ct.registerSaveRouter(C_);function N_(e="model"){return new Ga(e)}function R_(e){return new A_(e)}function by(e,t,s,n){o(e),s=s??0,n=n??1,a(s,n);let i=0;const r=l=>(l.then(c=>{const p=s+ ++i/e.length*(n-s);return t(p),c}),l);function o(l){I(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function a(l,c){I(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),I(c>=0&&c<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${c}`),I(c>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${c}`)}return Promise.all(e.map(r))}async function wy(e,t){t==null&&(t={});const s=t.fetchFunc==null?W().platform.fetch:t.fetchFunc,n=e.map(u=>s(u,t.requestInit,{isBinary:!0})),i=0,r=.5,o=t.onProgress==null?await Promise.all(n):await by(n,t.onProgress,i,r),a=o.map(u=>u.arrayBuffer()),l=.5,c=1,p=t.onProgress==null?await Promise.all(a):await by(a,t.onProgress,l,c);return p}async function O_(e,t="",s,n){const i=o=>wy(o,{requestInit:n}),r=nS(i);return r(e,t,s)}function nS(e){return async(t,s="",n)=>{const i=t.map(()=>!1),r={},o=n!=null?n.map(()=>!1):[],a=[];if(t.forEach((d,m)=>{let f=0;d.weights.forEach(g=>{const y="quantization"in g?g.quantization.dtype:g.dtype,w=xp[y]*We(g.shape),x=()=>{i[m]=!0,r[m]==null&&(r[m]=[]),r[m].push({manifestEntry:g,groupOffset:f,sizeBytes:w})};n!=null?n.forEach((T,A)=>{T===g.name&&(x(),o[A]=!0)}):x(),a.push(g.name),f+=w})}),!o.every(d=>d)){const d=n.filter((m,f)=>!o[f]);throw new Error(`Could not find weights in manifest with names: ${d.join(", ")}.
Manifest JSON has weights with names: ${a.join(", ")}.`)}const l=i.reduce((d,m,f)=>(m&&d.push(f),d),[]),c=[];l.forEach(d=>{t[d].paths.forEach(m=>{const f=s+(s.endsWith("/")?"":"/")+m;c.push(f)})});const p=await e(c),u={};let h=0;return l.forEach(d=>{const m=t[d].paths.length;let f=0;for(let T=0;T<m;T++)f+=p[h+T].byteLength;const g=new ArrayBuffer(f),y=new Uint8Array(g);let w=0;for(let T=0;T<m;T++){const A=new Uint8Array(p[h+T]);y.set(A,w),w+=A.byteLength}const x=r[d];x.forEach(T=>{const A=g.slice(T.groupOffset,T.groupOffset+T.sizeBytes),_=gy(A,[T.manifestEntry]);for(const E in _)u[E]=_[E]}),h+=m}),u}}const E_="application/octet-stream",__="application/json";class xy{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?(I(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=W().platform.fetch,I(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&I(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 s=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,userDefinedMetadata:e.userDefinedMetadata,weightsManifest:s};t.body.append("model.json",new Blob([JSON.stringify(n)],{type:__}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:E_}),"model.weights.bin");const i=await this.fetch(this.path,t);if(i.ok)return{modelArtifactsInfo:Sp(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(h){let d=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?d+=" 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.":d+=" Please make sure the server is serving valid JSON for this request.",new Error(d)}const s=t.modelTopology,n=t.weightsManifest,i=t.generatedBy,r=t.convertedBy,o=t.format,a=t.userDefinedMetadata;if(s==null&&n==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);let l,c;if(n!=null){const h=await this.loadWeights(n);[l,c]=h}const p={modelTopology:s,weightSpecs:l,weightData:c,userDefinedMetadata:a,generatedBy:i,convertedBy:r,format:o},u=t.modelInitializer;return u&&(p.modelInitializer=u),p}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[s,n]=k_(t),i=this.weightPathPrefix||s,r=[];for(const c of e)r.push(...c.weights);const o=[],a=[];for(const c of e)for(const p of c.paths)this.weightUrlConverter!=null?a.push(this.weightUrlConverter(p)):o.push(i+p+n);this.weightUrlConverter&&o.push(...await Promise.all(a));const l=await wy(o,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[r,Lp(l)]}}xy.URL_SCHEME_REGEX=/^https?:\/\//;function k_(e){const t=e.lastIndexOf("/"),s=e.lastIndexOf("?"),n=e.substring(0,t),i=s>t?e.substring(s):"";return[n+"/",i]}function Ly(e){return e.match(xy.URL_SCHEME_REGEX)!=null}const iS=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let s=!0;if(Array.isArray(e)?s=e.every(n=>Ly(n)):s=Ly(e),s)return Sy(e,t)}return null};Ct.registerSaveRouter(iS);Ct.registerLoadRouter(iS);function Sy(e,t){return new xy(e,t)}function D_(e,t){return Sy(e,t)}class Iy{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}}class F_{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}}function M_(e,t,s,n){if(arguments.length===1){const i=e.modelTopology!=null||e.weightSpecs!=null;return i?new Iy(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 Iy({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 Iy({modelTopology:e,weightSpecs:t,weightData:s,trainingConfig:n})}function U_(e){return new F_(e)}const Rt={};Ee(Rt,{browserFiles:()=>R_,browserHTTPRequest:()=>D_,concatenateArrayBuffers:()=>Lp,copyModel:()=>eS,decodeWeights:()=>gy,encodeWeights:()=>p_,fromMemory:()=>M_,getLoadHandlers:()=>w_,getModelArtifactsInfoForJSON:()=>Sp,getSaveHandlers:()=>b_,http:()=>Sy,isHTTPScheme:()=>Ly,listModels:()=>ZL,loadWeights:()=>O_,moveModel:()=>tS,registerLoadRouter:()=>y_,registerSaveRouter:()=>g_,removeModel:()=>QL,weightsLoaderFactory:()=>nS,withSaveHandler:()=>U_});function $_(e,t){const s=b(e,"x","reshape",null),n={x:s},i={shape:t},r=(o,a)=>(t=Qg(t,s.size),I(s.size===We(t),()=>"new shape and old shape must have the same number of elements."),a([s]),o.reshape(s,t));return v.runKernelFunc(r,n,null,Ci,i)}const O=S({reshape_:$_});function W_(e,t,s=!1,n=!1){let i=b(e,"a","matMul"),r=b(t,"b","matMul");[i,r]=Ce(i,r),I(i.rank>=2&&r.rank>=2&&i.rank===r.rank,()=>`Error in matMul: inputs must have the same rank of at least 2, got ranks ${i.rank} and ${r.rank}.`);const o=s?i.shape[i.rank-2]:i.shape[i.rank-1],a=n?r.shape[r.rank-1]:r.shape[r.rank-2],l=s?i.shape[i.rank-1]:i.shape[i.rank-2],c=n?r.shape[r.rank-2]:r.shape[r.rank-1],p=i.shape.slice(0,-2),u=r.shape.slice(0,-2),h=We(p),d=We(u);I(Nt(p,u),()=>`Error in matMul: outer dimensions (${p}) and (${u}) of Tensors with shapes ${i.shape} and ${r.shape} must match.`),I(o===a,()=>`Error in matMul: inner shapes (${o}) and (${a}) of Tensors with shapes ${i.shape} and ${r.shape} and transposeA=${s} and transposeB=${n} must match.`);const m=i.shape.slice(0,-2).concat([l,c]),f=s?O(i,[h,o,l]):O(i,[h,l,o]),g=n?O(r,[d,c,a]):O(r,[d,a,c]),y=(A,_)=>(_([f,g]),A.batchMatMul(f,g,s,n)),w={a:f,b:g},x={transposeA:s,transposeB:n},T=v.runKernelFunc(y,w,null,Lc,x);return O(T,m)}const Te=S({matMul_:W_});function z_(e,t,s=1,n=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const i=b(e,"indices","oneHot","int32"),r=[...i.shape,t],o=(c,p)=>(p([i]),O(c.oneHot(O(i,[i.size]),t,s,n),r)),a={indices:i},l={depth:t,onValue:s,offValue:n};return v.runKernelFunc(o,a,null,qc,l)}const ai=S({oneHot_:z_});function P_(e,t){const s=b(e,"x","transpose");if(t==null&&(t=s.shape.map((r,o)=>o).reverse()),I(s.rank===t.length,()=>`Error in transpose: rank of input ${s.rank} must match length of perm ${t}.`),t.forEach(r=>{I(r>=0&&r<s.rank,()=>`All entries in 'perm' must be between 0 and ${s.rank-1} but got ${t}`)}),s.rank<=1)return s.clone();const n={x:s},i={perm:t};return v.runKernelFunc(r=>r.transpose(s,t),n,null,Ri,i)}const se=S({transpose_:P_});function B_(e,t,s){const n=b(e,"labels","confusionMatrix"),i=b(t,"predictions","confusionMatrix");I(s==null||s>0&&Number.isInteger(s),()=>`If provided, numClasses must be a positive integer, but got ${s}`),I(n.rank===1,()=>`Expected the rank of labels to be 1, but got ${n.rank}`),I(i.rank===1,()=>`Expected the rank of predictions to be 1, but got ${i.rank}`),I(n.shape[0]===i.shape[0],()=>`Mismatch in the number of examples: ${n.shape[0]} vs. ${i.shape[0]}. Labels and predictions should have the same number of elements.`),I(s>0&&Number.isInteger(s),()=>`numClasses is required to be a positive integer, but got ${s}`);const r=ai(G(n,"int32"),s),o=ai(G(i,"int32"),s),a=se(r);return G(Te(a,o),"int32")}const j_=S({confusionMatrix_:B_});const rS={};Ee(rS,{confusionMatrix:()=>j_});function qa(e,t,s){if(qs(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");const n=Zt(e,s);if(n.length!==3&&n.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return us(e,t,n,s)}const Fr={};Ee(Fr,{fromPixels:()=>q_,toPixels:()=>G_});let Ha;function V_(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 s=!1,n=!1,i=!1,r=!1,o=!1;if(e.data instanceof Uint8Array)s=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)n=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)i=!0;else if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)r=!0;else if(e.getContext!=null)o=!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 d=2;if(i&&e.readyState<d)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.")}const a=pp(Da,v.backendName);if(a!=null){const d={pixels:e},m={numChannels:t};return v.runKernel(Da,d,m)}const[l,c]=i?[e.videoWidth,e.videoHeight]:[e.width,e.height];let p;o?p=e.getContext("2d").getImageData(0,0,l,c).data:n||s?p=e.data:(r||i)&&(Ha==null&&(Ha=document.createElement("canvas").getContext("2d")),Ha.canvas.width=l,Ha.canvas.height=c,Ha.drawImage(e,0,0,l,c),p=Ha.getImageData(0,0,l,c).data);let u;if(t===4)u=new Int32Array(p);else{const d=l*c;u=new Int32Array(d*t);for(let m=0;m<d;m++)for(let f=0;f<t;++f)u[m*t+f]=p[m*4+f]}const h=[c,l,t];return qa(u,h,"int32")}async function G_(e,t){let s=b(e,"img","toPixels");if(!(e instanceof me)){const c=s;s=G(c,"int32"),c.dispose()}if(s.rank!==2&&s.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${s.rank}.`);const[n,i]=s.shape.slice(0,2),r=s.rank===2?1:s.shape[2];if(r>4||r===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${r}`);if(s.dtype!=="float32"&&s.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${s.dtype}. Please use float32 or int32 tensors.`);const o=await s.data(),a=s.dtype==="float32"?255:1,l=new Uint8ClampedArray(i*n*4);for(let c=0;c<n*i;++c){const p=[0,0,0,255];for(let h=0;h<r;h++){const d=o[c*r+h];if(s.dtype==="float32"){if(d<0||d>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${d}.`)}else if(s.dtype==="int32"&&(d<0||d>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${d}.`);r===1?(p[0]=d*a,p[1]=d*a,p[2]=d*a):p[h]=d*a}const u=c*4;l[u+0]=Math.round(p[0]),l[u+1]=Math.round(p[1]),l[u+2]=Math.round(p[2]),l[u+3]=Math.round(p[3])}if(t!=null){t.width=i,t.height=n;const c=t.getContext("2d"),p=new ImageData(l,i,n);c.putImageData(p,0,0)}return s!==e&&s.dispose(),l}const q_=S({fromPixels_:V_});const oS={};Ee(oS,{prepareAndValidate:()=>aS});function aS(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 s=t.shape,n=s[s.length-1];let i=1;for(let c=0;c<s.length-1;++c)i*=s[c];const r=e.shape,o=s.slice();o.pop();let a=1;for(let c=n;c<e.rank;++c)a*=r[c],o.push(r[c]);const l=[...ni(e.shape).map(c=>c/a),1].slice(0,n);return[o,i,a,l]}const lS={};Ee(lS,{calculateShapes:()=>cS,validateInput:()=>Qu,validateUpdateShape:()=>vy});function vy(e,t,s){const n=t.rank>1?t.shape[t.rank-1]:1,i=t.rank>1?t.rank-1:1,r=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${s.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${n}, and batchDim: ${i}.`;if(s.rank<i)throw new Error(r+` update.rank < ${i}. `);if(e.length<n+(s.rank-i))throw new Error(r+` Output shape length < ${n+(s.rank-i)}`);if(s.rank!==i+e.length-n)throw new Error(r+` update.rank != ${i+e.length-n}`);for(let o=0;o<i;++o)if(s.shape[o]!==t.shape[o])throw new Error(r+` updates.shape[${o}] (${s.shape[o]}) != indices.shape[${o}] (${t.shape[o]}).`);for(let o=0;o<s.rank-i;++o)if(s.shape[o+i]!==e[o+n])throw new Error(r+` updates.shape[${o+i}] (${s.shape[o+i]}) != shape[${o+i}] (${e[o+i]})`)}function Qu(e,t,s){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(s.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${s}`);if(s.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}`)}vy(s,t,e)}function cS(e,t,s){const n=t.shape.length,i=n>1?t.shape[n-1]:1,r=s.length;let o=1;for(let u=i;u<r;++u)o*=s[u];const a=i<1?1:i,l=We(t.shape)/a,c=[...ni(s.slice(0,i)),1],p=We(s);return{sliceRank:i,numUpdates:l,sliceSize:o,strides:c,outputSize:p}}const Fs={};Ee(Fs,{assertParamsValid:()=>Ty,computeFlatOffset:()=>Y_,computeOutShape:()=>Ay,getNormalizedAxes:()=>Ny,isSliceContinous:()=>H_,maskToAxes:()=>Ip,parseSliceParams:()=>vp,startForAxis:()=>gS,startIndicesWithElidedDims:()=>dS,stopForAxis:()=>yS,stopIndicesWithElidedDims:()=>mS,stridesForAxis:()=>fS,stridesWithElidedDims:()=>pS});function Ty(e,t,s){const n=e.shape.length;I(n===t.length,()=>`Error in slice${n}D: Length of begin ${t} must match the rank of the array (${n}).`),I(n===s.length,()=>`Error in slice${n}D: Length of size ${s} must match the rank of the array (${n}).`);for(let i=0;i<n;++i)I(t[i]+s[i]<=e.shape[i],()=>`Error in slice${n}D: begin[${i}] + size[${i}] (${t[i]+s[i]}) would overflow input.shape[${i}] (${e.shape[i]})`)}function Ip(e){const t=[];let s=0;for(;e>0;)e&1&&t.push(s),e/=2,s++;return t}function Ay(e,t,s){const n=[];for(let i=0;i<e.length;i++)n[i]=Math.ceil((t[i]-e[i])/s[i]);return n}function pS(e,t,s,n){const i=[...e];for(let r=i.length;r<n.length;r++)i.push(1);for(let r=0;r<s;r++)r===0?i[t]=1:(i.splice(t,0,1),i.pop());return i}function uS(e,t,s){return s<=e?s:s-(t-1)}function hS(e,t){const s=[];for(let n=0;n<e;n++)s.push(t+n);return s}function Ny(e,t,s,n,i,r,o,a,l){const c=e.length;let p=new Array(c),u=new Array(c),h=new Array(c);if(t.length&&s>0){const d=t[0],m=s+1;p=dS(o,d,m,n,e),u=mS(a,d,m,i,e),h=pS(r,d,m,e)}else for(let d=0;d<c;d++)p[d]=gS(o,n,r,e,d,l),u[d]=yS(a,i,r,e,d,l),h[d]=fS(r,d,l);return{begin:p,end:u,strides:h}}function dS(e,t,s,n,i){const r=[...i],o=hS(s,t);for(let a=0;a<r.length;a++)if(o.indexOf(a)>-1)r[a]=0;else{const l=uS(t,s,a);let c=n[l];e&1<<l&&(c=0),r[a]=c}return r}function mS(e,t,s,n,i){const r=[...i],o=hS(s,t);for(let a=0;a<r.length;a++)if(o.indexOf(a)>-1)r[a]=Number.MAX_SAFE_INTEGER;else{const l=uS(t,s,a);let c=n[l];e&1<<l&&(c=Number.MAX_SAFE_INTEGER),r[a]=c}for(let a=0;a<r.length;a++){const l=i[a];r[a]<0&&(r[a]+=l),r[a]=Ua(0,r[a],i[a])}return r}function fS(e,t,s){let n=e[t];return(s&1<<t||n==null)&&(n=1),n}function gS(e,t,s,n,i,r){let o=t[i];const a=s[i]||1;(e&1<<i||r&1<<i||o==null)&&(a>0?o=Number.MIN_SAFE_INTEGER:o=Number.MAX_SAFE_INTEGER);const l=n[i];return o<0&&(o+=l),o=Ua(0,o,l-1),o}function yS(e,t,s,n,i,r){let o=t[i];const a=s[i]||1;(e&1<<i||r&1<<i||o==null)&&(a>0?o=Number.MAX_SAFE_INTEGER:o=Number.MIN_SAFE_INTEGER);const l=n[i];return o<0&&(o+=l),a>0?o=Ua(0,o,l):o=Ua(-1,o,l-1),o}function H_(e,t,s){let n=s.length;for(let i=0;i<s.length;i++)if(s[i]>1){n=i;break}for(let i=n+1;i<s.length;i++)if(t[i]>0||s[i]!==e[i])return!1;return!0}function Y_(e,t){let s=e.length>0?e[e.length-1]:1;for(let n=0;n<e.length-1;n++)s+=e[n]*t[n];return s}function vp(e,t,s){let n;const i=e.shape.length;typeof t=="number"?n=[t,...new Array(i-1).fill(0)]:t.length<i?n=t.concat(new Array(i-t.length).fill(0)):n=t.slice(),n.forEach(o=>{I(o!==-1,()=>"slice() does not support negative begin indexing.")});let r;return s==null?r=new Array(i).fill(-1):typeof s=="number"?r=[s,...new Array(i-1).fill(-1)]:s.length<i?r=s.concat(new Array(i-s.length).fill(-1)):r=s,r=r.map((o,a)=>o>=0?o:(I(o===-1,()=>`Negative size values should be exactly -1 but got ${o} for the slice() size at index ${a}.`),e.shape[a]-n[a])),[n,r]}const V={};Ee(V,{Serializable:()=>Cy,SerializationMap:()=>Fo,registerClass:()=>vs});class Cy{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class Fo{constructor(){this.classNameMap={}}static getMap(){return Fo.instance==null&&(Fo.instance=new Fo),Fo.instance}static register(e){Fo.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function vs(e){I(e.className!=null,()=>"Class being registered does not have the static className property defined."),I(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),I(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),Fo.register(e)}const bS={};Ee(bS,{TEST_EPSILON_FLOAT16:()=>wS,expectArrayBuffersEqual:()=>tk,expectArraysClose:()=>X_,expectArraysEqual:()=>Z_,expectNumbersClose:()=>Q_,expectPromiseToFail:()=>J_,expectValuesInRange:()=>ek,testEpsilon:()=>Ry});const K_=.001,wS=.1;function X_(e,t,s){return s==null&&(s=Ry()),Oy(e,t,(n,i)=>Ey(n,i,s))}function Ry(){return v.backend.floatPrecision()===32?K_:wS}function Oy(e,t,s){let n=!0;if((Dt(e)||Dt(t))&&(n=!1),Dt(e)&&Dt(t)&&(n=!0),n){const o=e.constructor.name,a=t.constructor.name;if(o!==a)throw new Error(`Arrays are of different type. Actual: ${o}. Expected: ${a}`)}if(Array.isArray(e)&&Array.isArray(t)){const o=Zt(e),a=Zt(t);if(!Nt(o,a))throw new Error(`Arrays have different shapes. Actual: [${o}]. Expected: [${a}]`)}const i=Dt(e)?e:ti(e),r=Dt(t)?t:ti(t);if(i.length!==r.length)throw new Error(`Arrays have different lengths actual: ${i.length} vs expected: ${r.length}.
Actual: ${i}.
Expected: ${r}.`);for(let o=0;o<r.length;++o){const a=i[o],l=r[o];if(!s(a,l))throw new Error(`Arrays differ: actual[${o}] = ${a}, expected[${o}] = ${l}.
Actual: ${i}.
Expected: ${r}.`)}}function J_(e,t){e().then(()=>t.fail(),()=>t())}function Z_(e,t){const s=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return kn(e)||kn(e[0])||kn(t)||kn(t[0])?Oy(e,s,(n,i)=>n==i):Oy(e,t,(n,i)=>Ey(n,i,0))}function Q_(e,t,s){if(s==null&&(s=Ry()),!Ey(e,t,s))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function Ey(e,t,s){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>s)}function ek(e,t,s){for(let n=0;n<e.length;n++)if(e[n]<t||e[n]>s)throw new Error(`Value out of range:${e[n]} low: ${t}, high: ${s}`)}function tk(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}const _y="2.6.0";function sk(){W().set("PROD",!0)}function nk(){W().set("DEBUG",!0)}function ik(){W().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function It(e){W().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}GL(It);function rk(){v.disposeVariables()}function Ms(){return v}function Ya(){return v.memory()}function ok(e){return v.profile(e)}function C(e,t){return v.tidy(e,t)}function ce(e){const t=bp(e);t.forEach(s=>s.dispose())}function pt(e){return v.keep(e)}function ak(e){return v.time(e)}function xS(e){return v.setBackend(e)}function lk(){return v.ready()}function ck(){return v.backendName}function pk(e){v.removeBackend(e)}function uk(e){return v.findBackend(e)}function hk(e){return v.findBackendFactory(e)}function Tp(e,t,s=1){return v.registerBackend(e,t,s)}function ky(){return v.backend}function dk(e,t){W().setPlatform(e,t)}function mk(e,t){let s=b(e,"a","add"),n=b(t,"b","add");[s,n]=Ce(s,n);const i=(o,a)=>{const l=o.add(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,Kn)}const $=S({add_:mk});function fk(e,t){let s=b(e,"a","floorDiv"),n=b(t,"b","floorDiv");[s,n]=Ce(s,n);const i=(o,a)=>{const l=o.floorDiv(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,Ec)}const Ka=S({floorDiv_:fk});function gk(e,t){let s=b(e,"a","div"),n=b(t,"b","div");if([s,n]=Ce(s,n),s.dtype==="int32"&&n.dtype==="int32")return Ka(s,n);const i=(a,l)=>{const c=a.realDivide(s,n);return l([s,n]),c},r={a:s,b:n},o={};return v.runKernelFunc(i,r,null,Jn,o)}const Z=S({div_:gk});function yk(e,t){let s=b(e,"a","mul"),n=b(t,"b","mul");[s,n]=Ce(s,n);const i=(o,a)=>{const l=o.multiply(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,Sr)}const R=S({mul_:yk});function bk(e){const t=b(e,"x","abs"),s={x:t};return v.runKernelFunc((n,i)=>(i([t]),t.dtype==="complex64"?n.complexAbs(t):n.abs(t)),s,null,yo)}const et=S({abs_:bk});function wk(e){const t=b(e,"x","acos"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.acos(t);return i([t]),r},s,null,nr)}const eh=S({acos_:wk});function xk(e){const t=b(e,"x","acosh"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.acosh(t);return i([t]),r},s,null,ir)}const th=S({acosh_:xk});function Lk(e){I(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),I(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);const t=e.map((r,o)=>b(r,`tensors${o}`,"addN")),s=t[0];t.forEach(r=>{if(r.dtype!==s.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(r=>{if(!Nt(r.shape,s.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});const n=(r,o)=>{const a=r.addN(t);return o(t),a},i=t;return v.runKernelFunc(n,i,null,yc)}const sh=S({addN_:Lk});function Dy(e,t){for(let s=0;s<e.length;++s)if(e[e.length-s-1]!==t-1-s)return!1;return!0}function LS(e,t,s){const n=e.length+t.length,i=[];let r=0,o=0;for(let a=0;a<n;a++)s.indexOf(a)===-1?i.push(e[r++]):i.push(t[o++]);return i}function Fy(e,t){const s=[],n=e.length;for(let r=0;r<n;r++)t.indexOf(r)===-1&&s.push(e[r]);const i=t.map(r=>e[r]);return[s,i]}function bt(e,t){const s=t.map(n=>1);return LS(e,s,t)}function Sk(e,t,s){I(Dy(t,s),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${s} input.`)}function ht(e,t){if(Dy(e,t))return null;const s=[];for(let n=0;n<t;++n)e.indexOf(n)===-1&&s.push(n);return e.forEach(n=>s.push(n)),s}function Mo(e){return e.map((t,s)=>[s,t]).sort((t,s)=>t[1]-s[1]).map(t=>t[0])}function qt(e,t){const s=[];for(let n=t-e;n<t;++n)s.push(n);return s}function Ik(e,t=null,s=!1){let n=b(e,"x","all","bool");const i=a=>{const l=Ne(t,n.shape);let c=l;const p=ht(c,n.rank);p!=null&&(n=se(n,p),c=qt(c.length,n.rank));const u=a.all(n,c);if(s){const h=bt(u.shape,l);return O(u,h)}return u},r={x:n},o={axis:t,keepDims:s};return v.runKernelFunc(i,r,null,xg,o)}const Xa=S({all_:Ik});function vk(e,t=null,s=!1){let n=b(e,"x","any","bool");const i=a=>{const l=Ne(t,n.shape);let c=l;const p=ht(c,n.rank);p!=null&&(n=se(n,p),c=qt(c.length,n.rank));const u=a.any(n,c);if(s){const h=bt(u.shape,l);return O(u,h)}return u},r={x:n},o={axis:t,keepDims:s};return v.runKernelFunc(i,r,null,Lg,o)}const Uo=S({any_:vk});function Tk(e,t=0){let s=b(e,"x","argMax");const n=(o,a)=>{a([s]);let l=Ne(t,s.shape);const c=ht(l,s.rank);return c!=null&&(s=se(s,c),l=qt(l.length,s.rank)),o.argMax(s,l[0])},i={x:s},r={axis:t};return v.runKernelFunc(n,i,null,bc,r)}const $o=S({argMax_:Tk});function Ak(e,t=0){let s=b(e,"x","argMin");const n=(o,a)=>{a([s]),t==null&&(t=0);let l=Ne(t,s.shape);const c=ht(l,s.rank);return c!=null&&(s=se(s,c),l=qt(l.length,s.rank)),o.argMin(s,l[0])},i={x:s},r={axis:t};return v.runKernelFunc(n,i,null,wc,r)}const nh=S({argMin_:Ak});function Nk(e){const t=b(e,"x","asin"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.asin(t);return i([t]),r},s,null,rr)}const ih=S({asin_:Nk});function Ck(e){const t=b(e,"x","asinh"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.asinh(t);return i([t]),r},s,null,or)}const rh=S({asinh_:Ck});function Rk(e){const t=b(e,"x","atan"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.atan(t);return i([t]),r},s,null,ar)}const oh=S({atan_:Rk});function Ok(e,t){let s=b(e,"a","atan2"),n=b(t,"b","atan2");[s,n]=Ce(s,n);const i=(o,a)=>{const l=o.atan2(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,bo)}const ah=S({atan2_:Ok});function Ek(e){const t=b(e,"x","atanh"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.atanh(t);return i([t]),r},s,null,lr)}const lh=S({atanh_:Ek});function _k(e,t,s,n,i="NHWC",r){const o=e[3],a=[...t,o],l=Mr(i);return is(e,a,s,r,n,null,null,l)}function Fn(e,t,s,n,i,r,o="channelsLast"){const[a,l]=ch(t);let c;if(o==="channelsLast")c=[a,l,e[3],e[3]];else if(o==="channelsFirst")c=[a,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return is(e,c,s,n,i,r,!1,o)}function _i(e,t,s,n,i,r,o="NDHWC"){const[a,l,c]=My(t);let p,u;if(o==="NDHWC")u="channelsLast",p=[a,l,c,e[4],e[4]];else if(o==="NCDHW")u="channelsFirst",p=[a,l,c,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return Ur(e,p,s,n,i,!1,u,r)}function is(e,t,s,n,i,r,o=!1,a="channelsLast"){let[l,c,p,u]=[-1,-1,-1,-1];if(a==="channelsLast")[l,c,p,u]=e;else if(a==="channelsFirst")[l,u,c,p]=e;else throw new Error(`Unknown dataFormat ${a}`);const[h,d,,m]=t,[f,g]=ch(s),[y,w]=ch(n),x=Ja(h,y),T=Ja(d,w),{padInfo:A,outHeight:_,outWidth:E}=kk(i,c,p,f,g,x,T,r,a),F=o?m*u:m;let D;return a==="channelsFirst"?D=[l,F,_,E]:a==="channelsLast"&&(D=[l,_,E,F]),{batchSize:l,dataFormat:a,inHeight:c,inWidth:p,inChannels:u,outHeight:_,outWidth:E,outChannels:F,padInfo:A,strideHeight:f,strideWidth:g,filterHeight:h,filterWidth:d,effectiveFilterHeight:x,effectiveFilterWidth:T,dilationHeight:y,dilationWidth:w,inShape:e,outShape:D,filterShape:t}}function Ur(e,t,s,n,i,r=!1,o="channelsLast",a){let[l,c,p,u,h]=[-1,-1,-1,-1,-1];if(o==="channelsLast")[l,c,p,u,h]=e;else if(o==="channelsFirst")[l,h,c,p,u]=e;else throw new Error(`Unknown dataFormat ${o}`);const[d,m,f,,g]=t,[y,w,x]=My(s),[T,A,_]=My(n),E=Ja(d,T),F=Ja(m,A),D=Ja(f,_),{padInfo:M,outDepth:P,outHeight:B,outWidth:Y}=Dk(i,c,p,u,y,w,x,E,F,D,a),q=r?g*h:g;let K;return o==="channelsFirst"?K=[l,q,P,B,Y]:o==="channelsLast"&&(K=[l,P,B,Y,q]),{batchSize:l,dataFormat:o,inDepth:c,inHeight:p,inWidth:u,inChannels:h,outDepth:P,outHeight:B,outWidth:Y,outChannels:q,padInfo:M,strideDepth:y,strideHeight:w,strideWidth:x,filterDepth:d,filterHeight:m,filterWidth:f,effectiveFilterDepth:E,effectiveFilterHeight:F,effectiveFilterWidth:D,dilationDepth:T,dilationHeight:A,dilationWidth:_,inShape:e,outShape:K,filterShape:t}}function Fk(e,t,s,n,i){n==null&&(n=Uy(e,t,s));const r=e[0],o=e[1],a=Wo((r-t+2*n)/s+1,i);I(ke(a),()=>`The output # of rows (${a}) must be an integer. Change the stride and/or zero pad parameters`);const l=Wo((o-t+2*n)/s+1,i);return I(ke(l),()=>`The output # of columns (${l}) must be an integer. Change the stride and/or zero pad parameters`),[a,l]}function Mk(e,t,s,n,i,r){i==null&&(i=Uy(e,t,n));const o=e[0],a=e[1],l=e[2],c=Wo((o-t+2*i)/n+1,r);I(ke(c),()=>`The output # of depths (${c}) must be an integer. Change the stride and/or zero pad parameters`);const p=Wo((a-t+2*i)/n+1,r);I(ke(p),()=>`The output # of rows (${p}) must be an integer. Change the stride and/or zero pad parameters`);const u=Wo((l-t+2*i)/n+1,r);return I(ke(u),()=>`The output # of columns (${u}) must be an integer. Change the stride and/or zero pad parameters`),[c,p,u,s]}function Uy(e,t,s,n=1){const i=Ja(t,n);return Math.floor((e[0]*(s-1)-s+i)/2)}function ch(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function My(e){return typeof e=="number"?[e,e,e]:e}function Ja(e,t){return t<=1?e:e+(e-1)*(t-1)}function kk(e,t,s,n,i,r,o,a,l){let c,p,u;if(typeof e=="number"){const h=e===0?"VALID":"NUMBER";c={top:e,bottom:e,left:e,right:e,type:h};const d=Fk([t,s],r,n,e,a);p=d[0],u=d[1]}else if(e==="same"){p=Math.ceil(t/n),u=Math.ceil(s/i);const h=Math.max(0,(p-1)*n+r-t),d=Math.max(0,(u-1)*i+o-s),m=Math.floor(h/2),f=h-m,g=Math.floor(d/2),y=d-g;c={top:m,bottom:f,left:g,right:y,type:"SAME"}}else if(e==="valid")c={top:0,bottom:0,left:0,right:0,type:"VALID"},p=Math.ceil((t-r+1)/n),u=Math.ceil((s-o+1)/i);else if(typeof e=="object"){const h=l==="channelsLast"?e[1][0]:e[2][0],d=l==="channelsLast"?e[1][1]:e[2][1],m=l==="channelsLast"?e[2][0]:e[3][0],f=l==="channelsLast"?e[2][1]:e[3][1],g=h===0&&d===0&&m===0&&f===0?"VALID":"EXPLICIT";c={top:h,bottom:d,left:m,right:f,type:g},p=Wo((t-r+h+d)/n+1,a),u=Wo((s-o+m+f)/i+1,a)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:c,outHeight:p,outWidth:u}}function Dk(e,t,s,n,i,r,o,a,l,c,p){let u,h,d,m;if(typeof e=="number"){const f=e===0?"VALID":"NUMBER";u={top:e,bottom:e,left:e,right:e,front:e,back:e,type:f};const g=Mk([t,s,n,1],a,1,i,e,p);h=g[0],d=g[1],m=g[2]}else if(e==="same"){h=Math.ceil(t/i),d=Math.ceil(s/r),m=Math.ceil(n/o);const f=(h-1)*i+a-t,g=(d-1)*r+l-s,y=(m-1)*o+c-n,w=Math.floor(f/2),x=f-w,T=Math.floor(g/2),A=g-T,_=Math.floor(y/2),E=y-_;u={top:T,bottom:A,left:_,right:E,front:w,back:x,type:"SAME"}}else if(e==="valid")u={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},h=Math.ceil((t-a+1)/i),d=Math.ceil((s-l+1)/r),m=Math.ceil((n-c+1)/o);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:u,outDepth:h,outHeight:d,outWidth:m}}function Wo(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 Hs(e){const[t,s,n]=ch(e);return t===1&&s===1&&n===1}function tt(e,t){return Hs(e)||Hs(t)}function Mr(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function Uk(e,t,s,n,i){const r=b(e,"x","avgPool","float32"),o=1;I(tt(s,o),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${o}'`);let a=r,l=!1;r.rank===3&&(l=!0,a=O(r,[1,r.shape[0],r.shape[1],r.shape[2]])),I(a.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${a.rank}.`),i!=null&&I(ke(n),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${i} but got pad ${n}.`);const c=(d,m)=>{const f=Fn(a.shape,t,s,1,n,i);return m([a]),f.filterWidth===1&&f.filterHeight===1&&Nt(f.inShape,f.outShape)?a.clone():d.avgPool(a,f)},p={x:a},u={filterSize:t,strides:s,pad:n,dimRoundingMode:i};let h=v.runKernelFunc(c,p,null,Si,u);return h=G(h,r.dtype),l?O(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const hs=S({avgPool_:Uk});function $k(e,t,s,n,i,r="NDHWC",o){o==null?o=[1,1,1]:It("dilations is deprecated, this field will be gone in v3.0.0.");const a=b(e,"x","avgPool3d","float32");let l=a,c=!1;a.rank===4&&(c=!0,l=O(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),I(l.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${l.rank}.`),I(r==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${r}`),I(tt(s,o),()=>`Error in avgPool3d: Either strides or dilations must be 1. Got strides ${s} and dilations '${o}'`),i!=null&&I(ke(n),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${n}.`);const p=(m,f)=>{o==null&&(o=[1,1,1]);const g=_i(l.shape,t,s,o,n,i,r);return f([l]),m.avgPool3d(l,g)},u={x:l},h={filterSize:t,strides:s,pad:n,dimRoundingMode:i,dataFormat:r,dilations:o};let d=v.runKernelFunc(p,u,null,xc,h);return d=G(d,l.dtype),c?O(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}const Za=S({avgPool3d_:$k});function $y(e,t){const s=e[0].length;e.forEach((i,r)=>{I(i.length===s,()=>`Error in concat${s}D: rank of tensors[${r}] must be the same as the rank of the rest (${s})`)}),I(t>=0&&t<s,()=>`Error in concat${s}D: axis must be between 0 and ${s-1}.`);const n=e[0];e.forEach((i,r)=>{for(let o=0;o<s;o++)I(o===t||i[o]===n[o],()=>`Error in concat${s}D: Shape of tensors[${r}] (${i}) does not match the shape of the rest (${n}) along the non-concatenated axis ${r}.`)})}function Wy(e,t){const s=e[0].slice();for(let n=1;n<e.length;n++)s[t]+=e[n][t];return s}function Wk(e,t=0){I(e.length>=1,()=>"Pass at least one tensor to concat");let s=Ei(e,"tensors","concat");s[0].dtype==="complex64"&&s.forEach(o=>{if(o.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
with dtype ${o.dtype}. `)});const n=(o,a)=>{const l=Ne(t,s[0].shape)[0],c=Wy(s.map(h=>h.shape),l);if(We(c)===0)return ze([],c);if(s=s.filter(h=>h.size>0),s.length===1)return s[0];const p=s.map(h=>h.shape);$y(p,l);const u=o.concat(s,l);return a(s),u},i=s,r={axis:t};return v.runKernelFunc(n,i,null,xo,r)}const be=S({concat_:Wk});function zk(e){const t=b(e,"x","sigmoid"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.sigmoid(t);return i([r]),r},s,null,Rr)}const rs=S({sigmoid_:zk});function Pk(e,t,s){const n=b(e,"x","slice");if(n.rank===0)throw new Error("Slicing scalar is not possible");const i=(a,l)=>{const[c,p]=vp(n,t,s);return Ty(n,c,p),l([n]),a.slice(n,c,p)},r={x:n},o={begin:t,size:s};return v.runKernelFunc(i,r,null,Co,o)}const he=S({slice_:Pk});function Bk(e){const t=b(e,"x","tanh"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.tanh(t);return i([r]),r},s,null,kr)}const ki=S({tanh_:Bk});function jk(e,t,s,n,i,r){const o=b(e,"forgetBias","basicLSTMCell"),a=b(t,"lstmKernel","basicLSTMCell"),l=b(s,"lstmBias","basicLSTMCell"),c=b(n,"data","basicLSTMCell"),p=b(i,"c","basicLSTMCell"),u=b(r,"h","basicLSTMCell"),h=be([c,u],1),d=Te(h,a),m=$(d,l),f=m.shape[0],g=m.shape[1]/4,y=[f,g],w=he(m,[0,0],y),x=he(m,[0,g],y),T=he(m,[0,g*2],y),A=he(m,[0,g*3],y),_=$(R(rs(w),ki(x)),R(p,rs($(o,T)))),E=R(ki(_),rs(A));return[_,E]}const SS=S({basicLSTMCell_:jk});function Vk(e,t,s){const n=b(e,"x","batchToSpaceND"),i=t.reduce((l,c)=>l*c);I(n.rank>=1+t.length,()=>`input rank is ${n.rank} but should be > than blockShape.length ${t.length}`),I(s.length===t.length,()=>`crops.length is ${s.length} but should be equal to blockShape.length ${t.length}`),I(n.shape[0]%i===0,()=>`input tensor batch is ${n.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${i}`);const r=l=>l.batchToSpaceND(n,t,s),o={x:n},a={blockShape:t,crops:s};return v.runKernelFunc(r,o,null,Sc,a)}const $r=S({batchToSpaceND_:Vk});function IS(e){let t;return e.rank===0||e.rank===1?t=O(e,[1,1,1,e.size]):e.rank===2?t=O(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=O(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function Gk(e,t,s,n,i,r){r==null&&(r=.001);const o=b(e,"x","batchNorm"),a=b(t,"mean","batchNorm"),l=b(s,"variance","batchNorm");let c;i!=null&&(c=b(i,"scale","batchNorm"));let p;n!=null&&(p=b(n,"offset","batchNorm")),I(a.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),I(p==null||a.rank===p.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),I(c==null||a.rank===c.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const u=IS(o),h=(g,y)=>(y([u,a,l,c]),g.batchNorm(u,ph(a),ph(l),ph(p),ph(c),r)),d={x:u,scale:c,offset:p,mean:a,variance:l},m={varianceEpsilon:r},f=v.runKernelFunc(h,d,null,vi,m);return O(f,o.shape)}function ph(e){return e==null?null:e.rank===0?O(e,[e.size]):e.rank===1?e:e.rank===2?O(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?O(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e}const Ys=S({batchNorm_:Gk});function qk(e,t,s,n,i,r){const o=b(e,"x","batchNorm"),a=b(t,"mean","batchNorm"),l=b(s,"variance","batchNorm");let c;i!=null&&(c=b(i,"scale","batchNorm"));let p;return n!=null&&(p=b(n,"offset","batchNorm")),I(o.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),I(a.rank===2||a.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${a.rank}.`),I(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),c!=null&&I(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`),p!=null&&I(p.rank===2||p.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${p.rank}.`),Ys(o,a,l,p,c,r)}const uh=S({batchNorm2d_:qk});function Hk(e,t,s,n,i,r){const o=b(e,"x","batchNorm"),a=b(t,"mean","batchNorm"),l=b(s,"variance","batchNorm");let c;i!=null&&(c=b(i,"scale","batchNorm"));let p;return n!=null&&(p=b(n,"offset","batchNorm")),I(o.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`),I(a.rank===3||a.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${a.rank}.`),I(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),c!=null&&I(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${c.rank}.`),p!=null&&I(p.rank===3||p.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${p.rank}.`),Ys(o,a,l,p,c,r)}const hh=S({batchNorm3d_:Hk});function Yk(e,t,s,n,i,r){const o=b(e,"x","batchNorm"),a=b(t,"mean","batchNorm"),l=b(s,"variance","batchNorm");let c;i!=null&&(c=b(i,"scale","batchNorm"));let p;return n!=null&&(p=b(n,"offset","batchNorm")),I(o.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`),I(a.rank===4||a.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${a.rank}.`),I(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),c!=null&&I(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${c.rank}.`),p!=null&&I(p.rank===4||p.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${p.rank}.`),Ys(o,a,l,p,c,r)}const dh=S({batchNorm4d_:Yk});function Kk(e,t){let s=b(e,"broadcastTo","x");const n=s.shape;if(t.some(p=>!(p>0)||p%1!==0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.length<s.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${s.rank}.`);if(t.length>s.rank){const p=s.shape.slice();for(;p.length<t.length;)p.unshift(1);s=O(s,p)}const i=s.shape,r=Array.from(t);for(let p=t.length-1;p>=0;p--)if(i[p]===t[p])r[p]=1;else if(s.shape[p]!==1)throw new Error(`broadcastTo(): [${n}] cannot be broadcast to [${t}].`);const o=r.map((p,u)=>p>1?u:-1).filter(p=>p>=0);if(o.length===0)return Ds(s);const a=p=>p.tile(s,r),l={x:s},c={shape:t,inputShape:i};return v.runKernelFunc(a,l,null,Ic,c)}const zo=S({broadcastTo_:Kk});function Xk(e){const t=b(e,"x","ceil"),s={x:t};return v.runKernelFunc(n=>n.ceil(t),s,null,cr)}const mh=S({ceil_:Xk});function Jk(e,t,s){const n=b(e,"x","clipByValue");I(t<=s,()=>`Error in clip: min (${t}) must be less than or equal to max (${s}).`);const i={x:n},r={clipValueMin:t,clipValueMax:s};return v.runKernelFunc((o,a)=>{const l=o.clip(n,t,s);return a([n]),l},i,null,pr,r)}const wt=S({clipByValue_:Jk});function Zk(e){return be(e,0)}const fh=S({concat1d_:Zk});function Qk(e,t){return be(e,t)}const gh=S({concat2d_:Qk});function eD(e,t){return be(e,t)}const yh=S({concat3d_:eD});function tD(e,t){return be(e,t)}const bh=S({concat4d_:tD});function sD(e,t,s,n,i="NHWC",r=[1,1],o){const a=b(e,"x","conv2d"),l=b(t,"filter","conv2d");let c=a,p=!1;a.rank===3&&(p=!0,c=O(a,[1,a.shape[0],a.shape[1],a.shape[2]])),I(c.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${c.rank}.`),I(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),o!=null&&I(ke(n),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`);const u=i==="NHWC"?c.shape[3]:c.shape[1];I(u===l.shape[2],()=>`Error in conv2d: depth of input (${u}) must match input depth for filter ${l.shape[2]}.`),I(tt(s,r),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`);const h=(g,y)=>{const w=Mr(i),x=is(c.shape,l.shape,s,r,n,o,!1,w),T=g.conv2d(c,l,x);return y([c,l]),T},d={x:c,filter:l},m={strides:s,pad:n,dataFormat:i,dilations:r,dimRoundingMode:o},f=v.runKernelFunc(h,d,null,Tc,m);return p?O(f,[f.shape[1],f.shape[2],f.shape[3]]):f}const nt=S({conv2d_:sD});function nD(e,t,s,n,i="NWC",r=1,o){const a=b(e,"x","conv1d"),l=b(t,"filter","conv1d");let c=a,p=!1;a.rank===2&&(p=!0,c=O(a,[1,a.shape[0],a.shape[1]])),I(c.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${c.rank}.`),I(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),o!=null&&I(ke(n),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`),I(c.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${c.shape[2]}) must match input depth for filter ${l.shape[1]}.`),I(tt(s,r),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${s} and dilation '${r}'`),I(i==="NWC",()=>`Error in conv1d: got dataFormat of ${i} but only NWC is currently supported.`);const u=O(l,[1,l.shape[0],l.shape[1],l.shape[2]]),h=O(c,[c.shape[0],1,c.shape[1],c.shape[2]]),d=[1,s],m=[1,r],f="NHWC",g=nt(h,u,d,n,f,m,o);return p?O(g,[g.shape[2],g.shape[3]]):O(g,[g.shape[0],g.shape[2],g.shape[3]])}const Qa=S({conv1d_:nD});function iD(e,t,s,n,i,r="NHWC",o){I(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let a=e,l=t,c=!1;t.rank===3&&(c=!0,l=O(t,[1,t.shape[0],t.shape[1],t.shape[2]]),a=[1,e[0],e[1],e[2]]),I(a.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${a.length}.`),I(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),I(s.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${s.rank}`);const p=r==="NHWC"?a[3]:a[1],u=r==="NHWC"?l.shape[3]:l.shape[1];I(p===s.shape[2],()=>`Error in conv2dDerInput: depth of input (${p}) must match input depth for filter ${s.shape[2]}.`),I(u===s.shape[3],()=>`Error in conv2dDerInput: depth of output (${u}) must match output depth for filter ${s.shape[3]}.`),o!=null&&I(ke(i),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${o} but got pad ${i}.`);const h=(g,y)=>{const w=1,x=Mr(r),T=is(a,s.shape,n,w,i,o,!1,x),A=g.conv2dDerInput(l,s,T);return y([l,s]),A},d={dy:l,filter:s},m={strides:n,pad:i,dataFormat:r,dimRoundingMode:o,inputShape:a},f=v.runKernelFunc(h,d,null,Ac,m);return c?O(f,[f.shape[1],f.shape[2],f.shape[3]]):f}const el=S({conv2DBackpropInput_:iD});function rD(e,t,s,n,i,r){const o=b(e,"x","conv2dTranspose"),a=b(t,"filter","conv2dTranspose");return el(s,o,a,n,i,"NHWC",r)}const tl=S({conv2dTranspose_:rD});function oD(e,t,s,n,i="NDHWC",r=[1,1,1]){const o=b(e,"x","conv3d"),a=b(t,"filter","conv3d");let l=o,c=!1;o.rank===4&&(c=!0,l=O(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),I(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),I(a.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${a.rank}.`),I(l.shape[4]===a.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${a.shape[3]}.`),I(tt(s,r),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`),I(i==="NDHWC",()=>`Error in conv3d: got dataFormat of ${i} but only NDHWC is currently supported.`);const p=(m,f)=>{const g=Ur(l.shape,a.shape,s,r,n),y=m.conv3d(l,a,g);return f([l,a]),y},u={x:l,filter:a},h={strides:s,pad:n,dataFormat:i,dilations:r},d=v.runKernelFunc(p,u,null,Nc,h);return c?O(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}const sl=S({conv3d_:oD});function aD(e,t,s,n,i){I(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let r=e,o=t,a=!1;t.rank===4&&(a=!0,o=O(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),r=[1,e[0],e[1],e[2],e[3]]);const l=r[4],c=o.shape[4];I(r.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${r.length}.`),I(o.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`),I(s.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${s.rank}`),I(l===s.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${s.shape[3]}.`),I(c===s.shape[4],()=>`Error in conv3dDerInput: depth of output (${c}) must match output depth for filter ${s.shape[4]}.`);const p=m=>{const f=1,g=Ur(r,s.shape,n,f,i);return m.conv3dDerInput(o,s,g)},u={dy:o},h={pad:i},d=v.runKernelFunc(p,u,null,Tg,h);return a?O(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}const wh=S({conv3DBackpropInput_:aD});function lD(e,t,s,n,i){const r=b(e,"x","conv3dTranspose"),o=b(t,"filter","conv3dTranspose");return wh(s,r,o,n,i)}const vS=S({conv3dTranspose_:lD});function cD(e){const t=b(e,"x","cos"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.cos(t);return i([t]),r},s,null,Xn)}const Wr=S({cos_:cD});function pD(e){const t=b(e,"x","cosh"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.cosh(t);return i([t]),r},s,null,ur)}const nl=S({cosh_:pD});function uD(e,t=0,s=!1,n=!1){const i=b(e,"x","cumsum"),r=(l,c)=>{const p=ht([t],i.rank);let u=i;p!=null&&(u=se(i,p));const h=qt(1,i.rank)[0];let d=l.cumsum(u,h,s,n);if(c([i]),p!=null){const m=Mo(p);d=se(d,m)}return d},o={x:i},a={axis:t,exclusive:s,reverse:n};return v.runKernelFunc(r,o,null,Cc,a)}const il=S({cumsum_:uD});function hD(e,t,s="NHWC"){const n=b(e,"x","depthToSpace"),i=s==="NHWC"?n.shape[1]:n.shape[2],r=s==="NHWC"?n.shape[2]:n.shape[3],o=s==="NHWC"?n.shape[3]:n.shape[1];I(i*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${i} and ${t} for depthToSpace with input shape
${n.shape}`),I(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying
${r} and ${t} for depthToSpace with input shape
${n.shape}`),I(o%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${o} for depthToSpace with input shape ${n.shape}`);const a=p=>p.depthToSpace(n,t,s),l={x:n},c={blockSize:t,dataFormat:s};return v.runKernelFunc(a,l,null,Ng,c)}const xh=S({depthToSpace_:hD});function dD(e,t,s,n,i="NHWC",r=[1,1],o){const a=b(e,"x","depthwiseConv2d"),l=b(t,"filter","depthwiseConv2d");let c=a,p=!1;a.rank===3&&(p=!0,c=O(a,[1,a.shape[0],a.shape[1],a.shape[2]])),I(c.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),I(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),I(c.shape[3]===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),o!=null&&I(ke(n),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`);const u=(f,g)=>{r==null&&(r=[1,1]),I(tt(s,r),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`);const y=is(c.shape,l.shape,s,r,n,o,!0),w=f.depthwiseConv2D(c,l,y);return g([c,l]),w},h={x:c,filter:l},d={strides:s,pad:n,dataFormat:i,dilations:r,dimRoundingMode:o},m=v.runKernelFunc(u,h,null,Rc,d);return p?O(m,[m.shape[1],m.shape[2],m.shape[3]]):m}const un=S({depthwiseConv2d_:dD});function mD(e){const t=b(e,"x","diag"),s=i=>{const r=O(t,[t.size]),o=i.diag(r),a=[...e.shape,...e.shape];return O(o,a)},n={x:t};return v.runKernelFunc(s,n,null,Og)}const TS=S({diag_:mD});function fD(e,t,s,n,i=[1,1],r="NHWC"){const o=b(e,"x","dilation2d"),a=b(t,"filter","dilation2d");I(o.rank===3||o.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),I(a.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${a.rank}.`),I(r==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${r}`);let l=o,c=!1;o.rank===3&&(l=O(o,[1,o.shape[0],o.shape[1],o.shape[2]]),c=!0);const p={x:l,filter:a},u={strides:s,pad:n,dilations:i},h=v.runKernel(Lo,p,u);return c?O(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const Lh=S({dilation2d_:fD});function gD(e,t){const s=e.length,n=[];for(let i=0;i<s;i++){const r=s-1-i,o=e[r]||1,a=t[t.length-1-i]||1;a>1&&o===1&&n.unshift(r)}return n}function Ye(e,t){const s=[];for(let n=0;n<t.length;n++){const i=e[e.length-n-1],r=t.length-n-1,o=t[r];(i==null||i===1&&o>1)&&s.unshift(r)}return s}function Ie(e,t){const s=[],n=Math.max(e.length,t.length);for(let i=0;i<n;i++){let r=e[e.length-i-1];r==null&&(r=1);let o=t[t.length-i-1];if(o==null&&(o=1),r===1)s.unshift(o);else if(o===1)s.unshift(r);else if(r!==o){const a=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(a)}else s.unshift(r)}return s}function yD(e,t){let s=b(e,"a","equal"),n=b(t,"b","equal");[s,n]=Ce(s,n),Ie(s.shape,n.shape);const i=o=>o.equal(s,n),r={a:s,b:n};return v.runKernelFunc(i,r,null,_g)}const os=S({equal_:yD});function bD(e,t,s){const n=b(t,"a","where"),i=b(s,"b","where"),r=b(e,"condition","where","bool"),o=Ie(n.shape,i.shape),a=zo(n,o),l=zo(i,o);r.rank===1&&I(r.shape[0]===n.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),r.rank!==1&&Se(r.shape,l.shape,"Error in where: ");const c=(u,h)=>{const d=u.select(r,a,l);return h([r]),d},p={condition:r,t:a,e:l};return v.runKernelFunc(c,p,null,tp)}const dt=S({where_:bD});function wD(e){const t=b(e,"x","zerosLike"),s={x:t};return v.runKernelFunc(n=>n.zerosLike(t),s,null,lp)}const re=S({zerosLike_:wD});function xD(e,t){let s=b(e,"a","div"),n=b(t,"b","div");[s,n]=Ce(s,n);const i=Z(s,n),r=re(i),o=os(n,r);return dt(o,r,i)}const Sh=S({divNoNan_:xD});function LD(e,t){const s=b(e,"t1","dot"),n=b(t,"t2","dot");I((s.rank===1||s.rank===2)&&(n.rank===1||n.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${s.rank} and ${n.rank}.`);const i=s.rank===1?s.size:s.shape[1],r=n.rank===1?n.size:n.shape[0];if(I(i===r,()=>`Error in dot: inner dimensions of inputs must match, but got ${i} and ${r}.`),s.rank===1&&n.rank===1){const o=O(s,[1,-1]),a=O(n,[-1,1]),l=Te(o,a);return O(l,[])}else if(s.rank===1&&n.rank===2){const o=O(s,[1,-1]),a=O(n,[n.shape[0],n.shape[1]]),l=Te(o,a);return O(l,[l.size])}else if(s.rank===2&&n.rank===1){const o=O(n,[-1,1]),a=Te(s,o);return O(a,[a.size])}else{const o=O(n,[n.shape[0],n.shape[1]]),a=Te(s,o);return a}}const AS=S({dot_:LD});function SD(e){const t=b(e,"x","elu"),s=(i,r)=>{const o=i.elu(t);return r([o]),o},n={x:t};return v.runKernelFunc(s,n,null,hr)}const hn=S({elu_:SD});function ID(e){let t=b(e,"x","erf");I(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=G(t,"float32"));const s={x:t};return v.runKernelFunc((n,i)=>{const r=n.erf(t);return i([t]),r},s,null,dr)}const Ih=S({erf_:ID});function vD(e){const t=b(e,"x","exp"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.exp(t);return i([r]),r},s,null,mr)}const ut=S({exp_:vD});function TD(e,t=0){const s=null,n=b(e,"x","expandDims",s);I(t<=n.rank,()=>"Axis must be <= rank of the tensor");const i=n.shape.slice();return t<0&&(I(-(n.rank+1)<=t,()=>`Axis must be in the interval [${-(n.rank+1)}, ${n.rank}]`),t=n.rank+t+1),i.splice(t,0,1),O(n,i)}const Mt=S({expandDims_:TD});function AD(e){const t=b(e,"x","expm1"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.expm1(t);return i([t]),r},s,null,fr)}const vh=S({expm1_:AD});function ND(e,t){const s=null,n=b(e,"x","tile",s);I(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);const i=(l,c)=>{const p=l.tile(n,t);return c([n]),p},r=[n],o={x:n},a={reps:t};return v.runKernelFunc(i,o,null,rp,a,r)}const Us=S({tile_:ND});function CD(e,t,s,n="float32"){t==null&&(t=e);const i=ge([e,t],n),r=e<=t?e:t;for(let a=0;a<r;++a)i.set(1,a,a);const o=O(i.toTensor(),[e,t]);if(s==null)return o;if(s.length===1)return Us(Mt(o,0),[s[0],1,1]);if(s.length===2)return Us(Mt(Mt(o,0),0),[s[0],s[1],1,1]);if(s.length===3)return Us(Mt(Mt(Mt(o,0),0),0),[s[0],s[1],s[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${s.length}D.`)}const Po=S({eye_:CD});function Wt(e,t,s){const n={shape:e,value:t,dtype:s};return v.runKernelFunc(i=>i.fill(e,t,s),{},null,kg,n)}function RD(e){const t=b(e,"x","floor"),s={x:t};return v.runKernelFunc(n=>n.floor(t),s,null,gr)}const li=S({floor_:RD});const Th=30;function OD(e){return e<=Th?e:za(e,Math.floor(Math.sqrt(e)))}const NS={};Ee(NS,{collectGatherOpShapeInfo:()=>zy,computeOutShape:()=>_D,segOpComputeOptimalWindowSize:()=>ED});function ED(e,t){let s=!1,n;for(e<=Th?(n=e,s=!0):n=za(e,Math.floor(Math.sqrt(e)));!s;)n>t||n===e?s=!0:n=za(e,n+1);return n}function _D(e,t,s){const n=[],i=e.length;for(let r=0;r<i;r++)r!==t?n.push(e[r]):n.push(s);return n}function zy(e,t,s){const n=e.shape[s],i=[];let r=1,o=1;for(let a=0;a<s;a++)i.push(e.shape[a]),r*=e.shape[a];for(let a=0;a<t.rank;a++)i.push(t.shape[a]);for(let a=s+1;a<e.rank;a++)i.push(e.shape[a]),o*=e.shape[a];return{batchSize:r,sliceSize:o,dimSize:n,outputShape:i}}function kD(e,t,s=0){const n=b(e,"x","gather"),i=b(t,"indices","gather","int32"),r={x:n,indices:i},o={axis:s},a=(l,c)=>{const p=Ne(s,n.shape)[0],u=zy(n,i,p),h=l.gather(n,O(i,[i.size]),p);return c([n,i]),O(h,u.outputShape)};return v.runKernelFunc(a,r,null,_c,o)}const ci=S({gather_:kD});function DD(e,t){let s=b(e,"a","greater"),n=b(t,"b","greater");[s,n]=Ce(s,n),Ie(s.shape,n.shape);const i=o=>o.greater(s,n),r={a:s,b:n};return v.runKernelFunc(i,r,null,Fg)}const Ut=S({greater_:DD});function FD(e,t){let s=b(e,"a","greaterEqual"),n=b(t,"b","greaterEqual");[s,n]=Ce(s,n),Ie(s.shape,n.shape);const i=(o,a)=>{const l=o.greaterEqual(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,kc)}const ds=S({greaterEqual_:FD});function MD(e){const t=b(e,"input","imag"),s=i=>i.imag(t),n={input:t};return v.runKernelFunc(s,n,null,Fc)}const dn=S({imag_:MD});function UD(e){const t=b(e,"x","isFinite"),s={x:t};return v.runKernelFunc(n=>n.isFinite(t),s,null,yr)}const CS=S({isFinite_:UD});function $D(e){const t=b(e,"x","isInf"),s={x:t};return v.runKernelFunc(n=>n.isInf(t),s,null,br)}const RS=S({isInf_:$D});function WD(e){const t=b(e,"x","isNaN"),s={x:t};return v.runKernelFunc(n=>n.isNaN(t),s,null,wr)}const OS=S({isNaN_:WD});function zD(e,t){let s=b(e,"a","maximum"),n=b(t,"b","maximum");[s,n]=Ce(s,n),s.dtype==="bool"&&(s=G(s,"int32"),n=G(n,"int32")),Ie(s.shape,n.shape);const i=(o,a)=>{const l=o.maximum(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,$c)}const Ht=S({maximum_:zD});function j(e,t){if((Dt(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"&&Dt(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");const s=[],n=[];return us(e,s,n,t)}function PD(e,t=.2){const s=b(e,"x","leakyRelu");return Ht(R(j(t),s),s)}const rl=S({leakyRelu_:PD});function BD(e,t){let s=b(e,"a","less"),n=b(t,"b","less");[s,n]=Ce(s,n),Ie(s.shape,n.shape);const i=o=>o.less(s,n),r={a:s,b:n};return v.runKernelFunc(i,r,null,Mg)}const zr=S({less_:BD});function jD(e,t){let s=b(e,"a","lessEqual"),n=b(t,"b","lessEqual");[s,n]=Ce(s,n),Ie(s.shape,n.shape);const i=(o,a)=>{const l=o.lessEqual(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,Ug)}const $s=S({lessEqual_:jD});function Ah(e,t,s){if(s<=0)throw new Error("The number of values should be positive.");const n={start:e,stop:t,num:s};return v.runKernelFunc(i=>i.linspace(e,t,s),{},null,$g,n)}function VD(e,t=5,s=1,n=1,i=.5){const r=b(e,"x","localResponseNormalization");I(r.rank===4||r.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
rank ${r.rank}.`),I(ke(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let o=r,a=!1;r.rank===3&&(a=!0,o=O(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const l=(h,d)=>{const m=h.localResponseNormalization4D(o,t,s,n,i);return d([o,m]),m},c={x:o},p={depthRadius:t,bias:s,alpha:n,beta:i},u=v.runKernelFunc(l,c,null,Uc,p);return a?O(u,[u.shape[1],u.shape[2],u.shape[3]]):u}const Nh=S({localResponseNormalization_:VD});function GD(e){const t=b(e,"x","log"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.log(t);return i([t]),r},s,null,xr)}const zt=S({log_:GD});function qD(e){const t=b(e,"x","log1p"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.log1p(t);return i([t]),r},s,null,Lr)}const ol=S({log1p_:qD});function HD(e){return I(si(e),()=>"The f passed in grad(f) must be a function"),(t,s)=>{const n=b(t,"x","tf.grad",null),i=s!=null?b(s,"dy","tf.grad"):null;return v.tidy(()=>{const{value:r,grads:o}=v.gradients(()=>e(n),[n],i);return i!=null&&Se(r.shape,i.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Ch(o),o[0]})}}function YD(e){return I(si(e),()=>"The f passed in grads(f) must be a function"),(t,s)=>{I(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");const n=Ei(t,"args","tf.grads",null),i=s!=null?b(s,"dy","tf.grads"):null;return v.tidy(()=>{const{value:r,grads:o}=v.gradients(()=>e(...n),n,i);return i!=null&&Se(r.shape,i.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Ch(o),o})}}function KD(e){return I(si(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,s)=>{I(t instanceof me,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),I(s==null||s instanceof me,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");const{grads:n,value:i}=v.gradients(()=>e(t),[t],s);return Ch(n),{grad:n[0],value:i}}}function XD(e){return I(si(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,s)=>{I(Array.isArray(t)&&t.every(i=>i instanceof me),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),I(s==null||s instanceof me,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");const n=v.gradients(()=>e(...t),t,s);return s!=null&&Se(n.value.shape,s.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Ch(n.grads),n}}function Rh(e,t){I(si(e),()=>"The f passed in variableGrads(f) must be a function"),I(t==null||Array.isArray(t)&&t.every(c=>c instanceof oi),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const s=t!=null;if(!s){t=[];for(const c in v.registeredVariables)t.push(v.registeredVariables[c])}const n=s?t.filter(c=>!c.trainable):null,i=t.length;t=t.filter(c=>c.trainable),I(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${i} variables is trainable.`);const r=!0,{value:o,grads:a}=v.gradients(e,t,null,r);I(a.some(c=>c!=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()."),I(o.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${o.rank} tensor`);const l={};return t.forEach((c,p)=>{a[p]!=null&&(l[c.name]=a[p])}),n!=null&&n.forEach(c=>l[c.name]=null),{value:o,grads:l}}function ms(e){return v.customGrad(e)}function Ch(e){const t=e.filter(s=>s==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 JD(e){const t=b(e,"x","neg"),s={x:t};return v.runKernelFunc(n=>n.neg(t),s,null,jc)}const _e=S({neg_:JD});function ZD(e){const t=b(e,"x","softplus"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.softplus(t);return i([t]),r},s,null,Or)}const pi=S({softplus_:ZD});function QD(e){const t=b(e,"x","logSigmoid"),s=ms(n=>{const i=_e(pi(_e(n))),r=o=>{const a=R(o,rs(_e(n)));return a};return{value:i,gradFunc:r}});return s(t)}const ES=S({logSigmoid_:QD});function eF(e,t=null,s=!1){const n=b(e,"x","max"),i=(a,l)=>{const c=Ne(t,n.shape);let p=c;const u=ht(p,n.rank);let h=n;u!=null&&(h=se(n,u),p=qt(p.length,h.rank));const d=a.max(h,p);u!=null&&h.dispose();let m=d;if(s){const f=bt(m.shape,Ne(t,n.shape));m=O(m,f),d.dispose()}return l([n,m]),m},r={x:n},o={reductionIndices:t,keepDims:s};return v.runKernelFunc(i,r,null,Ai,o)}const xt=S({max_:eF});function tF(e,t){let s=b(e,"a","sub"),n=b(t,"b","sub");[s,n]=Ce(s,n);const i=(o,a)=>{const l=o.subtract(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,_r)}const X=S({sub_:tF});function sF(e,t=null,s=!1){let n=b(e,"x","sum");n.dtype==="bool"&&(n=G(n,"int32"));const i=(a,l)=>{l([n]);const c=Ne(t,n.shape),p=ht(c,n.rank);let u=c,h=n;p!=null&&(h=se(n,p),u=qt(u.length,n.rank));let d=a.sum(h,u);if(s){const m=bt(d.shape,c);d=O(d,m)}return d},r={x:n},o={axis:t,keepDims:s};return v.runKernelFunc(i,r,null,sp,o)}const te=S({sum_:sF});function nF(e,t=-1){const s=b(e,"logits","logSoftmax");if(t===-1&&(t=s.rank-1),t!==s.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${s.rank} and axis was ${t}`);const n=(o,a)=>{const l=!0,c=xt(e,t,!0),p=X(e,c),u=X(G(p,"float32"),zt(te(ut(p),t,l)));return a([u]),u},i={logits:s},r={axis:t};return v.runKernelFunc(n,i,null,Mc,r)}const al=S({logSoftmax_:nF});function iF(e,t=null,s=!1){const n=b(e,"x","logSumExp"),i=Ne(t,n.shape),r=xt(n,i,!0),o=X(n,r),a=ut(o),l=te(a,i),c=zt(l),p=$(O(r,c.shape),c);if(s){const u=bt(p.shape,i);return O(p,u)}return p}const Oh=S({logSumExp_:iF});function rF(e,t){const s=b(e,"a","logicalAnd","bool"),n=b(t,"b","logicalAnd","bool");Ie(s.shape,n.shape);const i={a:s,b:n};return v.runKernelFunc(r=>r.logicalAnd(s,n),i,null,Wg)}const Yt=S({logicalAnd_:rF});function oF(e){const t=b(e,"x","logicalNot","bool"),s={x:t};return v.runKernelFunc(n=>n.logicalNot(t),s,null,_a)}const Pr=S({logicalNot_:oF});function aF(e,t){const s=b(e,"a","logicalOr","bool"),n=b(t,"b","logicalOr","bool");Ie(s.shape,n.shape);const i={a:s,b:n};return v.runKernelFunc(r=>r.logicalOr(s,n),i,null,zg)}const ll=S({logicalOr_:aF});function lF(e,t){const s=b(e,"a","logicalXor","bool"),n=b(t,"b","logicalXor","bool");return Ie(s.shape,n.shape),Yt(ll(e,t),Pr(Yt(e,t)))}const _S=S({logicalXor_:lF});function cF(e,t,s,n,i){const r=b(e,"x","maxPool"),o=1;let a=r,l=!1;r.rank===3&&(l=!0,a=O(r,[1,r.shape[0],r.shape[1],r.shape[2]])),I(a.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${a.rank}.`),I(tt(s,o),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${o}'`),i!=null&&I(ke(n),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${i} but got pad ${n}.`);const c=(d,m)=>{const f=Fn(a.shape,t,s,1,n,i);let g;return f.filterWidth===1&&f.filterHeight===1&&Nt(f.inShape,f.outShape)?g=a.clone():g=d.maxPool(a,f),m([a,g]),g},p={x:a},u={filterSize:t,strides:s,pad:n,dimRoundingMode:i},h=v.runKernelFunc(c,p,null,Ni,u);return l?O(h,[h.shape[1],h.shape[2],h.shape[3]]):h}const mt=S({maxPool_:cF});function pF(e,t=[1,1,1],s,n,i,r="NDHWC",o){o==null?o=[1,1,1]:It("dilations is deprecated, this field will be gone in v3.0.0.");const a=b(e,"x","maxPool3d");let l=a,c=!1;a.rank===4&&(c=!0,l=O(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),I(l.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${l.rank}.`),I(r==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${r}`),I(tt(s,o),()=>`Error in maxPool3d: Either strides or dilations must be 1. Got strides ${s} and dilations '${o}'`),i!=null&&I(ke(n),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${n}.`);const p=(m,f)=>{o==null&&(o=[1,1,1]);const g=_i(l.shape,t,s,o,n,i,r),y=m.maxPool3d(l,g);return f([l,y]),y},u={x:l},h={filterSize:t,strides:s,pad:n,dimRoundingMode:i,dataFormat:r,dilations:o},d=v.runKernelFunc(p,u,null,Wc,h);return c?O(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}const cl=S({maxPool3d_:pF});function uF(e,t,s,n,i=!1){const r=b(e,"x","maxPoolWithArgmax"),o={x:r},a={filterSize:t,strides:s,pad:n,includeBatchInIndex:i},l=v.runKernel(vo,o,a);return{result:l[0],indexes:l[1]}}const Eh=S({maxPoolWithArgmax_:uF});function ye(e,t="float32"){if(t==="complex64"){const n=ye(e,"float32"),i=ye(e,"float32");return Gt(n,i)}const s=ii(We(e),t);return v.makeTensor(s,e,t)}function Kt(e,t="float32"){if(t==="complex64"){const n=Kt(e,"float32"),i=ye(e,"float32");return Gt(n,i)}const s=hp(We(e),t);return v.makeTensor(s,e,t)}function hF(e,t=null,s=!1){const n=b(e,"x","mean"),i=Ne(t,n.shape),r=Fy(n.shape,i),o=r[1],a=We(o),l=ms(c=>{const p=j(a),u=p.dtype===c.dtype?c:G(c,p.dtype),h=Z(u,p),d=te(h,t,s),m=f=>{const g=c.shape.slice();i.forEach(x=>{g[x]=1});const y=O(f,g),w=Z(R(y,Kt(c.shape,"float32")),a);return w};return{value:d,gradFunc:m}});return l(n)}const Ke=S({mean_:hF});function dF(e,t=null,s=!1){const n=b(e,"x","min"),i=(a,l)=>{const c=Ne(t,n.shape);let p=c;const u=ht(p,n.rank);let h=n;u!=null&&(h=se(n,u),p=qt(p.length,n.rank));const d=a.min(h,p);u!=null&&h.dispose();let m=d;if(s){const f=bt(m.shape,c);m=O(d,f),d.dispose()}return l([n,m]),m},r={x:n},o={axis:t,keepDims:s};return v.runKernelFunc(i,r,null,zc,o)}const Di=S({min_:dF});function mF(e,t){let s=b(e,"a","minimum"),n=b(t,"b","minimum");[s,n]=Ce(s,n),s.dtype==="bool"&&(s=G(s,"int32"),n=G(n,"int32")),Ie(s.shape,n.shape);const i=(o,a)=>{const l=o.minimum(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,Pc)}const mn=S({minimum_:mF});function fF(e,t){let s=b(e,"a","mod"),n=b(t,"b","mod");[s,n]=Ce(s,n);const i=(o,a)=>{const l=o.mod(s,n);return a([s,n]),l},r={a:s,b:n};return v.runKernelFunc(i,r,null,Bc)}const pl=S({mod_:fF});function gF(e){const t=b(e,"x","square"),s={},n=[t],i=[];return v.runKernelFunc((r,o)=>(o([t]),r.square(t)),{x:t},null,"Square",s,n,i)}const xe=S({square_:gF});function yF(e,t=null,s=!1){e=b(e,"x","moments");const n=Ne(t,e.shape),i=Ke(e,n,s);let r=i.shape;s||(r=bt(i.shape,n));const o=xe(X(G(e,"float32"),O(i,r))),a=Ke(o,n,s);return{mean:i,variance:a}}const Bo=S({moments_:yF});function bF(e,t,s,n){const i=b(t,"data","multiRNNCell"),r=Ei(s,"c","multiRNNCell"),o=Ei(n,"h","multiRNNCell");let a=i;const l=[];for(let u=0;u<e.length;u++){const h=e[u](a,r[u],o[u]);l.push(h[0]),l.push(h[1]),a=h[1]}const c=[],p=[];for(let u=0;u<l.length;u+=2)c.push(l[u]),p.push(l[u+1]);return[c,p]}const kS=S({multiRNNCell_:bF});function wF(e,t,s,n=!1){const i=b(e,"logits","multinomial"),r=i.size,o=i.rank;if(r<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${r}.`);if(o>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${o}`);s=s||Math.random();const a=o===1?O(i,[1,-1]):i,l=v.runKernelFunc(c=>c.multinomial(a,n,t,s),{logits2D:a});return o===1?O(l,[l.size]):l}const _h=S({multinomial_:wF});function xF(e,t){let s=b(e,"a","notEqual"),n=b(t,"b","notEqual");[s,n]=Ce(s,n),Ie(s.shape,n.shape);const i=o=>o.notEqual(s,n),r={a:s,b:n};return v.runKernelFunc(i,r,null,ka)}const Ks=S({notEqual_:xF});function LF(e){const t=b(e,"input","real"),s=i=>i.real(t),n={input:t};return v.runKernelFunc(s,n,null,Kc)}const Xs=S({real_:LF});function SF(e){const t=b(e,"x","onesLike"),s=(i,r)=>{if(t.dtype==="complex64"){const o=Ot(Xs(t)),a=re(dn(t));return Gt(o,a)}return i.onesLike(t)},n={x:t};return v.runKernelFunc(s,n,null,Gc)}const Ot=S({onesLike_:SF});function IF(e,t){const s=b(e,"v1","outerProduct"),n=b(t,"v2","outerProduct");I(s.rank===1&&n.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${s.rank} and ${n.rank}.`);const i=O(s,[-1,1]),r=O(n,[1,-1]);return Te(i,r)}const DS=S({outerProduct_:IF});function vF(e,t,s=0){const n=b(e,"x","pad");if(n.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const i=(a,l)=>(l([n]),a.pad(n,t,s)),r={paddings:t,constantValue:s},o={x:n};return v.runKernelFunc(i,o,null,No,r)}const Pt=S({pad_:vF});function TF(e,t,s=0){return I(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),Pt(e,[t],s)}const FS=S({pad1d_:TF});function AF(e,t,s=0){return I(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Pt(e,t,s)}const MS=S({pad2d_:AF});function NF(e,t,s=0){return I(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."),Pt(e,t,s)}const US=S({pad3d_:NF});function CF(e,t,s=0){return I(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."),Pt(e,t,s)}const $S=S({pad4d_:CF});function RF(e,t,s){const n=b(e,"x","spaceToBatchND");I(n.rank>=1+t.length,()=>`input rank ${n.rank} should be > than [blockShape] ${t.length}`),I(s.length===t.length,()=>`paddings.shape[0] ${s.length} must be equal to [blockShape] ${t.length}`),I(n.shape.reduce((a,l,c)=>c>0&&c<=t.length?a&&(l+s[c-1][0]+s[c-1][1])%t[c-1]===0:a,!0),()=>`input spatial dimensions ${n.shape.slice(1)} with paddings ${s.toString()} must be divisible by blockShapes ${t.toString()}`);const i=a=>a.spaceToBatchND(n,t,s),r={x:n},o={blockShape:t,paddings:s};return v.runKernelFunc(i,r,null,Ro,o)}const Br=S({spaceToBatchND_:RF});function _F(e,t,s,n,i,r){i==null&&(i=[1,1]),r==null&&(r=1),n===0&&(n="valid");const o=b(e,"x","maxPool");let a=o,l=!1;o.rank===3&&(l=!0,a=O(o,[1,o.shape[0],o.shape[1],o.shape[2]])),I(tt(r,i),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${r} and dilations '${i}'`);const c=Fn(a.shape,t,r,i,n),p=[c.dilationHeight,c.dilationWidth];let u;n==="same"?u=EF([c.filterHeight,c.filterWidth],p):u=[[0,0],[0,0]];const h=p[0]===1&&p[1]===1,[d,m]=OF([c.inHeight,c.inWidth],p,u),f=h?n:"valid",g=h?a:Br(a,p,d),y=s==="avg"?()=>hs(g,t,r,f):()=>mt(g,t,r,f),w=y(),x=h?w:$r(w,p,m);return l?O(x,[x.shape[1],x.shape[2],x.shape[3]]):x}function OF(e,t,s){const n=s.map(p=>p[0]),i=s.map(p=>p[1]),r=e.concat(n,i),o=t.map((p,u)=>(p-r[u]%p)%p),a=i.map((p,u)=>p+o[u]),l=t.map((p,u)=>[n[u],a[u]]),c=t.map((p,u)=>[0,o[u]]);return[l,c]}function EF(e,t){const s=e.map((o,a)=>o+(o-1)*(t[a]-1)),n=s.map(o=>o-1),i=n.map(o=>Math.floor(o/2)),r=n.map((o,a)=>o-i[a]);return n.map((o,a)=>[i[a],r[a]])}const WS=S({pool_:_F});function kF(e,t){let s=b(e,"base","pow"),n=b(t,"exp","pow");[s,n]=Ce(s,n);const i={a:s,b:n},r=(o,a)=>{const l=o.pow(s,n);return a([s,n,l]),l};return v.runKernelFunc(r,i,null,Hc)}const Qt=S({pow_:kF});function DF(e,t){const s=b(e,"x","prelu"),n=b(t,"alpha","prelu"),i=(o,a)=>{const l=o.prelu(s,n);return a([s,n]),l},r={x:s,alpha:n};return v.runKernelFunc(i,r,null,Yc)}const jr=S({prelu_:DF});function FF(e,t=null,s=!1){let n=b(e,"x","prod");const i=a=>{n.dtype==="bool"&&(n=G(n,"int32"));const l=Ne(t,n.shape),c=ht(l,n.rank);let p=l,u=n;c!=null&&(u=se(n,c),p=qt(p.length,n.rank));let h=a.prod(u,p);if(s){const d=bt(h.shape,l);h=O(h,d)}return h},r={x:n},o={axis:t,keepDims:s};return v.runKernelFunc(i,r,null,jg,o)}const ul=S({prod_:FF});function MF(e,t,s){const n=We(e);let i=null;if(s==null||s==="float32")i=new Float32Array(n);else if(s==="int32")i=new Int32Array(n);else if(s==="bool")i=new Uint8Array(n);else throw new Error(`Unknown data type ${s}`);for(let r=0;r<n;r++)i[r]=t();return v.makeTensor(i,e,s)}const zS=S({rand_:MF});const kh=mc(fc());class Ap{constructor(e,t,s,n,i){this.mean=e,this.stdDev=t,this.dtype=s,this.nextVal=NaN,this.truncated=n,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);const r=i||Math.random();this.random=kh.alea(r.toString())}nextValue(){if(!isNaN(this.nextVal)){const n=this.nextVal;return this.nextVal=NaN,n}let e,t,s=!1;for(;!s;){let n,i,r;do n=2*this.random()-1,i=2*this.random()-1,r=n*n+i*i;while(r>=1||r===0);const o=Math.sqrt(-2*Math.log(r)/r);e=this.mean+this.stdDev*n*o,t=this.mean+this.stdDev*i*o,(!this.truncated||this.isValidTruncated(e))&&(s=!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 PS{constructor(e,t,s,n){this.alpha=e,this.beta=1/t,this.dtype=s;const i=n||Math.random();this.randu=kh.alea(i.toString()),this.randn=new Ap(0,1,s,!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,s,n,i,r;for(;;){do n=this.randn.nextValue(),r=1+this.c*n;while(r<=0);if(r*=r*r,e=n*n,t=1-.331*e*e,s=.5*e+this.d*(1-r+Math.log(r)),i=this.randu(),i<t||Math.log(i)<s)break}return r=1/this.beta*this.d*r,this.alpha<1&&(r*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(r)}convertValue(e){return this.dtype==="float32"?e:Math.round(e)}}class BS{constructor(e=0,t=1,s,n){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=s,n==null&&(n=Math.random()),typeof n=="number"&&(n=n.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=kh.alea(n)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}function UF(e,t,s=1,n="float32",i){if(s==null&&(s=1),n==null&&(n="float32"),n!=="float32"&&n!=="int32")throw new Error(`Unsupported data type ${n}`);const r=new PS(t,s,n,i),o=ge(e,n);for(let a=0;a<o.values.length;a++)o.values[a]=r.nextValue();return o.toTensor()}const jS=S({randomGamma_:UF});function $F(e,t=0,s=1,n,i){if(n!=null&&n==="bool")throw new Error(`Unsupported data type ${n}`);const r=new Ap(t,s,n,!1,i),o=ge(e,n);for(let a=0;a<o.values.length;a++)o.values[a]=r.nextValue();return o.toTensor()}const Np=S({randomNormal_:$F});function WF(e,t=0,s=1,n="float32",i){const r=ge(e,n),o=new BS(t,s,null,i);for(let a=0;a<r.values.length;a++)r.values[a]=o.nextValue();return r.toTensor()}const fn=S({randomUniform_:WF});function Oe(e,t){qs(e);const s=Zt(e,t);if(s.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");const n=null;return us(e,n,s,t)}function Fi(e,t,s=1,n="float32"){if(s===0)throw new Error("Cannot have a step of zero");const i=()=>{const o=e===t,a=e<t&&s<0,l=t<e&&s>1;if(o||a||l)return ye([0],n);const c=Math.abs(Math.ceil((t-e)/s)),p=ii(c,n);t<e&&s===1&&(s=-1),p[0]=e;for(let u=1;u<p.length;u++)p[u]=p[u-1]+s;return Oe(p,n)},r={start:e,stop:t,step:s,dtype:n};return v.runKernelFunc(i,{},null,Vg,r)}function zF(e){const t=b(e,"x","reciprocal"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.reciprocal(t);return i([t]),r},s,null,Ir)}const Dh=S({reciprocal_:zF});function PF(e){const t=b(e,"x","relu"),s=(i,r)=>(r([t]),t.dtype==="bool"?G(t,"int32"):i.relu(t)),n={x:t};return v.runKernelFunc(s,n,null,Xc)}const De=S({relu_:PF});function BF(e){const t=b(e,"x","relu6"),s=(i,r)=>(r([t]),t.dtype==="bool"?G(t,"int32"):i.relu6(t)),n={x:t};return v.runKernelFunc(s,n,null,Qc)}const Fh=S({relu6_:BF});function jF(e,t){const s=b(e,"x","reverse"),n=o=>{const a=Ne(t,s.shape);if(s.rank===0)return Ds(s);const l=o.reverse(s,a);return O(l,s.shape)},i={x:s},r={dims:t};return v.runKernelFunc(n,i,null,ep,r)}const Et=S({reverse_:jF});function VF(e){const t=b(e,"x","reverse");return I(t.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),Et(t,0)}const VS=S({reverse1d_:VF});function GF(e,t){const s=b(e,"x","reverse");return I(s.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${s.rank}.`),Et(s,t)}const GS=S({reverse2d_:GF});function qF(e,t){const s=b(e,"x","reverse");return I(s.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${s.rank}.`),Et(s,t)}const qS=S({reverse3d_:qF});function HF(e,t){const s=b(e,"x","reverse");return I(s.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${s.rank}.`),Et(s,t)}const HS=S({reverse4d_:HF});function YF(e){const t=b(e,"x","round"),s={x:t};return v.runKernelFunc(n=>n.round(t),s,null,vr)}const Mh=S({round_:YF});function KF(e){const t=b(e,"x","rsqrt"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.rsqrt(t);return i([t]),r},s,null,Tr)}const hl=S({rsqrt_:KF});function XF(e){const t=b(e,"x","selu"),s=(i,r)=>{const o=i.selu(t);return r([t]),o},n={x:t};return v.runKernelFunc(s,n,null,Ar)}const dl=S({selu_:XF});function JF(e,t,s,n,i,r=[1,1],o="NHWC"){const a=b(e,"x","separableConv2d"),l=b(t,"depthwiseFilter","separableConv2d"),c=b(s,"pointwiseFilter","separableConv2d");let p=a,u=!1;if(a.rank===3&&(u=!0,p=O(a,[1,a.shape[0],a.shape[1],a.shape[2]])),o==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");I(p.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${p.rank}.`),I(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),I(c.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),I(c.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${c.shape[0]}.`),I(c.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${c.shape[1]}.`);const h=l.shape[2],d=l.shape[3];I(c.shape[2]===h*d,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${h*d}, but got ${c.shape[2]}.`);const m=un(p,l,n,i,o,r),f=1,g=nt(m,c,f,"valid",o);return u?O(g,[g.shape[1],g.shape[2],g.shape[3]]):g}const Vr=S({separableConv2d_:JF});async function ZF(e,t){const s=b(e,"x","setdiff1d"),n=b(t,"y","setdiff1d");I(s.dtype===n.dtype,()=>`x and y should have the same dtype, but got x (${s.dtype}) and y (${n.dtype}).`),I(s.rank===1,()=>`x should be 1D tensor, but got x (${s.shape}).`),I(n.rank===1,()=>`y should be 1D tensor, but got y (${n.shape}).`);const i=await s.data(),r=await n.data(),o=new Set(r);let a=0;for(let p=0;p<i.length;p++)o.has(i[p])||a++;const l=new cn([a],s.dtype),c=new cn([a],"int32");for(let p=0,u=0;p<i.length;p++)o.has(i[p])||(l.values[u]=i[p],c.values[u]=p,u++);return[l.toTensor(),c.toTensor()]}const Uh=ZF;function QF(e){const t=b(e,"x","sign"),s={x:t};return v.runKernelFunc(n=>n.sign(t),s,null,Cr)}const $h=S({sign_:QF});function eM(e){const t=b(e,"x","sin"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.sin(t);return i([t]),r},s,null,Zn)}const ml=S({sin_:eM});function tM(e){const t=b(e,"x","sinh"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.sinh(t);return i([t]),r},s,null,Nr)}const fl=S({sinh_:tM});function sM(e,t,s){const n=b(e,"x","slice1d");return I(n.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${n.rank} tensor`),he(n,[t],[s])}const gl=S({slice1d_:sM});function nM(e,t,s){const n=b(e,"x","slice2d");return I(n.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${n.rank} tensor`),he(n,t,s)}const Cp=S({slice2d_:nM});function iM(e,t,s){const n=b(e,"x","slice3d");return I(n.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${n.rank} tensor`),he(n,t,s)}const Gr=S({slice3d_:iM});function rM(e,t,s){const n=b(e,"x","slice4d");return I(n.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${n.rank} tensor`),he(n,t,s)}const jo=S({slice4d_:rM});function oM(e,t=-1){const s=b(e,"logits","softmax","float32");if(t===-1&&(t=s.rank-1),t!==s.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${s.rank} and dim was ${t}`);const n={logits:s},i={dim:t};return v.runKernelFunc((r,o)=>{const a=r.softmax(s,t);return o([a]),a},n,null,ip,i)}const es=S({softmax_:oM});function aM(e){I(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);const t={input:e};return v.runKernelFunc(s=>{const n=e.shape[e.shape.length-1],i=e.size/n,r=e.as2D(i,n),o=s.fft(r);return o.reshape(e.shape)},t,null,Oc)}const qr=S({fft_:aM});function lM(e){I(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);const t={input:e};return v.runKernelFunc(s=>{const n=e.shape[e.shape.length-1],i=e.size/n,r=O(e,[i,n]),o=s.ifft(r);return O(o,e.shape)},t,null,Dc)}const Mi=S({ifft_:lM});function cM(e){const t=e.shape[e.shape.length-1],s=e.size/t;let n;if(t<=2){const i=O(e,[s,t]);n=Mi(i)}else{const i=[s,2*(t-1)],r=O(Xs(e),[s,t]),o=O(dn(e),[s,t]),a=Et(he(r,[0,1],[s,t-2]),1),l=R(Et(he(o,[0,1],[s,t-2]),1),j(-1)),c=be([r,a],1),p=be([o,l],1),u=O(Gt(c,p),[i[0],i[1]]);n=Mi(u)}if(n=Xs(n),e.rank===3&&e.shape[0]!==0){const i=n,r=e.shape[0];n=O(n,[r,n.shape[0]/r,n.shape[1]]),i.dispose()}return n}const yl=S({irfft_:cM});function Py(e,t,s=0){let n=[];if(typeof t=="number")I(e.shape[s]%t===0,()=>"Number of splits must evenly divide the axis."),n=new Array(t).fill(e.shape[s]/t);else{const i=t.reduce((o,a)=>(a===-1&&(o+=1),o),0);I(i<=1,()=>"There should be only one negative value in split array.");const r=t.indexOf(-1);if(r!==-1){const o=t.reduce((a,l)=>l>0?a+l:a);t[r]=e.shape[s]-o}I(e.shape[s]===t.reduce((o,a)=>o+a),()=>"The sum of sizes must match the size of the axis dimension."),n=t}return n}function pM(e,t,s=0){const n=b(e,"x","split"),i=(a,l)=>{const c=Ne(s,n.shape)[0],p=Py(n,t,c);return a.split(n,p,c)},r={x:n},o={numOrSizeSplits:t,axis:s};return v.runKernelFunc(i,r,null,np,o)}const Bt=S({split_:pM});function uM(e,t){I(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let s=e.shape[e.shape.length-1];const n=e.size/s;let i;if(t!=null&&t<s){const m=e.shape.map(g=>0),f=e.shape.map(g=>g);f[e.shape.length-1]=t,i=he(e,m,f),s=t}else if(t!=null&&t>s){const m=e.shape.map(f=>f);m[e.shape.length-1]=t-s,i=be([e,ye(m)],e.shape.length-1),s=t}else i=e;const r=re(i),o=O(Gt(i,r),[n,s]),a=qr(o),l=Math.floor(s/2)+1,c=Xs(a),p=dn(a),u=Bt(c,[l,s-l],c.shape.length-1),h=Bt(p,[l,s-l],p.shape.length-1),d=i.shape.slice();return d[i.shape.length-1]=l,O(Gt(u[0],h[0]),d)}const Hr=S({rfft_:uM});function hM(e){const t=b(e,"x","sqrt"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.sqrt(t);return i([t]),r},s,null,Er)}const Xe=S({sqrt_:hM});function dM(e,t){let s=b(e,"a","squaredDifference"),n=b(t,"b","squaredDifference");[s,n]=Ce(s,n),Ie(s.shape,n.shape);const i=(a,l)=>{const c=a.squaredDifference(s,n);return l([s,n]),c},r={a:s,b:n},o={};return v.runKernelFunc(i,r,null,Qn,o)}const Yr=S({squaredDifference_:dM});function mM(e,t){const s=b(e,"x","squeeze");return O(s,ey(s.shape,t).newShape)}const Js=S({squeeze_:mM});function fM(e,t=0){const s=Ei(e,"tensors","stack");if(I(s.length>=1,()=>"Pass at least one tensor to tf.stack"),s.length===1)return Mt(s[0],t);const n=s[0].rank,i=s[0].shape,r=s[0].dtype;I(t<=n,()=>"Axis must be <= rank of the tensor"),s.forEach(a=>{Se(i,a.shape,"All tensors passed to stack must have matching shapes"),I(r===a.dtype,()=>"All tensors passed to stack must have matching dtypes")});const o=s.map(a=>Mt(a,t));return be(o,t)}const Ve=S({stack_:fM});function gM(e,t=0){const s=b(e,"x","step"),n={x:s},i={alpha:t};return v.runKernelFunc(r=>r.step(s,t),n,null,Dr,i)}const ui=S({step_:gM});function yM(e,t,s,n,i=0,r=0,o=0,a=0,l=0){let c=b(e,"x","stridedSlice");const p=d=>{n==null&&(n=new Array(t.length));const m=Ip(o);if(m.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(o!==0&&a!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(o!==0&&l!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");const f=c.rank-t.length,g=Ip(a),y=c.shape.slice();g.forEach(M=>{t[M]=0,s[M]=1,y.splice(M,0,1)}),c=O(c,y);const{begin:w,end:x,strides:T}=Ny(c.shape,m,f,t,s,n,i,r,o);t=w,s=x,n=T;const A=Ip(l);A.forEach(M=>{s[M]=t[M]+1,n[M]=1});const _=Ay(t,s,n),E=_.filter((M,P)=>A.indexOf(P)===-1),F=n.every(M=>M===1);if(F)return O(he(c,t,_),E);const D=d.stridedSlice(c,t,s,n);return O(D,E)},u={x:c},h={begin:t,end:s,strides:n,beginMask:i,endMask:r,ellipsisMask:o,newAxisMask:a,shrinkAxisMask:l};return v.runKernelFunc(p,u,null,Kg,h)}const Wh=S({stridedSlice_:yM});function bM(e){const t=b(e,"x","tan"),s={x:t};return v.runKernelFunc((n,i)=>{const r=n.tan(t);return i([t]),r},s,null,ei)}const zh=S({tan_:bM});function as(e,t,s){if(qs(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");const n=Zt(e,s);if(n.length!==2&&n.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return us(e,t,n,s)}function ts(e,t,s){if(qs(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");const n=Zt(e,s);if(n.length!==4&&n.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return us(e,t,n,s)}function YS(e,t,s){if(qs(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");const n=Zt(e,s);if(n.length!==5&&n.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return us(e,t,n,s)}function KS(e,t,s){if(qs(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");const n=Zt(e,s);if(n.length!==6&&n.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||n,us(e,t,n,s)}function wM(e,t=1,s=!0){const n=b(e,"x","topk");if(n.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");const i=n.shape[n.shape.length-1];if(t>i)throw new Error(`'k' passed to topk() must be <= the last dimension (${i}) but got ${t}`);const r={x:n},o={k:t,sorted:s},[a,l]=v.runKernelFunc(c=>c.topk(n,t,s),r,null,Xg,o);return{values:a,indices:l}}const Ph=S({topk_:wM});function xM(e,t=0,s=1,n,i){if(n!=null&&n==="bool")throw new Error("Unsupported data type $ { dtype }");const r=new Ap(t,s,n,!0,i),o=ge(e,n);for(let a=0;a<o.values.length;a++)o.values[a]=r.nextValue();return o.toTensor()}const Kr=S({truncatedNormal_:xM});function LM(e,t=0){const s=b(e,"x","unique",null);I(s.rank>0,()=>"The input tensor must be at least 1D");const n={x:s},i={axis:t},[r,o]=v.runKernel(Eo,n,i);return{values:r,indices:o}}const Rp=S({unique_:LM});function SM(e,t,s){const n=b(e,"x","unsortedSegmentSum"),i=b(t,"segmentIds","unsortedSegmentSum","int32");I(ke(s),()=>"numSegments must be of dtype int");const r={x:n,segmentIds:i},o={numSegments:s},a=(l,c)=>{const p=l.unsortedSegmentSum(n,i,s);return c([i]),p};return v.runKernelFunc(a,r,null,ap,o)}const Bh=S({unsortedSegmentSum_:SM});function IM(e,t=0){const s=b(e,"x","unstack");I(t>=-s.shape.length&&t<s.shape.length,()=>`Axis = ${t} is not in [-${s.shape.length}, ${s.shape.length})`),t<0&&(t+=s.shape.length);const n={value:s},i={axis:t},r=o=>o.unstack(s,t);return v.runKernelFunc(r,n,null,op,i)}const Ge=S({unstack_:IM});function jh(e,t=!0,s,n){return v.makeVariable(e,t,s,n)}function Vh(e,t){const s=[];for(let r=0;r<t.length;r++)t[r]&&s.push(r);const n=ge(e,"int32"),i=ge([s.length,e.length],"int32");for(let r=0;r<s.length;r++){const o=n.indexToLoc(s[r]),a=r*e.length;i.values.set(o,a)}return i.toTensor()}async function vM(e){const t=b(e,"condition","whereAsync","bool"),s=await t.data(),n=Vh(t.shape,s);return e!==t&&t.dispose(),n}const bl=vM;async function TM(e,t,s){const n=b(e,"tensor","boolMask"),i=b(t,"mask","boolMask","bool"),r=s??0,o=i.rank,a=n.shape;I(o>0,()=>"mask cannot be scalar"),Se(a.slice(r,r+o),i.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let f=r;f<r+o;f++)l*=a[f];const c=a.slice(0,r).concat([l],a.slice(r+o)),p=O(n,c),u=O(i,[-1]),h=await bl(u),d=Js(h,[1]),m=ci(p,d,r);return e!==n&&n.dispose(),t!==i&&i.dispose(),d.dispose(),p.dispose(),u.dispose(),h.dispose(),m}const AM=TM;function NM(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","notEqualStrict"),n=b(t,"b","notEqualStrict");return Se(s.shape,n.shape,"Error in notEqualStrict: "),Ks(s,n)}function CM(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","lessStrict"),n=b(t,"b","lessStrict");return Se(s.shape,n.shape,"Error in lessStrict: "),zr(s,n)}function RM(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","equalStrict"),n=b(t,"b","equalStrict");return Se(s.shape,n.shape,"Error in equalStrict: "),os(s,n)}function OM(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","lessEqualStrict"),n=b(t,"b","lessEqualStrict");return Se(s.shape,n.shape,"Error in lessEqualStrict: "),$s(s,n)}function EM(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","greaterStrict"),n=b(t,"b","greaterStrict");return Se(s.shape,n.shape,"Error in greaterStrict: "),Ut(s,n)}function _M(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","greaterEqualStrict"),n=b(t,"b","greaterEqualStrict");return Se(s.shape,n.shape,"Error in greaterEqualStrict: "),ds(s,n)}const kM=S({equalStrict_:RM}),DM=S({greaterEqualStrict_:_M}),FM=S({greaterStrict_:EM}),MM=S({lessEqualStrict_:OM}),UM=S({lessStrict_:CM}),$M=S({notEqualStrict_:NM});function WM(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","addStrict"),n=b(t,"b","addStrict");return Se(s.shape,n.shape,"Error in addStrict: "),$(s,n)}function zM(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","subStrict"),n=b(t,"b","subStrict");return Se(s.shape,n.shape,"Error in subStrict: "),X(s,n)}function PM(e,t){return It("strict variants of ops have been deprecated and will be removed in future"),Se(e.shape,t.shape,"Error in powStrict: "),Qt(e,t)}function BM(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","mul"),n=b(t,"b","mul");return Se(s.shape,n.shape,"Error in multiplyStrict: "),R(s,n)}function jM(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","div"),n=b(t,"b","div");return Se(s.shape,n.shape,"Error in divideStrict: "),Z(s,n)}function VM(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","modStrict"),n=b(t,"b","modStrict");return Se(s.shape,n.shape,"Error in modStrict: "),pl(s,n)}function GM(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","minimumStrict"),n=b(t,"b","minimumStrict");return Se(s.shape,n.shape,"Error in minimumStrict: "),mn(s,n)}function qM(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","maximumStrict"),n=b(t,"b","maximumStrict");return Se(s.shape,n.shape,"Error in maximumStrict: "),Ht(s,n)}function HM(e,t){It("strict variants of ops have been deprecated and will be removed in future");const s=b(e,"a","squaredDifferenceStrict"),n=b(t,"b","squaredDifferenceStrict");return Se(s.shape,n.shape,"Error in squaredDifferenceStrict: "),Yr(s,n)}const YM=S({addStrict_:WM}),KM=S({divStrict_:jM}),XM=S({maximumStrict_:qM}),JM=S({minimumStrict_:GM}),ZM=S({modStrict_:VM}),QM=S({mulStrict_:BM}),eU=S({powStrict_:PM}),tU=S({squaredDifferenceStrict_:HM}),sU=S({subStrict_:zM});function nU(e,t="euclidean",s=null,n=!1){e=b(e,"x","norm");const i=XS(e,t,s);let r=i.shape;if(n){const o=Ne(s,e.shape);r=bt(i.shape,o)}return O(i,r)}function XS(e,t,s=null){if(e.rank===0)return et(e);if(e.rank!==1&&s===null)return XS(O(e,[-1]),t,s);if(e.rank===1||typeof s=="number"||Array.isArray(s)&&s.length===1){if(t===1)return te(et(e),s);if(t===Infinity)return xt(et(e),s);if(t===-Infinity)return Di(et(e),s);if(t==="euclidean"||t===2)return Xe(te(Qt(et(e),j(2,"int32")),s));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(s)&&s.length===2){if(t===1)return xt(te(et(e),s[0]),s[1]-1);if(t===Infinity)return xt(te(et(e),s[1]),s[0]);if(t===-Infinity)return Di(te(et(e),s[1]),s[0]);if(t==="fro"||t==="euclidean")return Xe(te(xe(e),s));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${s}`)}const Op=S({norm_:nU});function iU(e,t,s,n,i=!0){const r=b(e,"v","movingAverage"),o=b(t,"x","movingAverage"),a=b(s,"decay","movingAverage");hy(r,o),I(Nt(r.shape,o.shape),()=>"Shape mismatch in v and x");const l=j(1),c=X(l,a);let p=R(X(o,r),c);if(i){I(n!=null,()=>"When using zeroDebias: true, step is required.");const u=b(n,"step","movingAverage");p=Z(p,X(l,Qt(a,u)))}return $(r,p)}const rU=S({movingAverage_:iU});function oU(e,t,s){const n=b(e,"indices","scatterND","int32"),i=b(t,"updates","scatterND");Qu(i,n,s);const r=l=>l.scatterND(n,i,s),o={indices:n,updates:i},a={shape:s};return v.runKernelFunc(r,o,null,Hg,a)}const By=S({scatterND_:oU});function JS(e,t,s,n){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,r=e.rank>1?e.shape[1]:1;if(s.length!==r)throw new Error(`outputShape has incorrect number of elements:, ${s.length}, should be: ${r}.`);const o=t.size;if(!(t.rank===0||t.rank===1&&o===i))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${i}]`);if(t.dtype!==n.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function aU(e,t,s,n=0){const i=b(e,"sparseIndices","sparseToDense","int32"),r=b(t,"sparseValues","sparseToDense"),o=b(n,"defaultValue","sparseToDense",r.dtype);JS(i,r,s,o);const a={sparseIndices:i,sparseValues:r,defaultValue:o},l={outputShape:s};return v.runKernelFunc(c=>c.sparseToDense(i,r,s,o),a,null,Yg,l)}const Ep=S({sparseToDense_:aU});function lU(e,t){const s=b(t,"indices","gatherND","int32"),n=b(e,"x","gatherND"),i=o=>o.gatherND(n,s),r={params:n,indices:s};return v.runKernelFunc(i,r,null,Dg)}const jy=S({gatherND_:lU});function ZS(e,t){if(t==null)return e.shape.slice();if(Nt(e.shape,t))return t;if(e.shape.length===t.length){const s=[];for(let n=0;n<e.shape.length;n++)t[n]==null&&e.shape[n]!=null?s.push(e.shape[n]):s.push(t[n]);return s}return t}function cU(e,t,s,n){const i=b(e,"x","dropout");if(I(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.`),I(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof me?i.clone():i;const r=ZS(i,s),o=1-t,a=Z(li($(fn(r,0,1,"float32",n),o)),o);return R(i,a)}const Vy=S({dropout_:cU});function Gy(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function _p(e,t,s){const n=1-e%2,i=new Float32Array(e);for(let r=0;r<e;++r){const o=2*Math.PI*r/(e+n-1);i[r]=t-s*Math.cos(o)}return Oe(i,"float32")}async function pU(e,t,s=1){const n=b(e,"predictions","inTopK"),i=b(t,"targets","inTopK");I(n.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${n.rank}`),I(n.rank-1===i.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${n.rank} and targets rank ${i.rank}`),Se(n.shape.slice(0,n.shape.length-1),i.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const r=n.shape[n.shape.length-1];I(s>0&&s<=r,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${r}), but got ${s}`);const o=await n.data(),a=await i.data(),[l,c]=[o.length/r,r],p=$a("bool",l);for(let u=0;u<l;u++){const h=u*c,d=o.subarray(h,h+c),m=[];for(let f=0;f<d.length;f++)m.push({value:d[f],index:f});m.sort((f,g)=>g.value-f.value),p[u]=0;for(let f=0;f<s;f++)if(m[f].index===a[u]){p[u]=1;break}}return e!==n&&n.dispose(),t!==i&&i.dispose(),ze(p,i.shape,"bool")}const uU=pU;function hU(e,t,s,n,i,r="NHWC",o){let a=e;e.rank===3&&(a=O(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=O(t,[1,t.shape[0],t.shape[1],t.shape[2]])),I(a.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${a.shape}.`),I(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),I(s.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${s}.`);const c=r==="NHWC"?a.shape[3]:a.shape[1],p=r==="NHWC"?l.shape[3]:l.shape[1];I(c===s[2],()=>`Error in conv2dDerFilter: depth of input ${c}) must match input depth in filter (${s[2]}.`),I(p===s[3],()=>`Error in conv2dDerFilter: depth of dy (${p}) must match output depth for filter (${s[3]}).`),o!=null&&I(ke(i),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${o} but got pad ${i}.`);const u=m=>{const f=1,g=Mr(r),y=is(a.shape,s,n,f,i,o,!1,g);return m.conv2dDerFilter(a,l,y)},h={x:a,dy:l},d={strides:n,pad:i,dataFormat:r,dimRoundingMode:o};return v.runKernelFunc(u,h,null,Ig,d)}const wl=S({conv2DBackpropFilter_:hU});function Vo(e,t,s){if(s==null||s==="linear")return e;if(s==="relu")return R(e,ui(t));throw new Error(`Cannot compute gradient for fused activation ${s}.`)}function Go(e,t){let s=t;const n=Ye(e.shape,t.shape);return n.length>0&&(s=te(s,n)),O(s,e.shape)}function qo(e,t,s){if(t==="linear")return e;if(t==="relu")return De(e);if(t==="elu")return hn(e);if(t==="relu6")return Fh(e);if(t==="prelu")return jr(e,s);throw new Error(`Unknown fused activation ${t}.`)}const Ho=(e,t)=>{const s=e>0;return!s||t==="linear"};function dU({x:e,filter:t,strides:s,pad:n,dataFormat:i="NHWC",dilations:r=[1,1],dimRoundingMode:o,bias:a,activation:l="linear",preluActivationWeights:c}){if(l=l||"linear",Ho(v.state.gradientDepth,l)===!1){let A=nt(e,t,s,n,i,r,o);return a!=null&&(A=$(A,a)),qo(A,l,c)}const p=b(e,"x","conv2d"),u=b(t,"filter","conv2d");let h=p,d=!1;p.rank===3&&(d=!0,h=O(p,[1,p.shape[0],p.shape[1],p.shape[2]])),I(h.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${h.rank}.`),I(u.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${u.rank}.`),o!=null&&I(ke(n),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`),I(h.shape[3]===u.shape[2],()=>`Error in conv2d: depth of input (${h.shape[3]}) must match input depth for filter ${u.shape[2]}.`),I(tt(s,r),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`),I(i==="NHWC",()=>`Error in conv2d: got dataFormat of ${i} but only NHWC is currently supported.`);const m=is(h.shape,u.shape,s,r,n,o);let f;a!=null&&(f=b(a,"bias","fused conv2d"),[f]=Ce(f,p),Ie(m.outShape,f.shape));let g;c!=null&&(g=b(c,"prelu weights","fused conv2d"));const y=(A,_)=>{const[E,F,D,M]=_,P=Vo(A,D,l);I(Hs(r),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`);const B=el(F.shape,P,E,s,n),Y=wl(F,P,E.shape,s,n),q=[B,Y];if(M!=null){const K=Go(M,P);q.push(K)}return q},w=A=>{const _=A.fusedConv2d({input:h,filter:u,convInfo:m,bias:f,activation:l,preluActivationWeights:g});return _},x={x:h,filter:u,bias:f,preluActivationWeights:g},T={strides:s,pad:n,dataFormat:i,dilations:r,dimRoundingMode:o,activation:l};if(a==null){const A=ms((_,E,F)=>{let D=v.runKernelFunc(w,x,null,ju,T);return F([E,_,D]),d&&(D=O(D,[D.shape[1],D.shape[2],D.shape[3]])),{value:D,gradFunc:y}});return A(h,u)}else{const A=ms((_,E,F,D)=>{let M=v.runKernelFunc(w,x,null,ju,T);return D([E,_,M,F]),d&&(M=O(M,[M.shape[1],M.shape[2],M.shape[3]])),{value:M,gradFunc:y}});return A(h,u,f)}}const mU=S({fusedConv2d_:dU});function fU(e,t,s,n){let i=e;e.rank===3&&(i=O(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let r=t;r.rank===3&&(r=O(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const o=l=>l.depthwiseConv2DDerFilter(i,r,n),a={x:i,dy:r};return v.runKernelFunc(o,a,null,Cg)}const Gh=S({depthwiseConv2dNativeBackpropFilter_:fU});function gU(e,t,s,n){let i=t,r=!1;t.rank===3&&(r=!0,i=O(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const o=c=>c.depthwiseConv2DDerInput(i,s,n),a={dy:i},l=v.runKernelFunc(o,a,null,Rg);return r?O(l,[l.shape[1],l.shape[2],l.shape[3]]):l}const qh=S({depthwiseConv2dNativeBackpropInput_:gU});function yU({x:e,filter:t,strides:s,pad:n,dataFormat:i="NHWC",dilations:r=[1,1],dimRoundingMode:o,bias:a,activation:l="linear",preluActivationWeights:c}){if(Ho(v.state.gradientDepth,l)===!1){let A=un(e,t,s,n,i,r,o);return a!=null&&(A=$(A,a)),qo(A,l,c)}const p=b(e,"x","depthwiseConv2d"),u=b(t,"filter","depthwiseConv2d");let h=p,d=!1;p.rank===3&&(d=!0,h=O(p,[1,p.shape[0],p.shape[1],p.shape[2]])),I(h.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${h.rank}.`),I(u.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${u.rank}.`),I(h.shape[3]===u.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${h.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`),r==null&&(r=[1,1]),I(tt(s,r),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`),o!=null&&I(ke(n),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${o} but got pad ${n}.`);const m=is(h.shape,u.shape,s,r,n,o,!0);let f;a!=null&&(f=b(a,"bias","fused conv2d"),[f]=Ce(f,p),Ie(m.outShape,f.shape));let g;c!=null&&(g=b(c,"prelu weights","fused depthwiseConv2d"));const y=(A,_)=>{I(Hs(r),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${r}'`);const[E,F,D,M]=_,P=Vo(A,D,l),B=qh(F.shape,P,E,m),Y=Gh(F,P,E.shape,m);if(M!=null){const q=Go(f,P);return[B,Y,q]}return[B,Y]},w=A=>{const _=A.fusedDepthwiseConv2D({input:h,filter:u,convInfo:m,bias:f,activation:l,preluActivationWeights:g});return _},x={x:h,filter:u,bias:f,preluActivationWeights:g},T={strides:s,pad:n,dataFormat:i,dilations:r,dimRoundingMode:o,activation:l};if(a==null){const A=ms((_,E,F)=>{let D=v.runKernelFunc(w,x,null,Vu,T);return F([E,_,D]),d&&(D=O(D,[D.shape[1],D.shape[2],D.shape[3]])),{value:D,gradFunc:y}});return A(h,u)}else{const A=ms((_,E,F,D)=>{let M=v.runKernelFunc(w,x,null,Vu,T);return D([E,_,M,F]),d&&(M=O(M,[M.shape[1],M.shape[2],M.shape[3]])),{value:M,gradFunc:y}});return A(h,u,f)}}const bU=S({fusedDepthwiseConv2d_:yU});function wU({a:e,b:t,transposeA:s=!1,transposeB:n=!1,bias:i,activation:r="linear",preluActivationWeights:o}){if(Ho(v.state.gradientDepth,r)===!1){let M=Te(e,t,s,n);return i!=null&&(M=$(M,i)),qo(M,r,o)}let a=b(e,"a","fused matMul"),l=b(t,"b","fused matMul");[a,l]=Ce(a,l);const c=s?a.shape[a.rank-2]:a.shape[a.rank-1],p=n?l.shape[l.rank-1]:l.shape[l.rank-2],u=s?a.shape[a.rank-1]:a.shape[a.rank-2],h=n?l.shape[l.rank-2]:l.shape[l.rank-1],d=a.shape.slice(0,-2),m=l.shape.slice(0,-2),f=We(d),g=We(m);I(a.rank>=2&&l.rank>=2&&a.rank===l.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${a.rank} and ${l.rank}.`),I(Nt(d,m),()=>`Error in fused matMul: outer dimensions (${d}) and (${m}) of Tensors with shapes ${a.shape} and ${l.shape} must match.`),I(c===p,()=>`Error in fused matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${a.shape} and ${l.shape} and transposeA=${s} and transposeB=${n} must match.`);const y=a.shape.slice(0,-2).concat([u,h]),w=s?O(a,[f,c,u]):O(a,[f,u,c]),x=n?O(l,[g,h,p]):O(l,[g,p,h]);let T;i!=null&&(T=b(i,"bias","fused matMul"),[T]=Ce(T,a),Ie(y,T.shape));let A;o!=null&&(A=b(o,"prelu weights","fused matMul"));const _=(M,P)=>{const[B,Y,q,K]=P,H=Vo(O(M,q.shape),q,r);let Q,J;if(!s&&!n?(Q=Te(H,Y,!1,!0),J=Te(B,H,!0,!1)):!s&&n?(Q=Te(H,Y,!1,!1),J=Te(H,B,!0,!1)):s&&!n?(Q=Te(Y,H,!1,!0),J=Te(B,H,!1,!1)):(Q=Te(Y,H,!0,!0),J=Te(H,B,!0,!0)),i!=null){const ie=Go(K,H);return[Q,J,ie]}else return[Q,J]},E=M=>{const P=M.fusedBatchMatMul({a:w,b:x,transposeA:s,transposeB:n,bias:T,activation:r,preluActivationWeights:A});return P},F={a:w,b:x,bias:T,preluActivationWeights:A},D={transposeA:s,transposeB:n,activation:r};if(i==null){const M=ms((P,B,Y)=>{const q=v.runKernelFunc(E,F,null,Bu,D);return Y([P,B,q]),{value:O(q,y),gradFunc:_}});return M(w,x)}else{const M=ms((P,B,Y,q)=>{const K=v.runKernelFunc(E,F,null,Bu,D);return q([P,B,K,Y]),{value:O(K,y),gradFunc:_}});return M(w,x,T)}}const xU=S({fusedMatMul_:wU});const gn={};Ee(gn,{conv2d:()=>mU,depthwiseConv2d:()=>bU,matMul:()=>xU});function LU(e){return _p(e,.54,.46)}const QS=S({hammingWindow_:LU});function SU(e){return _p(e,.5,.5)}const Hh=S({hannWindow_:SU});function IU(e,t,s,n=!1,i=0){let r=0;const o=[];for(;r+t<=e.size;)o.push(he(e,r,t)),r+=s;if(n)for(;r<e.size;){const a=r+t-e.size,l=be([he(e,r,t-a),Wt([a],i)]);o.push(l),r+=s}return o.length===0?as([],[0,t]):O(be(o),[o.length,t])}const Yh=S({frame_:IU});function vU(e,t,s,n,i=Hh){n==null&&(n=Gy(t));const r=Yh(e,t,s),o=R(r,i(t)),a=[];for(let l=0;l<r.shape[0];l++)a.push(Hr(he(o,[l,0],[1,t]),n));return be(a)}const eI=S({stft_:vU});function TU(e,t,s,n,i,r){const o=b(e,"image","cropAndResize"),a=b(t,"boxes","cropAndResize","float32"),l=b(s,"boxInd","cropAndResize","int32");i=i||"bilinear",r=r||0;const c=a.shape[0];I(o.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${o.rank}.`),I(a.rank===2&&a.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${c},4] but had shape ${a.shape}.`),I(l.rank===1&&l.shape[0]===c,()=>`Error in cropAndResize: boxInd must be have size [${c}] but had shape ${a.shape}.`),I(n.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${n.length}.`),I(n[0]>=1&&n[1]>=1,()=>`cropSize must be atleast [1,1], but was ${n}`),I(i==="bilinear"||i==="nearest",()=>`method must be bilinear or nearest, but was ${i}`);const p=m=>m.cropAndResize(o,a,l,n,i,r),u={image:o,boxes:a,boxInd:l},h={method:i,extrapolationValue:r,cropSize:n},d=v.runKernelFunc(p,u,null,Ag,h);return d}const tI=S({cropAndResize_:TU});function AU(e){const t=b(e,"image","flipLeftRight","float32");I(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);const s={image:t},n=v.runKernel(So,s,{});return n}const sI=S({flipLeftRight_:AU});function NU(e,t,s=0,n=.5){const i=b(e,"image","rotateWithOffset","float32");I(i.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${i.rank}.`);const r={image:i},o={radians:t,fillValue:s,center:n},a=v.runKernel(_o,r,o);return a}const nI=S({rotateWithOffset_:NU});function yn(e,t,s,n,i,r){n==null&&(n=.5),i==null&&(i=Number.NEGATIVE_INFINITY),r==null&&(r=0);const o=e.shape[0];return s=Math.min(s,o),I(0<=n&&n<=1,()=>`iouThreshold must be in [0, 1], but was '${n}'`),I(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),I(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),I(t.rank===1,()=>"scores must be a 1D tensor"),I(t.shape[0]===o,()=>`scores has incompatible shape with boxes. Expected ${o}, but was ${t.shape[0]}`),I(0<=r&&r<=1,()=>`softNmsSigma must be in [0, 1], but was '${r}'`),{maxOutputSize:s,iouThreshold:n,scoreThreshold:i,softNmsSigma:r}}function CU(e,t,s,n=.5,i=Number.NEGATIVE_INFINITY){const r=b(e,"boxes","nonMaxSuppression"),o=b(t,"scores","nonMaxSuppression"),a=yn(r,o,s,n,i);s=a.maxOutputSize,n=a.iouThreshold,i=a.scoreThreshold;const l={maxOutputSize:s,iouThreshold:n,scoreThreshold:i};return v.runKernelFunc(c=>c.nonMaxSuppression(r,o,s,n,i),{boxes:r,scores:o},null,Vc,l)}const iI=S({nonMaxSuppression_:CU});function rI(e,t,s){const n=RU(e,t,s),i=n<0?-(n+1):n;e.splice(i,0,t)}function RU(e,t,s){return EU(e,t,s||OU)}function OU(e,t){return e>t?1:e<t?-1:0}function EU(e,t,s){let n=0,i=e.length,r=0,o=!1;for(;n<i;){r=n+(i-n>>>1);const a=s(t,e[r]);a>0?n=r+1:(i=r,o=!a)}return o?n:-n-1}function Kh(e,t,s,n,i){return qy(e,t,s,n,i,0).selectedIndices}function Xh(e,t,s,n,i,r){return qy(e,t,s,n,i,0,!1,r,!0)}function Jh(e,t,s,n,i,r){return qy(e,t,s,n,i,r,!0)}function qy(e,t,s,n,i,r,o=!1,a=!1,l=!1){const c=[];for(let g=0;g<t.length;g++)t[g]>i&&c.push({score:t[g],boxIndex:g,suppressBeginIndex:0});c.sort(oI);const p=r>0?-.5/r:0,u=[],h=[];for(;u.length<s&&c.length>0;){const g=c.pop(),{score:y,boxIndex:w,suppressBeginIndex:x}=g;if(y<i)break;let T=!1;for(let A=u.length-1;A>=x;--A){const _=_U(e,w,u[A]);if(_>=n){T=!0;break}if(g.score=g.score*kU(n,p,_),g.score<=i)break}g.suppressBeginIndex=u.length,T||(g.score===y?(u.push(w),h.push(g.score)):g.score>i&&rI(c,g,oI))}const d=u.length,m=s-d;a&&m>0&&(u.push(...new Array(m).fill(0)),h.push(...new Array(m).fill(0)));const f={selectedIndices:Oe(u,"int32")};return o&&(f.selectedScores=Oe(h,"float32")),l&&(f.validOutputs=j(d,"int32")),f}function _U(e,t,s){const n=e.subarray(t*4,t*4+4),i=e.subarray(s*4,s*4+4),r=Math.min(n[0],n[2]),o=Math.min(n[1],n[3]),a=Math.max(n[0],n[2]),l=Math.max(n[1],n[3]),c=Math.min(i[0],i[2]),p=Math.min(i[1],i[3]),u=Math.max(i[0],i[2]),h=Math.max(i[1],i[3]),d=(a-r)*(l-o),m=(u-c)*(h-p);if(d<=0||m<=0)return 0;const f=Math.max(r,c),g=Math.max(o,p),y=Math.min(a,u),w=Math.min(l,h),x=Math.max(y-f,0)*Math.max(w-g,0);return x/(d+m-x)}function kU(e,t,s){const n=Math.exp(t*s*s);return s<=e?n:0}function oI(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function DU(e,t,s,n=.5,i=Number.NEGATIVE_INFINITY){const r=b(e,"boxes","nonMaxSuppressionAsync"),o=b(t,"scores","nonMaxSuppressionAsync"),a=yn(r,o,s,n,i);s=a.maxOutputSize,n=a.iouThreshold,i=a.scoreThreshold;const l=await Promise.all([r.data(),o.data()]),c=l[0],p=l[1],u=Kh(c,p,s,n,i);return r!==e&&r.dispose(),o!==t&&o.dispose(),u}const aI=DU;function FU(e,t,s,n=.5,i=Number.NEGATIVE_INFINITY,r=0){const o=b(e,"boxes","nonMaxSuppression"),a=b(t,"scores","nonMaxSuppression"),l=yn(o,a,s,n,i,r);s=l.maxOutputSize,n=l.iouThreshold,i=l.scoreThreshold,r=l.softNmsSigma;const c={boxes:o,scores:a},p={maxOutputSize:s,iouThreshold:n,scoreThreshold:i,softNmsSigma:r},u=v.runKernel(Ao,c,p);return{selectedIndices:u[0],selectedScores:u[1]}}const lI=S({nonMaxSuppressionWithScore_:FU});async function MU(e,t,s,n=.5,i=Number.NEGATIVE_INFINITY,r=0){const o=b(e,"boxes","nonMaxSuppressionAsync"),a=b(t,"scores","nonMaxSuppressionAsync"),l=yn(o,a,s,n,i,r);s=l.maxOutputSize,n=l.iouThreshold,i=l.scoreThreshold,r=l.softNmsSigma;const c=await Promise.all([o.data(),a.data()]),p=c[0],u=c[1],h=Jh(p,u,s,n,i,r);return o!==e&&o.dispose(),a!==t&&a.dispose(),h}const cI=MU;function UU(e,t,s,n=.5,i=Number.NEGATIVE_INFINITY,r=!1){const o=b(e,"boxes","nonMaxSuppression"),a=b(t,"scores","nonMaxSuppression"),l=yn(o,a,s,n,i,null),c=l.maxOutputSize,p=l.iouThreshold,u=l.scoreThreshold,h={boxes:o,scores:a},d={maxOutputSize:c,iouThreshold:p,scoreThreshold:u,padToMaxOutputSize:r},m=v.runKernel(To,h,d);return{selectedIndices:m[0],validOutputs:m[1]}}const pI=S({nonMaxSuppressionPadded_:UU});async function $U(e,t,s,n=.5,i=Number.NEGATIVE_INFINITY,r=!1){const o=b(e,"boxes","nonMaxSuppressionAsync"),a=b(t,"scores","nonMaxSuppressionAsync"),l=yn(o,a,s,n,i,null),c=l.maxOutputSize,p=l.iouThreshold,u=l.scoreThreshold,[h,d]=await Promise.all([o.data(),a.data()]),m=Xh(h,d,c,p,u,r);return o!==e&&o.dispose(),a!==t&&a.dispose(),m}const uI=$U;function WU(e,t,s=!1){const n=b(e,"images","resizeBilinear");I(n.rank===3||n.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${n.rank}.`),I(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`);let i=n,r=!1;n.rank===3&&(r=!0,i=O(n,[1,n.shape[0],n.shape[1],n.shape[2]]));const[o,a]=t,l=(h,d)=>(d([i]),h.resizeBilinear(i,o,a,s)),c={images:i},p={alignCorners:s,size:t},u=v.runKernelFunc(l,c,null,Zc,p);return r?O(u,[u.shape[1],u.shape[2],u.shape[3]]):u}const hI=S({resizeBilinear_:WU});function zU(e,t,s=!1){const n=b(e,"images","resizeNearestNeighbor");I(n.rank===3||n.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${n.rank}.`),I(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),I(n.dtype==="float32"||n.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype");let i=n,r=!1;n.rank===3&&(r=!0,i=O(n,[1,n.shape[0],n.shape[1],n.shape[2]]));const[o,a]=t,l={images:i},c={alignCorners:s,size:t},p=(h,d)=>(d([i]),h.resizeNearestNeighbor(i,o,a,s)),u=v.runKernelFunc(p,l,null,Jc,c);return r?O(u,[u.shape[1],u.shape[2],u.shape[3]]):u}const dI=S({resizeNearestNeighbor_:zU});function PU(e,t,s){I(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),I(s%1===0,()=>`bandPart(): numUpper must be an integer, got ${s}.`);const n=b(e,"a","bandPart");I(n.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${n.rank}.`);const i=n.shape,[r,o]=n.shape.slice(-2);if(!(t<=r))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${r}).`);if(!(s<=o))throw new Error(`bandPart(): numUpper (${s}) must not be greater than the number of columns (${o}).`);t<0&&(t=r),s<0&&(s=o);const a=O(Fi(0,r,1,"int32"),[-1,1]),l=Fi(0,o,1,"int32"),c=X(a,l),p=Yt($s(c,j(+t,"int32")),ds(c,j(-s,"int32"))),u=ye([r,o],n.dtype);return O(Ve(Ge(O(n,[-1,r,o])).map(h=>dt(p,h,u))),i)}const mI=S({bandPart_:PU});function BU(e){let t;if(Array.isArray(e)){t=!1,I(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");const i=e[0].shape[0];for(let r=1;r<e.length;++r)I(e[r].shape[0]===i,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[r].shape[0]} vs. ${i})`)}else t=!0,e=Bt(e,e.shape[0],0).map(i=>Js(i,[0]));I(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);const s=[],n=e;for(let i=0;i<e.length;++i)s.push(v.tidy(()=>{let r=n[i];if(i>0)for(let o=0;o<i;++o){const a=R(te(R(s[o],r)),s[o]);r=X(r,a)}return Z(r,Op(r,"euclidean"))}));return t?Ve(s,0):s}const fI=S({gramSchmidt_:BU});function jU(e,t=!1){if(I(e.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return gI(e,t);{const s=e.shape.slice(0,e.shape.length-2).reduce((l,c)=>l*c),n=Ge(O(e,[s,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),i=[],r=[];n.forEach(l=>{const[c,p]=gI(l,t);i.push(c),r.push(p)});const o=O(Ve(i,0),e.shape),a=O(Ve(r,0),e.shape);return[o,a]}}function gI(e,t=!1){return v.tidy(()=>{I(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);const s=e.shape[0],n=e.shape[1];let i=Po(s),r=Ds(e);const o=as([[1]],[1,1]);let a=Ds(o);const l=s>=n?n:s;for(let c=0;c<l;++c){const p=r,u=a,h=i;[a,r,i]=v.tidy(()=>{const d=he(r,[c,c],[s-c,1]),m=Op(d),f=he(r,[c,c],[1,1]),g=dt(Ut(f,0),as([[-1]]),as([[1]])),y=X(f,R(g,m)),w=Z(d,y);w.shape[0]===1?a=Ds(o):a=be([o,he(w,[1,0],[w.shape[0]-1,w.shape[1]])],0);const x=_e(Z(Te(g,y),m)),T=he(r,[c,0],[s-c,n]),A=R(x,a),_=se(a);if(c===0)r=X(T,Te(A,Te(_,T)));else{const D=X(T,Te(A,Te(_,T)));r=be([he(r,[0,0],[c,n]),D],0)}const E=se(A),F=he(i,[0,c],[s,i.shape[1]-c]);if(c===0)i=X(F,Te(Te(F,a),E));else{const D=X(F,Te(Te(F,a),E));i=be([he(i,[0,0],[s,c]),D],1)}return[a,r,i]}),ce([p,u,h])}return!t&&s>n&&(i=he(i,[0,0],[s,n]),r=he(r,[0,0],[n,n])),[i,r]})}const yI=S({qr_:jU});var ft;(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"})(ft||(ft={}));function VU(e,t,s=ft.SUM_BY_NONZERO_WEIGHTS){const n=b(e,"losses","computeWeightedLoss");let i=null;t!=null&&(i=b(t,"weights","computeWeightedLoss"));const r=i==null?n:R(n,i);if(s===ft.NONE)return r;if(s===ft.SUM)return te(r);if(s===ft.MEAN){if(i==null)return Ke(r);{const o=n.size/i.size,a=Z(te(r),te(i));return o>1?Z(a,j(o)):a}}if(s===ft.SUM_BY_NONZERO_WEIGHTS){if(i==null)return Z(te(r),j(n.size));{const o=R(i,Kt(n.shape)),a=G(te(Ks(o,j(0))),"float32");return Z(te(r),a)}}throw Error(`Unknown reduction: ${s}`)}const ss=S({computeWeightedLoss_:VU});function GU(e,t,s,n=ft.SUM_BY_NONZERO_WEIGHTS){const i=b(e,"labels","absoluteDifference"),r=b(t,"predictions","absoluteDifference");let o=null;s!=null&&(o=b(s,"weights","absoluteDifference")),Se(i.shape,r.shape,"Error in absoluteDifference: ");const a=et(X(i,r));return ss(a,o,n)}const bI=S({absoluteDifference_:GU});function qU(e,t,s,n,i=ft.SUM_BY_NONZERO_WEIGHTS){const r=b(e,"labels","cosineDistance"),o=b(t,"predictions","cosineDistance");let a=null;n!=null&&(a=b(n,"weights","cosineDistance")),Se(r.shape,o.shape,"Error in cosineDistance: ");const l=j(1),c=X(l,te(R(r,o),s,!0));return ss(c,a,i)}const wI=S({cosineDistance_:qU});function HU(e,t,s,n=ft.SUM_BY_NONZERO_WEIGHTS){let i=b(e,"labels","hingeLoss");const r=b(t,"predictions","hingeLoss");let o=null;s!=null&&(o=b(s,"weights","hingeLoss")),Se(i.shape,r.shape,"Error in hingeLoss: ");const a=j(1);i=X(R(j(2),i),a);const l=De(X(a,R(i,r)));return ss(l,o,n)}const xI=S({hingeLoss_:HU});function YU(e,t,s,n=1,i=ft.SUM_BY_NONZERO_WEIGHTS){const r=b(e,"labels","huberLoss"),o=b(t,"predictions","huberLoss");let a=null;s!=null&&(a=b(s,"weights","huberLoss")),Se(r.shape,o.shape,"Error in huberLoss: ");const l=j(n),c=et(X(o,r)),p=mn(c,l),u=X(c,p),h=$(R(j(.5),xe(p)),R(l,u));return ss(h,a,i)}const LI=S({huberLoss_:YU});function KU(e,t,s,n=1e-7,i=ft.SUM_BY_NONZERO_WEIGHTS){const r=b(e,"labels","logLoss"),o=b(t,"predictions","logLoss");let a=null;s!=null&&(a=b(s,"weights","logLoss")),Se(r.shape,o.shape,"Error in logLoss: ");const l=j(1),c=j(n),p=_e(R(r,zt($(o,c)))),u=R(X(l,r),zt($(X(l,o),c))),h=X(p,u);return ss(h,a,i)}const SI=S({logLoss_:KU});function XU(e,t,s,n=ft.SUM_BY_NONZERO_WEIGHTS){const i=b(e,"labels","meanSquaredError"),r=b(t,"predictions","meanSquaredError");let o=null;s!=null&&(o=b(s,"weights","meanSquaredError")),Se(i.shape,r.shape,"Error in meanSquaredError: ");const a=Yr(i,r);return ss(a,o,n)}const II=S({meanSquaredError_:XU});function JU(e,t){const s=b(e,"labels","sigmoidCrossEntropyWithLogits"),n=b(t,"logits","sigmoidCrossEntropyWithLogits");Se(s.shape,n.shape,"Error in sigmoidCrossEntropyWithLogits: ");const i=De(n),r=R(n,s),o=ol(ut(_e(et(n))));return $(X(i,r),o)}function ZU(e,t,s,n=0,i=ft.SUM_BY_NONZERO_WEIGHTS){let r=b(e,"multiClassLabels","sigmoidCrossEntropy");const o=b(t,"logits","sigmoidCrossEntropy");let a=null;if(s!=null&&(a=b(s,"weights","sigmoidCrossEntropy")),Se(r.shape,o.shape,"Error in sigmoidCrossEntropy: "),n>0){const c=j(n),p=j(1),u=j(.5);r=$(R(r,X(p,c)),R(u,c))}const l=JU(r,o);return ss(l,a,i)}const vI=S({sigmoidCrossEntropy_:ZU});function QU(e,t,s=-1){if(s===-1&&(s=t.rank-1),s!==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 ${s}`);const n=ms((i,r,o)=>{const a=!0,l=Oh(r,[s],a),c=X(G(r,"float32"),l);o([i,c]);const p=_e(R(c,i)),u=te(p,[s]),h=(d,m)=>{const[f,g]=m,y=bt(d.shape,[s]);return[R(O(d,y),X(G(f,"float32"),ut(g))),R(O(d,y),X(ut(g),G(f,"float32")))]};return{value:u,gradFunc:h}});return n(e,t)}function e$(e,t,s,n=0,i=ft.SUM_BY_NONZERO_WEIGHTS){let r=b(e,"onehotLabels","softmaxCrossEntropy");const o=b(t,"logits","softmaxCrossEntropy");let a=null;if(s!=null&&(a=b(s,"weights","softmaxCrossEntropy")),Se(r.shape,o.shape,"Error in softmaxCrossEntropy: "),n>0){const c=j(n),p=j(1),u=j(r.shape[1]);r=$(R(r,X(p,c)),Z(c,u))}const l=QU(r,o);return ss(l,a,i)}const TI=S({softmaxCrossEntropy_:e$});const t$={fft:qr,ifft:Mi,rfft:Hr,irfft:yl},s$={hammingWindow:QS,hannWindow:Hh,frame:Yh,stft:eI},Zs={flipLeftRight:sI,resizeNearestNeighbor:dI,resizeBilinear:hI,rotateWithOffset:nI,cropAndResize:tI,nonMaxSuppression:iI,nonMaxSuppressionAsync:aI,nonMaxSuppressionWithScore:lI,nonMaxSuppressionWithScoreAsync:cI,nonMaxSuppressionPadded:pI,nonMaxSuppressionPaddedAsync:uI},Hy={bandPart:mI,gramSchmidt:fI,qr:yI},n$={absoluteDifference:bI,computeWeightedLoss:ss,cosineDistance:wI,hingeLoss:xI,huberLoss:LI,logLoss:SI,meanSquaredError:II,sigmoidCrossEntropy:vI,softmaxCrossEntropy:TI};class fs extends Cy{minimize(e,t=!1,s){const{value:n,grads:i}=this.computeGradients(e,s);if(s!=null){const r=s.map(o=>({name:o.name,tensor:i[o.name]}));this.applyGradients(r)}else this.applyGradients(i);return ce(i),t?n:(n.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return Rh(e,t)}dispose(){this.iterations_!=null&&ce(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:j(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(fs,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});class Yo extends fs{constructor(e,t,s=null){super();this.learningRate=e,this.rho=t,this.epsilon=s,this.accumulatedGrads=[],this.accumulatedUpdates=[],s==null&&(this.epsilon=v.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(s=>s.name):Object.keys(e);t.forEach((s,n)=>{const i=v.registeredVariables[s],r=!1;this.accumulatedGrads[n]==null&&(this.accumulatedGrads[n]={originalName:`${s}/accum_grad`,variable:C(()=>re(i).variable(r))}),this.accumulatedUpdates[n]==null&&(this.accumulatedUpdates[n]={originalName:`${s}/accum_var`,variable:C(()=>re(i).variable(r))});const o=Array.isArray(e)?e[n].tensor:e[s];if(o==null)return;const a=this.accumulatedGrads[n].variable,l=this.accumulatedUpdates[n].variable;C(()=>{const c=$(R(a,this.rho),R(xe(o),1-this.rho)),p=R(Z(Xe($(l,this.epsilon)),Xe($(a,this.epsilon))),o),u=$(R(l,this.rho),R(xe(p),1-this.rho));a.assign(c),l.assign(u);const h=$(R(p,-this.learningRate),i);i.assign(h)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(ce(this.accumulatedGrads.map(e=>e.variable)),ce(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,s=!1;this.accumulatedGrads=e.slice(0,t).map(n=>({originalName:n.name,variable:n.tensor.variable(s)})),this.accumulatedUpdates=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.tensor.variable(s)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}}Yo.className="Adadelta";vs(Yo);class Ko extends fs{constructor(e,t=.1){super();this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){const t=Array.isArray(e)?e.map(s=>s.name):Object.keys(e);t.forEach((s,n)=>{const i=v.registeredVariables[s];if(this.accumulatedGrads[n]==null){const a=!1;this.accumulatedGrads[n]={originalName:`${s}/accumulator`,variable:C(()=>Wt(i.shape,this.initialAccumulatorValue).variable(a))}}const r=Array.isArray(e)?e[n].tensor:e[s];if(r==null)return;const o=this.accumulatedGrads[n].variable;C(()=>{const a=$(o,xe(r));o.assign(a);const l=$(R(Z(r,Xe($(a,v.backend.epsilon()))),-this.learningRate),i);i.assign(l)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&ce(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(s=>({originalName:s.name,variable:s.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}Ko.className="Adagrad";vs(Ko);class Xo extends fs{constructor(e,t,s,n=null){super();this.learningRate=e,this.beta1=t,this.beta2=s,this.epsilon=n,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],C(()=>{this.accBeta1=j(t).variable(),this.accBeta2=j(s).variable()}),n==null&&(this.epsilon=v.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(s=>s.name):Object.keys(e);C(()=>{const s=X(1,this.accBeta1),n=X(1,this.accBeta2);t.forEach((i,r)=>{const o=v.registeredVariables[i],a=!1;this.accumulatedFirstMoment[r]==null&&(this.accumulatedFirstMoment[r]={originalName:`${i}/m`,variable:C(()=>re(o).variable(a))}),this.accumulatedSecondMoment[r]==null&&(this.accumulatedSecondMoment[r]={originalName:`${i}/v`,variable:C(()=>re(o).variable(a))});const l=Array.isArray(e)?e[r].tensor:e[i];if(l==null)return;const c=this.accumulatedFirstMoment[r].variable,p=this.accumulatedSecondMoment[r].variable,u=$(R(c,this.beta1),R(l,1-this.beta1)),h=$(R(p,this.beta2),R(xe(l),1-this.beta2)),d=Z(u,s),m=Z(h,n);c.assign(u),p.assign(h);const f=$(R(Z(d,$(Xe(m),this.epsilon)),-this.learningRate),o);o.assign(f)}),this.accBeta1.assign(R(this.accBeta1,this.beta1)),this.accBeta2.assign(R(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&ce(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&ce(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),C(()=>{this.accBeta1.assign(Qt(this.beta1,this.iterations_+1)),this.accBeta2.assign(Qt(this.beta2,this.iterations_+1))});const t=e.length/2,s=!1;this.accumulatedFirstMoment=e.slice(0,t).map(n=>({originalName:n.name,variable:n.tensor.variable(s)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.tensor.variable(s)}))}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)}}Xo.className="Adam";vs(Xo);class Jo extends fs{constructor(e,t,s,n=null,i=0){super();this.learningRate=e,this.beta1=t,this.beta2=s,this.epsilon=n,this.decay=i,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],C(()=>{this.iteration=j(0).variable(),this.accBeta1=j(t).variable()}),n==null&&(this.epsilon=v.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(s=>s.name):Object.keys(e);C(()=>{const s=X(1,this.accBeta1),n=Z(-this.learningRate,$(R(this.iteration,this.decay),1));t.forEach((i,r)=>{const o=v.registeredVariables[i],a=!1;this.accumulatedFirstMoment[r]==null&&(this.accumulatedFirstMoment[r]={originalName:`${i}/m`,variable:re(o).variable(a)}),this.accumulatedWeightedInfNorm[r]==null&&(this.accumulatedWeightedInfNorm[r]={originalName:`${i}/v`,variable:re(o).variable(a)});const l=Array.isArray(e)?e[r].tensor:e[i];if(l==null)return;const c=this.accumulatedFirstMoment[r].variable,p=this.accumulatedWeightedInfNorm[r].variable,u=$(R(c,this.beta1),R(l,1-this.beta1)),h=R(p,this.beta2),d=et(l),m=Ht(h,d);c.assign(u),p.assign(m);const f=$(R(Z(n,s),Z(u,$(m,this.epsilon))),o);o.assign(f)}),this.iteration.assign($(this.iteration,1)),this.accBeta1.assign(R(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&ce(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&ce(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)}}Jo.className="Adamax";vs(Jo);class Ui extends fs{constructor(e){super();this.learningRate=e,this.setLearningRate(e)}applyGradients(e){const t=Array.isArray(e)?e.map(s=>s.name):Object.keys(e);t.forEach((s,n)=>{const i=Array.isArray(e)?e[n].tensor:e[s];if(i==null)return;const r=v.registeredVariables[s];C(()=>{const o=$(R(this.c,i),r);r.assign(o)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=pt(j(-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)}}Ui.className="SGD";vs(Ui);class Zo extends Ui{constructor(e,t,s=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=s,this.accumulations=[],this.m=j(this.momentum)}applyGradients(e){const t=Array.isArray(e)?e.map(s=>s.name):Object.keys(e);t.forEach((s,n)=>{const i=v.registeredVariables[s];if(this.accumulations[n]==null){const a=!1;this.accumulations[n]={originalName:`${s}/momentum`,variable:C(()=>re(i).variable(a))}}const r=this.accumulations[n].variable,o=Array.isArray(e)?e[n].tensor:e[s];if(o==null)return;C(()=>{let a;const l=$(R(this.m,r),o);this.useNesterov?a=$(R(this.c,$(o,R(l,this.m))),i):a=$(R(this.c,l),i),r.assign(l),i.assign(a)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&ce(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(s=>({originalName:s.name,variable:s.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)}}Zo.className="Momentum";vs(Zo);class Qo extends fs{constructor(e,t=.9,s=0,n=null,i=!1){super();if(this.learningRate=e,this.decay=t,this.momentum=s,this.epsilon=n,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=i,n==null&&(this.epsilon=v.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){const t=Array.isArray(e)?e.map(s=>s.name):Object.keys(e);t.forEach((s,n)=>{const i=v.registeredVariables[s],r=!1;this.accumulatedMeanSquares[n]==null&&(this.accumulatedMeanSquares[n]={originalName:`${s}/rms`,variable:C(()=>re(i).variable(r))}),this.accumulatedMoments[n]==null&&(this.accumulatedMoments[n]={originalName:`${s}/momentum`,variable:C(()=>re(i).variable(r))}),this.accumulatedMeanGrads[n]==null&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${s}/mg`,variable:C(()=>re(i).variable(r))});const o=Array.isArray(e)?e[n].tensor:e[s];if(o==null)return;const a=this.accumulatedMeanSquares[n].variable,l=this.accumulatedMoments[n].variable;C(()=>{const c=$(R(a,this.decay),R(xe(o),1-this.decay));if(this.centered){const p=this.accumulatedMeanGrads[n].variable,u=$(R(p,this.decay),R(o,1-this.decay)),h=Z(R(o,this.learningRate),Xe(X(c,$(xe(u),this.epsilon)))),d=$(R(l,this.momentum),h);a.assign(c),p.assign(u),l.assign(d);const m=X(i,d);i.assign(m)}else{const p=$(R(a,this.decay),R(xe(o),1-this.decay)),u=$(R(l,this.momentum),Z(R(o,this.learningRate),Xe($(p,this.epsilon))));a.assign(p),l.assign(u);const h=X(i,u);i.assign(h)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&ce(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&ce(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&ce(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,s=!1;this.accumulatedMeanSquares=e.slice(0,t).map(n=>({originalName:n.name,variable:n.tensor.variable(s)})),this.accumulatedMoments=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.tensor.variable(s)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(n=>({originalName:n.name,variable:n.tensor.variable(s)})))}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)}}Qo.className="RMSProp";vs(Qo);class Xr{static sgd(e){return new Ui(e)}static momentum(e,t,s=!1){return new Zo(e,t,s)}static rmsprop(e,t=.9,s=0,n=null,i=!1){return new Qo(e,t,s,n,i)}static adam(e=.001,t=.9,s=.999,n=null){return new Xo(e,t,s,n)}static adadelta(e=.001,t=.95,s=null){return new Yo(e,t,s)}static adamax(e=.002,t=.9,s=.999,n=null,i=0){return new Jo(e,t,s,n,i)}static adagrad(e,t=.1){return new Ko(e,t)}}Zo,Ui,Yo,Ko,Qo,Jo,Xo;const Jr={sgd:Xr.sgd,momentum:Xr.momentum,adadelta:Xr.adadelta,adagrad:Xr.adagrad,rmsprop:Xr.rmsprop,adamax:Xr.adamax,adam:Xr.adam};const i$=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function kp(){return new Promise(e=>i$(()=>e()))}function r$(e,t,s){const n=s*(typeof e=="number"?e:e[0]),i=t*(typeof e=="number"?e:e[1]);return[n,i]}function o$(e,t,s,n=!0){let i=[];if(n)i=i.concat(t.slice(0)),i.push(e[0]/s),i=i.concat(e.slice(1));else{i=i.concat(e[0]);const r=t.length;for(let o=0;o<r;++o)i=i.concat([e[o+1]/t[o],t[o]]);i=i.concat(e.slice(r+1))}return i}function a$(e,t,s=!0){const n=[];if(s){n.push(t);for(let i=t+1;i<e;++i)i<=2*t?(n.push(i),n.push(i-(t+1))):n.push(i)}else{const i=[],r=[];for(let o=1;o<e;++o)o>=t*2+1||o%2===1?r.push(o):i.push(o);n.push(...i),n.push(0),n.push(...r)}return n}function l$(e,t,s,n=!0){const i=[];n?i.push(e[0]/s):i.push(e[0]*s);for(let r=1;r<e.length;++r)r<=t.length?n?i.push(t[r-1]*e[r]):i.push(e[r]/t[r-1]):i.push(e[r]);return i}function c$(e,t){const s=[0];for(let n=0;n<t;++n)s.push(e[n][0]);return s}function p$(e,t,s){const n=e.slice(0,1);for(let i=0;i<s;++i)n.push(e[i+1]-t[i][0]-t[i][1]);return n}const Yy=1.7580993408473768,Ky=1.0507009873554805;const u$=.3275911,h$=.254829592,d$=-.284496736,m$=1.421413741,f$=-1.453152027,g$=1.061405429;function y$(...e){W().getBool("IS_TEST")||console.warn(...e)}function b$(...e){W().getBool("IS_TEST")||console.log(...e)}function w$(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 s=new Float32Array(e.length*2);for(let n=0;n<s.length;n+=2)s[n]=e[n/2],s[n+1]=t[n/2];return s}function x$(e){const t=new Float32Array(e.length/2),s=new Float32Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=e[n],s[n/2]=e[n+1];return{real:t,imag:s}}function L$(e){const t=Math.ceil(e.length/4),s=new Float32Array(t),n=new Float32Array(t);for(let i=0;i<e.length;i+=4)s[Math.floor(i/4)]=e[i],n[Math.floor(i/4)]=e[i+1];return{real:s,imag:n}}function S$(e){const t=Math.floor(e.length/4),s=new Float32Array(t),n=new Float32Array(t);for(let i=2;i<e.length;i+=4)s[Math.floor(i/4)]=e[i],n[Math.floor(i/4)]=e[i+1];return{real:s,imag:n}}function I$(e,t){const s=e[t*2],n=e[t*2+1];return{real:s,imag:n}}function v$(e,t,s,n){e[n*2]=t,e[n*2+1]=s}function T$(e,t){const s=new Float32Array(e/2),n=new Float32Array(e/2);for(let i=0;i<Math.ceil(e/2);i++){const r=(t?2:-2)*Math.PI*(i/e);s[i]=Math.cos(r),n[i]=Math.sin(r)}return{real:s,imag:n}}function A$(e,t,s){const n=(s?2:-2)*Math.PI*(e/t),i=Math.cos(n),r=Math.sin(n);return{real:i,imag:r}}const U={};Ee(U,{ERF_A1:()=>h$,ERF_A2:()=>d$,ERF_A3:()=>m$,ERF_A4:()=>f$,ERF_A5:()=>g$,ERF_P:()=>u$,PARALLELIZE_THRESHOLD:()=>Th,SELU_SCALE:()=>Ky,SELU_SCALEALPHA:()=>Yy,applyActivation:()=>qo,assertAndGetBroadcastShape:()=>Ie,assertAxesAreInnerMostDims:()=>Sk,assertParamsConsistent:()=>$y,assignToTypedArray:()=>v$,axesAreInnerMostDims:()=>Dy,calculateShapes:()=>cS,castTensor:()=>N$,combineLocations:()=>LS,complexWithEvenIndex:()=>L$,complexWithOddIndex:()=>S$,computeConv2DInfo:()=>is,computeConv3DInfo:()=>Ur,computeDefaultPad:()=>Uy,computeDilation2DInfo:()=>_k,computeOptimalWindowSize:()=>OD,computeOutAndReduceShapes:()=>Fy,computeOutShape:()=>Wy,computePool2DInfo:()=>Fn,computePool3DInfo:()=>_i,convertConv2DDataFormat:()=>Mr,eitherStridesOrDilationsAreOne:()=>tt,expandShapeToKeepDim:()=>bt,exponent:()=>A$,exponents:()=>T$,getAxesPermutation:()=>ht,getBroadcastDims:()=>gD,getComplexWithIndex:()=>I$,getFusedBiasGradient:()=>Go,getFusedDyActivation:()=>Vo,getImageCenter:()=>r$,getInnerMostAxes:()=>qt,getPermuted:()=>a$,getReductionAxes:()=>Ye,getReshaped:()=>o$,getReshapedPermuted:()=>l$,getSliceBeginCoords:()=>c$,getSliceSize:()=>p$,getUndoAxesPermutation:()=>Mo,linspaceImpl:()=>R$,log:()=>b$,mergeRealAndImagArrays:()=>w$,prepareAndValidate:()=>aS,prepareSplitSize:()=>Py,reshapeTensor:()=>C$,segment_util:()=>NS,shouldFuse:()=>Ho,slice_util:()=>Fs,splitRealAndImagArrays:()=>x$,tupleValuesAreOne:()=>Hs,upcastType:()=>Ft,validateInput:()=>Qu,validateUpdateShape:()=>vy,warn:()=>y$});function N$(e,t,s){if(t==="complex64"){if(e.dtype==="complex64")return e.clone();const n=ye(e.shape),i=G(e,"float32"),r=s.complex(i,n);return n.dispose(),i.dispose(),r}if(!ny(e.dtype,t))return v.makeTensorFromDataId(e.dataId,e.shape,t);if(e.dtype==="complex64"){const n=s.real(e),i=G(n,t);return n.dispose(),i}if(t==="int32")return s.int(e);if(t==="bool"){const n=j(0,e.dtype),i=s.notEqual(e,n);return n.dispose(),i}else throw new Error(`Error in Cast: failed to cast ${e.dtype} to ${t}`)}function C$(e,t){return v.makeTensorFromDataId(e.dataId,t,e.dtype)}function R$(e,t,s){const n=(t-e)/(s-1),i=ii(s,"float32");i[0]=e;for(let r=1;r<i.length;r++)i[r]=i[r-1]+n;return Oe(i,"float32")}function AI(e,t,s){const n=new Array(e.rank).fill(0),i=e.shape.slice();return t.map(r=>{const o=[...i];o[s]=r;const a=he(e,n,o);return n[s]+=r,a})}function NI(e,t){const s=new Array(e.rank);for(let i=0;i<s.length;i++)s[i]=e.shape[i]*t[i];const n=ge(s,e.dtype);for(let i=0;i<n.values.length;++i){const r=n.indexToLoc(i),o=new Array(e.rank);for(let l=0;l<o.length;l++)o[l]=r[l]%e.shape[l];const a=e.locToIndex(o);n.values[i]=e.values[a]}return n.toTensor()}function CI(e,t,s,n,i){const r=t[t.length-1],[o,a]=[e.length/r,r],l=$a(s,o*n),c=$a("int32",o*n);for(let u=0;u<o;u++){const h=u*a,d=e.subarray(h,h+a),m=[];for(let w=0;w<d.length;w++)m.push({value:d[w],index:w});m.sort((w,x)=>x.value-w.value);const f=u*n,g=l.subarray(f,f+n),y=c.subarray(f,f+n);for(let w=0;w<n;w++)g[w]=m[w].value,y[w]=m[w].index}const p=t.slice();return p[p.length-1]=n,[ze(l,p,s),ze(c,p,"int32")]}const vt={};Ee(vt,{nonMaxSuppressionV3Impl:()=>Kh,nonMaxSuppressionV4Impl:()=>Xh,nonMaxSuppressionV5Impl:()=>Jh,split:()=>AI,tile:()=>NI,topkImpl:()=>CI,whereImpl:()=>Vh});const RI={kernelName:yo,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(e,ui(G(s,"float32"),-1))}}};const OI={kernelName:nr,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>{const n=xe(G(s,"float32")),i=Xe(X(j(1),n));return _e(Z(e,i))}}}};const EI={kernelName:ir,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>{const n=Xe(X(xe(G(s,"float32")),1));return Z(e,n)}}}};const _I={kernelName:Kn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=Ie(s.shape,n.shape),r=()=>{let a=e;const l=Ye(s.shape,i);return l.length>0&&(a=te(a,l)),O(a,s.shape)},o=()=>{let a=e;const l=Ye(n.shape,i);return l.length>0&&(a=te(a,l)),O(a,n.shape)};return{a:r,b:o}}};const kI={kernelName:yc,saveAllInputs:!0,gradFunc:(e,t)=>{const s={};return t.forEach((n,i)=>{s[i]=()=>e.clone()}),s}};const DI={kernelName:bc,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>re(s)}}};const FI={kernelName:wc,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>re(s)}}};const MI={kernelName:rr,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>Z(e,Xe(X(j(1),xe(G(s,"float32")))))}}};const UI={kernelName:or,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>{const n=Xe($(j(1),xe(G(s,"float32"))));return Z(e,n)}}}};const $I={kernelName:bo,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=Ie(s.shape,n.shape),r=()=>{const a=$(xe(s),xe(n));let l=R(e,Z(n,a));const c=Ye(s.shape,i);return c.length>0&&(l=te(l,c)),O(l,s.shape)},o=()=>{const a=$(xe(s),xe(n));let l=_e(R(e,Z(s,a)));const c=Ye(n.shape,i);return c.length>0&&(l=te(l,c)),O(l,n.shape)};return{a:r,b:o}}};const WI={kernelName:ar,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>Z(e,$(xe(G(s,"float32")),1))}}};const zI={kernelName:lr,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>Z(e,X(j(1),xe(G(s,"float32"))))}}};function O$(e,t,s,n,i=[1,1,1],r,o){const a=b(e,"dy","avgPool3dBackprop"),l=b(t,"input","avgPool3dBackprop");let c=a,p=l,u=!1;l.rank===4&&(u=!0,c=O(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]]),p=O(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]])),I(c.rank===5,()=>`Error in avgPool3dBackprop: dy must be rank 5 but got rank ${c.rank}.`),I(p.rank===5,()=>`Error in avgPool3dBackprop: input must be rank 5 but got rank ${p.rank}.`),I(tt(n,i),()=>`Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`),o!=null&&I(ke(r),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);const h=g=>{const y=_i(p.shape,s,n,i,r,o);return g.avgPool3dBackprop(c,p,y)},d={dy:c,input:p},m={filterSize:s,strides:n,dilations:i,pad:r,dimRoundingMode:o},f=v.runKernelFunc(h,d,null,Sg,m);return u?O(f,[f.shape[1],f.shape[2],f.shape[3],f.shape[4]]):f}const PI=S({avgPool3dBackprop_:O$});const BI={kernelName:xc,inputsToSave:["x"],gradFunc:(e,t,s)=>{const[n]=t,{filterSize:i,strides:r,dilations:o,pad:a,dimRoundingMode:l}=s,c=o??[1,1,1];return{x:()=>PI(e,n,i,r,c,a,l)}}};function E$(e,t,s,n,i){const r=b(e,"dy","avgPoolBackprop"),o=b(t,"input","avgPoolBackprop");I(o.rank===r.rank,()=>`Rank of input (${o.rank}) does not match rank of dy (${r.rank})`);let a=o,l=r,c=!1;o.rank===3&&(c=!0,a=O(o,[1,o.shape[0],o.shape[1],o.shape[2]]),l=O(r,[1,r.shape[0],r.shape[1],r.shape[2]])),I(l.rank===4,()=>`Error in avgPoolBackprop: dy must be rank 4 but got rank ${l.rank}.`),I(a.rank===4,()=>`Error in avgPoolBackprop: input must be rank 4 but got rank ${a.rank}.`);const p=m=>{const f=Fn(a.shape,s,n,1,i);return m.avgPoolBackprop(l,a,f)},u={dy:l,input:a},h={filterSize:s,strides:n,pad:i},d=v.runKernelFunc(p,u,null,wo,h);return c?O(d,[d.shape[1],d.shape[2],d.shape[3]]):d}const jI=S({avgPoolBackprop_:E$});const VI={kernelName:Si,inputsToSave:["x"],gradFunc:(e,t,s)=>{const[n]=t,{filterSize:i,strides:r,pad:o}=s;return{x:()=>jI(e,n,i,r,o)}}};const GI={kernelName:Lc,inputsToSave:["a","b"],gradFunc:(e,t,s)=>{const[n,i]=t,{transposeA:r,transposeB:o}=s;return!r&&!o?{a:()=>Te(e,i,!1,!0),b:()=>Te(n,e,!0,!1)}:!r&&o?{a:()=>Te(e,i,!1,!1),b:()=>Te(e,n,!0,!1)}:r&&!o?{a:()=>Te(i,e,!1,!0),b:()=>Te(n,e,!1,!1)}:{a:()=>Te(i,e,!0,!0),b:()=>Te(e,n,!0,!0)}}};const qI={kernelName:Sc,gradFunc:(e,t,s)=>{const{blockShape:n,crops:i}=s;return{x:()=>Br(e,n,i)}}};const HI={kernelName:Ic,gradFunc:(e,t,s)=>{const n=s,i=n.inputShape,r=n.shape,o=Array.from(r);for(let l=i.length-1;l>=0;l--)if(i[l]===r[l])o[l]=1;else if(i[l]!==1)throw new Error(`broadcastTo(): [${i}] cannot be broadcast to [${r}].`);const a=[];for(let l=0;l<o.length;l++)o[l]>1&&a.push(l);return{x:()=>te(e,a,!0)}}};const YI={kernelName:Ii,gradFunc:e=>({x:()=>e.clone()})};const KI={kernelName:cr,gradFunc:e=>({x:()=>re(e)})};const XI={kernelName:pr,inputsToSave:["x"],gradFunc:(e,t,s)=>{const[n]=t,{clipValueMin:i,clipValueMax:r}=s;return{x:()=>dt(Yt(ds(n,i),$s(n,r)),e,re(e))}}};const JI={kernelName:xo,saveAllInputs:!0,gradFunc:(e,t,s)=>{const n=t.map(l=>l.shape),{axis:i}=s,r=Ne(i,t[0].shape)[0],o=n.map(l=>l[r]),a=Bt(e,o,r);return a.map(l=>()=>l)}};const ZI={kernelName:Tc,inputsToSave:["x","filter"],gradFunc:(e,t,s)=>{const[n,i]=t,{dilations:r,strides:o,pad:a,dataFormat:l}=s;return I(Hs(r),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`),{x:()=>el(n.shape,e,i,o,a,l),filter:()=>wl(n,e,i.shape,o,a,l)}}};const QI={kernelName:Ac,inputsToSave:["dy","filter"],gradFunc:(e,t,s)=>{const[n,i]=t,{strides:r,pad:o,dataFormat:a,dimRoundingMode:l}=s;return{dy:()=>nt(e,i,r,o,a,1,l),filter:()=>wl(e,n,i.shape,r,o,a,l)}}};function _$(e,t,s,n,i){let r=e;e.rank===4&&(r=O(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let o=t;o.rank===4&&(o=O(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),I(r.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${r.shape}.`),I(o.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${o.shape}.`),I(s.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${s}.`),I(r.shape[4]===s[3],()=>`Error in conv3dDerFilter: depth of input ${r.shape[4]}) must match input depth in filter (${s[3]}.`),I(o.shape[4]===s[4],()=>`Error in conv3dDerFilter: depth of dy (${o.shape[4]}) must match output depth for filter (${s[4]}).`);const a=p=>{const u=1,h=Ur(r.shape,s,n,u,i);return p.conv3dDerFilter(r,o,h)},l={x:r,y:o},c={strides:n,pad:i};return v.runKernelFunc(a,l,null,vg,c)}const ev=S({conv3DBackpropFilter_:_$});const tv={kernelName:Nc,inputsToSave:["x","filter"],gradFunc:(e,t,s)=>{const{dilations:n,strides:i,pad:r}=s;I(Hs(n),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${n}'`);const[o,a]=t;return{x:()=>wh(o.shape,e,a,i,r),filter:()=>ev(o,e,a.shape,i,r)}}};const sv={kernelName:Xn,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(_e(ml(G(s,"float32"))),e)}}};const nv={kernelName:ur,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(fl(G(s,"float32")),e)}}};const iv={kernelName:Cc,inputsToSave:["x"],gradFunc:(e,t,s)=>{const[n]=t,{axis:i,exclusive:r,reverse:o}=s;return{x:()=>{const a=ht([i],n.rank);let l=il(e,i,r,!o);return a!=null&&(l=se(l,a)),l}}}};const rv={kernelName:Rc,inputsToSave:["x","filter"],gradFunc:(e,t,s)=>{const{dilations:n,strides:i,pad:r,dimRoundingMode:o}=s,a=n??[1,1];I(Hs(a),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);const[l,c]=t;I(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),I(c.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${c.rank}.`),I(l.shape[3]===c.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`),I(tt(i,a),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${a}'.`),o!=null&&I(ke(r),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);const p=is(l.shape,c.shape,i,a,r,o,!0);return{x:()=>qh(l.shape,e,c,p),filter:()=>Gh(l,e,c.shape,p)}}};const ov={kernelName:Lo,inputsToSave:["x","filter"],gradFunc:(e,t,s)=>{const[n,i]=t,r={x:n,filter:i,dy:e},o={x:n,filter:i,dy:e};return{x:()=>v.runKernel(Oa,r,s),filter:()=>v.runKernel(Ea,o,s)}}};const av={kernelName:Jn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=Ie(s.shape,n.shape),r=()=>{const a=Z(e,G(n,"float32")),l=Ye(s.shape,i);return l.length>0?O(te(a,l),s.shape):a},o=()=>{let a=R(e,G(s,"float32"));const l=Ye(n.shape,i);l.length>0&&(a=O(te(a,l),n.shape));const c=xe(n);return _e(Z(a,G(c,"float32")))};return{a:r,b:o}}};const lv={kernelName:hr,outputsToSave:[!0],gradFunc:(e,t)=>{const[s]=t,n=r=>r.eluDer(e,s),i={dy:e,y:s};return{x:()=>v.runKernelFunc(n,i,null,Eg)}}};const cv={kernelName:dr,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t,n=R(ut(_e(xe(s))),2/Math.sqrt(Math.PI));return{x:()=>R(e,n)}}};const pv={kernelName:mr,outputsToSave:[!0],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(e,s)}}};const uv={kernelName:fr,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(e,ut(s))}}};const hv={kernelName:gr,gradFunc:e=>({x:()=>re(e)})};const dv={kernelName:Ec,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=Ie(s.shape,n.shape),r=()=>{const a=Z(e,G(n,"float32")),l=Ye(s.shape,i);return l.length>0?O(te(a,l),s.shape):a},o=()=>{let a=R(e,G(s,"float32"));const l=Ye(n.shape,i);l.length>0&&(a=O(te(a,l),n.shape));const c=xe(n);return _e(Z(a,G(c,"float32")))};return{a:r,b:o}}};const mv={kernelName:vi,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,s)=>{const{varianceEpsilon:n}=s,[i,r,o,a]=t,l=a??j(1),c=Ye(r.shape,i.shape),p=[];if(r.rank===1){for(let T=0;T<i.shape.length-1;++T)p.push(i.shape[T]);p.push(1)}const u=X(i,r),h=R(e,l),d=hl($(o,j(n))),m=R(R(R(d,d),d),j(-.5)),f=()=>r.rank===1?O(R(R(e,Us(O(d,[1,1,1,r.shape[0]]),p)),l),i.shape):O(R(R(e,d),l),i.shape),g=()=>{let T=R(R(d,j(-1)),h);return r.rank===1&&(T=te(T,c)),O(T,r.shape)},y=()=>{let T=R(R(m,u),h);return r.rank===1&&(T=te(T,c)),O(T,r.shape)},w=()=>{const T=R(u,d);let A=R(e,T);return r.rank===1&&(A=te(A,c)),O(A,r.shape)},x=()=>{let T=e;return r.rank===1&&(T=te(T,c)),O(T,r.shape)};return{x:f,mean:g,variance:y,scale:w,offset:x}}};const yv={kernelName:_c,inputsToSave:["x","indices"],gradFunc:(e,t,s)=>{const[n,i]=t,{axis:r}=s,o=Ne(r,n.shape)[0],a=()=>{const l=n.shape,c=i.size,p=l.slice(0,o),u=p.length,h=l.slice(r,l.length).slice(1),d=h.length,m=fv(0,u),f=fv(u+1,u+1+d),g=gv([p,[c],h]),y=O(e,g),w=O(i,[c]),x=gv([[u],m,f]),T=se(y,x);let A=Bh(T,w,n.shape[o]);const _=Mo(x);return A=se(A,_),A};return{x:a,indices:()=>i}}};function fv(e,t){const s=[];for(let n=e;n<t;++n)s.push(n);return s}function gv(e){const t=[];for(let s=0;s<e.length;++s)for(let n=0;n<e[s].length;++n)t.push(e[s][n]);return t}const bv={kernelName:kc,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t;return{a:()=>re(s),b:()=>re(n)}}};const wv={kernelName:Ti,gradFunc:e=>({x:()=>G(e,"float32")})};const xv={kernelName:yr,gradFunc:e=>({x:()=>re(e)})};const Lv={kernelName:br,gradFunc:e=>({x:()=>re(e)})};const Sv={kernelName:wr,gradFunc:e=>({x:()=>re(e)})};const Iv={kernelName:Lr,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>Z(e,$(s,1))}}};const vv={kernelName:xr,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>Z(e,G(s,"float32"))}}};const Tv={kernelName:Mc,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,s)=>{const[n]=t,{axis:i}=s;return{logits:()=>{const r=!0,o=ut(n);return X(e,R(te(e,i,r),o))}}}};function k$(e,t,s,n=5,i=1,r=1,o=.5){const a=p=>p.LRNGrad(s,e,t,n,i,r,o),l={x:e,y:t,dy:s},c={depthRadius:n,bias:i,alpha:r,beta:o};return v.runKernelFunc(a,l,null,Pg,c)}const Av=S({localResponseNormalizationBackprop_:k$});const Nv={kernelName:Uc,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,s)=>{const[n,i]=t,{depthRadius:r,bias:o,alpha:a,beta:l}=s;return{x:()=>Av(n,i,e,r,o,a,l)}}};function Zh(e,t,s,n,i){return t.rank<s.rank&&(t=O(t,bt(t.shape,n))),e.rank<s.rank&&(e=O(e,bt(e.shape,n))),{x:()=>{const r=R(e,G(os(s,t),e.dtype));return i==null?r:se(r,i)}}}const Xy={kernelName:Ai,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,s)=>{const n=s,{reductionIndices:i}=n,[r,o]=t,a=Ne(i,r.shape),l=ht(a,r.rank),c=Zh(e,o,r,a,l);return{x:()=>{let p=c.x();return l!=null&&(p=se(p)),p}}}};const Cv={kernelName:$c,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=()=>R(e,G(ds(s,n),"float32")),r=()=>R(e,G(zr(s,n),"float32"));return{a:i,b:r}}};function D$(e,t,s,n,i,r=[1,1,1],o,a){const l=b(e,"dy","maxPool3dBackprop"),c=b(t,"input","maxPool3dBackprop"),p=b(s,"output","maxPool3dBackprop");let u=l,h=c,d=p,m=!1;c.rank===4&&(m=!0,u=O(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),h=O(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]]),d=O(p,[1,p.shape[0],p.shape[1],p.shape[2],p.shape[3]])),I(u.rank===5,()=>`Error in maxPool3dBackprop: dy must be rank 5 but got rank ${u.rank}.`),I(h.rank===5,()=>`Error in maxPool3dBackprop: input must be rank 5 but got rank ${h.rank}.`),I(d.rank===5,()=>`Error in maxPool3dBackprop: output must be rank 5 but got rank ${d.rank}.`),I(tt(i,r),()=>`Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides ${i} and dilations '${r}'`),a!=null&&I(ke(o),()=>`Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);const f=x=>{const T=_i(h.shape,n,i,r,o,a);return x.maxPool3dBackprop(u,h,d,T)},g={dy:u,input:h,output:d},y={filterSize:n,strides:i,dilations:r,pad:o,dimRoundingMode:a},w=v.runKernelFunc(f,g,null,Bg,y);return m?O(w,[w.shape[1],w.shape[2],w.shape[3],w.shape[4]]):w}const Rv=S({maxPool3dBackprop_:D$});const Ov={kernelName:Wc,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,s)=>{const[n,i]=t,{filterSize:r,strides:o,dilations:a,pad:l,dimRoundingMode:c}=s,p=a??[1,1,1];return{x:()=>Rv(e,n,i,r,o,p,l,c)}}};function F$(e,t,s,n,i,r,o){const a=b(e,"dy","maxPoolBackprop"),l=b(t,"input","maxPoolBackprop"),c=b(s,"output","maxPoolBackprop");I(l.rank===a.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${a.rank})`),I(a.rank===4,()=>`Error in maxPoolBackprop: dy must be rank 4 but got rank ${a.rank}.`),I(l.rank===4,()=>`Error in maxPoolBackprop: input must be rank 4 but got rank ${l.rank}.`),o!=null&&I(ke(r),()=>`Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode ${o} but got pad ${r}.`);const p=d=>{const m=Fn(l.shape,n,i,1,r,o);return d.maxPoolBackprop(a,l,c,m)},u={dy:a,input:l,output:c},h={filterSize:n,strides:i,pad:r,dimRoundingMode:o};return v.runKernelFunc(p,u,null,Io,h)}const Ev=S({maxPoolBackprop_:F$});const _v={kernelName:Ni,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,s)=>{const[n,i]=t,{filterSize:r,strides:o,pad:a}=s;return{x:()=>Ev(e,n,i,r,o,a)}}};const kv={kernelName:zc,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,s)=>{const n=s,{axis:i}=n,[r,o]=t,a=Ne(i,r.shape),l=ht(a,r.rank),c=Zh(e,o,r,a,l);return{x:()=>{let p=c.x();return l!=null&&(p=se(p)),p}}}};const Dv={kernelName:Pc,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=()=>R(e,G($s(s,n),"float32")),r=()=>R(e,G(Ut(s,n),"float32"));return{a:i,b:r}}};const Fv={kernelName:Bc,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=Ie(s.shape,n.shape),r=()=>{const a=Ye(s.shape,i);return a.length>0?O(te(e,a),s.shape):e},o=()=>{const a=R(e,_e(li(Z(s,n)))),l=Ye(n.shape,i);return l.length>0?O(te(a,l),n.shape):a};return{a:r,b:o}}};const Mv={kernelName:Sr,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=Ie(s.shape,n.shape),r=()=>{const a=R(e,G(n,"float32")),l=Ye(s.shape,i);return l.length>0?O(te(a,l),s.shape):a},o=()=>{const a=R(e,G(s,"float32")),l=Ye(n.shape,i);return l.length>0?O(te(a,l),n.shape):a};return{a:r,b:o}}};const Uv={kernelName:jc,gradFunc:e=>({x:()=>_e(e)})};const $v={kernelName:qc,inputsToSave:["indices"],gradFunc:(e,t)=>{const s=t[0];return{indices:()=>ye(s.shape,"float32")}}};const Wv={kernelName:Gc,gradFunc:e=>({x:()=>re(e)})};const Jy={kernelName:No,inputsToSave:["x"],gradFunc:(e,t,s)=>{const n=t[0],{paddings:i}=s,r=i.map(o=>o[0]);return{x:()=>he(e,r,n.shape)}}};const zv={kernelName:Hc,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[s,n,i]=t,r=s,o=n,a=Ie(r.shape,o.shape),l=()=>{const p=G(o,"float32");let u=R(e,R(p,Qt(r,X(p,j(1)))));const h=Ye(r.shape,a);return h.length>0&&(u=te(u,h)),O(u,r.shape)},c=()=>{const p=Ut(r,0),u=dt(p,zt(r),re(r));let h=R(e,R(i,u));const d=Ye(o.shape,a);return d.length>0&&(h=te(h,d)),O(h,o.shape)};return{a:l,b:c}}};const Pv={kernelName:Yc,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[s,n]=t,i=Ut(s,0);return{x:()=>dt(i,e,R(e,n)),alpha:()=>{let r=dt(i,re(e),R(e,s));const o=Ye(n.shape,e.shape);return o.length>0&&(r=te(r,o)),O(r,n.shape)}}}};const Bv={kernelName:Ir,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>Z(e,_e(xe(s)))}}};const jv={kernelName:Qc,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t,n=R($s(s,6),ui(s));return{x:()=>R(e,G(n,"float32"))}}};const Vv={kernelName:Xc,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(e,G(ui(s),"float32"))}}};const Gv={kernelName:Ci,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>O(e,s.shape)}}};const qv={kernelName:Zc,inputsToSave:["images"],gradFunc:(e,t,s)=>{const[n]=t,i=a=>{const{alignCorners:l}=s;return a.resizeBilinearBackprop(e,n,l)},r={images:n},o=()=>v.runKernelFunc(i,r,null,qg,s);return{images:o}}};const Hv={kernelName:Jc,inputsToSave:["images"],gradFunc:(e,t,s)=>{const[n]=t,i=a=>{const{alignCorners:l}=s;return a.resizeNearestNeighborBackprop(e,n,l)},r={images:n},o=()=>v.runKernelFunc(i,r,null,Gg,s);return{images:o}}};const Yv={kernelName:ep,gradFunc:(e,t,s)=>{const{dims:n}=s,i=Ne(n,e.shape);return{x:()=>Et(e,i)}}};const Kv={kernelName:vr,gradFunc:e=>({x:()=>re(e)})};const Xv={kernelName:Tr,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>_e(Z(e,R(Qt(s,1.5),2)))}}};const Jv={kernelName:tp,inputsToSave:["condition"],gradFunc:(e,t)=>{const[s]=t;return{condition:()=>G(re(s),"float32"),t:()=>R(e,G(s,e.dtype)),e:()=>R(e,G(Pr(s),e.dtype))}}};const Zv={kernelName:Ar,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>{const n=Ut(s,j(0)),i=j(Yy),r=j(Ky),o=R(e,r),a=R(R(e,i),ut(G(s,"float32")));return dt(n,o,a)}}}};const Qv={kernelName:Rr,outputsToSave:[!0],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(e,R(s,X(j(1),s)))}}};const eT={kernelName:Cr,gradFunc:e=>({x:()=>re(e)})};const tT={kernelName:Zn,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(Wr(G(s,"float32")),e)}}};const sT={kernelName:Nr,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(nl(G(s,"float32")),e)}}};const nT={kernelName:Co,inputsToSave:["x"],gradFunc:(e,t,s)=>{const[n]=t,{begin:i,size:r}=s,o=n.shape,[a,l]=vp(n,i,r),c=[];for(let p=0;p<e.rank;p++)c.push([a[p],o[p]-a[p]-l[p]]);return{x:()=>Pt(e,c)}}};const iT={kernelName:ip,outputsToSave:[!0],gradFunc:(e,t,s)=>{const[n]=t,{dim:i}=s,r=!0,o=R(e,n);return{logits:()=>X(o,R(te(o,[i],r),n))}}};const rT={kernelName:Or,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(e,rs(s))}}};const Zy={kernelName:Ro,gradFunc:(e,t,s)=>{const{blockShape:n,paddings:i}=s;return{x:()=>$r(e,n,i)}}};const Qy={kernelName:np,gradFunc:(e,t,s)=>{const{axis:n}=s;return{x:()=>be(e,n)}}};const oT={kernelName:Er,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>Z(e,R(Xe(G(s,"float32")),2))}}};const aT={kernelName:Oo,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(e,R(G(s,"float32"),2))}}};const lT={kernelName:Qn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=j(2),r=()=>R(e,R(i,X(s,n))),o=()=>R(e,R(i,X(n,s)));return{a:r,b:o}}};const cT={kernelName:Dr,gradFunc:e=>({x:()=>re(e)})};const pT={kernelName:_r,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[s,n]=t,i=Ie(s.shape,n.shape),r=()=>{let a=e;const l=Ye(s.shape,i);return l.length>0&&(a=te(a,l)),O(a,s.shape)},o=()=>{let a=e;const l=Ye(n.shape,i);return l.length>0&&(a=te(a,l)),O(_e(a),n.shape)};return{a:r,b:o}}};const uT={kernelName:sp,inputsToSave:["x"],gradFunc:(e,t,s)=>{const[n]=t,i=n.shape.slice(),{axis:r}=s,o=Ne(r,n.shape);o.forEach(c=>{i[c]=1});const a=O(e,i),l=R(a,Kt(n.shape,"float32"));return{x:()=>l}}};const hT={kernelName:ei,inputsToSave:["x"],gradFunc:(e,t)=>{const[s]=t;return{x:()=>Z(e,xe(Wr(s)))}}};const dT={kernelName:kr,outputsToSave:[!0],gradFunc:(e,t)=>{const[s]=t;return{x:()=>R(X(j(1),xe(s)),e)}}};const mT={kernelName:rp,inputsToSave:["x"],gradFunc:(e,t,s)=>{const[n]=t,{reps:i}=s,r=()=>{let o=re(n);if(n.rank===1)for(let a=0;a<i[0];++a)o=$(o,he(e,[a*n.shape[0]],[n.shape[0]]));else if(n.rank===2)for(let a=0;a<i[0];++a)for(let l=0;l<i[1];++l)o=$(o,he(e,[a*n.shape[0],l*n.shape[1]],[n.shape[0],n.shape[1]]));else if(n.rank===3)for(let a=0;a<i[0];++a)for(let l=0;l<i[1];++l)for(let c=0;c<i[2];++c)o=$(o,he(e,[a*n.shape[0],l*n.shape[1],c*n.shape[2]],[n.shape[0],n.shape[1],n.shape[2]]));else if(n.rank===4)for(let a=0;a<i[0];++a)for(let l=0;l<i[1];++l)for(let c=0;c<i[2];++c)for(let p=0;p<i[3];++p)o=$(o,he(e,[a*n.shape[0],l*n.shape[1],c*n.shape[2],p*n.shape[3]],[n.shape[0],n.shape[1],n.shape[2],n.shape[3]]));else throw new Error(`Gradient for tile operation is not implemented for rank-${n.rank} tensors yet.`);return o};return{x:r}}};const fT={kernelName:Ri,gradFunc:(e,t,s)=>{const n=s,{perm:i}=n,r=Mo(i);return{x:()=>se(e,r)}}};const gT={kernelName:op,gradFunc:(e,t,s)=>{const n=s,{axis:i}=n;return{value:()=>Ve(e,i)}}};const yT={kernelName:ap,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[s]=t,n=()=>M$(e,s);return{x:n}}};function M$(e,t){const s=Ht(t,re(t)),n=ci(e,s);let i=ds(t,j(0,"int32"));const r=n.rank-i.rank;for(let a=0;a<r;++a)i=Mt(i,a+1);i=Yt(i,Kt(n.shape,"bool"));const o=re(n);return dt(i,n,o)}const bT={kernelName:lp,gradFunc:e=>({x:()=>re(e)})};const U$=[RI,OI,EI,_I,kI,DI,FI,MI,UI,$I,WI,zI,BI,VI,GI,qI,HI,YI,KI,XI,JI,QI,ZI,tv,sv,nv,iv,rv,ov,av,lv,cv,pv,uv,dv,hv,mv,yv,bv,wv,xv,Lv,Sv,Iv,vv,Tv,Nv,Xy,Xy,Cv,Ov,_v,kv,Dv,Fv,Mv,Uv,$v,Wv,Jy,Jy,zv,Pv,Bv,jv,Vv,Gv,qv,Hv,Yv,Kv,Xv,Jv,Zv,Qv,eT,tT,sT,nT,iT,rT,Zy,Zy,Qy,Qy,oT,lT,aT,cT,pT,uT,hT,dT,mT,fT,gT,yT,bT];for(const e of U$)Zg(e);let eb;function Tt(){return eb==null&&(eb=ky().epsilon()),eb}function gs(){return"channelsLast"}class bn extends Error{constructor(e){super(e);Object.setPrototypeOf(this,bn.prototype)}}class Ts extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Ts.prototype)}}class k extends Error{constructor(e){super(e);Object.setPrototypeOf(this,k.prototype)}}class ae extends Error{constructor(e){super(e);Object.setPrototypeOf(this,ae.prototype)}}class tb extends Error{constructor(e){super(e);Object.setPrototypeOf(this,tb.prototype)}}class $$ extends Error{constructor(e){super(e);Object.setPrototypeOf(this,$$.prototype)}}function wn(e,t){if(Array.isArray(e)){let s=[];for(let n=0;n<t;n++)s=s.concat(e);return s}else{const s=new Array(t);return s.fill(e),s}}function Qs(e,t){if(!e)throw new tb(t)}function sb(e,t){let s=0;for(const n of e)n===t&&s++;return s}function jt(e){return e.length===1?e[0]:e}function qe(e){return Array.isArray(e)?e:[e]}function xn(e){const t=e.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2"),s=t.replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return s[0]!=="_"?s:"private"+s}function $i(e){return e.length<=1||e.indexOf("_")===-1?e:e.replace(/[_]+(\w|$)/g,(t,s)=>s.toUpperCase())}let Ln={};function xl(e){if(e==null)return null;const t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function nb(e){if(e==null||typeof e!="object")return;if(Array.isArray(e))e.forEach(t=>nb(t));else{const t=Object.keys(e);for(const s of t){const n=e[s];n!=null&&typeof n=="object"&&(!Array.isArray(n)&&n.type==="ndarray"&&typeof n.value=="number"?e[s]=n.value:nb(n))}}}function hi(e,t={},s={},n="object",i=!1){if(typeof e=="string"){const r=e;let o;if(r in s)o=s[r];else if(r in Ln)o=Ln[r];else if(o=t[r],o==null)throw new k(`Unknown ${n}: ${e}. This may be due to one of the following reasons:
1. The ${n} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${n} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return o}else{const r=e;if(r.className==null||r.config==null)throw new k(`${n}: Improper config format: ${JSON.stringify(r)}.
'className' and 'config' must set.`);const o=r.className;let a,l;if(o in s?[a,l]=s[o]:o in Ln?[a,l]=Ln.className:o in t&&([a,l]=t[o]),a==null)throw new k(`Unknown ${n}: ${o}. This may be due to one of the following reasons:
1. The ${n} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
2. The custom ${n} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(l!=null){const c={};for(const d of Object.keys(Ln))c[d]=Ln[d];for(const d of Object.keys(s))c[d]=s[d];const p=r.config;p.customObjects=c;const u=Object.assign({},Ln);for(const d of Object.keys(s))Ln[d]=s[d];nb(r.config);const h=l(a,r.config,s,i);return Ln=Object.assign({},u),h}else{const c=Object.assign({},Ln);for(const u of Object.keys(s))Ln[u]=s[u];const p=new a(r.config);return Ln=Object.assign({},c),p}}}function W$(e,t){return e<t?-1:e>t?1:0}function Dp(e,t){return-1*W$(e,t)}function Sn(e){if(e==null)return e;const t=[];for(const s of e)t.indexOf(s)===-1&&t.push(s);return t}function wT(e){if(e==null)throw new k(`Invalid value in obj: ${JSON.stringify(e)}`);for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function Wi(e,t,s){if(s==null)return;if(e.indexOf(s)<0)throw new k(`${s} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function Qh(e,t,s=0,n=Infinity){return Qs(s>=0),Qs(n>=s),Array.isArray(e)&&e.length>=s&&e.length<=n&&e.every(i=>typeof i===t)}function gt(e,t){Array.isArray(e)?(N.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((s,n)=>gt(s,`element ${n+1} of ${t}`))):N.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${xT(e)}.`)}function xT(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>xT(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function LT(e,t){let s=N.now(),n;const i=(...r)=>{const o=N.now();return o-s<t||(s=o,n=e(...r)),n};return i}function ed(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function ib(e,t){return C(()=>Xe(te(R(e,e),t,!0)))}class Fp extends V.Serializable{getConfig(){return{}}}class td extends Fp{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 C(()=>{const t=ib(e,this.axis),s=wt(t,0,this.maxValue);return R(e,Z(s,$(Tt(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}td.className="MaxNorm";V.registerClass(td);class sd extends Fp{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return C(()=>Z(e,$(Tt(),ib(e,this.axis))))}getConfig(){return{axis:this.axis}}}sd.className="UnitNorm";V.registerClass(sd);class nd extends Fp{apply(e){return De(e)}}nd.className="NonNeg";V.registerClass(nd);class id extends Fp{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 C(()=>{const t=ib(e,this.axis),s=$(R(this.rate,wt(t,this.minValue,this.maxValue)),R(1-this.rate,t));return R(e,Z(s,$(Tt(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}id.className="MinMaxNorm";V.registerClass(id);const ST={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function it(e){return xl(e)}function IT(e,t={}){return hi(e,V.SerializationMap.getMap().classNameMap,t,"constraint")}function rt(e){if(e==null)return null;if(typeof e=="string"){const t=e in ST?ST[e]:e,s={className:t,config:{}};return IT(s)}else return e instanceof Fp?e:IT(e)}const rb={};Ee(rb,{maxNorm:()=>z$,minMaxNorm:()=>j$,nonNeg:()=>B$,unitNorm:()=>P$});function z$(e){return new td(e)}function P$(e){return new sd(e)}function B$(){return new nd}function j$(e){return new id(e)}const vT=["channelsFirst","channelsLast"],TT=["valid","same","causal"],AT=["max","avg"],NT=["sum","mul","concat","ave"];const Ll=new Map;function ot(e){Wi(vT,"DataFormat",e)}function ys(e){Wi(TT,"PaddingMode",e)}function ob(e){Wi(AT,"PoolMode",e)}const Mp=[],CT="/";function Mn(e,t){Mp.push(e);try{const s=t();return Mp.pop(),s}catch(s){throw Mp.pop(),s}}function V$(){return Mp.length===0?"":Mp.join(CT)+CT}function rd(e){if(!RT(e))throw new Error("Not a valid tensor name: '"+e+"'");return V$()+e}function od(e){if(!RT(e))throw new Error("Not a valid tensor name: '"+e+"'");Ll.has(e)||Ll.set(e,0);const t=Ll.get(e);if(Ll.set(e,Ll.get(e)+1),t>0){const s=`${e}_${t}`;return Ll.set(s,1),s}else return e}const G$=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function RT(e){return!!e.match(G$)}function OT(e){return e===parseInt(e.toString(),10)}function In(e,t,s){t==null&&(t=0),s==null&&(s=e.length);let n=1;for(let i=t;i<s;++i)n*=e[i];return n}function ET(e){return e=Array.isArray(e)?new Float32Array(e):e,Oe(e)}function ea(e){return Di(ET(e)).dataSync()[0]}function Un(e){return xt(ET(e)).dataSync()[0]}function ls(e,t){if(t<e)throw new k(`end (${t}) < begin (${e}) is forbidden.`);const s=[];for(let n=e;n<t;++n)s.push(n);return s}function zi(e,t){return e.asType(t)}function Pi(e,t=-1){const s=e.shape.slice();return t<0&&(t=s.length+t+1),s.splice(t,0,1),e.reshape(s)}function _T(e,t){return C(()=>{if(e.shape.length!==2)throw new k(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);const s=Pi(e,1);return ad(s,[1,t,1])})}function kT(e){const t=[In(e.shape)];return e.reshape(t)}function DT(e){if(e.rank<=1)throw new k(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);const t=[e.shape[0],In(e.shape,1)];return e.reshape(t)}function Bi(e,t,s){return C(()=>{switch(e.rank){case 1:return gl(e,t,s);case 2:return Cp(e,[t,0],[s,e.shape[1]]);case 3:return Gr(e,[t,0,0],[s,e.shape[1],e.shape[2]]);case 4:return jo(e,[t,0,0,0],[s,e.shape[1],e.shape[2],e.shape[3]]);case 5:return he(e,[t,0,0,0,0],[s,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return he(e,[t,0,0,0,0,0],[s,e.shape[1],e.shape[2],e.shape[3],e.shape[4],e.shape[5]]);default:throw new k(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function ab(e,t,s){return C(()=>{switch(e.rank){case 1:return gl(e,t,s);case 2:return Cp(e,[0,t],[e.shape[0],s]);case 3:return Gr(e,[0,0,t],[e.shape[0],e.shape[1],s]);case 4:return jo(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],s]);default:throw new k(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Up(e,t,s,n){return C(()=>{switch(e.rank){case 1:return gl(e,t,s);case 2:switch(n){case 1:return Bi(e,t,s);case 2:return ab(e,t,s);default:throw new k(`The axis is not within the rank of the tensor ${n}`)}case 3:switch(n){case 1:return Bi(e,t,s);case 2:return Gr(e,[0,t,0],[e.shape[0],s,e.shape[2]]);case 3:return ab(e,t,s);default:throw new k(`The axis is not within the rank of the tensor ${n}`)}case 4:switch(n){case 1:return Bi(e,t,s);case 2:return jo(e,[0,t,0,0],[e.shape[0],s,e.shape[2],e.shape[3]]);case 3:return jo(e,[0,0,t,0],[e.shape[0],e.shape[1],s,e.shape[3]]);case 4:return ab(e,t,s);default:throw new k(`The axis is not within the rank of the tensor ${n}`)}default:throw new k(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Sl(e,t=-1){let s;return t<0&&(s=e[0].rank,s!==0?t=s:t=0),t===e[0].rank&&(t=-1),be(e,t)}function lb(e,t){switch(e.rank){case 1:return fh([e,t]);case 2:return gh([e,t],0);case 3:return yh([e,t],0);case 4:return bh([e,t],0);default:throw new k(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function ad(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new k(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return Us(e,t)}function Il(e,t=0,s=1,n,i){return Np(e,t,s,n,i)}function vn(e,t,s,n){if(e.rank<2||t.rank<2)throw new ae(`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],r=t.shape.slice(-2)[0];if(i!==r)throw new ae(`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,r=!1;return gn.matMul({a:e,b:t,transposeA:i,transposeB:r,bias:n?cb(e.rank,n,gs()):null,activation:s})}else{const i=e.shape.slice(),r=i.pop();e=e.reshape([-1,r]);const o=t.shape.slice(),a=o.pop(),l=o.pop(),c=[...o,a],p=Array.from({length:t.rank},(m,f)=>f===0?t.rank-2:f<=t.rank-2?f-1:f);t=t.transpose(p).reshape([l,-1]);const u=[...i,...c],h=!1,d=!1;return gn.matMul({a:e,b:t,transposeA:h,transposeB:d,bias:n?cb(e.rank,n,gs()):null,activation:s}).reshape(u)}}function ld(e,t,s){return C(()=>(Array.isArray(t)?t=Oe(t,"int32"):t=t.toInt(),ci(e,t,s)))}function ta(e){return R(e,e)}function cb(e,t,s){const n=t.shape;if(t.rank!==1&&t.rank!==e)throw new k(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(e===5){if(s==="channelsFirst")return n.length===1?t.reshape([1,n[0],1,1,1]):t.reshape([1,n[3],n[0],n[1],n[2]]);if(s==="channelsLast")return n.length===1?t.reshape([1,1,1,1,n[0]]):t.reshape([1].concat(n))}else if(e===4){if(s==="channelsFirst")return n.length===1?t.reshape([1,n[0],1,1]):t.reshape([1,n[2],n[0],n[1]]);if(s==="channelsLast")return n.length===1?t.reshape([1,1,1,n[0]]):t.reshape([1].concat(n))}else if(e===3){if(s==="channelsFirst")return n.length===1?t.reshape([1,n[0],1]):t.reshape([1,n[1],n[0]]);if(s==="channelsLast")return n.length===1?t.reshape([1,1,n[0]]):t.reshape([1].concat(n))}else if(e<3)return t;throw new k(`Unsupported input rank by biasAdd: ${t.rank}`)}function As(e,t,s){return C(()=>(s==null&&(s=gs()),ot(s),e.add(cb(e.rank,t,s))))}function FT(e,t=1){if(t!==1)throw new ae(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return hn(e)}function MT(e){return C(()=>Z(e,et(e).add(1)))}function cd(e,t,s,n){return C(()=>Vy(e,t,s,n))}function UT(e){return C(()=>{const t=$(.5,R(.2,e));return wt(t,0,1)})}function Zr(e,t,s=!1){return s?e():t()}const $T=["fanIn","fanOut","fanAvg"],WT=["normal","uniform","truncatedNormal"];function q$(e){Wi($T,"FanMode",e)}function H$(e){Wi(WT,"Distribution",e)}class Ws extends V.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class pd extends Ws{apply(e,t){return ye(e,t)}}pd.className="Zeros";V.registerClass(pd);class vl extends Ws{apply(e,t){return Kt(e,t)}}vl.className="Ones";V.registerClass(vl);class ud extends Ws{constructor(e){super();if(typeof e!="object")throw new k(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new k(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return C(()=>R(j(this.value),Kt(e,t)))}getConfig(){return{value:this.value}}}ud.className="Constant";V.registerClass(ud);class hd extends Ws{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 fn(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}hd.className="RandomUniform";V.registerClass(hd);class dd extends Ws{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 ae(`randomNormal does not support dType ${t}.`);return Il(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}dd.className="RandomNormal";V.registerClass(dd);class md extends Ws{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 ae(`truncatedNormal does not support dType ${t}.`);return Kr(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}md.className="TruncatedNormal";V.registerClass(md);class fd extends Ws{constructor(e){super();this.gain=e.gain!=null?e.gain:1}apply(e,t){return C(()=>{if(e.length!==2||e[0]!==e[1])throw new k("Identity matrix initializer can only be used for 2D square matrices.");return R(this.gain,Po(e[0]))})}getConfig(){return{gain:this.gain}}}fd.className="Identity";V.registerClass(fd);function Y$(e,t="channelsLast"){let s,n;if(ot(t),e.length===2)s=e[0],n=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){const i=In(e,2);s=e[1]*i,n=e[0]*i}else if(t==="channelsLast"){const i=In(e,0,e.length-2);s=e[e.length-2]*i,n=e[e.length-1]*i}}else{const i=In(e);s=Math.sqrt(i),n=Math.sqrt(i)}return[s,n]}class bs extends Ws{constructor(e){super();if(e.scale<0)throw new k(`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,q$(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,H$(this.distribution),this.seed=e.seed}apply(e,t){const s=Y$(e),n=s[0],i=s[1];let r=this.scale;if(this.mode==="fanIn"?r/=Math.max(1,n):this.mode==="fanOut"?r/=Math.max(1,i):r/=Math.max(1,(n+i)/2),this.distribution==="normal"){const o=Math.sqrt(r);if(t=t||"float32",t!=="float32"&&t!=="int32")throw new ae(`${this.getClassName()} does not support dType ${t}.`);return Kr(e,0,o,t,this.seed)}else{const o=Math.sqrt(3*r);return fn(e,-o,o,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}bs.className="VarianceScaling";V.registerClass(bs);class $p extends bs{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return bs.className}}$p.className="GlorotUniform";V.registerClass($p);class Wp extends bs{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return bs.className}}Wp.className="GlorotNormal";V.registerClass(Wp);class zp extends bs{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return bs.className}}zp.className="HeNormal";V.registerClass(zp);class Pp extends bs{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return bs.className}}Pp.className="HeUniform";V.registerClass(Pp);class Bp extends bs{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return bs.className}}Bp.className="LeCunNormal";V.registerClass(Bp);class jp extends bs{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return bs.className}}jp.className="LeCunNormal";V.registerClass(jp);class gd extends Ws{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 ae("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return C(()=>{if(e.length<2)throw new ae("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 s=e[0]>e[1]?[e[1],e[0]]:e,n=Il(s,0,1,"float32");let i=Hy.gramSchmidt(n);return e[0]>e[1]&&(i=i.transpose()),R(this.gain,i)})}getConfig(){return{gain:this.gain,seed:this.seed}}}gd.className="Orthogonal";V.registerClass(gd);const zT={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 PT(e,t={}){return hi(e,V.SerializationMap.getMap().classNameMap,t,"initializer")}function Je(e){return xl(e)}function Be(e){if(typeof e=="string"){const t=e in zT?zT[e]:e;if(t==="GlorotNormal")return new Wp;if(t==="GlorotUniform")return new $p;if(t==="HeNormal")return new zp;if(t==="HeUniform")return new Pp;if(t==="LeCunNormal")return new Bp;if(t==="LeCunUniform")return new jp;{const s={};return s.className=t,s.config={},PT(s)}}else return e instanceof Ws?e:PT(e)}const pb={};Ee(pb,{constant:()=>J$,glorotNormal:()=>iW,glorotUniform:()=>nW,heNormal:()=>rW,heUniform:()=>oW,identity:()=>tW,leCunNormal:()=>aW,leCunUniform:()=>lW,ones:()=>X$,orthogonal:()=>cW,randomNormal:()=>Q$,randomUniform:()=>Z$,truncatedNormal:()=>eW,varianceScaling:()=>sW,zeros:()=>K$});function K$(){return new pd}function X$(){return new vl}function J$(e){return new ud(e)}function Z$(e){return new hd(e)}function Q$(e){return new dd(e)}function eW(e){return new md(e)}function tW(e){return new fd(e)}function sW(e){return new bs(e)}function nW(e){return new $p(e)}function iW(e){return new Wp(e)}function rW(e){return new zp(e)}function oW(e){return new Pp(e)}function aW(e){return new Bp(e)}function lW(e){return new jp(e)}function cW(e){return new gd(e)}let pW=0;function yd(){return pW++}const bd={};function Qr(e=""){return e in bd||(bd[e]=0),bd[e]+=1,e+bd[e].toString()}function wd(e){return Array.isArray(e)&&Array.isArray(e[0])}function Tl(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function we(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new k(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function Ue(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(e.length===1)return e=e,e[0];throw new k(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function Al(e){let t=0;for(const s of e)s.shape.length===0?t+=1:t+=s.shape.reduce((n,i)=>n*i);return t}const BT="Variable";class xd{constructor(e,t="float32",s=BT,n=!0,i=null){this.dtype=t??"float32",this.shape=e.shape,this.id=yd(),s=s??BT,this.originalName=rd(s),this.name=od(this.originalName),this.trainable_=n,this.constraint=i,this.val=jh(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),uW(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 uW(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function Vp(e){return e.map(t=>t.read())}function Nl(e){e.forEach(t=>{const s=t[0];s.write(t[1])})}class st{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 ws{constructor(e,t,s,n,i,r,o){this.dtype=e,this.shape=t,this.sourceLayer=s,this.inputs=n,this.callArgs=i,this.outputTensorIndex=o,this.id=yd(),r!=null&&(this.originalName=rd(r),this.name=od(this.originalName)),this.rank=t.length}}let hW=0;class sa{constructor(e,t){this.callArgs=t,this.id=hW++,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 s of e.inboundLayers)s!=null&&s.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 dW=0;class Le extends V.Serializable{constructor(e={}){super();this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=dW++,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 s=this.getClassName();t=xn(s)+"_"+Qr(s)}if(this.name=t,this.trainable_=e.trainable==null?!0:e.trainable,e.inputShape!=null||e.batchInputShape!=null){let s;if(e.batchInputShape!=null)s=e.batchInputShape;else if(e.inputShape!=null){let i=null;e.batchSize!=null&&(i=e.batchSize),s=[i].concat(e.inputShape)}this.batchInputShape=s;let n=e.dtype;n==null&&(n=e.inputDType),n==null&&(n="float32"),this.dtype=n}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 Ts(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new k(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return jt(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return jt(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new bn(`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 bn(`Layer ${this.name} is not connected, no input to return.`);return jt(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new bn(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new bn(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return jt(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=qe(e),this.inputSpec==null||this.inputSpec.length===0)return;const t=qe(this.inputSpec);if(e.length!==t.length)throw new k(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let s=0;s<e.length;s++){const n=e[s],i=t[s];if(i==null)continue;const r=n.rank;if(i.ndim!=null&&r!==i.ndim)throw new k(`Input ${s} is incompatible with layer ${this.name}: expected ndim=${i.ndim}, found ndim=${r}`);if(i.maxNDim!=null&&r>i.maxNDim)throw new k(`Input ${s} is incompatible with layer ${this.name}: expected max_ndim=${i.maxNDim}, found ndim=${r}`);if(i.minNDim!=null&&r<i.minNDim)throw new k(`Input ${s} is incompatible with layer ${this.name}: expected min_ndim=${i.minNDim}, found ndim=${r}.`);if(i.dtype!=null&&n.dtype!==i.dtype)throw new k(`Input ${s} is incompatible with layer ${this.name} : expected dtype=${i.dtype}, found dtype=${n.dtype}.`);if(i.axes){const o=n.shape;for(const a in i.axes){const l=Number(a),c=i.axes[a],p=l>=0?o[l]:o[o.length+l];if(c!=null&&[c,null].indexOf(p)===-1)throw new k(`Input ${s} is incompatible with layer ${this.name}: expected axis ${l} of input shape to have value ${c} but got shape ${o}.`)}}if(i.shape!=null)for(let o=0;o<i.shape.length;++o){const a=i.shape[o],l=n.shape[o];if(a!=null&&l!=null&&a!==l)throw new k(`Input ${s} is incompatible with layer ${this.name}: expected shape=${i.shape}, found shape=${n.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 s=qe(e);let n=!0;for(const r of s)if(!(r instanceof ws)){n=!1;break}let i=!0;for(const r of s)if(r instanceof ws){i=!1;break}if(n===i)throw new k("Arguments to apply() must be all SymbolicTensors or all Tensors");return Mn(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);const r=[];for(const o of qe(e))r.push(o.shape);this.build(jt(r)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&i&&(this._refCount=1)}if(this.assertInputCompatibility(e),i){let r=this.call(e,t);const o=qe(r),a=[];for(let l of o)s.indexOf(l)!==-1&&(l=l.clone()),a.push(l);if(r=jt(a),this.activityRegularizer!=null)throw new ae("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return r}else{const r=mW(e),o=this.computeOutputShape(r);let a;const l=fW(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?r[0]:r),o!=null&&o.length>0&&Array.isArray(o[0])?a=o.map((c,p)=>new ws(l,c,this,qe(e),t,this.name,p)):a=new ws(l,o,this,qe(e),t,this.name),this.addInboundNode(e,a,null,null,r,o,t),this._refCount++,this.activityRegularizer!=null)throw new ae("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return a}})}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((s,n)=>{s!=null&&e[n]!=null&&e[n]!==s&&(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 bn(`The layer ${this.name} has never been called and thus has no defined output shape.`);const e=[];for(const t of this.inboundNodes){const s=JSON.stringify(t.outputShapes);e.indexOf(s)===-1&&e.push(s)}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 bn(`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 Ts(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Al(this.weights)}build(e){this.built=!0}getWeights(e=!1){return Vp(e?this.trainableWeights:this.weights)}setWeights(e){C(()=>{const t=this.weights;if(t.length!==e.length)throw new k(`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 s=[],n=Vp(t);for(let i=0;i<n.length;++i){const r=n[i],o=t[i],a=e[i];if(!N.arraysEqual(r.shape,a.shape))throw new k(`Layer weight shape ${r.shape} not compatible with provided weight shape ${a.shape}`);s.push([o,a])}Nl(s)})}addWeight(e,t,s,n,i,r,o){if(this._addedWeightNames.indexOf(e)!==-1)throw new k(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),s==null&&(s="float32"),this.fastWeightInitDuringBuild&&(n=Be("zeros"));const a=n.apply(t,s),l=new xd(a,s,e,r,o);return a.dispose(),i!=null&&this.addLoss(()=>i.apply(l.read())),r==null&&(r=!0),r?this._trainableWeights.push(l):this._nonTrainableWeights.push(l),l}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){if(e==null||Array.isArray(e)&&e.length===0)return;e=qe(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(s=>{if(s!=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,s,n,i,r,o=null){const a=qe(e);t=qe(t),s=qe(s),n=qe(n),i=Tl(i),r=Tl(r);const l=[],c=[],p=[];for(const u of a)l.push(u.sourceLayer),c.push(u.nodeIndex),p.push(u.tensorIndex);new sa({outboundLayer:this,inboundLayers:l,nodeIndices:c,tensorIndices:p,inputTensors:a,outputTensors:t,inputMasks:s,outputMasks:n,inputShapes:i,outputShapes:r},o);for(let u=0;u<t.length;u++)t[u].sourceLayer=this,t[u].nodeIndex=this.inboundNodes.length-1,t[u].tensorIndex=u}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 mW(e){e=qe(e);const t=[];for(const s of e)t.push(s.shape);return jt(t)}function fW(e){return"float32"}function ub(e,t,s){if((t==null||s!=null&&s>0)&&(t=e.sourceLayer,s=e.nodeIndex),t.inboundNodes.length===0)return[e];{const n=t.inboundNodes[s];if(n.inboundLayers.length===0)return n.inputTensors;{const i=[];for(let r=0;r<n.inboundLayers.length;r++){const o=n.inputTensors[r],a=n.inboundLayers[r],l=n.nodeIndices[r],c=ub(o,a,l);for(const p of c)i.indexOf(p)===-1&&i.push(p)}return i}}}class ji extends Le{constructor(e){super({dtype:e.dtype,name:e.name!=null?e.name:Qr("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 k("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 k("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(e.batchSize!=null)throw new k("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");const s=e.dtype||"float32";this.batchInputShape=t,this.dtype=s,this.inputSpec=[{shape:t}];const n=new ws(this.dtype,this.batchInputShape,this,[],{},this.name);n.nodeIndex=0,n.tensorIndex=0,new sa({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[n],outputTensors:[n],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new k(`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}}}ji.className="InputLayer";V.registerClass(ji);function Ld(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 k("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 s=e.dtype;s==null&&(s="float32");const n=new ji({batchInputShape:t,name:e.name,dtype:s,sparse:e.sparse}),i=n.inboundNodes[0].outputTensors;return i[0]}async function di(e){if(e==null)return;const t=[],s=[],n=[];for(const i in e){const r=e[i];if(typeof r!="number"){const o=r;t.push(o.data()),s.push(i),n.push(o)}}if(t.length>0){const i=await Promise.all(t);for(let r=0;r<i.length;++r)e[s[r]]=i[r][0];ce(n)}}function Sd(e){if(e==null)return;for(const t in e){const s=e[t];typeof s!="number"&&s.dispose()}}var jT;(function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"})(jT||(jT={}));const gW=125;class na{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 hb{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 s of this.callbacks)await s.onEpochBegin(e,t)}async onEpochEnd(e,t){t==null&&(t={});for(const s of this.callbacks)await s.onEpochEnd(e,t)}async onBatchBegin(e,t){t==null&&(t={});for(const s of this.callbacks)await s.onBatchBegin(e,t)}async onBatchEnd(e,t){t==null&&(t={});for(const s of this.callbacks)await s.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 yW extends na{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){t==null&&(t={});const s=t.size==null?0:t.size;this.seen+=s;for(const n in t){const i=t[n];if(typeof i=="number")this.totals.hasOwnProperty(n)||(this.totals[n]=0),this.totals[n]=this.totals[n]+i*s;else{let r;n in this.totals?r=this.totals[n]:this.totals[n]=0;const o=C(()=>$(this.totals[n],R(i,s)));this.totals[n]=o,r!=null&&r.dispose()}}}async onEpochEnd(e,t){if(t!=null)for(const s of this.params.metrics){if(this.totals[s]==null)continue;typeof this.totals[s]=="number"?t[s]=this.totals[s]/this.seen:C(()=>{const n=R(Z(1,this.seen),this.totals[s]);t[s]=n,this.totals[s].dispose(),pt(t[s])})}}}class db extends na{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){t==null&&(t={}),this.epoch.push(e);for(const s in t)this.history[s]==null&&(this.history[s]=[]),this.history[s].push(t[s])}async syncData(){const e=[],t=[],s=[];for(const i in this.history){const r=this.history[i];for(let o=0;o<r.length;++o)if(typeof r[o]!="number"){const a=r[o];e.push(a.data()),t.push(i),s.push(o)}}const n=await Promise.all(e);for(let i=0;i<n.length;++i){const r=this.history[t[i]][s[i]];r.dispose(),this.history[t[i]][s[i]]=n[i][0]}}}class mb extends na{constructor(e,t){super();if(this.currentEpoch=0,this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=gW),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");N.isNumber(this.yieldEvery)&&(this.maybeWait=LT(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,s){const n=[];this.yield!=null&&(await di(s),n.push(this.yield(e,t,s))),n.push(kp()),await Promise.all(n)}async onEpochBegin(e,t){this.currentEpoch=e,this.epochBegin!=null&&(await di(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){const s=[];this.epochEnd!=null&&(await di(t),s.push(this.epochEnd(e,t))),this.yieldEvery==="epoch"&&s.push(kp()),await Promise.all(s)}async onBatchBegin(e,t){this.batchBegin!=null&&(await di(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){const s=[];this.batchEnd!=null&&(await di(t),s.push(this.batchEnd(e,t))),this.yieldEvery==="batch"?s.push(kp()):N.isNumber(this.yieldEvery)&&s.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(s)}async onTrainBegin(e){this.trainBegin!=null&&(await di(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await di(e),await this.trainEnd(e))}}function Id(e,t){if(e==null&&(e={}),e instanceof na)return[e];if(Array.isArray(e)&&e[0]instanceof na)return e;const s=qe(e);return s.map(n=>new mb(n,t))}class en{constructor(){}static registerCallbackConstructor(e,t){N.assert(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),en.checkForDuplicate(t),en.constructors[e]==null&&(en.constructors[e]=[]),en.constructors[e].push(t)}static checkForDuplicate(e){for(const t in en.constructors){const s=en.constructors[+t];s.forEach(n=>{if(n===e)throw new k("Duplicate callback constructor.")})}}static clear(){en.constructors={}}static createCallbacks(e){const t=[];for(const s in en.constructors){const n=+s;e>=n&&t.push(...en.constructors[n])}return t.map(s=>new s)}}en.constructors={};function vd(e,t,s,n,i,r,o,a,l){const c=new db,p=[new yW,...en.createCallbacks(t)];e!=null&&p.push(...e),p.push(c);const u=new hb(p);return u.setParams({epochs:s,initialEpoch:n,samples:i,steps:r,batchSize:o,verbose:t,doValidation:a,metrics:l}),{callbackList:u,history:c}}function xs(e,t={},s=!1){return hi(e,V.SerializationMap.getMap().classNameMap,t,"layer",s)}function Gp(e,t){return C(()=>{e.dtype!=="float32"&&(e=e.asType("float32"));const s=te(ta(e),t,!0),n=Wt(s.shape,Tt()),i=Xe(Ht(s,n));return Z(e,i)})}function mi(e,t){return C(()=>Ke(ta(X(t,e)),-1))}function Cl(e,t){return C(()=>Ke(et(X(t,e)),-1))}function eo(e,t){return C(()=>{const s=X(e,t),n=wt(et(e),Tt(),Number.MAX_VALUE),i=et(Z(s,n));return R(100,Ke(i,-1))})}function bW(e,t){return C(()=>{const s=wt(t,Tt(),Number.MAX_VALUE),n=zt($(1,s)),i=wt(e,Tt(),Number.MAX_VALUE),r=zt($(1,i));return Ke(ta(X(n,r)),-1)})}function wW(e,t){return C(()=>{const s=Ht(0,X(1,R(e,t)));return Ke(ta(s),-1)})}function xW(e,t){return C(()=>{const s=Ht(0,X(1,R(e,t)));return Ke(s,-1)})}function LW(e,t){return C(()=>{const s=te(R(e,t),-1),n=xt(R(X(1,e),t),-1);return Ht(0,$(1,X(n,s)))})}function SW(e,t){return C(()=>{const s=Math.log(2),n=X(t,e),i=X($(n,pi(R(-2,n))),s);return Ke(i,-1)})}function ia(e,t,s=!1){return C(()=>{if(s)t=es(t);else{const n=te(t,t.shape.length-1,!0);t=Z(t,n)}return t=wt(t,Tt(),1-Tt()),_e(te(R(e.toFloat(),zt(t)),t.shape.length-1))})}function Rl(e,t,s=!1){return C(()=>{const n=li(kT(e)).toInt();t=wt(t,Tt(),1-Tt());const i=t.shape,r=ai(n,i[i.length-1]).reshape(i);return ia(r,t,s)})}function IW(e,t){if(!N.arraysEqual(e.shape,t.shape))throw new k(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return C(()=>{const s=t.relu(),n=t.abs().neg();return s.sub(t.mul(e)).add(n.exp().log1p())})}function Ol(e,t){return C(()=>{let s;return s=wt(t,Tt(),1-Tt()),s=zt(Z(s,X(1,s))),Ke(IW(e,s),-1)})}function vW(e,t){return C(()=>{const s=wt(e,Tt(),1),n=wt(t,Tt(),1);return te(R(e,zt(Z(s,n))),-1)})}function TW(e,t){return C(()=>{const s=zt($(Tt(),t));return Ke(X(t,R(e,s)),-1)})}function qp(e,t){return C(()=>{const s=Gp(e,-1),n=Gp(t,-1),i=R(s,n);return _e(te(i,-1))})}const Hp={meanSquaredError:mi,meanAbsoluteError:Cl,meanAbsolutePercentageError:eo,meanSquaredLogarithmicError:bW,squaredHinge:wW,hinge:xW,categoricalHinge:LW,logcosh:SW,categoricalCrossentropy:ia,sparseCategoricalCrossentropy:Rl,binaryCrossentropy:Ol,kullbackLeiblerDivergence:vW,poisson:TW,cosineProximity:qp};function Td(e){if(typeof e=="string"){if(e in Hp)return Hp[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 k(t)}else return e}function Yp(e,t){return C(()=>{const s=R(.5,Ot(t)),n=zi(Ut(t,s),e.dtype);return Ke(os(e,n),-1)})}function Kp(e,t){return C(()=>zi(os($o(e,-1),$o(t,-1)),"float32"))}function VT(e,t){return C(()=>Yt(e.equal(1),t.equal(1)).sum().cast("float32"))}function AW(e,t){return C(()=>Yt(e.equal(1),t.equal(0)).sum().cast("float32"))}function NW(e,t){return C(()=>Yt(e.equal(0),t.equal(1)).sum().cast("float32"))}function fb(e,t){return C(()=>{const s=VT(e,t),n=NW(e,t),i=s.add(n);return dt(Ut(i,0),s.div(i),0).cast("float32")})}function GT(e,t){return C(()=>{const s=VT(e,t),n=AW(e,t),i=s.add(n);return dt(Ut(i,0),s.div(i),0).cast("float32")})}function Ad(e,t){return Ol(e,t)}function Nd(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)),os(e,t).asType("float32")}const CW=mi,RW=mi,OW=Cl,EW=Cl,_W=eo,kW=eo,Xp=ia,DW=qp,gb=Rl,Cd={binaryAccuracy:Yp,categoricalAccuracy:Kp,precision:fb,categoricalCrossentropy:Xp,sparseCategoricalCrossentropy:gb,mse:CW,MSE:RW,mae:OW,MAE:EW,mape:_W,MAPE:kW,cosine:DW};function qT(e){if(typeof e=="string"&&e in Cd)return Cd[e];if(typeof e!="string"&&e!=null)return e;throw new k(`Unknown metric ${e}`)}function Jp(e){if(Qs(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(const s of Object.keys(Hp))if(Hp[s]===e){t=s;break}if(t!==void 0)return t;for(const s of Object.keys(Cd))if(Cd[s]===e){t=s;break}return t!==void 0?t:e.name}}function HT(e){const t={Adagrad:()=>Jr.adagrad(.01),Adadelta:()=>Jr.adadelta(1,.95,Tt()),Adam:()=>Jr.adam(.001,.9,.999,Tt()),Adamax:()=>Jr.adamax(.002,.9,.999,Tt(),0),RMSProp:()=>Jr.rmsprop(.001,.9,0,Tt()),SGD:()=>Jr.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 k(`Unknown Optimizer ${e}`)}const YT=1*1024*1024;function bb(e,t,s=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!yb(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(s){const n=JSON.stringify(e);n.length>YT&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${n.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= ${YT}.`)}}function yb(e){if(e===null)return!0;if(typeof e=="object")if(Object.getPrototypeOf(e)===Object.prototype){const t=Object.keys(e);for(const s of t){if(typeof s!="string")return!1;if(!yb(e[s]))return!1}return!0}else if(Array.isArray(e)){for(const t of e)if(!yb(t))return!1;return!0}else return!1;else{const t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function KT(e,t,s,n=console.log){const i=MW(e),r=["Layer (type)","Output shape","Param #"];i?(t=t||65,s=s||[.45,.85,1]):(t=t||98,s=s||[.33,.55,.67,1]),s[s.length-1]<=1&&(s=s.map(p=>Math.floor(t*p)));let o;if(!i){r.push("Receives inputs"),o=[];for(const p in e.nodesByDepth)o.push(...e.nodesByDepth[p])}n("_".repeat(t)),Rd(r,s,n),n("=".repeat(t));const a=e.layers;for(let p=0;p<a.length;++p)i?UW(a[p],s,n):$W(a[p],s,o,n),n((p===a.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();const l=FW(e),c=Al(e.nonTrainableWeights);n(`Total params: ${l+c}`),n(`Trainable params: ${l}`),n(`Non-trainable params: ${c}`),n("_".repeat(t))}function FW(e){let t;return e.collectedTrainableWeights!=null?t=Al(e.collectedTrainableWeights):t=Al(e.trainableWeights),t}function MW(e){let t=!0;const s=[],n=[];for(const i in e.nodesByDepth)s.push(e.nodesByDepth[i]);for(const i of s){if(i.length>1||i.length===1&&i[0].inboundLayers.length>1){t=!1;break}n.push(...i)}if(t)for(const i of e.layers){let r=!1;for(const o of i.inboundNodes)if(n.indexOf(o)!==-1)if(r){t=!1;break}else r=!0;if(!t)break}return t}function Rd(e,t,s=console.log){let n="";for(let i=0;i<e.length;++i)i>0&&(n=n.slice(0,n.length-1)+" "),n+=e[i],n=n.slice(0,t[i]),n+=" ".repeat(t[i]-n.length);s(n)}function UW(e,t,s){let n;try{n=JSON.stringify(e.outputShape)}catch(a){n="multiple"}const i=e.name,r=e.getClassName(),o=[`${i} (${r})`,n,e.countParams().toString()];Rd(o,t,s)}function $W(e,t,s,n){let i;try{i=JSON.stringify(e.outputShape)}catch(p){i="multiple"}const r=[];for(const p of e.inboundNodes){if(s!=null&&s.length>0&&s.indexOf(p)===-1)continue;for(let u=0;u<p.inboundLayers.length;++u){const h=p.inboundLayers[u].name,d=p.nodeIndices[u],m=p.tensorIndices[u];r.push(`${h}[${d}][${m}]`)}}const o=e.name,a=e.getClassName(),l=r.length===0?"":r[0],c=[`${o} (${a})`,i,e.countParams().toString(),l];Rd(c,t,n);for(let p=1;p<r.length;++p)Rd(["","","",r[p]],t,n)}function XT(e,t,s){return(e==="inboundNodes"||e==="outputLayers"||e==="inputLayers")&&t===0&&typeof s=="string"}function ra(e,t){if(e===null)return null;if(typeof e=="string")return $i(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){const s=[],n=e.length;for(let i=0;i<n;++i){const r=e[i];XT(t,i,r)?s.push(r):s.push(ra(r,t))}return s}else{const s={};for(const n of Object.keys(e)){const i=e[n];if(n==="name"&&typeof i=="string")s[n]=i;else{const r=$i(n);s[r]=ra(i,r)}}return s}}function Od(e,t){if(e==null)return null;if(typeof e=="string")return xn(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){const s=[],n=e.length;for(let i=0;i<n;++i){const r=e[i];XT(t,i,r)?s.push(r):s.push(Od(r,t))}return s}else{const s={};for(const n of Object.keys(e)){const i=e[n],r=xn(n);(n==="name"||n==="className")&&typeof i=="string"?s[r]=i:s[r]=Od(i,n)}return s}}const to="2.6.0";function WW(e,t){if(e.dtype==null||e.dtype===t.dtype)return t;try{return G(t,e.dtype)}catch(s){throw new k(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}class Vi{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof Vi)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,s){if(this.id2Value[e.id]==null)this.id2Value[e.id]=WW(e,t),this.name2Id[e.name]=e.id,s!=null&&(this.id2Mask[e.id]=s);else throw new k(`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 ws){if(this.id2Value[e.id]==null)throw new k(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}else{const t=this.name2Id[e];if(t==null)throw new k(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof ws){if(this.id2Value[e.id]==null)throw new k(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}else{const t=this.name2Id[e];if(t==null)throw new k(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){this.id2Mask!=null&&ce(this.id2Mask)}}const wb={},JT={};function oa(e,t,s,n){const i=s==null?!1:s.training,r=Array.isArray(e),o=r?e:[e],a=o.map(m=>m.name),l=[],c=t.names();for(const m of a)c.indexOf(m)!==-1?l.push(t.getValue(m)):l.push(null);n!=null&&(n.maxNumTensors=-Infinity,n.minNumTensors=Infinity);const p=a.join(",")+"|"+t.names().join(",");let u,h;if(wb[p]==null){const m=zW(o,t);u=m.sorted,h=m.recipientCounts,wb[p]=u,JT[p]=h}u=wb[p],h={},i||Object.assign(h,JT[p]);const d=new Vi(t);for(let m=0;m<u.length;++m){if(n!=null){const D=Ya().numTensors;D>n.maxNumTensors&&(n.maxNumTensors=D),D<n.minNumTensors&&(n.minNumTensors=D)}const f=u[m],g=f.sourceLayer;if(g instanceof ji)continue;const y=[],w=[],x=[];let T=!1;for(const D of f.inputs){const M=d.getValue(D),P=d.getMask(D);y.push(M),w.push(P),P!=null&&(T=!0),i||(h[D.name]--,h[D.name]===0&&!t.hasKey(D)&&a.indexOf(D.name)===-1&&!M.isDisposed&&D.sourceLayer.stateful!==!0&&x.push(M))}T&&(s=s||{},s.mask=w[0]);const A=qe(g.apply(y,s));let _=null;g.supportsMasking&&(_=g.computeMask(y,w));const E=PW(f),F=Array.isArray(E)?E:[E];for(let D=0;D<F.length;++D){d.hasKey(F[D])||d.add(F[D],A[D],Array.isArray(_)?_[0]:_);const M=a.indexOf(F[D].name);M!==-1&&(l[M]=A[D])}i||ce(x)}return d.disposeMasks(),r?l:l[0]}function zW(e,t){N.assert(e!=null&&e.length>0,()=>"Expected at least one fetch, got none");let s=[],n={};if(e.length===1){const i=ZT(e[0],t);s=i.sorted,n=i.recipientMap}else{const i=new Set;for(const r of e){const{sorted:o,recipientMap:a}=ZT(r,t);for(const l of o)i.has(l.name)||(s.push(l),i.add(l.name));for(const l in a)n[l]==null&&(n[l]=new Set),a[l].forEach(c=>n[l].add(c))}}return{sorted:s,recipientCounts:BW(n)}}function BW(e){const t={};for(const s in e)t[s]=e[s].size;return t}function ZT(e,t){const s=new Set,n=[],i={};for(const a of t.names())s.add(a);const r=[],o=[];for(r.push(e);r.length>0;){const a=r[r.length-1];if(s.has(a.name)){r.pop();continue}const l=o[o.length-1]===r.length-1;if(a.inputs.length===0||l)r.pop(),n.push(a),s.add(a.name),l&&o.pop();else{o.push(r.length-1);for(const c of a.inputs){if(i[c.name]==null&&(i[c.name]=new Set),i[c.name].add(a.name),s.has(c.name))continue;r.push(c)}}}return{sorted:n,recipientMap:i}}function PW(e){let t;if(e.sourceLayer.inboundNodes.length===1)t=e.sourceLayer.output;else{let s=null;for(let n=0;n<e.sourceLayer.inboundNodes.length;++n)for(const i of e.sourceLayer.inboundNodes[n].outputTensors)if(i.id===e.id){s=n;break}t=e.sourceLayer.getOutputAt(s)}return t}class $n extends Le{constructor(e){super({});if(this.containerNodes=new Set,this.name=e.name,this.name==null){const y=this.getClassName().toLowerCase();this.name=Qr(y)}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],Sn(this.inputs).length!==this.inputs.length)throw new k(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(y=>y.name)}`);Sn(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(y=>y.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(const y of this.outputs){const w=y.sourceLayer,x=y.nodeIndex,T=y.tensorIndex;this.outputLayers.push(w),this.outputLayersNodeIndices.push(x),this.outputLayersTensorIndices.push(T)}for(const y of this.inputs){const w=y.sourceLayer,x=y.nodeIndex,T=y.tensorIndex;Qs(x===0,"input layer has >1 nodes"),Qs(T===0,"input layer has >1 tensors"),this.inputLayers.push(w),this.inputLayersNodeIndices.push(x),this.inputLayersTensorIndices.push(T)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let y=0;y<this.inputLayers.length;y++){const w=this.inputLayers[y];if(!(w instanceof ji))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${y} (0-based) originates from layer type ${w.getClassName()}.`);this.inputNames.push(w.name),this.feedInputShapes.push(w.batchInputShape),this.feedInputNames.push(w.name)}for(const y of this.outputLayers)this.outputNames.push(y.name);this.internalInputShapes=this.inputs.map(y=>y.shape),this.internalOutputShapes=this.outputs.map(y=>y.shape);const t={},s={},n={},i={},r={},o=[],a=(y,w,x,T,A,_)=>{(T==null||A==null||_==null)&&(T=y.sourceLayer,A=y.nodeIndex,_=y.tensorIndex);const E=T.inboundNodes[A];if(x.indexOf(E)!==-1)throw new Ts(`The tensor ${y.name} at layer "${T.name}" is part of a cycle.`);if(w.indexOf(E)!==-1)return;this.containerNodes.add($n.nodeKey(T,A)),T.id in r||(r[T.id]=Object.keys(r).length),x.indexOf(E)===-1&&x.push(E);const F=E.inboundLayers.length;for(let D=0;D<F;D++){const M=E.inputTensors[D],P=E.inboundLayers[D],B=E.nodeIndices[D],Y=E.tensorIndices[D];a(M,w,x,P,B,Y)}for(w.push(E);x.indexOf(E)>=0;)x.splice(x.indexOf(E),1);o.push(E)},l=[],c=[];for(const y of this.outputs)a(y,l,c);const p=o.slice().reverse();for(const y of p){s[y.id]=y,y.id in t||(t[y.id]=0);let w=t[y.id];const x=n[y.outboundLayer.id]==null?0:n[y.outboundLayer.id];w=Math.max(w,x),n[y.outboundLayer.id]=w,i[y.outboundLayer.id]=y.outboundLayer,t[y.id]=w;for(let T=0;T<y.inboundLayers.length;T++){const A=y.inboundLayers[T],_=y.nodeIndices[T],E=A.inboundNodes[_],F=t[E.id]==null?0:t[E.id];t[E.id]=Math.max(w+1,F),s[E.id]=E}}const u={};for(const y in t){const w=t[y];w in u||(u[w]=[]),u[w].push(s[y])}const h={};for(const y in n){const w=n[y];w in h||(h[w]=[]),h[w].push(i[y])}let d=Object.keys(h).map(y=>parseInt(y,10)).sort(Dp);this.layers=[];for(const y of d){const w=h[y];w.sort((x,T)=>{const A=r[x.id],_=r[T.id];return A<_?-1:A>_?1:0});for(const x of w)x instanceof $n&&this.internalContainerRefs.push(x),this.layers.push(x)}this.layersByDepth=h,d=Object.keys(u).map(y=>parseInt(y,10)).sort(Dp);const m=this.inputs.slice(),f=[];for(const y of d)for(const w of u[y]){const x=w.outboundLayer;if(x!=null){for(const T of w.inputTensors)if(m.indexOf(T)===-1)throw new Ts(`Graph disconnected: cannot obtain value for tensor ${T} at layer "${x.name}". The following previous layers were accessed without issue: ${f}`);for(const T of w.outputTensors)m.push(T);f.push(x.name)}}this.nodesByDepth=u;const g=this.layers.map(y=>y.name);for(const y of g){const w=g.filter(x=>x===y).length;if(w!==1)throw new Ts(`The name "${y}" is used ${w} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new sa({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(y=>null),outputMasks:this.outputs.map(y=>null),inputShapes:this.inputs.map(y=>y.shape),outputShapes:this.outputs.map(y=>y.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(s=>s.trainable=e)}),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new k("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 s of this.layers)t.push(...s.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){const s={};let n=0;for(const r of this.layers)for(const o of r.weights){if(s[o.originalName]!=null)throw new k(`Duplicate weight name: ${o.originalName}`);s[o.originalName]=o,n++}const i=[];for(const r in e){let o=r;if(s[r]==null){const a=r.split("/"),l=a.slice(0,-2).concat([a[a.length-1]]);o=l.join("/")}if(s[o]!=null)i.push([s[o],e[r]]);else if(t)throw new k(`Provided weight data has no target variable: ${r}`);delete s[o]}if(t){const r=[];for(const o in s)r.push(o);if(r.length>0)throw new k(`${r.length} of ${n} weights are not set: ${r}`)}Nl(i)}updatedConfig(){const e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${to}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){const s=Od(this.updatedConfig());return t?JSON.stringify(s):s}call(e,t){return C(()=>{e=qe(e);const s=new Vi;for(let n=0;n<this.inputs.length;++n)s.add(this.inputs[n],e[n]);return oa(this.outputs,s,t)})}computeMask(e,t){return C(()=>{e=qe(e);let s;return t==null?s=wn(null,e.length):s=qe(t),this.runInternalGraph(e,s)[1]})}computeOutputShape(e){const t=Tl(e);if(t.length!==this.inputLayers.length)throw new k(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);const s={};for(let o=0;o<t.length;o++){const a=this.inputLayers[o],l=t[o],c=a.name+"_0_0";s[c]=l}const n=Object.keys(this.nodesByDepth).map(o=>parseInt(o,10)).sort(Dp);if(n.length>1)for(const o of n){const a=this.nodesByDepth[o];for(const l of a){const c=l.outboundLayer;if(this.inputLayers.map(m=>m.id).indexOf(c.id)!==-1)continue;const p=[];for(let m=0;m<l.inboundLayers.length;m++){const f=l.inboundLayers[m],g=l.nodeIndices[m],y=l.tensorIndices[m],w=`${f.name}_${g}_${y}`,x=s[w];p.push(x)}const u=c.computeOutputShape(jt(p)),h=Tl(u),d=c.inboundNodes.indexOf(l);for(let m=0;m<h.length;m++){const f=`${c.name}_${d}_${m}`;s[f]=h[m]}}}const i=[],r=[];for(let o=0;o<this.outputLayers.length;o++){const a=this.outputLayers[o],l=this.outputLayersNodeIndices[o],c=this.outputLayersTensorIndices[o],p=`${a.name}_${l}_${c}`;r.push(p)}for(let o=0;o<r.length;o++){const a=r[o];Qs(a in s),i.push(s[a])}return jt(i)}runInternalGraph(e,t){t==null&&(t=wn(null,e.length));const s={};for(let a=0;a<this.inputs.length;++a){const l=this.inputs[a],c=e[a],p=t[a];s[l.id]=[c,p]}const n=Object.keys(this.nodesByDepth).map(a=>parseInt(a,10)).sort(Dp);for(const a of n){const l=this.nodesByDepth[a];for(const c of l){const p=c.outboundLayer,u=c.inputTensors,h=c.outputTensors,d=new Array;for(const m of u)m.id in s&&d.push(s[m.id]);if(d.length===u.length){let m={},f,g,y,w;if(c.callArgs!=null&&(m=c.callArgs),d.length===1){const[x,T]=d[0];m.mask==null&&(m.mask=T),y=qe(p.call(x,m)),w=qe(p.computeMask(x,T)),f=[x],g=[T]}else f=d.map(x=>x[0]),g=d.map(x=>x[1]),m.mask==null&&(m.mask=g),y=qe(p.call(f,m)),w=qe(p.computeMask(f,g));if(p.activityRegularizer)throw new ae("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let x=0;x<h.length;++x){const T=h[x],A=y[x],_=w[x];s[T.id]=[A,_]}}}}const i=[],r=[],o=[];for(const a of this.outputs){Qs(a.id in s,`Could not compute output ${a.name} : ${a.id}`);const[l,c]=s[a.id];o.push(l.shape),i.push(l),r.push(c)}return[i,r,o]}buildNodeConversionMap(e){const t={};let s;for(const n of this.layers){s=n instanceof $n?1:0;for(let i=0;i<n.inboundNodes.length;i++){const r=$n.nodeKey(n,i);this.containerNodes.has(r)&&(t[r]=s,s+=1)}}return t}getLayer(e,t){if(t!=null){if(this.layers.length<=t)throw new k(`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 k("Provide either a layer name or layer index");for(const s of this.layers)if(s.name===e)return s;throw new k(`No such layer: ${e}`)}calculateLosses(){return C(()=>{const e=[];for(const t of this.layers)for(let s=0;s<t.inboundNodes.length;++s){const n=$n.nodeKey(t,s);this.containerNodes.has(n)&&e.push(...t.calculateLosses())}return e})}getConfig(){const e={name:this.name},t=this.buildNodeConversionMap(this.layers),s=[];for(const r of this.layers){const o=r.getClassName(),a=r.getConfig(),l=[];for(let p=0;p<r.inboundNodes.length;p++){const u=r.inboundNodes[p],h=$n.nodeKey(r,p);let d={};if(this.containerNodes.has(h)){if(u.callArgs)try{JSON.stringify(u.callArgs),d=u.callArgs}catch(m){console.warn(`Layer ${r.name} was passed non-serializable keyword arguments: ${u.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),d={}}if(u.inboundLayers.length>0){const m=[];for(let f=0;f<u.inboundLayers.length;f++){const g=u.inboundLayers[f],y=u.nodeIndices[f],w=u.tensorIndices[f],x=$n.nodeKey(g,y);let T=t[x];T==null&&(T=0),m.push([g.name,T,w,d])}l.push(m)}}}const c={};c.name=r.name,c.className=o,c.config=a,c.inboundNodes=l,s.push(c)}e.layers=s;const n=[];for(let r=0;r<this.inputLayers.length;r++){const o=this.inputLayers[r],a=this.inputLayersNodeIndices[r],l=$n.nodeKey(o,a);if(!this.containerNodes.has(l))continue;let c=t[l];c==null&&(c=0);const p=this.inputLayersTensorIndices[r];n.push([o.name,c,p])}e.inputLayers=n;const i=[];for(let r=0;r<this.outputLayers.length;r++){const o=this.outputLayers[r],a=this.outputLayersNodeIndices[r],l=$n.nodeKey(o,a);if(!this.containerNodes.has(l))continue;let c=t[l];c==null&&(c=0);const p=this.outputLayersTensorIndices[r];i.push([o.name,c,p])}return e.outputLayers=i,e}static fromConfig(e,t,s={},n=!1){const i={},r={};function o(f,g){f.name in r?r[f.name].push(g):r[f.name]=[g]}function a(f,g){const y=[];let w;for(const x of g){const T=x[0],A=x[1],_=x[2];if(w=x[3]==null?{}:x[3],!(T in i)){o(f,g);return}const E=i[T];if(E.inboundNodes.length<=A){o(f,g);return}const F=E.inboundNodes[A];y.push(F.outputTensors[_])}y.length>0&&f.apply(jt(y),w)}function l(f){const g=f.name,y=xs(f,t.customObjects!=null?t.customObjects:{});y.setFastWeightInitDuringBuild(n),i[g]=y;const w=f.inboundNodes;w.forEach(x=>{if(!(x instanceof Array))throw new k(`Corrupted configuration, expected array for nodeData: ${x}`);o(y,x)})}const c=t.name,p=t.layers;for(const f of p)l(f);for(;!wT(r);)for(const f of p){const g=i[f.name];if(g.name in r){const y=r[g.name];delete r[g.name];for(const w of y)a(g,w)}}const u=[],h=[],d=t.inputLayers;for(const f of d){const g=f[0],y=f[1],w=f[2];Qs(g in i);const x=i[g],T=x.inboundNodes[y].outputTensors;u.push(T[w])}const m=t.outputLayers;for(const f of m){const g=f[0],y=f[1],w=f[2];Qs(g in i);const x=i[g],T=x.inboundNodes[y].outputTensors;h.push(T[w])}return new e({inputs:u,outputs:h,name:c})}get stateful(){if(this._stateful)throw new k("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(){C(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}}function jW(e,t,s){const n=t.length;if(e==null||Array.isArray(e)&&e.length===0)return t.map(i=>null);if(n===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!==n)throw new Error(`Provided ${s} is an array of ${e.length} element(s), but the model has ${n} 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(r=>{r in e?i.push(e[r]):i.push(null)}),i}else throw new Error(`The model has multiple (${n}) outputs, so ${s} must be either an array with ${n} elements or an object with ${t} keys. Provided ${s} not understood: ${JSON.stringify(e)}`)}function Ed(e,t){return jW(e,t,"classWeight")}async function _d(e,t,s,n){if(t!=null||n!=null)throw new Error("Support sampleWeight is not implemented yet");if(s!=null){const i=C(()=>{if(e.shape.length===1)return e.clone();if(e.shape.length===2)if(e.shape[1]>1){const a=1;return e.argMax(a)}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.`)}),r=Array.from(await i.data());ce(i);const o=[];return r.forEach(a=>{if(s[a]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${a} exists in the data but not in classWeight`);o.push(s[a])}),Oe(o,"float32")}else return null}function QT(e,t){return R(e,t)}const VW=32;function tA(e,t){let s,n;const i=t;s=i.xs,n=i.ys,N.assert(s!=null&&n!=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 r=eA("input",e.inputNames,s),o=eA("output",e.outputNames,n),a=r[0].shape[0];N.assert(r.length===e.inputs.length,()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${r.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`),N.assert(o.length===e.outputs.length,()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${o.length} outputs. (Expected output keys: ${JSON.stringify(e.outputNames)})`);for(let l=0;l<r.length;l++)N.assert(r[l].shape[0]===a,()=>`Batch size mismatch: input ${e.inputNames[l]} has ${r[l].shape[0]}; expected ${a} based on input ${e.inputNames[0]}.`);for(let l=0;l<o.length;l++)N.assert(o[l].shape[0]===a,()=>`Batch size mismatch: output ${e.outputNames[l]} has ${o[l].shape[0]}; expected ${a} based on input ${e.inputNames[0]}.`);return{xs:r,ys:o}}function eA(e,t,s){if(s instanceof me)return[s];if(Array.isArray(s))return N.assert(s.length===t.length,()=>`Received an array of ${s.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`),s;{const n=[];for(const i of t){if(s[i]==null)throw new k(`The feature data generated by the dataset lacks the required ${e} key '${i}'.`);n.push(s[i])}return n}}function GW(e){if(e.length===3)throw new ae("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}async function nA(e,t,s){const n=s.batchesPerEpoch!=null;if(N.assert(e.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),N.assert(s!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),N.assert(s.epochs!=null&&s.epochs>0&&Number.isInteger(s.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${s.epochs}`),N.assert(!n||s.batchesPerEpoch>0&&Number.isInteger(s.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${s.batchesPerEpoch}`),N.assert(s.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=s.validationData!=null;let r,o;if(i)if(sA(s.validationData))N.assert(s.validationBatches==null||s.validationBatches>0&&Number.isInteger(s.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${s.validationBatches}`);else{const g=GW(s.validationData);r=g.xs,o=g.ys}const a=e.makeTrainFunction(),l=e.getDedupedMetricsNames();let c;i?c=l.slice().concat(l.map(g=>"val_"+g)):c=l.slice();const p=Id(s.callbacks,s.yieldEvery),u=s.verbose==null?1:s.verbose,{callbackList:h,history:d}=vd(p,u,s.epochs,null,null,qW(t,s),null,i,c);h.setModel(e),e.history=d,await h.onTrainBegin(),e.stopTraining_=!1;let m=s.initialEpoch==null?0:s.initialEpoch,f=await t.iterator();for(;m<s.epochs;){const g={};await h.onEpochBegin(m);let y=0,w=0;for(n||(f=await t.iterator());n?y<s.batchesPerEpoch:!0;){const x=await f.next();if(n&&x.done){console.warn(`You provided \`batchesPerEpoch\` as ${s.batchesPerEpoch}, but your dataset iterator ran out of data after ${y} batches; interrupting training. Make sure that your dataset can generate at least \`batchesPerEpoch * epochs\` batches (in this case, ${s.batchesPerEpoch*s.epochs} batches). You may need to use the repeat() function when building your dataset.`);break}if(x.value!=null){const{xs:T,ys:A}=tA(e,x.value),_={};_.batch=w,_.size=T[0].shape[0],await h.onBatchBegin(w,_);const E=[];if(s.classWeight!=null){const M=Ed(s.classWeight,e.outputNames);for(let P=0;P<M.length;++P)E.push(await _d(A[P],null,M[P]))}const F=T.concat(A).concat(E),D=a(F);ce(F);for(let M=0;M<l.length;++M){const P=l[M],B=D[M];_[P]=B,pt(B)}await h.onBatchEnd(w,_),Sd(_),w++,y++}if(n?y>=s.batchesPerEpoch:x.done){if(i){let T;sA(s.validationData)?T=qe(await e.evaluateDataset(s.validationData,{batches:s.validationBatches})):T=qe(e.evaluate(r,o,{batchSize:s.validationBatchSize==null?VW:s.validationBatchSize,verbose:0}));for(let A=0;A<e.metricsNames.length;++A)g[`val_${e.metricsNames[A]}`]=T[A]}break}if(e.stopTraining_)break}if(await h.onEpochEnd(m,g),m++,e.stopTraining_)break}return await h.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}function qW(e,t){let s=null;return t.batchesPerEpoch!=null?s=t.batchesPerEpoch:Number.isFinite(e.size)&&(s=e.size),s}function sA(e){return typeof e.iterator=="function"}function HW(e){return typeof e.next=="function"}async function iA(e,t,s){s=s||{};const n=s.batches!=null,i=e.testFunction;let r=[];if(s.verbose>0)throw new ae("Verbose mode is not implemented yet.");N.assert(!n||s.batches>0&&Number.isInteger(s.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(s.batches)}`);const o=HW(t)?t:await t.iterator();let a=0,l=0;for(;n?l<s.batches:!0;){const c=await o.next();if(r=C(()=>{if(c.value){const{xs:p,ys:u}=tA(e,c.value),h=p.concat(u),d=C(()=>i(h));if(ce(h),l===0)for(let f=0;f<d.length;++f)r.push(j(0));const m=h[0].shape[0];for(let f=0;f<d.length;++f){const g=d[f],y=r[f];r[f]=C(()=>$(r[f],R(m,g))),l>0&&ce(y)}ce(d),a+=m,++l}return r}),c.done){n&&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, ${s.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let c=0;c<r.length;++c){const p=r[c];r[c]=Z(r[c],a),ce(p)}return jt(r)}function kd(e){N.assert(e>0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function El(e,t,s){return e==null?[null]:Array.isArray(e)?e.map(n=>Bi(n,t,s-t)):Bi(e,t,s-t)}function Dd(e,t){return C(()=>e==null?null:Array.isArray(e)?e.map(s=>Dd(s,t)):ld(e,t.dtype==="int32"?t:t.toInt()))}function Fd(e,t){const s=[];let n=0,i=null;for(;n<e;)i=n+t,i>=e&&(i=e),s.push([n,i]),n=i;return s}async function YW(e,t,s,n,i,r,o,a,l,c,p,u,h,d,m){i==null&&(i=32),r==null&&(r=1),p==null&&(p=!0),h==null&&(h=0);let f=!1;if(l!=null&&c!=null&&(f=!0),m!=null&&(f=!0,d==null))throw new k("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");const g=e.checkNumSamples(s,i,d,"steps_per_epoch");let y;g!=null&&(y=ls(0,g)),o==null&&(o=1);const{callbackList:w,history:x}=vd(a,o,r,h,g,d,i,f,u);w.setModel(e),e.history=x,await w.onTrainBegin(),e.stopTraining_=!1;for(let T=h;T<r;++T){await w.onEpochBegin(T);const A={};if(d!=null)throw new ae("stepsPerEpoch mode is not implemented yet.");{if(p==="batch")throw new ae("batch shuffling is not implemneted yet");p&&N.shuffle(y);const _=Oe(y),E=Fd(g,i);for(let F=0;F<E.length;++F){const D={};if(await w.onBatchBegin(F,D),C(()=>{const M=E[F][0],P=E[F][1],B=Bi(_,M,P-M);D.batch=F,D.size=P-M;const Y=Dd(s,B),q=t(Y);for(let K=0;K<n.length;++K){const H=n[K],Q=q[K];D[H]=Q,pt(Q)}if(F===E.length-1&&f){const K=e.testLoop(l,c,i);for(let H=0;H<n.length;++H){const Q=n[H],J=K[H];pt(J),A["val_"+Q]=J}}}),await w.onBatchEnd(F,D),Sd(D),e.stopTraining_)break}_.dispose()}if(await w.onEpochEnd(T,A),e.stopTraining_)break}return await w.onTrainEnd(),await e.history.syncData(),e.history}async function rA(e,t,s,n={}){if(e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;let i,r,o,a,l,c,p;try{const u=n.batchSize==null?32:n.batchSize;kd(u);const h=!1,d=await e.standardizeUserData(t,s,n.sampleWeight,n.classWeight,h,u);i=d[0],r=d[1],p=d[2];let m=!1,f;if(n.validationData!=null&&n.validationData.length>0){if(m=!0,n.validationData.length===2)o=n.validationData[0],a=n.validationData[1];else throw n.validationData.length===3?new ae("validationData including sample weights is not supported yet."):new k(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${n.validationData} is invalid.`);const E=!0,F=await e.standardizeUserData(o,a,null,null,E,u);l=F[0],c=F[1],f=l.concat(c)}else if(n.validationSplit!=null&&n.validationSplit>0&&n.validationSplit<1){m=!0;const E=Math.floor(i[0].shape[0]*(1-n.validationSplit)),F=i[0].shape[0];l=El(i,E,F),i=El(i,0,E),c=El(r,E,F),r=El(r,0,E),f=l.concat(c)}else n.validationSteps!=null&&(m=!0);const g=i.concat(r).concat(p);e.checkTrainableWeightsConsistency();const y=e.makeTrainFunction(),w=e.getDedupedMetricsNames();let x,T;m?(e.makeTestFunction(),x=e.testFunction,T=w.slice().concat(w.map(E=>"val_"+E))):(x=null,f=[],T=w.slice());const A=Id(n.callbacks,n.yieldEvery),_=await YW(e,y,g,w,u,n.epochs,n.verbose,A,x,f,n.shuffle,T,n.initialEpoch,null,null);return _}finally{e.isTraining=!1,so(i,t),so(r,s),so(l,o),so(c,a),p!=null&&ce(p)}}function xb(e){const t=[];e instanceof me&&(e=[e]);for(let s=0;s<e.length;++s){const n=e[s];if(n.rank===1)t.push(Pi(n,1));else{if(n.rank===0)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(n)}}return t}function so(e,t){if(e==null)return;const s=[];if(t instanceof me)s.push(t.id);else if(Array.isArray(t))t.forEach(i=>s.push(i.id));else if(t!=null)for(const i in t){const r=t[i];s.push(r.id)}const n=[];if(e instanceof me)s.indexOf(e.id)===-1&&n.push(e);else if(Array.isArray(e))e.forEach(i=>{s.indexOf(i.id)===-1&&n.push(i)});else if(e!=null)for(const i in e){const r=e[i];s.indexOf(r.id)===-1&&n.push(r)}n.forEach(i=>{i.isDisposed||i.dispose()})}function KW(e){return e instanceof me}function Lb(e){return Array.isArray(e)}function oA(e){return!KW(e)&&!Lb(e)}function aA(e,t,s,n=!0,i=""){if(t==null||t.length===0){if(e!=null){let o=!1;if(Lb(e)&&e.length>0)o=!0;else if(oA(e)){for(const a in e)if(e.hasOwnProperty(a)){o=!0;break}}else o=!0;if(o)throw new k(`Error when checking model ${i} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(o=>null);let r;if(oA(e)){e=e,r=[];for(const o of t){if(e[o]==null)throw new k(`No data provided for "${o}". Need data for each key in: ${t}`);r.push(e[o])}}else if(Lb(e)){if(e=e,e.length!==t.length)throw new k(`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}`);r=e}else{if(e=e,t.length>1)throw new k(`The model ${i} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);r=[e]}if(r=xb(r),s!=null)for(let o=0;o<t.length;++o){if(s[o]==null)continue;const a=r[o];if(a.shape.length!==s[o].length)throw new k(`Error when checking ${i}: expected ${t[o]} to have ${s[o].length} dimension(s). but got array with shape ${a.shape}`);for(let l=0;l<s[o].length;++l){if(l===0&&!n)continue;const c=a.shape[l],p=s[o][l];if(p!=null&&p>=0&&c!==p)throw new k(`Error when checking ${i}: expected ${t[o]} to have shape [${s[o]}], but got array with shape [${a.shape}].`)}}return r}function XW(e,t,s){const n=Sn(e.map(r=>r.shape[0]));n.sort();const i=Sn(t.map(r=>r.shape[0]));if(i.sort(),n.length>1)throw new k(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(r=>r.shape))}`);if(i.length>1)throw new k(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(r=>r.shape))}`);if(n.length>0&&i.length>0&&!N.arraysEqual(n,i))throw new k(`Input Tensors should have the same number of samples as target Tensors. Found ${n[0]} input sample(s) and ${i[0]} target sample(s).`)}function JW(e,t,s){const n=[mi,Ol,ia];for(let i=0;i<e.length;++i){const r=e[i],o=t[i],a=s[i];if(o==null)continue;if(o===ia&&r.shape[r.shape.length-1]===1)throw new k(`You are passing a target array of shape ${r.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(n.indexOf(o)!==-1){const l=r.shape.slice(1),c=a.slice(1);for(let p=0;p<l.length;++p){const u=l[p],h=c[p];if(h!=null&&u!==h)throw new k(`A target Tensor with shape ${r.shape} was passed for an output of shape ${a}, while using a loss function that expects targets to have the same shape as the output.`)}}}}function lA(e,t,s,n=!0,i=""){let r;if(Array.isArray(e)){if(e.length!==t.length)throw new k(`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).`);r=e}else{if(t.length>1)throw new k(`The model expects ${t.length} ${i} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);r=[e]}if(s!=null)for(let o=0;o<t.length;++o){if(s[o]==null)continue;const a=r[o];if(a.shape.length!==s[o].length)throw new k(`Error when checking ${i}: expected ${t[o]} to have ${s[o].length} dimension(s), but got array with shape ${JSON.stringify(a.shape)}`);for(let l=0;l<s[o].length;++l){if(l===0&&!n)continue;const c=a.shape[l],p=s[o][l];if(p!=null&&p!==c)throw new k(`Error when checking ${i}: expected ${t[o]} to have shape ${JSON.stringify(s[o])} but got array with shape ${JSON.stringify(a.shape)}.`)}}}function ZW(e,t){if(e==null||Array.isArray(e)&&e.length===0)return t.map(n=>[]);let s;if(typeof e=="string"||typeof e=="function")s=[e];else if(Array.isArray(e)||typeof e=="object")s=e;else throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);if(Array.isArray(s))return t.map(n=>s);{const n=[];for(const i of t){let r=s.hasOwnProperty(i)?s[i]:[];Array.isArray(r)||(r=[r]),n.push(r)}return n}}const QW="layers-model";class tn extends $n{constructor(e){super(e);this.isTraining=!1}summary(e,t,s=console.log){if(!this.built)throw new k("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).");KT(this,e,t,s)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=HT(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof fs))throw new k("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 r in e.loss)if(this.outputNames.indexOf(r)===-1)throw new k(`Unknown entry in loss dictionary: "${r}". Only expected the following keys: ${this.outputNames}`);for(const r of this.outputNames)e.loss[r]==null&&console.warn(`Output "${r}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${r} during training`),t.push(Td(e.loss[r]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new k(`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 r=e.loss;t=r.map(o=>Td(o))}else{const r=Td(e.loss);this.outputs.forEach(o=>{t.push(r)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let r=0;r<this.outputs.length;++r){const o=this.internalOutputShapes[r],a=this.outputNames[r];this.feedOutputNames.push(a),this.feedOutputShapes.push(o),this.feedLossFns.push(this.lossFunctions[r])}const s=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],Mn("loss",()=>{for(let r=0;r<this.outputs.length;++r){if(s.indexOf(r)!==-1)continue;const o=this.lossFunctions[r];this.outputs.length>1&&(this.metricsTensors.push([o,r]),this.metricsNames.push(this.outputNames[r]+"_loss"))}});const n=ZW(e.metrics,this.outputNames),i=(r,o,a)=>{this.outputNames.length>1&&(o=this.outputNames[r]+"_"+o),this.metricsNames.push(o),this.metricsTensors.push([a,r])};Mn("metric",()=>{for(let r=0;r<this.outputs.length;++r){if(s.indexOf(r)!==-1)continue;const o=n[r],a=l=>{const c="";let p,u,h;for(const d of l){if(typeof d=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(d)!==-1){const f=this.internalOutputShapes[r];f[f.length-1]===1||this.lossFunctions[r]===Ol?["accuracy","acc"].indexOf(d)!==-1?u=Yp:["crossentropy","ce"].indexOf(d)!==-1&&(u=Ad):this.lossFunctions[r]===Rl?["accuracy","acc"].indexOf(d)!==-1?u=Nd:["crossentropy","ce"].indexOf(d)!==-1&&(u=gb):["accuracy","acc"].indexOf(d)!==-1?u=Kp:["crossentropy","ce"].indexOf(d)!==-1&&(u=Xp);let g;["accuracy","acc"].indexOf(d)!==-1?g="acc":["crossentropy","ce"].indexOf(d)!==-1&&(g="ce"),h=u,p=c+g}else{const f=qT(d);h=f,p=c+Jp(d)}let m;Mn(p,()=>{m=h}),i(r,p,m)}};a(o)}}),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,s={}){const n=s.batchSize==null?32:s.batchSize;kd(n);const i=!0,r=this.standardizeUserDataXY(e,t,i,n);try{const o=r[0].concat(r[1]);this.makeTestFunction();const a=this.testFunction,l=this.testLoop(a,o,n,s.verbose,s.steps);return jt(l)}finally{so(r[0],e),so(r[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),iA(this,e,t)}checkNumSamples(e,t,s,n="steps"){let i;if(s!=null){if(i=null,t!=null)throw new k(`If ${n} 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 k(`Either the input data should have a defined shape, or ${n} shoud be specified.`);return i}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new k("`outputs` is an empty Array, which is not allowed.");const s=Array.isArray(t),n=s?t:[t],i=this.retrieveSymbolicTensors(n),r=new Vi;if(e instanceof me&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new k(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let a=0;a<this.inputs.length;++a)r.add(this.inputs[a],e[a])}else for(const a of this.inputs){const l=e[a.name];if(l==null)throw new k(`No value is provided for the model's input ${a.name}`);r.add(a,l)}const o=oa(i,r);return s?o:o[0]}retrieveSymbolicTensors(e){const t=wn(null,e.length);let s=e.length;for(const n of this.layers){const i=Array.isArray(n.output)?n.output:[n.output],r=i.map(o=>o.name);for(let o=0;o<e.length;++o){const a=r.indexOf(e[o]);if(a!==-1&&(t[o]=i[a],s--),s===0)break}if(s===0)break}if(s>0){const n=[];throw t.forEach((i,r)=>{i==null&&n.push(e[r])}),new k(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(n)}`)}return t}predictLoop(e,t=32,s=!1){return C(()=>{const n=this.checkNumSamples(e);if(s)throw new ae("Verbose predictLoop() is not implemented yet.");const i=Fd(n,t),r=this.outputs.map(o=>[]);for(let o=0;o<i.length;++o){const a=C(()=>{const l=i[o][0],c=i[o][1],p=El(e,l,c),u=[];if(Array.isArray(p))for(let d=0;d<p.length;++d)u.push({key:this.inputs[d],value:p[d]});else u.push({key:this.inputs[0],value:p});const h=new Vi(u);return oa(this.outputs,h)});a.forEach((l,c)=>r[c].push(l))}return jt(r.map(o=>be(o,0)))})}predict(e,t={}){const s=xb(e);lA(s,this.inputNames,this.feedInputShapes,!1);try{const n=t.batchSize==null?32:t.batchSize;return kd(n),this.predictLoop(s,n)}finally{so(s,e)}}predictOnBatch(e){lA(e,this.inputNames,this.feedInputShapes,!0);const t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,s=!0,n){if(this.optimizer_==null)throw new Ts("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");const i=[];for(let r=0;r<this.feedOutputShapes.length;++r){const o=this.feedOutputShapes[r],a=this.feedLossFns[r];a===Rl?i.push(o.slice(0,o.length-1).concat([1])):i.push(o)}if(e=aA(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=aA(t,this.feedOutputNames,i,!1,"target"),XW(e,t,null),JW(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&n!=null&&n>0&&e[0].shape[0]%n!==0)throw new k(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${n}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,s,n,i=!0,r){const[o,a]=this.standardizeUserDataXY(e,t,i,r);if(s!=null)throw new Error("sample weight is not supported yet.");let l=null;if(n!=null){const c=Ed(n,this.outputNames);l=[];for(let p=0;p<c.length;++p)l.push(await _d(a[p],null,c[p]))}return[o,a,l]}testLoop(e,t,s,n=0,i){return C(()=>{const r=this.checkNumSamples(t,s,i,"steps"),o=[];if(n>0)throw new ae("Verbose mode is not implemented yet.");if(i!=null)throw new ae("steps mode in testLoop() is not implemented yet");{const a=Fd(r,s),l=Oe(ls(0,r));for(let c=0;c<a.length;++c){const p=a[c][0],u=a[c][1],h=Bi(l,p,u-p),d=Dd(t,h),m=e(d);if(c===0)for(let f=0;f<m.length;++f)o.push(j(0));for(let f=0;f<m.length;++f){const g=m[f];o[f]=$(o[f],R(u-p,g))}}for(let c=0;c<o.length;++c)o[c]=Z(o[c],r)}return o})}getDedupedMetricsNames(){const e=this.metricsNames,t=[];for(let s=0;s<e.length;++s){const n=e[s];let i=n;if(sb(e,n)>1){const r=sb(e.slice(0,s),n);i+=`_${r}`}t.push(i)}return t}makeTrainFunction(){return e=>{const t=[],s=e.slice(0,this.inputs.length),n=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),r=[],o=()=>{const p=[];for(let m=0;m<this.inputs.length;++m)p.push({key:this.inputs[m],value:s[m]});const u=new Vi(p),h=oa(this.outputs,u,{training:!0});let d;for(let m=0;m<this.lossFunctions.length;++m){const f=this.lossFunctions[m];let g=f(n[m],h[m]);i[m]!=null&&(g=QT(g,i[m]));const y=Ke(g);t.push(y),m===0?d=g:d=$(d,g)}for(let m=0;m<this.metricsTensors.length;++m){let f;if(this.outputs.length>1&&m<this.outputs.length)f=t[m];else{const g=this.metricsTensors[m][0],y=this.metricsTensors[m][1];f=Ke(g(n[y],h[y]))}pt(f),r.push(f)}return d=Ke(d),this.calculateLosses().forEach(m=>{d=$(d,m)}),d},a=this.collectedTrainableWeights.map(p=>p.read()),l=!0,c=this.optimizer_.minimize(o,l,a);return[c].concat(r)}}makeTestFunction(){this.testFunction=e=>C(()=>{const t=[];let s;const n=e.slice(0,this.inputs.length),i=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),r=[];for(let l=0;l<this.inputs.length;++l)r.push({key:this.inputs[l],value:n[l]});const o=new Vi(r),a=oa(this.outputs,o);for(let l=0;l<this.lossFunctions.length;++l){const c=this.lossFunctions[l],p=Ke(c(i[l],a[l]));l===0?s=p:s=$(s,p),t.push(s)}for(let l=0;l<this.metricsTensors.length;++l){const c=this.metricsTensors[l][0],p=this.metricsTensors[l][1],u=Ke(c(i[p],a[p]));t.push(u)}return t})}async fit(e,t,s={}){return rA(this,e,t,s)}async fitDataset(e,t){return nA(this,e,t)}async trainOnBatch(e,t){const s=await this.standardizeUserData(e,t),n=s[0],i=s[1],r=this.makeTrainFunction(),o=r(n.concat(i)),a=[];for(const l of o){const c=await l.data();a.push(c[0])}return ce(o),jt(a)}getNamedWeights(e){const t=[],s=e!=null&&e.trainableOnly,n=s?this.trainableWeights:this.weights,i=this.getWeights(s);for(let r=0;r<n.length;++r){if(s&&!n[r].trainable)continue;t.push({name:n[r].originalName,tensor:i[r]})}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=Ya().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-Ya().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=xn(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=>xn(t))}else{const t=Object.keys(this.loss);e={};const s=this.loss;for(const n of t)if(typeof s[n]=="string")e[n]=xn(s[n]);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[xn(Jp(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>xn(Jp(e)));{const e={};for(const t in this.metrics)e[t]=xn(Jp(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=ra(e.optimizer_config),s=xs(t);let n;if(typeof e.loss=="string")n=$i(e.loss);else if(Array.isArray(e.loss))n=e.loss.map(r=>$i(r));else if(e.loss!=null){n={};for(const r in e.loss)n[r]=$i(e.loss[r])}let i;if(Array.isArray(e.metrics))i=e.metrics.map(r=>$i(r));else if(e.metrics!=null){i={};for(const r in e.metrics)i[r]=$i(e.metrics[r])}this.compile({loss:n,metrics:i,optimizer:s})}async save(e,t){if(typeof e=="string"){const l=Rt.getSaveHandlers(e);if(l.length===0)throw new k(`Cannot find any save handlers for URL '${e}'`);if(l.length>1)throw new k(`Found more than one (${l.length}) save handlers for URL '${e}'`);e=l[0]}if(e.save==null)throw new k("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const s=await Rt.encodeWeights(this.getNamedWeights(t)),n=!1,i=null,r=this.toJSON(i,n),o={modelTopology:r,format:QW,generatedBy:`TensorFlow.js tfjs-layers v${to}`,convertedBy:null},a=t==null?!1:t.includeOptimizer;if(a&&this.optimizer!=null){o.trainingConfig=this.getTrainingConfig();const l="optimizer",{data:c,specs:p}=await Rt.encodeWeights(await this.optimizer.getWeights(),l);s.specs.push(...p),s.data=Rt.concatenateArrayBuffers([s.data,c])}if(this.userDefinedMetadata!=null){const l=!0;bb(this.userDefinedMetadata,this.name,l),o.userDefinedMetadata=this.userDefinedMetadata}return o.weightData=s.data,o.weightSpecs=s.specs,e.save(o)}setUserDefinedMetadata(e){bb(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}tn.className="Model";V.registerClass(tn);class cA extends tn{}cA.className="Functional";V.registerClass(cA);async function pA(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let s=e.modelTopology;s.model_config!=null&&(s=s.model_config);const n=ra(s),i=xs(n,t);if(e.weightsManifest!=null){const r=await Rt.loadWeights(e.weightsManifest,e.pathPrefix,i.weights.map(a=>a.originalName)),o={};for(const a of i.weights)o[a.originalName]=r[a.originalName];i.loadWeights(o),ce(r)}return i}async function uA(e,t){if(t==null&&(t={}),typeof e=="string"){const s=Rt.getLoadHandlers(e,t);if(s.length===0)s.push(Rt.browserHTTPRequest(e,t));else if(s.length>1)throw new k(`Found more than one (${s.length}) load handlers for URL '${e}'`);e=s[0]}return ez(e,void 0,t)}async function ez(e,t,s){if(s==null&&(s={}),e.load==null)throw new k("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const n=await e.load();let i=n.modelTopology;i.model_config!=null&&(i=i.model_config);const r=s.strict==null?!0:s.strict,o=n.weightData!=null&&n.weightSpecs!=null&&r,a=xs(ra(i),t,o),l=n.trainingConfig;if(l!=null&&a.loadTrainingConfig(l),n.userDefinedMetadata!=null&&a.setUserDefinedMetadata(n.userDefinedMetadata),n.weightData!=null){if(n.weightSpecs==null)throw new k("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");const{modelWeights:c,optimizerWeights:p}=tz(n.weightData,n.weightSpecs);a.loadWeights(c,r),a.optimizer!=null&&p.length>0&&await a.optimizer.setWeights(p),ce(c),ce(p.map(u=>u.tensor))}return a}function tz(e,t){const s=Rt.decodeWeights(e,t),n={},i=[];return t.forEach(r=>{r.group==="optimizer"?i.push({name:r.name,tensor:s[r.name]}):n[r.name]=s[r.name]}),{modelWeights:n,optimizerWeights:i}}class no extends tn{constructor(e){super({inputs:[],outputs:[]});if(e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:Qr("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(s=>s<0))throw new k(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const t=e instanceof no||e instanceof tn;let s;if(t){if(s=e,s.outputs.length!==1)throw new k("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(s.inputs.length!==1)throw new k("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 k("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const n=Ld({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(n)}if(t)this.outputs=s.outputs,this.inputs=s.inputs;else{if(e.inboundNodes.length!==1)throw new k(`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 k("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=ub(this.outputs[0])}this.inboundNodes=[],new sa({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:wn(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(n=>n.shape),outputShapes:this.outputs[0].shape})}else{const n=e.apply(this.outputs[0]);if(Array.isArray(n))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=[n],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(Ue(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 tn({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,s=console.log){this.built||this.build(),super.summary(e,t,s)}setWeights(e){this.model==null&&this.build(),this.model.setWeights(e)}evaluate(e,t,s={}){if(!this.built)throw new Ts("The model needs to be compiled before being used.");return this.model.evaluate(e,t,s)}async evaluateDataset(e,t){if(!this.built)throw new Ts("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,s={}){if(!this.built)throw new Ts("The model needs to be compiled before being used.");return this.model.fit(e,t,s)}async fitDataset(e,t){if(!this.built)throw new Ts("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,s={},n=!1){let i,r={};if(t instanceof Array){if(!(t[0].className!=null)||t[0].className==="Merge")throw new k("Legacy serialization format not supported yet.");i=t}else N.assert(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,r=t;const o=new e(r);if(!(o instanceof no))throw new ae(`Sequential.fromConfig called on non-Sequential input: ${o}`);for(const a of i){const l=void 0,c=xs(a,l,n);n&&c.setFastWeightInitDuringBuild(!0),o.add(c)}return o}set stopTraining(e){if(this.model==null)throw new k("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 k("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 s={};s.className=t.getClassName(),s.config=t.getConfig(),e.push(s)}return{name:this.name,layers:e}}}no.className="Sequential";V.registerClass(no);function hA(e){return new tn(e)}function dA(e){return new no(e)}function mA(e,t){return t==null&&(t={}),uA(e,t)}function Md(e){return Ld(e)}function fA(e,t){en.registerCallbackConstructor(e,t)}class zs extends V.Serializable{getConfig(){return{}}}class gA extends zs{apply(e,t=1){return FT(e,t)}}gA.className="elu";V.registerClass(gA);class yA extends zs{apply(e){return dl(e)}}yA.className="selu";V.registerClass(yA);class bA extends zs{apply(e){return De(e)}}bA.className="relu";V.registerClass(bA);class wA extends zs{apply(e){return C(()=>mn(6,De(e)))}}wA.className="relu6";V.registerClass(wA);class xA extends zs{apply(e){return e}}xA.className="linear";V.registerClass(xA);class LA extends zs{apply(e){return rs(e)}}LA.className="sigmoid";V.registerClass(LA);class SA extends zs{apply(e){return UT(e)}}SA.className="hardSigmoid";V.registerClass(SA);class IA extends zs{apply(e){return pi(e)}}IA.className="softplus";V.registerClass(IA);class vA extends zs{apply(e){return MT(e)}}vA.className="softsign";V.registerClass(vA);class TA extends zs{apply(e){return ki(e)}}TA.className="tanh";V.registerClass(TA);class Ud extends zs{apply(e,t=-1){return es(e,t)}}Ud.className="softmax";V.registerClass(Ud);class AA extends zs{apply(e,t=-1){return al(e,t)}}AA.className="logSoftmax";V.registerClass(AA);class NA extends zs{apply(e,t=1){return C(()=>rs(e.mul(t)).mul(e))}}NA.className="swish";V.registerClass(NA);function Wn(e){return e.getClassName()}function Sb(e,t={}){return hi(e,V.SerializationMap.getMap().classNameMap,t,"activation")}function zn(e){if(e==null){const t={};return t.className="linear",t.config={},Sb(t)}if(typeof e=="string"){const t={};return t.className=e,t.config={},Sb(t)}else return e instanceof zs?e:Sb(e)}function Ib(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 CA extends V.Serializable{}class _l extends CA{constructor(e){super();Ib(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 C(()=>{let t=ye([1]);return this.hasL1&&(t=$(t,te(R(this.l1,et(e))))),this.hasL2&&(t=$(t,te(R(this.l2,ta(e))))),t.asScalar()})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}}_l.className="L1L2";V.registerClass(_l);function RA(e){return Ib(e),new _l({l1:e!=null?e.l1:null,l2:0})}function OA(e){return Ib(e),new _l({l2:e!=null?e.l2:null,l1:0})}const EA={l1l2:"L1L2"};function Pe(e){return xl(e)}function _A(e,t={}){return hi(e,V.SerializationMap.getMap().classNameMap,t,"regularizer")}function He(e){if(e==null)return null;if(typeof e=="string"){const t=e in EA?EA[e]:e,s={className:t,config:{}};return _A(s)}else return e instanceof CA?e:_A(e)}class $d extends Le{constructor(e){super(e??{});this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=we(e);let s=De(e);return this.maxValue!=null&&(s=wt(s,0,this.maxValue)),s}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}}$d.className="ReLU";V.registerClass($d);class Wd extends Le{constructor(e){super(e??{});this.DEFAULT_ALPHA=.3,e==null&&(e={}),this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){const s=we(e);return rl(s,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}Wd.className="LeakyReLU";V.registerClass(Wd);class zd extends Le{constructor(e){super(e??{});if(this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=Be(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=He(e.alphaRegularizer),this.alphaConstraint=rt(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 k(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=Ue(e);const t=e.slice(1);if(this.sharedAxes!=null)for(const n of this.sharedAxes)t[n-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);const s={};if(this.sharedAxes!=null)for(let n=1;n<e.length;++n)s[n]=e[n];this.inputSpec=[new st({ndim:e.length,axes:s})],this.built=!0}call(e,t){return e=we(e),jr(e,this.alpha.read())}getConfig(){const e={alphaInitializer:Je(this.alphaInitializer),alphaRegularizer:Pe(this.alphaRegularizer),alphaConstraint:it(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}}zd.className="PReLU";V.registerClass(zd);class Pd extends Le{constructor(e){super(e??{});if(this.DEFAULT_ALPHA=1,e==null&&(e={}),e.alpha!=null&&e.alpha!==this.DEFAULT_ALPHA)throw new ae(`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 s=we(e);return hn(s)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}Pd.className="ELU";V.registerClass(Pd);class Bd extends Le{constructor(e){super(e??{});this.DEFAULT_THETA=1,e==null&&(e={}),this.theta=e.theta==null?this.DEFAULT_THETA:e.theta}call(e,t){const s=we(e);return s.mul(zi(s.greater(this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){const e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}}Bd.className="ThresholdedReLU";V.registerClass(Bd);class jd extends Le{constructor(e){super(e??{});this.DEFAULT_AXIS=1,e==null&&(e={}),this.softmax=new Ud().apply,this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis}call(e,t){const s=we(e);return this.softmax(s,this.axis)}computeOutputShape(e){return e}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}jd.className="Softmax";V.registerClass(jd);function io(e,t,s){if(typeof e=="number")return wn(e,t);if(e.length!==t)throw new k(`The ${s} argument must be an integer or tuple of ${t} integers. Received: ${e.length} elements.`);for(let n=0;n<t;++n){const i=e[n];if(!OT(i))throw new k(`The ${s} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(e)} including a non-integer number ${i}`)}return e}function Ns(e,t,s,n,i=1){if(e==null)return e;const r=t+(t-1)*(i-1);let o;return s==="same"?o=e:o=e-r+1,Math.floor((o+n-1)/n)}function Zp(e,t,s,n){if(e==null)return null;if(n==="valid")e=e*t+Un([s-t,0]);else if(n==="same")e=e*t;else throw new k(`Unsupport padding mode: ${n}.`);return e}function Qp(e,t){return C(()=>(ot(t),t==="channelsFirst"?se(e,[0,2,3,1]):e))}function vb(e,t){return C(()=>(ot(t),t==="channelsFirst"?se(e,[0,2,3,4,1]):e))}function sz(e,t,s,n=1,i="valid",r,o=1){return C(()=>{if(r==null&&(r=gs()),ot(r),e.shape.length!==3)throw new k(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new k(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(s!=null&&s.shape.length!==1)throw new k(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(r==="channelsFirst"&&(e=se(e,[0,2,1])),i==="causal")throw new ae("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let a=Qa(e,t,n,i==="same"?"same":"valid","NWC",o);return s!=null&&(a=As(a,s)),a})}function kA(e,t,s,n=[1,1],i="valid",r,o,a=null){return C(()=>{if(r==null&&(r=gs()),ot(r),e.rank!==3&&e.rank!==4)throw new k(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new k(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=Qp(e,r);if(i==="causal")throw new ae("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=gn.conv2d({x:l,filter:t,strides:n,pad:i==="same"?"same":"valid",dilations:o,dataFormat:"NHWC",bias:s,activation:a}),r==="channelsFirst"&&(l=se(l,[0,3,1,2])),l})}function nz(e,t,s,n=[1,1,1],i="valid",r,o){return C(()=>{if(r==null&&(r=gs()),ot(r),e.rank!==4&&e.rank!==5)throw new k(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new k(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let a=vb(e,r);if(i==="causal")throw new ae("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return a=sl(a,t,n,i==="same"?"same":"valid","NDHWC",o),s!=null&&(a=As(a,s)),r==="channelsFirst"&&(a=se(a,[0,4,1,2,3])),a})}class Vd extends Le{constructor(e,t){super(t);if(this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",Vd.verifyArgs(t),this.rank=e,gt(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new ae(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=io(t.kernelSize,e,"kernelSize"),this.strides=io(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,ys(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,ot(this.dataFormat),this.activation=zn(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=Be(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=rt(t.biasConstraint),this.biasRegularizer=He(t.biasRegularizer),this.activityRegularizer=He(t.activityRegularizer),this.dilationRate=io(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new k(`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 k(`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 k(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(Qs("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!Qh(e.kernelSize,"number",1,3))throw new k(`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:Wn(this.activation),useBias:this.useBias,biasInitializer:Je(this.biasInitializer),biasRegularizer:Pe(this.biasRegularizer),activityRegularizer:Pe(this.activityRegularizer),biasConstraint:it(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class eu extends Vd{constructor(e,t){super(e,t);this.kernel=null,eu.verifyArgs(t),this.filters=t.filters,gt(this.filters,"filters"),this.kernelInitializer=Be(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=rt(t.kernelConstraint),this.kernelRegularizer=He(t.kernelRegularizer)}build(e){e=Ue(e);const t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new k(`The channel dimension of the input should be defined. Found ${e[t]}`);const s=e[t],n=this.kernelSize.concat([s,this.filters]);this.kernel=this.addWeight("kernel",n,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]:s}}],this.built=!0}call(e,t){return C(()=>{e=we(e);let s;const n=this.bias==null?null:this.bias.read(),i=ed(this.activation.getClassName());if(i!=null&&this.rank===2)s=kA(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate,i);else{if(this.rank===1)s=sz(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)s=kA(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)s=nz(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new ae("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(s=this.activation.apply(s))}return s})}computeOutputShape(e){e=Ue(e);const t=[],s=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let i=0;i<s.length;++i){const r=Ns(s[i],this.kernelSize[i],this.padding,this.strides[i],typeof this.dilationRate=="number"?this.dilationRate:this.dilationRate[i]);t.push(r)}let n=[e[0]];return this.dataFormat==="channelsLast"?(n=n.concat(t),n.push(this.filters)):(n.push(this.filters),n=n.concat(t)),n}getConfig(){const e={filters:this.filters,kernelInitializer:Je(this.kernelInitializer),kernelRegularizer:Pe(this.kernelRegularizer),kernelConstraint:it(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 k(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}}class kl extends eu{constructor(e){super(2,e);kl.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!Qh(e.kernelSize,"number",1,2))throw new k(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}kl.className="Conv2D";V.registerClass(kl);class tu extends eu{constructor(e){super(3,e);tu.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 k(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}tu.className="Conv3D";V.registerClass(tu);class Gd extends kl{constructor(e){super(e);if(this.inputSpec=[new st({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new k(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=Ue(e),e.length!==4)throw new k("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 k("The channel dimension of the inputs should be defined. Found `None`.");const s=e[t],n=this.kernelSize.concat([this.filters,s]);this.kernel=this.addWeight("kernel",n,"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 st({ndim:4,axes:{[t]:s}})],this.built=!0}call(e,t){return C(()=>{let s=we(e);if(s.shape.length!==4)throw new k(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${s.shape.length}`);const n=s.shape,i=n[0];let r,o;this.dataFormat==="channelsFirst"?(r=2,o=3):(r=1,o=2);const a=n[r],l=n[o],c=this.kernelSize[0],p=this.kernelSize[1],u=this.strides[0],h=this.strides[1],d=Zp(a,u,c,this.padding),m=Zp(l,h,p,this.padding),f=[i,d,m,this.filters];this.dataFormat!=="channelsLast"&&(s=se(s,[0,2,3,1]));let g=tl(s,this.kernel.read(),f,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(g=se(g,[0,3,1,2])),this.bias!=null&&(g=As(g,this.bias.read(),this.dataFormat)),this.activation!=null&&(g=this.activation.apply(g)),g})}computeOutputShape(e){e=Ue(e);const t=e.slice();let s,n,i;this.dataFormat==="channelsFirst"?(s=1,n=2,i=3):(s=3,n=1,i=2);const r=this.kernelSize[0],o=this.kernelSize[1],a=this.strides[0],l=this.strides[1];return t[s]=this.filters,t[n]=Zp(t[n],a,r,this.padding),t[i]=Zp(t[i],l,o,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}Gd.className="Conv2DTranspose";V.registerClass(Gd);class DA extends eu{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 k("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new k("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 k(`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=Be(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=He(t.depthwiseRegularizer),this.depthwiseConstraint=rt(t.depthwiseConstraint),this.pointwiseInitializer=Be(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=He(t.pointwiseRegularizer),this.pointwiseConstraint=rt(t.pointwiseConstraint)}build(e){if(e=Ue(e),e.length<this.rank+2)throw new k(`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 k(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);const s=e[t],n=this.kernelSize.concat([s,this.depthMultiplier]),i=[];for(let o=0;o<this.rank;++o)i.push(1);i.push(s*this.depthMultiplier,this.filters);const r=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",n,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,r,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",i,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,r,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,r,this.biasConstraint):this.bias=null,this.inputSpec=[new st({ndim:this.rank+2,axes:{[t]:s}})],this.built=!0}call(e,t){return C(()=>{e=we(e);let s;if(this.rank===1)throw new ae("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=se(e,[0,2,3,1])),s=Vr(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(s=As(s,this.bias.read(),this.dataFormat)),this.activation!=null&&(s=this.activation.apply(s)),this.dataFormat==="channelsFirst"&&(s=se(s,[0,3,1,2])),s})}getConfig(){const e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=Je(this.depthwiseInitializer),e.pointwiseInitializer=Je(this.pointwiseInitializer),e.depthwiseRegularizer=Pe(this.depthwiseRegularizer),e.pointwiseRegularizer=Pe(this.pointwiseRegularizer),e.depthwiseConstraint=it(this.depthwiseConstraint),e.pointwiseConstraint=it(this.pointwiseConstraint),e}}DA.className="SeparableConv";class qd extends DA{constructor(e){super(2,e)}}qd.className="SeparableConv2D";V.registerClass(qd);class su extends eu{constructor(e){super(1,e);su.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"&&!Qh(e.kernelSize,"number",1,1))throw new k(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}su.className="Conv1D";V.registerClass(su);class Hd extends Le{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 C(()=>{if(e=we(e),this.dataFormat==="channelsLast"){const s=Up(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Up(s,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{const s=Up(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Up(s,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}}Hd.className="Cropping2D";V.registerClass(Hd);class Yd extends Le{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],s=e[3]==null?null:this.size[1]*e[3];return[e[0],e[1],t,s]}else{const t=e[1]==null?null:this.size[0]*e[1],s=e[2]==null?null:this.size[1]*e[2];return[e[0],t,s,e[3]]}}call(e,t){return C(()=>{let s=we(e);const n=s.shape;if(this.dataFormat==="channelsFirst"){s=se(s,[0,2,3,1]);const i=this.size[0]*n[2],r=this.size[1]*n[3],o=s.resizeNearestNeighbor([i,r]);return se(o,[0,3,1,2])}else{const i=this.size[0]*n[1],r=this.size[1]*n[2];return s.resizeNearestNeighbor([i,r])}})}getConfig(){const e={size:this.size,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}Yd.className="UpSampling2D";V.registerClass(Yd);function iz(e,t,s=[1,1],n="valid",i,r){return C(()=>{i==null&&(i=gs()),ot(i);let o=Qp(e,i);if(e.rank!==4)throw new k(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new k(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return o=un(o,t,s,n==="same"?"same":"valid","NHWC",r),i==="channelsFirst"&&(o=se(o,[0,3,1,2])),o})}class Kd extends Vd{constructor(e){super(2,e);this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=Be(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=rt(e.depthwiseConstraint),this.depthwiseRegularizer=He(e.depthwiseRegularizer)}build(e){if(e=Ue(e),e.length<4)throw new k(`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 k(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);const s=e[t],n=[this.kernelSize[0],this.kernelSize[1],s,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",n,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[s*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return C(()=>{e=we(e);let s=iz(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(s=As(s,this.bias.read(),this.dataFormat)),this.activation!=null&&(s=this.activation.apply(s)),s})}computeOutputShape(e){e=Ue(e);const t=this.dataFormat==="channelsFirst"?e[2]:e[1],s=this.dataFormat==="channelsFirst"?e[3]:e[2],n=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,i=Ns(t,this.kernelSize[0],this.padding,this.strides[0]),r=Ns(s,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],n,i,r]:[e[0],i,r,n]}getConfig(){const e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=Je(this.depthwiseInitializer),e.depthwiseRegularizer=Pe(this.depthwiseRegularizer),e.depthwiseConstraint=it(this.depthwiseRegularizer),e}}Kd.className="DepthwiseConv2D";V.registerClass(Kd);function Tb(e,t,s,n){if(Array.isArray(e)){if(t!=null||s!=null)throw new k("When inputs is an array, neither initialState or constants should be provided");n!=null&&(s=e.slice(e.length-n,e.length),e=e.slice(0,e.length-n)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function i(r){return r==null||Array.isArray(r)?r:[r]}return t=i(t),s=i(s),{inputs:e,initialState:t,constants:s}}function Ab(e,t,s,n=!1,i,r,o=!1,a=!1){return C(()=>{const l=t.shape.length;if(l<3)throw new k(`Input should be at least 3D, but is ${l}D.`);const c=[1,0].concat(ls(2,l));if(t=se(t,c),r!=null)throw new ae("The rnn() functoin of the deeplearn.js backend does not support constants yet.");o&&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===l-1&&(i=Mt(i,-1)),i=se(i,c)),n&&(t=Et(t,0),i!=null&&(i=Et(i,0)));const p=[];let u,h=s;const d=t.shape[0],m=Ge(t);let f;i!=null&&(f=Ge(i));for(let y=0;y<d;++y){const w=m[y],x=C(()=>e(w,h));if(i==null)u=x[0],h=x[1];else{const T=C(()=>{const A=f[y],_=Ot(A).sub(A),E=x[0].mul(A).add(h[0].mul(_)),F=h.map((D,M)=>x[1][M].mul(A).add(D.mul(_)));return{output:E,newStates:F}});u=T.output,h=T.newStates}a&&p.push(u)}let g;if(a){const y=1;g=Ve(p,y)}return[u,g,h]})}class sn extends Le{constructor(e){super(e);let t;if(e.cell==null)throw new k("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new nu({cells:e.cell}):t=e.cell,t.stateSize==null)throw new k("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 st({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 ls(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){wd(e)&&(e=e[0]),e=e;let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);const s=t[0];let n;if(this.returnSequences?n=[e[0],e[1],s]:n=[e[0],s],this.returnState){const i=[];for(const r of t)i.push([e[0],r]);return[n].concat(i)}else return n}computeMask(e,t){return C(()=>{Array.isArray(t)&&(t=t[0]);const s=this.returnSequences?t:null;if(this.returnState){const n=this.states.map(i=>null);return[s].concat(n)}else return s})}get states(){if(this.states_==null){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let s=0;s<e;++s)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 ae("Constants support is not implemented in RNN yet.");wd(e)&&(e=e[0]),e=e;const s=this.stateful?e[0]:null,n=e.slice(2);this.inputSpec[0]=new st({shape:[s,null,...n]});const i=[e[0]].concat(e.slice(2));if(t!=null)throw new ae("Constants support is not implemented in RNN yet.");this.cell.build(i);let r;if(Array.isArray(this.cell.stateSize)?r=this.cell.stateSize:r=[this.cell.stateSize],this.stateSpec!=null){if(!N.arraysEqual(this.stateSpec.map(o=>o.shape[o.shape.length-1]),r))throw new k(`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=r.map(o=>new st({shape:[null,o]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){C(()=>{if(!this.stateful)throw new bn("Cannot call resetStates() on an RNN Layer that is not stateful.");const s=this.inputSpec[0].shape[0];if(s==null)throw new k("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(n=>ye([s,n])):this.states_=[ye([s,this.cell.stateSize])];else if(e==null)ce(this.states_),this.keptStates!=null&&(ce(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(n=>ye([s,n])):this.states_[0]=ye([s,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new k(`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()):ce(this.states_);for(let n=0;n<this.states_.length;++n){const i=e[n],r=Array.isArray(this.cell.stateSize)?this.cell.stateSize[n]:this.cell.stateSize,o=[s,r];if(!N.arraysEqual(i.shape,o))throw new k(`State ${n} is incompatible with layer ${this.name}: expected shape=${o}, received shape=${i.shape}`);this.states_[n]=i}}this.states_=this.states_.map(n=>pt(n.clone()))})}apply(e,t){let s=t==null?null:t.initialState,n=t==null?null:t.constants;t==null&&(t={});const i=Tb(e,s,n,this.numConstants);e=i.inputs,s=i.initialState,n=i.constants;let r=[],o=[];if(s!=null){t.initialState=s,r=r.concat(s),this.stateSpec=[];for(const l of s)this.stateSpec.push(new st({shape:l.shape}));o=o.concat(this.stateSpec)}n!=null&&(t.constants=n,r=r.concat(n),this.numConstants=n.length);const a=r[0]instanceof ws;if(a){const l=[e].concat(r),c=this.inputSpec.concat(o),p=this.inputSpec;this.inputSpec=c;const u=super.apply(l,t);return this.inputSpec=p,u}else return super.apply(e,t)}call(e,t){return C(()=>{const s=t==null?null:t.mask,n=t==null?null:t.training;let i=t==null?null:t.initialState;e=we(e),i==null&&(this.stateful?i=this.states_:i=this.getInitialState(e));const r=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(i.length!==r)throw new k(`RNN Layer has ${r} 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 o={training:n},a=(d,m)=>{const f=this.cell.call([d].concat(m),o);return[f[0],f.slice(1)]},l=Ab(a,e,i,this.goBackwards,s,null,this.unroll,this.returnSequences),c=l[0],p=l[1],u=l[2];this.stateful&&this.resetStates(u,n);const h=this.returnSequences?p:c;return this.returnState?[h].concat(u):h})}getInitialState(e){return C(()=>{let t=ye(e.shape);return t=te(t,[1,2]),t=Pi(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(s=>s>1?ad(t,[1,s]):t):this.cell.stateSize>1?[ad(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 s=this.cell.getConfig();return this.getClassName()===sn.className&&(t.cell={className:this.cell.getClassName(),config:s}),Object.assign({},s,e,t)}static fromConfig(e,t,s={}){const n=t.cell,i=xs(n,s);return new e(Object.assign(t,{cell:i}))}}sn.className="RNN";V.registerClass(sn);class ro extends Le{}class iu extends ro{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,gt(this.units,"units"),this.activation=zn(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Be(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Be(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Be(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=He(e.kernelRegularizer),this.recurrentRegularizer=He(e.recurrentRegularizer),this.biasRegularizer=He(e.biasRegularizer),this.kernelConstraint=rt(e.kernelConstraint),this.recurrentConstraint=rt(e.recurrentConstraint),this.biasConstraint=rt(e.biasConstraint),this.dropout=ea([1,Un([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=ea([1,Un([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Ue(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 C(()=>{if(e=e,e.length!==2)throw new k(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let s=e[1];e=e[0];const n=t.training==null?!1:t.training;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Gi({ones:()=>Ot(e),rate:this.dropout,training:n})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Gi({ones:()=>Ot(s),rate:this.recurrentDropout,training:n}));let i;const r=this.dropoutMask,o=this.recurrentDropoutMask;r!=null?i=vn(R(e,r),this.kernel.read()):i=vn(e,this.kernel.read()),this.bias!=null&&(i=As(i,this.bias.read())),o!=null&&(s=R(s,o));let a=$(i,vn(s,this.recurrentKernel.read()));return this.activation!=null&&(a=this.activation.apply(a)),[a,a]})}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Wn(this.activation),useBias:this.useBias,kernelInitializer:Je(this.kernelInitializer),recurrentInitializer:Je(this.recurrentInitializer),biasInitializer:Je(this.biasInitializer),kernelRegularizer:Pe(this.kernelRegularizer),recurrentRegularizer:Pe(this.recurrentRegularizer),biasRegularizer:Pe(this.biasRegularizer),activityRegularizer:Pe(this.activityRegularizer),kernelConstraint:it(this.kernelConstraint),recurrentConstraint:it(this.recurrentConstraint),biasConstraint:it(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign({},e,t)}}iu.className="SimpleRNNCell";V.registerClass(iu);class Xd extends sn{constructor(e){e.cell=new iu(e),super(e)}call(e,t){return C(()=>{this.cell.dropoutMask!=null&&(ce(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(ce(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const s=t==null?null:t.mask,n=t==null?null:t.training,i=t==null?null:t.initialState;return super.call(e,{mask:s,training:n,initialState:i})})}static fromConfig(e,t){return new e(t)}}Xd.className="SimpleRNN";V.registerClass(Xd);class ru extends ro{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 k("GRUCell does not support reset_after parameter set to true.");this.units=e.units,gt(this.units,"units"),this.activation=zn(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=zn(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Be(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Be(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Be(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=He(e.kernelRegularizer),this.recurrentRegularizer=He(e.recurrentRegularizer),this.biasRegularizer=He(e.biasRegularizer),this.kernelConstraint=rt(e.kernelConstraint),this.recurrentConstraint=rt(e.recurrentConstraint),this.biasConstraint=rt(e.biasConstraint),this.dropout=ea([1,Un([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=ea([1,Un([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Ue(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 C(()=>{if(e=e,e.length!==2)throw new k(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);const s=t.training==null?!1:t.training;let n=e[1];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Gi({ones:()=>Ot(e),rate:this.dropout,training:s,count:3})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Gi({ones:()=>Ot(n),rate:this.recurrentDropout,training:s,count:3}));const i=this.dropoutMask,r=this.recurrentDropoutMask;let o,a,l;0<this.dropout&&this.dropout<1&&(e=R(e,i[0]));let c=vn(e,this.kernel.read());this.useBias&&(c=As(c,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(n=R(n,r[0]));const p=this.recurrentKernel.read(),[u,h]=Bt(p,[2*this.units,this.units],p.rank-1),d=vn(n,u),[m,f,g]=Bt(c,3,c.rank-1),[y,w]=Bt(d,2,d.rank-1);o=this.recurrentActivation.apply($(m,y)),a=this.recurrentActivation.apply($(f,w));const x=vn(R(a,n),h);l=this.activation.apply($(g,x));const T=$(R(o,n),R($(1,_e(o)),l));return[T,T]})}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Wn(this.activation),recurrentActivation:Wn(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Je(this.kernelInitializer),recurrentInitializer:Je(this.recurrentInitializer),biasInitializer:Je(this.biasInitializer),kernelRegularizer:Pe(this.kernelRegularizer),recurrentRegularizer:Pe(this.recurrentRegularizer),biasRegularizer:Pe(this.biasRegularizer),activityRegularizer:Pe(this.activityRegularizer),kernelConstraint:it(this.kernelConstraint),recurrentConstraint:it(this.recurrentConstraint),biasConstraint:it(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign({},e,t)}}ru.className="GRUCell";V.registerClass(ru);class Jd extends sn{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 ru(e),super(e)}call(e,t){return C(()=>{this.cell.dropoutMask!=null&&(ce(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(ce(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const s=t==null?null:t.mask,n=t==null?null:t.training,i=t==null?null:t.initialState;return super.call(e,{mask:s,training:n,initialState:i})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}}Jd.className="GRU";V.registerClass(Jd);class aa extends ro{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,gt(this.units,"units"),this.activation=zn(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=zn(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Be(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Be(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Be(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=He(e.kernelRegularizer),this.recurrentRegularizer=He(e.recurrentRegularizer),this.biasRegularizer=He(e.biasRegularizer),this.kernelConstraint=rt(e.kernelConstraint),this.recurrentConstraint=rt(e.recurrentConstraint),this.biasConstraint=rt(e.biasConstraint),this.dropout=ea([1,Un([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=ea([1,Un([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=Ue(e);const s=e[e.length-1];this.kernel=this.addWeight("kernel",[s,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 n;if(this.useBias){if(this.unitForgetBias){const i=this.biasInitializer,r=this.units;n=new(t=class extends Ws{apply(a,l){const c=i.apply([r]),p=new vl().apply([r]),u=i.apply([r*2]);return lb(lb(c,p),u)}},t.className="CustomInit",t)}else n=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,n,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return C(()=>{const s=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new k(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let n=e[1];const i=e[2];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Gi({ones:()=>Ot(e),rate:this.dropout,training:s,count:4})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Gi({ones:()=>Ot(n),rate:this.recurrentDropout,training:s,count:4}));const r=this.dropoutMask,o=this.recurrentDropoutMask;let a,l,c,p;0<this.dropout&&this.dropout<1&&(e=R(e,r[0]));let u=vn(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(n=R(n,o[0])),u=$(u,vn(n,this.recurrentKernel.read())),this.useBias&&(u=As(u,this.bias.read()));const[h,d,m,f]=Bt(u,4,u.rank-1);a=this.recurrentActivation.apply(h),l=this.recurrentActivation.apply(d),c=$(R(l,i),R(a,this.activation.apply(m))),p=this.recurrentActivation.apply(f);const g=R(p,this.activation.apply(c));return[g,g,c]})}getConfig(){const e=super.getConfig(),t={units:this.units,activation:Wn(this.activation),recurrentActivation:Wn(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Je(this.kernelInitializer),recurrentInitializer:Je(this.recurrentInitializer),biasInitializer:Je(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Pe(this.kernelRegularizer),recurrentRegularizer:Pe(this.recurrentRegularizer),biasRegularizer:Pe(this.biasRegularizer),activityRegularizer:Pe(this.activityRegularizer),kernelConstraint:it(this.kernelConstraint),recurrentConstraint:it(this.recurrentConstraint),biasConstraint:it(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign({},e,t)}}aa.className="LSTMCell";V.registerClass(aa);class Zd extends sn{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 aa(e),super(e)}call(e,t){return C(()=>{this.cell.dropoutMask!=null&&(ce(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(ce(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const s=t==null?null:t.mask,n=t==null?null:t.training,i=t==null?null:t.initialState;return super.call(e,{mask:s,training:n,initialState:i})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}}Zd.className="LSTM";V.registerClass(Zd);class nu extends ro{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 C(()=>{e=e;let s=e.slice(1);const n=[];for(const o of this.cells.slice().reverse())Array.isArray(o.stateSize)?n.push(s.splice(0,o.stateSize.length)):n.push(s.splice(0,1));n.reverse();const i=[];let r;for(let o=0;o<this.cells.length;++o){const a=this.cells[o];s=n[o],o===0?r=[e[0]].concat(s):r=[r[0]].concat(s),r=a.call(r,t),i.push(r.slice(1))}s=[];for(const o of i.slice().reverse())s.push(...o);return[r[0]].concat(s)})}build(e){wd(e)&&(e=e[0]),e=e;let t;this.cells.forEach((s,n)=>{Mn(`RNNCell_${n}`,()=>{s.build(e),Array.isArray(s.stateSize)?t=s.stateSize[0]:t=s.stateSize,e=[e[0],t]})}),this.built=!0}getConfig(){const e=super.getConfig(),t=i=>({className:i.getClassName(),config:i.getConfig()}),s=this.cells.map(t),n={cells:s};return Object.assign({},e,n)}static fromConfig(e,t,s={}){const n=[];for(const i of t.cells)n.push(xs(i,s));return new e({cells:n})}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 s of this.cells)t.push(...s.trainableWeights);return t.concat(e)}return e}getWeights(){const e=[];for(const t of this.cells)e.push(...t.weights);return Vp(e)}setWeights(e){const t=[];for(const s of this.cells){const n=s.weights.length,i=e.splice(n);for(let r=0;r<s.weights.length;++r)t.push([s.weights[r],i[r]])}Nl(t)}}nu.className="StackedRNNCells";V.registerClass(nu);function Gi(e){const{ones:t,rate:s,training:n=!1,count:i=1}=e,r=()=>cd(t(),s),o=()=>Zr(r,t,n);if(!i||i<=1)return pt(o().clone());const a=Array(i).fill(void 0).map(o);return a.map(l=>pt(l.clone()))}var rz=function(e,t){var s={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(s[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(e);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(s[n[i]]=e[n[i]]);return s};class XFe extends ro{}class FA extends sn{constructor(e){if(e.unroll)throw new ae("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new ae("It is not possible at the moment to stack convolutional cells.");super(e);this.inputSpec=[new st({ndim:5})]}call(e,t){return C(()=>{if(this.cell.dropoutMask!=null&&(ce(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(ce(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new k("ConvRNN2D cell does not support constants");const s=t==null?null:t.mask,n=t==null?null:t.training,i=t==null?null:t.initialState;return super.call(e,{mask:s,training:n,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 C(()=>{const{stateSize:t}=this.cell,s=e.shape,n=this.computeSingleOutputShape(s),i=[n[0],...n.slice(2)],r=ye(i);return Array.isArray(t)?Array(t.length).fill(r):[r]})}resetStates(e,t=!1){C(()=>{if(!this.stateful)throw new bn("Cannot call resetStates() on an RNN Layer that is not stateful.");const s=this.inputSpec[0].shape,n=this.computeSingleOutputShape(s),i=[n[0],...n.slice(2)],r=s[0];if(r==null)throw new k("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(()=>ye(i)):this.states_=[ye(i)];else if(e==null)ce(this.states_),this.keptStates!=null&&(ce(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>ye(i)):this.states_[0]=ye(i);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new k(`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()):ce(this.states_);for(let o=0;o<this.states_.length;++o){const a=e[o],l=i;if(!N.arraysEqual(a.shape,l))throw new k(`State ${o} is incompatible with layer ${this.name}: expected shape=${l}, received shape=${a.shape}`);this.states_[o]=a}}this.states_=this.states_.map(o=>pt(o.clone()))})}computeSingleOutputShape(e){const{dataFormat:t,filters:s,kernelSize:n,padding:i,strides:r,dilationRate:o}=this.cell,a=t==="channelsFirst",l=e[a?3:2],c=e[a?4:3],p=Ns(l,n[0],i,r[0],o[0]),u=Ns(c,n[1],i,r[1],o[1]),h=[...e.slice(0,2),...a?[s,p,u]:[p,u,s]];return h}}FA.className="ConvRNN2D";class ou extends aa{constructor(e){const{filters:t,kernelSize:s,strides:n,padding:i,dataFormat:r,dilationRate:o}=e;super(Object.assign({},e,{units:t}));this.filters=t,gt(this.filters,"filters"),this.kernelSize=io(s,2,"kernelSize"),this.kernelSize.forEach(a=>gt(a,"kernelSize")),this.strides=io(n||1,2,"strides"),this.strides.forEach(a=>gt(a,"strides")),this.padding=i||"valid",ys(this.padding),this.dataFormat=r||"channelsLast",ot(this.dataFormat),this.dilationRate=io(o||1,2,"dilationRate"),this.dilationRate.forEach(a=>gt(a,"dilationRate"))}build(e){var t;e=Ue(e);const s=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[s]==null)throw new k(`The channel dimension of the input should be defined. Found ${e[s]}`);const n=e[s],i=4,r=this.kernelSize.concat([n,this.filters*i]);this.kernel=this.addWeight("kernel",r,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);const o=this.kernelSize.concat([this.filters,this.filters*i]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",o,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let a;if(this.unitForgetBias){const l=this.biasInitializer,c=this.filters;a=new(t=class extends Ws{apply(u,h){const d=l.apply([c]),m=Kt([c]),f=l.apply([c*2]);return Sl([d,m,f])}},t.className="CustomInit",t)}else a=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*i],null,a,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return C(()=>{if(e.length!==3)throw new k(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);const s=t.training||!1,n=e[0],i=e[1],r=e[2],o=4;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Gi({ones:()=>Ot(n),rate:this.dropout,training:s,count:o}));const a=this.dropoutMask,l=(ie,ne,le)=>!ne||!ne[le]?ie:R(ne[le],ie);let c=l(n,a,0),p=l(n,a,1),u=l(n,a,2),h=l(n,a,3);0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Gi({ones:()=>Ot(i),rate:this.recurrentDropout,training:s,count:o}));const d=this.recurrentDropoutMask;let m=l(i,d,0),f=l(i,d,1),g=l(i,d,2),y=l(i,d,3);const w=3,[x,T,A,_]=Bt(this.kernel.read(),o,w),[E,F,D,M]=this.useBias?Bt(this.bias.read(),o):[null,null,null,null];c=this.inputConv(c,x,E,this.padding),p=this.inputConv(p,T,F,this.padding),u=this.inputConv(u,A,D,this.padding),h=this.inputConv(h,_,M,this.padding);const[P,B,Y,q]=Bt(this.recurrentKernel.read(),o,w);m=this.recurrentConv(m,P),f=this.recurrentConv(f,B),g=this.recurrentConv(g,Y),y=this.recurrentConv(y,q);const K=this.recurrentActivation.apply($(c,m)),H=this.recurrentActivation.apply($(p,f)),Q=$(R(H,r),R(K,this.activation.apply($(u,g)))),J=R(this.recurrentActivation.apply($(h,y)),this.activation.apply(Q));return[J,J,Q]})}getConfig(){const e=super.getConfig(),{units:t}=e,s=rz(e,["units"]),n={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign({},s,n)}inputConv(e,t,s,n){const i=nt(e,t,this.strides,n||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return s?As(i,s,this.dataFormat):i}recurrentConv(e,t){const s=1;return nt(e,t,s,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}}ou.className="ConvLSTM2DCell";V.registerClass(ou);class Qd extends FA{constructor(e){const t=new ou(e);super(Object.assign({},e,{cell:t}))}static fromConfig(e,t){return new e(t)}}Qd.className="ConvLSTM2D";V.registerClass(Qd);class au extends Le{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,s=[];for(let n=0;n<this.noiseShape.length;++n)s.push(this.noiseShape[n]==null?t[n]:this.noiseShape[n]);return s}call(e,t){return C(()=>{this.invokeCallHook(e,t);const s=we(e);if(0<this.rate&&this.rate<1){const n=t.training==null?!1:t.training,i=this.getNoiseShape(s),r=Zr(()=>cd(s,this.rate,i,this.seed),()=>s,n);return r}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()}}au.className="Dropout";V.registerClass(au);class em extends au{constructor(e){super(e);this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}em.className="SpatialDropout1D";V.registerClass(em);class tm extends Le{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,gt(this.units,"units"),this.activation=zn(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=Be(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=Be(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=rt(e.kernelConstraint),this.biasConstraint=rt(e.biasConstraint),this.kernelRegularizer=He(e.kernelRegularizer),this.biasRegularizer=He(e.biasRegularizer),this.activityRegularizer=He(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=Ue(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=Ue(e);const t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return C(()=>{this.invokeCallHook(e,t);const s=we(e),n=ed(this.activation.getClassName());let i;return n!=null?i=vn(s,this.kernel.read(),n,this.bias?this.bias.read():null):(i=vn(s,this.kernel.read()),this.bias!=null&&(i=As(i,this.bias.read())),this.activation!=null&&(i=this.activation.apply(i))),i})}getConfig(){const e={units:this.units,activation:Wn(this.activation),useBias:this.useBias,kernelInitializer:Je(this.kernelInitializer),biasInitializer:Je(this.biasInitializer),kernelRegularizer:Pe(this.kernelRegularizer),biasRegularizer:Pe(this.biasRegularizer),activityRegularizer:Pe(this.activityRegularizer),kernelConstraint:it(this.kernelConstraint),biasConstraint:it(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}tm.className="Dense";V.registerClass(tm);class sm extends Le{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=Ue(e);for(const t of e.slice(1))if(t==null)throw new k(`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],In(e,1)]}call(e,t){return C(()=>{this.invokeCallHook(e,t);let s=we(e);if(this.dataFormat==="channelsFirst"&&s.rank>1){const n=[0];for(let i=2;i<s.rank;++i)n.push(i);n.push(1),s=s.transpose(n)}return DT(s)})}getConfig(){const e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);const t=super.getConfig();return Object.assign(e,t),e}}sm.className="Flatten";V.registerClass(sm);class nm extends Le{constructor(e){super(e);this.supportsMasking=!0,this.activation=zn(e.activation)}call(e,t){return C(()=>{this.invokeCallHook(e,t);const s=we(e);return this.activation.apply(s)})}getConfig(){const e={activation:Wn(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}nm.className="Activation";V.registerClass(nm);class im extends Le{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 C(()=>(e=we(e),_T(e,this.n)))}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}im.className="RepeatVector";V.registerClass(im);class rm extends Le{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 s="Total size of new array must be unchanged.",n=t.slice();let i=1,r=null;for(let a=0;a<n.length;++a){const l=n[a];if(this.isUnknown(l))if(r===null)r=a;else throw new k("Can only specifiy one unknown dimension.");else i*=l}const o=In(e);if(r!==null){if(i===0||o%i!==0)throw new k(s);n[r]=o/i}else if(o!==i)throw new k(s);return n}computeOutputShape(e){let t=!1;for(let s=0;s<e.length;++s)if(this.isUnknown(e[s])){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 C(()=>{this.invokeCallHook(e,t);const s=we(e),n=s.shape,i=n.slice(0,1).concat(this.fixUnknownDimension(n.slice(1),this.targetShape));return s.reshape(i)})}getConfig(){const e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}}rm.className="Reshape";V.registerClass(rm);class om extends Le{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=ls(1,e.dims.length+1);if(!N.arraysEqual(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 st({ndim:this.dims.length+1})]}computeOutputShape(e){e=Ue(e);const t=e.slice();return this.dims.forEach((s,n)=>{t[n+1]=e[s]}),t}call(e,t){return se(we(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}}om.className="Permute";V.registerClass(om);class am extends Le{constructor(e){super(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 s=we(e),n=-1;return Uo(Ks(s,this.maskValue),n)}call(e,t){return C(()=>{this.invokeCallHook(e,t);const s=we(e),n=-1,i=!0,r=Uo(Ks(s,this.maskValue),n,i),o=s.mul(r.asType(s.dtype));return o})}}am.className="Masking";V.registerClass(am);class lm extends Le{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(qe(e.inputLength))}this.inputDim=e.inputDim,gt(this.inputDim,"inputDim"),this.outputDim=e.outputDim,gt(this.outputDim,"outputDim"),this.embeddingsInitializer=Be(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=He(e.embeddingsRegularizer),this.activityRegularizer=He(e.activityRegularizer),this.embeddingsConstraint=rt(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 C(()=>this.maskZero?(e=we(e),Ks(e,re(e))):null)}computeOutputShape(e){if(e=Ue(e),this.inputLength==null)return[...e,this.outputDim];const t=qe(this.inputLength);if(t.length!==e.length-1)throw new k(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let s=0;for(let n=0;n<t.length;++n){const i=t[n],r=e[n+1];if(i!=null&&r!=null&&i!==r)throw new k(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);i==null&&(t[s]=r),s++}}return[e[0],...t,this.outputDim]}call(e,t){return C(()=>{this.invokeCallHook(e,t);let s=we(e);s.dtype!=="int32"&&(s=zi(s,"int32"));const n=ld(this.embeddings.read(),s.as1D());return n.reshape(Ue(this.computeOutputShape(s.shape)))})}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Je(this.embeddingsInitializer),embeddingsRegularizer:Pe(this.embeddingsRegularizer),activityRegularizer:Pe(this.activityRegularizer),embeddingsConstraint:it(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}}lm.className="Embedding";V.registerClass(lm);class la extends Le{constructor(e){super(e||{});this.supportsMasking=!0}mergeFunction(e){throw new ae}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 s=e.slice(0,e.length-t.length);for(let n=0;n<t.length;++n){const i=e[e.length-t.length+n],r=t[n];if(i==null||r==null||i<0||r<0)s.push(null);else if(i===1)s.push(r);else if(r===1)s.push(i);else{if(i!==r)throw new k("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));s.push(i)}}return s}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[Ue(e)]),e=e,e.length<2)throw new k(`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=Sn(t),t.length>1)throw new k(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let s=e[0]==null?null:e[0].slice(1);for(let i=1;i<e.length;++i){const r=e[i]==null?null:e[i].slice(1);s=this.computeElementwiseOpOutputShape(s,r)}const n=e.map(i=>i.length);e.indexOf(null)===-1&&Sn(n).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return C(()=>{if(e=e,this.reshapeRequired){const s=[],n=e.map(i=>i.rank);if(n.indexOf(null)===-1){const i=Un(n);for(let r of e){const o=r.rank;for(let a=0;a<i-o;++a)r=Pi(r,1);s.push(r)}return this.mergeFunction(s)}else{let i=!1;for(const a of e){const l=a.rank;if(l==null){const c=a.shape,p=c[0],u=c.slice(1).concat([p]);let h=a.reshape([p].concat(In(c.slice(1))));h=se(h,[1,0]),h=h.reshape(u),s.push(h),i=!0}else if(l>1){const c=ls(1,l).concat([0]);s.push(se(a,c)),i=!0}else s.push(a)}let r=this.mergeFunction(s);const o=r.rank;if(i){if(o==null){const a=r.shape,l=a.length,c=a[l-1],p=[c].concat(a.slice(0,a.length-1));r=se(r.reshape([-1,c]),[1,0]).reshape(p)}else if(o>1){const a=[o-1].concat(ls(0,o-1));r=se(r,a)}}return r}}else return this.mergeFunction(e)})}computeOutputShape(e){e=e;let t;e[0]==null?t=null:t=e[0].slice(1);for(let n=1;n<e.length;++n){const i=e[n]==null?null:e[n].slice(1);t=this.computeElementwiseOpOutputShape(t,i)}let s=[];for(const n of e)n!=null&&n[0]!==null&&s.push(n[0]);return s=Sn(s),s.length===1?t=s.concat(t):t=[null].concat(t),t}computeMask(e,t){return C(()=>{if(t==null)return null;if(!Array.isArray(t))throw new k("`mask` should be an Array");if(!Array.isArray(e))throw new k("`inputs` should be an Array");if(t.length!==e.length)throw new k(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(n=>n==null))return null;t=t.map(n=>n==null?n:Mt(n,0));let s=t[0];for(let n=1;n<t.length-1;++n)s=Yt(s,t[n]);return s})}}class cm extends la{constructor(e){super(e)}mergeFunction(e){return C(()=>{let t=e[0].clone();for(let s=1;s<e.length;++s)t=$(t,e[s]);return t})}}cm.className="Add";V.registerClass(cm);class pm extends la{constructor(e){super(e)}mergeFunction(e){return C(()=>{let t=e[0].clone();for(let s=1;s<e.length;++s)t=R(t,e[s]);return t})}}pm.className="Multiply";V.registerClass(pm);class um extends la{constructor(e){super(e)}mergeFunction(e){return C(()=>{let t=e[0].clone();for(let s=1;s<e.length;++s)t=$(t,e[s]);return R(1/e.length,t)})}}um.className="Average";V.registerClass(um);class hm extends la{constructor(e){super(e)}mergeFunction(e){return C(()=>{let t=e[0];for(let s=1;s<e.length;++s)t=Ht(t,e[s]);return t})}}hm.className="Maximum";V.registerClass(hm);class dm extends la{constructor(e){super(e)}mergeFunction(e){return C(()=>{let t=e[0];for(let s=1;s<e.length;++s)t=mn(t,e[s]);return t})}}dm.className="Minimum";V.registerClass(dm);class mm extends la{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 k("A `Concatenate` layer should be called on a list of at least 2 inputs");e=e;let t=!0;for(const n of e)if(n!=null){t=!1;break}if(t)return;const s=[];for(let n=0;n<e.length;++n){const i=e[n].slice();i.splice(this.axis,1);let r=!1;for(const o of s)if(N.arraysEqual(o,i)){r=!0;break}r||s.push(i)}if(s.length>1)throw new k("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return C(()=>Sl(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new k("A `Concatenate` layer should be called on a list of inputs.");const t=e,s=t[0].slice(),n=this.axis<0?s.length+this.axis:this.axis;for(const i of t.slice(1)){if(s[n]==null||i[n]==null){s[n]=null;break}s[n]+=i[n]}return s}computeMask(e,t){if(t==null)return null;if(!Array.isArray(t))throw new k("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new k("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new k(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return C(()=>{let s=!0;if(t.forEach(r=>{if(r!=null){s=!1;return}}),s)return null;const n=[];for(let r=0;r<e.length;++r)t[r]==null?n.push(Ot(e[r]).asType("bool")):t[r].rank<e[r].rank?n.push(Mt(t[r],-1)):n.push(t[r]);const i=be(n,this.axis);return Xa(i,-1,!1)})}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}mm.className="Concatenate";V.registerClass(mm);function lu(e,t){for(;e<0;)e+=t;return e}function oz(e,t,s){if(e.shape.length>3||t.shape.length>3)throw new ae("batchDot is not implemented for tensors of 4D or higher rank yet");if(N.assert(e.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`),N.assert(e.shape.length>=2,()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`),typeof s=="number"&&(s=[s,s]),e.dtype==="complex64"||t.dtype==="complex64")throw new ae("batchDot is not implemented for complex64-type Tensors yet.");const n=e.shape.length,i=t.shape.length;s==null&&(s=[n-1,i-2]);const r=s;return C(()=>{let o;if(n>i){o=n-i;const l=[];for(let c=0;c<o;++c)l.push(1);t=t.reshape(t.shape.concat(l))}else if(i>n){o=i-n;const l=[];for(let c=0;c<o;++c)l.push(1);e=e.reshape(e.shape.concat(l))}else o=0;let a;if(e.shape.length===2&&t.shape.length===2)r[0]===r[1]?a=e.mul(t).sum(r[0]):a=e.transpose([1,0]).mul(t).sum(r[1]);else{const l=r[0]!==e.shape.length-1,c=r[1]===t.shape.length-1;a=e.matMul(t,l,c)}if(o>0){let l;n>i?l=n+i-3:l=n-1;const c=[];for(let p=l;p<l+o;++p)c.push(p);a=a.squeeze(c)}return a.shape.length===1&&(a=a.expandDims(1)),a})}class fm extends la{constructor(e){super(e);this.axes=e.axes,this.normalize=e.normalize==null?!1:e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){N.assert(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],s=e[1];if(t.length>3||s.length>3)throw new ae("Dot layer does not support tensors of 4D or higher rank yet.");const n=this.interpretAxes(t,s);if(t[n[0]]!==s[n[1]])throw new k(`Dimension incompatibility: ${t[n[0]]} !== ${s[n[1]]}`)}mergeFunction(e){if(e.length!==2)throw new k(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t=e[0],s=e[1],n;return Array.isArray(this.axes)?n=this.axes.map((i,r)=>lu(i,e[r].shape.length)):n=[lu(this.axes,t.shape.length),lu(this.axes,s.shape.length)],this.normalize&&(t=Gp(t,n[0]),s=Gp(s,n[1])),oz(t,s,n)}interpretAxes(e,t){let s;return Array.isArray(this.axes)?s=this.axes:s=[lu(this.axes,e.length),lu(this.axes,t.length)],s}computeOutputShape(e){N.assert(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(),s=e[1].slice();if(t.length>3||s.length>3)throw new ae("Dot layer does not support tensors of 4D or higher rank yet.");const n=this.interpretAxes(t,s);t.splice(n[0],1),s.splice(n[1],1),s.splice(0,1);const i=t.concat(s);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}}fm.className="Dot";V.registerClass(fm);class gm extends Le{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 C(()=>{this.invokeCallHook(e,t);const s=we(e),n=()=>Il(s.shape,0,this.stddev).add(s),i=Zr(n,()=>s,t.training||!1);return i})}}gm.className="GaussianNoise";V.registerClass(gm);class ym extends Le{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 C(()=>{this.invokeCallHook(e,t);const s=we(e);if(this.rate>0&&this.rate<1){const n=()=>{const i=Math.sqrt(this.rate/(1-this.rate));return s.mul(Il(s.shape,1,i))};return Zr(n,()=>s,t.training||!1)}return s})}}ym.className="GaussianDropout";V.registerClass(ym);class bm extends Le{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||we(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 C(()=>{if(this.rate<1&&this.rate>0){const s=this._getNoiseShape(e),n=()=>{const i=we(e),r=1.6732632423543772,o=1.0507009873554805,a=-r*o;let l=ds(fn(s),this.rate);l=zi(l,"float32");const c=((1-this.rate)*(1+this.rate*a**2))**-.5,p=-c*a*this.rate,u=i.mul(l).add(l.add(-1).mul(a));return u.mul(c).add(p)};return Zr(n,()=>we(e),t.training||!1)}return e})}}bm.className="AlphaDropout";V.registerClass(bm);function cu(e,t,s,n,i,r=.001){let o;if(e.rank===2)o=uh(e,t,s,n,i,r);else if(e.rank===3)o=hh(e,t,s,n,i,r);else if(e.rank===4)o=dh(e,t,s,n,i,r);else throw new ae(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return o}function az(e,t,s,n,i=.001){return C(()=>{const r=Bo(e,n),o=r.mean,a=r.variance,l=cu(e,o,a,s,t,i);return[l,o,a]})}function lz(e,t,s,n,i=.001){return C(()=>{const r=Bo(e,n),o=r.mean,a=r.variance,l=[];for(const m of ls(0,e.rank))n.indexOf(m)!==-1?l.push(1):l.push(e.shape[m]);const c=o.reshape(l),p=a.reshape(l),u=t==null?null:t.reshape(l),h=s==null?null:s.reshape(l),d=cu(e,c,p,h,u,i);return[d,o,a]})}function cz(e,t,s,n,i=.001){return N.arraysEqual(n.slice().sort(),ls(0,e.rank-1))?az(e,t,s,n,i):lz(e,t,s,n,i)}class wm extends Le{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=Be(e.betaInitializer||"zeros"),this.gammaInitializer=Be(e.gammaInitializer||"ones"),this.movingMeanInitializer=Be(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=Be(e.movingVarianceInitializer||"ones"),this.betaConstraint=rt(e.betaConstraint),this.gammaConstraint=rt(e.gammaConstraint),this.betaRegularizer=He(e.betaRegularizer),this.gammaRegularizer=He(e.gammaRegularizer)}build(e){e=Ue(e);const t=this.axis>=0?this.axis:this.axis+e.length,s=e[t];if(s==null)throw new k(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new st({ndim:e.length,axes:{[t]:s}})];const n=[s];this.scale&&(this.gamma=this.addWeight("gamma",n,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",n,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",n,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",n,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return C(()=>{const s=t.training==null?!1:t.training,n=we(e),i=n.shape,r=i.length,o=ls(0,r),a=this.axis>=0?this.axis:this.axis+r;o.splice(a,1);const l=wn(1,r);l[a]=i[a];const c=o.slice();c.sort();const p=!N.arraysEqual(c,ls(0,r).slice(0,r-1)),u=()=>{if(p){const y=this.movingMean.read().reshape(l),w=this.movingVariance.read().reshape(l),x=this.center?this.beta.read().reshape(l):null,T=this.scale?this.gamma.read().reshape(l):null;return cu(n,y,w,x,T,this.epsilon)}else return cu(n,this.movingMean.read(),this.movingVariance.read(),this.beta==null?null:this.beta.read(),this.gamma==null?null:this.gamma.read(),this.epsilon)};if(!s)return u();const[h,d,m]=cz(n,this.gamma.read(),this.beta.read(),o,this.epsilon),f=(y,w,x)=>{C(()=>{const T=1-x,A=y.read(),_=A.sub(w).mul(T);y.write(A.sub(_))})},g=()=>{f(this.movingMean,d,this.momentum),f(this.movingVariance,m,this.momentum)};return g(),h})}getConfig(){const e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Je(this.betaInitializer),gammaInitializer:Je(this.gammaInitializer),movingMeanInitializer:Je(this.movingMeanInitializer),movingVarianceInitializer:Je(this.movingVarianceInitializer),betaRegularizer:Pe(this.betaRegularizer),gammaRegularizer:Pe(this.gammaRegularizer),betaConstraint:it(this.betaConstraint),gammaConstraint:it(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}}wm.className="BatchNormalization";V.registerClass(wm);class xm extends Le{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=Be(e.betaInitializer||"zeros"),this.gammaInitializer=Be(e.gammaInitializer||"ones"),this.betaRegularizer=He(e.betaRegularizer),this.gammaRegularizer=He(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=Ue(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!==Sn(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);const s=this.axis.map(i=>e[i]),n=!0;this.scale?this.gamma=this.addWeight("gamma",s,"float32",this.gammaInitializer,this.gammaRegularizer,n):this.gamma=null,this.center?this.beta=this.addWeight("beta",s,"float32",this.betaInitializer,this.betaRegularizer,n):this.beta=null,this.built=!0}call(e,t){const s=we(e),n=s.shape,i=n.length;return C(()=>{const r=!0;let{mean:o,variance:a}=Bo(s,this.axis,r);const l=wn(1,i);for(const m of this.axis)l[m]=n[m];const c=m=>m!=null&&m.shape.length!==i&&this.axis!==[i-1]?m.reshape(l):m;let p=c(this.gamma.read()),u=c(this.beta.read());const h=[],d=[];for(let m=0;m<i;++m)this.axis.indexOf(m)!==-1?(h.push(n[m]),d.push(1)):(h.push(1),d.push(n[m]));return o=o.tile(h),a=a.tile(h),p=p.tile(d),u=u.tile(d),cu(s,o,a,u,p,this.epsilon)})}getConfig(){const e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Je(this.betaInitializer),gammaInitializer:Je(this.gammaInitializer),betaRegularizer:Pe(this.betaRegularizer),gammaRegularizer:Pe(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}}xm.className="LayerNormalization";V.registerClass(xm);function pz(e,t,s){return C(()=>{if(e.rank!==4)throw new k(`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 k("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(s==null&&(s=gs()),s!=="channelsLast"&&s!=="channelsFirst")throw new k(`Unknown data format: ${s}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let n;return s==="channelsFirst"?n=[[0,0],[0,0],t[0],t[1]]:n=[[0,0],t[0],t[1],[0,0]],Pt(e,n)})}class Lm extends Le{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?gs():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 k(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,s;if(typeof e.padding[0]=="number")t=[e.padding[0],e.padding[0]],s=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,e.padding[0].length!==2)throw new k(`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 k(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);s=e.padding[1]}this.padding=[t,s]}this.inputSpec=[new st({ndim:4})]}computeOutputShape(e){e=Ue(e);let t,s;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?s=e[3]+this.padding[1][0]+this.padding[1][1]:s=null,[e[0],e[1],t,s]):(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?s=e[2]+this.padding[1][0]+this.padding[1][1]:s=null,[e[0],t,s,e[3]])}call(e,t){return C(()=>pz(we(e),this.padding,this.dataFormat))}getConfig(){const e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}Lm.className="ZeroPadding2D";V.registerClass(Lm);function Sm(e,t,s,n,i,r){return C(()=>{ot(i),ob(r),ys(n),s==null&&(s=[1,1]),n==null&&(n="valid"),i==null&&(i=gs()),r==null&&(r="max"),e=Qp(e,i);let o;const a=n==="same"?"same":"valid";return r==="max"?o=mt(e,t,s,a):o=hs(e,t,s,a),i==="channelsFirst"&&(o=se(o,[0,3,1,2])),o})}function MA(e,t,s,n,i,r){return C(()=>{ot(i),ob(r),ys(n),s==null&&(s=[1,1,1]),n==null&&(n="valid"),i==null&&(i=gs()),r==null&&(r="max"),e=vb(e,i);let o;const a=n==="same"?"same":"valid";return r==="max"?o=cl(e,t,s,a):o=Za(e,t,s,a),i==="channelsFirst"&&(o=se(o,[0,4,1,2,3])),o})}class UA extends Le{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 k(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(gt(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 k(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);gt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,ys(this.padding),this.inputSpec=[new st({ndim:3})]}computeOutputShape(e){e=Ue(e);const t=Ns(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return C(()=>{this.invokeCallHook(e,t),e=Pi(we(e),2);const s=this.poolingFunction(we(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Js(s,[2])})}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class Im extends UA{constructor(e){super(e)}poolingFunction(e,t,s,n,i){return ot(i),ys(n),Sm(e,t,s,n,i,"max")}}Im.className="MaxPooling1D";V.registerClass(Im);class vm extends UA{constructor(e){super(e)}poolingFunction(e,t,s,n,i){return ot(i),ys(n),Sm(e,t,s,n,i,"avg")}}vm.className="AveragePooling1D";V.registerClass(vm);class $A extends Le{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 k(`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];gt(this.poolSize,"poolSize"),gt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,ot(this.dataFormat),ys(this.padding),this.inputSpec=[new st({ndim:4})]}computeOutputShape(e){e=Ue(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],s=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=Ns(t,this.poolSize[0],this.padding,this.strides[0]),s=Ns(s,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,s]:[e[0],t,s,e[3]]}call(e,t){return C(()=>(this.invokeCallHook(e,t),this.poolingFunction(we(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 Tm extends $A{constructor(e){super(e)}poolingFunction(e,t,s,n,i){return ot(i),ys(n),Sm(e,t,s,n,i,"max")}}Tm.className="MaxPooling2D";V.registerClass(Tm);class Am extends $A{constructor(e){super(e)}poolingFunction(e,t,s,n,i){return ot(i),ys(n),Sm(e,t,s,n,i,"avg")}}Am.className="AveragePooling2D";V.registerClass(Am);class WA extends Le{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 k(`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];gt(this.poolSize,"poolSize"),gt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,ot(this.dataFormat),ys(this.padding),this.inputSpec=[new st({ndim:5})]}computeOutputShape(e){e=Ue(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],s=this.dataFormat==="channelsFirst"?e[3]:e[2],n=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=Ns(t,this.poolSize[0],this.padding,this.strides[0]),s=Ns(s,this.poolSize[1],this.padding,this.strides[1]),n=Ns(n,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,s,n]:[e[0],t,s,n,e[4]]}call(e,t){return C(()=>(this.invokeCallHook(e,t),this.poolingFunction(we(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 Nm extends WA{constructor(e){super(e)}poolingFunction(e,t,s,n,i){return ot(i),ys(n),MA(e,t,s,n,i,"max")}}Nm.className="MaxPooling3D";V.registerClass(Nm);class Cm extends WA{constructor(e){super(e)}poolingFunction(e,t,s,n,i){return ot(i),ys(n),MA(e,t,s,n,i,"avg")}}Cm.className="AveragePooling3D";V.registerClass(Cm);class zA extends Le{constructor(e){super(e);this.inputSpec=[new st({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new ae}}class Rm extends zA{constructor(e){super(e||{})}call(e,t){return C(()=>{const s=we(e);return Ke(s,1)})}}Rm.className="GlobalAveragePooling1D";V.registerClass(Rm);class Om extends zA{constructor(e){super(e||{})}call(e,t){return C(()=>{const s=we(e);return xt(s,1)})}}Om.className="GlobalMaxPooling1D";V.registerClass(Om);class PA extends Le{constructor(e){super(e);this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,ot(this.dataFormat),this.inputSpec=[new st({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new ae}getConfig(){const e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class Em extends PA{call(e,t){return C(()=>{const s=we(e);return this.dataFormat==="channelsLast"?Ke(s,[1,2]):Ke(s,[2,3])})}}Em.className="GlobalAveragePooling2D";V.registerClass(Em);class _m extends PA{call(e,t){return C(()=>{const s=we(e);return this.dataFormat==="channelsLast"?xt(s,[1,2]):xt(s,[2,3])})}}_m.className="GlobalMaxPooling2D";V.registerClass(_m);class BA extends Le{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,s={}){const n=t.layer,i=xs(n,s);delete t.layer;const r={layer:i};return Object.assign(r,t),new e(r)}}class km extends BA{constructor(e){super(e);this.supportsMasking=!0}build(e){if(e=Ue(e),e.length<3)throw new k(`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=Ue(e);const t=[e[0]].concat(e.slice(2)),s=this.layer.computeOutputShape(t),n=e[1];return[s[0],n].concat(s.slice(1))}call(e,t){return C(()=>{e=we(e);const s=(r,o)=>{const a=we(this.layer.call(r,t));return[a,[]]},n=Ab(s,e,[],!1,null,null,!1,!0),i=n[1];return i})}}km.className="TimeDistributed";V.registerClass(km);function uz(e){Wi(NT,"BidirectionalMergeMode",e)}const hz="concat";class Dm extends BA{constructor(e){super(e);const t=e.layer.getConfig(),s={};s.className=e.layer.getClassName(),s.config=t,this.forwardLayer=xs(s),t.goBackwards=!(t.goBackwards===!0);const n={};if(n.className=e.layer.getClassName(),n.config=t,this.backwardLayer=xs(n),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?hz:e.mergeMode,uz(this.mergeMode),e.weights)throw new ae("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,s=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,s)),this.backwardLayer.setWeights(e.slice(s))}computeOutputShape(e){let t=this.forwardLayer.computeOutputShape(e);Array.isArray(t)&&Array.isArray(t[0])||(t=[t]),t=t;let s,n,i;return this.returnState&&(i=t.slice(1)),s=t[0],s=s,this.mergeMode==="concat"?(s[s.length-1]*=2,n=[s]):this.mergeMode==null?n=[s,s.slice()]:n=[s],this.returnState?this.mergeMode==null?n.concat(i).concat(i.slice()):[s].concat(i).concat(i.slice()):jt(n)}apply(e,t){let s=t==null?null:t.initialState,n=t==null?null:t.constants;t==null&&(t={});const i=Tb(e,s,n,this.numConstants);if(e=i.inputs,s=i.initialState,n=i.constants,Array.isArray(e)&&(s=e.slice(1),e=e[0]),(s==null||s.length===0)&&n==null)return super.apply(e,t);const r=[],o=[];if(s!=null){const l=s.length;if(l%2>0)throw new k("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=s,r.push(...s);const c=s.map(p=>new st({shape:p.shape}));this.forwardLayer.stateSpec=c.slice(0,l/2),this.backwardLayer.stateSpec=c.slice(l/2),o.push(...c)}if(n!=null)throw new ae("Support for constants in Bidirectional layers is not implemented yet.");const a=r[0]instanceof ws;for(const l of r)if(l instanceof ws!==a)throw new k("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(a){const l=[e].concat(r),c=this.inputSpec.concat(o),p=this.inputSpec;this.inputSpec=c;const u=super.apply(l,t);return this.inputSpec=p,u}else return super.apply(e,t)}call(e,t){return C(()=>{const s=t.initialState;let n,i;if(s==null)n=this.forwardLayer.call(e,t),i=this.backwardLayer.call(e,t);else{const a=s.slice(0,s.length/2),l=s.slice(s.length/2);n=this.forwardLayer.call(e,Object.assign(t,{initialState:a})),i=this.backwardLayer.call(e,Object.assign(t,{initialState:l}))}let r;this.returnState&&(Array.isArray(n)&&(r=n.slice(1).concat(i.slice(1))),n=n[0],i=i[0]),this.returnSequences&&(i=Et(i,1));let o;return this.mergeMode==="concat"?o=Sl([n,i]):this.mergeMode==="sum"?o=$(n,i):this.mergeMode==="ave"?o=R(.5,$(n,i)):this.mergeMode==="mul"?o=R(n,i):this.mergeMode==null&&(o=[n,i]),this.returnState?this.mergeMode==null?o.concat(r):[o].concat(r):o})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){Mn(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),Mn(this.backwardLayer.name,()=>{this.backwardLayer.build(e)}),this.built=!0}computeMask(e,t){Array.isArray(t)&&(t=t[0]);let s;if(this.returnSequences?this.mergeMode==null?s=[t,t]:s=t:this.mergeMode==null?s=[null,null]:s=null,this.returnState){const n=this.forwardLayer.states,i=n.map(r=>null);return Array.isArray(s)?s.concat(i).concat(i):[s].concat(i).concat(i)}else return s}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 s=xs(t.layer);if(delete t.layer,t.numConstants!=null)throw new ae("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const n=t;return n.layer=s,new e(n)}}Dm.className="Bidirectional";V.registerClass(Dm);const Nb={};Ee(Nb,{Layer:()=>Le,RNN:()=>sn,RNNCell:()=>ro,activation:()=>Cz,add:()=>Uz,alphaDropout:()=>xP,average:()=>$z,averagePooling1d:()=>Cb,averagePooling2d:()=>Rb,averagePooling3d:()=>Ob,avgPool1d:()=>Hz,avgPool2d:()=>Kz,avgPool3d:()=>Jz,avgPooling1d:()=>Yz,avgPooling2d:()=>Xz,avgPooling3d:()=>Zz,batchNormalization:()=>Vz,bidirectional:()=>hP,concatenate:()=>Wz,conv1d:()=>xz,conv2d:()=>Lz,conv2dTranspose:()=>Sz,conv3d:()=>Iz,convLstm2d:()=>lP,convLstm2dCell:()=>cP,cropping2D:()=>Tz,dense:()=>Rz,depthwiseConv2d:()=>Nz,dot:()=>jz,dropout:()=>Oz,elu:()=>mz,embedding:()=>Mz,flatten:()=>_z,gaussianDropout:()=>wP,gaussianNoise:()=>bP,globalAveragePooling1d:()=>Qz,globalAveragePooling2d:()=>eP,globalMaxPool1d:()=>mP,globalMaxPool2d:()=>fP,globalMaxPooling1d:()=>jA,globalMaxPooling2d:()=>VA,gru:()=>sP,gruCell:()=>nP,input:()=>Md,inputLayer:()=>dz,layerNormalization:()=>Gz,leakyReLU:()=>gz,lstm:()=>iP,lstmCell:()=>rP,masking:()=>LP,maxPool1d:()=>gP,maxPool2d:()=>yP,maxPooling1d:()=>GA,maxPooling2d:()=>qA,maxPooling3d:()=>tP,maximum:()=>zz,minimum:()=>Pz,multiply:()=>Bz,permute:()=>Fz,prelu:()=>yz,reLU:()=>fz,repeatVector:()=>kz,reshape:()=>Dz,rnn:()=>pP,separableConv2d:()=>vz,simpleRNN:()=>oP,simpleRNNCell:()=>aP,softmax:()=>bz,spatialDropout1d:()=>Ez,stackedRNNCells:()=>uP,thresholdedReLU:()=>wz,timeDistributed:()=>dP,upSampling2d:()=>Az,zeroPadding2d:()=>qz});function dz(e){return new ji(e)}function mz(e){return new Pd(e)}function fz(e){return new $d(e)}function gz(e){return new Wd(e)}function yz(e){return new zd(e)}function bz(e){return new jd(e)}function wz(e){return new Bd(e)}function xz(e){return new su(e)}function Lz(e){return new kl(e)}function Sz(e){return new Gd(e)}function Iz(e){return new tu(e)}function vz(e){return new qd(e)}function Tz(e){return new Hd(e)}function Az(e){return new Yd(e)}function Nz(e){return new Kd(e)}function Cz(e){return new nm(e)}function Rz(e){return new tm(e)}function Oz(e){return new au(e)}function Ez(e){return new em(e)}function _z(e){return new sm(e)}function kz(e){return new im(e)}function Dz(e){return new rm(e)}function Fz(e){return new om(e)}function Mz(e){return new lm(e)}function Uz(e){return new cm(e)}function $z(e){return new um(e)}function Wz(e){return new mm(e)}function zz(e){return new hm(e)}function Pz(e){return new dm(e)}function Bz(e){return new pm(e)}function jz(e){return new fm(e)}function Vz(e){return new wm(e)}function Gz(e){return new xm(e)}function qz(e){return new Lm(e)}function Cb(e){return new vm(e)}function Hz(e){return Cb(e)}function Yz(e){return Cb(e)}function Rb(e){return new Am(e)}function Kz(e){return Rb(e)}function Xz(e){return Rb(e)}function Ob(e){return new Cm(e)}function Jz(e){return Ob(e)}function Zz(e){return Ob(e)}function Qz(e){return new Rm(e)}function eP(e){return new Em(e)}function jA(e){return new Om(e)}function VA(e){return new _m(e)}function GA(e){return new Im(e)}function qA(e){return new Tm(e)}function tP(e){return new Nm(e)}function sP(e){return new Jd(e)}function nP(e){return new ru(e)}function iP(e){return new Zd(e)}function rP(e){return new aa(e)}function oP(e){return new Xd(e)}function aP(e){return new iu(e)}function lP(e){return new Qd(e)}function cP(e){return new ou(e)}function pP(e){return new sn(e)}function uP(e){return new nu(e)}function hP(e){return new Dm(e)}function dP(e){return new km(e)}const mP=jA,fP=VA,gP=GA,yP=qA;function bP(e){return new gm(e)}function wP(e){return new ym(e)}function xP(e){return new bm(e)}function LP(e){return new am(e)}const Eb={};Ee(Eb,{MAPE:()=>_P,MSE:()=>FP,binaryAccuracy:()=>SP,binaryCrossentropy:()=>IP,categoricalAccuracy:()=>TP,categoricalCrossentropy:()=>AP,cosineProximity:()=>RP,mape:()=>kP,meanAbsoluteError:()=>OP,meanAbsolutePercentageError:()=>EP,meanSquaredError:()=>DP,mse:()=>MP,precision:()=>NP,recall:()=>CP,sparseCategoricalAccuracy:()=>vP});function SP(e,t){return Yp(e,t)}function IP(e,t){return Ad(e,t)}function vP(e,t){return Nd(e,t)}function TP(e,t){return Kp(e,t)}function AP(e,t){return Xp(e,t)}function NP(e,t){return fb(e,t)}function CP(e,t){return GT(e,t)}function RP(e,t){return qp(e,t)}function OP(e,t){return Cl(e,t)}function EP(e,t){return eo(e,t)}function _P(e,t){return eo(e,t)}function kP(e,t){return eo(e,t)}function DP(e,t){return mi(e,t)}function FP(e,t){return mi(e,t)}function MP(e,t){return mi(e,t)}const _b={};Ee(_b,{modelFromJSON:()=>pA});const kb={};Ee(kb,{l1:()=>$P,l1l2:()=>UP,l2:()=>WP});function UP(e){return new _l(e)}function $P(e){return RA(e)}function WP(e){return OA(e)}class Db extends na{constructor(){super(...arguments);this.model=null}setModel(e){if(!(e instanceof tn))throw new Error("model must be a LayersModel, not some other Container");this.model=e}}function Fm(e,t){return e<t}function HA(e,t){return e>t}class Fb extends Db{constructor(e){super();if(e==null&&(e={}),e.restoreBestWeights)throw new ae("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=Fm:this.mode==="max"?this.monitorFunc=HA:this.monitor.indexOf("acc")!==-1?this.monitorFunc=HA:this.monitorFunc=Fm,this.monitorFunc===Fm&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Fm?Infinity:-Infinity}async onEpochEnd(e,t){await di(t);const s=this.getMonitorValue(t);if(s==null)return;this.monitorFunc(s-this.minDelta,this.best)?(this.best=s,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 zP(e){return new Fb(e)}const YA={earlyStopping:zP};var Tn;(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"})(Tn||(Tn={}));var KA;(function(e){let t;(function(s){s[s.LEGACY=0]="LEGACY",s[s.V1=1]="V1",s[s.V2=2]="V2"})(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))})(KA||(KA={}));const Mb={};function XA(e,t){const s={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};Mb[e]=s}function Mm(e){return Mb[e]}function JA(e){delete Mb[e]}function L(e,t,s,n){const i=t.inputParams[e];if(i&&i.inputIndexStart!==void 0){const o=i.inputIndexStart,a=i.inputIndexEnd===0?void 0:i.inputIndexEnd===void 0?o+1:i.inputIndexEnd;if(i.type==="tensor")return Vt(t.inputNames[i.inputIndexStart],s,n);if(i.type==="tensors"){const p=t.inputNames.slice(o,a);return p.map(u=>Vt(u,s,n))}const l=Vt(t.inputNames.slice(o)[0],s,n),c=l.dataSync();return i.type==="number"?c[0]:N.toNestedArray(l.shape,c)}const r=t.attrParams[e];return r&&r.value}function Vt(e,t,s){const[n,i]=Ls(e),r=s.currentContextIds.find(o=>!!t[Um(n,o)]);return r!==void 0?t[Um(n,r)][i]:void 0}function ZA(e,t,s){return t[Um(e,s.currentContextId)]}function Pn(e,t){const[s,n]=Ls(e);return[Um(s,t&&t.currentContextId),n]}function Um(e,t){return t?`${e}-${t}`:e}function Ls(e){const t=e.split(":");if(t.length===1)return[e,0];const s=t[0];return[s,Number(t[t.length-1])]}function pu(e,t,s){let n=L("pad",e,t,s);if(n==="explicit"){n=L("explicitPaddings",e,t,s);const i=[[0,0],[0,0],[0,0],[0,0]];for(let r=0;r<4;r++)i[r][0]=n[r*2],i[r][1]=n[r*2+1];return i}return n}function Bn(e){return e.kept?e:Ds(e)}const Ub={};Ee(Ub,{json:()=>PP});const PP=[{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}]}];const $b={};Ee($b,{json:()=>BP});const BP=[{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}]}];const Wb={};Ee(Wb,{json:()=>jP});const jP=[{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"}]}];const zb={};Ee(zb,{json:()=>VP});const VP=[{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"}]}];const Pb={};Ee(Pb,{json:()=>GP});const GP=[{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"}]}];const Bb={};Ee(Bb,{json:()=>qP});const qP=[{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}]}];const jb={};Ee(jb,{json:()=>HP});const HP=[{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"}]}];const Vb={};Ee(Vb,{json:()=>YP});const YP=[{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"}]}];const Gb={};Ee(Gb,{json:()=>KP});const KP=[{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"}]}];const qb={};Ee(qb,{json:()=>XP});const XP=[{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}]}];const Hb={};Ee(Hb,{json:()=>JP});const JP=[{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}]}];const Yb={};Ee(Yb,{json:()=>ZP});const ZP=[{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}]}];const Kb={};Ee(Kb,{json:()=>QP});const QP=[{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"}]}];const Xb={};Ee(Xb,{json:()=>eB});const eB=[{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}]}];const Jb={};Ee(Jb,{json:()=>tB});const tB=[{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}]}];const Zb={};Ee(Zb,{json:()=>sB});const sB=[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]}];class ew{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[Ub,$b,Wb,zb,Pb,Bb,jb,qb,Gb,Vb,Hb,Yb,Kb,Xb,Jb,Zb],t=[].concat(...e.map(s=>s.json));this.opMappers=t.reduce((s,n)=>(s[n.tfOpName]=n,s),{})}transformGraph(e,t={}){const s=e.node,n=[],i=[],r=[],o=s.reduce((m,f)=>(m[f.name]=this.mapNode(f),f.op.startsWith("Placeholder")?n.push(m[f.name]):f.op==="Const"?i.push(m[f.name]):(f.input==null||f.input.length===0)&&r.push(m[f.name]),m),{});let a=[];const l=[];let c={},p={};t!=null&&(c=this.mapSignatureEntries(t.inputs),p=this.mapSignatureEntries(t.outputs));const u=Object.keys(o);u.forEach(m=>{const f=o[m];f.inputNames.forEach(g=>{const[y]=Pn(g);f.inputs.push(o[y]),o[y].children.push(f)})}),Object.keys(p).length===0?u.forEach(m=>{const f=o[m];f.children.length===0&&l.push(f)}):Object.keys(p).forEach(m=>{const[f]=Pn(m),g=o[f];g!=null&&(g.signatureKey=p[m],l.push(g))}),Object.keys(c).length>0?Object.keys(c).forEach(m=>{const[f]=Pn(m),g=o[f];g&&(g.signatureKey=c[m],a.push(g))}):a=n;let h={};e.library!=null&&e.library.function!=null&&(h=e.library.function.reduce((m,f)=>(m[f.signature.name]=this.mapFunction(f),m),{}));const d={nodes:o,inputs:a,outputs:l,weights:i,placeholders:n,signature:t,functions:h};return r.length>0&&(d.initNodes=r),d}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,s)=>(t[e[s].name]=s,t),{})}mapNode(e){const t=Mm(e.op)||this.opMappers[e.op]||{};e.attr==null&&(e.attr={});const s={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(n=>n.startsWith("^")?n.substr(1):n),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr};return t.inputs!=null&&(s.inputParams=t.inputs.reduce((n,i)=>(n[i.name]={type:i.type,inputIndexStart:i.start,inputIndexEnd:i.end},n),{})),t.attrs!=null&&(s.attrParams=t.attrs.reduce((n,i)=>{const r=i.type;let o;switch(i.type){case"string":o=$m(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=$m(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"string[]":o=Gm(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=Gm(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"number":o=zm(e.attr,i.tfName,i.defaultValue||0),o===void 0&&!!i.tfDeprecatedName&&(o=zm(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"number[]":o=Vm(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=Vm(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"bool":o=Wm(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=Wm(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"bool[]":o=Hm(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=Hm(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"shape":o=jm(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=jm(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"shape[]":o=qm(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=qm(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"dtype":o=Pm(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=Pm(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"dtype[]":o=Bm(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=Bm(e.attr,i.tfDeprecatedName,i.defaultValue));break;case"func":o=QA(e.attr,i.tfName,i.defaultValue),o===void 0&&!!i.tfDeprecatedName&&(o=QA(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 n[i.name]={value:o,type:r},n},{})),s}mapFunction(e){const t=e.nodeDef,s=[],n=[];let i={};t!=null&&(i=t.reduce((p,u)=>(p[u.name]=this.mapNode(u),u.op==="Const"&&n.push(p[u.name]),p),{}));const r=[],o=[];e.signature.inputArg.forEach(p=>{const[u]=Pn(p.name),h={name:u,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:Qb(p.type),type:"dtype"}},children:[]};h.signatureKey=p.name,r.push(h),i[u]=h});const a=Object.keys(i);a.forEach(p=>{const u=i[p];u.inputNames.forEach(h=>{const[d]=Pn(h);u.inputs.push(i[d]),i[d].children.push(u)})});const l=e.ret;e.signature.outputArg.forEach(p=>{const[u,h]=Pn(l[p.name]),d=i[u];d!=null&&(d.defaultOutput=h,o.push(d))});const c=this.mapArgsToSignature(e);return{nodes:i,inputs:r,outputs:o,weights:n,placeholders:s,signature:c}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce((t,s)=>(t[s.name]=this.mapArgToTensorInfo(s),t),{}),outputs:e.signature.outputArg.reduce((t,s)=>(t[s.name]=this.mapArgToTensorInfo(s,e.ret),t),{})}}mapArgToTensorInfo(e,t){let s=e.name;return t!=null&&(s=t[s]),{name:s,dtype:e.type}}}function nB(e){const t=W().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 eN(e,t){const s=Array.isArray(e)?String.fromCharCode.apply(null,e):nB(e);return t?s:s.toLowerCase()}function $m(e,t,s,n=!1){const i=e[t];return i!=null?eN(i.s,n):s}function Wm(e,t,s){const n=e[t];return n?n.b:s}function zm(e,t,s){const n=e[t]||{},i=n.i!=null?n.i:n.f!=null?n.f:s;return typeof i=="number"?i:parseInt(i,10)}function Qb(e){typeof e=="string"&&(e=Tn[e]);switch(e){case Tn.DT_FLOAT:return"float32";case Tn.DT_INT32:case Tn.DT_INT64:case Tn.DT_INT8:case Tn.DT_UINT8:return"int32";case Tn.DT_BOOL:return"bool";case Tn.DT_DOUBLE:return"float32";case Tn.DT_STRING:return"string";default:return null}}function QA(e,t,s){const n=e[t];return n&&n.func?n.func.name:s}function Pm(e,t,s){const n=e[t];return n&&n.type?Qb(n.type):s}function Bm(e,t,s){const n=e[t];return n&&n.list&&n.list.type?n.list.type.map(i=>Qb(i)):s}function tN(e){return e.unknownRank?void 0:e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function jm(e,t,s){const n=e[t];return n&&n.shape?tN(n.shape):s}function Vm(e,t,s){const n=e[t];return n?((n.list.f&&n.list.f.length?n.list.f:n.list.i)||[]).map(i=>typeof i=="number"?i:parseInt(i,10)):s}function Gm(e,t,s,n=!1){const i=e[t];return i&&i.list&&i.list.s?i.list.s.map(r=>eN(r,n)):s}function qm(e,t,s){const n=e[t];return n&&n.list&&n.list.shape?n.list.shape.map(i=>tN(i)):s}function Hm(e,t,s){const n=e[t];return n&&n.list&&n.list.b?n.list.b:s}class sN{constructor(e,t,s){this.node=e,this.tensorMap=t,this.context=s,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(n=>this.getInput(n)),e.rawAttrs!=null&&(this.attrs=Object.keys(e.rawAttrs).reduce((n,i)=>(n[i]=this.getAttr(i),n),{}))}getInput(e){return Vt(e,this.tensorMap,this.context)}getAttr(e,t){const s=this.node.rawAttrs[e];if(s.tensor!=null)return Vt(e,this.tensorMap,this.context);if(s.i!=null||s.f!=null)return zm(this.node.rawAttrs,e,t);if(s.s!=null)return $m(this.node.rawAttrs,e,t);if(s.b!=null)return Wm(this.node.rawAttrs,e,t);if(s.shape!=null)return jm(this.node.rawAttrs,e,t);if(s.type!=null)return Pm(this.node.rawAttrs,e,t);if(s.list!=null){if(s.list.i!=null||s.list.f!=null)return Vm(this.node.rawAttrs,e,t);if(s.list.s!=null)return Gm(this.node.rawAttrs,e,t);if(s.list.shape!=null)return qm(this.node.rawAttrs,e,t);if(s.list.b!=null)return Hm(this.node.rawAttrs,e,t);if(s.list.type!=null)return Bm(this.node.rawAttrs,e,t)}return t}}const nN=(e,t,s)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[$(L("a",e,t,s),L("b",e,t,s))];case"AddN":return[sh(L("tensors",e,t,s))];case"FloorMod":case"Mod":return[pl(L("a",e,t,s),L("b",e,t,s))];case"Mul":return[R(L("a",e,t,s),L("b",e,t,s))];case"RealDiv":case"Div":return[Z(L("a",e,t,s),L("b",e,t,s))];case"DivNoNan":return[Sh(L("a",e,t,s),L("b",e,t,s))];case"FloorDiv":return[Ka(L("a",e,t,s),L("b",e,t,s))];case"Sub":return[X(L("a",e,t,s),L("b",e,t,s))];case"Minimum":return[mn(L("a",e,t,s),L("b",e,t,s))];case"Maximum":return[Ht(L("a",e,t,s),L("b",e,t,s))];case"Pow":return[Qt(L("a",e,t,s),L("b",e,t,s))];case"SquaredDifference":return[Yr(L("a",e,t,s),L("b",e,t,s))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};const iN=(e,t,s)=>{switch(e.op){case"Abs":case"ComplexAbs":return[et(L("x",e,t,s))];case"Acos":return[eh(L("x",e,t,s))];case"Acosh":return[th(L("x",e,t,s))];case"Asin":return[ih(L("x",e,t,s))];case"Asinh":return[rh(L("x",e,t,s))];case"Atan":return[oh(L("x",e,t,s))];case"Atan2":return[ah(L("x",e,t,s),L("y",e,t,s))];case"Atanh":return[lh(L("x",e,t,s))];case"Ceil":return[mh(L("x",e,t,s))];case"Complex":return[Gt(L("real",e,t,s),L("imag",e,t,s))];case"Cos":return[Wr(L("x",e,t,s))];case"Cosh":return[nl(L("x",e,t,s))];case"Elu":return[hn(L("x",e,t,s))];case"Erf":return[Ih(L("x",e,t,s))];case"Exp":return[ut(L("x",e,t,s))];case"Expm1":return[vh(L("x",e,t,s))];case"Floor":return[li(L("x",e,t,s))];case"Log":return[zt(L("x",e,t,s))];case"Log1p":return[ol(L("x",e,t,s))];case"Imag":return[dn(L("x",e,t,s))];case"Neg":return[_e(L("x",e,t,s))];case"Reciprocal":return[Dh(L("x",e,t,s))];case"Real":return[Xs(L("x",e,t,s))];case"Relu":return[De(L("x",e,t,s))];case"Round":return[Mh(L("x",e,t,s))];case"Selu":return[dl(L("x",e,t,s))];case"Sigmoid":return[rs(L("x",e,t,s))];case"Sin":return[ml(L("x",e,t,s))];case"Sign":return[$h(L("x",e,t,s))];case"Sinh":return[fl(L("x",e,t,s))];case"Softplus":return[pi(L("x",e,t,s))];case"Sqrt":return[Xe(L("x",e,t,s))];case"Square":return[xe(L("x",e,t,s))];case"Tanh":return[ki(L("x",e,t,s))];case"Tan":return[zh(L("x",e,t,s))];case"Relu6":case"ClipByValue":return[wt(L("x",e,t,s),L("clipValueMin",e,t,s),L("clipValueMax",e,t,s))];case"Rsqrt":return[hl(Vt(e.inputNames[0],t,s))];case"Prod":return[ul(L("x",e,t,s),L("axes",e,t,s))];case"LeakyRelu":return[rl(L("x",e,t,s),L("alpha",e,t,s))];case"Prelu":return[jr(L("x",e,t,s),L("alpha",e,t,s))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Ps(e,t,s=""){N.assert(iB(e,t),()=>s+` Shapes ${e} and ${t} must match`)}function iB(e,t){if(e.length!==t.length)return!1;for(let s=0;s<e.length;s++)if(e[s]!==-1&&t[s]!==-1&&e[s]!==t[s])return!1;return!0}class rN{constructor(e,t,s,n,i,r,o){this.name=e,this.dtype=t,this.maxSize=s,this.elementShape=n,this.identicalElementShapes=i,this.dynamicSize=r,this.clearAfterRead=o,this.tensors=[],this.closed_=!1,this.idTensor=j(0),pt(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 s=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},
because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=t.shape),Ps(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),s.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(s.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);s.tensor=t,pt(t),s.written=!0,this.tensors[e]=s}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((s,n)=>this.write(s,t[n]))}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 n=0;n<this.size();n++)e.push(n)}if(e.length===0)return ze([],[0].concat(this.elementShape));const s=this.readMany(e);return Ps(this.elementShape,s[0].shape,"TensorArray shape mismatch: "),Ve(s,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 ze([],[0].concat(this.elementShape));const t=[];for(let n=0;n<this.size();n++)t.push(n);const s=this.readMany(t);return Ps(this.elementShape,s[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${s[0].shape})`),be(s,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 s=Math.max(...e);if(!this.dynamicSize&&s>=this.maxSize)throw new Error(`Max index must be < array size (${s} vs. ${this.maxSize})`);this.writeMany(e,Ge(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 s=0;const n=e.map(a=>(s+=a,s));if(s!==t.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: ${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=s===0?0:t.size/s,r=[];C(()=>{t=O(t,[1,s,i]);for(let a=0;a<e.length;++a){const l=a===0?0:n[a-1],c=[0,l,0],p=[1,e[a],i];r[a]=O(he(t,c,p),this.elementShape)}return r});const o=[];for(let a=0;a<e.length;a++)o[a]=a;this.writeMany(o,r)}}class uu{constructor(e,t,s,n=-1){this.tensors=e,this.elementShape=t,this.elementDtype=s,e!=null&&e.forEach(i=>{if(s!==i.dtype)throw new Error(`Invalid data types; op elements ${s}, but list elements ${i.dtype}`);Ps(t,i.shape,"TensorList shape mismatch: "),pt(i)}),this.idTensor=j(0),this.maxNumElements=n,pt(this.idTensor)}get id(){return this.idTensor.id}copy(){return new uu([...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,s=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(s!==-1&&this.tensors.length!==s)throw new Error(`Operation expected a list with ${s} elements but got a list with ${this.tensors.length} elements.`);return Ps(e,this.elementShape,"TensorList shape mismatch: "),C(()=>{const n=this.tensors.map(i=>O(i,e));return Ve(n,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 s=this.tensors.pop();return Ps(s.shape,e,"TensorList shape mismatch: "),O(s,e)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Ps(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");pt(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,s){if(s!==this.elementDtype)throw new Error(`Invalid data types; op elements ${s}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(this.tensors[e]==null)throw new Error(`element at index ${e} is null.`);return Ps(this.tensors[e].shape,t,"TensorList shape mismatch: "),this.tensors[e]}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);Ps(this.elementShape,t.shape,"TensorList shape mismatch: "),pt(t),this.tensors[e]=t}gather(e,t,s){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);return Ps(this.elementShape,s,"TensorList shape mismatch: "),e=e.slice(0,this.size()),e.length===0?ze([],[0].concat(this.elementShape)):C(()=>{const n=e.map(i=>O(this.tensors[i],s));return Ve(n,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);return Ps(this.elementShape,t,"TensorList shape mismatch: "),this.size()===0?ze([],[0].concat(this.elementShape)):C(()=>{const s=this.tensors.map(n=>O(n,t));return be(s,0)})}}function oN(e,t,s){const n=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!==s)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${s}`);const i=e.shape.slice(1);Ps(i,t,"TensorList shape mismatch: ");const r=Ge(e);return new uu(r,t,n)}function aN(e,t,s){return new uu([],e,t,s)}function lN(e,t,s,n){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(n!=null&&n!==-1&&i>=n)throw new Error(`Max index must be < array size (${i} vs. ${n})`);const r=new uu([],s,e.dtype,n),o=Ge(e,0);return t.forEach((a,l)=>{r.setItem(a,o[l])}),r}function cN(e,t,s){let n=0;const i=t.map(l=>(n+=l,n));if(n!==e.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: ${e.shape}`);const r=n===0?0:e.size/n,o=C(()=>{const l=[];e=O(e,[1,n,r]);for(let c=0;c<t.length;++c){const p=c===0?0:i[c-1],u=[0,p,0],h=[1,t[c],r];l[c]=O(he(e,u,h),s)}return e.dispose(),l}),a=new uu([],s,e.dtype,t.length);for(let l=0;l<o.length;l++)a.setItem(l,o[l]);return a}const pN=async(e,t,s)=>{switch(e.op){case"If":case"StatelessIf":{const n=L("thenBranch",e,t,s),i=L("elseBranch",e,t,s),r=L("cond",e,t,s),o=L("args",e,t,s),a=await r.data();return a[0]?s.functionMap[n].executeFunctionAsync(o,s.tensorArrayMap,s.tensorListMap):s.functionMap[i].executeFunctionAsync(o,s.tensorArrayMap,s.tensorListMap)}case"While":case"StatelessWhile":{const n=L("body",e,t,s),i=L("cond",e,t,s),r=L("args",e,t,s),o=await s.functionMap[i].executeFunctionAsync(r,s.tensorArrayMap,s.tensorListMap),a=r.map(p=>p.id);let l=await o[0].data();o.forEach(p=>{!p.kept&&a.indexOf(p.id)===-1&&p.dispose()});let c=r;for(;l[0];){const p=c;c=await s.functionMap[n].executeFunctionAsync(c,s.tensorArrayMap,s.tensorListMap);const u=c.map(d=>d.id);p.forEach(d=>{!d.kept&&a.indexOf(d.id)===-1&&u.indexOf(d.id)===-1&&d.dispose()});const h=await s.functionMap[i].executeFunctionAsync(c,s.tensorArrayMap,s.tensorListMap);l=await h[0].data(),h.forEach(d=>{!d.kept&&a.indexOf(d.id)===-1&&u.indexOf(d.id)===-1&&d.dispose()})}return c}case"LoopCond":{const n=L("pred",e,t,s);return[Bn(n)]}case"Switch":{const n=L("pred",e,t,s);let i=L("data",e,t,s);return i.kept||(i=Bn(i)),(await n.data())[0]?[void 0,i]:[i,void 0]}case"Merge":{const n=e.inputNames.find(i=>Vt(i,t,s)!==void 0);if(n){const i=Vt(n,t,s);return[Bn(i)]}return}case"Enter":{const n=L("frameName",e,t,s),i=L("tensor",e,t,s);return s.enterFrame(n),[Bn(i)]}case"Exit":{const n=L("tensor",e,t,s);return s.exitFrame(),[Bn(n)]}case"NextIteration":{const n=L("tensor",e,t,s);return s.nextIteration(),[Bn(n)]}case"TensorArrayV3":{const n=L("size",e,t,s),i=L("dtype",e,t,s),r=L("elementShape",e,t,s),o=L("dynamicSize",e,t,s),a=L("clearAfterRead",e,t,s),l=L("identicalElementShapes",e,t,s),c=L("name",e,t,s),p=new rN(c,i,n,r,l,o,a);return s.addTensorArray(p),[p.idTensor,j(1)]}case"TensorArrayWriteV3":{const n=L("tensorArrayId",e,t,s),i=L("index",e,t,s),r=L("tensor",e,t,s),o=s.getTensorArray(n.id);return o.write(i,r),[o.idTensor]}case"TensorArrayReadV3":{const n=L("tensorArrayId",e,t,s),i=L("index",e,t,s),r=s.getTensorArray(n.id);return[r.read(i)]}case"TensorArrayGatherV3":{const n=L("tensorArrayId",e,t,s),i=L("indices",e,t,s),r=L("dtype",e,t,s),o=s.getTensorArray(n.id);return[o.gather(i,r)]}case"TensorArrayScatterV3":{const n=L("tensorArrayId",e,t,s),i=L("indices",e,t,s),r=L("tensor",e,t,s),o=s.getTensorArray(n.id);return o.scatter(i,r),[o.idTensor]}case"TensorArrayConcatV3":{const n=L("tensorArrayId",e,t,s),i=s.getTensorArray(n.id),r=L("dtype",e,t,s);return[i.concat(r)]}case"TensorArraySplitV3":{const n=L("tensorArrayId",e,t,s),i=L("tensor",e,t,s),r=L("lengths",e,t,s),o=s.getTensorArray(n.id);return o.split(r,i),[o.idTensor]}case"TensorArraySizeV3":{const n=L("tensorArrayId",e,t,s),i=s.getTensorArray(n.id);return[j(i.size(),"int32")]}case"TensorArrayCloseV3":{const n=L("tensorArrayId",e,t,s),i=s.getTensorArray(n.id);return i.clearAndClose(),[i.idTensor]}case"TensorListSetItem":{const n=L("tensorListId",e,t,s),i=L("index",e,t,s),r=L("tensor",e,t,s),o=s.getTensorList(n.id);return o.setItem(i,r),[o.idTensor]}case"TensorListGetItem":{const n=L("tensorListId",e,t,s),i=L("index",e,t,s),r=L("elementShape",e,t,s),o=L("elementDType",e,t,s),a=s.getTensorList(n.id);return[a.getItem(i,r,o)]}case"TensorListScatterV2":case"TensorListScatter":{const n=L("indices",e,t,s),i=L("tensor",e,t,s),r=L("elementShape",e,t,s),o=L("numElements",e,t,s),a=lN(i,n,r,o);return s.addTensorList(a),[a.idTensor]}case"TensorListReserve":{const n=L("elementShape",e,t,s),i=L("elementDType",e,t,s),r=L("numElements",e,t,s),o=aN(n,i,r);return s.addTensorList(o),[o.idTensor]}case"TensorListGather":{const n=L("tensorListId",e,t,s),i=L("indices",e,t,s),r=L("elementShape",e,t,s),o=L("elementDType",e,t,s),a=s.getTensorList(n.id);return[a.gather(i,o,r)]}case"TensorListStack":{const n=L("tensorListId",e,t,s),i=L("elementShape",e,t,s),r=L("elementDType",e,t,s),o=L("numElements",e,t,s),a=s.getTensorList(n.id);return[a.stack(i,r,o)]}case"TensorListFromTensor":{const n=L("tensor",e,t,s),i=L("elementShape",e,t,s),r=L("elementDType",e,t,s),o=oN(n,i,r);return s.addTensorList(o),[o.idTensor]}case"TensorListConcat":{const n=L("tensorListId",e,t,s),i=s.getTensorList(n.id),r=L("dtype",e,t,s),o=L("elementShape",e,t,s);return[i.concat(r,o)]}case"TensorListPushBack":{const n=L("tensorListId",e,t,s),i=L("tensor",e,t,s),r=s.getTensorList(n.id);return r.pushBack(i),[r.idTensor]}case"TensorListPopBack":{const n=L("tensorListId",e,t,s),i=L("elementShape",e,t,s),r=L("elementDType",e,t,s),o=s.getTensorList(n.id);return[o.popBack(i,r)]}case"TensorListSplit":{const n=L("tensor",e,t,s),i=L("elementShape",e,t,s),r=L("lengths",e,t,s),o=cN(n,r,i);return s.addTensorList(o),[o.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function uN(e,t,s){const[n,i]=L("fusedOps",e,t,s),r=n==="biasadd",o=i==="prelu",a=n==="fusedbatchnorm",l=L("numArgs",e,t,s);if(r){if(o&&l!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&l!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(a)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported.");const c=L("strides",e,t,s),p=pu(e,t,s),u=L("dataFormat",e,t,s).toUpperCase(),h=L("dilations",e,t,s),[d,m]=L("args",e,t,s);return{stride:c,pad:p,dataFormat:u,dilations:h,biasArg:d,preluArg:m,activationFunc:i}}const hN=(e,t,s)=>{switch(e.op){case"Conv1D":{const n=L("stride",e,t,s),i=L("pad",e,t,s),r=L("dataFormat",e,t,s).toUpperCase(),o=L("dilation",e,t,s);return[Qa(L("x",e,t,s),L("filter",e,t,s),n,i,r,o)]}case"Conv2D":{const n=L("strides",e,t,s),i=pu(e,t,s),r=L("dataFormat",e,t,s).toUpperCase(),o=L("dilations",e,t,s);return[nt(L("x",e,t,s),L("filter",e,t,s),[n[1],n[2]],i,r,[o[1],o[2]])]}case"_FusedConv2D":{const{stride:n,pad:i,dataFormat:r,dilations:o,biasArg:a,preluArg:l,activationFunc:c}=uN(e,t,s);return[gn.conv2d({x:L("x",e,t,s),filter:L("filter",e,t,s),strides:[n[1],n[2]],pad:i,dataFormat:r,dilations:[o[1],o[2]],bias:a,activation:c,preluActivationWeights:l})]}case"FusedDepthwiseConv2dNative":{const{stride:n,pad:i,dataFormat:r,dilations:o,biasArg:a,preluArg:l,activationFunc:c}=uN(e,t,s);return[gn.depthwiseConv2d({x:L("x",e,t,s),filter:L("filter",e,t,s),strides:[n[1],n[2]],pad:i,dataFormat:r,dilations:[o[1],o[2]],bias:a,activation:c,preluActivationWeights:l})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const n=L("outputShape",e,t,s),i=L("strides",e,t,s),r=pu(e,t,s);return[tl(L("x",e,t,s),L("filter",e,t,s),n,[i[1],i[2]],r)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const n=L("strides",e,t,s),i=pu(e,t,s),r=L("dilations",e,t,s),o=L("dataFormat",e,t,s).toUpperCase();return[un(L("input",e,t,s),L("filter",e,t,s),[n[1],n[2]],i,o,[r[1],r[2]])]}case"Conv3D":{const n=L("strides",e,t,s),i=L("pad",e,t,s),r=L("dataFormat",e,t,s).toUpperCase(),o=L("dilations",e,t,s);return[sl(L("x",e,t,s),L("filter",e,t,s),[n[1],n[2],n[3]],i,r,[o[1],o[2],o[3]])]}case"AvgPool":{const n=L("strides",e,t,s),i=L("pad",e,t,s),r=L("kernelSize",e,t,s);return[hs(L("x",e,t,s),[r[1],r[2]],[n[1],n[2]],i)]}case"MaxPool":{const n=L("strides",e,t,s),i=L("pad",e,t,s),r=L("kernelSize",e,t,s);return[mt(L("x",e,t,s),[r[1],r[2]],[n[1],n[2]],i)]}case"MaxPoolWithArgmax":{const n=L("strides",e,t,s),i=L("pad",e,t,s),r=L("kernelSize",e,t,s),o=L("includeBatchInIndex",e,t,s),{result:a,indexes:l}=Eh(L("x",e,t,s),[r[1],r[2]],[n[1],n[2]],i,o);return[a,l]}case"AvgPool3D":{const n=L("strides",e,t,s),i=L("pad",e,t,s),r=L("kernelSize",e,t,s);return[Za(L("x",e,t,s),[r[1],r[2],r[3]],[n[1],n[2],n[3]],i)]}case"MaxPool3D":{const n=L("strides",e,t,s),i=L("pad",e,t,s),r=L("kernelSize",e,t,s);return[cl(L("x",e,t,s),[r[1],r[2],r[3]],[n[1],n[2],n[3]],i)]}case"Dilation2D":{const n=L("strides",e,t,s),i=L("pad",e,t,s),r=L("dilations",e,t,s),o=n[1],a=n[2],l=r[1],c=r[2];return[Lh(L("x",e,t,s),L("filter",e,t,s),[o,a],i,[l,c],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const dN=(e,t,s)=>{switch(e.op){case"Fill":{const n=L("shape",e,t,s),i=L("dtype",e,t,s),r=L("value",e,t,s);return[Wt(n,r,i)]}case"LinSpace":{const n=L("start",e,t,s),i=L("stop",e,t,s),r=L("num",e,t,s);return[Ah(n,i,r)]}case"Multinomial":{const n=L("logits",e,t,s),i=L("numSamples",e,t,s),r=L("seed",e,t,s);return[_h(n,i,r)]}case"OneHot":{const n=L("indices",e,t,s),i=L("depth",e,t,s),r=L("onValue",e,t,s),o=L("offValue",e,t,s);return[ai(n,i,r,o)]}case"Ones":return[Kt(L("shape",e,t,s),L("dtype",e,t,s))];case"OnesLike":return[Ot(L("x",e,t,s))];case"RandomUniform":return[fn(L("shape",e,t,s),L("minval",e,t,s),L("maxval",e,t,s),L("dtype",e,t,s))];case"Range":{const n=L("start",e,t,s),i=L("stop",e,t,s),r=L("step",e,t,s);return[Fi(n,i,r,L("dtype",e,t,s))]}case"TruncatedNormal":{const n=L("shape",e,t,s),i=L("mean",e,t,s),r=L("stdDev",e,t,s),o=L("seed",e,t,s);return[Kr(n,i,r,L("dtype",e,t,s),o)]}case"Zeros":return[ye(L("shape",e,t,s),L("dtype",e,t,s))];case"ZerosLike":return[re(L("x",e,t,s))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function tw(e,t,s){const n=L("boxes",e,t,s),i=L("scores",e,t,s),r=L("maxOutputSize",e,t,s),o=L("iouThreshold",e,t,s),a=L("scoreThreshold",e,t,s),l=L("softNmsSigma",e,t,s);return{boxes:n,scores:i,maxOutputSize:r,iouThreshold:o,scoreThreshold:a,softNmsSigma:l}}const mN=async(e,t,s)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:n,scores:i,maxOutputSize:r,iouThreshold:o,scoreThreshold:a,softNmsSigma:l}=tw(e,t,s),c=await Zs.nonMaxSuppressionWithScoreAsync(n,i,r,o,a,l);return[c.selectedIndices,c.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:n,scores:i,maxOutputSize:r,iouThreshold:o,scoreThreshold:a}=tw(e,t,s),l=L("padToMaxOutputSize",e,t,s),c=await Zs.nonMaxSuppressionPaddedAsync(n,i,r,o,a,l);return[c.selectedIndices,c.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:n,scores:i,maxOutputSize:r,iouThreshold:o,scoreThreshold:a}=tw(e,t,s);return[await Zs.nonMaxSuppressionAsync(n,i,r,o,a)]}case"Where":{const n=G(L("condition",e,t,s),"bool"),i=[await bl(n)];return n.dispose(),i}case"ListDiff":return Uh(L("x",e,t,s),L("y",e,t,s));default:throw TypeError(`Node type ${e.op} is not implemented`)}};const fN=(e,t,s)=>{switch(e.op){case"TopKV2":{const n=L("x",e,t,s),i=L("k",e,t,s),r=L("sorted",e,t,s),o=Ph(n,i,r);return[o.values,o.indices]}case"Unique":{const n=L("x",e,t,s),i=Rp(n);return[i.values,i.indices]}case"UniqueV2":{const n=L("x",e,t,s),i=L("axis",e,t,s),r=Rp(n,i);return[r.values,r.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const gN=(e,t,s)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const n=L("default",e,t,s);return[Vt(e.name,t,s)||n];case"Placeholder":return[Vt(e.name,t,s)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{const c=L("x",e,t,s);return[Bn(c)]}case"IdentityN":return L("x",e,t,s).map(c=>Bn(c));case"Snapshot":const i=L("x",e,t,s);return[Bn(i)];case"Shape":return[Oe(L("x",e,t,s).shape,"int32")];case"ShapeN":return L("x",e,t,s).map(c=>Oe(c.shape));case"Size":return[j(L("x",e,t,s).size,"int32")];case"Rank":return[j(L("x",e,t,s).rank,"int32")];case"NoOp":return[j(1)];case"Print":const r=L("x",e,t,s),o=L("data",e,t,s),a=L("message",e,t,s),l=L("summarize",e,t,s);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(a);for(let c=0;c<o.length;c++)console.log(Array.prototype.slice.call(o[c].dataSync()).slice(0,l));return[r];default:throw TypeError(`Node type ${e.op} is not implemented`)}};const yN=(e,t,s)=>{switch(e.op){case"ResizeBilinear":{const n=L("images",e,t,s),i=L("size",e,t,s),r=L("alignCorners",e,t,s);return[Zs.resizeBilinear(n,[i[0],i[1]],r)]}case"ResizeNearestNeighbor":{const n=L("images",e,t,s),i=L("size",e,t,s),r=L("alignCorners",e,t,s);return[Zs.resizeNearestNeighbor(n,[i[0],i[1]],r)]}case"CropAndResize":{const n=L("image",e,t,s),i=L("boxes",e,t,s),r=L("boxInd",e,t,s),o=L("cropSize",e,t,s),a=L("method",e,t,s),l=L("extrapolationValue",e,t,s);return[Zs.cropAndResize(n,i,r,o,a,l)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const bN=(e,t,s)=>{switch(e.op){case"Equal":return[os(L("a",e,t,s),L("b",e,t,s))];case"NotEqual":return[Ks(L("a",e,t,s),L("b",e,t,s))];case"Greater":return[Ut(L("a",e,t,s),L("b",e,t,s))];case"GreaterEqual":return[ds(L("a",e,t,s),L("b",e,t,s))];case"Less":return[zr(L("a",e,t,s),L("b",e,t,s))];case"LessEqual":return[$s(L("a",e,t,s),L("b",e,t,s))];case"LogicalAnd":return[Yt(L("a",e,t,s),L("b",e,t,s))];case"LogicalNot":return[Pr(L("a",e,t,s))];case"LogicalOr":return[ll(L("a",e,t,s),L("b",e,t,s))];case"Select":case"SelectV2":return[dt(L("condition",e,t,s),L("a",e,t,s),L("b",e,t,s))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};const wN=(e,t,s)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[Te(L("a",e,t,s),L("b",e,t,s),L("transposeA",e,t,s),L("transposeB",e,t,s))];case"Transpose":return[se(L("x",e,t,s),L("perm",e,t,s))];case"_FusedMatMul":const[n,i]=L("fusedOps",e,t,s),r=n==="biasadd",o=i==="prelu",a=L("numArgs",e,t,s);if(r){if(o&&a!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&a!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}const[l,c]=L("args",e,t,s);return[gn.matMul({a:L("a",e,t,s),b:L("b",e,t,s),transposeA:L("transposeA",e,t,s),transposeB:L("transposeB",e,t,s),bias:l,activation:i,preluActivationWeights:c})];default:throw TypeError(`Node type ${e.op} is not implemented`)}};const xN=(e,t,s)=>{switch(e.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[Ys(L("x",e,t,s),L("mean",e,t,s),L("variance",e,t,s),L("offset",e,t,s),L("scale",e,t,s),L("epsilon",e,t,s))];case"FusedBatchNormV3":return[Ys(L("x",e,t,s),L("mean",e,t,s),L("variance",e,t,s),L("offset",e,t,s),L("scale",e,t,s),L("epsilon",e,t,s))];case"LRN":return[Nh(L("x",e,t,s),L("radius",e,t,s),L("bias",e,t,s),L("alpha",e,t,s),L("beta",e,t,s))];case"Softmax":return[es(L("x",e,t,s))];case"LogSoftmax":return[al(L("x",e,t,s))];case"SparseToDense":return[Ep(L("sparseIndices",e,t,s),L("outputShape",e,t,s),L("sparseValues",e,t,s),L("defaultValue",e,t,s))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};const LN=(e,t,s)=>{switch(e.op){case"Max":{const n=L("axis",e,t,s),i=L("keepDims",e,t,s);return[xt(L("x",e,t,s),n,i)]}case"Mean":{const n=L("axis",e,t,s),i=L("keepDims",e,t,s);return[Ke(L("x",e,t,s),n,i)]}case"Min":{const n=L("axis",e,t,s),i=L("keepDims",e,t,s);return[Di(L("x",e,t,s),n,i)]}case"Sum":{const n=L("axis",e,t,s),i=L("keepDims",e,t,s);return[te(L("x",e,t,s),n,i)]}case"All":{const n=L("axis",e,t,s),i=L("keepDims",e,t,s);return[Xa(L("x",e,t,s),n,i)]}case"Any":{const n=L("axis",e,t,s),i=L("keepDims",e,t,s);return[Uo(L("x",e,t,s),n,i)]}case"ArgMax":{const n=L("axis",e,t,s);return[$o(L("x",e,t,s),n)]}case"ArgMin":{const n=L("axis",e,t,s);return[nh(L("x",e,t,s),n)]}case"Prod":{const n=L("axis",e,t,s),i=L("keepDims",e,t,s);return[ul(L("x",e,t,s),n,i)]}case"Cumsum":{const n=L("axis",e,t,s),i=L("exclusive",e,t,s),r=L("reverse",e,t,s);return[il(L("x",e,t,s),n,i,r)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const SN=(e,t,s)=>{switch(e.op){case"ConcatV2":case"Concat":{const n=L("n",e,t,s),i=L("axis",e,t,s);let r=L("tensors",e,t,s);return r=r.slice(0,n),[be(r,i)]}case"GatherV2":case"Gather":{const n=L("axis",e,t,s),i=L("x",e,t,s),r=L("indices",e,t,s);return[ci(i,G(r,"int32"),n)]}case"ReverseV2":case"Reverse":{const n=L("axis",e,t,s),i=L("x",e,t,s);return[Et(i,n)]}case"Slice":{const n=L("begin",e,t,s),i=L("size",e,t,s);return[he(L("x",e,t,s),n,i)]}case"StridedSlice":{const n=L("begin",e,t,s),i=L("end",e,t,s),r=L("strides",e,t,s),o=L("beginMask",e,t,s),a=L("endMask",e,t,s),l=L("ellipsisMask",e,t,s),c=L("newAxisMask",e,t,s),p=L("shrinkAxisMask",e,t,s),u=L("x",e,t,s);return[Wh(u,n,i,r,o,a,l,c,p)]}case"Pack":return C(()=>{const n=L("axis",e,t,s),i=L("tensors",e,t,s),r=i[0].shape,o=Js(i[0]).shape,a=i.map(l=>{const c=N.arraysEqual(l.shape,r);if(!c&&!N.arraysEqual(Js(l).shape,o))throw new Error("the input tensors shape does not match");return c?l:O(l,r)});return[Ve(a,n)]});case"Unpack":{const n=L("axis",e,t,s),i=L("tensor",e,t,s);return Ge(i,n)}case"Tile":{const n=L("reps",e,t,s);return[Us(L("x",e,t,s),n)]}case"Split":case"SplitV":{const n=L("axis",e,t,s),i=L("numOrSizeSplits",e,t,s),r=L("x",e,t,s);return Bt(r,i,n)}case"ScatterNd":{const n=L("indices",e,t,s),i=L("values",e,t,s),r=L("shape",e,t,s);return[By(n,i,r)]}case"GatherNd":{const n=L("x",e,t,s),i=L("indices",e,t,s);return[jy(n,i)]}case"SparseToDense":{const n=L("sparseIndices",e,t,s),i=L("outputShape",e,t,s),r=L("sparseValues",e,t,s),o=L("defaultValue",e,t,s);return[Ep(n,r,i,r.dtype===o.dtype?o:G(o,r.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};const IN=(e,t,s)=>{switch(e.op){case"FFT":return[qr(L("x",e,t,s))];case"IFFT":return[Mi(L("x",e,t,s))];case"RFFT":return[Hr(L("x",e,t,s))];case"IRFFT":return[yl(L("x",e,t,s))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};const vN=(e,t,s)=>{switch(e.op){case"Cast":return[G(L("x",e,t,s),L("dtype",e,t,s))];case"ExpandDims":{const n=L("axis",e,t,s);return[Mt(L("x",e,t,s),n)]}case"Squeeze":{const n=L("axis",e,t,s);return[Js(L("x",e,t,s),n)]}case"Reshape":return[O(L("x",e,t,s),L("shape",e,t,s))];case"PadV2":case"Pad":return[Pt(L("x",e,t,s),L("padding",e,t,s),L("constantValue",e,t,s))];case"SpaceToBatchND":{const n=L("blockShape",e,t,s),i=L("paddings",e,t,s);return[Br(L("x",e,t,s),n,i)]}case"BatchToSpaceND":{const n=L("blockShape",e,t,s),i=L("crops",e,t,s);return[$r(L("x",e,t,s),n,i)]}case"DepthToSpace":{const n=L("blockSize",e,t,s),i=L("dataFormat",e,t,s).toUpperCase();return[xh(L("x",e,t,s),n,i)]}case"BroadcastTo":return[zo(L("x",e,t,s),L("shape",e,t,s))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function sw(e,t,s){const n=((i,r,o)=>{switch(i.category){case"arithmetic":return C(()=>nN(i,r,o));case"basic_math":return C(()=>iN(i,r,o));case"control":return pN(i,r,o);case"convolution":return C(()=>hN(i,r,o));case"creation":return C(()=>dN(i,r,o));case"dynamic":return mN(i,r,o);case"evaluation":return C(()=>fN(i,r,o));case"image":return C(()=>yN(i,r,o));case"graph":return C(()=>gN(i,r,o));case"logical":return C(()=>bN(i,r,o));case"matrices":return C(()=>wN(i,r,o));case"normalization":return C(()=>xN(i,r,o));case"reduction":return C(()=>LN(i,r,o));case"slice_join":return C(()=>SN(i,r,o));case"spectral":return C(()=>IN(i,r,o));case"transformation":return C(()=>vN(i,r,o));case"custom":const a=Mm(i.op);if(a&&a.customExecutor)return a.customExecutor(new sN(i,r,o));throw TypeError(`Custom op ${i.op} is not registered.`);default:throw TypeError(`Unknown op '${i.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(e,t,s);return n instanceof Promise?n.then(i=>[].concat(i)):[].concat(n)}class nw{constructor(e={},t={},s={},n={}){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=s,this.functionMap=n,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 s=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(s))}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 rw(e,t,s,n){const i=new Set,r=[];let o=null,a=null;const l=new Set,c=Object.keys(e).map(h=>Ls(h)[0]);let p=[];n!=null&&(p=n.map(h=>Ls(h.name)[0]));const u=[...t];for(;u.length>0;){const h=u.pop();if((iw(h)||rB(h))&&(o==null&&(o=h,a=o.children.map(d=>d.name).filter(d=>i.has(d)))),i.add(h.name),s[h.name]!=null)continue;if(c.indexOf(h.name)!==-1)continue;if(p.indexOf(h.name)!==-1)continue;if(h.inputs.length===0){r.push(h.name);continue}h.inputs.forEach(d=>{if(l.has(d.name))return;l.add(d.name),u.push(d)})}return{inputs:e,outputs:t,usedNodes:i,missingInputs:r,dynamicNode:o,syncInputs:a}}function TN(e,t,s){const{usedNodes:n,inputs:i}=s,r=[],o=Object.keys(i).map(p=>Ls(p)[0]).map(p=>e.nodes[p]),a=e.initNodes;o.forEach(p=>{n.has(p.name)&&r.push(p)}),e.weights.forEach(p=>{n.has(p.name)&&r.push(p)}),a!=null&&a.forEach(p=>{n.has(p.name)&&r.push(p)});const l=new Set,c=[];for(;r.length>0;){const p=r.pop();l.add(p.name),t[p.name]||c.push(p),p.children.forEach(u=>{!l.has(u.name)&&n.has(u.name)&&u.inputs.every(h=>l.has(h.name))&&r.push(u)})}return c}const oB=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],aB=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"];function iw(e){return oB.indexOf(e.op)>=0}function rB(e){return aB.indexOf(e.op)>=0}class Ym{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(s=>{this._functionExecutorMap[s]=new Ym(e.functions[s],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(s=>e[s].map(n=>n.id));this._weightIds=[].concat(...t),this._weightMap=e}get inputs(){return this._inputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(e=>e.signatureKey||e.name)}get outputNodes(){return this._outputs.map(e=>{const t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t})}get functions(){return Object.keys(this._functions).reduce((e,t)=>(e[t]=this._functions[t].signature,e),{})}getCompilationKey(e,t){const s=e.map(i=>i.name).sort(),n=t.map(i=>i.name).sort();return s.join(this.SEPERATOR)+"--"+n.join(this.SEPERATOR)}compile(e,t){const s=rw(e,t,this.weightMap,this._initNodes),{missingInputs:n,dynamicNode:i,syncInputs:r}=s;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 [${r}]`);if(n.length>0){const o=t.map(l=>l.name),a=Object.keys(e);throw new Error(`Cannot compute the outputs [${o}] from the provided inputs [${a}]. Missing the following inputs: [${n}]`)}return TN(this.graph,this.weightMap,s)}execute(e,t){e=this.mapInputs(e);const s=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);const n=s.map(p=>this.graph.nodes[Ls(p)[0]]),i=t.map(p=>Ls(p)[0]);let r=i.map(p=>this.graph.nodes[p]);r.length===0&&(r=this._outputs);const o=this.getCompilationKey(n,r);let a=this.compiledMap.get(o);a==null&&(a=this.compile(e,r),this.compiledMap.set(o,a));const l={},c={};return C(()=>{const p=new nw(this.weightMap,l,c,this.functionExecutorMap),u=Object.assign({},this.weightMap);Object.keys(e).forEach(m=>{const[f,g]=Ls(m),y=[];y[g]=e[m],u[f]=y});const h=this.getFrozenTensorIds(u),d={};for(let m=0;m<a.length;m++){const f=a[m];if(!u[f.name]){const g=sw(f,u,p);if(g instanceof Promise)throw new Error(`The execution of the op '${f.op}' returned a promise. Please use model.executeAsync() instead.`);u[f.name]=g,this.checkTensorForDisposal(f.name,f,u,p,h,i,d)}}return this.parent==null&&p.dispose(h),t.map(m=>Vt(m,u,p))})}getFrozenTensorIds(e){const t=[].concat.apply([],Object.keys(e).map(s=>e[s]).map(s=>s.map(n=>n.id)));return new Set(t)}checkTensorForDisposal(e,t,s,n,i,r,o){if(t.category==="control"||r.indexOf(e)!==-1)return;s[e].forEach(a=>{a!=null&&(o[a.id]=(o[a.id]||0)+t.children.length)}),t.inputs.forEach(a=>{if(a.category!=="control"){const l=ZA(a.name,s,n);l!=null&&l.forEach(c=>{if(c&&!i.has(c.id)){const p=o[c.id];p===1?(c.dispose(),delete o[c.id]):p!=null&&o[c.id]--}})}})}async executeAsync(e,t){return this._executeAsync(e,t)}async _executeAsync(e,t,s=!1,n={},i={}){s||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));const r=new nw(this.weightMap,n,i,this.functionExecutorMap),o=await this.executeWithControlFlow(e,r,t,s),a=t.map(u=>Vt(u,o,r)),l=a.map(u=>u.id),c=Object.keys(e).map(u=>e[u].id),p=new Set([...l,...c,...this.weightIds]);return Object.keys(o).forEach(u=>{const h=o[u];h.forEach(d=>{d&&!d.isDisposed&&!p.has(d.id)&&d.dispose()})}),this.parent==null&&r.dispose(p),a}async executeFunctionAsync(e,t,s){const n=e.reduce((i,r,o)=>(i[this.inputs[o].name]=r,i),{});return this._executeAsync(n,this.outputNodes,!0,t,s)}async executeWithControlFlow(e,t,s,n){const i=Object.keys(e),r=i.map(w=>this.graph.nodes[Ls(w)[0]]),o=s.map(w=>Ls(w)[0]),a=o.map(w=>this.graph.nodes[w]),{usedNodes:l,missingInputs:c,dynamicNode:p,syncInputs:u}=rw(e,a,this.weightMap),h=[...r,...this.graph.weights].map(w=>({node:w,contexts:t.currentContext})),d=Object.assign({},this.weightMap);Object.keys(e).forEach(w=>{const[x,T]=Ls(w),A=[];A[T]=e[w],d[x]=A});const m={},f=this.getFrozenTensorIds(d),g={};for(;h.length>0;){const w=this.processStack(r,h,t,d,g,f,o,m,l);await Promise.all(w)}p==null&&!n&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");const y=a.filter(w=>!iw(w)&&!Vt(w.name,d,t)).map(w=>w.name);if(y.length>0){let w="";throw p!=null&&(w=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${u}]`),new Error(`Cannot compute the outputs [${y}] from the provided inputs [${i}]. Consider providing the following inputs: [${c}]. ${w}`)}return d}processStack(e,t,s,n,i,r,o,a,l){const c=[];for(;t.length>0;){const p=t.pop();s.currentContext=p.contexts;let u="";if(p.node.op==="Enter"&&L("isConstant",p.node,n,s)&&([u]=Pn(p.node.name,s)),e.indexOf(p.node)===-1){const h=sw(p.node,n,s);u||([u]=Pn(p.node.name,s));const d=s.currentContext;h instanceof Promise?c.push(h.then(m=>(n[u]=m,s.currentContext=d,this.checkTensorForDisposal(u,p.node,n,s,r,o,a),this.processChildNodes(p.node,t,s,n,i,l),m))):(n[u]=h,this.checkTensorForDisposal(u,p.node,n,s,r,o,a),this.processChildNodes(p.node,t,s,n,i,l))}else this.processChildNodes(p.node,t,s,n,i,l)}return c}processChildNodes(e,t,s,n,i,r){e.children.forEach(o=>{const[a]=Pn(o.name,s);if(i[a]||!r.has(o.name))return;o.op==="Merge"?o.inputNames.some(l=>!!Vt(l,n,s))&&(i[a]=!0,t.push({contexts:s.currentContext,node:o})):o.inputNames.every(l=>!!Vt(l,n,s))&&(i[a]=!0,t.push({contexts:s.currentContext,node:o}))})}dispose(){Object.keys(this.weightMap).forEach(e=>this.weightMap[e].forEach(t=>t.dispose()))}checkInputShapeAndType(e){Object.keys(e).forEach(t=>{const s=e[t],[n]=Ls(t),i=this.graph.nodes[n];if(i.attrParams.shape&&i.attrParams.shape.value){const r=i.attrParams.shape.value,o=r.length===s.shape.length&&s.shape.every((a,l)=>r[l]===-1||r[l]===a);N.assert(o,()=>`The shape of dict['${i.name}'] provided in model.execute(dict) must be [${r}], but was [${s.shape}]`)}i.attrParams.dtype&&i.attrParams.dtype.value&&N.assert(s.dtype===i.attrParams.dtype.value,()=>`The dtype of dict['${i.name}'] provided in model.execute(dict) must be ${i.attrParams.dtype.value}, but was ${s.dtype}`)})}mapInputs(e){const t={};for(const s in e)if(this._signature!=null&&this._signature.inputs!=null&&this._signature.inputs[s]!=null){const n=this._signature.inputs[s];t[n.name]=e[s]}else t[s]=e[s];return t}checkInputs(e){const t=Object.keys(e).filter(s=>{const[n]=Ls(s);return this.graph.nodes[n]==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 s=this._signature.outputs[t];return s.name}return t},{})}checkOutputs(e){e.forEach(t=>{const[s]=Ls(t);if(!this.graph.nodes[s])throw new Error(`The output '${t}' is not found in the graph`)})}}const lB="?tfjs-format=file",cB="model.json";class ow{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={})}get modelVersion(){return this.version}get inputNodes(){return this.executor.inputNodes}get outputNodes(){return this.executor.outputNodes}get inputs(){return this.executor.inputs}get outputs(){return this.executor.outputs}get weights(){return this.executor.weightMap}findIOHandler(){const e=this.modelUrl;if(e.load!=null)this.handler=e;else if(this.loadOptions.requestInit!=null)this.handler=Rt.browserHTTPRequest(e,this.loadOptions);else{const t=Rt.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(Rt.browserHTTPRequest(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 s={};this.artifacts.userDefinedMetadata!=null&&(s=this.artifacts.userDefinedMetadata.signature),this.version=`${t.versions.producer}.${t.versions.minConsumer}`;const n=Rt.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new Ym(ew.Instance.transformGraph(t,s)),this.executor.weightMap=this.convertTensorMapToTensorsMap(n),e.modelInitializer!=null){const i=ew.Instance.transformGraph(e.modelInitializer);this.initializer=new Ym(i),this.initializer.weightMap=this.executor.weightMap,this.initializer.execute({},[])}return!0}async save(e,t){if(typeof e=="string"){const s=Rt.getSaveHandlers(e);if(s.length===0)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(s.length>1)throw new Error(`Found more than one (${s.length}) save handlers for URL '${e}'`);e=s[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 me)&&!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,s,n)=>(t[s]=e[n],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 s=this.executor.execute(e,t);return s.length>1?s:s[0]}async executeAsync(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const s=await this.executor.executeAsync(e,t);return s.length>1?s:s[0]}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,s)=>(t[s]=[e[s]],t),{})}dispose(){this.executor.dispose(),this.initializer&&this.initializer.dispose()}}async function AN(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}${cB}${lB}`));const s=new ow(e,t);return await s.load(),s}const Km="2.6.0";function NN(e,t){return Xm(e,t)}function Xm(e,t,s=new Map,n=new Set){if(e==null)return null;if(n.has(e))throw new Error("Circular references are not supported.");if(s.has(e))return s.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(oo(e)){const r=Array.isArray(e)?[]:{};n.add(e);for(const o in e){const a=e[o],l=Xm(a,t,s,n);r[o]=l}return n.delete(e),r}else throw new Error(`Can't recurse into non-iterable type: ${e}`);else return s.set(e,i.value),i.value}function RN(e,t=aw){return CN(e,t)}function CN(e,t,s=new Set){const n=e[0];if(s.has(n))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(oo(n)){const r=Array.isArray(n)?[]:{};s.add(n);for(const o in n){const a=e.map(c=>c[o]),l=CN(a,t,s);r[o]=l}return s.delete(n),r}else throw new Error(`Can't recurse into non-iterable type: ${n}`);else return i.value}function aw(e){return e===null?null:oo(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function Jm(e,t){const s=new Map;Xm(e,t,s);for(const i of Array.from(s.keys())){const r=s.get(i);if(r instanceof Promise){const o=await r;s.set(i,o)}}const n=Xm(e,t,s);return n}function oo(e){return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof me))}function ON(e){return e==null||pB(e)||Array.isArray(e)||typeof e=="object"&&e instanceof me||N.isTypedArray(e)}function pB(e){return e===null||typeof e!="object"&&typeof e!="function"}function EN(e){return NN(e,uB)}function uB(e){return e instanceof me?{value:e.clone(),recurse:!1}:oo(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}class Zm{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),s=this.get(t);return this.set(t,this.pop()),s}}class Qm extends Zm{constructor(){super(Qm.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),s=this.length();for(let n=0;n<s;n++)t[n]=this.get(this.wrap(this.begin+n));this.data=t,this.capacity=e,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=s}}Qm.INITIAL_CAPACITY=32;const _N=mc(fc());function lw(e){return new hB(e)}function hu(e){return new dB(e)}function DN(e,t){return new kN(e,t)}function FN(e,t=qi.FAIL){return new mB(e,t)}class At{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 s=await e.next();for(;!s.done;)t.push(s.value),s=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(),s=e(t.value);for(;!t.done&&s;)t=await this.next(),s=e(t.value)}handleErrors(e){return new LB(this,e)}filter(e){return new wB(this,e)}map(e){return new xB(this,e)}mapAsync(e){return new MN(this,e)}serialMapAsync(e){return new MN(this,e).serial()}flatmap(e){return new SB(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 bB(this,e,t)}columnMajorBatch(e,t=!0,s=aw){const n=this.rowMajorBatch(e,t);return n.map(i=>RN(i,s))}concatenate(e,t){return new kN(lw([this,e]),t)}take(e){return e<0||e==null?this:new yB(this,e)}skip(e){return e<0||e==null?this:new gB(this,e)}prefetch(e){return new UN(this,e)}shuffle(e,t){return new IB(this,e,t)}serial(){return new fB(this)}}class hB extends At{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:EN(e),done:!1}}}class dB extends At{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 fB extends At{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 gB extends At{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;ce(e.value)}return this.upstream.next()}}class yB extends At{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 bB extends At{constructor(e,t,s=!0){super();this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=s,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 wB extends At{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;ce(e.value)}}}class xB extends At{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=pn.getTensorsInContainer(e.value),s=this.transform(e.value),n=pn.getTensorsInContainer(s);for(const i of t)pn.isTensorInList(i,n)||i.dispose();return{value:s,done:!1}}}class LB extends At{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 MN extends At{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=pn.getTensorsInContainer(e.value),s=await this.transform(e.value),n=pn.getTensorsInContainer(s);for(const i of t)pn.isTensorInList(i,n)||i.dispose();return{value:s,done:!1}}}class du extends At{constructor(){super();this.outputQueue=new Qm,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 SB extends du{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=pn.getTensorsInContainer(e.value),s=this.transform(e.value),n=pn.getTensorsInContainer(s);this.outputQueue.pushAll(s);for(const i of t)pn.isTensorInList(i,n)||i.dispose();return!0}}class kN extends At{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 s=await this.moreIterators.next();if(s.done)return{value:null,done:!0};this.iterator=s.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 qi;(function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"})(qi||(qi={}));class mB extends At{constructor(e,t=qi.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,s=0;function n(r){if(r instanceof At){const o=r.next();return{value:o.then(a=>(t++,a.done&&s++,a.value)),recurse:!1}}else return{value:null,recurse:!0}}const i=await Jm(this.iterators,n);if(t===s)return{value:null,done:!0};if(s>0)switch(this.mismatchMode){case qi.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case qi.SHORTEST:return{value:null,done:!0};case qi.LONGEST:default:}return this.count++,{value:i,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}}class UN extends At{constructor(e,t){super();this.upstream=e,this.bufferSize=t,this.buffer=new Zm(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 IB extends UN{constructor(e,t,s){super(e,t);this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=_N.alea(s||N.now().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}}}const $N=mc(fc());class Hi{constructor(){this.size=null}batch(e,t=!0){const s=this;N.assert(e>0,()=>`batchSize needs to be positive, but it is
${e}`);let n;return this.size===Infinity||this.size==null?n=this.size:t?n=Math.ceil(this.size/e):n=Math.floor(this.size/e),Cs(async()=>(await s.iterator()).columnMajorBatch(e,t,vB),n)}concatenate(e){const t=this;let s;return this.size===Infinity||e.size===Infinity?s=Infinity:this.size!=null&&e.size!=null?s=this.size+e.size:s=null,Cs(async()=>(await t.iterator()).concatenate(await e.iterator()),s)}filter(e){const t=this;let s;return this.size===Infinity?s=Infinity:s=null,Cs(async()=>(await t.iterator()).filter(n=>C(()=>e(n))),s)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){const t=this;return Cs(async()=>(await t.iterator()).map(s=>C(()=>e(s))),this.size)}mapAsync(e){const t=this;return Cs(async()=>(await t.iterator()).mapAsync(e),this.size)}prefetch(e){if(e==null)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");const t=this;return Cs(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){const t=this;let s;return this.size!=null&&e>0?s=this.size*e:e===0?s=0:this.size!=null&&(e===void 0||e<0)?s=Infinity:s=null,Cs(async()=>{const n=hu(async()=>({value:await t.iterator(),done:!1}));return DN(n.take(e))},s)}skip(e){const t=this;let s;return this.size!=null&&e>=0&&this.size>=e?s=this.size-e:this.size!=null&&(this.size<e||e===void 0||e<0)?s=0:s=null,Cs(async()=>(await t.iterator()).skip(e),s)}shuffle(e,t,s=!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 n=this,i=$N.alea(t||N.now().toString());return Cs(async()=>{let r=i.int32();return s&&(r+=i.int32()),(await n.iterator()).shuffle(e,r.toString())},this.size)}take(e){const t=this;let s;return this.size!=null&&this.size>e?s=e:this.size!=null&&this.size<=e?s=this.size:s=null,Cs(async()=>(await t.iterator()).take(e),s)}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()}}Hi.MAX_BUFFER_SIZE=1e4;function Cs(e,t=null){return new class extends Hi{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function WN(e){return Cs(async()=>lw(e),e.length)}function zN(e){if(!oo(e))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(e))for(let s=0;s<e.length;s++)t=t==null?e[s].size:Math.min(t,e[s].size);else if(e instanceof Object)for(const s in e)t=t==null?e[s].size:Math.min(t,e[s].size);return Cs(async()=>{const s=await Jm(e,n=>{if(n instanceof Hi)return{value:n.iterator(),recurse:!1};if(oo(n))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return FN(s,qi.SHORTEST)},t)}function vB(e){if(e===null)return null;const t=e[0];if(ON(t)){const s=TB(e);return{value:s,recurse:!1}}return{value:null,recurse:!0}}function TB(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof me?Ve(e):ze(e)}class ef extends Hi{constructor(e){super();this.input=e}async iterator(){const e=await this.input.iterator(),t=e.decodeUTF8(),s=t.split(`
`).map(n=>(n.endsWith("\r")&&(n=n.slice(0,-1)),n));return s}}const tf='"',mu=Symbol("out"),PN=Symbol("field"),sf=Symbol("quote"),cw=Symbol("quoteafterquote"),BN=Symbol("quoteinquote");class nf extends Hi{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 ef(e),t||(t={}),this.hasHeader=!(t.hasHeader===!1),this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(N.assert(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&&N.assert(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((n,i)=>(n[i]=n[i]+1||1,n),{}),s=Object.keys(t).filter(n=>t[n]>1);if(N.assert(s.length===0,()=>"Duplicate column names found: "+s.toString()),this.columnConfigs)for(const n of Object.keys(this.columnConfigs)){const i=this.fullColumnNames.indexOf(n);if(i===-1)throw new Error('The key "'+n+'" 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 s=t.value,n=this.parseRow(s,!1);return n}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),s={},n={};for(let i=0;i<this.fullColumnNames.length;i++){const r=this.fullColumnNames[i],o=this.columnConfigs?this.columnConfigs[r]:null;if(this.configuredColumnsOnly&&!o)continue;{const a=t[i];let l=null;if(a==="")if(o&&o.default!==void 0)l=o.default;else{if(o&&(o.required||o.isLabel))throw new Error(`Required column ${r} is empty in this line: ${e}`);l=void 0}else{const c=Number(a);if(isNaN(c))o&&o.dtype==="bool"?l=this.getBoolean(a):l=a;else if(!o||!o.dtype)l=c;else switch(o.dtype){case"float32":l=c;break;case"int32":l=Math.floor(c);break;case"bool":l=this.getBoolean(a);break;default:l=c}}o&&o.isLabel?n[r]=l:s[r]=l}}return Object.keys(n).length===0?s:{xs:s,ys:n}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){const s=[];let n=0;const i=e.length;let r=mu;for(let o=0;o<i;o++)switch(r){case mu:switch(e.charAt(o)){case tf:n=o+1,r=sf;break;case this.delimiter:if(n=o+1,this.delimiter===" "&&this.delimWhitespace)break;s.push(""),r=mu;break;default:r=PN,n=o;break}break;case PN:switch(e.charAt(o)){case this.delimiter:s.push(e.substring(n,o)),r=mu,n=o+1;break;default:}break;case sf:switch(e.charAt(o)){case tf:r=cw;break;default:}break;case cw:switch(e.charAt(o)){case this.delimiter:s.push(e.substring(n,o-1)),r=mu,n=o+1;break;case tf:r=sf;break;default:r=BN;break}break;case BN:switch(e.charAt(o)){case tf:r=sf;break;default:}break;default:}if(r===cw?s.push(e.substring(n,i-1)):s.push(e.substring(n)),t&&s.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${s}`);return s}}class pw extends At{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(W().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");const t=new pw(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(s){throw new Error(`Error thrown while initializing video stream: ${s.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 s=await this.getAudioData();if(this.includeSpectrogram){const n=this.flattenQueue(s.freqDataQueue);e=this.getTensorFromAudioDataArray(n,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){const n=this.flattenQueue(s.timeDataQueue);t=this.getTensorFromAudioDataArray(n,[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 s=0;return new Promise(n=>{const i=setInterval(()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-Infinity&&n({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++s===this.numFrames&&(clearInterval(i),n({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,s=new Float32Array(e.length*t);return e.forEach((n,i)=>s.set(n,i*t)),s}getTensorFromAudioDataArray(e,t){const s=new Float32Array(N.sizeFromShape(t));return s.set(e,s.length-e.length),ze(s,t)}}class uw extends At{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=Oe([0],"int32"),this.webcamConfig.centerCrop){const s=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,n=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,i=(1-s)/2,r=(1-n)/2,o=i+s,a=n+r;this.cropBox=as([r,i,a,o],[1,4])}else this.cropBox=as([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(W().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 s=new uw(e,t);return await s.start(),s}async start(){this.webcamConfig.facingMode&&N.assert(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=Fr.fromPixels(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 C(()=>{const t=e.toFloat().expandDims(0);let s;s=Zs.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");const n=s.shape;return s.reshape(n.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 rf{}class hw extends At{split(e){return new AB(this,e)}}class AB extends hw{constructor(e,t){super();this.upstream=e,this.impl=new NB(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class NB extends du{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 s of t.slice(0,-1))this.outputQueue.push(s);return this.carryover=t[t.length-1],!0}}class jN extends At{decodeUTF8(){return new CB(this)}}class CB extends hw{constructor(e){super();this.upstream=e,this.impl=new RB(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class RB extends du{constructor(e){super();if(this.upstream=e,W().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{const{StringDecoder:t}=AL();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 s;return W().get("IS_BROWSER")?s=this.decoder.decode(t,{stream:!0}):s=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(s),!0}}class of extends jN{constructor(e,t={}){super();this.file=e,this.options=t,N.assert(e instanceof Uint8Array||(W().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,s)=>{const n=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)t(new Uint8Array(this.file.slice(this.offset,n)));else{const i=new FileReader;i.onload=o=>{let a=i.result;if(a instanceof ArrayBuffer&&(a=new Uint8Array(a)),!(a instanceof Uint8Array))return s(new TypeError("FileReader returned unknown type."));t(a)},i.onabort=o=>s(new Error("Aborted")),i.onerror=o=>s(new Error(o.type));const r=this.file.slice(this.offset,n);i.readAsArrayBuffer(r)}this.offset=n});return{value:await e,done:!1}}}async function VN(e,t={}){let s,n;typeof e=="string"?s=e:(s=e.url,n=OB(e));const i=await N.fetch(s,n);if(i.ok){const r=new Uint8Array(await i.arrayBuffer());return new of(r,t)}else throw new Error(i.statusText)}const OB=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 af(e){return typeof e=="string"&&e.substr(0,7)==="file://"}class lf extends rf{constructor(e,t={}){super();this.input=e,this.options=t}async iterator(){if(af(this.input)&&W().get("IS_NODE")){const e=NL();this.input=e.readFileSync(this.input.substr(7))}return new of(this.input,this.options)}}class cf extends rf{constructor(e,t={}){super();this.url=e,this.fileOptions=t}async iterator(){return af(this.url)?new lf(this.url,this.fileOptions).iterator():VN(this.url,this.fileOptions)}}function GN(e,t={}){return new nf(new cf(e),t)}function qN(e){const t=hu(e);return Cs(async()=>t)}function HN(e){return Cs(async()=>{const t=await e();return hu(()=>t.next())})}async function YN(e,t){return uw.create(e,t)}async function KN(e){return pw.create(e)}const pf="2.6.0";const dw={};Ee(dw,{CSVDataset:()=>nf,Dataset:()=>Hi,FileDataSource:()=>lf,TextLineDataset:()=>ef,URLDataSource:()=>cf,array:()=>WN,csv:()=>GN,func:()=>qN,generator:()=>HN,microphone:()=>KN,version_data:()=>pf,webcam:()=>YN,zip:()=>zN});function ee(e,t){Array.isArray(e)||(e=[e]),e.forEach(s=>{s!=null&&N.assert(s.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}const XN=mc(fc());const EB=vt.nonMaxSuppressionV3Impl,_B=vt.split,kB=vt.tile,DB=vt.topkImpl,FB=vt.whereImpl;function mw(e,t,s,n){if(s==="linear")return e.linear(t);if(s==="relu")return e.relu(t);if(s==="elu")return hn(t);if(s==="relu6")return e.relu6(t);if(s==="prelu")return e.prelu(t,n);throw new Error(`Activation ${s} has not been implemented for the CPU backend.`)}class fw extends go{constructor(){super();this.blockSize=48,this.firstUse=!0,this.data=new gc(this,Ms())}write(e,t,s){this.firstUse&&(this.firstUse=!1,W().get("IS_NODE")&&U.warn(`
============================
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 n={};return this.data.set(n,{values:e,dtype:s,refCount:1}),n}makeTensorInfo(e,t,s){const n=this.write(s,e,t);return{dataId:n,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,s,n){this.data.set(e,{values:t,dtype:n,refCount:1})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:s}=this.data.get(e);if(t==="complex64"){const n=this.readSync(s.real.dataId),i=this.readSync(s.imag.dataId);return U.mergeRealAndImagArrays(n,i)}return this.data.get(e).values}bufferSync(e){const t=this.readSync(e.dataId);let s=t;if(e.dtype==="string")try{s=t.map(n=>N.decodeString(n))}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return ge(e.shape,e.dtype,s)}makeOutput(e,t,s){const n=this.write(e,t,s);return Ms().makeTensorFromDataId(n,t,s,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 s=this.data.get(t);s.refCount--,s.refCount<1&&this.disposeData(t)}}async time(e){const t=N.now();e();const s=N.now()-t;return{kernelMs:s}}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,s,n){ee(e,"stridedSlice");const i=Fs.computeOutShape(t,s,n);if(i.some(a=>a===0))return ze([],i);const r=ge(i,e.dtype),o=this.bufferSync(e);for(let a=0;a<r.size;a++){const l=r.indexToLoc(a),c=new Array(l.length);for(let p=0;p<c.length;p++)c[p]=l[p]*n[p]+t[p];r.set(o.get(...c),...l)}return r.toTensor()}diag(e){const t=this.readSync(e.dataId),s=ge([e.size,e.size],e.dtype),n=s.values;for(let i=0;i<t.length;i++)n[i*e.size+i]=t[i];return s.toTensor()}unstack(e,t){const s=e.shape[t],n=new Array(e.rank-1);let i=0;for(let l=0;l<e.rank;l++)l!==t&&(n[i++]=e.shape[l]);const r=new Array(e.rank).fill(0),o=e.shape.slice();o[t]=1;const a=new Array(s);for(let l=0;l<a.length;l++)r[t]=l,a[l]=he(e,r,o).reshape(n);return a}reverse(e,t){ee(e,"reverse");const s=ge(e.shape,e.dtype),n=this.bufferSync(e);for(let i=0;i<s.size;i++){const r=s.indexToLoc(i),o=r.slice();t.forEach(a=>o[a]=e.shape[a]-1-o[a]),s.set(n.get(...o),...r)}return s.toTensor()}neg(e){return ee(e,"neg"),R(j(-1),e)}addN(e){ee(e,"addN");const t=e.map(i=>this.readSync(i.dataId)),s=ge(e[0].shape,e[0].dtype),n=s.values;for(let i=0;i<e.length;i++){const r=t[i];for(let o=0;o<n.length;o++)n[o]+=r[o]}return s.toTensor()}softmax(e,t){const s=N.parseAxisParam([t],e.shape),n=xt(e,s),i=U.expandShapeToKeepDim(n.shape,s),r=X(e,n.reshape(i)),o=ut(r),a=this.sum(o,s).reshape(i);return Z(o,a)}pow(e,t){return ee([e,t],"pow"),this.broadcastedBinaryOp(e,t,e.dtype,(s,n)=>Math.pow(s,n))}batchMatMul(e,t,s,n){ee([e,t],"matMul");const i=s?e.shape[1]:e.shape[2],r=s?e.shape[2]:e.shape[1],o=n?t.shape[1]:t.shape[2],a=e.shape[0],l=this.readSync(e.dataId),c=this.readSync(t.dataId),[p,u,h]=s?[e.strides[0],1,e.strides[1]]:[e.strides[0],e.strides[1],1],[d,m,f]=n?[1,t.strides[1],t.strides[0]]:[t.strides[1],1,t.strides[0]],g=r*o,y=ge([a,r,o],e.dtype),w=y.values,x=this.blockSize;for(let T=0;T<a;T++)for(let A=0;A<r;A+=x)for(let _=0;_<o;_+=x)for(let E=0;E<i;E+=x){const F=Math.min(A+x,r),D=Math.min(_+x,o),M=Math.min(E+x,i);for(let P=A;P<F;P++)for(let B=_;B<D;B++){let Y=0;for(let q=E;q<M;q++)Y+=l[T*p+P*u+q*h]*c[q*d+B*m+T*f];w[T*g+(P*o+B)]+=Y}}return y.toTensor()}fusedBatchMatMul({a:e,b:t,transposeA:s,transposeB:n,bias:i,activation:r,preluActivationWeights:o}){let a=this.batchMatMul(e,t,s,n);return i&&(a=$(a,i)),r&&(a=mw(this,a,r,o)),a}floorDiv(e,t){ee([e,t],"floorDiv");const s=(i,r)=>Math.floor(i/r),n="int32";return this.broadcastedBinaryOp(e,t,n,s)}sum(e,t){ee(e,"sum"),U.assertAxesAreInnerMostDims("sum",t,e.rank);const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=Ft(e.dtype,"int32"),r=ye(s,i),o=N.sizeFromShape(n),a=this.readSync(r.dataId),l=this.readSync(e.dataId);for(let c=0;c<a.length;++c){const p=c*o;let u=0;for(let h=0;h<o;++h)u+=l[p+h];a[c]=u}return r}prod(e,t){ee(e,"sum");const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=Ft(e.dtype,"int32"),r=ye(s,i),o=N.sizeFromShape(n),a=this.readSync(r.dataId),l=this.readSync(e.dataId);for(let c=0;c<a.length;++c){const p=c*o;let u=1;for(let h=0;h<o;++h)u*=l[p+h];a[c]=u}return r}unsortedSegmentSum(e,t,s){ee(e,"unsortedSegmentSum");const n=[],i=e.rank-t.rank;for(let r=0;r<i;++r)t=t.expandDims(r+1);for(let r=0;r<s;++r){const o=j(r,"int32"),a=os(o,t).asType("float32"),l=a.mul(e).sum(0);n.push(l)}return Ve(n)}argMin(e,t){ee(e,"argMin");const s=[t];U.assertAxesAreInnerMostDims("argMin",s,e.rank);const[n,i]=U.computeOutAndReduceShapes(e.shape,s),r=ye(n,"int32"),o=N.sizeFromShape(i),a=this.readSync(r.dataId),l=this.readSync(e.dataId);for(let c=0;c<a.length;++c){const p=c*o;let u=l[p],h=0;for(let d=0;d<o;++d){const m=l[p+d];m<u&&(u=m,h=d)}a[c]=h}return r}argMax(e,t){ee(e,"argMax");const s=[t];U.assertAxesAreInnerMostDims("argMax",s,e.rank);const[n,i]=U.computeOutAndReduceShapes(e.shape,s),r=ye(n,"int32"),o=N.sizeFromShape(i),a=this.readSync(r.dataId),l=this.readSync(e.dataId);for(let c=0;c<a.length;++c){const p=c*o;let u=l[p],h=0;for(let d=0;d<o;++d){const m=l[p+d];m>u&&(u=m,h=d)}a[c]=h}return r}cumsum(e,t,s,n){if(ee(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=Ft(e.dtype,"int32"),r=ye(e.shape,i),o=this.readSync(r.dataId),a=this.readSync(e.dataId),l=e.shape[e.rank-1],c=n?(p,u)=>p+l-u-1:(p,u)=>p+u;for(let p=0;p<a.length;p+=l)for(let u=0;u<l;u++){const h=c(p,u);if(u===0)o[h]=s?0:a[h];else{const d=c(p,u-1);o[h]=s?a[d]+o[d]:a[h]+o[d]}}return r}equal(e,t){return ee([e,t],"equal"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s===n?1:0)}notEqual(e,t){return ee([e,t],"notEqual"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s!==n?1:0)}less(e,t){return ee([e,t],"less"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s<n?1:0)}lessEqual(e,t){return ee([e,t],"lessEqual"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s<=n?1:0)}greater(e,t){return ee([e,t],"greater"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s>n?1:0)}greaterEqual(e,t){return ee([e,t],"greaterEqual"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s>=n?1:0)}logicalAnd(e,t){return ee([e,t],"logicalAnd"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s&&n)}logicalOr(e,t){return ee([e,t],"logicalOr"),this.broadcastedBinaryOp(e,t,"bool",(s,n)=>s||n)}select(e,t,s){ee([e,t,s],"select");const n=this.readSync(e.dataId),i=this.readSync(t.dataId),r=this.readSync(s.dataId),o=ye(t.shape,Ft(t.dtype,s.dtype)),a=this.readSync(o.dataId);let l=0;const c=e.rank===0||e.rank>1||t.rank===1?1:N.sizeFromShape(t.shape.slice(1));for(let p=0;p<n.length;p++)for(let u=0;u<c;u++)n[p]===1?a[l++]=i[p]:a[l++]=r[p];return o}where(e){ee([e],"where");const t=this.readSync(e.dataId);return FB(e.shape,t)}topk(e,t,s){ee(e,"topk");const n=this.readSync(e.dataId);return DB(n,e.shape,e.dtype,t,s)}min(e,t){ee(e,"min"),U.assertAxesAreInnerMostDims("min",t,e.rank);const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=ye(s,e.dtype),r=N.sizeFromShape(n),o=this.readSync(i.dataId),a=this.readSync(e.dataId);for(let l=0;l<o.length;++l){const c=l*r;let p=a[c];for(let u=0;u<r;++u){const h=a[c+u];h<p&&(p=h)}o[l]=p}return i}minimum(e,t){return ee([e,t],"minimum"),this.broadcastedBinaryOp(e,t,e.dtype,(s,n)=>Math.min(s,n))}mod(e,t){return ee([e,t],"mod"),this.broadcastedBinaryOp(e,t,e.dtype,(s,n)=>{const i=s%n;return s<0&&n<0||s>=0&&n>=0?i:(i+n)%n})}maximum(e,t){return ee([e,t],"maximum"),this.broadcastedBinaryOp(e,t,e.dtype,(s,n)=>Math.max(s,n))}all(e,t){ee(e,"all"),U.assertAxesAreInnerMostDims("all",t,e.rank);const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=ye(s,e.dtype),r=N.sizeFromShape(n),o=this.readSync(i.dataId),a=this.readSync(e.dataId);for(let l=0;l<o.length;++l){const c=l*r;let p=a[c];for(let u=0;u<r;++u){const h=a[c+u];p=p&&h}o[l]=p}return i}any(e,t){ee(e,"any"),U.assertAxesAreInnerMostDims("any",t,e.rank);const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=ye(s,e.dtype),r=N.sizeFromShape(n),o=this.readSync(i.dataId),a=this.readSync(e.dataId);for(let l=0;l<o.length;++l){const c=l*r;let p=a[c];for(let u=0;u<r;++u){const h=a[c+u];p=p||h}o[l]=p}return i}squaredDifference(e,t){return ee([e,t],"squaredDifference"),this.broadcastedBinaryOp(e,t,e.dtype,(s,n)=>{const i=s-n;return i*i})}linear(e){return e}relu(e){ee(e,"relu");const t=ye(e.shape,e.dtype),s=this.readSync(t.dataId),n=this.readSync(e.dataId);for(let i=0;i<n.length;++i)s[i]=Math.max(0,n[i]);return t}relu6(e){ee(e,"relu");const t=ye(e.shape,e.dtype),s=this.readSync(t.dataId),n=this.readSync(e.dataId);for(let i=0;i<n.length;++i)s[i]=Math.min(Math.max(0,n[i]),6);return t}prelu(e,t){return ee([e,t],"prelu"),this.broadcastedBinaryOp(e,t,e.dtype,(s,n)=>s<0?n*s:s)}eluDer(e,t){ee([e,t],"eluDer");const s=new Float32Array(t.size),n=this.readSync(t.dataId),i=this.readSync(e.dataId);for(let r=0;r<n.length;++r){const o=n[r];o>=1?s[r]=i[r]:s[r]=i[r]*(o+1)}return this.makeOutput(s,t.shape,"float32")}atan2(e,t){return ee([e,t],"atan2"),this.broadcastedBinaryOp(e,t,e.dtype,(s,n)=>Math.atan2(s,n))}fusedConv2d({input:e,filter:t,convInfo:s,bias:n,activation:i,preluActivationWeights:r}){let o=this.conv2d(e,t,s);return n&&(o=$(o,n)),i&&(o=mw(this,o,i,r)),o}conv2d(e,t,s){ee([e,t],"conv2d");const n=s.filterHeight,i=s.filterWidth,r=s.dilationHeight,o=s.dilationWidth,a=s.padInfo.left,l=s.padInfo.top,c=s.dataFormat==="channelsLast",p=ge(s.outShape,e.dtype),u=e.strides[0],h=c?e.strides[1]:e.strides[2],d=c?e.strides[2]:1,m=c?1:e.strides[1],f=p.strides[0],g=c?p.strides[1]:p.strides[2],y=c?p.strides[2]:1,w=c?1:p.strides[1],x=this.readSync(e.dataId),T=this.readSync(t.dataId),A=p.values;for(let _=0;_<s.batchSize;++_){const E=_*u,F=_*f;for(let D=0;D<s.outHeight;++D){const M=F+D*g,P=D*s.strideHeight-l;for(let B=0;B<n;B++){const Y=P+B*r;if(Y<0||Y>=s.inHeight)continue;const q=B*t.strides[0],K=E+Y*h;for(let H=0;H<s.outWidth;++H){const Q=M+H*y,J=H*s.strideWidth-a;for(let ie=0;ie<i;ie++){const ne=J+ie*o;if(ne<0||ne>=s.inWidth)continue;const le=q+ie*t.strides[1],ue=K+ne*d;let oe=le;for(let de=0;de<s.inChannels;++de){const Ae=x[ue+de*m];for(let Me=0;Me<s.outChannels;++Me)A[Q+Me*w]+=Ae*T[oe+Me];oe+=s.outChannels}}}}}}return p.toTensor()}conv3d(e,t,s){const n=s.filterDepth,i=s.filterHeight,r=s.filterWidth,o=s.dilationDepth,a=s.dilationHeight,l=s.dilationWidth,c=s.padInfo.front,p=s.padInfo.left,u=s.padInfo.top,h=ge(s.outShape,e.dtype),d=this.readSync(e.dataId),m=this.readSync(t.dataId),f=h.values;for(let g=0;g<s.batchSize;++g){const y=g*e.strides[0],w=g*h.strides[0];for(let x=0;x<s.outDepth;++x){const T=w+x*h.strides[1],A=x*s.strideDepth-c;for(let _=0;_<n;_++){const E=A+_*o;if(E<0||E>=s.inDepth)continue;const F=_*t.strides[0],D=y+E*e.strides[1];for(let M=0;M<s.outHeight;++M){const P=T+M*h.strides[2],B=M*s.strideHeight-u;for(let Y=0;Y<i;Y++){const q=B+Y*a;if(q<0||q>=s.inHeight)continue;const K=F+Y*t.strides[1],H=D+q*e.strides[2];for(let Q=0;Q<s.outWidth;++Q){const J=P+Q*s.outChannels,ie=Q*s.strideWidth-p;for(let ne=0;ne<r;ne++){const le=ie+ne*l;if(le<0||le>=s.inWidth)continue;const ue=K+ne*t.strides[2],oe=H+le*s.inChannels;let de=ue;for(let Ae=0;Ae<s.inChannels;++Ae){const Me=d[oe+Ae];for(let Qe=0;Qe<s.outChannels;++Qe)f[J+Qe]+=Me*m[de+Qe];de+=s.outChannels}}}}}}}}return h.toTensor()}conv2dDerInput(e,t,s){ee([e,t],"conv2dDerInput");const n=ge(s.inShape,"float32"),i=n.values,r=this.readSync(e.dataId),o=this.readSync(t.dataId),[a,l,c]=t.strides,{batchSize:p,filterHeight:u,filterWidth:h,inChannels:d,inHeight:m,inWidth:f,outChannels:g,outHeight:y,outWidth:w,strideHeight:x,strideWidth:T,dataFormat:A}=s,_=u-1-s.padInfo.top,E=h-1-s.padInfo.left,F=A==="channelsLast",D=n.strides[0],M=F?n.strides[1]:n.strides[2],P=F?n.strides[2]:1,B=F?1:n.strides[1],Y=e.strides[0],q=F?e.strides[1]:e.strides[2],K=F?e.strides[2]:1,H=F?1:e.strides[1];for(let Q=0;Q<p;++Q)for(let J=0;J<d;++J)for(let ie=0;ie<m;++ie){const ne=ie-_,le=Math.max(0,Math.ceil(ne/x)),ue=Math.min(y,(u+ne)/x);for(let oe=0;oe<f;++oe){const de=oe-E,Ae=Math.max(0,Math.ceil(de/T)),Me=Math.min(w,(h+de)/T);let Qe=0;for(let $t=le;$t<ue;++$t){const _s=$t*x-ne;for(let yt=Ae;yt<Me;++yt){const ps=yt*T-de,_n=Y*Q+q*$t+K*yt,Gs=a*(u-1-_s)+l*(h-1-ps)+c*J;for(let ks=0;ks<g;++ks){const an=r[_n+H*ks],dc=o[Gs+ks];Qe+=an*dc}}}const St=D*Q+M*ie+P*oe+B*J;i[St]=Qe}}return n.toTensor()}conv3dDerInput(e,t,s){const n=ge(s.inShape,"float32"),i=n.values,[r,o,a,l]=n.strides,c=this.readSync(e.dataId),[p,u,h,d]=e.strides,m=this.readSync(t.dataId),[f,g,y,w]=t.strides,{batchSize:x,filterDepth:T,filterHeight:A,filterWidth:_,inChannels:E,inDepth:F,inHeight:D,inWidth:M,outChannels:P,outDepth:B,outHeight:Y,outWidth:q,strideDepth:K,strideHeight:H,strideWidth:Q}=s,J=T-1-s.padInfo.front,ie=A-1-s.padInfo.top,ne=_-1-s.padInfo.left;for(let le=0;le<x;++le)for(let ue=0;ue<E;++ue)for(let oe=0;oe<F;++oe){const de=oe-J,Ae=Math.max(0,Math.ceil(de/K)),Me=Math.min(B,(T+de)/K);for(let Qe=0;Qe<D;++Qe){const St=Qe-ie,$t=Math.max(0,Math.ceil(St/H)),_s=Math.min(Y,(A+St)/H);for(let yt=0;yt<M;++yt){const ps=yt-ne,_n=Math.max(0,Math.ceil(ps/Q)),Gs=Math.min(q,(_+ps)/Q);let ks=0;for(let an=Ae;an<Me;++an){const dc=an*K-de;for(let Na=$t;Na<_s;++Na){const Ca=Na*H-St;for(let Ra=_n;Ra<Gs;++Ra){const ag=Ra*Q-ps,lg=p*le+u*an+h*Na+d*Ra,hE=f*(T-1-dc)+g*(A-1-Ca)+y*(_-1-ag)+w*ue;for(let Wu=0;Wu<P;++Wu){const dE=c[lg+Wu],mE=m[hE+Wu];ks+=dE*mE}}}}i[r*le+o*oe+a*Qe+l*yt+ue]=ks}}}return n.toTensor()}conv2dDerFilter(e,t,s){ee([e,t],"conv2dDerFilter");const n=s.strideHeight,i=s.strideWidth,r=s.filterHeight,o=s.filterWidth,a=s.dataFormat==="channelsLast",l=ge(s.filterShape,"float32"),c=s.padInfo.left,p=s.padInfo.top,u=this.bufferSync(e),h=this.bufferSync(t);for(let d=0;d<r;++d){const m=Math.max(0,Math.ceil((p-d)/n)),f=Math.min(s.outHeight,(s.inHeight+p-d)/n);for(let g=0;g<o;++g){const y=Math.max(0,Math.ceil((c-g)/i)),w=Math.min(s.outWidth,(s.inWidth+c-g)/i);for(let x=0;x<s.inChannels;++x)for(let T=0;T<s.outChannels;++T){let A=0;for(let _=0;_<s.batchSize;++_)for(let E=m;E<f;++E){const F=d+E*n-p;for(let D=y;D<w;++D){const M=g+D*i-c;a?A+=u.get(_,F,M,x)*h.get(_,E,D,T):A+=u.get(_,x,F,M)*h.get(_,T,E,D)}}l.set(A,d,g,x,T)}}}return l.toTensor()}conv3dDerFilter(e,t,s){const n=s.strideDepth,i=s.strideHeight,r=s.strideWidth,o=s.filterDepth,a=s.filterHeight,l=s.filterWidth,c=ge(s.filterShape,"float32"),p=c.values,[u,h,d,m]=c.strides,f=this.readSync(t.dataId),[g,y,w,x]=t.strides,T=this.readSync(e.dataId),[A,_,E,F]=e.strides,D=s.padInfo.front,M=s.padInfo.left,P=s.padInfo.top;for(let B=0;B<o;++B){const Y=Math.max(0,Math.ceil((D-B)/n)),q=Math.min(s.outDepth,(s.inDepth+D-B)/n),K=B*u;for(let H=0;H<a;++H){const Q=Math.max(0,Math.ceil((P-H)/i)),J=Math.min(s.outHeight,(s.inHeight+P-H)/i),ie=H*h+K;for(let ne=0;ne<l;++ne){const le=Math.max(0,Math.ceil((M-ne)/r)),ue=Math.min(s.outWidth,(s.inWidth+M-ne)/r),oe=ne*d+ie;for(let de=0;de<s.inChannels;++de){const Ae=de*m+oe;for(let Me=0;Me<s.outChannels;++Me){let Qe=0;for(let St=0;St<s.batchSize;++St){const $t=St*A,_s=St*g;for(let yt=Y;yt<q;++yt){const ps=B+yt*n-D,_n=ps*_+$t,Gs=yt*y+_s;for(let ks=Q;ks<J;++ks){const an=H+ks*i-P,dc=an*E+_n,Na=ks*w+Gs;for(let Ca=le;Ca<ue;++Ca){const Ra=ne+Ca*r-M,ag=Ra*F+dc,lg=Ca*x+Na;Qe+=T[ag+de]*f[lg+Me]}}}}p[Ae+Me]=Qe}}}}}return c.toTensor()}fusedDepthwiseConv2D({input:e,filter:t,convInfo:s,bias:n,activation:i,preluActivationWeights:r}){let o=this.depthwiseConv2D(e,t,s);return n&&(o=$(o,n)),i&&(o=mw(this,o,i,r)),o}depthwiseConv2D(e,t,s){ee([e,t],"depthwiseConv2D");const n=s.filterHeight,i=s.filterWidth,r=s.dilationHeight,o=s.dilationWidth,a=s.padInfo.left,l=s.padInfo.top,c=s.outChannels/s.inChannels,p=ge(s.outShape,e.dtype),u=this.readSync(e.dataId),h=this.readSync(t.dataId),d=p.values;for(let m=0;m<s.batchSize;++m){const f=m*e.strides[0],g=m*p.strides[0];for(let y=0;y<s.outHeight;++y){const w=g+y*p.strides[1],x=y*s.strideHeight-a;for(let T=0;T<n;++T){const A=x+T*r;if(A<0||A>=s.inHeight)continue;const _=T*t.strides[0],E=f+A*e.strides[1];for(let F=0;F<s.outWidth;++F){const D=w+F*p.strides[2],M=F*s.strideWidth-l;for(let P=0;P<i;++P){const B=M+P*o;if(B<0||B>=s.inWidth)continue;const Y=_+P*t.strides[1],q=E+B*s.inChannels;let K=D,H=Y;for(let Q=0;Q<s.inChannels;++Q){const J=u[q+Q];for(let ie=0;ie<c;++ie)d[K+ie]+=J*h[H+ie];K+=c,H+=c}}}}}}return p.toTensor()}depthwiseConv2DDerInput(e,t,s){ee([e,t],"depthwiseConv2DDerInput");const n=ge(s.inShape,"float32"),i=n.values,[r,o,a]=n.strides,l=this.readSync(e.dataId),[c,p,u]=e.strides,h=this.readSync(t.dataId),[d,m,f]=t.strides,{batchSize:g,filterHeight:y,filterWidth:w,inChannels:x,inHeight:T,inWidth:A,outChannels:_,outHeight:E,outWidth:F,strideHeight:D,strideWidth:M}=s,P=y-1-s.padInfo.top,B=w-1-s.padInfo.left,Y=_/x;for(let q=0;q<g;++q)for(let K=0;K<x;++K)for(let H=0;H<T;++H){const Q=H-P,J=Math.max(0,Math.ceil(Q/D)),ie=Math.min(E,(y+Q)/D);for(let ne=0;ne<A;++ne){const le=ne-B,ue=Math.max(0,Math.ceil(le/M)),oe=Math.min(F,(w+le)/M);let de=0;for(let Ae=J;Ae<ie;++Ae){const Me=Ae*D-Q;for(let Qe=ue;Qe<oe;++Qe){const St=Qe*M-le,$t=c*q+p*Ae+u*Qe,_s=d*(y-1-Me)+m*(w-1-St)+f*K;for(let yt=0;yt<Y;++yt){const ps=K*Y+yt,_n=l[$t+ps],Gs=h[_s+yt];de+=_n*Gs}}}i[r*q+o*H+a*ne+K]=de}}return n.toTensor()}depthwiseConv2DDerFilter(e,t,s){ee([e,t],"depthwiseConv2DDerFilter");const n=s.strideHeight,i=s.strideWidth,r=s.filterHeight,o=s.filterWidth,a=ge(s.filterShape,"float32"),l=s.padInfo.left,c=s.padInfo.top,p=s.outChannels/s.inChannels,u=this.bufferSync(e),h=this.bufferSync(t);for(let d=0;d<r;++d){const m=Math.max(0,Math.ceil((c-d)/n)),f=Math.min(s.outHeight,(s.inHeight+c-d)/n);for(let g=0;g<o;++g){const y=Math.max(0,Math.ceil((l-g)/i)),w=Math.min(s.outWidth,(s.inWidth+l-g)/i);for(let x=0;x<s.outChannels;++x){const T=Math.trunc(x/p),A=x%p;let _=0;for(let E=0;E<s.batchSize;++E)for(let F=m;F<f;++F){const D=d+F*n-c;for(let M=y;M<w;++M){const P=g+M*i-l;_+=u.get(E,D,P,T)*h.get(E,F,M,x)}}a.set(_,d,g,T,A)}}}return a.toTensor()}tile(e,t){return ee(e,"tile"),kB(this.bufferSync(e),t)}gather(e,t,s){ee([e,t],"gather");const n=e.shape.slice(),i=this.readSync(t.dataId);n[s]=i.length;const r=ge(n,e.dtype),o=this.bufferSync(e);for(let a=0;a<r.size;++a){const l=r.indexToLoc(a),c=l.slice();c[s]=i[l[s]];const p=o.locToIndex(c);r.values[a]=o.values[p]}return r.toTensor()}batchToSpaceND(e,t,s){ee([e],"batchToSpaceND");const n=t.reduce((c,p)=>c*p),i=U.getReshaped(e.shape,t,n),r=U.getPermuted(i.length,t.length),o=U.getReshapedPermuted(e.shape,t,n),a=U.getSliceBeginCoords(s,t.length),l=U.getSliceSize(o,s,t.length);return se(e.reshape(i),r).reshape(o).slice(a,l)}pool3d(e,t,s){ee(e,"pool3d");const n=t.strideDepth,i=t.strideHeight,r=t.strideWidth,o=t.dilationDepth,a=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,p=t.effectiveFilterHeight,u=t.effectiveFilterWidth,h=t.padInfo.front,d=t.padInfo.top,m=t.padInfo.left,f=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,g=this.readSync(e.dataId),y=ge(t.outShape,e.dtype),w=y.values,x=t.outShape[1]*t.outShape[2]*t.outShape[3]*t.outShape[4],T=t.outShape[2]*t.outShape[3]*t.outShape[4],A=t.outShape[3]*t.outShape[4],_=t.outShape[4];for(let E=0;E<t.batchSize;++E){const F=E*x,D=E*e.strides[0];for(let M=0;M<t.inChannels;++M)for(let P=0;P<t.outDepth;++P){const B=P*n-h;let Y=B;for(;Y<0;)Y+=o;const q=Math.min(t.inDepth,c+B),K=F+P*T;for(let H=0;H<t.outHeight;++H){const Q=H*i-d;let J=Q;for(;J<0;)J+=a;const ie=Math.min(t.inHeight,p+Q),ne=K+H*A;for(let le=0;le<t.outWidth;++le){const ue=le*r-m;let oe=ue;for(;oe<0;)oe+=l;const de=Math.min(t.inWidth,u+ue),Ae=ne+le*_;let Me=f,Qe=0,St=0;for(let _s=Y;_s<q;_s+=o){const yt=D+_s*e.strides[1];for(let ps=J;ps<ie;ps+=a){const _n=yt+ps*e.strides[2];for(let Gs=oe;Gs<de;Gs+=l){const ks=_n+Gs*e.strides[3],an=g[ks+M];if(s==="max"&&an>Me?Me=an:s==="avg"&&(Qe+=an,St++),isNaN(Me))break}if(isNaN(Me))break}if(isNaN(Me))break}const $t=Ae+M;w[$t]=s==="avg"?Qe/St:Me}}}}return y.toTensor()}avgPool3d(e,t){return ee(e,"avgPool3d"),this.pool3d(e,t,"avg").toFloat()}avgPool3dBackprop(e,t,s){ee([e,t],"avgPool3dBackprop");const n=s.strideDepth,i=s.strideHeight,r=s.strideWidth,o=s.filterDepth,a=s.filterHeight,l=s.filterWidth,c=s.dilationDepth,p=s.dilationHeight,u=s.dilationWidth,h=s.effectiveFilterDepth,d=s.effectiveFilterHeight,m=s.effectiveFilterWidth,f=h-1-s.padInfo.front,g=m-1-s.padInfo.left,y=d-1-s.padInfo.top,w=ge(t.shape,"float32"),x=1/(o*a*l),T=this.bufferSync(e);for(let A=0;A<s.batchSize;++A)for(let _=0;_<s.inChannels;++_)for(let E=0;E<s.inDepth;++E)for(let F=0;F<s.inHeight;++F)for(let D=0;D<s.inWidth;++D){const M=E-f,P=F-y,B=D-g;let Y=0;for(let q=0;q<h;q+=c){const K=(M+q)/n;if(K<0||K>=s.outDepth||Math.floor(K)!==K)continue;for(let H=0;H<d;H+=p){const Q=(P+H)/i;if(Q<0||Q>=s.outHeight||Math.floor(Q)!==Q)continue;for(let J=0;J<m;J+=u){const ie=(B+J)/r;if(ie<0||ie>=s.outWidth||Math.floor(ie)!==ie)continue;const ne=T.get(A,K,Q,ie,_);Y+=ne}}}w.set(Y*x,A,E,F,D,_)}return w.toTensor()}maxPool3d(e,t){return ee(e,"maxPool3d"),this.pool3d(e,t,"max").toFloat()}maxPool3dPositions(e,t){const s=ge(t.outShape,"int32"),n=t.strideDepth,i=t.strideHeight,r=t.strideWidth,o=t.dilationDepth,a=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,p=t.effectiveFilterHeight,u=t.effectiveFilterWidth,h=t.padInfo.front,d=t.padInfo.top,m=t.padInfo.left,f=this.bufferSync(e);for(let g=0;g<t.batchSize;++g)for(let y=0;y<t.inChannels;++y)for(let w=0;w<t.outDepth;++w){const x=w*n-h;let T=x;for(;T<0;)T+=o;const A=Math.min(t.inDepth,c+x);for(let _=0;_<t.outHeight;++_){const E=_*i-d;let F=E;for(;F<0;)F+=a;const D=Math.min(t.inHeight,p+E);for(let M=0;M<t.outWidth;++M){const P=M*r-m;let B=P;for(;B<0;)B+=l;const Y=Math.min(t.inWidth,u+P);let q=Number.NEGATIVE_INFINITY,K=-1;for(let H=T;H<A;H+=o){const Q=H-x;for(let J=F;J<D;J+=a){const ie=J-E;for(let ne=B;ne<Y;ne+=l){const le=ne-P,ue=f.get(g,H,J,ne,y);ue>=q&&(q=ue,K=Q*p*u+ie*p+le)}}}s.set(K,g,w,_,M,y)}}}return s.toTensor()}maxPool3dBackprop(e,t,s,n){ee([t,s],"maxPool3dBackprop");const i=this.maxPool3dPositions(t,n),r=n.strideDepth,o=n.strideHeight,a=n.strideWidth,l=n.dilationDepth,c=n.dilationHeight,p=n.dilationWidth,u=n.effectiveFilterDepth,h=n.effectiveFilterHeight,d=n.effectiveFilterWidth,m=u-1-n.padInfo.front,f=d-1-n.padInfo.left,g=h-1-n.padInfo.top,y=ge(t.shape,"float32"),w=this.bufferSync(i),x=this.bufferSync(e);for(let T=0;T<n.batchSize;++T)for(let A=0;A<n.inChannels;++A)for(let _=0;_<n.inDepth;++_)for(let E=0;E<n.inHeight;++E)for(let F=0;F<n.inWidth;++F){const D=_-m,M=E-g,P=F-f;let B=0;for(let Y=0;Y<u;Y+=l){const q=(D+Y)/r;if(q<0||q>=n.outDepth||Math.floor(q)!==q)continue;for(let K=0;K<h;K+=c){const H=(M+K)/o;if(H<0||H>=n.outHeight||Math.floor(H)!==H)continue;for(let Q=0;Q<d;Q+=p){const J=(P+Q)/a;if(J<0||J>=n.outWidth||Math.floor(J)!==J)continue;const ie=u*h*d-1-w.get(T,q,H,J,A),ne=Y*h*d+K*d+Q,le=ie===ne?1:0;if(le===0)continue;const ue=x.get(T,q,H,J,A);B+=ue*le}}}y.set(B,T,_,E,F,A)}return y.toTensor()}resizeBilinear(e,t,s,n){ee(e,"resizeBilinear");const[i,r,o,a]=e.shape,l=this.readSync(e.dataId),c=new Float32Array(N.sizeFromShape([i,t,s,a])),p=[n&&t>1?r-1:r,n&&s>1?o-1:o],u=[n&&t>1?t-1:t,n&&s>1?s-1:s];let h=0;const d=p[0]/u[0],m=p[1]/u[1];for(let f=0;f<i;f++)for(let g=0;g<t;g++){const y=d*g,w=Math.floor(y),x=y-w,T=Math.min(r-1,Math.ceil(y)),A=f*e.strides[0]+w*e.strides[1],_=f*e.strides[0]+T*e.strides[1];for(let E=0;E<s;E++){const F=m*E,D=Math.floor(F),M=F-D,P=Math.min(o-1,Math.ceil(F)),B=A+D*e.strides[2],Y=_+D*e.strides[2],q=A+P*e.strides[2],K=_+P*e.strides[2];for(let H=0;H<a;H++){const Q=l[B+H],J=l[Y+H],ie=l[q+H],ne=l[K+H],le=Q+(ie-Q)*M,ue=J+(ne-J)*M,oe=le+(ue-le)*x;c[h++]=oe}}}return ze(c,[i,t,s,a])}resizeBilinearBackprop(e,t,s){ee([e,t],"resizeBilinearBackprop");const[n,i,r,o]=t.shape,[,a,l]=e.shape,c=new Float32Array(n*i*r*o),p=[s&&a>1?i-1:i,s&&l>1?r-1:r],u=[s&&a>1?a-1:a,s&&l>1?l-1:l],h=p[0]/u[0],d=p[1]/u[1],m=this.readSync(e.dataId);let f=0;for(let g=0;g<n;g++){const y=g*t.strides[0];for(let w=0;w<a;w++){const x=w*h,T=Math.floor(x),A=Math.min(Math.ceil(x),i-1),_=y+T*t.strides[1],E=y+A*t.strides[1],F=x-T,D=1-F;for(let M=0;M<l;M++){const P=M*d,B=Math.floor(P),Y=Math.min(Math.ceil(P),r-1),q=P-B,K=1-q,H=_+B*t.strides[2],Q=_+Y*t.strides[2],J=E+B*t.strides[2],ie=E+Y*t.strides[2],ne=D*K,le=D*q,ue=F*K,oe=F*q;for(let de=0;de<o;de++){const Ae=m[f++];c[H+de]+=Ae*ne,c[Q+de]+=Ae*le,c[J+de]+=Ae*ue,c[ie+de]+=Ae*oe}}}}return ts(c,[n,r,i,o],t.dtype)}resizeNearestNeighbor(e,t,s,n){ee(e,"resizeNearestNeighbor");const[i,r,o,a]=e.shape,l=this.readSync(e.dataId),c=new Float32Array(i*t*s*a),p=[n&&t>1?r-1:r,n&&s>1?o-1:o],u=[n&&t>1?t-1:t,n&&s>1?s-1:s],h=p[0]/u[0],d=p[1]/u[1];let m=0;for(let f=0;f<i;f++){const g=f*e.strides[0];for(let y=0;y<t;y++){const w=h*y,x=Math.min(r-1,n?Math.round(w):Math.floor(w)),T=g+x*e.strides[1];for(let A=0;A<s;A++){const _=d*A,E=Math.min(o-1,n?Math.round(_):Math.floor(_)),F=T+E*e.strides[2];for(let D=0;D<a;D++){const M=l[F+D];c[m++]=M}}}}return ze(c,[i,t,s,a],e.dtype)}resizeNearestNeighborBackprop(e,t,s){ee([e,t],"resizeNearestNeighborBackprop");const[n,i,r,o]=t.shape,[,a,l]=e.shape,c=new Float32Array(n*i*r*o),p=this.readSync(e.dataId),u=[s&&a>1?i-1:i,s&&l>1?r-1:r],h=[s&&a>1?a-1:a,s&&l>1?l-1:l],d=u[0]/h[0],m=u[1]/h[1],f=1/d,g=1/m,y=Math.ceil(f)*2+2,w=Math.ceil(g)*2+2;for(let x=0;x<n;x++){const T=x*t.strides[0];for(let A=0;A<i;A++){const _=T+A*t.strides[1],E=Math.floor(A*f),F=Math.floor(E-y/2);for(let D=0;D<r;D++){const M=_+D*t.strides[2],P=Math.floor(D*g),B=Math.floor(P-w/2);for(let Y=0;Y<o;Y++){let q=0;for(let K=0;K<y;K++){const H=K+F;if(H<0||H>=a)continue;const Q=T+H*e.strides[1],J=H*d,ie=Math.min(i-1,s?Math.round(J):Math.floor(J));if(A!==ie)continue;for(let ne=0;ne<w;ne++){const le=ne+B;if(le<0||le>=l)continue;const ue=Q+le*e.strides[2],oe=le*m,de=Math.min(r-1,s?Math.round(oe):Math.floor(oe));D===de&&(q+=p[ue+Y])}}c[M+Y]=q}}}}return ts(c,t.shape,t.dtype)}localResponseNormalization4D(e,t,s,n,i){ee(e,"localResponseNormalization4D");const r=e.shape[3],o=r-1,a=this.readSync(e.dataId),l=e.size,c=new Float32Array(l);function p(u){const h=u%r;let d=u-h+Math.max(0,h-t);const m=u-h+Math.min(h+t,o);let f=0;for(;d<=m;d++){const g=a[d];f+=g*g}return f}for(let u=0;u<l;u++){const h=p(u),d=a[u]*Math.pow(s+n*h,-i);c[u]=d}return ts(c,e.shape)}LRNGrad(e,t,s,n,i,r,o){ee(e,"LRNGrad");const a=e.shape[3],l=this.readSync(e.dataId),c=this.readSync(t.dataId),p=this.readSync(s.dataId),u=new Float32Array(e.size),h=e.size;for(let d=0;d<h;d++){const m=d%a,f=d-m+Math.max(0,m-n),g=d-m+Math.min(a,m+n+1);let y=0;for(let w=f;w<g;w++)y+=Math.pow(c[w],2);y=r*y+i;for(let w=f;w<g;w++){let x=-2*r*o*c[w]*p[d]/y;d===w&&(x+=Math.pow(y,-o)),x*=l[d],u[w]+=x}}return ts(u,e.shape)}multinomial(e,t,s,n){ee(e,"multinomial");const i=t?e:es(e),r=i.shape[0],o=i.shape[1],a=ye([r,s],"int32"),l=this.readSync(a.dataId),c=this.readSync(i.dataId);for(let p=0;p<r;++p){const u=p*o,h=new Float32Array(o-1);h[0]=c[u];for(let f=1;f<h.length;++f)h[f]=h[f-1]+c[u+f];const d=XN.alea(n.toString()),m=p*s;for(let f=0;f<s;++f){const g=d();l[m+f]=h.length;for(let y=0;y<h.length;y++)if(g<h[y]){l[m+f]=y;break}}}return a}oneHot(e,t,s,n){ee(e,"oneHot");const i=new Float32Array(e.size*t);i.fill(n);const r=this.readSync(e.dataId);for(let o=0;o<e.size;++o)r[o]>=0&&r[o]<t&&(i[o*t+r[o]]=s);return as(i,[e.size,t],"int32")}nonMaxSuppression(e,t,s,n,i){ee(e,"nonMaxSuppression");const r=this.readSync(e.dataId),o=this.readSync(t.dataId);return EB(r,o,s,n,i)}depthToSpace(e,t,s){N.assert(s==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${s}`),N.assert(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`);const n=e.shape[0],i=e.shape[1],r=e.shape[2],o=e.shape[3],a=i*t,l=r*t,c=o/(t*t),p=this.readSync(e.dataId),u=new Float32Array(n*a*l*c);let h=0;for(let d=0;d<n;++d)for(let m=0;m<a;++m){const f=Math.floor(m/t),g=m%t;for(let y=0;y<l;++y){const w=Math.floor(y/t),x=y%t,T=(g*t+x)*c;for(let A=0;A<c;++A){const _=A+T,E=_+o*(w+r*(f+i*d));u[h++]=p[E]}}}return ts(u,[n,a,l,c])}broadcastedBinaryOp(e,t,s,n){const i=U.assertAndGetBroadcastShape(e.shape,t.shape),r=ge(i,s),o=this.readSync(e.dataId),a=this.readSync(t.dataId),l=U.getBroadcastDims(e.shape,i),c=U.getBroadcastDims(t.shape,i),p=r.values;if(l.length+c.length===0)for(let u=0;u<p.length;++u)p[u]=n(o[u%o.length],a[u%a.length]);else{const u=this.bufferSync(e),h=this.bufferSync(t);for(let d=0;d<p.length;++d){const m=r.indexToLoc(d),f=m.slice(-e.rank);l.forEach(x=>f[x]=0);const g=u.locToIndex(f),y=m.slice(-t.rank);c.forEach(x=>y[x]=0);const w=h.locToIndex(y);p[d]=n(o[g],a[w])}}return r.toTensor()}split(e,t,s){return _B(e,t,s)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}cropAndResize(e,t,s,n,i,r){const[o,a,l,c]=e.shape,p=t.shape[0],[u,h]=n,d=ge([p,u,h,c],"float32"),m=this.readSync(t.dataId),f=this.readSync(s.dataId),g=this.readSync(e.dataId),y=e.strides,w=d.strides;for(let x=0;x<p;x++){const T=x*4,A=m[T],_=m[T+1],E=m[T+2],F=m[T+3],D=f[x];if(D>=o)continue;const M=u>1?(E-A)*(a-1)/(u-1):0,P=h>1?(F-_)*(l-1)/(h-1):0;for(let B=0;B<u;B++){const Y=u>1?A*(a-1)+B*M:.5*(A+E)*(a-1);if(Y<0||Y>a-1){for(let q=0;q<h;q++)for(let K=0;K<c;K++){const H=K+q*w[2]+B*w[1]+x*w[0];d.values[H]=r}continue}if(i==="bilinear"){const q=Math.floor(Y),K=Math.ceil(Y),H=Y-q;for(let Q=0;Q<h;Q++){const J=h>1?_*(l-1)+Q*P:.5*(_+F)*(l-1);if(J<0||J>l-1){for(let ue=0;ue<c;ue++){const oe=ue+Q*w[2]+B*w[1]+x*w[0];d.values[oe]=r}continue}const ie=Math.floor(J),ne=Math.ceil(J),le=J-ie;for(let ue=0;ue<c;ue++){let oe=ue+ie*y[2]+q*y[1]+D*y[0];const de=g[oe];oe=ue+ne*y[2]+q*y[1]+D*y[0];const Ae=g[oe];oe=ue+ie*y[2]+K*y[1]+D*y[0];const Me=g[oe];oe=ue+ne*y[2]+K*y[1]+D*y[0];const Qe=g[oe],St=de+(Ae-de)*le,$t=Me+(Qe-Me)*le;oe=ue+Q*w[2]+B*w[1]+x*w[0],d.values[oe]=St+($t-St)*H}}}else for(let q=0;q<h;++q){const K=h>1?_*(l-1)+q*P:.5*(_+F)*(l-1);if(K<0||K>l-1){for(let J=0;J<c;J++){const ie=J+q*w[2]+B*w[1]+x*w[0];d.values[ie]=r}continue}const H=Math.round(K),Q=Math.round(Y);for(let J=0;J<c;J++){const ie=J+H*y[2]+Q*y[1]+D*y[0],ne=J+q*w[2]+B*w[1]+x*w[0];d.values[ne]=g[ie]}}}}return d.toTensor()}sparseToDense(e,t,s,n){const{sliceRank:i,numUpdates:r,sliceSize:o,strides:a,outputSize:l}=U.calculateShapes(t,e,s),c=!1;return this.scatter(e,t,s,l,o,r,i,a,n,c)}gatherND(e,t){const s=t.shape,n=s[s.length-1],[i,r,o,a]=U.prepareAndValidate(e,t);if(r===0)return ze([],i,e.dtype);const l=new cn([r,o],e.dtype),c=this.readSync(t.dataId),p=this.readSync(e.dataId);for(let u=0;u<r;u++){const h=[];let d=0;for(let m=0;m<n;m++){const f=c[u*n+m];d+=f*a[m],h.push(f)}if(d<0||d>=e.size/o)throw new Error(`Invalid indices: ${h} does not index into ${e.shape}`);for(let m=0;m<o;m++)l.values[u*o+m]=p[d*o+m]}return l.toTensor().reshape(i)}scatterND(e,t,s){const{sliceRank:n,numUpdates:i,sliceSize:r,strides:o,outputSize:a}=U.calculateShapes(t,e,s),l=j(0),c=!0;return this.scatter(e,t,s,a,r,i,n,o,l,c)}fill(e,t,s){s=s||N.inferDtype(t);const n=N.getArrayFromDType(s,N.sizeFromShape(e));return n.fill(t),Ms().makeTensor(n,e,s,this)}onesLike(e){if(e.dtype==="string")throw new Error("onesLike is not supported for string tensors");return this.fill(e.shape,1,e.dtype)}zerosLike(e){const t=N.getArrayFromDType(e.dtype,N.sizeFromShape(e.shape));return this.makeOutput(t,e.shape,e.dtype)}linspace(e,t,s){return U.linspaceImpl(e,t,s)}scatter(e,t,s,n,i,r,o,a,l,c){const p=[n/i,i],u=this.readSync(e.dataId),h=this.readSync(t.dataId);if(n===0)return ze([],s,t.dtype);const d=new cn(p,t.dtype);d.values.fill(this.readSync(l.dataId)[0]);for(let m=0;m<r;m++){const f=[];let g=0;for(let y=0;y<o;y++){const w=u[m*o+y];f.push(w),g+=w*a[y]}if(g<0||g>=n/i)throw new Error(`Invalid indices: ${f} does not index into ${s}`);for(let y=0;y<i;y++)c?d.values[g*i+y]+=h[m*i+y]:d.values[g*i+y]=t.rank===0?h[0]:h[m*i+y]}return d.toTensor().reshape(s)}}function gw(e){const t=new Float32Array(e.length);for(let s=0;s<e.length;++s)t[s]=Math.abs(e[s]);return t}const MB=e=>{const{x:t}=e.inputs,s=e.backend;let n=new Float32Array(N.sizeFromShape(t.shape));if(t.dtype!=="complex64"){const i=s.data.get(t.dataId).values;n=gw(i)}else{const i=s.data.get(t.dataId),r=i.complexTensorInfos.real,o=i.complexTensorInfos.imag,a=s.data.get(r.dataId).values,l=s.data.get(o.dataId).values;for(let c=0;c<a.length;c++){const p=a[c],u=l[c];n[c]=Math.hypot(p,u)}}return s.makeOutput(n,t.shape,"float32")},JN={kernelName:yo,backendName:"cpu",kernelFunc:MB};function Bs(e){return(t,s,n,i,r)=>{const o=U.assertAndGetBroadcastShape(t,s),a=o.length,l=N.computeStrides(o),c=N.sizeFromShape(o),p=N.getTypedArrayFromDType(r,c),u=t.length,h=s.length,d=N.computeStrides(t),m=N.computeStrides(s),f=U.getBroadcastDims(t,o),g=U.getBroadcastDims(s,o);if(f.length+g.length===0)for(let y=0;y<p.length;++y)p[y]=e(n[y%n.length],i[y%i.length]);else for(let y=0;y<p.length;++y){const w=N.indexToLoc(y,a,l),x=w.slice(-u);f.forEach(E=>x[E]=0);const T=N.locToIndex(x,u,d),A=w.slice(-h);g.forEach(E=>A[E]=0);const _=N.locToIndex(A,h,m);p[y]=e(n[T],i[_])}return[p,o]}}function Rs(e){const{inputs:t,backend:s}=e,{real:n,imag:i}=t,r=s.data.get(n.dataId).values,o=s.data.get(i.dataId).values,a=s.makeTensorInfo(n.shape,"complex64"),l=s.data.get(a.dataId);return l.complexTensorInfos={real:s.makeTensorInfo(n.shape,"float32",r),imag:s.makeTensorInfo(i.shape,"float32",o)},a}const ZN={kernelName:vc,backendName:"cpu",kernelFunc:Rs};function fi(e){const{inputs:t,backend:s}=e,{x:n}=t;return s.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}const QN={kernelName:Ti,backendName:"cpu",kernelFunc:fi};function ao(e){const{inputs:t,backend:s}=e,{input:n}=t,i=s.data.get(n.dataId).complexTensorInfos.real,r=s.data.get(i.dataId).values;return s.makeTensorInfo(i.shape,i.dtype,r)}const eC={kernelName:Kc,backendName:"cpu",kernelFunc:ao};function Dl(e){const{inputs:t,backend:s,attrs:n}=e,{x:i}=t,{dtype:r}=n;if(r==="complex64"){if(i.dtype==="complex64")return fi({inputs:{x:i},backend:s});const o=ye(i.shape),a=Dl({inputs:{x:i},backend:s,attrs:{dtype:"float32"}}),l=Rs({inputs:{real:a,imag:o},backend:s});return o.dispose(),s.disposeIntermediateTensorInfo(a),l}if(i.dtype==="complex64"){const o=ao({inputs:{input:i},backend:s}),a=Dl({inputs:{x:o},backend:s,attrs:{dtype:r}});return s.disposeIntermediateTensorInfo(o),a}if(!N.hasEncodingLoss(i.dtype,r)){const o=fi({inputs:{x:i},backend:s});return{dataId:o.dataId,shape:o.shape,dtype:r}}if(r==="int32"){const o=s.data.get(i.dataId).values,a=Int32Array.from(o);return s.makeTensorInfo(i.shape,"int32",a)}if(r==="bool"){const o=s.data.get(i.dataId).values,a=N.toTypedArray([0],i.dtype),[l,c]=Bs((p,u)=>p!==u?1:0)(i.shape,[],o,a,"bool");return s.makeTensorInfo(c,"bool",l)}throw new Error(`Error in Cast: failed to cast ${i.dtype} to ${r}`)}const tC={kernelName:Ii,backendName:"cpu",kernelFunc:Dl};function An(e,t,s,n){return s==null?({inputs:i,backend:r})=>{const{a:o,b:a}=i,l=r;ee([o,a],e);const c=l.data.get(o.dataId).values,p=l.data.get(a.dataId).values,u=n||o.dtype,[h,d]=t(o.shape,a.shape,c,p,u);return l.makeTensorInfo(d,u,h)}:({inputs:i,backend:r})=>{const{a:o,b:a}=i,l=r;if(o.dtype==="complex64"||a.dtype==="complex64"){const c=Dl({inputs:{x:o},backend:l,attrs:{dtype:"complex64"}}),p=l.data.get(c.dataId),u=p.complexTensorInfos.real,h=p.complexTensorInfos.imag,d=l.data.get(u.dataId).values,m=l.data.get(h.dataId).values,f=Dl({inputs:{x:a},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(f.dataId),y=g.complexTensorInfos.real,w=g.complexTensorInfos.imag,x=l.data.get(y.dataId).values,T=l.data.get(w.dataId).values,[A,_,E]=s(o.shape,a.shape,d,m,x,T),F=l.makeTensorInfo(E,"float32",A),D=l.makeTensorInfo(E,"float32",_),M=Rs({inputs:{real:F,imag:D},backend:l});return l.disposeIntermediateTensorInfo(c),l.disposeIntermediateTensorInfo(f),l.disposeIntermediateTensorInfo(F),l.disposeIntermediateTensorInfo(D),M}else{const c=l.data.get(o.dataId).values,p=l.data.get(a.dataId).values,u=n||o.dtype,[h,d]=t(o.shape,a.shape,c,p,u);return l.makeTensorInfo(d,u,h)}}}function Fl(e){return(t,s,n,i,r,o)=>{const a=U.assertAndGetBroadcastShape(t,s),l=N.sizeFromShape(a),c=a.length,p=N.computeStrides(a),u=N.getTypedArrayFromDType("float32",l),h=N.getTypedArrayFromDType("float32",l),d=U.getBroadcastDims(t,a),m=U.getBroadcastDims(s,a),f=U.mergeRealAndImagArrays(n,i),g=U.mergeRealAndImagArrays(r,o),y=t.length,w=N.computeStrides(t),x=s.length,T=N.computeStrides(s);if(d.length+m.length===0)for(let A=0;A<u.length;A++){const _=A%f.length,E=A%g.length,F=e(f[_*2],f[_*2+1],g[E*2],g[E*2+1]);u[A]=F.real,h[A]=F.imag}else for(let A=0;A<u.length;A++){const _=N.indexToLoc(A,c,p),E=_.slice(-y);d.forEach(B=>E[B]=0);const F=N.locToIndex(E,y,w),D=_.slice(-x);m.forEach(B=>D[B]=0);const M=N.locToIndex(D,x,T),P=e(f[F*2],f[F*2+1],g[M*2],g[M*2+1]);u[A]=P.real,h[A]=P.imag}return[u,h,a]}}const yw=Bs((e,t)=>e+t),UB=Fl((e,t,s,n)=>({real:e+s,imag:t+n})),bw=An(Kn,yw,UB),sC={kernelName:Kn,backendName:"cpu",kernelFunc:bw};function Nn(e){return(t,s,n)=>{const i=N.getTypedArrayFromDType(s,t.length);for(let r=0;r<t.length;++r)i[r]=e(t[r],n);return i}}function fe(e,t,s){return({inputs:n,attrs:i,backend:r})=>{const{x:o}=n;if(ee(o,e),o.dtype==="string"||s==="string")throw new Error("unaryKernelFunc does not support string input/output");const a=r,l=a.data.get(o.dataId).values,c=N.sizeFromShape(o.shape),p=s||o.dtype,u=N.getArrayFromDType(p,c);for(let h=0;h<c;++h)u[h]=t(l[h],i);return a.makeTensorInfo(o.shape,p,u)}}function Cn(e,t,s){return({inputs:n,attrs:i,backend:r})=>{const{x:o}=n;if(ee(o,e),o.dtype==="string"||s==="string")throw new Error("unaryKernelFunc does not support string input/output");const a=r,l=a.data.get(o.dataId).values,c=s||o.dtype,p=t(l,c,i);return a.makeTensorInfo(o.shape,c,p)}}const ww=Nn(e=>Math.ceil(e)),$B=Cn(cr,ww),nC={kernelName:cr,backendName:"cpu",kernelFunc:$B};const xw=Nn(e=>Math.exp(e)),WB=Cn(mr,xw),iC={kernelName:mr,backendName:"cpu",kernelFunc:WB};const Lw=Nn(e=>Math.expm1(e)),zB=Cn(fr,Lw),rC={kernelName:fr,backendName:"cpu",kernelFunc:zB};const Sw=Nn(e=>Math.floor(e)),PB=Cn(gr,Sw),oC={kernelName:gr,backendName:"cpu",kernelFunc:PB};const Iw=Nn(e=>Math.log(e)),BB=Cn(xr,Iw),aC={kernelName:xr,backendName:"cpu",kernelFunc:BB};function uf(e,t,s,n){const i=N.getTypedArrayFromDType(n,N.sizeFromShape(s));for(let r=0;r<i.length;++r){const o=r*t;let a=e[o];for(let l=0;l<t;++l){const c=e[o+l];c>a&&(a=c)}i[r]=a}return i}const vw=Bs((e,t)=>e*t),jB=Fl((e,t,s,n)=>({real:e*s-t*n,imag:e*n+t*s})),Tw=An(Sr,vw,jB),lC={kernelName:Sr,backendName:"cpu",kernelFunc:Tw};const Aw=Nn(e=>1/Math.sqrt(e)),VB=Cn(Tr,Aw),cC={kernelName:Tr,backendName:"cpu",kernelFunc:VB};function Nw(e,t,s,n,i){const r=Fs.isSliceContinous(n,t,s),o=N.sizeFromShape(s),a=N.computeStrides(n);if(r){const c=Fs.computeFlatOffset(t,a);return e.subarray(c,c+o)}const l=N.getTypedArrayFromDType(i,o);for(let c=0;c<o;++c){const p=s.length,u=N.computeStrides(s),h=N.indexToLoc(c,p,u),d=h.map((f,g)=>f+t[g]),m=N.locToIndex(d,n.length,a);l[c]=e[m]}return l}function hf(e){const{inputs:t,backend:s,attrs:n}=e,{x:i}=t,{begin:r,size:o}=n;ee(i,"slice");const[a,l]=Fs.parseSliceParams(i,r,o);Fs.assertParamsValid(i,a,l);const c=s.data.get(i.dataId).values,p=Nw(c,a,l,i.shape,i.dtype);return s.makeTensorInfo(l,i.dtype,p)}const pC={kernelName:Co,backendName:"cpu",kernelFunc:hf};const Cw=Bs((e,t)=>e-t),GB=Fl((e,t,s,n)=>({real:e-s,imag:t-n})),Rw=An(_r,Cw,GB),uC={kernelName:_r,backendName:"cpu",kernelFunc:Rw};function Ml(e,t,s,n,i){const r=t.length,o=N.sizeFromShape(t),a=N.computeStrides(t),l=N.computeStrides(i),c=N.getTypedArrayFromDType(s,N.sizeFromShape(i));for(let p=0;p<o;++p){const u=N.indexToLoc(p,r,a),h=new Array(u.length);for(let m=0;m<h.length;m++)h[m]=u[n[m]];const d=N.locToIndex(h,r,l);c[d]=e[p]}return c}function df(e,t,s,n){const i=N.parseAxisParam(t,s)[0],r=[1,s[0],1];for(let m=0;m<i;m++)r[0]*=s[m];r[1]=s[i];for(let m=i+1;m<s.length;m++)r[2]*=s[m];const o={},a=new Int32Array(s[i]),l=new cn(r,n,e),c=[],p=r[0]===1&&r[2]===1;for(let m=0;m<s[i];m++){let f;if(p)f=e[m].toString();else{const g=[];for(let y=0;y<r[0];y++)for(let w=0;w<r[2];w++)g.push(l.get(y,m,w));f=g.join(",")}if(o[f]!==void 0)a[m]=o[f];else{const g=Object.keys(o).length;o[f]=g,a[m]=g,c.push(m)}}const u=r.slice();u[1]=Object.keys(o).length;const h=new cn(u,n);c.forEach((m,f)=>{for(let g=0;g<r[0];g++)for(let y=0;y<r[2];y++)h.set(l.get(g,m,y),g,f,y)});const d=s.slice();return d[i]=u[1],{outputValues:h.values,outputShape:d,indices:a}}const Ow={};Ee(Ow,{addImpl:()=>yw,ceilImpl:()=>ww,expImpl:()=>xw,expm1Impl:()=>Lw,floorImpl:()=>Sw,logImpl:()=>Iw,maxImpl:()=>uf,multiplyImpl:()=>vw,rsqrtImpl:()=>Aw,simpleAbsImpl:()=>gw,sliceImpl:()=>Nw,subImpl:()=>Cw,transposeImpl:()=>Ml,uniqueImpl:()=>df});const Ew="2.6.0";Tp("cpu",()=>new fw,1);const qB=fe(nr,e=>Math.acos(e)),hC={kernelName:nr,backendName:"cpu",kernelFunc:qB};const HB=fe(ir,e=>Math.acosh(e)),dC={kernelName:ir,backendName:"cpu",kernelFunc:HB};const YB=fe(rr,e=>Math.asin(e)),mC={kernelName:rr,backendName:"cpu",kernelFunc:YB};const KB=fe(or,e=>Math.asinh(e)),fC={kernelName:or,backendName:"cpu",kernelFunc:KB};const XB=fe(ar,e=>Math.atan(e)),gC={kernelName:ar,backendName:"cpu",kernelFunc:XB};const JB=fe(lr,e=>Math.atanh(e)),yC={kernelName:lr,backendName:"cpu",kernelFunc:JB};function Ul(e,t,s,n,i,r){const o=i.strideHeight,a=i.strideWidth,l=i.dilationHeight,c=i.dilationWidth,p=i.effectiveFilterHeight,u=i.effectiveFilterWidth,h=i.padInfo.top,d=i.padInfo.left,m=r==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,f=ge(i.outShape,s),g=f.values,y=i.outShape[1]*i.outShape[2]*i.outShape[3],w=i.outShape[2]*i.outShape[3],x=i.outShape[3];for(let T=0;T<i.batchSize;++T){const A=T*y,_=T*n[0];for(let E=0;E<i.inChannels;++E)for(let F=0;F<i.outHeight;++F){const D=F*o-h,M=Math.max(0,D),P=Math.min(i.inHeight,p+D),B=A+F*w;for(let Y=0;Y<i.outWidth;++Y){const q=Y*a-d,K=Math.max(0,q),H=Math.min(i.inWidth,u+q);let Q=m,J=0,ie=0;for(let le=M;le<P;le+=l){const ue=_+le*n[1];for(let oe=K;oe<H;oe+=c){const de=ue+oe*n[2],Ae=e[de+E];r==="max"&&Ae>Q?Q=Ae:r==="avg"&&(J+=Ae,ie++)}if(isNaN(Q))break}const ne=B+Y*x+E;g[ne]=r==="avg"?J/ie:Q}}}return f}function mf(e,t,s,n,i=!1,r=!1){const o=ge(n.outShape,"int32"),a=n.strideHeight,l=n.strideWidth,c=n.dilationHeight,p=n.dilationWidth,u=n.effectiveFilterHeight,h=n.effectiveFilterWidth,d=n.padInfo.top,m=n.padInfo.left,f=ge(t,s,e);for(let g=0;g<n.batchSize;++g)for(let y=0;y<n.inChannels;++y)for(let w=0;w<n.outHeight;++w){const x=w*a-d;let T=x;for(;T<0;)T+=c;const A=Math.min(n.inHeight,u+x);for(let _=0;_<n.outWidth;++_){const E=_*l-m;let F=E;for(;F<0;)F+=p;const D=Math.min(n.inWidth,h+E);let M=Number.NEGATIVE_INFINITY,P=-1;for(let B=T;B<A;B+=c){const Y=B-x;for(let q=F;q<D;q+=p){const K=q-E,H=f.get(g,B,q,y);H>M&&(M=H,i?P=r?((g*n.inHeight+B)*n.inWidth+q)*n.inChannels+y:(B*n.inWidth+q)*n.inChannels+y:P=Y*h+K)}}o.set(P,g,w,_,y)}}return o}function ZB(e){const{inputs:t,backend:s,attrs:n}=e,{x:i}=t;ee(i,"avgPool");const{filterSize:r,strides:o,pad:a,dimRoundingMode:l}=n,c=1;N.assert(U.eitherStridesOrDilationsAreOne(o,c),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);const p=U.computePool2DInfo(i.shape,r,o,c,a,l);let u;if(p.filterWidth===1&&p.filterHeight===1&&N.arraysEqual(p.inShape,p.outShape))u=fi({inputs:{x:i},backend:s});else{const h=s.data.get(i.dataId).values,d=N.computeStrides(i.shape),m=Ul(h,i.shape,i.dtype,d,p,"avg");u=s.makeTensorInfo(p.outShape,i.dtype,m.values)}return u}const bC={kernelName:Si,backendName:"cpu",kernelFunc:ZB};function QB(e){const{inputs:t,backend:s,attrs:n}=e,{dy:i,input:r}=t,o=r;ee([i,r],"avgPoolBackprop");const{filterSize:a,strides:l,pad:c}=n,p=U.computePool2DInfo(o.shape,a,l,1,c),u=p.strideHeight,h=p.strideWidth,d=p.filterHeight,m=p.filterWidth,f=p.dilationHeight,g=p.dilationWidth,y=p.effectiveFilterHeight,w=p.effectiveFilterWidth,x=w-1-p.padInfo.left,T=y-1-p.padInfo.top,A=ge(o.shape,"float32"),_=1/(d*m),E=s.data.get(i.dataId).values,F=ge(i.shape,"float32",E);for(let D=0;D<p.batchSize;++D)for(let M=0;M<p.inChannels;++M)for(let P=0;P<p.inHeight;++P)for(let B=0;B<p.inWidth;++B){const Y=P-T,q=B-x;let K=0;for(let H=0;H<y;H+=f){const Q=(Y+H)/u;if(Q<0||Q>=p.outHeight||Math.floor(Q)!==Q)continue;for(let J=0;J<w;J+=g){const ie=(q+J)/h;if(ie<0||ie>=p.outWidth||Math.floor(ie)!==ie)continue;const ne=F.get(D,Q,ie,M);K+=ne}}A.set(K*_,D,P,B,M)}return s.makeTensorInfo(A.shape,A.dtype,A.values)}const wC={kernelName:wo,backendName:"cpu",kernelFunc:QB};function ej(e){const{inputs:t,backend:s,attrs:n}=e,{x:i,scale:r,offset:o,mean:a,variance:l}=t;N.assert(a.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),N.assert(o==null||a.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),N.assert(r==null||a.shape.length===r.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),ee([i,a,l,r,o],"batchNorm");let{varianceEpsilon:c}=n;c==null&&(c=.001);const p=s.data.get(i.dataId).values,u=s.data.get(a.dataId).values,h=s.data.get(l.dataId).values,d=r?s.data.get(r.dataId).values:new Float32Array([1]),m=o?s.data.get(o.dataId).values:new Float32Array([0]),f=new Float32Array(p.length),g=m.length,y=d.length,w=h.length,x=u.length;let T=0,A=0,_=0,E=0;for(let F=0;F<p.length;++F)f[F]=m[T++]+(p[F]-u[A++])*d[_++]/Math.sqrt(h[E++]+c),T>=g&&(T=0),A>=x&&(A=0),_>=y&&(_=0),E>=w&&(E=0);return s.makeTensorInfo(i.shape,i.dtype,f)}const xC={kernelName:vi,backendName:"cpu",kernelFunc:ej};const tj=fe(pr,(e,t)=>{const s=t;return e>s.clipValueMax?s.clipValueMax:e<s.clipValueMin?s.clipValueMin:e}),LC={kernelName:pr,backendName:"cpu",kernelFunc:tj};function $l(e){const{inputs:t,backend:s}=e,{input:n}=t,i=s.data.get(n.dataId).complexTensorInfos.imag,r=s.data.get(i.dataId).values;return s.makeTensorInfo(i.shape,i.dtype,r)}const SC={kernelName:Fc,backendName:"cpu",kernelFunc:$l};function Rn(e){const{inputs:t,backend:s,attrs:n}=e,{x:i}=t,{shape:r}=n,o=N.sizeFromShape(i.shape),a=N.inferFromImplicitShape(r,o),l=N.sizeFromShape(a);N.assert(o===l,()=>`The new shape (${a}) has ${l} elements and the old shape (${i.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`),s.incRef(i.dataId);const c=s.data.get(i.dataId);if(c.complexTensorInfos!=null){const p=c.complexTensorInfos.real,u=c.complexTensorInfos.imag;p.shape=a,u.shape=a}return{dataId:i.dataId,shape:a,dtype:i.dtype}}const IC={kernelName:Ci,backendName:"cpu",kernelFunc:Rn};function Wl(e){const{inputs:t,backend:s,attrs:n}=e,{axis:i}=n,r=N.parseAxisParam(i,t[0].shape)[0];let o=U.computeOutShape(t.map(d=>d.shape),r);if(N.sizeFromShape(o)===0)return s.makeTensorInfo(o,t[0].dtype,[]);const a=t.filter(d=>N.sizeFromShape(d.shape)>0);if(a.length===1)return a[0];const l=a.map(d=>d.shape);if(U.assertParamsConsistent(l,r),a[0].dtype==="complex64"){const d=a.map(w=>ao({inputs:{input:w},backend:s})),m=a.map(w=>$l({inputs:{input:w},backend:s})),f=Wl({inputs:d,backend:s,attrs:{axis:i}}),g=Wl({inputs:m,backend:s,attrs:{axis:i}}),y=Rs({inputs:{real:f,imag:g},backend:s});return d.forEach(w=>s.disposeIntermediateTensorInfo(w)),m.forEach(w=>s.disposeIntermediateTensorInfo(w)),s.disposeIntermediateTensorInfo(f),s.disposeIntermediateTensorInfo(g),y}const c=a.map(d=>{const m=N.sizeFromShape(d.shape.slice(r)),f=[-1,m];return Rn({inputs:{x:d},backend:s,attrs:{shape:f}})});o=U.computeOutShape(c.map(d=>d.shape),1);const p=N.getTypedArrayFromDType(a[0].dtype,N.sizeFromShape(o));if(c[0].shape[0]===1){let d=0;c.forEach(m=>{const f=s.data.get(m.dataId).values,g=N.sizeFromShape(m.shape);p.set(f,d),d+=g})}else{let d=0;c.forEach(m=>{const f=s.data.get(m.dataId).values;let g=0;for(let y=0;y<m.shape[0];++y){const w=y*o[1]+d;for(let x=0;x<m.shape[1];++x)p[w+x]=f[g++]}d+=m.shape[1]})}const u=U.computeOutShape(a.map(d=>d.shape),r),h=s.makeTensorInfo(u,t[0].dtype,p);return c.forEach(d=>s.disposeIntermediateTensorInfo(d)),h}const vC={kernelName:xo,backendName:"cpu",kernelFunc:Wl};const sj=fe(Xn,e=>Math.cos(e)),TC={kernelName:Xn,backendName:"cpu",kernelFunc:sj};const nj=fe(ur,e=>Math.cosh(e)),AC={kernelName:ur,backendName:"cpu",kernelFunc:nj};const NC={kernelName:Lo,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:s})=>{const{x:n,filter:i}=e,{strides:r,pad:o,dilations:a}=s,l=t,c=l.data.get(n.dataId).values,p=n.shape.length,u=l.data.get(i.dataId).values,h=i.shape.length,{batchSize:d,inHeight:m,inWidth:f,inChannels:g,outHeight:y,outWidth:w,padInfo:x,strideHeight:T,strideWidth:A,filterHeight:_,filterWidth:E,dilationHeight:F,dilationWidth:D,outShape:M}=U.computeDilation2DInfo(n.shape,i.shape,r,o,"NHWC",a),P=N.sizeFromShape(M),B=M.length,Y=N.getArrayFromDType(n.dtype,P);for(let K=0;K<d;++K)for(let H=0;H<y;++H){const Q=H*T-x.top;for(let J=0;J<w;++J){const ie=J*A-x.left;for(let ne=0;ne<g;++ne){let le=Number.MIN_SAFE_INTEGER;for(let oe=0;oe<_;++oe){const de=Q+oe*F;if(de>=0&&de<m)for(let Ae=0;Ae<E;++Ae){const Me=ie+Ae*D;if(Me>=0&&Me<f){const Qe=N.locToIndex([K,de,Me,ne],p,N.computeStrides(n.shape)),St=N.locToIndex([oe,Ae,ne],h,N.computeStrides(i.shape)),$t=c[Qe]+u[St];$t>le&&(le=$t)}}}const ue=N.locToIndex([K,H,J,ne],B,N.computeStrides(M));Y[ue]=le}}}const q=l.write(N.toTypedArray(Y,n.dtype),M,n.dtype);return{dataId:q,shape:M,dtype:n.dtype}}};const CC={kernelName:Ea,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:s})=>{const{x:n,filter:i,dy:r}=e,{strides:o,pad:a,dilations:l}=s,c=t,p=N.toNestedArray(n.shape,c.data.get(n.dataId).values),u=N.toNestedArray(i.shape,c.data.get(i.dataId).values),{batchSize:h,inHeight:d,inWidth:m,inChannels:f,outHeight:g,outWidth:y,padInfo:w,strideHeight:x,strideWidth:T,filterHeight:A,filterWidth:_,dilationHeight:E,dilationWidth:F,outShape:D}=U.computeDilation2DInfo(n.shape,i.shape,o,a,"NHWC",l);N.assert(r.rank===D.length,()=>`Error in ${Ea}, dy must have the same rank as output ${D.length}, but got ${r.rank}`);const M=N.toNestedArray(D,c.data.get(r.dataId).values),P=N.makeZerosNestedTypedArray(i.shape,i.dtype);for(let Y=0;Y<h;++Y)for(let q=0;q<g;++q){const K=q*x-w.top;for(let H=0;H<y;++H){const Q=H*T-w.left;for(let J=0;J<f;++J){let ie=Number.MIN_SAFE_INTEGER,ne=0,le=0;for(let ue=0;ue<A;++ue){const oe=K+ue*E;if(oe>=0&&oe<d)for(let de=0;de<_;++de){const Ae=Q+de*F;if(Ae>=0&&Ae<m){const Me=p[Y][oe][Ae][J]+u[ue][de][J];Me>ie&&(ie=Me,ne=ue,le=de)}}}P[ne][le][J]+=M[Y][q][H][J]}}}const B=c.write(N.toTypedArray(P,n.dtype),i.shape,i.dtype);return{dataId:B,shape:i.shape,dtype:i.dtype}}};const RC={kernelName:Oa,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:s})=>{const{x:n,filter:i,dy:r}=e,{strides:o,pad:a,dilations:l}=s,c=t,p=N.toNestedArray(n.shape,c.data.get(n.dataId).values),u=N.toNestedArray(i.shape,c.data.get(i.dataId).values),{batchSize:h,inHeight:d,inWidth:m,inChannels:f,outHeight:g,outWidth:y,padInfo:w,strideHeight:x,strideWidth:T,filterHeight:A,filterWidth:_,dilationHeight:E,dilationWidth:F,outShape:D}=U.computeDilation2DInfo(n.shape,i.shape,o,a,"NHWC",l);N.assert(r.rank===D.length,()=>`Error in ${Oa}, dy must have the same rank as output ${D.length}, but got ${r.rank}`);const M=N.toNestedArray(D,c.data.get(r.dataId).values),P=N.makeZerosNestedTypedArray(n.shape,n.dtype);for(let Y=0;Y<h;++Y)for(let q=0;q<g;++q){const K=q*x-w.top;for(let H=0;H<y;++H){const Q=H*T-w.left;for(let J=0;J<f;++J){let ie=Number.MIN_SAFE_INTEGER,ne=K<0?0:K,le=Q<0?0:Q;for(let ue=0;ue<A;++ue){const oe=K+ue*E;if(oe>=0&&oe<d)for(let de=0;de<_;++de){const Ae=Q+de*F;if(Ae>=0&&Ae<m){const Me=p[Y][oe][Ae][J]+u[ue][de][J];Me>ie&&(ie=Me,ne=oe,le=Ae)}}}P[Y][ne][le][J]+=M[Y][q][H][J]}}}const B=c.write(N.toTypedArray(P,n.dtype),n.shape,n.dtype);return{dataId:B,shape:n.shape,dtype:n.dtype}}};const ij=Bs((e,t)=>e/t),rj=An(Jn,ij),fu={kernelName:Jn,backendName:"cpu",kernelFunc:rj};const oj=fe(hr,e=>e>=0?e:Math.exp(e)-1),OC={kernelName:hr,backendName:"cpu",kernelFunc:oj};const aj=U.ERF_P,lj=U.ERF_A1,cj=U.ERF_A2,pj=U.ERF_A3,uj=U.ERF_A4,hj=U.ERF_A5,dj=fe(dr,e=>{const t=Math.sign(e),s=Math.abs(e),n=1/(1+aj*s);return t*(1-((((hj*n+uj)*n+pj)*n+cj)*n+lj)*n*Math.exp(-s*s))}),EC={kernelName:dr,backendName:"cpu",kernelFunc:dj};function ff(e,t,s){const n=e.shape,i=n[0],r=n[1],o=s.data.get(e.dataId),a=o.complexTensorInfos.real,l=o.complexTensorInfos.imag,c=[i,r],p=N.sizeFromShape(c),u=N.getTypedArrayFromDType("float32",p),h=N.getTypedArrayFromDType("float32",p);for(let g=0;g<i;g++){const y=hf({inputs:{x:a},backend:s,attrs:{begin:[g,0],size:[1,r]}}),w=hf({inputs:{x:l},backend:s,attrs:{begin:[g,0],size:[1,r]}}),x=Rs({inputs:{real:y,imag:w},backend:s}),{real:T,imag:A}=mj(x,t,s),_=U.mergeRealAndImagArrays(T,A);for(let E=0;E<r;E++){const F=U.getComplexWithIndex(_,E);u[g*r+E]=F.real,h[g*r+E]=F.imag}s.disposeIntermediateTensorInfo(y),s.disposeIntermediateTensorInfo(w),s.disposeIntermediateTensorInfo(x)}const d=s.makeTensorInfo(c,"float32",u),m=s.makeTensorInfo(c,"float32",h),f=Rs({inputs:{real:d,imag:m},backend:s});return s.disposeIntermediateTensorInfo(d),s.disposeIntermediateTensorInfo(m),f}function mj(e,t,s){const n=N.sizeFromShape(e.shape),i=s.data.get(e.dataId),r=s.data.get(i.complexTensorInfos.real.dataId).values,o=s.data.get(i.complexTensorInfos.imag.dataId).values;if(fj(n)){const a=_w(r,o,n,t,s),l=[e.shape[0],e.shape[1]];if(t){const c=s.makeTensorInfo(l,"float32",a.real),p=s.makeTensorInfo(l,"float32",a.imag),u=s.makeTensorInfo([],"float32",N.createScalarValue(n,"float32")),h=fi({inputs:{x:u},backend:s}),d=fu.kernelFunc({inputs:{a:c,b:u},backend:s}),m=fu.kernelFunc({inputs:{a:p,b:h},backend:s}),f=s.data.get(d.dataId).values,g=s.data.get(m.dataId).values;return s.disposeIntermediateTensorInfo(c),s.disposeIntermediateTensorInfo(p),s.disposeIntermediateTensorInfo(u),s.disposeIntermediateTensorInfo(h),s.disposeIntermediateTensorInfo(d),s.disposeIntermediateTensorInfo(m),{real:f,imag:g}}return a}else{const a=U.mergeRealAndImagArrays(r,o),l=gj(a,n,t);return U.splitRealAndImagArrays(l)}}function fj(e){return(e&e-1)===0}function _w(e,t,s,n,i){if(s===1)return{real:e,imag:t};const r=U.mergeRealAndImagArrays(e,t),o=s/2,a=U.complexWithEvenIndex(r),l=a.real,c=a.imag,p=[l.length],u=i.makeTensorInfo(p,"float32",l),h=i.makeTensorInfo(p,"float32",c),d=Rs({inputs:{real:u,imag:h},backend:i}),m=U.complexWithOddIndex(r),f=m.real,g=m.imag,y=[f.length],w=i.makeTensorInfo(y,"float32",f),x=i.makeTensorInfo(y,"float32",g),T=Rs({inputs:{real:w,imag:x},backend:i}),A=_w(l,c,o,n,i),_=A.real,E=A.imag,F=[_.length],D=i.makeTensorInfo(F,"float32",_),M=i.makeTensorInfo(F,"float32",E),P=Rs({inputs:{real:D,imag:M},backend:i}),B=_w(f,g,o,n,i),Y=B.real,q=B.imag,K=[Y.length],H=i.makeTensorInfo(K,"float32",Y),Q=i.makeTensorInfo(K,"float32",q),J=Rs({inputs:{real:H,imag:Q},backend:i}),ie=U.exponents(s,n),ne=[ie.real.length],le=i.makeTensorInfo(ne,"float32",ie.real),ue=i.makeTensorInfo(ne,"float32",ie.imag),oe=Rs({inputs:{real:le,imag:ue},backend:i}),de=Tw({inputs:{a:oe,b:J},backend:i}),Ae=bw({inputs:{a:P,b:de},backend:i}),Me=Rw({inputs:{a:P,b:de},backend:i}),Qe=ao({inputs:{input:Ae},backend:i}),St=ao({inputs:{input:Me},backend:i}),$t=$l({inputs:{input:Ae},backend:i}),_s=$l({inputs:{input:Me},backend:i}),yt=Wl({inputs:[Qe,St],backend:i,attrs:{axis:0}}),ps=Wl({inputs:[$t,_s],backend:i,attrs:{axis:0}}),_n=i.data.get(yt.dataId).values,Gs=i.data.get(ps.dataId).values;return i.disposeIntermediateTensorInfo(u),i.disposeIntermediateTensorInfo(h),i.disposeIntermediateTensorInfo(d),i.disposeIntermediateTensorInfo(w),i.disposeIntermediateTensorInfo(x),i.disposeIntermediateTensorInfo(T),i.disposeIntermediateTensorInfo(D),i.disposeIntermediateTensorInfo(M),i.disposeIntermediateTensorInfo(P),i.disposeIntermediateTensorInfo(H),i.disposeIntermediateTensorInfo(Q),i.disposeIntermediateTensorInfo(J),i.disposeIntermediateTensorInfo(le),i.disposeIntermediateTensorInfo(ue),i.disposeIntermediateTensorInfo(oe),i.disposeIntermediateTensorInfo(de),i.disposeIntermediateTensorInfo(Ae),i.disposeIntermediateTensorInfo(Me),i.disposeIntermediateTensorInfo(Qe),i.disposeIntermediateTensorInfo($t),i.disposeIntermediateTensorInfo(St),i.disposeIntermediateTensorInfo(_s),i.disposeIntermediateTensorInfo(yt),i.disposeIntermediateTensorInfo(ps),{real:_n,imag:Gs}}function gj(e,t,s){const n=new Float32Array(t*2);for(let i=0;i<t;i++){let r=0,o=0;for(let a=0;a<t;a++){const l=U.exponent(i*a,t,s),c=U.getComplexWithIndex(e,a);r+=c.real*l.real-c.imag*l.imag,o+=c.real*l.imag+c.imag*l.real}s&&(r/=t,o/=t),U.assignToTypedArray(n,r,o,i)}return n}function yj(e){const{inputs:t,backend:s}=e,{input:n}=t,i=N.sizeFromShape(n.shape),r=n.shape[n.shape.length-1],o=i/r,a=Rn({inputs:{x:n},backend:s,attrs:{shape:[o,r]}}),l=ff(a,!1,s),c=Rn({inputs:{x:l},backend:s,attrs:{shape:n.shape}});return s.disposeIntermediateTensorInfo(a),s.disposeIntermediateTensorInfo(l),c}const _C={kernelName:Oc,backendName:"cpu",kernelFunc:yj};const kC={kernelName:So,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{image:n}=e,i=s,r=N.getTypedArrayFromDType(n.dtype,N.sizeFromShape(n.shape)),[o,a,l,c]=n.shape,p=i.data.get(n.dataId).values;for(let h=0;h<o;h++){const d=h*l*a*c;for(let m=0;m<a;m++){const f=m*(l*c);for(let g=0;g<l;g++){const y=g*c;for(let w=0;w<c;w++){const x=[o,m,g,w],T=x[2],A=Math.round(l-T),_=d+f+y+w;let E=p[_];if(A>=0&&A<l){const F=A*c,D=d+f+F+w;E=p[D]}r[_]=E}}}}const u=i.write(r,n.shape,n.dtype);return{dataId:u,shape:n.shape,dtype:n.dtype}}};function bj(e){const{inputs:t,backend:s}=e,{input:n}=t,i=N.sizeFromShape(n.shape),r=n.shape[n.shape.length-1],o=i/r,a=Rn({inputs:{x:n},backend:s,attrs:{shape:[o,r]}}),l=ff(a,!0,s),c=Rn({inputs:{x:l},backend:s,attrs:{shape:n.shape}});return s.disposeIntermediateTensorInfo(a),s.disposeIntermediateTensorInfo(l),c}const DC={kernelName:Dc,backendName:"cpu",kernelFunc:bj};const wj=fe(yr,e=>Number.isFinite(e)?1:0,"bool"),FC={kernelName:yr,backendName:"cpu",kernelFunc:wj};const xj=fe(br,e=>Math.abs(e)===Infinity?1:0,"bool"),MC={kernelName:br,backendName:"cpu",kernelFunc:xj};const Lj=fe(wr,e=>Number.isNaN(e)?1:0,"bool"),UC={kernelName:wr,backendName:"cpu",kernelFunc:Lj};const Sj=fe(Lr,e=>Math.log1p(e)),$C={kernelName:Lr,backendName:"cpu",kernelFunc:Sj};const Ij=fe(_a,e=>e?0:1,"bool"),WC={kernelName:_a,backendName:"cpu",kernelFunc:Ij};const zC={kernelName:Ai,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{x:n}=e,{reductionIndices:i,keepDims:r}=t,o=s;let a=n.shape;const l=a.length,c=N.parseAxisParam(i,a);let p=c;const u=U.getAxesPermutation(p,l);let h=o.data.get(n.dataId).values;if(u!=null){const x=new Array(l);for(let T=0;T<x.length;T++)x[T]=a[u[T]];h=Ml(h,a,n.dtype,u,x),p=U.getInnerMostAxes(p.length,l),a=x}ee(n,"max"),U.assertAxesAreInnerMostDims("max",p,l);const[d,m]=U.computeOutAndReduceShapes(a,p),f=N.sizeFromShape(m),g=uf(h,f,d,n.dtype),y=o.write(g,d,n.dtype);let w=d;if(r){const x=U.expandShapeToKeepDim(d,c);w=x}return{dataId:y,shape:w,dtype:n.dtype}}};function vj(e){const{inputs:t,backend:s,attrs:n}=e,{x:i}=t;ee(i,"maxPool");const{filterSize:r,strides:o,pad:a,dimRoundingMode:l}=n,c=1;N.assert(U.eitherStridesOrDilationsAreOne(o,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);const p=U.computePool2DInfo(i.shape,r,o,c,a,l);let u;if(p.filterWidth===1&&p.filterHeight===1&&N.arraysEqual(p.inShape,p.outShape))u=fi({inputs:{x:i},backend:s});else{const h=s.data.get(i.dataId).values,d=N.computeStrides(i.shape),m=Ul(h,i.shape,i.dtype,d,p,"max");u=s.makeTensorInfo(p.outShape,i.dtype,m.values)}return u}const PC={kernelName:Ni,backendName:"cpu",kernelFunc:vj};function Tj(e){const{inputs:t,backend:s,attrs:n}=e,{dy:i,input:r,output:o}=t,a=r;ee([r,o],"maxPoolBackprop");const{filterSize:l,strides:c,pad:p,dimRoundingMode:u}=n,h=U.computePool2DInfo(a.shape,l,c,1,p,u),d=s.data.get(a.dataId).values,m=ge(h.outShape,a.dtype,mf(d,a.shape,a.dtype,h).values),f=h.strideHeight,g=h.strideWidth,y=h.dilationHeight,w=h.dilationWidth,x=h.effectiveFilterHeight,T=h.effectiveFilterWidth,A=T-1-h.padInfo.left,_=x-1-h.padInfo.top,E=ge(a.shape,"float32"),F=s.data.get(i.dataId).values,D=ge(i.shape,"float32",F);for(let M=0;M<h.batchSize;++M)for(let P=0;P<h.inChannels;++P)for(let B=0;B<h.inHeight;++B)for(let Y=0;Y<h.inWidth;++Y){const q=B-_,K=Y-A;let H=0;for(let Q=0;Q<x;Q+=y){const J=(q+Q)/f;if(J<0||J>=h.outHeight||Math.floor(J)!==J)continue;for(let ie=0;ie<T;ie+=w){const ne=(K+ie)/g;if(ne<0||ne>=h.outWidth||Math.floor(ne)!==ne)continue;const le=x*T-1-m.get(M,J,ne,P),ue=Q*T+ie,oe=le===ue?1:0;if(oe===0)continue;const de=D.get(M,J,ne,P);H+=de*oe}}E.set(H,M,B,Y,P)}return s.makeTensorInfo(E.shape,E.dtype,E.values)}const BC={kernelName:Io,backendName:"cpu",kernelFunc:Tj};function jC(e,t,s,n,i){const r=N.computeStrides(t),o=Ul(e,t,s,r,i,"max"),a=mf(e,t,s,i,!0,n);return[o.values,a.values]}const VC={kernelName:vo,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{x:n}=e,{filterSize:i,strides:r,pad:o,includeBatchInIndex:a}=t,l=s;ee(n,"MaxPoolWithArgmax");const c=l.data.get(n.dataId).values,p=U.computePool2DInfo(n.shape,i,r,[1,1],o),[u,h]=jC(c,n.shape,n.dtype,a,p),d=l.write(u,p.outShape,n.dtype),m=l.write(h,p.outShape,n.dtype);return[{dataId:d,shape:p.outShape,dtype:n.dtype},{dataId:m,shape:p.outShape,dtype:"int32"}]}};const Aj=vt.nonMaxSuppressionV4Impl,GC={kernelName:To,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:s})=>{const{boxes:n,scores:i}=e,{maxOutputSize:r,iouThreshold:o,scoreThreshold:a,padToMaxOutputSize:l}=s,c=t;ee(n,"NonMaxSuppressionPadded");const p=c.data.get(n.dataId).values,u=c.data.get(i.dataId).values,{selectedIndices:h,validOutputs:d}=Aj(p,u,r,o,a,l);return[h,d]}};const Nj=vt.nonMaxSuppressionV5Impl,qC={kernelName:Ao,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:s})=>{const{boxes:n,scores:i}=e,{maxOutputSize:r,iouThreshold:o,scoreThreshold:a,softNmsSigma:l}=s,c=t;ee(n,"NonMaxSuppressionWithScore");const p=c.data.get(n.dataId).values,u=c.data.get(i.dataId).values,h=r,d=o,m=a,f=l,{selectedIndices:g,selectedScores:y}=Nj(p,u,h,d,m,f);return[g,y]}};const Cj=Bs((e,t)=>e!==t?1:0),Rj=An(ka,Cj,null,"bool"),HC={kernelName:ka,backendName:"cpu",kernelFunc:Rj};function Oj(e){const{inputs:t,backend:s,attrs:n}=e,{x:i}=t,{paddings:r,constantValue:o}=n;ee(i,"pad");const a=r.map((w,x)=>w[0]+i.shape[x]+w[1]),l=r.map(w=>w[0]),c=s.data.get(i.dataId).values,p=N.sizeFromShape(i.shape),u=i.shape.length,h=N.computeStrides(i.shape),d=N.sizeFromShape(a),m=a.length,f=N.computeStrides(a),g=N.getTypedArrayFromDType(i.dtype,d);o!==0&&g.fill(o);for(let w=0;w<p;w++){const x=N.indexToLoc(w,u,h),T=x.map((_,E)=>_+l[E]),A=N.locToIndex(T,m,f);g[A]=c[w]}const y=s.write(g,a,i.dtype);return{dataId:y,shape:a,dtype:i.dtype}}const gf={kernelName:No,backendName:"cpu",kernelFunc:Oj};const Ej=fe(Ir,e=>1/e),YC={kernelName:Ir,backendName:"cpu",kernelFunc:Ej};const KC={kernelName:_o,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{image:n}=e,{radians:i,fillValue:r,center:o}=t,a=s,l=N.getTypedArrayFromDType(n.dtype,N.sizeFromShape(n.shape)),[c,p,u,h]=n.shape,[d,m]=U.getImageCenter(o,p,u),f=255,g=Math.sin(i),y=Math.cos(i),w=a.data.get(n.dataId).values;for(let T=0;T<c;T++){const A=T*u*p*h;for(let _=0;_<p;_++){const E=_*(u*h);for(let F=0;F<u;F++){const D=F*h;for(let M=0;M<h;M++){const P=[c,_,F,M],B=P[2],Y=P[1];let q=(B-d)*y-(Y-m)*g,K=(B-d)*g+(Y-m)*y;q=Math.round(q+d),K=Math.round(K+m);let H=r;if(typeof r!="number"&&(M===3?H=f:H=r[M]),q>=0&&q<u&&K>=0&&K<p){const J=K*(u*h),ie=q*h,ne=A+J+ie+M;H=w[ne]}const Q=A+E+D+M;l[Q]=H}}}}const x=a.write(l,n.shape,n.dtype);return{dataId:x,shape:n.shape,dtype:n.dtype}}};const _j=fe(vr,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}),XC={kernelName:vr,backendName:"cpu",kernelFunc:_j};const kj=U.SELU_SCALEALPHA,Dj=U.SELU_SCALE,Fj=fe(Ar,e=>e>=0?Dj*e:kj*(Math.exp(e)-1)),JC={kernelName:Ar,backendName:"cpu",kernelFunc:Fj};const Mj=fe(Rr,e=>1/(1+Math.exp(-e))),ZC={kernelName:Rr,backendName:"cpu",kernelFunc:Mj};const Uj=fe(Cr,e=>e<0?-1:e>0?1:0),QC={kernelName:Cr,backendName:"cpu",kernelFunc:Uj};const $j=fe(Zn,e=>Math.sin(e)),e0={kernelName:Zn,backendName:"cpu",kernelFunc:$j};const Wj=fe(Nr,e=>Math.sinh(e)),t0={kernelName:Nr,backendName:"cpu",kernelFunc:Wj};const zj=11920928955078125e-23,s0=Math.log(zj)+2,Pj=fe(Or,e=>{const t=e>-s0,s=e<s0,n=Math.exp(e);let i;return s?i=n:t?i=e:i=Math.log(1+n),i}),n0={kernelName:Or,backendName:"cpu",kernelFunc:Pj};function kw(e){const{inputs:t,attrs:s,backend:n}=e,{x:i}=t,{perm:r}=s;ee(i,"transpose");const o=i.shape.length,a=new Array(o);for(let u=0;u<a.length;u++)a[u]=i.shape[r[u]];const l=n.data.get(i.dataId).values,c=Ml(l,i.shape,i.dtype,r,a),p=n.write(c,a,i.dtype);return{dataId:p,shape:a,dtype:i.dtype}}const i0={kernelName:Ri,backendName:"cpu",kernelFunc:kw};function Bj(e){const{inputs:t,backend:s,attrs:n}=e,{x:i}=t,{blockShape:r,paddings:o}=n;ee([i],"spaceToBatchND");const a=N.sizeFromShape(r),l=[[0,0]];l.push(...o);for(let _=1+r.length;_<i.shape.length;++_)l.push([0,0]);const c=gf.kernelFunc({inputs:{x:i},backend:s,attrs:{paddings:l,constantValue:0}}),p=U.getReshaped(c.shape,r,a,!1),u=U.getPermuted(p.length,r.length,!1),h=U.getReshapedPermuted(c.shape,r,a,!1),d={x:c},m={shape:p},f=Rn({inputs:d,backend:s,attrs:m}),g={x:f},y={perm:u},w=kw({inputs:g,backend:s,attrs:y}),x={x:w},T={shape:h},A=Rn({inputs:x,backend:s,attrs:T});return s.disposeIntermediateTensorInfo(c),s.disposeIntermediateTensorInfo(f),s.disposeIntermediateTensorInfo(w),A}const r0={kernelName:Ro,backendName:"cpu",kernelFunc:Bj};const jj=fe(Er,e=>Math.sqrt(e)),o0={kernelName:Er,backendName:"cpu",kernelFunc:jj};const a0={kernelName:Oo,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{const{x:s}=e,n=t;ee(s,"square");const i=n.data.get(s.dataId).values,r=new Float32Array(i.length);for(let a=0;a<i.length;++a){const l=i[a];r[a]=l*l}const o=n.write(r,s.shape,s.dtype);return{dataId:o,shape:s.shape,dtype:s.dtype}}};const Vj=Bs((e,t)=>{const s=e-t;return s*s}),Gj=An(Qn,Vj),l0={kernelName:Qn,backendName:"cpu",kernelFunc:Gj};const qj=fe(Dr,(e,t)=>{const s=t;return isNaN(e)?NaN:e>0?1:s.alpha}),c0={kernelName:Dr,backendName:"cpu",kernelFunc:qj};const Hj=fe(ei,e=>Math.tan(e)),p0={kernelName:ei,backendName:"cpu",kernelFunc:Hj};const Yj=fe(kr,e=>Math.tanh(e)),u0={kernelName:kr,backendName:"cpu",kernelFunc:Yj};function Kj(e){const{inputs:t,attrs:s,backend:n}=e,{axis:i}=s,{x:r}=t;ee(r,"unique");const o=n.data.get(r.dataId).values,{outputValues:a,outputShape:l,indices:c}=df(o,i,r.shape,r.dtype);return[n.makeTensorInfo(l,r.dtype,a),n.makeTensorInfo([c.length],"int32",c)]}const h0={kernelName:Eo,backendName:"cpu",kernelFunc:Kj};const Xj=[JN,hC,dC,sC,mC,fC,gC,yC,bC,wC,xC,tC,nC,LC,ZN,vC,TC,AC,NC,RC,CC,fu,OC,EC,iC,rC,_C,kC,oC,QN,DC,SC,FC,MC,UC,aC,$C,WC,PC,BC,VC,zC,lC,GC,qC,HC,gf,eC,YC,IC,KC,XC,cC,JC,ZC,QC,e0,t0,pC,n0,r0,o0,a0,l0,c0,uC,p0,u0,i0,h0];for(const e of Xj)Ma(e);const ca={},Dw={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Fw(e,t){ca[e]=t}function nn(e){if(!(e in ca)){const s=Jj(e);if(s!==null)ca[e]=s;else return console.log("Could not get context for WebGL version",e),null}const t=ca[e];return t.isContextLost()?(delete ca[e],nn(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),ca[e])}function Zj(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 Jj(e){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");const t=Zj(e);return t.addEventListener("webglcontextlost",s=>{s.preventDefault(),delete ca[e]},!1),e===1?t.getContext("webgl",Dw)||t.getContext("experimental-webgl",Dw):t.getContext("webgl2",Dw)}var lo;(function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"})(lo||(lo={}));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 Xt;(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"})(Xt||(Xt={}));function pa(e,t){return[t,e]}function d0(e,t){return e*t}function co(e){const t=N.sizeFromShape(e),s=Math.ceil(t/4);return N.sizeToSquarishShape(s)}function gi(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function m0(e,t){const[s,n]=gi(e,t);return s*n*4}function gu(e,t){const s=e;let n,i,r,o,a,l,c,p,u,h;return W().getNumber("WEBGL_VERSION")===2?(n=s.R32F,i=s.R16F,r=s.RGBA16F,o=s.RGBA32F,a=s.RED,c=4,p=1,u=s.HALF_FLOAT,h=s.FLOAT):(n=e.RGBA,i=e.RGBA,r=e.RGBA,o=s.RGBA,a=e.RGBA,c=4,p=4,u=t!=null?t.HALF_FLOAT_OES:null,h=e.FLOAT),l=e.RGBA,{internalFormatFloat:n,internalFormatHalfFloat:i,internalFormatPackedHalfFloat:r,internalFormatPackedFloat:o,textureFormatFloat:a,downloadTextureFormat:l,downloadUnpackNumChannels:c,defaultNumChannels:p,textureTypeHalfFloat:u,textureTypeFloat:h}}function pe(e,t){const s=t();return W().getBool("DEBUG")&&Qj(e),s}function Qj(e){const t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+e3(e,t))}const t3=596e-10,s3=65504;function f0(e){return!!(W().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||t3<Math.abs(e)&&Math.abs(e)<s3)}function e3(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 yu(e,t){return Yi(e,()=>e.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function g0(e,t){const s=Yi(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(pe(e,()=>e.shaderSource(s,t)),pe(e,()=>e.compileShader(s)),e.getShaderParameter(s,e.COMPILE_STATUS)===!1)throw console.log(e.getShaderInfoLog(s)),new Error("Failed to compile vertex shader.");return s}function y0(e,t){const s=Yi(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(pe(e,()=>e.shaderSource(s,t)),pe(e,()=>e.compileShader(s)),e.getShaderParameter(s,e.COMPILE_STATUS)===!1)throw n3(t,e.getShaderInfoLog(s)),new Error("Failed to compile fragment shader.");return s}const i3=/ERROR: [0-9]+:([0-9]+):/g;function n3(e,t){const s=i3.exec(t);if(s==null){console.log(`Couldn't parse line number in error: ${t}`),console.log(e);return}const n=+s[1],i=e.split(`
`),r=i.length.toString().length+2,o=i.map((u,h)=>N.rightPad((h+1).toString(),r)+u);let a=0;for(let u=0;u<o.length;u++)a=Math.max(o[u].length,a);const l=o.slice(0,n-1),c=o.slice(n-1,n),p=o.slice(n);console.log(l.join(`
`)),console.log(t.split(`
`)[0]),console.log(`%c ${N.rightPad(c[0],a)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(p.join(`
`))}function b0(e){return Yi(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function w0(e,t){if(pe(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 yf(e,t){if(pe(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function x0(e,t){const s=Yi(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return pe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,s)),pe(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),s}function L0(e,t){const s=Yi(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return pe(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,s)),pe(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),s}function S0(e){return Yi(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function I0(e,t){const s=W().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){const n=`[${e}x${t}]`;throw new Error("Requested texture size "+n+" is invalid.")}if(e>s||t>s){const n=`[${e}x${t}]`,i=`[${s}x${s}]`;throw new Error("Requested texture size "+n+" greater than WebGL maximum on this browser / GPU "+i+".")}}function v0(e){return Yi(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function Mw(e,t,s,n,i,r,o){const a=e.getAttribLocation(t,s);return a===-1?!1:(pe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),pe(e,()=>e.vertexAttribPointer(a,i,e.FLOAT,!1,r,o)),pe(e,()=>e.enableVertexAttribArray(a)),!0)}function o3(e,t,s){r3(e,s),pe(e,()=>e.activeTexture(e.TEXTURE0+s)),pe(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function T0(e,t,s){return Yi(e,()=>e.getUniformLocation(t,s),'uniform "'+s+'" not present in program.')}function A0(e,t,s){return e.getUniformLocation(t,s)}function N0(e,t,s,n){pe(e,()=>o3(e,t,n)),pe(e,()=>e.uniform1i(s,n))}function bf(e,t,s){pe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,s)),pe(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function Uw(e,t){pe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),pe(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function bu(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+a3(e,t))}function a3(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 Yi(e,t,s){const n=pe(e,()=>t());if(n==null)throw new Error(s);return n}function r3(e,t){const s=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,n=t+e.TEXTURE0;if(n<e.TEXTURE0||n>s){const i=`[gl.TEXTURE0, gl.TEXTURE${s}]`;throw new Error(`textureUnit must be in ${i}.`)}}function po(e,t=2){return N.sizeFromShape(e.slice(0,e.length-t))}function uo(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 wf(e){let t=[1,1,1];const s=e.length===0||e.length===1&&e[0]===1;return s||(t=[po(e),...uo(e)]),t}function C0(e,t=!1){let s=W().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t&&(s=s*2,e=e.map((i,r)=>r>=e.length-2?N.nearestLargerEven(e[r]):e[r]),e.length===1&&(e=[2,e[0]])),e.length!==2){const i=N.squeezeShape(e);e=i.newShape}let n=N.sizeFromShape(e);if(e.length<=1&&n<=s)return[1,n];if(e.length===2&&e[0]<=s&&e[1]<=s)return e;if(e.length===3&&e[0]*e[1]<=s&&e[2]<=s)return[e[0]*e[1],e[2]];if(e.length===3&&e[0]<=s&&e[1]*e[2]<=s)return[e[0],e[1]*e[2]];if(e.length===4&&e[0]*e[1]*e[2]<=s&&e[3]<=s)return[e[0]*e[1]*e[2],e[3]];if(e.length===4&&e[0]<=s&&e[1]*e[2]*e[3]<=s)return[e[0],e[1]*e[2]*e[3]];if(t){const i=po(e);let r=2,o=2;return e.length&&([r,o]=uo(e)),n=i*(r/2)*(o/2),N.sizeToSquarishShape(n).map(a=>a*2)}return N.sizeToSquarishShape(n)}function xf(e){return e%2===0}function zl(e,t){if(e=e.slice(-2),t=t.slice(-2),N.arraysEqual(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 s=e.slice(-1)[0],n=t.slice(-1)[0];if(s===n)return!0;if(xf(s)&&xf(n)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&xf(e[0])&&xf(t[0])}let $w,Ww;function R0(e){if($w==null){const t=nn(e);$w=t.getParameter(t.MAX_TEXTURE_SIZE)}return $w}function O0(e){if(Ww==null){const t=nn(e);Ww=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Ww)}function E0(e){if(e===0)return 0;let t;const s=nn(e);return rn(s,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:rn(s,"EXT_disjoint_timer_query")?t=1:t=0,t}function rn(e,t){const s=e.getExtension(t);return s!=null}function zw(e){try{const t=nn(e);if(t!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function _0(e){if(e===0)return!1;const t=nn(e);if(e===1){if(!rn(t,"OES_texture_float"))return!1}else if(!rn(t,"EXT_color_buffer_float"))return!1;const s=Pw(t);return s}function k0(e){if(e===0)return!1;const t=nn(e);if(e===1){if(!rn(t,"OES_texture_float"))return!1;if(!rn(t,"WEBGL_color_buffer_float"))return!1}else{if(rn(t,"EXT_color_buffer_float"))return Pw(t);const n="EXT_color_buffer_half_float";if(rn(t,n)){const i=t.getExtension(n);return l3(t,i)}return!1}const s=Pw(t);return s}function Pw(e){const t=gu(e),s=e.createTexture();e.bindTexture(e.TEXTURE_2D,s);const n=1,i=1;e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,n,i,0,t.textureFormatFloat,t.textureTypeFloat,null);const r=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,r),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const o=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(s),e.deleteFramebuffer(r),o}function l3(e,t){const s=gu(e,t),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n);const i=1,r=1;e.texImage2D(e.TEXTURE_2D,0,s.internalFormatHalfFloat,i,r,0,s.textureFormatFloat,s.textureTypeHalfFloat,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 D0(e){if(e!==2)return!1;const t=nn(e),s=t.fenceSync!=null;return s}function yi(e,t){Array.isArray(e)||(e=[e]),e.forEach(s=>{s!=null&&N.assert(s.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the WebGL backend.`)})}const ve=W();ve.registerFlag("HAS_WEBGL",()=>ve.getNumber("WEBGL_VERSION")>0);ve.registerFlag("WEBGL_VERSION",()=>zw(2)?2:zw(1)?1:0);ve.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);ve.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>ve.get("WEBGL_VERSION")===2);ve.registerFlag("WEBGL_CPU_FORWARD",()=>!0);ve.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);ve.registerFlag("WEBGL_PACK",()=>ve.getBool("HAS_WEBGL"));ve.registerFlag("WEBGL_PACK_NORMALIZATION",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_PACK_CLIP",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>!1);ve.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_PACK_REDUCE",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_LAZILY_UNPACK",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_CONV_IM2COL",()=>ve.getBool("WEBGL_PACK"));ve.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>R0(ve.getNumber("WEBGL_VERSION")));ve.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>O0(ve.getNumber("WEBGL_VERSION")));ve.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{const e=ve.getNumber("WEBGL_VERSION");return e===0?0:E0(e)});ve.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>ve.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!ja.isMobile());ve.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>_0(ve.getNumber("WEBGL_VERSION")));ve.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>ve.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:ve.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));ve.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>k0(ve.getNumber("WEBGL_VERSION")));ve.registerFlag("WEBGL_FENCE_API_ENABLED",()=>D0(ve.getNumber("WEBGL_VERSION")));ve.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>{const e=ve.getBool("WEBGL_RENDER_FLOAT32_ENABLED");return e?4:0});ve.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:F0,addImpl:M0,ceilImpl:U0,expImpl:$0,expm1Impl:W0,floorImpl:z0,logImpl:P0,maxImpl:B0,multiplyImpl:j0,rsqrtImpl:V0,sliceImpl:G0,subImpl:q0,transposeImpl:Lf,uniqueImpl:H0}=Ow;class Y0{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((i,r)=>`T${r}`);const s=[];this.variableNames.forEach(i=>{s.push(`float v${i} = get${i}AtOutCoords();`)});const n=this.variableNames.map(i=>`v${i}`).join(" + ");this.userCode=`
void main() {
${s.join(`
`)}
float result = ${n};
setOutput(result);
}
`}}class K0{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((i,r)=>`T${r}`);const s=[];this.variableNames.forEach(i=>{s.push(`vec4 v${i} = get${i}AtOutCoords();`)});const n=this.variableNames.map(i=>`v${i}`).join(" + ");this.userCode=`
void main() {
${s.join(`
`)}
vec4 result = ${n};
setOutput(result);
}
`}}class X0{constructor(e,t,s){this.variableNames=["A"];const{windowSize:n,batchSize:i,outSize:r}=e;s||this.variableNames.push("bestIndicesA"),this.outputShape=[i,r];const o=t==="max"?">":"<",a=s?"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 * ${n};
int bestIndex = inOffset;
float bestValue = getA(batch, bestIndex);
for (int i = 0; i < ${n}; i++) {
int inIdx = ${a};
float candidate = getA(batch, inIdx);
if (candidate ${o} bestValue) {
bestValue = candidate;
bestIndex = inIdx;
}
}
setOutput(float(bestIndex));
}
`}}function Bw(e,t){return["x","y","z","w","u","v"].slice(0,t).map(s=>`${e}.${s}`)}function _t(e,t){return t===1?[e]:Bw(e,t)}function J0(e,t){if(e===1)return"rc";let s="";for(let n=0;n<e;n++)s+=t[n],n<e-1&&(s+=",");return s}function at(){let e,t,s,n,i,r,o,a,l,c;return W().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",s="out",n="in",i="texture",r="outputColor",o="out vec4 outputColor;",a=`
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)
`,l="",c=`
#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",s="varying",n="varying",i="texture2D",r="gl_FragColor",o="",a=`
#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));
}
`,l=`
uniform float INFINITY;
bool isinf(float val) {
return abs(val) == INFINITY;
}
bvec4 isinf(vec4 val) {
return equal(abs(val), vec4(INFINITY));
}
`,c=`
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:s,varyingFs:n,texture2D:i,output:r,defineOutput:o,defineSpecialNaN:a,defineSpecialInf:l,defineRound:c}}function jn(e,t,s="index"){const n=N.computeStrides(t);return n.map((i,r)=>{const o=`int ${e[r]} = ${s} / ${i}`,a=r===n.length-1?`int ${e[r+1]} = ${s} - ${e[r]} * ${i}`:`index -= ${e[r]} * ${i}`;return`${o}; ${a};`}).join("")}function Pl(e){const t=N.computeStrides(e).map(s=>s.toString());return`
int getFlatIndex(ivec3 coords) {
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
}
`}const Sf=`
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:Z0}=U;function Q0(e,t,s,n){const i=[];e.forEach(m=>{const f=N.sizeFromShape(m.shapeInfo.logicalShape);m.shapeInfo.isUniform?i.push(`uniform float ${m.name}${f>1?`[${f}]`:""};`):(i.push(`uniform sampler2D ${m.name};`),i.push(`uniform int offset${m.name};`))});const r=i.join(`
`),o=e.map(m=>c3(m,t,n)).join(`
`),a=t.texShape,l=at(),c=h3(l);let p,u,h=f3(l);t.isPacked?(p=p3(t.logicalShape,a),u=m3(l)):(p=u3(t.logicalShape,a),u=d3(l)),n&&(h+=g3);const d=[h,c,u,r,p,o,s].join(`
`);return d}function Bl(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return y3(e);case 1:return b3(e);case 2:return w3(e);case 3:return x3(e);case 4:return L3(e);case 5:return S3(e);case 6:return I3(e);default:throw new Error(`${t.length}-D input sampling is not yet supported`)}}function eR(e){const t=e.shapeInfo.logicalShape;switch(t.length){case 0:return v3(e);case 1:return T3(e);case 2:return A3(e);case 3:return N3(e);default:return C3(e)}}function c3(e,t,s=!1){let n="";s?n+=eR(e):n+=Bl(e);const i=e.shapeInfo.logicalShape,r=t.logicalShape;return i.length<=r.length&&(s?n+=R3(e,t):n+=O3(e,t)),n}function p3(e,t){switch(e.length){case 0:return tR();case 1:return E3(e,t);case 2:return D3(e,t);case 3:return _3(e,t);default:return k3(e,t)}}function u3(e,t){switch(e.length){case 0:return tR();case 1:return F3(e,t);case 2:return z3(e,t);case 3:return M3(e,t);case 4:return U3(e,t);case 5:return $3(e,t);case 6:return W3(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function h3(e){return`
float sampleTexture(sampler2D textureSampler, vec2 uv) {
return ${e.texture2D}(textureSampler, uv).r;
}
`}function d3(e){return`
void setOutput(float val) {
${e.output} = vec4(val, 0, 0, 0);
}
`}function m3(e){return`
void setOutput(vec4 val) {
${e.output} = val;
}
`}function f3(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);
}
${P3}
${B3}
${j3}
`;return t}const P3=`
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);
}
`,B3=`
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);
}
`,j3=`
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);
}
`,g3=`
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 tR(){return`
int getOutputCoords() {
return 0;
}
`}function E3(e,t){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return s[0]===1?`
int getOutputCoords() {
return 2 * int(resultUV.x * ${s[1]}.0);
}
`:s[1]===1?`
int getOutputCoords() {
return 2 * int(resultUV.y * ${s[0]}.0);
}
`:`
int getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${s[0]}, ${s[1]}));
return 2 * (resTexRC.x * ${s[1]} + resTexRC.y);
}
`}function F3(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 _3(e,t){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],n=Math.ceil(e[2]/2),i=n*Math.ceil(e[1]/2);return`
ivec3 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${s[0]}, ${s[1]}));
int index = resTexRC.x * ${s[1]} + resTexRC.y;
int b = index / ${i};
index -= b * ${i};
int r = 2 * (index / ${n});
int c = imod(index, ${n}) * 2;
return ivec3(b, r, c);
}
`}function M3(e,t){const s=jn(["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;
${s}
return ivec3(r, c, d);
}
`}function k3(e,t){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],n=Math.ceil(e[e.length-1]/2),i=n*Math.ceil(e[e.length-2]/2);let r=i,o="",a="b, r, c";for(let l=2;l<e.length-1;l++)r*=e[e.length-l-1],o=`
int b${l} = index / ${r};
index -= b${l} * ${r};
`+o,a=`b${l}, `+a;return`
ivec${e.length} getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${s[0]}, ${s[1]}));
int index = resTexRC.x * ${s[1]} + resTexRC.y;
${o}
int b = index / ${i};
index -= b * ${i};
int r = 2 * (index / ${n});
int c = imod(index, ${n}) * 2;
return ivec${e.length}(${a});
}
`}function U3(e,t){const s=jn(["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;
${s}
return ivec4(r, c, d, d2);
}
`}function $3(e,t){const s=jn(["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;
${s}
ivec5 outShape = ivec5(r, c, d, d2, d3);
return outShape;
}
`}function W3(e,t){const s=jn(["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;
${s}
ivec6 result = ivec6(r, c, d, d2, d3, d4);
return result;
}
`}function D3(e,t){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(N.arraysEqual(e,t))return`
ivec2 getOutputCoords() {
return 2 * ivec2(resultUV.yx * vec2(${s[0]}, ${s[1]}));
}
`;const n=Math.ceil(e[1]/2);return`
ivec2 getOutputCoords() {
ivec2 resTexRC = ivec2(resultUV.yx *
vec2(${s[0]}, ${s[1]}));
int index = resTexRC.x * ${s[1]} + resTexRC.y;
int r = 2 * (index / ${n});
int c = imod(index, ${n}) * 2;
return ivec2(r, c);
}
`}function z3(e,t){return N.arraysEqual(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 ua(e){return`offset${e}`}function v3(e){const t=e.name,s="get"+t.charAt(0).toUpperCase()+t.slice(1),n=at();return`
vec4 ${s}() {
return ${n.texture2D}(${t}, halfCR);
}
`}function y3(e){const t=e.name,s="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`float ${s}() {return ${t};}`;const[n,i]=e.shapeInfo.texShape;if(n===1&&i===1)return`
float ${s}() {
return sampleTexture(${t}, halfCR);
}
`;const[r,o]=e.shapeInfo.texShape,a=ua(t);return`
float ${s}() {
vec2 uv = uvFromFlat(${r}, ${o}, ${a});
return sampleTexture(${t}, uv);
}
`}function T3(e){const t=e.name,s="get"+t.charAt(0).toUpperCase()+t.slice(1),n=e.shapeInfo.texShape,i=[Math.ceil(n[0]/2),Math.ceil(n[1]/2)],r=at();return`
vec4 ${s}(int index) {
vec2 uv = packedUVfrom1D(
${i[0]}, ${i[1]}, index);
return ${r.texture2D}(${t}, uv);
}
`}function b3(e){const t=e.name,s="get"+t.charAt(0).toUpperCase()+t.slice(1);if(e.shapeInfo.isUniform)return`
float ${s}(int index) {
${jl(e)}
}
`;const n=e.shapeInfo.texShape,i=n[0],r=n[1];if(r===1&&i===1)return`
float ${s}(int index) {
return sampleTexture(${t}, halfCR);
}
`;const o=ua(t);return r===1?`
float ${s}(int index) {
vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / ${i}.0);
return sampleTexture(${t}, uv);
}
`:i===1?`
float ${s}(int index) {
vec2 uv = vec2((float(index + ${o}) + 0.5) / ${r}.0, 0.5);
return sampleTexture(${t}, uv);
}
`:`
float ${s}(int index) {
vec2 uv = uvFromFlat(${i}, ${r}, index + ${o});
return sampleTexture(${t}, uv);
}
`}function A3(e){const t=e.shapeInfo.logicalShape,s=e.name,n="get"+s.charAt(0).toUpperCase()+s.slice(1),i=e.shapeInfo.texShape,r=i[0],o=i[1],a=at();if(i!=null&&N.arraysEqual(t,i))return`
vec4 ${n}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${o}.0, ${r}.0);
return ${a.texture2D}(${s}, uv);
}
`;const l=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],c=Math.ceil(t[1]/2);return`
vec4 ${n}(int row, int col) {
vec2 uv = packedUVfrom2D(${c}, ${l[0]}, ${l[1]}, row, col);
return ${a.texture2D}(${s}, uv);
}
`}function w3(e){const t=e.shapeInfo.logicalShape,s=e.name,n="get"+s.charAt(0).toUpperCase()+s.slice(1),i=e.shapeInfo.texShape;if(i!=null&&N.arraysEqual(t,i)){const u=i[0],h=i[1];return`
float ${n}(int row, int col) {
vec2 uv = (vec2(col, row) + halfCR) / vec2(${h}.0, ${u}.0);
return sampleTexture(${s}, uv);
}
`}const{newShape:r,keptDims:o}=N.squeezeShape(t),a=r;if(a.length<t.length){const u=Vl(e,a),h=["row","col"];return`
${Bl(u)}
float ${n}(int row, int col) {
return ${n}(${Gl(h,o)});
}
`}if(e.shapeInfo.isUniform)return`
float ${n}(int row, int col) {
int index = round(dot(vec2(row, col), vec2(${t[1]}, 1)));
${jl(e)}
}
`;const l=i[0],c=i[1],p=ua(s);return c===1?`
float ${n}(int row, int col) {
float index = dot(vec3(row, col, ${p}), vec3(${t[1]}, 1, 1));
vec2 uv = vec2(0.5, (index + 0.5) / ${l}.0);
return sampleTexture(${s}, uv);
}
`:l===1?`
float ${n}(int row, int col) {
float index = dot(vec3(row, col, ${p}), vec3(${t[1]}, 1, 1));
vec2 uv = vec2((index + 0.5) / ${c}.0, 0.5);
return sampleTexture(${s}, uv);
}
`:`
float ${n}(int row, int col) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${t[1]} + col + ${p};
vec2 uv = uvFromFlat(${l}, ${c}, index);
return sampleTexture(${s}, uv);
}
`}function N3(e){const t=e.shapeInfo.logicalShape,s=e.name,n="get"+s.charAt(0).toUpperCase()+s.slice(1),i=e.shapeInfo.texShape,r=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)];if(t[0]===1){const u=t.slice(1),h=[1,2],d=Vl(e,u),m=["b","row","col"];return`
${eR(d)}
vec4 ${n}(int b, int row, int col) {
return ${n}(${Gl(m,h)});
}
`}const o=r[0],a=r[1],l=Math.ceil(t[2]/2),c=l*Math.ceil(t[1]/2),p=at();return`
vec4 ${n}(int b, int row, int col) {
vec2 uv = packedUVfrom3D(
${o}, ${a}, ${c}, ${l}, b, row, col);
return ${p.texture2D}(${s}, uv);
}
`}function x3(e){const t=e.shapeInfo.logicalShape,s=e.name,n="get"+s.charAt(0).toUpperCase()+s.slice(1),i=t[1]*t[2],r=t[2],{newShape:o,keptDims:a}=N.squeezeShape(t),l=o;if(l.length<t.length){const m=Vl(e,l),f=["row","col","depth"];return`
${Bl(m)}
float ${n}(int row, int col, int depth) {
return ${n}(${Gl(f,a)});
}
`}if(e.shapeInfo.isUniform)return`
float ${n}(int row, int col, int depth) {
int index = round(dot(vec3(row, col, depth),
vec3(${i}, ${r}, 1)));
${jl(e)}
}
`;const c=e.shapeInfo.texShape,p=c[0],u=c[1],h=e.shapeInfo.flatOffset;if(u===i&&h==null)return`
float ${n}(int row, int col, int depth) {
float texR = float(row);
float texC = dot(vec2(col, depth), vec2(${r}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${u}.0, ${p}.0);
return sampleTexture(${s}, uv);
}
`;if(u===r&&h==null)return`
float ${n}(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(${u}.0, ${p}.0);
return sampleTexture(${s}, uv);
}
`;const d=ua(s);return`
float ${n}(int row, int col, int depth) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${i} + col * ${r} + depth + ${d};
vec2 uv = uvFromFlat(${p}, ${u}, index);
return sampleTexture(${s}, uv);
}
`}function C3(e){const t=e.shapeInfo.logicalShape,s=t.length,n=e.name,i="get"+n.charAt(0).toUpperCase()+n.slice(1),r=e.shapeInfo.texShape,o=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],a=o[0],l=o[1],c=Math.ceil(t[s-1]/2);let p=c*Math.ceil(t[s-2]/2),u="int b, int row, int col",h=`b * ${p} + (row / 2) * ${c} + (col / 2)`;for(let m=2;m<s-1;m++)u=`int b${m}, `+u,p*=t[s-m-1],h=`b${m} * ${p} + `+h;const d=at();return`
vec4 ${i}(${u}) {
int index = ${h};
int texR = index / ${l};
int texC = index - texR * ${l};
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${l}, ${a});
return ${d.texture2D}(${n}, uv);
}
`}function L3(e){const t=e.shapeInfo.logicalShape,s=e.name,n="get"+s.charAt(0).toUpperCase()+s.slice(1),i=t[3],r=t[2]*i,o=t[1]*r,{newShape:a,keptDims:l}=N.squeezeShape(t);if(a.length<t.length){const m=Vl(e,a),f=["row","col","depth","depth2"];return`
${Bl(m)}
float ${n}(int row, int col, int depth, int depth2) {
return ${n}(${Gl(f,l)});
}
`}if(e.shapeInfo.isUniform)return`
float ${n}(int row, int col, int depth, int depth2) {
int index = round(dot(vec4(row, col, depth, depth2),
vec4(${o}, ${r}, ${i}, 1)));
${jl(e)}
}
`;const c=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,u=p[0],h=p[1];if(h===o&&c==null)return`
float ${n}(int row, int col, int depth, int depth2) {
float texR = float(row);
float texC =
dot(vec3(col, depth, depth2),
vec3(${r}, ${i}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${h}.0, ${u}.0);
return sampleTexture(${s}, uv);
}
`;if(h===i&&c==null)return`
float ${n}(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(${h}.0, ${u}.0);
return sampleTexture(${s}, uv);
}
`;const d=ua(s);return`
float ${n}(int row, int col, int depth, int depth2) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${o} + col * ${r} +
depth * ${i} + depth2;
vec2 uv = uvFromFlat(${u}, ${h}, index + ${d});
return sampleTexture(${s}, uv);
}
`}function S3(e){const t=e.shapeInfo.logicalShape,s=e.name,n="get"+s.charAt(0).toUpperCase()+s.slice(1),i=t[4],r=t[3]*i,o=t[2]*r,a=t[1]*o,{newShape:l,keptDims:c}=N.squeezeShape(t);if(l.length<t.length){const f=Vl(e,l),g=["row","col","depth","depth2","depth3"];return`
${Bl(f)}
float ${n}(int row, int col, int depth, int depth2, int depth3) {
return ${n}(${Gl(g,c)});
}
`}if(e.shapeInfo.isUniform)return`
float ${n}(int row, int col, int depth, int depth2, int depth3) {
float index = dot(
vec4(row, col, depth, depth2),
vec4(${a}, ${o}, ${r}, ${i})) +
depth3;
${jl(e)}
}
`;const p=e.shapeInfo.flatOffset,u=e.shapeInfo.texShape,h=u[0],d=u[1];if(d===a&&p==null)return`
float ${n}(int row, int col, int depth, int depth2, int depth3) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${o}, ${r}, ${i}, 1));
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${d}.0, ${h}.0);
return sampleTexture(${s}, uv);
}
`;if(d===i&&p==null)return`
float ${n}(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(${d}.0, ${h}.0);
return sampleTexture(${s}, uv);
}
`;const m=ua(s);return`
float ${n}(int row, int col, int depth, int depth2, int depth3) {
// Explicitly use integer operations as dot() only works on floats.
int index = row * ${a} + col * ${o} + depth * ${r} +
depth2 * ${i} + depth3 + ${m};
vec2 uv = uvFromFlat(${h}, ${d}, index);
return sampleTexture(${s}, uv);
}
`}function I3(e){const t=e.shapeInfo.logicalShape,s=e.name,n="get"+s.charAt(0).toUpperCase()+s.slice(1),{newShape:i,keptDims:r}=N.squeezeShape(t);if(i.length<t.length){const g=Vl(e,i),y=["row","col","depth","depth2","depth3","depth4"];return`
${Bl(g)}
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
return ${n}(${Gl(y,r)});
}
`}const o=t[5],a=t[4]*o,l=t[3]*a,c=t[2]*l,p=t[1]*c;if(e.shapeInfo.isUniform)return`
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int index = round(dot(
vec4(row, col, depth, depth2),
vec4(${p}, ${c}, ${l}, ${a})) +
dot(
vec2(depth3, depth4),
vec2(${o}, 1)));
${jl(e)}
}
`;const u=e.shapeInfo.flatOffset,h=e.shapeInfo.texShape,d=h[0],m=h[1];if(m===p&&u==null)return`
float ${n}(int row, int col, int depth,
int depth2, int depth3, int depth4) {
int texR = row;
float texC = dot(vec4(col, depth, depth2, depth3),
vec4(${c}, ${l}, ${a}, ${o})) +
float(depth4);
vec2 uv = (vec2(texC, texR) + halfCR) /
vec2(${m}.0, ${d}.0);
return sampleTexture(${s}, uv);
}
`;if(m===o&&u==null)return`
float ${n}(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(${m}.0, ${d}.0);
return sampleTexture(${s}, uv);
}
`;const f=ua(s);return`
float ${n}(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 * ${p} + col * ${c} + depth * ${l} +
depth2 * ${a} + depth3 * ${o} + depth4 + ${f};
vec2 uv = uvFromFlat(${d}, ${m}, index);
return sampleTexture(${s}, uv);
}
`}function jl(e){const t=e.name,s=N.sizeFromShape(e.shapeInfo.logicalShape);return s<2?`return ${t};`:`
for (int i = 0; i < ${s}; i++) {
if (i == index) {
return ${t}[i];
}
}
`}function R3(e,t){const s=e.name,n=s.charAt(0).toUpperCase()+s.slice(1),i="get"+n+"AtOutCoords",r=e.shapeInfo.logicalShape.length,o=t.logicalShape.length,a=Z0(e.shapeInfo.logicalShape,t.logicalShape),l=Re(o),c=o-r;let p;const u=["x","y","z","w","u","v"];r===0?p="":o<2&&a.length>=1?p="coords = 0;":p=a.map(w=>`coords.${u[w+c]} = 0;`).join(`
`);let h="";o<2&&r>0?h="coords":h=e.shapeInfo.logicalShape.map((w,x)=>`coords.${u[x+c]}`).join(", ");let d="return outputValue;";const m=N.sizeFromShape(e.shapeInfo.logicalShape),f=m===1,g=N.sizeFromShape(t.logicalShape),y=g===1;if(r===1&&!f&&!y)d=`
return vec4(outputValue.xy, outputValue.xy);
`;else if(f&&!y)o===1?d=`
return vec4(outputValue.x, outputValue.x, 0., 0.);
`:d=`
return vec4(outputValue.x);
`;else if(a.length){const w=r-2,x=r-1;a.indexOf(w)>-1&&a.indexOf(x)>-1?d="return vec4(outputValue.x);":a.indexOf(w)>-1?d="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":a.indexOf(x)>-1&&(d="return vec4(outputValue.xx, outputValue.zz);")}return`
vec4 ${i}() {
${l} coords = getOutputCoords();
${p}
vec4 outputValue = get${n}(${h});
${d}
}
`}function O3(e,t){const s=e.name,n=s.charAt(0).toUpperCase()+s.slice(1),i="get"+n+"AtOutCoords",r=t.texShape,o=e.shapeInfo.texShape,a=e.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!e.shapeInfo.isUniform&&a===l&&e.shapeInfo.flatOffset==null&&N.arraysEqual(o,r))return`
float ${i}() {
return sampleTexture(${s}, resultUV);
}
`;const c=Re(l),p=Z0(e.shapeInfo.logicalShape,t.logicalShape),u=l-a;let h;const d=["x","y","z","w","u","v"];a===0?h="":l<2&&p.length>=1?h="coords = 0;":h=p.map(f=>`coords.${d[f+u]} = 0;`).join(`
`);let m="";return l<2&&a>0?m="coords":m=e.shapeInfo.logicalShape.map((f,g)=>`coords.${d[g+u]}`).join(", "),`
float ${i}() {
${c} coords = getOutputCoords();
${h}
return get${n}(${m});
}
`}function Re(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 Vl(e,t){const s=JSON.parse(JSON.stringify(e));return s.shapeInfo.logicalShape=t,s}function Gl(e,t){return t.map(s=>e[s]).join(", ")}class sR{constructor(e,t,s,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,N.assert(e.length>2,()=>`Packed arg${s.charAt(0).toUpperCase()+s.slice(1)} supports only inputs with rank above 2.`);const i=e[e.length-1],r=Math.ceil(i/t);this.outputShape=e.slice(0,-1),r>1&&this.outputShape.push(r),n||this.variableNames.push("bestIndicesA");const o=this.outputShape,a=o.length,l=Re(a),c=_t("coords",a);let p,u;if(r===1){u=a+1;const E=Re(u);p=`
${E} sourceLocR = ${E}(${c.join()}, 0);
++${c[a-1]};
${E} sourceLocG = ${E}(${c.join()}, 0);
++${c[a-2]};
${E} sourceLocA = ${E}(${c.join()}, 0);
--${c[a-1]};
${E} sourceLocB = ${E}(${c.join()}, 0);
--${c[a-2]};`}else u=a,p=`
${l} sourceLocR = coords;
++${c[a-1]};
${l} sourceLocG = coords;
++${c[a-2]};
${l} sourceLocA = coords;
--${c[a-1]};
${l} sourceLocB = coords;
--${c[a-2]};`;const h=["x","y","z","w","u","v"].slice(0,u),d="."+h[u-1],m=h.map(E=>"int "+E),f=_t("sourceLocR",u-1).concat("inIdx.r"),g=_t("sourceLocG",u-1).concat("inIdx.g"),y=_t("sourceLocB",u-1).concat("inIdx.b"),w=_t("sourceLocA",u-1).concat("inIdx.a"),x=s==="max"?"greaterThan":"lessThan",T=n?"":`
inIdx = round(vec4(getBestIndicesAChannel(${f.join()}),
getBestIndicesAChannel(${g.join()}),
getBestIndicesAChannel(${y.join()}),
getBestIndicesAChannel(${w.join()})));`,A=`vec4(
getAChannel(${f.join()}),
hasNextCol ? getAChannel(${g.join()}) : 0.,
hasNextRow ? getAChannel(${y.join()}) : 0.,
hasNextRow && hasNextCol ? getAChannel(${w.join()}) : 0.)`,_=n?"":`
float getBestIndicesAChannel(${m.join()}) {
return getChannel(getBestIndicesA(${h.join()}),
vec2(${h.slice(-2).join()}));
}`;this.userCode=`
float getAChannel(${m.join()}) {
return getChannel(getA(${h.join()}),
vec2(${h.slice(-2).join()}));
}
${_}
void main() {
${l} coords = getOutputCoords();
bool hasNextCol = ${c[a-1]} < ${o[a-1]-1};
bool hasNextRow = ${c[a-2]} < ${o[a-2]-1};
${p}
ivec4 srcIdx = ivec4(sourceLocR${d}, sourceLocG${d},
sourceLocB${d}, sourceLocA${d}) * ${t};
ivec4 inIdx = srcIdx;
vec4 bestIndex = vec4(inIdx);
vec4 bestValue = ${A};
for (int i = 0; i < ${t}; i++) {
inIdx = srcIdx;
${T}
vec4 candidate = ${A};
bvec4 nan = isnan(candidate);
bvec4 replace = bvec4(
vec4(${x}(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 nR{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterHeight,s=e.filterWidth,n=e.strideHeight,i=e.strideWidth,r=e.dilationHeight,o=e.dilationWidth,a=e.effectiveFilterHeight,l=e.effectiveFilterWidth,c=a-1-e.padInfo.top,p=l-1-e.padInfo.left,u=1/(t*s);this.userCode=`
const ivec2 pads = ivec2(${c}, ${p});
const float avgMultiplier = float(${u});
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 < ${a};
wR += ${r}) {
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 < ${l};
wC+= ${o}) {
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 iR{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterDepth,s=e.filterHeight,n=e.filterWidth,i=e.strideDepth,r=e.strideHeight,o=e.strideWidth,a=e.dilationDepth,l=e.dilationHeight,c=e.dilationWidth,p=e.effectiveFilterDepth,u=e.effectiveFilterHeight,h=e.effectiveFilterWidth,d=p-1-e.padInfo.front,m=u-1-e.padInfo.top,f=h-1-e.padInfo.left,g=1/(t*s*n);this.userCode=`
const ivec3 pads = ivec3(${d}, ${m}, ${f});
const float avgMultiplier = float(${g});
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 < ${p};
wD += ${a}) {
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 < ${u};
wR += ${l}) {
float dyR = float(dyRCorner + wR) / ${r}.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 += ${c}) {
float dyC = float(dyCCorner + wC) / ${o}.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 jw={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"};class Vw{constructor(e,t,s){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=U.assertAndGetBroadcastShape(t,s),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 rR=`
if (isnan(a)) return a;
if (isnan(b)) return b;
`,If="return a + b;",vf="return a - b;",Gw="return a * b;",oR=`
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;
}
`,aR=`
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);
`,lR="return float(a == b);",cR="return float(a != b);",pR="return float(a < b);",uR="return float(a <= b);",hR="return float(a > b);",dR="return float(a >= b);",mR="return float(a >= 1.0 && b >= 1.0);",fR="return float(a >= 1.0 || b >= 1.0);",gR=rR+`
return max(a, b);
`,yR=rR+`
return min(a, b);
`,bR=`if (b == 0.0) return NAN;
return mod(a, b);`,wR="return (b >= 1.0) ? a : a * (b + 1.0);",qw="return (a < 0.) ? b * a : a;";class kt{constructor(e,t,s){this.variableNames=["A","B"],this.outputShape=U.assertAndGetBroadcastShape(t,s),this.userCode=`
float binaryOperation(float a, float b) {
${e}
}
void main() {
float a = getAAtOutCoords();
float b = getBAtOutCoords();
setOutput(binaryOperation(a, b));
}
`}}const Tf=`
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;
`,xR=`
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);
`,LR=`
// 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));
`+Tf+`
return result;
`,Hw=`
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
`,SR=`
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
`,IR=`
return vec4(equal(a, b));
`,vR=`
return vec4(notEqual(a, b));
`,TR=`
return vec4(lessThan(a, b));
`,AR=`
return vec4(lessThanEqual(a, b));
`,NR=`
return vec4(greaterThan(a, b));
`,CR=`
return vec4(greaterThanEqual(a, b));
`,RR=`
return vec4(
vec4(greaterThanEqual(a, vec4(1.0))) *
vec4(greaterThanEqual(b, vec4(1.0))));
`,OR=`
return min(
vec4(greaterThanEqual(a, vec4(1.0))) +
vec4(greaterThanEqual(b, vec4(1.0))),
vec4(1.0));
`,ER=`
vec4 result = vec4(max(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+Tf+`
return result;
`,_R=`
vec4 result = vec4(min(a, b));
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+Tf+`
return result;
`,kR=`
vec4 result = mod(a, b);
vec4 isNaN = vec4(equal(b, vec4(0.0)));
`+Tf+`
return result;
`;class bi{constructor(e,t,s,n=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=U.assertAndGetBroadcastShape(t,s);const i=this.outputShape.length;let r="";if(n)if(i===0||N.sizeFromShape(this.outputShape)===1)r=`
result.y = 0.;
result.z = 0.;
result.w = 0.;
`;else{const o=Re(i);if(r=`
${o} coords = getOutputCoords();
`,i===1)r+=`
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
result.z = 0.;
result.w = 0.;
`;else{const a=_t("coords",i);r+=`
bool nextRowOutOfBounds =
(${a[i-2]} + 1) >= ${this.outputShape[i-2]};
bool nextColOutOfBounds =
(${a[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);
${r}
setOutput(result);
}
`}}class DR{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(s,n)=>{this.minLoc==null&&(this.minLoc=s.getUniformLocationNoThrow(n,"minVal"),this.maxLoc=s.getUniformLocationNoThrow(n,"maxVal")),s.gl.uniform1f(this.minLoc,e),s.gl.uniform1f(this.maxLoc,t)}}}class FR{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(s,n)=>{this.minLoc==null&&(this.minLoc=s.getUniformLocationNoThrow(n,"minVal"),this.maxLoc=s.getUniformLocationNoThrow(n,"maxVal")),s.gl.uniform1f(this.minLoc,e),s.gl.uniform1f(this.maxLoc,t)}}}class MR{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 UR{constructor(e){this.outputShape=[],this.outputShape=U.computeOutShape(e,1),this.variableNames=e.map((r,o)=>`T${o}`);const t=new Array(e.length-1);t[0]=e[0][1];for(let r=1;r<t.length;r++)t[r]=t[r-1]+e[r][1];const s=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let r=1;r<t.length;r++){const o=t[r-1];s.push(`else if (yC < ${t[r]}) setOutput(getT${r}(yR, yC-${o}));`)}const n=t.length,i=t[t.length-1];s.push(`else setOutput(getT${n}(yR, yC-${i}));`),this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int yR = coords.x;
int yC = coords.y;
${s.join(`
`)}
}
`}}class $R{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=U.computeOutShape(e,t);const s=this.outputShape,n=s.length,i=Re(n),r=_t("coords",n),o=["x","y","z","w","u","v"].slice(0,n);this.variableNames=e.map((m,f)=>`T${f}`);const a=new Array(e.length-1);a[0]=e[0][t];for(let m=1;m<a.length;m++)a[m]=a[m-1]+e[m][t];const l=o[t],c=o.slice(-2),p=o.join();let u=`if (${l} < ${a[0]}) {
return getChannel(
getT0(${p}), vec2(${c.join()}));
}`;for(let m=1;m<a.length;m++){const f=a[m-1];u+=`
if (${l} < ${a[m]} && ${l} >= ${a[m-1]}) {
return getChannel(
getT${m}(${Af(o,l,f)}),
vec2(${Af(c,l,f)}));
}`}const h=a.length,d=a[a.length-1];u+=`
return getChannel(
getT${h}(${Af(o,l,d)}),
vec2(${Af(c,l,d)}));`,this.userCode=`
float getValue(${o.map(m=>"int "+m)}) {
${u}
}
void main() {
${i} coords = getOutputCoords();
vec4 result = vec4(getValue(${r}), 0., 0., 0.);
${r[n-1]} = ${r[n-1]} + 1;
if (${r[n-1]} < ${s[n-1]}) {
result.g = getValue(${r});
}
${r[n-2]} = ${r[n-2]} + 1;
if (${r[n-2]} < ${s[n-2]}) {
result.a = getValue(${r});
}
${r[n-1]} = ${r[n-1]} - 1;
if (${r[n-2]} < ${s[n-2]} &&
${r[n-1]} < ${s[n-1]}) {
result.b = getValue(${r});
}
setOutput(result);
}
`}}function Af(e,t,s){const n=e.indexOf(t),i=e.map((r,o)=>o===n?`${r} - ${s}`:r);return i.join()}class WR{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,s=e.strideWidth,n=e.padInfo.top,i=e.padInfo.left,r=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} - ${n};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${s} - ${i};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
if (${r}) {
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 zR{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,s=e.filterWidth,n=e.strideHeight,i=e.strideWidth,r=e.dataFormat==="channelsLast",o=t-1-e.padInfo.top,a=s-1-e.padInfo.left,l=r?1:2,c=r?2:3,p=r?3:1;this.userCode=`
const ivec2 pads = ivec2(${o}, ${a});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d1 = coords[${p}];
ivec2 dyCorner = ivec2(coords[${l}], coords[${c}]) - 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) / ${n}.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 < ${s}; 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 = ${s} - 1 - wC;
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
if (${r}) {
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 PR{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideDepth,s=e.strideHeight,n=e.strideWidth,i=e.padInfo.front,r=e.padInfo.top,o=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 * ${s} - ${r};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${n} - ${o};
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 BR{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterDepth,s=e.filterHeight,n=e.filterWidth,i=e.strideDepth,r=e.strideHeight,o=e.strideWidth,a=t-1-e.padInfo.front,l=s-1-e.padInfo.top,c=n-1-e.padInfo.left;this.userCode=`
const ivec3 pads = ivec3(${a}, ${l}, ${c});
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 < ${s}; wR++) {
float dyR = float(dyRCorner + wR) / ${r}.0;
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
fract(dyR) > 0.0) {
continue;
}
int idyR = int(dyR);
int wRPerm = ${s} - 1 - wR;
for (int wC = 0; wC < ${n}; wC++) {
float dyC = float(dyCCorner + wC) / ${o}.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++) {
float xValue = getDy(batch, idyF, idyR, idyC, d2);
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
dotProd += xValue * wValue;
}
}
}
}
setOutput(dotProd);
}
`}}class jR{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,s=e.strideWidth,n=e.padInfo.top,i=e.padInfo.left,r=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 * ${r} + 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} - ${n};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int yC = 0; yC < ${e.outWidth}; yC++) {
int xC = wC + yC * ${s} - ${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 VR{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,s=e.filterWidth,n=e.strideHeight,i=e.strideWidth,r=t-1-e.padInfo.top,o=s-1-e.padInfo.left,a=e.outChannels/e.inChannels;this.userCode=`
const ivec2 pads = ivec2(${r}, ${o});
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) / ${n}.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 < ${s}; 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 = ${s} - 1 - wC;
// TO DO: Vec4 over the channelMul
for (int dm = 0; dm < ${a}; dm++) {
int d2 = d1 * ${a} + dm;
float xValue = getDy(batch, idyR, idyC, d2);
float wValue = getW(wRPerm, wCPerm, d1, dm);
dotProd += xValue * wValue;
}
}
}
setOutput(dotProd);
}
`}}class Yw{constructor(e,t=!1,s=null,n=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const i=e.padInfo.top,r=e.padInfo.left,o=e.strideHeight,a=e.strideWidth,l=e.dilationHeight,c=e.dilationWidth,p=e.filterHeight,u=e.filterWidth,h=Math.floor(e.inChannels/4)*4,d=e.inChannels%4,m=e.dataFormat==="channelsLast",f=m?1:2,g=m?2:3,y=m?3:1;let w="",x="";s&&(n?w=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${s}
}`:w=`
float activation(float x) {
${s}
}
`,x="result = activation(result);");const T=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${w}
const ivec2 strides = ivec2(${o}, ${a});
const ivec2 pads = ivec2(${i}, ${r});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords[0];
int d2 = coords[${y}];
ivec2 xRCCorner =
ivec2(coords[${f}], coords[${g}]) * 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 < ${p}; wR++) {
int xR = xRCorner + wR * ${l};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${u}; wC++) {
int xC = xCCorner + wC * ${c};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
for (int d1 = 0; d1 < ${h}; 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 (${m}) {
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 (${d===1}) {
if (${m}) {
dotProd +=
getX(batch, xR, xC, ${h}) *
getW(wR, wC, ${h}, d2);
} else {
dotProd +=
getX(batch, ${h}, xR, xC) *
getW(wR, wC, ${h}, d2);
}
} else if (${d===2}) {
vec2 wValues = vec2(
getW(wR, wC, ${h}, d2),
getW(wR, wC, ${h} + 1, d2)
);
if (${m}) {
vec2 xValues = vec2(
getX(batch, xR, xC, ${h}),
getX(batch, xR, xC, ${h} + 1)
);
dotProd += dot(xValues, wValues);
} else {
vec2 xValues = vec2(
getX(batch, ${h}, xR, xC),
getX(batch, ${h} + 1, xR, xC)
);
dotProd += dot(xValues, wValues);
}
} else if (${d===3}) {
vec3 wValues = vec3(
getW(wR, wC, ${h}, d2),
getW(wR, wC, ${h} + 1, d2),
getW(wR, wC, ${h} + 2, d2)
);
if (${m}) {
vec3 xValues = vec3(
getX(batch, xR, xC, ${h}),
getX(batch, xR, xC, ${h} + 1),
getX(batch, xR, xC, ${h} + 2)
);
dotProd += dot(xValues, wValues);
} else {
vec3 xValues = vec3(
getX(batch, ${h}, xR, xC),
getX(batch, ${h} + 1, xR, xC),
getX(batch, ${h} + 2, xR, xC)
);
dotProd += dot(xValues, wValues);
}
}
}
}
float result = dotProd;
${T}
${x}
setOutput(result);
}
`}}class GR{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const t=e.padInfo.front,s=e.padInfo.top,n=e.padInfo.left,i=e.strideDepth,r=e.strideHeight,o=e.strideWidth,a=e.dilationDepth,l=e.dilationHeight,c=e.dilationWidth,p=e.filterDepth,u=e.filterHeight,h=e.filterWidth,d=Math.floor(e.inChannels/4)*4,m=e.inChannels%4;this.userCode=`
const ivec3 strides = ivec3(${i}, ${r}, ${o});
const ivec3 pads = ivec3(${t}, ${s}, ${n});
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 < ${p}; wF++) {
int xF = xFCorner + wF * ${a};
if (xF < 0 || xF >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${u}; wR++) {
int xR = xRCorner + wR * ${l};
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${h}; wC++) {
int xC = xCCorner + wC * ${c};
if (xC < 0 || xC >= ${e.inWidth}) {
continue;
}
for (int d1 = 0; d1 < ${d}; 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 (${m===1}) {
dotProd +=
getX(batch, xF, xR, xC, ${d}) *
getW(wF, wR, wC, ${d}, d2);
} else if (${m===2}) {
vec2 xValues = vec2(
getX(batch, xF, xR, xC, ${d}),
getX(batch, xF, xR, xC, ${d} + 1)
);
vec2 wValues = vec2(
getW(wF, wR, wC, ${d}, d2),
getW(wF, wR, wC, ${d} + 1, d2)
);
dotProd += dot(xValues, wValues);
} else if (${m===3}) {
vec3 xValues = vec3(
getX(batch, xF, xR, xC, ${d}),
getX(batch, xF, xR, xC, ${d} + 1),
getX(batch, xF, xR, xC, ${d} + 2)
);
vec3 wValues = vec3(
getW(wF, wR, wC, ${d}, d2),
getW(wF, wR, wC, ${d} + 1, d2),
getW(wF, wR, wC, ${d} + 2, d2)
);
dotProd += dot(xValues, wValues);
}
}
}
}
setOutput(dotProd);
}
`}}class Kw{constructor(e,t=!1,s=null,n=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const i=e.inHeight,r=e.inWidth,o=e.padInfo.top,a=e.padInfo.left,l=e.strideHeight,c=e.strideWidth,p=e.dilationHeight,u=e.dilationWidth,h=e.filterHeight,d=e.filterWidth,m=e.outChannels/e.inChannels;let f="",g="";s&&(n?f=`float activation(float a) {
float b = getPreluActivationWeightsAtOutCoords();
${s}
}`:f=`
float activation(float x) {
${s}
}
`,g="result = activation(result);");const y=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${f}
const ivec2 strides = ivec2(${l}, ${c});
const ivec2 pads = ivec2(${o}, ${a});
void main() {
ivec4 coords = getOutputCoords();
int batch = coords.x;
ivec2 xRCCorner = coords.yz * strides - pads;
int d2 = coords.w;
int d1 = d2 / ${m};
int q = d2 - d1 * ${m};
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 < ${h}; wR++) {
int xR = xRCorner + wR * ${p};
if (xR < 0 || xR >= ${i}) {
continue;
}
for (int wC = 0; wC < ${d}; wC++) {
int xC = xCCorner + wC * ${u};
if (xC < 0 || xC >= ${r}) {
continue;
}
float xVal = getX(batch, xR, xC, d1);
float wVal = getW(wR, wC, d1, q);
dotProd += xVal * wVal;
}
}
float result = dotProd;
${y}
${g}
setOutput(result);
}
`}}class Xw{constructor(e,t=!1,s=null,n=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.outShape;const i=e.inHeight,r=e.inWidth,o=e.padInfo.top,a=e.padInfo.left,l=e.strideHeight,c=e.strideWidth,p=e.dilationHeight,u=e.dilationWidth,h=e.filterHeight,d=e.filterWidth,m=d;let f="int xR; int xC; int xCOffset;";for(let x=0;x<h;x++)for(let T=0;T<d;T++)f+=`
vec4 xTexelR${x}C${T*2} = vec4(0.);
vec4 wR${x}C${T} = vec4(0.);
vec4 xR${x}C${T} = vec4(0.);`;for(let x=0;x<h;x++)for(let T=0;T<m;T++){const A=T*2;if(f+=`
xR = xRCorner + ${x*p};
xC = xCCorner + ${A*u};
`,c===1){if(A<d&&(a%2===1?f+=`
xCOffset = xC + 1;
if(xR >= 0 && xR < ${i} && xCOffset >= 0 && xCOffset < ${r}) {
xTexelR${x}C${A} = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if(xCOffset + 1 >= ${r}) {
xTexelR${x}C${A}.zw = vec2(0.);
}
} else {
xTexelR${x}C${A} = vec4(0.);
}
xCOffset = xC + 1 - 2;
if(xR >= 0 && xR < ${i} && xCOffset >= 0 && xCOffset < ${r}) {
vec4 previous = getX(batch, xR, xCOffset, d1);
// Need to manually clear unused channels in case
// we're reading from recycled texture.
if(xCOffset + 1 >= ${r}) {
previous.zw = vec2(0.);
}
xR${x}C${A} = vec4(previous.zw, xTexelR${x}C${A}.xy);
} else {
xR${x}C${A} = vec4(0, 0, xTexelR${x}C${A}.xy);
}
`:f+=`
if(xR >= 0 && xR < ${i} && xC >= 0 && xC < ${r}) {
xTexelR${x}C${A} = getX(batch, xR, xC, d1);
} else {
xTexelR${x}C${A} = vec4(0.);
}
xR${x}C${A} = xTexelR${x}C${A};
`,A+1<d)){const _=a%2===0?N.nearestLargerEven(u):u;u%2===0&&a%2===1||u%2!==0&&a%2!==1?(f+=`
xCOffset = xC + ${a%2} + ${_};
if(xR >= 0 && xR < ${i} &&
xCOffset >= 0 && xCOffset < ${r}) {
xTexelR${x}C${A+2} = getX(batch, xR, xCOffset, d1);
}
`,u>1&&(f+=`
xCOffset -= 2;
if(xR >= 0 && xR < ${i} &&
xCOffset >= 0 && xCOffset < ${r}) {
xTexelR${x}C${A} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${x}C${A} = vec4(0.);
}
`),f+=`
xR${x}C${A+1} = vec4(
xTexelR${x}C${A}.zw, xTexelR${x}C${A+2}.xy);
`):f+=`
xCOffset = xC + ${_};
if(xR >= 0 && xR < ${i} &&
xCOffset >= 0 && xCOffset < ${r}) {
xTexelR${x}C${A+2} = getX(batch, xR, xCOffset, d1);
}
xR${x}C${A+1} = xTexelR${x}C${A+2};
`}}else A<d&&(f+=`
if(xR >= 0 && xR < ${i}) {
`,a%2===1?(f+=`
xCOffset = xC + 1 - ${c};
if(xCOffset >= 0 && xCOffset < ${r}) {
xTexelR${x}C${A} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${x}C${A} = vec4(0.);
}
if(xC + 1 >= 0 && xC + 1 < ${r}) {
xTexelR${x}C${A+2} = getX(batch, xR, xC + 1, d1);
} else {
xTexelR${x}C${A+2} = vec4(0.);
}
xR${x}C${A} = vec4(
xTexelR${x}C${A}.zw, xTexelR${x}C${A+2}.zw);
`,A+1<d&&(f+=`
vec4 final = vec4(0.);
xCOffset = xC + 1 + ${c};
if(xCOffset >= 0 && xCOffset < ${r}) {
final = getX(batch, xR, xCOffset, d1);
}
xR${x}C${A+1} = vec4(xTexelR${x}C${A+2}.xy, final.xy);
`)):(f+=`
if(xC >= 0 && xC < ${r}) {
xTexelR${x}C${A} = getX(batch, xR, xC, d1);
} else {
xTexelR${x}C${A} = vec4(0.);
}
xCOffset = xC + ${c};
if(xCOffset >= 0 && xCOffset < ${r}) {
xTexelR${x}C${A+2} = getX(batch, xR, xCOffset, d1);
} else {
xTexelR${x}C${A+2} = vec4(0.);
}
xR${x}C${A} = vec4(
xTexelR${x}C${A}.xy, xTexelR${x}C${A+2}.xy);
`,A+1<d&&(f+=`
xR${x}C${A+1} = vec4(
xTexelR${x}C${A}.zw, xTexelR${x}C${A+2}.zw);
`)),f+="}");A<d&&(f+=`
vec4 wTexelR${x}C${A} = getW(${x}, ${A}, d1, q);
wR${x}C${A} = vec4(wTexelR${x}C${A}.xz, wTexelR${x}C${A}.xz);
`,A+1<d&&(f+=`
vec4 wTexelR${x}C${A+1} = getW(${x}, ${A+1}, d1, q);
wR${x}C${A+1} =
vec4(wTexelR${x}C${A+1}.xz, wTexelR${x}C${A+1}.xz);`))}for(let x=0;x<h;x++)for(let T=0;T<d;T++)f+=`dotProd += xR${x}C${T} * wR${x}C${T};`;let g="",y="";s&&(n?g=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${s}
}`:g=`vec4 activation(vec4 x) {
${s}
}`,y="result = activation(result);");const w=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${g}
const ivec2 strides = ivec2(${l}, ${c});
const ivec2 pads = ivec2(${o}, ${a});
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.);
${f}
vec4 result = dotProd;
${w}
${y}
setOutput(result);
}
`}}class qR{constructor(e,t,s,n,i){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[r,o,a,l]=e,[c]=t,[p,u]=s;this.outputShape=[c,p,u,l];const h=n==="bilinear"?1:0,[d,m]=[`${o-1}.0`,`${a-1}.0`],[f,g,y]=p>1?[`${(o-1)/(p-1)}`,"(y2-y1) * height_ratio",`y1*${d} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${d}`],[w,x,T]=u>1?[`${(a-1)/(u-1)}`,"(x2-x1) * width_ratio",`x1*${m} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${m}`];this.userCode=`
const float height_ratio = float(${f});
const float width_ratio = float(${w});
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 >= ${r}) {
return;
}
float height_scale = ${g};
float width_scale = ${x};
float in_y = ${y};
if( in_y < 0.0 || in_y > ${d} ) {
setOutput(float(${i}));
return;
}
float in_x = ${T};
if( in_x < 0.0 || in_x > ${m} ) {
setOutput(float(${i}));
return;
}
vec2 sourceFracIndexCR = vec2(in_x,in_y);
if(${h} == 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 Jw{constructor(e,t,s){this.variableNames=["x"],this.outputShape=e;const n=e.length,i=t?"0.0":`getX(${HR(n,"coords")})`,r=e[e.length-1];let o="",a="";t?(o=s?`end != ${r-1}`:"end != 0",a=s?"end + 1":"end - 1"):(o=s?`end + pow2 < ${r}`:"end >= pow2",a=s?"end + pow2":"end - pow2"),this.userCode=`
uniform float index;
void main() {
${Re(n)} coords = getOutputCoords();
int end = ${YR(n,"coords")};
float val = ${i};
int pow2 = int(pow(2.0, index));
if (${o}) {
int idx = ${a};
${YR(n,"coords")} = idx;
val += getX(${HR(n,"coords")});
}
setOutput(val);
}
`}getCustomSetupFunc(e){return(t,s)=>{this.index==null&&(this.index=t.getUniformLocation(s,"index")),t.gl.uniform1f(this.index,e)}}}function HR(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 YR(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 KR{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=lo.DENSE;const t=co(e),s=at();this.outputShape=e,this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
${jn(["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);
}
${s.output} = result;
}
`}}class XR{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=lo.DENSE;const t=co(e),s=at();this.outputShape=e,this.userCode=`
ivec3 outCoordsFromFlatIndex(int index) {
${jn(["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));
}
${s.output} = result;
}
`}}class JR{constructor(e,t,s){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=s,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 ZR{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 QR{constructor(e){this.variableNames=["A"],this.outTexUsage=ns.DOWNLOAD;const t=at();this.outputShape=e,this.userCode=`
${Sf}
void main() {
float x = getAAtOutCoords();
${t.output} = encode_float(x);
}
`}}class e2{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=ns.DOWNLOAD;const t=at();this.outputShape=e,this.userCode=`
${Sf}
void main() {
ivec3 coords = getOutputCoords();
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
${t.output} = encode_float(x);
}
`}}class t2{constructor(e,t,s=!1){this.variableNames=["A"];const n=at(),[i,r]=t;this.outputShape=e;let o="result";s&&(o="floor(result * 255. + 0.5)"),this.userCode=`
${Pl(e)}
void main() {
ivec3 coords = getOutputCoords();
int flatIndex = getFlatIndex(coords);
int offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
int r = flatIndex / ${r};
int c = imod(flatIndex, ${r});
vec2 uv = (vec2(c, r) + halfCR) / vec2(${r}.0, ${i}.0);
vec4 values = ${n.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];
}
${n.output} = vec4(${o}, 0., 0., 0.);
}
`}}class s2{constructor(e,t,s=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const n=at(),[i,r]=t;this.outputShape=e;let o="",a="result";s&&(a="floor(result * 255. + 0.5)");for(let l=0;l<=1;l++)for(let c=0;c<=1;c++){const p=l*2+c;o+=`
localCoords = coords;
if(localCoords[2] + ${c} < ${e[2]}) {
localCoords[2] += ${c};
if(localCoords[1] + ${l} < ${e[1]}) {
localCoords[1] += ${l};
flatIndex = getFlatIndex(localCoords);
offset = imod(flatIndex, 4);
flatIndex = idiv(flatIndex, 4, 1.);
r = flatIndex / ${r};
c = imod(flatIndex, ${r});
uv = (vec2(c, r) + halfCR) / vec2(${r}.0, ${i}.0);
values = ${n.texture2D}(A, uv);
if(offset == 0) {
result[${p}] = values[0];
} else if(offset == 1) {
result[${p}] = values[1];
} else if(offset == 2) {
result[${p}] = values[2];
} else {
result[${p}] = values[3];
}
}
}
`}this.userCode=`
${Pl(e)}
void main() {
ivec3 coords = getOutputCoords();
vec4 result = vec4(0.);
int flatIndex, r, c, offset;
ivec3 localCoords;
vec2 uv;
vec4 values;
${o}
${n.output} = ${a};
}
`}}const Zw={REAL:"return real * expR - imag * expI;",IMAG:"return real * expI + imag * expR;"};class Qw{constructor(e,t,s){this.variableNames=["real","imag"];const n=t[1];this.outputShape=t;const i=s?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,r=s?`${n}.0`:"1.0";this.userCode=`
const float exponentMultiplier = ${i};
float unaryOpComplex(float real, float expR, float imag, float expI) {
${e}
}
float mulMatDFT(int batch, int index) {
float indexRatio = float(index) / float(${n});
float exponentMultiplierTimesIndexRatio =
exponentMultiplier * indexRatio;
float result = 0.0;
for (int i = 0; i < ${n}; 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) / ${r};
}
return result;
}
void main() {
ivec2 coords = getOutputCoords();
setOutput(mulMatDFT(coords[0], coords[1]));
}
`}}class n2{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,s)=>{this.valueLoc==null&&(this.valueLoc=t.getUniformLocationNoThrow(s,"value")),t.gl.uniform1f(this.valueLoc,e)}}}class i2{constructor(e,t,s){this.variableNames=["A","indices"];const n=e.slice();n[s]=t,this.outputShape=n,this.rank=n.length;const i=Re(this.rank),r=V3(e,s);this.userCode=`
void main() {
${i} resRC = getOutputCoords();
setOutput(getA(${r}));
}
`}}function V3(e,t){const s=e.length;if(s>4)throw Error(`Gather for rank ${s} is not yet supported`);if(s===1)return"int(getIndices(resRC))";const n=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[];for(let r=0;r<e.length;r++)r===t?i.push(`int(getIndices(${n[r]}))`):i.push(`${n[r]}`);return i.join()}class r2{constructor(e,t,s){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=s;const n=Re(t.length),i=Re(s.length),r=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
${n} strides = ${n}(${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 * ${r};
}
setOutput(getX(flattenIndex, coords[1]));
}
`}}function o2(e){const t=at(),s=`${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 g0(e,s)}function a2(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 x0(e,t)}function l2(e){const t=new Uint16Array([0,1,2,2,1,3]);return L0(e,t)}function wu(e,t,s,n,i,r){I0(t,s);const o=S0(e),a=e.TEXTURE_2D;return pe(e,()=>e.bindTexture(a,o)),pe(e,()=>e.texParameteri(a,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),pe(e,()=>e.texParameteri(a,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),pe(e,()=>e.texParameteri(a,e.TEXTURE_MIN_FILTER,e.NEAREST)),pe(e,()=>e.texParameteri(a,e.TEXTURE_MAG_FILTER,e.NEAREST)),pe(e,()=>e.texImage2D(a,0,n,t,s,0,i,r,null)),pe(e,()=>e.bindTexture(e.TEXTURE_2D,null)),o}function ex(e){return e.internalFormatFloat}function c2(e,t,s,n){const[i,r]=pa(t,s);return wu(e,i,r,ex(n),n.textureFormatFloat,e.FLOAT)}function tx(e){return e.internalFormatHalfFloat}function p2(e,t,s,n){const[i,r]=pa(t,s);return wu(e,i,r,tx(n),n.textureFormatFloat,n.textureTypeHalfFloat)}function sx(e){return e.downloadTextureFormat}function u2(e,t,s,n){const[i,r]=pa(t,s);return wu(e,i,r,sx(n),e.RGBA,e.UNSIGNED_BYTE)}function nx(e){return e.internalFormatPackedFloat}function h2(e,t,s,n){const[i,r]=gi(t,s);return wu(e,i,r,nx(n),e.RGBA,e.FLOAT)}function ix(e){return e.internalFormatPackedHalfFloat}function d2(e,t,s,n){const[i,r]=gi(t,s);return wu(e,i,r,ix(n),e.RGBA,n.textureTypeHalfFloat)}function m2(e,t,s){const n=0,i=3*4,r=3*4+2*4;pe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,s));const o=Mw(e,t,"clipSpacePos",s,3,r,n);return o&&Mw(e,t,"uv",s,2,r,i)}function f2(e,t,s,n,i,r){pe(e,()=>e.bindTexture(e.TEXTURE_2D,t));let o,a,l;i instanceof Uint8Array?(o=new Uint8Array(s*n*4),a=e.UNSIGNED_BYTE,l=e.RGBA):(o=new Float32Array(s*n*4),a=e.FLOAT,l=r.internalFormatPackedFloat),o.set(i),pe(e,()=>e.texImage2D(e.TEXTURE_2D,0,l,s,n,0,e.RGBA,a,o)),pe(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function g2(e,t,s){pe(e,()=>e.bindTexture(e.TEXTURE_2D,t)),s.data instanceof Uint8Array?pe(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,s.width,s.height,0,e.RGBA,e.UNSIGNED_BYTE,s.data)):pe(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,s)),pe(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function y2(e,t,s,n){const i=e.createBuffer();pe(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,i));const r=4,o=4,a=r*o*t*s;return pe(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,a,e.STREAM_READ)),pe(e,()=>e.readPixels(0,0,s,t,e.RGBA,e.FLOAT,0)),pe(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),i}function b2(e,t,s){const n=e,i=new Float32Array(s);return n.bindBuffer(n.PIXEL_PACK_BUFFER,t),n.getBufferSubData(n.PIXEL_PACK_BUFFER,0,i),n.bindBuffer(n.PIXEL_PACK_BUFFER,null),i}function w2(e,t,s,n){const[i,r]=pa(t,s),o=4,a=new Uint8Array(d0(t*s,o));return pe(e,()=>e.readPixels(0,0,i,r,n.downloadTextureFormat,e.UNSIGNED_BYTE,a)),new Float32Array(a.buffer)}function x2(e,t,s,n,i,r,o,a){const l=e,c=new Float32Array(m0(r,o));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,c),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),c}function L2(e,t,s){const n=new Float32Array(t*s*4);return pe(e,()=>e.readPixels(0,0,s,t,e.RGBA,e.FLOAT,n)),n}class rx{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];const t=W().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,Fw(t,e)):this.gl=nn(t);let s="WEBGL_color_buffer_float";const n="EXT_color_buffer_half_float";if(W().getNumber("WEBGL_VERSION")===1){const i="OES_texture_float",r="OES_texture_half_float";if(this.textureFloatExtension=yu(this.gl,i),rn(this.gl,r))this.textureHalfFloatExtension=yu(this.gl,r);else if(W().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(s),rn(this.gl,n))this.colorBufferHalfFloatExtension=yu(this.gl,n);else if(W().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(s="EXT_color_buffer_float",rn(this.gl,s))this.colorBufferFloatExtension=this.gl.getExtension(s);else if(rn(this.gl,n))this.colorBufferHalfFloatExtension=this.gl.getExtension(n);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=a2(this.gl),this.indexBuffer=l2(this.gl),this.framebuffer=v0(this.gl),this.textureConfig=gu(this.gl,this.textureHalfFloatExtension)}get debug(){return W().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;pe(e,()=>e.finish()),pe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),pe(e,()=>e.deleteFramebuffer(this.framebuffer)),pe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),pe(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),pe(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),c2(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),p2(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),u2(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),g2(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,s,n){this.throwIfDisposed(),f2(this.gl,e,t,s,n,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),d2(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),h2(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(Uw(this.gl,this.framebuffer),this.outputTexture=null),pe(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,s){return this.downloadMatrixDriver(e,()=>w2(this.gl,t,s,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,s,n,i,r){return x2(this.gl,e,t,s,n,i,r,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return b2(this.gl,e,t)}createBufferFromTexture(e,t,s){this.bindTextureToFrameBuffer(e);const n=y2(this.gl,t,s,this.textureConfig);return this.unbindTextureToFrameBuffer(),n}createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,s;if(W().getBool("WEBGL_FENCE_API_ENABLED")){const n=e,i=n.fenceSync(n.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),s=()=>{const r=n.clientWaitSync(i,0,0);return r===n.ALREADY_SIGNALED||r===n.CONDITION_SATISFIED},t=i}else W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),s=()=>this.isQueryAvailable(t,W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):s=()=>!0;return{query:t,isFencePassed:s}}downloadMatrixFromPackedTexture(e,t,s){return this.downloadMatrixDriver(e,()=>L2(this.gl,t,s))}createProgram(e){this.throwIfDisposed();const t=this.gl,s=y0(t,e),n=o2(t),i=b0(t);return pe(t,()=>t.attachShader(i,n)),pe(t,()=>t.attachShader(i,s)),w0(t,i),this.debug&&yf(t,i),this.vertexAttrsAreBound||(this.setProgram(i),this.vertexAttrsAreBound=m2(t,this.program,this.vertexBuffer)),i}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&pe(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&yf(this.gl,this.program),pe(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,s=!0){return this.throwIfDisposed(),s?T0(this.gl,e,t):A0(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),pe(this.gl,()=>this.gl.getAttribLocation(e,t))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,s){this.throwIfDisposed(),this.throwIfNoProgram(),N0(this.gl,e,t,s)}setOutputMatrixTexture(e,t,s){this.setOutputMatrixTextureDriver(e,s,t)}setOutputPackedMatrixTexture(e,t,s){this.throwIfDisposed();const[n,i]=gi(t,s);this.setOutputMatrixTextureDriver(e,n,i)}setOutputMatrixWriteRegion(e,t,s,n){this.setOutputMatrixWriteRegionDriver(s,e,n,t)}setOutputPackedMatrixWriteRegion(e,t,s,n){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&yf(this.gl,this.program),bu(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const e=this.gl;this.debug&&this.debugValidate(),pe(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),pe(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=yu(this.gl,W().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(W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){const s=this.gl,n=this.getQueryTimerExtensionWebGL2(),i=s.createQuery();return s.beginQuery(n.TIME_ELAPSED_EXT,i),i}const e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){const t=this.gl,s=this.getQueryTimerExtensionWebGL2();t.endQuery(s.TIME_ELAPSED_EXT);return}const e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await N.repeatedTry(()=>this.disposed||this.isQueryAvailable(e,W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(t===0)return null;if(t===2){const s=this.gl,n=s.getQueryParameter(e,s.QUERY_RESULT);return n/1e6}else{const s=this.getQueryTimerExtensionWebGL1(),n=s.getQueryObjectEXT(e,s.QUERY_RESULT_EXT);return n/1e6}}isQueryAvailable(e,t){if(t===0)return!0;if(t===2){const s=this.gl,n=this.getQueryTimerExtensionWebGL2(),i=s.getQueryParameter(e,s.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),i&&!this.disjoint}else{const s=this.getQueryTimerExtensionWebGL1(),n=s.getQueryObjectEXT(e,s.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(s.GPU_DISJOINT_EXT)),n&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){const e=G3(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=e;++t){const{resolveFn:s}=this.itemsToPoll[t];s()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){if(this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1)return;N.repeatedTry(()=>(this.pollItems(),this.itemsToPoll.length===0))}bindTextureToFrameBuffer(e){this.throwIfDisposed(),bf(this.gl,e,this.framebuffer),this.debug&&bu(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(bf(this.gl,this.outputTexture,this.framebuffer),this.debug&&bu(this.gl)):Uw(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);const s=t();return this.unbindTextureToFrameBuffer(),s}setOutputMatrixTextureDriver(e,t,s){this.throwIfDisposed();const n=this.gl;bf(n,e,this.framebuffer),this.debug&&bu(n),this.outputTexture=e,pe(n,()=>n.viewport(0,0,t,s)),pe(n,()=>n.scissor(0,0,t,s))}setOutputMatrixWriteRegionDriver(e,t,s,n){this.throwIfDisposed(),pe(this.gl,()=>this.gl.scissor(e,t,s,n))}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 G3(e){let t=0;for(;t<e.length;++t){const s=e[t]();if(!s)break}return t-1}function S2(e,t,s,n){const i=t.userCode,r=s.map((d,m)=>{const f={logicalShape:d.shape,texShape:d.isUniform?null:d.texData.texShape,isUniform:d.isUniform,isPacked:d.isUniform?!1:d.texData.isPacked,flatOffset:null};return d.texData!=null&&d.texData.slice!=null&&d.texData.slice.flatOffset>0&&(f.flatOffset=d.texData.slice.flatOffset),{name:t.variableNames[m],shapeInfo:f}}),o=r.map(d=>d.shapeInfo),a={logicalShape:n.shape,texShape:n.texData.texShape,isUniform:!1,isPacked:n.texData.isPacked,flatOffset:null},l=Q0(r,a,i,t.packedInputs),c=e.createProgram(l);let p=null;const u=e.getUniformLocation(c,"NAN",!1);W().getNumber("WEBGL_VERSION")===1&&(p=e.getUniformLocation(c,"INFINITY",!1));const h={};for(let d=0;d<t.variableNames.length;d++){const m=t.variableNames[d],f=!1;h[m]=e.getUniformLocation(c,m,f),h[`offset${m}`]=e.getUniformLocation(c,`offset${m}`,f)}return{program:t,source:l,webGLProgram:c,uniformLocations:h,inShapeInfos:o,outShapeInfo:a,infLoc:p,nanLoc:u}}function I2(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((s,n)=>{const i=s.logicalShape,r=t[n],o=r.shape;if(!N.arraysEqual(i,o))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${i} and ${o} must match`);if(s.isUniform&&r.isUniform)return;const a=s.texShape,l=r.isUniform?null:r.texData.texShape;if(!N.arraysEqual(a,l))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${a} and ${l} must match`)})}function v2(e,t,s,n,i){I2(t.inShapeInfos,s),I2([t.outShapeInfo],[n]);const r=n.texData.texture,o=n.texData.texShape;n.texData.isPacked?e.setOutputPackedMatrixTexture(r,o[0],o[1]):e.setOutputMatrixTexture(r,o[0],o[1]),e.setProgram(t.webGLProgram),W().getNumber("WEBGL_VERSION")===1&&(t.infLoc!==null&&e.gl.uniform1f(t.infLoc,Infinity)),t.nanLoc!==null&&e.gl.uniform1f(t.nanLoc,NaN),s.forEach((a,l)=>{const c=t.program.variableNames[l],p=t.uniformLocations[c],u=t.uniformLocations[`offset${c}`];if(p==null)return;if(a.isUniform){if(N.sizeFromShape(a.shape)<2)e.gl.uniform1f(p,a.uniformValues[0]);else{let h=a.uniformValues;h instanceof Float32Array||(h=new Float32Array(h)),e.gl.uniform1fv(p,h)}return}a.texData.slice!=null&&u!=null&&e.gl.uniform1i(u,a.texData.slice.flatOffset),e.setInputMatrixTexture(a.texData.texture,p,l)}),i!=null&&i(e,t.webGLProgram),e.executeProgram()}function T2(e,t,s){let n="";t.concat(s).forEach(o=>{const a=o.texData!=null&&o.texData.slice!=null&&o.texData.slice.flatOffset>0,l=o.isUniform?"uniform":o.texData.texShape;n+=`${o.shape}_${l}_${a}`});const i=e.userCode;let r=e.constructor.name;return r+="_"+n+"_"+i,r}class A2{constructor(e,t,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;const{filterWidth:n,inChannels:i,strideWidth:r,strideHeight:o,padInfo:a,outWidth:l,dilationWidth:c,dilationHeight:p,dataFormat:u}=s,{left:h,top:d}=a,m=i*n,f=at(),g=u==="channelsLast",y=g?0:1,w=g?1:2;let x="";for(let T=0;T<=1;T++)for(let A=0;A<=1;A++)x+=`
blockIndex = rc.y + ${A};
pos = rc.x + ${T};
if(blockIndex < ${e[1]} && pos < ${e[0]}) {
offsetY = int(blockIndex / (${l})) * ${o} - ${d};
d0 = offsetY + ${p} * (pos / ${m});
if(d0 < ${t[y]} && d0 >= 0) {
offsetX = int(mod(float(blockIndex), ${l}.) * ${r}. - ${h}.);
d1 = offsetX + ${c} * (int(mod(float(pos), ${m}.) / ${i}.));
if(d1 < ${t[w]} && d1 >= 0) {
ch = int(mod(float(pos), ${i}.));
if (${g}) {
innerDims = vec2(d1, ch);
result[${T*2+A}] = getChannel(
getA(d0, int(innerDims.x),
int(innerDims.y)), innerDims);
} else {
innerDims = vec2(d0, d1);
result[${T*2+A}] = 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;
${x}
${f.output} = result;
}
`}}class N2{constructor(e,t,s,n,i){this.variableNames=["x"],this.outputShape=[];const r=t,o=e[3]-1;this.outputShape=e;let a;const l=`float(${s}) + float(${n}) * sum`;i===.5?a=`inversesqrt(${l})`:i===1?a=`1.0/(${l})`:a=`exp(log(${l}) * 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 = -${r}; j <= ${r}; j++) {
int idx = d + j;
if (idx >= 0 && idx <= ${o}) {
float z = getX(b, r, c, idx);
sum += z * z;
}
}
float val = x * ${a};
setOutput(val);
}
`}}class C2{constructor(e,t,s,n,i){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=s,this.alpha=n,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(${n}) * norm + float(${s});
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(${n})
* 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 R2{constructor(e,t,s,n,i){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;const r=t,o=e[3]-1;this.outputShape=e;let a;const l=`float(${s}) + float(${n}) * sum`;i===.5?a=`inversesqrt(${l})`:i===1?a=`1.0/(${l})`:a=`exp(log(${l}) * 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 - ${r};
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 = - ${r}; j <= ${r}; j++) {
ivec2 idx = depth + j;
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${o}));
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 * ${a};
setOutput(result);
}
`}}class O2{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideHeight,s=e.strideWidth,n=e.dilationHeight,i=e.effectiveFilterHeight,r=e.effectiveFilterWidth,o=i-1-e.padInfo.top,a=r-1-e.padInfo.left,l=i*r-1;this.userCode=`
const ivec2 pads = ivec2(${o}, ${a});
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 += ${n}) {
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 < ${r}; wC++) {
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(b, idyR, idyC, d);
int maxPosValue = ${l} - int(getMaxPos(b, idyR, idyC, d));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue = wR * ${r} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
setOutput(dotProd);
}
`}}class E2{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideDepth,s=e.strideHeight,n=e.strideWidth,i=e.dilationDepth,r=e.dilationHeight,o=e.dilationWidth,a=e.effectiveFilterDepth,l=e.effectiveFilterHeight,c=e.effectiveFilterWidth,p=a-1-e.padInfo.front,u=l-1-e.padInfo.top,h=c-1-e.padInfo.left,d=a*l*c-1;this.userCode=`
const ivec3 pads = ivec3(${p}, ${u}, ${h});
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 < ${a};
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 < ${l};
wR += ${r}) {
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 < ${c};
wC += ${o}) {
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(batch, idyD, idyR, idyC, ch);
int maxPosValue = ${d} -
int(getMaxPos(batch, idyD, idyR, idyC, ch));
// Get the current value, check it against the value from the
// position matrix.
int curPosValue =
wD * ${l} * ${c} +
wR * ${c} + wC;
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
dotProd += dyValue * mask;
}
}
}
setOutput(dotProd);
}
`}}class Nf{constructor(e,t,s=!1,n=!1,i=!1,r=null,o=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;const a=s?e[1]:e[2],l=Math.ceil(a/2),c=s?"i * 2, rc.y":"rc.y, i * 2",p=n?"rc.z, i * 2":"i * 2, rc.z",u=s?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],h=n?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let d="",m="";r&&(o?d=`vec4 activation(vec4 a) {
vec4 b = getPreluActivationWeightsAtOutCoords();
${r}
}`:d=`vec4 activation(vec4 x) {
${r}
}`,m="result = activation(result);");const f=i?"result += getBiasAtOutCoords();":"";i&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),this.userCode=`
${d}
const float sharedDimension = ${l}.0;
vec4 dot2x2ARowBCol(ivec3 rc) {
vec4 result = vec4(0);
for (int i = 0; i < ${l}; i++) {
vec4 a = getMatrixA(rc.x, ${c});
vec4 b = getMatrixB(rc.x, ${p});
// These swizzled products need to be separately added.
// See: https://github.com/tensorflow/tfjs/issues/1735
result += (${u[0]} * ${h[0]});
result += (${u[1]} * ${h[1]});
}
return result;
}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = dot2x2ARowBCol(rc);
${f}
${m}
setOutput(result);
}
`}}class _2{constructor(e,t,s){this.variableNames=["probs"],this.outputShape=[e,s],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,s)=>{this.seedLoc==null&&(this.seedLoc=t.getUniformLocation(s,"seed")),t.gl.uniform1f(this.seedLoc,e)}}}class k2{constructor(e,t,s,n){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
void main() {
ivec2 coords = getOutputCoords();
int index = round(getIndices(coords.x));
setOutput(mix(float(${n}), float(${s}),
float(index == coords.y)));
}
`}}class D2{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 s=_t("rc",t),n=Re(t),i=q3(t,e,s),r=H3(t,e[e.length-1],e[e.length-2],s),o=Y3(e,s);this.userCode=`
void main() {
${n} rc = getOutputCoords();
if(${i}) {
setOutput(vec4(0));
} else {
${r}
setOutput(vec4(${o}));
}
}
`}}}function K3(e,t){const s=[];for(let n=0;n<=1;n++)for(let i=0;i<=1;i++){let r=`${n===0?"r":"rp1"}, ${i===0?"c":"cp1"}`;for(let o=2;o<e;o++)r=`${t[t.length-1-o]},`+r;s.push(r)}return s}function q3(e,t,s){if(e===1)return`rc > ${t[0]}`;let n="";for(let i=e-2;i<e;i++)n+=`${s[i]} >= ${t[i]}`,i<e-1&&(n+="||");return n}function H3(e,t,s,n){if(e===1)return"";const i=n.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 >= ${s};
`}function Y3(e,t){const s=e.length,n=K3(s,t);return s===1?`getA(rc),
rc + 1 >= ${e[0]} ? 0. : getA(rc + 1),
0, 0`:`getA(${n[0]}),
cEdge ? 0. : getA(${n[1]}),
rEdge ? 0. : getA(${n[2]}),
rEdge || cEdge ? 0. : getA(${n[3]})`}class F2{constructor(e,t,s){this.variableNames=["x"],this.outputShape=t.map((l,c)=>l[0]+e[c]+l[1]);const n=e.length,i=Re(n),r=t.map(l=>l[0]).join(","),o=t.map((l,c)=>l[0]+e[c]).join(","),a=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n);if(n===1){this.userCode=`
int start = ${r};
int end = ${o};
void main() {
int outC = getOutputCoords();
if (outC < start || outC >= end) {
setOutput(float(${s}));
} else {
setOutput(getX(outC - start));
}
}
`;return}this.userCode=`
${i} start = ${i}(${r});
${i} end = ${i}(${o});
void main() {
${i} outC = getOutputCoords();
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
setOutput(float(${s}));
} else {
${i} coords = outC - start;
setOutput(getX(${a}));
}
}
`}}class M2{constructor(e,t,s){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((m,f)=>m[0]+e[f]+m[1]);const n=e.length,i=Re(n),r=t.map(m=>m[0]).join(","),o=t.map((m,f)=>m[0]+e[f]).join(","),a=_t("rc",n),l=_t("source",n),c=`${a[n-1]} < ${this.outputShape[n-1]}`,p=n===1?"source":`vec2(${l.slice(-2).join()})`,u=[`${i} rc = outputLoc;`,`${a[n-1]} += 1;
if(${c}) {
`,n===1?"":`}
rc = outputLoc;
${a[n-2]} += 1;
if(${a[n-2]} < ${this.outputShape[n-2]}) {`,n===1?"":` ${a[n-1]} += 1;
if(${c}) {`],h=n===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let d="";for(let m=0,f=n===1?2:4;m<f;m++)d+=`
${u[m]}
if (${h}) {
result[${m}] = float(${s});
} else {
${i} source = rc - start;
result[${m}] = getChannel(getX(${l.join()}), ${p});
}
`;d+=n===1?"} ":"}}",this.userCode=`
const ${i} start = ${i}(${r});
const ${i} end = ${i}(${o});
void main() {
${i} outputLoc = getOutputCoords();
vec4 result = vec4(0.);
${d}
setOutput(result);
}
`}}class Ki{constructor(e,t,s,n=!1,i=!1){if(this.variableNames=["x"],t==="avg"&&s)throw new Error("Cannot compute positions for average pool.");const r=e.filterWidth,o=e.strideHeight,a=e.strideWidth,l=e.dilationHeight,c=e.dilationWidth,p=e.effectiveFilterHeight,u=e.effectiveFilterWidth,h=e.padInfo.top,d=e.padInfo.left;this.outputShape=e.outShape;const m=t==="avg",f=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let y="0.0";if(m||(y="-1.0 / 1e-20"),s){const E=">=";this.userCode=`
const ivec2 strides = ivec2(${o}, ${a});
const ivec2 pads = ivec2(${h}, ${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
float minMaxValue = 0.0;
float minMaxValueFound = 0.0;
int minMaxPosition = 0;
float avgValue = 0.0;
for (int wR = 0; wR < ${p};
wR += ${l}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${u};
wC += ${c}) {
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 ${E} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${n?i?f:g:`wR * ${u} + wC`};
}
}
}
setOutput(float(minMaxPosition));
}
`;return}const w="max";let x=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(x="avgValue / count");const T=Math.floor(r/4)*4,A=r%4,_=`
if (${m}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${w}(values, minMaxValue);
}
`;this.userCode=`
const ivec2 strides = ivec2(${o}, ${a});
const ivec2 pads = ivec2(${h}, ${d});
const float initializationValue = ${y};
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(${y});
float avgValue = 0.0;
count = 0.0;
for (int wR = 0; wR < ${p};
wR += ${l}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${T}; wC += 4) {
int xC = xCCorner + wC * ${c};
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${c}, d),
getValue(batch, xR, xC + 2 * ${c}, d),
getValue(batch, xR, xC + 3 * ${c}, d)
);
${_}
}
int xC = xCCorner + ${T};
if (${A===1}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
initializationValue,
initializationValue,
initializationValue
);
${_}
} else if (${A===2}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${c}, d),
initializationValue,
initializationValue
);
${_}
} else if (${A===3}) {
vec4 values = vec4(
getValue(batch, xR, xC, d),
getValue(batch, xR, xC + ${c}, d),
getValue(batch, xR, xC + 2 * ${c}, d),
initializationValue
);
${_}
}
}
setOutput(${x});
}
`}}class Cf{constructor(e,t,s,n=!1,i=!1){if(this.variableNames=["x"],t==="avg"&&s)throw new Error("Cannot compute positions for average pool.");const r=e.filterWidth,o=e.strideDepth,a=e.strideHeight,l=e.strideWidth,c=e.dilationDepth,p=e.dilationHeight,u=e.dilationWidth,h=e.effectiveFilterDepth,d=e.effectiveFilterHeight,m=e.effectiveFilterWidth,f=e.padInfo.front,g=e.padInfo.top,y=e.padInfo.left;this.outputShape=e.outShape;const w=t==="avg";let x="0.0";if(w||(x="-1.0 / 1e-20"),s){const D=">=";this.userCode=`
const ivec3 strides =
ivec3(${o}, ${a}, ${l});
const ivec3 pads = ivec3(${f}, ${g}, ${y});
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 < ${h};
wD += ${c}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${d};
wR += ${p}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${m};
wC += ${u}) {
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 ${D} currMinMaxValue) {
minMaxValue = value;
minMaxValueFound = 1.0;
minMaxPosition = ${n?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 * ${d} * ${m} +
wR * ${m} + wC`};
}
}
}
}
setOutput(float(minMaxPosition));
}
`;return}const T="max";let A=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(A="avgValue / count");const _=Math.floor(r/4)*4,E=r%4,F=`
if (${w}) {
avgValue += dot(values, ones);
} else {
minMaxValue = ${T}(values, minMaxValue);
}
`;this.userCode=`
const ivec3 strides =
ivec3(${o}, ${a}, ${l});
const ivec3 pads = ivec3(${f}, ${g}, ${y});
const float initializationValue = ${x};
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(${x});
float avgValue = 0.0;
count = 0.0;
for (int wD = 0; wD < ${h};
wD += ${c}) {
int xD = xDCorner + wD;
if (xD < 0 || xD >= ${e.inDepth}) {
continue;
}
for (int wR = 0; wR < ${d};
wR += ${p}) {
int xR = xRCorner + wR;
if (xR < 0 || xR >= ${e.inHeight}) {
continue;
}
for (int wC = 0; wC < ${_}; wC += 4) {
int xC = xCCorner + wC * ${u};
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${u}, ch),
getValue(batch, xD, xR, xC + 2 * ${u}, ch),
getValue(batch, xD, xR, xC + 3 * ${u}, ch)
);
${F}
}
int xC = xCCorner + ${_};
if (${E===1}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
initializationValue,
initializationValue,
initializationValue
);
${F}
} else if (${E===2}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${u}, ch),
initializationValue,
initializationValue
);
${F}
} else if (${E===3}) {
vec4 values = vec4(
getValue(batch, xD, xR, xC, ch),
getValue(batch, xD, xR, xC + ${u}, ch),
getValue(batch, xD, xR, xC + 2 * ${u}, ch),
initializationValue
);
${F}
}
}
setOutput(${A});
}
}
`}}class Rf{constructor(e,t){this.variableNames=["x"];const{windowSize:s,batchSize:n,inSize:i,outSize:r}=e;this.outputShape=[n,r];let o="0.0",a="";t==="prod"?o="1.0":t==="min"?(o="1.0 / 1e-20",a="min"):t==="max"&&(o="-1.0 / 1e-20",a="max");let l=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?l="sumValue":t==="prod"?l="prodValue":t==="all"?l="allValue":t==="any"&&(l="anyValue");const c=Math.floor(s/4)*4,p=s%4;let u=`
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 = ${a}(values, minMaxValue);
}
`,h="vec4";t==="all"?(o="1.0",u=`
bool reducedAllValue = all(values);
float floatedReducedAllValue = float(reducedAllValue);
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
`,h="bvec4"):t==="any"&&(o="0.0",u=`
bool reducedAnyValue = any(values);
float floatedReducedAnyValue = float(reducedAnyValue);
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
`,h="bvec4");let d="";i%s>0&&(d=`
if (inIdx < 0 || inIdx >= ${i}) {
return initializationValue;
}
`),this.userCode=`
const float initializationValue = ${o};
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 * ${s};
vec4 minMaxValue = vec4(${o});
float prodValue = 1.0;
float sumValue = 0.0;
float allValue = 1.0;
float anyValue = 0.0;
for (int i = 0; i < ${c}; i += 4) {
int inIdx = inOffset + i;
${h} values = ${h}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
getValue(batch, inIdx + 3)
);
${u}
}
int inIdx = inOffset + ${c};
if (${p===1}) {
${h} values = ${h}(
getValue(batch, inIdx),
initializationValue,
initializationValue,
initializationValue
);
${u}
} else if (${p===2}) {
${h} values = ${h}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
initializationValue,
initializationValue
);
${u}
} else if (${p===3}) {
${h} values = ${h}(
getValue(batch, inIdx),
getValue(batch, inIdx + 1),
getValue(batch, inIdx + 2),
initializationValue
);
${u}
}
setOutput(${l});
}
`}}class Of{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;let s="";for(let n=0;n<4;n++){let i="thisRC = rc;";n%2===1&&(i+="thisRC.z += 1;"),n>1&&(i+="thisRC.y += 1;"),s+=`
${i}
${n>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[${n}] =
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
${n>0?"}":""}
`}this.userCode=`
${X3(t)}
${Pl(e)}
void main() {
ivec3 rc = getOutputCoords();
vec4 result = vec4(0.);
ivec3 thisRC;
int rows = ${e[1]};
int cols = ${e[2]};
${s}
setOutput(result);
}
`}}function X3(e){const t=jn(["r","c","d"],e);return`
ivec3 inputCoordsFromReshapedOutCoords(int index) {
${t}
return ivec3(r, c, d);
}
`}class U2{constructor(e,t,s){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;const[,n,i]=t.shape,[,r,o]=e.shape,a=[s&&r>1?n-1:n,s&&o>1?i-1:i],l=[s&&r>1?r-1:r,s&&o>1?o-1:o],c=a[0]/l[0],p=a[1]/l[1],u=1/c,h=1/p,d=Math.ceil(u)*2+2,m=Math.ceil(h)*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(${c});
const float widthScale = float(${p});
const float invHeightScale = float(${u});
const float invWidthScale = float(${h});
const int winHeight = int(${d});
const int winWidth = int(${m});
// 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 >= ${r}) {
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 >= ${o}) {
continue;
}
float dxR = float(dyR) * heightScale;
int topDxRIndex = int(floor(dxR));
int bottomDxRIndex = int(min(ceil(dxR), ${n-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 $2{constructor(e,t,s,n){this.variableNames=["A"],this.outputShape=[];const[i,r,o,a]=e;this.outputShape=[i,t,s,a];const l=[n&&t>1?r-1:r,n&&s>1?o-1:o],c=[n&&t>1?t-1:t,n&&s>1?s-1:s];this.userCode=`
const vec2 effectiveInputOverOutputRatioRC = vec2(
${l[0]/c[0]},
${l[1]/c[1]});
const vec2 inputShapeRC = vec2(${r}.0, ${o}.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 W2{constructor(e,t,s,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[i,r,o,a]=e;this.outputShape=[i,t,s,a];const l=[n&&t>1?r-1:r,n&&s>1?o-1:o],c=[n&&t>1?t-1:t,n&&s>1?s-1:s];this.userCode=`
const vec3 effectiveInputOverOutputRatioRC = vec3(
${l[0]/c[0]},
${l[1]/c[1]},
${l[1]/c[1]});
const vec3 inputShapeRC = vec3(${r}.0, ${o}.0,
${o}.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 < ${a-1};
bool hasNextRow = coords.z < ${s-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 z2{constructor(e,t,s){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;const[,n,i]=t.shape,[,r,o]=e.shape,a=[s&&r>1?n-1:n,s&&o>1?i-1:i],l=[s&&r>1?r-1:r,s&&o>1?o-1:o],c=a[0]/l[0],p=a[1]/l[1],u=1/c,h=1/p,d=Math.ceil(u)*2+2,m=Math.ceil(h)*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(${c});
const float widthScale = float(${p});
const float invHeightScale = float(${u});
const float invWidthScale = float(${h});
const int winHeight = int(${d});
const int winWidth = int(${m});
// 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 >= ${r}) {
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 >= ${o}) {
continue;
}
float sourceFracRow =
float(${a[0]}) *
(float(dyR) / float(${l[0]}));
float sourceFracCol =
float(${a[1]}) *
(float(dyC) / float(${l[1]}));
int sourceNearestRow = int(min(
float(int(${n}) - 1),
${s} ? float(round(sourceFracRow)) :
float(floor(sourceFracRow))));
int sourceNearestCol = int(min(
float(int(${i}) - 1),
${s} ? float(round(sourceFracCol)) :
float(floor(sourceFracCol))));
if (r == sourceNearestRow && c == sourceNearestCol) {
accumulator += getDy(b, dyR, dyC, d);
}
}
}
// End loop over dy
setOutput(accumulator);
}
`}}class P2{constructor(e,t,s,n){this.variableNames=["A"],this.outputShape=[];const[i,r,o,a]=e;this.outputShape=[i,t,s,a];const l=[n&&t>1?r-1:r,n&&s>1?o-1:o],c=[n&&t>1?t-1:t,n&&s>1?s-1:s],p=n?"0.5":"0.0";this.userCode=`
const vec2 effectiveInputOverOutputRatioRC = vec2(
${l[0]/c[0]},
${l[1]/c[1]});
const vec2 inputShapeRC = vec2(${r}.0, ${o}.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 + ${p})));
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
setOutput(newValue);
}
`}}class B2{constructor(e,t){this.variableNames=["x"];const s=e.length;if(s>4)throw new Error(`WebGL backend: Reverse of rank-${s} tensor is not yet supported`);if(this.outputShape=e,s===1){this.userCode=`
void main() {
int coord = getOutputCoords();
setOutput(getX(${e[0]} - coord - 1));
}
`;return}const n=o=>t.indexOf(o)!==-1&&e[o]!==1?`${e[o]} - coords[${o}] - 1`:`coords[${o}]`,i=e.map((o,a)=>n(a)).join(","),r=Re(s);this.userCode=`
void main() {
${r} coords = getOutputCoords();
setOutput(getX(${i}));
}
`}}class j2{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const s=e.length;if(s>4)throw new Error(`WebGL backend: Reverse of rank-${s} tensor is not yet supported`);this.outputShape=e;const n=_t("rc",s),i=`${n[s-1]} + 1 < ${this.outputShape[s-1]}`,r=`${n[s-2]} + 1 < ${this.outputShape[s-2]}`,o=Re(s);s===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() {
${o} rc = getOutputCoords();
vec4 result = vec4(0.);
result.r = ${a(n.slice())};
if(${i}){
result.g = ${l(n.slice())};
}
if(${r}) {
result.b = ${c(n.slice())};
if(${i}) {
result.a = ${p(n.slice())};
}
}
setOutput(result);
}
`;function a(d){return u(d)}function l(d){return d[s-1]="("+d[s-1]+" + 1)",u(d)}function c(d){return d[s-2]="("+d[s-2]+" + 1)",u(d)}function p(d){return d[s-1]="("+d[s-1]+" + 1)",d[s-2]="("+d[s-2]+" + 1)",u(d)}function u(d){const m=e.map((y,w)=>h(w,d)),f=m.join(","),g=m.slice(-2).join(",");return`getChannel(getX(${f}), vec2(${g}))`}function h(d,m){return t.indexOf(d)!==-1&&e[d]!==1?`${e[d]} - ${m[d]} - 1`:`${m[d]}`}}}class ox{constructor(e,t,s,n,i,r,o=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=r;const a=Re(i.length),l=Re(r.length);let c="";s===1?c="i":s===2&&(c="i, j");const p=`getIndices(${c})`;let u="";n===1?u="i":n===2&&(u="i, coords[1]");const h=`getUpdates(${u})`,d=t>1?"strides[j]":"strides";this.userCode=`
${a} strides = ${a}(${i});
void main() {
${l} 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(${p});
flattenedIndex += index * ${d};
}
if (flattenedIndex == coords[0]) {
sum += ${h};
found = true;
}
}
setOutput(mix(getDefaultValue(), sum, float(found)));
}
`}}class V2{constructor(e,t){this.variableNames=["x","segmentIds"];const s=e.windowSize,n=e.batchSize,i=e.inSize,r=e.numSegments,o=r*Math.ceil(i/s);this.outputShape=[n,o];const a="0.0",l="sumValue",c=Math.floor(s/4)*4,p=s%4,u=`
sumValue += dot(values, segFilter);
`;let h="";i%s>0&&(h=`
if (inIdx < 0 || inIdx >= ${i}) {
return initializationValue;
}
`);let d="";i%s>0&&(d=`
if (inIdx < 0 || inIdx >= ${i}) {
return -1.0;
}
`),this.userCode=`
const float initializationValue = ${a};
float getValue(int batch, int inIdx) {
${h}
return getX(batch, inIdx);
}
float getSegmentIdAtIndex(int inIdx) {
${d}
return getSegmentIds(inIdx);
}
void main() {
ivec2 coords = getOutputCoords();
int batch = coords[0];
int outIdx = coords[1];
int inOffset = int(floor(float(outIdx) / float(
${r})) * float(${s}));
int currentSeg = int(mod(float(outIdx), float(${r})));
float sumValue = 0.0;
for (int i = 0; i < ${c}; 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
);
${u}
}
int inIdx = inOffset + ${c};
if (${p===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
);
${u}
} else if (${p===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
);
${u}
} else if (${p===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
);
${u}
}
setOutput(${l});
}
`}}class G2{constructor(e,t,s){this.variableNames=["c","a","b"],this.outputShape=t;let n,i;if(s>4)throw Error(`Where for rank ${s} is not yet supported`);if(s===1)i="resRC",n="resRC";else{const o=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],l=[];for(let c=0;c<t.length;c++)l.push(`${o[c]}`),c<e&&a.push(`${o[c]}`);n=a.join(),i=l.join()}const r=Re(s);this.userCode=`
void main() {
${r} resRC = getOutputCoords();
float cVal = getC(${n});
if (cVal >= 1.0) {
setOutput(getA(${i}));
} else {
setOutput(getB(${i}));
}
}
`}}class q2{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=Re(this.rank),s=`uniform int start[${this.rank}];`,n=J3(this.rank);let i;const r=e.map((o,a)=>`sourceLoc.${ax[a]} = start[${a}] + coords.${ax[a]};`);i=`
${t} sourceLoc;
${t} coords = getOutputCoords();
${r.join(`
`)}
`,this.userCode=`
${s}
void main() {
${i}
setOutput(getSource(${n}));
}
`}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,s)=>{if(this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(s,"start"),this.startLoc==null))return;t.gl.uniform1iv(this.startLoc,e)}}}const ax=["x","y","z","w","u","v"];function J3(e){if(e===1)return"sourceLoc";if(e<=6)return ax.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}class H2{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;const t=Re(this.rank),s=_t("coords",this.rank),n=_t("sourceLoc",this.rank),i=this.rank===1?"sourceLoc":`vec2(${n.slice(-2).join()})`,r=`getChannel(getSource(${n.join()}), ${i})`,o=`
result.x = ${r};
if (++${s[this.rank-1]} < ${e[this.rank-1]}) {
++${n[this.rank-1]};
result.y = ${r};
--${n[this.rank-1]};
}
`,a=this.rank===1?"":`
--${s[this.rank-1]};
if (++${s[this.rank-2]} < ${e[this.rank-2]}) {
++${n[this.rank-2]};
result.z = ${r};
if (++${s[this.rank-1]} < ${e[this.rank-1]}) {
++${n[this.rank-1]};
result.w = ${r};
}
}
`,l=this.rank<=4?`sourceLoc = coords +
${t}(${e.map((c,p)=>`start[${p}]`).join()});`:e.map((c,p)=>`${n[p]} = ${s[p]} + start[${p}];`).join(`
`);this.userCode=`
uniform int start[${this.rank}];
void main() {
${t} coords = getOutputCoords();
${t} sourceLoc;
${l}
vec4 result = vec4(0.);
${o}
${a}
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,s)=>{if(this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(s,"start"),this.startLoc==null))return;t.gl.uniform1iv(this.startLoc,e)}}}class Y2{constructor(e,t,s){this.variableNames=["x"],this.outputShape=s;const n=s.length,i=Re(s.length),r=Re(s.length);let o="";if(n===1)o="coords * strides + begin";else{let a=0;o=s.map((l,c)=>(a++,s.length===1?`coords * strides[${c}] + begin[${c}]`:`coords[${a-1}] * strides[${c}] + begin[${c}]`)).join(",")}this.userCode=`
${i} begin = ${i}(${e});
${i} strides = ${i}(${t});
void main() {
${r} coords = getOutputCoords();
setOutput(getX(${o}));
}
`}}class Z2{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,s){const n=X2(t,s),i=J2(e,n,s);i in this.freeTextures||(this.freeTextures[i]=[]),i in this.usedTextures||(this.usedTextures[i]=[]);const r=K2(e,n,this.gpgpu.gl,this.gpgpu.textureConfig,s);if(this.freeTextures[i].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=r,this.log();const a=this.freeTextures[i].shift();return this.usedTextures[i].push(a),a}let o;return n===Xt.PACKED_2X2_FLOAT32?o=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):n===Xt.PACKED_2X2_FLOAT16?o=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):n===Xt.UNPACKED_FLOAT32?o=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):n===Xt.UNPACKED_FLOAT16?o=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):n===Xt.PACKED_4X1_UNSIGNED_BYTE&&(o=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[i].push(o),this.numUsedTextures++,this._numBytesAllocated+=r,this.log(),o}releaseTexture(e,t,s,n){if(this.freeTextures==null)return;const i=X2(s,n),r=J2(t,i,n);r in this.freeTextures||(this.freeTextures[r]=[]);const o=K2(t,i,this.gpgpu.gl,this.gpgpu.textureConfig,n),a=W().get("WEBGL_DELETE_TEXTURE_THRESHOLD");a!==-1&&this._numBytesAllocated>a?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=o):(this.freeTextures[r].push(e),this.numFreeTextures++,this._numBytesFree+=o),this.numUsedTextures--;const l=this.usedTextures[r],c=l.indexOf(e);if(c<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l.splice(c,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 Z3(e,t){const s=e;if(t===s.R32F)return 4;if(t===s.R16F)return 2;if(t===s.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===s.RGBA16F)return 8;throw new Error(`Unknown internal format ${t}`)}function K2(e,t,s,n,i){const r=Q3(t,n);let o;if(i){const[l,c]=gi(e[0],e[1]);o=l*c}else{const[l,c]=pa(e[0],e[1]);o=l*c}const a=Z3(s,r);return o*a}function Q3(e,t){switch(e){case Xt.PACKED_2X2_FLOAT32:return nx(t);case Xt.PACKED_2X2_FLOAT16:return ix(t);case Xt.UNPACKED_FLOAT32:return ex(t);case Xt.UNPACKED_FLOAT16:return tx(t);case Xt.PACKED_4X1_UNSIGNED_BYTE:return sx(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function eV(e){return W().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Xt.PACKED_2X2_FLOAT32:Xt.UNPACKED_FLOAT32:e?Xt.PACKED_2X2_FLOAT16:Xt.UNPACKED_FLOAT16}function X2(e,t){if(e===ns.UPLOAD)return Xt.PACKED_2X2_FLOAT32;if(e===ns.RENDER||e==null)return eV(t);if(e===ns.DOWNLOAD||e===ns.PIXELS)return Xt.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function J2(e,t,s){return`${e[0]}_${e[1]}_${t}_${s}`}class Q2{constructor(e,t){this.variableNames=["A"];const s=new Array(e.length);for(let r=0;r<s.length;r++)s[r]=e[r]*t[r];this.outputShape=s,this.rank=s.length;const n=Re(this.rank),i=tV(e);this.userCode=`
void main() {
${n} resRC = getOutputCoords();
setOutput(getA(${i}));
}
`}}function tV(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 s=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],n=[];for(let i=0;i<e.length;i++)n.push(`imod(${s[i]}, ${e[i]})`);return n.join()}class $e{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 Xi="if (isnan(x)) return x;",eO="return x;",lx="return abs(x);",cx=Xi+`
return (x < 0.0) ? 0.0 : x;
`,px=Xi+`
return (x < 0.0) ? 0.0 : min(6.0, x);
`,ux="return (x >= 0.0) ? x : (exp(x) - 1.0);",tO=`
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
// see: https://arxiv.org/abs/1706.02515
float scaleAlpha = ${U.SELU_SCALEALPHA};
float scale = ${U.SELU_SCALE};
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
`;function sO(e=0){return Xi+`
return x > 0.0 ? 1.0 : float(${e});
`}const hx="return -x;",dx="return ceil(x);",mx="return floor(x);",nO=`
if (isnan(x)) { return 0.0; }
return sign(x);
`,iO="return float(isnan(x));",rO="return float(isinf(x));",oO="return float(!isnan(x) && !isinf(x));",aO=`
// 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;
}
}
`,fx="return exp(x);",gx="return exp(x) - 1.0;",lO=`if (x < 0.0) return NAN;
return log(x);`,cO="return log(1.0 + x);",pO="return sqrt(x);",uO="return inversesqrt(x);",hO="return 1.0 / (1.0 + exp(-1.0 * x));",dO=`
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;
`,mO=Xi+`
if (abs(x) > 1.) {
return NAN;
}
return asin(x);
`,fO=Xi+`
if (abs(x) > 1.) {
return NAN;
}
return acos(x);
`,gO=Xi+`
return atan(x);
`,yO=`
float e2x = exp(x);
return (e2x - 1.0 / e2x) / 2.0;
`,bO=`
float e2x = exp(-x);
return (e2x + 1.0 / e2x) / 2.0;
`,wO=`
float e2x = exp(-2.0 * abs(x));
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
`,xO=Xi+"return log(x + sqrt(x * x + 1.0));",LO=Xi+`
if (x < 1.0) return NAN;
return log(x + sqrt(x * x - 1.0));`,SO=Xi+`
if ((x < -1.0) || (x > 1.0)) return NAN;
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,IO=`
// Error function is calculated approximately with elementary function.
// See "Handbook of Mathematical Functions with Formulas,
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
float p = ${U.ERF_P};
float a1 = ${U.ERF_A1};
float a2 = ${U.ERF_A2};
float a3 = ${U.ERF_A3};
float a4 = ${U.ERF_A4};
float a5 = ${U.ERF_A5};
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));
`,vO="return 1.0 / x;",TO="return float(!(x >= 1.0));",AO="return float(int(x));",xu="return x;";const NO="return x;",CO=`
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;
`,yx=`
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;
`,bx=`
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;
`,wx=`
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 ql{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 RO{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;const t=e.length,s=_t("rc",t),n=Re(t),i=J0(t,s),r=s.slice(-2),o=t<=1?"rc":`vec2(${r.join(",")})`;this.userCode=`
void main() {
${n} rc = getOutputCoords();
vec4 packedInput = getA(${i});
setOutput(getChannel(packedInput, ${o}));
}
`}}const{segment_util:OO}=U,sV=vt.split,nV=vt.tile,iV=vt.topkImpl,rV=vt.whereImpl,oV=1e-7,aV=1e-4,Ef={};function lV(e){return e in Ef||(Ef[e]={}),Ef[e]}function _f(e,t=!1){if(e==="linear")return t?NO:eO;if(e==="relu")return t?yx:cx;if(e==="elu")return t?wx:ux;if(e==="relu6")return t?bx:px;if(e==="prelu")return t?Hw:qw;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}const cV=128,pV=600;function uV(){return W().global.screen==null?1024:W().global.screen.height*W().global.screen.width*window.devicePixelRatio*pV/1024/1024}const EO=1e3;class xx extends go{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,!W().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){const t=nn(W().getNumber("WEBGL_VERSION"));this.binaryCache=lV(W().getNumber("WEBGL_VERSION")),this.gpgpu=new rx(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 Z2(this.gpgpu),this.numMBBeforeWarning=uV(),this.texData=new gc(this,Ms())}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(e,t,s){if((W().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||W().getBool("DEBUG"))&&this.checkNumericalProblems(e),s==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const n={};return this.texData.set(n,{shape:t,dtype:s,values:e,usage:ns.UPLOAD,refCount:1}),n}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,s,n){if(W().getBool("DEBUG")&&this.checkNumericalProblems(t),n==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:s,dtype:n,values:t,usage:ns.UPLOAD,refCount:1})}disposeIntermediateTensorInfo(e){const t=e.dataId;if(this.texData.has(t)){const s=this.texData.get(t);s.refCount--,s.refCount<1&&this.disposeData(t)}}readSync(e){const t=this.texData.get(e),{values:s,dtype:n,complexTensors:i,slice:r,shape:o,isPacked:a}=t;if(r!=null){let u;a?u=new ql(o,xu):u=new $e(o,xu);const h=this.runWebGLProgram(u,[{dataId:e,shape:o,dtype:n}],n),d=this.readSync(h.dataId);return this.disposeIntermediateTensorInfo(h),d}if(s!=null)return this.convertAndCacheOnCPU(e);if(n==="string")return s;const l=this.activeTimers!=null;let c;l&&(c=N.now());let p;if(n==="complex64"){const u=i.real.dataSync(),h=i.imag.dataSync();p=U.mergeRealAndImagArrays(u,h)}else p=this.getValuesFromTexture(e);return l&&(this.downloadWaitMs+=N.now()-c),this.convertAndCacheOnCPU(e,p)}async read(e){if(this.pendingRead.has(e)){const d=this.pendingRead.get(e);return new Promise(m=>d.push(m))}const t=this.texData.get(e),{values:s,shape:n,slice:i,dtype:r,complexTensors:o,isPacked:a}=t;if(i!=null){let d;a?d=new ql(n,xu):d=new $e(n,xu);const m=this.runWebGLProgram(d,[{dataId:e,shape:n,dtype:r}],r),f=this.read(m.dataId);return this.disposeIntermediateTensorInfo(m),f}if(s!=null)return this.convertAndCacheOnCPU(e);if(!W().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&W().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let l=null,c;if(r!=="complex64"&&W().get("WEBGL_BUFFER_SUPPORTED")){c=this.decode(e);const d=this.texData.get(c.dataId);l=this.gpgpu.createBufferFromTexture(d.texture,...co(n))}this.pendingRead.set(e,[]),r!=="complex64"&&await this.gpgpu.createAndWaitForFence();let p;if(r==="complex64"){const d=await Promise.all([o.real.data(),o.imag.data()]),m=d[0],f=d[1];p=U.mergeRealAndImagArrays(m,f)}else if(l==null)p=this.getValuesFromTexture(e);else{const d=N.sizeFromShape(n);p=this.gpgpu.downloadFloat32MatrixFromBuffer(l,d)}c!=null&&this.disposeIntermediateTensorInfo(c);const u=this.convertAndCacheOnCPU(e,p),h=this.pendingRead.get(e);return this.pendingRead.delete(e),h.forEach(d=>d(u)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e),this.pendingDeletes--),u}checkNumericalProblems(e){if(e==null)return;for(let t=0;t<e.length;t++){const s=e[t];if(!f0(s))throw W().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")?Error(`The value ${s} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`):Error(`The value ${s} cannot be represented on this device.`)}}getValuesFromTexture(e){const{shape:t,dtype:s,isPacked:n}=this.texData.get(e),i=N.sizeFromShape(t);if(W().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){const u=this.decode(e),h=this.texData.get(u.dataId),d=this.gpgpu.downloadMatrixFromPackedTexture(h.texture,...co(t)).subarray(0,i);return this.disposeIntermediateTensorInfo(u),d}const r=W().getBool("WEBGL_PACK")&&n===!0,o=r?wf(t):t,a=r?new e2(o):new QR(o),l=this.runWebGLProgram(a,[{shape:o,dtype:s,dataId:e}],"float32"),c=this.texData.get(l.dataId),p=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(c.texture,c.texShape[0],c.texShape[1]).subarray(0,i);return this.disposeIntermediateTensorInfo(l),p}async time(e){const t=this.activeTimers,s=[];let n=!1;this.programTimersStack==null?(this.programTimersStack=s,n=!0):this.activeTimers.push(s),this.activeTimers=s,e();const i=N.flatten(this.activeTimers.map(a=>a.query)).filter(a=>a!=null),r=N.flatten(this.activeTimers.map(a=>a.name)).filter(a=>a!=null);this.activeTimers=t,n&&(this.programTimersStack=null);const o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};if(W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const a=await Promise.all(i);o.kernelMs=N.sum(a),o.getExtraProfileInfo=()=>a.map((l,c)=>({name:r[c],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", ")}else o.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,o}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:N.now(),endMs:null}}endTimer(e){return W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=N.now(),e)}async getQueryTime(e){if(W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);const t=e;return t.endMs-t.startMs}disposeData(e){if(this.pendingDisposal.has(e))return;if(this.pendingRead.has(e)){this.pendingDisposal.add(e),this.pendingDeletes++;return}if(!this.texData.has(e))return;this.releaseGPUData(e);const{complexTensors:t}=this.texData.get(e);t!=null&&(t.real.dispose(),t.imag.dispose()),this.texData.delete(e)}releaseGPUData(e){const{texture:t,dtype:s,texShape:n,usage:i,isPacked:r,slice:o}=this.texData.get(e),a=o&&o.origDataId||e,l=this.dataRefCount.get(a);l>1?this.dataRefCount.set(a,l-1):(this.dataRefCount.delete(a),t!=null&&(this.numBytesInGPU-=this.computeBytes(n,s),this.textureManager.releaseTexture(t,n,i,r)));const c=this.texData.get(e);c.texture=null,c.texShape=null,c.isPacked=!1,c.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture}getDataInfo(e){return this.texData.get(e)}getCPUBackend(){return W().getBool("WEBGL_CPU_FORWARD")?(this.cpuBackend==null&&(this.cpuBackend=Ms().findBackend("cpu")),this.cpuBackend):null}shouldExecuteOnCPU(e,t=cV){const s=this.getCPUBackend();return!this.warnedAboutCPUBackend&&s==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),s!=null&&e.every(n=>this.texData.get(n.dataId).texture==null&&N.sizeFromShape(n.shape)<t)}getGPGPUContext(){return this.gpgpu}complex(e,t){const s=this.makeOutput(e.shape,"complex64"),n=this.texData.get(s.dataId);return n.complexTensors={real:Ms().keep(e.clone()),imag:Ms().keep(t.clone())},s}real(e){const t=this.texData.get(e.dataId);return t.complexTensors.real.clone()}imag(e){const t=this.texData.get(e.dataId);return t.complexTensors.imag.clone()}slice(e,t,s){if(this.shouldExecuteOnCPU([e])){const r=G0(this.texData.get(e.dataId).values,t,s,e.shape,e.dtype);return this.makeOutput(s,e.dtype,r)}if(N.sizeFromShape(s)===0)return ze([],s,e.dtype);const{isPacked:n}=this.texData.get(e.dataId),i=Fs.isSliceContinous(e.shape,t,s);if(n||!i){const r=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new H2(s):new q2(s),o=r.getCustomSetupFunc(t);return this.compileAndRun(r,[e],null,o)}return this.uploadToGPU(e.dataId),this.shallowSlice(e,t,s)}shallowSlice(e,t,s){const n=this.texData.get(e.dataId),i=this.makeOutput(s,e.dtype),r=this.texData.get(i.dataId);Object.assign(r,n),r.shape=s,r.dtype=e.dtype;let o=Fs.computeFlatOffset(t,e.strides);n.slice&&(o+=n.slice.flatOffset),r.slice={flatOffset:o,origDataId:n.slice&&n.slice.origDataId||e.dataId};const a=this.dataRefCount.get(r.slice.origDataId)||1;return this.dataRefCount.set(r.slice.origDataId,a+1),i}stridedSlice(e,t,s,n){const i=this.tryRunOnCpuOrThrow([e],()=>this.cpuBackend.stridedSlice(e,t,s,n));if(i)return i;const r=Fs.computeOutShape(t,s,n);if(r.some(a=>a===0))return ze([],r);const o=new Y2(t,n,r);return this.compileAndRun(o,[e])}reverse(e,t){const s=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new j2(e.shape,t):new B2(e.shape,t);return this.compileAndRun(s,[e])}concat(e,t){if(e[0].dtype==="complex64"){const o=e.map(l=>Xs(l)),a=e.map(l=>dn(l));return Gt(this.concat(o,t),this.concat(a,t))}if(e.length===1)return e[0];if(e.length>W().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const o=Math.floor(e.length/2),a=this.concat(e.slice(0,o),t),l=this.concat(e.slice(o),t);return this.concat([a,l],t)}if(W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].rank>1){const o=new $R(e.map(a=>a.shape),t);return this.compileAndRun(o,e)}const s=U.computeOutShape(e.map(o=>o.shape),t),n=e.map(o=>o.as2D(-1,N.sizeFromShape(o.shape.slice(t)))),i=new UR(n.map(o=>o.shape)),r=this.compileAndRun(i,n);return r.reshape(s)}neg(e){const t=this.tryRunOnCpuOrThrow([e],()=>this.cpuBackend.neg(e));if(t)return t;if(W().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,hx,e.dtype);const s=new $e(e.shape,hx);return this.compileAndRun(s,[e])}batchMatMul(e,t,s,n){const i=s?e.shape[2]:e.shape[1],r=n?t.shape[1]:t.shape[2],o=s?e.shape[1]:e.shape[2],[a,,]=e.shape;if((i===1||r===1)&&o>EO){s&&(e=se(e,[0,2,1])),n&&(t=se(t,[0,2,1]));const p=r===1?e:e.as3D(a,o,1),u=r===1?2:1,h=r===1?t.as3D(a,1,o):t;return this.multiply(p,h).sum(u,!0)}const l=Ft(e.dtype,t.dtype),c=new Nf(e.shape,[a,i,r],s,n);return this.compileAndRun(c,[e,t],l)}fusedBatchMatMul({a:e,b:t,transposeA:s,transposeB:n,bias:i,activation:r,preluActivationWeights:o}){const a=s?e.shape[2]:e.shape[1],l=n?t.shape[1]:t.shape[2],[c,,]=e.shape,p=Ft(e.dtype,t.dtype),u=i!=null,h=o!=null,d=r?_f(r,!0):null,m=new Nf(e.shape,[c,a,l],s,n,u,d,h),f=[e,t];return i&&f.push(i),o&&f.push(o),this.compileAndRun(m,f,p)}multiply(e,t){if(e.dtype==="complex64"){const i=this.texData.get(e.dataId),r=this.texData.get(t.dataId),o=new Vw(jw.REAL,e.shape,t.shape),a=new Vw(jw.IMAG,e.shape,t.shape),l=[this.makeComplexComponentTensorInfo(e,i.complexTensors.real),this.makeComplexComponentTensorInfo(e,i.complexTensors.imag),this.makeComplexComponentTensorInfo(t,r.complexTensors.real),this.makeComplexComponentTensorInfo(t,r.complexTensors.imag)],c=this.compileAndRun(o,l),p=this.compileAndRun(a,l),u=this.complex(c,p);return c.dispose(),p.dispose(),u}const s=Ft(e.dtype,t.dtype);if(this.shouldExecuteOnCPU([e,t])){const i=this.texData.get(e.dataId),r=this.texData.get(t.dataId),[o,a]=j0(e.shape,t.shape,i.values,r.values,s);return this.makeOutput(a,s,o)}if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,Gw,e.dtype);const n=new kt(Gw,e.shape,t.shape);return this.compileAndRun(n,[e,t],e.dtype)}localResponseNormalization4D(e,t,s,n,i){const r=W().getBool("WEBGL_PACK_NORMALIZATION")?new R2(e.shape,t,s,n,i):new N2(e.shape,t,s,n,i);return this.compileAndRun(r,[e])}LRNGrad(e,t,s,n,i,r,o){const a=new C2(t.shape,n,i,r,o);return this.compileAndRun(a,[t,s,e])}tile(e,t){if(e.dtype==="string"){const n=this.readSync(e.dataId),i=n.map(o=>N.decodeString(o)),r=ge(e.shape,e.dtype,i);return nV(r,t)}const s=new Q2(e.shape,t);return this.compileAndRun(s,[e])}pad(e,t,s){const n=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new M2(e.shape,t,s):new F2(e.shape,t,s);return this.compileAndRun(n,[e])}gather(e,t,s){const n=this.tryRunOnCpuOrThrow([e,t],()=>this.cpuBackend.gather(e,t,s));if(n)return n;const i=new i2(e.shape,t.size,s);return this.compileAndRun(i,[e,t])}batchToSpaceND(e,t,s){N.assert(e.rank<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");const n=t.reduce((c,p)=>c*p),i=U.getReshaped(e.shape,t,n),r=U.getPermuted(i.length,t.length),o=U.getReshapedPermuted(e.shape,t,n),a=U.getSliceBeginCoords(s,t.length),l=U.getSliceSize(o,s,t.length);return se(e.reshape(i),r).reshape(o).slice(a,l)}spaceToBatchND(e,t,s){N.assert(e.rank<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");const n=t.reduce((p,u)=>p*u),i=[[0,0]];i.push(...s);for(let p=1+t.length;p<e.shape.length;++p)i.push([0,0]);const r=e.pad(i),o=U.getReshaped(r.shape,t,n,!1),a=U.getPermuted(o.length,t.length,!1),l=U.getReshapedPermuted(r.shape,t,n,!1),c=se(r.reshape(o),a);return O(c,l)}reduce(e,t,s){const n=e.shape[0],i=e.shape[1],r=U.computeOptimalWindowSize(i),o=Math.ceil(i/r),a={windowSize:r,inSize:i,batchSize:n,outSize:o},l=new Rf(a,t),c=this.compileAndRun(l,[e],s);return c.shape[1]===1?c:this.reduce(c,t,s)}argReduce(e,t,s=null){let n=e.shape[0],i=e.shape[1];s!=null&&(n=s.shape[0],i=s.shape[1]);const r=U.computeOptimalWindowSize(i),o={windowSize:r,inSize:i,batchSize:n,outSize:Math.ceil(i/r)},a=new X0(o,t,s==null),l=[e];s!=null&&l.push(s);const c=this.compileAndRun(a,l,"int32");return c.shape[1]===1?c:this.argReduce(e,t,c)}argReducePacked(e,t,s=null){const n=s!=null?s.shape:e.shape,i=n[n.length-1],r=U.computeOptimalWindowSize(i),o=new sR(n,r,t,s==null),a=s==null?[e]:[e,s],l=this.compileAndRun(o,a,"int32");return l.rank===e.rank?this.argReducePacked(e,t,l):l}sum(e,t){U.assertAxesAreInnerMostDims("sum",t,e.rank);const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=N.sizeFromShape(n),r=e.as2D(-1,i),o=yp(e.dtype);return this.reduce(r,"sum",o).reshape(s)}prod(e,t){const s=this.tryRunOnCpuOrThrow([e],()=>this.cpuBackend.prod(e,t));if(s)return s;const[n,i]=U.computeOutAndReduceShapes(e.shape,t),r=N.sizeFromShape(i),o=e.as2D(-1,r),a=yp(e.dtype);return this.reduce(o,"prod",a).reshape(n)}unsortedSegmentSum(e,t,s){let n=0;const i=U.getAxesPermutation([n],e.rank);let r=e;i!=null&&(r=se(e,i),n=U.getInnerMostAxes(1,e.rank)[0]);const o=OO.computeOutShape(r.shape,n,s),a=N.sizeFromShape([r.shape[n]]),l=r.as2D(-1,a),c=yp(e.dtype);let p=this.segOpCompute(l,"unsortedSegmentSum",t,c,s).reshape(o);return i!=null&&(p=se(p,U.getUndoAxesPermutation(i))),p}segOpCompute(e,t,s,n,i){const r=e.shape[0],o=e.shape[1],a=OO.segOpComputeOptimalWindowSize(o,i),l={windowSize:a,inSize:o,batchSize:r,numSegments:i},c=new V2(l,t),p=this.compileAndRun(c,[e,s],n);return p.shape[1]===i?p:(s=Fi(0,i).tile([o/a]),this.segOpCompute(p,t,s,n,i))}argMinMaxReduce(e,t,s){const n=[t];if(U.assertAxesAreInnerMostDims("arg"+s.charAt(0).toUpperCase()+s.slice(1),n,e.rank),!W().getBool("WEBGL_PACK_REDUCE")||e.rank<=2){const[i,r]=U.computeOutAndReduceShapes(e.shape,n),o=N.sizeFromShape(r),a=e.as2D(-1,o);return this.argReduce(a,s).reshape(i)}return this.argReducePacked(e,s)}argMin(e,t){return this.argMinMaxReduce(e,t,"min")}argMax(e,t){return this.argMinMaxReduce(e,t,"max")}cumsum(e,t,s,n){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 r=e;for(let o=0;o<=Math.ceil(Math.log2(i))-1;o++){const a=new Jw(e.shape,!1,n),l=a.getCustomSetupFunc(o),c=r;r=this.compileAndRun(a,[r],r.dtype,l),c.dispose()}if(s){const o=new Jw(e.shape,s,n),a=r;r=this.compileAndRun(o,[r]),a.dispose()}return r}equal(e,t){if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,IR,"bool");const s=new kt(lR,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}notEqual(e,t){if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,vR,"bool");const s=new kt(cR,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}less(e,t){const s=this.tryRunOnCpuOrThrow([e,t],()=>this.cpuBackend.less(e,t));if(s)return s;if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,TR,"bool");const n=new kt(pR,e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")}lessEqual(e,t){if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,AR,"bool");const s=new kt(uR,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}greater(e,t){const s=this.tryRunOnCpuOrThrow([e,t],()=>this.cpuBackend.greater(e,t));if(s)return s;if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,NR,"bool");const n=new kt(hR,e.shape,t.shape);return this.compileAndRun(n,[e,t],"bool")}greaterEqual(e,t){if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,CR,"bool");const s=new kt(dR,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}logicalNot(e){const t=new $e(e.shape,TO);return this.compileAndRun(t,[e])}logicalAnd(e,t){if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,RR,"bool");const s=new kt(mR,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}logicalOr(e,t){if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,OR,"bool");const s=new kt(fR,e.shape,t.shape);return this.compileAndRun(s,[e,t],"bool")}select(e,t,s){const n=new G2(e.rank,t.shape,t.rank);return this.compileAndRun(n,[e,t,s],Ft(t.dtype,s.dtype))}where(e){U.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");const t=e.dataSync();return rV(e.shape,t)}topk(e,t,s){const n=e.dataSync();return iV(n,e.shape,e.dtype,t,s)}min(e,t){U.assertAxesAreInnerMostDims("min",t,e.rank);const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=N.sizeFromShape(n),r=e.as2D(-1,i);return this.reduce(r,"min",r.dtype).reshape(s)}minimum(e,t){const s=this.tryRunOnCpuOrThrow([e,t],()=>this.cpuBackend.minimum(e,t));if(s)return s;const n=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new bi(_R,e.shape,t.shape):new kt(yR,e.shape,t.shape);return this.compileAndRun(n,[e,t])}mod(e,t){const s=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new bi(kR,e.shape,t.shape):new kt(bR,e.shape,t.shape);return this.compileAndRun(s,[e,t])}maximum(e,t){const s=this.tryRunOnCpuOrThrow([e,t],()=>this.cpuBackend.maximum(e,t));if(s)return s;const n=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new bi(ER,e.shape,t.shape):new kt(gR,e.shape,t.shape);return this.compileAndRun(n,[e,t])}all(e,t){U.assertAxesAreInnerMostDims("all",t,e.rank);const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=N.sizeFromShape(n),r=e.as2D(-1,i);return this.reduce(r,"all",r.dtype).reshape(s)}any(e,t){U.assertAxesAreInnerMostDims("any",t,e.rank);const[s,n]=U.computeOutAndReduceShapes(e.shape,t),i=N.sizeFromShape(n),r=e.as2D(-1,i);return this.reduce(r,"any",r.dtype).reshape(s)}floorDiv(e,t){const s=oR,n="int32";if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,xR,n);const i=new kt(s,e.shape,t.shape);return this.compileAndRun(i,[e,t],n)}add(e,t){if(e.dtype==="complex64"&&t.dtype==="complex64")return this.complexSeparableBinaryOp(e,t,If);const s=Ft(e.dtype,t.dtype);if(this.shouldExecuteOnCPU([e,t])){const i=this.texData.get(e.dataId),r=this.texData.get(t.dataId),[o,a]=M0(e.shape,t.shape,i.values,r.values,s);return this.makeOutput(a,s,o)}if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,If,s);const n=new kt(If,e.shape,t.shape);return this.compileAndRun(n,[e,t],s)}packedUnaryOp(e,t,s){const n=new ql(e.shape,t);return this.compileAndRun(n,[e],s)}packedBinaryOp(e,t,s,n,i=!1){const r=new bi(s,e.shape,t.shape,i);return this.compileAndRun(r,[e,t],n)}complexSeparableBinaryOp(e,t,s){const n=this.texData.get(e.dataId),i=this.texData.get(t.dataId),[r,o]=[[n.complexTensors.real,i.complexTensors.real],[n.complexTensors.imag,i.complexTensors.imag]].map(l=>{const[c,p]=l,u=this.makeComplexComponentTensorInfo(e,c),h=this.makeComplexComponentTensorInfo(t,p),d=new kt(s,e.shape,t.shape);return this.compileAndRun(d,[u,h],Ft(c.dtype,p.dtype))}),a=this.complex(r,o);return r.dispose(),o.dispose(),a}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>W().get("WEBGL_MAX_TEXTURES_IN_SHADER")){const r=Math.floor(e.length/2),o=this.addN(e.slice(0,r)),a=this.addN(e.slice(r));return this.addN([o,a])}const t=e.map(r=>r.dtype).reduce((r,o)=>Ft(r,o)),s=e.map(r=>r.shape),n=W().getBool("WEBGL_PACK"),i=n?new K0(e[0].shape,s):new Y0(e[0].shape,s);return this.compileAndRun(i,e,t)}subtract(e,t){if(e.dtype==="complex64"&&t.dtype==="complex64")return this.complexSeparableBinaryOp(e,t,vf);const s=Ft(e.dtype,t.dtype);if(this.shouldExecuteOnCPU([e,t])){const i=this.texData.get(e.dataId),r=this.texData.get(t.dataId),[o,a]=q0(e.shape,t.shape,i.values,r.values,s);return this.makeOutput(a,s,o)}if(W().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(e,t,vf,e.dtype);const n=new kt(vf,e.shape,t.shape);return this.compileAndRun(n,[e,t],s)}pow(e,t){const s=W().getBool("WEBGL_PACK_BINARY_OPERATIONS"),n=s?new bi(LR,e.shape,t.shape):new kt(aR,e.shape,t.shape),i=Ft(e.dtype,t.dtype);return this.compileAndRun(n,[e,t],i)}ceil(e){if(this.shouldExecuteOnCPU([e])){const s=U0(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,s)}if(W().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,dx,e.dtype);const t=new $e(e.shape,dx);return this.compileAndRun(t,[e])}floor(e){if(this.shouldExecuteOnCPU([e])){const s=z0(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,s)}if(W().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,mx,e.dtype);const t=new $e(e.shape,mx);return this.compileAndRun(t,[e])}sign(e){const t=new $e(e.shape,nO);return this.compileAndRun(t,[e])}isNaN(e){const t=new $e(e.shape,iO);return this.compileAndRun(t,[e],"bool")}isInf(e){const t=new $e(e.shape,rO);return this.compileAndRun(t,[e],"bool")}isFinite(e){const t=new $e(e.shape,oO);return this.compileAndRun(t,[e],"bool")}round(e){const t=new $e(e.shape,aO);return this.compileAndRun(t,[e])}exp(e){if(this.shouldExecuteOnCPU([e])){const s=$0(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,s)}if(W().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,fx,e.dtype);const t=new $e(e.shape,fx);return this.compileAndRun(t,[e])}expm1(e){if(this.shouldExecuteOnCPU([e])){const s=W0(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,s)}if(W().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,gx,e.dtype);const t=new $e(e.shape,gx);return this.compileAndRun(t,[e])}softmax(e,t){const s=N.parseAxisParam([t],e.shape),n=xt(e,s),i=U.expandShapeToKeepDim(n.shape,s),r=this.subtract(e,n.reshape(i)),o=this.exp(r),a=this.sum(o,s).reshape(i);return Z(o,a)}log(e){if(this.shouldExecuteOnCPU([e])){const s=P0(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,s)}if(W().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,CO,e.dtype);const t=new $e(e.shape,lO);return this.compileAndRun(t,[e])}log1p(e){const t=new $e(e.shape,cO);return this.compileAndRun(t,[e])}sqrt(e){const t=new $e(e.shape,pO);return this.compileAndRun(t,[e])}rsqrt(e){if(this.shouldExecuteOnCPU([e])){const s=V0(this.texData.get(e.dataId).values,e.dtype);return this.makeOutput(e.shape,e.dtype,s)}const t=new $e(e.shape,uO);return this.compileAndRun(t,[e])}reciprocal(e){const t=new $e(e.shape,vO);return this.compileAndRun(t,[e])}relu(e){let t;return W().getBool("WEBGL_PACK")?t=new ql(e.shape,yx):t=new $e(e.shape,cx),this.compileAndRun(t,[e])}relu6(e){let t;return W().getBool("WEBGL_PACK")?t=new ql(e.shape,bx):t=new $e(e.shape,px),this.compileAndRun(t,[e])}prelu(e,t){const s=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new bi(Hw,e.shape,t.shape):new kt(qw,e.shape,t.shape);return this.compileAndRun(s,[e,t])}elu(e){if(W().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,wx,e.dtype);const t=new $e(e.shape,ux);return this.compileAndRun(t,[e])}eluDer(e,t){const s=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new bi(SR,e.shape,t.shape):new kt(wR,e.shape,t.shape);return this.compileAndRun(s,[e,t])}selu(e){const t=new $e(e.shape,tO);return this.compileAndRun(t,[e])}int(e){const t=new $e(e.shape,AO);return this.compileAndRun(t,[e],"int32")}clip(e,t,s){let n;W().getBool("WEBGL_PACK_CLIP")?n=new FR(e.shape):n=new DR(e.shape);const i=n.getCustomSetupFunc(t,s);return this.compileAndRun(n,[e],null,i)}abs(e){if(this.shouldExecuteOnCPU([e])&&e.dtype!=="complex64"){const s=F0(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,s)}if(W().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,lx,e.dtype);const t=new $e(e.shape,lx);return this.compileAndRun(t,[e])}complexAbs(e){const t=this.texData.get(e.dataId),s=new MR(e.shape),n=[this.makeComplexComponentTensorInfo(e,t.complexTensors.real),this.makeComplexComponentTensorInfo(e,t.complexTensors.imag)];return this.compileAndRun(s,n)}sigmoid(e){const t=new $e(e.shape,hO);return this.compileAndRun(t,[e])}softplus(e){const t=new $e(e.shape,dO);return this.compileAndRun(t,[e])}asin(e){const t=new $e(e.shape,mO);return this.compileAndRun(t,[e])}acos(e){const t=new $e(e.shape,fO);return this.compileAndRun(t,[e])}atan(e){const t=new $e(e.shape,gO);return this.compileAndRun(t,[e])}sinh(e){const t=new $e(e.shape,yO);return this.compileAndRun(t,[e])}cosh(e){const t=new $e(e.shape,bO);return this.compileAndRun(t,[e])}tanh(e){const t=new $e(e.shape,wO);return this.compileAndRun(t,[e])}asinh(e){const t=new $e(e.shape,xO);return this.compileAndRun(t,[e])}acosh(e){const t=new $e(e.shape,LO);return this.compileAndRun(t,[e])}atanh(e){const t=new $e(e.shape,SO);return this.compileAndRun(t,[e])}erf(e){const t=new $e(e.shape,IO);return this.compileAndRun(t,[e])}step(e,t){const s=new $e(e.shape,sO(t));return this.compileAndRun(s,[e])}conv2dByMatMul(e,t,s,n,i,r){const o=e.shape,a=this.texData.get(e.dataId),l=s.inChannels,c=o[0]*o[1]*o[2],p=s.outChannels,u=s.dataFormat==="channelsLast",h=!1,d=!1,m=(c===1||p===1)&&l>EO,f=o[2]%2!==0&&!!a.isPacked;if(m||!W().getBool("WEBGL_LAZILY_UNPACK")||!W().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!f){const _=u?o[0]*o[1]*o[2]:o[0]*o[2]*o[3],E=O(e,[1,_,s.inChannels]),F=O(t,[1,s.inChannels,s.outChannels]),D=this.fusedBatchMatMul({a:E,b:F,transposeA:h,transposeB:d,bias:n,activation:i,preluActivationWeights:r});return O(D,s.outShape)}const g=u?o[0]*o[1]*(o[2]+1):o[0]*o[2]*(o[3]+1),y={dataId:e.dataId,shape:[1,g,s.inChannels],dtype:e.dtype},w=a.shape;a.shape=a.shape.slice(),a.shape[a.shape.length-2]++,N.assert(zl(a.shape,y.shape),()=>`packed reshape ${a.shape} to ${y.shape} isn't free`);const x=O(t,[1,s.inChannels,s.outChannels]),T=this.fusedBatchMatMul({a:y,b:x,transposeA:h,transposeB:d,bias:n,activation:i,preluActivationWeights:r}),A=this.texData.get(T.dataId);return N.assert(A.isPacked,()=>"batchMatMul result is expected to be packed"),a.shape=w,A.shape=s.outShape,Ms().makeTensorFromDataId(T.dataId,s.outShape,T.dtype)}conv2dWithIm2Row(e,t,s,n,i,r){const{filterWidth:o,filterHeight:a,inChannels:l,outWidth:c,outHeight:p,dataFormat:u}=s,h=u==="channelsLast",d=o*a*l,m=p*c,f=[d,m],g=!0,y=!1,w=e.squeeze([0]),x=t.reshape([1,d,-1]),T=new A2(f,w.shape,s),A=this.compileAndRun(T,[w]).reshape([1,f[0],f[1]]),_=n!=null,E=r!=null,F=i?_f(i,!0):null,D=new Nf(A.shape,[1,m,s.outChannels],g,y,_,F,E),M=[A,x];n&&M.push(n),E&&M.push(r);const P=this.compileAndRun(D,M);return h?P.reshape([1,p,c,s.outChannels]):P.reshape([1,s.outChannels,p,c])}fusedConv2d({input:e,filter:t,convInfo:s,bias:n,activation:i,preluActivationWeights:r}){if(s.filterHeight===1&&s.filterWidth===1&&s.dilationHeight===1&&s.dilationWidth===1&&s.strideHeight===1&&s.strideWidth===1&&(s.padInfo.type==="SAME"||s.padInfo.type==="VALID"))return this.conv2dByMatMul(e,t,s,n,i,r);if(W().getBool("WEBGL_CONV_IM2COL")&&e.shape[0]===1)return this.conv2dWithIm2Row(e,t,s,n,i,r);const o=n!=null,a=r!=null,l=i?_f(i,!1):null,c=new Yw(s,o,l,a),p=[e,t];return n&&p.push(n),r&&p.push(r),this.compileAndRun(c,p)}conv2d(e,t,s){if(s.filterHeight===1&&s.filterWidth===1&&s.dilationHeight===1&&s.dilationWidth===1&&s.strideHeight===1&&s.strideWidth===1&&(s.padInfo.type==="SAME"||s.padInfo.type==="VALID"))return this.conv2dByMatMul(e,t,s);if(W().getBool("WEBGL_CONV_IM2COL")&&e.shape[0]===1)return this.conv2dWithIm2Row(e,t,s);const n=new Yw(s);return this.compileAndRun(n,[e,t])}conv2dDerInput(e,t,s){const n=new zR(s);return this.compileAndRun(n,[e,t])}conv2dDerFilter(e,t,s){const n=new WR(s);return this.compileAndRun(n,[e,t])}fusedDepthwiseConv2D({input:e,filter:t,convInfo:s,bias:n,activation:i,preluActivationWeights:r}){const o=W().getBool("WEBGL_PACK_DEPTHWISECONV")&&s.strideWidth<=2&&s.outChannels/s.inChannels===1,a=i?_f(i,o):null,l=[e,t],c=n!=null,p=r!=null;c&&l.push(n),p&&l.push(r);let u;return o?(u=new Xw(s,c,a,p),this.compileAndRun(u,l)):(u=new Kw(s,c,a,p),this.compileAndRun(u,l))}depthwiseConv2D(e,t,s){let n;return W().getBool("WEBGL_PACK_DEPTHWISECONV")&&s.strideWidth<=2&&s.outChannels/s.inChannels===1?(n=new Xw(s),this.compileAndRun(n,[e,t])):(n=new Kw(s),this.compileAndRun(n,[e,t]))}depthwiseConv2DDerInput(e,t,s){const n=new VR(s);return this.compileAndRun(n,[e,t])}depthwiseConv2DDerFilter(e,t,s){const n=new jR(s);return this.compileAndRun(n,[e,t])}conv3d(e,t,s){const n=new GR(s);return this.compileAndRun(n,[e,t])}conv3dDerInput(e,t,s){const n=new BR(s);return this.compileAndRun(n,[e,t])}conv3dDerFilter(e,t,s){const n=new PR(s);return this.compileAndRun(n,[e,t])}cast(e,t){return U.castTensor(e,t,this)}unstack(e,t){const s=e.shape[t],n=new Array(e.rank-1);let i=0;for(let l=0;l<e.rank;l++)l!==t&&(n[i++]=e.shape[l]);const r=new Array(e.rank).fill(0),o=e.shape.slice();o[t]=1;const a=new Array(s);for(let l=0;l<a.length;l++)r[t]=l,a[l]=this.slice(e,r,o).reshape(n);return a}avgPool3d(e,t){const s=new Cf(t,"avg",!1);return this.compileAndRun(s,[e],"float32")}avgPool3dBackprop(e,t,s){const n=new iR(s);return this.compileAndRun(n,[e],t.dtype)}maxPool3d(e,t){const s=new Cf(t,"max",!1);return this.compileAndRun(s,[e],"float32")}maxPool3dBackprop(e,t,s,n){const i=!0,r=new Cf(n,"max",i),o=this.compileAndRun(r,[t]),a=new E2(n),l=this.compileAndRun(a,[e,o],t.dtype);return o.dispose(),l}resizeBilinear(e,t,s,n){const i=W().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new W2(e.shape,t,s,n):new $2(e.shape,t,s,n);return this.compileAndRun(i,[e],"float32")}resizeBilinearBackprop(e,t,s){const n=new U2(e,t,s);return this.compileAndRun(n,[e])}resizeNearestNeighbor(e,t,s,n){const i=new P2(e.shape,t,s,n);return this.compileAndRun(i,[e])}resizeNearestNeighborBackprop(e,t,s){const n=new z2(e,t,s);return this.compileAndRun(n,[e])}multinomial(e,t,s,n){const i=t?e:es(e),r=i.shape[0],o=i.shape[1],a=new _2(r,o,s),l=a.getCustomSetupFunc(n);return this.compileAndRun(a,[i],"int32",l)}oneHot(e,t,s,n){const i=new k2(e.size,t,s,n);return this.compileAndRun(i,[e])}diag(e){const t=new ZR(e.size);return this.compileAndRun(t,[e])}cropAndResize(e,t,s,n,i,r){const o=new qR(e.shape,t.shape,n,i,r);return this.compileAndRun(o,[e,t,s],"float32")}depthToSpace(e,t,s){N.assert(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`);const n=e.shape[0],i=s==="NHWC"?e.shape[1]:e.shape[2],r=s==="NHWC"?e.shape[2]:e.shape[3],o=s==="NHWC"?e.shape[3]:e.shape[1],a=i*t,l=r*t,c=o/(t*t),p=s==="NHWC"?[n,a,l,c]:[n,c,a,l],u=new JR(p,t,s);return this.compileAndRun(u,[e])}split(e,t,s){return sV(e,t,s)}scatterND(e,t,s){const{sliceRank:n,numUpdates:i,sliceSize:r,strides:o,outputSize:a}=U.calculateShapes(t,e,s),l=[a/r,r],c=e.reshape([i,n]),p=t.reshape([i,r]);if(a===0)return U.reshapeTensor(ze([]),s);const u=j(0),h=new ox(i,n,c.rank,p.rank,o,l),d=this.compileAndRun(h,[p,c,u]);return d.reshape(s)}sparseToDense(e,t,s,n){const{sliceRank:i,numUpdates:r,strides:o,outputSize:a}=U.calculateShapes(t,e,s),l=!1,c=new ox(r,i,e.rank,t.rank,o,[a,1],l),p=this.compileAndRun(c,[t,e,n]);return p.reshape(s)}fft(e){const t=!1;return this.fftImpl(e,t)}ifft(e){const t=!0;return this.fftImpl(e,t)}fftImpl(e,t){const s=this.texData.get(e.dataId),n=new Qw(Zw.REAL,e.shape,t),i=new Qw(Zw.IMAG,e.shape,t),r=[this.makeComplexComponentTensorInfo(e,s.complexTensors.real),this.makeComplexComponentTensorInfo(e,s.complexTensors.imag)],o=this.compileAndRun(n,r),a=this.compileAndRun(i,r),l=this.complex(o,a).as2D(e.shape[0],e.shape[1]);return o.dispose(),a.dispose(),l}gatherND(e,t){const s=t.shape,n=s[s.length-1],[i,r,o,a]=U.prepareAndValidate(e,t),l=t.reshape([r,n]),c=e.reshape([e.size/o,o]),p=new r2(n,a,[r,o]),u=this.compileAndRun(p,[c,l]);return u.reshape(i)}fill(e,t,s){if(s=s||N.inferDtype(t),s==="string"){const n=N.getArrayFromDType(s,N.sizeFromShape(e));return n.fill(t),Ms().makeTensor(n,e,s,this)}else{const n=new n2(e,t),i=n.getCustomSetupFunc(t);return this.compileAndRun(n,[],s,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,s){return U.linspaceImpl(e,t,s)}makeTensorInfo(e,t,s){const n=this.write(s,e,t);return this.texData.get(n).usage=null,{dataId:n,shape:e,dtype:t}}makeOutput(e,t,s){const{dataId:n}=this.makeTensorInfo(e,t,s);return Ms().makeTensorFromDataId(n,e,t,this)}unpackTensor(e){const t=new RO(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new D2(e.shape),s=!0;return this.runWebGLProgram(t,[e],e.dtype,null,s)}packedReshape(e,t){const s=[po(e.shape),...uo(e.shape)],n={dtype:e.dtype,shape:s,dataId:e.dataId},i=[po(t),...uo(t)],r=new Of(i,s),o=!0,a=this.runWebGLProgram(r,[n],e.dtype,null,o);return{dataId:a.dataId,shape:t,dtype:a.dtype}}decode(e){const t=this.texData.get(e),{isPacked:s,shape:n,dtype:i}=t,r=wf(n);let o;s?o=new XR(r):o=new KR(r);const a=!0,l=this.runWebGLProgram(o,[{shape:r,dtype:i,dataId:e}],i,null,a);return{dtype:i,shape:n,dataId:l.dataId}}runWebGLProgram(e,t,s,n,i=!1){const r=this.makeTensorInfo(e.outputShape,s),o=this.texData.get(r.dataId);if(e.packedOutput&&(o.isPacked=!0),e.outPackingScheme===lo.DENSE){const m=co(e.outputShape);o.texShape=m.map(f=>f*2)}if(e.outTexUsage!=null&&(o.usage=e.outTexUsage),N.sizeFromShape(r.shape)===0)return o.values=N.getTypedArrayFromDType(r.dtype,0),r;const a=[],l=t.map(m=>{if(m.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let f=this.texData.get(m.dataId);if(f.texture==null){if(!e.packedInputs&&N.sizeFromShape(m.shape)<=W().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:m.shape,texData:null,isUniform:!0,uniformValues:f.values};e.packedInputs&&(f.isPacked=!0,f.shape=m.shape)}else if(!!f.isPacked!==!!e.packedInputs)m=f.isPacked?this.unpackTensor(m):this.packTensor(m),a.push(m),f=this.texData.get(m.dataId);else if(f.isPacked&&!zl(f.shape,m.shape)){const g=m,y=m.shape;m.shape=f.shape,m=this.packedReshape(m,y),a.push(m),f=this.texData.get(m.dataId),g.shape=y}return this.uploadToGPU(m.dataId),{shape:m.shape,texData:f,isUniform:!1}});this.uploadToGPU(r.dataId);const c={shape:r.shape,texData:o,isUniform:!1},p=T2(e,l,c),u=this.getAndSaveBinary(p,()=>S2(this.gpgpu,e,l,c)),h=this.activeTimers!=null;let d;if(h&&(d=this.startTimer()),v2(this.gpgpu,u,l,c,n),a.forEach(m=>this.disposeIntermediateTensorInfo(m)),h&&(d=this.endTimer(d),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(d)})),!W().getBool("WEBGL_LAZILY_UNPACK")&&o.isPacked&&i===!1){const m=this.unpackTensor(r);return this.disposeIntermediateTensorInfo(r),m}return r}compileAndRun(e,t,s,n,i=!1){s=s||t[0].dtype;const r=this.runWebGLProgram(e,t,s,n,i);return Ms().makeTensorFromDataId(r.dataId,r.shape,r.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(!W().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=C(()=>{if(!W().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=W().getBool("DEBUG");W().set("DEBUG",!1);const t=this.abs(j(1e-8)).dataSync()[0];if(W().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?oV:aV}uploadToGPU(e){const t=this.texData.get(e),{shape:s,dtype:n,values:i,texture:r,usage:o,isPacked:a}=t;if(r!=null)return;const l=this.activeTimers!=null;let c;l&&(c=N.now());let p=t.texShape;if(p==null&&(p=C0(s,a),t.texShape=p),i!=null){const u=wf(s);let h,d=p[1],m=p[0];const f=i instanceof Uint8Array;a?([d,m]=gi(p[0],p[1]),h=new s2(u,[m,d],f)):h=new t2(u,[m,d],f);const g=this.makeTensorInfo([m,d],n);f?this.texData.get(g.dataId).usage=ns.PIXELS:this.texData.get(g.dataId).usage=ns.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(g.dataId),d,m,i);const y=!0,w=this.runWebGLProgram(h,[g],n,null,y),x=this.texData.get(w.dataId);t.texture=x.texture,t.texShape=x.texShape,t.isPacked=x.isPacked,t.usage=x.usage,this.disposeIntermediateTensorInfo(g),this.texData.delete(w.dataId),t.values=null,l&&(this.uploadWaitMs+=N.now()-c)}else{const u=this.acquireTexture(p,o,n,a);t.texture=u}}convertAndCacheOnCPU(e,t){const s=this.texData.get(e),{dtype:n}=s;return this.releaseGPUData(e),t!=null&&(s.values=hV(t,n)),s.values}acquireTexture(e,t,s,n){if(this.numBytesInGPU+=this.computeBytes(e,s),!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,n)}computeBytes(e,t){return e[0]*e[1]*N.bytesPerElement(t)}tryRunOnCpuOrThrow(e,t){if(this.shouldExecuteOnCPU(e))try{return t()}catch(s){if(W().getBool("IS_TEST"))throw new Error("CPU forwarding failed")}return null}}function hV(e,t){if(t==="float32"||t==="complex64")return e;if(t==="int32"||t==="bool"){const s=t==="int32"?new Int32Array(e.length):new Uint8Array(e.length);for(let n=0;n<s.length;++n)s[n]=Math.round(e[n]);return s}else throw new Error(`Unknown dtype ${t}`)}const Lx="2.6.0";function _O(){W().set("WEBGL_FORCE_F16_TEXTURES",!0)}ja.isBrowser()&&Tp("webgl",()=>new xx,2);const H8e={forceHalfFloat:_O};const kf="if (isnan(x)) return x;",kO=`
if (isnan(a)) return a;
if (isnan(b)) return b;
`,DO=`
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 ho(e){return({inputs:t,backend:s})=>{const{x:n}=t,i=s,r=new $e(n.shape,e);return i.runWebGLProgram(r,[n],n.dtype)}}function Hl(e,t,s,n){return({inputs:i,backend:r})=>{const{a:o,b:a}=i,l=r,c=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new bi(t,o.shape,a.shape,!!s):new kt(e,o.shape,a.shape),p=n||o.dtype,u=l.runWebGLProgram(c,[o,a],p);return u}}const dV=kO+`
return atan(a, b);
`,mV=`
vec4 result = atan(a, b);
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
`+DO+`
return result;
`,fV=Hl(dV,mV),FO={kernelName:bo,backendName:"webgl",kernelFunc:fV};function Lu(e){const{inputs:t,backend:s}=e,{x:n}=t;return s.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}const MO={kernelName:Ti,backendName:"webgl",kernelFunc:Lu};function gV(e){const{inputs:t,backend:s,attrs:n}=e,{x:i}=t;yi(i,"avgPool");const{filterSize:r,strides:o,pad:a,dimRoundingMode:l}=n,c=1;N.assert(U.eitherStridesOrDilationsAreOne(o,c),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);const p=U.computePool2DInfo(i.shape,r,o,c,a,l);if(p.filterWidth===1&&p.filterHeight===1&&N.arraysEqual(p.inShape,p.outShape))return Lu({inputs:{x:i},backend:s});const u=new Ki(p,"avg",!1);return s.runWebGLProgram(u,[i],"float32")}const UO={kernelName:Si,backendName:"webgl",kernelFunc:gV};function yV(e){const{inputs:t,backend:s,attrs:n}=e,{dy:i,input:r}=t,o=r;yi([i,r],"avgPoolBackprop");const{filterSize:a,strides:l,pad:c}=n,p=U.computePool2DInfo(o.shape,a,l,1,c),u=new nR(p);return s.runWebGLProgram(u,[i],o.dtype)}const $O={kernelName:wo,backendName:"webgl",kernelFunc:yV};class WO{constructor(e,t,s,n,i,r){this.outputShape=[],this.variableNames=["x","mean","variance"],U.assertAndGetBroadcastShape(e,t),U.assertAndGetBroadcastShape(e,s);let o="0.0";n!=null&&(U.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let a="1.0";i!=null&&(U.assertAndGetBroadcastShape(e,i),this.variableNames.push("scale"),a="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
void main() {
float x = getXAtOutCoords();
float mean = getMeanAtOutCoords();
float variance = getVarianceAtOutCoords();
float offset = ${o};
float scale = ${a};
float inv = scale * inversesqrt(variance + float(${r}));
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
}
`}}class zO{constructor(e,t,s,n,i,r){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],U.assertAndGetBroadcastShape(e,t),U.assertAndGetBroadcastShape(e,s);let o="vec4(0.0)";n!=null&&(U.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let a="vec4(1.0)";i!=null&&(U.assertAndGetBroadcastShape(e,i),this.variableNames.push("scale"),a="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
void main() {
vec4 offset = ${o};
vec4 scale = ${a};
vec4 x = getXAtOutCoords();
vec4 mean = getMeanAtOutCoords();
vec4 variance = getVarianceAtOutCoords();
vec4 inv = scale * inversesqrt(variance + vec4(${r}));
setOutput((x - mean) * inv + offset);
}
`}}const bV=({inputs:e,backend:t,attrs:s})=>{const{x:n,mean:i,variance:r,offset:o,scale:a}=e;N.assert(i.shape.length===r.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),N.assert(o==null||i.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),N.assert(a==null||i.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=s;l==null&&(l=.001);const c=[n,i,r];let p=null;o!=null&&(p=o.shape,c.push(o));let u=null;a!=null&&(u=a.shape,c.push(a));const h=W().getBool("WEBGL_PACK_NORMALIZATION")?new zO(n.shape,i.shape,r.shape,p,u,l):new WO(n.shape,i.shape,r.shape,p,u,l),d=t.runWebGLProgram(h,c,c[0].dtype);return d},PO={kernelName:vi,backendName:"webgl",kernelFunc:bV};const wV=kf+`
return cos(x);
`,xV=ho(wV),BO={kernelName:Xn,backendName:"webgl",kernelFunc:xV};const LV=`
if (a == b) {
return 1.0;
};
return a / b;`,SV=`
// 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;
`,IV=Hl(LV,SV,!0),jO={kernelName:Jn,backendName:"webgl",kernelFunc:IV};class VO{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 GO={kernelName:So,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:s}=e,n=t,i=new VO(s.shape),r=n.runWebGLProgram(i,[s],s.dtype);return r}};class qO{constructor(e){this.variableNames=["A"];const t=at(),[s,n]=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(${n}.0, ${s}.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 HO{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=at(),[s,n]=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(${n}.0, ${s}.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 YO={kernelName:Da,backendName:"webgl",kernelFunc:vV};let Yl;function vV(e){const{inputs:t,backend:s,attrs:n}=e;let{pixels:i}=t;const{numChannels:r}=n,o=typeof HTMLVideoElement!="undefined"&&i instanceof HTMLVideoElement,a=typeof HTMLImageElement!="undefined"&&i instanceof HTMLImageElement,[l,c]=o?[i.videoWidth,i.videoHeight]:[i.width,i.height],p=[c,l],u=[c,l,r];(a||o)&&(Yl==null&&(Yl=document.createElement("canvas").getContext("2d")),Yl.canvas.width=l,Yl.canvas.height=c,Yl.drawImage(i,0,0,l,c),i=Yl.canvas);const h=s.makeTensorInfo(p,"int32");s.texData.get(h.dataId).usage=ns.PIXELS,s.gpgpu.uploadPixelDataToTexture(s.getTexture(h.dataId),i);const d=W().getBool("WEBGL_PACK")?new HO(u):new qO(u),m=s.runWebGLProgram(d,[h],"int32");return s.disposeData(h.dataId),m}function TV(e){const t=[];for(;t.length===0||t[t.length-1].outSize!==1;){const s=t.length?t[t.length-1].outSize:e[1],n=U.computeOptimalWindowSize(s);t.push({inSize:s,windowSize:n,outSize:Math.ceil(s/n)})}return t}function KO(e,t,s,n){const i=TV(e.shape);let r=e;for(let o=0;o<i.length;o++){const{inSize:a,windowSize:l,outSize:c}=i[o],p=new Rf({windowSize:l,inSize:a,batchSize:e.shape[0],outSize:c},s),u=r;r=n.runWebGLProgram(p,[r],t),u.dataId!==e.dataId&&n.disposeData(u.dataId)}return r}function XO(e,t,s){const n=[po(e.shape),...uo(e.shape)],i={dtype:e.dtype,shape:n,dataId:e.dataId},r=[po(t),...uo(t)],o=new Of(r,n),a=!0,l=s.runWebGLProgram(o,[i],e.dtype,null,a);return{dataId:l.dataId,shape:t,dtype:l.dtype}}function Df(e){const{inputs:t,backend:s,attrs:n}=e,{x:i}=t,{shape:r}=n,o=s,a=N.sizeFromShape(i.shape),l=N.inferFromImplicitShape(r,a),c=N.sizeFromShape(l);N.assert(a===c,()=>`The new shape (${l}) has ${c} elements and the old shape (${i.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`);const p=o.texData.get(i.dataId);return p.isPacked&&!zl(i.shape,l)&&!(p.texture!==null&&zl(p.shape,l))?XO(i,l,o):(o.incRef(i.dataId),{dataId:i.dataId,shape:l,dtype:i.dtype})}const JO={kernelName:Ci,backendName:"webgl",kernelFunc:Df};function ZO(e,t,s,n){const i=N.sizeFromShape(t),r=N.sizeFromShape(e.shape),o=r/i,a=Df({inputs:{x:e},attrs:{shape:[o,i]},backend:n}),l=KO(a,e.dtype,"max",n),c=Df({inputs:{x:l},attrs:{shape:s},backend:n});return n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(l),c}class QO{constructor(e,t){this.variableNames=["A"];const s=new Array(e.length);for(let r=0;r<s.length;r++)s[r]=e[t[r]];this.outputShape=s,this.rank=s.length;const n=Re(this.rank),i=AV(t);this.userCode=`
void main() {
${n} resRC = getOutputCoords();
setOutput(getA(${i}));
}
`}}function AV(e){const t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);const s=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],n=new Array(t);for(let i=0;i<e.length;i++)n[e[i]]=s[i];return n.join()}class e1{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;const s=new Array(e.length);for(let c=0;c<s.length;c++)s[c]=e[t[c]];if(this.outputShape=s,this.rank=s.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const n=Re(this.rank),i=Bw("rc",this.rank),r=new Array(this.rank);for(let c=0;c<t.length;c++)r[t[c]]=i[c];const o=`vec2(${r.slice(-2).join()})`,a=`++${i[this.rank-1]} < ${s[this.rank-1]}`,l=`getChannel(getA(${r.join()}), ${o})`;this.userCode=`
void main() {
${n} rc = getOutputCoords();
vec4 result = vec4(0.);
result[0] = ${l};
if(${a}) {
result[1] = ${l};
}
--${i[this.rank-1]};
if(++${i[this.rank-2]} < ${s[this.rank-2]}) {
result[2] = ${l};
if(${a}) {
result[3] = ${l};
}
}
setOutput(result);
}
`}}function Ff(e,t,s){const n=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new e1(e.shape,t):new QO(e.shape,t);return s.runWebGLProgram(n,[e],e.dtype)}const t1={kernelName:Ai,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{x:n}=e,{reductionIndices:i,keepDims:r}=t,o=s,a=n.shape.length,l=N.parseAxisParam(i,n.shape);let c=l;const p=U.getAxesPermutation(c,a),u=p!=null,h=o.shouldExecuteOnCPU([n]);let d=n;if(u){if(h){const w=o.texData.get(d.dataId),x=w.values,T=new Array(a);for(let E=0;E<T.length;E++)T[E]=n.shape[p[E]];const A=Lf(x,n.shape,n.dtype,p,T);d=o.makeTensorInfo(T,n.dtype);const _=o.texData.get(d.dataId);_.values=A}else d=Ff(n,p,o);c=U.getInnerMostAxes(c.length,a)}U.assertAxesAreInnerMostDims("max",c,a);const[m,f]=U.computeOutAndReduceShapes(d.shape,c);let g=m;r&&(g=U.expandShapeToKeepDim(m,l));let y;if(h){const w=o.texData.get(d.dataId),x=w.values,T=B0(x,N.sizeFromShape(f),g,n.dtype);y=o.makeTensorInfo(g,n.dtype);const A=o.texData.get(y.dataId);A.values=T}else y=ZO(d,f,g,o);return u&&o.disposeIntermediateTensorInfo(d),y}};function NV(e){const{inputs:t,backend:s,attrs:n}=e,{x:i}=t;yi(i,"maxPool");const{filterSize:r,strides:o,pad:a,dimRoundingMode:l}=n,c=1;N.assert(U.eitherStridesOrDilationsAreOne(o,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);const p=U.computePool2DInfo(i.shape,r,o,c,a,l);if(p.filterWidth===1&&p.filterHeight===1&&N.arraysEqual(p.inShape,p.outShape))return Lu({inputs:{x:i},backend:s});const u=new Ki(p,"max",!1);return s.runWebGLProgram(u,[i],i.dtype)}const s1={kernelName:Ni,backendName:"webgl",kernelFunc:NV};function CV(e){const{inputs:t,backend:s,attrs:n}=e,{dy:i,input:r,output:o}=t,a=r;yi([r,o],"maxPoolBackprop");const{filterSize:l,strides:c,pad:p,dimRoundingMode:u}=n,h=U.computePool2DInfo(a.shape,l,c,1,p,u),d=!0,m=new Ki(h,"max",d),f=s.runWebGLProgram(m,[a],a.dtype),g=new O2(h),y=s.runWebGLProgram(g,[i,f],a.dtype);return s.disposeIntermediateTensorInfo(f),y}const n1={kernelName:Io,backendName:"webgl",kernelFunc:CV};function i1(e,t,s,n){let i=new Ki(s,"max",!1);const r=n.runWebGLProgram(i,[e],"float32");i=new Ki(s,"max",!0,!0,t);const o=n.runWebGLProgram(i,[e],"float32");return[r,o]}const r1={kernelName:vo,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{x:n}=e,{filterSize:i,strides:r,pad:o,includeBatchInIndex:a}=t,l=s;N.assert(n.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${n.shape.length}.`);const c=[1,1];N.assert(U.eitherStridesOrDilationsAreOne(r,c),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${r} and dilations '${c}'`);const p=U.computePool2DInfo(n.shape,i,r,c,o),[u,h]=i1(n,a,p,l);return[u,h]}};const o1={kernelName:Vc,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:s})=>{U.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{boxes:n,scores:i}=e,{maxOutputSize:r,iouThreshold:o,scoreThreshold:a}=s,l=t,c=l.readSync(n.dataId),p=l.readSync(i.dataId),u=r,h=o,d=a;return vt.nonMaxSuppressionV3Impl(c,p,u,h,d)}};const RV=vt.nonMaxSuppressionV4Impl,a1={kernelName:To,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:s})=>{U.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{boxes:n,scores:i}=e,{maxOutputSize:r,iouThreshold:o,scoreThreshold:a,padToMaxOutputSize:l}=s,c=t,p=c.readSync(n.dataId),u=c.readSync(i.dataId),{selectedIndices:h,validOutputs:d}=RV(p,u,r,o,a,l);return[h,d]}};const OV=vt.nonMaxSuppressionV5Impl,l1={kernelName:Ao,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:s})=>{U.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{boxes:n,scores:i}=e,{maxOutputSize:r,iouThreshold:o,scoreThreshold:a,softNmsSigma:l}=s,c=t,p=c.readSync(n.dataId),u=c.readSync(i.dataId),h=r,d=o,m=a,f=l,{selectedIndices:g,selectedScores:y}=OV(p,u,h,d,m,f);return[g,y]}};class c1{constructor(e,t,s,n){this.variableNames=["Image"],this.outputShape=[];const i=e[1],r=e[2],o=Math.sin(t).toFixed(3),a=Math.cos(t).toFixed(3);this.outputShape=e;const[l,c]=U.getImageCenter(n,i,r),p=l.toFixed(3),u=c.toFixed(3);let h="";typeof s=="number"?h=`float outputValue = ${s.toFixed(2)};`:h=`
vec3 fill = vec3(${s.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) - ${p}) * ${a} - (float(y) - ${u}) * ${o};
float coordYFloat = (float(x) - ${p}) * ${o} + (float(y) - ${u}) * ${a};
int coordX = int(round(coordXFloat + ${p}));
int coordY = int(round(coordYFloat + ${u}));
${h}
if(coordX >= 0 && coordX < ${r} && coordY >= 0 && coordY < ${i}) {
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
}
setOutput(outputValue);
}
`}}const p1={kernelName:_o,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{image:n}=e,{radians:i,fillValue:r,center:o}=t,a=s,l=new c1(n.shape,i,r,o),c=a.runWebGLProgram(l,[n],n.dtype);return c}};const EV=kf+`
return sin(x);
`,_V=ho(EV),u1={kernelName:Zn,backendName:"webgl",kernelFunc:_V};const kV="return x * x;",DV=ho(kV),h1={kernelName:Oo,backendName:"webgl",kernelFunc:DV};const d1="return (a - b) * (a - b);",FV=Hl(d1,d1),m1={kernelName:Qn,backendName:"webgl",kernelFunc:FV};const MV="return tan(x);",UV=ho(MV),f1={kernelName:ei,backendName:"webgl",kernelFunc:UV};const g1={kernelName:Ri,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:s})=>{const{x:n}=e,{perm:i}=t,r=s,o=n.shape.length,a=new Array(o);for(let c=0;c<a.length;c++)a[c]=n.shape[i[c]];let l;if(r.shouldExecuteOnCPU([n])){const c=r.texData.get(n.dataId),p=c.values,u=Lf(p,n.shape,n.dtype,i,a);l=r.makeTensorInfo(a,n.dtype);const h=r.texData.get(l.dataId);h.values=u}else l=Ff(n,i,r);return l}};function $V(e){const{inputs:t,attrs:s,backend:n}=e,{axis:i}=s,{x:r}=t;yi(r,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const o=n.readSync(r.dataId),{outputValues:a,outputShape:l,indices:c}=H0(o,i,r.shape,r.dtype);return[n.makeTensorInfo(l,r.dtype,a),n.makeTensorInfo([c.length],"int32",c)]}const y1={kernelName:Eo,backendName:"webgl",kernelFunc:$V};const WV=[FO,UO,$O,PO,BO,jO,GO,YO,MO,t1,s1,n1,r1,o1,a1,l1,JO,p1,u1,h1,m1,f1,g1,y1];for(const e of WV)Ma(e);const b1="2.6.0";const Sx={};Ee(Sx,{Abs:()=>yo,Acos:()=>nr,Acosh:()=>ir,AdadeltaOptimizer:()=>Yo,AdagradOptimizer:()=>Ko,AdamOptimizer:()=>Xo,AdamaxOptimizer:()=>Jo,Add:()=>Kn,AddN:()=>yc,All:()=>xg,Any:()=>Lg,ArgMax:()=>bc,ArgMin:()=>wc,Asin:()=>rr,Asinh:()=>or,Atan:()=>ar,Atan2:()=>bo,Atanh:()=>lr,AvgPool:()=>Si,AvgPool3D:()=>xc,AvgPool3DBackprop:()=>Sg,AvgPoolBackprop:()=>wo,BatchMatMul:()=>Lc,BatchToSpaceND:()=>Sc,BroadcastTo:()=>Ic,Callback:()=>Db,CallbackList:()=>hb,Cast:()=>Ii,Ceil:()=>cr,ClipByValue:()=>pr,Complex:()=>vc,Concat:()=>xo,Conv2D:()=>Tc,Conv2DBackpropFilter:()=>Ig,Conv2DBackpropInput:()=>Ac,Conv3D:()=>Nc,Conv3DBackpropFilterV2:()=>vg,Conv3DBackpropInputV2:()=>Tg,Cos:()=>Xn,Cosh:()=>ur,CropAndResize:()=>Ag,Cumsum:()=>Cc,CustomCallback:()=>mb,DataStorage:()=>gc,DepthToSpace:()=>Ng,DepthwiseConv2dNative:()=>Rc,DepthwiseConv2dNativeBackpropFilter:()=>Cg,DepthwiseConv2dNativeBackpropInput:()=>Rg,Diag:()=>Og,Dilation2D:()=>Lo,Dilation2DBackpropFilter:()=>Ea,Dilation2DBackpropInput:()=>Oa,Div:()=>Jn,ENV:()=>gg,EarlyStopping:()=>Fb,Elu:()=>hr,EluGrad:()=>Eg,Environment:()=>fg,Equal:()=>_g,Erf:()=>dr,Exp:()=>mr,Expm1:()=>fr,FFT:()=>Oc,Fill:()=>kg,FlipLeftRight:()=>So,Floor:()=>gr,FloorDiv:()=>Ec,FromPixels:()=>Da,FusedBatchNorm:()=>vi,FusedConv2D:()=>ju,FusedDepthwiseConv2D:()=>Vu,GatherNd:()=>Dg,GatherV2:()=>_c,GraphModel:()=>ow,Greater:()=>Fg,GreaterEqual:()=>kc,History:()=>db,IFFT:()=>Dc,Identity:()=>Ti,Imag:()=>Fc,InputSpec:()=>st,IsFinite:()=>yr,IsInf:()=>br,IsNan:()=>wr,KernelBackend:()=>go,LRN:()=>Uc,LRNBackprop:()=>Pg,LayerVariable:()=>xd,LayersModel:()=>tn,Less:()=>Mg,LessEqual:()=>Ug,LinSpace:()=>$g,Log:()=>xr,Log1p:()=>Lr,LogSoftmax:()=>Mc,LogicalAnd:()=>Wg,LogicalNot:()=>_a,LogicalOr:()=>zg,Max:()=>Ai,MaxPool:()=>Ni,MaxPool3D:()=>Wc,MaxPool3DBackprop:()=>Bg,MaxPoolBackprop:()=>Io,MaxPoolWithArgmax:()=>vo,Maximum:()=>$c,Mean:()=>EE,Min:()=>zc,Minimum:()=>Pc,Mod:()=>Bc,MomentumOptimizer:()=>Zo,Multiply:()=>Sr,Negate:()=>jc,NonMaxSuppressionV3:()=>Vc,NonMaxSuppressionV4:()=>To,NonMaxSuppressionV5:()=>Ao,NotEqual:()=>ka,OP_SCOPE_SUFFIX:()=>fy,OneHot:()=>qc,OnesLike:()=>Gc,Optimizer:()=>fs,PadV2:()=>No,Pool:()=>_E,Pow:()=>Hc,Prelu:()=>Yc,Prod:()=>jg,RMSPropOptimizer:()=>Qo,RNN:()=>sn,Range:()=>Vg,Rank:()=>ay,Real:()=>Kc,Reciprocal:()=>Ir,Reduction:()=>ft,Relu:()=>Xc,Relu6:()=>Qc,Reshape:()=>Ci,ResizeBilinear:()=>Zc,ResizeBilinearGrad:()=>qg,ResizeNearestNeighbor:()=>Jc,ResizeNearestNeighborGrad:()=>Gg,Reverse:()=>ep,RotateWithOffset:()=>_o,Round:()=>vr,Rsqrt:()=>Tr,SGDOptimizer:()=>Ui,ScatterNd:()=>Hg,SelectV2:()=>tp,Selu:()=>Ar,Sequential:()=>no,Sigmoid:()=>Rr,Sign:()=>Cr,Sin:()=>Zn,Sinh:()=>Nr,Slice:()=>Co,Softmax:()=>ip,Softplus:()=>Or,SpaceToBatchND:()=>Ro,SparseToDense:()=>Yg,SplitV:()=>np,Sqrt:()=>Er,Square:()=>Oo,SquaredDifference:()=>Qn,Step:()=>Dr,StridedSlice:()=>Kg,Sub:()=>_r,Sum:()=>sp,SymbolicTensor:()=>ws,Tan:()=>ei,Tanh:()=>kr,Tensor:()=>me,TensorBuffer:()=>cn,Tile:()=>rp,TopK:()=>Xg,Transpose:()=>Ri,Unique:()=>Eo,Unpack:()=>op,UnsortedSegmentSum:()=>ap,Variable:()=>oi,ZerosLike:()=>lp,_FusedMatMul:()=>Bu,abs:()=>et,acos:()=>eh,acosh:()=>th,add:()=>$,addN:()=>sh,addStrict:()=>YM,all:()=>Xa,any:()=>Uo,argMax:()=>$o,argMin:()=>nh,asin:()=>ih,asinh:()=>rh,atan:()=>oh,atan2:()=>ah,atanh:()=>lh,avgPool:()=>hs,avgPool3d:()=>Za,backend:()=>ky,backend_util:()=>U,basicLSTMCell:()=>SS,batchNorm:()=>Ys,batchNorm2d:()=>uh,batchNorm3d:()=>hh,batchNorm4d:()=>dh,batchToSpaceND:()=>$r,booleanMaskAsync:()=>AM,broadcastTo:()=>zo,browser:()=>Fr,buffer:()=>ge,callbacks:()=>YA,cast:()=>G,ceil:()=>mh,clipByValue:()=>wt,clone:()=>Ds,complex:()=>Gt,concat:()=>be,concat1d:()=>fh,concat2d:()=>gh,concat3d:()=>yh,concat4d:()=>bh,constraints:()=>rb,conv1d:()=>Qa,conv2d:()=>nt,conv2dTranspose:()=>tl,conv3d:()=>sl,conv3dTranspose:()=>vS,copyRegisteredKernels:()=>FE,cos:()=>Wr,cosh:()=>nl,cosineWindow:()=>_p,cumsum:()=>il,customGrad:()=>ms,data:()=>dw,deprecationWarn:()=>It,depthToSpace:()=>xh,depthwiseConv2d:()=>un,deregisterOp:()=>JA,device_util:()=>ja,diag:()=>TS,dilation2d:()=>Lh,disableDeprecationWarnings:()=>ik,dispose:()=>ce,disposeVariables:()=>rk,div:()=>Z,divNoNan:()=>Sh,divStrict:()=>KM,dot:()=>AS,dropout:()=>Vy,elu:()=>hn,enableDebugMode:()=>nk,enableProdMode:()=>sk,enclosingPowerOfTwo:()=>Gy,engine:()=>Ms,env:()=>W,equal:()=>os,equalStrict:()=>kM,erf:()=>Ih,exp:()=>ut,expandDims:()=>Mt,expm1:()=>vh,eye:()=>Po,fft:()=>qr,fill:()=>Wt,findBackend:()=>uk,findBackendFactory:()=>hk,floor:()=>li,floorDiv:()=>Ka,fused:()=>gn,gather:()=>ci,gatherND:()=>jy,gather_util:()=>oS,getBackend:()=>ck,getGradient:()=>Gu,getKernel:()=>pp,getKernelsForBackend:()=>up,grad:()=>HD,grads:()=>YD,greater:()=>Ut,greaterEqual:()=>ds,greaterEqualStrict:()=>DM,greaterStrict:()=>FM,ifft:()=>Mi,imag:()=>dn,image:()=>Zs,inTopKAsync:()=>uU,initializers:()=>pb,input:()=>Md,io:()=>Rt,irfft:()=>yl,isFinite:()=>CS,isInf:()=>RS,isNaN:()=>OS,keep:()=>pt,kernel_impls:()=>vt,layers:()=>Nb,leakyRelu:()=>rl,less:()=>zr,lessEqual:()=>$s,lessEqualStrict:()=>MM,lessStrict:()=>UM,linalg:()=>Hy,linspace:()=>Ah,loadGraphModel:()=>AN,loadLayersModel:()=>mA,localResponseNormalization:()=>Nh,log:()=>zt,log1p:()=>ol,logSigmoid:()=>ES,logSoftmax:()=>al,logSumExp:()=>Oh,logicalAnd:()=>Yt,logicalNot:()=>Pr,logicalOr:()=>ll,logicalXor:()=>_S,losses:()=>n$,matMul:()=>Te,math:()=>rS,max:()=>xt,maxPool:()=>mt,maxPool3d:()=>cl,maxPoolWithArgmax:()=>Eh,maximum:()=>Ht,maximumStrict:()=>XM,mean:()=>Ke,memory:()=>Ya,metrics:()=>Eb,min:()=>Di,minimum:()=>mn,minimumStrict:()=>JM,mod:()=>pl,modStrict:()=>ZM,model:()=>hA,models:()=>_b,moments:()=>Bo,movingAverage:()=>rU,mul:()=>R,mulStrict:()=>QM,multiRNNCell:()=>kS,multinomial:()=>_h,neg:()=>_e,nextFrame:()=>kp,norm:()=>Op,notEqual:()=>Ks,notEqualStrict:()=>$M,oneHot:()=>ai,ones:()=>Kt,onesLike:()=>Ot,op:()=>S,outerProduct:()=>DS,pad:()=>Pt,pad1d:()=>FS,pad2d:()=>MS,pad3d:()=>US,pad4d:()=>$S,pool:()=>WS,pow:()=>Qt,powStrict:()=>eU,prelu:()=>jr,print:()=>Zu,prod:()=>ul,profile:()=>ok,rand:()=>zS,randomGamma:()=>jS,randomNormal:()=>Np,randomUniform:()=>fn,range:()=>Fi,ready:()=>lk,real:()=>Xs,reciprocal:()=>Dh,registerBackend:()=>Tp,registerCallbackConstructor:()=>fA,registerGradient:()=>Zg,registerKernel:()=>Ma,registerOp:()=>XA,regularizers:()=>kb,relu:()=>De,relu6:()=>Fh,removeBackend:()=>pk,reshape:()=>O,reverse:()=>Et,reverse1d:()=>VS,reverse2d:()=>GS,reverse3d:()=>qS,reverse4d:()=>HS,rfft:()=>Hr,round:()=>Mh,rsqrt:()=>hl,scalar:()=>j,scatterND:()=>By,scatter_util:()=>lS,selu:()=>dl,separableConv2d:()=>Vr,sequential:()=>dA,serialization:()=>V,setBackend:()=>xS,setPlatform:()=>dk,setdiff1dAsync:()=>Uh,sigmoid:()=>rs,sign:()=>$h,signal:()=>s$,sin:()=>ml,sinh:()=>fl,slice:()=>he,slice1d:()=>gl,slice2d:()=>Cp,slice3d:()=>Gr,slice4d:()=>jo,slice_util:()=>Fs,softmax:()=>es,softplus:()=>pi,spaceToBatchND:()=>Br,sparseToDense:()=>Ep,spectral:()=>t$,split:()=>Bt,sqrt:()=>Xe,square:()=>xe,squaredDifference:()=>Yr,squaredDifferenceStrict:()=>tU,squeeze:()=>Js,stack:()=>Ve,step:()=>ui,stridedSlice:()=>Wh,sub:()=>X,subStrict:()=>sU,sum:()=>te,sumOutType:()=>yp,tan:()=>zh,tanh:()=>ki,tensor:()=>ze,tensor1d:()=>Oe,tensor2d:()=>as,tensor3d:()=>qa,tensor4d:()=>ts,tensor5d:()=>YS,tensor6d:()=>KS,tensor_util:()=>pn,test_util:()=>bS,tidy:()=>C,tile:()=>Us,time:()=>ak,topk:()=>Ph,train:()=>Jr,transpose:()=>se,truncatedNormal:()=>Kr,unique:()=>Rp,unregisterGradient:()=>DE,unregisterKernel:()=>kE,unsortedSegmentSum:()=>Bh,unstack:()=>Ge,upcastType:()=>Ft,util:()=>N,valueAndGrad:()=>KD,valueAndGrads:()=>XD,variable:()=>jh,variableGrads:()=>Rh,version:()=>zV,version_converter:()=>Km,version_core:()=>_y,version_layers:()=>to,where:()=>dt,whereAsync:()=>bl,zeros:()=>ye,zerosLike:()=>re});const zV={"tfjs-core":_y,"tfjs-backend-cpu":Ew,"tfjs-backend-webgl":Lx,"tfjs-data":pf,"tfjs-layers":to,"tfjs-converter":Km,tfjs:b1};function Ji(e,t,s=!1){if(e.beginPath(),t.slice(1).forEach(({x:n,y:i},r)=>{const o=t[r];e.moveTo(o.x,o.y),e.lineTo(n,i)}),s){const n=t[t.length-1],i=t[0];if(!n||!i)return;e.moveTo(n.x,n.y),e.lineTo(i.x,i.y)}e.stroke()}class js{constructor(e,t){if(!Vn(e)||!Vn(t))throw new Error(`Dimensions.constructor - expected width and height to be valid numbers, instead have ${JSON.stringify({width:e,height:t})}`);this._width=e,this._height=t}get width(){return this._width}get height(){return this._height}reverse(){return new js(1/this.width,1/this.height)}}const Ix={};Ee(Ix,{computeReshapedDimensions:()=>Ax,getCenterPoint:()=>ma,isDimensions:()=>Uf,isEven:()=>Mf,isFloat:()=>Tx,isTensor:()=>ha,isTensor1D:()=>PV,isTensor2D:()=>vx,isTensor3D:()=>Zi,isTensor4D:()=>on,isValidNumber:()=>Vn,isValidProbablitiy:()=>Kl,range:()=>wi,round:()=>da});function ha(e,t){return e instanceof me&&e.shape.length===t}function PV(e){return ha(e,1)}function vx(e){return ha(e,2)}function Zi(e){return ha(e,3)}function on(e){return ha(e,4)}function Tx(e){return e%1!==0}function Mf(e){return e%2===0}function da(e,t=2){const s=Math.pow(10,t);return Math.floor(e*s)/s}function Uf(e){return e&&e.width&&e.height}function Ax({width:e,height:t},s){const n=s/Math.max(t,e);return new js(Math.round(e*n),Math.round(t*n))}function ma(e){return e.reduce((t,s)=>t.add(s),new Fe(0,0)).div(new Fe(e.length,e.length))}function wi(e,t,s){return Array(e).fill(0).map((n,i)=>t+i*s)}function Vn(e){return!!e&&e!==Infinity&&e!==-Infinity&&!isNaN(e)||e===0}function Kl(e){return Vn(e)&&0<=e&&e<=1}class Fe{constructor(e,t){this._x=e,this._y=t}get x(){return this._x}get y(){return this._y}add(e){return new Fe(this.x+e.x,this.y+e.y)}sub(e){return new Fe(this.x-e.x,this.y-e.y)}mul(e){return new Fe(this.x*e.x,this.y*e.y)}div(e){return new Fe(this.x/e.x,this.y/e.y)}abs(){return new Fe(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 Fe(Math.floor(this.x),Math.floor(this.y))}}class lt{constructor(e,t=!0){const s=e||{},n=[s.left,s.top,s.right,s.bottom].every(Vn),i=[s.x,s.y,s.width,s.height].every(Vn);if(!i&&!n)throw new Error(`Box.constructor - expected box to be IBoundingBox | IRect, instead have ${JSON.stringify(s)}`);const[r,o,a,l]=i?[s.x,s.y,s.width,s.height]:[s.left,s.top,s.right-s.left,s.bottom-s.top];lt.assertIsValidBox({x:r,y:o,width:a,height:l},"Box.constructor",t),this._x=r,this._y=o,this._width=a,this._height=l}static isRect(e){return!!e&&[e.x,e.y,e.width,e.height].every(Vn)}static assertIsValidBox(e,t,s=!1){if(!lt.isRect(e))throw new Error(`${t} - invalid box: ${JSON.stringify(e)}, expected object with properties x, y, width, height`);if(!s&&(e.width<0||e.height<0))throw new Error(`${t} - width (${e.width}) and height (${e.height}) must be positive numbers`)}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 Fe(this.left,this.top)}get topRight(){return new Fe(this.right,this.top)}get bottomLeft(){return new Fe(this.left,this.bottom)}get bottomRight(){return new Fe(this.right,this.bottom)}round(){const[e,t,s,n]=[this.x,this.y,this.width,this.height].map(i=>Math.round(i));return new lt({x:e,y:t,width:s,height:n})}floor(){const[e,t,s,n]=[this.x,this.y,this.width,this.height].map(i=>Math.floor(i));return new lt({x:e,y:t,width:s,height:n})}toSquare(){let{x:e,y:t,width:s,height:n}=this;const i=Math.abs(s-n);return s<n&&(e-=i/2,s+=i),n<s&&(t-=i/2,n+=i),new lt({x:e,y:t,width:s,height:n})}rescale(e){const t=Uf(e)?e.width:e,s=Uf(e)?e.height:e;return new lt({x:this.x*t,y:this.y*s,width:this.width*t,height:this.height*s})}pad(e,t){let[s,n,i,r]=[this.x-e/2,this.y-t/2,this.width+e,this.height+t];return new lt({x:s,y:n,width:i,height:r})}clipAtImageBorders(e,t){const{x:s,y:n,right:i,bottom:r}=this,o=Math.max(s,0),a=Math.max(n,0),l=i-o,c=r-a,p=Math.min(l,e-o),u=Math.min(c,t-a);return new lt({x:o,y:a,width:p,height:u}).floor()}shift(e,t){const{width:s,height:n}=this,i=this.x+e,r=this.y+t;return new lt({x:i,y:r,width:s,height:n})}padAtBorders(e,t){const s=this.width+1,n=this.height+1;let i=1,r=1,o=s,a=n,l=this.left,c=this.top,p=this.right,u=this.bottom;return p>t&&(o=-p+t+s,p=t),u>e&&(a=-u+e+n,u=e),l<1&&(a=2-l,l=1),c<1&&(a=2-c,c=1),{dy:r,edy:a,dx:i,edx:o,y:c,ey:u,x:l,ex:p,w:s,h:n}}calibrate(e){return new lt({left:this.left+e.left*this.width,top:this.top+e.top*this.height,right:this.right+e.right*this.width,bottom:this.bottom+e.bottom*this.height}).toSquare().round()}}class Su extends lt{constructor(e,t,s,n,i=!1){super({left:e,top:t,right:s,bottom:n},i)}}class Xl{constructor(e,t,s,n,i){this._imageDims=new js(i.width,i.height),this._score=e,this._classScore=t,this._className=s,this._box=new lt(n).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 lt(this._box).rescale(this.imageDims.reverse())}forSize(e,t){return new Xl(this.score,this.classScore,this.className,this.relativeBox,{width:e,height:t})}}class Lt extends Xl{constructor(e,t,s){super(e,e,"",t,s)}forSize(e,t){const{score:s,relativeBox:n,imageDims:i}=super.forSize(e,t);return new Lt(s,n,i)}}function Nx(e,t,s=!0){const n=Math.max(0,Math.min(e.right,t.right)-Math.max(e.left,t.left)),i=Math.max(0,Math.min(e.bottom,t.bottom)-Math.max(e.top,t.top)),r=n*i;return s?r/(e.area+t.area-r):r/Math.min(e.area,t.area)}function Cx(e){const t=e.map(a=>a.x),s=e.map(a=>a.y),n=t.reduce((a,l)=>l<a?l:a,Infinity),i=s.reduce((a,l)=>l<a?l:a,Infinity),r=t.reduce((a,l)=>a<l?l:a,0),o=s.reduce((a,l)=>a<l?l:a,0);return new Su(n,i,r,o)}function Rx(e,t,s,n=!0){let i=t.map((o,a)=>({score:o,boxIndex:a})).sort((o,a)=>o.score-a.score).map(o=>o.boxIndex);const r=[];for(;i.length>0;){const o=i.pop();r.push(o);const a=i,l=[];for(let c=0;c<a.length;c++){const p=a[c],u=e[o],h=e[p];l.push(Nx(u,h,n))}i=i.filter((c,p)=>l[p]<=s)}return r}function Gn(e,t){return C(()=>{const[s,n,i]=t,r=Wt([...e.shape.slice(0,3),1],s),o=Wt([...e.shape.slice(0,3),1],n),a=Wt([...e.shape.slice(0,3),1],i),l=be([r,o,a],3);return X(e,l)})}function Ox(e,t=!1){return C(()=>{const[s,n]=e.shape.slice(1);if(s===n)return e;const i=Math.abs(s-n),r=Math.round(i*(t?.5:1)),o=s>n?2:1,a=h=>{const d=e.shape.slice();return d[o]=h,Wt(d,0)},l=a(r),c=i-l.shape[o],p=t&&c?a(c):null,u=[p,e,l].filter(h=>!!h).map(h=>G(h,"float32"));return be(u,o)})}function BV(e){const t=e.slice();for(let s=t.length-1;s>0;s--){const n=Math.floor(Math.random()*(s+1)),i=t[s];t[s]=t[n],t[n]=i}return t}function Iu(e){return 1/(1+Math.exp(-e))}function jV(e){return Math.log(e/(1-e))}class vu extends lt{constructor(e,t,s,n,i=!1){super({x:e,y:t,width:s,height:n},i)}}const VV=.5,GV=.43,qV=.45;class On{constructor(e,t,s=new Fe(0,0)){const{width:n,height:i}=t;this._imgDims=new js(n,i),this._shift=s,this._positions=e.map(r=>r.mul(new Fe(n,i)).add(s))}get shift(){return new Fe(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(e=>e.sub(this._shift).div(new Fe(this.imageWidth,this.imageHeight)))}forSize(e,t){return new this.constructor(this.relativePositions,{width:e,height:t})}shiftBy(e,t){return new this.constructor(this.relativePositions,this._imgDims,new Fe(e,t))}shiftByPoint(e){return this.shiftBy(e.x,e.y)}align(e,t={}){if(e){const i=e instanceof Lt?e.box.floor():new lt(e);return this.shiftBy(i.x,i.y).align(null,t)}const{useDlibAlignment:s,minBoxPadding:n}=Object.assign({},{useDlibAlignment:!1,minBoxPadding:.2},t);return s?this.alignDlib():this.alignMinBbox(n)}alignDlib(){const e=this.getRefPointsForAlignment(),[t,s,n]=e,i=p=>n.sub(p).magnitude(),r=(i(t)+i(s))/2,o=Math.floor(r/qV),a=ma(e),l=Math.floor(Math.max(0,a.x-VV*o)),c=Math.floor(Math.max(0,a.y-GV*o));return new vu(l,c,Math.min(o,this.imageWidth+l),Math.min(o,this.imageHeight+c))}alignMinBbox(e){const t=Cx(this.positions);return t.pad(t.width*e,t.height*e)}getRefPointsForAlignment(){throw new Error("getRefPointsForAlignment not implemented by base class")}}class HV extends On{getRefPointsForAlignment(){const e=this.positions;return[e[0],e[1],ma([e[3],e[4]])]}}class Tu extends On{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(ma)}}class $f{constructor(e,t){this._label=e,this._distance=t}get label(){return this._label}get distance(){return this._distance}toString(e=!0){return`${this.label}${e?` (${da(this.distance)})`:""}`}}class Wf extends lt{constructor(e,t){super(e);this._label=t}static assertIsValidLabeledBox(e,t){if(lt.assertIsValidBox(e,t),!Vn(e.label))throw new Error(`${t} - expected property label (${e.label}) to be a number`)}get label(){return this._label}}class fa{constructor(e,t){if(!(typeof e=="string"))throw new Error("LabeledFaceDescriptors - constructor expected label to be a string");if(!Array.isArray(t)||t.some(s=>!(s instanceof Float32Array)))throw new Error("LabeledFaceDescriptors - constructor expected descriptors to be an array of Float32Array");this._label=e,this._descriptors=t}get label(){return this._label}get descriptors(){return this._descriptors}toJSON(){return{label:this.label,descriptors:this.descriptors.map(e=>Array.from(e))}}static fromJSON(e){const t=e.descriptors.map(s=>new Float32Array(s));return new fa(e.label,t)}}class YV extends Wf{constructor(e,t,s,n){super(e,t);this._score=s,this._classScore=n}static assertIsValidPredictedBox(e,t){if(Wf.assertIsValidLabeledBox(e,t),!Kl(e.score)||!Kl(e.classScore))throw new Error(`${t} - expected properties score (${e.score}) and (${e.classScore}) to be a number between [0, 1]`)}get score(){return this._score}get classScore(){return this._classScore}}function xi(e){return e.detection instanceof Lt}function ga(e,t){const s={detection:t};return Object.assign({},e,s)}function Ex(){const e=window.fetch||function(){throw new Error("fetch - missing fetch implementation for browser environment")},t=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:e,readFile:t}}function zf(e){let t="";if(!e)try{e=require("fs")}catch(n){t=n.toString()}const s=e?function(n){return new Promise((i,r)=>{e.readFile(n,function(o,a){return o?r(o):i(a)})})}:function(){throw new Error(`readFile - failed to require fs in nodejs environment with error: ${t}`)};return{readFile:s}}function _x(){const e=global.Canvas||global.HTMLCanvasElement,t=global.Image||global.HTMLImageElement,s=function(){if(e)return new e;throw new Error("createCanvasElement - missing Canvas implementation for nodejs environment")},n=function(){if(t)return new t;throw new Error("createImageElement - missing Image implementation for nodejs environment")},i=global.fetch||function(){throw new Error("fetch - missing fetch implementation for nodejs environment")},r=zf();return{Canvas:e||class{},CanvasRenderingContext2D:global.CanvasRenderingContext2D||class{},Image:t||class{},ImageData:global.ImageData||class{},Video:global.HTMLVideoElement||class{},createCanvasElement:s,createImageElement:n,fetch:i,...r}}function kx(){return typeof window=="object"&&typeof document!="undefined"&&typeof HTMLImageElement!="undefined"&&typeof HTMLCanvasElement!="undefined"&&typeof HTMLVideoElement!="undefined"&&typeof ImageData!="undefined"&&typeof CanvasRenderingContext2D!="undefined"}const Dx=mc(RL());let Jt;function KV(){if(!Jt)throw new Error("getEnv - environment is not defined, check isNodejs() and isBrowser()");return Jt}function Fx(e){Jt=e}function Mx(){if(kx())return Fx(Ex());if(Dx.isNodejs())return Fx(_x())}function XV(e){if(Jt||Mx(),!Jt)throw new Error("monkeyPatch - environment is not defined, check isNodejs() and isBrowser()");const{Canvas:t=Jt.Canvas,Image:s=Jt.Image}=e;Jt.Canvas=t,Jt.Image=s,Jt.createCanvasElement=e.createCanvasElement||(()=>new t),Jt.createImageElement=e.createImageElement||(()=>new s),Jt.ImageData=e.ImageData||Jt.ImageData,Jt.Video=e.Video||Jt.Video,Jt.fetch=e.fetch||Jt.fetch,Jt.readFile=e.readFile||Jt.readFile}const Ze={getEnv:KV,setEnv:Fx,initialize:Mx,createBrowserEnv:Ex,createFileSystem:zf,createNodejsEnv:_x,monkeyPatch:XV,isBrowser:kx,isNodejs:Dx.isNodejs};Mx();function ya(e){return!Ze.isNodejs()&&typeof e=="string"?document.getElementById(e):e}function Os(e){const{Canvas:t,CanvasRenderingContext2D:s}=Ze.getEnv();if(e instanceof s)return e;const n=ya(e);if(!(n instanceof t))throw new Error("resolveContext2d - expected canvas to be of instance of Canvas");const i=n.getContext("2d");if(!i)throw new Error("resolveContext2d - canvas 2d context is null");return i}var Li;(function(e){e.TOP_LEFT="TOP_LEFT",e.TOP_RIGHT="TOP_RIGHT",e.BOTTOM_LEFT="BOTTOM_LEFT",e.BOTTOM_RIGHT="BOTTOM_RIGHT"})(Li||(Li={}));class Pf{constructor(e={}){const{anchorPosition:t,backgroundColor:s,fontColor:n,fontSize:i,fontStyle:r,padding:o}=e;this.anchorPosition=t||Li.TOP_LEFT,this.backgroundColor=s||"rgba(0, 0, 0, 0.5)",this.fontColor=n||"rgba(255, 255, 255, 1)",this.fontSize=i||14,this.fontStyle=r||"Georgia",this.padding=o||4}}class Jl{constructor(e,t,s={}){this.text=typeof e=="string"?[e]:e instanceof Jl?e.text:e,this.anchor=t,this.options=new Pf(s)}measureWidth(e){const{padding:t}=this.options;return this.text.map(s=>e.measureText(s).width).reduce((s,n)=>s<n?n:s,0)+2*t}measureHeight(){const{fontSize:e,padding:t}=this.options;return this.text.length*e+2*t}getUpperLeft(e,t){const{anchorPosition:s}=this.options,n=s===Li.BOTTOM_RIGHT||s===Li.TOP_RIGHT,i=s===Li.BOTTOM_LEFT||s===Li.BOTTOM_RIGHT,r=this.measureWidth(e),o=this.measureHeight(),a=n?this.anchor.x-r:this.anchor.x,l=i?this.anchor.y-o:this.anchor.y;if(t){const{width:c,height:p}=t,u=Math.max(Math.min(a,c-r),0),h=Math.max(Math.min(l,p-o),0);return{x:u,y:h}}return{x:a,y:l}}draw(e){const t=ya(e),s=Os(t),{backgroundColor:n,fontColor:i,fontSize:r,fontStyle:o,padding:a}=this.options;s.font=`${r}px ${o}`;const l=this.measureWidth(s),c=this.measureHeight();s.fillStyle=n;const p=this.getUpperLeft(s,t);s.fillRect(p.x,p.y,l,c),s.fillStyle=i,this.text.forEach((u,h)=>{const d=a+p.x,m=a+p.y+(h+1)*r;s.fillText(u,d,m)})}}class w1{constructor(e={}){const{boxColor:t,lineWidth:s,label:n,drawLabelOptions:i}=e;this.boxColor=t||"rgba(0, 0, 255, 1)",this.lineWidth=s||2,this.label=n;const r={anchorPosition:Li.BOTTOM_LEFT,backgroundColor:this.boxColor};this.drawLabelOptions=new Pf(Object.assign({},r,i))}}class Ux{constructor(e,t={}){this.box=new lt(e),this.options=new w1(t)}draw(e){const t=Os(e),{boxColor:s,lineWidth:n}=this.options,{x:i,y:r,width:o,height:a}=this.box;t.strokeStyle=s,t.lineWidth=n,t.strokeRect(i,r,o,a);const{label:l}=this.options;l&&new Jl([l],{x:i-n/2,y:r},this.options.drawLabelOptions).draw(e)}}function JV(e,t){const s=Array.isArray(t)?t:[t];s.forEach(n=>{const i=n instanceof Lt?n.score:xi(n)?n.detection.score:void 0,r=n instanceof Lt?n.box:xi(n)?n.detection.box:new lt(n),o=i?`${da(i)}`:void 0;new Ux(r,{label:o}).draw(e)})}function Au(e){const{Image:t,Video:s}=Ze.getEnv();return e instanceof t&&e.complete||e instanceof s&&e.readyState>=3}function $x(e){return new Promise((t,s)=>{if(e instanceof Ze.getEnv().Canvas||Au(e))return t(null);function n(r){if(!r.currentTarget)return;r.currentTarget.removeEventListener("load",n),r.currentTarget.removeEventListener("error",i),t(r)}function i(r){if(!r.currentTarget)return;r.currentTarget.removeEventListener("load",n),r.currentTarget.removeEventListener("error",i),s(r)}e.addEventListener("load",n),e.addEventListener("error",i)})}function Wx(e){return new Promise((t,s)=>{if(!(e instanceof Blob))return s("bufferToImage - expected buf to be of type: Blob");const n=new FileReader;n.onload=()=>{if(typeof n.result!="string")return s("bufferToImage - expected reader.result to be a string, in onload");const i=Ze.getEnv().createImageElement();i.onload=()=>t(i),i.onerror=s,i.src=n.result},n.onerror=s,n.readAsDataURL(e)})}function ba(e){const{Image:t,Video:s}=Ze.getEnv();return e instanceof t?new js(e.naturalWidth,e.naturalHeight):e instanceof s?new js(e.videoWidth,e.videoHeight):new js(e.width,e.height)}function Zl({width:e,height:t}){const{createCanvasElement:s}=Ze.getEnv(),n=s();return n.width=e,n.height=t,n}function Nu(e,t){const{ImageData:s}=Ze.getEnv();if(!(e instanceof s)&&!Au(e))throw new Error("createCanvasFromMedia - media has not finished loading yet");const{width:n,height:i}=t||ba(e),r=Zl({width:n,height:i});return e instanceof s?Os(r).putImageData(e,0,0):Os(r).drawImage(e,0,0,n,i),r}async function zx(e,t){const s=t||Ze.getEnv().createCanvasElement(),[n,i,r]=e.shape.slice(on(e)?1:0),o=C(()=>e.as3D(n,i,r).toInt());return await Fr.toPixels(o,s),o.dispose(),s}function Bf(e){const{Image:t,Canvas:s,Video:n}=Ze.getEnv();return e instanceof t||e instanceof s||e instanceof n}function Px(e,t,s=!1){const{Image:n,Canvas:i}=Ze.getEnv();if(!(e instanceof n||e instanceof i))throw new Error("imageToSquare - expected arg0 to be HTMLImageElement | HTMLCanvasElement");const r=ba(e),o=t/Math.max(r.height,r.width),a=o*r.width,l=o*r.height,c=Zl({width:t,height:t}),p=e instanceof i?e:Nu(e),u=Math.abs(a-l)/2,h=s&&a<l?u:0,d=s&&l<a?u:0;return Os(c).drawImage(p,h,d,a,l),c}class mo{constructor(e,t=!1){if(this._imageTensors=[],this._canvases=[],this._treatAsBatchInput=!1,this._inputDimensions=[],!Array.isArray(e))throw new Error(`NetInput.constructor - expected inputs to be an Array of TResolvedNetInput or to be instanceof tf.Tensor4D, instead have ${e}`);this._treatAsBatchInput=t,this._batchSize=e.length,e.forEach((s,n)=>{if(Zi(s)){this._imageTensors[n]=s,this._inputDimensions[n]=s.shape;return}if(on(s)){const r=s.shape[0];if(r!==1)throw new Error(`NetInput - tf.Tensor4D with batchSize ${r} passed, but not supported in input array`);this._imageTensors[n]=s,this._inputDimensions[n]=s.shape.slice(1);return}const i=s instanceof Ze.getEnv().Canvas?s:Nu(s);this._canvases[n]=i,this._inputDimensions[n]=[i.height,i.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 wi(this.batchSize,0,1).map((e,t)=>this.getReshapedInputDimensions(t))}getInput(e){return this.canvases[e]||this.imageTensors[e]}getInputDimensions(e){return this._inputDimensions[e]}getInputHeight(e){return this._inputDimensions[e][0]}getInputWidth(e){return this._inputDimensions[e][1]}getReshapedInputDimensions(e){if(typeof this.inputSize!="number")throw new Error("getReshapedInputDimensions - inputSize not set, toBatchTensor has not been called yet");const t=this.getInputWidth(e),s=this.getInputHeight(e);return Ax({width:t,height:s},this.inputSize)}toBatchTensor(e,t=!0){return this._inputSize=e,C(()=>{const s=wi(this.batchSize,0,1).map(i=>{const r=this.getInput(i);if(r instanceof me){let o=on(r)?r:r.expandDims();return o=Ox(o,t),(o.shape[1]!==e||o.shape[2]!==e)&&(o=Zs.resizeBilinear(o,[e,e])),o.as3D(e,e,3)}if(r instanceof Ze.getEnv().Canvas)return Fr.fromPixels(Px(r,e,t));throw new Error(`toBatchTensor - at batchIdx ${i}, expected input to be instanceof tf.Tensor or instanceof HTMLCanvasElement, instead have ${r}`)}),n=Ve(s.map(i=>G(i,"float32"))).as4D(this.batchSize,e,e,3);return n})}}async function ct(e){if(e instanceof mo)return e;let t=Array.isArray(e)?e:[e];if(!t.length)throw new Error("toNetInput - empty array passed as input");const s=i=>Array.isArray(e)?` at input index ${i}:`:"",n=t.map(ya);return n.forEach((i,r)=>{if(!Bf(i)&&!Zi(i)&&!on(i))throw typeof t[r]=="string"?new Error(`toNetInput -${s(r)} string passed, but could not resolve HTMLElement for element id ${t[r]}`):new Error(`toNetInput -${s(r)} expected media to be of type HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | tf.Tensor3D, or to be an element id`);if(on(i)){const o=i.shape[0];if(o!==1)throw new Error(`toNetInput -${s(r)} tf.Tensor4D with batchSize ${o} passed, but not supported in input array`)}}),await Promise.all(n.map(i=>Bf(i)&&$x(i))),new mo(n,Array.isArray(e))}async function Ql(e,t){const{Canvas:s}=Ze.getEnv();let n=e;if(!(e instanceof s)){const o=await ct(e);if(o.batchSize>1)throw new Error("extractFaces - batchSize > 1 not supported");const a=o.getInput(0);n=a instanceof s?a:await zx(a)}const i=Os(n),r=t.map(o=>o instanceof Lt?o.forSize(n.width,n.height).box.floor():o).map(o=>o.clipAtImageBorders(n.width,n.height));return r.map(({x:o,y:a,width:l,height:c})=>{const p=Zl({width:l,height:c});return Os(p).putImageData(i.getImageData(o,a,l,c),0,0),p})}async function ec(e,t){if(!Zi(e)&&!on(e))throw new Error("extractFaceTensors - expected image tensor to be 3D or 4D");if(on(e)&&e.shape[0]>1)throw new Error("extractFaceTensors - batchSize > 1 not supported");return C(()=>{const[s,n,i]=e.shape.slice(on(e)?1:0),r=t.map(a=>a instanceof Lt?a.forSize(n,s).box:a).map(a=>a.clipAtImageBorders(n,s)),o=r.map(({x:a,y:l,width:c,height:p})=>Gr(e.as3D(s,n,i),[l,a,0],[p,c,i]));return o})}async function wa(e,t){const s=Ze.getEnv().fetch,n=await s(e,t);if(!(n.status<400))throw new Error(`failed to fetch: (${n.status}) ${n.statusText}, from url: ${n.url}`);return n}async function ZV(e){const t=await wa(e),s=await t.blob();if(!s.type.startsWith("image/"))throw new Error(`fetchImage - expected blob type to be of type image/*, instead have: ${s.type}, for url: ${t.url}`);return Wx(s)}async function Bx(e){return(await wa(e)).json()}async function QV(e){return new Float32Array(await(await wa(e)).arrayBuffer())}function jf(e,t){const s=`${t}-weights_manifest.json`;if(!e)return{modelBaseUri:"",manifestUri:s};if(e==="/")return{modelBaseUri:"/",manifestUri:`/${s}`};const n=e.startsWith("http://")?"http://":e.startsWith("https://")?"https://":"";e=e.replace(n,"");const i=e.split("/").filter(a=>a),r=e.endsWith(".json")?i[i.length-1]:s;let o=n+(e.endsWith(".json")?i.slice(0,i.length-1):i).join("/");return o=e.startsWith("/")?`/${o}`:o,{modelBaseUri:o,manifestUri:o==="/"?`/${r}`:`${o}/${r}`}}async function jx(e,t){const{manifestUri:s,modelBaseUri:n}=jf(e,t);let i=await Bx(s);return Rt.loadWeights(i,n)}function eG(e,t,s=!1){const{width:n,height:i}=s?ba(t):t;return e.width=n,e.height=i,{width:n,height:i}}class cs{constructor(e){this._name=e,this._params=void 0,this._paramMappings=[]}get params(){return this._params}get paramMappings(){return this._paramMappings}get isLoaded(){return!!this.params}getParamFromPath(e){const{obj:t,objProp:s}=this.traversePropertyPath(e);return t[s]}reassignParamFromPath(e,t){const{obj:s,objProp:n}=this.traversePropertyPath(e);s[n].dispose(),s[n]=t}getParamList(){return this._paramMappings.map(({paramPath:e})=>({path:e,tensor:this.getParamFromPath(e)}))}getTrainableParams(){return this.getParamList().filter(e=>e.tensor instanceof oi)}getFrozenParams(){return this.getParamList().filter(e=>!(e.tensor instanceof oi))}variable(){this.getFrozenParams().forEach(({path:e,tensor:t})=>{this.reassignParamFromPath(e,t.variable())})}freeze(){this.getTrainableParams().forEach(({path:e,tensor:t})=>{const s=ze(t.dataSync());t.dispose(),this.reassignParamFromPath(e,s)})}dispose(e=!0){this.getParamList().forEach(t=>{if(e&&t.tensor.isDisposed)throw new Error(`param tensor has already been disposed for path ${t.path}`);t.tensor.dispose()}),this._params=void 0}serializeParams(){return new Float32Array(this.getParamList().map(({tensor:e})=>Array.from(e.dataSync())).reduce((e,t)=>e.concat(t)))}async load(e){if(e instanceof Float32Array){this.extractWeights(e);return}await this.loadFromUri(e)}async loadFromUri(e){if(e&&typeof e!="string")throw new Error(`${this._name}.loadFromUri - expected model uri`);const t=await jx(e,this.getDefaultModelName());this.loadFromWeightMap(t)}async loadFromDisk(e){if(e&&typeof e!="string")throw new Error(`${this._name}.loadFromDisk - expected model file path`);const{readFile:t}=Ze.getEnv(),{manifestUri:s,modelBaseUri:n}=jf(e,this.getDefaultModelName()),i=l=>Promise.all(l.map(c=>t(c).then(p=>p.buffer))),r=Rt.weightsLoaderFactory(i),o=JSON.parse((await t(s)).toString()),a=await r(o,n);this.loadFromWeightMap(a)}loadFromWeightMap(e){const{paramMappings:t,params:s}=this.extractParamsFromWeigthMap(e);this._paramMappings=t,this._params=s}extractWeights(e){const{paramMappings:t,params:s}=this.extractParams(e);this._paramMappings=t,this._params=s}traversePropertyPath(e){if(!this.params)throw new Error("traversePropertyPath - model has no loaded params");const t=e.split("/").reduce((i,r)=>{if(!i.nextObj.hasOwnProperty(r))throw new Error(`traversePropertyPath - object does not have property ${r}, for path ${e}`);return{obj:i.nextObj,objProp:r,nextObj:i.nextObj[r]}},{nextObj:this.params}),{obj:s,objProp:n}=t;if(!s||!n||!(s[n]instanceof me))throw new Error(`traversePropertyPath - parameter is not a tensor, for path ${e}`);return{obj:s,objProp:n}}}function Es(e,t,s){return C(()=>{let n=Vr(e,t.depthwise_filter,t.pointwise_filter,s,"same");return n=$(n,t.bias),n})}function Vf(e,t,s=!1){return C(()=>{const n=De(s?$(nt(e,t.conv0.filters,[2,2],"same"),t.conv0.bias):Es(e,t.conv0,[2,2])),i=Es(n,t.conv1,[1,1]),r=De($(n,i)),o=Es(r,t.conv2,[1,1]);return De($(n,$(i,o)))})}function Cu(e,t,s=!1,n=!0){return C(()=>{const i=De(s?$(nt(e,t.conv0.filters,n?[2,2]:[1,1],"same"),t.conv0.bias):Es(e,t.conv0,n?[2,2]:[1,1])),r=Es(i,t.conv1,[1,1]),o=De($(i,r)),a=Es(o,t.conv2,[1,1]),l=De($(i,$(r,a))),c=Es(l,t.conv3,[1,1]);return De($(i,$(r,$(a,c))))})}function xa(e,t,s="same",n=!1){return C(()=>{const i=$(nt(e,t.filters,[1,1],s),t.bias);return n?De(i):i})}function Ss(e,t){Object.keys(e).forEach(s=>{t.some(n=>n.originalPath===s)||e[s].dispose()})}function tc(e,t){return function(s,n,i,r){const o=ts(e(s*n*i*i),[i,i,s,n]),a=Oe(e(n));return t.push({paramPath:`${r}/filters`},{paramPath:`${r}/bias`}),{filters:o,bias:a}}}function Gf(e,t){return function(s,n,i){const r=as(e(s*n),[s,n]),o=Oe(e(n));return t.push({paramPath:`${i}/weights`},{paramPath:`${i}/bias`}),{weights:r,bias:o}}}class Vx{constructor(e,t,s){this.depthwise_filter=e,this.pointwise_filter=t,this.bias=s}}function sc(e,t){return function(s,n,i){const r=ts(e(3*3*s),[3,3,s,1]),o=ts(e(s*n),[1,1,s,n]),a=Oe(e(n));return t.push({paramPath:`${i}/depthwise_filter`},{paramPath:`${i}/pointwise_filter`},{paramPath:`${i}/bias`}),new Vx(r,o,a)}}function nc(e){return function(t){const s=e(`${t}/depthwise_filter`,4),n=e(`${t}/pointwise_filter`,4),i=e(`${t}/bias`,1);return new Vx(s,n,i)}}function Vs(e,t){return function(s,n,i){const r=e[s];if(!ha(r,n))throw new Error(`expected weightMap[${s}] to be a Tensor${n}D, instead have ${r}`);return t.push({originalPath:s,paramPath:i||s}),r}}function Is(e){let t=e;function s(i){const r=t.slice(0,i);return t=t.slice(i),r}function n(){return t}return{extractWeights:s,getRemainingWeights:n}}function qf(e,t){const s=tc(e,t),n=sc(e,t);function i(o,a,l,c=!1){const p=c?s(o,a,3,`${l}/conv0`):n(o,a,`${l}/conv0`),u=n(a,a,`${l}/conv1`),h=n(a,a,`${l}/conv2`);return{conv0:p,conv1:u,conv2:h}}function r(o,a,l,c=!1){const{conv0:p,conv1:u,conv2:h}=i(o,a,l,c),d=n(a,a,`${l}/conv3`);return{conv0:p,conv1:u,conv2:h,conv3:d}}return{extractDenseBlock3Params:i,extractDenseBlock4Params:r}}function x1(e){const t=[],{extractWeights:s,getRemainingWeights:n}=Is(e),{extractDenseBlock4Params:i}=qf(s,t),r=i(3,32,"dense0",!0),o=i(32,64,"dense1"),a=i(64,128,"dense2"),l=i(128,256,"dense3");if(n().length!==0)throw new Error(`weights remaing after extract: ${n().length}`);return{paramMappings:t,params:{dense0:r,dense1:o,dense2:a,dense3:l}}}function Hf(e){return function(t){const s=e(`${t}/filters`,4),n=e(`${t}/bias`,1);return{filters:s,bias:n}}}function Yf(e,t){const s=Vs(e,t),n=Hf(s),i=nc(s);function r(a,l=!1){const c=l?n(`${a}/conv0`):i(`${a}/conv0`),p=i(`${a}/conv1`),u=i(`${a}/conv2`);return{conv0:c,conv1:p,conv2:u}}function o(a,l=!1){const c=l?n(`${a}/conv0`):i(`${a}/conv0`),p=i(`${a}/conv1`),u=i(`${a}/conv2`),h=i(`${a}/conv3`);return{conv0:c,conv1:p,conv2:u,conv3:h}}return{extractDenseBlock3Params:r,extractDenseBlock4Params:o}}function L1(e){const t=[],{extractDenseBlock4Params:s}=Yf(e,t),n={dense0:s("dense0",!0),dense1:s("dense1"),dense2:s("dense2"),dense3:s("dense3")};return Ss(e,t),{params:n,paramMappings:t}}class Kf extends cs{constructor(){super("FaceFeatureExtractor")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("FaceFeatureExtractor - load model before inference");return C(()=>{const s=e.toBatchTensor(112,!0),n=[122.782,117.001,104.298],i=Gn(s,n).div(j(255));let r=Cu(i,t.dense0,!0);return r=Cu(r,t.dense1),r=Cu(r,t.dense2),r=Cu(r,t.dense3),r=hs(r,[7,7],[2,2],"valid"),r})}async forward(e){return this.forwardInput(await ct(e))}getDefaultModelName(){return"face_feature_extractor_model"}extractParamsFromWeigthMap(e){return L1(e)}extractParams(e){return x1(e)}}function Ru(e,t){return C(()=>$(Te(e,t.weights),t.bias))}function S1(e,t,s){const n=[],{extractWeights:i,getRemainingWeights:r}=Is(e),o=Gf(i,n),a=o(t,s,"fc");if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{paramMappings:n,params:{fc:a}}}function I1(e){const t=[],s=Vs(e,t);function n(r){const o=s(`${r}/weights`,2),a=s(`${r}/bias`,1);return{weights:o,bias:a}}const i={fc:n("fc")};return Ss(e,t),{params:i,paramMappings:t}}function Xf(e){const t={},s={};return Object.keys(e).forEach(n=>{const i=n.startsWith("fc")?s:t;i[n]=e[n]}),{featureExtractorMap:t,classifierMap:s}}class Jf extends cs{constructor(e,t){super(e);this._faceFeatureExtractor=t}get faceFeatureExtractor(){return this._faceFeatureExtractor}runNet(e){const{params:t}=this;if(!t)throw new Error(`${this._name} - load model before inference`);return C(()=>{const s=e instanceof mo?this.faceFeatureExtractor.forwardInput(e):e;return Ru(s.as2D(s.shape[0],-1),t.fc)})}dispose(e=!0){this.faceFeatureExtractor.dispose(e),super.dispose(e)}loadClassifierParams(e){const{params:t,paramMappings:s}=this.extractClassifierParams(e);this._params=t,this._paramMappings=s}extractClassifierParams(e){return S1(e,this.getClassifierChannelsIn(),this.getClassifierChannelsOut())}extractParamsFromWeigthMap(e){const{featureExtractorMap:t,classifierMap:s}=Xf(e);return this.faceFeatureExtractor.loadFromWeightMap(t),I1(s)}extractParams(e){const t=this.getClassifierChannelsIn(),s=this.getClassifierChannelsOut(),n=s*t+s,i=e.slice(0,e.length-n),r=e.slice(e.length-n);return this.faceFeatureExtractor.extractWeights(i),this.extractClassifierParams(r)}}const Gx=["neutral","happy","sad","angry","fearful","disgusted","surprised"];class La{constructor(e){if(e.length!==7)throw new Error(`FaceExpressions.constructor - expected probabilities.length to be 7, have: ${e.length}`);Gx.forEach((t,s)=>{this[t]=e[s]})}asSortedArray(){return Gx.map(e=>({expression:e,probability:this[e]})).sort((e,t)=>t.probability-e.probability)}}class qx extends Jf{constructor(e=new Kf){super("FaceExpressionNet",e)}forwardInput(e){return C(()=>es(this.runNet(e)))}async forward(e){return this.forwardInput(await ct(e))}async predictExpressions(e){const t=await ct(e),s=await this.forwardInput(t),n=await Promise.all(Ge(s).map(async r=>{const o=await r.data();return r.dispose(),o}));s.dispose();const i=n.map(r=>new La(r));return t.isBatchInput?i:i[0]}getDefaultModelName(){return"face_expression_model"}getClassifierChannelsIn(){return 256}getClassifierChannelsOut(){return 7}}function Hx(e){return e.expressions instanceof La}function Zf(e,t){const s={expressions:t};return Object.assign({},e,s)}function tG(e,t,s=.1,n){const i=Array.isArray(t)?t:[t];i.forEach(r=>{const o=r instanceof La?r:Hx(r)?r.expressions:void 0;if(!o)throw new Error("drawFaceExpressions - expected faceExpressions to be FaceExpressions | WithFaceExpressions<{}> or array thereof");const a=o.asSortedArray(),l=a.filter(u=>u.probability>s),c=xi(r)?r.detection.box.bottomLeft:n||new Fe(0,0),p=new Jl(l.map(u=>`${u.expression} (${da(u.probability)})`),c);p.draw(e)})}function Sa(e){return xi(e)&&e.landmarks instanceof On&&e.unshiftedLandmarks instanceof On&&e.alignedRect instanceof Lt}function ic(e,t){const{box:s}=e.detection,n=t.shiftBy(s.x,s.y),i=n.align(),{imageDims:r}=e.detection,o=new Lt(e.detection.score,i.rescale(r.reverse()),r),a={landmarks:n,unshiftedLandmarks:t,alignedRect:o};return Object.assign({},e,a)}class v1{constructor(e={}){const{drawLines:t=!0,drawPoints:s=!0,lineWidth:n,lineColor:i,pointSize:r,pointColor:o}=e;this.drawLines=t,this.drawPoints=s,this.lineWidth=n||1,this.pointSize=r||2,this.lineColor=i||"rgba(0, 255, 255, 1)",this.pointColor=o||"rgba(255, 0, 255, 1)"}}class T1{constructor(e,t={}){this.faceLandmarks=e,this.options=new v1(t)}draw(e){const t=Os(e),{drawLines:s,drawPoints:n,lineWidth:i,lineColor:r,pointSize:o,pointColor:a}=this.options;if(s&&this.faceLandmarks instanceof Tu&&(t.strokeStyle=r,t.lineWidth=i,Ji(t,this.faceLandmarks.getJawOutline()),Ji(t,this.faceLandmarks.getLeftEyeBrow()),Ji(t,this.faceLandmarks.getRightEyeBrow()),Ji(t,this.faceLandmarks.getNose()),Ji(t,this.faceLandmarks.getLeftEye(),!0),Ji(t,this.faceLandmarks.getRightEye(),!0),Ji(t,this.faceLandmarks.getMouth(),!0)),n){t.strokeStyle=a,t.fillStyle=a;const l=c=>{t.beginPath(),t.arc(c.x,c.y,o,0,2*Math.PI),t.fill()};this.faceLandmarks.positions.forEach(l)}}}function sG(e,t){const s=Array.isArray(t)?t:[t];s.forEach(n=>{const i=n instanceof On?n:Sa(n)?n.landmarks:void 0;if(!i)throw new Error("drawFaceLandmarks - expected faceExpressions to be FaceLandmarks | WithFaceLandmarks<WithFaceDetection<{}>> or array thereof");new T1(i).draw(e)})}const Yx={};Ee(Yx,{AnchorPosition:()=>Li,DrawBox:()=>Ux,DrawBoxOptions:()=>w1,DrawFaceLandmarks:()=>T1,DrawFaceLandmarksOptions:()=>v1,DrawTextField:()=>Jl,DrawTextFieldOptions:()=>Pf,drawContour:()=>Ji,drawDetections:()=>JV,drawFaceExpressions:()=>tG,drawFaceLandmarks:()=>sG});function nG(e,t){const s=tc(e,t),n=sc(e,t);function i(o,a,l){const c=n(o,a,`${l}/separable_conv0`),p=n(a,a,`${l}/separable_conv1`),u=s(o,a,1,`${l}/expansion_conv`);return{separable_conv0:c,separable_conv1:p,expansion_conv:u}}function r(o,a){const l=n(o,o,`${a}/separable_conv0`),c=n(o,o,`${a}/separable_conv1`),p=n(o,o,`${a}/separable_conv2`);return{separable_conv0:l,separable_conv1:c,separable_conv2:p}}return{extractConvParams:s,extractSeparableConvParams:n,extractReductionBlockParams:i,extractMainBlockParams:r}}function A1(e,t){const s=[],{extractWeights:n,getRemainingWeights:i}=Is(e),{extractConvParams:r,extractSeparableConvParams:o,extractReductionBlockParams:a,extractMainBlockParams:l}=nG(n,s),c=r(3,32,3,"entry_flow/conv_in"),p=a(32,64,"entry_flow/reduction_block_0"),u=a(64,128,"entry_flow/reduction_block_1"),h={conv_in:c,reduction_block_0:p,reduction_block_1:u},d={};wi(t,0,1).forEach(y=>{d[`main_block_${y}`]=l(128,`middle_flow/main_block_${y}`)});const m=a(128,256,"exit_flow/reduction_block"),f=o(256,512,"exit_flow/separable_conv"),g={reduction_block:m,separable_conv:f};if(i().length!==0)throw new Error(`weights remaing after extract: ${i().length}`);return{paramMappings:s,params:{entry_flow:h,middle_flow:d,exit_flow:g}}}function iG(e,t){const s=Vs(e,t),n=Hf(s),i=nc(s);function r(a){const l=i(`${a}/separable_conv0`),c=i(`${a}/separable_conv1`),p=n(`${a}/expansion_conv`);return{separable_conv0:l,separable_conv1:c,expansion_conv:p}}function o(a){const l=i(`${a}/separable_conv0`),c=i(`${a}/separable_conv1`),p=i(`${a}/separable_conv2`);return{separable_conv0:l,separable_conv1:c,separable_conv2:p}}return{extractConvParams:n,extractSeparableConvParams:i,extractReductionBlockParams:r,extractMainBlockParams:o}}function N1(e,t){const s=[],{extractConvParams:n,extractSeparableConvParams:i,extractReductionBlockParams:r,extractMainBlockParams:o}=iG(e,s),a=n("entry_flow/conv_in"),l=r("entry_flow/reduction_block_0"),c=r("entry_flow/reduction_block_1"),p={conv_in:a,reduction_block_0:l,reduction_block_1:c},u={};wi(t,0,1).forEach(f=>{u[`main_block_${f}`]=o(`middle_flow/main_block_${f}`)});const h=r("exit_flow/reduction_block"),d=i("exit_flow/separable_conv"),m={reduction_block:h,separable_conv:d};return Ss(e,s),{params:{entry_flow:p,middle_flow:u,exit_flow:m},paramMappings:s}}function C1(e,t,s){return $(nt(e,t.filters,s,"same"),t.bias)}function Kx(e,t,s=!0){let n=s?De(e):e;return n=Es(n,t.separable_conv0,[1,1]),n=Es(De(n),t.separable_conv1,[1,1]),n=mt(n,[3,3],[2,2],"same"),n=$(n,C1(e,t.expansion_conv,[2,2])),n}function rG(e,t){let s=Es(De(e),t.separable_conv0,[1,1]);return s=Es(De(s),t.separable_conv1,[1,1]),s=Es(De(s),t.separable_conv2,[1,1]),s=$(s,e),s}class R1 extends cs{constructor(e){super("TinyXception");this._numMainBlocks=e}forwardInput(e){const{params:t}=this;if(!t)throw new Error("TinyXception - load model before inference");return C(()=>{const s=e.toBatchTensor(112,!0),n=[122.782,117.001,104.298],i=Gn(s,n).div(j(256));let r=De(C1(i,t.entry_flow.conv_in,[2,2]));return r=Kx(r,t.entry_flow.reduction_block_0,!1),r=Kx(r,t.entry_flow.reduction_block_1),wi(this._numMainBlocks,0,1).forEach(o=>{r=rG(r,t.middle_flow[`main_block_${o}`])}),r=Kx(r,t.exit_flow.reduction_block),r=De(Es(r,t.exit_flow.separable_conv,[1,1])),r})}async forward(e){return this.forwardInput(await ct(e))}getDefaultModelName(){return"tiny_xception_model"}extractParamsFromWeigthMap(e){return N1(e,this._numMainBlocks)}extractParams(e){return A1(e,this._numMainBlocks)}}function O1(e){const t=[],{extractWeights:s,getRemainingWeights:n}=Is(e),i=Gf(s,t),r=i(512,1,"fc/age"),o=i(512,2,"fc/gender");if(n().length!==0)throw new Error(`weights remaing after extract: ${n().length}`);return{paramMappings:t,params:{fc:{age:r,gender:o}}}}function E1(e){const t=[],s=Vs(e,t);function n(r){const o=s(`${r}/weights`,2),a=s(`${r}/bias`,1);return{weights:o,bias:a}}const i={fc:{age:n("fc/age"),gender:n("fc/gender")}};return Ss(e,t),{params:i,paramMappings:t}}var Qi;(function(e){e.FEMALE="female",e.MALE="male"})(Qi||(Qi={}));class Xx extends cs{constructor(e=new R1(2)){super("AgeGenderNet");this._faceFeatureExtractor=e}get faceFeatureExtractor(){return this._faceFeatureExtractor}runNet(e){const{params:t}=this;if(!t)throw new Error(`${this._name} - load model before inference`);return C(()=>{const s=e instanceof mo?this.faceFeatureExtractor.forwardInput(e):e,n=hs(s,[7,7],[2,2],"valid").as2D(s.shape[0],-1),i=Ru(n,t.fc.age).as1D(),r=Ru(n,t.fc.gender);return{age:i,gender:r}})}forwardInput(e){return C(()=>{const{age:t,gender:s}=this.runNet(e);return{age:t,gender:es(s)}})}async forward(e){return this.forwardInput(await ct(e))}async predictAgeAndGender(e){const t=await ct(e),s=await this.forwardInput(t),n=Ge(s.age),i=Ge(s.gender),r=n.map((a,l)=>({ageTensor:a,genderTensor:i[l]})),o=await Promise.all(r.map(async({ageTensor:a,genderTensor:l})=>{const c=(await a.data())[0],p=(await l.data())[0],u=p>.5,h=u?Qi.MALE:Qi.FEMALE,d=u?p:1-p;return a.dispose(),l.dispose(),{age:c,gender:h,genderProbability:d}}));return s.age.dispose(),s.gender.dispose(),t.isBatchInput?o:o[0]}getDefaultModelName(){return"age_gender_model"}dispose(e=!0){this.faceFeatureExtractor.dispose(e),super.dispose(e)}loadClassifierParams(e){const{params:t,paramMappings:s}=this.extractClassifierParams(e);this._params=t,this._paramMappings=s}extractClassifierParams(e){return O1(e)}extractParamsFromWeigthMap(e){const{featureExtractorMap:t,classifierMap:s}=Xf(e);return this.faceFeatureExtractor.loadFromWeightMap(t),E1(s)}extractParams(e){const t=512*1+1+(512*2+2),s=e.slice(0,e.length-t),n=e.slice(e.length-t);return this.faceFeatureExtractor.extractWeights(s),this.extractClassifierParams(n)}}class Qf extends Jf{postProcess(e,t,s){const n=s.map(({width:r,height:o})=>{const a=t/Math.max(o,r);return{width:r*a,height:o*a}}),i=n.length;return C(()=>{const r=(p,u)=>Ve([Wt([68],p),Wt([68],u)],1).as2D(1,136).as1D(),o=(p,u)=>{const{width:h,height:d}=n[p];return u(h,d)?Math.abs(h-d)/2:0},a=p=>o(p,(u,h)=>u<h),l=p=>o(p,(u,h)=>h<u),c=e.mul(Wt([i,136],t)).sub(Ve(Array.from(Array(i),(p,u)=>r(a(u),l(u))))).div(Ve(Array.from(Array(i),(p,u)=>r(n[u].width,n[u].height))));return c})}forwardInput(e){return C(()=>{const t=this.runNet(e);return this.postProcess(t,e.inputSize,e.inputDimensions.map(([s,n])=>({height:s,width:n})))})}async forward(e){return this.forwardInput(await ct(e))}async detectLandmarks(e){const t=await ct(e),s=C(()=>Ge(this.forwardInput(t))),n=await Promise.all(s.map(async(i,r)=>{const o=Array.from(await i.data()),a=o.filter((c,p)=>Mf(p)),l=o.filter((c,p)=>!Mf(p));return new Tu(Array(68).fill(0).map((c,p)=>new Fe(a[p],l[p])),{height:t.getInputHeight(r),width:t.getInputWidth(r)})}));return s.forEach(i=>i.dispose()),t.isBatchInput?n:n[0]}getClassifierChannelsOut(){return 136}}class Ou extends Qf{constructor(e=new Kf){super("FaceLandmark68Net",e)}getDefaultModelName(){return"face_landmark_68_model"}getClassifierChannelsIn(){return 256}}function _1(e){const t=[],{extractDenseBlock3Params:s}=Yf(e,t),n={dense0:s("dense0",!0),dense1:s("dense1"),dense2:s("dense2")};return Ss(e,t),{params:n,paramMappings:t}}function k1(e){const t=[],{extractWeights:s,getRemainingWeights:n}=Is(e),{extractDenseBlock3Params:i}=qf(s,t),r=i(3,32,"dense0",!0),o=i(32,64,"dense1"),a=i(64,128,"dense2");if(n().length!==0)throw new Error(`weights remaing after extract: ${n().length}`);return{paramMappings:t,params:{dense0:r,dense1:o,dense2:a}}}class D1 extends cs{constructor(){super("TinyFaceFeatureExtractor")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("TinyFaceFeatureExtractor - load model before inference");return C(()=>{const s=e.toBatchTensor(112,!0),n=[122.782,117.001,104.298],i=Gn(s,n).div(j(255));let r=Vf(i,t.dense0,!0);return r=Vf(r,t.dense1),r=Vf(r,t.dense2),r=hs(r,[14,14],[2,2],"valid"),r})}async forward(e){return this.forwardInput(await ct(e))}getDefaultModelName(){return"face_feature_extractor_tiny_model"}extractParamsFromWeigthMap(e){return _1(e)}extractParams(e){return k1(e)}}class Jx extends Qf{constructor(e=new D1){super("FaceLandmark68TinyNet",e)}getDefaultModelName(){return"face_landmark_68_tiny_model"}getClassifierChannelsIn(){return 128}}class oG extends Ou{}function F1(e,t){return $(R(e,t.weights),t.biases)}function Zx(e,t,s,n,i="same"){const{filters:r,bias:o}=t.conv;let a=nt(e,r,s,i);return a=$(a,o),a=F1(a,t.scale),n?De(a):a}function M1(e,t){return Zx(e,t,[1,1],!0)}function Qx(e,t){return Zx(e,t,[1,1],!1)}function eg(e,t){return Zx(e,t,[2,2],!0,"valid")}function aG(e,t){function s(a,l,c){const p=e(a),u=p.length/(l*c*c);if(Tx(u))throw new Error(`depth has to be an integer: ${u}, weights.length: ${p.length}, numFilters: ${l}, filterSize: ${c}`);return C(()=>se(ts(p,[l,u,c,c]),[2,3,1,0]))}function n(a,l,c,p){const u=s(a,l,c),h=Oe(e(l));return t.push({paramPath:`${p}/filters`},{paramPath:`${p}/bias`}),{filters:u,bias:h}}function i(a,l){const c=Oe(e(a)),p=Oe(e(a));return t.push({paramPath:`${l}/weights`},{paramPath:`${l}/biases`}),{weights:c,biases:p}}function r(a,l,c,p){const u=n(a,l,c,`${p}/conv`),h=i(l,`${p}/scale`);return{conv:u,scale:h}}function o(a,l,c,p,u=!1){const h=r((u?.5:1)*a,l,c,`${p}/conv1`),d=r(a,l,c,`${p}/conv2`);return{conv1:h,conv2:d}}return{extractConvLayerParams:r,extractResidualLayerParams:o}}function U1(e){const{extractWeights:t,getRemainingWeights:s}=Is(e),n=[],{extractConvLayerParams:i,extractResidualLayerParams:r}=aG(t,n),o=i(4704,32,7,"conv32_down"),a=r(9216,32,3,"conv32_1"),l=r(9216,32,3,"conv32_2"),c=r(9216,32,3,"conv32_3"),p=r(36864,64,3,"conv64_down",!0),u=r(36864,64,3,"conv64_1"),h=r(36864,64,3,"conv64_2"),d=r(36864,64,3,"conv64_3"),m=r(147456,128,3,"conv128_down",!0),f=r(147456,128,3,"conv128_1"),g=r(147456,128,3,"conv128_2"),y=r(589824,256,3,"conv256_down",!0),w=r(589824,256,3,"conv256_1"),x=r(589824,256,3,"conv256_2"),T=r(589824,256,3,"conv256_down_out"),A=C(()=>se(as(t(256*128),[128,256]),[1,0]));if(n.push({paramPath:"fc"}),s().length!==0)throw new Error(`weights remaing after extract: ${s().length}`);const _={conv32_down:o,conv32_1:a,conv32_2:l,conv32_3:c,conv64_down:p,conv64_1:u,conv64_2:h,conv64_3:d,conv128_down:m,conv128_1:f,conv128_2:g,conv256_down:y,conv256_1:w,conv256_2:x,conv256_down_out:T,fc:A};return{params:_,paramMappings:n}}function lG(e,t){const s=Vs(e,t);function n(o){const a=s(`${o}/scale/weights`,1),l=s(`${o}/scale/biases`,1);return{weights:a,biases:l}}function i(o){const a=s(`${o}/conv/filters`,4),l=s(`${o}/conv/bias`,1),c=n(o);return{conv:{filters:a,bias:l},scale:c}}function r(o){return{conv1:i(`${o}/conv1`),conv2:i(`${o}/conv2`)}}return{extractConvLayerParams:i,extractResidualLayerParams:r}}function $1(e){const t=[],{extractConvLayerParams:s,extractResidualLayerParams:n}=lG(e,t),i=s("conv32_down"),r=n("conv32_1"),o=n("conv32_2"),a=n("conv32_3"),l=n("conv64_down"),c=n("conv64_1"),p=n("conv64_2"),u=n("conv64_3"),h=n("conv128_down"),d=n("conv128_1"),m=n("conv128_2"),f=n("conv256_down"),g=n("conv256_1"),y=n("conv256_2"),w=n("conv256_down_out"),x=e.fc;if(t.push({originalPath:"fc",paramPath:"fc"}),!vx(x))throw new Error(`expected weightMap[fc] to be a Tensor2D, instead have ${x}`);const T={conv32_down:i,conv32_1:r,conv32_2:o,conv32_3:a,conv64_down:l,conv64_1:c,conv64_2:p,conv64_3:u,conv128_down:h,conv128_1:d,conv128_2:m,conv256_down:f,conv256_1:g,conv256_2:y,conv256_down_out:w,fc:x};return Ss(e,t),{params:T,paramMappings:t}}function qn(e,t){let s=M1(e,t.conv1);return s=Qx(s,t.conv2),s=$(s,e),s=De(s),s}function Eu(e,t){let s=eg(e,t.conv1);s=Qx(s,t.conv2);let n=hs(e,2,2,"valid");const i=ye(n.shape),r=n.shape[3]!==s.shape[3],o=n.shape[1]!==s.shape[1]||n.shape[2]!==s.shape[2];if(o){const a=[...s.shape];a[1]=1;const l=ye(a);s=be([s,l],1);const c=[...s.shape];c[2]=1;const p=ye(c);s=be([s,p],2)}return n=r?be([n,i],3):n,s=$(n,s),s=De(s),s}class _u extends cs{constructor(){super("FaceRecognitionNet")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("FaceRecognitionNet - load model before inference");return C(()=>{const s=G(e.toBatchTensor(150,!0),"float32"),n=[122.782,117.001,104.298],i=Gn(s,n).div(j(256));let r=eg(i,t.conv32_down);r=mt(r,3,2,"valid"),r=qn(r,t.conv32_1),r=qn(r,t.conv32_2),r=qn(r,t.conv32_3),r=Eu(r,t.conv64_down),r=qn(r,t.conv64_1),r=qn(r,t.conv64_2),r=qn(r,t.conv64_3),r=Eu(r,t.conv128_down),r=qn(r,t.conv128_1),r=qn(r,t.conv128_2),r=Eu(r,t.conv256_down),r=qn(r,t.conv256_1),r=qn(r,t.conv256_2),r=Eu(r,t.conv256_down_out);const o=r.mean([1,2]),a=Te(o,t.fc);return a})}async forward(e){return this.forwardInput(await ct(e))}async computeFaceDescriptor(e){const t=await ct(e),s=C(()=>Ge(this.forwardInput(t))),n=await Promise.all(s.map(i=>i.data()));return s.forEach(i=>i.dispose()),t.isBatchInput?n:n[0]}getDefaultModelName(){return"face_recognition_model"}extractParamsFromWeigthMap(e){return $1(e)}extractParams(e){return U1(e)}}function cG(e){const t=new _u;return t.extractWeights(e),t}function tg(e,t){const s={descriptor:t};return Object.assign({},e,s)}function pG(e){return typeof e.age=="number"}function sg(e,t){const s={age:t};return Object.assign({},e,s)}function uG(e){return(e.gender===Qi.MALE||e.gender===Qi.FEMALE)&&Kl(e.genderProbability)}function ng(e,t,s){const n={gender:t,genderProbability:s};return Object.assign({},e,n)}function hG(e,t){function s(l,c){const p=ts(e(3*3*l),[3,3,l,1]),u=Oe(e(l)),h=Oe(e(l)),d=Oe(e(l)),m=Oe(e(l));return t.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:p,batch_norm_scale:u,batch_norm_offset:h,batch_norm_mean:d,batch_norm_variance:m}}function n(l,c,p,u,h){const d=ts(e(l*c*p*p),[p,p,l,c]),m=Oe(e(c));return t.push({paramPath:`${u}/filters`},{paramPath:`${u}/${h?"batch_norm_offset":"bias"}`}),{filters:d,bias:m}}function i(l,c,p,u){const{filters:h,bias:d}=n(l,c,p,u,!0);return{filters:h,batch_norm_offset:d}}function r(l,c,p){const u=s(l,`${p}/depthwise_conv`),h=i(l,c,1,`${p}/pointwise_conv`);return{depthwise_conv:u,pointwise_conv:h}}function o(){const l=i(3,32,3,"mobilenetv1/conv_0"),c=r(32,64,"mobilenetv1/conv_1"),p=r(64,128,"mobilenetv1/conv_2"),u=r(128,128,"mobilenetv1/conv_3"),h=r(128,256,"mobilenetv1/conv_4"),d=r(256,256,"mobilenetv1/conv_5"),m=r(256,512,"mobilenetv1/conv_6"),f=r(512,512,"mobilenetv1/conv_7"),g=r(512,512,"mobilenetv1/conv_8"),y=r(512,512,"mobilenetv1/conv_9"),w=r(512,512,"mobilenetv1/conv_10"),x=r(512,512,"mobilenetv1/conv_11"),T=r(512,1024,"mobilenetv1/conv_12"),A=r(1024,1024,"mobilenetv1/conv_13");return{conv_0:l,conv_1:c,conv_2:p,conv_3:u,conv_4:h,conv_5:d,conv_6:m,conv_7:f,conv_8:g,conv_9:y,conv_10:w,conv_11:x,conv_12:T,conv_13:A}}function a(){const l=i(1024,256,1,"prediction_layer/conv_0"),c=i(256,512,3,"prediction_layer/conv_1"),p=i(512,128,1,"prediction_layer/conv_2"),u=i(128,256,3,"prediction_layer/conv_3"),h=i(256,128,1,"prediction_layer/conv_4"),d=i(128,256,3,"prediction_layer/conv_5"),m=i(256,64,1,"prediction_layer/conv_6"),f=i(64,128,3,"prediction_layer/conv_7"),g=n(512,12,1,"prediction_layer/box_predictor_0/box_encoding_predictor"),y=n(512,9,1,"prediction_layer/box_predictor_0/class_predictor"),w=n(1024,24,1,"prediction_layer/box_predictor_1/box_encoding_predictor"),x=n(1024,18,1,"prediction_layer/box_predictor_1/class_predictor"),T=n(512,24,1,"prediction_layer/box_predictor_2/box_encoding_predictor"),A=n(512,18,1,"prediction_layer/box_predictor_2/class_predictor"),_=n(256,24,1,"prediction_layer/box_predictor_3/box_encoding_predictor"),E=n(256,18,1,"prediction_layer/box_predictor_3/class_predictor"),F=n(256,24,1,"prediction_layer/box_predictor_4/box_encoding_predictor"),D=n(256,18,1,"prediction_layer/box_predictor_4/class_predictor"),M=n(128,24,1,"prediction_layer/box_predictor_5/box_encoding_predictor"),P=n(128,18,1,"prediction_layer/box_predictor_5/class_predictor"),B={box_encoding_predictor:g,class_predictor:y},Y={box_encoding_predictor:w,class_predictor:x},q={box_encoding_predictor:T,class_predictor:A},K={box_encoding_predictor:_,class_predictor:E},H={box_encoding_predictor:F,class_predictor:D},Q={box_encoding_predictor:M,class_predictor:P};return{conv_0:l,conv_1:c,conv_2:p,conv_3:u,conv_4:h,conv_5:d,conv_6:m,conv_7:f,box_predictor_0:B,box_predictor_1:Y,box_predictor_2:q,box_predictor_3:K,box_predictor_4:H,box_predictor_5:Q}}return{extractMobilenetV1Params:o,extractPredictionLayerParams:a}}function W1(e){const t=[],{extractWeights:s,getRemainingWeights:n}=Is(e),{extractMobilenetV1Params:i,extractPredictionLayerParams:r}=hG(s,t),o=i(),a=r(),l=qa(s(5118*4),[1,5118,4]),c={extra_dim:l};if(t.push({paramPath:"output_layer/extra_dim"}),n().length!==0)throw new Error(`weights remaing after extract: ${n().length}`);return{params:{mobilenetv1:o,prediction_layer:a,output_layer:c},paramMappings:t}}function dG(e,t){const s=Vs(e,t);function n(c,p,u){const h=s(`${c}/Conv2d_${p}_pointwise/weights`,4,`${u}/filters`),d=s(`${c}/Conv2d_${p}_pointwise/convolution_bn_offset`,1,`${u}/batch_norm_offset`);return{filters:h,batch_norm_offset:d}}function i(c){const p=`mobilenetv1/conv_${c}`,u=`MobilenetV1/Conv2d_${c}_depthwise`,h=`${p}/depthwise_conv`,d=`${p}/pointwise_conv`,m=s(`${u}/depthwise_weights`,4,`${h}/filters`),f=s(`${u}/BatchNorm/gamma`,1,`${h}/batch_norm_scale`),g=s(`${u}/BatchNorm/beta`,1,`${h}/batch_norm_offset`),y=s(`${u}/BatchNorm/moving_mean`,1,`${h}/batch_norm_mean`),w=s(`${u}/BatchNorm/moving_variance`,1,`${h}/batch_norm_variance`);return{depthwise_conv:{filters:m,batch_norm_scale:f,batch_norm_offset:g,batch_norm_mean:y,batch_norm_variance:w},pointwise_conv:n("MobilenetV1",c,d)}}function r(){return{conv_0:n("MobilenetV1",0,"mobilenetv1/conv_0"),conv_1:i(1),conv_2:i(2),conv_3:i(3),conv_4:i(4),conv_5:i(5),conv_6:i(6),conv_7:i(7),conv_8:i(8),conv_9:i(9),conv_10:i(10),conv_11:i(11),conv_12:i(12),conv_13:i(13)}}function o(c,p){const u=s(`${c}/weights`,4,`${p}/filters`),h=s(`${c}/biases`,1,`${p}/bias`);return{filters:u,bias:h}}function a(c){const p=o(`Prediction/BoxPredictor_${c}/BoxEncodingPredictor`,`prediction_layer/box_predictor_${c}/box_encoding_predictor`),u=o(`Prediction/BoxPredictor_${c}/ClassPredictor`,`prediction_layer/box_predictor_${c}/class_predictor`);return{box_encoding_predictor:p,class_predictor:u}}function l(){return{conv_0:n("Prediction",0,"prediction_layer/conv_0"),conv_1:n("Prediction",1,"prediction_layer/conv_1"),conv_2:n("Prediction",2,"prediction_layer/conv_2"),conv_3:n("Prediction",3,"prediction_layer/conv_3"),conv_4:n("Prediction",4,"prediction_layer/conv_4"),conv_5:n("Prediction",5,"prediction_layer/conv_5"),conv_6:n("Prediction",6,"prediction_layer/conv_6"),conv_7:n("Prediction",7,"prediction_layer/conv_7"),box_predictor_0:a(0),box_predictor_1:a(1),box_predictor_2:a(2),box_predictor_3:a(3),box_predictor_4:a(4),box_predictor_5:a(5)}}return{extractMobilenetV1Params:r,extractPredictionLayerParams:l}}function z1(e){const t=[],{extractMobilenetV1Params:s,extractPredictionLayerParams:n}=dG(e,t),i=e["Output/extra_dim"];if(t.push({originalPath:"Output/extra_dim",paramPath:"output_layer/extra_dim"}),!Zi(i))throw new Error(`expected weightMap['Output/extra_dim'] to be a Tensor3D, instead have ${i}`);const r={mobilenetv1:s(),prediction_layer:n(),output_layer:{extra_dim:i}};return Ss(e,t),{params:r,paramMappings:t}}function En(e,t,s){return C(()=>{let n=nt(e,t.filters,s,"same");return n=$(n,t.batch_norm_offset),wt(n,0,6)})}const mG=.0010000000474974513;function fG(e,t,s){return C(()=>{let n=un(e,t.filters,s,"same");return n=Ys(n,t.batch_norm_mean,t.batch_norm_variance,t.batch_norm_offset,t.batch_norm_scale,mG),wt(n,0,6)})}function gG(e){return[2,4,6,12].some(t=>t===e)?[2,2]:[1,1]}function P1(e,t){return C(()=>{let s,n=En(e,t.conv_0,[2,2]);const i=[t.conv_1,t.conv_2,t.conv_3,t.conv_4,t.conv_5,t.conv_6,t.conv_7,t.conv_8,t.conv_9,t.conv_10,t.conv_11,t.conv_12,t.conv_13];if(i.forEach((r,o)=>{const a=o+1,l=gG(a);n=fG(n,r.depthwise_conv,l),n=En(n,r.pointwise_conv,[1,1]),a===11&&(s=n)}),s===null)throw new Error("mobileNetV1 - output of conv layer 11 is null");return{out:n,conv11:s}})}function B1(e,t,s,n,i){const r=e.shape[0],o=Math.min(s,r),a=t.map((p,u)=>({score:p,boxIndex:u})).filter(p=>p.score>i).sort((p,u)=>u.score-p.score),l=p=>p<=n?1:0,c=[];return a.forEach(p=>{if(c.length>=o)return;const u=p.score;for(let h=c.length-1;h>=0;--h){const d=yG(e,p.boxIndex,c[h]);if(d===0)continue;if(p.score*=l(d),p.score<=i)break}u===p.score&&c.push(p.boxIndex)}),c}function yG(e,t,s){const n=e.arraySync(),i=Math.min(n[t][0],n[t][2]),r=Math.min(n[t][1],n[t][3]),o=Math.max(n[t][0],n[t][2]),a=Math.max(n[t][1],n[t][3]),l=Math.min(n[s][0],n[s][2]),c=Math.min(n[s][1],n[s][3]),p=Math.max(n[s][0],n[s][2]),u=Math.max(n[s][1],n[s][3]),h=(o-i)*(a-r),d=(p-l)*(u-c);if(h<=0||d<=0)return 0;const m=Math.max(i,l),f=Math.max(r,c),g=Math.min(o,p),y=Math.min(a,u),w=Math.max(g-m,0)*Math.max(y-f,0);return w/(h+d-w)}function bG(e){const t=Ge(se(e,[1,0])),s=[X(t[2],t[0]),X(t[3],t[1])],n=[$(t[0],Z(s[0],j(2))),$(t[1],Z(s[1],j(2)))];return{sizes:s,centers:n}}function wG(e,t){const{sizes:s,centers:n}=bG(e),i=Ge(se(t,[1,0])),r=Z(R(ut(Z(i[2],j(5))),s[0]),j(2)),o=$(R(Z(i[0],j(10)),s[0]),n[0]),a=Z(R(ut(Z(i[3],j(5))),s[1]),j(2)),l=$(R(Z(i[1],j(10)),s[1]),n[1]);return se(Ve([X(o,r),X(l,a),$(o,r),$(l,a)]),[1,0])}function j1(e,t,s){return C(()=>{const n=e.shape[0];let i=wG(O(Us(s.extra_dim,[n,1,1]),[-1,4]),O(e,[-1,4]));i=O(i,[n,i.shape[0]/n,4]);const r=rs(he(t,[0,0,1],[-1,-1,-1]));let o=he(r,[0,0,0],[-1,-1,1]);o=O(o,[n,o.shape[1]]);const a=Ge(i),l=Ge(o);return{boxes:a,scores:l}})}function Ia(e,t){return C(()=>{const s=e.shape[0],n=O(xa(e,t.box_encoding_predictor),[s,-1,1,4]),i=O(xa(e,t.class_predictor),[s,-1,3]);return{boxPredictionEncoding:n,classPrediction:i}})}function V1(e,t,s){return C(()=>{const n=En(e,s.conv_0,[1,1]),i=En(n,s.conv_1,[2,2]),r=En(i,s.conv_2,[1,1]),o=En(r,s.conv_3,[2,2]),a=En(o,s.conv_4,[1,1]),l=En(a,s.conv_5,[2,2]),c=En(l,s.conv_6,[1,1]),p=En(c,s.conv_7,[2,2]),u=Ia(t,s.box_predictor_0),h=Ia(e,s.box_predictor_1),d=Ia(i,s.box_predictor_2),m=Ia(o,s.box_predictor_3),f=Ia(l,s.box_predictor_4),g=Ia(p,s.box_predictor_5),y=be([u.boxPredictionEncoding,h.boxPredictionEncoding,d.boxPredictionEncoding,m.boxPredictionEncoding,f.boxPredictionEncoding,g.boxPredictionEncoding],1),w=be([u.classPrediction,h.classPrediction,d.classPrediction,m.classPrediction,f.classPrediction,g.classPrediction],1);return{boxPredictions:y,classPredictions:w}})}class Hn{constructor({minConfidence:e,maxResults:t}={}){if(this._name="SsdMobilenetv1Options",this._minConfidence=e||.5,this._maxResults=t||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}}class rc extends cs{constructor(){super("SsdMobilenetv1")}forwardInput(e){const{params:t}=this;if(!t)throw new Error("SsdMobilenetv1 - load model before inference");return C(()=>{const s=G(e.toBatchTensor(512,!1),"float32"),n=X(R(s,j(.007843137718737125)),j(1)),i=P1(n,t.mobilenetv1),{boxPredictions:r,classPredictions:o}=V1(i.out,i.conv11,t.prediction_layer);return j1(r,o,t.output_layer)})}async forward(e){return this.forwardInput(await ct(e))}async locateFaces(e,t={}){const{maxResults:s,minConfidence:n}=new Hn(t),i=await ct(e),{boxes:r,scores:o}=this.forwardInput(i),a=r[0],l=o[0];for(let w=1;w<r.length;w++)r[w].dispose(),o[w].dispose();const c=Array.from(await l.data()),p=.5,u=B1(a,c,s,p,n),h=i.getReshapedInputDimensions(0),d=i.inputSize,m=d/h.width,f=d/h.height,g=a.arraySync(),y=u.map(w=>{const[x,T]=[Math.max(0,g[w][0]),Math.min(1,g[w][2])].map(E=>E*f),[A,_]=[Math.max(0,g[w][1]),Math.min(1,g[w][3])].map(E=>E*m);return new Lt(c[w],new vu(A,x,_-A,T-x),{height:i.getInputHeight(0),width:i.getInputWidth(0)})});return a.dispose(),l.dispose(),y}getDefaultModelName(){return"ssd_mobilenetv1_model"}extractParamsFromWeigthMap(e){return z1(e)}extractParams(e){return W1(e)}}function G1(e){const t=new rc;return t.extractWeights(e),t}function xG(e){return G1(e)}class LG extends rc{}const q1=.4,H1=[new Fe(.738768,.874946),new Fe(2.42204,2.65704),new Fe(4.30971,7.04493),new Fe(10.246,4.59428),new Fe(12.6868,11.8741)],Y1=[new Fe(1.603231,2.094468),new Fe(6.041143,7.080126),new Fe(2.882459,3.518061),new Fe(4.266906,5.178857),new Fe(9.041765,10.66308)],K1=[117.001,114.697,97.404],X1="tiny_yolov2_model",J1="tiny_yolov2_separable_conv_model";const ig=e=>typeof e=="number";function eL(e){if(!e)throw new Error(`invalid config: ${e}`);if(typeof e.withSeparableConvs!="boolean")throw new Error(`config.withSeparableConvs has to be a boolean, have: ${e.withSeparableConvs}`);if(!ig(e.iouThreshold)||e.iouThreshold<0||e.iouThreshold>1)throw new Error(`config.iouThreshold has to be a number between [0, 1], have: ${e.iouThreshold}`);if(!Array.isArray(e.classes)||!e.classes.length||!e.classes.every(t=>typeof t=="string"))throw new Error(`config.classes has to be an array class names: string[], have: ${JSON.stringify(e.classes)}`);if(!Array.isArray(e.anchors)||!e.anchors.length||!e.anchors.map(t=>t||{}).every(t=>ig(t.x)&&ig(t.y)))throw new Error(`config.anchors has to be an array of { x: number, y: number }, have: ${JSON.stringify(e.anchors)}`);if(e.meanRgb&&(!Array.isArray(e.meanRgb)||e.meanRgb.length!==3||!e.meanRgb.every(ig)))throw new Error(`config.meanRgb has to be an array of shape [number, number, number], have: ${JSON.stringify(e.meanRgb)}`)}function oc(e){return C(()=>{const t=R(e,j(.10000000149011612));return $(De(X(e,t)),t)})}function er(e,t){return C(()=>{let s=Pt(e,[[0,0],[1,1],[1,1],[0,0]]);return s=nt(s,t.conv.filters,[1,1],"valid"),s=X(s,t.bn.sub),s=R(s,t.bn.truediv),s=$(s,t.conv.bias),oc(s)})}function tr(e,t){return C(()=>{let s=Pt(e,[[0,0],[1,1],[1,1],[0,0]]);return s=Vr(s,t.depthwise_filter,t.pointwise_filter,[1,1],"valid"),s=$(s,t.bias),oc(s)})}function SG(e,t){const s=tc(e,t);function n(o,a){const l=Oe(e(o)),c=Oe(e(o));return t.push({paramPath:`${a}/sub`},{paramPath:`${a}/truediv`}),{sub:l,truediv:c}}function i(o,a,l){const c=s(o,a,3,`${l}/conv`),p=n(a,`${l}/bn`);return{conv:c,bn:p}}const r=sc(e,t);return{extractConvParams:s,extractConvWithBatchNormParams:i,extractSeparableConvParams:r}}function Z1(e,t,s,n){const{extractWeights:i,getRemainingWeights:r}=Is(e),o=[],{extractConvParams:a,extractConvWithBatchNormParams:l,extractSeparableConvParams:c}=SG(i,o);let p;if(t.withSeparableConvs){const[u,h,d,m,f,g,y,w,x]=n,T=t.isFirstLayerConv2d?a(u,h,3,"conv0"):c(u,h,"conv0"),A=c(h,d,"conv1"),_=c(d,m,"conv2"),E=c(m,f,"conv3"),F=c(f,g,"conv4"),D=c(g,y,"conv5"),M=w?c(y,w,"conv6"):void 0,P=x?c(w,x,"conv7"):void 0,B=a(x||w||y,5*s,1,"conv8");p={conv0:T,conv1:A,conv2:_,conv3:E,conv4:F,conv5:D,conv6:M,conv7:P,conv8:B}}else{const[u,h,d,m,f,g,y,w,x]=n,T=l(u,h,"conv0"),A=l(h,d,"conv1"),_=l(d,m,"conv2"),E=l(m,f,"conv3"),F=l(f,g,"conv4"),D=l(g,y,"conv5"),M=l(y,w,"conv6"),P=l(w,x,"conv7"),B=a(x,5*s,1,"conv8");p={conv0:T,conv1:A,conv2:_,conv3:E,conv4:F,conv5:D,conv6:M,conv7:P,conv8:B}}if(r().length!==0)throw new Error(`weights remaing after extract: ${r().length}`);return{params:p,paramMappings:o}}function IG(e,t){const s=Vs(e,t);function n(a){const l=s(`${a}/sub`,1),c=s(`${a}/truediv`,1);return{sub:l,truediv:c}}function i(a){const l=s(`${a}/filters`,4),c=s(`${a}/bias`,1);return{filters:l,bias:c}}function r(a){const l=i(`${a}/conv`),c=n(`${a}/bn`);return{conv:l,bn:c}}const o=nc(s);return{extractConvParams:i,extractConvWithBatchNormParams:r,extractSeparableConvParams:o}}function Q1(e,t){const s=[],{extractConvParams:n,extractConvWithBatchNormParams:i,extractSeparableConvParams:r}=IG(e,s);let o;if(t.withSeparableConvs){const a=t.filterSizes&&t.filterSizes.length||9;o={conv0:t.isFirstLayerConv2d?n("conv0"):r("conv0"),conv1:r("conv1"),conv2:r("conv2"),conv3:r("conv3"),conv4:r("conv4"),conv5:r("conv5"),conv6:a>7?r("conv6"):void 0,conv7:a>8?r("conv7"):void 0,conv8:n("conv8")}}else o={conv0:i("conv0"),conv1:i("conv1"),conv2:i("conv2"),conv3:i("conv3"),conv4:i("conv4"),conv5:i("conv5"),conv6:i("conv6"),conv7:i("conv7"),conv8:n("conv8")};return Ss(e,s),{params:o,paramMappings:s}}var tL;(function(e){e[e.XS=224]="XS",e[e.SM=320]="SM",e[e.MD=416]="MD",e[e.LG=608]="LG"})(tL||(tL={}));class sr{constructor({inputSize:e,scoreThreshold:t}={}){if(this._name="TinyYolov2Options",this._inputSize=e||416,this._scoreThreshold=t||.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}}class ac extends cs{constructor(e){super("TinyYolov2");eL(e),this._config=e}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(e,t){let s=er(e,t.conv0);return s=mt(s,[2,2],[2,2],"same"),s=er(s,t.conv1),s=mt(s,[2,2],[2,2],"same"),s=er(s,t.conv2),s=mt(s,[2,2],[2,2],"same"),s=er(s,t.conv3),s=mt(s,[2,2],[2,2],"same"),s=er(s,t.conv4),s=mt(s,[2,2],[2,2],"same"),s=er(s,t.conv5),s=mt(s,[2,2],[1,1],"same"),s=er(s,t.conv6),s=er(s,t.conv7),xa(s,t.conv8,"valid",!1)}runMobilenet(e,t){let s=this.config.isFirstLayerConv2d?oc(xa(e,t.conv0,"valid",!1)):tr(e,t.conv0);return s=mt(s,[2,2],[2,2],"same"),s=tr(s,t.conv1),s=mt(s,[2,2],[2,2],"same"),s=tr(s,t.conv2),s=mt(s,[2,2],[2,2],"same"),s=tr(s,t.conv3),s=mt(s,[2,2],[2,2],"same"),s=tr(s,t.conv4),s=mt(s,[2,2],[2,2],"same"),s=tr(s,t.conv5),s=mt(s,[2,2],[1,1],"same"),s=t.conv6?tr(s,t.conv6):s,s=t.conv7?tr(s,t.conv7):s,xa(s,t.conv8,"valid",!1)}forwardInput(e,t){const{params:s}=this;if(!s)throw new Error("TinyYolov2 - load model before inference");return C(()=>{let n=G(e.toBatchTensor(t,!1),"float32");return n=this.config.meanRgb?Gn(n,this.config.meanRgb):n,n=n.div(j(256)),this.config.withSeparableConvs?this.runMobilenet(n,s):this.runTinyYolov2(n,s)})}async forward(e,t){return await this.forwardInput(await ct(e),t)}async detect(e,t={}){const{inputSize:s,scoreThreshold:n}=new sr(t),i=await ct(e),r=await this.forwardInput(i,s),o=C(()=>Ge(r)[0].expandDims()),a={width:i.getInputWidth(0),height:i.getInputHeight(0)},l=await this.extractBoxes(o,i.getReshapedInputDimensions(0),n);r.dispose(),o.dispose();const c=l.map(f=>f.box),p=l.map(f=>f.score),u=l.map(f=>f.classScore),h=l.map(f=>this.config.classes[f.label]),d=Rx(c.map(f=>f.rescale(s)),p,this.config.iouThreshold,!0),m=d.map(f=>new Xl(p[f],u[f],h[f],c[f],a));return m}getDefaultModelName(){return""}extractParamsFromWeigthMap(e){return Q1(e,this.config)}extractParams(e){const t=this.config.filterSizes||ac.DEFAULT_FILTER_SIZES,s=t?t.length:void 0;if(s!==7&&s!==8&&s!==9)throw new Error(`TinyYolov2 - expected 7 | 8 | 9 convolutional filters, but found ${s} filterSizes in config`);return Z1(e,this.config,this.boxEncodingSize,t)}async extractBoxes(e,t,s){const{width:n,height:i}=t,r=Math.max(n,i),o=r/n,a=r/i,l=e.shape[1],c=this.config.anchors.length,[p,u,h]=C(()=>{const g=e.reshape([l,l,c,this.boxEncodingSize]),y=g.slice([0,0,0,0],[l,l,c,4]),w=g.slice([0,0,0,4],[l,l,c,1]),x=this.withClassScores?es(g.slice([0,0,0,5],[l,l,c,this.config.classes.length]),3):j(0);return[y,w,x]}),d=[],m=await u.array(),f=await p.array();for(let g=0;g<l;g++)for(let y=0;y<l;y++)for(let w=0;w<c;w++){const x=Iu(m[g][y][w][0]);if(!s||x>s){const T=(y+Iu(f[g][y][w][0]))/l*o,A=(g+Iu(f[g][y][w][1]))/l*a,_=Math.exp(f[g][y][w][2])*this.config.anchors[w].x/l*o,E=Math.exp(f[g][y][w][3])*this.config.anchors[w].y/l*a,F=T-_/2,D=A-E/2,M={row:g,col:y,anchor:w},{classScore:P,label:B}=this.withClassScores?await this.extractPredictedClass(h,M):{classScore:1,label:0};d.push({box:new Su(F,D,F+_,D+E),score:x,classScore:x*P,label:B,...M})}}return p.dispose(),u.dispose(),h.dispose(),d}async extractPredictedClass(e,t){const{row:s,col:n,anchor:i}=t,r=await e.array();return Array(this.config.classes.length).fill(0).map((o,a)=>r[s][n][i][a]).map((o,a)=>({classScore:o,label:a})).reduce((o,a)=>o.classScore>a.classScore?o:a)}}ac.DEFAULT_FILTER_SIZES=[3,16,32,64,128,256,512,1024,1024];class ku extends ac{constructor(e=!0){const t=Object.assign({},{withSeparableConvs:e,iouThreshold:q1,classes:["face"]},e?{anchors:Y1,meanRgb:K1}:{anchors:H1,withClassScores:!0});super(t)}get withSeparableConvs(){return this.config.withSeparableConvs}get anchors(){return this.config.anchors}async locateFaces(e,t){const s=await this.detect(e,t);return s.map(n=>new Lt(n.score,n.relativeBox,{width:n.imageWidth,height:n.imageHeight}))}getDefaultModelName(){return this.withSeparableConvs?J1:X1}extractParamsFromWeigthMap(e){return super.extractParamsFromWeigthMap(e)}}function vG(e,t=!0){const s=new ku(t);return s.extractWeights(e),s}class sL extends sr{constructor(){super(...arguments);this._name="TinyFaceDetectorOptions"}}class Yn{async then(e){return e(await this.run())}async run(){throw new Error("ComposableTask - run is not implemented")}}async function va(e,t,s,n,i=({alignedRect:r})=>r){const r=e.map(l=>Sa(l)?i(l):l.detection),o=n||(t instanceof me?await ec(t,r):await Ql(t,r)),a=await s(o);return o.forEach(l=>l instanceof me&&l.dispose()),a}async function lc(e,t,s,n,i){return va([e],t,async r=>s(r[0]),n,i)}const eE=.4,tE=[new Fe(1.603231,2.094468),new Fe(6.041143,7.080126),new Fe(2.882459,3.518061),new Fe(4.266906,5.178857),new Fe(9.041765,10.66308)],sE=[117.001,114.697,97.404];class Du extends ac{constructor(){const e={withSeparableConvs:!0,iouThreshold:eE,classes:["face"],anchors:tE,meanRgb:sE,isFirstLayerConv2d:!0,filterSizes:[3,16,32,64,128,256,512]};super(e)}get anchors(){return this.config.anchors}async locateFaces(e,t){const s=await this.detect(e,t);return s.map(n=>new Lt(n.score,n.relativeBox,{width:n.imageWidth,height:n.imageHeight}))}getDefaultModelName(){return"tiny_face_detector_model"}extractParamsFromWeigthMap(e){return super.extractParamsFromWeigthMap(e)}}const je={ssdMobilenetv1:new rc,tinyFaceDetector:new Du,tinyYolov2:new ku,faceLandmark68Net:new Ou,faceLandmark68TinyNet:new Jx,faceRecognitionNet:new _u,faceExpressionNet:new qx,ageGenderNet:new Xx},nE=(e,t)=>je.ssdMobilenetv1.locateFaces(e,t),TG=(e,t)=>je.tinyFaceDetector.locateFaces(e,t),AG=(e,t)=>je.tinyYolov2.locateFaces(e,t),iE=e=>je.faceLandmark68Net.detectLandmarks(e),NG=e=>je.faceLandmark68TinyNet.detectLandmarks(e),CG=e=>je.faceRecognitionNet.computeFaceDescriptor(e),RG=e=>je.faceExpressionNet.predictExpressions(e),OG=e=>je.ageGenderNet.predictAgeAndGender(e),rE=e=>je.ssdMobilenetv1.load(e),EG=e=>je.tinyFaceDetector.load(e),_G=e=>je.tinyYolov2.load(e),kG=e=>je.faceLandmark68Net.load(e),DG=e=>je.faceLandmark68TinyNet.load(e),FG=e=>je.faceRecognitionNet.load(e),MG=e=>je.faceExpressionNet.load(e),UG=e=>je.ageGenderNet.load(e),$G=rE,WG=nE,zG=iE;class oE extends Yn{constructor(e,t,s){super();this.parentTask=e,this.input=t,this.extractedFaces=s}}class Uu extends oE{async run(){const e=await this.parentTask,t=await va(e,this.input,async s=>await Promise.all(s.map(n=>je.faceExpressionNet.predictExpressions(n))),this.extractedFaces);return e.map((s,n)=>Zf(s,t[n]))}withAgeAndGender(){return new Fu(this,this.input)}}class $u extends oE{async run(){const e=await this.parentTask;if(!e)return;const t=await lc(e,this.input,s=>je.faceExpressionNet.predictExpressions(s),this.extractedFaces);return Zf(e,t)}withAgeAndGender(){return new Mu(this,this.input)}}class uc extends Uu{withAgeAndGender(){return new cc(this,this.input)}withFaceDescriptors(){return new Ta(this,this.input)}}class hc extends $u{withAgeAndGender(){return new pc(this,this.input)}withFaceDescriptor(){return new Aa(this,this.input)}}class aE extends Yn{constructor(e,t,s){super();this.parentTask=e,this.input=t,this.extractedFaces=s}}class Fu extends aE{async run(){const e=await this.parentTask,t=await va(e,this.input,async s=>await Promise.all(s.map(n=>je.ageGenderNet.predictAgeAndGender(n))),this.extractedFaces);return e.map((s,n)=>{const{age:i,gender:r,genderProbability:o}=t[n];return sg(ng(s,r,o),i)})}withFaceExpressions(){return new Uu(this,this.input)}}class Mu extends aE{async run(){const e=await this.parentTask;if(!e)return;const{age:t,gender:s,genderProbability:n}=await lc(e,this.input,i=>je.ageGenderNet.predictAgeAndGender(i),this.extractedFaces);return sg(ng(e,s,n),t)}withFaceExpressions(){return new $u(this,this.input)}}class cc extends Fu{withFaceExpressions(){return new uc(this,this.input)}withFaceDescriptors(){return new Ta(this,this.input)}}class pc extends Mu{withFaceExpressions(){return new hc(this,this.input)}withFaceDescriptor(){return new Aa(this,this.input)}}class nL extends Yn{constructor(e,t){super();this.parentTask=e,this.input=t}}class Ta extends nL{async run(){const e=await this.parentTask,t=await va(e,this.input,s=>Promise.all(s.map(n=>je.faceRecognitionNet.computeFaceDescriptor(n))),null,s=>s.landmarks.align(null,{useDlibAlignment:!0}));return t.map((s,n)=>tg(e[n],s))}withFaceExpressions(){return new uc(this,this.input)}withAgeAndGender(){return new cc(this,this.input)}}class Aa extends nL{async run(){const e=await this.parentTask;if(!e)return;const t=await lc(e,this.input,s=>je.faceRecognitionNet.computeFaceDescriptor(s),null,s=>s.landmarks.align(null,{useDlibAlignment:!0}));return tg(e,t)}withFaceExpressions(){return new hc(this,this.input)}withAgeAndGender(){return new pc(this,this.input)}}class iL extends Yn{constructor(e,t,s){super();this.parentTask=e,this.input=t,this.useTinyLandmarkNet=s}get landmarkNet(){return this.useTinyLandmarkNet?je.faceLandmark68TinyNet:je.faceLandmark68Net}}class rL extends iL{async run(){const e=await this.parentTask,t=e.map(i=>i.detection),s=this.input instanceof me?await ec(this.input,t):await Ql(this.input,t),n=await Promise.all(s.map(i=>this.landmarkNet.detectLandmarks(i)));return s.forEach(i=>i instanceof me&&i.dispose()),e.map((i,r)=>ic(i,n[r]))}withFaceExpressions(){return new uc(this,this.input)}withAgeAndGender(){return new cc(this,this.input)}withFaceDescriptors(){return new Ta(this,this.input)}}class oL extends iL{async run(){const e=await this.parentTask;if(!e)return;const{detection:t}=e,s=this.input instanceof me?await ec(this.input,[t]):await Ql(this.input,[t]),n=await this.landmarkNet.detectLandmarks(s[0]);return s.forEach(i=>i instanceof me&&i.dispose()),ic(e,n)}withFaceExpressions(){return new hc(this,this.input)}withAgeAndGender(){return new pc(this,this.input)}withFaceDescriptor(){return new Aa(this,this.input)}}class aL extends Yn{constructor(e,t=new Hn){super();this.input=e,this.options=t}}class rg extends aL{async run(){const{input:e,options:t}=this,s=t instanceof sL?n=>je.tinyFaceDetector.locateFaces(n,t):t instanceof Hn?n=>je.ssdMobilenetv1.locateFaces(n,t):t instanceof sr?n=>je.tinyYolov2.locateFaces(n,t):null;if(!s)throw new Error("detectFaces - expected options to be instance of TinyFaceDetectorOptions | SsdMobilenetv1Options | MtcnnOptions | TinyYolov2Options");return s(e)}runAndExtendWithFaceDetections(){return new Promise(async e=>{const t=await this.run();return e(t.map(s=>ga({},s)))})}withFaceLandmarks(e=!1){return new rL(this.runAndExtendWithFaceDetections(),this.input,e)}withFaceExpressions(){return new Uu(this.runAndExtendWithFaceDetections(),this.input)}withAgeAndGender(){return new Fu(this.runAndExtendWithFaceDetections(),this.input)}}class lL extends aL{async run(){const e=await new rg(this.input,this.options);let t=e[0];return e.forEach(s=>{s.score>t.score&&(t=s)}),t}runAndExtendWithFaceDetection(){return new Promise(async e=>{const t=await this.run();return e(t?ga({},t):void 0)})}withFaceLandmarks(e=!1){return new oL(this.runAndExtendWithFaceDetection(),this.input,e)}withFaceExpressions(){return new $u(this.runAndExtendWithFaceDetection(),this.input)}withAgeAndGender(){return new Mu(this.runAndExtendWithFaceDetection(),this.input)}}function PG(e,t=new Hn){return new lL(e,t)}function og(e,t=new Hn){return new rg(e,t)}async function lE(e,t){return console.warn("allFacesSsdMobilenetv1 is deprecated and will be removed soon, use the high level api instead"),await og(e,new Hn(t?{minConfidence:t}:{})).withFaceLandmarks().withFaceDescriptors()}async function BG(e,t={}){return console.warn("allFacesTinyYolov2 is deprecated and will be removed soon, use the high level api instead"),await og(e,new sr(t)).withFaceLandmarks().withFaceDescriptors()}const jG=lE;function cL(e,t){if(e.length!==t.length)throw new Error("euclideanDistance: arr1.length !== arr2.length");const s=Array.from(e),n=Array.from(t);return Math.sqrt(s.map((i,r)=>i-n[r]).reduce((i,r)=>i+Math.pow(r,2),0))}class cE{constructor(e,t=.6){this._distanceThreshold=t;const s=Array.isArray(e)?e:[e];if(!s.length)throw new Error("FaceRecognizer.constructor - expected atleast one input");let n=1;const i=()=>`person ${n++}`;this._labeledDescriptors=s.map(r=>{if(r instanceof fa)return r;if(r instanceof Float32Array)return new fa(i(),[r]);if(r.descriptor&&r.descriptor instanceof Float32Array)return new fa(i(),[r.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(e,t){return t.map(s=>cL(s,e)).reduce((s,n)=>s+n,0)/(t.length||1)}matchDescriptor(e){return this.labeledDescriptors.map(({descriptors:t,label:s})=>new $f(s,this.computeMeanDistance(e,t))).reduce((t,s)=>t.distance<s.distance?t:s)}findBestMatch(e){const t=this.matchDescriptor(e);return t.distance<this.distanceThreshold?t:new $f("unknown",t.distance)}toJSON(){return{distanceThreshold:this.distanceThreshold,labeledDescriptors:this.labeledDescriptors.map(e=>e.toJSON())}}static fromJSON(e){const t=e.labeledDescriptors.map(s=>fa.fromJSON(s));return new cE(t,e.distanceThreshold)}}function VG(e){const t=new Du;return t.extractWeights(e),t}function pE(e,t){const{width:s,height:n}=new js(t.width,t.height);if(s<=0||n<=0)throw new Error(`resizeResults - invalid dimensions: ${JSON.stringify({width:s,height:n})}`);if(Array.isArray(e))return e.map(i=>pE(i,{width:s,height:n}));if(Sa(e)){const i=e.detection.forSize(s,n),r=e.unshiftedLandmarks.forSize(i.box.width,i.box.height);return ic(ga(e,i),r)}return xi(e)?ga(e,e.detection.forSize(s,n)):e instanceof On||e instanceof Lt?e.forSize(s,n):e}var uE="0.6.2";const GG=typeof process!="undefined",qG=typeof navigator!="undefined"&&typeof navigator.userAgent!="undefined",HG={faceapi:uE,node:GG,browser:qG};export{Xx as AgeGenderNet,Su as BoundingBox,lt as Box,Yn as ComposableTask,Ta as ComputeAllFaceDescriptorsTask,nL as ComputeFaceDescriptorsTaskBase,Aa as ComputeSingleFaceDescriptorTask,rL as DetectAllFaceLandmarksTask,rg as DetectAllFacesTask,iL as DetectFaceLandmarksTaskBase,aL as DetectFacesTaskBase,oL as DetectSingleFaceLandmarksTask,lL as DetectSingleFaceTask,js as Dimensions,Gx as FACE_EXPRESSION_LABELS,Lt as FaceDetection,LG as FaceDetectionNet,qx as FaceExpressionNet,La as FaceExpressions,Ou as FaceLandmark68Net,Jx as FaceLandmark68TinyNet,oG as FaceLandmarkNet,On as FaceLandmarks,HV as FaceLandmarks5,Tu as FaceLandmarks68,$f as FaceMatch,cE as FaceMatcher,_u as FaceRecognitionNet,Qi as Gender,Wf as LabeledBox,fa as LabeledFaceDescriptors,mo as NetInput,cs as NeuralNetwork,Xl as ObjectDetection,Fe as Point,YV as PredictedBox,vu as Rect,rc as SsdMobilenetv1,Hn as SsdMobilenetv1Options,Du as TinyFaceDetector,sL as TinyFaceDetectorOptions,ku as TinyYolov2,sr as TinyYolov2Options,tL as TinyYolov2SizeType,jG as allFaces,lE as allFacesSsdMobilenetv1,BG as allFacesTinyYolov2,$x as awaitMediaLoaded,Wx as bufferToImage,CG as computeFaceDescriptor,Zl as createCanvas,Nu as createCanvasFromMedia,xG as createFaceDetectionNet,cG as createFaceRecognitionNet,G1 as createSsdMobilenetv1,VG as createTinyFaceDetector,vG as createTinyYolov2,og as detectAllFaces,iE as detectFaceLandmarks,NG as detectFaceLandmarksTiny,zG as detectLandmarks,PG as detectSingleFace,Yx as draw,Ze as env,cL as euclideanDistance,sg as extendWithAge,tg as extendWithFaceDescriptor,ga as extendWithFaceDetection,Zf as extendWithFaceExpressions,ic as extendWithFaceLandmarks,ng as extendWithGender,ec as extractFaceTensors,Ql as extractFaces,ZV as fetchImage,Bx as fetchJson,QV as fetchNetWeights,wa as fetchOrThrow,Os as getContext2dOrThrow,ba as getMediaDimensions,zx as imageTensorToCanvas,Px as imageToSquare,jV as inverseSigmoid,Nx as iou,Bf as isMediaElement,Au as isMediaLoaded,pG as isWithAge,xi as isWithFaceDetection,Hx as isWithFaceExpressions,Sa as isWithFaceLandmarks,uG as isWithGender,UG as loadAgeGenderModel,$G as loadFaceDetectionModel,MG as loadFaceExpressionModel,kG as loadFaceLandmarkModel,DG as loadFaceLandmarkTinyModel,FG as loadFaceRecognitionModel,rE as loadSsdMobilenetv1Model,EG as loadTinyFaceDetectorModel,_G as loadTinyYolov2Model,jx as loadWeightMap,WG as locateFaces,eG as matchDimensions,Cx as minBbox,je as nets,Rx as nonMaxSuppression,Gn as normalize,Ox as padToSquare,OG as predictAgeAndGender,RG as recognizeFaceExpressions,pE as resizeResults,ya as resolveInput,BV as shuffleArray,Iu as sigmoid,nE as ssdMobilenetv1,Sx as tf,TG as tinyFaceDetector,AG as tinyYolov2,ct as toNetInput,Ix as utils,eL as validateConfig,HG as version};
/**
* @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.esm.js.map