mirror of https://github.com/vladmandic/human
4497 lines
1.3 MiB
4497 lines
1.3 MiB
|
|
/*
|
|
Human library
|
|
homepage: <https://github.com/vladmandic/human>
|
|
author: <https://github.com/vladmandic>'
|
|
*/
|
|
var wX=Object.create;var fx=Object.defineProperty;var _X=Object.getOwnPropertyDescriptor;var CX=Object.getOwnPropertyNames;var SX=Object.getPrototypeOf,NX=Object.prototype.hasOwnProperty;var AX=r=>fx(r,"__esModule",{value:!0});var Ap=r=>{if(typeof require!="undefined")return require(r);throw new Error('Dynamic require of "'+r+'" is not supported')};var hr=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ge=(r,e)=>{for(var t in e)fx(r,t,{get:e[t],enumerable:!0})},DX=(r,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of CX(e))!NX.call(r,n)&&n!=="default"&&fx(r,n,{get:()=>e[n],enumerable:!(t=_X(e,n))||t.enumerable});return r},Wi=r=>DX(AX(fx(r!=null?wX(SX(r)):{},"default",r&&r.__esModule&&"default"in r?{get:()=>r.default,enumerable:!0}:{value:r,enumerable:!0})),r);var Dw=hr((Owe,TF)=>{TF.exports=pr;var rs=null;try{rs=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(r){}function pr(r,e,t){this.low=r|0,this.high=e|0,this.unsigned=!!t}pr.prototype.__isLong__;Object.defineProperty(pr.prototype,"__isLong__",{value:!0});function yo(r){return(r&&r.__isLong__)===!0}pr.isLong=yo;var cF={},mF={};function Mp(r,e){var t,n,o;return e?(r>>>=0,(o=0<=r&&r<256)&&(n=mF[r],n)?n:(t=cr(r,(r|0)<0?-1:0,!0),o&&(mF[r]=t),t)):(r|=0,(o=-128<=r&&r<128)&&(n=cF[r],n)?n:(t=cr(r,r<0?-1:0,!1),o&&(cF[r]=t),t))}pr.fromInt=Mp;function ns(r,e){if(isNaN(r))return e?Fp:os;if(e){if(r<0)return Fp;if(r>=dF)return xF}else{if(r<=-hF)return xo;if(r+1>=hF)return yF}return r<0?ns(-r,e).neg():cr(r%Pm|0,r/Pm|0,e)}pr.fromNumber=ns;function cr(r,e,t){return new pr(r,e,t)}pr.fromBits=cr;var Ix=Math.pow;function Nw(r,e,t){if(r.length===0)throw Error("empty string");if(r==="NaN"||r==="Infinity"||r==="+Infinity"||r==="-Infinity")return os;if(typeof e=="number"?(t=e,e=!1):e=!!e,t=t||10,t<2||36<t)throw RangeError("radix");var n;if((n=r.indexOf("-"))>0)throw Error("interior hyphen");if(n===0)return Nw(r.substring(1),e,t).neg();for(var o=ns(Ix(t,8)),s=os,i=0;i<r.length;i+=8){var a=Math.min(8,r.length-i),l=parseInt(r.substring(i,i+a),t);if(a<8){var u=ns(Ix(t,a));s=s.mul(u).add(ns(l))}else s=s.mul(o),s=s.add(ns(l))}return s.unsigned=e,s}pr.fromString=Nw;function Ps(r,e){return typeof r=="number"?ns(r,e):typeof r=="string"?Nw(r,e):cr(r.low,r.high,typeof e=="boolean"?e:r.unsigned)}pr.fromValue=Ps;var fF=1<<16,i7=1<<24,Pm=fF*fF,dF=Pm*Pm,hF=dF/2,gF=Mp(i7),os=Mp(0);pr.ZERO=os;var Fp=Mp(0,!0);pr.UZERO=Fp;var Bm=Mp(1);pr.ONE=Bm;var bF=Mp(1,!0);pr.UONE=bF;var Aw=Mp(-1);pr.NEG_ONE=Aw;var yF=cr(4294967295|0,2147483647|0,!1);pr.MAX_VALUE=yF;var xF=cr(4294967295|0,4294967295|0,!0);pr.MAX_UNSIGNED_VALUE=xF;var xo=cr(0,2147483648|0,!1);pr.MIN_VALUE=xo;var Se=pr.prototype;Se.toInt=function(){return this.unsigned?this.low>>>0:this.low};Se.toNumber=function(){return this.unsigned?(this.high>>>0)*Pm+(this.low>>>0):this.high*Pm+(this.low>>>0)};Se.toString=function(e){if(e=e||10,e<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(xo)){var t=ns(e),n=this.div(t),o=n.mul(t).sub(this);return n.toString(e)+o.toInt().toString(e)}else return"-"+this.neg().toString(e);for(var s=ns(Ix(e,6),this.unsigned),i=this,a="";;){var l=i.div(s),u=i.sub(l.mul(s)).toInt()>>>0,p=u.toString(e);if(i=l,i.isZero())return p+a;for(;p.length<6;)p="0"+p;a=""+p+a}};Se.getHighBits=function(){return this.high};Se.getHighBitsUnsigned=function(){return this.high>>>0};Se.getLowBits=function(){return this.low};Se.getLowBitsUnsigned=function(){return this.low>>>0};Se.getNumBitsAbs=function(){if(this.isNegative())return this.eq(xo)?64:this.neg().getNumBitsAbs();for(var e=this.high!=0?this.high:this.low,t=31;t>0&&(e&1<<t)==0;t--);return this.high!=0?t+33:t+1};Se.isZero=function(){return this.high===0&&this.low===0};Se.eqz=Se.isZero;Se.isNegative=function(){return!this.unsigned&&this.high<0};Se.isPositive=function(){return this.unsigned||this.high>=0};Se.isOdd=function(){return(this.low&1)==1};Se.isEven=function(){return(this.low&1)==0};Se.equals=function(e){return yo(e)||(e=Ps(e)),this.unsigned!==e.unsigned&&this.high>>>31==1&&e.high>>>31==1?!1:this.high===e.high&&this.low===e.low};Se.eq=Se.equals;Se.notEquals=function(e){return!this.eq(e)};Se.neq=Se.notEquals;Se.ne=Se.notEquals;Se.lessThan=function(e){return this.comp(e)<0};Se.lt=Se.lessThan;Se.lessThanOrEqual=function(e){return this.comp(e)<=0};Se.lte=Se.lessThanOrEqual;Se.le=Se.lessThanOrEqual;Se.greaterThan=function(e){return this.comp(e)>0};Se.gt=Se.greaterThan;Se.greaterThanOrEqual=function(e){return this.comp(e)>=0};Se.gte=Se.greaterThanOrEqual;Se.ge=Se.greaterThanOrEqual;Se.compare=function(e){if(yo(e)||(e=Ps(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1};Se.comp=Se.compare;Se.negate=function(){return!this.unsigned&&this.eq(xo)?xo:this.not().add(Bm)};Se.neg=Se.negate;Se.add=function(e){yo(e)||(e=Ps(e));var t=this.high>>>16,n=this.high&65535,o=this.low>>>16,s=this.low&65535,i=e.high>>>16,a=e.high&65535,l=e.low>>>16,u=e.low&65535,p=0,c=0,m=0,f=0;return f+=s+u,m+=f>>>16,f&=65535,m+=o+l,c+=m>>>16,m&=65535,c+=n+a,p+=c>>>16,c&=65535,p+=t+i,p&=65535,cr(m<<16|f,p<<16|c,this.unsigned)};Se.subtract=function(e){return yo(e)||(e=Ps(e)),this.add(e.neg())};Se.sub=Se.subtract;Se.multiply=function(e){if(this.isZero())return os;if(yo(e)||(e=Ps(e)),rs){var t=rs.mul(this.low,this.high,e.low,e.high);return cr(t,rs.get_high(),this.unsigned)}if(e.isZero())return os;if(this.eq(xo))return e.isOdd()?xo:os;if(e.eq(xo))return this.isOdd()?xo:os;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(gF)&&e.lt(gF))return ns(this.toNumber()*e.toNumber(),this.unsigned);var n=this.high>>>16,o=this.high&65535,s=this.low>>>16,i=this.low&65535,a=e.high>>>16,l=e.high&65535,u=e.low>>>16,p=e.low&65535,c=0,m=0,f=0,d=0;return d+=i*p,f+=d>>>16,d&=65535,f+=s*p,m+=f>>>16,f&=65535,f+=i*u,m+=f>>>16,f&=65535,m+=o*p,c+=m>>>16,m&=65535,m+=s*u,c+=m>>>16,m&=65535,m+=i*l,c+=m>>>16,m&=65535,c+=n*p+o*u+s*l+i*a,c&=65535,cr(f<<16|d,c<<16|m,this.unsigned)};Se.mul=Se.multiply;Se.divide=function(e){if(yo(e)||(e=Ps(e)),e.isZero())throw Error("division by zero");if(rs){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?rs.div_u:rs.div_s)(this.low,this.high,e.low,e.high);return cr(t,rs.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?Fp:os;var n,o,s;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Fp;if(e.gt(this.shru(1)))return bF;s=Fp}else{if(this.eq(xo)){if(e.eq(Bm)||e.eq(Aw))return xo;if(e.eq(xo))return Bm;var i=this.shr(1);return n=i.div(e).shl(1),n.eq(os)?e.isNegative()?Bm:Aw:(o=this.sub(e.mul(n)),s=n.add(o.div(e)),s)}else if(e.eq(xo))return this.unsigned?Fp:os;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();s=os}for(o=this;o.gte(e);){n=Math.max(1,Math.floor(o.toNumber()/e.toNumber()));for(var a=Math.ceil(Math.log(n)/Math.LN2),l=a<=48?1:Ix(2,a-48),u=ns(n),p=u.mul(e);p.isNegative()||p.gt(o);)n-=l,u=ns(n,this.unsigned),p=u.mul(e);u.isZero()&&(u=Bm),s=s.add(u),o=o.sub(p)}return s};Se.div=Se.divide;Se.modulo=function(e){if(yo(e)||(e=Ps(e)),rs){var t=(this.unsigned?rs.rem_u:rs.rem_s)(this.low,this.high,e.low,e.high);return cr(t,rs.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};Se.mod=Se.modulo;Se.rem=Se.modulo;Se.not=function(){return cr(~this.low,~this.high,this.unsigned)};Se.and=function(e){return yo(e)||(e=Ps(e)),cr(this.low&e.low,this.high&e.high,this.unsigned)};Se.or=function(e){return yo(e)||(e=Ps(e)),cr(this.low|e.low,this.high|e.high,this.unsigned)};Se.xor=function(e){return yo(e)||(e=Ps(e)),cr(this.low^e.low,this.high^e.high,this.unsigned)};Se.shiftLeft=function(e){return yo(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?cr(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):cr(0,this.low<<e-32,this.unsigned)};Se.shl=Se.shiftLeft;Se.shiftRight=function(e){return yo(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?cr(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):cr(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};Se.shr=Se.shiftRight;Se.shiftRightUnsigned=function(e){if(yo(e)&&(e=e.toInt()),e&=63,e===0)return this;var t=this.high;if(e<32){var n=this.low;return cr(n>>>e|t<<32-e,t>>>e,this.unsigned)}else return e===32?cr(t,0,this.unsigned):cr(t>>>e-32,0,this.unsigned)};Se.shru=Se.shiftRightUnsigned;Se.shr_u=Se.shiftRightUnsigned;Se.toSigned=function(){return this.unsigned?cr(this.low,this.high,!1):this};Se.toUnsigned=function(){return this.unsigned?this:cr(this.low,this.high,!0)};Se.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};Se.toBytesLE=function(){var e=this.high,t=this.low;return[t&255,t>>>8&255,t>>>16&255,t>>>24,e&255,e>>>8&255,e>>>16&255,e>>>24]};Se.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,e&255,t>>>24,t>>>16&255,t>>>8&255,t&255]};pr.fromBytes=function(e,t,n){return n?pr.fromBytesLE(e,t):pr.fromBytesBE(e,t)};pr.fromBytesLE=function(e,t){return new pr(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};pr.fromBytesBE=function(e,t){return new pr(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)}});var Zw=hr(()=>{});var HR=hr((jR,L_)=>{(function(r,e,t){function n(a){var l=this,u=i();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=u(" "),l.s1=u(" "),l.s2=u(" "),l.s0-=u(a),l.s0<0&&(l.s0+=1),l.s1-=u(a),l.s1<0&&(l.s1+=1),l.s2-=u(a),l.s2<0&&(l.s2+=1),u=null}function o(a,l){return l.c=a.c,l.s0=a.s0,l.s1=a.s1,l.s2=a.s2,l}function s(a,l){var u=new n(a),p=l&&l.state,c=u.next;return c.int32=function(){return u.next()*4294967296|0},c.double=function(){return c()+(c()*2097152|0)*11102230246251565e-32},c.quick=c,p&&(typeof p=="object"&&o(p,u),c.state=function(){return o(u,{})}),c}function i(){var a=4022871197,l=function(u){u=u.toString();for(var p=0;p<u.length;p++){a+=u.charCodeAt(p);var c=.02519603282416938*a;a=c>>>0,c-=a,c*=a,a=c>>>0,c-=a,a+=c*4294967296}return(a>>>0)*23283064365386963e-26};return l}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.alea=s})(jR,typeof L_=="object"&&L_,typeof define=="function"&&define)});var XR=hr((qR,$_)=>{(function(r,e,t){function n(i){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},i===(i|0)?a.x=i:l+=i;for(var u=0;u<l.length+64;u++)a.x^=l.charCodeAt(u)|0,a.next()}function o(i,a){return a.x=i.x,a.y=i.y,a.z=i.z,a.w=i.w,a}function s(i,a){var l=new n(i),u=a&&a.state,p=function(){return(l.next()>>>0)/4294967296};return p.double=function(){do var c=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=l.next,p.quick=p,u&&(typeof u=="object"&&o(u,l),p.state=function(){return o(l,{})}),p}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xor128=s})(qR,typeof $_=="object"&&$_,typeof define=="function"&&define)});var ZR=hr((YR,P_)=>{(function(r,e,t){function n(i){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,i===(i|0)?a.x=i:l+=i;for(var u=0;u<l.length+64;u++)a.x^=l.charCodeAt(u)|0,u==l.length&&(a.d=a.x<<10^a.x>>>4),a.next()}function o(i,a){return a.x=i.x,a.y=i.y,a.z=i.z,a.w=i.w,a.v=i.v,a.d=i.d,a}function s(i,a){var l=new n(i),u=a&&a.state,p=function(){return(l.next()>>>0)/4294967296};return p.double=function(){do var c=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=l.next,p.quick=p,u&&(typeof u=="object"&&o(u,l),p.state=function(){return o(l,{})}),p}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xorwow=s})(YR,typeof P_=="object"&&P_,typeof define=="function"&&define)});var QR=hr((JR,B_)=>{(function(r,e,t){function n(i){var a=this;a.next=function(){var u=a.x,p=a.i,c,m,f;return c=u[p],c^=c>>>7,m=c^c<<24,c=u[p+1&7],m^=c^c>>>10,c=u[p+3&7],m^=c^c>>>3,c=u[p+4&7],m^=c^c<<7,c=u[p+7&7],c=c^c<<13,m^=c^c<<9,u[p]=m,a.i=p+1&7,m};function l(u,p){var c,m,f=[];if(p===(p|0))m=f[0]=p;else for(p=""+p,c=0;c<p.length;++c)f[c&7]=f[c&7]<<15^p.charCodeAt(c)+f[c+1&7]<<13;for(;f.length<8;)f.push(0);for(c=0;c<8&&f[c]===0;++c);for(c==8?m=f[7]=-1:m=f[c],u.x=f,u.i=0,c=256;c>0;--c)u.next()}l(a,i)}function o(i,a){return a.x=i.x.slice(),a.i=i.i,a}function s(i,a){i==null&&(i=+new Date);var l=new n(i),u=a&&a.state,p=function(){return(l.next()>>>0)/4294967296};return p.double=function(){do var c=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=l.next,p.quick=p,u&&(u.x&&o(u,l),p.state=function(){return o(l,{})}),p}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xorshift7=s})(JR,typeof B_=="object"&&B_,typeof define=="function"&&define)});var tL=hr((eL,O_)=>{(function(r,e,t){function n(i){var a=this;a.next=function(){var u=a.w,p=a.X,c=a.i,m,f;return a.w=u=u+1640531527|0,f=p[c+34&127],m=p[c=c+1&127],f^=f<<13,m^=m<<17,f^=f>>>15,m^=m>>>12,f=p[c]=f^m,a.i=c,f+(u^u>>>16)|0};function l(u,p){var c,m,f,d,h,g=[],b=128;for(p===(p|0)?(m=p,p=null):(p=p+"\0",m=0,b=Math.max(b,p.length)),f=0,d=-32;d<b;++d)p&&(m^=p.charCodeAt((d+32)%p.length)),d===0&&(h=m),m^=m<<10,m^=m>>>15,m^=m<<4,m^=m>>>13,d>=0&&(h=h+1640531527|0,c=g[d&127]^=m+h,f=c==0?f+1:0);for(f>=128&&(g[(p&&p.length||0)&127]=-1),f=127,d=4*128;d>0;--d)m=g[f+34&127],c=g[f=f+1&127],m^=m<<13,c^=c<<17,m^=m>>>15,c^=c>>>12,g[f]=m^c;u.w=h,u.X=g,u.i=f}l(a,i)}function o(i,a){return a.i=i.i,a.w=i.w,a.X=i.X.slice(),a}function s(i,a){i==null&&(i=+new Date);var l=new n(i),u=a&&a.state,p=function(){return(l.next()>>>0)/4294967296};return p.double=function(){do var c=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=l.next,p.quick=p,u&&(u.X&&o(u,l),p.state=function(){return o(l,{})}),p}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xor4096=s})(eL,typeof O_=="object"&&O_,typeof define=="function"&&define)});var nL=hr((rL,z_)=>{(function(r,e,t){function n(i){var a=this,l="";a.next=function(){var p=a.b,c=a.c,m=a.d,f=a.a;return p=p<<25^p>>>7^c,c=c-m|0,m=m<<24^m>>>8^f,f=f-p|0,a.b=p=p<<20^p>>>12^c,a.c=c=c-m|0,a.d=m<<16^c>>>16^f,a.a=f-p|0},a.a=0,a.b=0,a.c=2654435769|0,a.d=1367130551,i===Math.floor(i)?(a.a=i/4294967296|0,a.b=i|0):l+=i;for(var u=0;u<l.length+20;u++)a.b^=l.charCodeAt(u)|0,a.next()}function o(i,a){return a.a=i.a,a.b=i.b,a.c=i.c,a.d=i.d,a}function s(i,a){var l=new n(i),u=a&&a.state,p=function(){return(l.next()>>>0)/4294967296};return p.double=function(){do var c=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=l.next,p.quick=p,u&&(typeof u=="object"&&o(u,l),p.state=function(){return o(l,{})}),p}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.tychei=s})(rL,typeof z_=="object"&&z_,typeof define=="function"&&define)});var G_=hr(()=>{});var oL=hr((GGe,jx)=>{(function(r,e){var t=this,n=256,o=6,s=52,i="random",a=e.pow(n,o),l=e.pow(2,s),u=l*2,p=n-1,c;function m(T,k,I){var S=[];k=k==!0?{entropy:!0}:k||{};var N=g(h(k.entropy?[T,y(r)]:T==null?b():T,3),S),F=new f(S),$=function(){for(var O=F.g(o),V=a,q=0;O<l;)O=(O+q)*n,V*=n,q=F.g(1);for(;O>=u;)O/=2,V/=2,q>>>=1;return(O+q)/V};return $.int32=function(){return F.g(4)|0},$.quick=function(){return F.g(4)/4294967296},$.double=$,g(y(F.S),r),(k.pass||I||function(O,V,q,W){return W&&(W.S&&d(W,F),O.state=function(){return d(F,{})}),q?(e[i]=O,V):O})($,N,"global"in k?k.global:this==e,k.state)}e["seed"+i]=m;function f(T){var k,I=T.length,S=this,N=0,F=S.i=S.j=0,$=S.S=[];for(I||(T=[I++]);N<n;)$[N]=N++;for(N=0;N<n;N++)$[N]=$[F=p&F+T[N%I]+(k=$[N])],$[F]=k;(S.g=function(O){for(var V,q=0,W=S.i,Y=S.j,Z=S.S;O--;)V=Z[W=p&W+1],q=q*n+Z[p&(Z[W]=Z[Y=p&Y+V])+(Z[Y]=V)];return S.i=W,S.j=Y,q})(n)}function d(T,k){return k.i=T.i,k.j=T.j,k.S=T.S.slice(),k}function h(T,k){var I=[],S=typeof T,N;if(k&&S=="object")for(N in T)try{I.push(h(T[N],k-1))}catch(F){}return I.length?I:S=="string"?T:T+"\0"}function g(T,k){for(var I=T+"",S,N=0;N<I.length;)k[p&N]=p&(S^=k[p&N]*19)+I.charCodeAt(N++);return y(k)}function b(){try{var T;return c&&(T=c.randomBytes)?T=T(n):(T=new Uint8Array(n),(t.crypto||t.msCrypto).getRandomValues(T)),y(T)}catch(S){var k=t.navigator,I=k&&k.plugins;return[+new Date,t,I,t.screen,y(r)]}}function y(T){return String.fromCharCode.apply(0,T)}if(g(e.random(),r),typeof jx=="object"&&jx.exports){jx.exports=m;try{c=G_()}catch(T){}}else typeof define=="function"&&define.amd&&define(function(){return m})})([],Math)});var Hx=hr((WGe,sL)=>{var cQ=HR(),mQ=XR(),fQ=ZR(),dQ=QR(),hQ=tL(),gQ=nL(),Up=oL();Up.alea=cQ;Up.xor128=mQ;Up.xorwow=fQ;Up.xorshift7=dQ;Up.xor4096=hQ;Up.tychei=gQ;sL.exports=Up});var U3=hr((V3,aA)=>{(function(r,e,t){function n(a){var l=this,u=i();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=u(" "),l.s1=u(" "),l.s2=u(" "),l.s0-=u(a),l.s0<0&&(l.s0+=1),l.s1-=u(a),l.s1<0&&(l.s1+=1),l.s2-=u(a),l.s2<0&&(l.s2+=1),u=null}function o(a,l){return l.c=a.c,l.s0=a.s0,l.s1=a.s1,l.s2=a.s2,l}function s(a,l){var u=new n(a),p=l&&l.state,c=u.next;return c.int32=function(){return u.next()*4294967296|0},c.double=function(){return c()+(c()*2097152|0)*11102230246251565e-32},c.quick=c,p&&(typeof p=="object"&&o(p,u),c.state=function(){return o(u,{})}),c}function i(){var a=4022871197,l=function(u){u=String(u);for(var p=0;p<u.length;p++){a+=u.charCodeAt(p);var c=.02519603282416938*a;a=c>>>0,c-=a,c*=a,a=c>>>0,c-=a,a+=c*4294967296}return(a>>>0)*23283064365386963e-26};return l}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.alea=s})(V3,typeof aA=="object"&&aA,typeof define=="function"&&define)});var H3=hr((j3,iA)=>{(function(r,e,t){function n(i){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},i===(i|0)?a.x=i:l+=i;for(var u=0;u<l.length+64;u++)a.x^=l.charCodeAt(u)|0,a.next()}function o(i,a){return a.x=i.x,a.y=i.y,a.z=i.z,a.w=i.w,a}function s(i,a){var l=new n(i),u=a&&a.state,p=function(){return(l.next()>>>0)/4294967296};return p.double=function(){do var c=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=l.next,p.quick=p,u&&(typeof u=="object"&&o(u,l),p.state=function(){return o(l,{})}),p}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xor128=s})(j3,typeof iA=="object"&&iA,typeof define=="function"&&define)});var X3=hr((q3,lA)=>{(function(r,e,t){function n(i){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,i===(i|0)?a.x=i:l+=i;for(var u=0;u<l.length+64;u++)a.x^=l.charCodeAt(u)|0,u==l.length&&(a.d=a.x<<10^a.x>>>4),a.next()}function o(i,a){return a.x=i.x,a.y=i.y,a.z=i.z,a.w=i.w,a.v=i.v,a.d=i.d,a}function s(i,a){var l=new n(i),u=a&&a.state,p=function(){return(l.next()>>>0)/4294967296};return p.double=function(){do var c=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=l.next,p.quick=p,u&&(typeof u=="object"&&o(u,l),p.state=function(){return o(l,{})}),p}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xorwow=s})(q3,typeof lA=="object"&&lA,typeof define=="function"&&define)});var Z3=hr((Y3,uA)=>{(function(r,e,t){function n(i){var a=this;a.next=function(){var u=a.x,p=a.i,c,m,f;return c=u[p],c^=c>>>7,m=c^c<<24,c=u[p+1&7],m^=c^c>>>10,c=u[p+3&7],m^=c^c>>>3,c=u[p+4&7],m^=c^c<<7,c=u[p+7&7],c=c^c<<13,m^=c^c<<9,u[p]=m,a.i=p+1&7,m};function l(u,p){var c,m,f=[];if(p===(p|0))m=f[0]=p;else for(p=""+p,c=0;c<p.length;++c)f[c&7]=f[c&7]<<15^p.charCodeAt(c)+f[c+1&7]<<13;for(;f.length<8;)f.push(0);for(c=0;c<8&&f[c]===0;++c);for(c==8?m=f[7]=-1:m=f[c],u.x=f,u.i=0,c=256;c>0;--c)u.next()}l(a,i)}function o(i,a){return a.x=i.x.slice(),a.i=i.i,a}function s(i,a){i==null&&(i=+new Date);var l=new n(i),u=a&&a.state,p=function(){return(l.next()>>>0)/4294967296};return p.double=function(){do var c=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=l.next,p.quick=p,u&&(u.x&&o(u,l),p.state=function(){return o(l,{})}),p}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xorshift7=s})(Y3,typeof uA=="object"&&uA,typeof define=="function"&&define)});var Q3=hr((J3,pA)=>{(function(r,e,t){function n(i){var a=this;a.next=function(){var u=a.w,p=a.X,c=a.i,m,f;return a.w=u=u+1640531527|0,f=p[c+34&127],m=p[c=c+1&127],f^=f<<13,m^=m<<17,f^=f>>>15,m^=m>>>12,f=p[c]=f^m,a.i=c,f+(u^u>>>16)|0};function l(u,p){var c,m,f,d,h,g=[],b=128;for(p===(p|0)?(m=p,p=null):(p=p+"\0",m=0,b=Math.max(b,p.length)),f=0,d=-32;d<b;++d)p&&(m^=p.charCodeAt((d+32)%p.length)),d===0&&(h=m),m^=m<<10,m^=m>>>15,m^=m<<4,m^=m>>>13,d>=0&&(h=h+1640531527|0,c=g[d&127]^=m+h,f=c==0?f+1:0);for(f>=128&&(g[(p&&p.length||0)&127]=-1),f=127,d=4*128;d>0;--d)m=g[f+34&127],c=g[f=f+1&127],m^=m<<13,c^=c<<17,m^=m>>>15,c^=c>>>12,g[f]=m^c;u.w=h,u.X=g,u.i=f}l(a,i)}function o(i,a){return a.i=i.i,a.w=i.w,a.X=i.X.slice(),a}function s(i,a){i==null&&(i=+new Date);var l=new n(i),u=a&&a.state,p=function(){return(l.next()>>>0)/4294967296};return p.double=function(){do var c=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=l.next,p.quick=p,u&&(u.X&&o(u,l),p.state=function(){return o(l,{})}),p}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xor4096=s})(J3,typeof pA=="object"&&pA,typeof define=="function"&&define)});var tG=hr((eG,cA)=>{(function(r,e,t){function n(i){var a=this,l="";a.next=function(){var p=a.b,c=a.c,m=a.d,f=a.a;return p=p<<25^p>>>7^c,c=c-m|0,m=m<<24^m>>>8^f,f=f-p|0,a.b=p=p<<20^p>>>12^c,a.c=c=c-m|0,a.d=m<<16^c>>>16^f,a.a=f-p|0},a.a=0,a.b=0,a.c=2654435769|0,a.d=1367130551,i===Math.floor(i)?(a.a=i/4294967296|0,a.b=i|0):l+=i;for(var u=0;u<l.length+20;u++)a.b^=l.charCodeAt(u)|0,a.next()}function o(i,a){return a.a=i.a,a.b=i.b,a.c=i.c,a.d=i.d,a}function s(i,a){var l=new n(i),u=a&&a.state,p=function(){return(l.next()>>>0)/4294967296};return p.double=function(){do var c=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=l.next,p.quick=p,u&&(typeof u=="object"&&o(u,l),p.state=function(){return o(l,{})}),p}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.tychei=s})(eG,typeof cA=="object"&&cA,typeof define=="function"&&define)});var nG=hr((rG,Fk)=>{(function(r,e,t){var n=256,o=6,s=52,i="random",a=t.pow(n,o),l=t.pow(2,s),u=l*2,p=n-1,c;function m(T,k,I){var S=[];k=k==!0?{entropy:!0}:k||{};var N=g(h(k.entropy?[T,y(e)]:T==null?b():T,3),S),F=new f(S),$=function(){for(var O=F.g(o),V=a,q=0;O<l;)O=(O+q)*n,V*=n,q=F.g(1);for(;O>=u;)O/=2,V/=2,q>>>=1;return(O+q)/V};return $.int32=function(){return F.g(4)|0},$.quick=function(){return F.g(4)/4294967296},$.double=$,g(y(F.S),e),(k.pass||I||function(O,V,q,W){return W&&(W.S&&d(W,F),O.state=function(){return d(F,{})}),q?(t[i]=O,V):O})($,N,"global"in k?k.global:this==t,k.state)}function f(T){var k,I=T.length,S=this,N=0,F=S.i=S.j=0,$=S.S=[];for(I||(T=[I++]);N<n;)$[N]=N++;for(N=0;N<n;N++)$[N]=$[F=p&F+T[N%I]+(k=$[N])],$[F]=k;(S.g=function(O){for(var V,q=0,W=S.i,Y=S.j,Z=S.S;O--;)V=Z[W=p&W+1],q=q*n+Z[p&(Z[W]=Z[Y=p&Y+V])+(Z[Y]=V)];return S.i=W,S.j=Y,q})(n)}function d(T,k){return k.i=T.i,k.j=T.j,k.S=T.S.slice(),k}function h(T,k){var I=[],S=typeof T,N;if(k&&S=="object")for(N in T)try{I.push(h(T[N],k-1))}catch(F){}return I.length?I:S=="string"?T:T+"\0"}function g(T,k){for(var I=T+"",S,N=0;N<I.length;)k[p&N]=p&(S^=k[p&N]*19)+I.charCodeAt(N++);return y(k)}function b(){try{var T;return c&&(T=c.randomBytes)?T=T(n):(T=new Uint8Array(n),(r.crypto||r.msCrypto).getRandomValues(T)),y(T)}catch(S){var k=r.navigator,I=k&&k.plugins;return[+new Date,r,I,r.screen,y(e)]}}function y(T){return String.fromCharCode.apply(0,T)}if(g(t.random(),e),typeof Fk=="object"&&Fk.exports){Fk.exports=m;try{c=G_()}catch(T){}}else typeof define=="function"&&define.amd?define(function(){return m}):t["seed"+i]=m})(typeof self!="undefined"?self:rG,[],Math)});var mA=hr((Bfr,oG)=>{var gfe=U3(),bfe=H3(),yfe=X3(),xfe=Z3(),Tfe=Q3(),kfe=tG(),lm=nG();lm.alea=gfe;lm.xor128=bfe;lm.xorwow=yfe;lm.xorshift7=xfe;lm.xor4096=Tfe;lm.tychei=kfe;oG.exports=lm});var MG=hr(()=>{});var eh=hr(()=>{});var N5=hr(()=>{});var A5=hr(()=>{});var D5=hr((zI,J1)=>{var Z1=function(){var r=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(r=r||__filename),function(e){e=e||{};function t(){return ae.buffer!=ot&&Or(ae.buffer),At}function n(){return ae.buffer!=ot&&Or(ae.buffer),Et}function o(){return ae.buffer!=ot&&Or(ae.buffer),Nr}function s(){return ae.buffer!=ot&&Or(ae.buffer),Zn}function i(){return ae.buffer!=ot&&Or(ae.buffer),es}var a=typeof e!="undefined"?e:{},l,u;a.ready=new Promise(function(D,B){l=D,u=B});var p={},c;for(c in a)a.hasOwnProperty(c)&&(p[c]=a[c]);var m=[],f="./this.program",d=function(D,B){throw B},h=!1,g=!1,b=!1,y=!1;h=typeof window=="object",g=typeof importScripts=="function",b=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",y=!h&&!b&&!g;var T=a.ENVIRONMENT_IS_PTHREAD||!1;T&&(ot=a.buffer);var k="";function I(D){return a.locateFile?a.locateFile(D,k):k+D}var S,N,F,$,O,V;if(b){g?k=eh().dirname(k)+"/":k=__dirname+"/",S=function(B,H){return O||(O=Ap("fs")),V||(V=eh()),B=V.normalize(B),O.readFileSync(B,H?null:"utf8")},F=function(B){var H=S(B,!0);return H.buffer||(H=new Uint8Array(H)),xe(H.buffer),H},process.argv.length>1&&(f=process.argv[1].replace(/\\/g,"/")),m=process.argv.slice(2),process.on("uncaughtException",function(D){if(!(D instanceof ch))throw D}),process.on("unhandledRejection",Oi),d=function(D){process.exit(D)},a.inspect=function(){return"[Emscripten Module object]"};var q;try{q=N5()}catch(D){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),D}global.Worker=q.Worker}else y?(typeof read!="undefined"&&(S=function(B){return read(B)}),F=function(B){var H;return typeof readbuffer=="function"?new Uint8Array(readbuffer(B)):(H=read(B,"binary"),xe(typeof H=="object"),H)},typeof scriptArgs!="undefined"?m=scriptArgs:typeof arguments!="undefined"&&(m=arguments),typeof quit=="function"&&(d=function(D){quit(D)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(h||g)&&(g?k=self.location.href:typeof document!="undefined"&&document.currentScript&&(k=document.currentScript.src),typeof r!="undefined"&&r&&(k=r),k.indexOf("blob:")!==0?k=k.substr(0,k.lastIndexOf("/")+1):k="",b?(S=function(B,H){return O||(O=Ap("fs")),V||(V=eh()),B=V.normalize(B),O.readFileSync(B,H?null:"utf8")},F=function(B){var H=S(B,!0);return H.buffer||(H=new Uint8Array(H)),xe(H.buffer),H}):(S=function(D){var B=new XMLHttpRequest;return B.open("GET",D,!1),B.send(null),B.responseText},g&&(F=function(D){var B=new XMLHttpRequest;return B.open("GET",D,!1),B.responseType="arraybuffer",B.send(null),new Uint8Array(B.response)}),N=function(D,B,H){var Q=new XMLHttpRequest;Q.open("GET",D,!0),Q.responseType="arraybuffer",Q.onload=function(){if(Q.status==200||Q.status==0&&Q.response){B(Q.response);return}H()},Q.onerror=H,Q.send(null)}),$=function(D){document.title=D});b&&typeof performance=="undefined"&&(global.performance=A5().performance);var W=a.print||console.log.bind(console),Y=a.printErr||console.warn.bind(console);for(c in p)p.hasOwnProperty(c)&&(a[c]=p[c]);p=null,a.arguments&&(m=a.arguments),a.thisProgram&&(f=a.thisProgram),a.quit&&(d=a.quit);var Z=Atomics.load,J=Atomics.store,se=Atomics.compareExchange,ee;a.wasmBinary&&(ee=a.wasmBinary);var le=a.noExitRuntime||!0;typeof WebAssembly!="object"&&Oi("no native wasm support detected");var ae,ce,ye=!1,me;function xe(D,B){D||Oi("Assertion failed: "+B)}function ke(D){var B=a["_"+D];return xe(B,"Cannot call unknown function "+D+", make sure it is exported"),B}function we(D,B,H,Q,Ce){var Ie={string:function(Dn){var Em=0;if(Dn!=null&&Dn!==0){var dE=(Dn.length<<2)+1;Em=Nm(dE),at(Dn,Em,dE)}return Em},array:function(Dn){var Em=Nm(Dn.length);return qt(Dn,Em),Em}};function _e(Dn){return B==="string"?Ee(Dn):B==="boolean"?Boolean(Dn):Dn}var $e=ke(D),zt=[],Qr=0;if(Q)for(var Hr=0;Hr<Q.length;Hr++){var Iu=Ie[H[Hr]];Iu?(Qr===0&&(Qr=ph()),zt[Hr]=Iu(Q[Hr])):zt[Hr]=Q[Hr]}var Dm=$e.apply(null,zt);return Dm=_e(Dm),Qr!==0&&Sm(Qr),Dm}function Ne(D,B,H,Q){H=H||[];var Ce=H.every(function(_e){return _e==="number"}),Ie=B!=="string";return Ie&&Ce&&!Q?ke(D):function(){return we(D,B,H,arguments,Q)}}function Oe(D,B,H){for(var Q=B+H,Ce="";!(B>=Q);){var Ie=D[B++];if(!Ie)return Ce;if(!(Ie&128)){Ce+=String.fromCharCode(Ie);continue}var _e=D[B++]&63;if((Ie&224)==192){Ce+=String.fromCharCode((Ie&31)<<6|_e);continue}var $e=D[B++]&63;if((Ie&240)==224?Ie=(Ie&15)<<12|_e<<6|$e:Ie=(Ie&7)<<18|_e<<12|$e<<6|D[B++]&63,Ie<65536)Ce+=String.fromCharCode(Ie);else{var zt=Ie-65536;Ce+=String.fromCharCode(55296|zt>>10,56320|zt&1023)}}return Ce}function Ee(D,B){return D?Oe(n(),D,B):""}function Ye(D,B,H,Q){if(!(Q>0))return 0;for(var Ce=H,Ie=H+Q-1,_e=0;_e<D.length;++_e){var $e=D.charCodeAt(_e);if($e>=55296&&$e<=57343){var zt=D.charCodeAt(++_e);$e=65536+(($e&1023)<<10)|zt&1023}if($e<=127){if(H>=Ie)break;B[H++]=$e}else if($e<=2047){if(H+1>=Ie)break;B[H++]=192|$e>>6,B[H++]=128|$e&63}else if($e<=65535){if(H+2>=Ie)break;B[H++]=224|$e>>12,B[H++]=128|$e>>6&63,B[H++]=128|$e&63}else{if(H+3>=Ie)break;B[H++]=240|$e>>18,B[H++]=128|$e>>12&63,B[H++]=128|$e>>6&63,B[H++]=128|$e&63}}return B[H]=0,H-Ce}function at(D,B,H){return Ye(D,n(),B,H)}function wt(D){for(var B=0,H=0;H<D.length;++H){var Q=D.charCodeAt(H);Q>=55296&&Q<=57343&&(Q=65536+((Q&1023)<<10)|D.charCodeAt(++H)&1023),Q<=127?++B:Q<=2047?B+=2:Q<=65535?B+=3:B+=4}return B}function qt(D,B){t().set(D,B)}function Xt(D,B){return D%B>0&&(D+=B-D%B),D}var ot,At,Et,ur,ho,Nr,Zn,xn,es;function Or(D){ot=D,a.HEAP8=At=new Int8Array(D),a.HEAP16=ur=new Int16Array(D),a.HEAP32=Nr=new Int32Array(D),a.HEAPU8=Et=new Uint8Array(D),a.HEAPU16=ho=new Uint16Array(D),a.HEAPU32=Zn=new Uint32Array(D),a.HEAPF32=xn=new Float32Array(D),a.HEAPF64=es=new Float64Array(D)}var go=a.INITIAL_MEMORY||16777216;if(T)ae=a.wasmMemory,ot=a.buffer;else if(a.wasmMemory)ae=a.wasmMemory;else if(ae=new WebAssembly.Memory({initial:go/65536,maximum:2147483648/65536,shared:!0}),!(ae.buffer instanceof SharedArrayBuffer))throw Y("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),b&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");ae&&(ot=ae.buffer),go=ot.byteLength,Or(ot);var An,Jr=[],Jn=[],So=[],wp=[],bu=[],ti=!1,Pi=!1;T||Jn.push({func:function(){ax()}});function th(){if(!T){if(a.preRun)for(typeof a.preRun=="function"&&(a.preRun=[a.preRun]);a.preRun.length;)Hy(a.preRun.shift());vm(Jr)}}function _p(){ti=!0,!T&&vm(Jn)}function VI(){T||vm(So)}function jy(){T||(Pi=!0)}function Qn(){if(!T){if(a.postRun)for(typeof a.postRun=="function"&&(a.postRun=[a.postRun]);a.postRun.length;)UI(a.postRun.shift());vm(bu)}}function Hy(D){Jr.unshift(D)}function UI(D){bu.unshift(D)}var Bi=0,yu=null,Cp=null;function jI(D){xe(!T,"addRunDependency cannot be used in a pthread worker"),Bi++,a.monitorRunDependencies&&a.monitorRunDependencies(Bi)}function HI(D){if(Bi--,a.monitorRunDependencies&&a.monitorRunDependencies(Bi),Bi==0&&(yu!==null&&(clearInterval(yu),yu=null),Cp)){var B=Cp;Cp=null,B()}}a.preloadedImages={},a.preloadedAudios={};function Oi(D){a.onAbort&&a.onAbort(D),T&&console.error("Pthread aborting at "+new Error().stack),D+="",Y(D),ye=!0,me=1,D="abort("+D+"). Build with -s ASSERTIONS=1 for more info.";var B=new WebAssembly.RuntimeError(D);throw u(B),B}function qy(D,B){return String.prototype.startsWith?D.startsWith(B):D.indexOf(B)===0}var Im="data:application/octet-stream;base64,";function Xy(D){return qy(D,Im)}var qI="file://";function Yy(D){return qy(D,qI)}var eo="tfjs-backend-wasm-threaded-simd.wasm";Xy(eo)||(eo=I(eo));function Zy(D){try{if(D==eo&&ee)return new Uint8Array(ee);if(F)return F(D);throw"both async and sync fetching of the wasm failed"}catch(B){Oi(B)}}function XI(){if(!ee&&(h||g)){if(typeof fetch=="function"&&!Yy(eo))return fetch(eo,{credentials:"same-origin"}).then(function(D){if(!D.ok)throw"failed to load wasm binary file at '"+eo+"'";return D.arrayBuffer()}).catch(function(){return Zy(eo)});if(N)return new Promise(function(D,B){N(eo,function(H){D(new Uint8Array(H))},B)})}return Promise.resolve().then(function(){return Zy(eo)})}function YI(){var D={a:zv};function B(_e,$e){var zt=_e.exports;if(a.asm=zt,An=a.asm.F,ce=$e,!T){var Qr=Pe.unusedWorkers.length;Pe.unusedWorkers.forEach(function(Hr){Pe.loadWasmModuleToWorker(Hr,function(){--Qr||HI("wasm-instantiate")})})}}T||jI("wasm-instantiate");function H(_e){B(_e.instance,_e.module)}function Q(_e){return XI().then(function($e){return WebAssembly.instantiate($e,D)}).then(_e,function($e){Y("failed to asynchronously prepare wasm: "+$e),Oi($e)})}function Ce(){return!ee&&typeof WebAssembly.instantiateStreaming=="function"&&!Xy(eo)&&!Yy(eo)&&typeof fetch=="function"?fetch(eo,{credentials:"same-origin"}).then(function(_e){var $e=WebAssembly.instantiateStreaming(_e,D);return $e.then(H,function(zt){return Y("wasm streaming compile failed: "+zt),Y("falling back to ArrayBuffer instantiation"),Q(H)})}):Q(H)}if(a.instantiateWasm)try{var Ie=a.instantiateWasm(D,B);return Ie}catch(_e){return Y("Module.instantiateWasm callback failed with error: "+_e),!1}return Ce().catch(u),{}}var ZI={9816:function(){throw"Canceled!"},9834:function(D,B){setTimeout(function(){lE(D,B)},0)}};function Jy(){Pe.initRuntime()}function vm(D){for(;D.length>0;){var B=D.shift();if(typeof B=="function"){B(a);continue}var H=B.func;typeof H=="number"?B.arg===void 0?An.get(H)():An.get(H)(B.arg):H(B.arg===void 0?null:B.arg)}}function rh(D,B){if(D<=0||D>t().length||D&!0||B<0)return-28;if(B==0)return 0;B>=2147483647&&(B=Infinity);var H=Atomics.load(o(),Am>>2),Q=0;if(H==D){var Ce=Atomics.compareExchange(o(),Am>>2,H,0);if(Ce==H&&(--B,Q=1,B<=0))return 1}var Ie=Atomics.notify(o(),D>>2,B);if(Ie>=0)return Ie+Q;throw"Atomics.notify returned an unexpected value "+Ie}a._emscripten_futex_wake=rh;function JI(D){if(T)throw"Internal Error! killThread() can only ever be called from main application thread!";if(!D)throw"Internal Error! Null pthread_ptr in killThread!";o()[D+12>>2]=0;var B=Pe.pthreads[D];B.worker.terminate(),Pe.freeThreadData(B),Pe.runningWorkers.splice(Pe.runningWorkers.indexOf(B.worker),1),B.worker.pthread=void 0}function QI(D){if(T)throw"Internal Error! cancelThread() can only ever be called from main application thread!";if(!D)throw"Internal Error! Null pthread_ptr in cancelThread!";var B=Pe.pthreads[D];B.worker.postMessage({cmd:"cancel"})}function ev(D){if(T)throw"Internal Error! cleanupThread() can only ever be called from main application thread!";if(!D)throw"Internal Error! Null pthread_ptr in cleanupThread!";var B=Pe.pthreads[D];if(B){o()[D+12>>2]=0;var H=B.worker;Pe.returnWorkerToPool(H)}}var Pe={unusedWorkers:[],runningWorkers:[],initMainThreadBlock:function(){for(var D=Math.min(4,Math.max(1,(navigator.hardwareConcurrency||1)/2)),B=0;B<D;++B)Pe.allocateUnusedWorker()},initRuntime:function(){for(var D=Np(228),B=0;B<228/4;++B)s()[D/4+B]=0;o()[D+12>>2]=D;var H=D+152;o()[H>>2]=H;for(var Q=Np(512),B=0;B<128;++B)s()[Q/4+B]=0;Atomics.store(s(),D+100>>2,Q),Atomics.store(s(),D+40>>2,D),cw(D,!g,1),iE(D)},initWorker:function(){},pthreads:{},threadExitHandlers:[],setThreadStatus:function(){},runExitHandlers:function(){for(;Pe.threadExitHandlers.length>0;)Pe.threadExitHandlers.pop()();T&&Cm()&&aE()},runExitHandlersAndDeinitThread:function(D,B){Atomics.store(s(),D+56>>2,1),Atomics.store(s(),D+60>>2,0),Pe.runExitHandlers(),Atomics.store(s(),D+4>>2,B),Atomics.store(s(),D+0>>2,1),rh(D+0,2147483647),cw(0,0,0)},threadExit:function(D){var B=Cm();B&&(Pe.runExitHandlersAndDeinitThread(B,D),T&&postMessage({cmd:"exit"}))},threadCancel:function(){Pe.runExitHandlersAndDeinitThread(Cm(),-1),postMessage({cmd:"cancelDone"})},terminateAllThreads:function(){for(var D in Pe.pthreads){var B=Pe.pthreads[D];B&&B.worker&&Pe.returnWorkerToPool(B.worker)}Pe.pthreads={};for(var H=0;H<Pe.unusedWorkers.length;++H){var Q=Pe.unusedWorkers[H];Q.terminate()}Pe.unusedWorkers=[];for(var H=0;H<Pe.runningWorkers.length;++H){var Q=Pe.runningWorkers[H],B=Q.pthread;Pe.freeThreadData(B),Q.terminate()}Pe.runningWorkers=[]},freeThreadData:function(D){if(!!D){if(D.threadInfoStruct){var B=o()[D.threadInfoStruct+100>>2];o()[D.threadInfoStruct+100>>2]=0,uh(B),uh(D.threadInfoStruct)}D.threadInfoStruct=0,D.allocatedOwnStack&&D.stackBase&&uh(D.stackBase),D.stackBase=0,D.worker&&(D.worker.pthread=null)}},returnWorkerToPool:function(D){Pe.runWithoutMainThreadQueuedCalls(function(){delete Pe.pthreads[D.pthread.threadInfoStruct],Pe.unusedWorkers.push(D),Pe.runningWorkers.splice(Pe.runningWorkers.indexOf(D),1),Pe.freeThreadData(D.pthread),D.pthread=void 0})},runWithoutMainThreadQueuedCalls:function(D){o()[fE>>2]=0;try{D()}finally{o()[fE>>2]=1}},receiveObjectTransfer:function(D){},loadWasmModuleToWorker:function(D,B){D.onmessage=function(H){var Q=H.data,Ce=Q.cmd;if(D.pthread&&(Pe.currentProxiedOperationCallerThread=D.pthread.threadInfoStruct),Q.targetThread&&Q.targetThread!=Cm()){var Ie=Pe.pthreads[Q.targetThread];Ie?Ie.worker.postMessage(H.data,Q.transferList):console.error('Internal error! Worker sent a message "'+Ce+'" to target pthread '+Q.targetThread+", but that thread no longer exists!"),Pe.currentProxiedOperationCallerThread=void 0;return}if(Ce==="processQueuedMainThreadWork")uw();else if(Ce==="spawnThread")ox(H.data);else if(Ce==="cleanupThread")ev(Q.thread);else if(Ce==="killThread")JI(Q.thread);else if(Ce==="cancelThread")QI(Q.thread);else if(Ce==="loaded")D.loaded=!0,B&&B(D),D.runPthread&&(D.runPthread(),delete D.runPthread);else if(Ce==="print")W("Thread "+Q.threadId+": "+Q.text);else if(Ce==="printErr")Y("Thread "+Q.threadId+": "+Q.text);else if(Ce==="alert")alert("Thread "+Q.threadId+": "+Q.text);else if(Ce==="exit"){var _e=D.pthread&&Atomics.load(s(),D.pthread.threadInfoStruct+64>>2);_e&&Pe.returnWorkerToPool(D)}else if(Ce==="exitProcess")try{vX(Q.returnCode)}catch($e){if($e instanceof ch)return;throw $e}else Ce==="cancelDone"?Pe.returnWorkerToPool(D):Ce==="objectTransfer"?Pe.receiveObjectTransfer(H.data):H.data.target==="setimmediate"?D.postMessage(H.data):Y("worker sent an unknown command "+Ce);Pe.currentProxiedOperationCallerThread=void 0},D.onerror=function(H){Y("pthread sent an error! "+H.filename+":"+H.lineno+": "+H.message)},b&&(D.on("message",function(H){D.onmessage({data:H})}),D.on("error",function(H){D.onerror(H)}),D.on("exit",function(H){})),D.postMessage({cmd:"load",urlOrBlob:a.mainScriptUrlOrBlob||r,wasmMemory:ae,wasmModule:ce})},allocateUnusedWorker:function(){var D=I("tfjs-backend-wasm-threaded-simd.worker.js");Pe.unusedWorkers.push(new Worker(D))},getNewWorker:function(){return Pe.unusedWorkers.length==0&&(Pe.allocateUnusedWorker(),Pe.loadWasmModuleToWorker(Pe.unusedWorkers[0])),Pe.unusedWorkers.length>0?Pe.unusedWorkers.pop():null},busySpinWait:function(D){for(var B=performance.now()+D;performance.now()<B;);}};function tv(D,B){cE(D,B),Sm(D)}a.establishStackSpace=tv;function rv(){return le}a.getNoExitRuntime=rv;function nv(D,B){return An.get(D)(B)}a.invokeEntryPoint=nv;function ov(D,B,H,Q){Oi("Assertion failed: "+Ee(D)+", at: "+[B?Ee(B):"unknown filename",H,Q?Ee(Q):"unknown function"])}function sv(D,B){var H=_main(D,B)}var Sp;b?Sp=function(){var D=process.hrtime();return D[0]*1e3+D[1]/1e6}:T?Sp=function(){return performance.now()-a.__performance_now_clock_drift}:typeof dateNow!="undefined"?Sp=dateNow:Sp=function(){return performance.now()};function av(D){return o()[oE()>>2]=D,D}function iv(D,B){if(T)return xu(1,1,D,B)}function lv(D,B){if(D==B)postMessage({cmd:"processQueuedMainThreadWork"});else if(T)postMessage({targetThread:D,cmd:"processThreadQueue"});else{var H=Pe.pthreads[D],Q=H&&H.worker;if(!Q)return;Q.postMessage({cmd:"processThreadQueue"})}return 1}function uv(){Oi()}function pv(D,B,H){var Q=hv(B,H);return ZI[D].apply(null,Q)}function cv(D,B){}function mv(D,B,H){if(D<=0||D>t().length||D&!0)return-28;if(h){if(Atomics.load(o(),D>>2)!=B)return-6;for(var Ce=performance.now(),Ie=Ce+H,_e=Atomics.exchange(o(),Am>>2,D);;){if(Ce=performance.now(),Ce>Ie)return _e=Atomics.exchange(o(),Am>>2,0),-73;if(_e=Atomics.exchange(o(),Am>>2,0),_e==0)break;if(uw(),Atomics.load(o(),D>>2)!=B)return-6;_e=Atomics.exchange(o(),Am>>2,D)}return 0}else{var Q=Atomics.wait(o(),D>>2,B,H);if(Q==="timed-out")return-73;if(Q==="not-equal")return-6;if(Q==="ok")return 0;throw"Atomics.wait returned an unexpected value "+Q}}function fv(D,B,H){n().copyWithin(D,B,B+H)}function dv(){return b?Ap("os").cpus().length:navigator.hardwareConcurrency}function xu(D,B){for(var H=arguments.length-2,Q=ph(),Ce=H,Ie=Nm(Ce*8),_e=Ie>>3,$e=0;$e<H;$e++){var zt=arguments[2+$e];i()[_e+$e]=zt}var Qr=pE(D,Ce,Ie,B);return Sm(Q),Qr}var nh=[],oh=[];function hv(D,B){oh.length=0;var H;for(B>>=2;H=n()[D++];){var Q=H<105;Q&&B&1&&B++,oh.push(Q?i()[B++>>1]:o()[B]),++B}return oh}function gv(D,B,H){nh.length=B;for(var Q=H>>3,Ce=0;Ce<B;Ce++)nh[Ce]=i()[Q+Ce];var Ie=D<0,_e=Ie?ZI[-D-1]:Ov[D];return _e.apply(null,nh)}function bv(){return n().length}function yv(D){try{return ae.grow(D-ot.byteLength+65535>>>16),Or(ae.buffer),1}catch(B){}}function xv(D){var B=bv();if(D<=B)return!1;var H=2147483648;if(D>H)return!1;for(var Q=1;Q<=4;Q*=2){var Ce=B*(1+.2/Q);Ce=Math.min(Ce,D+100663296);var Ie=Math.min(H,Xt(Math.max(D,Ce),65536)),_e=yv(Ie);if(_e)return!0}return!1}var pt={inEventHandler:0,removeAllEventListeners:function(){for(var D=pt.eventHandlers.length-1;D>=0;--D)pt._removeHandler(D);pt.eventHandlers=[],pt.deferredCalls=[]},registerRemoveEventListeners:function(){pt.removeEventListenersRegistered||(wp.push(pt.removeAllEventListeners),pt.removeEventListenersRegistered=!0)},deferredCalls:[],deferCall:function(D,B,H){function Q(_e,$e){if(_e.length!=$e.length)return!1;for(var zt in _e)if(_e[zt]!=$e[zt])return!1;return!0}for(var Ce in pt.deferredCalls){var Ie=pt.deferredCalls[Ce];if(Ie.targetFunction==D&&Q(Ie.argsList,H))return}pt.deferredCalls.push({targetFunction:D,precedence:B,argsList:H}),pt.deferredCalls.sort(function(_e,$e){return _e.precedence<$e.precedence})},removeDeferredCalls:function(D){for(var B=0;B<pt.deferredCalls.length;++B)pt.deferredCalls[B].targetFunction==D&&(pt.deferredCalls.splice(B,1),--B)},canPerformEventHandlerRequests:function(){return pt.inEventHandler&&pt.currentEventHandler.allowsDeferredCalls},runDeferredCalls:function(){if(!!pt.canPerformEventHandlerRequests())for(var D=0;D<pt.deferredCalls.length;++D){var B=pt.deferredCalls[D];pt.deferredCalls.splice(D,1),--D,B.targetFunction.apply(null,B.argsList)}},eventHandlers:[],removeAllHandlersOnTarget:function(D,B){for(var H=0;H<pt.eventHandlers.length;++H)pt.eventHandlers[H].target==D&&(!B||B==pt.eventHandlers[H].eventTypeString)&&pt._removeHandler(H--)},_removeHandler:function(D){var B=pt.eventHandlers[D];B.target.removeEventListener(B.eventTypeString,B.eventListenerFunc,B.useCapture),pt.eventHandlers.splice(D,1)},registerOrRemoveHandler:function(D){var B=function(Ce){++pt.inEventHandler,pt.currentEventHandler=D,pt.runDeferredCalls(),D.handlerFunc(Ce),pt.runDeferredCalls(),--pt.inEventHandler};if(D.callbackfunc)D.eventListenerFunc=B,D.target.addEventListener(D.eventTypeString,B,D.useCapture),pt.eventHandlers.push(D),pt.registerRemoveEventListeners();else for(var H=0;H<pt.eventHandlers.length;++H)pt.eventHandlers[H].target==D.target&&pt.eventHandlers[H].eventTypeString==D.eventTypeString&&pt._removeHandler(H--)},queueEventHandlerOnThread_iiii:function(D,B,H,Q,Ce){var Ie=ph(),_e=Nm(12);o()[_e>>2]=H,o()[_e+4>>2]=Q,o()[_e+8>>2]=Ce,pw(0,D,637534208,B,Q,_e),Sm(Ie)},getTargetThreadForEventCallback:function(D){switch(D){case 1:return 0;case 2:return Pe.currentProxiedOperationCallerThread;default:return D}},getNodeNameForTarget:function(D){return D?D==window?"#window":D==screen?"#screen":D&&D.nodeName?D.nodeName:"":""},fullscreenEnabled:function(){return document.fullscreenEnabled||document.webkitFullscreenEnabled}};function Tv(D){var B=wt(D)+1,H=Np(B);return at(D,H,B),H}function kv(D,B,H,Q){var Ce=ph(),Ie=Nm(12),_e=0;B&&(_e=Tv(B)),o()[Ie>>2]=_e,o()[Ie+4>>2]=H,o()[Ie+8>>2]=Q,pw(0,D,657457152,0,_e,Ie),Sm(Ce)}function Iv(D,B,H,Q){B=B?Ee(B):"",kv(D,B,H,Q)}function vv(D){return D>2?Ee(D):D}var wv=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];function _v(D){D=vv(D);var B=wv[D]||(typeof document!="undefined"?document.querySelector(D):void 0);return B}function sh(D){return _v(D)}function Qy(D,B,H){var Q=sh(D);if(!Q)return-4;if(Q.canvasSharedPtr&&(o()[Q.canvasSharedPtr>>2]=B,o()[Q.canvasSharedPtr+4>>2]=H),Q.offscreenCanvas||!Q.controlTransferredOffscreen){Q.offscreenCanvas&&(Q=Q.offscreenCanvas);var Ce=!1;if(Q.GLctxObject&&Q.GLctxObject.GLctx){var Ie=Q.GLctxObject.GLctx.getParameter(2978);Ce=Ie[0]===0&&Ie[1]===0&&Ie[2]===Q.width&&Ie[3]===Q.height}Q.width=B,Q.height=H,Ce&&Q.GLctxObject.GLctx.viewport(0,0,B,H)}else if(Q.canvasSharedPtr){var _e=o()[Q.canvasSharedPtr+8>>2];return Iv(_e,D,B,H),1}else return-4;return 0}function ex(D,B,H){return T?xu(2,1,D,B,H):Qy(D,B,H)}function Cv(D,B,H){var Q=sh(D);return Q?Qy(D,B,H):ex(D,B,H)}function Sv(D){}function Nv(D,B){}function Av(D){var B=D.getExtension("ANGLE_instanced_arrays");if(B)return D.vertexAttribDivisor=function(H,Q){B.vertexAttribDivisorANGLE(H,Q)},D.drawArraysInstanced=function(H,Q,Ce,Ie){B.drawArraysInstancedANGLE(H,Q,Ce,Ie)},D.drawElementsInstanced=function(H,Q,Ce,Ie,_e){B.drawElementsInstancedANGLE(H,Q,Ce,Ie,_e)},1}function Dv(D){var B=D.getExtension("OES_vertex_array_object");if(B)return D.createVertexArray=function(){return B.createVertexArrayOES()},D.deleteVertexArray=function(H){B.deleteVertexArrayOES(H)},D.bindVertexArray=function(H){B.bindVertexArrayOES(H)},D.isVertexArray=function(H){return B.isVertexArrayOES(H)},1}function Ev(D){var B=D.getExtension("WEBGL_draw_buffers");if(B)return D.drawBuffers=function(H,Q){B.drawBuffersWEBGL(H,Q)},1}function Mv(D){return!!(D.multiDrawWebgl=D.getExtension("WEBGL_multi_draw"))}var Mt={counter:1,buffers:[],programs:[],framebuffers:[],renderbuffers:[],textures:[],uniforms:[],shaders:[],vaos:[],contexts:{},offscreenCanvases:{},timerQueriesEXT:[],programInfos:{},stringCache:{},unpackAlignment:4,recordError:function(B){Mt.lastError||(Mt.lastError=B)},getNewId:function(D){for(var B=Mt.counter++,H=D.length;H<B;H++)D[H]=null;return B},getSource:function(D,B,H,Q){for(var Ce="",Ie=0;Ie<B;++Ie){var _e=Q?o()[Q+Ie*4>>2]:-1;Ce+=Ee(o()[H+Ie*4>>2],_e<0?void 0:_e)}return Ce},createContext:function(D,B){var H=D.getContext("webgl",B);if(!H)return 0;var Q=Mt.registerContext(H,B);return Q},registerContext:function(D,B){var H=Np(8);o()[H+4>>2]=Cm();var Q={handle:H,attributes:B,version:B.majorVersion,GLctx:D};return D.canvas&&(D.canvas.GLctxObject=Q),Mt.contexts[H]=Q,(typeof B.enableExtensionsByDefault=="undefined"||B.enableExtensionsByDefault)&&Mt.initExtensions(Q),H},makeContextCurrent:function(D){return Mt.currentContext=Mt.contexts[D],a.ctx=Tu=Mt.currentContext&&Mt.currentContext.GLctx,!(D&&!Tu)},getContext:function(D){return Mt.contexts[D]},deleteContext:function(D){Mt.currentContext===Mt.contexts[D]&&(Mt.currentContext=null),typeof pt=="object"&&pt.removeAllHandlersOnTarget(Mt.contexts[D].GLctx.canvas),Mt.contexts[D]&&Mt.contexts[D].GLctx.canvas&&(Mt.contexts[D].GLctx.canvas.GLctxObject=void 0),uh(Mt.contexts[D].handle),Mt.contexts[D]=null},initExtensions:function(D){if(D||(D=Mt.currentContext),!D.initExtensionsDone){D.initExtensionsDone=!0;var B=D.GLctx;Av(B),Dv(B),Ev(B),B.disjointTimerQueryExt=B.getExtension("EXT_disjoint_timer_query"),Mv(B);var H=B.getSupportedExtensions()||[];H.forEach(function(Q){Q.indexOf("lose_context")<0&&Q.indexOf("debug")<0&&B.getExtension(Q)})}},populateUniformTable:function(D){for(var B=Mt.programs[D],H=Mt.programInfos[D]={uniforms:{},maxUniformLength:0,maxAttributeLength:-1,maxUniformBlockNameLength:-1},Q=H.uniforms,Ce=Tu.getProgramParameter(B,35718),Ie=0;Ie<Ce;++Ie){var _e=Tu.getActiveUniform(B,Ie),$e=_e.name;H.maxUniformLength=Math.max(H.maxUniformLength,$e.length+1),$e.slice(-1)=="]"&&($e=$e.slice(0,$e.lastIndexOf("[")));var zt=Tu.getUniformLocation(B,$e);if(zt){var Qr=Mt.getNewId(Mt.uniforms);Q[$e]=[_e.size,Qr],Mt.uniforms[Qr]=zt;for(var Hr=1;Hr<_e.size;++Hr){var Iu=$e+"["+Hr+"]";zt=Tu.getUniformLocation(B,Iu),Qr=Mt.getNewId(Mt.uniforms),Mt.uniforms[Qr]=zt}}}}},Fv=["default","low-power","high-performance"];function Rv(D,B){var H=B>>2,Q=o()[H+(24>>2)],Ce={alpha:!!o()[H+(0>>2)],depth:!!o()[H+(4>>2)],stencil:!!o()[H+(8>>2)],antialias:!!o()[H+(12>>2)],premultipliedAlpha:!!o()[H+(16>>2)],preserveDrawingBuffer:!!o()[H+(20>>2)],powerPreference:Fv[Q],failIfMajorPerformanceCaveat:!!o()[H+(28>>2)],majorVersion:o()[H+(32>>2)],minorVersion:o()[H+(36>>2)],enableExtensionsByDefault:o()[H+(40>>2)],explicitSwapControl:o()[H+(44>>2)],proxyContextToMainThread:o()[H+(48>>2)],renderViaOffscreenBackBuffer:o()[H+(52>>2)]},Ie=sh(D);if(!Ie||Ce.explicitSwapControl)return 0;var _e=Mt.createContext(Ie,Ce);return _e}function Lv(D,B){return Rv(D,B)}var wm={mappings:{},buffers:[null,[],[]],printChar:function(D,B){var H=wm.buffers[D];B===0||B===10?((D===1?W:Y)(Oe(H,0)),H.length=0):H.push(B)},varargs:void 0,get:function(){wm.varargs+=4;var D=o()[wm.varargs-4>>2];return D},getStr:function(D){var B=Ee(D);return B},get64:function(D,B){return D}};function tx(D){return T?xu(3,1,D):0}function rx(D,B,H,Q,Ce){if(T)return xu(4,1,D,B,H,Q,Ce)}function nx(D,B,H,Q){if(T)return xu(5,1,D,B,H,Q);for(var Ce=0,Ie=0;Ie<H;Ie++){for(var _e=o()[B+Ie*8>>2],$e=o()[B+(Ie*8+4)>>2],zt=0;zt<$e;zt++)wm.printChar(D,n()[_e+zt]);Ce+=$e}return o()[Q>>2]=Ce,0}function $v(D){var B=Pe.threadExitHandlers.pop();D&&B()}function Pv(D,B){Pe.threadExitHandlers.push(function(){An.get(D)(B)})}function ox(D){if(T)throw"Internal Error! spawnThread() can only ever be called from main application thread!";var B=Pe.getNewWorker();if(B.pthread!==void 0)throw"Internal error!";if(!D.pthread_ptr)throw"Internal error, no pthread ptr!";Pe.runningWorkers.push(B);for(var H=Np(128*4),Q=0;Q<128;++Q)o()[H+Q*4>>2]=0;var Ce=D.stackBase+D.stackSize,Ie=Pe.pthreads[D.pthread_ptr]={worker:B,stackBase:D.stackBase,stackSize:D.stackSize,allocatedOwnStack:D.allocatedOwnStack,threadInfoStruct:D.pthread_ptr},_e=Ie.threadInfoStruct>>2;Atomics.store(s(),_e+(64>>2),D.detached),Atomics.store(s(),_e+(100>>2),H),Atomics.store(s(),_e+(40>>2),Ie.threadInfoStruct),Atomics.store(s(),_e+(80>>2),D.stackSize),Atomics.store(s(),_e+(76>>2),Ce),Atomics.store(s(),_e+(104>>2),D.stackSize),Atomics.store(s(),_e+(104+8>>2),Ce),Atomics.store(s(),_e+(104+12>>2),D.detached);var $e=sE(),zt=$e+40;Atomics.store(s(),_e+(172>>2),zt),B.pthread=Ie;var Qr={cmd:"run",start_routine:D.startRoutine,arg:D.arg,threadInfoStruct:D.pthread_ptr,stackBase:D.stackBase,stackSize:D.stackSize};B.runPthread=function(){Qr.time=performance.now(),B.postMessage(Qr,D.transferList)},B.loaded&&(B.runPthread(),delete B.runPthread)}function Bv(D,B,H,Q){if(typeof SharedArrayBuffer=="undefined")return Y("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;if(!D)return Y("pthread_create called with a null thread pointer!"),28;var Ce=[],Ie=0;if(T&&(Ce.length===0||Ie))return uE(687865856,D,B,H,Q);if(Ie)return Ie;var _e=0,$e=0,zt=0;B&&B!=-1?(_e=o()[B>>2],_e+=81920,$e=o()[B+8>>2],zt=o()[B+12>>2]!==0):_e=2097152;var Qr=$e==0;Qr?$e=mE(16,_e):($e-=_e,xe($e>0));for(var Hr=Np(228),Iu=0;Iu<228>>2;++Iu)s()[(Hr>>2)+Iu]=0;o()[D>>2]=Hr,o()[Hr+12>>2]=Hr;var Dm=Hr+152;o()[Dm>>2]=Dm;var Dn={stackBase:$e,stackSize:_e,allocatedOwnStack:Qr,detached:zt,startRoutine:H,pthread_ptr:Hr,arg:Q,transferList:Ce};return T?(Dn.cmd="spawnThread",postMessage(Dn,Ce)):ox(Dn),0}function sx(D){if(T)return xu(6,1,D);switch(D){case 30:return 16384;case 85:var B=2147483648;return B/16384;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:return 200809;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:case 80:case 81:case 79:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:return typeof navigator=="object"&&navigator.hardwareConcurrency||1}return av(28),-1}T||Pe.initMainThreadBlock();var Tu,Ov=[null,iv,ex,tx,rx,nx,sx],zv={e:ov,r:sv,x:lv,b:uv,y:pv,j:cv,c:mv,d:rh,f:Sp,p:fv,z:dv,u:gv,q:xv,v:Cv,i:Sv,t:Nv,w:Lv,m:tx,n:rx,g:nx,o:Jy,a:ae||a.wasmMemory,k:$v,l:Pv,h:Bv,s:sx},nE=YI(),ax=a.___wasm_call_ctors=function(){return(ax=a.___wasm_call_ctors=a.asm.A).apply(null,arguments)},Gv=a._init=function(){return(Gv=a._init=a.asm.B).apply(null,arguments)},Wv=a._register_tensor=function(){return(Wv=a._register_tensor=a.asm.C).apply(null,arguments)},Kv=a._dispose_data=function(){return(Kv=a._dispose_data=a.asm.D).apply(null,arguments)},Vv=a._dispose=function(){return(Vv=a._dispose=a.asm.E).apply(null,arguments)},Uv=a._Abs=function(){return(Uv=a._Abs=a.asm.G).apply(null,arguments)},jv=a._Add=function(){return(jv=a._Add=a.asm.H).apply(null,arguments)},Hv=a._AddN=function(){return(Hv=a._AddN=a.asm.I).apply(null,arguments)},qv=a._All=function(){return(qv=a._All=a.asm.J).apply(null,arguments)},Xv=a._Any=function(){return(Xv=a._Any=a.asm.K).apply(null,arguments)},Yv=a._ArgMax=function(){return(Yv=a._ArgMax=a.asm.L).apply(null,arguments)},Zv=a._AvgPool=function(){return(Zv=a._AvgPool=a.asm.M).apply(null,arguments)},Jv=a._BatchMatMul=function(){return(Jv=a._BatchMatMul=a.asm.N).apply(null,arguments)},Qv=a._Ceil=function(){return(Qv=a._Ceil=a.asm.O).apply(null,arguments)},ew=a._ClipByValue=function(){return(ew=a._ClipByValue=a.asm.P).apply(null,arguments)},tw=a._Conv2D=function(){return(tw=a._Conv2D=a.asm.Q).apply(null,arguments)},rw=a._Conv2DBackpropInput=function(){return(rw=a._Conv2DBackpropInput=a.asm.R).apply(null,arguments)},nw=a._Cos=function(){return(nw=a._Cos=a.asm.S).apply(null,arguments)},ow=a._CropAndResize=function(){return(ow=a._CropAndResize=a.asm.T).apply(null,arguments)},sw=a._Cumsum=function(){return(sw=a._Cumsum=a.asm.U).apply(null,arguments)},aw=a._DepthToSpace=function(){return(aw=a._DepthToSpace=a.asm.V).apply(null,arguments)},iw=a._DepthwiseConv2dNative=function(){return(iw=a._DepthwiseConv2dNative=a.asm.W).apply(null,arguments)},ix=a._Equal=function(){return(ix=a._Equal=a.asm.X).apply(null,arguments)},lx=a._Exp=function(){return(lx=a._Exp=a.asm.Y).apply(null,arguments)},ux=a._FlipLeftRight=function(){return(ux=a._FlipLeftRight=a.asm.Z).apply(null,arguments)},ah=a._Floor=function(){return(ah=a._Floor=a.asm._).apply(null,arguments)},_m=a._FloorDiv=function(){return(_m=a._FloorDiv=a.asm.$).apply(null,arguments)},lw=a._FusedBatchNorm=function(){return(lw=a._FusedBatchNorm=a.asm.aa).apply(null,arguments)},ih=a._FusedConv2D=function(){return(ih=a._FusedConv2D=a.asm.ba).apply(null,arguments)},re=a._FusedDepthwiseConv2D=function(){return(re=a._FusedDepthwiseConv2D=a.asm.ca).apply(null,arguments)},pe=a._Gather=function(){return(pe=a._Gather=a.asm.da).apply(null,arguments)},De=a._GatherNd=function(){return(De=a._GatherNd=a.asm.ea).apply(null,arguments)},_t=a._Greater=function(){return(_t=a._Greater=a.asm.fa).apply(null,arguments)},Ar=a._GreaterEqual=function(){return(Ar=a._GreaterEqual=a.asm.ga).apply(null,arguments)},dr=a._LeakyRelu=function(){return(dr=a._LeakyRelu=a.asm.ha).apply(null,arguments)},ht=a._Less=function(){return(ht=a._Less=a.asm.ia).apply(null,arguments)},yt=a._LessEqual=function(){return(yt=a._LessEqual=a.asm.ja).apply(null,arguments)},an=a._Log=function(){return(an=a._Log=a.asm.ka).apply(null,arguments)},zi=a._LogicalAnd=function(){return(zi=a._LogicalAnd=a.asm.la).apply(null,arguments)},Gi=a._Max=function(){return(Gi=a._Max=a.asm.ma).apply(null,arguments)},px=a._MaxPool=function(){return(px=a._MaxPool=a.asm.na).apply(null,arguments)},lh=a._Maximum=function(){return(lh=a._Maximum=a.asm.oa).apply(null,arguments)},bo=a._Mean=function(){return(bo=a._Mean=a.asm.pa).apply(null,arguments)},ku=a._Min=function(){return(ku=a._Min=a.asm.qa).apply(null,arguments)},cx=a._Minimum=function(){return(cx=a._Minimum=a.asm.ra).apply(null,arguments)},$5=a._MirrorPad=function(){return($5=a._MirrorPad=a.asm.sa).apply(null,arguments)},P5=a._Multiply=function(){return(P5=a._Multiply=a.asm.ta).apply(null,arguments)},B5=a._Neg=function(){return(B5=a._Neg=a.asm.ua).apply(null,arguments)},O5=a._NonMaxSuppressionV3=function(){return(O5=a._NonMaxSuppressionV3=a.asm.va).apply(null,arguments)},z5=a._NonMaxSuppressionV4=function(){return(z5=a._NonMaxSuppressionV4=a.asm.wa).apply(null,arguments)},G5=a._NonMaxSuppressionV5=function(){return(G5=a._NonMaxSuppressionV5=a.asm.xa).apply(null,arguments)},W5=a._NotEqual=function(){return(W5=a._NotEqual=a.asm.ya).apply(null,arguments)},K5=a._OneHot=function(){return(K5=a._OneHot=a.asm.za).apply(null,arguments)},V5=a._PadV2=function(){return(V5=a._PadV2=a.asm.Aa).apply(null,arguments)},U5=a._Pow=function(){return(U5=a._Pow=a.asm.Ba).apply(null,arguments)},j5=a._Prelu=function(){return(j5=a._Prelu=a.asm.Ca).apply(null,arguments)},H5=a._Prod=function(){return(H5=a._Prod=a.asm.Da).apply(null,arguments)},q5=a._RealDiv=function(){return(q5=a._RealDiv=a.asm.Ea).apply(null,arguments)},X5=a._Relu=function(){return(X5=a._Relu=a.asm.Fa).apply(null,arguments)},Y5=a._Relu6=function(){return(Y5=a._Relu6=a.asm.Ga).apply(null,arguments)},Z5=a._ResizeBilinear=function(){return(Z5=a._ResizeBilinear=a.asm.Ha).apply(null,arguments)},J5=a._Reverse=function(){return(J5=a._Reverse=a.asm.Ia).apply(null,arguments)},Q5=a._RotateWithOffset=function(){return(Q5=a._RotateWithOffset=a.asm.Ja).apply(null,arguments)},eX=a._Round=function(){return(eX=a._Round=a.asm.Ka).apply(null,arguments)},tX=a._Rsqrt=function(){return(tX=a._Rsqrt=a.asm.La).apply(null,arguments)},rX=a._ScatterNd=function(){return(rX=a._ScatterNd=a.asm.Ma).apply(null,arguments)},nX=a._SelectV2=function(){return(nX=a._SelectV2=a.asm.Na).apply(null,arguments)},oX=a._Sigmoid=function(){return(oX=a._Sigmoid=a.asm.Oa).apply(null,arguments)},sX=a._Sin=function(){return(sX=a._Sin=a.asm.Pa).apply(null,arguments)},aX=a._Softmax=function(){return(aX=a._Softmax=a.asm.Qa).apply(null,arguments)},iX=a._Sqrt=function(){return(iX=a._Sqrt=a.asm.Ra).apply(null,arguments)},lX=a._Square=function(){return(lX=a._Square=a.asm.Sa).apply(null,arguments)},uX=a._SquaredDifference=function(){return(uX=a._SquaredDifference=a.asm.Ta).apply(null,arguments)},pX=a._Step=function(){return(pX=a._Step=a.asm.Ua).apply(null,arguments)},cX=a._StridedSlice=function(){return(cX=a._StridedSlice=a.asm.Va).apply(null,arguments)},mX=a._Sub=function(){return(mX=a._Sub=a.asm.Wa).apply(null,arguments)},fX=a._Sum=function(){return(fX=a._Sum=a.asm.Xa).apply(null,arguments)},dX=a._Tan=function(){return(dX=a._Tan=a.asm.Ya).apply(null,arguments)},hX=a._Tanh=function(){return(hX=a._Tanh=a.asm.Za).apply(null,arguments)},gX=a._Tile=function(){return(gX=a._Tile=a.asm._a).apply(null,arguments)},bX=a._TopK=function(){return(bX=a._TopK=a.asm.$a).apply(null,arguments)},yX=a._Transform=function(){return(yX=a._Transform=a.asm.ab).apply(null,arguments)},xX=a._Transpose=function(){return(xX=a._Transpose=a.asm.bb).apply(null,arguments)},TX=a.__FusedMatMul=function(){return(TX=a.__FusedMatMul=a.asm.cb).apply(null,arguments)},Np=a._malloc=function(){return(Np=a._malloc=a.asm.db).apply(null,arguments)},uh=a._free=function(){return(uh=a._free=a.asm.eb).apply(null,arguments)},oE=a.___errno_location=function(){return(oE=a.___errno_location=a.asm.fb).apply(null,arguments)},sE=a._emscripten_get_global_libc=function(){return(sE=a._emscripten_get_global_libc=a.asm.gb).apply(null,arguments)},Cm=a._pthread_self=function(){return(Cm=a._pthread_self=a.asm.hb).apply(null,arguments)},aE=a.___pthread_tsd_run_dtors=function(){return(aE=a.___pthread_tsd_run_dtors=a.asm.ib).apply(null,arguments)},uw=a._emscripten_main_thread_process_queued_calls=function(){return(uw=a._emscripten_main_thread_process_queued_calls=a.asm.jb).apply(null,arguments)},kX=a._emscripten_current_thread_process_queued_calls=function(){return(kX=a._emscripten_current_thread_process_queued_calls=a.asm.kb).apply(null,arguments)},iE=a._emscripten_register_main_browser_thread_id=function(){return(iE=a._emscripten_register_main_browser_thread_id=a.asm.lb).apply(null,arguments)},lE=a.__emscripten_do_dispatch_to_thread=function(){return(lE=a.__emscripten_do_dispatch_to_thread=a.asm.mb).apply(null,arguments)},uE=a._emscripten_sync_run_in_main_thread_4=function(){return(uE=a._emscripten_sync_run_in_main_thread_4=a.asm.nb).apply(null,arguments)},pE=a._emscripten_run_in_main_runtime_thread_js=function(){return(pE=a._emscripten_run_in_main_runtime_thread_js=a.asm.ob).apply(null,arguments)},pw=a.__emscripten_call_on_thread=function(){return(pw=a.__emscripten_call_on_thread=a.asm.pb).apply(null,arguments)},IX=a._emscripten_tls_init=function(){return(IX=a._emscripten_tls_init=a.asm.qb).apply(null,arguments)},cw=a.__emscripten_thread_init=function(){return(cw=a.__emscripten_thread_init=a.asm.rb).apply(null,arguments)},ph=a.stackSave=function(){return(ph=a.stackSave=a.asm.sb).apply(null,arguments)},Sm=a.stackRestore=function(){return(Sm=a.stackRestore=a.asm.tb).apply(null,arguments)},Nm=a.stackAlloc=function(){return(Nm=a.stackAlloc=a.asm.ub).apply(null,arguments)},cE=a._emscripten_stack_set_limits=function(){return(cE=a._emscripten_stack_set_limits=a.asm.vb).apply(null,arguments)},mE=a._memalign=function(){return(mE=a._memalign=a.asm.wb).apply(null,arguments)},fE=a.__emscripten_allow_main_runtime_queued_calls=9808,Am=a.__emscripten_main_thread_futex=11432;a.cwrap=Ne,a.PThread=Pe,a.PThread=Pe,a.wasmMemory=ae,a.ExitStatus=ch;var mx;function ch(D){this.name="ExitStatus",this.message="Program terminated with exit("+D+")",this.status=D}Cp=function D(){mx||mw(),mx||(Cp=D)};function mw(D){if(D=D||m,Bi>0)return;if(T){l(a),_p(),postMessage({cmd:"loaded"});return}if(th(),Bi>0)return;function B(){mx||(mx=!0,a.calledRun=!0,!ye&&(_p(),VI(),l(a),a.onRuntimeInitialized&&a.onRuntimeInitialized(),Qn()))}a.setStatus?(a.setStatus("Running..."),setTimeout(function(){setTimeout(function(){a.setStatus("")},1),B()},1)):B()}a.run=mw;function vX(D,B){if(!(B&&le&&D===0)){if(!B&&T)throw postMessage({cmd:"exitProcess",returnCode:D}),new ch(D);le||(Pe.terminateAllThreads(),me=D,jy(),a.onExit&&a.onExit(D),ye=!0),d(D,new ch(D))}}if(a.preInit)for(typeof a.preInit=="function"&&(a.preInit=[a.preInit]);a.preInit.length>0;)a.preInit.pop()();return T&&(le=!1,Pe.initWorker()),mw(),e.ready}}();typeof zI=="object"&&typeof J1=="object"?J1.exports=Z1:typeof define=="function"&&define.amd?define([],function(){return Z1}):typeof zI=="object"&&(zI.WasmBackendModuleThreadedSimd=Z1)});var M5=hr((GI,eE)=>{var Q1=function(){var r=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(r=r||__filename),function(e){e=e||{};var t=typeof e!="undefined"?e:{},n,o;t.ready=new Promise(function(re,pe){n=re,o=pe});var s={},i;for(i in t)t.hasOwnProperty(i)&&(s[i]=t[i]);var a=[],l="./this.program",u=function(re,pe){throw pe},p=!1,c=!1,m=!1,f=!1;p=typeof window=="object",c=typeof importScripts=="function",m=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",f=!p&&!m&&!c;var d="";function h(re){return t.locateFile?t.locateFile(re,d):d+re}var g,b,y,T,k,I;m?(c?d=eh().dirname(d)+"/":d=__dirname+"/",g=function(pe,De){return k||(k=Ap("fs")),I||(I=eh()),pe=I.normalize(pe),k.readFileSync(pe,De?null:"utf8")},y=function(pe){var De=g(pe,!0);return De.buffer||(De=new Uint8Array(De)),W(De.buffer),De},process.argv.length>1&&(l=process.argv[1].replace(/\\/g,"/")),a=process.argv.slice(2),process.on("uncaughtException",function(re){if(!(re instanceof lw))throw re}),process.on("unhandledRejection",ti),u=function(re){process.exit(re)},t.inspect=function(){return"[Emscripten Module object]"}):f?(typeof read!="undefined"&&(g=function(pe){return read(pe)}),y=function(pe){var De;return typeof readbuffer=="function"?new Uint8Array(readbuffer(pe)):(De=read(pe,"binary"),W(typeof De=="object"),De)},typeof scriptArgs!="undefined"?a=scriptArgs:typeof arguments!="undefined"&&(a=arguments),typeof quit=="function"&&(u=function(re){quit(re)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(p||c)&&(c?d=self.location.href:typeof document!="undefined"&&document.currentScript&&(d=document.currentScript.src),r&&(d=r),d.indexOf("blob:")!==0?d=d.substr(0,d.lastIndexOf("/")+1):d="",g=function(re){var pe=new XMLHttpRequest;return pe.open("GET",re,!1),pe.send(null),pe.responseText},c&&(y=function(re){var pe=new XMLHttpRequest;return pe.open("GET",re,!1),pe.responseType="arraybuffer",pe.send(null),new Uint8Array(pe.response)}),b=function(re,pe,De){var _t=new XMLHttpRequest;_t.open("GET",re,!0),_t.responseType="arraybuffer",_t.onload=function(){if(_t.status==200||_t.status==0&&_t.response){pe(_t.response);return}De()},_t.onerror=De,_t.send(null)},T=function(re){document.title=re});var S=t.print||console.log.bind(console),N=t.printErr||console.warn.bind(console);for(i in s)s.hasOwnProperty(i)&&(t[i]=s[i]);s=null,t.arguments&&(a=t.arguments),t.thisProgram&&(l=t.thisProgram),t.quit&&(u=t.quit);var F;t.wasmBinary&&(F=t.wasmBinary);var $=t.noExitRuntime||!0;typeof WebAssembly!="object"&&ti("no native wasm support detected");var O,V=!1,q;function W(re,pe){re||ti("Assertion failed: "+pe)}function Y(re){var pe=t["_"+re];return W(pe,"Cannot call unknown function "+re+", make sure it is exported"),pe}function Z(re,pe,De,_t,Ar){var dr={string:function(bo){var ku=0;if(bo!=null&&bo!==0){var cx=(bo.length<<2)+1;ku=ah(cx),ce(bo,ku,cx)}return ku},array:function(bo){var ku=ah(bo.length);return ye(bo,ku),ku}};function ht(bo){return pe==="string"?le(bo):pe==="boolean"?Boolean(bo):bo}var yt=Y(re),an=[],zi=0;if(_t)for(var Gi=0;Gi<_t.length;Gi++){var px=dr[De[Gi]];px?(zi===0&&(zi=lx()),an[Gi]=px(_t[Gi])):an[Gi]=_t[Gi]}var lh=yt.apply(null,an);return lh=ht(lh),zi!==0&&ux(zi),lh}function J(re,pe,De,_t){De=De||[];var Ar=De.every(function(ht){return ht==="number"}),dr=pe!=="string";return dr&&Ar&&!_t?Y(re):function(){return Z(re,pe,De,arguments,_t)}}var se=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function ee(re,pe,De){for(var _t=pe+De,Ar=pe;re[Ar]&&!(Ar>=_t);)++Ar;if(Ar-pe>16&&re.subarray&&se)return se.decode(re.subarray(pe,Ar));for(var dr="";pe<Ar;){var ht=re[pe++];if(!(ht&128)){dr+=String.fromCharCode(ht);continue}var yt=re[pe++]&63;if((ht&224)==192){dr+=String.fromCharCode((ht&31)<<6|yt);continue}var an=re[pe++]&63;if((ht&240)==224?ht=(ht&15)<<12|yt<<6|an:ht=(ht&7)<<18|yt<<12|an<<6|re[pe++]&63,ht<65536)dr+=String.fromCharCode(ht);else{var zi=ht-65536;dr+=String.fromCharCode(55296|zi>>10,56320|zi&1023)}}return dr}function le(re,pe){return re?ee(we,re,pe):""}function ae(re,pe,De,_t){if(!(_t>0))return 0;for(var Ar=De,dr=De+_t-1,ht=0;ht<re.length;++ht){var yt=re.charCodeAt(ht);if(yt>=55296&&yt<=57343){var an=re.charCodeAt(++ht);yt=65536+((yt&1023)<<10)|an&1023}if(yt<=127){if(De>=dr)break;pe[De++]=yt}else if(yt<=2047){if(De+1>=dr)break;pe[De++]=192|yt>>6,pe[De++]=128|yt&63}else if(yt<=65535){if(De+2>=dr)break;pe[De++]=224|yt>>12,pe[De++]=128|yt>>6&63,pe[De++]=128|yt&63}else{if(De+3>=dr)break;pe[De++]=240|yt>>18,pe[De++]=128|yt>>12&63,pe[De++]=128|yt>>6&63,pe[De++]=128|yt&63}}return pe[De]=0,De-Ar}function ce(re,pe,De){return ae(re,we,pe,De)}function ye(re,pe){ke.set(re,pe)}function me(re,pe){return re%pe>0&&(re+=pe-re%pe),re}var xe,ke,we,Ne,Oe,Ee,Ye,at,wt;function qt(re){xe=re,t.HEAP8=ke=new Int8Array(re),t.HEAP16=Ne=new Int16Array(re),t.HEAP32=Ee=new Int32Array(re),t.HEAPU8=we=new Uint8Array(re),t.HEAPU16=Oe=new Uint16Array(re),t.HEAPU32=Ye=new Uint32Array(re),t.HEAPF32=at=new Float32Array(re),t.HEAPF64=wt=new Float64Array(re)}var Xt=t.INITIAL_MEMORY||16777216,ot,At=[],Et=[],ur=[],ho=[],Nr=!1;Et.push({func:function(){Jy()}});function Zn(){if(t.preRun)for(typeof t.preRun=="function"&&(t.preRun=[t.preRun]);t.preRun.length;)go(t.preRun.shift());yu(At)}function xn(){Nr=!0,yu(Et)}function es(){yu(ur)}function Or(){if(t.postRun)for(typeof t.postRun=="function"&&(t.postRun=[t.postRun]);t.postRun.length;)An(t.postRun.shift());yu(ho)}function go(re){At.unshift(re)}function An(re){ho.unshift(re)}var Jr=0,Jn=null,So=null;function wp(re){Jr++,t.monitorRunDependencies&&t.monitorRunDependencies(Jr)}function bu(re){if(Jr--,t.monitorRunDependencies&&t.monitorRunDependencies(Jr),Jr==0&&(Jn!==null&&(clearInterval(Jn),Jn=null),So)){var pe=So;So=null,pe()}}t.preloadedImages={},t.preloadedAudios={};function ti(re){t.onAbort&&t.onAbort(re),re+="",N(re),V=!0,q=1,re="abort("+re+"). Build with -s ASSERTIONS=1 for more info.";var pe=new WebAssembly.RuntimeError(re);throw o(pe),pe}function Pi(re,pe){return String.prototype.startsWith?re.startsWith(pe):re.indexOf(pe)===0}var th="data:application/octet-stream;base64,";function _p(re){return Pi(re,th)}var VI="file://";function jy(re){return Pi(re,VI)}var Qn="tfjs-backend-wasm.wasm";_p(Qn)||(Qn=h(Qn));function Hy(re){try{if(re==Qn&&F)return new Uint8Array(F);if(y)return y(re);throw"both async and sync fetching of the wasm failed"}catch(pe){ti(pe)}}function UI(){if(!F&&(p||c)){if(typeof fetch=="function"&&!jy(Qn))return fetch(Qn,{credentials:"same-origin"}).then(function(re){if(!re.ok)throw"failed to load wasm binary file at '"+Qn+"'";return re.arrayBuffer()}).catch(function(){return Hy(Qn)});if(b)return new Promise(function(re,pe){b(Qn,function(De){re(new Uint8Array(De))},pe)})}return Promise.resolve().then(function(){return Hy(Qn)})}function Bi(){var re={a:YI};function pe(ht,yt){var an=ht.exports;t.asm=an,O=t.asm.i,qt(O.buffer),ot=t.asm.o,bu("wasm-instantiate")}wp("wasm-instantiate");function De(ht){pe(ht.instance)}function _t(ht){return UI().then(function(yt){return WebAssembly.instantiate(yt,re)}).then(ht,function(yt){N("failed to asynchronously prepare wasm: "+yt),ti(yt)})}function Ar(){return!F&&typeof WebAssembly.instantiateStreaming=="function"&&!_p(Qn)&&!jy(Qn)&&typeof fetch=="function"?fetch(Qn,{credentials:"same-origin"}).then(function(ht){var yt=WebAssembly.instantiateStreaming(ht,re);return yt.then(De,function(an){return N("wasm streaming compile failed: "+an),N("falling back to ArrayBuffer instantiation"),_t(De)})}):_t(De)}if(t.instantiateWasm)try{var dr=t.instantiateWasm(re,pe);return dr}catch(ht){return N("Module.instantiateWasm callback failed with error: "+ht),!1}return Ar().catch(o),{}}function yu(re){for(;re.length>0;){var pe=re.shift();if(typeof pe=="function"){pe(t);continue}var De=pe.func;typeof De=="number"?pe.arg===void 0?ot.get(De)():ot.get(De)(pe.arg):De(pe.arg===void 0?null:pe.arg)}}function Cp(){ti()}function jI(re,pe,De){we.copyWithin(re,pe,pe+De)}function HI(){return we.length}function Oi(re){try{return O.grow(re-xe.byteLength+65535>>>16),qt(O.buffer),1}catch(pe){}}function qy(re){var pe=HI(),De=2147483648;if(re>De)return!1;for(var _t=1;_t<=4;_t*=2){var Ar=pe*(1+.2/_t);Ar=Math.min(Ar,re+100663296);var dr=Math.min(De,me(Math.max(re,Ar),65536)),ht=Oi(dr);if(ht)return!0}return!1}var Im={mappings:{},buffers:[null,[],[]],printChar:function(re,pe){var De=Im.buffers[re];pe===0||pe===10?((re===1?S:N)(ee(De,0)),De.length=0):De.push(pe)},varargs:void 0,get:function(){Im.varargs+=4;var re=Ee[Im.varargs-4>>2];return re},getStr:function(re){var pe=le(re);return pe},get64:function(re,pe){return re}};function Xy(re){return 0}function qI(re,pe,De,_t,Ar){}function Yy(re,pe,De,_t){for(var Ar=0,dr=0;dr<De;dr++){for(var ht=Ee[pe+dr*8>>2],yt=Ee[pe+(dr*8+4)>>2],an=0;an<yt;an++)Im.printChar(re,we[ht+an]);Ar+=yt}return Ee[_t>>2]=Ar,0}function eo(){return 6}function Zy(re){return Ee[ix()>>2]=re,re}function XI(re){switch(re){case 30:return 16384;case 85:var pe=2147483648;return pe/16384;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:return 200809;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:case 80:case 81:case 79:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:return typeof navigator=="object"&&navigator.hardwareConcurrency||1}return Zy(28),-1}var YI={a:Cp,d:jI,e:qy,f:Xy,c:qI,b:Yy,g:eo,h:XI},ZI=Bi(),Jy=t.___wasm_call_ctors=function(){return(Jy=t.___wasm_call_ctors=t.asm.j).apply(null,arguments)},vm=t._init=function(){return(vm=t._init=t.asm.k).apply(null,arguments)},rh=t._register_tensor=function(){return(rh=t._register_tensor=t.asm.l).apply(null,arguments)},JI=t._dispose_data=function(){return(JI=t._dispose_data=t.asm.m).apply(null,arguments)},QI=t._dispose=function(){return(QI=t._dispose=t.asm.n).apply(null,arguments)},ev=t._Abs=function(){return(ev=t._Abs=t.asm.p).apply(null,arguments)},Pe=t._Add=function(){return(Pe=t._Add=t.asm.q).apply(null,arguments)},tv=t._AddN=function(){return(tv=t._AddN=t.asm.r).apply(null,arguments)},rv=t._All=function(){return(rv=t._All=t.asm.s).apply(null,arguments)},nv=t._Any=function(){return(nv=t._Any=t.asm.t).apply(null,arguments)},ov=t._ArgMax=function(){return(ov=t._ArgMax=t.asm.u).apply(null,arguments)},sv=t._AvgPool=function(){return(sv=t._AvgPool=t.asm.v).apply(null,arguments)},Sp=t._BatchMatMul=function(){return(Sp=t._BatchMatMul=t.asm.w).apply(null,arguments)},av=t._Ceil=function(){return(av=t._Ceil=t.asm.x).apply(null,arguments)},iv=t._ClipByValue=function(){return(iv=t._ClipByValue=t.asm.y).apply(null,arguments)},lv=t._Conv2D=function(){return(lv=t._Conv2D=t.asm.z).apply(null,arguments)},uv=t._Conv2DBackpropInput=function(){return(uv=t._Conv2DBackpropInput=t.asm.A).apply(null,arguments)},pv=t._Cos=function(){return(pv=t._Cos=t.asm.B).apply(null,arguments)},cv=t._CropAndResize=function(){return(cv=t._CropAndResize=t.asm.C).apply(null,arguments)},mv=t._Cumsum=function(){return(mv=t._Cumsum=t.asm.D).apply(null,arguments)},fv=t._DepthToSpace=function(){return(fv=t._DepthToSpace=t.asm.E).apply(null,arguments)},dv=t._DepthwiseConv2dNative=function(){return(dv=t._DepthwiseConv2dNative=t.asm.F).apply(null,arguments)},xu=t._Equal=function(){return(xu=t._Equal=t.asm.G).apply(null,arguments)},nh=t._Exp=function(){return(nh=t._Exp=t.asm.H).apply(null,arguments)},oh=t._FlipLeftRight=function(){return(oh=t._FlipLeftRight=t.asm.I).apply(null,arguments)},hv=t._Floor=function(){return(hv=t._Floor=t.asm.J).apply(null,arguments)},gv=t._FloorDiv=function(){return(gv=t._FloorDiv=t.asm.K).apply(null,arguments)},bv=t._FusedBatchNorm=function(){return(bv=t._FusedBatchNorm=t.asm.L).apply(null,arguments)},yv=t._FusedConv2D=function(){return(yv=t._FusedConv2D=t.asm.M).apply(null,arguments)},xv=t._FusedDepthwiseConv2D=function(){return(xv=t._FusedDepthwiseConv2D=t.asm.N).apply(null,arguments)},pt=t._Gather=function(){return(pt=t._Gather=t.asm.O).apply(null,arguments)},Tv=t._GatherNd=function(){return(Tv=t._GatherNd=t.asm.P).apply(null,arguments)},kv=t._Greater=function(){return(kv=t._Greater=t.asm.Q).apply(null,arguments)},Iv=t._GreaterEqual=function(){return(Iv=t._GreaterEqual=t.asm.R).apply(null,arguments)},vv=t._LeakyRelu=function(){return(vv=t._LeakyRelu=t.asm.S).apply(null,arguments)},wv=t._Less=function(){return(wv=t._Less=t.asm.T).apply(null,arguments)},_v=t._LessEqual=function(){return(_v=t._LessEqual=t.asm.U).apply(null,arguments)},sh=t._Log=function(){return(sh=t._Log=t.asm.V).apply(null,arguments)},Qy=t._LogicalAnd=function(){return(Qy=t._LogicalAnd=t.asm.W).apply(null,arguments)},ex=t._Max=function(){return(ex=t._Max=t.asm.X).apply(null,arguments)},Cv=t._MaxPool=function(){return(Cv=t._MaxPool=t.asm.Y).apply(null,arguments)},Sv=t._Maximum=function(){return(Sv=t._Maximum=t.asm.Z).apply(null,arguments)},Nv=t._Mean=function(){return(Nv=t._Mean=t.asm._).apply(null,arguments)},Av=t._Min=function(){return(Av=t._Min=t.asm.$).apply(null,arguments)},Dv=t._Minimum=function(){return(Dv=t._Minimum=t.asm.aa).apply(null,arguments)},Ev=t._MirrorPad=function(){return(Ev=t._MirrorPad=t.asm.ba).apply(null,arguments)},Mv=t._Multiply=function(){return(Mv=t._Multiply=t.asm.ca).apply(null,arguments)},Mt=t._Neg=function(){return(Mt=t._Neg=t.asm.da).apply(null,arguments)},Fv=t._NonMaxSuppressionV3=function(){return(Fv=t._NonMaxSuppressionV3=t.asm.ea).apply(null,arguments)},Rv=t._NonMaxSuppressionV4=function(){return(Rv=t._NonMaxSuppressionV4=t.asm.fa).apply(null,arguments)},Lv=t._NonMaxSuppressionV5=function(){return(Lv=t._NonMaxSuppressionV5=t.asm.ga).apply(null,arguments)},wm=t._NotEqual=function(){return(wm=t._NotEqual=t.asm.ha).apply(null,arguments)},tx=t._OneHot=function(){return(tx=t._OneHot=t.asm.ia).apply(null,arguments)},rx=t._PadV2=function(){return(rx=t._PadV2=t.asm.ja).apply(null,arguments)},nx=t._Pow=function(){return(nx=t._Pow=t.asm.ka).apply(null,arguments)},$v=t._Prelu=function(){return($v=t._Prelu=t.asm.la).apply(null,arguments)},Pv=t._Prod=function(){return(Pv=t._Prod=t.asm.ma).apply(null,arguments)},ox=t._RealDiv=function(){return(ox=t._RealDiv=t.asm.na).apply(null,arguments)},Bv=t._Relu=function(){return(Bv=t._Relu=t.asm.oa).apply(null,arguments)},sx=t._Relu6=function(){return(sx=t._Relu6=t.asm.pa).apply(null,arguments)},Tu=t._ResizeBilinear=function(){return(Tu=t._ResizeBilinear=t.asm.qa).apply(null,arguments)},Ov=t._Reverse=function(){return(Ov=t._Reverse=t.asm.ra).apply(null,arguments)},zv=t._RotateWithOffset=function(){return(zv=t._RotateWithOffset=t.asm.sa).apply(null,arguments)},nE=t._Round=function(){return(nE=t._Round=t.asm.ta).apply(null,arguments)},ax=t._Rsqrt=function(){return(ax=t._Rsqrt=t.asm.ua).apply(null,arguments)},Gv=t._ScatterNd=function(){return(Gv=t._ScatterNd=t.asm.va).apply(null,arguments)},Wv=t._SelectV2=function(){return(Wv=t._SelectV2=t.asm.wa).apply(null,arguments)},Kv=t._Sigmoid=function(){return(Kv=t._Sigmoid=t.asm.xa).apply(null,arguments)},Vv=t._Sin=function(){return(Vv=t._Sin=t.asm.ya).apply(null,arguments)},Uv=t._Softmax=function(){return(Uv=t._Softmax=t.asm.za).apply(null,arguments)},jv=t._Sqrt=function(){return(jv=t._Sqrt=t.asm.Aa).apply(null,arguments)},Hv=t._Square=function(){return(Hv=t._Square=t.asm.Ba).apply(null,arguments)},qv=t._SquaredDifference=function(){return(qv=t._SquaredDifference=t.asm.Ca).apply(null,arguments)},Xv=t._Step=function(){return(Xv=t._Step=t.asm.Da).apply(null,arguments)},Yv=t._StridedSlice=function(){return(Yv=t._StridedSlice=t.asm.Ea).apply(null,arguments)},Zv=t._Sub=function(){return(Zv=t._Sub=t.asm.Fa).apply(null,arguments)},Jv=t._Sum=function(){return(Jv=t._Sum=t.asm.Ga).apply(null,arguments)},Qv=t._Tan=function(){return(Qv=t._Tan=t.asm.Ha).apply(null,arguments)},ew=t._Tanh=function(){return(ew=t._Tanh=t.asm.Ia).apply(null,arguments)},tw=t._Tile=function(){return(tw=t._Tile=t.asm.Ja).apply(null,arguments)},rw=t._TopK=function(){return(rw=t._TopK=t.asm.Ka).apply(null,arguments)},nw=t._Transform=function(){return(nw=t._Transform=t.asm.La).apply(null,arguments)},ow=t._Transpose=function(){return(ow=t._Transpose=t.asm.Ma).apply(null,arguments)},sw=t.__FusedMatMul=function(){return(sw=t.__FusedMatMul=t.asm.Na).apply(null,arguments)},aw=t._malloc=function(){return(aw=t._malloc=t.asm.Oa).apply(null,arguments)},iw=t._free=function(){return(iw=t._free=t.asm.Pa).apply(null,arguments)},ix=t.___errno_location=function(){return(ix=t.___errno_location=t.asm.Qa).apply(null,arguments)},lx=t.stackSave=function(){return(lx=t.stackSave=t.asm.Ra).apply(null,arguments)},ux=t.stackRestore=function(){return(ux=t.stackRestore=t.asm.Sa).apply(null,arguments)},ah=t.stackAlloc=function(){return(ah=t.stackAlloc=t.asm.Ta).apply(null,arguments)};t.cwrap=J;var _m;function lw(re){this.name="ExitStatus",this.message="Program terminated with exit("+re+")",this.status=re}So=function re(){_m||ih(),_m||(So=re)};function ih(re){if(re=re||a,Jr>0||(Zn(),Jr>0))return;function pe(){_m||(_m=!0,t.calledRun=!0,!V&&(xn(),es(),n(t),t.onRuntimeInitialized&&t.onRuntimeInitialized(),Or()))}t.setStatus?(t.setStatus("Running..."),setTimeout(function(){setTimeout(function(){t.setStatus("")},1),pe()},1)):pe()}if(t.run=ih,t.preInit)for(typeof t.preInit=="function"&&(t.preInit=[t.preInit]);t.preInit.length>0;)t.preInit.pop()();return ih(),e.ready}}();typeof GI=="object"&&typeof eE=="object"?eE.exports=Q1:typeof define=="function"&&define.amd?define([],function(){return Q1}):typeof GI=="object"&&(GI.WasmBackendModule=Q1)});var hE="3.7.0";var gE="3.7.0";var bE="3.7.0";var yE="3.7.0";var xE="3.7.0";var TE="3.7.0";var kE="3.7.0";var IE="3.7.0";var OX=1e-7,zX=1e-4,vE=class{constructor(e,t){this.backend=e;this.dataMover=t;this.data=new WeakMap;this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}},dx=class{refCount(e){return ts("refCount")}incRef(e){return ts("incRef")}timerAvailable(){return!0}time(e){return ts("time")}read(e){return ts("read")}readSync(e){return ts("readSync")}numDataIds(){return ts("numDataIds")}disposeData(e,t){return ts("disposeData")}write(e,t,n){return ts("write")}move(e,t,n,o,s){return ts("move")}memory(){return ts("memory")}floatPrecision(){return ts("floatPrecision")}epsilon(){return this.floatPrecision()===32?OX:zX}dispose(){return ts("dispose")}};function ts(r){throw new Error(`'${r}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function wE(r){let e=r.length,t=0,n=0;for(;e>0;)n=Math.random()*e|0,e--,t=r[e],r[e]=r[n],r[n]=t}function GX(r,e){if(r.length!==e.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${r.length}Second array length was ${e.length}`);let t=r.length,n,o,s=0;for(;t>0;)s=Math.random()*t|0,t--,n=r[t],o=e[t],r[t]=r[s],e[t]=e[s],r[s]=n,e[s]=o}function Mm(r,e,t){return Math.max(r,Math.min(e,t))}function WX(r){return r%2==0?r:r+1}function KX(r){let e=0;for(let t=0;t<r.length;t++)e+=r[t];return e}function VX(r,e){let t=Math.random();return e*t+(1-t)*r}function UX(r,e){let t=0;for(let n=0;n<r.length;n++){let o=Number(r[n])-Number(e[n]);t+=o*o}return t}function P(r,e){if(!r)throw new Error(typeof e=="string"?e:e())}function Jt(r,e,t=""){P(En(r,e),()=>t+` Shapes ${r} and ${e} must match`)}function No(r){P(r!=null,()=>"The input to the tensor constructor must be a non-null value.")}function Ls(r,e=[],t=!1){if(e==null&&(e=[]),Array.isArray(r)||zr(r)&&!t)for(let n=0;n<r.length;++n)Ls(r[n],e,t);else e.push(r);return e}function Ct(r){if(r.length===0)return 1;let e=r[0];for(let t=1;t<r.length;t++)e*=r[t];return e}function jX(r){return r.length===0}function En(r,e){if(r===e)return!0;if(r==null||e==null||r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}function Qt(r){return r%1==0}function HX(r){if(Math.tanh!=null)return Math.tanh(r);if(r===Infinity)return 1;if(r===-Infinity)return-1;{let e=Math.exp(2*r);return(e-1)/(e+1)}}function qX(r){let e=Math.ceil(Math.sqrt(r));return[e,Math.ceil(r/e)]}function XX(r){let e=new Uint32Array(r);for(let t=0;t<r;++t)e[t]=t;return wE(e),e}function Dp(r,e){return e<=r.length?r:r+" ".repeat(e-r.length)}function YX(r,e=n=>0,t){return new Promise((n,o)=>{let s=0,i=()=>{if(r()){n();return}s++;let a=e(s);if(t!=null&&s>=t){o();return}setTimeout(i,a)};i()})}function ZX(r,e){let t=1,n=-1;for(let s=0;s<r.length;++s)if(r[s]>=0)t*=r[s];else if(r[s]===-1){if(n!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${n} and dim ${s}`);n=s}else if(r[s]<0)throw Error(`Shapes can not be < 0. Found ${r[s]} at dim ${s}`);if(n===-1){if(e>0&&e!==t)throw Error(`Size(${e}) must match the product of shape ${r}`);return r}if(t===0)throw Error(`Cannot infer the missing size in [${r}] when there are 0 elements`);if(e%t!=0)throw Error(`The implicit shape can't be a fractional number. Got ${e} / ${t}`);let o=r.slice();return o[n]=e/t,o}function vu(r,e){let t=e.length;return r=r==null?e.map((n,o)=>o):[].concat(r),P(r.every(n=>n>=-t&&n<t),()=>`All values in axis param must be in range [-${t}, ${t}) but got axis ${r}`),P(r.every(n=>Qt(n)),()=>`All values in axis param must be integers but got axis ${r}`),r.map(n=>n<0?t+n:n)}function fw(r,e){let t=[],n=[],o=e!=null&&Array.isArray(e)&&e.length===0,s=e==null||o?null:vu(e,r).sort(),i=0;for(let a=0;a<r.length;++a){if(s!=null){if(s[i]===a&&r[a]!==1)throw new Error(`Can't squeeze axis ${a} since its dim '${r[a]}' is not 1`);(s[i]==null||s[i]>a)&&r[a]===1&&(t.push(r[a]),n.push(a)),s[i]<=a&&i++}r[a]!==1&&(t.push(r[a]),n.push(a))}return{newShape:t,keptDims:n}}function dw(r,e){let t=null;if(r==null||r==="float32")t=new Float32Array(e);else if(r==="int32")t=new Int32Array(e);else if(r==="bool")t=new Uint8Array(e);else throw new Error(`Unknown data type ${r}`);return t}function hw(r,e){let t=null;if(r==null||r==="float32")t=new Float32Array(e);else if(r==="int32")t=new Int32Array(e);else if(r==="bool")t=new Uint8Array(e);else if(r==="string")t=new Array(e);else throw new Error(`Unknown data type ${r}`);return t}function gw(r,e){for(let t=0;t<r.length;t++){let n=r[t];if(isNaN(n)||!isFinite(n))throw Error(`A tensor of type ${e} being uploaded contains ${n}.`)}}function bw(r){return r==="bool"||r==="complex64"||r==="float32"||r==="int32"||r==="string"}function JX(r,e){return!(e==="complex64"||e==="float32"&&r!=="complex64"||e==="int32"&&r!=="float32"&&r!=="complex64"||e==="bool"&&r==="bool")}function zr(r){return r instanceof Float32Array||r instanceof Int32Array||r instanceof Uint8Array}function hx(r){if(r==="float32"||r==="int32")return 4;if(r==="complex64")return 8;if(r==="bool")return 1;throw new Error(`Unknown dtype ${r}`)}function yw(r){if(r==null)return 0;let e=0;return r.forEach(t=>e+=t.length),e}function $s(r){return typeof r=="string"||r instanceof String}function _E(r){return typeof r=="boolean"}function CE(r){return typeof r=="number"}function Fm(r){return Array.isArray(r)?Fm(r[0]):r instanceof Float32Array?"float32":r instanceof Int32Array||r instanceof Uint8Array?"int32":CE(r)?"float32":$s(r)?"string":_E(r)?"bool":"float32"}function ri(r){return!!(r&&r.constructor&&r.call&&r.apply)}function Rm(r,e){for(let t=e;t<r;++t)if(r%t==0)return t;return r}function ni(r){let e=r.length;if(e<2)return[];let t=new Array(e-1);t[e-2]=r[e-1];for(let n=e-3;n>=0;--n)t[n]=t[n+1]*r[n+1];return t}function SE(r,e,t,n=!1){let o=new Array;if(e.length===1){let s=e[0]*(n?2:1);for(let i=0;i<s;i++)o[i]=t[r+i]}else{let s=e[0],i=e.slice(1),a=i.reduce((l,u)=>l*u)*(n?2:1);for(let l=0;l<s;l++)o[l]=SE(r+l*a,i,t,n)}return o}function Ep(r,e,t=!1){if(r.length===0)return e[0];let n=r.reduce((o,s)=>o*s)*(t?2:1);if(n===0)return[];if(n!==e.length)throw new Error(`[${r}] does not match the input size ${e.length}${t?" for a complex tensor":""}.`);return SE(0,r,e,t)}function mh(r,e){let t=Lm(r,e);for(let n=0;n<t.length;n++)t[n]=1;return t}function Lm(r,e){if(e==null||e==="float32"||e==="complex64")return new Float32Array(r);if(e==="int32")return new Int32Array(r);if(e==="bool")return new Uint8Array(r);throw new Error(`Unknown data type ${e}`)}function QX(r,e){let t=r.reduce((n,o)=>n*o,1);if(e==null||e==="float32")return Ep(r,new Float32Array(t));if(e==="int32")return Ep(r,new Int32Array(t));if(e==="bool")return Ep(r,new Uint8Array(t));throw new Error(`Unknown data type ${e}`)}function fh(r){r.forEach(e=>{P(Number.isInteger(e)&&e>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${r}].`)})}function e7(r,e,t){if(e===0)return 0;if(e===1)return r[0];let n=r[r.length-1];for(let o=0;o<r.length-1;++o)n+=t[o]*r[o];return n}function t7(r,e,t){if(e===0)return[];if(e===1)return[r];let n=new Array(e);for(let o=0;o<n.length-1;++o)n[o]=Math.floor(r/t[o]),r-=n[o]*t[o];return n[n.length-1]=r,n}function dh(r){return r&&r.then&&typeof r.then=="function"}var NE="tfjsflags",gx=class{constructor(e){this.global=e;this.flags={};this.flagRegistry={};this.urlFlags={};this.getQueryParams=r7;this.populateURLFlags()}setPlatform(e,t){this.platform!=null&&console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${t}.`),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},this.urlFlags[e]!=null){let o=this.urlFlags[e];console.warn(`Setting feature override from URL ${e}: ${o}.`),this.set(e,o)}}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];let t=this.evaluateFlag(e);if(dh(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(this.flagRegistry[e]==null)throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,this.flagRegistry[e].setHook!=null&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(this.flagRegistry[e]==null)throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(typeof this.global=="undefined"||typeof this.global.location=="undefined"||typeof this.global.location.search=="undefined")return;let e=this.getQueryParams(this.global.location.search);NE in e&&e[NE].split(",").forEach(n=>{let[o,s]=n.split(":");this.urlFlags[o]=o7(o,s)})}};function r7(r){let e={};return r.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(t,...n)=>(n7(e,n[0],n[1]),n.join("="))),e}function n7(r,e,t){r[decodeURIComponent(e)]=decodeURIComponent(t||"")}function o7(r,e){if(e=e.toLowerCase(),e==="true"||e==="false")return e==="true";if(`${+e}`===e)return+e;throw new Error(`Could not parse value flag value ${e} for flag ${r}.`)}function Ze(){return xw}var xw=null;function AE(r){xw=r}var Tw;function kw(){if(Tw==null){let r;if(typeof window!="undefined")r=window;else if(typeof global!="undefined")r=global;else if(typeof process!="undefined")r=process;else if(typeof self!="undefined")r=self;else throw new Error("Could not find a global object");Tw=r}return Tw}function s7(){let r=kw();return r._tfGlobals==null&&(r._tfGlobals=new Map),r._tfGlobals}function hh(r,e){let t=s7();if(t.has(r))return t.get(r);{let n=e();return t.set(r,n),t.get(r)}}var DE="Abs",EE="Acos",ME="Acosh",bx="Add",FE="AddN",RE="All",LE="Any",$E="ArgMax",PE="ArgMin",BE="Asin",OE="Asinh",zE="Atan",GE="Atanh",WE="Atan2",KE="AvgPool",gwe="AvgPoolGrad",VE="AvgPool3D",bwe="AvgPool3DGrad",UE="BatchMatMul",jE="BatchToSpaceND",HE="Bincount",ywe="BroadcastTo",yx="Cast",qE="Ceil",XE="ClipByValue",YE="Complex",ZE="ComplexAbs",JE="Concat",QE="Conv2D",e2="Conv2DBackpropFilter",t2="Conv2DBackpropInput",r2="Conv3D",xwe="Conv3DBackpropFilterV2",n2="Conv3DBackpropInputV2",o2="Cos",s2="Cosh",a2="Cumsum",i2="CropAndResize",l2="DenseBincount",u2="DepthToSpace",p2="DepthwiseConv2dNative",c2="DepthwiseConv2dNativeBackpropFilter",m2="DepthwiseConv2dNativeBackpropInput",f2="Diag",d2="Dilation2D",Twe="Dilation2DBackpropInput",kwe="Dilation2DBackpropFilter",h2="RealDiv",g2="Einsum",b2="Elu",Iwe="EluGrad",y2="Erf",x2="Equal",T2="Exp",k2="ExpandDims",I2="Expm1",v2="FFT",w2="Fill",_2="FlipLeftRight",C2="Floor",S2="FloorDiv",N2="FusedBatchNorm",A2="GatherV2",D2="GatherNd",E2="Greater",M2="GreaterEqual",xx="Identity",F2="IFFT",R2="Imag",L2="IsFinite",$2="IsInf",P2="IsNan",B2="LeakyRelu",O2="Less",z2="LessEqual",G2="LinSpace",W2="Log",K2="Log1p",V2="LogicalAnd",U2="LogicalNot",j2="LogicalOr",vwe="LogSoftmax",H2="LRN",wwe="LRNGrad",q2="Max",X2="Maximum",Y2="MaxPool",_we="MaxPoolGrad",Z2="MaxPool3D",Cwe="MaxPool3DGrad",J2="MaxPoolWithArgmax",Q2="Mean",eM="Min",tM="Minimum",rM="MirrorPad",nM="Mod",oM="Multinomial",sM="Multiply",aM="Neg",iM="NotEqual",lM="NonMaxSuppressionV3",uM="NonMaxSuppressionV4",pM="NonMaxSuppressionV5",cM="OnesLike",mM="OneHot",fM="Pack",dM="PadV2",Swe="Pool",hM="Pow",gM="Prelu",bM="Prod",yM="Range",xM="Real",TM="Reciprocal",kM="Relu",IM="Reshape",vM="ResizeNearestNeighbor",Nwe="ResizeNearestNeighborGrad",wM="ResizeBilinear",Awe="ResizeBilinearGrad",_M="Relu6",CM="Reverse",SM="Round",NM="Rsqrt",AM="ScatterNd",DM="Select",EM="Selu",MM="Slice",FM="Sin",RM="Sinh",LM="Sign",$M="Sigmoid",PM="Softplus",BM="Sqrt",OM="Sum",zM="SpaceToBatchND",GM="SplitV",WM="Softmax",KM="SparseFillEmptyRows",VM="SparseReshape",UM="SparseSegmentMean",jM="SparseSegmentSum",HM="SparseToDense",qM="SquaredDifference",Dwe="Square",XM="StridedSlice",YM="StringNGrams",ZM="StringSplit",JM="StringToHashBucketFast",QM="Sub",eF="Tan",tF="Tanh",Tx="Tile",rF="TopK",nF="Transform",oF="Transpose",sF="Unique",aF="Unpack",iF="UnsortedSegmentSum",lF="ZerosLike",uF="Step",Iw="FromPixels",pF="RotateWithOffset",vw="_FusedMatMul",ww="FusedConv2D",_w="FusedDepthwiseConv2D";var $m=hh("kernelRegistry",()=>new Map),gh=hh("gradRegistry",()=>new Map);function bh(r,e){let t=Sw(r,e);return $m.get(t)}function Cw(r){return gh.get(r)}function kx(r){let e=$m.entries(),t=[];for(;;){let{done:n,value:o}=e.next();if(n)break;let[s,i]=o,[a]=s.split("_");a===r&&t.push(i)}return t}function a7(r){let{kernelName:e,backendName:t}=r,n=Sw(e,t);$m.has(n)&&console.warn(`The kernel '${e}' for backend '${t}' is already registered`),$m.set(n,r)}function Rwe(r){let{kernelName:e}=r;gh.has(e)&&Ze().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${e}'`),gh.set(e,r)}function Lwe(r,e){let t=Sw(r,e);if(!$m.has(t))throw new Error(`The kernel '${r}' for backend '${e}' is not registered`);$m.delete(t)}function $we(r){if(!gh.has(r))throw new Error(`The gradient '${r}' for backend is not registered`);gh.delete(r)}function Pwe(r,e){kx(r).forEach(n=>{let o=Object.assign({},n,{backendName:e});a7(o)})}function Sw(r,e){return`${e}_${r}`}var _F={};Ge(_F,{arraysEqual:()=>En,assert:()=>P,assertNonNegativeIntegerDimensions:()=>fh,assertNonNull:()=>No,assertShapesMatch:()=>Jt,bytesFromStringArray:()=>yw,bytesPerElement:()=>hx,checkConversionForErrors:()=>gw,clamp:()=>Mm,computeStrides:()=>ni,createScalarValue:()=>f7,createShuffledIndices:()=>XX,decodeString:()=>zm,distSquared:()=>UX,encodeString:()=>_u,fetch:()=>h7,fingerPrint64:()=>m7,flatten:()=>Ls,getArrayFromDType:()=>hw,getTypedArrayFromDType:()=>dw,hasEncodingLoss:()=>JX,hexToLong:()=>yh,indexToLoc:()=>t7,inferDtype:()=>Fm,inferFromImplicitShape:()=>ZX,isBoolean:()=>_E,isFunction:()=>ri,isInt:()=>Qt,isNumber:()=>CE,isPromise:()=>dh,isScalarShape:()=>jX,isString:()=>$s,isTypedArray:()=>zr,isValidDtype:()=>bw,locToIndex:()=>e7,makeOnesTypedArray:()=>mh,makeZerosNestedTypedArray:()=>QX,makeZerosTypedArray:()=>Lm,nearestDivisor:()=>Rm,nearestLargerEven:()=>WX,now:()=>$p,parseAxisParam:()=>vu,randUniform:()=>VX,repeatedTry:()=>YX,rightPad:()=>Dp,shuffle:()=>wE,shuffleCombo:()=>GX,sizeFromShape:()=>Ct,sizeToSquarishShape:()=>qX,squeezeShape:()=>fw,sum:()=>KX,tanh:()=>HX,toNestedArray:()=>Ep,toTypedArray:()=>Om});var kF=Wi(Dw());var Rp=kF.default||kF;function yh(r){return Rp.fromString(r,!0,16)}var IF=yh("c3a5c85c97cb3127"),Lp=yh("b492b66fbe98f273"),Mn=yh("9ae16a3b2f90404f");function Ew(r){return r.xor(r.shru(47))}function vF(r,e,t){let n=r.slice(e,e+t);return Rp.fromBytes(Array.from(n),!0,!0)}function or(r,e){return vF(r,e,8)}function wF(r,e){return vF(r,e,4)}function en(r,e){return e===0?r:r.shru(e).or(r.shl(64-e))}function wu(r,e,t=yh("9ddfea08eb382d69")){let n=r.xor(e).mul(t);n=n.xor(n.shru(47));let o=e.xor(n).mul(t);return o=o.xor(o.shru(47)),o=o.mul(t),o}function l7(r,e,t,n,o,s){o=o.add(r),s=en(s.add(o).add(n),21);let i=o;return o=o.add(e),o=o.add(t),s=s.add(en(o,44)),[o.add(n),s.add(i)]}function vx(r,e,t,n){return l7(or(r,e),or(r,e+8),or(r,e+16),or(r,e+24),t,n)}function u7(r,e=r.length){if(e>=8){let t=Mn.add(e*2),n=or(r,0).add(Mn),o=or(r,e-8),s=en(o,37).mul(t).add(n),i=en(n,25).add(o).mul(t);return wu(s,i,t)}if(e>=4){let t=Mn.add(e*2),n=wF(r,0);return wu(n.shl(3).add(e),wF(r,e-4),t)}if(e>0){let t=r[0],n=r[e>>1],o=r[e-1],s=t+(n<<8),i=e+(o<<2);return Ew(Mn.mul(s).xor(IF.mul(i))).mul(Mn)}return Mn}function p7(r,e=r.length){let t=Mn.add(e*2),n=or(r,0).mul(Lp),o=or(r,8),s=or(r,e-8).mul(t),i=or(r,e-16).mul(Mn);return wu(en(n.add(o),43).add(en(s,30)).add(i),n.add(en(o.add(Mn),18)).add(s),t)}function c7(r,e=r.length){let t=Mn.add(e*2),n=or(r,0).mul(Mn),o=or(r,8),s=or(r,e-8).mul(t),i=or(r,e-16).mul(Mn),a=en(n.add(o),43).add(en(s,30)).add(i),l=wu(a,n.add(en(o.add(Mn),18)).add(s),t),u=or(r,16).mul(t),p=or(r,24),c=a.add(or(r,e-32)).mul(t),m=l.add(or(r,e-24)).mul(t);return wu(en(u.add(p),43).add(en(c,30)).add(m),u.add(en(p.add(n),18)).add(c),t)}function m7(r,e=r.length){let t=Rp.fromNumber(81,!0);if(e<=32)return e<=16?u7(r,e):p7(r,e);if(e<=64)return c7(r,e);let n=t,o=t.mul(Lp).add(113),s=Ew(o.mul(Mn).add(113)).mul(Mn),i=[Rp.UZERO,Rp.UZERO],a=[Rp.UZERO,Rp.UZERO];n=n.mul(Mn).add(or(r,0));let l=0,u=(e-1>>6)*64,p=u+(e-1&63)-63;do n=en(n.add(o).add(i[0]).add(or(r,l+8)),37).mul(Lp),o=en(o.add(i[1]).add(or(r,l+48)),42).mul(Lp),n=n.xor(a[1]),o=o.add(i[0]).add(or(r,l+40)),s=en(s.add(a[0]),33).mul(Lp),i=vx(r,l,i[1].mul(Lp),n.add(a[0])),a=vx(r,l+32,s.add(a[1]),o.add(or(r,l+16))),[s,n]=[n,s],l+=64;while(l!==u);let c=Lp.add(s.and(255).shl(1));return l=p,a[0]=a[0].add(e-1&63),i[0]=i[0].add(a[0]),a[0]=a[0].add(i[0]),n=en(n.add(o).add(i[0]).add(or(r,l+8)),37).mul(c),o=en(o.add(i[1]).add(or(r,l+48)),42).mul(c),n=n.xor(a[1].mul(9)),o=o.add(i[0].mul(9).add(or(r,l+40))),s=en(s.add(a[0]),33).mul(c),i=vx(r,l,i[1].mul(c),n.add(a[0])),a=vx(r,l+32,s.add(a[1]),o.add(or(r,l+16))),[s,n]=[n,s],wu(wu(i[0],a[0],c).add(Ew(o).mul(IF)).add(s),wu(i[1],a[1],c).add(n),c)}function f7(r,e){return e==="string"?_u(r):Om([r],e)}function d7(r,e){return r instanceof Float32Array&&e==="float32"||r instanceof Int32Array&&e==="int32"||r instanceof Uint8Array&&e==="bool"}function Om(r,e){if(e==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(r)&&(r=Ls(r)),Ze().getBool("DEBUG")&&gw(r,e),d7(r,e))return r;if(e==null||e==="float32"||e==="complex64")return new Float32Array(r);if(e==="int32")return new Int32Array(r);if(e==="bool"){let t=new Uint8Array(r.length);for(let n=0;n<t.length;++n)Math.round(r[n])!==0&&(t[n]=1);return t}else throw new Error(`Unknown data type ${e}`)}function $p(){return Ze().platform.now()}function h7(r,e){return Ze().platform.fetch(r,e)}function _u(r,e="utf-8"){return e=e||"utf-8",Ze().platform.encode(r,e)}function zm(r,e="utf-8"){return e=e||"utf-8",Ze().platform.decode(r,e)}var Mw=class{constructor(e,t){this.backendTimer=e;this.logger=t;t==null&&(this.logger=new CF)}profileKernel(e,t,n){let o,s=()=>{o=n()},i,a=$p();if(this.backendTimer.timerAvailable())i=this.backendTimer.time(s);else{s();for(let u of o)u.dataSync();i=Promise.resolve({kernelMs:$p()-a})}if(Ze().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let u=0;u<o.length;u++){let p=o[u];p.data().then(c=>{g7(c,p.dtype,e)})}return{kernelName:e,outputs:o,inputs:t,timeMs:i.then(u=>u.kernelMs),extraInfo:i.then(u=>u.getExtraProfileInfo!=null?u.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:n,timeMs:o,inputs:s,extraInfo:i}=e;n.forEach(a=>{Promise.all([a.data(),o,i]).then(l=>{this.logger.logKernelProfile(t,a,l[0],l[1],s,l[2])})})}};function g7(r,e,t){if(e!=="float32")return!1;for(let n=0;n<r.length;n++){let o=r[n];if(isNaN(o)||!isFinite(o))return console.warn(`Found ${o} in the result of '${t}'`),!0}return!1}var CF=class{logKernelProfile(e,t,n,o,s,i){let a=typeof o=="number"?Dp(`${o}ms`,9):o.error,l=Dp(e,25),u=t.rank,p=t.size,c=Dp(t.shape.toString(),14),m="";for(let f in s){let d=s[f];if(d!=null){let h=d.shape||t.shape,g=h.length;m+=`${f}: ${g}D ${g>0?h:""} `}}console.log(`%c${l} %c${a} %c${u}D ${c} %c${p} %c${m} %c${i}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function SF(r,e,t){let n={},o={};for(let l=0;l<e.length;l++)n[e[l].id]=!0;for(let l=0;l<r.length;l++){let u=r[l],p=u.inputs;for(let c in p){let m=p[c],f=!1;for(let d=0;d<e.length;d++)if(n[m.id]){u.outputs.forEach(h=>n[h.id]=!0),f=!0,o[u.id]=!0;break}if(f)break}}let s={};s[t.id]=!0;let i={};for(let l=r.length-1;l>=0;l--){let u=r[l],p=u.inputs;for(let c=0;c<u.outputs.length;c++)if(s[u.outputs[c].id]){for(let m in p)s[p[m].id]=!0,i[u.id]=!0;break}}let a=[];for(let l=0;l<r.length;l++){let u=r[l];if(o[u.id]&&i[u.id]){let p={};for(let m in u.inputs){let f=u.inputs[m];n[f.id]&&(p[m]=f)}let c=Object.assign({},u);c.inputs=p,c.outputs=u.outputs,a.push(c)}}return a}function NF(r,e,t,n){for(let o=e.length-1;o>=0;o--){let s=e[o],i=[];if(s.outputs.forEach(l=>{let u=r[l.id];u!=null?i.push(u):i.push(null)}),s.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);let a=s.gradient(i);for(let l in s.inputs){if(!(l in a))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(a)}.`);let u=t(()=>a[l]());if(u.dtype!=="float32")throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${u.dtype}'`);let p=s.inputs[l];if(!En(u.shape,p.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${l}' has shape '${u.shape}', which does not match the shape of the input '${p.shape}'`);if(r[p.id]==null)r[p.id]=u;else{let c=r[p.id];r[p.id]=n(c,u),c.dispose()}}}}var AF=20,xh=3,Fw=7;function DF(r,e,t,n){let o=ni(e),s=b7(r,e,t,o),i=e.length,a=wx(r,e,t,o,s),l=["Tensor"];return n&&(l.push(` dtype: ${t}`),l.push(` rank: ${i}`),l.push(` shape: [${e}]`),l.push(" values:")),l.push(a.map(u=>" "+u).join(`
|
|
`)),l.join(`
|
|
`)}function b7(r,e,t,n){let o=Ct(e),s=n[n.length-1],i=new Array(s).fill(0),a=e.length,l=t==="complex64"?kh(r):r;if(a>1)for(let u=0;u<o/s;u++){let p=u*s;for(let c=0;c<s;c++)i[c]=Math.max(i[c],Th(l[p+c],0,t).length)}return i}function Th(r,e,t){let n;return Array.isArray(r)?n=`${parseFloat(r[0].toFixed(Fw))} + ${parseFloat(r[1].toFixed(Fw))}j`:$s(r)?n=`'${r}'`:t==="bool"?n=EF(r):n=parseFloat(r.toFixed(Fw)).toString(),Dp(n,e)}function EF(r){return r===0?"false":"true"}function wx(r,e,t,n,o,s=!0){let i=t==="complex64"?2:1,a=e[0],l=e.length;if(l===0){if(t==="complex64"){let h=kh(r);return[Th(h[0],0,t)]}return t==="bool"?[EF(r[0])]:[r[0].toString()]}if(l===1){if(a>AF){let g=xh*i,b=Array.from(r.slice(0,g)),y=Array.from(r.slice((a-xh)*i,a*i));return t==="complex64"&&(b=kh(b),y=kh(y)),["["+b.map((T,k)=>Th(T,o[k],t)).join(", ")+", ..., "+y.map((T,k)=>Th(T,o[a-xh+k],t)).join(", ")+"]"]}let h=t==="complex64"?kh(r):Array.from(r);return["["+h.map((g,b)=>Th(g,o[b],t)).join(", ")+"]"]}let u=e.slice(1),p=n.slice(1),c=n[0]*i,m=[];if(a>AF){for(let h=0;h<xh;h++){let g=h*c,b=g+c;m.push(...wx(r.slice(g,b),u,t,p,o,!1))}m.push("...");for(let h=a-xh;h<a;h++){let g=h*c,b=g+c;m.push(...wx(r.slice(g,b),u,t,p,o,h===a-1))}}else for(let h=0;h<a;h++){let g=h*c,b=g+c;m.push(...wx(r.slice(g,b),u,t,p,o,h===a-1))}let f=l===2?",":"";m[0]="["+m[0]+f;for(let h=1;h<m.length-1;h++)m[h]=" "+m[h]+f;let d=`,
|
|
`;for(let h=2;h<l;h++)d+=`
|
|
`;return m[m.length-1]=" "+m[m.length-1]+"]"+(s?"":d),m}function kh(r){let e=[];for(let t=0;t<r.length;t+=2)e.push([r[t],r[t+1]]);return e}var Pp=class{constructor(e,t,n){this.dtype=t;if(this.shape=e.slice(),this.size=Ct(e),n!=null){let o=n.length;P(o===this.size,()=>`Length of values '${o}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||hw(t,this.size),this.strides=ni(e)}set(e,...t){t.length===0&&(t=[0]),P(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let o of e){if(o<0||o>=this.shape[t]){let s=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(s)}t++}let n=e[e.length-1];for(let o=0;o<e.length-1;++o)n+=this.strides[o]*e[o];return this.values[n]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];let t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return oi().makeTensor(this.values,this.shape,this.dtype)}},oi=null,Gm=null,y7=null;function MF(r){oi=r}function FF(r){Gm=r}function RF(r){y7=r}var Yt=class{constructor(e,t,n,o){this.kept=!1;this.isDisposedInternal=!1;this.shape=e.slice(),this.dtype=t||"float32",this.size=Ct(e),this.strides=ni(e),this.dataId=n,this.id=o,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let e=await this.data();return Gm.buffer(this.shape,this.dtype,e)}bufferSync(){return Gm.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return Ep(this.shape,e,this.dtype==="complex64")}arraySync(){return Ep(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();let e=oi().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(n=>zm(n))}catch(n){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataSync(){this.throwIfDisposed();let e=oi().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>zm(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();let e=await oi().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(oi().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Gm.print(this,e)}clone(){return this.throwIfDisposed(),Gm.clone(this)}toString(e=!1){let t=this.dataSync();return DF(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Gm.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),oi().makeVariable(this,e,t,n)}};Object.defineProperty(Yt,Symbol.hasInstance,{value:r=>!!r&&r.data!=null&&r.dataSync!=null&&r.throwIfDisposed!=null});function x7(){return hh("Tensor",()=>Yt)}x7();var Cu=class extends Yt{constructor(e,t,n,o){super(e.shape,e.dtype,e.dataId,o);this.trainable=t;this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!En(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);oi().disposeTensor(this),this.dataId=e.dataId,oi().incRef(this,null)}dispose(){oi().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(Cu,Symbol.hasInstance,{value:r=>r instanceof Yt&&r.assign!=null&&r.assign instanceof Function});var $F={};Ge($F,{assertTypesMatch:()=>Ow,getTensorsInContainer:()=>Ih,isTensorInList:()=>I7,makeTypesMatch:()=>Qe});var Rw;(function(a){a.R0="R0",a.R1="R1",a.R2="R2",a.R3="R3",a.R4="R4",a.R5="R5",a.R6="R6"})(Rw||(Rw={}));var Lw;(function(o){o.float32="float32",o.int32="int32",o.bool="int32",o.complex64="complex64"})(Lw||(Lw={}));var $w;(function(o){o.float32="float32",o.int32="int32",o.bool="bool",o.complex64="complex64"})($w||($w={}));var Pw;(function(o){o.float32="float32",o.int32="float32",o.bool="float32",o.complex64="complex64"})(Pw||(Pw={}));var Bw;(function(o){o.float32="complex64",o.int32="complex64",o.bool="complex64",o.complex64="complex64"})(Bw||(Bw={}));var T7={float32:Pw,int32:Lw,bool:$w,complex64:Bw};function Wm(r,e){if(r==="string"||e==="string"){if(r==="string"&&e==="string")return"string";throw new Error(`Can not upcast ${r} with ${e}`)}return T7[r][e]}function k7(r){return Wm(r,"int32")}function Qe(r,e){if(r.dtype===e.dtype)return[r,e];let t=Wm(r.dtype,e.dtype);return[r.cast(t),e.cast(t)]}function Ow(r,e){P(r.dtype===e.dtype,()=>`The dtypes of the first(${r.dtype}) and second(${e.dtype}) input must match`)}function I7(r,e){return e.some(t=>t.id===r.id)}function Ih(r){let e=[],t=new Set;return LF(r,e,t),e}function LF(r,e,t){if(r==null)return;if(r instanceof Yt){e.push(r);return}if(!v7(r))return;let n=r;for(let o in n){let s=n[o];t.has(s)||(t.add(s),LF(s,e,t))}}function v7(r){return Array.isArray(r)||typeof r=="object"}function zw(r){return r.kernelName!=null}var Gw=class{constructor(){this.registeredVariables={};this.nextTapeNodeId=0;this.numBytes=0;this.numTensors=0;this.numStringTensors=0;this.numDataBuffers=0;this.gradientDepth=0;this.kernelDepth=0;this.scopeStack=[];this.numDataMovesStack=[];this.nextScopeId=0;this.tensorInfo=new WeakMap;this.profiling=!1;this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null,get kernelNames(){return Array.from(new Set(this.kernels.map(e=>e.name)))}}}dispose(){for(let e in this.registeredVariables)this.registeredVariables[e].dispose()}},Cx=class{constructor(e){this.ENV=e;this.registry={};this.registryFactory={};this.pendingBackendInitId=0;this.state=new Gw}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;let e=this.getSortedBackends();for(let t=0;t<e.length;t++){let n=e[t];if(await this.initializeBackend(n).success){await this.setBackend(n);return}}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(this.pendingBackendInit!=null)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(this.backendInstance==null){let{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){let{asyncInit:t}=this.initializeBackend(e);if(t)return null}else return null;return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(console.warn(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(this.registryFactory[e]==null)throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,this.registry[e]==null){this.backendInstance=null;let{success:t,asyncInit:n}=this.initializeBackend(e);if(!(n?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new Mw(this.backendInstance),!0}setupRegisteredKernels(){kx(this.backendName).forEach(t=>{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){kx(e).forEach(n=>{n.disposeFunc!=null&&n.disposeFunc(this.registry[e])})}initializeBackend(e){let t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{let n=t.factory();if(n&&!(n instanceof dx)&&typeof n.then=="function"){let o=++this.pendingBackendInitId,s=n.then(i=>o<this.pendingBackendInitId?!1:(this.registry[e]=i,this.pendingBackendInit=null,!0)).catch(i=>(o<this.pendingBackendInitId||(this.pendingBackendInit=null,console.warn(`Initialization of backend ${e} failed`),console.warn(i.stack||i.message)),!1));return this.pendingBackendInit=s,{success:s,asyncInit:!0}}else return this.registry[e]=n,{success:!0,asyncInit:!1}}catch(n){return console.warn(`Initialization of backend ${e} failed`),console.warn(n.stack||n.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(Object.keys(this.registryFactory).length===0)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){let e=this.getSortedBackends();for(let t=0;t<e.length;t++){let n=e[t],{success:o,asyncInit:s}=this.initializeBackend(n);if(s||o)return{name:n,asyncInit:s}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){let n=this.state.tensorInfo.get(t),o=n.backend,s=this.readSync(t),i=o.refCount(t);o.disposeData(t,!0),n.backend=e,e.move(t,s,n.shape,n.dtype,i),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n=null;if(t==null){if(typeof e!="function")throw new Error("Please provide a function to tidy()");t=e}else{if(typeof e!="string"&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof t!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");n=e}let o;return this.scopedRun(()=>this.startScope(n),()=>this.endScope(o),()=>(o=t(),o instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),o))}scopedRun(e,t,n){e();try{let o=n();return t(),o}catch(o){throw t(),o}}nextTensorId(){return Cx.nextTensorId++}nextVariableId(){return Cx.nextVariableId++}clone(e){let t=L.runKernel(xx,{x:e}),n={x:e},o=i=>({x:()=>{let a="float32",l={x:i},u={dtype:a};return L.runKernel(yx,l,u)}}),s=[];return this.addTapeNode(this.state.activeScope.name,n,[t],o,s,{}),t}runKernel(e,t,n){if(!(bh(e,this.backendName)!=null))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){let o=this.backend.numDataIds(),s=0;n.forEach(l=>{s+=l.dtype==="complex64"?3:1});let i=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],a=o-t-s-i;if(a>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${a} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[],o=this.isTapeOn(),s=this.state.numBytes,i=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let a;this.backendName==null&&this.backend;let l,u=zw(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(zw(e)){let{kernelName:d,inputs:h,attrs:g}=e;this.backendName==null&&this.backend;let b=bh(d,this.backendName);P(b!=null,()=>`Cannot find registered kernel '${d}' for backend '${this.backendName}'`),a=()=>{let y=this.backend.numDataIds();l=b.kernelFunc({inputs:h,attrs:g,backend:this.backend});let T=Array.isArray(l)?l:[l];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(d,y,T);let k=T.map(I=>{if(I.rank!=null)return I;let{dataId:S,shape:N,dtype:F}=I;return this.makeTensorFromDataId(S,N,F)});if(o){let I=this.getTensorsForGradient(d,h,k);n=this.saveTensorsForBackwardMode(I)}return k}}else{let{forwardFunc:d}=e,h=g=>{!o||(n=g.map(b=>this.keep(this.clone(b))))};a=()=>{let g=this.backend.numDataIds();l=this.tidy(()=>d(this.backend,h));let b=Array.isArray(l)?l:[l];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(u,g,b),b}}let{inputs:p,attrs:c}=e,m=zw(e)?null:e.backwardsFunc,f;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=a():(f=this.profiler.profileKernel(u,p,()=>a()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(f),t=f.outputs)}),o&&this.addTapeNode(u,p,t,m,n,c),this.state.profiling&&this.state.activeProfile.kernels.push({name:u,bytesAdded:this.state.numBytes-s,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-i,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(p).map(d=>p[d]!=null?p[d].shape:null),outputShapes:t.map(d=>d.shape),kernelTimeMs:f.timeMs,extraInfo:f.extraInfo}),Array.isArray(l)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(n=>this.keep(this.clone(n)))}getTensorsForGradient(e,t,n){let o=Cw(e);if(o!=null){let s=o.inputsToSave||[],i=o.outputsToSave||[],a;o.saveAllInputs?(P(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),a=Object.keys(t).map(u=>t[u])):a=s.map(u=>t[u]);let l=n.filter((u,p)=>i[p]);return a.concat(l)}return[]}makeTensor(e,t,n,o){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",o=o||this.backend;let s=e;n==="string"&&$s(e[0])&&(s=e.map(l=>_u(l)));let i=o.write(s,t,n),a=new Yt(t,n,i,this.nextTensorId());if(this.trackTensor(a,o),n==="string"){let l=this.state.tensorInfo.get(i),u=yw(s);this.state.numBytes+=u-l.bytes,l.bytes=u}return a}makeTensorFromDataId(e,t,n,o){n=n||"float32";let s=new Yt(t,n,e,this.nextTensorId());return this.trackTensor(s,o),s}makeVariable(e,t=!0,n,o){n=n||this.nextVariableId().toString(),o!=null&&o!==e.dtype&&(e=e.cast(o));let s=new Cu(e,t,n,this.nextTensorId());if(this.state.registeredVariables[s.name]!=null)throw new Error(`Variable with name ${s.name} was already registered`);return this.state.registeredVariables[s.name]=s,this.incRef(s,this.backend),s}trackTensor(e,t){this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++;let n=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(n=e.size*hx(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof Cu||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;let t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,e.dtype==="string"&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),e.dtype!=="complex64"&&e.dtype!=="string"){let n=e.size*hx(e.dtype);this.state.numBytes-=n}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(let e in this.state.registeredVariables){let 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(){let 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;let t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(o=>o.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(let o of this.state.activeProfile.kernels)o.kernelTimeMs=await o.kernelTimeMs,o.extraInfo=await o.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,n,o,s,i){let a={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:s},l=Cw(e);l!=null&&(o=l.gradFunc),o!=null&&(a.gradient=u=>(u=u.map((p,c)=>{if(p==null){let m=n[c],f=Lm(m.size,m.dtype);return this.makeTensor(f,m.shape,m.dtype)}return p}),o(u.length>1?u:u[0],s,i))),this.state.activeTape.push(a)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){let t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){let t=Ih(e),n=new Set(t.map(s=>s.id));for(let s=0;s<this.state.activeScope.track.length;s++){let i=this.state.activeScope.track[s];!i.kept&&!n.has(i.id)&&i.dispose()}let o=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(s=>{!s.kept&&s.scopeId===o.id&&this.track(s)})}gradients(e,t,n,o=!1){if(P(t.length>0,()=>"gradients() received an empty list of xs."),n!=null&&n.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);let s=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));P(s instanceof Yt,()=>"The result y returned by f() must be a tensor.");let i=SF(this.state.activeTape,t,s);if(!o&&i.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",()=>{let a={};a[s.id]=n==null?w7(s.shape):n,NF(a,i,u=>this.tidy(u),_7);let l=t.map(u=>a[u.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(u=>{for(let p of u.saved)p.dispose()}),this.state.activeTape=null),{value:s,grads:l}})}customGrad(e){return P(ri(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{P(t.every(a=>a instanceof Yt),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n,o={};t.forEach((a,l)=>{o[l]=a});let s=(a,l)=>(n=e(...t,l),P(n.value instanceof Yt,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),P(ri(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),i=(a,l)=>{let u=n.gradFunc(a,l),p=Array.isArray(u)?u:[u];P(p.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(...)."),P(p.every(m=>m instanceof Yt),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");let c={};return p.forEach((m,f)=>{c[f]=()=>m}),c};return this.runKernelFunc({forwardFunc:s,backwardsFunc:i,inputs:o})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}async time(e){let t=$p(),n=await this.backend.time(e);return n.wallMs=$p()-t,n}track(e){return this.state.activeScope!=null&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new Gw;for(let e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}},_x=Cx;_x.nextTensorId=0,_x.nextVariableId=0;function w7(r){let e=mh(Ct(r),"float32");return L.makeTensor(e,r,"float32")}function Ww(){let r=kw();if(r._tfengine==null){let e=new gx(r);r._tfengine=new _x(e)}return AE(r._tfengine.ENV),MF(()=>r._tfengine),r._tfengine}var L=Ww();function _7(r,e){let t={a:r,b:e};return L.runKernel(bx,t)}var PF={};Ge(PF,{isBrowser:()=>Kw,isMobile:()=>S7});function C7(){return typeof navigator!="undefined"&&navigator!=null}function S7(r){if(r||C7()){if(r||(r=navigator),r.product==="ReactNative")return!0;let e=r.userAgent||r.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 Kw(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var Bs=Ze();Bs.registerFlag("DEBUG",()=>!1,r=>{r&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")});Bs.registerFlag("IS_BROWSER",()=>Kw());Bs.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Bs.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Bs.registerFlag("PROD",()=>!1);Bs.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Bs.getBool("DEBUG"));Bs.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Bs.registerFlag("IS_TEST",()=>!1);Bs.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);Bs.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);function ln(r,e){let t=r;if(zr(r))return e==="string"?[]:[r.length];if(!Array.isArray(r))return[];let n=[];for(;Array.isArray(t)||zr(t)&&e!=="string";)n.push(t.length),t=t[0];return Array.isArray(r)&&Ze().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&BF(r,n,[]),n}function BF(r,e,t){if(t=t||[],!Array.isArray(r)&&!zr(r)){P(e.length===0,()=>`Element arr[${t.join("][")}] is a primitive, but should be an array/TypedArray of ${e[0]} elements`);return}P(e.length>0,()=>`Element arr[${t.join("][")}] should be a primitive, but is an array of ${r.length} elements`),P(r.length===e[0],()=>`Element arr[${t.join("][")}] should have ${e[0]} elements, but has ${r.length} elements`);let n=e.slice(1);for(let o=0;o<r.length;++o)BF(r[o],n,t.concat(o))}function OF(r,e,t,n){if(r!=="string_or_numeric"){if(r==null)throw new Error("Expected dtype cannot be null.");if(r!=="numeric"&&r!==e||r==="numeric"&&e==="string")throw new Error(`Argument '${t}' passed to '${n}' must be ${r} tensor, but got ${e} tensor`)}}function w(r,e,t,n="numeric"){if(r instanceof Yt)return OF(n,r.dtype,e,t),r;let o=Fm(r);if(o!=="string"&&["bool","int32","float32"].indexOf(n)>=0&&(o=n),OF(n,o,e,t),r==null||!zr(r)&&!Array.isArray(r)&&typeof r!="number"&&typeof r!="boolean"&&typeof r!="string"){let l=r==null?"null":r.constructor.name;throw new Error(`Argument '${e}' passed to '${t}' must be a Tensor or TensorLike, but got '${l}'`)}let s=ln(r,o);!zr(r)&&!Array.isArray(r)&&(r=[r]);let a=o!=="string"?Om(r,o):Ls(r,[],!0);return L.makeTensor(a,s,o)}function Ki(r,e,t,n="numeric"){if(!Array.isArray(r))throw new Error(`Argument ${e} passed to ${t} must be a \`Tensor[]\` or \`TensorLike[]\``);return r.map((s,i)=>w(s,`${e}[${i}]`,t,n))}var zF="__op";function E(r){let e=Object.keys(r);if(e.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${e.length} keys.`);let t=e[0],n=r[t];t.endsWith("_")&&(t=t.substring(0,t.length-1)),t=t+zF;let o=(...s)=>{L.startScope(t);try{let i=n(...s);return dh(i)&&console.error("Cannot return a Promise inside of tidy."),L.endScope(i),i}catch(i){throw L.endScope(null),i}};return Object.defineProperty(o,"name",{value:t,configurable:!0}),o}function N7(r,e){let t=w(r,"real","complex"),n=w(e,"imag","complex");Jt(t.shape,n.shape,`real and imag shapes, ${t.shape} and ${n.shape}, must match in call to tf.complex().`);let o={real:t,imag:n};return L.runKernel(YE,o)}var ss=E({complex_:N7});function Fn(r,e,t,n){if(n==null&&(n=Fm(r)),n==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!zr(r)&&!Array.isArray(r)&&typeof r!="number"&&typeof r!="boolean"&&typeof r!="string")throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(e!=null){fh(e);let o=Ct(e),s=Ct(t);P(o===s,()=>`Based on the provided shape, [${e}], the tensor should have ${o} values but has ${s}`);for(let i=0;i<t.length;++i){let a=t[i],l=i===t.length-1?a!==Ct(e.slice(i)):!0;P(t[i]===e[i]||!l,()=>`Error creating a new Tensor. Inferred shape (${t}) does not match the provided shape (${e}). `)}}return!zr(r)&&!Array.isArray(r)&&(r=[r]),e=e||t,r=n!=="string"?Om(r,n):Ls(r,[],!0),L.makeTensor(r,e,n)}function Vi(r,e,t){let n=ln(r,t);return Fn(r,e,n,t)}var vh={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};var Sx=4;async function GF(r,e){let t=[],n=[],o=Array.isArray(r)?r.map(i=>i.name):Object.keys(r);for(let i=0;i<o.length;++i){let a=o[i],l=Array.isArray(r)?r[i].tensor:r[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}`);let u={name:a,shape:l.shape,dtype:l.dtype};if(l.dtype==="string"){let p=new Promise(async c=>{let m=await l.bytes(),f=m.reduce((g,b)=>g+b.length,0)+Sx*m.length,d=new Uint8Array(f),h=0;for(let g=0;g<m.length;g++){let b=m[g],y=new Uint8Array(new Uint32Array([b.length]).buffer);d.set(y,h),h+=Sx,d.set(b,h),h+=b.length}c(d)});n.push(p)}else n.push(l.data());e!=null&&(u.group=e),t.push(u)}let s=await Promise.all(n);return{data:A7(s),specs:t}}function Nx(r,e){let t={},n,o=0;for(let s of e){let i=s.name,a=s.dtype,l=s.shape,u=Ct(l),p;if("quantization"in s){let c=s.quantization;if(c.dtype==="uint8"||c.dtype==="uint16"){if(!("min"in c&&"scale"in c))throw new Error(`Weight ${s.name} with quantization ${c.dtype} doesn't have corresponding metadata min and scale.`)}else if(c.dtype==="float16"){if(a!=="float32")throw new Error(`Weight ${s.name} is quantized with ${c.dtype} which only supports weights of type float32 not ${a}.`)}else throw new Error(`Weight ${s.name} has unknown quantization dtype ${c.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);let m=vh[c.dtype],f=r.slice(o,o+u*m),d=c.dtype==="uint8"?new Uint8Array(f):new Uint16Array(f);if(a==="float32")if(c.dtype==="uint8"||c.dtype==="uint16"){p=new Float32Array(d.length);for(let h=0;h<d.length;h++){let g=d[h];p[h]=g*c.scale+c.min}}else if(c.dtype==="float16")n===void 0&&(n=F7()),p=n(d);else throw new Error(`Unsupported quantization type ${c.dtype} for weight type float32.`);else if(a==="int32"){if(c.dtype!=="uint8"&&c.dtype!=="uint16")throw new Error(`Unsupported quantization type ${c.dtype} for weight type int32.`);p=new Int32Array(d.length);for(let h=0;h<d.length;h++){let g=d[h];p[h]=Math.round(g*c.scale+c.min)}}else throw new Error(`Unsupported dtype in weight '${i}': ${a}`);o+=u*m}else if(a==="string"){let c=Ct(s.shape);p=[];for(let m=0;m<c;m++){let f=new Uint32Array(r.slice(o,o+Sx))[0];o+=Sx;let d=new Uint8Array(r.slice(o,o+f));p.push(d),o+=f}}else{let c=vh[a],m=r.slice(o,o+u*c);if(a==="float32")p=new Float32Array(m);else if(a==="int32")p=new Int32Array(m);else if(a==="bool")p=new Uint8Array(m);else if(a==="complex64"){p=new Float32Array(m);let f=new Float32Array(p.length/2),d=new Float32Array(p.length/2);for(let b=0;b<f.length;b++)f[b]=p[b*2],d[b]=p[b*2+1];let h=Vi(f,l,"float32"),g=Vi(d,l,"float32");t[i]=ss(h,g),h.dispose(),g.dispose()}else throw new Error(`Unsupported dtype in weight '${i}': ${a}`);o+=u*c}a!=="complex64"&&(t[i]=Vi(p,l,a))}return t}function A7(r){if(r===null)throw new Error(`Invalid input value: ${JSON.stringify(r)}`);let e=0,t=[];r.forEach(s=>{if(e+=s.byteLength,t.push(s.byteLength===s.buffer.byteLength?s:new s.constructor(s)),!(s instanceof Float32Array||s instanceof Int32Array||s instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${s.constructor.name}`)});let n=new Uint8Array(e),o=0;return t.forEach(s=>{n.set(new Uint8Array(s.buffer),o),o+=s.byteLength}),n.buffer}var Vw=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function WF(r){return Vw?Buffer.byteLength(r):new Blob([r]).size}function KF(r){if(Vw)return Buffer.from(r).toString("base64");let e=new Uint8Array(r),t="";for(let n=0,o=e.length;n<o;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function VF(r){if(Vw){let n=Buffer.from(r,"base64");return n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t.set([e.charCodeAt(n)],n);return t.buffer}function Km(r){if(r.length===1)return r[0];let e=0;r.forEach(o=>{e+=o.byteLength});let t=new Uint8Array(e),n=0;return r.forEach(o=>{t.set(new Uint8Array(o),n),n+=o.byteLength}),t.buffer}function Uw(r){let e="/";for(r=r.trim();r.endsWith(e);)r=r.slice(0,r.length-1);let t=r.split(e);return t[t.length-1]}function si(r){if(r.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:r.modelTopology==null?0:WF(JSON.stringify(r.modelTopology)),weightSpecsBytes:r.weightSpecs==null?0:WF(JSON.stringify(r.weightSpecs)),weightDataBytes:r.weightData==null?0:r.weightData.byteLength}}function D7(){let r=t=>{let n=t<<13,o=0;for(;(n&8388608)==0;)o-=8388608,n<<=1;return n&=~8388608,o+=947912704,n|o},e=new Uint32Array(2048);e[0]=0;for(let t=1;t<1024;t++)e[t]=r(t);for(let t=1024;t<2048;t++)e[t]=939524096+(t-1024<<13);return e}function E7(){let r=new Uint32Array(64);r[0]=0,r[31]=1199570944,r[32]=2147483648,r[63]=3347054592;for(let e=1;e<31;e++)r[e]=e<<23;for(let e=33;e<63;e++)r[e]=2147483648+(e-32<<23);return r}function M7(){let r=new Uint32Array(64);for(let e=0;e<64;e++)r[e]=1024;return r[0]=r[32]=0,r}function F7(){let r=D7(),e=E7(),t=M7();return n=>{let o=new ArrayBuffer(4*n.length),s=new Uint32Array(o);for(let i=0;i<n.length;i++){let a=n[i],l=r[t[a>>10]+(a&1023)]+e[a>>10];s[i]=l}return new Float32Array(o)}}var Ut=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Ut.instance==null&&(Ut.instance=new Ut),Ut.instance}static registerSaveRouter(e){Ut.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Ut.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Ut.getHandlers(e,"save")}static getLoadHandlers(e,t){return Ut.getHandlers(e,"load",t)}static getHandlers(e,t,n){let o=[];return(t==="load"?Ut.getInstance().loadRouters:Ut.getInstance().saveRouters).forEach(i=>{let a=i(e,n);a!==null&&o.push(a)}),o}},UF=r=>Ut.registerSaveRouter(r),jF=r=>Ut.registerLoadRouter(r),HF=r=>Ut.getSaveHandlers(r),qF=(r,e)=>Ut.getLoadHandlers(r,e);var jw="tensorflowjs",Hw=1,Bp="models_store",Su="model_info_store";function XF(){if(!Ze().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");let r=typeof window=="undefined"?self:window,e=r.indexedDB||r.mozIndexedDB||r.webkitIndexedDB||r.msIndexedDB||r.shimIndexedDB;if(e==null)throw new Error("The current browser does not appear to support IndexedDB.");return e}function qw(r){let e=r.result;e.createObjectStore(Bp,{keyPath:"modelPath"}),e.createObjectStore(Su,{keyPath:"modelPath"})}var Ui=class{constructor(e){if(this.indexedDB=XF(),e==null||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise((n,o)=>{let s=this.indexedDB.open(jw,Hw);s.onupgradeneeded=()=>qw(s),s.onsuccess=()=>{let i=s.result;if(t==null){let a=i.transaction(Bp,"readonly"),u=a.objectStore(Bp).get(this.modelPath);u.onsuccess=()=>{if(u.result==null)return i.close(),o(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));n(u.result.modelArtifacts)},u.onerror=p=>(i.close(),o(u.error)),a.oncomplete=()=>i.close()}else{let a=si(t),l=i.transaction(Su,"readwrite"),u=l.objectStore(Su),p=u.put({modelPath:this.modelPath,modelArtifactsInfo:a}),c;p.onsuccess=()=>{c=i.transaction(Bp,"readwrite");let f=c.objectStore(Bp).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:a});f.onsuccess=()=>n({modelArtifactsInfo:a}),f.onerror=d=>{u=l.objectStore(Su);let h=u.delete(this.modelPath);h.onsuccess=()=>(i.close(),o(f.error)),h.onerror=g=>(i.close(),o(f.error))}},p.onerror=m=>(i.close(),o(p.error)),l.oncomplete=()=>{c==null?i.close():c.oncomplete=()=>i.close()}}},s.onerror=i=>o(s.error)})}};Ui.URL_SCHEME="indexeddb://";var YF=r=>Ze().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(Ui.URL_SCHEME)?R7(r.slice(Ui.URL_SCHEME.length)):null;Ut.registerSaveRouter(YF);Ut.registerLoadRouter(YF);function R7(r){return new Ui(r)}function L7(r){return r.startsWith(Ui.URL_SCHEME)?r.slice(Ui.URL_SCHEME.length):r}var Xw=class{constructor(){this.indexedDB=XF()}async listModels(){return new Promise((e,t)=>{let n=this.indexedDB.open(jw,Hw);n.onupgradeneeded=()=>qw(n),n.onsuccess=()=>{let o=n.result,s=o.transaction(Su,"readonly"),a=s.objectStore(Su).getAll();a.onsuccess=()=>{let l={};for(let u of a.result)l[u.modelPath]=u.modelArtifactsInfo;e(l)},a.onerror=l=>(o.close(),t(a.error)),s.oncomplete=()=>o.close()},n.onerror=o=>t(n.error)})}async removeModel(e){return e=L7(e),new Promise((t,n)=>{let o=this.indexedDB.open(jw,Hw);o.onupgradeneeded=()=>qw(o),o.onsuccess=()=>{let s=o.result,i=s.transaction(Su,"readwrite"),a=i.objectStore(Su),l=a.get(e),u;l.onsuccess=()=>{if(l.result==null)return s.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{let p=a.delete(e),c=()=>{u=s.transaction(Bp,"readwrite");let f=u.objectStore(Bp).delete(e);f.onsuccess=()=>t(l.result.modelArtifactsInfo),f.onerror=d=>n(l.error)};p.onsuccess=c,p.onerror=m=>(c(),s.close(),n(l.error))}},l.onerror=p=>(s.close(),n(l.error)),i.oncomplete=()=>{u==null?s.close():u.oncomplete=()=>s.close()}},o.onerror=s=>n(o.error)})}};var ji="/",Vm="tensorflowjs_models",ZF="info",$7="model_topology",P7="weight_specs",B7="weight_data",O7="model_metadata";function JF(r){return{info:[Vm,r,ZF].join(ji),topology:[Vm,r,$7].join(ji),weightSpecs:[Vm,r,P7].join(ji),weightData:[Vm,r,B7].join(ji),modelMetadata:[Vm,r,O7].join(ji)}}function z7(r){let e=r.split(ji);if(e.length<3)throw new Error(`Invalid key format: ${r}`);return e.slice(1,e.length-1).join(ji)}function G7(r){return r.startsWith(Hi.URL_SCHEME)?r.slice(Hi.URL_SCHEME.length):r}var Hi=class{constructor(e){if(!Ze().getBool("IS_BROWSER")||typeof window=="undefined"||typeof window.localStorage=="undefined")throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,e==null||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=JF(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{let t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),o=si(e);try{this.LS.setItem(this.keys.info,JSON.stringify(o)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,KF(e.weightData));let s={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};return e.signature!=null&&(s.signature=e.signature),e.userDefinedMetadata!=null&&(s.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(s.modelInitializer=e.modelInitializer),this.LS.setItem(this.keys.modelMetadata,JSON.stringify(s)),{modelArtifactsInfo:o}}catch(s){throw this.LS.removeItem(this.keys.info),this.LS.removeItem(this.keys.topology),this.LS.removeItem(this.keys.weightSpecs),this.LS.removeItem(this.keys.weightData),this.LS.removeItem(this.keys.modelMetadata),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${o.modelTopologyBytes}, weightSpecsBytes=${o.weightSpecsBytes}, weightDataBytes=${o.weightDataBytes}.`)}}}async load(){let e=JSON.parse(this.LS.getItem(this.keys.info));if(e==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(e.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");let t={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(n==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=n;let o=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(o==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=o;let s=this.LS.getItem(this.keys.modelMetadata);if(s!=null){let a=JSON.parse(s);t.format=a.format,t.generatedBy=a.generatedBy,t.convertedBy=a.convertedBy,a.signature!=null&&(t.signature=a.signature),a.userDefinedMetadata!=null&&(t.userDefinedMetadata=a.userDefinedMetadata),a.modelInitializer!=null&&(t.modelInitializer=a.modelInitializer)}let i=this.LS.getItem(this.keys.weightData);if(i==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=VF(i),t}};Hi.URL_SCHEME="localstorage://";var QF=r=>Ze().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(Hi.URL_SCHEME)?W7(r.slice(Hi.URL_SCHEME.length)):null;Ut.registerSaveRouter(QF);Ut.registerLoadRouter(QF);function W7(r){return new Hi(r)}var Yw=class{constructor(){P(Ze().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),P(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=Vm+ji,n=ji+ZF;for(let o=0;o<this.LS.length;++o){let s=this.LS.key(o);if(s.startsWith(t)&&s.endsWith(n)){let i=z7(s);e[i]=JSON.parse(this.LS.getItem(s))}}return e}async removeModel(e){e=G7(e);let t=JF(e);if(this.LS.getItem(t.info)==null)throw new Error(`Cannot find model at path '${e}'`);let n=JSON.parse(this.LS.getItem(t.info));return this.LS.removeItem(t.info),this.LS.removeItem(t.topology),this.LS.removeItem(t.weightSpecs),this.LS.removeItem(t.weightData),n}};var Um="://",Rn=class{constructor(){this.managers={}}static getInstance(){return Rn.instance==null&&(Rn.instance=new Rn),Rn.instance}static registerManager(e,t){P(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(Um)&&(e=e.slice(0,e.indexOf(Um))),P(e.length>0,()=>"scheme must not be an empty string.");let n=Rn.getInstance();P(n.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),n.managers[e]=t}static getManager(e){let 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 Ax(r){if(r.indexOf(Um)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Rn.getSchemes().join(",")}`);return{scheme:r.split(Um)[0],path:r.split(Um)[1]}}async function eR(r,e,t=!1){P(r!==e,()=>`Old path and new path are the same: '${r}'`);let n=Ut.getLoadHandlers(r);P(n.length>0,()=>`Copying failed because no load handler is found for source URL ${r}.`),P(n.length<2,()=>`Copying failed because more than one (${n.length}) load handlers for source URL ${r}.`);let o=n[0],s=Ut.getSaveHandlers(e);P(s.length>0,()=>`Copying failed because no save handler is found for destination URL ${e}.`),P(s.length<2,()=>`Copying failed because more than one (${n.length}) save handlers for destination URL ${e}.`);let i=s[0],a=Ax(r).scheme,l=Ax(r).path,u=a===Ax(r).scheme,p=await o.load();t&&u&&await Rn.getManager(a).removeModel(l);let c=await i.save(p);return t&&!u&&await Rn.getManager(a).removeModel(l),c.modelArtifactsInfo}async function tR(){let r=Rn.getSchemes(),e={};for(let t of r){let n=await Rn.getManager(t).listModels();for(let o in n){let s=t+Um+o;e[s]=n[o]}}return e}async function rR(r){let e=Ax(r);return Rn.getManager(e.scheme).removeModel(e.path)}async function nR(r,e){return eR(r,e,!1)}async function oR(r,e){return eR(r,e,!0)}var sR=class{fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return this.textEncoder==null&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}};if(Ze().get("IS_BROWSER")){Ze().setPlatform("browser",new sR);try{Rn.registerManager(Hi.URL_SCHEME,new Yw)}catch(r){}try{Rn.registerManager(Ui.URL_SCHEME,new Xw)}catch(r){}}var K7={importFetch:()=>Zw()},Jw;var aR=class{constructor(){this.util=Ap("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return Ze().global.fetch!=null?Ze().global.fetch(e,t):(Jw==null&&(Jw=K7.importFetch()),Jw(e,t))}now(){let e=process.hrtime();return e[0]*1e3+e[1]/1e6}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return e.length===0?"":new this.util.TextDecoder(t).decode(e)}};Ze().get("IS_NODE")&&Ze().setPlatform("node",new aR);function Ln(r,e="float32",t){return e=e||"float32",fh(r),new Pp(r,e,t)}function V7(r,e){let t=w(r,"x","cast");if(!bw(e))throw new Error(`Failed to cast to unknown dtype ${e}`);if(e==="string"&&t.dtype!=="string"||e!=="string"&&t.dtype==="string")throw new Error("Only strings can be casted to strings");let n={x:t},o={dtype:e};return L.runKernel(yx,n,o)}var ft=E({cast_:V7});function U7(r){let t={x:w(r,"x","clone","string_or_numeric")};return L.runKernel(xx,t)}var Os=E({clone_:U7});function Qw(r,e=!1){console.log(r.toString(e))}Ww();var j7={buffer:Ln,cast:ft,clone:Os,print:Qw};FF(j7);var gR={};Ge(gR,{browserFiles:()=>uR,browserHTTPRequest:()=>mR,concatenateArrayBuffers:()=>Km,copyModel:()=>nR,decodeWeights:()=>Nx,encodeWeights:()=>GF,fromMemory:()=>dR,getLoadHandlers:()=>qF,getModelArtifactsInfoForJSON:()=>si,getSaveHandlers:()=>HF,http:()=>Fx,isHTTPScheme:()=>Mx,listModels:()=>tR,loadWeights:()=>pR,moveModel:()=>oR,registerLoadRouter:()=>jF,registerSaveRouter:()=>UF,removeModel:()=>rR,weightsLoaderFactory:()=>r_,withSaveHandler:()=>hR});var H7="model",q7=".json",X7=".weights.bin";function iR(r){return new Promise(e=>setTimeout(e)).then(r)}var Dx=class{constructor(e){if(!Ze().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Dx.URL_SCHEME)&&(e=e.slice(Dx.URL_SCHEME.length)),(e==null||e.length===0)&&(e=H7),this.modelTopologyFileName=e+q7,this.weightDataFileName=e+X7}async save(e){if(typeof document=="undefined")throw new Error("Browser downloads are not supported in this environment since `document` is not present");let 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.");{let n=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],o={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:n};e.signature!=null&&(o.signature=e.signature),e.userDefinedMetadata!=null&&(o.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(o.modelInitializer=e.modelInitializer);let s=window.URL.createObjectURL(new Blob([JSON.stringify(o)],{type:"application/json"})),i=this.jsonAnchor==null?document.createElement("a"):this.jsonAnchor;if(i.download=this.modelTopologyFileName,i.href=s,await iR(()=>i.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){let a=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;a.download=this.weightDataFileName,a.href=t,await iR(()=>a.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:si(e)}}}},wh=Dx;wh.URL_SCHEME="downloads://";var lR=class{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(){let e=this.files[0],t=this.files.slice(1);return new Promise((n,o)=>{let s=new FileReader;s.onload=i=>{let a=JSON.parse(i.target.result),l=a.modelTopology;if(l==null){o(new Error(`modelTopology field is missing from file ${e.name}`));return}t.length===0&&n({modelTopology:l});let u=a.weightsManifest;if(u==null){o(new Error(`weightManifest field is missing from file ${e.name}`));return}let p;try{p=this.checkManifestAndWeightFiles(u,t)}catch(d){o(d);return}let c=[],m=[],f=[];u.forEach(d=>{d.paths.forEach(h=>{m.push(h),f.push(null)}),c.push(...d.weights)}),u.forEach(d=>{d.paths.forEach(h=>{let g=new FileReader;g.onload=b=>{let y=b.target.result,T=m.indexOf(h);if(f[T]=y,f.indexOf(null)===-1){let k={modelTopology:l,weightSpecs:c,weightData:Km(f),format:a.format,generatedBy:a.generatedBy,convertedBy:a.convertedBy};a.signature!=null&&(k.signature=a.signature),a.userDefinedMetadata!=null&&(k.userDefinedMetadata=a.userDefinedMetadata),a.modelInitializer!=null&&(k.modelInitializer=a.modelInitializer),n(k)}},g.onerror=b=>o(`Failed to weights data from file of path '${h}'.`),g.readAsArrayBuffer(p[h])})})},s.onerror=i=>o(`Failed to read model topology and weights manifest JSON from file '${e.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),s.readAsText(e)})}checkManifestAndWeightFiles(e,t){let n=[],o=t.map(i=>Uw(i.name)),s={};for(let i of e)i.paths.forEach(a=>{let l=Uw(a);if(n.indexOf(l)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${l}'`);if(n.push(l),o.indexOf(l)===-1)throw new Error(`Weight file with basename '${l}' is not provided.`);s[a]=t[o.indexOf(l)]});if(n.length!==t.length)throw new Error(`Mismatch in the number of files in weights manifest (${n.length}) and the number of weight files provided (${t.length}).`);return s}},Y7=r=>Ze().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(wh.URL_SCHEME)?Z7(r.slice(wh.URL_SCHEME.length)):null;Ut.registerSaveRouter(Y7);function Z7(r="model"){return new wh(r)}function uR(r){return new lR(r)}function e_(r,e,t,n){i(r),t=t==null?0:t,n=n==null?1:n,a(t,n);let o=0,s=l=>(l.then(u=>{let p=t+ ++o/r.length*(n-t);return e(p),u}),l);function i(l){P(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function a(l,u){P(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),P(u>=0&&u<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${u}`),P(u>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${u}`)}return Promise.all(r.map(s))}async function t_(r,e){e==null&&(e={});let t=e.fetchFunc==null?Ze().platform.fetch:e.fetchFunc,n=r.map(c=>t(c,e.requestInit,{isBinary:!0})),o=0,s=.5,a=(e.onProgress==null?await Promise.all(n):await e_(n,e.onProgress,o,s)).map(c=>c.arrayBuffer()),l=.5,u=1;return e.onProgress==null?await Promise.all(a):await e_(a,e.onProgress,l,u)}async function pR(r,e="",t,n){return r_(i=>t_(i,{requestInit:n}))(r,e,t)}function r_(r){return async(e,t="",n)=>{let o=e.map(()=>!1),s={},i=n!=null?n.map(()=>!1):[],a=[];if(e.forEach((f,d)=>{let h=0;f.weights.forEach(g=>{let b="quantization"in g?g.quantization.dtype:g.dtype,y=vh[b]*Ct(g.shape),T=()=>{o[d]=!0,s[d]==null&&(s[d]=[]),s[d].push({manifestEntry:g,groupOffset:h,sizeBytes:y})};n!=null?n.forEach((k,I)=>{k===g.name&&(T(),i[I]=!0)}):T(),a.push(g.name),h+=y})}),!i.every(f=>f)){let f=n.filter((d,h)=>!i[h]);throw new Error(`Could not find weights in manifest with names: ${f.join(", ")}.
|
|
Manifest JSON has weights with names: ${a.join(", ")}.`)}let l=o.reduce((f,d,h)=>(d&&f.push(h),f),[]),u=[];l.forEach(f=>{e[f].paths.forEach(d=>{let h=t+(t.endsWith("/")?"":"/")+d;u.push(h)})});let p=await r(u),c={},m=0;return l.forEach(f=>{let d=e[f].paths.length,h=0;for(let k=0;k<d;k++)h+=p[m+k].byteLength;let g=new ArrayBuffer(h),b=new Uint8Array(g),y=0;for(let k=0;k<d;k++){let I=new Uint8Array(p[m+k]);b.set(I,y),y+=I.byteLength}s[f].forEach(k=>{let I=g.slice(k.groupOffset,k.groupOffset+k.sizeBytes),S=Nx(I,[k.manifestEntry]);for(let N in S)c[N]=S[N]}),m+=d}),c}}var J7="application/octet-stream",Q7="application/json",Ex=class{constructor(e,t){this.DEFAULT_METHOD="POST";if(t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(P(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=Ze().platform.fetch,P(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&P(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.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],o={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:n};e.signature!=null&&(o.signature=e.signature),e.userDefinedMetadata!=null&&(o.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(o.modelInitializer=e.modelInitializer),t.body.append("model.json",new Blob([JSON.stringify(o)],{type:Q7}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:J7}),"model.weights.bin");let s=await this.fetch(this.path,t);if(s.ok)return{modelArtifactsInfo:si(e),responses:[s]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${s.status}.`)}async load(){let 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(d){let h=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?h+=" 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.":h+=" Please make sure the server is serving valid JSON for this request.",new Error(h)}let n=t.modelTopology,o=t.weightsManifest,s=t.generatedBy,i=t.convertedBy,a=t.format,l=t.signature,u=t.userDefinedMetadata;if(n==null&&o==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);let p,c;o!=null&&([p,c]=await this.loadWeights(o));let m={modelTopology:n,weightSpecs:p,weightData:c,generatedBy:s,convertedBy:i,format:a};l!=null&&(m.signature=l),u!=null&&(m.userDefinedMetadata=u);let f=t.modelInitializer;return f&&(m.modelInitializer=f),m}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,o]=eY(t),s=this.weightPathPrefix||n,i=[];for(let p of e)i.push(...p.weights);let a=[],l=[];for(let p of e)for(let c of p.paths)this.weightUrlConverter!=null?l.push(this.weightUrlConverter(c)):a.push(s+c+o);this.weightUrlConverter&&a.push(...await Promise.all(l));let u=await t_(a,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[i,Km(u)]}};Ex.URL_SCHEME_REGEX=/^https?:\/\//;function eY(r){let e=r.lastIndexOf("/"),t=r.lastIndexOf("?"),n=r.substring(0,e),o=t>e?r.substring(t):"";return[n+"/",o]}function Mx(r){return r.match(Ex.URL_SCHEME_REGEX)!=null}var cR=(r,e)=>{if(typeof fetch=="undefined"&&(e==null||e.fetchFunc==null))return null;{let t=!0;if(Array.isArray(r)?t=r.every(n=>Mx(n)):t=Mx(r),t)return Fx(r,e)}return null};Ut.registerSaveRouter(cR);Ut.registerLoadRouter(cR);function Fx(r,e){return new Ex(r,e)}function mR(r,e){return Fx(r,e)}var Rx=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},fR=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function dR(r,e,t,n){return arguments.length===1?r.modelTopology!=null||r.weightSpecs!=null?new Rx(r):(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 Rx({modelTopology:r})):(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 Rx({modelTopology:r,weightSpecs:e,weightData:t,trainingConfig:n}))}function hR(r){return new fR(r)}var yR={};Ge(yR,{confusionMatrix:()=>bR});function tY(r,e,t=!1,n=!1){let o=w(r,"a","matMul"),s=w(e,"b","matMul");[o,s]=Qe(o,s);let i={a:o,b:s},a={transposeA:t,transposeB:n};return L.runKernel(UE,i,a)}var gt=E({matMul_:tY});function rY(r,e,t=1,n=0){if(e<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${e}`);let s={indices:w(r,"indices","oneHot","int32")},i={depth:e,onValue:t,offValue:n};return L.runKernel(mM,s,i)}var Lx=E({oneHot_:rY});function nY(r,e){let t=w(r,"x","transpose");if(e==null&&(e=t.shape.map((s,i)=>i).reverse()),P(t.rank===e.length,()=>`Error in transpose: rank of input ${t.rank} must match length of perm ${e}.`),e.forEach(s=>{P(s>=0&&s<t.rank,()=>`All entries in 'perm' must be between 0 and ${t.rank-1} but got ${e}`)}),t.rank<=1)return t.clone();let n={x:t},o={perm:e};return L.runKernel(oF,n,o)}var _h=E({transpose_:nY});function oY(r,e,t){let n=w(r,"labels","confusionMatrix"),o=w(e,"predictions","confusionMatrix");P(t==null||t>0&&Number.isInteger(t),()=>`If provided, numClasses must be a positive integer, but got ${t}`),P(n.rank===1,()=>`Expected the rank of labels to be 1, but got ${n.rank}`),P(o.rank===1,()=>`Expected the rank of predictions to be 1, but got ${o.rank}`),P(n.shape[0]===o.shape[0],()=>`Mismatch in the number of examples: ${n.shape[0]} vs. ${o.shape[0]}. Labels and predictions should have the same number of elements.`),P(t>0&&Number.isInteger(t),()=>`numClasses is required to be a positive integer, but got ${t}`);let s=Lx(ft(n,"int32"),t),i=Lx(ft(o,"int32"),t),a=_h(s),l=gt(a,i);return ft(l,"int32")}var bR=E({confusionMatrix_:oY});var TR={};Ge(TR,{fromPixels:()=>cY,fromPixelsAsync:()=>uY,toPixels:()=>pY});function n_(r,e,t){if(No(r),e!=null&&e.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let n=ln(r,t);if(n.length!==3&&n.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(n.length===1&&e==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Fn(r,e,n,t)}var jm;function xR(r,e=3){if(e>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(r==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let t=!1,n=!1,o=!1,s=!1,i=!1,a=!1;if(r.data instanceof Uint8Array)t=!0;else if(typeof ImageData!="undefined"&&r instanceof ImageData)n=!0;else if(typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement)o=!0;else if(typeof HTMLImageElement!="undefined"&&r instanceof HTMLImageElement)s=!0;else if(r.getContext!=null)i=!0;else if(typeof ImageBitmap!="undefined"&&r instanceof ImageBitmap)a=!0;else throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${r.constructor.name}`);if(o){let d=2;if(o&&r.readyState<d)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.")}if(bh(Iw,L.backendName)!=null){let d={pixels:r},h={numChannels:e};return L.runKernel(Iw,d,h)}let[u,p]=o?[r.videoWidth,r.videoHeight]:[r.width,r.height],c;i?c=r.getContext("2d").getImageData(0,0,u,p).data:n||t?c=r.data:(s||o||a)&&(jm==null&&(jm=document.createElement("canvas").getContext("2d")),jm.canvas.width=u,jm.canvas.height=p,jm.drawImage(r,0,0,u,p),c=jm.getImageData(0,0,u,p).data);let m;if(e===4)m=new Int32Array(c);else{let d=u*p;m=new Int32Array(d*e);for(let h=0;h<d;h++)for(let g=0;g<e;++g)m[h*e+g]=c[h*4+g]}return n_(m,[p,u,e],"int32")}function sY(r){return r!=null&&r.data instanceof Uint8Array}function aY(){return typeof window!="undefined"&&typeof ImageBitmap!="undefined"&&window.hasOwnProperty("createImageBitmap")}function iY(r){return r!=null&&r.width!==0&&r.height!==0}function lY(r){return aY()&&!(r instanceof ImageBitmap)&&iY(r)&&!sY(r)}async function uY(r,e=3){let t=null;if(Ze().getBool("WRAP_TO_IMAGEBITMAP")&&lY(r)){let n;try{n=await createImageBitmap(r,{premultiplyAlpha:"none"})}catch(o){n=null}n!=null&&n.width===r.width&&n.height===r.height?t=n:t=r}else t=r;return xR(t,e)}async function pY(r,e){let t=w(r,"img","toPixels");if(!(r instanceof Yt)){let u=t;t=ft(u,"int32"),u.dispose()}if(t.rank!==2&&t.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${t.rank}.`);let[n,o]=t.shape.slice(0,2),s=t.rank===2?1:t.shape[2];if(s>4||s===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${s}`);if(t.dtype!=="float32"&&t.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${t.dtype}. Please use float32 or int32 tensors.`);let i=await t.data(),a=t.dtype==="float32"?255:1,l=new Uint8ClampedArray(o*n*4);for(let u=0;u<n*o;++u){let p=[0,0,0,255];for(let m=0;m<s;m++){let f=i[u*s+m];if(t.dtype==="float32"){if(f<0||f>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${f}.`)}else if(t.dtype==="int32"&&(f<0||f>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${f}.`);s===1?(p[0]=f*a,p[1]=f*a,p[2]=f*a):p[m]=f*a}let c=u*4;l[c+0]=Math.round(p[0]),l[c+1]=Math.round(p[1]),l[c+2]=Math.round(p[2]),l[c+3]=Math.round(p[3])}if(e!=null){e.width=o,e.height=n;let u=e.getContext("2d"),p=new ImageData(l,o,n);u.putImageData(p,0,0)}return t!==r&&t.dispose(),l}var cY=E({fromPixels_:xR});var IR={};Ge(IR,{prepareAndValidate:()=>kR});function kR(r,e){let t=r.shape.length,n=e.shape.length;if(t<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${t}.`);if(n<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${n}.`);if(e.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.shape[n-1]>t)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${e.shape[n-1]} vs. ${t}`);if(Ct(r.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${r.shape}.`);let o=e.shape,s=o[o.length-1],i=1;for(let c=0;c<o.length-1;++c)i*=o[c];let a=r.shape,l=o.slice();l.pop();let u=1;for(let c=s;c<t;++c)u*=a[c],l.push(a[c]);let p=[...ni(r.shape).map(c=>c/u),1].slice(0,s);return[l,i,u,p]}var wR={};Ge(wR,{calculateShapes:()=>vR,validateInput:()=>$x,validateUpdateShape:()=>o_});function o_(r,e,t){let n=e.rank>1?e.shape[e.rank-1]:1,o=e.rank>1?e.rank-1:1,s=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${t.shape}, indices.shape: ${e.shape}, shape: ${r}, sliceDim: ${n}, and batchDim: ${o}.`;if(t.rank<o)throw new Error(s+` update.rank < ${o}. `);if(r.length<n+(t.rank-o))throw new Error(s+` Output shape length < ${n+(t.rank-o)}`);if(t.rank!==o+r.length-n)throw new Error(s+` update.rank != ${o+r.length-n}`);for(let i=0;i<o;++i)if(t.shape[i]!==e.shape[i])throw new Error(s+` updates.shape[${i}] (${t.shape[i]}) != indices.shape[${i}] (${e.shape[i]}).`);for(let i=0;i<t.rank-o;++i)if(t.shape[i+o]!==r[i+n])throw new Error(s+` updates.shape[${i+o}] (${t.shape[i+o]}) != shape[${i+o}] (${r[i+o]})`)}function $x(r,e,t){if(e.rank<1)throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${e.rank}.`);if(r.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${r.rank}.`);if(e.dtype!=="int32")throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${e.dtype}`);if(t.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${t}`);if(t.length===0){if(e.size===0)throw new Error(`Indices specified for empty output. indices shape: ${e.shape}`);if(r.size===0)throw new Error(`Updates specified for empty output. updates shape: ${r.shape}`)}o_(t,e,r)}function vR(r,e,t){let n=e.shape.length,o=n>1?e.shape[n-1]:1,s=t.length,i=1;for(let c=o;c<s;++c)i*=t[c];let a=o<1?1:o,l=Ct(e.shape)/a,u=[...ni(t.slice(0,o)),1],p=Ct(t);return{sliceRank:o,numUpdates:l,sliceSize:i,strides:u,outputSize:p}}var Bx={};Ge(Bx,{assertParamsValid:()=>mY,computeFlatOffset:()=>dY,computeOutShape:()=>_R,getNormalizedAxes:()=>AR,isSliceContinous:()=>fY,maskToAxes:()=>Px,parseSliceParams:()=>hY,sliceInfo:()=>gY,startForAxis:()=>FR,startIndicesWithElidedDims:()=>DR,stopForAxis:()=>RR,stopIndicesWithElidedDims:()=>ER,stridesForAxis:()=>MR,stridesWithElidedDims:()=>CR});function mY(r,e,t){let n=r.shape.length;P(n===e.length,()=>`Error in slice${n}D: Length of begin ${e} must match the rank of the array (${n}).`),P(n===t.length,()=>`Error in slice${n}D: Length of size ${t} must match the rank of the array (${n}).`);for(let o=0;o<n;++o)P(e[o]+t[o]<=r.shape[o],()=>`Error in slice${n}D: begin[${o}] + size[${o}] (${e[o]+t[o]}) would overflow input.shape[${o}] (${r.shape[o]})`)}function Px(r){let e=[],t=0;for(;r>0;)r&1&&e.push(t),r/=2,t++;return e}function _R(r,e,t){let n=[];for(let o=0;o<r.length;o++)n[o]=Math.ceil((e[o]-r[o])/t[o]);return n}function CR(r,e,t,n){let o=[...r];for(let s=o.length;s<n.length;s++)o.push(1);for(let s=0;s<t;s++)s===0?o[e]=1:(o.splice(e,0,1),o.pop());return o}function SR(r,e,t){return t<=r?t:t-(e-1)}function NR(r,e){let t=[];for(let n=0;n<r;n++)t.push(e+n);return t}function AR(r,e,t,n,o,s,i,a,l){let u=r.length,p=new Array(u),c=new Array(u),m=new Array(u);if(e.length&&t>0){let f=e[0],d=t+1;p=DR(i,f,d,n,r),c=ER(a,f,d,o,r),m=CR(s,f,d,r)}else for(let f=0;f<u;f++)p[f]=FR(i,n,s,r,f,l),c[f]=RR(a,o,s,r,f,l),m[f]=MR(s,f,l);return{begin:p,end:c,strides:m}}function DR(r,e,t,n,o){let s=[...o],i=NR(t,e);for(let a=0;a<s.length;a++)if(i.indexOf(a)>-1)s[a]=0;else{let l=SR(e,t,a),u=n[l];r&1<<l&&(u=0),s[a]=u}return s}function ER(r,e,t,n,o){let s=[...o],i=NR(t,e);for(let a=0;a<s.length;a++)if(i.indexOf(a)>-1)s[a]=Number.MAX_SAFE_INTEGER;else{let l=SR(e,t,a),u=n[l];r&1<<l&&(u=Number.MAX_SAFE_INTEGER),s[a]=u}for(let a=0;a<s.length;a++){let l=o[a];s[a]<0&&(s[a]+=l),s[a]=Mm(0,s[a],o[a])}return s}function MR(r,e,t){let n=r[e];return(t&1<<e||n==null)&&(n=1),n}function FR(r,e,t,n,o,s){let i=e[o],a=t[o]||1;(r&1<<o||s&1<<o||i==null)&&(a>0?i=Number.MIN_SAFE_INTEGER:i=Number.MAX_SAFE_INTEGER);let l=n[o];return i<0&&(i+=l),i=Mm(0,i,l-1),i}function RR(r,e,t,n,o,s){let i=e[o],a=t[o]||1;(r&1<<o||s&1<<o||i==null)&&(a>0?i=Number.MAX_SAFE_INTEGER:i=Number.MIN_SAFE_INTEGER);let l=n[o];return i<0&&(i+=l),a>0?i=Mm(0,i,l):i=Mm(-1,i,l-1),i}function fY(r,e,t){let n=t.length;for(let o=0;o<t.length;o++)if(t[o]>1){n=o;break}for(let o=n+1;o<t.length;o++)if(e[o]>0||t[o]!==r[o])return!1;return!0}function dY(r,e){let t=r.length>0?r[r.length-1]:1;for(let n=0;n<r.length-1;n++)t+=r[n]*e[n];return t}function hY(r,e,t){let n,o=r.shape.length;typeof e=="number"?n=[e,...new Array(o-1).fill(0)]:e.length<o?n=e.concat(new Array(o-e.length).fill(0)):n=e.slice(),n.forEach(i=>{P(i!==-1,()=>"slice() does not support negative begin indexing.")});let s;return t==null?s=new Array(o).fill(-1):typeof t=="number"?s=[t,...new Array(o-1).fill(-1)]:t.length<o?s=t.concat(new Array(o-t.length).fill(-1)):s=t,s=s.map((i,a)=>i>=0?i:(P(i===-1,()=>`Negative size values should be exactly -1 but got ${i} for the slice() size at index ${a}.`),r.shape[a]-n[a])),[n,s]}function gY(r,e,t,n,o,s,i,a,l){let u=e.slice(),p=t.slice(),c=n;n==null&&(c=new Array(u.length));let m=Px(i);if(m.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(i!==0&&a!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(i!==0&&l!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");let f=r.length-u.length,d=Px(a),h=r.slice();d.forEach(N=>{u[N]=0,p[N]=1,h.splice(N,0,1)});let{begin:g,end:b,strides:y}=AR(h,m,f,u,p,c,o,s,i);u=g,p=b,c=y;let T=Px(l);T.forEach(N=>{p[N]=u[N]+1,c[N]=1});let k=_R(u,p,c),I=k.filter((N,F)=>T.indexOf(F)===-1);return{nonStrided:c.every(N=>N===1),$begin:u,$end:p,$strides:c,size:k,newShape:h,outShape:I}}var LR={};Ge(LR,{Serializable:()=>Ox,SerializationMap:()=>qi,registerClass:()=>to});var Ox=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},qi=class{constructor(){this.classNameMap={}}static getMap(){return qi.instance==null&&(qi.instance=new qi),qi.instance}static register(e){qi.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function to(r){P(r.className!=null,()=>"Class being registered does not have the static className property defined."),P(typeof r.className=="string",()=>"className is required to be a string, but got type "+typeof r.className),P(r.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),qi.register(r)}var OR={};Ge(OR,{TEST_EPSILON_FLOAT16:()=>$R,encodeStrings:()=>BR,expectArrayBuffersEqual:()=>IY,expectArraysClose:()=>yY,expectArraysEqual:()=>TY,expectNumbersClose:()=>PR,expectPromiseToFail:()=>xY,expectValuesInRange:()=>kY,testEpsilon:()=>zx});var bY=.001,$R=.1;function yY(r,e,t){return t==null&&(t=zx()),s_(r,e,(n,o)=>a_(n,o,t))}function zx(){return L.backend.floatPrecision()===32?bY:$R}function s_(r,e,t){let n=!0;if((zr(r)||zr(e))&&(n=!1),zr(r)&&zr(e)&&(n=!0),n){let i=r.constructor.name,a=e.constructor.name;if(i!==a)throw new Error(`Arrays are of different type. Actual: ${i}. Expected: ${a}`)}if(Array.isArray(r)&&Array.isArray(e)){let i=ln(r),a=ln(e);if(!En(i,a))throw new Error(`Arrays have different shapes. Actual: [${i}]. Expected: [${a}]`)}let o=zr(r)?r:Ls(r),s=zr(e)?e:Ls(e);if(o.length!==s.length)throw new Error(`Arrays have different lengths actual: ${o.length} vs expected: ${s.length}.
|
|
Actual: ${o}.
|
|
Expected: ${s}.`);for(let i=0;i<s.length;++i){let a=o[i],l=s[i];if(!t(a,l))throw new Error(`Arrays differ: actual[${i}] = ${a}, expected[${i}] = ${l}.
|
|
Actual: ${o}.
|
|
Expected: ${s}.`)}}function xY(r,e){r().then(()=>e.fail(),()=>e())}function TY(r,e){let t=typeof e=="string"||typeof e=="number"||typeof e=="boolean"?[e]:e;return $s(r)||$s(r[0])||$s(e)||$s(e[0])?s_(r,t,(n,o)=>n==o):s_(r,e,(n,o)=>a_(n,o,0))}function PR(r,e,t){if(t==null&&(t=zx()),!a_(r,e,t))throw new Error(`Numbers differ: actual === ${r}, expected === ${e}`)}function a_(r,e,t){return!isFinite(r)&&!isFinite(e)?!0:!(isNaN(r)||isNaN(e)||Math.abs(r-e)>t)}function kY(r,e,t){for(let n=0;n<r.length;n++)if(r[n]<e||r[n]>t)throw new Error(`Value out of range:${r[n]} low: ${e}, high: ${t}`)}function IY(r,e){expect(new Float32Array(r)).toEqual(new Float32Array(e))}function BR(r){for(let e=0;e<r.length;e++){let t=r[e];Array.isArray(t)?BR(t):r[e]=_u(t)}return r}var vY="3.7.0";function xAe(){Ze().set("PROD",!0)}function TAe(){Ze().set("DEBUG",!0)}function kAe(){Ze().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function wY(r){Ze().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(r+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}RF(wY);function IAe(){L.disposeVariables()}function vAe(){return L}function wAe(){return L.memory()}function _Ae(r){return L.profile(r)}function mr(r,e){return L.tidy(r,e)}function $r(r){Ih(r).forEach(t=>t.dispose())}function zR(r){return L.keep(r)}function CAe(r){return L.time(r)}function SAe(r){return L.setBackend(r)}function NAe(){return L.ready()}function AAe(){return L.backendName}function DAe(r){L.removeBackend(r)}function EAe(r){return L.findBackend(r)}function MAe(r){return L.findBackendFactory(r)}function FAe(r,e,t=1){return L.registerBackend(r,e,t)}function RAe(){return L.backend}function LAe(r,e){Ze().setPlatform(r,e)}function _Y(r,e){let t=w(r,"a","add"),n=w(e,"b","add");[t,n]=Qe(t,n);let o={a:t,b:n};return L.runKernel(bx,o)}var Re=E({add_:_Y});function CY(r,e){let t=w(r,"a","floorDiv"),n=w(e,"b","floorDiv");[t,n]=Qe(t,n);let o={a:t,b:n};return L.runKernel(S2,o)}var i_=E({floorDiv_:CY});function SY(r,e){let t=w(r,"a","div"),n=w(e,"b","div");if([t,n]=Qe(t,n),t.dtype==="int32"&&n.dtype==="int32")return i_(t,n);let o={a:t,b:n},s={};return L.runKernel(h2,o,s)}var ct=E({div_:SY});function NY(r,e){let t=w(r,"a","mul"),n=w(e,"b","mul");[t,n]=Qe(t,n);let o={a:t,b:n};return L.runKernel(sM,o)}var fe=E({mul_:NY});function AY(r){let e=w(r,"x","abs");if(e.dtype==="complex64"){let t={x:e};return L.runKernel(ZE,t)}else{let t={x:e};return L.runKernel(DE,t)}}var un=E({abs_:AY});function DY(r){let t={x:w(r,"x","acos")};return L.runKernel(EE,t)}var EY=E({acos_:DY});function MY(r){let t={x:w(r,"x","acosh")};return L.runKernel(ME,t)}var FY=E({acosh_:MY});function RY(r){P(Array.isArray(r),()=>"The argument passed to tf.addN() must be a list of tensors"),P(r.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${r.length}`);let e=r.map((o,s)=>w(o,`tensors${s}`,"addN")),t=e[0];e.forEach(o=>{if(o.dtype!==t.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),e.forEach(o=>{if(!En(o.shape,t.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let n=e;return L.runKernel(FE,n)}var LY=E({addN_:RY});function $Y(r,e=null,t=!1){let o={x:w(r,"x","all","bool")},s={axis:e,keepDims:t};return L.runKernel(RE,o,s)}var PY=E({all_:$Y});function BY(r,e=null,t=!1){let o={x:w(r,"x","any","bool")},s={axis:e,keepDims:t};return L.runKernel(LE,o,s)}var OY=E({any_:BY});function zY(r,e=0){let n={x:w(r,"x","argMax")},o={axis:e};return L.runKernel($E,n,o)}var GY=E({argMax_:zY});function WY(r,e=0){let n={x:w(r,"x","argMin")},o={axis:e};return L.runKernel(PE,n,o)}var KY=E({argMin_:WY});function VY(r){let t={x:w(r,"x","asin")};return L.runKernel(BE,t)}var UY=E({asin_:VY});function jY(r){let t={x:w(r,"x","asinh")};return L.runKernel(OE,t)}var HY=E({asinh_:jY});function qY(r){let t={x:w(r,"x","atan")};return L.runKernel(zE,t)}var XY=E({atan_:qY});function YY(r,e){let t=w(r,"a","atan2"),n=w(e,"b","atan2");[t,n]=Qe(t,n);let o={a:t,b:n};return L.runKernel(WE,o)}var ZY=E({atan2_:YY});function JY(r){let t={x:w(r,"x","atanh")};return L.runKernel(GE,t)}var QY=E({atanh_:JY});function e9(r,e,t,n,o="NHWC",s){let i=r[3],a=[...e,i],l=WR(o);return Op(r,a,t,s,n,null,null,l)}function l_(r,e,t,n,o,s,i="channelsLast"){let[a,l]=Gx(e),u;if(i==="channelsLast")u=[a,l,r[3],r[3]];else if(i==="channelsFirst")u=[a,l,r[1],r[1]];else throw new Error(`Unknown dataFormat ${i}`);return Op(r,u,t,n,o,s,!1,i)}function t9(r,e,t,n,o,s,i="NDHWC"){let[a,l,u]=p_(e),p,c;if(i==="NDHWC")c="channelsLast",p=[a,l,u,r[4],r[4]];else if(i==="NCDHW")c="channelsFirst",p=[a,l,u,r[1],r[1]];else throw new Error(`Unknown dataFormat ${i}`);return GR(r,p,t,n,o,!1,c,s)}function Op(r,e,t,n,o,s,i=!1,a="channelsLast"){let[l,u,p,c]=[-1,-1,-1,-1];if(a==="channelsLast")[l,u,p,c]=r;else if(a==="channelsFirst")[l,c,u,p]=r;else throw new Error(`Unknown dataFormat ${a}`);let[m,f,,d]=e,[h,g]=Gx(t),[b,y]=Gx(n),T=Hm(m,b),k=Hm(f,y),{padInfo:I,outHeight:S,outWidth:N}=o9(o,u,p,h,g,T,k,s,a),F=i?d*c:d,$;return a==="channelsFirst"?$=[l,F,S,N]:a==="channelsLast"&&($=[l,S,N,F]),{batchSize:l,dataFormat:a,inHeight:u,inWidth:p,inChannels:c,outHeight:S,outWidth:N,outChannels:F,padInfo:I,strideHeight:h,strideWidth:g,filterHeight:m,filterWidth:f,effectiveFilterHeight:T,effectiveFilterWidth:k,dilationHeight:b,dilationWidth:y,inShape:r,outShape:$,filterShape:e}}function GR(r,e,t,n,o,s=!1,i="channelsLast",a){let[l,u,p,c,m]=[-1,-1,-1,-1,-1];if(i==="channelsLast")[l,u,p,c,m]=r;else if(i==="channelsFirst")[l,m,u,p,c]=r;else throw new Error(`Unknown dataFormat ${i}`);let[f,d,h,,g]=e,[b,y,T]=p_(t),[k,I,S]=p_(n),N=Hm(f,k),F=Hm(d,I),$=Hm(h,S),{padInfo:O,outDepth:V,outHeight:q,outWidth:W}=s9(o,u,p,c,b,y,T,N,F,$,a),Y=s?g*m:g,Z;return i==="channelsFirst"?Z=[l,Y,V,q,W]:i==="channelsLast"&&(Z=[l,V,q,W,Y]),{batchSize:l,dataFormat:i,inDepth:u,inHeight:p,inWidth:c,inChannels:m,outDepth:V,outHeight:q,outWidth:W,outChannels:Y,padInfo:O,strideDepth:b,strideHeight:y,strideWidth:T,filterDepth:f,filterHeight:d,filterWidth:h,effectiveFilterDepth:N,effectiveFilterHeight:F,effectiveFilterWidth:$,dilationDepth:k,dilationHeight:I,dilationWidth:S,inShape:r,outShape:Z,filterShape:e}}function r9(r,e,t,n,o){n==null&&(n=u_(r,e,t));let s=r[0],i=r[1],a=zp((s-e+2*n)/t+1,o),l=zp((i-e+2*n)/t+1,o);return[a,l]}function n9(r,e,t,n,o,s){o==null&&(o=u_(r,e,n));let i=r[0],a=r[1],l=r[2],u=zp((i-e+2*o)/n+1,s),p=zp((a-e+2*o)/n+1,s),c=zp((l-e+2*o)/n+1,s);return[u,p,c,t]}function u_(r,e,t,n=1){let o=Hm(e,n);return Math.floor((r[0]*(t-1)-t+o)/2)}function Gx(r){return typeof r=="number"?[r,r,r]:r.length===2?[r[0],r[1],1]:r}function p_(r){return typeof r=="number"?[r,r,r]:r}function Hm(r,e){return e<=1?r:r+(r-1)*(e-1)}function o9(r,e,t,n,o,s,i,a,l){let u,p,c;if(typeof r=="number"){u={top:r,bottom:r,left:r,right:r,type:r===0?"VALID":"NUMBER"};let f=r9([e,t],s,n,r,a);p=f[0],c=f[1]}else if(r==="same"){p=Math.ceil(e/n),c=Math.ceil(t/o);let m=Math.max(0,(p-1)*n+s-e),f=Math.max(0,(c-1)*o+i-t),d=Math.floor(m/2),h=m-d,g=Math.floor(f/2),b=f-g;u={top:d,bottom:h,left:g,right:b,type:"SAME"}}else if(r==="valid")u={top:0,bottom:0,left:0,right:0,type:"VALID"},p=Math.ceil((e-s+1)/n),c=Math.ceil((t-i+1)/o);else if(typeof r=="object"){let m=l==="channelsLast"?r[1][0]:r[2][0],f=l==="channelsLast"?r[1][1]:r[2][1],d=l==="channelsLast"?r[2][0]:r[3][0],h=l==="channelsLast"?r[2][1]:r[3][1];u={top:m,bottom:f,left:d,right:h,type:m===0&&f===0&&d===0&&h===0?"VALID":"EXPLICIT"},p=zp((e-s+m+f)/n+1,a),c=zp((t-i+d+h)/o+1,a)}else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:u,outHeight:p,outWidth:c}}function s9(r,e,t,n,o,s,i,a,l,u,p){let c,m,f,d;if(typeof r=="number"){c={top:r,bottom:r,left:r,right:r,front:r,back:r,type:r===0?"VALID":"NUMBER"};let g=n9([e,t,n,1],a,1,o,r,p);m=g[0],f=g[1],d=g[2]}else if(r==="same"){m=Math.ceil(e/o),f=Math.ceil(t/s),d=Math.ceil(n/i);let h=(m-1)*o+a-e,g=(f-1)*s+l-t,b=(d-1)*i+u-n,y=Math.floor(h/2),T=h-y,k=Math.floor(g/2),I=g-k,S=Math.floor(b/2),N=b-S;c={top:k,bottom:I,left:S,right:N,front:y,back:T,type:"SAME"}}else if(r==="valid")c={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},m=Math.ceil((e-a+1)/o),f=Math.ceil((t-l+1)/s),d=Math.ceil((n-u+1)/i);else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:c,outDepth:m,outHeight:f,outWidth:d}}function zp(r,e){if(!e)return Math.trunc(r);switch(e){case"round":return Math.round(r);case"ceil":return Math.ceil(r);case"floor":return Math.floor(r);default:throw new Error(`Unknown roundingMode ${e}`)}}function Gp(r){let[e,t,n]=Gx(r);return e===1&&t===1&&n===1}function Tn(r,e){return Gp(r)||Gp(e)}function WR(r){if(r==="NHWC")return"channelsLast";if(r==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${r}`)}function a9(r,e){let n={x:w(r,"x","reshape","string_or_numeric")},o={shape:e};return L.runKernel(IM,n,o)}var te=E({reshape_:a9});function i9(r,e,t,n,o){let s=w(r,"x","avgPool","float32"),i=1;P(Tn(t,i),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${t} and dilations '${i}'`);let a=s,l=!1;s.rank===3&&(l=!0,a=te(s,[1,s.shape[0],s.shape[1],s.shape[2]])),P(a.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${a.rank}.`),o!=null&&P(Qt(n),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`);let u={x:a},p={filterSize:e,strides:t,pad:n,dimRoundingMode:o},c=L.runKernel(KE,u,p);return c=ft(c,s.dtype),l?te(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var c_=E({avgPool_:i9});function l9(r,e,t,n,o,s="NDHWC"){let i=w(r,"x","avgPool3d","float32"),a=i,l=!1;i.rank===4&&(l=!0,a=te(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),P(a.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${a.rank}.`),P(s==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),o!=null&&P(Qt(n),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`);let u={x:a},p={filterSize:e,strides:t,pad:n,dimRoundingMode:o,dataFormat:s},c=L.runKernel(VE,u,p);return c=ft(c,a.dtype),l?te(c,[c.shape[1],c.shape[2],c.shape[3],c.shape[4]]):c}var u9=E({avgPool3d_:l9});function p9(r,e=0){P(r.length>=1,()=>"Pass at least one tensor to concat");let t=Ki(r,"tensors","concat","string_or_numeric");if(t[0].dtype==="complex64"&&t.forEach(s=>{if(s.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
|
|
with dtype ${s.dtype}. `)}),t.length===1)return Os(t[0]);let n=t,o={axis:e};return L.runKernel(JE,n,o)}var Dr=E({concat_:p9});function c9(r){let t={x:w(r,"x","sigmoid")};return L.runKernel($M,t)}var Xi=E({sigmoid_:c9});function m9(r,e,t){let n=w(r,"x","slice","string_or_numeric");if(n.rank===0)throw new Error("Slicing scalar is not possible");let o={x:n},s={begin:e,size:t};return L.runKernel(MM,o,s)}var kt=E({slice_:m9});function f9(r){let t={x:w(r,"x","tanh")};return L.runKernel(tF,t)}var Wx=E({tanh_:f9});function d9(r,e,t,n,o,s){let i=w(r,"forgetBias","basicLSTMCell"),a=w(e,"lstmKernel","basicLSTMCell"),l=w(t,"lstmBias","basicLSTMCell"),u=w(n,"data","basicLSTMCell"),p=w(o,"c","basicLSTMCell"),c=w(s,"h","basicLSTMCell"),m=Dr([u,c],1),f=gt(m,a),d=Re(f,l),h=d.shape[0],g=d.shape[1]/4,b=[h,g],y=kt(d,[0,0],b),T=kt(d,[0,g],b),k=kt(d,[0,g*2],b),I=kt(d,[0,g*3],b),S=Re(fe(Xi(y),Wx(T)),fe(p,Xi(Re(i,k)))),N=fe(Wx(S),Xi(I));return[S,N]}var h9=E({basicLSTMCell_:d9});function g9(r,e,t){let n=w(r,"x","batchToSpaceND"),o=e.reduce((a,l)=>a*l);P(n.rank>=1+e.length,()=>`input rank is ${n.rank} but should be > than blockShape.length ${e.length}`),P(t.length===e.length,()=>`crops.length is ${t.length} but should be equal to blockShape.length ${e.length}`),P(n.shape[0]%o==0,()=>`input tensor batch is ${n.shape[0]} but is not divisible by the product of the elements of blockShape ${e.join(" * ")} === ${o}`);let s={x:n},i={blockShape:e,crops:t};return L.runKernel(jE,s,i)}var m_=E({batchToSpaceND_:g9});function KR(r){let e;return r.rank===0||r.rank===1?e=te(r,[1,1,1,r.size]):r.rank===2?e=te(r,[1,1,r.shape[0],r.shape[1]]):r.rank===3?e=te(r,[1,r.shape[0],r.shape[1],r.shape[2]]):e=r,e}function b9(r,e,t,n,o,s){s==null&&(s=.001);let i=w(r,"x","batchNorm"),a=w(e,"mean","batchNorm"),l=w(t,"variance","batchNorm"),u;o!=null&&(u=w(o,"scale","batchNorm"));let p;n!=null&&(p=w(n,"offset","batchNorm")),P(a.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),P(p==null||a.rank===p.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),P(u==null||a.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let m={x:KR(i),scale:u,offset:p,mean:a,variance:l},f={varianceEpsilon:s},d=L.runKernel(N2,m,f);return te(d,i.shape)}var Wp=E({batchNorm_:b9});function y9(r,e,t,n,o,s){let i=w(r,"x","batchNorm"),a=w(e,"mean","batchNorm"),l=w(t,"variance","batchNorm"),u;o!=null&&(u=w(o,"scale","batchNorm"));let p;return n!=null&&(p=w(n,"offset","batchNorm")),P(i.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`),P(a.rank===2||a.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${a.rank}.`),P(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&P(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),p!=null&&P(p.rank===2||p.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${p.rank}.`),Wp(i,a,l,p,u,s)}var x9=E({batchNorm2d_:y9});function T9(r,e,t,n,o,s){let i=w(r,"x","batchNorm"),a=w(e,"mean","batchNorm"),l=w(t,"variance","batchNorm"),u;o!=null&&(u=w(o,"scale","batchNorm"));let p;return n!=null&&(p=w(n,"offset","batchNorm")),P(i.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`),P(a.rank===3||a.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${a.rank}.`),P(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&P(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),p!=null&&P(p.rank===3||p.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${p.rank}.`),Wp(i,a,l,p,u,s)}var k9=E({batchNorm3d_:T9});function I9(r,e,t,n,o,s){let i=w(r,"x","batchNorm"),a=w(e,"mean","batchNorm"),l=w(t,"variance","batchNorm"),u;o!=null&&(u=w(o,"scale","batchNorm"));let p;return n!=null&&(p=w(n,"offset","batchNorm")),P(i.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`),P(a.rank===4||a.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${a.rank}.`),P(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),u!=null&&P(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`),p!=null&&P(p.rank===4||p.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${p.rank}.`),Wp(i,a,l,p,u,s)}var v9=E({batchNorm4d_:I9});function w9(r,e,t){let n=w(r,"x","bincount"),o=w(e,"weights","bincount");P(n.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${n.dtype}`),P(t>=0,()=>`size must be non-negative, but got ${t}.`),P(o.size===n.size||o.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${n.shape}, weights shape: ${o.shape}.`);let s={x:n,weights:o},i={size:t};return L.runKernel(HE,s,i)}var f_=E({bincount_:w9});function _9(r,e){let t=w(r,"broadcastTo","x"),n=t.shape;if(e.some(u=>!(u>0)||u%1!=0))throw new Error(`broadcastTo(): Invalid broadcast shape [${e}].`);if(e.length<t.rank)throw new Error(`broadcastTo(): shape.length=${e.length} < input.rank=${t.rank}.`);if(e.length>t.rank){let u=t.shape.slice();for(;u.length<e.length;)u.unshift(1);t=te(t,u)}let o=t.shape,s=Array.from(e);for(let u=e.length-1;u>=0;u--)if(o[u]===e[u])s[u]=1;else if(t.shape[u]!==1)throw new Error(`broadcastTo(): [${n}] cannot be broadcast to [${e}].`);if(s.map((u,p)=>u>1?p:-1).filter(u=>u>=0).length===0)return Os(t);let a={x:t},l={reps:s};return L.runKernel(Tx,a,l)}var Ch=E({broadcastTo_:_9});function C9(r){let t={x:w(r,"x","ceil")};return L.runKernel(qE,t)}var S9=E({ceil_:C9});function N9(r,e,t){let n=w(r,"x","clipByValue");P(e<=t,()=>`Error in clip: min (${e}) must be less than or equal to max (${t}).`);let o={x:n},s={clipValueMin:e,clipValueMax:t};return L.runKernel(XE,o,s)}var A9=E({clipByValue_:N9});function D9(r){return Dr(r,0)}var E9=E({concat1d_:D9});function M9(r,e){return Dr(r,e)}var F9=E({concat2d_:M9});function R9(r,e){return Dr(r,e)}var L9=E({concat3d_:R9});function $9(r,e){return Dr(r,e)}var P9=E({concat4d_:$9});function B9(r,e,t,n,o="NHWC",s=[1,1],i){let a=w(r,"x","conv2d"),l=w(e,"filter","conv2d"),u=a,p=!1;a.rank===3&&(p=!0,u=te(a,[1,a.shape[0],a.shape[1],a.shape[2]])),P(u.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`),P(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),i!=null&&P(Qt(n),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${n}.`);let c=o==="NHWC"?u.shape[3]:u.shape[1];P(c===l.shape[2],()=>`Error in conv2d: depth of input (${c}) must match input depth for filter ${l.shape[2]}.`),P(Tn(t,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`);let m={x:u,filter:l},f={strides:t,pad:n,dataFormat:o,dilations:s,dimRoundingMode:i},d=L.runKernel(QE,m,f);return p?te(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Kp=E({conv2d_:B9});function O9(r,e,t,n,o="NWC",s=1,i){let a=w(r,"x","conv1d"),l=w(e,"filter","conv1d"),u=a,p=!1;a.rank===2&&(p=!0,u=te(a,[1,a.shape[0],a.shape[1]])),P(u.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`),P(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),i!=null&&P(Qt(n),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${n}.`),P(u.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`),P(Tn(t,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${t} and dilation '${s}'`),P(o==="NWC",()=>`Error in conv1d: got dataFormat of ${o} but only NWC is currently supported.`);let c=te(l,[1,l.shape[0],l.shape[1],l.shape[2]]),m=te(u,[u.shape[0],1,u.shape[1],u.shape[2]]),g=Kp(m,c,[1,t],n,"NHWC",[1,s],i);return p?te(g,[g.shape[2],g.shape[3]]):te(g,[g.shape[0],g.shape[2],g.shape[3]])}var z9=E({conv1d_:O9});function G9(r,e,t,n,o,s="NHWC",i){P(r.length===e.rank,()=>`Length of inShape (${r.length}) and rank of dy (${e.rank}) must match`);let a=r,l=e,u=!1;e.rank===3&&(u=!0,l=te(e,[1,e.shape[0],e.shape[1],e.shape[2]]),a=[1,r[0],r[1],r[2]]),P(a.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${a.length}.`),P(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),P(t.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${t.rank}`);let p=s==="NHWC"?a[3]:a[1],c=s==="NHWC"?l.shape[3]:l.shape[1];P(p===t.shape[2],()=>`Error in conv2dDerInput: depth of input (${p}) must match input depth for filter ${t.shape[2]}.`),P(c===t.shape[3],()=>`Error in conv2dDerInput: depth of output (${c}) must match output depth for filter ${t.shape[3]}.`),i!=null&&P(Qt(o),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${i} but got pad ${o}.`);let m={dy:l,filter:t},f={strides:n,pad:o,dataFormat:s,dimRoundingMode:i,inputShape:a},d=L.runKernel(t2,m,f);return u?te(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Kx=E({conv2DBackpropInput_:G9});function W9(r,e,t,n,o,s){let i=w(r,"x","conv2dTranspose"),a=w(e,"filter","conv2dTranspose");return Kx(t,i,a,n,o,"NHWC",s)}var K9=E({conv2dTranspose_:W9});function V9(r,e,t,n,o="NDHWC",s=[1,1,1]){let i=w(r,"x","conv3d"),a=w(e,"filter","conv3d"),l=i,u=!1;i.rank===4&&(u=!0,l=te(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),P(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),P(a.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${a.rank}.`),P(l.shape[4]===a.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${a.shape[3]}.`),P(Tn(t,s),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`),P(o==="NDHWC",()=>`Error in conv3d: got dataFormat of ${o} but only NDHWC is currently supported.`);let p={x:l,filter:a},c={strides:t,pad:n,dataFormat:o,dilations:s},m=L.runKernel(r2,p,c);return u?te(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}var U9=E({conv3d_:V9});function j9(r,e,t,n,o){P(r.length===e.rank,()=>`Length of inShape (${r.length}) and rank of dy (${e.rank}) must match`);let s=r,i=e,a=!1;e.rank===4&&(a=!0,i=te(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]),s=[1,r[0],r[1],r[2],r[3]]);let l=s[4],u=i.shape[4];P(s.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`),P(i.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`),P(t.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${t.rank}`),P(l===t.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${t.shape[3]}.`),P(u===t.shape[4],()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${t.shape[4]}.`);let p={dy:i,filter:t},c={pad:o,strides:n,inputShape:s},m=L.runKernel(n2,p,c);return a?te(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}var VR=E({conv3DBackpropInput_:j9});function H9(r,e,t,n,o){let s=w(r,"x","conv3dTranspose"),i=w(e,"filter","conv3dTranspose");return VR(t,s,i,n,o)}var q9=E({conv3dTranspose_:H9});function X9(r){let t={x:w(r,"x","cos")};return L.runKernel(o2,t)}var Y9=E({cos_:X9});function Z9(r){let t={x:w(r,"x","cosh")};return L.runKernel(s2,t)}var J9=E({cosh_:Z9});function Q9(r,e=0,t=!1,n=!1){let s={x:w(r,"x","cumsum")},i={axis:e,exclusive:t,reverse:n};return L.runKernel(a2,s,i)}var eZ=E({cumsum_:Q9});function tZ(r,e,t,n=!1){let o=w(r,"x","denseBincount"),s=w(e,"weights","denseBincount");P(o.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${o.dtype}`),P(o.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${o.rank}.`),P(t>=0,()=>`size must be non-negative, but got ${t}.`),P(s.size===o.size||s.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${o.shape}, weights shape: ${s.shape}.`);let i={x:o,weights:s},a={size:t,binaryOutput:n};return L.runKernel(l2,i,a)}var rZ=E({denseBincount_:tZ});function nZ(r,e,t="NHWC"){let n=w(r,"x","depthToSpace"),o=t==="NHWC"?n.shape[1]:n.shape[2],s=t==="NHWC"?n.shape[2]:n.shape[3],i=t==="NHWC"?n.shape[3]:n.shape[1];P(o*e>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${o} and ${e} for depthToSpace with input shape
|
|
${n.shape}`),P(s*e>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${s} and ${e} for depthToSpace with input shape
|
|
${n.shape}`),P(i%(e*e)==0,()=>`Dimension size must be evenly divisible by ${e*e} but is ${i} for depthToSpace with input shape ${n.shape}`);let a={x:n},l={blockSize:e,dataFormat:t};return L.runKernel(u2,a,l)}var oZ=E({depthToSpace_:nZ});function sZ(r,e,t,n,o="NHWC",s=[1,1],i){let a=w(r,"x","depthwiseConv2d"),l=w(e,"filter","depthwiseConv2d"),u=a,p=!1;a.rank===3&&(p=!0,u=te(a,[1,a.shape[0],a.shape[1],a.shape[2]])),P(u.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),P(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),P(u.shape[3]===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${u.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),i!=null&&P(Qt(n),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${n}.`);let c={x:u,filter:l},m={strides:t,pad:n,dataFormat:o,dilations:s,dimRoundingMode:i},f=L.runKernel(p2,c,m);return p?te(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Sh=E({depthwiseConv2d_:sZ});function aZ(r){let t={x:w(r,"x","diag")};return L.runKernel(f2,t)}var iZ=E({diag_:aZ});function lZ(r,e,t,n,o=[1,1],s="NHWC"){let i=w(r,"x","dilation2d"),a=w(e,"filter","dilation2d");P(i.rank===3||i.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`),P(a.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${a.rank}.`),P(s==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);let l=i,u=!1;i.rank===3&&(l=te(i,[1,i.shape[0],i.shape[1],i.shape[2]]),u=!0);let p={x:l,filter:a},c={strides:t,pad:n,dilations:o},m=L.runKernel(d2,p,c);return u?te(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var uZ=E({dilation2d_:lZ});function pZ(r,e){let t=r.length,n=[];for(let o=0;o<t;o++){let s=t-1-o,i=r[s]||1;(e[e.length-1-o]||1)>1&&i===1&&n.unshift(s)}return n}function d_(r,e){let t=[];for(let n=0;n<e.length;n++){let o=r[r.length-n-1],s=e.length-n-1,i=e[s];(o==null||o===1&&i>1)&&t.unshift(s)}return t}function St(r,e){let t=[],n=Math.max(r.length,e.length);for(let o=0;o<n;o++){let s=r[r.length-o-1];s==null&&(s=1);let i=e[e.length-o-1];if(i==null&&(i=1),s===1)t.unshift(i);else if(i===1)t.unshift(s);else if(s!==i){let a=`Operands could not be broadcast together with shapes ${r} and ${e}.`;throw Error(a)}else t.unshift(s)}return t}function cZ(r,e){let t=w(r,"a","equal","string_or_numeric"),n=w(e,"b","equal","string_or_numeric");[t,n]=Qe(t,n),St(t.shape,n.shape);let o={a:t,b:n};return L.runKernel(x2,o)}var h_=E({equal_:cZ});function mZ(r,e,t){let n=w(e,"a","where"),o=w(t,"b","where"),s=w(r,"condition","where","bool"),i=St(St(s.shape,n.shape),o.shape),a=Ch(s,i),l=Ch(n,i),u=Ch(o,i),p={condition:a,t:l,e:u};return L.runKernel(DM,p)}var ai=E({where_:mZ});function fZ(r){let t={x:w(r,"x","zerosLike")};return L.runKernel(lF,t)}var qr=E({zerosLike_:fZ});function dZ(r,e){let t=w(r,"a","div"),n=w(e,"b","div");[t,n]=Qe(t,n);let o=ct(t,n),s=qr(o),i=h_(n,s);return ai(i,s,o)}var hZ=E({divNoNan_:dZ});function gZ(r,e){let t=w(r,"t1","dot"),n=w(e,"t2","dot");P((t.rank===1||t.rank===2)&&(n.rank===1||n.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${t.rank} and ${n.rank}.`);let o=t.rank===1?t.size:t.shape[1],s=n.rank===1?n.size:n.shape[0];if(P(o===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${o} and ${s}.`),t.rank===1&&n.rank===1){let i=te(t,[1,-1]),a=te(n,[-1,1]),l=gt(i,a);return te(l,[])}else if(t.rank===1&&n.rank===2){let i=te(t,[1,-1]),a=te(n,[n.shape[0],n.shape[1]]),l=gt(i,a);return te(l,[l.size])}else if(t.rank===2&&n.rank===1){let i=te(n,[-1,1]),a=gt(t,i);return te(a,[a.size])}else{let i=te(n,[n.shape[0],n.shape[1]]);return gt(t,i)}}var bZ=E({dot_:gZ});function yZ(r,...e){let t=e.map((o,s)=>w(o,`tensors${s}`,"einsum")),n={equation:r};return L.runKernel(g2,t,n)}var xZ=E({einsum_:yZ});function TZ(r){let t={x:w(r,"x","elu")};return L.runKernel(b2,t)}var g_=E({elu_:TZ});function kZ(r){let e=w(r,"x","erf");P(e.dtype==="int32"||e.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),e.dtype==="int32"&&(e=ft(e,"float32"));let t={x:e};return L.runKernel(y2,t)}var IZ=E({erf_:kZ});function vZ(r){let t={x:w(r,"x","exp")};return L.runKernel(T2,t)}var zs=E({exp_:vZ});function wZ(r,e=0){let t=w(r,"x","expandDims","string_or_numeric");P(e<=t.rank,()=>"Axis must be <= rank of the tensor");let n={input:t},o={dim:e};return L.runKernel(k2,n,o)}var Nu=E({expandDims_:wZ});function _Z(r){let t={x:w(r,"x","expm1")};return L.runKernel(I2,t)}var CZ=E({expm1_:_Z});function SZ(r,e){let t=w(r,"x","tile","string_or_numeric");P(t.rank===e.length,()=>`Error in transpose: rank of input ${t.rank} must match length of reps ${e}.`);let n={x:t},o={reps:e};return L.runKernel(Tx,n,o)}var Nh=E({tile_:SZ});function NZ(r,e,t,n="float32"){e==null&&(e=r);let o=Ln([r,e],n),s=r<=e?r:e;for(let a=0;a<s;++a)o.set(1,a,a);let i=te(o.toTensor(),[r,e]);if(t==null)return i;if(t.length===1)return Nh(Nu(i,0),[t[0],1,1]);if(t.length===2)return Nh(Nu(Nu(i,0),0),[t[0],t[1],1,1]);if(t.length===3)return Nh(Nu(Nu(Nu(i,0),0),0),[t[0],t[1],t[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${t.length}D.`)}var b_=E({eye_:NZ});function Vp(r,e,t){let n={shape:r,value:e,dtype:t};return L.runKernel(w2,{},n)}function AZ(r){let t={x:w(r,"x","floor")};return L.runKernel(C2,t)}var y_=E({floor_:AZ});function DZ(r,e,t=0,n=0){let o=w(r,"x","gather"),s=w(e,"indices","gather","int32"),i={x:o,indices:s},a={axis:t,batchDims:n};return L.runKernel(A2,i,a)}var x_=E({gather_:DZ});function EZ(r,e){let t=w(r,"a","greater","string_or_numeric"),n=w(e,"b","greater","string_or_numeric");[t,n]=Qe(t,n),St(t.shape,n.shape);let o={a:t,b:n};return L.runKernel(E2,o)}var qm=E({greater_:EZ});function MZ(r,e){let t=w(r,"a","greaterEqual","string_or_numeric"),n=w(e,"b","greaterEqual","string_or_numeric");[t,n]=Qe(t,n),St(t.shape,n.shape);let o={a:t,b:n};return L.runKernel(M2,o)}var T_=E({greaterEqual_:MZ});function FZ(r){let t={input:w(r,"input","imag")};return L.runKernel(R2,t)}var Ah=E({imag_:FZ});function RZ(r){let t={x:w(r,"x","isFinite")};return L.runKernel(L2,t)}var LZ=E({isFinite_:RZ});function $Z(r){let t={x:w(r,"x","isInf")};return L.runKernel($2,t)}var PZ=E({isInf_:$Z});function BZ(r){let t={x:w(r,"x","isNaN")};return L.runKernel(P2,t)}var OZ=E({isNaN_:BZ});function zZ(r,e=.2){let n={x:w(r,"x","leakyRelu")},o={alpha:e};return L.runKernel(B2,n,o)}var k_=E({leakyRelu_:zZ});function GZ(r,e){let t=w(r,"a","less","string_or_numeric"),n=w(e,"b","less","string_or_numeric");[t,n]=Qe(t,n),St(t.shape,n.shape);let o={a:t,b:n};return L.runKernel(O2,o)}var WZ=E({less_:GZ});function KZ(r,e){let t=w(r,"a","lessEqual","string_or_numeric"),n=w(e,"b","lessEqual","string_or_numeric");[t,n]=Qe(t,n),St(t.shape,n.shape);let o={a:t,b:n};return L.runKernel(z2,o)}var Dh=E({lessEqual_:KZ});function VZ(r,e,t){if(t<=0)throw new Error("The number of values should be positive.");let n={start:r,stop:e,num:t};return L.runKernel(G2,{},n)}function UZ(r,e=5,t=1,n=1,o=.5){let s=w(r,"x","localResponseNormalization");P(s.rank===4||s.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
|
|
rank ${s.rank}.`),P(Qt(e),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${e}.`);let i=s,a=!1;s.rank===3&&(a=!0,i=te(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let l={x:i},u={depthRadius:e,bias:t,alpha:n,beta:o},p=L.runKernel(H2,l,u);return a?te(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var jZ=E({localResponseNormalization_:UZ});function HZ(r){let t={x:w(r,"x","log")};return L.runKernel(W2,t)}var Au=E({log_:HZ});function qZ(r){let t={x:w(r,"x","log1p")};return L.runKernel(K2,t)}var I_=E({log1p_:qZ});function XZ(r){return P(ri(r),()=>"The f passed in grad(f) must be a function"),(e,t)=>{let n=w(e,"x","tf.grad","string_or_numeric"),o=t!=null?w(t,"dy","tf.grad"):null;return L.tidy(()=>{let{value:s,grads:i}=L.gradients(()=>r(n),[n],o);return o!=null&&Jt(s.shape,o.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Vx(i),i[0]})}}function YZ(r){return P(ri(r),()=>"The f passed in grads(f) must be a function"),(e,t)=>{P(Array.isArray(e),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let n=Ki(e,"args","tf.grads","string_or_numeric"),o=t!=null?w(t,"dy","tf.grads"):null;return L.tidy(()=>{let{value:s,grads:i}=L.gradients(()=>r(...n),n,o);return o!=null&&Jt(s.shape,o.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Vx(i),i})}}function ZZ(r){return P(ri(r),()=>"The f passed in valueAndGrad(f) must be a function"),(e,t)=>{P(e instanceof Yt,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),P(t==null||t instanceof Yt,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:n,value:o}=L.gradients(()=>r(e),[e],t);return Vx(n),{grad:n[0],value:o}}}function JZ(r){return P(ri(r),()=>"The f passed in valueAndGrads(f) must be a function"),(e,t)=>{P(Array.isArray(e)&&e.every(o=>o instanceof Yt),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),P(t==null||t instanceof Yt,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let n=L.gradients(()=>r(...e),e,t);return t!=null&&Jt(n.value.shape,t.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Vx(n.grads),n}}function v_(r,e){P(ri(r),()=>"The f passed in variableGrads(f) must be a function"),P(e==null||Array.isArray(e)&&e.every(u=>u instanceof Cu),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let t=e!=null;if(!t){e=[];for(let u in L.registeredVariables)e.push(L.registeredVariables[u])}let n=t?e.filter(u=>!u.trainable):null,o=e.length;e=e.filter(u=>u.trainable),P(e.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${o} variables is trainable.`);let s=!0,{value:i,grads:a}=L.gradients(r,e,null,s);P(a.some(u=>u!=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()."),P(i.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${i.rank} tensor`);let l={};return e.forEach((u,p)=>{a[p]!=null&&(l[u.name]=a[p])}),n!=null&&n.forEach(u=>l[u.name]=null),{value:i,grads:l}}function $n(r){return L.customGrad(r)}function Vx(r){if(r.filter(t=>t==null).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.`)}function QZ(r){let t={x:w(r,"x","neg")};return L.runKernel(aM,t)}var Ao=E({neg_:QZ});function eJ(r){let t={x:w(r,"x","softplus")};return L.runKernel(PM,t)}var w_=E({softplus_:eJ});function tJ(r){let e=w(r,"x","logSigmoid");return $n(n=>({value:Ao(w_(Ao(n))),gradFunc:i=>fe(i,Xi(Ao(n)))}))(e)}var rJ=E({logSigmoid_:tJ});function nJ(r,e=null,t=!1){let o={x:w(r,"x","max")},s={reductionIndices:e,keepDims:t};return L.runKernel(q2,o,s)}var Yi=E({max_:nJ});function oJ(r,e){let t=w(r,"a","sub"),n=w(e,"b","sub");[t,n]=Qe(t,n);let o={a:t,b:n};return L.runKernel(QM,o)}var We=E({sub_:oJ});function sJ(r,e=null,t=!1){let n=w(r,"x","sum");n.dtype==="bool"&&(n=ft(n,"int32"));let o={x:n},s={axis:e,keepDims:t};return L.runKernel(OM,o,s)}var It=E({sum_:sJ});function aJ(r,e=-1){let t=w(r,"logits","logSoftmax");if(e===-1&&(e=t.rank-1),e!==t.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${t.rank} and axis was ${e}`);return $n((o,s)=>{let i=!0,a=Yi(o,e,!0),l=We(o,a),u=We(ft(l,"float32"),Au(It(zs(l),e,i)));return s([u]),{value:u,gradFunc:(c,m)=>{let[f]=m,d=!0,h=zs(f);return We(c,fe(It(c,e,d),h))}}})(t)}var iJ=E({logSoftmax_:aJ});function __(r,e){for(let t=0;t<r.length;++t)if(r[r.length-t-1]!==e-1-t)return!1;return!0}function UR(r,e,t){let n=r.length+e.length,o=[],s=0,i=0;for(let a=0;a<n;a++)t.indexOf(a)===-1?o.push(r[s++]):o.push(e[i++]);return o}function lJ(r,e){let t=[],n=r.length;for(let s=0;s<n;s++)e.indexOf(s)===-1&&t.push(r[s]);let o=e.map(s=>r[s]);return[t,o]}function Zi(r,e){let t=e.map(n=>1);return UR(r,t,e)}function uJ(r,e,t){P(__(e,t),()=>`${r} supports only inner-most axes for now. Got axes ${e} and rank-${t} input.`)}function pJ(r,e){if(__(r,e))return null;let t=[];for(let n=0;n<e;++n)r.indexOf(n)===-1&&t.push(n);return r.forEach(n=>t.push(n)),t}function cJ(r){return r.map((e,t)=>[t,e]).sort((e,t)=>e[1]-t[1]).map(e=>e[0])}function mJ(r,e){let t=[];for(let n=e-r;n<e;++n)t.push(n);return t}function fJ(r,e=null,t=!1){let n=w(r,"x","logSumExp"),o=vu(e,n.shape),s=Yi(n,o,!0),i=We(n,s),a=zs(i),l=It(a,o),u=Au(l),p=Re(te(s,u.shape),u);if(t){let c=Zi(p.shape,o);return te(p,c)}return p}var C_=E({logSumExp_:fJ});function dJ(r,e){let t=w(r,"a","logicalAnd","bool"),n=w(e,"b","logicalAnd","bool");St(t.shape,n.shape);let o={a:t,b:n};return L.runKernel(V2,o)}var Xm=E({logicalAnd_:dJ});function hJ(r){let t={x:w(r,"x","logicalNot","bool")};return L.runKernel(U2,t)}var S_=E({logicalNot_:hJ});function gJ(r,e){let t=w(r,"a","logicalOr","bool"),n=w(e,"b","logicalOr","bool");St(t.shape,n.shape);let o={a:t,b:n};return L.runKernel(j2,o)}var N_=E({logicalOr_:gJ});function bJ(r,e){let t=w(r,"a","logicalXor","bool"),n=w(e,"b","logicalXor","bool");return St(t.shape,n.shape),Xm(N_(r,e),S_(Xm(r,e)))}var yJ=E({logicalXor_:bJ});function xJ(r,e,t,n,o){let s=w(r,"x","maxPool"),i=1,a=s,l=!1;s.rank===3&&(l=!0,a=te(s,[1,s.shape[0],s.shape[1],s.shape[2]])),P(a.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${a.rank}.`),P(Tn(t,i),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${t} and dilations '${i}'`),o!=null&&P(Qt(n),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`);let u={x:a},p={filterSize:e,strides:t,pad:n,dimRoundingMode:o},c=L.runKernel(Y2,u,p);return l?te(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var A_=E({maxPool_:xJ});function TJ(r,e=[1,1,1],t,n,o,s="NDHWC"){let i=w(r,"x","maxPool3d"),a=i,l=!1;i.rank===4&&(l=!0,a=te(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),P(a.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${a.rank}.`),P(s==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),o!=null&&P(Qt(n),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`);let u={x:a},p={filterSize:e,strides:t,pad:n,dimRoundingMode:o,dataFormat:s},c=L.runKernel(Z2,u,p);return l?te(c,[c.shape[1],c.shape[2],c.shape[3],c.shape[4]]):c}var kJ=E({maxPool3d_:TJ});function IJ(r,e,t,n,o=!1){let i={x:w(r,"x","maxPoolWithArgmax")},a={filterSize:e,strides:t,pad:n,includeBatchInIndex:o},l=L.runKernel(J2,i,a);return{result:l[0],indexes:l[1]}}var vJ=E({maxPoolWithArgmax_:IJ});function wJ(r,e){let t=w(r,"a","maximum"),n=w(e,"b","maximum");[t,n]=Qe(t,n),t.dtype==="bool"&&(t=ft(t,"int32"),n=ft(n,"int32")),St(t.shape,n.shape);let o={a:t,b:n};return L.runKernel(X2,o)}var D_=E({maximum_:wJ});function _J(r,e=null,t=!1){let o={x:w(r,"x","mean")},s={axis:e,keepDims:t};return L.runKernel(Q2,o,s)}var Ym=E({mean_:_J});function Ji(r,e="float32"){if(e==="complex64"){let n=Ji(r,"float32"),o=Ji(r,"float32");return ss(n,o)}let t=Lm(Ct(r),e);return L.makeTensor(t,r,e)}function Qi(r,e="float32"){if(e==="complex64"){let n=Qi(r,"float32"),o=Ji(r,"float32");return ss(n,o)}let t=mh(Ct(r),e);return L.makeTensor(t,r,e)}function CJ(r,e,{indexing:t="xy"}={}){if(t!=="xy"&&t!=="ij")throw new TypeError(`${t} is not a valid third argument to meshgrid`);if(r===void 0)return[];let n=w(r,"x","meshgrid",r instanceof Yt?r.dtype:"float32");if(e===void 0)return[n];let o=w(e,"y","meshgrid",e instanceof Yt?e.dtype:"float32"),s=Ct(n.shape),i=Ct(o.shape);return t==="xy"?(n=te(n,[1,-1]),o=te(o,[-1,1]),[gt(Qi([i,1],n.dtype),n),gt(o,Qi([1,s],o.dtype))]):(n=te(n,[-1,1]),o=te(o,[1,-1]),[gt(n,Qi([1,i],n.dtype)),gt(Qi([s,1],o.dtype),o)])}function SJ(r,e=null,t=!1){let o={x:w(r,"x","min")},s={axis:e,keepDims:t};return L.runKernel(eM,o,s)}var Ux=E({min_:SJ});function NJ(r,e){let t=w(r,"a","minimum"),n=w(e,"b","minimum");[t,n]=Qe(t,n),t.dtype==="bool"&&(t=ft(t,"int32"),n=ft(n,"int32")),St(t.shape,n.shape);let o={a:t,b:n};return L.runKernel(tM,o)}var E_=E({minimum_:NJ});function AJ(r,e,t){P(t==="reflect"||t==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${t}.`);let n=w(r,"x","mirrorPad");if(n.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");P(e.length===n.rank,()=>`Padding doesn't match input. Must be ${n.rank}. Got ${e.length}.`);let o=t==="reflect"?1:0;for(let a=0;a<n.rank;a++)P(e[a].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),P(e[a][0]>=0&&e[a][0]<=n.shape[a]-o&&e[a][1]>=0&&e[a][1]<=n.shape[a]-o,()=>`Padding in dimension ${a} cannot be greater than or equal to ${n.shape[a]-o} or less than 0 for input of shape ${n.shape}`);let s={paddings:e,mode:t},i={x:n};return L.runKernel(rM,i,s)}var DJ=E({mirrorPad_:AJ});function EJ(r,e){let t=w(r,"a","mod"),n=w(e,"b","mod");[t,n]=Qe(t,n);let o={a:t,b:n};return L.runKernel(nM,o)}var MJ=E({mod_:EJ});function FJ(r){let e=w(r,"x","square"),t={};return L.runKernel("Square",{x:e},t)}var pn=E({square_:FJ});function RJ(r,e=null,t=!1){r=w(r,"x","moments");let n=vu(e,r.shape),o=Ym(r,n,t),s=o.shape;t||(s=Zi(o.shape,n));let i=pn(We(ft(r,"float32"),te(o,s))),a=Ym(i,n,t);return{mean:o,variance:a}}var LJ=E({moments_:RJ});function $J(r,e,t,n){let o=w(e,"data","multiRNNCell"),s=Ki(t,"c","multiRNNCell"),i=Ki(n,"h","multiRNNCell"),a=o,l=[];for(let c=0;c<r.length;c++){let m=r[c](a,s[c],i[c]);l.push(m[0]),l.push(m[1]),a=m[1]}let u=[],p=[];for(let c=0;c<l.length;c+=2)u.push(l[c]),p.push(l[c+1]);return[u,p]}var PJ=E({multiRNNCell_:$J});function BJ(r,e,t,n=!1){let o=w(r,"logits","multinomial"),s=o.size,i=o.rank;if(s<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${s}.`);if(i>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${i}`);t=t||Math.random();let l={logits:i===1?te(o,[1,-1]):o},u={numSamples:e,seed:t,normalized:n},p=L.runKernel(oM,l,u);return i===1?te(p,[p.size]):p}var OJ=E({multinomial_:BJ});function zJ(r,e){let t=w(r,"a","notEqual","string_or_numeric"),n=w(e,"b","notEqual","string_or_numeric");[t,n]=Qe(t,n),St(t.shape,n.shape);let o={a:t,b:n};return L.runKernel(iM,o)}var M_=E({notEqual_:zJ});function GJ(r){let t={x:w(r,"x","onesLike")};return L.runKernel(cM,t)}var WJ=E({onesLike_:GJ});function KJ(r,e){let t=w(r,"v1","outerProduct"),n=w(e,"v2","outerProduct");P(t.rank===1&&n.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${t.rank} and ${n.rank}.`);let o=te(t,[-1,1]),s=te(n,[1,-1]);return gt(o,s)}var VJ=E({outerProduct_:KJ});function UJ(r,e,t=0){let n=w(r,"x","pad");if(n.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let o={paddings:e,constantValue:t},s={x:n};return L.runKernel(dM,s,o)}var el=E({pad_:UJ});function jJ(r,e,t=0){return P(e.length===2,()=>"Invalid number of paddings. Must be length of 2."),el(r,[e],t)}var HJ=E({pad1d_:jJ});function qJ(r,e,t=0){return P(e.length===2&&e[0].length===2&&e[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),el(r,e,t)}var XJ=E({pad2d_:qJ});function YJ(r,e,t=0){return P(e.length===3&&e[0].length===2&&e[1].length===2&&e[2].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),el(r,e,t)}var ZJ=E({pad3d_:YJ});function JJ(r,e,t=0){return P(e.length===4&&e[0].length===2&&e[1].length===2&&e[2].length===2&&e[3].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),el(r,e,t)}var QJ=E({pad4d_:JJ});function eQ(r,e,t){let n=w(r,"x","spaceToBatchND");P(n.rank>=1+e.length,()=>`input rank ${n.rank} should be > than [blockShape] ${e.length}`),P(t.length===e.length,()=>`paddings.shape[0] ${t.length} must be equal to [blockShape] ${e.length}`),P(n.shape.reduce((i,a,l)=>l>0&&l<=e.length?i&&(a+t[l-1][0]+t[l-1][1])%e[l-1]==0:i,!0),()=>`input spatial dimensions ${n.shape.slice(1)} with paddings ${t.toString()} must be divisible by blockShapes ${e.toString()}`);let o={x:n},s={blockShape:e,paddings:t};return L.runKernel(zM,o,s)}var F_=E({spaceToBatchND_:eQ});function tQ(r,e,t,n,o,s){o==null&&(o=[1,1]),s==null&&(s=1),n===0&&(n="valid");let i=w(r,"x","maxPool"),a=i,l=!1;i.rank===3&&(l=!0,a=te(i,[1,i.shape[0],i.shape[1],i.shape[2]])),P(Tn(s,o),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${o}'`);let u=l_(a.shape,e,s,o,n),p=[u.dilationHeight,u.dilationWidth],c;n==="same"?c=nQ([u.filterHeight,u.filterWidth],p):c=[[0,0],[0,0]];let m=p[0]===1&&p[1]===1,[f,d]=rQ([u.inHeight,u.inWidth],p,c),h=m?n:"valid",g=m?a:F_(a,p,f),y=(t==="avg"?()=>c_(g,e,s,h):()=>A_(g,e,s,h))(),T=m?y:m_(y,p,d);return l?te(T,[T.shape[1],T.shape[2],T.shape[3]]):T}function rQ(r,e,t){let n=t.map(p=>p[0]),o=t.map(p=>p[1]),s=r.concat(n,o),i=e.map((p,c)=>(p-s[c]%p)%p),a=o.map((p,c)=>p+i[c]),l=e.map((p,c)=>[n[c],a[c]]),u=e.map((p,c)=>[0,i[c]]);return[l,u]}function nQ(r,e){let n=r.map((i,a)=>i+(i-1)*(e[a]-1)).map(i=>i-1),o=n.map(i=>Math.floor(i/2)),s=n.map((i,a)=>i-o[a]);return n.map((i,a)=>[o[a],s[a]])}var oQ=E({pool_:tQ});function sQ(r,e){let t=w(r,"base","pow"),n=w(e,"exp","pow");[t,n]=Qe(t,n);let o={a:t,b:n};return L.runKernel(hM,o)}var Du=E({pow_:sQ});function aQ(r,e){let t=w(r,"x","prelu"),n=w(e,"alpha","prelu"),o={x:t,alpha:n};return L.runKernel(gM,o)}var R_=E({prelu_:aQ});function iQ(r,e=null,t=!1){let n=w(r,"x","prod");n.dtype==="bool"&&(n=ft(n,"int32"));let o={x:n},s={axis:e,keepDims:t};return L.runKernel(bM,o,s)}var lQ=E({prod_:iQ});function uQ(r,e,t){let n=Ct(r),o=null;if(t==null||t==="float32")o=new Float32Array(n);else if(t==="int32")o=new Int32Array(n);else if(t==="bool")o=new Uint8Array(n);else throw new Error(`Unknown data type ${t}`);for(let s=0;s<n;s++)o[s]=e();return L.makeTensor(o,r,t)}var pQ=E({rand_:uQ});var qx=Wi(Hx());var Zm=class{constructor(e,t,n,o,s){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=o,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);let i=s||Math.random();this.random=qx.alea(i.toString())}nextValue(){if(!isNaN(this.nextVal)){let o=this.nextVal;return this.nextVal=NaN,o}let e,t,n=!1;for(;!n;){let o,s,i;do o=2*this.random()-1,s=2*this.random()-1,i=o*o+s*s;while(i>=1||i===0);let a=Math.sqrt(-2*Math.log(i)/i);e=this.mean+this.stdDev*o*a,t=this.mean+this.stdDev*s*a,(!this.truncated||this.isValidTruncated(e))&&(n=!0)}return(!this.truncated||this.isValidTruncated(t))&&(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return this.dtype==null||this.dtype==="float32"?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}},W_=class{constructor(e,t,n,o){this.alpha=e,this.beta=1/t,this.dtype=n;let s=o||Math.random();this.randu=qx.alea(s.toString()),this.randn=new Zm(0,1,n,!1,this.randu()),e<1?this.d=e+2/3:this.d=e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,o,s,i;for(;;){do o=this.randn.nextValue(),i=1+this.c*o;while(i<=0);if(i*=i*i,e=o*o,t=1-.331*e*e,n=.5*e+this.d*(1-i+Math.log(i)),s=this.randu(),s<t||Math.log(s)<n)break}return i=1/this.beta*this.d*i,this.alpha<1&&(i*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(i)}convertValue(e){return this.dtype==="float32"?e:Math.round(e)}},K_=class{constructor(e=0,t=1,n,o){this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32";if(this.min=e,this.range=t-e,this.dtype=n,o==null&&(o=Math.random()),typeof o=="number"&&(o=o.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=qx.alea(o)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function bQ(r,e,t=1,n="float32",o){if(t==null&&(t=1),n==null&&(n="float32"),n!=="float32"&&n!=="int32")throw new Error(`Unsupported data type ${n}`);let s=new W_(e,t,n,o),i=Ln(r,n);for(let a=0;a<i.values.length;a++)i.values[a]=s.nextValue();return i.toTensor()}var yQ=E({randomGamma_:bQ});function xQ(r,e=0,t=1,n,o){if(n!=null&&n==="bool")throw new Error(`Unsupported data type ${n}`);let s=new Zm(e,t,n,!1,o),i=Ln(r,n);for(let a=0;a<i.values.length;a++)i.values[a]=s.nextValue();return i.toTensor()}var TQ=E({randomNormal_:xQ});function kQ(r,e=0,t=1,n="float32",o){let s=Ln(r,n),i=new K_(e,t,null,o);for(let a=0;a<s.values.length;a++)s.values[a]=i.nextValue();return s.toTensor()}var V_=E({randomUniform_:kQ});function jp(r,e,t=1,n="float32"){if(t===0)throw new Error("Cannot have a step of zero");let o={start:r,stop:e,step:t,dtype:n};return L.runKernel(yM,{},o)}function IQ(r){let t={input:w(r,"input","real")};return L.runKernel(xM,t)}var Jm=E({real_:IQ});function vQ(r){let t={x:w(r,"x","reciprocal")};return L.runKernel(TM,t)}var wQ=E({reciprocal_:vQ});function _Q(r){let t={x:w(r,"x","relu")};return L.runKernel(kM,t)}var Hp=E({relu_:_Q});function CQ(r){let t={x:w(r,"x","relu6")};return L.runKernel(_M,t)}var U_=E({relu6_:CQ});function SQ(r,e){let n={x:w(r,"x","reverse")},o={dims:e};return L.runKernel(CM,n,o)}var as=E({reverse_:SQ});function NQ(r){let e=w(r,"x","reverse");return P(e.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${e.rank}.`),as(e,0)}var AQ=E({reverse1d_:NQ});function DQ(r,e){let t=w(r,"x","reverse");return P(t.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${t.rank}.`),as(t,e)}var EQ=E({reverse2d_:DQ});function MQ(r,e){let t=w(r,"x","reverse");return P(t.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${t.rank}.`),as(t,e)}var FQ=E({reverse3d_:MQ});function RQ(r,e){let t=w(r,"x","reverse");return P(t.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${t.rank}.`),as(t,e)}var LQ=E({reverse4d_:RQ});function $Q(r){let t={x:w(r,"x","round")};return L.runKernel(SM,t)}var j_=E({round_:$Q});function PQ(r){let t={x:w(r,"x","rsqrt")};return L.runKernel(NM,t)}var BQ=E({rsqrt_:PQ});function Je(r,e){if((zr(r)&&e!=="string"||Array.isArray(r))&&e!=="complex64")throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if(e==="string"&&zr(r)&&!(r instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Fn(r,[],[],e)}function OQ(r){let t={x:w(r,"x","selu")};return L.runKernel(EM,t)}var zQ=E({selu_:OQ});function GQ(r,e,t,n,o,s=[1,1],i="NHWC"){let a=w(r,"x","separableConv2d"),l=w(e,"depthwiseFilter","separableConv2d"),u=w(t,"pointwiseFilter","separableConv2d"),p=a,c=!1;if(a.rank===3&&(c=!0,p=te(a,[1,a.shape[0],a.shape[1],a.shape[2]])),i==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");P(p.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${p.rank}.`),P(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),P(u.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),P(u.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`),P(u.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${u.shape[1]}.`);let m=l.shape[2],f=l.shape[3];P(u.shape[2]===m*f,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${m*f}, but got ${u.shape[2]}.`);let d=Sh(p,l,n,o,i,s),g=Kp(d,u,1,"valid",i);return c?te(g,[g.shape[1],g.shape[2],g.shape[3]]):g}var WQ=E({separableConv2d_:GQ});async function KQ(r,e){let t=w(r,"x","setdiff1d"),n=w(e,"y","setdiff1d");P(t.dtype===n.dtype,()=>`x and y should have the same dtype, but got x (${t.dtype}) and y (${n.dtype}).`),P(t.rank===1,()=>`x should be 1D tensor, but got x (${t.shape}).`),P(n.rank===1,()=>`y should be 1D tensor, but got y (${n.shape}).`);let o=await t.data(),s=await n.data(),i=new Set(s),a=0;for(let p=0;p<o.length;p++)i.has(o[p])||a++;let l=new Pp([a],t.dtype),u=new Pp([a],"int32");for(let p=0,c=0;p<o.length;p++)i.has(o[p])||(l.values[c]=o[p],u.values[c]=p,c++);return[l.toTensor(),u.toTensor()]}var VQ=KQ;function UQ(r){let t={x:w(r,"x","sign")};return L.runKernel(LM,t)}var jQ=E({sign_:UQ});function HQ(r){let t={x:w(r,"x","sin")};return L.runKernel(FM,t)}var qQ=E({sin_:HQ});function XQ(r){let t={x:w(r,"x","sinh")};return L.runKernel(RM,t)}var YQ=E({sinh_:XQ});function ZQ(r,e,t){let n=w(r,"x","slice1d");return P(n.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${n.rank} tensor`),kt(n,[e],[t])}var JQ=E({slice1d_:ZQ});function QQ(r,e,t){let n=w(r,"x","slice2d");return P(n.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${n.rank} tensor`),kt(n,e,t)}var eee=E({slice2d_:QQ});function tee(r,e,t){let n=w(r,"x","slice3d");return P(n.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${n.rank} tensor`),kt(n,e,t)}var ree=E({slice3d_:tee});function nee(r,e,t){let n=w(r,"x","slice4d");return P(n.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${n.rank} tensor`),kt(n,e,t)}var oee=E({slice4d_:nee});function see(r,e=-1){let t=w(r,"logits","softmax","float32");if(e===-1&&(e=t.rank-1),e!==t.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${t.rank} and dim was ${e}`);let n={logits:t},o={dim:e};return L.runKernel(WM,n,o)}var aee=E({softmax_:see});function iee(r){P(r.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${r.dtype}.`);let e={input:r};return L.runKernel(v2,e)}var Eh=E({fft_:iee});function lee(r){P(r.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${r.dtype}.`);let e={input:r};return L.runKernel(F2,e)}var Qm=E({ifft_:lee});function uee(r){let e=r.shape[r.shape.length-1],t=r.size/e,n;if(e<=2){let o=te(r,[t,e]);n=Qm(o)}else{let o=[t,2*(e-1)],s=te(Jm(r),[t,e]),i=te(Ah(r),[t,e]),a=as(kt(s,[0,1],[t,e-2]),1),l=fe(as(kt(i,[0,1],[t,e-2]),1),Je(-1)),u=Dr([s,a],1),p=Dr([i,l],1),c=te(ss(u,p),[o[0],o[1]]);n=Qm(c)}if(n=Jm(n),r.rank===3&&r.shape[0]!==0){let o=n,s=r.shape[0];n=te(n,[s,n.shape[0]/s,n.shape[1]]),o.dispose()}return n}var H_=E({irfft_:uee});function pee(r,e,t=0){let o={x:w(r,"x","split")},s={numOrSizeSplits:e,axis:t};return L.runKernel(GM,o,s)}var Eu=E({split_:pee});function cee(r,e){P(r.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${r.dtype}`);let t=r.shape[r.shape.length-1],n=r.size/t,o;if(e!=null&&e<t){let d=r.shape.map(g=>0),h=r.shape.map(g=>g);h[r.shape.length-1]=e,o=kt(r,d,h),t=e}else if(e!=null&&e>t){let d=r.shape.map(h=>h);d[r.shape.length-1]=e-t,o=Dr([r,Ji(d)],r.shape.length-1),t=e}else o=r;let s=qr(o),i=te(ss(o,s),[n,t]),a=Eh(i),l=Math.floor(t/2)+1,u=Jm(a),p=Ah(a),c=Eu(u,[l,t-l],u.shape.length-1),m=Eu(p,[l,t-l],p.shape.length-1),f=o.shape.slice();return f[o.shape.length-1]=l,te(ss(c[0],m[0]),f)}var Mh=E({rfft_:cee});function mee(r){let t={x:w(r,"x","sqrt")};return L.runKernel(BM,t)}var To=E({sqrt_:mee});function fee(r,e){let t=w(r,"a","squaredDifference"),n=w(e,"b","squaredDifference");[t,n]=Qe(t,n),St(t.shape,n.shape);let o={a:t,b:n},s={};return L.runKernel(qM,o,s)}var q_=E({squaredDifference_:fee});function dee(r,e){let t=w(r,"x","squeeze");return te(t,fw(t.shape,e).newShape)}var Fh=E({squeeze_:dee});function hee(r,e=0){let t=Ki(r,"tensors","stack","string_or_numeric");P(t.length>=1,()=>"Pass at least one tensor to tf.stack"),t.length>0&&P(e<=t[0].rank,()=>"Axis must be <= rank of the tensor");let n=t,o={axis:e};return L.runKernel(fM,n,o)}var Mu=E({stack_:hee});function gee(r,e=0){let n={x:w(r,"x","step")},o={alpha:e};return L.runKernel(uF,n,o)}var X_=E({step_:gee});function bee(r,e,t,n,o=0,s=0,i=0,a=0,l=0){let p={x:w(r,"x","stridedSlice","string_or_numeric")},c={begin:e,end:t,strides:n,beginMask:o,endMask:s,ellipsisMask:i,newAxisMask:a,shrinkAxisMask:l};return L.runKernel(XM,p,c)}var yee=E({stridedSlice_:bee});function xee(r){let t={x:w(r,"x","tan")};return L.runKernel(eF,t)}var Tee=E({tan_:xee});function Pn(r,e){No(r);let t=ln(r,e);if(t.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Fn(r,null,t,e)}function qp(r,e,t){if(No(r),e!=null&&e.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let n=ln(r,t);if(n.length!==2&&n.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(n.length===1&&e==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Fn(r,e,n,t)}function kee(r,e,t){if(No(r),e!=null&&e.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let n=ln(r,t);if(n.length!==4&&n.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(n.length===1&&e==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Fn(r,e,n,t)}function Iee(r,e,t){if(No(r),e!=null&&e.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let n=ln(r,t);if(n.length!==5&&n.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(n.length===1&&e==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Fn(r,e,n,t)}function vee(r,e,t){if(No(r),e!=null&&e.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let n=ln(r,t);if(n.length!==6&&n.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(n.length===1&&e==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return e=e||n,Fn(r,e,n,t)}function wee(r,e=1,t=!0){let n=w(r,"x","topk");if(n.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let o=n.shape[n.shape.length-1];if(e>o)throw new Error(`'k' passed to topk() must be <= the last dimension (${o}) but got ${e}`);let s={x:n},i={k:e,sorted:t},[a,l]=L.runKernel(rF,s,i);return{values:a,indices:l}}var _ee=E({topk_:wee});function Cee(r,e=0,t=1,n,o){if(n!=null&&n==="bool")throw new Error("Unsupported data type $ { dtype }");let s=new Zm(e,t,n,!0,o),i=Ln(r,n);for(let a=0;a<i.values.length;a++)i.values[a]=s.nextValue();return i.toTensor()}var See=E({truncatedNormal_:Cee});function Nee(r,e=0){let t=w(r,"x","unique","string_or_numeric");P(t.rank>0,()=>"The input tensor must be at least 1D");let n={x:t},o={axis:e},[s,i]=L.runKernel(sF,n,o);return{values:s,indices:i}}var Aee=E({unique_:Nee});function Dee(r,e,t){let n=w(r,"x","unsortedSegmentSum"),o=w(e,"segmentIds","unsortedSegmentSum","int32");P(Qt(t),()=>"numSegments must be of dtype int");let s={x:n,segmentIds:o},i={numSegments:t};return L.runKernel(iF,s,i)}var Eee=E({unsortedSegmentSum_:Dee});function Mee(r,e=0){let t=w(r,"x","unstack","string_or_numeric");P(e>=-t.shape.length&&e<t.shape.length,()=>`Axis = ${e} is not in [-${t.shape.length}, ${t.shape.length})`);let n={value:t},o={axis:e};return L.runKernel(aF,n,o)}var Rh=E({unstack_:Mee});function Fee(r,e=!0,t,n){return L.makeVariable(r,e,t,n)}function Xx(r,e){let t=[];for(let s=0;s<e.length;s++)e[s]&&t.push(s);let n=Ln(r,"int32"),o=Ln([t.length,r.length],"int32");for(let s=0;s<t.length;s++){let i=n.indexToLoc(t[s]),a=s*r.length;o.values.set(i,a)}return o.toTensor()}async function Ree(r){let e=w(r,"condition","whereAsync","bool"),t=await e.data(),n=Xx(e.shape,t);return r!==e&&e.dispose(),n}var Y_=Ree;async function Lee(r,e,t){let n=w(r,"tensor","boolMask"),o=w(e,"mask","boolMask","bool"),s=t==null?0:t,i=o.rank,a=n.shape;P(i>0,()=>"mask cannot be scalar"),Jt(a.slice(s,s+i),o.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let h=s;h<s+i;h++)l*=a[h];let u=a.slice(0,s).concat([l],a.slice(s+i)),p=te(n,u),c=te(o,[-1]),m=await Y_(c),f=Fh(m,[1]),d=x_(p,f,s);return r!==n&&n.dispose(),e!==o&&o.dispose(),f.dispose(),p.dispose(),c.dispose(),m.dispose(),d}var _je=Lee;function $ee(r,e="euclidean",t=null,n=!1){r=w(r,"x","norm");let o=aL(r,e,t),s=o.shape;if(n){let i=vu(t,r.shape);s=Zi(o.shape,i)}return te(o,s)}function aL(r,e,t=null){if(r.rank===0)return un(r);if(r.rank!==1&&t===null)return aL(te(r,[-1]),e,t);if(r.rank===1||typeof t=="number"||Array.isArray(t)&&t.length===1){if(e===1)return It(un(r),t);if(e===Infinity)return Yi(un(r),t);if(e===-Infinity)return Ux(un(r),t);if(e==="euclidean"||e===2)return To(It(Du(un(r),Je(2,"int32")),t));throw new Error(`Error in norm: invalid ord value: ${e}`)}if(Array.isArray(t)&&t.length===2){if(e===1)return Yi(It(un(r),t[0]),t[1]-1);if(e===Infinity)return Yi(It(un(r),t[1]),t[0]);if(e===-Infinity)return Ux(It(un(r),t[1]),t[0]);if(e==="fro"||e==="euclidean")return To(It(pn(r),t));throw new Error(`Error in norm: invalid ord value: ${e}`)}throw new Error(`Error in norm: invalid axis: ${t}`)}var Yx=E({norm_:$ee});function Pee(r,e,t,n,o=!0){let s=w(r,"v","movingAverage"),i=w(e,"x","movingAverage"),a=w(t,"decay","movingAverage");Ow(s,i),P(En(s.shape,i.shape),()=>"Shape mismatch in v and x");let l=Je(1),u=We(l,a),p=fe(We(i,s),u);if(o){P(n!=null,()=>"When using zeroDebias: true, step is required.");let c=w(n,"step","movingAverage");p=ct(p,We(l,Du(a,c)))}return Re(s,p)}var Zje=E({movingAverage_:Pee});function Bee(r,e,t){let n=w(r,"indices","scatterND","int32"),o=w(e,"updates","scatterND");$x(o,n,t);let s={indices:n,updates:o},i={shape:t};return L.runKernel(AM,s,i)}var aHe=E({scatterND_:Bee});function iL(r,e,t,n){if(r.dtype!=="int32")throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${r.dtype}.`);if(r.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${r.shape}.`);let o=r.rank>0?r.shape[0]:1,s=r.rank>1?r.shape[1]:1;if(t.length!==s)throw new Error(`outputShape has incorrect number of elements:, ${t.length}, should be: ${s}.`);let i=e.size;if(!(e.rank===0||e.rank===1&&i===o))throw new Error(`sparseValues has incorrect shape ${e.shape}, should be [] or [${o}]`);if(e.dtype!==n.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function Oee(r,e,t,n=0){let o=w(r,"sparseIndices","sparseToDense","int32"),s=w(e,"sparseValues","sparseToDense"),i=w(n,"defaultValue","sparseToDense",s.dtype);iL(o,s,t,i);let a={sparseIndices:o,sparseValues:s,defaultValue:i},l={outputShape:t};return L.runKernel(HM,a,l)}var gHe=E({sparseToDense_:Oee});function zee(r,e){let t=w(e,"indices","gatherND","int32"),o={params:w(r,"x","gatherND","string_or_numeric"),indices:t};return L.runKernel(D2,o)}var vHe=E({gatherND_:zee});function lL(r,e){if(e==null)return r.shape.slice();if(En(r.shape,e))return e;if(r.shape.length===e.length){let t=[];for(let n=0;n<r.shape.length;n++)e[n]==null&&r.shape[n]!=null?t.push(r.shape[n]):t.push(e[n]);return t}return e}function Gee(r,e,t,n){let o=w(r,"x","dropout");if(P(o.dtype==="float32",()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${o.dtype} tensor instead.`),P(e>=0&&e<1,()=>`rate must be a float in the range [0, 1), but got ${e}.`),e===0)return r instanceof Yt?o.clone():o;let s=lL(o,t),i=1-e,a=ct(y_(Re(V_(s,0,1,"float32",n),i)),i);return fe(o,a)}var PHe=E({dropout_:Gee});function uL(r){return Math.floor(Math.pow(2,Math.ceil(Math.log(r)/Math.log(2))))}function Zx(r,e,t){let n=1-r%2,o=new Float32Array(r);for(let s=0;s<r;++s){let i=2*Math.PI*s/(r+n-1);o[s]=e-t*Math.cos(i)}return Pn(o,"float32")}async function Wee(r,e,t=1){let n=w(r,"predictions","inTopK"),o=w(e,"targets","inTopK");P(n.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${n.rank}`),P(n.rank-1===o.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${n.rank} and targets rank ${o.rank}`),Jt(n.shape.slice(0,n.shape.length-1),o.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let s=n.shape[n.shape.length-1];P(t>0&&t<=s,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${s}), but got ${t}`);let i=await n.data(),a=await o.data(),[l,u]=[i.length/s,s],p=dw("bool",l);for(let c=0;c<l;c++){let m=c*u,f=i.subarray(m,m+u),d=[];for(let h=0;h<f.length;h++)d.push({value:f[h],index:h});d.sort((h,g)=>g.value-h.value),p[c]=0;for(let h=0;h<t;h++)if(d[h].index===a[c]){p[c]=1;break}}return r!==n&&n.dispose(),e!==o&&o.dispose(),Vi(p,o.shape,"bool")}var VHe=Wee;var gL={};Ge(gL,{conv2d:()=>cL,depthwiseConv2d:()=>dL,matMul:()=>hL});function Kee(r,e,t,n,o,s="NHWC",i){let a=r;r.rank===3&&(a=te(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let l=e;l.rank===3&&(l=te(e,[1,e.shape[0],e.shape[1],e.shape[2]])),P(a.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${a.shape}.`),P(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),P(t.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${t}.`);let u=s==="NHWC"?a.shape[3]:a.shape[1],p=s==="NHWC"?l.shape[3]:l.shape[1];P(u===t[2],()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${t[2]}.`),P(p===t[3],()=>`Error in conv2dDerFilter: depth of dy (${p}) must match output depth for filter (${t[3]}).`),i!=null&&P(Qt(o),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${i} but got pad ${o}.`);let c={x:a,dy:l},m={strides:n,pad:o,dataFormat:s,dimRoundingMode:i,filterShape:t};return L.runKernel(e2,c,m)}var pL=E({conv2DBackpropFilter_:Kee});function Xp(r,e,t){if(t==null||t==="linear")return r;if(t==="relu")return fe(r,X_(e));throw new Error(`Cannot compute gradient for fused activation ${t}.`)}function Yp(r,e){let t=e,n=d_(r.shape,e.shape);return n.length>0&&(t=It(t,n)),te(t,r.shape)}function Zp(r,e,t,n){if(e==="linear")return r;if(e==="relu")return Hp(r);if(e==="elu")return g_(r);if(e==="relu6")return U_(r);if(e==="prelu")return R_(r,t);if(e==="leakyrelu")return k_(r,n);if(e==="sigmoid")return Xi(r);throw new Error(`Unknown fused activation ${e}.`)}var Jp=(r,e)=>!(r>0)||e==="linear";function Vee({x:r,filter:e,strides:t,pad:n,dataFormat:o="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:a,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:p}){if(l=l||"linear",Jp(L.state.gradientDepth,l)===!1){let I=Kp(r,e,t,n,o,s,i);return a!=null&&(I=Re(I,a)),Zp(I,l,u,p)}let c=w(r,"x","conv2d"),m=w(e,"filter","conv2d"),f=c,d=!1;c.rank===3&&(d=!0,f=te(c,[1,c.shape[0],c.shape[1],c.shape[2]])),P(f.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${f.rank}.`),P(m.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${m.rank}.`),i!=null&&P(Qt(n),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${n}.`),P(f.shape[3]===m.shape[2],()=>`Error in conv2d: depth of input (${f.shape[3]}) must match input depth for filter ${m.shape[2]}.`),P(Tn(t,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`),P(o==="NHWC",()=>`Error in conv2d: got dataFormat of ${o} but only NHWC is currently supported.`);let h=Op(f.shape,m.shape,t,s,n,i),g;a!=null&&(g=w(a,"bias","fused conv2d"),[g]=Qe(g,c),St(h.outShape,g.shape));let b;u!=null&&(b=w(u,"prelu weights","fused conv2d"));let y=(I,S)=>{let[N,F,$,O]=S,V=Xp(I,$,l);P(Gp(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let q=Kx(F.shape,V,N,t,n),W=pL(F,V,N.shape,t,n),Y=[q,W];if(O!=null){let Z=Yp(O,V);Y.push(Z)}return Y},T={x:f,filter:m,bias:g,preluActivationWeights:b},k={strides:t,pad:n,dataFormat:o,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:p};return a==null?$n((S,N,F)=>{let $=L.runKernel(ww,T,k);return F([N,S,$]),d&&($=te($,[$.shape[1],$.shape[2],$.shape[3]])),{value:$,gradFunc:y}})(f,m):$n((S,N,F,$)=>{let O=L.runKernel(ww,T,k);return $([N,S,O,F]),d&&(O=te(O,[O.shape[1],O.shape[2],O.shape[3]])),{value:O,gradFunc:y}})(f,m,g)}var cL=E({fusedConv2d_:Vee});function Uee(r,e,t,n,o,s=[1,1],i){let a=r;r.rank===3&&(a=te(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let l=e;l.rank===3&&(l=te(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u={x:a,dy:l},p={strides:n,pad:o,dimRoundingMode:i,dilations:s,filterShape:t};return L.runKernel(c2,u,p)}var mL=E({depthwiseConv2dNativeBackpropFilter_:Uee});function jee(r,e,t,n,o,s=[1,1],i){let a=e,l=!1;e.rank===3&&(l=!0,a=te(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u={dy:a,filter:t},p={strides:n,pad:o,dimRoundingMode:i,dilations:s,inputShape:r},c=L.runKernel(m2,u,p);return l?te(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var fL=E({depthwiseConv2dNativeBackpropInput_:jee});function Hee({x:r,filter:e,strides:t,pad:n,dataFormat:o="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:a,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:p}){if(Jp(L.state.gradientDepth,l)===!1){let I=Sh(r,e,t,n,o,s,i);return a!=null&&(I=Re(I,a)),Zp(I,l,u,p)}let c=w(r,"x","depthwiseConv2d"),m=w(e,"filter","depthwiseConv2d"),f=c,d=!1;c.rank===3&&(d=!0,f=te(c,[1,c.shape[0],c.shape[1],c.shape[2]])),P(f.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${f.rank}.`),P(m.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${m.rank}.`),P(f.shape[3]===m.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${f.shape[3]}) must match the inChannels dimension in filter ${m.shape[2]}.`),s==null&&(s=[1,1]),P(Tn(t,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`),i!=null&&P(Qt(n),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${i} but got pad ${n}.`);let h=Op(f.shape,m.shape,t,s,n,i,!0),g;a!=null&&(g=w(a,"bias","fused conv2d"),[g]=Qe(g,c),St(h.outShape,g.shape));let b;u!=null&&(b=w(u,"prelu weights","fused depthwiseConv2d"));let y=(I,S)=>{P(Gp(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);let[N,F,$,O]=S,V=Xp(I,$,l),q=fL(F.shape,V,N,t,n,s,i),W=mL(F,V,N.shape,t,n,s,i);if(O!=null){let Y=Yp(g,V);return[q,W,Y]}return[q,W]},T={x:f,filter:m,bias:g,preluActivationWeights:b},k={strides:t,pad:n,dataFormat:o,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:p};return a==null?$n((S,N,F)=>{let $=L.runKernel(_w,T,k);return F([N,S,$]),d&&($=te($,[$.shape[1],$.shape[2],$.shape[3]])),{value:$,gradFunc:y}})(f,m):$n((S,N,F,$)=>{let O=L.runKernel(_w,T,k);return $([N,S,O,F]),d&&(O=te(O,[O.shape[1],O.shape[2],O.shape[3]])),{value:O,gradFunc:y}})(f,m,g)}var dL=E({fusedDepthwiseConv2d_:Hee});function qee({a:r,b:e,transposeA:t=!1,transposeB:n=!1,bias:o,activation:s="linear",preluActivationWeights:i,leakyreluAlpha:a}){if(Jp(L.state.gradientDepth,s)===!1){let O=gt(r,e,t,n);return o!=null&&(O=Re(O,o)),Zp(O,s,i,a)}let l=w(r,"a","fused matMul"),u=w(e,"b","fused matMul");[l,u]=Qe(l,u);let p=t?l.shape[l.rank-2]:l.shape[l.rank-1],c=n?u.shape[u.rank-1]:u.shape[u.rank-2],m=t?l.shape[l.rank-1]:l.shape[l.rank-2],f=n?u.shape[u.rank-2]:u.shape[u.rank-1],d=l.shape.slice(0,-2),h=u.shape.slice(0,-2),g=Ct(d),b=Ct(h);P(l.rank>=2&&u.rank>=2&&l.rank===u.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${l.rank} and ${u.rank}.`),P(En(d,h),()=>`Error in fused matMul: outer dimensions (${d}) and (${h}) of Tensors with shapes ${l.shape} and ${u.shape} must match.`),P(p===c,()=>`Error in fused matMul: inner shapes (${p}) and (${c}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${t} and transposeB=${n} must match.`);let y=l.shape.slice(0,-2).concat([m,f]),T=t?te(l,[g,p,m]):te(l,[g,m,p]),k=n?te(u,[b,f,c]):te(u,[b,c,f]),I;o!=null&&(I=w(o,"bias","fused matMul"),[I]=Qe(I,l),St(y,I.shape));let S;i!=null&&(S=w(i,"prelu weights","fused matMul"));let N=(O,V)=>{let[q,W,Y,Z]=V,J=Xp(te(O,Y.shape),Y,s),se,ee;if(!t&&!n?(se=gt(J,W,!1,!0),ee=gt(q,J,!0,!1)):!t&&n?(se=gt(J,W,!1,!1),ee=gt(J,q,!0,!1)):t&&!n?(se=gt(W,J,!1,!0),ee=gt(q,J,!1,!1)):(se=gt(W,J,!0,!0),ee=gt(J,q,!0,!0)),o!=null){let le=Yp(Z,J);return[se,ee,le]}else return[se,ee]},F={a:T,b:k,bias:I,preluActivationWeights:S},$={transposeA:t,transposeB:n,activation:s,leakyreluAlpha:a};return o==null?$n((V,q,W)=>{let Y=L.runKernel(vw,F,$);return W([V,q,Y]),{value:te(Y,y),gradFunc:N}})(T,k):$n((V,q,W,Y)=>{let Z=L.runKernel(vw,F,$);return Y([V,q,Z,W]),{value:te(Z,y),gradFunc:N}})(T,k,I)}var hL=E({fusedMatMul_:qee});function Xee(r){return Zx(r,.54,.46)}var bL=E({hammingWindow_:Xee});function Yee(r){return Zx(r,.5,.5)}var Jx=E({hannWindow_:Yee});function Zee(r,e,t,n=!1,o=0){let s=0,i=[];for(;s+e<=r.size;)i.push(kt(r,s,e)),s+=t;if(n)for(;s<r.size;){let a=s+e-r.size,l=Dr([kt(r,s,e-a),Vp([a],o)]);i.push(l),s+=t}return i.length===0?qp([],[0,e]):te(Dr(i),[i.length,e])}var Qx=E({frame_:Zee});function Jee(r,e,t,n,o=Jx){n==null&&(n=uL(e));let s=Qx(r,e,t),i=fe(s,o(e));return Mh(i,n)}var yL=E({stft_:Jee});function Qee(r,e,t,n,o="bilinear",s=0){let i=w(r,"image","cropAndResize"),a=w(e,"boxes","cropAndResize","float32"),l=w(t,"boxInd","cropAndResize","int32"),u=a.shape[0];P(i.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`),P(a.rank===2&&a.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${a.shape}.`),P(l.rank===1&&l.shape[0]===u,()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${a.shape}.`),P(n.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${n.length}.`),P(n[0]>=1&&n[1]>=1,()=>`cropSize must be atleast [1,1], but was ${n}`),P(o==="bilinear"||o==="nearest",()=>`method must be bilinear or nearest, but was ${o}`);let p={image:i,boxes:a,boxInd:l},c={method:o,extrapolationValue:s,cropSize:n};return L.runKernel(i2,p,c)}var xL=E({cropAndResize_:Qee});function ete(r){let e=w(r,"image","flipLeftRight","float32");P(e.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${e.rank}.`);let t={image:e};return L.runKernel(_2,t,{})}var TL=E({flipLeftRight_:ete});function tte(r,e,t=0,n=.5){let o=w(r,"image","rotateWithOffset","float32");P(o.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${o.rank}.`);let s={image:o},i={radians:e,fillValue:t,center:n};return L.runKernel(pF,s,i)}var kL=E({rotateWithOffset_:tte});function is(r,e,t,n,o,s){n==null&&(n=.5),o==null&&(o=Number.NEGATIVE_INFINITY),s==null&&(s=0);let i=r.shape[0];return t=Math.min(t,i),P(0<=n&&n<=1,()=>`iouThreshold must be in [0, 1], but was '${n}'`),P(r.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${r.rank}'`),P(r.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${r.shape[1]}`),P(e.rank===1,()=>"scores must be a 1D tensor"),P(e.shape[0]===i,()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${e.shape[0]}`),P(0<=s&&s<=1,()=>`softNmsSigma must be in [0, 1], but was '${s}'`),{maxOutputSize:t,iouThreshold:n,scoreThreshold:o,softNmsSigma:s}}function rte(r,e,t,n=.5,o=Number.NEGATIVE_INFINITY){let s=w(r,"boxes","nonMaxSuppression"),i=w(e,"scores","nonMaxSuppression"),a=is(s,i,t,n,o);t=a.maxOutputSize,n=a.iouThreshold,o=a.scoreThreshold;let l={maxOutputSize:t,iouThreshold:n,scoreThreshold:o};return L.runKernel(lM,{boxes:s,scores:i},l)}var IL=E({nonMaxSuppression_:rte});function vL(r,e,t){let n=nte(r,e,t),o=n<0?-(n+1):n;r.splice(o,0,e)}function nte(r,e,t){return ste(r,e,t||ote)}function ote(r,e){return r>e?1:r<e?-1:0}function ste(r,e,t){let n=0,o=r.length,s=0,i=!1;for(;n<o;){s=n+(o-n>>>1);let a=t(e,r[s]);a>0?n=s+1:(o=s,i=!a)}return i?n:-n-1}function eT(r,e,t,n,o){return Z_(r,e,t,n,o,0)}function tT(r,e,t,n,o,s){return Z_(r,e,t,n,o,0,!1,s,!0)}function rT(r,e,t,n,o,s){return Z_(r,e,t,n,o,s,!0)}function Z_(r,e,t,n,o,s,i=!1,a=!1,l=!1){let u=[];for(let g=0;g<e.length;g++)e[g]>o&&u.push({score:e[g],boxIndex:g,suppressBeginIndex:0});u.sort(wL);let p=s>0?-.5/s:0,c=[],m=[];for(;c.length<t&&u.length>0;){let g=u.pop(),{score:b,boxIndex:y,suppressBeginIndex:T}=g;if(b<o)break;let k=!1;for(let I=c.length-1;I>=T;--I){let S=ate(r,y,c[I]);if(S>=n){k=!0;break}if(g.score=g.score*ite(n,p,S),g.score<=o)break}g.suppressBeginIndex=c.length,k||(g.score===b?(c.push(y),m.push(g.score)):g.score>o&&vL(u,g,wL))}let f=c.length,d=t-f;a&&d>0&&(c.push(...new Array(d).fill(0)),m.push(...new Array(d).fill(0)));let h={selectedIndices:c};return i&&(h.selectedScores=m),l&&(h.validOutputs=f),h}function ate(r,e,t){let n=r.subarray(e*4,e*4+4),o=r.subarray(t*4,t*4+4),s=Math.min(n[0],n[2]),i=Math.min(n[1],n[3]),a=Math.max(n[0],n[2]),l=Math.max(n[1],n[3]),u=Math.min(o[0],o[2]),p=Math.min(o[1],o[3]),c=Math.max(o[0],o[2]),m=Math.max(o[1],o[3]),f=(a-s)*(l-i),d=(c-u)*(m-p);if(f<=0||d<=0)return 0;let h=Math.max(s,u),g=Math.max(i,p),b=Math.min(a,c),y=Math.min(l,m),T=Math.max(b-h,0)*Math.max(y-g,0);return T/(f+d-T)}function ite(r,e,t){let n=Math.exp(e*t*t);return t<=r?n:0}function wL(r,e){return r.score-e.score||r.score===e.score&&e.boxIndex-r.boxIndex}async function lte(r,e,t,n=.5,o=Number.NEGATIVE_INFINITY){let s=w(r,"boxes","nonMaxSuppressionAsync"),i=w(e,"scores","nonMaxSuppressionAsync"),a=is(s,i,t,n,o);t=a.maxOutputSize,n=a.iouThreshold,o=a.scoreThreshold;let l=await Promise.all([s.data(),i.data()]),u=l[0],p=l[1],{selectedIndices:c}=eT(u,p,t,n,o);return s!==r&&s.dispose(),i!==e&&i.dispose(),Pn(c,"int32")}var _L=lte;function ute(r,e,t,n=.5,o=Number.NEGATIVE_INFINITY,s=0){let i=w(r,"boxes","nonMaxSuppression"),a=w(e,"scores","nonMaxSuppression"),l=is(i,a,t,n,o,s);t=l.maxOutputSize,n=l.iouThreshold,o=l.scoreThreshold,s=l.softNmsSigma;let u={boxes:i,scores:a},p={maxOutputSize:t,iouThreshold:n,scoreThreshold:o,softNmsSigma:s},c=L.runKernel(pM,u,p);return{selectedIndices:c[0],selectedScores:c[1]}}var CL=E({nonMaxSuppressionWithScore_:ute});async function pte(r,e,t,n=.5,o=Number.NEGATIVE_INFINITY,s=0){let i=w(r,"boxes","nonMaxSuppressionAsync"),a=w(e,"scores","nonMaxSuppressionAsync"),l=is(i,a,t,n,o,s);t=l.maxOutputSize,n=l.iouThreshold,o=l.scoreThreshold,s=l.softNmsSigma;let u=await Promise.all([i.data(),a.data()]),p=u[0],c=u[1],{selectedIndices:m,selectedScores:f}=rT(p,c,t,n,o,s);return i!==r&&i.dispose(),a!==e&&a.dispose(),{selectedIndices:Pn(m,"int32"),selectedScores:Pn(f)}}var SL=pte;function cte(r,e,t,n=.5,o=Number.NEGATIVE_INFINITY,s=!1){let i=w(r,"boxes","nonMaxSuppression"),a=w(e,"scores","nonMaxSuppression"),l=is(i,a,t,n,o,null),u=l.maxOutputSize,p=l.iouThreshold,c=l.scoreThreshold,m={boxes:i,scores:a},f={maxOutputSize:u,iouThreshold:p,scoreThreshold:c,padToMaxOutputSize:s},d=L.runKernel(uM,m,f);return{selectedIndices:d[0],validOutputs:d[1]}}var NL=E({nonMaxSuppressionPadded_:cte});async function mte(r,e,t,n=.5,o=Number.NEGATIVE_INFINITY,s=!1){let i=w(r,"boxes","nonMaxSuppressionAsync"),a=w(e,"scores","nonMaxSuppressionAsync"),l=is(i,a,t,n,o,null),u=l.maxOutputSize,p=l.iouThreshold,c=l.scoreThreshold,[m,f]=await Promise.all([i.data(),a.data()]),{selectedIndices:d,validOutputs:h}=tT(m,f,u,p,c,s);return i!==r&&i.dispose(),a!==e&&a.dispose(),{selectedIndices:Pn(d,"int32"),validOutputs:Je(h,"int32")}}var AL=mte;function fte(r,e,t=!1,n=!1){let o=w(r,"images","resizeBilinear");P(o.rank===3||o.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${o.rank}.`),P(e.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${e}.`),P(n===!1||t===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let s=o,i=!1;o.rank===3&&(i=!0,s=te(o,[1,o.shape[0],o.shape[1],o.shape[2]]));let[]=e,a={images:s},l={alignCorners:t,halfPixelCenters:n,size:e},u=L.runKernel(wM,a,l);return i?te(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var DL=E({resizeBilinear_:fte});function dte(r,e,t=!1,n=!1){let o=w(r,"images","resizeNearestNeighbor");P(o.rank===3||o.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${o.rank}.`),P(e.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${e}.`),P(o.dtype==="float32"||o.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),P(n===!1||t===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let s=o,i=!1;o.rank===3&&(i=!0,s=te(o,[1,o.shape[0],o.shape[1],o.shape[2]]));let[]=e,a={images:s},l={alignCorners:t,halfPixelCenters:n,size:e},u=L.runKernel(vM,a,l);return i?te(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var EL=E({resizeNearestNeighbor_:dte});function hte(r,e="binary",t=!1,n=.5){let o=w(r,"image","threshold"),s=.2989,i=.587,a=.114,l=o.shape[0]*o.shape[1],u=fe(Pn([n]),255),p,c,m,f;if(P(o.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${o.rank}.`),P(o.shape[2]===3||o.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${o.shape[2]}.`),P(o.dtype==="int32"||o.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${o.dtype}.`),P(e==="otsu"||e==="binary",()=>`Method must be binary or otsu, but was ${e}`),o.shape[2]===3){[p,c,m]=Eu(o,[1,1,1],-1);let g=fe(p,s),b=fe(c,i),y=fe(m,a);f=Re(Re(g,b),y)}else f=r;if(e==="otsu"){let g=f_(ft(j_(f),"int32"),Vi([]),256);u=gte(g,l)}let d=t?Dh(f,u):qm(f,u);return ft(fe(d,255),"int32")}function gte(r,e){let t=Pn([-1]),n=Pn([0]),o=Pn([0]),s,i,a,l,u,p;for(let c=0;c<r.size-1;c++){s=kt(r,0,c+1),i=kt(r,c+1),u=ct(It(s),e),p=ct(It(i),e);let m=It(fe(s,jp(0,s.size)));a=ct(m,It(s));let f=Vp(i.shape,s.size),d=Re(jp(0,i.size),f),h=fe(i,d);l=ct(It(h),It(i));let g=We(a,l),b=We(a,l),y=fe(u,p);o=fe(fe(y,g),b);let T=qm(o,n);n=ai(T,o,n),t=ai(T,Pn([c]),t)}return t}var ML=E({threshold_:hte});function bte(r,e,t="nearest",n="constant",o=0,s){let i=w(r,"image","transform","float32"),a=w(e,"transforms","transform","float32");P(i.rank===4,()=>`Error in transform: image must be rank 4,but got rank ${i.rank}.`),P(a.rank===2&&(a.shape[0]===i.shape[0]||a.shape[0]===1)&&a.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),P(s==null||s.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${s}.`);let l={image:i,transforms:a},u={interpolation:t,fillMode:n,fillValue:o,outputShape:s};return L.runKernel(nF,l,u)}var FL=E({transform_:bte});function yte(r,e,t){P(e%1==0,()=>`bandPart(): numLower must be an integer, got ${e}.`),P(t%1==0,()=>`bandPart(): numUpper must be an integer, got ${t}.`);let n=w(r,"a","bandPart");P(n.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${n.rank}.`);let o=n.shape,[s,i]=n.shape.slice(-2);if(!(e<=s))throw new Error(`bandPart(): numLower (${e}) must not be greater than the number of rows (${s}).`);if(!(t<=i))throw new Error(`bandPart(): numUpper (${t}) must not be greater than the number of columns (${i}).`);e<0&&(e=s),t<0&&(t=i);let a=te(jp(0,s,1,"int32"),[-1,1]),l=jp(0,i,1,"int32"),u=We(a,l),p=Xm(Dh(u,Je(+e,"int32")),T_(u,Je(-t,"int32"))),c=Ji([s,i],n.dtype);return te(Mu(Rh(te(n,[-1,s,i])).map(m=>ai(p,m,c))),o)}var RL=E({bandPart_:yte});function xte(r){let e;if(Array.isArray(r)){e=!1,P(r!=null&&r.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let o=r[0].shape[0];for(let s=1;s<r.length;++s)P(r[s].shape[0]===o,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${r[s].shape[0]} vs. ${o})`)}else e=!0,r=Eu(r,r.shape[0],0).map(o=>Fh(o,[0]));P(r.length<=r[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${r.length}) exceeds number of dimensions (${r[0].shape[0]}).`);let t=[],n=r;for(let o=0;o<r.length;++o)t.push(L.tidy(()=>{let s=n[o];if(o>0)for(let i=0;i<o;++i){let a=fe(It(fe(t[i],s)),t[i]);s=We(s,a)}return ct(s,Yx(s,"euclidean"))}));return e?Mu(t,0):t}var LL=E({gramSchmidt_:xte});function Tte(r,e=!1){if(P(r.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${r.rank}`),r.rank===2)return $L(r,e);{let t=r.shape.slice(0,r.shape.length-2).reduce((l,u)=>l*u),n=Rh(te(r,[t,r.shape[r.shape.length-2],r.shape[r.shape.length-1]]),0),o=[],s=[];n.forEach(l=>{let[u,p]=$L(l,e);o.push(u),s.push(p)});let i=te(Mu(o,0),r.shape),a=te(Mu(s,0),r.shape);return[i,a]}}function $L(r,e=!1){return L.tidy(()=>{P(r.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${r.shape.length}D Tensor.`);let t=r.shape[0],n=r.shape[1],o=b_(t),s=Os(r),i=qp([[1]],[1,1]),a=Os(i),l=t>=n?n:t;for(let u=0;u<l;++u){let p=s,c=a,m=o;[a,s,o]=L.tidy(()=>{let f=kt(s,[u,u],[t-u,1]),d=Yx(f),h=kt(s,[u,u],[1,1]),g=ai(qm(h,0),qp([[-1]]),qp([[1]])),b=We(h,fe(g,d)),y=ct(f,b);y.shape[0]===1?a=Os(i):a=Dr([i,kt(y,[1,0],[y.shape[0]-1,y.shape[1]])],0);let T=Ao(ct(gt(g,b),d)),k=kt(s,[u,0],[t-u,n]),I=fe(T,a),S=_h(a);if(u===0)s=We(k,gt(I,gt(S,k)));else{let $=We(k,gt(I,gt(S,k)));s=Dr([kt(s,[0,0],[u,n]),$],0)}let N=_h(I),F=kt(o,[0,u],[t,o.shape[1]-u]);if(u===0)o=We(F,gt(gt(F,a),N));else{let $=We(F,gt(gt(F,a),N));o=Dr([kt(o,[0,0],[t,u]),$],1)}return[a,s,o]}),$r([p,c,m])}return!e&&t>n&&(o=kt(o,[0,0],[t,n]),s=kt(s,[0,0],[n,n])),[o,s]})}var PL=E({qr_:Tte});var gr;(function(o){o[o.NONE=0]="NONE",o[o.MEAN=1]="MEAN",o[o.SUM=2]="SUM",o[o.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"})(gr||(gr={}));function kte(r,e,t=gr.SUM_BY_NONZERO_WEIGHTS){let n=w(r,"losses","computeWeightedLoss"),o=null;e!=null&&(o=w(e,"weights","computeWeightedLoss"));let s=o==null?n:fe(n,o);if(t===gr.NONE)return s;if(t===gr.SUM)return It(s);if(t===gr.MEAN){if(o==null)return Ym(s);{let i=n.size/o.size,a=ct(It(s),It(o));return i>1?ct(a,Je(i)):a}}if(t===gr.SUM_BY_NONZERO_WEIGHTS){if(o==null)return ct(It(s),Je(n.size));{let i=fe(o,Qi(n.shape)),a=ft(It(M_(i,Je(0))),"float32");return ct(It(s),a)}}throw Error(`Unknown reduction: ${t}`)}var cn=E({computeWeightedLoss_:kte});function Ite(r,e,t,n=gr.SUM_BY_NONZERO_WEIGHTS){let o=w(r,"labels","absoluteDifference"),s=w(e,"predictions","absoluteDifference"),i=null;t!=null&&(i=w(t,"weights","absoluteDifference")),Jt(o.shape,s.shape,"Error in absoluteDifference: ");let a=un(We(o,s));return cn(a,i,n)}var BL=E({absoluteDifference_:Ite});function vte(r,e,t,n,o=gr.SUM_BY_NONZERO_WEIGHTS){let s=w(r,"labels","cosineDistance"),i=w(e,"predictions","cosineDistance"),a=null;n!=null&&(a=w(n,"weights","cosineDistance")),Jt(s.shape,i.shape,"Error in cosineDistance: ");let l=Je(1),u=We(l,It(fe(s,i),t,!0));return cn(u,a,o)}var OL=E({cosineDistance_:vte});function wte(r,e,t,n=gr.SUM_BY_NONZERO_WEIGHTS){let o=w(r,"labels","hingeLoss"),s=w(e,"predictions","hingeLoss"),i=null;t!=null&&(i=w(t,"weights","hingeLoss")),Jt(o.shape,s.shape,"Error in hingeLoss: ");let a=Je(1);o=We(fe(Je(2),o),a);let l=Hp(We(a,fe(o,s)));return cn(l,i,n)}var zL=E({hingeLoss_:wte});function _te(r,e,t,n=1,o=gr.SUM_BY_NONZERO_WEIGHTS){let s=w(r,"labels","huberLoss"),i=w(e,"predictions","huberLoss"),a=null;t!=null&&(a=w(t,"weights","huberLoss")),Jt(s.shape,i.shape,"Error in huberLoss: ");let l=Je(n),u=un(We(i,s)),p=E_(u,l),c=We(u,p),m=Re(fe(Je(.5),pn(p)),fe(l,c));return cn(m,a,o)}var GL=E({huberLoss_:_te});function Cte(r,e,t,n=1e-7,o=gr.SUM_BY_NONZERO_WEIGHTS){let s=w(r,"labels","logLoss"),i=w(e,"predictions","logLoss"),a=null;t!=null&&(a=w(t,"weights","logLoss")),Jt(s.shape,i.shape,"Error in logLoss: ");let l=Je(1),u=Je(n),p=Ao(fe(s,Au(Re(i,u)))),c=fe(We(l,s),Au(Re(We(l,i),u))),m=We(p,c);return cn(m,a,o)}var WL=E({logLoss_:Cte});function Ste(r,e,t,n=gr.SUM_BY_NONZERO_WEIGHTS){let o=w(r,"labels","meanSquaredError"),s=w(e,"predictions","meanSquaredError"),i=null;t!=null&&(i=w(t,"weights","meanSquaredError")),Jt(o.shape,s.shape,"Error in meanSquaredError: ");let a=q_(o,s);return cn(a,i,n)}var KL=E({meanSquaredError_:Ste});function Nte(r,e){let t=w(r,"labels","sigmoidCrossEntropyWithLogits"),n=w(e,"logits","sigmoidCrossEntropyWithLogits");Jt(t.shape,n.shape,"Error in sigmoidCrossEntropyWithLogits: ");let o=Hp(n),s=fe(n,t),i=I_(zs(Ao(un(n))));return Re(We(o,s),i)}function Ate(r,e,t,n=0,o=gr.SUM_BY_NONZERO_WEIGHTS){let s=w(r,"multiClassLabels","sigmoidCrossEntropy"),i=w(e,"logits","sigmoidCrossEntropy"),a=null;if(t!=null&&(a=w(t,"weights","sigmoidCrossEntropy")),Jt(s.shape,i.shape,"Error in sigmoidCrossEntropy: "),n>0){let u=Je(n),p=Je(1),c=Je(.5);s=Re(fe(s,We(p,u)),fe(c,u))}let l=Nte(s,i);return cn(l,a,o)}var VL=E({sigmoidCrossEntropy_:Ate});function Dte(r,e,t=-1){if(t===-1&&(t=e.rank-1),t!==e.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${e.rank} and dim was ${t}`);return $n((o,s,i)=>{let l=C_(s,[t],!0),u=We(ft(s,"float32"),l);i([o,u]);let p=Ao(fe(u,o));return{value:It(p,[t]),gradFunc:(f,d)=>{let[h,g]=d,b=Zi(f.shape,[t]);return[fe(te(f,b),We(ft(h,"float32"),zs(g))),fe(te(f,b),We(zs(g),ft(h,"float32")))]}}})(r,e)}function Ete(r,e,t,n=0,o=gr.SUM_BY_NONZERO_WEIGHTS){let s=w(r,"onehotLabels","softmaxCrossEntropy"),i=w(e,"logits","softmaxCrossEntropy"),a=null;if(t!=null&&(a=w(t,"weights","softmaxCrossEntropy")),Jt(s.shape,i.shape,"Error in softmaxCrossEntropy: "),n>0){let u=Je(n),p=Je(1),c=Je(s.shape[1]);s=Re(fe(s,We(p,u)),ct(u,c))}let l=Dte(s,i);return cn(l,a,o)}var UL=E({softmaxCrossEntropy_:Ete});function Mte(r,e,t,n){let o=w(r,"indices","sparseFillEmptyRows"),s=w(e,"values","sparseFillEmptyRows"),i=w(t,"denseShape","sparseFillEmptyRows"),a=w(n,"defaultValue","sparseFillEmptyRows",s.dtype);if(o.rank!==2)throw new Error(`Indices should be Tensor2D but received shape
|
|
${o.shape}`);if(s.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${s.shape}`);if(i.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${i.shape}`);if(a.rank!==0)throw new Error(`Default value should be a scalar but received shape ${a.shape}`);let l={indices:o,values:s,denseShape:i,defaultValue:a},u=L.runKernel(KM,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}var jL=E({sparseFillEmptyRows_:Mte});function Fte(r,e,t){let n=w(r,"inputIndices","sparseReshape"),o=w(e,"inputShape","sparseReshape"),s=w(t,"newShape","sparseReshape");if(n.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape
|
|
${n.shape}`);if(o.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${o.shape}`);if(s.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${s.shape}`);let i={inputIndices:n,inputShape:o,newShape:s},a=L.runKernel(VM,i);return{outputIndices:a[0],outputShape:a[1]}}var HL=E({sparseReshape_:Fte});function Rte(r,e,t){let n=w(r,"data","sparseSegmentMean"),o=w(e,"indices","sparseSegmentMean"),s=w(t,"segmentIds","sparseSegmentMean");if(n.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
|
|
${o.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
|
|
${s.shape}`);let i={data:n,indices:o,segmentIds:s};return L.runKernel(UM,i)}var qL=E({sparseSegmentMean_:Rte});function Lte(r,e,t){let n=w(r,"data","sparseSegmentSum"),o=w(e,"indices","sparseSegmentSum"),s=w(t,"segmentIds","sparseSegmentSum");if(n.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
|
|
${o.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
|
|
${s.shape}`);let i={data:n,indices:o,segmentIds:s};return L.runKernel(jM,i)}var XL=E({sparseSegmentSum_:Lte});function $te(r,e,t,n,o,s,i,a){let l=w(r,"data","stringNGrams","string");if(l.dtype!=="string")throw new Error("Data must be of datatype string");if(l.shape.length!==1)throw new Error(`Data must be a vector, saw: ${l.shape}`);let u=w(e,"dataSplits","stringNGrams");if(u.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let p={separator:t,nGramWidths:n,leftPad:o,rightPad:s,padWidth:i,preserveShortSequences:a},c={data:l,dataSplits:u},m=L.runKernel(YM,c,p);return{nGrams:m[0],nGramsSplits:m[1]}}var YL=E({stringNGrams_:$te});function Pte(r,e,t=!0){let n=w(r,"input","stringSplit","string"),o=w(e,"delimiter","stringSplit","string");if(n.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${n.shape}`);if(o.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${o.shape}`);let s={skipEmpty:t},i={input:n,delimiter:o},a=L.runKernel(ZM,i,s);return{indices:a[0],values:a[1],shape:a[2]}}var ZL=E({stringSplit_:Pte});function Bte(r,e){let t=w(r,"input","stringToHashBucketFast","string"),n={numBuckets:e};if(e<=0)throw new Error("Number of buckets must be at least 1");let o={input:t};return L.runKernel(JM,o,n)}var JL=E({stringToHashBucketFast_:Bte});var W9e={fft:Eh,ifft:Qm,rfft:Mh,irfft:H_},H9e={hammingWindow:bL,hannWindow:Jx,frame:Qx,stft:yL},iZe={flipLeftRight:TL,resizeNearestNeighbor:EL,resizeBilinear:DL,rotateWithOffset:kL,cropAndResize:xL,nonMaxSuppression:IL,nonMaxSuppressionAsync:_L,nonMaxSuppressionWithScore:CL,nonMaxSuppressionWithScoreAsync:SL,nonMaxSuppressionPadded:NL,nonMaxSuppressionPaddedAsync:AL,threshold:ML,transform:FL},cZe={bandPart:RL,gramSchmidt:LL,qr:PL},kZe={absoluteDifference:BL,computeWeightedLoss:cn,cosineDistance:OL,hingeLoss:zL,huberLoss:GL,logLoss:WL,meanSquaredError:KL,sigmoidCrossEntropy:VL,softmaxCrossEntropy:UL},CZe={sparseFillEmptyRows:jL,sparseReshape:HL,sparseSegmentMean:qL,sparseSegmentSum:XL},DZe={stringNGrams:YL,stringSplit:ZL,stringToHashBucketFast:JL};var ro=class extends Ox{minimize(e,t=!1,n){let{value:o,grads:s}=this.computeGradients(e,n);if(n!=null){let i=n.map(a=>({name:a.name,tensor:s[a.name]}));this.applyGradients(i)}else this.applyGradients(s);return $r(s),t?o:(o.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return v_(e,t)}dispose(){this.iterations_!=null&&$r(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Je(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(ro,Symbol.hasInstance,{value:r=>r.minimize!=null&&r.computeGradients!=null&&r.applyGradients!=null});var Qp=class extends ro{constructor(e,t,n=null){super();this.learningRate=e;this.rho=t;this.epsilon=n;this.accumulatedGrads=[];this.accumulatedUpdates=[];n==null&&(this.epsilon=L.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,o)=>{let s=L.registeredVariables[n],i=!1;this.accumulatedGrads[o]==null&&(this.accumulatedGrads[o]={originalName:`${n}/accum_grad`,variable:mr(()=>qr(s).variable(i))}),this.accumulatedUpdates[o]==null&&(this.accumulatedUpdates[o]={originalName:`${n}/accum_var`,variable:mr(()=>qr(s).variable(i))});let a=Array.isArray(e)?e[o].tensor:e[n];if(a==null)return;let l=this.accumulatedGrads[o].variable,u=this.accumulatedUpdates[o].variable;mr(()=>{let p=Re(fe(l,this.rho),fe(pn(a),1-this.rho)),c=fe(ct(To(Re(u,this.epsilon)),To(Re(l,this.epsilon))),a),m=Re(fe(u,this.rho),fe(pn(c),1-this.rho));l.assign(p),u.assign(m);let f=Re(fe(c,-this.learningRate),s);s.assign(f)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&($r(this.accumulatedGrads.map(e=>e.variable)),$r(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){let 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);let t=e.length/2,n=!1;this.accumulatedGrads=e.slice(0,t).map(o=>({originalName:o.name,variable:o.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,t*2).map(o=>({originalName:o.name,variable:o.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}};Qp.className="Adadelta";to(Qp);var ec=class extends ro{constructor(e,t=.1){super();this.learningRate=e;this.initialAccumulatorValue=t;this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,o)=>{let s=L.registeredVariables[n];if(this.accumulatedGrads[o]==null){let l=!1;this.accumulatedGrads[o]={originalName:`${n}/accumulator`,variable:mr(()=>Vp(s.shape,this.initialAccumulatorValue).variable(l))}}let i=Array.isArray(e)?e[o].tensor:e[n];if(i==null)return;let a=this.accumulatedGrads[o].variable;mr(()=>{let l=Re(a,pn(i));a.assign(l);let u=Re(fe(ct(i,To(Re(l,L.backend.epsilon()))),-this.learningRate),s);s.assign(u)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&$r(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);let t=!1;this.accumulatedGrads=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}};ec.className="Adagrad";to(ec);var tc=class extends ro{constructor(e,t,n,o=null){super();this.learningRate=e;this.beta1=t;this.beta2=n;this.epsilon=o;this.accumulatedFirstMoment=[];this.accumulatedSecondMoment=[];mr(()=>{this.accBeta1=Je(t).variable(),this.accBeta2=Je(n).variable()}),o==null&&(this.epsilon=L.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);mr(()=>{let n=We(1,this.accBeta1),o=We(1,this.accBeta2);t.forEach((s,i)=>{let a=L.registeredVariables[s],l=!1;this.accumulatedFirstMoment[i]==null&&(this.accumulatedFirstMoment[i]={originalName:`${s}/m`,variable:mr(()=>qr(a).variable(l))}),this.accumulatedSecondMoment[i]==null&&(this.accumulatedSecondMoment[i]={originalName:`${s}/v`,variable:mr(()=>qr(a).variable(l))});let u=Array.isArray(e)?e[i].tensor:e[s];if(u==null)return;let p=this.accumulatedFirstMoment[i].variable,c=this.accumulatedSecondMoment[i].variable,m=Re(fe(p,this.beta1),fe(u,1-this.beta1)),f=Re(fe(c,this.beta2),fe(pn(u),1-this.beta2)),d=ct(m,n),h=ct(f,o);p.assign(m),c.assign(f);let g=Re(fe(ct(d,Re(To(h),this.epsilon)),-this.learningRate),a);a.assign(g)}),this.accBeta1.assign(fe(this.accBeta1,this.beta1)),this.accBeta2.assign(fe(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&$r(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&$r(this.accumulatedSecondMoment.map(e=>e.variable))}async getWeights(){let 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),mr(()=>{this.accBeta1.assign(Du(this.beta1,this.iterations_+1)),this.accBeta2.assign(Du(this.beta2,this.iterations_+1))});let t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(o=>({originalName:o.name,variable:o.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(o=>({originalName:o.name,variable:o.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}};tc.className="Adam";to(tc);var rc=class extends ro{constructor(e,t,n,o=null,s=0){super();this.learningRate=e;this.beta1=t;this.beta2=n;this.epsilon=o;this.decay=s;this.accumulatedFirstMoment=[];this.accumulatedWeightedInfNorm=[];mr(()=>{this.iteration=Je(0).variable(),this.accBeta1=Je(t).variable()}),o==null&&(this.epsilon=L.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);mr(()=>{let n=We(1,this.accBeta1),o=ct(-this.learningRate,Re(fe(this.iteration,this.decay),1));t.forEach((s,i)=>{let a=L.registeredVariables[s],l=!1;this.accumulatedFirstMoment[i]==null&&(this.accumulatedFirstMoment[i]={originalName:`${s}/m`,variable:qr(a).variable(l)}),this.accumulatedWeightedInfNorm[i]==null&&(this.accumulatedWeightedInfNorm[i]={originalName:`${s}/v`,variable:qr(a).variable(l)});let u=Array.isArray(e)?e[i].tensor:e[s];if(u==null)return;let p=this.accumulatedFirstMoment[i].variable,c=this.accumulatedWeightedInfNorm[i].variable,m=Re(fe(p,this.beta1),fe(u,1-this.beta1)),f=fe(c,this.beta2),d=un(u),h=D_(f,d);p.assign(m),c.assign(h);let g=Re(fe(ct(o,n),ct(m,Re(h,this.epsilon))),a);a.assign(g)}),this.iteration.assign(Re(this.iteration,1)),this.accBeta1.assign(fe(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&$r(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&$r(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)}};rc.className="Adamax";to(rc);var tl=class extends ro{constructor(e){super();this.learningRate=e;this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,o)=>{let s=Array.isArray(e)?e[o].tensor:e[n];if(s==null)return;let i=L.registeredVariables[n];mr(()=>{let a=Re(fe(this.c,s),i);i.assign(a)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=zR(Je(-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)}};tl.className="SGD";to(tl);var nc=class extends tl{constructor(e,t,n=!1){super(e);this.learningRate=e;this.momentum=t;this.useNesterov=n;this.accumulations=[];this.m=Je(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,o)=>{let s=L.registeredVariables[n];if(this.accumulations[o]==null){let l=!1;this.accumulations[o]={originalName:`${n}/momentum`,variable:mr(()=>qr(s).variable(l))}}let i=this.accumulations[o].variable,a=Array.isArray(e)?e[o].tensor:e[n];a!=null&&mr(()=>{let l,u=Re(fe(this.m,i),a);this.useNesterov?l=Re(fe(this.c,Re(a,fe(u,this.m))),s):l=Re(fe(this.c,u),s),i.assign(u),s.assign(l)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&$r(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);let t=!1;this.accumulations=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}};nc.className="Momentum";to(nc);var oc=class extends ro{constructor(e,t=.9,n=0,o=null,s=!1){super();this.learningRate=e;this.decay=t;this.momentum=n;this.epsilon=o;this.accumulatedMeanSquares=[];this.accumulatedMoments=[];this.accumulatedMeanGrads=[];if(this.centered=s,o==null&&(this.epsilon=L.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,o)=>{let s=L.registeredVariables[n],i=!1;this.accumulatedMeanSquares[o]==null&&(this.accumulatedMeanSquares[o]={originalName:`${n}/rms`,variable:mr(()=>qr(s).variable(i))}),this.accumulatedMoments[o]==null&&(this.accumulatedMoments[o]={originalName:`${n}/momentum`,variable:mr(()=>qr(s).variable(i))}),this.accumulatedMeanGrads[o]==null&&this.centered&&(this.accumulatedMeanGrads[o]={originalName:`${n}/mg`,variable:mr(()=>qr(s).variable(i))});let a=Array.isArray(e)?e[o].tensor:e[n];if(a==null)return;let l=this.accumulatedMeanSquares[o].variable,u=this.accumulatedMoments[o].variable;mr(()=>{let p=Re(fe(l,this.decay),fe(pn(a),1-this.decay));if(this.centered){let c=this.accumulatedMeanGrads[o].variable,m=Re(fe(c,this.decay),fe(a,1-this.decay)),f=ct(fe(a,this.learningRate),To(We(p,Re(pn(m),this.epsilon)))),d=Re(fe(u,this.momentum),f);l.assign(p),c.assign(m),u.assign(d);let h=We(s,d);s.assign(h)}else{let c=Re(fe(l,this.decay),fe(pn(a),1-this.decay)),m=Re(fe(u,this.momentum),ct(fe(a,this.learningRate),To(Re(c,this.epsilon))));l.assign(c),u.assign(m);let f=We(s,m);s.assign(f)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&$r(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&$r(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&$r(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){let 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);let t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map(o=>({originalName:o.name,variable:o.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,t*2).map(o=>({originalName:o.name,variable:o.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(o=>({originalName:o.name,variable:o.tensor.variable(n)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}};oc.className="RMSProp";to(oc);var rl=class{static sgd(e){return new tl(e)}static momentum(e,t,n=!1){return new nc(e,t,n)}static rmsprop(e,t=.9,n=0,o=null,s=!1){return new oc(e,t,n,o,s)}static adam(e=.001,t=.9,n=.999,o=null){return new tc(e,t,n,o)}static adadelta(e=.001,t=.95,n=null){return new Qp(e,t,n)}static adamax(e=.002,t=.9,n=.999,o=null,s=0){return new rc(e,t,n,o,s)}static adagrad(e,t=.1){return new ec(e,t)}};var Ant={sgd:rl.sgd,momentum:rl.momentum,adadelta:rl.adadelta,adagrad:rl.adagrad,rmsprop:rl.rmsprop,adamax:rl.adamax,adam:rl.adam};var Ote=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:r=>r())();function zte(){return new Promise(r=>Ote(()=>r()))}var t$={};Ge(t$,{ERF_A1:()=>Qte,ERF_A2:()=>ere,ERF_A3:()=>tre,ERF_A4:()=>rre,ERF_A5:()=>nre,ERF_P:()=>Jte,PARALLELIZE_THRESHOLD:()=>nT,SELU_SCALE:()=>Zte,SELU_SCALEALPHA:()=>Yte,applyActivation:()=>Zp,assertAndGetBroadcastShape:()=>St,assertAxesAreInnerMostDims:()=>uJ,assertParamsConsistent:()=>Gte,assignToTypedArray:()=>cre,axesAreInnerMostDims:()=>__,calculateShapes:()=>vR,checkEinsumDimSizes:()=>bre,combineLocations:()=>UR,complexWithEvenIndex:()=>lre,complexWithOddIndex:()=>ure,computeConv2DInfo:()=>Op,computeConv3DInfo:()=>GR,computeDefaultPad:()=>u_,computeDilation2DInfo:()=>e9,computeOptimalWindowSize:()=>Kte,computeOutAndReduceShapes:()=>lJ,computeOutShape:()=>Wte,computePool2DInfo:()=>l_,computePool3DInfo:()=>t9,convertConv2DDataFormat:()=>WR,decodeEinsumEquation:()=>hre,eitherStridesOrDilationsAreOne:()=>Tn,expandShapeToKeepDim:()=>Zi,exponent:()=>fre,exponents:()=>mre,fromStringArrayToUint8:()=>Cre,fromUint8ToStringArray:()=>_re,getAxesPermutation:()=>pJ,getBroadcastDims:()=>pZ,getComplexWithIndex:()=>pre,getEinsumComputePath:()=>yre,getEinsumPermutation:()=>gre,getFusedBiasGradient:()=>Yp,getFusedDyActivation:()=>Xp,getImageCenter:()=>Vte,getInnerMostAxes:()=>mJ,getPermuted:()=>jte,getReductionAxes:()=>d_,getReshaped:()=>Ute,getReshapedPermuted:()=>Hte,getSliceBeginCoords:()=>qte,getSliceSize:()=>Xte,getUndoAxesPermutation:()=>cJ,isIdentityPermutation:()=>xre,log:()=>sre,mergeRealAndImagArrays:()=>are,prepareAndValidate:()=>kR,prepareSplitSize:()=>kre,segment_util:()=>Q_,shouldFuse:()=>Jp,slice_util:()=>Bx,splitRealAndImagArrays:()=>ire,tupleValuesAreOne:()=>Gp,upcastType:()=>Wm,validateInput:()=>$x,validateUpdateShape:()=>o_,warn:()=>ore});function Gte(r,e){let t=r[0].length;r.forEach((o,s)=>{P(o.length===t,()=>`Error in concat${t}D: rank of tensors[${s}] must be the same as the rank of the rest (${t})`)}),P(e>=0&&e<t,()=>`Error in concat${t}D: axis must be between 0 and ${t-1}.`);let n=r[0];r.forEach((o,s)=>{for(let i=0;i<t;i++)P(i===e||o[i]===n[i],()=>`Error in concat${t}D: Shape of tensors[${s}] (${o}) does not match the shape of the rest (${n}) along the non-concatenated axis ${s}.`)})}function Wte(r,e){let t=r[0].slice();for(let n=1;n<r.length;n++)t[e]+=r[n][e];return t}var nT=30;function Kte(r){return r<=nT?r:Rm(r,Math.floor(Math.sqrt(r)))}function Vte(r,e,t){let n=t*(typeof r=="number"?r:r[0]),o=e*(typeof r=="number"?r:r[1]);return[n,o]}function Ute(r,e,t,n=!0){let o=[];if(n)o=o.concat(e.slice(0)),o.push(r[0]/t),o=o.concat(r.slice(1));else{o=o.concat(r[0]);let s=e.length;for(let i=0;i<s;++i)o=o.concat([r[i+1]/e[i],e[i]]);o=o.concat(r.slice(s+1))}return o}function jte(r,e,t=!0){let n=[];if(t){n.push(e);for(let o=e+1;o<r;++o)o<=2*e?(n.push(o),n.push(o-(e+1))):n.push(o)}else{let o=[],s=[];for(let i=1;i<r;++i)i>=e*2+1||i%2==1?s.push(i):o.push(i);n.push(...o),n.push(0),n.push(...s)}return n}function Hte(r,e,t,n=!0){let o=[];n?o.push(r[0]/t):o.push(r[0]*t);for(let s=1;s<r.length;++s)s<=e.length?n?o.push(e[s-1]*r[s]):o.push(r[s]/e[s-1]):o.push(r[s]);return o}function qte(r,e){let t=[0];for(let n=0;n<e;++n)t.push(r[n][0]);return t}function Xte(r,e,t){let n=r.slice(0,1);for(let o=0;o<t;++o)n.push(r[o+1]-e[o][0]-e[o][1]);return n}var Yte=1.7580993408473768,Zte=1.0507009873554805;var Jte=.3275911,Qte=.254829592,ere=-.284496736,tre=1.421413741,rre=-1.453152027,nre=1.061405429;function ore(...r){Ze().getBool("IS_TEST")||console.warn(...r)}function sre(...r){Ze().getBool("IS_TEST")||console.log(...r)}function are(r,e){if(r.length!==e.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${r.length}, imag: ${e.length}.`);let t=new Float32Array(r.length*2);for(let n=0;n<t.length;n+=2)t[n]=r[n/2],t[n+1]=e[n/2];return t}function ire(r){let e=new Float32Array(r.length/2),t=new Float32Array(r.length/2);for(let n=0;n<r.length;n+=2)e[n/2]=r[n],t[n/2]=r[n+1];return{real:e,imag:t}}function lre(r){let e=Math.ceil(r.length/4),t=new Float32Array(e),n=new Float32Array(e);for(let o=0;o<r.length;o+=4)t[Math.floor(o/4)]=r[o],n[Math.floor(o/4)]=r[o+1];return{real:t,imag:n}}function ure(r){let e=Math.floor(r.length/4),t=new Float32Array(e),n=new Float32Array(e);for(let o=2;o<r.length;o+=4)t[Math.floor(o/4)]=r[o],n[Math.floor(o/4)]=r[o+1];return{real:t,imag:n}}function pre(r,e){let t=r[e*2],n=r[e*2+1];return{real:t,imag:n}}function cre(r,e,t,n){r[n*2]=e,r[n*2+1]=t}function mre(r,e){let t=new Float32Array(r/2),n=new Float32Array(r/2);for(let o=0;o<Math.ceil(r/2);o++){let s=(e?2:-2)*Math.PI*(o/r);t[o]=Math.cos(s),n[o]=Math.sin(s)}return{real:t,imag:n}}function fre(r,e,t){let n=(t?2:-2)*Math.PI*(r/e),o=Math.cos(n),s=Math.sin(n);return{real:o,imag:s}}var J_="->",dre=/->/g,QL=",",e$="...";function hre(r,e){r=r.replace(/\s/g,"");let t=(r.length-r.replace(dre,"").length)/J_.length;if(t<1)throw new Error("Equations without an arrow are not supported.");if(t>1)throw new Error(`Equation must contain exactly one arrow ("${J_}").`);let[n,o]=r.split(J_);P(n.indexOf(e$)===-1,()=>`The ellipsis notation ("${e$}") is not supported yet.`);let s=n.split(QL),i=s.length;if(e!==i)throw new Error(`Expected ${i} input tensors, received ${e}`);if(i>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");let a=[];for(let m=0;m<o.length;++m){let f=o[m];if(!s.some(d=>d.indexOf(f)!==-1))throw new Error(`Output subscripts contain the label ${f} not present in the input subscripts.`);a.indexOf(f)===-1&&a.push(f)}for(let m=0;m<n.length;++m){let f=n[m];a.indexOf(f)===-1&&f!==QL&&a.push(f)}let l=new Array(s.length);for(let m=0;m<i;++m){if(new Set(s[m].split("")).size!==s[m].length)throw new Error(`Found duplicate axes in input component ${s[m]}. Support for duplicate axes in input is not implemented yet.`);l[m]=[];for(let f=0;f<s[m].length;++f)l[m].push(a.indexOf(s[m][f]))}let u=a.length,p=o.length,c=[];for(let m=p;m<u;++m)c.push(m);return{allDims:a,summedDims:c,idDims:l}}function gre(r,e){let t=new Array(r);t.fill(-1);for(let o=0;o<e.length;++o)t[e[o]]=o;let n=[];for(let o=0;o<r;++o)t[o]===-1&&n.push(o);return t=t.filter(o=>o!==-1),{permutationIndices:t,expandDims:n}}function bre(r,e,t){let n=new Array(r);for(let o=0;o<t.length;++o){let s=t[o].shape;for(let i=0;i<e[o].length;++i)n[e[o][i]]===void 0?n[e[o][i]]=s[i]:P(n[e[o][i]]===s[i],()=>`Expected dimension ${n[e[o][i]]} at axis ${i} of input shaped ${JSON.stringify(s)}, but got dimension ${s[i]}`)}}function yre(r,e){let t=r,n=[],o=0;r.length===0&&t.push(-1),o=r.length+1;for(let i=0;i<o;++i)n.push([]);let s=[];for(let i=0;i<t.length;++i){let a=t[i],l=Tre(e,a);for(let u of l)s.indexOf(u)===-1&&(n[i].push(u),s.push(u))}return{path:t,steps:n}}function xre(r){return r.every((e,t)=>e===t)}function Tre(r,e){let t=[];for(let n=0;n<r.length;++n)(r[n].length===0||r[n].indexOf(e)!==-1||e===-1)&&t.push(n);return t}function kre(r,e,t=0){let n=[];if(typeof e=="number")P(r.shape[t]%e==0,()=>"Number of splits must evenly divide the axis."),n=new Array(e).fill(r.shape[t]/e);else{let o=e.reduce((i,a)=>(a===-1&&(i+=1),i),0);P(o<=1,()=>"There should be only one negative value in split array.");let s=e.indexOf(-1);if(s!==-1){let i=e.reduce((a,l)=>l>0?a+l:a);e[s]=r.shape[t]-i}P(r.shape[t]===e.reduce((i,a)=>i+a),()=>"The sum of sizes must match the size of the axis dimension."),n=e}return n}var Q_={};Ge(Q_,{collectGatherOpShapeInfo:()=>wre,computeOutShape:()=>vre,segOpComputeOptimalWindowSize:()=>Ire});function Ire(r,e){let t=!1,n;for(r<=nT?(n=r,t=!0):n=Rm(r,Math.floor(Math.sqrt(r)));!t;)n>e||n===r?t=!0:n=Rm(r,n+1);return n}function vre(r,e,t){let n=[],o=r.length;for(let s=0;s<o;s++)s!==e?n.push(r[s]):n.push(t);return n}function wre(r,e,t,n){let o=e.shape.length,s=r.shape.length;if(n!==0&&(n<-o||n>o))throw new Error(`Expect batchDims in the range of [-${o}, ${o}], but got ${n}`);if(n<0&&(n+=o),n>s)throw new Error(`batchDims (${n}) must be less than rank(x) (
|
|
${s}).`);if(t<n)throw new Error(`batchDims (${n}) must be less than or equal to axis (${t}).`);for(let c=0;c<n;++c)if(r.shape[c]!==e.shape[c])throw new Error(`x.shape[${c}]: ${r.shape[c]} should be equal to indices.shape[${c}]: ${e.shape[c]}.`);let i=r.shape[t],a=[],l=1,u=1,p=1;for(let c=0;c<n;++c)a.push(r.shape[c]),l*=r.shape[c];for(let c=n;c<t;c++)a.push(r.shape[c]),u*=r.shape[c];for(let c=n;c<o;c++)a.push(e.shape[c]);for(let c=t+1;c<s;c++)a.push(r.shape[c]),p*=r.shape[c];return{batchSize:l,sliceSize:p,outerSize:u,dimSize:i,outputShape:a}}function _re(r){try{return r.map(e=>zm(e))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function Cre(r){return r.map(e=>_u(e))}var r$={};Ge(r$,{nonMaxSuppressionV3Impl:()=>eT,nonMaxSuppressionV4Impl:()=>tT,nonMaxSuppressionV5Impl:()=>rT,whereImpl:()=>Xx});var Sre=1e-7,Nre=1e-4,Fu=class{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}},ii=class{refCount(e){return ls("refCount")}incRef(e){return ls("incRef")}timerAvailable(){return!0}time(e){return ls("time")}read(e){return ls("read")}readSync(e){return ls("readSync")}numDataIds(){return ls("numDataIds")}disposeData(e,t){return ls("disposeData")}write(e,t,n){return ls("write")}move(e,t,n,o,s){return ls("move")}memory(){return ls("memory")}floatPrecision(){return ls("floatPrecision")}epsilon(){return this.floatPrecision()===32?Sre:Nre}dispose(){return ls("dispose")}};function ls(r){throw new Error(`'${r}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function n$(r){let e=r.length,t=0,n=0;for(;e>0;)n=Math.random()*e|0,e--,t=r[e],r[e]=r[n],r[n]=t}function Are(r,e){if(r.length!==e.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${r.length}Second array length was ${e.length}`);let t=r.length,n,o,s=0;for(;t>0;)s=Math.random()*t|0,t--,n=r[t],o=e[t],r[t]=r[s],e[t]=e[s],r[s]=n,e[s]=o}function ef(r,e,t){return Math.max(r,Math.min(e,t))}function Dre(r){return r%2==0?r:r+1}function Ere(r){let e=0;for(let t=0;t<r.length;t++)e+=r[t];return e}function Mre(r,e){let t=Math.random();return e*t+(1-t)*r}function Fre(r,e){let t=0;for(let n=0;n<r.length;n++){let o=Number(r[n])-Number(e[n]);t+=o*o}return t}function R(r,e){if(!r)throw new Error(typeof e=="string"?e:e())}function Er(r,e,t=""){R(no(r,e),()=>t+` Shapes ${r} and ${e} must match`)}function li(r){R(r!=null,()=>"The input to the tensor constructor must be a non-null value.")}function nl(r,e=[],t=!1){if(e==null&&(e=[]),Array.isArray(r)||oo(r)&&!t)for(let n=0;n<r.length;++n)nl(r[n],e,t);else e.push(r);return e}function Nt(r){if(r.length===0)return 1;let e=r[0];for(let t=1;t<r.length;t++)e*=r[t];return e}function Rre(r){return r.length===0}function no(r,e){if(r===e)return!0;if(r==null||e==null||r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}function xt(r){return r%1==0}function Lre(r){if(Math.tanh!=null)return Math.tanh(r);if(r===Infinity)return 1;if(r===-Infinity)return-1;{let e=Math.exp(2*r);return(e-1)/(e+1)}}function $re(r){let e=Math.ceil(Math.sqrt(r));return[e,Math.ceil(r/e)]}function Pre(r){let e=new Uint32Array(r);for(let t=0;t<r;++t)e[t]=t;return n$(e),e}function sc(r,e){return e<=r.length?r:r+" ".repeat(e-r.length)}function Bre(r,e=n=>0,t){return new Promise((n,o)=>{let s=0,i=()=>{if(r()){n();return}s++;let a=e(s);if(t!=null&&s>=t){o();return}setTimeout(i,a)};i()})}function Ore(r,e){let t=1,n=-1;for(let s=0;s<r.length;++s)if(r[s]>=0)t*=r[s];else if(r[s]===-1){if(n!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${n} and dim ${s}`);n=s}else if(r[s]<0)throw Error(`Shapes can not be < 0. Found ${r[s]} at dim ${s}`);if(n===-1){if(e>0&&e!==t)throw Error(`Size(${e}) must match the product of shape ${r}`);return r}if(t===0)throw Error(`Cannot infer the missing size in [${r}] when there are 0 elements`);if(e%t!=0)throw Error(`The implicit shape can't be a fractional number. Got ${e} / ${t}`);let o=r.slice();return o[n]=e/t,o}function Pr(r,e){let t=e.length;return r=r==null?e.map((n,o)=>o):[].concat(r),R(r.every(n=>n>=-t&&n<t),()=>`All values in axis param must be in range [-${t}, ${t}) but got axis ${r}`),R(r.every(n=>xt(n)),()=>`All values in axis param must be integers but got axis ${r}`),r.map(n=>n<0?t+n:n)}function eC(r,e){let t=[],n=[],o=e!=null&&Array.isArray(e)&&e.length===0,s=e==null||o?null:Pr(e,r).sort(),i=0;for(let a=0;a<r.length;++a){if(s!=null){if(s[i]===a&&r[a]!==1)throw new Error(`Can't squeeze axis ${a} since its dim '${r[a]}' is not 1`);(s[i]==null||s[i]>a)&&r[a]===1&&(t.push(r[a]),n.push(a)),s[i]<=a&&i++}r[a]!==1&&(t.push(r[a]),n.push(a))}return{newShape:t,keptDims:n}}function o$(r,e){let t=null;if(r==null||r==="float32")t=new Float32Array(e);else if(r==="int32")t=new Int32Array(e);else if(r==="bool")t=new Uint8Array(e);else throw new Error(`Unknown data type ${r}`);return t}function tC(r,e){let t=null;if(r==null||r==="float32")t=new Float32Array(e);else if(r==="int32")t=new Int32Array(e);else if(r==="bool")t=new Uint8Array(e);else if(r==="string")t=new Array(e);else throw new Error(`Unknown data type ${r}`);return t}function rC(r,e){for(let t=0;t<r.length;t++){let n=r[t];if(isNaN(n)||!isFinite(n))throw Error(`A tensor of type ${e} being uploaded contains ${n}.`)}}function nC(r){return r==="bool"||r==="complex64"||r==="float32"||r==="int32"||r==="string"}function zre(r,e){return!(e==="complex64"||e==="float32"&&r!=="complex64"||e==="int32"&&r!=="float32"&&r!=="complex64"||e==="bool"&&r==="bool")}function oo(r){return r instanceof Float32Array||r instanceof Int32Array||r instanceof Uint8Array}function oT(r){if(r==="float32"||r==="int32")return 4;if(r==="complex64")return 8;if(r==="bool")return 1;throw new Error(`Unknown dtype ${r}`)}function oC(r){if(r==null)return 0;let e=0;return r.forEach(t=>e+=t.length),e}function ac(r){return typeof r=="string"||r instanceof String}function s$(r){return typeof r=="boolean"}function a$(r){return typeof r=="number"}function tf(r){return Array.isArray(r)?tf(r[0]):r instanceof Float32Array?"float32":r instanceof Int32Array||r instanceof Uint8Array?"int32":a$(r)?"float32":ac(r)?"string":s$(r)?"bool":"float32"}function rf(r){return!!(r&&r.constructor&&r.call&&r.apply)}function nf(r,e){for(let t=e;t<r;++t)if(r%t==0)return t;return r}function ui(r){let e=r.length;if(e<2)return[];let t=new Array(e-1);t[e-2]=r[e-1];for(let n=e-3;n>=0;--n)t[n]=t[n+1]*r[n+1];return t}function i$(r,e,t,n=!1){let o=new Array;if(e.length===1){let s=e[0]*(n?2:1);for(let i=0;i<s;i++)o[i]=t[r+i]}else{let s=e[0],i=e.slice(1),a=i.reduce((l,u)=>l*u)*(n?2:1);for(let l=0;l<s;l++)o[l]=i$(r+l*a,i,t,n)}return o}function ic(r,e,t=!1){if(r.length===0)return e[0];let n=r.reduce((o,s)=>o*s)*(t?2:1);if(n===0)return[];if(n!==e.length)throw new Error(`[${r}] does not match the input size ${e.length}${t?" for a complex tensor":""}.`);return i$(0,r,e,t)}function Lh(r,e){let t=of(r,e);for(let n=0;n<t.length;n++)t[n]=1;return t}function of(r,e){if(e==null||e==="float32"||e==="complex64")return new Float32Array(r);if(e==="int32")return new Int32Array(r);if(e==="bool")return new Uint8Array(r);throw new Error(`Unknown data type ${e}`)}function Gre(r,e){let t=r.reduce((n,o)=>n*o,1);if(e==null||e==="float32")return ic(r,new Float32Array(t));if(e==="int32")return ic(r,new Int32Array(t));if(e==="bool")return ic(r,new Uint8Array(t));throw new Error(`Unknown data type ${e}`)}function $h(r){r.forEach(e=>{R(Number.isInteger(e)&&e>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${r}].`)})}function Wre(r,e,t){if(e===0)return 0;if(e===1)return r[0];let n=r[r.length-1];for(let o=0;o<r.length-1;++o)n+=t[o]*r[o];return n}function Kre(r,e,t){if(e===0)return[];if(e===1)return[r];let n=new Array(e);for(let o=0;o<n.length-1;++o)n[o]=Math.floor(r/t[o]),r-=n[o]*t[o];return n[n.length-1]=r,n}function Ph(r){return r&&r.then&&typeof r.then=="function"}var l$="tfjsflags",sT=class{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=Vre,this.populateURLFlags()}setPlatform(e,t){this.platform!=null&&console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${t}.`),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},this.urlFlags[e]!=null){let o=this.urlFlags[e];console.warn(`Setting feature override from URL ${e}: ${o}.`),this.set(e,o)}}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];let t=this.evaluateFlag(e);if(Ph(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(this.flagRegistry[e]==null)throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,this.flagRegistry[e].setHook!=null&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(this.flagRegistry[e]==null)throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(typeof this.global=="undefined"||typeof this.global.location=="undefined"||typeof this.global.location.search=="undefined")return;let e=this.getQueryParams(this.global.location.search);l$ in e&&e[l$].split(",").forEach(n=>{let[o,s]=n.split(":");this.urlFlags[o]=jre(o,s)})}};function Vre(r){let e={};return r.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(t,...n)=>(Ure(e,n[0],n[1]),n.join("="))),e}function Ure(r,e,t){r[decodeURIComponent(e)]=decodeURIComponent(t||"")}function jre(r,e){if(e=e.toLowerCase(),e==="true"||e==="false")return e==="true";if(`${+e}`===e)return+e;throw new Error(`Could not parse value flag value ${e} for flag ${r}.`)}function X(){return sC}var sC=null;function u$(r){sC=r}var aC;function iC(){if(aC==null){let r;if(typeof window!="undefined")r=window;else if(typeof global!="undefined")r=global;else if(typeof process!="undefined")r=process;else if(typeof self!="undefined")r=self;else throw new Error("Could not find a global object");aC=r}return aC}function Hre(){let r=iC();return r._tfGlobals==null&&(r._tfGlobals=new Map),r._tfGlobals}function Bh(r,e){let t=Hre();if(t.has(r))return t.get(r);{let n=e();return t.set(r,n),t.get(r)}}var Gs="Abs",ol="Acos",sl="Acosh",so="Add",Ws="AddN",al="All",il="Any",Ks="ArgMax",Ru="ArgMin",ll="Asin",ul="Asinh",pl="Atan",cl="Atanh",ml="Atan2",Vs="AvgPool",sf="AvgPoolGrad",Lu="AvgPool3D",af="AvgPool3DGrad",Us="BatchMatMul",$u="BatchToSpaceND",lf="Bincount",p$="BroadcastTo",Do="Cast",Eo="Ceil",us="ClipByValue",lc="Complex",Pu="ComplexAbs",pi="Concat",js="Conv2D",uf="Conv2DBackpropFilter",Hs="Conv2DBackpropInput",Bu="Conv3D",pf="Conv3DBackpropFilterV2",cf="Conv3DBackpropInputV2",qs="Cos",fl="Cosh",Xs="Cumsum",dl="CropAndResize",mf="DenseBincount",hl="DepthToSpace",Ys="DepthwiseConv2dNative",ff="DepthwiseConv2dNativeBackpropFilter",df="DepthwiseConv2dNativeBackpropInput",hf="Diag",Ou="Dilation2D",Oh="Dilation2DBackpropInput",zh="Dilation2DBackpropFilter",Zs="RealDiv",gf="Einsum",gl="Elu",bf="EluGrad",bl="Erf",Js="Equal",Mo="Exp",ci="ExpandDims",Qs="Expm1",yf="FFT",zu="Fill",yl="FlipLeftRight",Fo="Floor",ea="FloorDiv",ta="FusedBatchNorm",mi="GatherV2",xl="GatherNd",ra="Greater",Ro="GreaterEqual",Lo="Identity",xf="IFFT",Tf="Imag",Tl="IsFinite",kl="IsInf",Il="IsNan",na="LeakyRelu",oa="Less",sa="LessEqual",kf="LinSpace",$o="Log",vl="Log1p",wl="LogicalAnd",uc="LogicalNot",pc="LogicalOr",c$="LogSoftmax",Gu="LRN",If="LRNGrad",aa="Max",Po="Maximum",ia="MaxPool",vf="MaxPoolGrad",Wu="MaxPool3D",wf="MaxPool3DGrad",_f="MaxPoolWithArgmax",la="Mean",ua="Min",Bo="Minimum",pa="MirrorPad",_l="Mod",Cf="Multinomial",Oo="Multiply",ca="Neg",ma="NotEqual",Cl="NonMaxSuppressionV3",Sl="NonMaxSuppressionV4",Nl="NonMaxSuppressionV5",fi="OnesLike",fa="OneHot",di="Pack",da="PadV2";var ha="Pow",ga="Prelu",hi="Prod",Ku="Range",cc="Real",Al="Reciprocal",ba="Relu",gi="Reshape",Vu="ResizeNearestNeighbor",Sf="ResizeNearestNeighborGrad",ya="ResizeBilinear",Nf="ResizeBilinearGrad",xa="Relu6",Ta="Reverse",ka="Round",zo="Rsqrt",Dl="ScatterNd",bi="Select",El="Selu",Ia="Slice",va="Sin",Ml="Sinh",Fl="Sign",wa="Sigmoid",Rl="Softplus",_a="Sqrt",Ca="Sum",Uu="SpaceToBatchND",yi="SplitV",Sa="Softmax",Af="SparseFillEmptyRows",Df="SparseReshape",Ef="SparseSegmentMean",Mf="SparseSegmentSum",Ff="SparseToDense",Go="SquaredDifference",ju="Square",Ll="StridedSlice",Rf="StringNGrams",Lf="StringSplit",$f="StringToHashBucketFast",Wo="Sub",Na="Tan",Aa="Tanh",Ko="Tile",$l="TopK",Pl="Transform",ps="Transpose",Pf="Unique",xi="Unpack",Hu="UnsortedSegmentSum",Ti="ZerosLike",cs="Step",Gh="FromPixels",Bl="RotateWithOffset",ki="_FusedMatMul",Ii="FusedConv2D",vi="FusedDepthwiseConv2D";var aT=Bh("kernelRegistry",()=>new Map),lC=Bh("gradRegistry",()=>new Map);function Wh(r,e){let t=f$(r,e);return aT.get(t)}function uC(r){return lC.get(r)}function pC(r){let e=aT.entries(),t=[];for(;;){let{done:n,value:o}=e.next();if(n)break;let[s,i]=o,[a]=s.split("_");a===r&&t.push(i)}return t}function Bf(r){let{kernelName:e,backendName:t}=r,n=f$(e,t);aT.has(n)&&console.warn(`The kernel '${e}' for backend '${t}' is already registered`),aT.set(n,r)}function m$(r){let{kernelName:e}=r;lC.has(e)&&X().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${e}'`),lC.set(e,r)}function f$(r,e){return`${e}_${r}`}var x={};Ge(x,{arraysEqual:()=>no,assert:()=>R,assertNonNegativeIntegerDimensions:()=>$h,assertNonNull:()=>li,assertShapesMatch:()=>Er,bytesFromStringArray:()=>oC,bytesPerElement:()=>oT,checkConversionForErrors:()=>rC,clamp:()=>ef,computeStrides:()=>ui,createScalarValue:()=>Qre,createShuffledIndices:()=>Pre,decodeString:()=>zf,distSquared:()=>Fre,encodeString:()=>hc,fetch:()=>tne,fingerPrint64:()=>Jre,flatten:()=>nl,getArrayFromDType:()=>tC,getTypedArrayFromDType:()=>o$,hasEncodingLoss:()=>zre,hexToLong:()=>Kh,indexToLoc:()=>Kre,inferDtype:()=>tf,inferFromImplicitShape:()=>Ore,isBoolean:()=>s$,isFunction:()=>rf,isInt:()=>xt,isNumber:()=>a$,isPromise:()=>Ph,isScalarShape:()=>Rre,isString:()=>ac,isTypedArray:()=>oo,isValidDtype:()=>nC,locToIndex:()=>Wre,makeOnesTypedArray:()=>Lh,makeZerosNestedTypedArray:()=>Gre,makeZerosTypedArray:()=>of,nearestDivisor:()=>nf,nearestLargerEven:()=>Dre,now:()=>dc,parseAxisParam:()=>Pr,randUniform:()=>Mre,repeatedTry:()=>Bre,rightPad:()=>sc,shuffle:()=>n$,shuffleCombo:()=>Are,sizeFromShape:()=>Nt,sizeToSquarishShape:()=>$re,squeezeShape:()=>eC,sum:()=>Ere,tanh:()=>Lre,toNestedArray:()=>ic,toTypedArray:()=>Of});var d$=Wi(Dw());var mc=d$.default||d$;function Kh(r){return mc.fromString(r,!0,16)}var h$=Kh("c3a5c85c97cb3127"),fc=Kh("b492b66fbe98f273"),Bn=Kh("9ae16a3b2f90404f");function cC(r){return r.xor(r.shru(47))}function g$(r,e,t){let n=r.slice(e,e+t);return mc.fromBytes(Array.from(n),!0,!0)}function sr(r,e){return g$(r,e,8)}function b$(r,e){return g$(r,e,4)}function tn(r,e){return e===0?r:r.shru(e).or(r.shl(64-e))}function qu(r,e,t=Kh("9ddfea08eb382d69")){let n=r.xor(e).mul(t);n=n.xor(n.shru(47));let o=e.xor(n).mul(t);return o=o.xor(o.shru(47)),o=o.mul(t),o}function qre(r,e,t,n,o,s){o=o.add(r),s=tn(s.add(o).add(n),21);let i=o;return o=o.add(e),o=o.add(t),s=s.add(tn(o,44)),[o.add(n),s.add(i)]}function iT(r,e,t,n){return qre(sr(r,e),sr(r,e+8),sr(r,e+16),sr(r,e+24),t,n)}function Xre(r,e=r.length){if(e>=8){let t=Bn.add(e*2),n=sr(r,0).add(Bn),o=sr(r,e-8),s=tn(o,37).mul(t).add(n),i=tn(n,25).add(o).mul(t);return qu(s,i,t)}if(e>=4){let t=Bn.add(e*2),n=b$(r,0);return qu(n.shl(3).add(e),b$(r,e-4),t)}if(e>0){let t=r[0],n=r[e>>1],o=r[e-1],s=t+(n<<8),i=e+(o<<2);return cC(Bn.mul(s).xor(h$.mul(i))).mul(Bn)}return Bn}function Yre(r,e=r.length){let t=Bn.add(e*2),n=sr(r,0).mul(fc),o=sr(r,8),s=sr(r,e-8).mul(t),i=sr(r,e-16).mul(Bn);return qu(tn(n.add(o),43).add(tn(s,30)).add(i),n.add(tn(o.add(Bn),18)).add(s),t)}function Zre(r,e=r.length){let t=Bn.add(e*2),n=sr(r,0).mul(Bn),o=sr(r,8),s=sr(r,e-8).mul(t),i=sr(r,e-16).mul(Bn),a=tn(n.add(o),43).add(tn(s,30)).add(i),l=qu(a,n.add(tn(o.add(Bn),18)).add(s),t),u=sr(r,16).mul(t),p=sr(r,24),c=a.add(sr(r,e-32)).mul(t),m=l.add(sr(r,e-24)).mul(t);return qu(tn(u.add(p),43).add(tn(c,30)).add(m),u.add(tn(p.add(n),18)).add(c),t)}function Jre(r,e=r.length){let t=mc.fromNumber(81,!0);if(e<=32)return e<=16?Xre(r,e):Yre(r,e);if(e<=64)return Zre(r,e);let n=t,o=t.mul(fc).add(113),s=cC(o.mul(Bn).add(113)).mul(Bn),i=[mc.UZERO,mc.UZERO],a=[mc.UZERO,mc.UZERO];n=n.mul(Bn).add(sr(r,0));let l=0,u=(e-1>>6)*64,p=u+(e-1&63)-63;do n=tn(n.add(o).add(i[0]).add(sr(r,l+8)),37).mul(fc),o=tn(o.add(i[1]).add(sr(r,l+48)),42).mul(fc),n=n.xor(a[1]),o=o.add(i[0]).add(sr(r,l+40)),s=tn(s.add(a[0]),33).mul(fc),i=iT(r,l,i[1].mul(fc),n.add(a[0])),a=iT(r,l+32,s.add(a[1]),o.add(sr(r,l+16))),[s,n]=[n,s],l+=64;while(l!==u);let c=fc.add(s.and(255).shl(1));return l=p,a[0]=a[0].add(e-1&63),i[0]=i[0].add(a[0]),a[0]=a[0].add(i[0]),n=tn(n.add(o).add(i[0]).add(sr(r,l+8)),37).mul(c),o=tn(o.add(i[1]).add(sr(r,l+48)),42).mul(c),n=n.xor(a[1].mul(9)),o=o.add(i[0].mul(9).add(sr(r,l+40))),s=tn(s.add(a[0]),33).mul(c),i=iT(r,l,i[1].mul(c),n.add(a[0])),a=iT(r,l+32,s.add(a[1]),o.add(sr(r,l+16))),[s,n]=[n,s],qu(qu(i[0],a[0],c).add(cC(o).mul(h$)).add(s),qu(i[1],a[1],c).add(n),c)}function Qre(r,e){return e==="string"?hc(r):Of([r],e)}function ene(r,e){return r instanceof Float32Array&&e==="float32"||r instanceof Int32Array&&e==="int32"||r instanceof Uint8Array&&e==="bool"}function Of(r,e){if(e==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(r)&&(r=nl(r)),X().getBool("DEBUG")&&rC(r,e),ene(r,e))return r;if(e==null||e==="float32"||e==="complex64")return new Float32Array(r);if(e==="int32")return new Int32Array(r);if(e==="bool"){let t=new Uint8Array(r.length);for(let n=0;n<t.length;++n)Math.round(r[n])!==0&&(t[n]=1);return t}else throw new Error(`Unknown data type ${e}`)}function dc(){return X().platform.now()}function tne(r,e){return X().platform.fetch(r,e)}function hc(r,e="utf-8"){return e=e||"utf-8",X().platform.encode(r,e)}function zf(r,e="utf-8"){return e=e||"utf-8",X().platform.decode(r,e)}var mC=class{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new y$)}profileKernel(e,t,n){let o,s=()=>{o=n()},i,a=dc();if(this.backendTimer.timerAvailable())i=this.backendTimer.time(s);else{s();for(let u of o)u.dataSync();i=Promise.resolve({kernelMs:dc()-a})}if(X().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let u=0;u<o.length;u++){let p=o[u];p.data().then(c=>{rne(c,p.dtype,e)})}return{kernelName:e,outputs:o,inputs:t,timeMs:i.then(u=>u.kernelMs),extraInfo:i.then(u=>u.getExtraProfileInfo!=null?u.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:n,timeMs:o,inputs:s,extraInfo:i}=e;n.forEach(a=>{Promise.all([a.data(),o,i]).then(l=>{this.logger.logKernelProfile(t,a,l[0],l[1],s,l[2])})})}};function rne(r,e,t){if(e!=="float32")return!1;for(let n=0;n<r.length;n++){let o=r[n];if(isNaN(o)||!isFinite(o))return console.warn(`Found ${o} in the result of '${t}'`),!0}return!1}var y$=class{logKernelProfile(e,t,n,o,s,i){let a=typeof o=="number"?sc(`${o}ms`,9):o.error,l=sc(e,25),u=t.rank,p=t.size,c=sc(t.shape.toString(),14),m="";for(let f in s){let d=s[f];if(d!=null){let h=d.shape||t.shape,g=h.length;m+=`${f}: ${g}D ${g>0?h:""} `}}console.log(`%c${l} %c${a} %c${u}D ${c} %c${p} %c${m} %c${i}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function x$(r,e,t){let n={},o={};for(let l=0;l<e.length;l++)n[e[l].id]=!0;for(let l=0;l<r.length;l++){let u=r[l],p=u.inputs;for(let c in p){let m=p[c],f=!1;for(let d=0;d<e.length;d++)if(n[m.id]){u.outputs.forEach(h=>n[h.id]=!0),f=!0,o[u.id]=!0;break}if(f)break}}let s={};s[t.id]=!0;let i={};for(let l=r.length-1;l>=0;l--){let u=r[l],p=u.inputs;for(let c=0;c<u.outputs.length;c++)if(s[u.outputs[c].id]){for(let m in p)s[p[m].id]=!0,i[u.id]=!0;break}}let a=[];for(let l=0;l<r.length;l++){let u=r[l];if(o[u.id]&&i[u.id]){let p={};for(let m in u.inputs){let f=u.inputs[m];n[f.id]&&(p[m]=f)}let c=Object.assign({},u);c.inputs=p,c.outputs=u.outputs,a.push(c)}}return a}function T$(r,e,t,n){for(let o=e.length-1;o>=0;o--){let s=e[o],i=[];if(s.outputs.forEach(l=>{let u=r[l.id];u!=null?i.push(u):i.push(null)}),s.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);let a=s.gradient(i);for(let l in s.inputs){if(!(l in a))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(a)}.`);let u=t(()=>a[l]());if(u.dtype!=="float32")throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${u.dtype}'`);let p=s.inputs[l];if(!no(u.shape,p.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${l}' has shape '${u.shape}', which does not match the shape of the input '${p.shape}'`);if(r[p.id]==null)r[p.id]=u;else{let c=r[p.id];r[p.id]=n(c,u),c.dispose()}}}}var k$=20,Vh=3,fC=7;function I$(r,e,t,n){let o=ui(e),s=nne(r,e,t,o),i=e.length,a=lT(r,e,t,o,s),l=["Tensor"];return n&&(l.push(` dtype: ${t}`),l.push(` rank: ${i}`),l.push(` shape: [${e}]`),l.push(" values:")),l.push(a.map(u=>" "+u).join(`
|
|
`)),l.join(`
|
|
`)}function nne(r,e,t,n){let o=Nt(e),s=n[n.length-1],i=new Array(s).fill(0),a=e.length,l=t==="complex64"?jh(r):r;if(a>1)for(let u=0;u<o/s;u++){let p=u*s;for(let c=0;c<s;c++)i[c]=Math.max(i[c],Uh(l[p+c],0,t).length)}return i}function Uh(r,e,t){let n;return Array.isArray(r)?n=`${parseFloat(r[0].toFixed(fC))} + ${parseFloat(r[1].toFixed(fC))}j`:ac(r)?n=`'${r}'`:t==="bool"?n=v$(r):n=parseFloat(r.toFixed(fC)).toString(),sc(n,e)}function v$(r){return r===0?"false":"true"}function lT(r,e,t,n,o,s=!0){let i=t==="complex64"?2:1,a=e[0],l=e.length;if(l===0){if(t==="complex64"){let h=jh(r);return[Uh(h[0],0,t)]}return t==="bool"?[v$(r[0])]:[r[0].toString()]}if(l===1){if(a>k$){let g=Vh*i,b=Array.from(r.slice(0,g)),y=Array.from(r.slice((a-Vh)*i,a*i));return t==="complex64"&&(b=jh(b),y=jh(y)),["["+b.map((T,k)=>Uh(T,o[k],t)).join(", ")+", ..., "+y.map((T,k)=>Uh(T,o[a-Vh+k],t)).join(", ")+"]"]}let h=t==="complex64"?jh(r):Array.from(r);return["["+h.map((g,b)=>Uh(g,o[b],t)).join(", ")+"]"]}let u=e.slice(1),p=n.slice(1),c=n[0]*i,m=[];if(a>k$){for(let h=0;h<Vh;h++){let g=h*c,b=g+c;m.push(...lT(r.slice(g,b),u,t,p,o,!1))}m.push("...");for(let h=a-Vh;h<a;h++){let g=h*c,b=g+c;m.push(...lT(r.slice(g,b),u,t,p,o,h===a-1))}}else for(let h=0;h<a;h++){let g=h*c,b=g+c;m.push(...lT(r.slice(g,b),u,t,p,o,h===a-1))}let f=l===2?",":"";m[0]="["+m[0]+f;for(let h=1;h<m.length-1;h++)m[h]=" "+m[h]+f;let d=`,
|
|
`;for(let h=2;h<l;h++)d+=`
|
|
`;return m[m.length-1]=" "+m[m.length-1]+"]"+(s?"":d),m}function jh(r){let e=[];for(let t=0;t<r.length;t+=2)e.push([r[t],r[t+1]]);return e}var bt=class{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=Nt(e),n!=null){let o=n.length;R(o===this.size,()=>`Length of values '${o}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||tC(t,this.size),this.strides=ui(e)}set(e,...t){t.length===0&&(t=[0]),R(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let o of e){if(o<0||o>=this.shape[t]){let s=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(s)}t++}let n=e[e.length-1];for(let o=0;o<e.length-1;++o)n+=this.strides[o]*e[o];return this.values[n]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];let t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return wi().makeTensor(this.values,this.shape,this.dtype)}},wi=null,Gf=null,one=null;function w$(r){wi=r}function _$(r){Gf=r}function C$(r){one=r}var rt=class{constructor(e,t,n,o){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=Nt(e),this.strides=ui(e),this.dataId=n,this.id=o,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let e=await this.data();return Gf.buffer(this.shape,this.dtype,e)}bufferSync(){return Gf.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return ic(this.shape,e,this.dtype==="complex64")}arraySync(){return ic(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();let e=wi().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(n=>zf(n))}catch(n){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataSync(){this.throwIfDisposed();let e=wi().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>zf(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();let e=await wi().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(wi().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Gf.print(this,e)}clone(){return this.throwIfDisposed(),Gf.clone(this)}toString(e=!1){let t=this.dataSync();return I$(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Gf.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),wi().makeVariable(this,e,t,n)}};Object.defineProperty(rt,Symbol.hasInstance,{value:r=>!!r&&r.data!=null&&r.dataSync!=null&&r.throwIfDisposed!=null});function z(){return Bh("Tensor",()=>rt)}z();var Xu=class extends rt{constructor(e,t,n,o){super(e.shape,e.dtype,e.dataId,o);this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!no(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);wi().disposeTensor(this),this.dataId=e.dataId,wi().incRef(this,null)}dispose(){wi().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(Xu,Symbol.hasInstance,{value:r=>r instanceof rt&&r.assign!=null&&r.assign instanceof Function});var ms={};Ge(ms,{assertTypesMatch:()=>xC,getTensorsInContainer:()=>Hh,isTensorInList:()=>ane,makeTypesMatch:()=>et});var dC;(function(r){r.R0="R0",r.R1="R1",r.R2="R2",r.R3="R3",r.R4="R4",r.R5="R5",r.R6="R6"})(dC||(dC={}));var hC;(function(r){r.float32="float32",r.int32="int32",r.bool="int32",r.complex64="complex64"})(hC||(hC={}));var gC;(function(r){r.float32="float32",r.int32="int32",r.bool="bool",r.complex64="complex64"})(gC||(gC={}));var bC;(function(r){r.float32="float32",r.int32="float32",r.bool="float32",r.complex64="complex64"})(bC||(bC={}));var yC;(function(r){r.float32="complex64",r.int32="complex64",r.bool="complex64",r.complex64="complex64"})(yC||(yC={}));var sne={float32:bC,int32:hC,bool:gC,complex64:yC};function Mr(r,e){if(r==="string"||e==="string"){if(r==="string"&&e==="string")return"string";throw new Error(`Can not upcast ${r} with ${e}`)}return sne[r][e]}function gc(r){return Mr(r,"int32")}function et(r,e){if(r.dtype===e.dtype)return[r,e];let t=Mr(r.dtype,e.dtype);return[r.cast(t),e.cast(t)]}function xC(r,e){R(r.dtype===e.dtype,()=>`The dtypes of the first(${r.dtype}) and second(${e.dtype}) input must match`)}function ane(r,e){return e.some(t=>t.id===r.id)}function Hh(r){let e=[],t=new Set;return S$(r,e,t),e}function S$(r,e,t){if(r==null)return;if(r instanceof rt){e.push(r);return}if(!ine(r))return;let n=r;for(let o in n){let s=n[o];t.has(s)||(t.add(s),S$(s,e,t))}}function ine(r){return Array.isArray(r)||typeof r=="object"}function TC(r){return r.kernelName!=null}var kC=class{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null,get kernelNames(){return Array.from(new Set(this.kernels.map(e=>e.name)))}}}dispose(){for(let e in this.registeredVariables)this.registeredVariables[e].dispose()}},bc=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new kC}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;let e=this.getSortedBackends();for(let t=0;t<e.length;t++){let n=e[t];if(await this.initializeBackend(n).success){await this.setBackend(n);return}}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(this.pendingBackendInit!=null)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(this.backendInstance==null){let{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){let{asyncInit:t}=this.initializeBackend(e);if(t)return null}else return null;return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(console.warn(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(this.registryFactory[e]==null)throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,this.registry[e]==null){this.backendInstance=null;let{success:t,asyncInit:n}=this.initializeBackend(e);if(!(n?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new mC(this.backendInstance),!0}setupRegisteredKernels(){pC(this.backendName).forEach(t=>{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){pC(e).forEach(n=>{n.disposeFunc!=null&&n.disposeFunc(this.registry[e])})}initializeBackend(e){let t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{let n=t.factory();if(n&&!(n instanceof ii)&&typeof n.then=="function"){let o=++this.pendingBackendInitId,s=n.then(i=>o<this.pendingBackendInitId?!1:(this.registry[e]=i,this.pendingBackendInit=null,!0)).catch(i=>(o<this.pendingBackendInitId||(this.pendingBackendInit=null,console.warn(`Initialization of backend ${e} failed`),console.warn(i.stack||i.message)),!1));return this.pendingBackendInit=s,{success:s,asyncInit:!0}}else return this.registry[e]=n,{success:!0,asyncInit:!1}}catch(n){return console.warn(`Initialization of backend ${e} failed`),console.warn(n.stack||n.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(Object.keys(this.registryFactory).length===0)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){let e=this.getSortedBackends();for(let t=0;t<e.length;t++){let n=e[t],{success:o,asyncInit:s}=this.initializeBackend(n);if(s||o)return{name:n,asyncInit:s}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){let n=this.state.tensorInfo.get(t),o=n.backend,s=this.readSync(t),i=o.refCount(t);o.disposeData(t,!0),n.backend=e,e.move(t,s,n.shape,n.dtype,i),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n=null;if(t==null){if(typeof e!="function")throw new Error("Please provide a function to tidy()");t=e}else{if(typeof e!="string"&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof t!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");n=e}let o;return this.scopedRun(()=>this.startScope(n),()=>this.endScope(o),()=>(o=t(),o instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),o))}scopedRun(e,t,n){e();try{let o=n();return t(),o}catch(o){throw t(),o}}nextTensorId(){return bc.nextTensorId++}nextVariableId(){return bc.nextVariableId++}clone(e){let t=M.runKernel(Lo,{x:e}),n={x:e},o=i=>({x:()=>{let a="float32",l={x:i},u={dtype:a};return M.runKernel(Do,l,u)}}),s=[];return this.addTapeNode(this.state.activeScope.name,n,[t],o,s,{}),t}runKernel(e,t,n){if(!(Wh(e,this.backendName)!=null))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){let o=this.backend.numDataIds(),s=0;n.forEach(l=>{s+=l.dtype==="complex64"?3:1});let i=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],a=o-t-s-i;if(a>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${a} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[],o=this.isTapeOn(),s=this.state.numBytes,i=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let a;this.backendName==null&&this.backend;let l,u=TC(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(TC(e)){let{kernelName:d,inputs:h,attrs:g}=e;this.backendName==null&&this.backend;let b=Wh(d,this.backendName);R(b!=null,()=>`Cannot find registered kernel '${d}' for backend '${this.backendName}'`),a=()=>{let y=this.backend.numDataIds();l=b.kernelFunc({inputs:h,attrs:g,backend:this.backend});let T=Array.isArray(l)?l:[l];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(d,y,T);let k=T.map(I=>{if(I.rank!=null)return I;let{dataId:S,shape:N,dtype:F}=I;return this.makeTensorFromDataId(S,N,F)});if(o){let I=this.getTensorsForGradient(d,h,k);n=this.saveTensorsForBackwardMode(I)}return k}}else{let{forwardFunc:d}=e,h=g=>{!o||(n=g.map(b=>this.keep(this.clone(b))))};a=()=>{let g=this.backend.numDataIds();l=this.tidy(()=>d(this.backend,h));let b=Array.isArray(l)?l:[l];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(u,g,b),b}}let{inputs:p,attrs:c}=e,m=TC(e)?null:e.backwardsFunc,f;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=a():(f=this.profiler.profileKernel(u,p,()=>a()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(f),t=f.outputs)}),o&&this.addTapeNode(u,p,t,m,n,c),this.state.profiling&&this.state.activeProfile.kernels.push({name:u,bytesAdded:this.state.numBytes-s,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-i,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(p).map(d=>p[d]!=null?p[d].shape:null),outputShapes:t.map(d=>d.shape),kernelTimeMs:f.timeMs,extraInfo:f.extraInfo}),Array.isArray(l)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(n=>this.keep(this.clone(n)))}getTensorsForGradient(e,t,n){let o=uC(e);if(o!=null){let s=o.inputsToSave||[],i=o.outputsToSave||[],a;o.saveAllInputs?(R(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),a=Object.keys(t).map(u=>t[u])):a=s.map(u=>t[u]);let l=n.filter((u,p)=>i[p]);return a.concat(l)}return[]}makeTensor(e,t,n,o){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",o=o||this.backend;let s=e;n==="string"&&ac(e[0])&&(s=e.map(l=>hc(l)));let i=o.write(s,t,n),a=new rt(t,n,i,this.nextTensorId());if(this.trackTensor(a,o),n==="string"){let l=this.state.tensorInfo.get(i),u=oC(s);this.state.numBytes+=u-l.bytes,l.bytes=u}return a}makeTensorFromDataId(e,t,n,o){n=n||"float32";let s=new rt(t,n,e,this.nextTensorId());return this.trackTensor(s,o),s}makeVariable(e,t=!0,n,o){n=n||this.nextVariableId().toString(),o!=null&&o!==e.dtype&&(e=e.cast(o));let s=new Xu(e,t,n,this.nextTensorId());if(this.state.registeredVariables[s.name]!=null)throw new Error(`Variable with name ${s.name} was already registered`);return this.state.registeredVariables[s.name]=s,this.incRef(s,this.backend),s}trackTensor(e,t){this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++;let n=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(n=e.size*oT(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof Xu||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;let t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,e.dtype==="string"&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),e.dtype!=="complex64"&&e.dtype!=="string"){let n=e.size*oT(e.dtype);this.state.numBytes-=n}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(let e in this.state.registeredVariables){let 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(){let 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;let t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(o=>o.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(let o of this.state.activeProfile.kernels)o.kernelTimeMs=await o.kernelTimeMs,o.extraInfo=await o.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,n,o,s,i){let a={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:s},l=uC(e);l!=null&&(o=l.gradFunc),o!=null&&(a.gradient=u=>(u=u.map((p,c)=>{if(p==null){let m=n[c],f=of(m.size,m.dtype);return this.makeTensor(f,m.shape,m.dtype)}return p}),o(u.length>1?u:u[0],s,i))),this.state.activeTape.push(a)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){let t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){let t=Hh(e),n=new Set(t.map(s=>s.id));for(let s=0;s<this.state.activeScope.track.length;s++){let i=this.state.activeScope.track[s];!i.kept&&!n.has(i.id)&&i.dispose()}let o=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(s=>{!s.kept&&s.scopeId===o.id&&this.track(s)})}gradients(e,t,n,o=!1){if(R(t.length>0,()=>"gradients() received an empty list of xs."),n!=null&&n.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);let s=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));R(s instanceof rt,()=>"The result y returned by f() must be a tensor.");let i=x$(this.state.activeTape,t,s);if(!o&&i.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",()=>{let a={};a[s.id]=n==null?lne(s.shape):n,T$(a,i,u=>this.tidy(u),une);let l=t.map(u=>a[u.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(u=>{for(let p of u.saved)p.dispose()}),this.state.activeTape=null),{value:s,grads:l}})}customGrad(e){return R(rf(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{R(t.every(a=>a instanceof rt),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n,o={};t.forEach((a,l)=>{o[l]=a});let s=(a,l)=>(n=e(...t,l),R(n.value instanceof rt,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),R(rf(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),i=(a,l)=>{let u=n.gradFunc(a,l),p=Array.isArray(u)?u:[u];R(p.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(...)."),R(p.every(m=>m instanceof rt),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");let c={};return p.forEach((m,f)=>{c[f]=()=>m}),c};return this.runKernelFunc({forwardFunc:s,backwardsFunc:i,inputs:o})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}async time(e){let t=dc(),n=await this.backend.time(e);return n.wallMs=dc()-t,n}track(e){return this.state.activeScope!=null&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new kC;for(let e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}};bc.nextTensorId=0;bc.nextVariableId=0;function lne(r){let e=Lh(Nt(r),"float32");return M.makeTensor(e,r,"float32")}function IC(){let r=iC();if(r._tfengine==null){let e=new sT(r);r._tfengine=new bc(e)}return u$(r._tfengine.ENV),w$(()=>r._tfengine),r._tfengine}var M=IC();function une(r,e){let t={a:r,b:e};return M.runKernel(so,t)}var yc={};Ge(yc,{isBrowser:()=>vC,isMobile:()=>cne});function pne(){return typeof navigator!="undefined"&&navigator!=null}function cne(r){if(r||pne()){if(r||(r=navigator),r.product==="ReactNative")return!0;let e=r.userAgent||r.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 vC(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var Da=X();Da.registerFlag("DEBUG",()=>!1,r=>{r&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")});Da.registerFlag("IS_BROWSER",()=>vC());Da.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Da.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Da.registerFlag("PROD",()=>!1);Da.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Da.getBool("DEBUG"));Da.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Da.registerFlag("IS_TEST",()=>!1);Da.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);Da.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);function Vo(r,e){let t=r;if(oo(r))return e==="string"?[]:[r.length];if(!Array.isArray(r))return[];let n=[];for(;Array.isArray(t)||oo(t)&&e!=="string";)n.push(t.length),t=t[0];return Array.isArray(r)&&X().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&N$(r,n,[]),n}function N$(r,e,t){if(t=t||[],!Array.isArray(r)&&!oo(r)){R(e.length===0,()=>`Element arr[${t.join("][")}] is a primitive, but should be an array/TypedArray of ${e[0]} elements`);return}R(e.length>0,()=>`Element arr[${t.join("][")}] should be a primitive, but is an array of ${r.length} elements`),R(r.length===e[0],()=>`Element arr[${t.join("][")}] should have ${e[0]} elements, but has ${r.length} elements`);let n=e.slice(1);for(let o=0;o<r.length;++o)N$(r[o],n,t.concat(o))}function A$(r,e,t,n){if(r!=="string_or_numeric"){if(r==null)throw new Error("Expected dtype cannot be null.");if(r!=="numeric"&&r!==e||r==="numeric"&&e==="string")throw new Error(`Argument '${t}' passed to '${n}' must be ${r} tensor, but got ${e} tensor`)}}function v(r,e,t,n="numeric"){if(r instanceof rt)return A$(n,r.dtype,e,t),r;let o=tf(r);if(o!=="string"&&["bool","int32","float32"].indexOf(n)>=0&&(o=n),A$(n,o,e,t),r==null||!oo(r)&&!Array.isArray(r)&&typeof r!="number"&&typeof r!="boolean"&&typeof r!="string"){let l=r==null?"null":r.constructor.name;throw new Error(`Argument '${e}' passed to '${t}' must be a Tensor or TensorLike, but got '${l}'`)}let s=Vo(r,o);!oo(r)&&!Array.isArray(r)&&(r=[r]);let a=o!=="string"?Of(r,o):nl(r,[],!0);return M.makeTensor(a,s,o)}function Yu(r,e,t,n="numeric"){if(!Array.isArray(r))throw new Error(`Argument ${e} passed to ${t} must be a \`Tensor[]\` or \`TensorLike[]\``);return r.map((s,i)=>v(s,`${e}[${i}]`,t,n))}var D$="__op";function A(r){let e=Object.keys(r);if(e.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${e.length} keys.`);let t=e[0],n=r[t];t.endsWith("_")&&(t=t.substring(0,t.length-1)),t=t+D$;let o=(...s)=>{M.startScope(t);try{let i=n(...s);return Ph(i)&&console.error("Cannot return a Promise inside of tidy."),M.endScope(i),i}catch(i){throw M.endScope(null),i}};return Object.defineProperty(o,"name",{value:t,configurable:!0}),o}function mne(r,e){let t=v(r,"real","complex"),n=v(e,"imag","complex");Er(t.shape,n.shape,`real and imag shapes, ${t.shape} and ${n.shape}, must match in call to tf.complex().`);let o={real:t,imag:n};return M.runKernel(lc,o)}var ko=A({complex_:mne});function Uo(r,e,t,n){if(n==null&&(n=tf(r)),n==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!oo(r)&&!Array.isArray(r)&&typeof r!="number"&&typeof r!="boolean"&&typeof r!="string")throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(e!=null){$h(e);let o=Nt(e),s=Nt(t);R(o===s,()=>`Based on the provided shape, [${e}], the tensor should have ${o} values but has ${s}`);for(let i=0;i<t.length;++i){let a=t[i],l=i===t.length-1?a!==Nt(e.slice(i)):!0;R(t[i]===e[i]||!l,()=>`Error creating a new Tensor. Inferred shape (${t}) does not match the provided shape (${e}). `)}}return!oo(r)&&!Array.isArray(r)&&(r=[r]),e=e||t,r=n!=="string"?Of(r,n):nl(r,[],!0),M.makeTensor(r,e,n)}function mn(r,e,t){let n=Vo(r,t);return Uo(r,e,n,t)}var qh={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};var uT=4;async function E$(r,e){let t=[],n=[],o=Array.isArray(r)?r.map(i=>i.name):Object.keys(r);for(let i=0;i<o.length;++i){let a=o[i],l=Array.isArray(r)?r[i].tensor:r[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}`);let u={name:a,shape:l.shape,dtype:l.dtype};if(l.dtype==="string"){let p=new Promise(async c=>{let m=await l.bytes(),f=m.reduce((g,b)=>g+b.length,0)+uT*m.length,d=new Uint8Array(f),h=0;for(let g=0;g<m.length;g++){let b=m[g],y=new Uint8Array(new Uint32Array([b.length]).buffer);d.set(y,h),h+=uT,d.set(b,h),h+=b.length}c(d)});n.push(p)}else n.push(l.data());e!=null&&(u.group=e),t.push(u)}let s=await Promise.all(n);return{data:fne(s),specs:t}}function pT(r,e){let t={},n,o=0;for(let s of e){let i=s.name,a=s.dtype,l=s.shape,u=Nt(l),p;if("quantization"in s){let c=s.quantization;if(c.dtype==="uint8"||c.dtype==="uint16"){if(!("min"in c&&"scale"in c))throw new Error(`Weight ${s.name} with quantization ${c.dtype} doesn't have corresponding metadata min and scale.`)}else if(c.dtype==="float16"){if(a!=="float32")throw new Error(`Weight ${s.name} is quantized with ${c.dtype} which only supports weights of type float32 not ${a}.`)}else throw new Error(`Weight ${s.name} has unknown quantization dtype ${c.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);let m=qh[c.dtype],f=r.slice(o,o+u*m),d=c.dtype==="uint8"?new Uint8Array(f):new Uint16Array(f);if(a==="float32")if(c.dtype==="uint8"||c.dtype==="uint16"){p=new Float32Array(d.length);for(let h=0;h<d.length;h++){let g=d[h];p[h]=g*c.scale+c.min}}else if(c.dtype==="float16")n===void 0&&(n=bne()),p=n(d);else throw new Error(`Unsupported quantization type ${c.dtype} for weight type float32.`);else if(a==="int32"){if(c.dtype!=="uint8"&&c.dtype!=="uint16")throw new Error(`Unsupported quantization type ${c.dtype} for weight type int32.`);p=new Int32Array(d.length);for(let h=0;h<d.length;h++){let g=d[h];p[h]=Math.round(g*c.scale+c.min)}}else throw new Error(`Unsupported dtype in weight '${i}': ${a}`);o+=u*m}else if(a==="string"){let c=Nt(s.shape);p=[];for(let m=0;m<c;m++){let f=new Uint32Array(r.slice(o,o+uT))[0];o+=uT;let d=new Uint8Array(r.slice(o,o+f));p.push(d),o+=f}}else{let c=qh[a],m=r.slice(o,o+u*c);if(a==="float32")p=new Float32Array(m);else if(a==="int32")p=new Int32Array(m);else if(a==="bool")p=new Uint8Array(m);else if(a==="complex64"){p=new Float32Array(m);let f=new Float32Array(p.length/2),d=new Float32Array(p.length/2);for(let b=0;b<f.length;b++)f[b]=p[b*2],d[b]=p[b*2+1];let h=mn(f,l,"float32"),g=mn(d,l,"float32");t[i]=ko(h,g),h.dispose(),g.dispose()}else throw new Error(`Unsupported dtype in weight '${i}': ${a}`);o+=u*c}a!=="complex64"&&(t[i]=mn(p,l,a))}return t}function fne(r){if(r===null)throw new Error(`Invalid input value: ${JSON.stringify(r)}`);let e=0,t=[];r.forEach(s=>{if(e+=s.byteLength,t.push(s.byteLength===s.buffer.byteLength?s:new s.constructor(s)),!(s instanceof Float32Array||s instanceof Int32Array||s instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${s.constructor.name}`)});let n=new Uint8Array(e),o=0;return t.forEach(s=>{n.set(new Uint8Array(s.buffer),o),o+=s.byteLength}),n.buffer}var wC=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function M$(r){return wC?Buffer.byteLength(r):new Blob([r]).size}function F$(r){if(wC)return Buffer.from(r).toString("base64");let e=new Uint8Array(r),t="";for(let n=0,o=e.length;n<o;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function R$(r){if(wC){let n=Buffer.from(r,"base64");return n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t.set([e.charCodeAt(n)],n);return t.buffer}function Wf(r){if(r.length===1)return r[0];let e=0;r.forEach(o=>{e+=o.byteLength});let t=new Uint8Array(e),n=0;return r.forEach(o=>{t.set(new Uint8Array(o),n),n+=o.byteLength}),t.buffer}function _C(r){let e="/";for(r=r.trim();r.endsWith(e);)r=r.slice(0,r.length-1);let t=r.split(e);return t[t.length-1]}function _i(r){if(r.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:r.modelTopology==null?0:M$(JSON.stringify(r.modelTopology)),weightSpecsBytes:r.weightSpecs==null?0:M$(JSON.stringify(r.weightSpecs)),weightDataBytes:r.weightData==null?0:r.weightData.byteLength}}function dne(){let r=t=>{let n=t<<13,o=0;for(;(n&8388608)==0;)o-=8388608,n<<=1;return n&=~8388608,o+=947912704,n|o},e=new Uint32Array(2048);e[0]=0;for(let t=1;t<1024;t++)e[t]=r(t);for(let t=1024;t<2048;t++)e[t]=939524096+(t-1024<<13);return e}function hne(){let r=new Uint32Array(64);r[0]=0,r[31]=1199570944,r[32]=2147483648,r[63]=3347054592;for(let e=1;e<31;e++)r[e]=e<<23;for(let e=33;e<63;e++)r[e]=2147483648+(e-32<<23);return r}function gne(){let r=new Uint32Array(64);for(let e=0;e<64;e++)r[e]=1024;return r[0]=r[32]=0,r}function bne(){let r=dne(),e=hne(),t=gne();return n=>{let o=new ArrayBuffer(4*n.length),s=new Uint32Array(o);for(let i=0;i<n.length;i++){let a=n[i],l=r[t[a>>10]+(a&1023)]+e[a>>10];s[i]=l}return new Float32Array(o)}}var jt=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return jt.instance==null&&(jt.instance=new jt),jt.instance}static registerSaveRouter(e){jt.getInstance().saveRouters.push(e)}static registerLoadRouter(e){jt.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return jt.getHandlers(e,"save")}static getLoadHandlers(e,t){return jt.getHandlers(e,"load",t)}static getHandlers(e,t,n){let o=[];return(t==="load"?jt.getInstance().loadRouters:jt.getInstance().saveRouters).forEach(i=>{let a=i(e,n);a!==null&&o.push(a)}),o}},L$=r=>jt.registerSaveRouter(r),$$=r=>jt.registerLoadRouter(r),P$=r=>jt.getSaveHandlers(r),B$=(r,e)=>jt.getLoadHandlers(r,e);var CC="tensorflowjs",SC=1,xc="models_store",Zu="model_info_store";function O$(){if(!X().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");let r=typeof window=="undefined"?self:window,e=r.indexedDB||r.mozIndexedDB||r.webkitIndexedDB||r.msIndexedDB||r.shimIndexedDB;if(e==null)throw new Error("The current browser does not appear to support IndexedDB.");return e}function NC(r){let e=r.result;e.createObjectStore(xc,{keyPath:"modelPath"}),e.createObjectStore(Zu,{keyPath:"modelPath"})}var Ol=class{constructor(e){if(this.indexedDB=O$(),e==null||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise((n,o)=>{let s=this.indexedDB.open(CC,SC);s.onupgradeneeded=()=>NC(s),s.onsuccess=()=>{let i=s.result;if(t==null){let a=i.transaction(xc,"readonly"),u=a.objectStore(xc).get(this.modelPath);u.onsuccess=()=>{if(u.result==null)return i.close(),o(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));n(u.result.modelArtifacts)},u.onerror=p=>(i.close(),o(u.error)),a.oncomplete=()=>i.close()}else{let a=_i(t),l=i.transaction(Zu,"readwrite"),u=l.objectStore(Zu),p=u.put({modelPath:this.modelPath,modelArtifactsInfo:a}),c;p.onsuccess=()=>{c=i.transaction(xc,"readwrite");let f=c.objectStore(xc).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:a});f.onsuccess=()=>n({modelArtifactsInfo:a}),f.onerror=d=>{u=l.objectStore(Zu);let h=u.delete(this.modelPath);h.onsuccess=()=>(i.close(),o(f.error)),h.onerror=g=>(i.close(),o(f.error))}},p.onerror=m=>(i.close(),o(p.error)),l.oncomplete=()=>{c==null?i.close():c.oncomplete=()=>i.close()}}},s.onerror=i=>o(s.error)})}};Ol.URL_SCHEME="indexeddb://";var z$=r=>X().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(Ol.URL_SCHEME)?yne(r.slice(Ol.URL_SCHEME.length)):null;jt.registerSaveRouter(z$);jt.registerLoadRouter(z$);function yne(r){return new Ol(r)}function xne(r){return r.startsWith(Ol.URL_SCHEME)?r.slice(Ol.URL_SCHEME.length):r}var AC=class{constructor(){this.indexedDB=O$()}async listModels(){return new Promise((e,t)=>{let n=this.indexedDB.open(CC,SC);n.onupgradeneeded=()=>NC(n),n.onsuccess=()=>{let o=n.result,s=o.transaction(Zu,"readonly"),a=s.objectStore(Zu).getAll();a.onsuccess=()=>{let l={};for(let u of a.result)l[u.modelPath]=u.modelArtifactsInfo;e(l)},a.onerror=l=>(o.close(),t(a.error)),s.oncomplete=()=>o.close()},n.onerror=o=>t(n.error)})}async removeModel(e){return e=xne(e),new Promise((t,n)=>{let o=this.indexedDB.open(CC,SC);o.onupgradeneeded=()=>NC(o),o.onsuccess=()=>{let s=o.result,i=s.transaction(Zu,"readwrite"),a=i.objectStore(Zu),l=a.get(e),u;l.onsuccess=()=>{if(l.result==null)return s.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{let p=a.delete(e),c=()=>{u=s.transaction(xc,"readwrite");let f=u.objectStore(xc).delete(e);f.onsuccess=()=>t(l.result.modelArtifactsInfo),f.onerror=d=>n(l.error)};p.onsuccess=c,p.onerror=m=>(c(),s.close(),n(l.error))}},l.onerror=p=>(s.close(),n(l.error)),i.oncomplete=()=>{u==null?s.close():u.oncomplete=()=>s.close()}},o.onerror=s=>n(o.error)})}};var zl="/",Kf="tensorflowjs_models",G$="info",Tne="model_topology",kne="weight_specs",Ine="weight_data",vne="model_metadata";function W$(r){return{info:[Kf,r,G$].join(zl),topology:[Kf,r,Tne].join(zl),weightSpecs:[Kf,r,kne].join(zl),weightData:[Kf,r,Ine].join(zl),modelMetadata:[Kf,r,vne].join(zl)}}function wne(r){let e=r.split(zl);if(e.length<3)throw new Error(`Invalid key format: ${r}`);return e.slice(1,e.length-1).join(zl)}function _ne(r){return r.startsWith(Gl.URL_SCHEME)?r.slice(Gl.URL_SCHEME.length):r}var Gl=class{constructor(e){if(!X().getBool("IS_BROWSER")||typeof window=="undefined"||typeof window.localStorage=="undefined")throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,e==null||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=W$(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{let t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),o=_i(e);try{this.LS.setItem(this.keys.info,JSON.stringify(o)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,F$(e.weightData));let s={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};return e.signature!=null&&(s.signature=e.signature),e.userDefinedMetadata!=null&&(s.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(s.modelInitializer=e.modelInitializer),this.LS.setItem(this.keys.modelMetadata,JSON.stringify(s)),{modelArtifactsInfo:o}}catch(s){throw this.LS.removeItem(this.keys.info),this.LS.removeItem(this.keys.topology),this.LS.removeItem(this.keys.weightSpecs),this.LS.removeItem(this.keys.weightData),this.LS.removeItem(this.keys.modelMetadata),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${o.modelTopologyBytes}, weightSpecsBytes=${o.weightSpecsBytes}, weightDataBytes=${o.weightDataBytes}.`)}}}async load(){let e=JSON.parse(this.LS.getItem(this.keys.info));if(e==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(e.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");let t={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(n==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=n;let o=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(o==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=o;let s=this.LS.getItem(this.keys.modelMetadata);if(s!=null){let a=JSON.parse(s);t.format=a.format,t.generatedBy=a.generatedBy,t.convertedBy=a.convertedBy,a.signature!=null&&(t.signature=a.signature),a.userDefinedMetadata!=null&&(t.userDefinedMetadata=a.userDefinedMetadata),a.modelInitializer!=null&&(t.modelInitializer=a.modelInitializer)}let i=this.LS.getItem(this.keys.weightData);if(i==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=R$(i),t}};Gl.URL_SCHEME="localstorage://";var K$=r=>X().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(Gl.URL_SCHEME)?Cne(r.slice(Gl.URL_SCHEME.length)):null;jt.registerSaveRouter(K$);jt.registerLoadRouter(K$);function Cne(r){return new Gl(r)}var DC=class{constructor(){R(X().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),R(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=Kf+zl,n=zl+G$;for(let o=0;o<this.LS.length;++o){let s=this.LS.key(o);if(s.startsWith(t)&&s.endsWith(n)){let i=wne(s);e[i]=JSON.parse(this.LS.getItem(s))}}return e}async removeModel(e){e=_ne(e);let t=W$(e);if(this.LS.getItem(t.info)==null)throw new Error(`Cannot find model at path '${e}'`);let n=JSON.parse(this.LS.getItem(t.info));return this.LS.removeItem(t.info),this.LS.removeItem(t.topology),this.LS.removeItem(t.weightSpecs),this.LS.removeItem(t.weightData),n}};var Vf="://",On=class{constructor(){this.managers={}}static getInstance(){return On.instance==null&&(On.instance=new On),On.instance}static registerManager(e,t){R(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(Vf)&&(e=e.slice(0,e.indexOf(Vf))),R(e.length>0,()=>"scheme must not be an empty string.");let n=On.getInstance();R(n.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),n.managers[e]=t}static getManager(e){let 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 cT(r){if(r.indexOf(Vf)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${On.getSchemes().join(",")}`);return{scheme:r.split(Vf)[0],path:r.split(Vf)[1]}}async function V$(r,e,t=!1){R(r!==e,()=>`Old path and new path are the same: '${r}'`);let n=jt.getLoadHandlers(r);R(n.length>0,()=>`Copying failed because no load handler is found for source URL ${r}.`),R(n.length<2,()=>`Copying failed because more than one (${n.length}) load handlers for source URL ${r}.`);let o=n[0],s=jt.getSaveHandlers(e);R(s.length>0,()=>`Copying failed because no save handler is found for destination URL ${e}.`),R(s.length<2,()=>`Copying failed because more than one (${n.length}) save handlers for destination URL ${e}.`);let i=s[0],a=cT(r).scheme,l=cT(r).path,u=a===cT(r).scheme,p=await o.load();t&&u&&await On.getManager(a).removeModel(l);let c=await i.save(p);return t&&!u&&await On.getManager(a).removeModel(l),c.modelArtifactsInfo}async function U$(){let r=On.getSchemes(),e={};for(let t of r){let n=await On.getManager(t).listModels();for(let o in n){let s=t+Vf+o;e[s]=n[o]}}return e}async function j$(r){let e=cT(r);return On.getManager(e.scheme).removeModel(e.path)}async function H$(r,e){return V$(r,e,!1)}async function q$(r,e){return V$(r,e,!0)}var X$=class{fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return this.textEncoder==null&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}};if(X().get("IS_BROWSER")){X().setPlatform("browser",new X$);try{On.registerManager(Gl.URL_SCHEME,new DC)}catch(r){}try{On.registerManager(Ol.URL_SCHEME,new AC)}catch(r){}}var Sne={importFetch:()=>Zw()},EC;var Y$=class{constructor(){this.util=Ap("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return X().global.fetch!=null?X().global.fetch(e,t):(EC==null&&(EC=Sne.importFetch()),EC(e,t))}now(){let e=process.hrtime();return e[0]*1e3+e[1]/1e6}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return e.length===0?"":new this.util.TextDecoder(t).decode(e)}};X().get("IS_NODE")&&X().setPlatform("node",new Y$);function ve(r,e="float32",t){return e=e||"float32",$h(r),new bt(r,e,t)}function Nne(r,e){let t=v(r,"x","cast");if(!nC(e))throw new Error(`Failed to cast to unknown dtype ${e}`);if(e==="string"&&t.dtype!=="string"||e!=="string"&&t.dtype==="string")throw new Error("Only strings can be casted to strings");let n={x:t},o={dtype:e};return M.runKernel(Do,n,o)}var ue=A({cast_:Nne});function Ane(r){let t={x:v(r,"x","clone","string_or_numeric")};return M.runKernel(Lo,t)}var jo=A({clone_:Ane});function MC(r,e=!1){console.log(r.toString(e))}IC();var Dne={buffer:ve,cast:ue,clone:jo,print:MC};_$(Dne);var fn={};Ge(fn,{browserFiles:()=>Q$,browserHTTPRequest:()=>rP,concatenateArrayBuffers:()=>Wf,copyModel:()=>H$,decodeWeights:()=>pT,encodeWeights:()=>E$,fromMemory:()=>oP,getLoadHandlers:()=>B$,getModelArtifactsInfoForJSON:()=>_i,getSaveHandlers:()=>P$,http:()=>dT,isHTTPScheme:()=>fT,listModels:()=>U$,loadWeights:()=>eP,moveModel:()=>q$,registerLoadRouter:()=>$$,registerSaveRouter:()=>L$,removeModel:()=>j$,weightsLoaderFactory:()=>LC,withSaveHandler:()=>sP});var Ene="model",Mne=".json",Fne=".weights.bin";function Z$(r){return new Promise(e=>setTimeout(e)).then(r)}var Ju=class{constructor(e){if(!X().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Ju.URL_SCHEME)&&(e=e.slice(Ju.URL_SCHEME.length)),(e==null||e.length===0)&&(e=Ene),this.modelTopologyFileName=e+Mne,this.weightDataFileName=e+Fne}async save(e){if(typeof document=="undefined")throw new Error("Browser downloads are not supported in this environment since `document` is not present");let 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.");{let n=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],o={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:n};e.signature!=null&&(o.signature=e.signature),e.userDefinedMetadata!=null&&(o.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(o.modelInitializer=e.modelInitializer);let s=window.URL.createObjectURL(new Blob([JSON.stringify(o)],{type:"application/json"})),i=this.jsonAnchor==null?document.createElement("a"):this.jsonAnchor;if(i.download=this.modelTopologyFileName,i.href=s,await Z$(()=>i.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){let a=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;a.download=this.weightDataFileName,a.href=t,await Z$(()=>a.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:_i(e)}}}};Ju.URL_SCHEME="downloads://";var J$=class{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(){let e=this.files[0],t=this.files.slice(1);return new Promise((n,o)=>{let s=new FileReader;s.onload=i=>{let a=JSON.parse(i.target.result),l=a.modelTopology;if(l==null){o(new Error(`modelTopology field is missing from file ${e.name}`));return}t.length===0&&n({modelTopology:l});let u=a.weightsManifest;if(u==null){o(new Error(`weightManifest field is missing from file ${e.name}`));return}let p;try{p=this.checkManifestAndWeightFiles(u,t)}catch(d){o(d);return}let c=[],m=[],f=[];u.forEach(d=>{d.paths.forEach(h=>{m.push(h),f.push(null)}),c.push(...d.weights)}),u.forEach(d=>{d.paths.forEach(h=>{let g=new FileReader;g.onload=b=>{let y=b.target.result,T=m.indexOf(h);if(f[T]=y,f.indexOf(null)===-1){let k={modelTopology:l,weightSpecs:c,weightData:Wf(f),format:a.format,generatedBy:a.generatedBy,convertedBy:a.convertedBy};a.signature!=null&&(k.signature=a.signature),a.userDefinedMetadata!=null&&(k.userDefinedMetadata=a.userDefinedMetadata),a.modelInitializer!=null&&(k.modelInitializer=a.modelInitializer),n(k)}},g.onerror=b=>o(`Failed to weights data from file of path '${h}'.`),g.readAsArrayBuffer(p[h])})})},s.onerror=i=>o(`Failed to read model topology and weights manifest JSON from file '${e.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),s.readAsText(e)})}checkManifestAndWeightFiles(e,t){let n=[],o=t.map(i=>_C(i.name)),s={};for(let i of e)i.paths.forEach(a=>{let l=_C(a);if(n.indexOf(l)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${l}'`);if(n.push(l),o.indexOf(l)===-1)throw new Error(`Weight file with basename '${l}' is not provided.`);s[a]=t[o.indexOf(l)]});if(n.length!==t.length)throw new Error(`Mismatch in the number of files in weights manifest (${n.length}) and the number of weight files provided (${t.length}).`);return s}},Rne=r=>X().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(Ju.URL_SCHEME)?Lne(r.slice(Ju.URL_SCHEME.length)):null;jt.registerSaveRouter(Rne);function Lne(r="model"){return new Ju(r)}function Q$(r){return new J$(r)}function FC(r,e,t,n){i(r),t=t==null?0:t,n=n==null?1:n,a(t,n);let o=0,s=l=>(l.then(u=>{let p=t+ ++o/r.length*(n-t);return e(p),u}),l);function i(l){R(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function a(l,u){R(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),R(u>=0&&u<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${u}`),R(u>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${u}`)}return Promise.all(r.map(s))}async function RC(r,e){e==null&&(e={});let t=e.fetchFunc==null?X().platform.fetch:e.fetchFunc,n=r.map(c=>t(c,e.requestInit,{isBinary:!0})),o=0,s=.5,a=(e.onProgress==null?await Promise.all(n):await FC(n,e.onProgress,o,s)).map(c=>c.arrayBuffer()),l=.5,u=1;return e.onProgress==null?await Promise.all(a):await FC(a,e.onProgress,l,u)}async function eP(r,e="",t,n){return LC(i=>RC(i,{requestInit:n}))(r,e,t)}function LC(r){return async(e,t="",n)=>{let o=e.map(()=>!1),s={},i=n!=null?n.map(()=>!1):[],a=[];if(e.forEach((f,d)=>{let h=0;f.weights.forEach(g=>{let b="quantization"in g?g.quantization.dtype:g.dtype,y=qh[b]*Nt(g.shape),T=()=>{o[d]=!0,s[d]==null&&(s[d]=[]),s[d].push({manifestEntry:g,groupOffset:h,sizeBytes:y})};n!=null?n.forEach((k,I)=>{k===g.name&&(T(),i[I]=!0)}):T(),a.push(g.name),h+=y})}),!i.every(f=>f)){let f=n.filter((d,h)=>!i[h]);throw new Error(`Could not find weights in manifest with names: ${f.join(", ")}.
|
|
Manifest JSON has weights with names: ${a.join(", ")}.`)}let l=o.reduce((f,d,h)=>(d&&f.push(h),f),[]),u=[];l.forEach(f=>{e[f].paths.forEach(d=>{let h=t+(t.endsWith("/")?"":"/")+d;u.push(h)})});let p=await r(u),c={},m=0;return l.forEach(f=>{let d=e[f].paths.length,h=0;for(let k=0;k<d;k++)h+=p[m+k].byteLength;let g=new ArrayBuffer(h),b=new Uint8Array(g),y=0;for(let k=0;k<d;k++){let I=new Uint8Array(p[m+k]);b.set(I,y),y+=I.byteLength}s[f].forEach(k=>{let I=g.slice(k.groupOffset,k.groupOffset+k.sizeBytes),S=pT(I,[k.manifestEntry]);for(let N in S)c[N]=S[N]}),m+=d}),c}}var $ne="application/octet-stream",Pne="application/json",mT=class{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?(R(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=X().platform.fetch,R(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&R(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.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],o={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:n};e.signature!=null&&(o.signature=e.signature),e.userDefinedMetadata!=null&&(o.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(o.modelInitializer=e.modelInitializer),t.body.append("model.json",new Blob([JSON.stringify(o)],{type:Pne}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:$ne}),"model.weights.bin");let s=await this.fetch(this.path,t);if(s.ok)return{modelArtifactsInfo:_i(e),responses:[s]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${s.status}.`)}async load(){let 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(d){let h=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?h+=" 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.":h+=" Please make sure the server is serving valid JSON for this request.",new Error(h)}let n=t.modelTopology,o=t.weightsManifest,s=t.generatedBy,i=t.convertedBy,a=t.format,l=t.signature,u=t.userDefinedMetadata;if(n==null&&o==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);let p,c;o!=null&&([p,c]=await this.loadWeights(o));let m={modelTopology:n,weightSpecs:p,weightData:c,generatedBy:s,convertedBy:i,format:a};l!=null&&(m.signature=l),u!=null&&(m.userDefinedMetadata=u);let f=t.modelInitializer;return f&&(m.modelInitializer=f),m}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,o]=Bne(t),s=this.weightPathPrefix||n,i=[];for(let p of e)i.push(...p.weights);let a=[],l=[];for(let p of e)for(let c of p.paths)this.weightUrlConverter!=null?l.push(this.weightUrlConverter(c)):a.push(s+c+o);this.weightUrlConverter&&a.push(...await Promise.all(l));let u=await RC(a,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[i,Wf(u)]}};mT.URL_SCHEME_REGEX=/^https?:\/\//;function Bne(r){let e=r.lastIndexOf("/"),t=r.lastIndexOf("?"),n=r.substring(0,e),o=t>e?r.substring(t):"";return[n+"/",o]}function fT(r){return r.match(mT.URL_SCHEME_REGEX)!=null}var tP=(r,e)=>{if(typeof fetch=="undefined"&&(e==null||e.fetchFunc==null))return null;{let t=!0;if(Array.isArray(r)?t=r.every(n=>fT(n)):t=fT(r),t)return dT(r,e)}return null};jt.registerSaveRouter(tP);jt.registerLoadRouter(tP);function dT(r,e){return new mT(r,e)}function rP(r,e){return dT(r,e)}var hT=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},nP=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function oP(r,e,t,n){return arguments.length===1?r.modelTopology!=null||r.weightSpecs!=null?new hT(r):(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 hT({modelTopology:r})):(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 hT({modelTopology:r,weightSpecs:e,weightData:t,trainingConfig:n}))}function sP(r){return new nP(r)}function One(r,e,t=!1,n=!1){let o=v(r,"a","matMul"),s=v(e,"b","matMul");[o,s]=et(o,s);let i={a:o,b:s},a={transposeA:t,transposeB:n};return M.runKernel(Us,i,a)}var tt=A({matMul_:One});function zne(r,e,t=1,n=0){if(e<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${e}`);let s={indices:v(r,"indices","oneHot","int32")},i={depth:e,onValue:t,offValue:n};return M.runKernel(fa,s,i)}var Ea=A({oneHot_:zne});function Gne(r,e){let t=v(r,"x","transpose");if(e==null&&(e=t.shape.map((s,i)=>i).reverse()),R(t.rank===e.length,()=>`Error in transpose: rank of input ${t.rank} must match length of perm ${e}.`),e.forEach(s=>{R(s>=0&&s<t.rank,()=>`All entries in 'perm' must be between 0 and ${t.rank-1} but got ${e}`)}),t.rank<=1)return t.clone();let n={x:t},o={perm:e};return M.runKernel(ps,n,o)}var nt=A({transpose_:Gne});function Wne(r,e,t){let n=v(r,"labels","confusionMatrix"),o=v(e,"predictions","confusionMatrix");R(t==null||t>0&&Number.isInteger(t),()=>`If provided, numClasses must be a positive integer, but got ${t}`),R(n.rank===1,()=>`Expected the rank of labels to be 1, but got ${n.rank}`),R(o.rank===1,()=>`Expected the rank of predictions to be 1, but got ${o.rank}`),R(n.shape[0]===o.shape[0],()=>`Mismatch in the number of examples: ${n.shape[0]} vs. ${o.shape[0]}. Labels and predictions should have the same number of elements.`),R(t>0&&Number.isInteger(t),()=>`numClasses is required to be a positive integer, but got ${t}`);let s=Ea(ue(n,"int32"),t),i=Ea(ue(o,"int32"),t),a=nt(s),l=tt(a,i);return ue(l,"int32")}var Kne=A({confusionMatrix_:Wne});var gT={};Ge(gT,{fromPixels:()=>Zne,fromPixelsAsync:()=>Xne,toPixels:()=>Yne});function $C(r,e,t){if(li(r),e!=null&&e.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let n=Vo(r,t);if(n.length!==3&&n.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(n.length===1&&e==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Uo(r,e,n,t)}var Uf;function aP(r,e=3){if(e>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(r==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let t=!1,n=!1,o=!1,s=!1,i=!1,a=!1;if(r.data instanceof Uint8Array)t=!0;else if(typeof ImageData!="undefined"&&r instanceof ImageData)n=!0;else if(typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement)o=!0;else if(typeof HTMLImageElement!="undefined"&&r instanceof HTMLImageElement)s=!0;else if(r.getContext!=null)i=!0;else if(typeof ImageBitmap!="undefined"&&r instanceof ImageBitmap)a=!0;else throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${r.constructor.name}`);if(o){let d=2;if(o&&r.readyState<d)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.")}if(Wh(Gh,M.backendName)!=null){let d={pixels:r},h={numChannels:e};return M.runKernel(Gh,d,h)}let[u,p]=o?[r.videoWidth,r.videoHeight]:[r.width,r.height],c;i?c=r.getContext("2d").getImageData(0,0,u,p).data:n||t?c=r.data:(s||o||a)&&(Uf==null&&(Uf=document.createElement("canvas").getContext("2d")),Uf.canvas.width=u,Uf.canvas.height=p,Uf.drawImage(r,0,0,u,p),c=Uf.getImageData(0,0,u,p).data);let m;if(e===4)m=new Int32Array(c);else{let d=u*p;m=new Int32Array(d*e);for(let h=0;h<d;h++)for(let g=0;g<e;++g)m[h*e+g]=c[h*4+g]}return $C(m,[p,u,e],"int32")}function Une(r){return r!=null&&r.data instanceof Uint8Array}function jne(){return typeof window!="undefined"&&typeof ImageBitmap!="undefined"&&window.hasOwnProperty("createImageBitmap")}function Hne(r){return r!=null&&r.width!==0&&r.height!==0}function qne(r){return jne()&&!(r instanceof ImageBitmap)&&Hne(r)&&!Une(r)}async function Xne(r,e=3){let t=null;if(X().getBool("WRAP_TO_IMAGEBITMAP")&&qne(r)){let n;try{n=await createImageBitmap(r,{premultiplyAlpha:"none"})}catch(o){n=null}n!=null&&n.width===r.width&&n.height===r.height?t=n:t=r}else t=r;return aP(t,e)}async function Yne(r,e){let t=v(r,"img","toPixels");if(!(r instanceof rt)){let u=t;t=ue(u,"int32"),u.dispose()}if(t.rank!==2&&t.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${t.rank}.`);let[n,o]=t.shape.slice(0,2),s=t.rank===2?1:t.shape[2];if(s>4||s===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${s}`);if(t.dtype!=="float32"&&t.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${t.dtype}. Please use float32 or int32 tensors.`);let i=await t.data(),a=t.dtype==="float32"?255:1,l=new Uint8ClampedArray(o*n*4);for(let u=0;u<n*o;++u){let p=[0,0,0,255];for(let m=0;m<s;m++){let f=i[u*s+m];if(t.dtype==="float32"){if(f<0||f>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${f}.`)}else if(t.dtype==="int32"&&(f<0||f>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${f}.`);s===1?(p[0]=f*a,p[1]=f*a,p[2]=f*a):p[m]=f*a}let c=u*4;l[c+0]=Math.round(p[0]),l[c+1]=Math.round(p[1]),l[c+2]=Math.round(p[2]),l[c+3]=Math.round(p[3])}if(e!=null){e.width=o,e.height=n;let u=e.getContext("2d"),p=new ImageData(l,o,n);u.putImageData(p,0,0)}return t!==r&&t.dispose(),l}var Zne=A({fromPixels_:aP});var bT={};Ge(bT,{prepareAndValidate:()=>iP});function iP(r,e){let t=r.shape.length,n=e.shape.length;if(t<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${t}.`);if(n<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${n}.`);if(e.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.shape[n-1]>t)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${e.shape[n-1]} vs. ${t}`);if(Nt(r.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${r.shape}.`);let o=e.shape,s=o[o.length-1],i=1;for(let c=0;c<o.length-1;++c)i*=o[c];let a=r.shape,l=o.slice();l.pop();let u=1;for(let c=s;c<t;++c)u*=a[c],l.push(a[c]);let p=[...ui(r.shape).map(c=>c/u),1].slice(0,s);return[l,i,u,p]}var xT={};Ge(xT,{calculateShapes:()=>lP,validateInput:()=>yT,validateUpdateShape:()=>PC});function PC(r,e,t){let n=e.rank>1?e.shape[e.rank-1]:1,o=e.rank>1?e.rank-1:1,s=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${t.shape}, indices.shape: ${e.shape}, shape: ${r}, sliceDim: ${n}, and batchDim: ${o}.`;if(t.rank<o)throw new Error(s+` update.rank < ${o}. `);if(r.length<n+(t.rank-o))throw new Error(s+` Output shape length < ${n+(t.rank-o)}`);if(t.rank!==o+r.length-n)throw new Error(s+` update.rank != ${o+r.length-n}`);for(let i=0;i<o;++i)if(t.shape[i]!==e.shape[i])throw new Error(s+` updates.shape[${i}] (${t.shape[i]}) != indices.shape[${i}] (${e.shape[i]}).`);for(let i=0;i<t.rank-o;++i)if(t.shape[i+o]!==r[i+n])throw new Error(s+` updates.shape[${i+o}] (${t.shape[i+o]}) != shape[${i+o}] (${r[i+o]})`)}function yT(r,e,t){if(e.rank<1)throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${e.rank}.`);if(r.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${r.rank}.`);if(e.dtype!=="int32")throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${e.dtype}`);if(t.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${t}`);if(t.length===0){if(e.size===0)throw new Error(`Indices specified for empty output. indices shape: ${e.shape}`);if(r.size===0)throw new Error(`Updates specified for empty output. updates shape: ${r.shape}`)}PC(t,e,r)}function lP(r,e,t){let n=e.shape.length,o=n>1?e.shape[n-1]:1,s=t.length,i=1;for(let c=o;c<s;++c)i*=t[c];let a=o<1?1:o,l=Nt(e.shape)/a,u=[...ui(t.slice(0,o)),1],p=Nt(t);return{sliceRank:o,numUpdates:l,sliceSize:i,strides:u,outputSize:p}}var br={};Ge(br,{assertParamsValid:()=>Jne,computeFlatOffset:()=>eoe,computeOutShape:()=>uP,getNormalizedAxes:()=>fP,isSliceContinous:()=>Qne,maskToAxes:()=>TT,parseSliceParams:()=>BC,sliceInfo:()=>toe,startForAxis:()=>bP,startIndicesWithElidedDims:()=>dP,stopForAxis:()=>yP,stopIndicesWithElidedDims:()=>hP,stridesForAxis:()=>gP,stridesWithElidedDims:()=>pP});function Jne(r,e,t){let n=r.shape.length;R(n===e.length,()=>`Error in slice${n}D: Length of begin ${e} must match the rank of the array (${n}).`),R(n===t.length,()=>`Error in slice${n}D: Length of size ${t} must match the rank of the array (${n}).`);for(let o=0;o<n;++o)R(e[o]+t[o]<=r.shape[o],()=>`Error in slice${n}D: begin[${o}] + size[${o}] (${e[o]+t[o]}) would overflow input.shape[${o}] (${r.shape[o]})`)}function TT(r){let e=[],t=0;for(;r>0;)r&1&&e.push(t),r/=2,t++;return e}function uP(r,e,t){let n=[];for(let o=0;o<r.length;o++)n[o]=Math.ceil((e[o]-r[o])/t[o]);return n}function pP(r,e,t,n){let o=[...r];for(let s=o.length;s<n.length;s++)o.push(1);for(let s=0;s<t;s++)s===0?o[e]=1:(o.splice(e,0,1),o.pop());return o}function cP(r,e,t){return t<=r?t:t-(e-1)}function mP(r,e){let t=[];for(let n=0;n<r;n++)t.push(e+n);return t}function fP(r,e,t,n,o,s,i,a,l){let u=r.length,p=new Array(u),c=new Array(u),m=new Array(u);if(e.length&&t>0){let f=e[0],d=t+1;p=dP(i,f,d,n,r),c=hP(a,f,d,o,r),m=pP(s,f,d,r)}else for(let f=0;f<u;f++)p[f]=bP(i,n,s,r,f,l),c[f]=yP(a,o,s,r,f,l),m[f]=gP(s,f,l);return{begin:p,end:c,strides:m}}function dP(r,e,t,n,o){let s=[...o],i=mP(t,e);for(let a=0;a<s.length;a++)if(i.indexOf(a)>-1)s[a]=0;else{let l=cP(e,t,a),u=n[l];r&1<<l&&(u=0),s[a]=u}return s}function hP(r,e,t,n,o){let s=[...o],i=mP(t,e);for(let a=0;a<s.length;a++)if(i.indexOf(a)>-1)s[a]=Number.MAX_SAFE_INTEGER;else{let l=cP(e,t,a),u=n[l];r&1<<l&&(u=Number.MAX_SAFE_INTEGER),s[a]=u}for(let a=0;a<s.length;a++){let l=o[a];s[a]<0&&(s[a]+=l),s[a]=ef(0,s[a],o[a])}return s}function gP(r,e,t){let n=r[e];return(t&1<<e||n==null)&&(n=1),n}function bP(r,e,t,n,o,s){let i=e[o],a=t[o]||1;(r&1<<o||s&1<<o||i==null)&&(a>0?i=Number.MIN_SAFE_INTEGER:i=Number.MAX_SAFE_INTEGER);let l=n[o];return i<0&&(i+=l),i=ef(0,i,l-1),i}function yP(r,e,t,n,o,s){let i=e[o],a=t[o]||1;(r&1<<o||s&1<<o||i==null)&&(a>0?i=Number.MAX_SAFE_INTEGER:i=Number.MIN_SAFE_INTEGER);let l=n[o];return i<0&&(i+=l),a>0?i=ef(0,i,l):i=ef(-1,i,l-1),i}function Qne(r,e,t){let n=t.length;for(let o=0;o<t.length;o++)if(t[o]>1){n=o;break}for(let o=n+1;o<t.length;o++)if(e[o]>0||t[o]!==r[o])return!1;return!0}function eoe(r,e){let t=r.length>0?r[r.length-1]:1;for(let n=0;n<r.length-1;n++)t+=r[n]*e[n];return t}function BC(r,e,t){let n,o=r.shape.length;typeof e=="number"?n=[e,...new Array(o-1).fill(0)]:e.length<o?n=e.concat(new Array(o-e.length).fill(0)):n=e.slice(),n.forEach(i=>{R(i!==-1,()=>"slice() does not support negative begin indexing.")});let s;return t==null?s=new Array(o).fill(-1):typeof t=="number"?s=[t,...new Array(o-1).fill(-1)]:t.length<o?s=t.concat(new Array(o-t.length).fill(-1)):s=t,s=s.map((i,a)=>i>=0?i:(R(i===-1,()=>`Negative size values should be exactly -1 but got ${i} for the slice() size at index ${a}.`),r.shape[a]-n[a])),[n,s]}function toe(r,e,t,n,o,s,i,a,l){let u=e.slice(),p=t.slice(),c=n;n==null&&(c=new Array(u.length));let m=TT(i);if(m.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(i!==0&&a!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(i!==0&&l!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");let f=r.length-u.length,d=TT(a),h=r.slice();d.forEach(N=>{u[N]=0,p[N]=1,h.splice(N,0,1)});let{begin:g,end:b,strides:y}=fP(h,m,f,u,p,c,o,s,i);u=g,p=b,c=y;let T=TT(l);T.forEach(N=>{p[N]=u[N]+1,c[N]=1});let k=uP(u,p,c),I=k.filter((N,F)=>T.indexOf(F)===-1);return{nonStrided:c.every(N=>N===1),$begin:u,$end:p,$strides:c,size:k,newShape:h,outShape:I}}var oe={};Ge(oe,{Serializable:()=>kT,SerializationMap:()=>Wl,registerClass:()=>ao});var kT=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},Wl=class{constructor(){this.classNameMap={}}static getMap(){return Wl.instance==null&&(Wl.instance=new Wl),Wl.instance}static register(e){Wl.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function ao(r){R(r.className!=null,()=>"Class being registered does not have the static className property defined."),R(typeof r.className=="string",()=>"className is required to be a string, but got type "+typeof r.className),R(r.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),Wl.register(r)}function OC(r){X().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(r+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}C$(OC);function Ma(){return M}function Xh(){return M.memory()}function j(r,e){return M.tidy(r,e)}function Be(r){Hh(r).forEach(t=>t.dispose())}function er(r){return M.keep(r)}function jf(r,e,t=1){return M.registerBackend(r,e,t)}function xP(){return M.backend}function noe(r,e){let t=v(r,"a","add"),n=v(e,"b","add");[t,n]=et(t,n);let o={a:t,b:n};return M.runKernel(so,o)}var ne=A({add_:noe});function ooe(r,e){let t=v(r,"a","floorDiv"),n=v(e,"b","floorDiv");[t,n]=et(t,n);let o={a:t,b:n};return M.runKernel(ea,o)}var Tc=A({floorDiv_:ooe});function soe(r,e){let t=v(r,"a","div"),n=v(e,"b","div");if([t,n]=et(t,n),t.dtype==="int32"&&n.dtype==="int32")return Tc(t,n);let o={a:t,b:n},s={};return M.runKernel(Zs,o,s)}var he=A({div_:soe});function aoe(r,e){let t=v(r,"a","mul"),n=v(e,"b","mul");[t,n]=et(t,n);let o={a:t,b:n};return M.runKernel(Oo,o)}var G=A({mul_:aoe});function ioe(r){let e=v(r,"x","abs");if(e.dtype==="complex64"){let t={x:e};return M.runKernel(Pu,t)}else{let t={x:e};return M.runKernel(Gs,t)}}var Ht=A({abs_:ioe});function loe(r){let t={x:v(r,"x","acos")};return M.runKernel(ol,t)}var Yh=A({acos_:loe});function uoe(r){let t={x:v(r,"x","acosh")};return M.runKernel(sl,t)}var Zh=A({acosh_:uoe});function poe(r){R(Array.isArray(r),()=>"The argument passed to tf.addN() must be a list of tensors"),R(r.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${r.length}`);let e=r.map((o,s)=>v(o,`tensors${s}`,"addN")),t=e[0];e.forEach(o=>{if(o.dtype!==t.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),e.forEach(o=>{if(!no(o.shape,t.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let n=e;return M.runKernel(Ws,n)}var zC=A({addN_:poe});function coe(r,e=null,t=!1){let o={x:v(r,"x","all","bool")},s={axis:e,keepDims:t};return M.runKernel(al,o,s)}var kc=A({all_:coe});function moe(r,e=null,t=!1){let o={x:v(r,"x","any","bool")},s={axis:e,keepDims:t};return M.runKernel(il,o,s)}var Qu=A({any_:moe});function foe(r,e=0){let n={x:v(r,"x","argMax")},o={axis:e};return M.runKernel(Ks,n,o)}var ep=A({argMax_:foe});function doe(r,e=0){let n={x:v(r,"x","argMin")},o={axis:e};return M.runKernel(Ru,n,o)}var Jh=A({argMin_:doe});function hoe(r){let t={x:v(r,"x","asin")};return M.runKernel(ll,t)}var Qh=A({asin_:hoe});function goe(r){let t={x:v(r,"x","asinh")};return M.runKernel(ul,t)}var eg=A({asinh_:goe});function boe(r){let t={x:v(r,"x","atan")};return M.runKernel(pl,t)}var tg=A({atan_:boe});function yoe(r,e){let t=v(r,"a","atan2"),n=v(e,"b","atan2");[t,n]=et(t,n);let o={a:t,b:n};return M.runKernel(ml,o)}var rg=A({atan2_:yoe});function xoe(r){let t={x:v(r,"x","atanh")};return M.runKernel(cl,t)}var ng=A({atanh_:xoe});function Toe(r,e,t,n,o="NHWC",s){let i=r[3],a=[...e,i],l=kP(o);return Ic(r,a,t,s,n,null,null,l)}function GC(r,e,t,n,o,s,i="channelsLast"){let[a,l]=IT(e),u;if(i==="channelsLast")u=[a,l,r[3],r[3]];else if(i==="channelsFirst")u=[a,l,r[1],r[1]];else throw new Error(`Unknown dataFormat ${i}`);return Ic(r,u,t,n,o,s,!1,i)}function koe(r,e,t,n,o,s,i="NDHWC"){let[a,l,u]=KC(e),p,c;if(i==="NDHWC")c="channelsLast",p=[a,l,u,r[4],r[4]];else if(i==="NCDHW")c="channelsFirst",p=[a,l,u,r[1],r[1]];else throw new Error(`Unknown dataFormat ${i}`);return TP(r,p,t,n,o,!1,c,s)}function Ic(r,e,t,n,o,s,i=!1,a="channelsLast"){let[l,u,p,c]=[-1,-1,-1,-1];if(a==="channelsLast")[l,u,p,c]=r;else if(a==="channelsFirst")[l,c,u,p]=r;else throw new Error(`Unknown dataFormat ${a}`);let[m,f,,d]=e,[h,g]=IT(t),[b,y]=IT(n),T=Hf(m,b),k=Hf(f,y),{padInfo:I,outHeight:S,outWidth:N}=woe(o,u,p,h,g,T,k,s,a),F=i?d*c:d,$;return a==="channelsFirst"?$=[l,F,S,N]:a==="channelsLast"&&($=[l,S,N,F]),{batchSize:l,dataFormat:a,inHeight:u,inWidth:p,inChannels:c,outHeight:S,outWidth:N,outChannels:F,padInfo:I,strideHeight:h,strideWidth:g,filterHeight:m,filterWidth:f,effectiveFilterHeight:T,effectiveFilterWidth:k,dilationHeight:b,dilationWidth:y,inShape:r,outShape:$,filterShape:e}}function TP(r,e,t,n,o,s=!1,i="channelsLast",a){let[l,u,p,c,m]=[-1,-1,-1,-1,-1];if(i==="channelsLast")[l,u,p,c,m]=r;else if(i==="channelsFirst")[l,m,u,p,c]=r;else throw new Error(`Unknown dataFormat ${i}`);let[f,d,h,,g]=e,[b,y,T]=KC(t),[k,I,S]=KC(n),N=Hf(f,k),F=Hf(d,I),$=Hf(h,S),{padInfo:O,outDepth:V,outHeight:q,outWidth:W}=_oe(o,u,p,c,b,y,T,N,F,$,a),Y=s?g*m:g,Z;return i==="channelsFirst"?Z=[l,Y,V,q,W]:i==="channelsLast"&&(Z=[l,V,q,W,Y]),{batchSize:l,dataFormat:i,inDepth:u,inHeight:p,inWidth:c,inChannels:m,outDepth:V,outHeight:q,outWidth:W,outChannels:Y,padInfo:O,strideDepth:b,strideHeight:y,strideWidth:T,filterDepth:f,filterHeight:d,filterWidth:h,effectiveFilterDepth:N,effectiveFilterHeight:F,effectiveFilterWidth:$,dilationDepth:k,dilationHeight:I,dilationWidth:S,inShape:r,outShape:Z,filterShape:e}}function Ioe(r,e,t,n,o){n==null&&(n=WC(r,e,t));let s=r[0],i=r[1],a=vc((s-e+2*n)/t+1,o),l=vc((i-e+2*n)/t+1,o);return[a,l]}function voe(r,e,t,n,o,s){o==null&&(o=WC(r,e,n));let i=r[0],a=r[1],l=r[2],u=vc((i-e+2*o)/n+1,s),p=vc((a-e+2*o)/n+1,s),c=vc((l-e+2*o)/n+1,s);return[u,p,c,t]}function WC(r,e,t,n=1){let o=Hf(e,n);return Math.floor((r[0]*(t-1)-t+o)/2)}function IT(r){return typeof r=="number"?[r,r,r]:r.length===2?[r[0],r[1],1]:r}function KC(r){return typeof r=="number"?[r,r,r]:r}function Hf(r,e){return e<=1?r:r+(r-1)*(e-1)}function woe(r,e,t,n,o,s,i,a,l){let u,p,c;if(typeof r=="number"){u={top:r,bottom:r,left:r,right:r,type:r===0?"VALID":"NUMBER"};let f=Ioe([e,t],s,n,r,a);p=f[0],c=f[1]}else if(r==="same"){p=Math.ceil(e/n),c=Math.ceil(t/o);let m=Math.max(0,(p-1)*n+s-e),f=Math.max(0,(c-1)*o+i-t),d=Math.floor(m/2),h=m-d,g=Math.floor(f/2),b=f-g;u={top:d,bottom:h,left:g,right:b,type:"SAME"}}else if(r==="valid")u={top:0,bottom:0,left:0,right:0,type:"VALID"},p=Math.ceil((e-s+1)/n),c=Math.ceil((t-i+1)/o);else if(typeof r=="object"){let m=l==="channelsLast"?r[1][0]:r[2][0],f=l==="channelsLast"?r[1][1]:r[2][1],d=l==="channelsLast"?r[2][0]:r[3][0],h=l==="channelsLast"?r[2][1]:r[3][1];u={top:m,bottom:f,left:d,right:h,type:m===0&&f===0&&d===0&&h===0?"VALID":"EXPLICIT"},p=vc((e-s+m+f)/n+1,a),c=vc((t-i+d+h)/o+1,a)}else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:u,outHeight:p,outWidth:c}}function _oe(r,e,t,n,o,s,i,a,l,u,p){let c,m,f,d;if(typeof r=="number"){c={top:r,bottom:r,left:r,right:r,front:r,back:r,type:r===0?"VALID":"NUMBER"};let g=voe([e,t,n,1],a,1,o,r,p);m=g[0],f=g[1],d=g[2]}else if(r==="same"){m=Math.ceil(e/o),f=Math.ceil(t/s),d=Math.ceil(n/i);let h=(m-1)*o+a-e,g=(f-1)*s+l-t,b=(d-1)*i+u-n,y=Math.floor(h/2),T=h-y,k=Math.floor(g/2),I=g-k,S=Math.floor(b/2),N=b-S;c={top:k,bottom:I,left:S,right:N,front:y,back:T,type:"SAME"}}else if(r==="valid")c={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},m=Math.ceil((e-a+1)/o),f=Math.ceil((t-l+1)/s),d=Math.ceil((n-u+1)/i);else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:c,outDepth:m,outHeight:f,outWidth:d}}function vc(r,e){if(!e)return Math.trunc(r);switch(e){case"round":return Math.round(r);case"ceil":return Math.ceil(r);case"floor":return Math.floor(r);default:throw new Error(`Unknown roundingMode ${e}`)}}function Ho(r){let[e,t,n]=IT(r);return e===1&&t===1&&n===1}function rn(r,e){return Ho(r)||Ho(e)}function kP(r){if(r==="NHWC")return"channelsLast";if(r==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${r}`)}function Coe(r,e){let n={x:v(r,"x","reshape","string_or_numeric")},o={shape:e};return M.runKernel(gi,n,o)}var K=A({reshape_:Coe});function Soe(r,e,t,n,o){let s=v(r,"x","avgPool","float32"),i=1;R(rn(t,i),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${t} and dilations '${i}'`);let a=s,l=!1;s.rank===3&&(l=!0,a=K(s,[1,s.shape[0],s.shape[1],s.shape[2]])),R(a.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${a.rank}.`),o!=null&&R(xt(n),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`);let u={x:a},p={filterSize:e,strides:t,pad:n,dimRoundingMode:o},c=M.runKernel(Vs,u,p);return c=ue(c,s.dtype),l?K(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var Kl=A({avgPool_:Soe});function Noe(r,e,t,n,o,s="NDHWC"){let i=v(r,"x","avgPool3d","float32"),a=i,l=!1;i.rank===4&&(l=!0,a=K(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),R(a.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${a.rank}.`),R(s==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),o!=null&&R(xt(n),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`);let u={x:a},p={filterSize:e,strides:t,pad:n,dimRoundingMode:o,dataFormat:s},c=M.runKernel(Lu,u,p);return c=ue(c,a.dtype),l?K(c,[c.shape[1],c.shape[2],c.shape[3],c.shape[4]]):c}var og=A({avgPool3d_:Noe});function Aoe(r,e=0){R(r.length>=1,()=>"Pass at least one tensor to concat");let t=Yu(r,"tensors","concat","string_or_numeric");if(t[0].dtype==="complex64"&&t.forEach(s=>{if(s.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
|
|
with dtype ${s.dtype}. `)}),t.length===1)return jo(t[0]);let n=t,o={axis:e};return M.runKernel(pi,n,o)}var mt=A({concat_:Aoe});function Doe(r){let t={x:v(r,"x","sigmoid")};return M.runKernel(wa,t)}var dn=A({sigmoid_:Doe});function Eoe(r,e,t){let n=v(r,"x","slice","string_or_numeric");if(n.rank===0)throw new Error("Slicing scalar is not possible");let o={x:n},s={begin:e,size:t};return M.runKernel(Ia,o,s)}var Ke=A({slice_:Eoe});function Moe(r){let t={x:v(r,"x","tanh")};return M.runKernel(Aa,t)}var Fa=A({tanh_:Moe});function Foe(r,e,t,n,o,s){let i=v(r,"forgetBias","basicLSTMCell"),a=v(e,"lstmKernel","basicLSTMCell"),l=v(t,"lstmBias","basicLSTMCell"),u=v(n,"data","basicLSTMCell"),p=v(o,"c","basicLSTMCell"),c=v(s,"h","basicLSTMCell"),m=mt([u,c],1),f=tt(m,a),d=ne(f,l),h=d.shape[0],g=d.shape[1]/4,b=[h,g],y=Ke(d,[0,0],b),T=Ke(d,[0,g],b),k=Ke(d,[0,g*2],b),I=Ke(d,[0,g*3],b),S=ne(G(dn(y),Fa(T)),G(p,dn(ne(i,k)))),N=G(Fa(S),dn(I));return[S,N]}var Roe=A({basicLSTMCell_:Foe});function Loe(r,e,t){let n=v(r,"x","batchToSpaceND"),o=e.reduce((a,l)=>a*l);R(n.rank>=1+e.length,()=>`input rank is ${n.rank} but should be > than blockShape.length ${e.length}`),R(t.length===e.length,()=>`crops.length is ${t.length} but should be equal to blockShape.length ${e.length}`),R(n.shape[0]%o==0,()=>`input tensor batch is ${n.shape[0]} but is not divisible by the product of the elements of blockShape ${e.join(" * ")} === ${o}`);let s={x:n},i={blockShape:e,crops:t};return M.runKernel($u,s,i)}var Vl=A({batchToSpaceND_:Loe});function IP(r){let e;return r.rank===0||r.rank===1?e=K(r,[1,1,1,r.size]):r.rank===2?e=K(r,[1,1,r.shape[0],r.shape[1]]):r.rank===3?e=K(r,[1,r.shape[0],r.shape[1],r.shape[2]]):e=r,e}function $oe(r,e,t,n,o,s){s==null&&(s=.001);let i=v(r,"x","batchNorm"),a=v(e,"mean","batchNorm"),l=v(t,"variance","batchNorm"),u;o!=null&&(u=v(o,"scale","batchNorm"));let p;n!=null&&(p=v(n,"offset","batchNorm")),R(a.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),R(p==null||a.rank===p.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),R(u==null||a.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let m={x:IP(i),scale:u,offset:p,mean:a,variance:l},f={varianceEpsilon:s},d=M.runKernel(ta,m,f);return K(d,i.shape)}var fs=A({batchNorm_:$oe});function Poe(r,e,t,n,o,s){let i=v(r,"x","batchNorm"),a=v(e,"mean","batchNorm"),l=v(t,"variance","batchNorm"),u;o!=null&&(u=v(o,"scale","batchNorm"));let p;return n!=null&&(p=v(n,"offset","batchNorm")),R(i.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`),R(a.rank===2||a.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${a.rank}.`),R(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&R(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),p!=null&&R(p.rank===2||p.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${p.rank}.`),fs(i,a,l,p,u,s)}var VC=A({batchNorm2d_:Poe});function Boe(r,e,t,n,o,s){let i=v(r,"x","batchNorm"),a=v(e,"mean","batchNorm"),l=v(t,"variance","batchNorm"),u;o!=null&&(u=v(o,"scale","batchNorm"));let p;return n!=null&&(p=v(n,"offset","batchNorm")),R(i.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`),R(a.rank===3||a.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${a.rank}.`),R(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&R(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),p!=null&&R(p.rank===3||p.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${p.rank}.`),fs(i,a,l,p,u,s)}var UC=A({batchNorm3d_:Boe});function Ooe(r,e,t,n,o,s){let i=v(r,"x","batchNorm"),a=v(e,"mean","batchNorm"),l=v(t,"variance","batchNorm"),u;o!=null&&(u=v(o,"scale","batchNorm"));let p;return n!=null&&(p=v(n,"offset","batchNorm")),R(i.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`),R(a.rank===4||a.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${a.rank}.`),R(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),u!=null&&R(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`),p!=null&&R(p.rank===4||p.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${p.rank}.`),fs(i,a,l,p,u,s)}var jC=A({batchNorm4d_:Ooe});function zoe(r,e,t){let n=v(r,"x","bincount"),o=v(e,"weights","bincount");R(n.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${n.dtype}`),R(t>=0,()=>`size must be non-negative, but got ${t}.`),R(o.size===n.size||o.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${n.shape}, weights shape: ${o.shape}.`);let s={x:n,weights:o},i={size:t};return M.runKernel(lf,s,i)}var sg=A({bincount_:zoe});function Goe(r,e){let t=v(r,"broadcastTo","x"),n=t.shape;if(e.some(u=>!(u>0)||u%1!=0))throw new Error(`broadcastTo(): Invalid broadcast shape [${e}].`);if(e.length<t.rank)throw new Error(`broadcastTo(): shape.length=${e.length} < input.rank=${t.rank}.`);if(e.length>t.rank){let u=t.shape.slice();for(;u.length<e.length;)u.unshift(1);t=K(t,u)}let o=t.shape,s=Array.from(e);for(let u=e.length-1;u>=0;u--)if(o[u]===e[u])s[u]=1;else if(t.shape[u]!==1)throw new Error(`broadcastTo(): [${n}] cannot be broadcast to [${e}].`);if(s.map((u,p)=>u>1?p:-1).filter(u=>u>=0).length===0)return jo(t);let a={x:t},l={reps:s};return M.runKernel(Ko,a,l)}var Ul=A({broadcastTo_:Goe});function Woe(r){let t={x:v(r,"x","ceil")};return M.runKernel(Eo,t)}var ag=A({ceil_:Woe});function Koe(r,e,t){let n=v(r,"x","clipByValue");R(e<=t,()=>`Error in clip: min (${e}) must be less than or equal to max (${t}).`);let o={x:n},s={clipValueMin:e,clipValueMax:t};return M.runKernel(us,o,s)}var Gr=A({clipByValue_:Koe});function Voe(r){return mt(r,0)}var HC=A({concat1d_:Voe});function Uoe(r,e){return mt(r,e)}var qC=A({concat2d_:Uoe});function joe(r,e){return mt(r,e)}var XC=A({concat3d_:joe});function Hoe(r,e){return mt(r,e)}var YC=A({concat4d_:Hoe});function qoe(r,e,t,n,o="NHWC",s=[1,1],i){let a=v(r,"x","conv2d"),l=v(e,"filter","conv2d"),u=a,p=!1;a.rank===3&&(p=!0,u=K(a,[1,a.shape[0],a.shape[1],a.shape[2]])),R(u.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`),R(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),i!=null&&R(xt(n),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${n}.`);let c=o==="NHWC"?u.shape[3]:u.shape[1];R(c===l.shape[2],()=>`Error in conv2d: depth of input (${c}) must match input depth for filter ${l.shape[2]}.`),R(rn(t,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`);let m={x:u,filter:l},f={strides:t,pad:n,dataFormat:o,dilations:s,dimRoundingMode:i},d=M.runKernel(js,m,f);return p?K(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var zn=A({conv2d_:qoe});function Xoe(r,e,t,n,o="NWC",s=1,i){let a=v(r,"x","conv1d"),l=v(e,"filter","conv1d"),u=a,p=!1;a.rank===2&&(p=!0,u=K(a,[1,a.shape[0],a.shape[1]])),R(u.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`),R(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),i!=null&&R(xt(n),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${n}.`),R(u.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`),R(rn(t,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${t} and dilation '${s}'`),R(o==="NWC",()=>`Error in conv1d: got dataFormat of ${o} but only NWC is currently supported.`);let c=K(l,[1,l.shape[0],l.shape[1],l.shape[2]]),m=K(u,[u.shape[0],1,u.shape[1],u.shape[2]]),g=zn(m,c,[1,t],n,"NHWC",[1,s],i);return p?K(g,[g.shape[2],g.shape[3]]):K(g,[g.shape[0],g.shape[2],g.shape[3]])}var wc=A({conv1d_:Xoe});function Yoe(r,e,t,n,o,s="NHWC",i){R(r.length===e.rank,()=>`Length of inShape (${r.length}) and rank of dy (${e.rank}) must match`);let a=r,l=e,u=!1;e.rank===3&&(u=!0,l=K(e,[1,e.shape[0],e.shape[1],e.shape[2]]),a=[1,r[0],r[1],r[2]]),R(a.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${a.length}.`),R(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),R(t.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${t.rank}`);let p=s==="NHWC"?a[3]:a[1],c=s==="NHWC"?l.shape[3]:l.shape[1];R(p===t.shape[2],()=>`Error in conv2dDerInput: depth of input (${p}) must match input depth for filter ${t.shape[2]}.`),R(c===t.shape[3],()=>`Error in conv2dDerInput: depth of output (${c}) must match output depth for filter ${t.shape[3]}.`),i!=null&&R(xt(o),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${i} but got pad ${o}.`);let m={dy:l,filter:t},f={strides:n,pad:o,dataFormat:s,dimRoundingMode:i,inputShape:a},d=M.runKernel(Hs,m,f);return u?K(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var qf=A({conv2DBackpropInput_:Yoe});function Zoe(r,e,t,n,o,s){let i=v(r,"x","conv2dTranspose"),a=v(e,"filter","conv2dTranspose");return qf(t,i,a,n,o,"NHWC",s)}var _c=A({conv2dTranspose_:Zoe});function Joe(r,e,t,n,o="NDHWC",s=[1,1,1]){let i=v(r,"x","conv3d"),a=v(e,"filter","conv3d"),l=i,u=!1;i.rank===4&&(u=!0,l=K(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),R(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),R(a.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${a.rank}.`),R(l.shape[4]===a.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${a.shape[3]}.`),R(rn(t,s),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`),R(o==="NDHWC",()=>`Error in conv3d: got dataFormat of ${o} but only NDHWC is currently supported.`);let p={x:l,filter:a},c={strides:t,pad:n,dataFormat:o,dilations:s},m=M.runKernel(Bu,p,c);return u?K(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}var ig=A({conv3d_:Joe});function Qoe(r,e,t,n,o){R(r.length===e.rank,()=>`Length of inShape (${r.length}) and rank of dy (${e.rank}) must match`);let s=r,i=e,a=!1;e.rank===4&&(a=!0,i=K(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]),s=[1,r[0],r[1],r[2],r[3]]);let l=s[4],u=i.shape[4];R(s.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`),R(i.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`),R(t.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${t.rank}`),R(l===t.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${t.shape[3]}.`),R(u===t.shape[4],()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${t.shape[4]}.`);let p={dy:i,filter:t},c={pad:o,strides:n,inputShape:s},m=M.runKernel(cf,p,c);return a?K(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}var vT=A({conv3DBackpropInput_:Qoe});function ese(r,e,t,n,o){let s=v(r,"x","conv3dTranspose"),i=v(e,"filter","conv3dTranspose");return vT(t,s,i,n,o)}var ZC=A({conv3dTranspose_:ese});function tse(r){let t={x:v(r,"x","cos")};return M.runKernel(qs,t)}var jl=A({cos_:tse});function rse(r){let t={x:v(r,"x","cosh")};return M.runKernel(fl,t)}var Cc=A({cosh_:rse});function nse(r,e=0,t=!1,n=!1){let s={x:v(r,"x","cumsum")},i={axis:e,exclusive:t,reverse:n};return M.runKernel(Xs,s,i)}var Sc=A({cumsum_:nse});function ose(r,e,t,n=!1){let o=v(r,"x","denseBincount"),s=v(e,"weights","denseBincount");R(o.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${o.dtype}`),R(o.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${o.rank}.`),R(t>=0,()=>`size must be non-negative, but got ${t}.`),R(s.size===o.size||s.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${o.shape}, weights shape: ${s.shape}.`);let i={x:o,weights:s},a={size:t,binaryOutput:n};return M.runKernel(mf,i,a)}var JC=A({denseBincount_:ose});function sse(r,e,t="NHWC"){let n=v(r,"x","depthToSpace"),o=t==="NHWC"?n.shape[1]:n.shape[2],s=t==="NHWC"?n.shape[2]:n.shape[3],i=t==="NHWC"?n.shape[3]:n.shape[1];R(o*e>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${o} and ${e} for depthToSpace with input shape
|
|
${n.shape}`),R(s*e>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${s} and ${e} for depthToSpace with input shape
|
|
${n.shape}`),R(i%(e*e)==0,()=>`Dimension size must be evenly divisible by ${e*e} but is ${i} for depthToSpace with input shape ${n.shape}`);let a={x:n},l={blockSize:e,dataFormat:t};return M.runKernel(hl,a,l)}var lg=A({depthToSpace_:sse});function ase(r,e,t,n,o="NHWC",s=[1,1],i){let a=v(r,"x","depthwiseConv2d"),l=v(e,"filter","depthwiseConv2d"),u=a,p=!1;a.rank===3&&(p=!0,u=K(a,[1,a.shape[0],a.shape[1],a.shape[2]])),R(u.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),R(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),R(u.shape[3]===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${u.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),i!=null&&R(xt(n),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${n}.`);let c={x:u,filter:l},m={strides:t,pad:n,dataFormat:o,dilations:s,dimRoundingMode:i},f=M.runKernel(Ys,c,m);return p?K(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Ra=A({depthwiseConv2d_:ase});function ise(r){let t={x:v(r,"x","diag")};return M.runKernel(hf,t)}var lse=A({diag_:ise});function use(r,e,t,n,o=[1,1],s="NHWC"){let i=v(r,"x","dilation2d"),a=v(e,"filter","dilation2d");R(i.rank===3||i.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`),R(a.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${a.rank}.`),R(s==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);let l=i,u=!1;i.rank===3&&(l=K(i,[1,i.shape[0],i.shape[1],i.shape[2]]),u=!0);let p={x:l,filter:a},c={strides:t,pad:n,dilations:o},m=M.runKernel(Ou,p,c);return u?K(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var ug=A({dilation2d_:use});function pse(r,e){let t=r.length,n=[];for(let o=0;o<t;o++){let s=t-1-o,i=r[s]||1;(e[e.length-1-o]||1)>1&&i===1&&n.unshift(s)}return n}function Gt(r,e){let t=[];for(let n=0;n<e.length;n++){let o=r[r.length-n-1],s=e.length-n-1,i=e[s];(o==null||o===1&&i>1)&&t.unshift(s)}return t}function qe(r,e){let t=[],n=Math.max(r.length,e.length);for(let o=0;o<n;o++){let s=r[r.length-o-1];s==null&&(s=1);let i=e[e.length-o-1];if(i==null&&(i=1),s===1)t.unshift(i);else if(i===1)t.unshift(s);else if(s!==i){let a=`Operands could not be broadcast together with shapes ${r} and ${e}.`;throw Error(a)}else t.unshift(s)}return t}function cse(r,e){let t=v(r,"a","equal","string_or_numeric"),n=v(e,"b","equal","string_or_numeric");[t,n]=et(t,n),qe(t.shape,n.shape);let o={a:t,b:n};return M.runKernel(Js,o)}var Io=A({equal_:cse});function mse(r,e,t){let n=v(e,"a","where"),o=v(t,"b","where"),s=v(r,"condition","where","bool"),i=qe(qe(s.shape,n.shape),o.shape),a=Ul(s,i),l=Ul(n,i),u=Ul(o,i),p={condition:a,t:l,e:u};return M.runKernel(bi,p)}var Wt=A({where_:mse});function fse(r){let t={x:v(r,"x","zerosLike")};return M.runKernel(Ti,t)}var Me=A({zerosLike_:fse});function dse(r,e){let t=v(r,"a","div"),n=v(e,"b","div");[t,n]=et(t,n);let o=he(t,n),s=Me(o),i=Io(n,s);return Wt(i,s,o)}var pg=A({divNoNan_:dse});function hse(r,e){let t=v(r,"t1","dot"),n=v(e,"t2","dot");R((t.rank===1||t.rank===2)&&(n.rank===1||n.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${t.rank} and ${n.rank}.`);let o=t.rank===1?t.size:t.shape[1],s=n.rank===1?n.size:n.shape[0];if(R(o===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${o} and ${s}.`),t.rank===1&&n.rank===1){let i=K(t,[1,-1]),a=K(n,[-1,1]),l=tt(i,a);return K(l,[])}else if(t.rank===1&&n.rank===2){let i=K(t,[1,-1]),a=K(n,[n.shape[0],n.shape[1]]),l=tt(i,a);return K(l,[l.size])}else if(t.rank===2&&n.rank===1){let i=K(n,[-1,1]),a=tt(t,i);return K(a,[a.size])}else{let i=K(n,[n.shape[0],n.shape[1]]);return tt(t,i)}}var QC=A({dot_:hse});function gse(r,...e){let t=e.map((o,s)=>v(o,`tensors${s}`,"einsum")),n={equation:r};return M.runKernel(gf,t,n)}var eS=A({einsum_:gse});function bse(r){let t={x:v(r,"x","elu")};return M.runKernel(gl,t)}var La=A({elu_:bse});function yse(r){let e=v(r,"x","erf");R(e.dtype==="int32"||e.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),e.dtype==="int32"&&(e=ue(e,"float32"));let t={x:e};return M.runKernel(bl,t)}var cg=A({erf_:yse});function xse(r){let t={x:v(r,"x","exp")};return M.runKernel(Mo,t)}var Fr=A({exp_:xse});function Tse(r,e=0){let t=v(r,"x","expandDims","string_or_numeric");R(e<=t.rank,()=>"Axis must be <= rank of the tensor");let n={input:t},o={dim:e};return M.runKernel(ci,n,o)}var Wr=A({expandDims_:Tse});function kse(r){let t={x:v(r,"x","expm1")};return M.runKernel(Qs,t)}var mg=A({expm1_:kse});function Ise(r,e){let t=v(r,"x","tile","string_or_numeric");R(t.rank===e.length,()=>`Error in transpose: rank of input ${t.rank} must match length of reps ${e}.`);let n={x:t},o={reps:e};return M.runKernel(Ko,n,o)}var qo=A({tile_:Ise});function vse(r,e,t,n="float32"){e==null&&(e=r);let o=ve([r,e],n),s=r<=e?r:e;for(let a=0;a<s;++a)o.set(1,a,a);let i=K(o.toTensor(),[r,e]);if(t==null)return i;if(t.length===1)return qo(Wr(i,0),[t[0],1,1]);if(t.length===2)return qo(Wr(Wr(i,0),0),[t[0],t[1],1,1]);if(t.length===3)return qo(Wr(Wr(Wr(i,0),0),0),[t[0],t[1],t[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${t.length}D.`)}var Xf=A({eye_:vse});function $a(r,e,t){let n={shape:r,value:e,dtype:t};return M.runKernel(zu,{},n)}function wse(r){let t={x:v(r,"x","floor")};return M.runKernel(Fo,t)}var Pa=A({floor_:wse});function _se(r,e,t=0,n=0){let o=v(r,"x","gather"),s=v(e,"indices","gather","int32"),i={x:o,indices:s},a={axis:t,batchDims:n};return M.runKernel(mi,i,a)}var Ba=A({gather_:_se});function Cse(r,e){let t=v(r,"a","greater","string_or_numeric"),n=v(e,"b","greater","string_or_numeric");[t,n]=et(t,n),qe(t.shape,n.shape);let o={a:t,b:n};return M.runKernel(ra,o)}var yr=A({greater_:Cse});function Sse(r,e){let t=v(r,"a","greaterEqual","string_or_numeric"),n=v(e,"b","greaterEqual","string_or_numeric");[t,n]=et(t,n),qe(t.shape,n.shape);let o={a:t,b:n};return M.runKernel(Ro,o)}var io=A({greaterEqual_:Sse});function Nse(r){let t={input:v(r,"input","imag")};return M.runKernel(Tf,t)}var Nc=A({imag_:Nse});function Ase(r){let t={x:v(r,"x","isFinite")};return M.runKernel(Tl,t)}var tS=A({isFinite_:Ase});function Dse(r){let t={x:v(r,"x","isInf")};return M.runKernel(kl,t)}var rS=A({isInf_:Dse});function Ese(r){let t={x:v(r,"x","isNaN")};return M.runKernel(Il,t)}var fg=A({isNaN_:Ese});function Mse(r,e=.2){let n={x:v(r,"x","leakyRelu")},o={alpha:e};return M.runKernel(na,n,o)}var Hl=A({leakyRelu_:Mse});function Fse(r,e){let t=v(r,"a","less","string_or_numeric"),n=v(e,"b","less","string_or_numeric");[t,n]=et(t,n),qe(t.shape,n.shape);let o={a:t,b:n};return M.runKernel(oa,o)}var Ac=A({less_:Fse});function Rse(r,e){let t=v(r,"a","lessEqual","string_or_numeric"),n=v(e,"b","lessEqual","string_or_numeric");[t,n]=et(t,n),qe(t.shape,n.shape);let o={a:t,b:n};return M.runKernel(sa,o)}var lo=A({lessEqual_:Rse});function nS(r,e,t){if(t<=0)throw new Error("The number of values should be positive.");let n={start:r,stop:e,num:t};return M.runKernel(kf,{},n)}function Lse(r,e=5,t=1,n=1,o=.5){let s=v(r,"x","localResponseNormalization");R(s.rank===4||s.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
|
|
rank ${s.rank}.`),R(xt(e),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${e}.`);let i=s,a=!1;s.rank===3&&(a=!0,i=K(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let l={x:i},u={depthRadius:e,bias:t,alpha:n,beta:o},p=M.runKernel(Gu,l,u);return a?K(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var dg=A({localResponseNormalization_:Lse});function $se(r){let t={x:v(r,"x","log")};return M.runKernel($o,t)}var Kr=A({log_:$se});function Pse(r){let t={x:v(r,"x","log1p")};return M.runKernel(vl,t)}var Dc=A({log1p_:Pse});function wT(r,e){R(rf(r),()=>"The f passed in variableGrads(f) must be a function"),R(e==null||Array.isArray(e)&&e.every(u=>u instanceof Xu),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let t=e!=null;if(!t){e=[];for(let u in M.registeredVariables)e.push(M.registeredVariables[u])}let n=t?e.filter(u=>!u.trainable):null,o=e.length;e=e.filter(u=>u.trainable),R(e.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${o} variables is trainable.`);let s=!0,{value:i,grads:a}=M.gradients(r,e,null,s);R(a.some(u=>u!=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()."),R(i.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${i.rank} tensor`);let l={};return e.forEach((u,p)=>{a[p]!=null&&(l[u.name]=a[p])}),n!=null&&n.forEach(u=>l[u.name]=null),{value:i,grads:l}}function Gn(r){return M.customGrad(r)}function Bse(r){let t={x:v(r,"x","neg")};return M.runKernel(ca,t)}var st=A({neg_:Bse});function Ose(r){let t={x:v(r,"x","softplus")};return M.runKernel(Rl,t)}var ds=A({softplus_:Ose});function zse(r){let e=v(r,"x","logSigmoid");return Gn(n=>({value:st(ds(st(n))),gradFunc:i=>G(i,dn(st(n)))}))(e)}var oS=A({logSigmoid_:zse});function Gse(r,e=null,t=!1){let o={x:v(r,"x","max")},s={reductionIndices:e,keepDims:t};return M.runKernel(aa,o,s)}var nn=A({max_:Gse});function Wse(r,e){let t=v(r,"a","sub"),n=v(e,"b","sub");[t,n]=et(t,n);let o={a:t,b:n};return M.runKernel(Wo,o)}var ge=A({sub_:Wse});function Kse(r,e=null,t=!1){let n=v(r,"x","sum");n.dtype==="bool"&&(n=ue(n,"int32"));let o={x:n},s={axis:e,keepDims:t};return M.runKernel(Ca,o,s)}var Te=A({sum_:Kse});function Vse(r,e=-1){let t=v(r,"logits","logSoftmax");if(e===-1&&(e=t.rank-1),e!==t.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${t.rank} and axis was ${e}`);return Gn((o,s)=>{let i=!0,a=nn(o,e,!0),l=ge(o,a),u=ge(ue(l,"float32"),Kr(Te(Fr(l),e,i)));return s([u]),{value:u,gradFunc:(c,m)=>{let[f]=m,d=!0,h=Fr(f);return ge(c,G(Te(c,e,d),h))}}})(t)}var Ec=A({logSoftmax_:Vse});function sS(r,e){for(let t=0;t<r.length;++t)if(r[r.length-t-1]!==e-1-t)return!1;return!0}function vP(r,e,t){let n=r.length+e.length,o=[],s=0,i=0;for(let a=0;a<n;a++)t.indexOf(a)===-1?o.push(r[s++]):o.push(e[i++]);return o}function aS(r,e){let t=[],n=r.length;for(let s=0;s<n;s++)e.indexOf(s)===-1&&t.push(r[s]);let o=e.map(s=>r[s]);return[t,o]}function hs(r,e){let t=e.map(n=>1);return vP(r,t,e)}function Use(r,e,t){R(sS(e,t),()=>`${r} supports only inner-most axes for now. Got axes ${e} and rank-${t} input.`)}function iS(r,e){if(sS(r,e))return null;let t=[];for(let n=0;n<e;++n)r.indexOf(n)===-1&&t.push(n);return r.forEach(n=>t.push(n)),t}function hg(r){return r.map((e,t)=>[t,e]).sort((e,t)=>e[1]-t[1]).map(e=>e[0])}function jse(r,e){let t=[];for(let n=e-r;n<e;++n)t.push(n);return t}function Hse(r,e=null,t=!1){let n=v(r,"x","logSumExp"),o=Pr(e,n.shape),s=nn(n,o,!0),i=ge(n,s),a=Fr(i),l=Te(a,o),u=Kr(l),p=ne(K(s,u.shape),u);if(t){let c=hs(p.shape,o);return K(p,c)}return p}var gg=A({logSumExp_:Hse});function qse(r,e){let t=v(r,"a","logicalAnd","bool"),n=v(e,"b","logicalAnd","bool");qe(t.shape,n.shape);let o={a:t,b:n};return M.runKernel(wl,o)}var Xr=A({logicalAnd_:qse});function Xse(r){let t={x:v(r,"x","logicalNot","bool")};return M.runKernel(uc,t)}var ql=A({logicalNot_:Xse});function Yse(r,e){let t=v(r,"a","logicalOr","bool"),n=v(e,"b","logicalOr","bool");qe(t.shape,n.shape);let o={a:t,b:n};return M.runKernel(pc,o)}var Mc=A({logicalOr_:Yse});function Zse(r,e){let t=v(r,"a","logicalXor","bool"),n=v(e,"b","logicalXor","bool");return qe(t.shape,n.shape),Xr(Mc(r,e),ql(Xr(r,e)))}var lS=A({logicalXor_:Zse});function Jse(r,e,t,n,o){let s=v(r,"x","maxPool"),i=1,a=s,l=!1;s.rank===3&&(l=!0,a=K(s,[1,s.shape[0],s.shape[1],s.shape[2]])),R(a.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${a.rank}.`),R(rn(t,i),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${t} and dilations '${i}'`),o!=null&&R(xt(n),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`);let u={x:a},p={filterSize:e,strides:t,pad:n,dimRoundingMode:o},c=M.runKernel(ia,u,p);return l?K(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var Xl=A({maxPool_:Jse});function Qse(r,e=[1,1,1],t,n,o,s="NDHWC"){let i=v(r,"x","maxPool3d"),a=i,l=!1;i.rank===4&&(l=!0,a=K(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),R(a.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${a.rank}.`),R(s==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),o!=null&&R(xt(n),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`);let u={x:a},p={filterSize:e,strides:t,pad:n,dimRoundingMode:o,dataFormat:s},c=M.runKernel(Wu,u,p);return l?K(c,[c.shape[1],c.shape[2],c.shape[3],c.shape[4]]):c}var bg=A({maxPool3d_:Qse});function eae(r,e,t,n,o=!1){let i={x:v(r,"x","maxPoolWithArgmax")},a={filterSize:e,strides:t,pad:n,includeBatchInIndex:o},l=M.runKernel(_f,i,a);return{result:l[0],indexes:l[1]}}var uS=A({maxPoolWithArgmax_:eae});function tae(r,e){let t=v(r,"a","maximum"),n=v(e,"b","maximum");[t,n]=et(t,n),t.dtype==="bool"&&(t=ue(t,"int32"),n=ue(n,"int32")),qe(t.shape,n.shape);let o={a:t,b:n};return M.runKernel(Po,o)}var Wn=A({maximum_:tae});function rae(r,e=null,t=!1){let o={x:v(r,"x","mean")},s={axis:e,keepDims:t};return M.runKernel(la,o,s)}var Ft=A({mean_:rae});function Rt(r,e="float32"){if(e==="complex64"){let n=Rt(r,"float32"),o=Rt(r,"float32");return ko(n,o)}let t=of(Nt(r),e);return M.makeTensor(t,r,e)}function on(r,e="float32"){if(e==="complex64"){let n=on(r,"float32"),o=Rt(r,"float32");return ko(n,o)}let t=Lh(Nt(r),e);return M.makeTensor(t,r,e)}function nae(r,e=null,t=!1){let o={x:v(r,"x","min")},s={axis:e,keepDims:t};return M.runKernel(ua,o,s)}var tp=A({min_:nae});function oae(r,e){let t=v(r,"a","minimum"),n=v(e,"b","minimum");[t,n]=et(t,n),t.dtype==="bool"&&(t=ue(t,"int32"),n=ue(n,"int32")),qe(t.shape,n.shape);let o={a:t,b:n};return M.runKernel(Bo,o)}var Oa=A({minimum_:oae});function sae(r,e,t){R(t==="reflect"||t==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${t}.`);let n=v(r,"x","mirrorPad");if(n.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");R(e.length===n.rank,()=>`Padding doesn't match input. Must be ${n.rank}. Got ${e.length}.`);let o=t==="reflect"?1:0;for(let a=0;a<n.rank;a++)R(e[a].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),R(e[a][0]>=0&&e[a][0]<=n.shape[a]-o&&e[a][1]>=0&&e[a][1]<=n.shape[a]-o,()=>`Padding in dimension ${a} cannot be greater than or equal to ${n.shape[a]-o} or less than 0 for input of shape ${n.shape}`);let s={paddings:e,mode:t},i={x:n};return M.runKernel(pa,i,s)}var yg=A({mirrorPad_:sae});function aae(r,e){let t=v(r,"a","mod"),n=v(e,"b","mod");[t,n]=et(t,n);let o={a:t,b:n};return M.runKernel(_l,o)}var xg=A({mod_:aae});function iae(r){let e=v(r,"x","square"),t={};return M.runKernel("Square",{x:e},t)}var je=A({square_:iae});function lae(r,e=null,t=!1){r=v(r,"x","moments");let n=Pr(e,r.shape),o=Ft(r,n,t),s=o.shape;t||(s=hs(o.shape,n));let i=je(ge(ue(r,"float32"),K(o,s))),a=Ft(i,n,t);return{mean:o,variance:a}}var Yf=A({moments_:lae});function uae(r,e,t,n){let o=v(e,"data","multiRNNCell"),s=Yu(t,"c","multiRNNCell"),i=Yu(n,"h","multiRNNCell"),a=o,l=[];for(let c=0;c<r.length;c++){let m=r[c](a,s[c],i[c]);l.push(m[0]),l.push(m[1]),a=m[1]}let u=[],p=[];for(let c=0;c<l.length;c+=2)u.push(l[c]),p.push(l[c+1]);return[u,p]}var pae=A({multiRNNCell_:uae});function cae(r,e,t,n=!1){let o=v(r,"logits","multinomial"),s=o.size,i=o.rank;if(s<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${s}.`);if(i>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${i}`);t=t||Math.random();let l={logits:i===1?K(o,[1,-1]):o},u={numSamples:e,seed:t,normalized:n},p=M.runKernel(Cf,l,u);return i===1?K(p,[p.size]):p}var pS=A({multinomial_:cae});function mae(r,e){let t=v(r,"a","notEqual","string_or_numeric"),n=v(e,"b","notEqual","string_or_numeric");[t,n]=et(t,n),qe(t.shape,n.shape);let o={a:t,b:n};return M.runKernel(ma,o)}var gs=A({notEqual_:mae});function fae(r){let t={x:v(r,"x","onesLike")};return M.runKernel(fi,t)}var Br=A({onesLike_:fae});function dae(r,e){let t=v(r,"v1","outerProduct"),n=v(e,"v2","outerProduct");R(t.rank===1&&n.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${t.rank} and ${n.rank}.`);let o=K(t,[-1,1]),s=K(n,[1,-1]);return tt(o,s)}var hae=A({outerProduct_:dae});function gae(r,e,t=0){let n=v(r,"x","pad");if(n.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let o={paddings:e,constantValue:t},s={x:n};return M.runKernel(da,s,o)}var kn=A({pad_:gae});function bae(r,e,t=0){return R(e.length===2,()=>"Invalid number of paddings. Must be length of 2."),kn(r,[e],t)}var yae=A({pad1d_:bae});function xae(r,e,t=0){return R(e.length===2&&e[0].length===2&&e[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),kn(r,e,t)}var Tae=A({pad2d_:xae});function kae(r,e,t=0){return R(e.length===3&&e[0].length===2&&e[1].length===2&&e[2].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),kn(r,e,t)}var Iae=A({pad3d_:kae});function vae(r,e,t=0){return R(e.length===4&&e[0].length===2&&e[1].length===2&&e[2].length===2&&e[3].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),kn(r,e,t)}var wae=A({pad4d_:vae});function _ae(r,e,t){let n=v(r,"x","spaceToBatchND");R(n.rank>=1+e.length,()=>`input rank ${n.rank} should be > than [blockShape] ${e.length}`),R(t.length===e.length,()=>`paddings.shape[0] ${t.length} must be equal to [blockShape] ${e.length}`),R(n.shape.reduce((i,a,l)=>l>0&&l<=e.length?i&&(a+t[l-1][0]+t[l-1][1])%e[l-1]==0:i,!0),()=>`input spatial dimensions ${n.shape.slice(1)} with paddings ${t.toString()} must be divisible by blockShapes ${e.toString()}`);let o={x:n},s={blockShape:e,paddings:t};return M.runKernel(Uu,o,s)}var Yl=A({spaceToBatchND_:_ae});function Cae(r,e,t,n,o,s){o==null&&(o=[1,1]),s==null&&(s=1),n===0&&(n="valid");let i=v(r,"x","maxPool"),a=i,l=!1;i.rank===3&&(l=!0,a=K(i,[1,i.shape[0],i.shape[1],i.shape[2]])),R(rn(s,o),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${o}'`);let u=GC(a.shape,e,s,o,n),p=[u.dilationHeight,u.dilationWidth],c;n==="same"?c=Nae([u.filterHeight,u.filterWidth],p):c=[[0,0],[0,0]];let m=p[0]===1&&p[1]===1,[f,d]=Sae([u.inHeight,u.inWidth],p,c),h=m?n:"valid",g=m?a:Yl(a,p,f),y=(t==="avg"?()=>Kl(g,e,s,h):()=>Xl(g,e,s,h))(),T=m?y:Vl(y,p,d);return l?K(T,[T.shape[1],T.shape[2],T.shape[3]]):T}function Sae(r,e,t){let n=t.map(p=>p[0]),o=t.map(p=>p[1]),s=r.concat(n,o),i=e.map((p,c)=>(p-s[c]%p)%p),a=o.map((p,c)=>p+i[c]),l=e.map((p,c)=>[n[c],a[c]]),u=e.map((p,c)=>[0,i[c]]);return[l,u]}function Nae(r,e){let n=r.map((i,a)=>i+(i-1)*(e[a]-1)).map(i=>i-1),o=n.map(i=>Math.floor(i/2)),s=n.map((i,a)=>i-o[a]);return n.map((i,a)=>[o[a],s[a]])}var cS=A({pool_:Cae});function Aae(r,e){let t=v(r,"base","pow"),n=v(e,"exp","pow");[t,n]=et(t,n);let o={a:t,b:n};return M.runKernel(ha,o)}var In=A({pow_:Aae});function Dae(r,e){let t=v(r,"x","prelu"),n=v(e,"alpha","prelu"),o={x:t,alpha:n};return M.runKernel(ga,o)}var Zl=A({prelu_:Dae});function Eae(r,e=null,t=!1){let n=v(r,"x","prod");n.dtype==="bool"&&(n=ue(n,"int32"));let o={x:n},s={axis:e,keepDims:t};return M.runKernel(hi,o,s)}var Fc=A({prod_:Eae});function Mae(r,e,t){let n=Nt(r),o=null;if(t==null||t==="float32")o=new Float32Array(n);else if(t==="int32")o=new Int32Array(n);else if(t==="bool")o=new Uint8Array(n);else throw new Error(`Unknown data type ${t}`);for(let s=0;s<n;s++)o[s]=e();return M.makeTensor(o,r,t)}var Fae=A({rand_:Mae});var _T=Wi(Hx());var Zf=class{constructor(e,t,n,o,s){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=o,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);let i=s||Math.random();this.random=_T.alea(i.toString())}nextValue(){if(!isNaN(this.nextVal)){let o=this.nextVal;return this.nextVal=NaN,o}let e,t,n=!1;for(;!n;){let o,s,i;do o=2*this.random()-1,s=2*this.random()-1,i=o*o+s*s;while(i>=1||i===0);let a=Math.sqrt(-2*Math.log(i)/i);e=this.mean+this.stdDev*o*a,t=this.mean+this.stdDev*s*a,(!this.truncated||this.isValidTruncated(e))&&(n=!0)}return(!this.truncated||this.isValidTruncated(t))&&(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return this.dtype==null||this.dtype==="float32"?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}},mS=class{constructor(e,t,n,o){this.alpha=e,this.beta=1/t,this.dtype=n;let s=o||Math.random();this.randu=_T.alea(s.toString()),this.randn=new Zf(0,1,n,!1,this.randu()),e<1?this.d=e+2/3:this.d=e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,o,s,i;for(;;){do o=this.randn.nextValue(),i=1+this.c*o;while(i<=0);if(i*=i*i,e=o*o,t=1-.331*e*e,n=.5*e+this.d*(1-i+Math.log(i)),s=this.randu(),s<t||Math.log(s)<n)break}return i=1/this.beta*this.d*i,this.alpha<1&&(i*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(i)}convertValue(e){return this.dtype==="float32"?e:Math.round(e)}},fS=class{constructor(e=0,t=1,n,o){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=n,o==null&&(o=Math.random()),typeof o=="number"&&(o=o.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=_T.alea(o)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function Rae(r,e,t=1,n="float32",o){if(t==null&&(t=1),n==null&&(n="float32"),n!=="float32"&&n!=="int32")throw new Error(`Unsupported data type ${n}`);let s=new mS(e,t,n,o),i=ve(r,n);for(let a=0;a<i.values.length;a++)i.values[a]=s.nextValue();return i.toTensor()}var Lae=A({randomGamma_:Rae});function $ae(r,e=0,t=1,n,o){if(n!=null&&n==="bool")throw new Error(`Unsupported data type ${n}`);let s=new Zf(e,t,n,!1,o),i=ve(r,n);for(let a=0;a<i.values.length;a++)i.values[a]=s.nextValue();return i.toTensor()}var CT=A({randomNormal_:$ae});function Pae(r,e=0,t=1,n="float32",o){let s=ve(r,n),i=new fS(e,t,null,o);for(let a=0;a<s.values.length;a++)s.values[a]=i.nextValue();return s.toTensor()}var za=A({randomUniform_:Pae});function Jl(r,e,t=1,n="float32"){if(t===0)throw new Error("Cannot have a step of zero");let o={start:r,stop:e,step:t,dtype:n};return M.runKernel(Ku,{},o)}function Bae(r){let t={input:v(r,"input","real")};return M.runKernel(cc,t)}var rp=A({real_:Bae});function Oae(r){let t={x:v(r,"x","reciprocal")};return M.runKernel(Al,t)}var Tg=A({reciprocal_:Oae});function zae(r){let t={x:v(r,"x","relu")};return M.runKernel(ba,t)}var hn=A({relu_:zae});function Gae(r){let t={x:v(r,"x","relu6")};return M.runKernel(xa,t)}var Rc=A({relu6_:Gae});function Wae(r,e){let n={x:v(r,"x","reverse")},o={dims:e};return M.runKernel(Ta,n,o)}var wr=A({reverse_:Wae});function Kae(r){let e=v(r,"x","reverse");return R(e.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${e.rank}.`),wr(e,0)}var Vae=A({reverse1d_:Kae});function Uae(r,e){let t=v(r,"x","reverse");return R(t.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${t.rank}.`),wr(t,e)}var jae=A({reverse2d_:Uae});function Hae(r,e){let t=v(r,"x","reverse");return R(t.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${t.rank}.`),wr(t,e)}var qae=A({reverse3d_:Hae});function Xae(r,e){let t=v(r,"x","reverse");return R(t.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${t.rank}.`),wr(t,e)}var Yae=A({reverse4d_:Xae});function Zae(r){let t={x:v(r,"x","round")};return M.runKernel(ka,t)}var Lc=A({round_:Zae});function Jae(r){let t={x:v(r,"x","rsqrt")};return M.runKernel(zo,t)}var $c=A({rsqrt_:Jae});function be(r,e){if((oo(r)&&e!=="string"||Array.isArray(r))&&e!=="complex64")throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if(e==="string"&&oo(r)&&!(r instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Uo(r,[],[],e)}function Qae(r){let t={x:v(r,"x","selu")};return M.runKernel(El,t)}var Pc=A({selu_:Qae});function eie(r,e,t,n,o,s=[1,1],i="NHWC"){let a=v(r,"x","separableConv2d"),l=v(e,"depthwiseFilter","separableConv2d"),u=v(t,"pointwiseFilter","separableConv2d"),p=a,c=!1;if(a.rank===3&&(c=!0,p=K(a,[1,a.shape[0],a.shape[1],a.shape[2]])),i==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");R(p.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${p.rank}.`),R(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),R(u.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),R(u.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`),R(u.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${u.shape[1]}.`);let m=l.shape[2],f=l.shape[3];R(u.shape[2]===m*f,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${m*f}, but got ${u.shape[2]}.`);let d=Ra(p,l,n,o,i,s),g=zn(d,u,1,"valid",i);return c?K(g,[g.shape[1],g.shape[2],g.shape[3]]):g}var kg=A({separableConv2d_:eie});async function tie(r,e){let t=v(r,"x","setdiff1d"),n=v(e,"y","setdiff1d");R(t.dtype===n.dtype,()=>`x and y should have the same dtype, but got x (${t.dtype}) and y (${n.dtype}).`),R(t.rank===1,()=>`x should be 1D tensor, but got x (${t.shape}).`),R(n.rank===1,()=>`y should be 1D tensor, but got y (${n.shape}).`);let o=await t.data(),s=await n.data(),i=new Set(s),a=0;for(let p=0;p<o.length;p++)i.has(o[p])||a++;let l=new bt([a],t.dtype),u=new bt([a],"int32");for(let p=0,c=0;p<o.length;p++)i.has(o[p])||(l.values[c]=o[p],u.values[c]=p,c++);return[l.toTensor(),u.toTensor()]}var dS=tie;function rie(r){let t={x:v(r,"x","sign")};return M.runKernel(Fl,t)}var Ig=A({sign_:rie});function nie(r){let t={x:v(r,"x","sin")};return M.runKernel(va,t)}var Bc=A({sin_:nie});function oie(r){let t={x:v(r,"x","sinh")};return M.runKernel(Ml,t)}var Oc=A({sinh_:oie});function sie(r,e,t){let n=v(r,"x","slice1d");return R(n.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${n.rank} tensor`),Ke(n,[e],[t])}var vg=A({slice1d_:sie});function aie(r,e,t){let n=v(r,"x","slice2d");return R(n.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${n.rank} tensor`),Ke(n,e,t)}var ST=A({slice2d_:aie});function iie(r,e,t){let n=v(r,"x","slice3d");return R(n.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${n.rank} tensor`),Ke(n,e,t)}var wg=A({slice3d_:iie});function lie(r,e,t){let n=v(r,"x","slice4d");return R(n.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${n.rank} tensor`),Ke(n,e,t)}var Jf=A({slice4d_:lie});function uie(r,e=-1){let t=v(r,"logits","softmax","float32");if(e===-1&&(e=t.rank-1),e!==t.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${t.rank} and dim was ${e}`);let n={logits:t},o={dim:e};return M.runKernel(Sa,n,o)}var Ql=A({softmax_:uie});function pie(r){R(r.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${r.dtype}.`);let e={input:r};return M.runKernel(yf,e)}var np=A({fft_:pie});function cie(r){R(r.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${r.dtype}.`);let e={input:r};return M.runKernel(xf,e)}var eu=A({ifft_:cie});function mie(r){let e=r.shape[r.shape.length-1],t=r.size/e,n;if(e<=2){let o=K(r,[t,e]);n=eu(o)}else{let o=[t,2*(e-1)],s=K(rp(r),[t,e]),i=K(Nc(r),[t,e]),a=wr(Ke(s,[0,1],[t,e-2]),1),l=G(wr(Ke(i,[0,1],[t,e-2]),1),be(-1)),u=mt([s,a],1),p=mt([i,l],1),c=K(ko(u,p),[o[0],o[1]]);n=eu(c)}if(n=rp(n),r.rank===3&&r.shape[0]!==0){let o=n,s=r.shape[0];n=K(n,[s,n.shape[0]/s,n.shape[1]]),o.dispose()}return n}var Qf=A({irfft_:mie});function fie(r,e,t=0){let o={x:v(r,"x","split")},s={numOrSizeSplits:e,axis:t};return M.runKernel(yi,o,s)}var Rr=A({split_:fie});function die(r,e){R(r.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${r.dtype}`);let t=r.shape[r.shape.length-1],n=r.size/t,o;if(e!=null&&e<t){let d=r.shape.map(g=>0),h=r.shape.map(g=>g);h[r.shape.length-1]=e,o=Ke(r,d,h),t=e}else if(e!=null&&e>t){let d=r.shape.map(h=>h);d[r.shape.length-1]=e-t,o=mt([r,Rt(d)],r.shape.length-1),t=e}else o=r;let s=Me(o),i=K(ko(o,s),[n,t]),a=np(i),l=Math.floor(t/2)+1,u=rp(a),p=Nc(a),c=Rr(u,[l,t-l],u.shape.length-1),m=Rr(p,[l,t-l],p.shape.length-1),f=o.shape.slice();return f[o.shape.length-1]=l,K(ko(c[0],m[0]),f)}var op=A({rfft_:die});function hie(r){let t={x:v(r,"x","sqrt")};return M.runKernel(_a,t)}var Lt=A({sqrt_:hie});function gie(r,e){let t=v(r,"a","squaredDifference"),n=v(e,"b","squaredDifference");[t,n]=et(t,n),qe(t.shape,n.shape);let o={a:t,b:n},s={};return M.runKernel(Go,o,s)}var zc=A({squaredDifference_:gie});function bie(r,e){let t=v(r,"x","squeeze");return K(t,eC(t.shape,e).newShape)}var Xo=A({squeeze_:bie});function yie(r,e=0){let t=Yu(r,"tensors","stack","string_or_numeric");R(t.length>=1,()=>"Pass at least one tensor to tf.stack"),t.length>0&&R(e<=t[0].rank,()=>"Axis must be <= rank of the tensor");let n=t,o={axis:e};return M.runKernel(di,n,o)}var xr=A({stack_:yie});function xie(r,e=0){let n={x:v(r,"x","step")},o={alpha:e};return M.runKernel(cs,n,o)}var Ga=A({step_:xie});function Tie(r,e,t,n,o=0,s=0,i=0,a=0,l=0){let p={x:v(r,"x","stridedSlice","string_or_numeric")},c={begin:e,end:t,strides:n,beginMask:o,endMask:s,ellipsisMask:i,newAxisMask:a,shrinkAxisMask:l};return M.runKernel(Ll,p,c)}var _g=A({stridedSlice_:Tie});function kie(r){let t={x:v(r,"x","tan")};return M.runKernel(Na,t)}var Cg=A({tan_:kie});function Zt(r,e){li(r);let t=Vo(r,e);if(t.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Uo(r,null,t,e)}function Ci(r,e,t){if(li(r),e!=null&&e.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let n=Vo(r,t);if(n.length!==2&&n.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(n.length===1&&e==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Uo(r,e,n,t)}function Iie(r,e=1,t=!0){let n=v(r,"x","topk");if(n.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let o=n.shape[n.shape.length-1];if(e>o)throw new Error(`'k' passed to topk() must be <= the last dimension (${o}) but got ${e}`);let s={x:n},i={k:e,sorted:t},[a,l]=M.runKernel($l,s,i);return{values:a,indices:l}}var Sg=A({topk_:Iie});function vie(r,e=0,t=1,n,o){if(n!=null&&n==="bool")throw new Error("Unsupported data type $ { dtype }");let s=new Zf(e,t,n,!0,o),i=ve(r,n);for(let a=0;a<i.values.length;a++)i.values[a]=s.nextValue();return i.toTensor()}var Gc=A({truncatedNormal_:vie});function wie(r,e=0){let t=v(r,"x","unique","string_or_numeric");R(t.rank>0,()=>"The input tensor must be at least 1D");let n={x:t},o={axis:e},[s,i]=M.runKernel(Pf,n,o);return{values:s,indices:i}}var ed=A({unique_:wie});function _ie(r,e,t){let n=v(r,"x","unsortedSegmentSum"),o=v(e,"segmentIds","unsortedSegmentSum","int32");R(xt(t),()=>"numSegments must be of dtype int");let s={x:n,segmentIds:o},i={numSegments:t};return M.runKernel(Hu,s,i)}var Ng=A({unsortedSegmentSum_:_ie});function Cie(r,e=0){let t=v(r,"x","unstack","string_or_numeric");R(e>=-t.shape.length&&e<t.shape.length,()=>`Axis = ${e} is not in [-${t.shape.length}, ${t.shape.length})`);let n={value:t},o={axis:e};return M.runKernel(xi,n,o)}var Vr=A({unstack_:Cie});function hS(r,e=!0,t,n){return M.makeVariable(r,e,t,n)}function NT(r,e){let t=[];for(let s=0;s<e.length;s++)e[s]&&t.push(s);let n=ve(r,"int32"),o=ve([t.length,r.length],"int32");for(let s=0;s<t.length;s++){let i=n.indexToLoc(t[s]),a=s*r.length;o.values.set(i,a)}return o.toTensor()}async function Sie(r){let e=v(r,"condition","whereAsync","bool"),t=await e.data(),n=NT(e.shape,t);return r!==e&&e.dispose(),n}var AT=Sie;function Nie(r,e="euclidean",t=null,n=!1){r=v(r,"x","norm");let o=wP(r,e,t),s=o.shape;if(n){let i=Pr(t,r.shape);s=hs(o.shape,i)}return K(o,s)}function wP(r,e,t=null){if(r.rank===0)return Ht(r);if(r.rank!==1&&t===null)return wP(K(r,[-1]),e,t);if(r.rank===1||typeof t=="number"||Array.isArray(t)&&t.length===1){if(e===1)return Te(Ht(r),t);if(e===Infinity)return nn(Ht(r),t);if(e===-Infinity)return tp(Ht(r),t);if(e==="euclidean"||e===2)return Lt(Te(In(Ht(r),be(2,"int32")),t));throw new Error(`Error in norm: invalid ord value: ${e}`)}if(Array.isArray(t)&&t.length===2){if(e===1)return nn(Te(Ht(r),t[0]),t[1]-1);if(e===Infinity)return nn(Te(Ht(r),t[1]),t[0]);if(e===-Infinity)return tp(Te(Ht(r),t[1]),t[0]);if(e==="fro"||e==="euclidean")return Lt(Te(je(r),t));throw new Error(`Error in norm: invalid ord value: ${e}`)}throw new Error(`Error in norm: invalid axis: ${t}`)}var td=A({norm_:Nie});function Aie(r,e,t,n,o=!0){let s=v(r,"v","movingAverage"),i=v(e,"x","movingAverage"),a=v(t,"decay","movingAverage");xC(s,i),R(no(s.shape,i.shape),()=>"Shape mismatch in v and x");let l=be(1),u=ge(l,a),p=G(ge(i,s),u);if(o){R(n!=null,()=>"When using zeroDebias: true, step is required.");let c=v(n,"step","movingAverage");p=he(p,ge(l,In(a,c)))}return ne(s,p)}var yNt=A({movingAverage_:Aie});function Die(r,e,t){let n=v(r,"indices","scatterND","int32"),o=v(e,"updates","scatterND");yT(o,n,t);let s={indices:n,updates:o},i={shape:t};return M.runKernel(Dl,s,i)}var _P=A({scatterND_:Die});function CP(r,e,t,n){if(r.dtype!=="int32")throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${r.dtype}.`);if(r.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${r.shape}.`);let o=r.rank>0?r.shape[0]:1,s=r.rank>1?r.shape[1]:1;if(t.length!==s)throw new Error(`outputShape has incorrect number of elements:, ${t.length}, should be: ${s}.`);let i=e.size;if(!(e.rank===0||e.rank===1&&i===o))throw new Error(`sparseValues has incorrect shape ${e.shape}, should be [] or [${o}]`);if(e.dtype!==n.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function Eie(r,e,t,n=0){let o=v(r,"sparseIndices","sparseToDense","int32"),s=v(e,"sparseValues","sparseToDense"),i=v(n,"defaultValue","sparseToDense",s.dtype);CP(o,s,t,i);let a={sparseIndices:o,sparseValues:s,defaultValue:i},l={outputShape:t};return M.runKernel(Ff,a,l)}var DT=A({sparseToDense_:Eie});function Mie(r,e){let t=v(e,"indices","gatherND","int32"),o={params:v(r,"x","gatherND","string_or_numeric"),indices:t};return M.runKernel(xl,o)}var SP=A({gatherND_:Mie});function NP(r,e){if(e==null)return r.shape.slice();if(no(r.shape,e))return e;if(r.shape.length===e.length){let t=[];for(let n=0;n<r.shape.length;n++)e[n]==null&&r.shape[n]!=null?t.push(r.shape[n]):t.push(e[n]);return t}return e}function Fie(r,e,t,n){let o=v(r,"x","dropout");if(R(o.dtype==="float32",()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${o.dtype} tensor instead.`),R(e>=0&&e<1,()=>`rate must be a float in the range [0, 1), but got ${e}.`),e===0)return r instanceof rt?o.clone():o;let s=NP(o,t),i=1-e,a=he(Pa(ne(za(s,0,1,"float32",n),i)),i);return G(o,a)}var AP=A({dropout_:Fie});function DP(r){return Math.floor(Math.pow(2,Math.ceil(Math.log(r)/Math.log(2))))}function ET(r,e,t){let n=1-r%2,o=new Float32Array(r);for(let s=0;s<r;++s){let i=2*Math.PI*s/(r+n-1);o[s]=e-t*Math.cos(i)}return Zt(o,"float32")}var bs={};Ge(bs,{conv2d:()=>EP,depthwiseConv2d:()=>MP,matMul:()=>FP});function Rie(r,e,t,n,o,s="NHWC",i){let a=r;r.rank===3&&(a=K(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let l=e;l.rank===3&&(l=K(e,[1,e.shape[0],e.shape[1],e.shape[2]])),R(a.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${a.shape}.`),R(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),R(t.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${t}.`);let u=s==="NHWC"?a.shape[3]:a.shape[1],p=s==="NHWC"?l.shape[3]:l.shape[1];R(u===t[2],()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${t[2]}.`),R(p===t[3],()=>`Error in conv2dDerFilter: depth of dy (${p}) must match output depth for filter (${t[3]}).`),i!=null&&R(xt(o),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${i} but got pad ${o}.`);let c={x:a,dy:l},m={strides:n,pad:o,dataFormat:s,dimRoundingMode:i,filterShape:t};return M.runKernel(uf,c,m)}var rd=A({conv2DBackpropFilter_:Rie});function Wc(r,e,t){if(t==null||t==="linear")return r;if(t==="relu")return G(r,Ga(e));throw new Error(`Cannot compute gradient for fused activation ${t}.`)}function Kc(r,e){let t=e,n=Gt(r.shape,e.shape);return n.length>0&&(t=Te(t,n)),K(t,r.shape)}function Vc(r,e,t,n){if(e==="linear")return r;if(e==="relu")return hn(r);if(e==="elu")return La(r);if(e==="relu6")return Rc(r);if(e==="prelu")return Zl(r,t);if(e==="leakyrelu")return Hl(r,n);if(e==="sigmoid")return dn(r);throw new Error(`Unknown fused activation ${e}.`)}var Uc=(r,e)=>!(r>0)||e==="linear";function Lie({x:r,filter:e,strides:t,pad:n,dataFormat:o="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:a,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:p}){if(l=l||"linear",Uc(M.state.gradientDepth,l)===!1){let I=zn(r,e,t,n,o,s,i);return a!=null&&(I=ne(I,a)),Vc(I,l,u,p)}let c=v(r,"x","conv2d"),m=v(e,"filter","conv2d"),f=c,d=!1;c.rank===3&&(d=!0,f=K(c,[1,c.shape[0],c.shape[1],c.shape[2]])),R(f.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${f.rank}.`),R(m.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${m.rank}.`),i!=null&&R(xt(n),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${n}.`),R(f.shape[3]===m.shape[2],()=>`Error in conv2d: depth of input (${f.shape[3]}) must match input depth for filter ${m.shape[2]}.`),R(rn(t,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`),R(o==="NHWC",()=>`Error in conv2d: got dataFormat of ${o} but only NHWC is currently supported.`);let h=Ic(f.shape,m.shape,t,s,n,i),g;a!=null&&(g=v(a,"bias","fused conv2d"),[g]=et(g,c),qe(h.outShape,g.shape));let b;u!=null&&(b=v(u,"prelu weights","fused conv2d"));let y=(I,S)=>{let[N,F,$,O]=S,V=Wc(I,$,l);R(Ho(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let q=qf(F.shape,V,N,t,n),W=rd(F,V,N.shape,t,n),Y=[q,W];if(O!=null){let Z=Kc(O,V);Y.push(Z)}return Y},T={x:f,filter:m,bias:g,preluActivationWeights:b},k={strides:t,pad:n,dataFormat:o,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:p};return a==null?Gn((S,N,F)=>{let $=M.runKernel(Ii,T,k);return F([N,S,$]),d&&($=K($,[$.shape[1],$.shape[2],$.shape[3]])),{value:$,gradFunc:y}})(f,m):Gn((S,N,F,$)=>{let O=M.runKernel(Ii,T,k);return $([N,S,O,F]),d&&(O=K(O,[O.shape[1],O.shape[2],O.shape[3]])),{value:O,gradFunc:y}})(f,m,g)}var EP=A({fusedConv2d_:Lie});function $ie(r,e,t,n,o,s=[1,1],i){let a=r;r.rank===3&&(a=K(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let l=e;l.rank===3&&(l=K(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u={x:a,dy:l},p={strides:n,pad:o,dimRoundingMode:i,dilations:s,filterShape:t};return M.runKernel(ff,u,p)}var MT=A({depthwiseConv2dNativeBackpropFilter_:$ie});function Pie(r,e,t,n,o,s=[1,1],i){let a=e,l=!1;e.rank===3&&(l=!0,a=K(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u={dy:a,filter:t},p={strides:n,pad:o,dimRoundingMode:i,dilations:s,inputShape:r},c=M.runKernel(df,u,p);return l?K(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var FT=A({depthwiseConv2dNativeBackpropInput_:Pie});function Bie({x:r,filter:e,strides:t,pad:n,dataFormat:o="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:a,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:p}){if(Uc(M.state.gradientDepth,l)===!1){let I=Ra(r,e,t,n,o,s,i);return a!=null&&(I=ne(I,a)),Vc(I,l,u,p)}let c=v(r,"x","depthwiseConv2d"),m=v(e,"filter","depthwiseConv2d"),f=c,d=!1;c.rank===3&&(d=!0,f=K(c,[1,c.shape[0],c.shape[1],c.shape[2]])),R(f.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${f.rank}.`),R(m.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${m.rank}.`),R(f.shape[3]===m.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${f.shape[3]}) must match the inChannels dimension in filter ${m.shape[2]}.`),s==null&&(s=[1,1]),R(rn(t,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`),i!=null&&R(xt(n),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${i} but got pad ${n}.`);let h=Ic(f.shape,m.shape,t,s,n,i,!0),g;a!=null&&(g=v(a,"bias","fused conv2d"),[g]=et(g,c),qe(h.outShape,g.shape));let b;u!=null&&(b=v(u,"prelu weights","fused depthwiseConv2d"));let y=(I,S)=>{R(Ho(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);let[N,F,$,O]=S,V=Wc(I,$,l),q=FT(F.shape,V,N,t,n,s,i),W=MT(F,V,N.shape,t,n,s,i);if(O!=null){let Y=Kc(g,V);return[q,W,Y]}return[q,W]},T={x:f,filter:m,bias:g,preluActivationWeights:b},k={strides:t,pad:n,dataFormat:o,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:p};return a==null?Gn((S,N,F)=>{let $=M.runKernel(vi,T,k);return F([N,S,$]),d&&($=K($,[$.shape[1],$.shape[2],$.shape[3]])),{value:$,gradFunc:y}})(f,m):Gn((S,N,F,$)=>{let O=M.runKernel(vi,T,k);return $([N,S,O,F]),d&&(O=K(O,[O.shape[1],O.shape[2],O.shape[3]])),{value:O,gradFunc:y}})(f,m,g)}var MP=A({fusedDepthwiseConv2d_:Bie});function Oie({a:r,b:e,transposeA:t=!1,transposeB:n=!1,bias:o,activation:s="linear",preluActivationWeights:i,leakyreluAlpha:a}){if(Uc(M.state.gradientDepth,s)===!1){let O=tt(r,e,t,n);return o!=null&&(O=ne(O,o)),Vc(O,s,i,a)}let l=v(r,"a","fused matMul"),u=v(e,"b","fused matMul");[l,u]=et(l,u);let p=t?l.shape[l.rank-2]:l.shape[l.rank-1],c=n?u.shape[u.rank-1]:u.shape[u.rank-2],m=t?l.shape[l.rank-1]:l.shape[l.rank-2],f=n?u.shape[u.rank-2]:u.shape[u.rank-1],d=l.shape.slice(0,-2),h=u.shape.slice(0,-2),g=Nt(d),b=Nt(h);R(l.rank>=2&&u.rank>=2&&l.rank===u.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${l.rank} and ${u.rank}.`),R(no(d,h),()=>`Error in fused matMul: outer dimensions (${d}) and (${h}) of Tensors with shapes ${l.shape} and ${u.shape} must match.`),R(p===c,()=>`Error in fused matMul: inner shapes (${p}) and (${c}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${t} and transposeB=${n} must match.`);let y=l.shape.slice(0,-2).concat([m,f]),T=t?K(l,[g,p,m]):K(l,[g,m,p]),k=n?K(u,[b,f,c]):K(u,[b,c,f]),I;o!=null&&(I=v(o,"bias","fused matMul"),[I]=et(I,l),qe(y,I.shape));let S;i!=null&&(S=v(i,"prelu weights","fused matMul"));let N=(O,V)=>{let[q,W,Y,Z]=V,J=Wc(K(O,Y.shape),Y,s),se,ee;if(!t&&!n?(se=tt(J,W,!1,!0),ee=tt(q,J,!0,!1)):!t&&n?(se=tt(J,W,!1,!1),ee=tt(J,q,!0,!1)):t&&!n?(se=tt(W,J,!1,!0),ee=tt(q,J,!1,!1)):(se=tt(W,J,!0,!0),ee=tt(J,q,!0,!0)),o!=null){let le=Kc(Z,J);return[se,ee,le]}else return[se,ee]},F={a:T,b:k,bias:I,preluActivationWeights:S},$={transposeA:t,transposeB:n,activation:s,leakyreluAlpha:a};return o==null?Gn((V,q,W)=>{let Y=M.runKernel(ki,F,$);return W([V,q,Y]),{value:K(Y,y),gradFunc:N}})(T,k):Gn((V,q,W,Y)=>{let Z=M.runKernel(ki,F,$);return Y([V,q,Z,W]),{value:K(Z,y),gradFunc:N}})(T,k,I)}var FP=A({fusedMatMul_:Oie});function zie(r){return ET(r,.54,.46)}var Gie=A({hammingWindow_:zie});function Wie(r){return ET(r,.5,.5)}var gS=A({hannWindow_:Wie});function Kie(r,e,t,n=!1,o=0){let s=0,i=[];for(;s+e<=r.size;)i.push(Ke(r,s,e)),s+=t;if(n)for(;s<r.size;){let a=s+e-r.size,l=mt([Ke(r,s,e-a),$a([a],o)]);i.push(l),s+=t}return i.length===0?Ci([],[0,e]):K(mt(i),[i.length,e])}var bS=A({frame_:Kie});function Vie(r,e,t,n,o=gS){n==null&&(n=DP(e));let s=bS(r,e,t),i=G(s,o(e));return op(i,n)}var Uie=A({stft_:Vie});function jie(r,e,t,n,o="bilinear",s=0){let i=v(r,"image","cropAndResize"),a=v(e,"boxes","cropAndResize","float32"),l=v(t,"boxInd","cropAndResize","int32"),u=a.shape[0];R(i.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`),R(a.rank===2&&a.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${a.shape}.`),R(l.rank===1&&l.shape[0]===u,()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${a.shape}.`),R(n.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${n.length}.`),R(n[0]>=1&&n[1]>=1,()=>`cropSize must be atleast [1,1], but was ${n}`),R(o==="bilinear"||o==="nearest",()=>`method must be bilinear or nearest, but was ${o}`);let p={image:i,boxes:a,boxInd:l},c={method:o,extrapolationValue:s,cropSize:n};return M.runKernel(dl,p,c)}var RP=A({cropAndResize_:jie});function Hie(r){let e=v(r,"image","flipLeftRight","float32");R(e.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${e.rank}.`);let t={image:e};return M.runKernel(yl,t,{})}var LP=A({flipLeftRight_:Hie});function qie(r,e,t=0,n=.5){let o=v(r,"image","rotateWithOffset","float32");R(o.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${o.rank}.`);let s={image:o},i={radians:e,fillValue:t,center:n};return M.runKernel(Bl,s,i)}var $P=A({rotateWithOffset_:qie});function ys(r,e,t,n,o,s){n==null&&(n=.5),o==null&&(o=Number.NEGATIVE_INFINITY),s==null&&(s=0);let i=r.shape[0];return t=Math.min(t,i),R(0<=n&&n<=1,()=>`iouThreshold must be in [0, 1], but was '${n}'`),R(r.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${r.rank}'`),R(r.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${r.shape[1]}`),R(e.rank===1,()=>"scores must be a 1D tensor"),R(e.shape[0]===i,()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${e.shape[0]}`),R(0<=s&&s<=1,()=>`softNmsSigma must be in [0, 1], but was '${s}'`),{maxOutputSize:t,iouThreshold:n,scoreThreshold:o,softNmsSigma:s}}function Xie(r,e,t,n=.5,o=Number.NEGATIVE_INFINITY){let s=v(r,"boxes","nonMaxSuppression"),i=v(e,"scores","nonMaxSuppression"),a=ys(s,i,t,n,o);t=a.maxOutputSize,n=a.iouThreshold,o=a.scoreThreshold;let l={maxOutputSize:t,iouThreshold:n,scoreThreshold:o};return M.runKernel(Cl,{boxes:s,scores:i},l)}var PP=A({nonMaxSuppression_:Xie});function BP(r,e,t){let n=Yie(r,e,t),o=n<0?-(n+1):n;r.splice(o,0,e)}function Yie(r,e,t){return Jie(r,e,t||Zie)}function Zie(r,e){return r>e?1:r<e?-1:0}function Jie(r,e,t){let n=0,o=r.length,s=0,i=!1;for(;n<o;){s=n+(o-n>>>1);let a=t(e,r[s]);a>0?n=s+1:(o=s,i=!a)}return i?n:-n-1}function RT(r,e,t,n,o){return yS(r,e,t,n,o,0)}function LT(r,e,t,n,o,s){return yS(r,e,t,n,o,0,!1,s,!0)}function $T(r,e,t,n,o,s){return yS(r,e,t,n,o,s,!0)}function yS(r,e,t,n,o,s,i=!1,a=!1,l=!1){let u=[];for(let g=0;g<e.length;g++)e[g]>o&&u.push({score:e[g],boxIndex:g,suppressBeginIndex:0});u.sort(OP);let p=s>0?-.5/s:0,c=[],m=[];for(;c.length<t&&u.length>0;){let g=u.pop(),{score:b,boxIndex:y,suppressBeginIndex:T}=g;if(b<o)break;let k=!1;for(let I=c.length-1;I>=T;--I){let S=Qie(r,y,c[I]);if(S>=n){k=!0;break}if(g.score=g.score*ele(n,p,S),g.score<=o)break}g.suppressBeginIndex=c.length,k||(g.score===b?(c.push(y),m.push(g.score)):g.score>o&&BP(u,g,OP))}let f=c.length,d=t-f;a&&d>0&&(c.push(...new Array(d).fill(0)),m.push(...new Array(d).fill(0)));let h={selectedIndices:c};return i&&(h.selectedScores=m),l&&(h.validOutputs=f),h}function Qie(r,e,t){let n=r.subarray(e*4,e*4+4),o=r.subarray(t*4,t*4+4),s=Math.min(n[0],n[2]),i=Math.min(n[1],n[3]),a=Math.max(n[0],n[2]),l=Math.max(n[1],n[3]),u=Math.min(o[0],o[2]),p=Math.min(o[1],o[3]),c=Math.max(o[0],o[2]),m=Math.max(o[1],o[3]),f=(a-s)*(l-i),d=(c-u)*(m-p);if(f<=0||d<=0)return 0;let h=Math.max(s,u),g=Math.max(i,p),b=Math.min(a,c),y=Math.min(l,m),T=Math.max(b-h,0)*Math.max(y-g,0);return T/(f+d-T)}function ele(r,e,t){let n=Math.exp(e*t*t);return t<=r?n:0}function OP(r,e){return r.score-e.score||r.score===e.score&&e.boxIndex-r.boxIndex}async function tle(r,e,t,n=.5,o=Number.NEGATIVE_INFINITY){let s=v(r,"boxes","nonMaxSuppressionAsync"),i=v(e,"scores","nonMaxSuppressionAsync"),a=ys(s,i,t,n,o);t=a.maxOutputSize,n=a.iouThreshold,o=a.scoreThreshold;let l=await Promise.all([s.data(),i.data()]),u=l[0],p=l[1],{selectedIndices:c}=RT(u,p,t,n,o);return s!==r&&s.dispose(),i!==e&&i.dispose(),Zt(c,"int32")}var zP=tle;function rle(r,e,t,n=.5,o=Number.NEGATIVE_INFINITY,s=0){let i=v(r,"boxes","nonMaxSuppression"),a=v(e,"scores","nonMaxSuppression"),l=ys(i,a,t,n,o,s);t=l.maxOutputSize,n=l.iouThreshold,o=l.scoreThreshold,s=l.softNmsSigma;let u={boxes:i,scores:a},p={maxOutputSize:t,iouThreshold:n,scoreThreshold:o,softNmsSigma:s},c=M.runKernel(Nl,u,p);return{selectedIndices:c[0],selectedScores:c[1]}}var GP=A({nonMaxSuppressionWithScore_:rle});async function nle(r,e,t,n=.5,o=Number.NEGATIVE_INFINITY,s=0){let i=v(r,"boxes","nonMaxSuppressionAsync"),a=v(e,"scores","nonMaxSuppressionAsync"),l=ys(i,a,t,n,o,s);t=l.maxOutputSize,n=l.iouThreshold,o=l.scoreThreshold,s=l.softNmsSigma;let u=await Promise.all([i.data(),a.data()]),p=u[0],c=u[1],{selectedIndices:m,selectedScores:f}=$T(p,c,t,n,o,s);return i!==r&&i.dispose(),a!==e&&a.dispose(),{selectedIndices:Zt(m,"int32"),selectedScores:Zt(f)}}var WP=nle;function ole(r,e,t,n=.5,o=Number.NEGATIVE_INFINITY,s=!1){let i=v(r,"boxes","nonMaxSuppression"),a=v(e,"scores","nonMaxSuppression"),l=ys(i,a,t,n,o,null),u=l.maxOutputSize,p=l.iouThreshold,c=l.scoreThreshold,m={boxes:i,scores:a},f={maxOutputSize:u,iouThreshold:p,scoreThreshold:c,padToMaxOutputSize:s},d=M.runKernel(Sl,m,f);return{selectedIndices:d[0],validOutputs:d[1]}}var KP=A({nonMaxSuppressionPadded_:ole});async function sle(r,e,t,n=.5,o=Number.NEGATIVE_INFINITY,s=!1){let i=v(r,"boxes","nonMaxSuppressionAsync"),a=v(e,"scores","nonMaxSuppressionAsync"),l=ys(i,a,t,n,o,null),u=l.maxOutputSize,p=l.iouThreshold,c=l.scoreThreshold,[m,f]=await Promise.all([i.data(),a.data()]),{selectedIndices:d,validOutputs:h}=LT(m,f,u,p,c,s);return i!==r&&i.dispose(),a!==e&&a.dispose(),{selectedIndices:Zt(d,"int32"),validOutputs:be(h,"int32")}}var VP=sle;function ale(r,e,t=!1,n=!1){let o=v(r,"images","resizeBilinear");R(o.rank===3||o.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${o.rank}.`),R(e.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${e}.`),R(n===!1||t===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let s=o,i=!1;o.rank===3&&(i=!0,s=K(o,[1,o.shape[0],o.shape[1],o.shape[2]]));let[]=e,a={images:s},l={alignCorners:t,halfPixelCenters:n,size:e},u=M.runKernel(ya,a,l);return i?K(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var PT=A({resizeBilinear_:ale});function ile(r,e,t=!1,n=!1){let o=v(r,"images","resizeNearestNeighbor");R(o.rank===3||o.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${o.rank}.`),R(e.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${e}.`),R(o.dtype==="float32"||o.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),R(n===!1||t===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let s=o,i=!1;o.rank===3&&(i=!0,s=K(o,[1,o.shape[0],o.shape[1],o.shape[2]]));let[]=e,a={images:s},l={alignCorners:t,halfPixelCenters:n,size:e},u=M.runKernel(Vu,a,l);return i?K(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var BT=A({resizeNearestNeighbor_:ile});function lle(r,e="binary",t=!1,n=.5){let o=v(r,"image","threshold"),s=.2989,i=.587,a=.114,l=o.shape[0]*o.shape[1],u=G(Zt([n]),255),p,c,m,f;if(R(o.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${o.rank}.`),R(o.shape[2]===3||o.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${o.shape[2]}.`),R(o.dtype==="int32"||o.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${o.dtype}.`),R(e==="otsu"||e==="binary",()=>`Method must be binary or otsu, but was ${e}`),o.shape[2]===3){[p,c,m]=Rr(o,[1,1,1],-1);let g=G(p,s),b=G(c,i),y=G(m,a);f=ne(ne(g,b),y)}else f=r;if(e==="otsu"){let g=sg(ue(Lc(f),"int32"),mn([]),256);u=ule(g,l)}let d=t?lo(f,u):yr(f,u);return ue(G(d,255),"int32")}function ule(r,e){let t=Zt([-1]),n=Zt([0]),o=Zt([0]),s,i,a,l,u,p;for(let c=0;c<r.size-1;c++){s=Ke(r,0,c+1),i=Ke(r,c+1),u=he(Te(s),e),p=he(Te(i),e);let m=Te(G(s,Jl(0,s.size)));a=he(m,Te(s));let f=$a(i.shape,s.size),d=ne(Jl(0,i.size),f),h=G(i,d);l=he(Te(h),Te(i));let g=ge(a,l),b=ge(a,l),y=G(u,p);o=G(G(y,g),b);let T=yr(o,n);n=Wt(T,o,n),t=Wt(T,Zt([c]),t)}return t}var UP=A({threshold_:lle});function ple(r,e,t="nearest",n="constant",o=0,s){let i=v(r,"image","transform","float32"),a=v(e,"transforms","transform","float32");R(i.rank===4,()=>`Error in transform: image must be rank 4,but got rank ${i.rank}.`),R(a.rank===2&&(a.shape[0]===i.shape[0]||a.shape[0]===1)&&a.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),R(s==null||s.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${s}.`);let l={image:i,transforms:a},u={interpolation:t,fillMode:n,fillValue:o,outputShape:s};return M.runKernel(Pl,l,u)}var jP=A({transform_:ple});function cle(r,e,t){R(e%1==0,()=>`bandPart(): numLower must be an integer, got ${e}.`),R(t%1==0,()=>`bandPart(): numUpper must be an integer, got ${t}.`);let n=v(r,"a","bandPart");R(n.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${n.rank}.`);let o=n.shape,[s,i]=n.shape.slice(-2);if(!(e<=s))throw new Error(`bandPart(): numLower (${e}) must not be greater than the number of rows (${s}).`);if(!(t<=i))throw new Error(`bandPart(): numUpper (${t}) must not be greater than the number of columns (${i}).`);e<0&&(e=s),t<0&&(t=i);let a=K(Jl(0,s,1,"int32"),[-1,1]),l=Jl(0,i,1,"int32"),u=ge(a,l),p=Xr(lo(u,be(+e,"int32")),io(u,be(-t,"int32"))),c=Rt([s,i],n.dtype);return K(xr(Vr(K(n,[-1,s,i])).map(m=>Wt(p,m,c))),o)}var HP=A({bandPart_:cle});function mle(r){let e;if(Array.isArray(r)){e=!1,R(r!=null&&r.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let o=r[0].shape[0];for(let s=1;s<r.length;++s)R(r[s].shape[0]===o,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${r[s].shape[0]} vs. ${o})`)}else e=!0,r=Rr(r,r.shape[0],0).map(o=>Xo(o,[0]));R(r.length<=r[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${r.length}) exceeds number of dimensions (${r[0].shape[0]}).`);let t=[],n=r;for(let o=0;o<r.length;++o)t.push(M.tidy(()=>{let s=n[o];if(o>0)for(let i=0;i<o;++i){let a=G(Te(G(t[i],s)),t[i]);s=ge(s,a)}return he(s,td(s,"euclidean"))}));return e?xr(t,0):t}var qP=A({gramSchmidt_:mle});function fle(r,e=!1){if(R(r.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${r.rank}`),r.rank===2)return XP(r,e);{let t=r.shape.slice(0,r.shape.length-2).reduce((l,u)=>l*u),n=Vr(K(r,[t,r.shape[r.shape.length-2],r.shape[r.shape.length-1]]),0),o=[],s=[];n.forEach(l=>{let[u,p]=XP(l,e);o.push(u),s.push(p)});let i=K(xr(o,0),r.shape),a=K(xr(s,0),r.shape);return[i,a]}}function XP(r,e=!1){return M.tidy(()=>{R(r.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${r.shape.length}D Tensor.`);let t=r.shape[0],n=r.shape[1],o=Xf(t),s=jo(r),i=Ci([[1]],[1,1]),a=jo(i),l=t>=n?n:t;for(let u=0;u<l;++u){let p=s,c=a,m=o;[a,s,o]=M.tidy(()=>{let f=Ke(s,[u,u],[t-u,1]),d=td(f),h=Ke(s,[u,u],[1,1]),g=Wt(yr(h,0),Ci([[-1]]),Ci([[1]])),b=ge(h,G(g,d)),y=he(f,b);y.shape[0]===1?a=jo(i):a=mt([i,Ke(y,[1,0],[y.shape[0]-1,y.shape[1]])],0);let T=st(he(tt(g,b),d)),k=Ke(s,[u,0],[t-u,n]),I=G(T,a),S=nt(a);if(u===0)s=ge(k,tt(I,tt(S,k)));else{let $=ge(k,tt(I,tt(S,k)));s=mt([Ke(s,[0,0],[u,n]),$],0)}let N=nt(I),F=Ke(o,[0,u],[t,o.shape[1]-u]);if(u===0)o=ge(F,tt(tt(F,a),N));else{let $=ge(F,tt(tt(F,a),N));o=mt([Ke(o,[0,0],[t,u]),$],1)}return[a,s,o]}),Be([p,c,m])}return!e&&t>n&&(o=Ke(o,[0,0],[t,n]),s=Ke(s,[0,0],[n,n])),[o,s]})}var YP=A({qr_:fle});var Tr;(function(r){r[r.NONE=0]="NONE",r[r.MEAN=1]="MEAN",r[r.SUM=2]="SUM",r[r.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"})(Tr||(Tr={}));function dle(r,e,t=Tr.SUM_BY_NONZERO_WEIGHTS){let n=v(r,"losses","computeWeightedLoss"),o=null;e!=null&&(o=v(e,"weights","computeWeightedLoss"));let s=o==null?n:G(n,o);if(t===Tr.NONE)return s;if(t===Tr.SUM)return Te(s);if(t===Tr.MEAN){if(o==null)return Ft(s);{let i=n.size/o.size,a=he(Te(s),Te(o));return i>1?he(a,be(i)):a}}if(t===Tr.SUM_BY_NONZERO_WEIGHTS){if(o==null)return he(Te(s),be(n.size));{let i=G(o,on(n.shape)),a=ue(Te(gs(i,be(0))),"float32");return he(Te(s),a)}}throw Error(`Unknown reduction: ${t}`)}var vn=A({computeWeightedLoss_:dle});function hle(r,e,t,n=Tr.SUM_BY_NONZERO_WEIGHTS){let o=v(r,"labels","absoluteDifference"),s=v(e,"predictions","absoluteDifference"),i=null;t!=null&&(i=v(t,"weights","absoluteDifference")),Er(o.shape,s.shape,"Error in absoluteDifference: ");let a=Ht(ge(o,s));return vn(a,i,n)}var gle=A({absoluteDifference_:hle});function ble(r,e,t,n,o=Tr.SUM_BY_NONZERO_WEIGHTS){let s=v(r,"labels","cosineDistance"),i=v(e,"predictions","cosineDistance"),a=null;n!=null&&(a=v(n,"weights","cosineDistance")),Er(s.shape,i.shape,"Error in cosineDistance: ");let l=be(1),u=ge(l,Te(G(s,i),t,!0));return vn(u,a,o)}var yle=A({cosineDistance_:ble});function xle(r,e,t,n=Tr.SUM_BY_NONZERO_WEIGHTS){let o=v(r,"labels","hingeLoss"),s=v(e,"predictions","hingeLoss"),i=null;t!=null&&(i=v(t,"weights","hingeLoss")),Er(o.shape,s.shape,"Error in hingeLoss: ");let a=be(1);o=ge(G(be(2),o),a);let l=hn(ge(a,G(o,s)));return vn(l,i,n)}var Tle=A({hingeLoss_:xle});function kle(r,e,t,n=1,o=Tr.SUM_BY_NONZERO_WEIGHTS){let s=v(r,"labels","huberLoss"),i=v(e,"predictions","huberLoss"),a=null;t!=null&&(a=v(t,"weights","huberLoss")),Er(s.shape,i.shape,"Error in huberLoss: ");let l=be(n),u=Ht(ge(i,s)),p=Oa(u,l),c=ge(u,p),m=ne(G(be(.5),je(p)),G(l,c));return vn(m,a,o)}var Ile=A({huberLoss_:kle});function vle(r,e,t,n=1e-7,o=Tr.SUM_BY_NONZERO_WEIGHTS){let s=v(r,"labels","logLoss"),i=v(e,"predictions","logLoss"),a=null;t!=null&&(a=v(t,"weights","logLoss")),Er(s.shape,i.shape,"Error in logLoss: ");let l=be(1),u=be(n),p=st(G(s,Kr(ne(i,u)))),c=G(ge(l,s),Kr(ne(ge(l,i),u))),m=ge(p,c);return vn(m,a,o)}var wle=A({logLoss_:vle});function _le(r,e,t,n=Tr.SUM_BY_NONZERO_WEIGHTS){let o=v(r,"labels","meanSquaredError"),s=v(e,"predictions","meanSquaredError"),i=null;t!=null&&(i=v(t,"weights","meanSquaredError")),Er(o.shape,s.shape,"Error in meanSquaredError: ");let a=zc(o,s);return vn(a,i,n)}var Cle=A({meanSquaredError_:_le});function Sle(r,e){let t=v(r,"labels","sigmoidCrossEntropyWithLogits"),n=v(e,"logits","sigmoidCrossEntropyWithLogits");Er(t.shape,n.shape,"Error in sigmoidCrossEntropyWithLogits: ");let o=hn(n),s=G(n,t),i=Dc(Fr(st(Ht(n))));return ne(ge(o,s),i)}function Nle(r,e,t,n=0,o=Tr.SUM_BY_NONZERO_WEIGHTS){let s=v(r,"multiClassLabels","sigmoidCrossEntropy"),i=v(e,"logits","sigmoidCrossEntropy"),a=null;if(t!=null&&(a=v(t,"weights","sigmoidCrossEntropy")),Er(s.shape,i.shape,"Error in sigmoidCrossEntropy: "),n>0){let u=be(n),p=be(1),c=be(.5);s=ne(G(s,ge(p,u)),G(c,u))}let l=Sle(s,i);return vn(l,a,o)}var Ale=A({sigmoidCrossEntropy_:Nle});function Dle(r,e,t=-1){if(t===-1&&(t=e.rank-1),t!==e.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${e.rank} and dim was ${t}`);return Gn((o,s,i)=>{let l=gg(s,[t],!0),u=ge(ue(s,"float32"),l);i([o,u]);let p=st(G(u,o));return{value:Te(p,[t]),gradFunc:(f,d)=>{let[h,g]=d,b=hs(f.shape,[t]);return[G(K(f,b),ge(ue(h,"float32"),Fr(g))),G(K(f,b),ge(Fr(g),ue(h,"float32")))]}}})(r,e)}function Ele(r,e,t,n=0,o=Tr.SUM_BY_NONZERO_WEIGHTS){let s=v(r,"onehotLabels","softmaxCrossEntropy"),i=v(e,"logits","softmaxCrossEntropy"),a=null;if(t!=null&&(a=v(t,"weights","softmaxCrossEntropy")),Er(s.shape,i.shape,"Error in softmaxCrossEntropy: "),n>0){let u=be(n),p=be(1),c=be(s.shape[1]);s=ne(G(s,ge(p,u)),he(u,c))}let l=Dle(s,i);return vn(l,a,o)}var Mle=A({softmaxCrossEntropy_:Ele});function Fle(r,e,t,n){let o=v(r,"indices","sparseFillEmptyRows"),s=v(e,"values","sparseFillEmptyRows"),i=v(t,"denseShape","sparseFillEmptyRows"),a=v(n,"defaultValue","sparseFillEmptyRows",s.dtype);if(o.rank!==2)throw new Error(`Indices should be Tensor2D but received shape
|
|
${o.shape}`);if(s.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${s.shape}`);if(i.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${i.shape}`);if(a.rank!==0)throw new Error(`Default value should be a scalar but received shape ${a.shape}`);let l={indices:o,values:s,denseShape:i,defaultValue:a},u=M.runKernel(Af,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}var ZP=A({sparseFillEmptyRows_:Fle});function Rle(r,e,t){let n=v(r,"inputIndices","sparseReshape"),o=v(e,"inputShape","sparseReshape"),s=v(t,"newShape","sparseReshape");if(n.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape
|
|
${n.shape}`);if(o.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${o.shape}`);if(s.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${s.shape}`);let i={inputIndices:n,inputShape:o,newShape:s},a=M.runKernel(Df,i);return{outputIndices:a[0],outputShape:a[1]}}var JP=A({sparseReshape_:Rle});function Lle(r,e,t){let n=v(r,"data","sparseSegmentMean"),o=v(e,"indices","sparseSegmentMean"),s=v(t,"segmentIds","sparseSegmentMean");if(n.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
|
|
${o.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
|
|
${s.shape}`);let i={data:n,indices:o,segmentIds:s};return M.runKernel(Ef,i)}var QP=A({sparseSegmentMean_:Lle});function $le(r,e,t){let n=v(r,"data","sparseSegmentSum"),o=v(e,"indices","sparseSegmentSum"),s=v(t,"segmentIds","sparseSegmentSum");if(n.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
|
|
${o.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
|
|
${s.shape}`);let i={data:n,indices:o,segmentIds:s};return M.runKernel(Mf,i)}var eB=A({sparseSegmentSum_:$le});function Ple(r,e,t,n,o,s,i,a){let l=v(r,"data","stringNGrams","string");if(l.dtype!=="string")throw new Error("Data must be of datatype string");if(l.shape.length!==1)throw new Error(`Data must be a vector, saw: ${l.shape}`);let u=v(e,"dataSplits","stringNGrams");if(u.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let p={separator:t,nGramWidths:n,leftPad:o,rightPad:s,padWidth:i,preserveShortSequences:a},c={data:l,dataSplits:u},m=M.runKernel(Rf,c,p);return{nGrams:m[0],nGramsSplits:m[1]}}var tB=A({stringNGrams_:Ple});function Ble(r,e,t=!0){let n=v(r,"input","stringSplit","string"),o=v(e,"delimiter","stringSplit","string");if(n.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${n.shape}`);if(o.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${o.shape}`);let s={skipEmpty:t},i={input:n,delimiter:o},a=M.runKernel(Lf,i,s);return{indices:a[0],values:a[1],shape:a[2]}}var rB=A({stringSplit_:Ble});function Ole(r,e){let t=v(r,"input","stringToHashBucketFast","string"),n={numBuckets:e};if(e<=0)throw new Error("Number of buckets must be at least 1");let o={input:t};return M.runKernel($f,o,n)}var nB=A({stringToHashBucketFast_:Ole});var Si={flipLeftRight:LP,resizeNearestNeighbor:BT,resizeBilinear:PT,rotateWithOffset:$P,cropAndResize:RP,nonMaxSuppression:PP,nonMaxSuppressionAsync:zP,nonMaxSuppressionWithScore:GP,nonMaxSuppressionWithScoreAsync:WP,nonMaxSuppressionPadded:KP,nonMaxSuppressionPaddedAsync:VP,threshold:UP,transform:jP},oB={bandPart:HP,gramSchmidt:qP,qr:YP};var Ag={sparseFillEmptyRows:ZP,sparseReshape:JP,sparseSegmentMean:QP,sparseSegmentSum:eB},OT={stringNGrams:tB,stringSplit:rB,stringToHashBucketFast:nB};var wn=class extends kT{minimize(e,t=!1,n){let{value:o,grads:s}=this.computeGradients(e,n);if(n!=null){let i=n.map(a=>({name:a.name,tensor:s[a.name]}));this.applyGradients(i)}else this.applyGradients(s);return Be(s),t?o:(o.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return wT(e,t)}dispose(){this.iterations_!=null&&Be(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:be(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(wn,Symbol.hasInstance,{value:r=>r.minimize!=null&&r.computeGradients!=null&&r.applyGradients!=null});var jc=class extends wn{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=M.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,o)=>{let s=M.registeredVariables[n],i=!1;this.accumulatedGrads[o]==null&&(this.accumulatedGrads[o]={originalName:`${n}/accum_grad`,variable:j(()=>Me(s).variable(i))}),this.accumulatedUpdates[o]==null&&(this.accumulatedUpdates[o]={originalName:`${n}/accum_var`,variable:j(()=>Me(s).variable(i))});let a=Array.isArray(e)?e[o].tensor:e[n];if(a==null)return;let l=this.accumulatedGrads[o].variable,u=this.accumulatedUpdates[o].variable;j(()=>{let p=ne(G(l,this.rho),G(je(a),1-this.rho)),c=G(he(Lt(ne(u,this.epsilon)),Lt(ne(l,this.epsilon))),a),m=ne(G(u,this.rho),G(je(c),1-this.rho));l.assign(p),u.assign(m);let f=ne(G(c,-this.learningRate),s);s.assign(f)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(Be(this.accumulatedGrads.map(e=>e.variable)),Be(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){let 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);let t=e.length/2,n=!1;this.accumulatedGrads=e.slice(0,t).map(o=>({originalName:o.name,variable:o.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,t*2).map(o=>({originalName:o.name,variable:o.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}};jc.className="Adadelta";ao(jc);var Hc=class extends wn{constructor(e,t=.1){super();this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,o)=>{let s=M.registeredVariables[n];if(this.accumulatedGrads[o]==null){let l=!1;this.accumulatedGrads[o]={originalName:`${n}/accumulator`,variable:j(()=>$a(s.shape,this.initialAccumulatorValue).variable(l))}}let i=Array.isArray(e)?e[o].tensor:e[n];if(i==null)return;let a=this.accumulatedGrads[o].variable;j(()=>{let l=ne(a,je(i));a.assign(l);let u=ne(G(he(i,Lt(ne(l,M.backend.epsilon()))),-this.learningRate),s);s.assign(u)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&Be(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);let t=!1;this.accumulatedGrads=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}};Hc.className="Adagrad";ao(Hc);var qc=class extends wn{constructor(e,t,n,o=null){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=o,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],j(()=>{this.accBeta1=be(t).variable(),this.accBeta2=be(n).variable()}),o==null&&(this.epsilon=M.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);j(()=>{let n=ge(1,this.accBeta1),o=ge(1,this.accBeta2);t.forEach((s,i)=>{let a=M.registeredVariables[s],l=!1;this.accumulatedFirstMoment[i]==null&&(this.accumulatedFirstMoment[i]={originalName:`${s}/m`,variable:j(()=>Me(a).variable(l))}),this.accumulatedSecondMoment[i]==null&&(this.accumulatedSecondMoment[i]={originalName:`${s}/v`,variable:j(()=>Me(a).variable(l))});let u=Array.isArray(e)?e[i].tensor:e[s];if(u==null)return;let p=this.accumulatedFirstMoment[i].variable,c=this.accumulatedSecondMoment[i].variable,m=ne(G(p,this.beta1),G(u,1-this.beta1)),f=ne(G(c,this.beta2),G(je(u),1-this.beta2)),d=he(m,n),h=he(f,o);p.assign(m),c.assign(f);let g=ne(G(he(d,ne(Lt(h),this.epsilon)),-this.learningRate),a);a.assign(g)}),this.accBeta1.assign(G(this.accBeta1,this.beta1)),this.accBeta2.assign(G(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&Be(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&Be(this.accumulatedSecondMoment.map(e=>e.variable))}async getWeights(){let 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),j(()=>{this.accBeta1.assign(In(this.beta1,this.iterations_+1)),this.accBeta2.assign(In(this.beta2,this.iterations_+1))});let t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(o=>({originalName:o.name,variable:o.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(o=>({originalName:o.name,variable:o.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}};qc.className="Adam";ao(qc);var Xc=class extends wn{constructor(e,t,n,o=null,s=0){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=o,this.decay=s,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],j(()=>{this.iteration=be(0).variable(),this.accBeta1=be(t).variable()}),o==null&&(this.epsilon=M.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);j(()=>{let n=ge(1,this.accBeta1),o=he(-this.learningRate,ne(G(this.iteration,this.decay),1));t.forEach((s,i)=>{let a=M.registeredVariables[s],l=!1;this.accumulatedFirstMoment[i]==null&&(this.accumulatedFirstMoment[i]={originalName:`${s}/m`,variable:Me(a).variable(l)}),this.accumulatedWeightedInfNorm[i]==null&&(this.accumulatedWeightedInfNorm[i]={originalName:`${s}/v`,variable:Me(a).variable(l)});let u=Array.isArray(e)?e[i].tensor:e[s];if(u==null)return;let p=this.accumulatedFirstMoment[i].variable,c=this.accumulatedWeightedInfNorm[i].variable,m=ne(G(p,this.beta1),G(u,1-this.beta1)),f=G(c,this.beta2),d=Ht(u),h=Wn(f,d);p.assign(m),c.assign(h);let g=ne(G(he(o,n),he(m,ne(h,this.epsilon))),a);a.assign(g)}),this.iteration.assign(ne(this.iteration,1)),this.accBeta1.assign(G(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Be(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&Be(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)}};Xc.className="Adamax";ao(Xc);var tu=class extends wn{constructor(e){super();this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,o)=>{let s=Array.isArray(e)?e[o].tensor:e[n];if(s==null)return;let i=M.registeredVariables[n];j(()=>{let a=ne(G(this.c,s),i);i.assign(a)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=er(be(-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)}};tu.className="SGD";ao(tu);var Yc=class extends tu{constructor(e,t,n=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=be(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,o)=>{let s=M.registeredVariables[n];if(this.accumulations[o]==null){let l=!1;this.accumulations[o]={originalName:`${n}/momentum`,variable:j(()=>Me(s).variable(l))}}let i=this.accumulations[o].variable,a=Array.isArray(e)?e[o].tensor:e[n];a!=null&&j(()=>{let l,u=ne(G(this.m,i),a);this.useNesterov?l=ne(G(this.c,ne(a,G(u,this.m))),s):l=ne(G(this.c,u),s),i.assign(u),s.assign(l)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&Be(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);let t=!1;this.accumulations=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}};Yc.className="Momentum";ao(Yc);var Zc=class extends wn{constructor(e,t=.9,n=0,o=null,s=!1){super();if(this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=o,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=s,o==null&&(this.epsilon=M.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,o)=>{let s=M.registeredVariables[n],i=!1;this.accumulatedMeanSquares[o]==null&&(this.accumulatedMeanSquares[o]={originalName:`${n}/rms`,variable:j(()=>Me(s).variable(i))}),this.accumulatedMoments[o]==null&&(this.accumulatedMoments[o]={originalName:`${n}/momentum`,variable:j(()=>Me(s).variable(i))}),this.accumulatedMeanGrads[o]==null&&this.centered&&(this.accumulatedMeanGrads[o]={originalName:`${n}/mg`,variable:j(()=>Me(s).variable(i))});let a=Array.isArray(e)?e[o].tensor:e[n];if(a==null)return;let l=this.accumulatedMeanSquares[o].variable,u=this.accumulatedMoments[o].variable;j(()=>{let p=ne(G(l,this.decay),G(je(a),1-this.decay));if(this.centered){let c=this.accumulatedMeanGrads[o].variable,m=ne(G(c,this.decay),G(a,1-this.decay)),f=he(G(a,this.learningRate),Lt(ge(p,ne(je(m),this.epsilon)))),d=ne(G(u,this.momentum),f);l.assign(p),c.assign(m),u.assign(d);let h=ge(s,d);s.assign(h)}else{let c=ne(G(l,this.decay),G(je(a),1-this.decay)),m=ne(G(u,this.momentum),he(G(a,this.learningRate),Lt(ne(c,this.epsilon))));l.assign(c),u.assign(m);let f=ge(s,m);s.assign(f)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&Be(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&Be(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&Be(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){let 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);let t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map(o=>({originalName:o.name,variable:o.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,t*2).map(o=>({originalName:o.name,variable:o.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(o=>({originalName:o.name,variable:o.tensor.variable(n)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}};Zc.className="RMSProp";ao(Zc);var ru=class{static sgd(e){return new tu(e)}static momentum(e,t,n=!1){return new Yc(e,t,n)}static rmsprop(e,t=.9,n=0,o=null,s=!1){return new Zc(e,t,n,o,s)}static adam(e=.001,t=.9,n=.999,o=null){return new qc(e,t,n,o)}static adadelta(e=.001,t=.95,n=null){return new jc(e,t,n)}static adamax(e=.002,t=.9,n=.999,o=null,s=0){return new Xc(e,t,n,o,s)}static adagrad(e,t=.1){return new Hc(e,t)}};var Jc={sgd:ru.sgd,momentum:ru.momentum,adadelta:ru.adadelta,adagrad:ru.adagrad,rmsprop:ru.rmsprop,adamax:ru.adamax,adam:ru.adam};var zle=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:r=>r())();function Dg(){return new Promise(r=>zle(()=>r()))}var C={};Ge(C,{ERF_A1:()=>Zle,ERF_A2:()=>Jle,ERF_A3:()=>Qle,ERF_A4:()=>eue,ERF_A5:()=>tue,ERF_P:()=>Yle,PARALLELIZE_THRESHOLD:()=>zT,SELU_SCALE:()=>TS,SELU_SCALEALPHA:()=>xS,applyActivation:()=>Vc,assertAndGetBroadcastShape:()=>qe,assertAxesAreInnerMostDims:()=>Use,assertParamsConsistent:()=>Gle,assignToTypedArray:()=>uue,axesAreInnerMostDims:()=>sS,calculateShapes:()=>lP,checkEinsumDimSizes:()=>hue,combineLocations:()=>vP,complexWithEvenIndex:()=>aue,complexWithOddIndex:()=>iue,computeConv2DInfo:()=>Ic,computeConv3DInfo:()=>TP,computeDefaultPad:()=>WC,computeDilation2DInfo:()=>Toe,computeOptimalWindowSize:()=>Kle,computeOutAndReduceShapes:()=>aS,computeOutShape:()=>Wle,computePool2DInfo:()=>GC,computePool3DInfo:()=>koe,convertConv2DDataFormat:()=>kP,decodeEinsumEquation:()=>fue,eitherStridesOrDilationsAreOne:()=>rn,expandShapeToKeepDim:()=>hs,exponent:()=>cue,exponents:()=>pue,fromStringArrayToUint8:()=>wue,fromUint8ToStringArray:()=>vue,getAxesPermutation:()=>iS,getBroadcastDims:()=>pse,getComplexWithIndex:()=>lue,getEinsumComputePath:()=>gue,getEinsumPermutation:()=>due,getFusedBiasGradient:()=>Kc,getFusedDyActivation:()=>Wc,getImageCenter:()=>Vle,getInnerMostAxes:()=>jse,getPermuted:()=>jle,getReductionAxes:()=>Gt,getReshaped:()=>Ule,getReshapedPermuted:()=>Hle,getSliceBeginCoords:()=>qle,getSliceSize:()=>Xle,getUndoAxesPermutation:()=>hg,isIdentityPermutation:()=>bue,log:()=>nue,mergeRealAndImagArrays:()=>oue,prepareAndValidate:()=>iP,prepareSplitSize:()=>xue,segment_util:()=>IS,shouldFuse:()=>Uc,slice_util:()=>br,splitRealAndImagArrays:()=>sue,tupleValuesAreOne:()=>Ho,upcastType:()=>Mr,validateInput:()=>yT,validateUpdateShape:()=>PC,warn:()=>rue});function Gle(r,e){let t=r[0].length;r.forEach((o,s)=>{R(o.length===t,()=>`Error in concat${t}D: rank of tensors[${s}] must be the same as the rank of the rest (${t})`)}),R(e>=0&&e<t,()=>`Error in concat${t}D: axis must be between 0 and ${t-1}.`);let n=r[0];r.forEach((o,s)=>{for(let i=0;i<t;i++)R(i===e||o[i]===n[i],()=>`Error in concat${t}D: Shape of tensors[${s}] (${o}) does not match the shape of the rest (${n}) along the non-concatenated axis ${s}.`)})}function Wle(r,e){let t=r[0].slice();for(let n=1;n<r.length;n++)t[e]+=r[n][e];return t}var zT=30;function Kle(r){return r<=zT?r:nf(r,Math.floor(Math.sqrt(r)))}function Vle(r,e,t){let n=t*(typeof r=="number"?r:r[0]),o=e*(typeof r=="number"?r:r[1]);return[n,o]}function Ule(r,e,t,n=!0){let o=[];if(n)o=o.concat(e.slice(0)),o.push(r[0]/t),o=o.concat(r.slice(1));else{o=o.concat(r[0]);let s=e.length;for(let i=0;i<s;++i)o=o.concat([r[i+1]/e[i],e[i]]);o=o.concat(r.slice(s+1))}return o}function jle(r,e,t=!0){let n=[];if(t){n.push(e);for(let o=e+1;o<r;++o)o<=2*e?(n.push(o),n.push(o-(e+1))):n.push(o)}else{let o=[],s=[];for(let i=1;i<r;++i)i>=e*2+1||i%2==1?s.push(i):o.push(i);n.push(...o),n.push(0),n.push(...s)}return n}function Hle(r,e,t,n=!0){let o=[];n?o.push(r[0]/t):o.push(r[0]*t);for(let s=1;s<r.length;++s)s<=e.length?n?o.push(e[s-1]*r[s]):o.push(r[s]/e[s-1]):o.push(r[s]);return o}function qle(r,e){let t=[0];for(let n=0;n<e;++n)t.push(r[n][0]);return t}function Xle(r,e,t){let n=r.slice(0,1);for(let o=0;o<t;++o)n.push(r[o+1]-e[o][0]-e[o][1]);return n}var xS=1.7580993408473768,TS=1.0507009873554805;var Yle=.3275911,Zle=.254829592,Jle=-.284496736,Qle=1.421413741,eue=-1.453152027,tue=1.061405429;function rue(...r){X().getBool("IS_TEST")||console.warn(...r)}function nue(...r){X().getBool("IS_TEST")||console.log(...r)}function oue(r,e){if(r.length!==e.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${r.length}, imag: ${e.length}.`);let t=new Float32Array(r.length*2);for(let n=0;n<t.length;n+=2)t[n]=r[n/2],t[n+1]=e[n/2];return t}function sue(r){let e=new Float32Array(r.length/2),t=new Float32Array(r.length/2);for(let n=0;n<r.length;n+=2)e[n/2]=r[n],t[n/2]=r[n+1];return{real:e,imag:t}}function aue(r){let e=Math.ceil(r.length/4),t=new Float32Array(e),n=new Float32Array(e);for(let o=0;o<r.length;o+=4)t[Math.floor(o/4)]=r[o],n[Math.floor(o/4)]=r[o+1];return{real:t,imag:n}}function iue(r){let e=Math.floor(r.length/4),t=new Float32Array(e),n=new Float32Array(e);for(let o=2;o<r.length;o+=4)t[Math.floor(o/4)]=r[o],n[Math.floor(o/4)]=r[o+1];return{real:t,imag:n}}function lue(r,e){let t=r[e*2],n=r[e*2+1];return{real:t,imag:n}}function uue(r,e,t,n){r[n*2]=e,r[n*2+1]=t}function pue(r,e){let t=new Float32Array(r/2),n=new Float32Array(r/2);for(let o=0;o<Math.ceil(r/2);o++){let s=(e?2:-2)*Math.PI*(o/r);t[o]=Math.cos(s),n[o]=Math.sin(s)}return{real:t,imag:n}}function cue(r,e,t){let n=(t?2:-2)*Math.PI*(r/e),o=Math.cos(n),s=Math.sin(n);return{real:o,imag:s}}var kS="->",mue=/->/g,sB=",",aB="...";function fue(r,e){r=r.replace(/\s/g,"");let t=(r.length-r.replace(mue,"").length)/kS.length;if(t<1)throw new Error("Equations without an arrow are not supported.");if(t>1)throw new Error(`Equation must contain exactly one arrow ("${kS}").`);let[n,o]=r.split(kS);R(n.indexOf(aB)===-1,()=>`The ellipsis notation ("${aB}") is not supported yet.`);let s=n.split(sB),i=s.length;if(e!==i)throw new Error(`Expected ${i} input tensors, received ${e}`);if(i>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");let a=[];for(let m=0;m<o.length;++m){let f=o[m];if(!s.some(d=>d.indexOf(f)!==-1))throw new Error(`Output subscripts contain the label ${f} not present in the input subscripts.`);a.indexOf(f)===-1&&a.push(f)}for(let m=0;m<n.length;++m){let f=n[m];a.indexOf(f)===-1&&f!==sB&&a.push(f)}let l=new Array(s.length);for(let m=0;m<i;++m){if(new Set(s[m].split("")).size!==s[m].length)throw new Error(`Found duplicate axes in input component ${s[m]}. Support for duplicate axes in input is not implemented yet.`);l[m]=[];for(let f=0;f<s[m].length;++f)l[m].push(a.indexOf(s[m][f]))}let u=a.length,p=o.length,c=[];for(let m=p;m<u;++m)c.push(m);return{allDims:a,summedDims:c,idDims:l}}function due(r,e){let t=new Array(r);t.fill(-1);for(let o=0;o<e.length;++o)t[e[o]]=o;let n=[];for(let o=0;o<r;++o)t[o]===-1&&n.push(o);return t=t.filter(o=>o!==-1),{permutationIndices:t,expandDims:n}}function hue(r,e,t){let n=new Array(r);for(let o=0;o<t.length;++o){let s=t[o].shape;for(let i=0;i<e[o].length;++i)n[e[o][i]]===void 0?n[e[o][i]]=s[i]:R(n[e[o][i]]===s[i],()=>`Expected dimension ${n[e[o][i]]} at axis ${i} of input shaped ${JSON.stringify(s)}, but got dimension ${s[i]}`)}}function gue(r,e){let t=r,n=[],o=0;r.length===0&&t.push(-1),o=r.length+1;for(let i=0;i<o;++i)n.push([]);let s=[];for(let i=0;i<t.length;++i){let a=t[i],l=yue(e,a);for(let u of l)s.indexOf(u)===-1&&(n[i].push(u),s.push(u))}return{path:t,steps:n}}function bue(r){return r.every((e,t)=>e===t)}function yue(r,e){let t=[];for(let n=0;n<r.length;++n)(r[n].length===0||r[n].indexOf(e)!==-1||e===-1)&&t.push(n);return t}function xue(r,e,t=0){let n=[];if(typeof e=="number")R(r.shape[t]%e==0,()=>"Number of splits must evenly divide the axis."),n=new Array(e).fill(r.shape[t]/e);else{let o=e.reduce((i,a)=>(a===-1&&(i+=1),i),0);R(o<=1,()=>"There should be only one negative value in split array.");let s=e.indexOf(-1);if(s!==-1){let i=e.reduce((a,l)=>l>0?a+l:a);e[s]=r.shape[t]-i}R(r.shape[t]===e.reduce((i,a)=>i+a),()=>"The sum of sizes must match the size of the axis dimension."),n=e}return n}var IS={};Ge(IS,{collectGatherOpShapeInfo:()=>Iue,computeOutShape:()=>kue,segOpComputeOptimalWindowSize:()=>Tue});function Tue(r,e){let t=!1,n;for(r<=zT?(n=r,t=!0):n=nf(r,Math.floor(Math.sqrt(r)));!t;)n>e||n===r?t=!0:n=nf(r,n+1);return n}function kue(r,e,t){let n=[],o=r.length;for(let s=0;s<o;s++)s!==e?n.push(r[s]):n.push(t);return n}function Iue(r,e,t,n){let o=e.shape.length,s=r.shape.length;if(n!==0&&(n<-o||n>o))throw new Error(`Expect batchDims in the range of [-${o}, ${o}], but got ${n}`);if(n<0&&(n+=o),n>s)throw new Error(`batchDims (${n}) must be less than rank(x) (
|
|
${s}).`);if(t<n)throw new Error(`batchDims (${n}) must be less than or equal to axis (${t}).`);for(let c=0;c<n;++c)if(r.shape[c]!==e.shape[c])throw new Error(`x.shape[${c}]: ${r.shape[c]} should be equal to indices.shape[${c}]: ${e.shape[c]}.`);let i=r.shape[t],a=[],l=1,u=1,p=1;for(let c=0;c<n;++c)a.push(r.shape[c]),l*=r.shape[c];for(let c=n;c<t;c++)a.push(r.shape[c]),u*=r.shape[c];for(let c=n;c<o;c++)a.push(e.shape[c]);for(let c=t+1;c<s;c++)a.push(r.shape[c]),p*=r.shape[c];return{batchSize:l,sliceSize:p,outerSize:u,dimSize:i,outputShape:a}}function vue(r){try{return r.map(e=>zf(e))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function wue(r){return r.map(e=>hc(e))}var gn={};Ge(gn,{nonMaxSuppressionV3Impl:()=>RT,nonMaxSuppressionV4Impl:()=>LT,nonMaxSuppressionV5Impl:()=>$T,whereImpl:()=>NT});z().prototype.abs=function(){return this.throwIfDisposed(),Ht(this)};z().prototype.acos=function(){return this.throwIfDisposed(),Yh(this)};z().prototype.acosh=function(){return this.throwIfDisposed(),Zh(this)};z().prototype.add=function(r){return this.throwIfDisposed(),ne(this,r)};z().prototype.all=function(r,e){return this.throwIfDisposed(),kc(this,r,e)};z().prototype.any=function(r,e){return this.throwIfDisposed(),Qu(this,r,e)};z().prototype.argMax=function(r){return this.throwIfDisposed(),ep(this,r)};z().prototype.argMin=function(r){return this.throwIfDisposed(),Jh(this,r)};z().prototype.asScalar=function(){return this.throwIfDisposed(),R(this.size===1,()=>"The array must have only 1 element."),K(this,[])};z().prototype.asType=function(r){return this.throwIfDisposed(),ue(this,r)};z().prototype.as1D=function(){return this.throwIfDisposed(),K(this,[this.size])};z().prototype.as2D=function(r,e){return this.throwIfDisposed(),K(this,[r,e])};z().prototype.as3D=function(r,e,t){return this.throwIfDisposed(),K(this,[r,e,t])};z().prototype.as4D=function(r,e,t,n){return this.throwIfDisposed(),K(this,[r,e,t,n])};z().prototype.as5D=function(r,e,t,n,o){return this.throwIfDisposed(),K(this,[r,e,t,n,o])};z().prototype.asin=function(){return this.throwIfDisposed(),Qh(this)};z().prototype.asinh=function(){return this.throwIfDisposed(),eg(this)};z().prototype.atan=function(){return this.throwIfDisposed(),tg(this)};z().prototype.atan2=function(r){return this.throwIfDisposed(),rg(this,r)};z().prototype.atanh=function(){return this.throwIfDisposed(),ng(this)};z().prototype.avgPool=function(r,e,t,n){return this.throwIfDisposed(),Kl(this,r,e,t,n)};z().prototype.batchToSpaceND=function(r,e){return this.throwIfDisposed(),Vl(this,r,e)};z().prototype.batchNorm=function(r,e,t,n,o){return this.throwIfDisposed(),fs(this,r,e,t,n,o)};z().prototype.broadcastTo=function(r){return this.throwIfDisposed(),Ul(this,r)};z().prototype.cast=function(r){return this.throwIfDisposed(),ue(this,r)};z().prototype.ceil=function(){return this.throwIfDisposed(),ag(this)};z().prototype.clipByValue=function(r,e){return this.throwIfDisposed(),Gr(this,r,e)};z().prototype.concat=function(r,e){return this.throwIfDisposed(),r instanceof rt&&(r=[r]),mt([this,...r],e)};z().prototype.conv1d=function(r,e,t,n,o,s){return this.throwIfDisposed(),wc(this,r,e,t,n,o,s)};z().prototype.conv2dTranspose=function(r,e,t,n,o){return this.throwIfDisposed(),_c(this,r,e,t,n,o)};z().prototype.conv2d=function(r,e,t,n,o,s){return this.throwIfDisposed(),zn(this,r,e,t,n,o,s)};z().prototype.cos=function(){return this.throwIfDisposed(),jl(this)};z().prototype.cosh=function(){return this.throwIfDisposed(),Cc(this)};z().prototype.cumsum=function(r,e,t){return this.throwIfDisposed(),Sc(this,r,e,t)};z().prototype.depthToSpace=function(r,e){return this.throwIfDisposed(),lg(this,r,e)};z().prototype.depthwiseConv2d=function(r,e,t,n,o,s){return this.throwIfDisposed(),Ra(this,r,e,t,n,o,s)};z().prototype.dilation2d=function(r,e,t,n,o){return this.throwIfDisposed(),ug(this,r,e,t,n,o)};z().prototype.divNoNan=function(r){return this.throwIfDisposed(),pg(this,r)};z().prototype.div=function(r){return this.throwIfDisposed(),he(this,r)};z().prototype.dot=function(r){return this.throwIfDisposed(),QC(this,r)};z().prototype.elu=function(){return this.throwIfDisposed(),La(this)};z().prototype.equal=function(r){return this.throwIfDisposed(),Io(this,r)};z().prototype.erf=function(){return this.throwIfDisposed(),cg(this)};z().prototype.exp=function(){return this.throwIfDisposed(),Fr(this)};z().prototype.expandDims=function(r){return this.throwIfDisposed(),Wr(this,r)};z().prototype.expm1=function(){return this.throwIfDisposed(),mg(this)};z().prototype.fft=function(){return this.throwIfDisposed(),np(this)};z().prototype.flatten=function(){return this.throwIfDisposed(),K(this,[this.size])};z().prototype.floor=function(){return this.throwIfDisposed(),Pa(this)};z().prototype.floorDiv=function(r){return this.throwIfDisposed(),Tc(this,r)};z().prototype.gather=function(r,e){return this.throwIfDisposed(),Ba(this,r,e)};z().prototype.greaterEqual=function(r){return this.throwIfDisposed(),io(this,r)};z().prototype.greater=function(r){return this.throwIfDisposed(),yr(this,r)};z().prototype.ifft=function(){return this.throwIfDisposed(),eu(this)};z().prototype.irfft=function(){return this.throwIfDisposed(),Qf(this)};z().prototype.isFinite=function(){return this.throwIfDisposed(),tS(this)};z().prototype.isInf=function(){return this.throwIfDisposed(),rS(this)};z().prototype.isNaN=function(){return this.throwIfDisposed(),fg(this)};z().prototype.leakyRelu=function(r){return this.throwIfDisposed(),Hl(this,r)};z().prototype.lessEqual=function(r){return this.throwIfDisposed(),lo(this,r)};z().prototype.less=function(r){return this.throwIfDisposed(),Ac(this,r)};z().prototype.localResponseNormalization=function(r,e,t,n){return this.throwIfDisposed(),dg(this,r,e,t,n)};z().prototype.logSigmoid=function(){return this.throwIfDisposed(),oS(this)};z().prototype.logSoftmax=function(r){return this.throwIfDisposed(),Ec(this,r)};z().prototype.logSumExp=function(r,e){return this.throwIfDisposed(),gg(this,r,e)};z().prototype.log=function(){return this.throwIfDisposed(),Kr(this)};z().prototype.log1p=function(){return this.throwIfDisposed(),Dc(this)};z().prototype.logicalAnd=function(r){return this.throwIfDisposed(),Xr(this,r)};z().prototype.logicalNot=function(){return this.throwIfDisposed(),ql(this)};z().prototype.logicalOr=function(r){return this.throwIfDisposed(),Mc(this,r)};z().prototype.logicalXor=function(r){return this.throwIfDisposed(),lS(this,r)};z().prototype.matMul=function(r,e,t){return this.throwIfDisposed(),tt(this,r,e,t)};z().prototype.maxPool=function(r,e,t,n){return this.throwIfDisposed(),Xl(this,r,e,t,n)};z().prototype.max=function(r,e){return this.throwIfDisposed(),nn(this,r,e)};z().prototype.maximum=function(r){return this.throwIfDisposed(),Wn(this,r)};z().prototype.mean=function(r,e){return this.throwIfDisposed(),Ft(this,r,e)};z().prototype.min=function(r,e){return this.throwIfDisposed(),tp(this,r,e)};z().prototype.minimum=function(r){return this.throwIfDisposed(),Oa(this,r)};z().prototype.mirrorPad=function(r,e){return this.throwIfDisposed(),yg(this,r,e)};z().prototype.mod=function(r){return this.throwIfDisposed(),xg(this,r)};z().prototype.mul=function(r){return this.throwIfDisposed(),G(this,r)};z().prototype.neg=function(){return this.throwIfDisposed(),st(this)};z().prototype.norm=function(r,e,t){return this.throwIfDisposed(),td(this,r,e,t)};z().prototype.notEqual=function(r){return this.throwIfDisposed(),gs(this,r)};z().prototype.oneHot=function(r,e=1,t=0){return this.throwIfDisposed(),Ea(this,r,e,t)};z().prototype.onesLike=function(){return this.throwIfDisposed(),Br(this)};z().prototype.pad=function(r,e){return this.throwIfDisposed(),kn(this,r,e)};z().prototype.pool=function(r,e,t,n,o){return this.throwIfDisposed(),cS(this,r,e,t,n,o)};z().prototype.pow=function(r){return this.throwIfDisposed(),In(this,r)};z().prototype.prelu=function(r){return this.throwIfDisposed(),Zl(this,r)};z().prototype.prod=function(r,e){return this.throwIfDisposed(),Fc(this,r,e)};z().prototype.reciprocal=function(){return this.throwIfDisposed(),Tg(this)};z().prototype.relu=function(){return this.throwIfDisposed(),hn(this)};z().prototype.relu6=function(){return this.throwIfDisposed(),Rc(this)};z().prototype.reshapeAs=function(r){return this.throwIfDisposed(),K(this,r.shape)};z().prototype.reshape=function(r){return this.throwIfDisposed(),K(this,r)};z().prototype.resizeBilinear=function(r,e,t){return this.throwIfDisposed(),PT(this,r,e,t)};z().prototype.resizeNearestNeighbor=function(r,e,t){return this.throwIfDisposed(),BT(this,r,e,t)};z().prototype.reverse=function(r){return this.throwIfDisposed(),wr(this,r)};z().prototype.rfft=function(){return this.throwIfDisposed(),op(this)};z().prototype.round=function(){return this.throwIfDisposed(),Lc(this)};z().prototype.rsqrt=function(){return this.throwIfDisposed(),$c(this)};z().prototype.selu=function(){return this.throwIfDisposed(),Pc(this)};z().prototype.separableConv2d=function(r,e,t,n,o,s){return this.throwIfDisposed(),kg(this,r,e,t,n,o,s)};z().prototype.sigmoid=function(){return this.throwIfDisposed(),dn(this)};z().prototype.sign=function(){return this.throwIfDisposed(),Ig(this)};z().prototype.sin=function(){return this.throwIfDisposed(),Bc(this)};z().prototype.sinh=function(){return this.throwIfDisposed(),Oc(this)};z().prototype.slice=function(r,e){return this.throwIfDisposed(),Ke(this,r,e)};z().prototype.softmax=function(r){return this.throwIfDisposed(),Ql(this,r)};z().prototype.softplus=function(){return this.throwIfDisposed(),ds(this)};z().prototype.spaceToBatchND=function(r,e){return this.throwIfDisposed(),Yl(this,r,e)};z().prototype.split=function(r,e){return this.throwIfDisposed(),Rr(this,r,e)};z().prototype.sqrt=function(){return this.throwIfDisposed(),Lt(this)};z().prototype.square=function(){return this.throwIfDisposed(),je(this)};z().prototype.squaredDifference=function(r){return this.throwIfDisposed(),zc(this,r)};z().prototype.squeeze=function(r){return this.throwIfDisposed(),Xo(this,r)};z().prototype.stack=function(r,e){this.throwIfDisposed();let t=r instanceof rt?[this,r]:[this,...r];return xr(t,e)};z().prototype.step=function(r){return this.throwIfDisposed(),Ga(this,r)};z().prototype.stridedSlice=function(r,e,t,n,o,s,i,a){return this.throwIfDisposed(),_g(this,r,e,t,n,o,s,i,a)};z().prototype.sub=function(r){return this.throwIfDisposed(),ge(this,r)};z().prototype.sum=function(r,e){return this.throwIfDisposed(),Te(this,r,e)};z().prototype.tan=function(){return this.throwIfDisposed(),Cg(this)};z().prototype.tanh=function(){return this.throwIfDisposed(),Fa(this)};z().prototype.tile=function(r){return this.throwIfDisposed(),qo(this,r)};z().prototype.toBool=function(){return this.throwIfDisposed(),ue(this,"bool")};z().prototype.toFloat=function(){return this.throwIfDisposed(),ue(this,"float32")};z().prototype.toInt=function(){return this.throwIfDisposed(),ue(this,"int32")};z().prototype.topk=function(r,e){return this.throwIfDisposed(),Sg(this,r,e)};z().prototype.transpose=function(r){return this.throwIfDisposed(),nt(this,r)};z().prototype.unique=function(r){return this.throwIfDisposed(),ed(this,r)};z().prototype.unsortedSegmentSum=function(r,e){return this.throwIfDisposed(),Ng(this,r,e)};z().prototype.unstack=function(r){return this.throwIfDisposed(),Vr(this,r)};z().prototype.where=function(r,e){return this.throwIfDisposed(),Wt(r,this,e)};z().prototype.zerosLike=function(){return this.throwIfDisposed(),Me(this)};var GT={kernelName:Gs,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>G(r,Ga(ue(t,"float32"),-1))}}};var iB={kernelName:ol,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let n=je(ue(t,"float32")),o=Lt(ge(be(1),n));return st(he(r,o))}}}};var lB={kernelName:sl,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let n=Lt(ge(je(ue(t,"float32")),1));return he(r,n)}}}};var uB={kernelName:so,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,n]=e,o=qe(t.shape,n.shape);return{a:()=>{let a=r,l=Gt(t.shape,o);return l.length>0&&(a=Te(a,l)),K(a,t.shape)},b:()=>{let a=r,l=Gt(n.shape,o);return l.length>0&&(a=Te(a,l)),K(a,n.shape)}}}};var pB={kernelName:Ws,saveAllInputs:!0,gradFunc:(r,e)=>{let t={};return e.forEach((n,o)=>{t[o]=()=>r.clone()}),t}};var cB={kernelName:Ks,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>Me(t)}}};var mB={kernelName:Ru,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>Me(t)}}};var fB={kernelName:ll,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>he(r,Lt(ge(be(1),je(ue(t,"float32")))))}}};var dB={kernelName:ul,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let n=Lt(ne(be(1),je(ue(t,"float32"))));return he(r,n)}}}};var hB={kernelName:ml,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,n]=e,o=qe(t.shape,n.shape);return{a:()=>{let a=ne(je(t),je(n)),l=G(r,he(n,a)),u=Gt(t.shape,o);return u.length>0&&(l=Te(l,u)),K(l,t.shape)},b:()=>{let a=ne(je(t),je(n)),l=st(G(r,he(t,a))),u=Gt(n.shape,o);return u.length>0&&(l=Te(l,u)),K(l,n.shape)}}}};var gB={kernelName:pl,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>he(r,ne(je(ue(t,"float32")),1))}}};var bB={kernelName:cl,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>he(r,ge(be(1),je(ue(t,"float32"))))}}};function _ue(r,e,t,n,o,s){let i=v(r,"dy","avgPool3dGrad"),a=v(e,"input","avgPool3dGrad"),l=i,u=a,p=!1;a.rank===4&&(p=!0,l=K(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),u=K(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),R(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),R(u.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`),s!=null&&R(xt(o),()=>`Error in avgPool3dGrad: pad must be an integer when using, dimRoundingMode ${s} but got pad ${o}.`);let c={dy:l,input:u},m={filterSize:t,strides:n,pad:o,dimRoundingMode:s},f=M.runKernel(af,c,m);return p?K(f,[f.shape[1],f.shape[2],f.shape[3],f.shape[4]]):f}var yB=A({avgPool3dGrad_:_ue});var xB={kernelName:Lu,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[n]=e,{filterSize:o,strides:s,pad:i,dimRoundingMode:a}=t;return{x:()=>yB(r,n,o,s,i,a)}}};function Cue(r,e,t,n,o){let s=v(r,"dy","avgPoolGrad"),i=v(e,"input","avgPoolGrad");R(i.rank===s.rank,()=>`Rank of input (${i.rank}) does not match rank of dy (${s.rank})`);let a=i,l=s,u=!1;i.rank===3&&(u=!0,a=K(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=K(s,[1,s.shape[0],s.shape[1],s.shape[2]])),R(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),R(a.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${a.rank}.`);let p={dy:l,input:a},c={filterSize:t,strides:n,pad:o},m=M.runKernel(sf,p,c);return u?K(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var TB=A({avgPoolGrad_:Cue});var kB={kernelName:Vs,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[n]=e,{filterSize:o,strides:s,pad:i}=t;return{x:()=>TB(r,n,o,s,i)}}};var IB={kernelName:Us,inputsToSave:["a","b"],gradFunc:(r,e,t)=>{let[n,o]=e,{transposeA:s,transposeB:i}=t;return!s&&!i?{a:()=>tt(r,o,!1,!0),b:()=>tt(n,r,!0,!1)}:!s&&i?{a:()=>tt(r,o,!1,!1),b:()=>tt(r,n,!0,!1)}:s&&!i?{a:()=>tt(o,r,!1,!0),b:()=>tt(n,r,!1,!1)}:{a:()=>tt(o,r,!0,!0),b:()=>tt(r,n,!0,!0)}}};var vB={kernelName:$u,gradFunc:(r,e,t)=>{let{blockShape:n,crops:o}=t;return{x:()=>Yl(r,n,o)}}};var wB={kernelName:p$,gradFunc:(r,e,t)=>{let n=t,o=n.inputShape,s=n.shape,i=Array.from(s);for(let l=o.length-1;l>=0;l--)if(o[l]===s[l])i[l]=1;else if(o[l]!==1)throw new Error(`broadcastTo(): [${o}] cannot be broadcast to [${s}].`);let a=[];for(let l=0;l<i.length;l++)i[l]>1&&a.push(l);return{x:()=>Te(r,a,!0)}}};var _B={kernelName:Do,gradFunc:r=>({x:()=>r.clone()})};var CB={kernelName:Eo,gradFunc:r=>({x:()=>Me(r)})};var SB={kernelName:us,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[n]=e,{clipValueMin:o,clipValueMax:s}=t;return{x:()=>Wt(Xr(io(n,o),lo(n,s)),r,Me(r))}}};var NB={kernelName:Pu,inputsToSave:["x"],gradFunc:GT.gradFunc};var AB={kernelName:pi,saveAllInputs:!0,gradFunc:(r,e,t)=>{let n=e.map(l=>l.shape),{axis:o}=t,s=Pr(o,e[0].shape)[0],i=n.map(l=>l[s]);return Rr(r,i,s).map(l=>()=>l)}};var DB={kernelName:js,inputsToSave:["x","filter"],gradFunc:(r,e,t)=>{let[n,o]=e,{dilations:s,strides:i,pad:a,dataFormat:l}=t;return R(Ho(s),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`),{x:()=>qf(n.shape,r,o,i,a,l),filter:()=>rd(n,r,o.shape,i,a,l)}}};var EB={kernelName:Hs,inputsToSave:["dy","filter"],gradFunc:(r,e,t)=>{let[n,o]=e,{strides:s,pad:i,dataFormat:a,dimRoundingMode:l}=t;return{dy:()=>zn(r,o,s,i,a,1,l),filter:()=>rd(r,n,o.shape,s,i,a,l)}}};function Sue(r,e,t,n,o){let s=r;r.rank===4&&(s=K(r,[1,r.shape[0],r.shape[1],r.shape[2],r.shape[3]]));let i=e;i.rank===4&&(i=K(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]])),R(s.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${s.shape}.`),R(i.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`),R(t.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${t}.`),R(s.shape[4]===t[3],()=>`Error in conv3dDerFilter: depth of input ${s.shape[4]}) must match input depth in filter (${t[3]}.`),R(i.shape[4]===t[4],()=>`Error in conv3dDerFilter: depth of dy (${i.shape[4]}) must match output depth for filter (${t[4]}).`);let a={x:s,dy:i},l={strides:n,pad:o,filterShape:t};return M.runKernel(pf,a,l)}var MB=A({conv3DBackpropFilter_:Sue});var FB={kernelName:Bu,inputsToSave:["x","filter"],gradFunc:(r,e,t)=>{let{dilations:n,strides:o,pad:s}=t;R(Ho(n),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${n}'`);let[i,a]=e;return{x:()=>vT(i.shape,r,a,o,s),filter:()=>MB(i,r,a.shape,o,s)}}};var RB={kernelName:qs,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>G(st(Bc(ue(t,"float32"))),r)}}};var LB={kernelName:fl,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>G(Oc(ue(t,"float32")),r)}}};var $B={kernelName:Xs,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[n]=e,{axis:o,exclusive:s,reverse:i}=t;return{x:()=>{let a=iS([o],n.rank),l=Sc(r,o,s,!i);return a!=null&&(l=nt(l,a)),l}}}};var PB={kernelName:Ys,inputsToSave:["x","filter"],gradFunc:(r,e,t)=>{let{dilations:n,strides:o,pad:s,dimRoundingMode:i}=t,a=n==null?[1,1]:n;R(Ho(a),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);let[l,u]=e;return R(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),R(u.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${u.rank}.`),R(l.shape[3]===u.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`),R(rn(o,a),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${a}'.`),i!=null&&R(xt(s),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`),{x:()=>FT(l.shape,r,u,o,s,n,i),filter:()=>MT(l,r,u.shape,o,s,n,i)}}};var BB={kernelName:Ou,inputsToSave:["x","filter"],gradFunc:(r,e,t)=>{let[n,o]=e,s={x:n,filter:o,dy:r},i={x:n,filter:o,dy:r};return{x:()=>M.runKernel(Oh,s,t),filter:()=>M.runKernel(zh,i,t)}}};var OB={kernelName:gl,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e,n={dy:r,y:t};return{x:()=>M.runKernel(bf,n)}}};var zB={kernelName:bl,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e,n=G(Fr(st(je(t))),2/Math.sqrt(Math.PI));return{x:()=>G(r,n)}}};var GB={kernelName:Mo,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e;return{x:()=>G(r,t)}}};var WB={kernelName:ci,inputsToSave:["input"],gradFunc:(r,e)=>{let[t]=e;return{input:()=>K(r,t.shape)}}};var KB={kernelName:Qs,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>G(r,Fr(t))}}};var VB={kernelName:Fo,gradFunc:r=>({x:()=>Me(r)})};var UB={kernelName:ea,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,n]=e,o=qe(t.shape,n.shape);return{a:()=>{let a=he(r,ue(n,"float32")),l=Gt(t.shape,o);return l.length>0?K(Te(a,l),t.shape):a},b:()=>{let a=G(r,ue(t,"float32")),l=Gt(n.shape,o);l.length>0&&(a=K(Te(a,l),n.shape));let u=je(n);return st(he(a,ue(u,"float32")))}}}};var jB={kernelName:ta,inputsToSave:["x","mean","variance","scale"],gradFunc:(r,e,t)=>{let{varianceEpsilon:n}=t,[o,s,i,a]=e,l=a==null?be(1):a,u=Gt(s.shape,o.shape),p=[];if(s.rank===1){for(let k=0;k<o.shape.length-1;++k)p.push(o.shape[k]);p.push(1)}let c=ge(o,s),m=G(r,l),f=$c(ne(i,be(n))),d=G(G(G(f,f),f),be(-.5));return{x:()=>s.rank===1?K(G(G(r,qo(K(f,[1,1,1,s.shape[0]]),p)),l),o.shape):K(G(G(r,f),l),o.shape),mean:()=>{let k=G(G(f,be(-1)),m);return s.rank===1&&(k=Te(k,u)),K(k,s.shape)},variance:()=>{let k=G(G(d,c),m);return s.rank===1&&(k=Te(k,u)),K(k,s.shape)},scale:()=>{let k=G(c,f),I=G(r,k);return s.rank===1&&(I=Te(I,u)),K(I,s.shape)},offset:()=>{let k=r;return s.rank===1&&(k=Te(k,u)),K(k,s.shape)}}}};var HB={kernelName:mi,inputsToSave:["x","indices"],gradFunc:(r,e,t)=>{let[n,o]=e,{axis:s}=t,i=Pr(s,n.shape)[0];return{x:()=>{let l=n.shape,u=o.size,p=l.slice(0,i),c=p.length,m=l.slice(s,l.length).slice(1),f=m.length,d=qB(0,c),h=qB(c+1,c+1+f),g=XB([p,[u],m]),b=K(r,g),y=K(o,[u]),T=XB([[c],d,h]),k=nt(b,T),I=Ng(k,y,n.shape[i]),S=hg(T);return I=nt(I,S),I},indices:()=>o}}};function qB(r,e){let t=[];for(let n=r;n<e;++n)t.push(n);return t}function XB(r){let e=[];for(let t=0;t<r.length;++t)for(let n=0;n<r[t].length;++n)e.push(r[t][n]);return e}var YB={kernelName:Ro,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,n]=e;return{a:()=>Me(t),b:()=>Me(n)}}};var ZB={kernelName:Lo,gradFunc:r=>({x:()=>ue(r,"float32")})};var JB={kernelName:Tl,gradFunc:r=>({x:()=>Me(r)})};var QB={kernelName:kl,gradFunc:r=>({x:()=>Me(r)})};var eO={kernelName:Il,gradFunc:r=>({x:()=>Me(r)})};var tO={kernelName:na,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[n]=e,{alpha:o}=t,s=yr(n,0);return{x:()=>Wt(s,r,G(r,o))}}};var rO={kernelName:vl,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>he(r,ne(t,1))}}};var nO={kernelName:$o,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>he(r,ue(t,"float32"))}}};var oO={kernelName:c$,inputsToSave:[],outputsToSave:[!0],gradFunc:(r,e,t)=>{let[n]=e,{axis:o}=t;return{logits:()=>{let s=!0,i=Fr(n);return ge(r,G(Te(r,o,s),i))}}}};function Nue(r,e,t,n=5,o=1,s=1,i=.5){let a={x:r,y:e,dy:t},l={depthRadius:n,bias:o,alpha:s,beta:i};return M.runKernel(If,a,l)}var sO=A({localResponseNormalizationBackprop_:Nue});var aO={kernelName:Gu,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let[n,o]=e,{depthRadius:s,bias:i,alpha:a,beta:l}=t;return{x:()=>sO(n,o,r,s,i,a,l)}}};function WT(r,e,t,n){return e.rank<t.rank&&(e=K(e,hs(e.shape,n))),r.rank<t.rank&&(r=K(r,hs(r.shape,n))),{x:()=>G(r,ue(Io(t,e),r.dtype))}}var vS={kernelName:aa,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let n=t,{reductionIndices:o}=n,s=e[0],i=e[1],a=Pr(o,s.shape),l=WT(r,i,s,a);return{x:()=>l.x()}}};var iO={kernelName:Po,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,n]=e;return{a:()=>G(r,ue(io(t,n),"float32")),b:()=>G(r,ue(Ac(t,n),"float32"))}}};function Aue(r,e,t,n,o,s,i){let a=v(r,"dy","maxPool3dGrad"),l=v(e,"input","maxPool3dGrad"),u=v(t,"output","maxPool3dGrad"),p=a,c=l,m=u,f=!1;l.rank===4&&(f=!0,p=K(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]]),c=K(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),m=K(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]])),R(p.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${p.rank}.`),R(c.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${c.rank}.`),R(m.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${m.rank}.`),i!=null&&R(xt(s),()=>`Error in maxPool3dGrad: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);let d={dy:p,input:c,output:m},h={filterSize:n,strides:o,pad:s,dimRoundingMode:i},g=M.runKernel(wf,d,h);return f?K(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var lO=A({maxPool3dGrad_:Aue});var uO={kernelName:Wu,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let[n,o]=e,{filterSize:s,strides:i,pad:a,dimRoundingMode:l}=t;return{x:()=>lO(r,n,o,s,i,a,l)}}};function Due(r,e,t,n,o,s,i){let a=v(r,"dy","maxPoolGrad"),l=v(e,"input","maxPoolGrad"),u=v(t,"output","maxPoolGrad");R(l.rank===a.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${a.rank})`),R(a.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${a.rank}.`),R(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),i!=null&&R(xt(s),()=>`Error in maxPoolGrad: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);let p={dy:a,input:l,output:u},c={filterSize:n,strides:o,pad:s,dimRoundingMode:i};return M.runKernel(vf,p,c)}var pO=A({maxPoolGrad_:Due});var cO={kernelName:ia,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let[n,o]=e,{filterSize:s,strides:i,pad:a}=t;return{x:()=>pO(r,n,o,s,i,a)}}};var mO={kernelName:la,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[n]=e,{axis:o}=t,s=Pr(o,n.shape),a=aS(n.shape,s)[1],l=Nt(a);return{x:()=>{let p=n.shape.slice();s.forEach(f=>{p[f]=1});let c=K(r,p);return he(G(c,on(n.shape,"float32")),l)}}}};var fO={kernelName:ua,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let n=t,{axis:o}=n,[s,i]=e,a=Pr(o,s.shape),l=WT(r,i,s,a);return{x:()=>l.x()}}};var dO={kernelName:Bo,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,n]=e;return{a:()=>G(r,ue(lo(t,n),"float32")),b:()=>G(r,ue(yr(t,n),"float32"))}}};var hO={kernelName:pa,inputsToSave:["x"],gradFunc:(r,e,t)=>{let n=e[0],{paddings:o}=t,s=o.map(i=>i[0]);return{x:()=>Ke(r,s,n.shape)}}};var gO={kernelName:_l,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,n]=e,o=qe(t.shape,n.shape);return{a:()=>{let a=Gt(t.shape,o);return a.length>0?K(Te(r,a),t.shape):r},b:()=>{let a=G(r,st(Pa(he(t,n)))),l=Gt(n.shape,o);return l.length>0?K(Te(a,l),n.shape):a}}}};var bO={kernelName:Oo,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,n]=e,o=qe(t.shape,n.shape);return{a:()=>{let a=G(r,ue(n,"float32")),l=Gt(t.shape,o);return l.length>0?K(Te(a,l),t.shape):a},b:()=>{let a=G(r,ue(t,"float32")),l=Gt(n.shape,o);return l.length>0?K(Te(a,l),n.shape):a}}}};var yO={kernelName:ca,gradFunc:r=>({x:()=>st(r)})};var xO={kernelName:fa,inputsToSave:["indices"],gradFunc:(r,e)=>{let t=e[0];return{indices:()=>Rt(t.shape,"float32")}}};var TO={kernelName:fi,gradFunc:r=>({x:()=>Me(r)})};var kO={kernelName:di,saveAllInputs:!0,gradFunc:(r,e,t)=>{let{axis:n}=t;return Vr(r,n).map(s=>()=>s)}};var wS={kernelName:da,inputsToSave:["x"],gradFunc:(r,e,t)=>{let n=e[0],{paddings:o}=t,s=o.map(i=>i[0]);return{x:()=>Ke(r,s,n.shape)}}};var IO={kernelName:ha,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(r,e)=>{let[t,n,o]=e,s=t,i=n,a=qe(s.shape,i.shape);return{a:()=>{let p=ue(i,"float32"),c=G(r,G(p,In(s,ge(p,be(1))))),m=Gt(s.shape,a);return m.length>0&&(c=Te(c,m)),K(c,s.shape)},b:()=>{let p=yr(s,0),c=Wt(p,Kr(s),Me(s)),m=G(r,G(o,c)),f=Gt(i.shape,a);return f.length>0&&(m=Te(m,f)),K(m,i.shape)}}}};var vO={kernelName:ga,inputsToSave:["x","alpha"],gradFunc:(r,e)=>{let[t,n]=e,o=yr(t,0);return{x:()=>Wt(o,r,G(r,n)),alpha:()=>{let s=Wt(o,Me(r),G(r,t)),i=Gt(n.shape,r.shape);return i.length>0&&(s=Te(s,i)),K(s,n.shape)}}}};var wO={kernelName:Zs,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,n]=e,o=qe(t.shape,n.shape);return{a:()=>{let a=he(r,ue(n,"float32")),l=Gt(t.shape,o);return l.length>0?K(Te(a,l),t.shape):a},b:()=>{let a=G(r,ue(t,"float32")),l=Gt(n.shape,o);l.length>0&&(a=K(Te(a,l),n.shape));let u=je(n);return st(he(a,ue(u,"float32")))}}}};var _O={kernelName:Al,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>he(r,st(je(t)))}}};var CO={kernelName:xa,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e,n=G(lo(t,6),Ga(t));return{x:()=>G(r,ue(n,"float32"))}}};var SO={kernelName:ba,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>G(r,ue(Ga(t),"float32"))}}};var NO={kernelName:gi,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>K(r,t.shape)}}};var AO={kernelName:ya,inputsToSave:["images"],gradFunc:(r,e,t)=>{let[n]=e,o={dy:r,images:n};return{images:()=>M.runKernel(Nf,o,t)}}};var DO={kernelName:Vu,inputsToSave:["images"],gradFunc:(r,e,t)=>{let[n]=e,o={dy:r,images:n};return{images:()=>M.runKernel(Sf,o,t)}}};var EO={kernelName:Ta,gradFunc:(r,e,t)=>{let{dims:n}=t,o=Pr(n,r.shape);return{x:()=>wr(r,o)}}};var MO={kernelName:ka,gradFunc:r=>({x:()=>Me(r)})};var FO={kernelName:zo,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>st(he(r,G(In(t,1.5),2)))}}};var RO={kernelName:bi,inputsToSave:["condition"],gradFunc:(r,e)=>{let[t]=e;return{condition:()=>ue(Me(t),"float32"),t:()=>G(r,ue(t,r.dtype)),e:()=>G(r,ue(ql(t),r.dtype))}}};var LO={kernelName:El,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let n=yr(t,be(0)),o=be(xS),s=be(TS),i=G(r,s),a=G(G(r,o),Fr(ue(t,"float32")));return Wt(n,i,a)}}}};var $O={kernelName:wa,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e;return{x:()=>G(r,G(t,ge(be(1),t)))}}};var PO={kernelName:Fl,gradFunc:r=>({x:()=>Me(r)})};var BO={kernelName:va,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>G(jl(ue(t,"float32")),r)}}};var OO={kernelName:Ml,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>G(Cc(ue(t,"float32")),r)}}};var zO={kernelName:Ia,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[n]=e,{begin:o,size:s}=t,i=n.shape,[a,l]=BC(n,o,s),u=[];for(let p=0;p<r.rank;p++)u.push([a[p],i[p]-a[p]-l[p]]);return{x:()=>kn(r,u)}}};var GO={kernelName:Sa,outputsToSave:[!0],gradFunc:(r,e,t)=>{let[n]=e,{dim:o}=t,s=!0,i=G(r,n);return{logits:()=>ge(i,G(Te(i,[o],s),n))}}};var WO={kernelName:Rl,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>G(r,dn(t))}}};var _S={kernelName:Uu,gradFunc:(r,e,t)=>{let{blockShape:n,paddings:o}=t;return{x:()=>Vl(r,n,o)}}};var CS={kernelName:yi,gradFunc:(r,e,t)=>{let{axis:n}=t;return{x:()=>mt(r,n)}}};var KO={kernelName:_a,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>he(r,G(Lt(ue(t,"float32")),2))}}};var VO={kernelName:ju,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>G(r,G(ue(t,"float32"),2))}}};var UO={kernelName:Go,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,n]=e,o=be(2);return{a:()=>G(r,G(o,ge(t,n))),b:()=>G(r,G(o,ge(n,t)))}}};var jO={kernelName:cs,gradFunc:r=>({x:()=>Me(r)})};var HO={kernelName:Wo,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,n]=e,o=qe(t.shape,n.shape);return{a:()=>{let a=r,l=Gt(t.shape,o);return l.length>0&&(a=Te(a,l)),K(a,t.shape)},b:()=>{let a=r,l=Gt(n.shape,o);return l.length>0&&(a=Te(a,l)),K(st(a),n.shape)}}}};var qO={kernelName:Ca,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[n]=e,o=n.shape.slice(),{axis:s}=t;Pr(s,n.shape).forEach(u=>{o[u]=1});let a=K(r,o),l=G(a,on(n.shape,"float32"));return{x:()=>l}}};var XO={kernelName:Na,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>he(r,je(jl(t)))}}};var YO={kernelName:Aa,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e;return{x:()=>G(ge(be(1),je(t)),r)}}};var ZO={kernelName:Ko,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[n]=e,{reps:o}=t;return{x:()=>{let i=Me(n);if(n.rank===1)for(let a=0;a<o[0];++a)i=ne(i,Ke(r,[a*n.shape[0]],[n.shape[0]]));else if(n.rank===2)for(let a=0;a<o[0];++a)for(let l=0;l<o[1];++l)i=ne(i,Ke(r,[a*n.shape[0],l*n.shape[1]],[n.shape[0],n.shape[1]]));else if(n.rank===3)for(let a=0;a<o[0];++a)for(let l=0;l<o[1];++l)for(let u=0;u<o[2];++u)i=ne(i,Ke(r,[a*n.shape[0],l*n.shape[1],u*n.shape[2]],[n.shape[0],n.shape[1],n.shape[2]]));else if(n.rank===4)for(let a=0;a<o[0];++a)for(let l=0;l<o[1];++l)for(let u=0;u<o[2];++u)for(let p=0;p<o[3];++p)i=ne(i,Ke(r,[a*n.shape[0],l*n.shape[1],u*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 i}}}};var JO={kernelName:ps,gradFunc:(r,e,t)=>{let n=t,{perm:o}=n,s=hg(o);return{x:()=>nt(r,s)}}};var QO={kernelName:xi,gradFunc:(r,e,t)=>{let n=t,{axis:o}=n;return{value:()=>xr(r,o)}}};var ez={kernelName:Hu,inputsToSave:["segmentIds"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>Eue(r,t)}}};function Eue(r,e){let t=Wn(e,Me(e)),n=Ba(r,t),o=io(e,be(0,"int32")),s=n.rank-o.rank;for(let a=0;a<s;++a)o=Wr(o,a+1);o=Xr(o,on(n.shape,"bool"));let i=Me(n);return Wt(o,n,i)}var tz={kernelName:Ti,gradFunc:r=>({x:()=>Me(r)})};var Mue=[GT,iB,lB,uB,pB,cB,mB,fB,dB,hB,gB,bB,xB,kB,IB,vB,wB,_B,CB,SB,NB,AB,EB,DB,FB,RB,LB,$B,PB,BB,wO,OB,zB,GB,WB,KB,UB,VB,jB,HB,YB,ZB,JB,QB,eO,tO,rO,nO,oO,aO,vS,vS,iO,uO,cO,mO,fO,dO,hO,gO,bO,yO,xO,TO,kO,wS,wS,IO,vO,_O,CO,SO,NO,AO,DO,EO,MO,FO,RO,LO,$O,PO,BO,OO,zO,GO,WO,_S,_S,CS,CS,KO,UO,VO,jO,HO,qO,XO,YO,ZO,JO,QO,ez,tz];for(let r of Mue)m$(r);var iz={};Ge(iz,{maxNorm:()=>Rue,minMaxNorm:()=>Pue,nonNeg:()=>$ue,unitNorm:()=>Lue});var SS;function Lr(){return SS==null&&(SS=xP().epsilon()),SS}function Kn(){return"channelsLast"}var vo=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,vo.prototype)}},_n=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,_n.prototype)}},U=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,U.prototype)}},Le=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Le.prototype)}},Eg=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Eg.prototype)}};function xs(r,e){if(Array.isArray(r)){let t=[];for(let n=0;n<e;n++)t=t.concat(r);return t}else{let t=new Array(e);return t.fill(r),t}}function Yo(r,e){if(!r)throw new Eg(e)}function NS(r,e){let t=0;for(let n of r)n===e&&t++;return t}function Yr(r){return r.length===1?r[0]:r}function $t(r){return Array.isArray(r)?r:[r]}function Ts(r){let t=r.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return t[0]!=="_"?t:"private"+t}function nu(r){return r.length<=1||r.indexOf("_")===-1?r:r.replace(/[_]+(\w|$)/g,(e,t)=>t.toUpperCase())}var ks={};function nd(r){if(r==null)return null;let e={};return e.className=r.getClassName(),e.config=r.getConfig(),e}function AS(r){if(!(r==null||typeof r!="object"))if(Array.isArray(r))r.forEach(e=>AS(e));else{let e=Object.keys(r);for(let t of e){let n=r[t];n!=null&&typeof n=="object"&&(!Array.isArray(n)&&n.type==="ndarray"&&typeof n.value=="number"?r[t]=n.value:AS(n))}}}function Ni(r,e={},t={},n="object",o=!1){if(typeof r=="string"){let s=r,i;if(s in t)i=t[s];else if(s in ks)i=ks[s];else if(i=e[s],i==null)throw new U(`Unknown ${n}: ${r}. 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 i}else{let s=r;if(s.className==null||s.config==null)throw new U(`${n}: Improper config format: ${JSON.stringify(s)}.
|
|
'className' and 'config' must set.`);let i=s.className,a,l;if(i in t?[a,l]=t[i]:i in ks?[a,l]=ks.className:i in e&&([a,l]=e[i]),a==null)throw new U(`Unknown ${n}: ${i}. 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){let u={};for(let f of Object.keys(ks))u[f]=ks[f];for(let f of Object.keys(t))u[f]=t[f];let p=s.config;p.customObjects=u;let c={...ks};for(let f of Object.keys(t))ks[f]=t[f];AS(s.config);let m=l(a,s.config,t,o);return ks={...c},m}else{let u={...ks};for(let c of Object.keys(t))ks[c]=t[c];let p=new a(s.config);return ks={...u},p}}}function Fue(r,e){return r<e?-1:r>e?1:0}function Mg(r,e){return-1*Fue(r,e)}function Is(r){if(r==null)return r;let e=[];for(let t of r)e.indexOf(t)===-1&&e.push(t);return e}function rz(r){if(r==null)throw new U(`Invalid value in obj: ${JSON.stringify(r)}`);for(let e in r)if(r.hasOwnProperty(e))return!1;return!0}function Ai(r,e,t){if(t!=null&&r.indexOf(t)<0)throw new U(`${t} is not a valid ${e}. Valid values are ${r} or null/undefined.`)}function KT(r,e,t=0,n=Infinity){return Yo(t>=0),Yo(n>=t),Array.isArray(r)&&r.length>=t&&r.length<=n&&r.every(o=>typeof o===e)}function kr(r,e){Array.isArray(r)?(x.assert(r.length>0,()=>`${e} is unexpectedly an empty array.`),r.forEach((t,n)=>kr(t,`element ${n+1} of ${e}`))):x.assert(Number.isInteger(r)&&r>0,()=>`Expected ${e} to be a positive integer, but got ${nz(r)}.`)}function nz(r){return r===null?"null":Array.isArray(r)?"["+r.map(e=>nz(e)).join(",")+"]":typeof r=="string"?`"${r}"`:`${r}`}function oz(r,e){let t=x.now(),n;return(...s)=>{let i=x.now();return i-t<e||(t=i,n=r(...s)),n}}function VT(r){return r==="relu"?"relu":r==="linear"?"linear":r==="elu"?"elu":null}function DS(r,e){return j(()=>Lt(Te(G(r,r),e,!0)))}var od=class extends oe.Serializable{getConfig(){return{}}},Fg=class extends od{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 j(()=>{let t=DS(e,this.axis),n=Gr(t,0,this.maxValue);return G(e,he(n,ne(Lr(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};Fg.className="MaxNorm";oe.registerClass(Fg);var Rg=class extends od{constructor(e){super();this.defaultAxis=0;this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return j(()=>he(e,ne(Lr(),DS(e,this.axis))))}getConfig(){return{axis:this.axis}}};Rg.className="UnitNorm";oe.registerClass(Rg);var Lg=class extends od{apply(e){return hn(e)}};Lg.className="NonNeg";oe.registerClass(Lg);var $g=class extends od{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 j(()=>{let t=DS(e,this.axis),n=ne(G(this.rate,Gr(t,this.minValue,this.maxValue)),G(1-this.rate,t));return G(e,he(n,ne(Lr(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};$g.className="MinMaxNorm";oe.registerClass($g);var sz={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function ar(r){return nd(r)}function az(r,e={}){return Ni(r,oe.SerializationMap.getMap().classNameMap,e,"constraint")}function ir(r){if(r==null)return null;if(typeof r=="string"){let t={className:r in sz?sz[r]:r,config:{}};return az(t)}else return r instanceof od?r:az(r)}function Rue(r){return new Fg(r)}function Lue(r){return new Rg(r)}function $ue(){return new Lg}function Pue(r){return new $g(r)}var Sz={};Ge(Sz,{constant:()=>Uue,glorotNormal:()=>Jue,glorotUniform:()=>Zue,heNormal:()=>Que,heUniform:()=>epe,identity:()=>Xue,leCunNormal:()=>tpe,leCunUniform:()=>rpe,ones:()=>Vue,orthogonal:()=>npe,randomNormal:()=>Hue,randomUniform:()=>jue,truncatedNormal:()=>que,varianceScaling:()=>Yue,zeros:()=>Kue});var lz=["channelsFirst","channelsLast"],uz=["nearest","bilinear"],pz=["valid","same","causal"],cz=["max","avg"],mz=["sum","mul","concat","ave"];var sd=new Map;function tr(r){Ai(lz,"DataFormat",r)}function fz(r){Ai(uz,"InterpolationFormat",r)}function Vn(r){Ai(pz,"PaddingMode",r)}function ES(r){Ai(cz,"PoolMode",r)}var Pg=[],dz="/";function Wa(r,e){Pg.push(r);try{let t=e();return Pg.pop(),t}catch(t){throw Pg.pop(),t}}function Bue(){return Pg.length===0?"":Pg.join(dz)+dz}function UT(r){if(!hz(r))throw new Error("Not a valid tensor name: '"+r+"'");return Bue()+r}function jT(r){if(!hz(r))throw new Error("Not a valid tensor name: '"+r+"'");sd.has(r)||sd.set(r,0);let e=sd.get(r);if(sd.set(r,sd.get(r)+1),e>0){let t=`${r}_${e}`;return sd.set(t,1),t}else return r}var Oue=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function hz(r){return!!r.match(Oue)}function gz(r){return r===parseInt(r.toString(),10)}function vs(r,e,t){e==null&&(e=0),t==null&&(t=r.length);let n=1;for(let o=e;o<t;++o)n*=r[o];return n}function Qc(r){if(r.length===0)return Number.NaN;let e=Number.POSITIVE_INFINITY;for(let t=0;t<r.length;t++){let n=r[t];n<e&&(e=n)}return e}function Ka(r){if(r.length===0)return Number.NaN;let e=Number.NEGATIVE_INFINITY;for(let t=0;t<r.length;t++){let n=r[t];n>e&&(e=n)}return e}function Cn(r,e){if(e<r)throw new U(`end (${e}) < begin (${r}) is forbidden.`);let t=[];for(let n=r;n<e;++n)t.push(n);return t}function ou(r,e){return r.asType(e)}function su(r,e=-1){let t=r.shape.slice();return e<0&&(e=t.length+e+1),t.splice(e,0,1),r.reshape(t)}function bz(r,e){return j(()=>{if(r.shape.length!==2)throw new U(`repeat() expects a rank-2 tensor, but received a rank-${r.shape.length} tensor.`);let t=su(r,1);return HT(t,[1,e,1])})}function yz(r){let e=[vs(r.shape)];return r.reshape(e)}function xz(r){if(r.rank<=1)throw new U(`batchFlatten requires a minimum rank of 2. Got rank: ${r.rank}.`);let e=[r.shape[0],vs(r.shape,1)];return r.reshape(e)}function au(r,e,t){return j(()=>{switch(r.rank){case 1:return vg(r,e,t);case 2:return ST(r,[e,0],[t,r.shape[1]]);case 3:return wg(r,[e,0,0],[t,r.shape[1],r.shape[2]]);case 4:return Jf(r,[e,0,0,0],[t,r.shape[1],r.shape[2],r.shape[3]]);case 5:return Ke(r,[e,0,0,0,0],[t,r.shape[1],r.shape[2],r.shape[3],r.shape[4]]);case 6:return Ke(r,[e,0,0,0,0,0],[t,r.shape[1],r.shape[2],r.shape[3],r.shape[4],r.shape[5]]);default:throw new U(`sliceAlongFirstAxis() received an unsupported tensor rank: ${r.rank}`)}})}function MS(r,e,t){return j(()=>{switch(r.rank){case 1:return vg(r,e,t);case 2:return ST(r,[0,e],[r.shape[0],t]);case 3:return wg(r,[0,0,e],[r.shape[0],r.shape[1],t]);case 4:return Jf(r,[0,0,0,e],[r.shape[0],r.shape[1],r.shape[2],t]);default:throw new U(`sliceAlongLastAxis() received an unsupported tensor rank: ${r.rank}`)}})}function Bg(r,e,t,n){return j(()=>{switch(r.rank){case 1:return vg(r,e,t);case 2:switch(n){case 1:return au(r,e,t);case 2:return MS(r,e,t);default:throw new U(`The axis is not within the rank of the tensor ${n}`)}case 3:switch(n){case 1:return au(r,e,t);case 2:return wg(r,[0,e,0],[r.shape[0],t,r.shape[2]]);case 3:return MS(r,e,t);default:throw new U(`The axis is not within the rank of the tensor ${n}`)}case 4:switch(n){case 1:return au(r,e,t);case 2:return Jf(r,[0,e,0,0],[r.shape[0],t,r.shape[2],r.shape[3]]);case 3:return Jf(r,[0,0,e,0],[r.shape[0],r.shape[1],t,r.shape[3]]);case 4:return MS(r,e,t);default:throw new U(`The axis is not within the rank of the tensor ${n}`)}default:throw new U(`sliceAlongLastAxis() received an unsupported tensor rank: ${r.rank}`)}})}function ad(r,e=-1){let t;return e<0&&(t=r[0].rank,t!==0?e=t:e=0),e===r[0].rank&&(e=-1),mt(r,e)}function FS(r,e){switch(r.rank){case 1:return HC([r,e]);case 2:return qC([r,e],0);case 3:return XC([r,e],0);case 4:return YC([r,e],0);default:throw new U(`concatAlongFirstAxis() received an unsupported tensor rank: ${r.rank}`)}}function HT(r,e){if(Array.isArray(e)||(e=[e]),r.rank!==e.length)throw new U(`The length of input n (${e.length}) does not match the number of dimensions in input x (${r.rank})`);return qo(r,e)}function id(r,e=0,t=1,n,o){return CT(r,e,t,n,o)}function ws(r,e,t,n){if(r.rank<2||e.rank<2)throw new Le(`dot requires both inputs to be rank >= 2 but got x shape = ${r.shape} and y shape = ${e.shape}`);if(e.rank>=3){let o=r.shape.slice(-1)[0],s=e.shape.slice(-2)[0];if(o!==s)throw new Le(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${r.shape} and y shape = ${e.shape}`)}if(r.rank===2&&e.rank===2){let o=!1,s=!1;return bs.matMul({a:r,b:e,transposeA:o,transposeB:s,bias:n?RS(r.rank,n,Kn()):null,activation:t})}else{let o=r.shape.slice(),s=o.pop();r=r.reshape([-1,s]);let i=e.shape.slice(),a=i.pop(),l=i.pop(),u=[...i,a],p=Array.from({length:e.rank},(d,h)=>h===0?e.rank-2:h<=e.rank-2?h-1:h);e=e.transpose(p).reshape([l,-1]);let c=[...o,...u],m=!1,f=!1;return bs.matMul({a:r,b:e,transposeA:m,transposeB:f,bias:n?RS(r.rank,n,Kn()):null,activation:t}).reshape(c)}}function qT(r,e,t){return j(()=>(Array.isArray(e)?e=Zt(e,"int32"):e=e.toInt(),Ba(r,e,t)))}function em(r){return G(r,r)}function RS(r,e,t){let n=e.shape;if(e.rank!==1&&e.rank!==r)throw new U(`Unexpected bias dimensions: ${e.rank}; expected it to be 1 or ${r}`);if(r===5){if(t==="channelsFirst")return n.length===1?e.reshape([1,n[0],1,1,1]):e.reshape([1,n[3],n[0],n[1],n[2]]);if(t==="channelsLast")return n.length===1?e.reshape([1,1,1,1,n[0]]):e.reshape([1].concat(n))}else if(r===4){if(t==="channelsFirst")return n.length===1?e.reshape([1,n[0],1,1]):e.reshape([1,n[2],n[0],n[1]]);if(t==="channelsLast")return n.length===1?e.reshape([1,1,1,n[0]]):e.reshape([1].concat(n))}else if(r===3){if(t==="channelsFirst")return n.length===1?e.reshape([1,n[0],1]):e.reshape([1,n[1],n[0]]);if(t==="channelsLast")return n.length===1?e.reshape([1,1,n[0]]):e.reshape([1].concat(n))}else if(r<3)return e;throw new U(`Unsupported input rank by biasAdd: ${e.rank}`)}function Un(r,e,t){return j(()=>(t==null&&(t=Kn()),tr(t),r.add(RS(r.rank,e,t))))}function Tz(r,e=1){if(e!==1)throw new Le(`Support for alpha values other than 1 (${e}) is not implemented yet.`);return La(r)}function kz(r){return j(()=>he(r,Ht(r).add(1)))}function XT(r,e,t,n){return j(()=>AP(r,e,t,n))}function Iz(r){return j(()=>{let e=ne(.5,G(.2,r));return Gr(e,0,1)})}function sp(r,e,t=!1){return t?r():e()}var vz=["fanIn","fanOut","fanAvg"],wz=["normal","uniform","truncatedNormal"];function zue(r){Ai(vz,"FanMode",r)}function Gue(r){Ai(wz,"Distribution",r)}var uo=class extends oe.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},Og=class extends uo{apply(e,t){return Rt(e,t)}};Og.className="Zeros";oe.registerClass(Og);var tm=class extends uo{apply(e,t){return on(e,t)}};tm.className="Ones";oe.registerClass(tm);var zg=class extends uo{constructor(e){super();if(typeof e!="object")throw new U(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new U(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return j(()=>G(be(this.value),on(e,t)))}getConfig(){return{value:this.value}}};zg.className="Constant";oe.registerClass(zg);var Gg=class extends uo{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 za(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}};Gg.className="RandomUniform";oe.registerClass(Gg);var Wg=class extends uo{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 Le(`randomNormal does not support dType ${t}.`);return id(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};Wg.className="RandomNormal";oe.registerClass(Wg);var Kg=class extends uo{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 Le(`truncatedNormal does not support dType ${t}.`);return Gc(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};Kg.className="TruncatedNormal";oe.registerClass(Kg);var Vg=class extends uo{constructor(e){super();this.gain=e.gain!=null?e.gain:1}apply(e,t){return j(()=>{if(e.length!==2||e[0]!==e[1])throw new U("Identity matrix initializer can only be used for 2D square matrices.");return G(this.gain,Xf(e[0]))})}getConfig(){return{gain:this.gain}}};Vg.className="Identity";oe.registerClass(Vg);function Wue(r,e="channelsLast"){let t,n;if(tr(e),r.length===2)t=r[0],n=r[1];else if([3,4,5].indexOf(r.length)!==-1){if(e==="channelsFirst"){let o=vs(r,2);t=r[1]*o,n=r[0]*o}else if(e==="channelsLast"){let o=vs(r,0,r.length-2);t=r[r.length-2]*o,n=r[r.length-1]*o}}else{let o=vs(r);t=Math.sqrt(o),n=Math.sqrt(o)}return[t,n]}var Sn=class extends uo{constructor(e){super();if(e.scale<0)throw new U(`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,zue(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,Gue(this.distribution),this.seed=e.seed}apply(e,t){let n=Wue(e),o=n[0],s=n[1],i=this.scale;if(this.mode==="fanIn"?i/=Math.max(1,o):this.mode==="fanOut"?i/=Math.max(1,s):i/=Math.max(1,(o+s)/2),this.distribution==="normal"){let a=Math.sqrt(i);if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Le(`${this.getClassName()} does not support dType ${t}.`);return Gc(e,0,a,t,this.seed)}else{let a=Math.sqrt(3*i);return za(e,-a,a,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};Sn.className="VarianceScaling";oe.registerClass(Sn);var ld=class extends Sn{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Sn.className}};ld.className="GlorotUniform";oe.registerClass(ld);var ud=class extends Sn{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Sn.className}};ud.className="GlorotNormal";oe.registerClass(ud);var pd=class extends Sn{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Sn.className}};pd.className="HeNormal";oe.registerClass(pd);var cd=class extends Sn{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Sn.className}};cd.className="HeUniform";oe.registerClass(cd);var md=class extends Sn{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Sn.className}};md.className="LeCunNormal";oe.registerClass(md);var fd=class extends Sn{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Sn.className}};fd.className="LeCunNormal";oe.registerClass(fd);var Ug=class extends uo{constructor(e){super();this.DEFAULT_GAIN=1;if(this.gain=e.gain==null?this.DEFAULT_GAIN:e.gain,this.seed=e.seed,this.seed!=null)throw new Le("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return j(()=>{if(e.length<2)throw new Le("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.`);let n=e[0]>e[1]?[e[1],e[0]]:e,o=id(n,0,1,"float32"),s=oB.gramSchmidt(o);return e[0]>e[1]&&(s=s.transpose()),G(this.gain,s)})}getConfig(){return{gain:this.gain,seed:this.seed}}};Ug.className="Orthogonal";oe.registerClass(Ug);var _z={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 Cz(r,e={}){return Ni(r,oe.SerializationMap.getMap().classNameMap,e,"initializer")}function Kt(r){return nd(r)}function Dt(r){if(typeof r=="string"){let e=r in _z?_z[r]:r;if(e==="GlorotNormal")return new ud;if(e==="GlorotUniform")return new ld;if(e==="HeNormal")return new pd;if(e==="HeUniform")return new cd;if(e==="LeCunNormal")return new md;if(e==="LeCunUniform")return new fd;{let t={};return t.className=e,t.config={},Cz(t)}}else return r instanceof uo?r:Cz(r)}function Kue(){return new Og}function Vue(){return new tm}function Uue(r){return new zg(r)}function jue(r){return new Gg(r)}function Hue(r){return new Wg(r)}function que(r){return new Kg(r)}function Xue(r){return new Vg(r)}function Yue(r){return new Sn(r)}function Zue(r){return new ld(r)}function Jue(r){return new ud(r)}function Que(r){return new pd(r)}function epe(r){return new cd(r)}function tpe(r){return new md(r)}function rpe(r){return new fd(r)}function npe(r){return new Ug(r)}var l3={};Ge(l3,{Layer:()=>He,RNN:()=>_s,RNNCell:()=>mp,activation:()=>_ce,add:()=>Rce,alphaDropout:()=>bme,average:()=>Lce,averagePooling1d:()=>_N,averagePooling2d:()=>CN,averagePooling3d:()=>SN,avgPool1d:()=>Vce,avgPool2d:()=>jce,avgPool3d:()=>qce,avgPooling1d:()=>Uce,avgPooling2d:()=>Hce,avgPooling3d:()=>Xce,batchNormalization:()=>Gce,bidirectional:()=>ume,concatenate:()=>$ce,conv1d:()=>gce,conv2d:()=>bce,conv2dTranspose:()=>yce,conv3d:()=>xce,conv3dTranspose:()=>Tce,convLstm2d:()=>sme,convLstm2dCell:()=>ame,cropping2D:()=>Ice,dense:()=>Cce,depthwiseConv2d:()=>wce,dot:()=>zce,dropout:()=>Sce,elu:()=>pce,embedding:()=>Fce,flatten:()=>Ace,gaussianDropout:()=>gme,gaussianNoise:()=>hme,globalAveragePooling1d:()=>Yce,globalAveragePooling2d:()=>Zce,globalMaxPool1d:()=>cme,globalMaxPool2d:()=>mme,globalMaxPooling1d:()=>o3,globalMaxPooling2d:()=>s3,gru:()=>Qce,gruCell:()=>eme,input:()=>HS,inputLayer:()=>uce,layerNormalization:()=>Wce,leakyReLU:()=>mce,lstm:()=>tme,lstmCell:()=>rme,masking:()=>yme,maxPool1d:()=>fme,maxPool2d:()=>dme,maxPooling1d:()=>a3,maxPooling2d:()=>i3,maxPooling3d:()=>Jce,maximum:()=>Pce,minimum:()=>Bce,multiply:()=>Oce,permute:()=>Mce,prelu:()=>fce,reLU:()=>cce,repeatVector:()=>Dce,reshape:()=>Ece,rnn:()=>ime,separableConv2d:()=>kce,simpleRNN:()=>nme,simpleRNNCell:()=>ome,softmax:()=>dce,spatialDropout1d:()=>Nce,stackedRNNCells:()=>lme,thresholdedReLU:()=>hce,timeDistributed:()=>pme,upSampling2d:()=>vce,zeroPadding2d:()=>Kce});var ope=0;function YT(){return ope++}var ZT={};function ap(r=""){return r in ZT||(ZT[r]=0),ZT[r]+=1,r+ZT[r].toString()}function JT(r){return Array.isArray(r)&&Array.isArray(r[0])}function dd(r){return r.length===0?[]:Array.isArray(r[0])?r:[r]}function Ve(r){let e;if(Array.isArray(r)){if(r.length!==1)throw new U(`Expected Tensor length to be 1; got ${r.length}`);e=r[0]}else e=r;return e}function it(r){if(Array.isArray(r)&&Array.isArray(r[0])){if(r.length===1)return r=r,r[0];throw new U(`Expected exactly 1 Shape; got ${r.length}`)}else return r}function hd(r){let e=0;for(let t of r)t.shape.length===0?e+=1:e+=t.shape.reduce((n,o)=>n*o);return e}var Nz="Variable",QT=class{constructor(e,t="float32",n=Nz,o=!0,s=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=YT(),n=n==null?Nz:n,this.originalName=UT(n),this.name=jT(this.originalName),this.trainable_=o,this.constraint=s,this.val=hS(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),spe(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 spe(r,e){if(r.shape.toString()!==e.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(r.shape)+" vs. "+JSON.stringify(e.shape))}function jg(r){return r.map(e=>e.read())}function gd(r){r.forEach(e=>{e[0].write(e[1])})}var Vt=class{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||{}}},jn=class{constructor(e,t,n,o,s,i,a){this.dtype=e;this.shape=t;this.sourceLayer=n;this.inputs=o;this.callArgs=s;this.outputTensorIndex=a;this.id=YT(),i!=null&&(this.originalName=UT(i),this.name=jT(this.originalName)),this.rank=t.length}},ape=0,ip=class{constructor(e,t){this.callArgs=t;this.id=ape++,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(let n of e.inboundLayers)n!=null&&n.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){let e=[];for(let 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}}},ipe=0,He=class extends oe.Serializable{constructor(e={}){super();this._callHook=null;this._addedWeightNames=[];this._stateful=!1;this.id=ipe++,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){let n=this.getClassName();t=Ts(n)+"_"+ap(n)}if(this.name=t,this.trainable_=e.trainable==null?!0:e.trainable,e.inputShape!=null||e.batchInputShape!=null){let n;if(e.batchInputShape!=null)n=e.batchInputShape;else if(e.inputShape!=null){let s=null;e.batchSize!=null&&(s=e.batchSize),n=[s].concat(e.inputShape)}this.batchInputShape=n;let o=e.dtype;o==null&&(o=e.inputDType),o==null&&(o="float32"),this.dtype=o}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 _n(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new U(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return Yr(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return Yr(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new vo(`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 vo(`Layer ${this.name} is not connected, no input to return.`);return Yr(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new vo(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new vo(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return Yr(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=$t(e),this.inputSpec==null||this.inputSpec.length===0)return;let t=$t(this.inputSpec);if(e.length!==t.length)throw new U(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let n=0;n<e.length;n++){let o=e[n],s=t[n];if(s==null)continue;let i=o.rank;if(s.ndim!=null&&i!==s.ndim)throw new U(`Input ${n} is incompatible with layer ${this.name}: expected ndim=${s.ndim}, found ndim=${i}`);if(s.maxNDim!=null&&i>s.maxNDim)throw new U(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${s.maxNDim}, found ndim=${i}`);if(s.minNDim!=null&&i<s.minNDim)throw new U(`Input ${n} is incompatible with layer ${this.name}: expected min_ndim=${s.minNDim}, found ndim=${i}.`);if(s.dtype!=null&&o.dtype!==s.dtype)throw new U(`Input ${n} is incompatible with layer ${this.name} : expected dtype=${s.dtype}, found dtype=${o.dtype}.`);if(s.axes){let a=o.shape;for(let l in s.axes){let u=Number(l),p=s.axes[l],c=u>=0?a[u]:a[a.length+u];if(p!=null&&[p,null].indexOf(c)===-1)throw new U(`Input ${n} is incompatible with layer ${this.name}: expected axis ${u} of input shape to have value ${p} but got shape ${a}.`)}}if(s.shape!=null)for(let a=0;a<s.shape.length;++a){let l=s.shape[a],u=o.shape[a];if(l!=null&&u!=null&&l!==u)throw new U(`Input ${n} is incompatible with layer ${this.name}: expected shape=${s.shape}, found shape=${o.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();let n=$t(e),o=!0;for(let i of n)if(!(i instanceof jn)){o=!1;break}let s=!0;for(let i of n)if(i instanceof jn){s=!1;break}if(o===s)throw new U("Arguments to apply() must be all SymbolicTensors or all Tensors");return Wa(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);let i=[];for(let a of $t(e))i.push(a.shape);this.build(Yr(i)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&s&&(this._refCount=1)}if(this.assertInputCompatibility(e),s){let i=this.call(e,t),a=$t(i),l=[];for(let u of a)n.indexOf(u)!==-1&&(u=u.clone()),l.push(u);if(i=Yr(l),this.activityRegularizer!=null)throw new Le("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return i}else{let i=lpe(e),a=this.computeOutputShape(i),l,u=upe(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?i[0]:i),a!=null&&a.length>0&&Array.isArray(a[0])?l=a.map((p,c)=>new jn(u,p,this,$t(e),t,this.name,c)):l=new jn(u,a,this,$t(e),t,this.name),this.addInboundNode(e,l,null,null,i,a,t),this._refCount++,this.activityRegularizer!=null)throw new Le("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return l}})}warnOnIncompatibleInputShape(e){if(this.batchInputShape!=null)if(e.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach((n,o)=>{n!=null&&e[o]!=null&&e[o]!==n&&(t=!0)}),t&&console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(this.inboundNodes==null||this.inboundNodes.length===0)throw new vo(`The layer ${this.name} has never been called and thus has no defined output shape.`);let e=[];for(let t of this.inboundNodes){let n=JSON.stringify(t.outputShapes);e.indexOf(n)===-1&&e.push(n)}if(e.length===1){let t=this.inboundNodes[0].outputShapes;return Array.isArray(t)&&Array.isArray(t[0])&&t.length===1?t[0]:t}else throw new vo(`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 _n(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return hd(this.weights)}build(e){this.built=!0}getWeights(e=!1){return jg(e?this.trainableWeights:this.weights)}setWeights(e){j(()=>{let t=this.weights;if(t.length!==e.length)throw new U(`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;let n=[],o=jg(t);for(let s=0;s<o.length;++s){let i=o[s],a=t[s],l=e[s];if(!x.arraysEqual(i.shape,l.shape))throw new U(`Layer weight shape ${i.shape} not compatible with provided weight shape ${l.shape}`);n.push([a,l])}gd(n)})}addWeight(e,t,n,o,s,i,a){if(this._addedWeightNames.indexOf(e)!==-1)throw new U(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),n==null&&(n="float32"),this.fastWeightInitDuringBuild&&(o=Dt("zeros"));let l=o.apply(t,n),u=new QT(l,n,e,i,a);return l.dispose(),s!=null&&this.addLoss(()=>s.apply(u.read())),i==null&&(i=!0),i?this._trainableWeights.push(u):this._nonTrainableWeights.push(u),u}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){e==null||Array.isArray(e)&&e.length===0||(e=$t(e),this._losses!==void 0&&this._losses!==null&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(t!=null)if(Array.isArray(t))t.forEach(n=>{if(n!=null)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)});else throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);return null}return t}addInboundNode(e,t,n,o,s,i,a=null){let l=$t(e);t=$t(t),n=$t(n),o=$t(o),s=dd(s),i=dd(i);let u=[],p=[],c=[];for(let m of l)u.push(m.sourceLayer),p.push(m.nodeIndex),c.push(m.tensorIndex);new ip({outboundLayer:this,inboundLayers:u,nodeIndices:p,tensorIndices:c,inputTensors:l,outputTensors:t,inputMasks:n,outputMasks:o,inputShapes:s,outputShapes:i},a);for(let m=0;m<t.length;m++)t[m].sourceLayer=this,t[m].nodeIndex=this.inboundNodes.length-1,t[m].tensorIndex=m}getConfig(){let 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 lpe(r){r=$t(r);let e=[];for(let t of r)e.push(t.shape);return Yr(e)}function upe(r){return"float32"}function LS(r,e,t){if((e==null||t!=null&&t>0)&&(e=r.sourceLayer,t=r.nodeIndex),e.inboundNodes.length===0)return[r];{let n=e.inboundNodes[t];if(n.inboundLayers.length===0)return n.inputTensors;{let o=[];for(let s=0;s<n.inboundLayers.length;s++){let i=n.inputTensors[s],a=n.inboundLayers[s],l=n.nodeIndices[s],u=LS(i,a,l);for(let p of u)o.indexOf(p)===-1&&o.push(p)}return o}}}var Di=class extends He{constructor(e){super({dtype:e.dtype,name:e.name!=null?e.name:ap("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 U("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 U("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(e.batchSize!=null)throw new U("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");let n=e.dtype||"float32";this.batchInputShape=t,this.dtype=n,this.inputSpec=[{shape:t}];let o=new jn(this.dtype,this.batchInputShape,this,[],{},this.name);o.nodeIndex=0,o.tensorIndex=0,new ip({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[o],outputTensors:[o],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new U(`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}}};Di.className="InputLayer";oe.registerClass(Di);function ek(r){if(r.batchShape==null&&r.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(r.batchShape!=null&&r.shape!=null)throw new U("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let e=r.batchShape;r.shape!=null&&e==null&&(e=[null].concat(r.shape));let t=r.dtype;return t==null&&(t="float32"),new Di({batchInputShape:e,name:r.name,dtype:t,sparse:r.sparse}).inboundNodes[0].outputTensors[0]}async function Ei(r){if(r==null)return;let e=[],t=[],n=[];for(let o in r){let s=r[o];if(typeof s!="number"){let i=s;e.push(i.data()),t.push(o),n.push(i)}}if(e.length>0){let o=await Promise.all(e);for(let s=0;s<o.length;++s)r[t[s]]=o[s][0];Be(n)}}function tk(r){if(r!=null)for(let e in r){let t=r[e];typeof t!="number"&&t.dispose()}}var Az;(function(t){t[t.SILENT=0]="SILENT",t[t.VERBOSE=1]="VERBOSE"})(Az||(Az={}));var ppe=125,lp=class{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){}},$S=class{constructor(e,t=10){e==null&&(e=[]),this.callbacks=e,this.queueLength=t}append(e){this.callbacks.push(e)}setParams(e){for(let t of this.callbacks)t.setParams(e)}setModel(e){for(let t of this.callbacks)t.setModel(e)}async onEpochBegin(e,t){t==null&&(t={});for(let n of this.callbacks)await n.onEpochBegin(e,t)}async onEpochEnd(e,t){t==null&&(t={});for(let n of this.callbacks)await n.onEpochEnd(e,t)}async onBatchBegin(e,t){t==null&&(t={});for(let n of this.callbacks)await n.onBatchBegin(e,t)}async onBatchEnd(e,t){t==null&&(t={});for(let n of this.callbacks)await n.onBatchEnd(e,t)}async onTrainBegin(e){e==null&&(e={});for(let t of this.callbacks)await t.onTrainBegin(e)}async onTrainEnd(e){e==null&&(e={});for(let t of this.callbacks)await t.onTrainEnd(e)}},Dz=class extends lp{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){t==null&&(t={});let n=t.size==null?0:t.size;this.seen+=n;for(let o in t){let s=t[o];if(typeof s=="number")this.totals.hasOwnProperty(o)||(this.totals[o]=0),this.totals[o]=this.totals[o]+s*n;else{let i;o in this.totals?i=this.totals[o]:this.totals[o]=0;let a=j(()=>ne(this.totals[o],G(s,n)));this.totals[o]=a,i!=null&&i.dispose()}}}async onEpochEnd(e,t){if(t!=null)for(let n of this.params.metrics)this.totals[n]!=null&&(typeof this.totals[n]=="number"?t[n]=this.totals[n]/this.seen:j(()=>{let o=G(he(1,this.seen),this.totals[n]);t[n]=o,this.totals[n].dispose(),er(t[n])}))}},PS=class extends lp{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){t==null&&(t={}),this.epoch.push(e);for(let n in t)this.history[n]==null&&(this.history[n]=[]),this.history[n].push(t[n])}async syncData(){let e=[],t=[],n=[];for(let s in this.history){let i=this.history[s];for(let a=0;a<i.length;++a)if(typeof i[a]!="number"){let l=i[a];e.push(l.data()),t.push(s),n.push(a)}}let o=await Promise.all(e);for(let s=0;s<o.length;++s)this.history[t[s]][n[s]].dispose(),this.history[t[s]][n[s]]=o[s][0]}},BS=class extends lp{constructor(e,t){super();this.currentEpoch=0;if(this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=ppe),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");x.isNumber(this.yieldEvery)&&(this.maybeWait=oz(this.maybeWait.bind(this),this.yieldEvery)),this.trainBegin=e.onTrainBegin,this.trainEnd=e.onTrainEnd,this.epochBegin=e.onEpochBegin,this.epochEnd=e.onEpochEnd,this.batchBegin=e.onBatchBegin,this.batchEnd=e.onBatchEnd,this.yield=e.onYield}async maybeWait(e,t,n){let o=[];this.yield!=null&&(await Ei(n),o.push(this.yield(e,t,n))),o.push(Dg()),await Promise.all(o)}async onEpochBegin(e,t){this.currentEpoch=e,this.epochBegin!=null&&(await Ei(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){let n=[];this.epochEnd!=null&&(await Ei(t),n.push(this.epochEnd(e,t))),this.yieldEvery==="epoch"&&n.push(Dg()),await Promise.all(n)}async onBatchBegin(e,t){this.batchBegin!=null&&(await Ei(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){let n=[];this.batchEnd!=null&&(await Ei(t),n.push(this.batchEnd(e,t))),this.yieldEvery==="batch"?n.push(Dg()):x.isNumber(this.yieldEvery)&&n.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(n)}async onTrainBegin(e){this.trainBegin!=null&&(await Ei(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await Ei(e),await this.trainEnd(e))}};function rk(r,e){return r==null&&(r={}),r instanceof lp?[r]:Array.isArray(r)&&r[0]instanceof lp?r:$t(r).map(n=>new BS(n,e))}var Va=class{constructor(){}static registerCallbackConstructor(e,t){x.assert(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),Va.checkForDuplicate(t),Va.constructors[e]==null&&(Va.constructors[e]=[]),Va.constructors[e].push(t)}static checkForDuplicate(e){for(let t in Va.constructors)Va.constructors[+t].forEach(o=>{if(o===e)throw new U("Duplicate callback constructor.")})}static clear(){Va.constructors={}}static createCallbacks(e){let t=[];for(let n in Va.constructors){let o=+n;e>=o&&t.push(...Va.constructors[o])}return t.map(n=>new n)}},Hg=Va;Hg.constructors={};function nk(r,e,t,n,o,s,i,a,l){let u=new PS,p=[new Dz,...Hg.createCallbacks(e)];r!=null&&p.push(...r),p.push(u);let c=new $S(p);return c.setParams({epochs:t,initialEpoch:n,samples:o,steps:s,batchSize:i,verbose:e,doValidation:a,metrics:l}),{callbackList:c,history:u}}function Hn(r,e={},t=!1){return Ni(r,oe.SerializationMap.getMap().classNameMap,e,"layer",t)}function qg(r,e){return j(()=>{r.dtype!=="float32"&&(r=r.asType("float32"));let t=Te(em(r),e,!0),n=$a(t.shape,Lr()),o=Lt(Wn(t,n));return he(r,o)})}function Mi(r,e){return j(()=>Ft(em(ge(e,r)),-1))}function bd(r,e){return j(()=>Ft(Ht(ge(e,r)),-1))}function up(r,e){return j(()=>{let t=ge(r,e),n=Gr(Ht(r),Lr(),Number.MAX_VALUE),o=Ht(he(t,n));return G(100,Ft(o,-1))})}function cpe(r,e){return j(()=>{let t=Gr(e,Lr(),Number.MAX_VALUE),n=Kr(ne(1,t)),o=Gr(r,Lr(),Number.MAX_VALUE),s=Kr(ne(1,o));return Ft(em(ge(n,s)),-1)})}function mpe(r,e){return j(()=>{let t=Wn(0,ge(1,G(r,e)));return Ft(em(t),-1)})}function fpe(r,e){return j(()=>{let t=Wn(0,ge(1,G(r,e)));return Ft(t,-1)})}function dpe(r,e){return j(()=>{let t=Te(G(r,e),-1),n=nn(G(ge(1,r),e),-1);return Wn(0,ne(1,ge(n,t)))})}function hpe(r,e){return j(()=>{let t=Math.log(2),n=ge(e,r),o=ge(ne(n,ds(G(-2,n))),t);return Ft(o,-1)})}function rm(r,e,t=!1){return j(()=>{if(t)e=Ql(e);else{let n=Te(e,e.shape.length-1,!0);e=he(e,n)}return e=Gr(e,Lr(),1-Lr()),st(Te(G(r.toFloat(),Kr(e)),e.shape.length-1))})}function yd(r,e,t=!1){return j(()=>{let n=Pa(yz(r)).toInt();e=Gr(e,Lr(),1-Lr());let o=e.shape,s=Ea(n,o[o.length-1]).reshape(o);return rm(s,e,t)})}function gpe(r,e){if(!x.arraysEqual(r.shape,e.shape))throw new U(`logits and labels must have the same shape, but got shapes ${JSON.stringify(r.shape)} and ${JSON.stringify(e.shape)}`);return j(()=>{let t=e.relu(),n=e.abs().neg();return t.sub(e.mul(r)).add(n.exp().log1p())})}function xd(r,e){return j(()=>{let t;return t=Gr(e,Lr(),1-Lr()),t=Kr(he(t,ge(1,t))),Ft(gpe(r,t),-1)})}function bpe(r,e){return j(()=>{let t=Gr(r,Lr(),1),n=Gr(e,Lr(),1);return Te(G(r,Kr(he(t,n))),-1)})}function ype(r,e){return j(()=>{let t=Kr(ne(Lr(),e));return Ft(ge(e,G(r,t)),-1)})}function Xg(r,e){return j(()=>{let t=qg(r,-1),n=qg(e,-1),o=G(t,n);return st(Te(o,-1))})}var Yg={meanSquaredError:Mi,meanAbsoluteError:bd,meanAbsolutePercentageError:up,meanSquaredLogarithmicError:cpe,squaredHinge:mpe,hinge:fpe,categoricalHinge:dpe,logcosh:hpe,categoricalCrossentropy:rm,sparseCategoricalCrossentropy:yd,binaryCrossentropy:xd,kullbackLeiblerDivergence:bpe,poisson:ype,cosineProximity:Xg};function ok(r){if(typeof r=="string"){if(r in Yg)return Yg[r];let e=`Unknown loss ${r}`;throw r.toLowerCase().includes("softmaxcrossentropy")&&(e=`Unknown loss ${r}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new U(e)}else return r}function Zg(r,e){return j(()=>{let t=G(.5,Br(e)),n=ou(yr(e,t),r.dtype);return Ft(Io(r,n),-1)})}function Jg(r,e){return j(()=>ou(Io(ep(r,-1),ep(e,-1)),"float32"))}function Ez(r,e){return j(()=>Xr(r.equal(1),e.equal(1)).sum().cast("float32"))}function xpe(r,e){return j(()=>Xr(r.equal(1),e.equal(0)).sum().cast("float32"))}function Tpe(r,e){return j(()=>Xr(r.equal(0),e.equal(1)).sum().cast("float32"))}function OS(r,e){return j(()=>{let t=Ez(r,e),n=Tpe(r,e),o=t.add(n);return Wt(yr(o,0),t.div(o),0).cast("float32")})}function Mz(r,e){return j(()=>{let t=Ez(r,e),n=xpe(r,e),o=t.add(n);return Wt(yr(o,0),t.div(o),0).cast("float32")})}function sk(r,e){return xd(r,e)}function ak(r,e){return r.rank===e.rank&&(r=r.squeeze([r.rank-1])),e=e.argMax(-1),e.dtype!==r.dtype&&(e=e.asType(r.dtype)),Io(r,e).asType("float32")}var kpe=Mi,Ipe=Mi,vpe=bd,wpe=bd,_pe=up,Cpe=up,Qg=rm,Spe=Xg,zS=yd,ik={binaryAccuracy:Zg,categoricalAccuracy:Jg,precision:OS,categoricalCrossentropy:Qg,sparseCategoricalCrossentropy:zS,mse:kpe,MSE:Ipe,mae:vpe,MAE:wpe,mape:_pe,MAPE:Cpe,cosine:Spe};function Fz(r){if(typeof r=="string"&&r in ik)return ik[r];if(typeof r!="string"&&r!=null)return r;throw new U(`Unknown metric ${r}`)}function eb(r){if(Yo(r!==null,`Unknown LossOrMetricFn ${r}`),typeof r=="string")return r;{let e;for(let t of Object.keys(Yg))if(Yg[t]===r){e=t;break}if(e!==void 0)return e;for(let t of Object.keys(ik))if(ik[t]===r){e=t;break}return e!==void 0?e:r.name}}function Rz(r){let e={Adagrad:()=>Jc.adagrad(.01),Adadelta:()=>Jc.adadelta(1,.95,Lr()),Adam:()=>Jc.adam(.001,.9,.999,Lr()),Adamax:()=>Jc.adamax(.002,.9,.999,Lr(),0),RMSProp:()=>Jc.rmsprop(.001,.9,0,Lr()),SGD:()=>Jc.sgd(.01)};if(e.adagrad=e.Adagrad,e.adadelta=e.Adadelta,e.adam=e.Adam,e.adamax=e.Adamax,e.rmsprop=e.RMSProp,e.sgd=e.SGD,r in e)return e[r]();throw new U(`Unknown Optimizer ${r}`)}var Lz=1*1024*1024;function GS(r,e,t=!1){if(r==null||typeof r!="object"||Object.getPrototypeOf(r)!==Object.prototype||!WS(r))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(t){let n=JSON.stringify(r);n.length>Lz&&console.warn(`User-defined metadata of model "${e}" 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 <= ${Lz}.`)}}function WS(r){if(r===null)return!0;if(typeof r=="object")if(Object.getPrototypeOf(r)===Object.prototype){let e=Object.keys(r);for(let t of e)if(typeof t!="string"||!WS(r[t]))return!1;return!0}else if(Array.isArray(r)){for(let e of r)if(!WS(e))return!1;return!0}else return!1;else{let e=typeof r;return e==="string"||e==="number"||e==="boolean"}}function $z(r,e,t,n=console.log){let o=Ape(r),s=["Layer (type)","Output shape","Param #"];o?(e=e||65,t=t||[.45,.85,1]):(e=e||98,t=t||[.33,.55,.67,1]),t[t.length-1]<=1&&(t=t.map(p=>Math.floor(e*p)));let i;if(!o){s.push("Receives inputs"),i=[];for(let p in r.nodesByDepth)i.push(...r.nodesByDepth[p])}n("_".repeat(e)),lk(s,t,n),n("=".repeat(e));let a=r.layers;for(let p=0;p<a.length;++p)o?Dpe(a[p],t,n):Epe(a[p],t,i,n),n((p===a.length-1?"=":"_").repeat(e));r.checkTrainableWeightsConsistency();let l=Npe(r),u=hd(r.nonTrainableWeights);n(`Total params: ${l+u}`),n(`Trainable params: ${l}`),n(`Non-trainable params: ${u}`),n("_".repeat(e))}function Npe(r){let e;return r.collectedTrainableWeights!=null?e=hd(r.collectedTrainableWeights):e=hd(r.trainableWeights),e}function Ape(r){let e=!0,t=[],n=[];for(let o in r.nodesByDepth)t.push(r.nodesByDepth[o]);for(let o of t){if(o.length>1||o.length===1&&o[0].inboundLayers.length>1){e=!1;break}n.push(...o)}if(e)for(let o of r.layers){let s=!1;for(let i of o.inboundNodes)if(n.indexOf(i)!==-1)if(s){e=!1;break}else s=!0;if(!e)break}return e}function lk(r,e,t=console.log){let n="";for(let o=0;o<r.length;++o)o>0&&(n=n.slice(0,n.length-1)+" "),n+=r[o],n=n.slice(0,e[o]),n+=" ".repeat(e[o]-n.length);t(n)}function Dpe(r,e,t){let n;try{n=JSON.stringify(r.outputShape)}catch(a){n="multiple"}let o=r.name,s=r.getClassName(),i=[`${o} (${s})`,n,r.countParams().toString()];lk(i,e,t)}function Epe(r,e,t,n){let o;try{o=JSON.stringify(r.outputShape)}catch(p){o="multiple"}let s=[];for(let p of r.inboundNodes)if(!(t!=null&&t.length>0&&t.indexOf(p)===-1))for(let c=0;c<p.inboundLayers.length;++c){let m=p.inboundLayers[c].name,f=p.nodeIndices[c],d=p.tensorIndices[c];s.push(`${m}[${f}][${d}]`)}let i=r.name,a=r.getClassName(),l=s.length===0?"":s[0],u=[`${i} (${a})`,o,r.countParams().toString(),l];lk(u,e,n);for(let p=1;p<s.length;++p)lk(["","","",s[p]],e,n)}function Pz(r,e,t){return(r==="inboundNodes"||r==="outputLayers"||r==="inputLayers")&&e===0&&typeof t=="string"}function nm(r,e){if(r===null)return null;if(typeof r=="string")return nu(r);if(typeof r=="number"||typeof r=="boolean")return r;if(r instanceof Array){let t=[],n=r.length;for(let o=0;o<n;++o){let s=r[o];Pz(e,o,s)?t.push(s):t.push(nm(s,e))}return t}else{let t={};for(let n of Object.keys(r)){let o=r[n];if(n==="name"&&typeof o=="string")t[n]=o;else{let s=nu(n);t[s]=nm(o,s)}}return t}}function uk(r,e){if(r==null)return null;if(typeof r=="string")return Ts(r);if(typeof r=="number"||typeof r=="boolean")return r;if(r instanceof Array){let t=[],n=r.length;for(let o=0;o<n;++o){let s=r[o];Pz(e,o,s)?t.push(s):t.push(uk(s,e))}return t}else{let t={};for(let n of Object.keys(r)){let o=r[n],s=Ts(n);(n==="name"||n==="className")&&typeof o=="string"?t[s]=o:t[s]=uk(o,n)}return t}}var tb="3.7.0";function Mpe(r,e){if(r.dtype==null||r.dtype===e.dtype)return e;try{return ue(e,r.dtype)}catch(t){throw new U(`The dtype of the feed (${e.dtype}) can not be cast to the dtype of the key '${r.name}' (${r.dtype}).`)}}var Ua=class{constructor(e){this.id2Value={};this.id2Mask={};this.name2Id={};if(e instanceof Ua)for(let 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(let t of e)this.add(t.key,t.value)}}add(e,t,n){if(this.id2Value[e.id]==null)this.id2Value[e.id]=Mpe(e,t),this.name2Id[e.name]=e.id,n!=null&&(this.id2Mask[e.id]=n);else throw new U(`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 jn){if(this.id2Value[e.id]==null)throw new U(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}else{let t=this.name2Id[e];if(t==null)throw new U(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof jn){if(this.id2Value[e.id]==null)throw new U(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}else{let t=this.name2Id[e];if(t==null)throw new U(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){this.id2Mask!=null&&Be(this.id2Mask)}},KS={},Bz={};function om(r,e,t,n){let o=t==null?!1:t.training,s=Array.isArray(r),i=s?r:[r],a=i.map(d=>d.name),l=[],u=e.names();for(let d of a)u.indexOf(d)!==-1?l.push(e.getValue(d)):l.push(null);n!=null&&(n.maxNumTensors=-Infinity,n.minNumTensors=Infinity);let p=a.join(",")+"|"+e.names().join(","),c,m;if(KS[p]==null){let d=Fpe(i,e);c=d.sorted,m=d.recipientCounts,KS[p]=c,Bz[p]=m}c=KS[p],m={},o||Object.assign(m,Bz[p]);let f=new Ua(e);for(let d=0;d<c.length;++d){if(n!=null){let $=Xh().numTensors;$>n.maxNumTensors&&(n.maxNumTensors=$),$<n.minNumTensors&&(n.minNumTensors=$)}let h=c[d],g=h.sourceLayer;if(g instanceof Di)continue;let b=[],y=[],T=[],k=!1;for(let $ of h.inputs){let O=f.getValue($),V=f.getMask($);b.push(O),y.push(V),V!=null&&(k=!0),o||(m[$.name]--,m[$.name]===0&&!e.hasKey($)&&a.indexOf($.name)===-1&&!O.isDisposed&&$.sourceLayer.stateful!==!0&&T.push(O))}k&&(t=t||{},t.mask=y[0]);let I=$t(g.apply(b,t)),S=null;g.supportsMasking&&(S=g.computeMask(b,y));let N=Lpe(h),F=Array.isArray(N)?N:[N];for(let $=0;$<F.length;++$){f.hasKey(F[$])||f.add(F[$],I[$],Array.isArray(S)?S[0]:S);let O=a.indexOf(F[$].name);O!==-1&&(l[O]=I[$])}o||Be(T)}return f.disposeMasks(),s?l:l[0]}function Fpe(r,e){x.assert(r!=null&&r.length>0,()=>"Expected at least one fetch, got none");let t=[],n={};if(r.length===1){let o=Oz(r[0],e);t=o.sorted,n=o.recipientMap}else{let o=new Set;for(let s of r){let{sorted:i,recipientMap:a}=Oz(s,e);for(let l of i)o.has(l.name)||(t.push(l),o.add(l.name));for(let l in a)n[l]==null&&(n[l]=new Set),a[l].forEach(u=>n[l].add(u))}}return{sorted:t,recipientCounts:Rpe(n)}}function Rpe(r){let e={};for(let t in r)e[t]=r[t].size;return e}function Oz(r,e){let t=new Set,n=[],o={};for(let a of e.names())t.add(a);let s=[],i=[];for(s.push(r);s.length>0;){let a=s[s.length-1];if(t.has(a.name)){s.pop();continue}let l=i[i.length-1]===s.length-1;if(a.inputs.length===0||l)s.pop(),n.push(a),t.add(a.name),l&&i.pop();else{i.push(s.length-1);for(let u of a.inputs)o[u.name]==null&&(o[u.name]=new Set),o[u.name].add(a.name),!t.has(u.name)&&s.push(u)}}return{sorted:n,recipientMap:o}}function Lpe(r){let e;if(r.sourceLayer.inboundNodes.length===1)e=r.sourceLayer.output;else{let t=null;for(let n=0;n<r.sourceLayer.inboundNodes.length;++n)for(let o of r.sourceLayer.inboundNodes[n].outputTensors)if(o.id===r.id){t=n;break}e=r.sourceLayer.getOutputAt(t)}return e}var Zo=class extends He{constructor(e){super({});this.containerNodes=new Set;if(this.name=e.name,this.name==null){let y=this.getClassName().toLowerCase();this.name=ap(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],Is(this.inputs).length!==this.inputs.length)throw new U(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(y=>y.name)}`);Is(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(let y of this.outputs){let T=y.sourceLayer,k=y.nodeIndex,I=y.tensorIndex;this.outputLayers.push(T),this.outputLayersNodeIndices.push(k),this.outputLayersTensorIndices.push(I)}for(let y of this.inputs){let T=y.sourceLayer,k=y.nodeIndex,I=y.tensorIndex;Yo(k===0,"input layer has >1 nodes"),Yo(I===0,"input layer has >1 tensors"),this.inputLayers.push(T),this.inputLayersNodeIndices.push(k),this.inputLayersTensorIndices.push(I)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let y=0;y<this.inputLayers.length;y++){let T=this.inputLayers[y];if(!(T instanceof Di))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${y} (0-based) originates from layer type ${T.getClassName()}.`);this.inputNames.push(T.name),this.feedInputShapes.push(T.batchInputShape),this.feedInputNames.push(T.name)}for(let 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);let t={},n={},o={},s={},i={},a=[],l=(y,T,k,I,S,N)=>{(I==null||S==null||N==null)&&(I=y.sourceLayer,S=y.nodeIndex,N=y.tensorIndex);let F=I.inboundNodes[S];if(k.indexOf(F)!==-1)throw new _n(`The tensor ${y.name} at layer "${I.name}" is part of a cycle.`);if(T.indexOf(F)!==-1)return;this.containerNodes.add(Zo.nodeKey(I,S)),I.id in i||(i[I.id]=Object.keys(i).length),k.indexOf(F)===-1&&k.push(F);let $=F.inboundLayers.length;for(let O=0;O<$;O++){let V=F.inputTensors[O],q=F.inboundLayers[O],W=F.nodeIndices[O],Y=F.tensorIndices[O];l(V,T,k,q,W,Y)}for(T.push(F);k.indexOf(F)>=0;)k.splice(k.indexOf(F),1);a.push(F)},u=[],p=[];for(let y of this.outputs)l(y,u,p);let c=a.slice().reverse();for(let y of c){n[y.id]=y,y.id in t||(t[y.id]=0);let T=t[y.id],k=o[y.outboundLayer.id]==null?0:o[y.outboundLayer.id];T=Math.max(T,k),o[y.outboundLayer.id]=T,s[y.outboundLayer.id]=y.outboundLayer,t[y.id]=T;for(let I=0;I<y.inboundLayers.length;I++){let S=y.inboundLayers[I],N=y.nodeIndices[I],F=S.inboundNodes[N],$=t[F.id]==null?0:t[F.id];t[F.id]=Math.max(T+1,$),n[F.id]=F}}let m={};for(let y in t){let T=t[y];T in m||(m[T]=[]),m[T].push(n[y])}let f={};for(let y in o){let T=o[y];T in f||(f[T]=[]),f[T].push(s[y])}let d=Object.keys(f).map(y=>parseInt(y,10)).sort(Mg);this.layers=[];for(let y of d){let T=f[y];T.sort((k,I)=>{let S=i[k.id],N=i[I.id];return S<N?-1:S>N?1:0});for(let k of T)k instanceof Zo&&this.internalContainerRefs.push(k),this.layers.push(k)}this.layersByDepth=f,d=Object.keys(m).map(y=>parseInt(y,10)).sort(Mg);let h=this.inputs.slice(),g=[];for(let y of d)for(let T of m[y]){let k=T.outboundLayer;if(k!=null){for(let I of T.inputTensors)if(h.indexOf(I)===-1)throw new _n(`Graph disconnected: cannot obtain value for tensor ${I} at layer "${k.name}". The following previous layers were accessed without issue: ${g}`);for(let I of T.outputTensors)h.push(I);g.push(k.name)}}this.nodesByDepth=m;let b=this.layers.map(y=>y.name);for(let y of b){let T=b.filter(k=>k===y).length;if(T!==1)throw new _n(`The name "${y}" is used ${T} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(b))}this.outboundNodes=[],this.inboundNodes=[],new ip({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();let e={refCountAfterDispose:null,numDisposedVariables:0};if(--this._refCount==0){for(let t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(let t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach(t=>{t._trainableWeights.forEach(n=>n.trainable=e)}),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new U("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(let t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let n of this.layers)t.push(...n.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){let n={},o=0;for(let i of this.layers)for(let a of i.weights){if(n[a.originalName]!=null)throw new U(`Duplicate weight name: ${a.originalName}`);n[a.originalName]=a,o++}let s=[];for(let i in e){let a=i;if(n[i]==null){let l=i.split("/");a=l.slice(0,-2).concat([l[l.length-1]]).join("/")}if(n[a]!=null)s.push([n[a],e[i]]);else if(t)throw new U(`Provided weight data has no target variable: ${i}`);delete n[a]}if(t){let i=[];for(let a in n)i.push(a);if(i.length>0)throw new U(`${i.length} of ${o} weights are not set: ${i}`)}gd(s)}updatedConfig(){let e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${tb}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){let n=uk(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return j(()=>{e=$t(e);let n=new Ua;for(let o=0;o<this.inputs.length;++o)n.add(this.inputs[o],e[o]);return om(this.outputs,n,t)})}computeMask(e,t){return j(()=>{e=$t(e);let n;return t==null?n=xs(null,e.length):n=$t(t),this.runInternalGraph(e,n)[1]})}computeOutputShape(e){let t=dd(e);if(t.length!==this.inputLayers.length)throw new U(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);let n={};for(let a=0;a<t.length;a++){let l=this.inputLayers[a],u=t[a],p=l.name+"_0_0";n[p]=u}let o=Object.keys(this.nodesByDepth).map(a=>parseInt(a,10)).sort(Mg);if(o.length>1)for(let a of o){let l=this.nodesByDepth[a];for(let u of l){let p=u.outboundLayer;if(this.inputLayers.map(h=>h.id).indexOf(p.id)!==-1)continue;let c=[];for(let h=0;h<u.inboundLayers.length;h++){let g=u.inboundLayers[h],b=u.nodeIndices[h],y=u.tensorIndices[h],T=`${g.name}_${b}_${y}`,k=n[T];c.push(k)}let m=p.computeOutputShape(Yr(c)),f=dd(m),d=p.inboundNodes.indexOf(u);for(let h=0;h<f.length;h++){let g=`${p.name}_${d}_${h}`;n[g]=f[h]}}}let s=[],i=[];for(let a=0;a<this.outputLayers.length;a++){let l=this.outputLayers[a],u=this.outputLayersNodeIndices[a],p=this.outputLayersTensorIndices[a],c=`${l.name}_${u}_${p}`;i.push(c)}for(let a=0;a<i.length;a++){let l=i[a];Yo(l in n),s.push(n[l])}return Yr(s)}runInternalGraph(e,t){t==null&&(t=xs(null,e.length));let n={};for(let l=0;l<this.inputs.length;++l){let u=this.inputs[l],p=e[l],c=t[l];n[u.id]=[p,c]}let o=Object.keys(this.nodesByDepth).map(l=>parseInt(l,10)).sort(Mg);for(let l of o){let u=this.nodesByDepth[l];for(let p of u){let c=p.outboundLayer,m=p.inputTensors,f=p.outputTensors,d=new Array;for(let h of m)h.id in n&&d.push(n[h.id]);if(d.length===m.length){let h={},g,b,y,T;if(p.callArgs!=null&&(h=p.callArgs),d.length===1){let[k,I]=d[0];h.mask==null&&(h.mask=I),y=$t(c.call(k,h)),T=$t(c.computeMask(k,I)),g=[k],b=[I]}else g=d.map(k=>k[0]),b=d.map(k=>k[1]),h.mask==null&&(h.mask=b),y=$t(c.call(g,h)),T=$t(c.computeMask(g,b));if(c.activityRegularizer)throw new Le("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let k=0;k<f.length;++k){let I=f[k],S=y[k],N=T[k];n[I.id]=[S,N]}}}}let s=[],i=[],a=[];for(let l of this.outputs){Yo(l.id in n,`Could not compute output ${l.name} : ${l.id}`);let[u,p]=n[l.id];a.push(u.shape),s.push(u),i.push(p)}return[s,i,a]}buildNodeConversionMap(e){let t={},n;for(let o of this.layers){n=o instanceof Zo?1:0;for(let s=0;s<o.inboundNodes.length;s++){let i=Zo.nodeKey(o,s);this.containerNodes.has(i)&&(t[i]=n,n+=1)}}return t}getLayer(e,t){if(t!=null){if(this.layers.length<=t)throw new U(`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 U("Provide either a layer name or layer index");for(let n of this.layers)if(n.name===e)return n;throw new U(`No such layer: ${e}`)}calculateLosses(){return j(()=>{let e=[];for(let t of this.layers)for(let n=0;n<t.inboundNodes.length;++n){let o=Zo.nodeKey(t,n);this.containerNodes.has(o)&&e.push(...t.calculateLosses())}return e})}getConfig(){let e={name:this.name},t=this.buildNodeConversionMap(this.layers),n=[];for(let i of this.layers){let a=i.getClassName(),l=i.getConfig(),u=[];for(let c=0;c<i.inboundNodes.length;c++){let m=i.inboundNodes[c],f=Zo.nodeKey(i,c),d={};if(this.containerNodes.has(f)){if(m.callArgs)try{JSON.stringify(m.callArgs),d=m.callArgs}catch(h){console.warn(`Layer ${i.name} was passed non-serializable keyword arguments: ${m.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),d={}}if(m.inboundLayers.length>0){let h=[];for(let g=0;g<m.inboundLayers.length;g++){let b=m.inboundLayers[g],y=m.nodeIndices[g],T=m.tensorIndices[g],k=Zo.nodeKey(b,y),I=t[k];I==null&&(I=0),h.push([b.name,I,T,d])}u.push(h)}}}let p={};p.name=i.name,p.className=a,p.config=l,p.inboundNodes=u,n.push(p)}e.layers=n;let o=[];for(let i=0;i<this.inputLayers.length;i++){let a=this.inputLayers[i],l=this.inputLayersNodeIndices[i],u=Zo.nodeKey(a,l);if(!this.containerNodes.has(u))continue;let p=t[u];p==null&&(p=0);let c=this.inputLayersTensorIndices[i];o.push([a.name,p,c])}e.inputLayers=o;let s=[];for(let i=0;i<this.outputLayers.length;i++){let a=this.outputLayers[i],l=this.outputLayersNodeIndices[i],u=Zo.nodeKey(a,l);if(!this.containerNodes.has(u))continue;let p=t[u];p==null&&(p=0);let c=this.outputLayersTensorIndices[i];s.push([a.name,p,c])}return e.outputLayers=s,e}static fromConfig(e,t,n={},o=!1){let s={},i={};function a(g,b){g.name in i?i[g.name].push(b):i[g.name]=[b]}function l(g,b){let y=[],T;for(let k of b){let I=k[0],S=k[1],N=k[2];if(T=k[3]==null?{}:k[3],!(I in s)){a(g,b);return}let F=s[I];if(F.inboundNodes.length<=S){a(g,b);return}let $=F.inboundNodes[S];y.push($.outputTensors[N])}y.length>0&&g.apply(Yr(y),T)}function u(g){let b=g.name,y=Hn(g,t.customObjects!=null?t.customObjects:{});y.setFastWeightInitDuringBuild(o),s[b]=y,g.inboundNodes.forEach(k=>{if(!(k instanceof Array))throw new U(`Corrupted configuration, expected array for nodeData: ${k}`);a(y,k)})}let p=t.name,c=t.layers;for(let g of c)u(g);for(;!rz(i);)for(let g of c){let b=s[g.name];if(b.name in i){let y=i[b.name];delete i[b.name];for(let T of y)l(b,T)}}let m=[],f=[],d=t.inputLayers;for(let g of d){let b=g[0],y=g[1],T=g[2];Yo(b in s);let I=s[b].inboundNodes[y].outputTensors;m.push(I[T])}let h=t.outputLayers;for(let g of h){let b=g[0],y=g[1],T=g[2];Yo(b in s);let I=s[b].inboundNodes[y].outputTensors;f.push(I[T])}return new e({inputs:m,outputs:f,name:p})}get stateful(){if(this._stateful)throw new U("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(let e of this.layers)if(e.stateful)return!0;return!1}resetStates(){j(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}};function $pe(r,e,t){let n=e.length;if(r==null||Array.isArray(r)&&r.length===0)return e.map(o=>null);if(n===1)return Array.isArray(r)&&r.length===1?r:typeof r=="object"&&e[0]in r?[r[e[0]]]:[r];if(Array.isArray(r)){if(r.length!==n)throw new Error(`Provided ${t} is an array of ${r.length} element(s), but the model has ${n} outputs. Make sure a set of weights is provided for each model output.`);return r}else if(typeof r=="object"&&Object.keys(r).length>0&&typeof r[Object.keys(r)[0]]=="object"){let o=[];return e.forEach(s=>{s in r?o.push(r[s]):o.push(null)}),o}else throw new Error(`The model has multiple (${n}) outputs, so ${t} must be either an array with ${n} elements or an object with ${e} keys. Provided ${t} not understood: ${JSON.stringify(r)}`)}function pk(r,e){return $pe(r,e,"classWeight")}async function ck(r,e,t,n){if(e!=null||n!=null)throw new Error("Support sampleWeight is not implemented yet");if(t!=null){let o=j(()=>{if(r.shape.length===1)return r.clone();if(r.shape.length===2)if(r.shape[1]>1){let a=1;return r.argMax(a)}else{if(r.shape[1]===1)return r.reshape([r.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${r.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}else throw new Error(`Unexpected rank of target (y) tensor (${r.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)}),s=Array.from(await o.data());Be(o);let i=[];return s.forEach(a=>{if(t[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`);i.push(t[a])}),Zt(i,"float32")}else return null}function zz(r,e){return G(r,e)}var Ppe=32;function Gz(r,e){let t,n,o=e;t=o.xs,n=o.ys,x.assert(t!=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 ${e}`);let s=Wz("input",r.inputNames,t),i=Wz("output",r.outputNames,n),a=s[0].shape[0];x.assert(s.length===r.inputs.length,()=>`LayersModel has ${r.inputs.length} inputs, but the dataset provides ${s.length} inputs. (Expected input keys: ${JSON.stringify(r.inputNames)})`),x.assert(i.length===r.outputs.length,()=>`LayersModel has ${r.outputs.length} outputs, but the dataset provides ${i.length} outputs. (Expected output keys: ${JSON.stringify(r.outputNames)})`);for(let l=0;l<s.length;l++)x.assert(s[l].shape[0]===a,()=>`Batch size mismatch: input ${r.inputNames[l]} has ${s[l].shape[0]}; expected ${a} based on input ${r.inputNames[0]}.`);for(let l=0;l<i.length;l++)x.assert(i[l].shape[0]===a,()=>`Batch size mismatch: output ${r.outputNames[l]} has ${i[l].shape[0]}; expected ${a} based on input ${r.inputNames[0]}.`);return{xs:s,ys:i}}function Wz(r,e,t){if(t instanceof rt)return[t];if(Array.isArray(t))return x.assert(t.length===e.length,()=>`Received an array of ${t.length} Tensors, but expected ${e.length} to match the ${r} keys ${e}.`),t;{let n=[];for(let o of e){if(t[o]==null)throw new U(`The feature data generated by the dataset lacks the required ${r} key '${o}'.`);n.push(t[o])}return n}}function Bpe(r){if(r.length===3)throw new Le("Validation with sample weights is not implemented yet.");return{xs:r[0],ys:r[1]}}async function Kz(r,e,t){let n=t.batchesPerEpoch!=null;if(x.assert(r.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),x.assert(t!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),x.assert(t.epochs!=null&&t.epochs>0&&Number.isInteger(t.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${t.epochs}`),x.assert(!n||t.batchesPerEpoch>0&&Number.isInteger(t.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${t.batchesPerEpoch}`),x.assert(t.validationSplit==null,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),r.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");r.isTraining=!0;try{let o=t.validationData!=null,s,i;if(o)if(Vz(t.validationData))x.assert(t.validationBatches==null||t.validationBatches>0&&Number.isInteger(t.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${t.validationBatches}`);else{let g=Bpe(t.validationData);s=g.xs,i=g.ys}let a=r.makeTrainFunction(),l=r.getDedupedMetricsNames(),u;o?u=l.slice().concat(l.map(g=>"val_"+g)):u=l.slice();let p=rk(t.callbacks,t.yieldEvery),c=t.verbose==null?1:t.verbose,{callbackList:m,history:f}=nk(p,c,t.epochs,null,null,Ope(e,t),null,o,u);m.setModel(r),r.history=f,await m.onTrainBegin(),r.stopTraining_=!1;let d=t.initialEpoch==null?0:t.initialEpoch,h=await e.iterator();for(;d<t.epochs;){let g={};await m.onEpochBegin(d);let b=0,y=0;for(n||(h=await e.iterator());n?b<t.batchesPerEpoch:!0;){let T=await h.next();if(n&&T.done){console.warn(`You provided \`batchesPerEpoch\` as ${t.batchesPerEpoch}, but your dataset iterator ran out of data after ${b} batches; interrupting training. Make sure that your dataset can generate at least \`batchesPerEpoch * epochs\` batches (in this case, ${t.batchesPerEpoch*t.epochs} batches). You may need to use the repeat() function when building your dataset.`);break}if(T.value!=null){let{xs:k,ys:I}=Gz(r,T.value),S={};S.batch=y,S.size=k[0].shape[0],await m.onBatchBegin(y,S);let N=[];if(t.classWeight!=null){let O=pk(t.classWeight,r.outputNames);for(let V=0;V<O.length;++V)N.push(await ck(I[V],null,O[V]))}let F=k.concat(I).concat(N),$=a(F);Be(F);for(let O=0;O<l.length;++O){let V=l[O],q=$[O];S[V]=q,er(q)}await m.onBatchEnd(y,S),tk(S),y++,b++}if(n?b>=t.batchesPerEpoch:T.done){if(o){let k;Vz(t.validationData)?k=$t(await r.evaluateDataset(t.validationData,{batches:t.validationBatches})):k=$t(r.evaluate(s,i,{batchSize:t.validationBatchSize==null?Ppe:t.validationBatchSize,verbose:0}));for(let I=0;I<r.metricsNames.length;++I)g[`val_${r.metricsNames[I]}`]=k[I]}break}if(r.stopTraining_)break}if(await m.onEpochEnd(d,g),d++,r.stopTraining_)break}return await m.onTrainEnd(),await r.history.syncData(),r.history}finally{r.isTraining=!1}}function Ope(r,e){let t=null;return e.batchesPerEpoch!=null?t=e.batchesPerEpoch:Number.isFinite(r.size)&&(t=r.size),t}function Vz(r){return typeof r.iterator=="function"}function zpe(r){return typeof r.next=="function"}async function Uz(r,e,t){t=t||{};let n=t.batches!=null,o=r.testFunction,s=[];if(t.verbose>0)throw new Le("Verbose mode is not implemented yet.");x.assert(!n||t.batches>0&&Number.isInteger(t.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(t.batches)}`);let i=zpe(e)?e:await e.iterator(),a=0,l=0;for(;n?l<t.batches:!0;){let u=await i.next();if(s=j(()=>{if(u.value){let{xs:p,ys:c}=Gz(r,u.value),m=p.concat(c),f=j(()=>o(m));if(Be(m),l===0)for(let h=0;h<f.length;++h)s.push(be(0));let d=m[0].shape[0];for(let h=0;h<f.length;++h){let g=f[h],b=s[h];s[h]=j(()=>ne(s[h],G(d,g))),l>0&&Be(b)}Be(f),a+=d,++l}return s}),u.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, ${t.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let u=0;u<s.length;++u){let p=s[u];s[u]=he(s[u],a),Be(p)}return Yr(s)}function mk(r){x.assert(r>0&&Number.isInteger(r),()=>`batchSize is required to be a positive integer, but got ${r}`)}function Td(r,e,t){return r==null?[null]:Array.isArray(r)?r.map(n=>au(n,e,t-e)):au(r,e,t-e)}function fk(r,e){return j(()=>r==null?null:Array.isArray(r)?r.map(t=>fk(t,e)):qT(r,e.dtype==="int32"?e:e.toInt()))}function dk(r,e){let t=[],n=0,o=null;for(;n<r;)o=n+e,o>=r&&(o=r),t.push([n,o]),n=o;return t}async function Gpe(r,e,t,n,o,s,i,a,l,u,p,c,m,f,d){o==null&&(o=32),s==null&&(s=1),p==null&&(p=!0),m==null&&(m=0);let h=!1;if(l!=null&&u!=null&&(h=!0),d!=null&&(h=!0,f==null))throw new U("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");let g=r.checkNumSamples(t,o,f,"steps_per_epoch"),b;g!=null&&(b=Cn(0,g)),i==null&&(i=1);let{callbackList:y,history:T}=nk(a,i,s,m,g,f,o,h,c);y.setModel(r),r.history=T,await y.onTrainBegin(),r.stopTraining_=!1;for(let k=m;k<s;++k){await y.onEpochBegin(k);let I={};if(f!=null)throw new Le("stepsPerEpoch mode is not implemented yet.");{if(p==="batch")throw new Le("batch shuffling is not implemneted yet");p&&x.shuffle(b);let S=Zt(b),N=dk(g,o);for(let F=0;F<N.length;++F){let $={};if(await y.onBatchBegin(F,$),j(()=>{let O=N[F][0],V=N[F][1],q=au(S,O,V-O);$.batch=F,$.size=V-O;let W=fk(t,q),Y=e(W);for(let Z=0;Z<n.length;++Z){let J=n[Z],se=Y[Z];$[J]=se,er(se)}if(F===N.length-1&&h){let Z=r.testLoop(l,u,o);for(let J=0;J<n.length;++J){let se=n[J],ee=Z[J];er(ee),I["val_"+se]=ee}}}),await y.onBatchEnd(F,$),tk($),r.stopTraining_)break}S.dispose()}if(await y.onEpochEnd(k,I),r.stopTraining_)break}return await y.onTrainEnd(),await r.history.syncData(),r.history}async function jz(r,e,t,n={}){if(r.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");r.isTraining=!0;let o,s,i,a,l,u,p;try{let c=n.batchSize==null?32:n.batchSize;mk(c);let m=!1,f=await r.standardizeUserData(e,t,n.sampleWeight,n.classWeight,m,c);o=f[0],s=f[1],p=f[2];let d=!1,h;if(n.validationData!=null&&n.validationData.length>0){if(d=!0,n.validationData.length===2)i=n.validationData[0],a=n.validationData[1];else throw n.validationData.length===3?new Le("validationData including sample weights is not supported yet."):new U(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${n.validationData} is invalid.`);let N=!0,F=await r.standardizeUserData(i,a,null,null,N,c);l=F[0],u=F[1],h=l.concat(u)}else if(n.validationSplit!=null&&n.validationSplit>0&&n.validationSplit<1){d=!0;let N=Math.floor(o[0].shape[0]*(1-n.validationSplit)),F=o[0].shape[0];l=Td(o,N,F),o=Td(o,0,N),u=Td(s,N,F),s=Td(s,0,N),h=l.concat(u)}else n.validationSteps!=null&&(d=!0);let g=o.concat(s).concat(p);r.checkTrainableWeightsConsistency();let b=r.makeTrainFunction(),y=r.getDedupedMetricsNames(),T,k;d?(r.makeTestFunction(),T=r.testFunction,k=y.slice().concat(y.map(N=>"val_"+N))):(T=null,h=[],k=y.slice());let I=rk(n.callbacks,n.yieldEvery);return await Gpe(r,b,g,y,c,n.epochs,n.verbose,I,T,h,n.shuffle,k,n.initialEpoch,null,null)}finally{r.isTraining=!1,pp(o,e),pp(s,t),pp(l,i),pp(u,a),p!=null&&Be(p)}}function VS(r){let e=[];r instanceof rt&&(r=[r]);for(let t=0;t<r.length;++t){let n=r[t];if(n.rank===1)e.push(su(n,1));else{if(n.rank===0)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");e.push(n)}}return e}function pp(r,e){if(r==null)return;let t=[];if(e instanceof rt)t.push(e.id);else if(Array.isArray(e))e.forEach(o=>t.push(o.id));else if(e!=null)for(let o in e){let s=e[o];t.push(s.id)}let n=[];if(r instanceof rt)t.indexOf(r.id)===-1&&n.push(r);else if(Array.isArray(r))r.forEach(o=>{t.indexOf(o.id)===-1&&n.push(o)});else if(r!=null)for(let o in r){let s=r[o];t.indexOf(s.id)===-1&&n.push(s)}n.forEach(o=>{o.isDisposed||o.dispose()})}function Wpe(r){return r instanceof rt}function US(r){return Array.isArray(r)}function Hz(r){return!Wpe(r)&&!US(r)}function qz(r,e,t,n=!0,o=""){if(e==null||e.length===0){if(r!=null){let i=!1;if(US(r)&&r.length>0)i=!0;else if(Hz(r)){for(let a in r)if(r.hasOwnProperty(a)){i=!0;break}}else i=!0;if(i)throw new U(`Error when checking model ${o} expected no data, but got ${r}`)}return[]}if(r==null)return e.map(i=>null);let s;if(Hz(r)){r=r,s=[];for(let i of e){if(r[i]==null)throw new U(`No data provided for "${i}". Need data for each key in: ${e}`);s.push(r[i])}}else if(US(r)){if(r=r,r.length!==e.length)throw new U(`Error when checking model ${o}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${e.length} Tensor(s), but instead got the following list of Tensor(s): ${r}`);s=r}else{if(r=r,e.length>1)throw new U(`The model ${o} expects ${e.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${r.shape}`);s=[r]}if(s=VS(s),t!=null)for(let i=0;i<e.length;++i){if(t[i]==null)continue;let a=s[i];if(a.shape.length!==t[i].length)throw new U(`Error when checking ${o}: expected ${e[i]} to have ${t[i].length} dimension(s). but got array with shape ${a.shape}`);for(let l=0;l<t[i].length;++l){if(l===0&&!n)continue;let u=a.shape[l],p=t[i][l];if(p!=null&&p>=0&&u!==p)throw new U(`Error when checking ${o}: expected ${e[i]} to have shape [${t[i]}], but got array with shape [${a.shape}].`)}}return s}function Kpe(r,e,t){let n=Is(r.map(s=>s.shape[0]));n.sort();let o=Is(e.map(s=>s.shape[0]));if(o.sort(),n.length>1)throw new U(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(r.map(s=>s.shape))}`);if(o.length>1)throw new U(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(s=>s.shape))}`);if(n.length>0&&o.length>0&&!x.arraysEqual(n,o))throw new U(`Input Tensors should have the same number of samples as target Tensors. Found ${n[0]} input sample(s) and ${o[0]} target sample(s).`)}function Vpe(r,e,t){let n=[Mi,xd,rm];for(let o=0;o<r.length;++o){let s=r[o],i=e[o],a=t[o];if(i!=null){if(i===rm&&s.shape[s.shape.length-1]===1)throw new U(`You are passing a target array of shape ${s.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(i)!==-1){let l=s.shape.slice(1),u=a.slice(1);for(let p=0;p<l.length;++p){let c=l[p],m=u[p];if(m!=null&&c!==m)throw new U(`A target Tensor with shape ${s.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 Xz(r,e,t,n=!0,o=""){let s;if(Array.isArray(r)){if(r.length!==e.length)throw new U(`Error when checking model ${o}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${e.length} Tensor(s), but instead got ${r.length} Tensors(s).`);s=r}else{if(e.length>1)throw new U(`The model expects ${e.length} ${o} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(r.shape)}.`);s=[r]}if(t!=null)for(let i=0;i<e.length;++i){if(t[i]==null)continue;let a=s[i];if(a.shape.length!==t[i].length)throw new U(`Error when checking ${o}: expected ${e[i]} to have ${t[i].length} dimension(s), but got array with shape ${JSON.stringify(a.shape)}`);for(let l=0;l<t[i].length;++l){if(l===0&&!n)continue;let u=a.shape[l],p=t[i][l];if(p!=null&&p!==u)throw new U(`Error when checking ${o}: expected ${e[i]} to have shape ${JSON.stringify(t[i])} but got array with shape ${JSON.stringify(a.shape)}.`)}}}function Upe(r,e){if(r==null||Array.isArray(r)&&r.length===0)return e.map(n=>[]);let t;if(typeof r=="string"||typeof r=="function")t=[r];else if(Array.isArray(r)||typeof r=="object")t=r;else throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${r}`);if(Array.isArray(t))return e.map(n=>t);{let n=[];for(let o of e){let s=t.hasOwnProperty(o)?t[o]:[];Array.isArray(s)||(s=[s]),n.push(s)}return n}}var jpe="layers-model",Jo=class extends Zo{constructor(e){super(e);this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new U("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).");$z(this,e,t,n)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=Rz(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof wn))throw new U("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(let i in e.loss)if(this.outputNames.indexOf(i)===-1)throw new U(`Unknown entry in loss dictionary: "${i}". Only expected the following keys: ${this.outputNames}`);for(let i of this.outputNames)e.loss[i]==null&&console.warn(`Output "${i}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${i} during training`),t.push(ok(e.loss[i]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new U(`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}.`);t=e.loss.map(a=>ok(a))}else{let i=ok(e.loss);this.outputs.forEach(a=>{t.push(i)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let i=0;i<this.outputs.length;++i){let a=this.internalOutputShapes[i],l=this.outputNames[i];this.feedOutputNames.push(l),this.feedOutputShapes.push(a),this.feedLossFns.push(this.lossFunctions[i])}let n=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],Wa("loss",()=>{for(let i=0;i<this.outputs.length;++i){if(n.indexOf(i)!==-1)continue;let a=this.lossFunctions[i];this.outputs.length>1&&(this.metricsTensors.push([a,i]),this.metricsNames.push(this.outputNames[i]+"_loss"))}});let o=Upe(e.metrics,this.outputNames),s=(i,a,l)=>{this.outputNames.length>1&&(a=this.outputNames[i]+"_"+a),this.metricsNames.push(a),this.metricsTensors.push([l,i])};Wa("metric",()=>{for(let i=0;i<this.outputs.length;++i){if(n.indexOf(i)!==-1)continue;let a=o[i];(u=>{let p="",c,m,f;for(let d of u){if(typeof d=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(d)!==-1){let g=this.internalOutputShapes[i];g[g.length-1]===1||this.lossFunctions[i]===xd?["accuracy","acc"].indexOf(d)!==-1?m=Zg:["crossentropy","ce"].indexOf(d)!==-1&&(m=sk):this.lossFunctions[i]===yd?["accuracy","acc"].indexOf(d)!==-1?m=ak:["crossentropy","ce"].indexOf(d)!==-1&&(m=zS):["accuracy","acc"].indexOf(d)!==-1?m=Jg:["crossentropy","ce"].indexOf(d)!==-1&&(m=Qg);let b;["accuracy","acc"].indexOf(d)!==-1?b="acc":["crossentropy","ce"].indexOf(d)!==-1&&(b="ce"),f=m,c=p+b}else f=Fz(d),c=p+eb(d);let h;Wa(c,()=>{h=f}),s(i,c,h)}})(a)}}),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){this.collectedTrainableWeights!=null&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(e,t,n={}){let o=n.batchSize==null?32:n.batchSize;mk(o);let s=!0,i=this.standardizeUserDataXY(e,t,s,o);try{let a=i[0].concat(i[1]);this.makeTestFunction();let l=this.testFunction,u=this.testLoop(l,a,o,n.verbose,n.steps);return Yr(u)}finally{pp(i[0],e),pp(i[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),Uz(this,e,t)}checkNumSamples(e,t,n,o="steps"){let s;if(n!=null){if(s=null,t!=null)throw new U(`If ${o} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else if(e!=null)Array.isArray(e)?s=e[0].shape[0]:s=e.shape[0];else throw new U(`Either the input data should have a defined shape, or ${o} shoud be specified.`);return s}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new U("`outputs` is an empty Array, which is not allowed.");let n=Array.isArray(t),o=n?t:[t],s=this.retrieveSymbolicTensors(o),i=new Ua;if(e instanceof rt&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new U(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let l=0;l<this.inputs.length;++l)i.add(this.inputs[l],e[l])}else for(let l of this.inputs){let u=e[l.name];if(u==null)throw new U(`No value is provided for the model's input ${l.name}`);i.add(l,u)}let a=om(s,i);return n?a:a[0]}retrieveSymbolicTensors(e){let t=xs(null,e.length),n=e.length;for(let o of this.layers){let s=Array.isArray(o.output)?o.output:[o.output],i=s.map(a=>a.name);for(let a=0;a<e.length;++a){let l=i.indexOf(e[a]);if(l!==-1&&(t[a]=s[l],n--),n===0)break}if(n===0)break}if(n>0){let o=[];throw t.forEach((s,i)=>{s==null&&o.push(e[i])}),new U(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(o)}`)}return t}predictLoop(e,t=32,n=!1){return j(()=>{let o=this.checkNumSamples(e);if(n)throw new Le("Verbose predictLoop() is not implemented yet.");let s=dk(o,t),i=this.outputs.map(a=>[]);for(let a=0;a<s.length;++a)j(()=>{let u=s[a][0],p=s[a][1],c=Td(e,u,p),m=[];if(Array.isArray(c))for(let d=0;d<c.length;++d)m.push({key:this.inputs[d],value:c[d]});else m.push({key:this.inputs[0],value:c});let f=new Ua(m);return om(this.outputs,f)}).forEach((u,p)=>i[p].push(u));return Yr(i.map(a=>mt(a,0)))})}predict(e,t={}){let n=VS(e);Xz(n,this.inputNames,this.feedInputShapes,!1);try{let o=t.batchSize==null?32:t.batchSize;return mk(o),this.predictLoop(n,o)}finally{pp(n,e)}}predictOnBatch(e){Xz(e,this.inputNames,this.feedInputShapes,!0);let t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,o){if(this.optimizer_==null)throw new _n("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");let s=[];for(let i=0;i<this.feedOutputShapes.length;++i){let a=this.feedOutputShapes[i];this.feedLossFns[i]===yd?s.push(a.slice(0,a.length-1).concat([1])):s.push(a)}if(e=qz(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=qz(t,this.feedOutputNames,s,!1,"target"),Kpe(e,t,null),Vpe(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&o!=null&&o>0&&e[0].shape[0]%o!=0)throw new U(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${o}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,o,s=!0,i){let[a,l]=this.standardizeUserDataXY(e,t,s,i);if(n!=null)throw new Error("sample weight is not supported yet.");let u=null;if(o!=null){let p=pk(o,this.outputNames);u=[];for(let c=0;c<p.length;++c)u.push(await ck(l[c],null,p[c]))}return[a,l,u]}testLoop(e,t,n,o=0,s){return j(()=>{let i=this.checkNumSamples(t,n,s,"steps"),a=[];if(o>0)throw new Le("Verbose mode is not implemented yet.");if(s!=null)throw new Le("steps mode in testLoop() is not implemented yet");{let l=dk(i,n),u=Zt(Cn(0,i));for(let p=0;p<l.length;++p){let c=l[p][0],m=l[p][1],f=au(u,c,m-c),d=fk(t,f),h=e(d);if(p===0)for(let g=0;g<h.length;++g)a.push(be(0));for(let g=0;g<h.length;++g){let b=h[g];a[g]=ne(a[g],G(m-c,b))}}for(let p=0;p<a.length;++p)a[p]=he(a[p],i)}return a})}getDedupedMetricsNames(){let e=this.metricsNames,t=[];for(let n=0;n<e.length;++n){let o=e[n],s=o;NS(e,o)>1&&(s+=`_${NS(e.slice(0,n),o)}`),t.push(s)}return t}makeTrainFunction(){return e=>{let t=[],n=e.slice(0,this.inputs.length),o=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),s=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),i=[],a=()=>{let c=[];for(let h=0;h<this.inputs.length;++h)c.push({key:this.inputs[h],value:n[h]});let m=new Ua(c),f=om(this.outputs,m,{training:!0}),d;for(let h=0;h<this.lossFunctions.length;++h){let b=this.lossFunctions[h](o[h],f[h]);s[h]!=null&&(b=zz(b,s[h]));let y=Ft(b);t.push(y),h===0?d=b:d=ne(d,b)}for(let h=0;h<this.metricsTensors.length;++h){let g;if(this.outputs.length>1&&h<this.outputs.length)g=t[h];else{let b=this.metricsTensors[h][0],y=this.metricsTensors[h][1];g=Ft(b(o[y],f[y]))}er(g),i.push(g)}return d=Ft(d),this.calculateLosses().forEach(h=>{d=ne(d,h)}),d},l=this.collectedTrainableWeights.map(c=>c.read()),u=!0;return[this.optimizer_.minimize(a,u,l)].concat(i)}}makeTestFunction(){this.testFunction=e=>j(()=>{let t=[],n,o=e.slice(0,this.inputs.length),s=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),i=[];for(let u=0;u<this.inputs.length;++u)i.push({key:this.inputs[u],value:o[u]});let a=new Ua(i),l=om(this.outputs,a);for(let u=0;u<this.lossFunctions.length;++u){let p=this.lossFunctions[u],c=Ft(p(s[u],l[u]));u===0?n=c:n=ne(n,c),t.push(n)}for(let u=0;u<this.metricsTensors.length;++u){let p=this.metricsTensors[u][0],c=this.metricsTensors[u][1],m=Ft(p(s[c],l[c]));t.push(m)}return t})}async fit(e,t,n={}){return jz(this,e,t,n)}async fitDataset(e,t){return Kz(this,e,t)}async trainOnBatch(e,t){let n=await this.standardizeUserData(e,t),o=n[0],s=n[1],a=this.makeTrainFunction()(o.concat(s)),l=[];for(let u of a){let p=await u.data();l.push(p[0])}return Be(a),Yr(l)}getNamedWeights(e){let t=[],n=e!=null&&e.trainableOnly,o=n?this.trainableWeights:this.weights,s=this.getWeights(n);for(let i=0;i<o.length;++i)n&&!o[i].trainable||t.push({name:o[i].originalName,tensor:s[i]});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(){let e=super.dispose();if(e.refCountAfterDispose===0&&this.optimizer!=null&&this.isOptimizerOwned){let t=Xh().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-Xh().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=Ts(this.loss);else if(Array.isArray(this.loss)){for(let t of this.loss)if(typeof t!="string")throw new Error("Serialization of non-string loss is not supported.");e=this.loss.map(t=>Ts(t))}else{let t=Object.keys(this.loss);e={};let n=this.loss;for(let o of t)if(typeof n[o]=="string")e[o]=Ts(n[o]);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[Ts(eb(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>Ts(eb(e)));{let e={};for(let t in this.metrics)e[t]=Ts(eb(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.");let t=nm(e.optimizer_config),n=Hn(t),o;if(typeof e.loss=="string")o=nu(e.loss);else if(Array.isArray(e.loss))o=e.loss.map(i=>nu(i));else if(e.loss!=null){o={};for(let i in e.loss)o[i]=nu(e.loss[i])}let s;if(Array.isArray(e.metrics))s=e.metrics.map(i=>nu(i));else if(e.metrics!=null){s={};for(let i in e.metrics)s[i]=nu(e.metrics[i])}this.compile({loss:o,metrics:s,optimizer:n})}async save(e,t){if(typeof e=="string"){let u=fn.getSaveHandlers(e);if(u.length===0)throw new U(`Cannot find any save handlers for URL '${e}'`);if(u.length>1)throw new U(`Found more than one (${u.length}) save handlers for URL '${e}'`);e=u[0]}if(e.save==null)throw new U("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");let n=await fn.encodeWeights(this.getNamedWeights(t)),o=!1,s=null,a={modelTopology:this.toJSON(s,o),format:jpe,generatedBy:`TensorFlow.js tfjs-layers v${tb}`,convertedBy:null};if((t==null?!1:t.includeOptimizer)&&this.optimizer!=null){a.trainingConfig=this.getTrainingConfig();let u="optimizer",{data:p,specs:c}=await fn.encodeWeights(await this.optimizer.getWeights(),u);n.specs.push(...c),n.data=fn.concatenateArrayBuffers([n.data,p])}if(this.userDefinedMetadata!=null){let u=!0;GS(this.userDefinedMetadata,this.name,u),a.userDefinedMetadata=this.userDefinedMetadata}return a.weightData=n.data,a.weightSpecs=n.specs,e.save(a)}setUserDefinedMetadata(e){GS(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};Jo.className="Model";oe.registerClass(Jo);var jS=class extends Jo{};jS.className="Functional";oe.registerClass(jS);async function Yz(r,e){"modelTopology"in r||(r={modelTopology:r}),r=r;let t=r.modelTopology;t.model_config!=null&&(t=t.model_config);let n=nm(t),o=Hn(n,e);if(r.weightsManifest!=null){let s=await fn.loadWeights(r.weightsManifest,r.pathPrefix,o.weights.map(a=>a.originalName)),i={};for(let a of o.weights)i[a.originalName]=s[a.originalName];o.loadWeights(i),Be(s)}return o}async function Zz(r,e){if(e==null&&(e={}),typeof r=="string"){let t=fn.getLoadHandlers(r,e);if(t.length===0)t.push(fn.browserHTTPRequest(r,e));else if(t.length>1)throw new U(`Found more than one (${t.length}) load handlers for URL '${r}'`);r=t[0]}return Hpe(r,void 0,e)}async function Hpe(r,e,t){if(t==null&&(t={}),r.load==null)throw new U("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let n=await r.load(),o=n.modelTopology;o.model_config!=null&&(o=o.model_config);let s=t.strict==null?!0:t.strict,i=n.weightData!=null&&n.weightSpecs!=null&&s,a=Hn(nm(o),e,i),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 U("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");let{modelWeights:u,optimizerWeights:p}=qpe(n.weightData,n.weightSpecs);a.loadWeights(u,s),a.optimizer!=null&&p.length>0&&await a.optimizer.setWeights(p),Be(u),Be(p.map(c=>c.tensor))}return a}function qpe(r,e){let t=fn.decodeWeights(r,e),n={},o=[];return e.forEach(s=>{s.group==="optimizer"?o.push({name:s.name,tensor:t[s.name]}):n[s.name]=t[s.name]}),{modelWeights:n,optimizerWeights:o}}var hk=class extends Jo{constructor(e){super({inputs:[],outputs:[]});if(e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:ap("sequential_"),e.layers!=null)for(let t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some(n=>n<0))throw new U(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){let t=e instanceof hk||e instanceof Jo,n;if(t){if(n=e,n.outputs.length!==1)throw new U("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(n.inputs.length!==1)throw new U("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 U("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");let o=ek({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(o)}if(t)this.outputs=n.outputs,this.inputs=n.inputs;else{if(e.inboundNodes.length!==1)throw new U(`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 U("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=LS(this.outputs[0])}this.inboundNodes=[],new ip({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:xs(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(o=>o.shape),outputShapes:this.outputs[0].shape})}else{let o=e.apply(this.outputs[0]);if(Array.isArray(o))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=[o],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{let 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(it(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 Jo({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(e,t,n=console.log){this.built||this.build(),super.summary(e,t,n)}setWeights(e){this.model==null&&this.build(),this.model.setWeights(e)}evaluate(e,t,n={}){if(!this.built)throw new _n("The model needs to be compiled before being used.");return this.model.evaluate(e,t,n)}async evaluateDataset(e,t){if(!this.built)throw new _n("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return this.model==null&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return this.model==null&&this.build(),this.model.predictOnBatch(e)}compile(e){this.build(),this.model.compile(e),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return this.model==null?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,n={}){if(!this.built)throw new _n("The model needs to be compiled before being used.");return this.model.fit(e,t,n)}async fitDataset(e,t){if(!this.built)throw new _n("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,n={},o=!1){let s,i={};if(t instanceof Array){if(t[0].className==null||t[0].className==="Merge")throw new U("Legacy serialization format not supported yet.");s=t}else x.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."),s=t.layers,delete t.layers,i=t;let a=new e(i);if(!(a instanceof hk))throw new Le(`Sequential.fromConfig called on non-Sequential input: ${a}`);for(let l of s){let p=Hn(l,void 0,o);o&&p.setFastWeightInitDuringBuild(!0),a.add(p)}return a}set stopTraining(e){if(this.model==null)throw new U("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 U("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){let e=[];for(let t of this.layers){let n={};n.className=t.getClassName(),n.config=t.getConfig(),e.push(n)}return{name:this.name,layers:e}}},kd=hk;kd.className="Sequential";oe.registerClass(kd);function Xpe(r){return new Jo(r)}function Ype(r){return new kd(r)}function Zpe(r,e){return e==null&&(e={}),Zz(r,e)}function HS(r){return ek(r)}function Jpe(r,e){Hg.registerCallbackConstructor(r,e)}var qn=class extends oe.Serializable{getConfig(){return{}}},qS=class extends qn{apply(e,t=1){return Tz(e,t)}};qS.className="elu";oe.registerClass(qS);var XS=class extends qn{apply(e){return Pc(e)}};XS.className="selu";oe.registerClass(XS);var YS=class extends qn{apply(e){return hn(e)}};YS.className="relu";oe.registerClass(YS);var ZS=class extends qn{apply(e){return j(()=>Oa(6,hn(e)))}};ZS.className="relu6";oe.registerClass(ZS);var JS=class extends qn{apply(e){return e}};JS.className="linear";oe.registerClass(JS);var QS=class extends qn{apply(e){return dn(e)}};QS.className="sigmoid";oe.registerClass(QS);var eN=class extends qn{apply(e){return Iz(e)}};eN.className="hardSigmoid";oe.registerClass(eN);var tN=class extends qn{apply(e){return ds(e)}};tN.className="softplus";oe.registerClass(tN);var rN=class extends qn{apply(e){return kz(e)}};rN.className="softsign";oe.registerClass(rN);var nN=class extends qn{apply(e){return Fa(e)}};nN.className="tanh";oe.registerClass(nN);var rb=class extends qn{apply(e,t=-1){return Ql(e,t)}};rb.className="softmax";oe.registerClass(rb);var oN=class extends qn{apply(e,t=-1){return Ec(e,t)}};oN.className="logSoftmax";oe.registerClass(oN);var sN=class extends qn{apply(e,t=1){return j(()=>dn(e.mul(t)).mul(e))}};sN.className="swish";oe.registerClass(sN);var aN=class extends qn{apply(e){return j(()=>G(e,Fa(ds(e))))}};aN.className="mish";oe.registerClass(aN);function ja(r){return r.getClassName()}function iN(r,e={}){return Ni(r,oe.SerializationMap.getMap().classNameMap,e,"activation")}function Ha(r){if(r==null){let e={};return e.className="linear",e.config={},iN(e)}if(typeof r=="string"){let e={};return e.className=r,e.config={},iN(e)}else return r instanceof qn?r:iN(r)}function lN(r){if(r!=null&&typeof r!="object")throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${r}`)}var uN=class extends oe.Serializable{},sm=class extends uN{constructor(e){super();lN(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 j(()=>{let t=Rt([1]);return this.hasL1&&(t=ne(t,Te(G(this.l1,Ht(e))))),this.hasL2&&(t=ne(t,Te(G(this.l2,em(e))))),t.asScalar()})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}};sm.className="L1L2";oe.registerClass(sm);function Jz(r){return lN(r),new sm({l1:r!=null?r.l1:null,l2:0})}function Qz(r){return lN(r),new sm({l2:r!=null?r.l2:null,l1:0})}var e3={l1l2:"L1L2"};function vt(r){return nd(r)}function t3(r,e={}){return Ni(r,oe.SerializationMap.getMap().classNameMap,e,"regularizer")}function Pt(r){if(r==null)return null;if(typeof r=="string"){let t={className:r in e3?e3[r]:r,config:{}};return t3(t)}else return r instanceof uN?r:t3(r)}var nb=class extends He{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=Ve(e);let n=hn(e);return this.maxValue!=null&&(n=Gr(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){let e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}};nb.className="ReLU";oe.registerClass(nb);var ob=class extends He{constructor(e){super(e==null?{}:e);this.DEFAULT_ALPHA=.3;e==null&&(e={}),this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){let n=Ve(e);return Hl(n,this.alpha)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};ob.className="LeakyReLU";oe.registerClass(ob);var sb=class extends He{constructor(e){super(e==null?{}:e);this.DEFAULT_ALPHA_INITIALIZER="zeros";if(e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=Dt(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=Pt(e.alphaRegularizer),this.alphaConstraint=ir(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 U(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=it(e);let t=e.slice(1);if(this.sharedAxes!=null)for(let o of this.sharedAxes)t[o-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);let n={};if(this.sharedAxes!=null)for(let o=1;o<e.length;++o)n[o]=e[o];this.inputSpec=[new Vt({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=Ve(e),Zl(e,this.alpha.read())}getConfig(){let e={alphaInitializer:Kt(this.alphaInitializer),alphaRegularizer:vt(this.alphaRegularizer),alphaConstraint:ar(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}};sb.className="PReLU";oe.registerClass(sb);var ab=class extends He{constructor(e){super(e==null?{}:e);this.DEFAULT_ALPHA=1;if(e==null&&(e={}),e.alpha!=null&&e.alpha!==this.DEFAULT_ALPHA)throw new Le(`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){let n=Ve(e);return La(n)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};ab.className="ELU";oe.registerClass(ab);var ib=class extends He{constructor(e){super(e==null?{}:e);this.DEFAULT_THETA=1;e==null&&(e={}),this.theta=e.theta==null?this.DEFAULT_THETA:e.theta}call(e,t){let n=Ve(e);return n.mul(ou(n.greater(this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){let e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}};ib.className="ThresholdedReLU";oe.registerClass(ib);var lb=class extends He{constructor(e){super(e==null?{}:e);this.DEFAULT_AXIS=1;e==null&&(e={}),this.softmax=new rb().apply,this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis}call(e,t){let n=Ve(e);return this.softmax(n,this.axis)}computeOutputShape(e){return e}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};lb.className="Softmax";oe.registerClass(lb);function cp(r,e,t){if(typeof r=="number")return xs(r,e);if(r.length!==e)throw new U(`The ${t} argument must be an integer or tuple of ${e} integers. Received: ${r.length} elements.`);for(let n=0;n<e;++n){let o=r[n];if(!gz(o))throw new U(`The ${t} argument must be an integer or tuple of ${e} integers. Received: ${JSON.stringify(r)} including a non-integer number ${o}`)}return r}function po(r,e,t,n,o=1){if(r==null)return r;let s=e+(e-1)*(o-1),i;return t==="same"?i=r:i=r-s+1,Math.floor((i+n-1)/n)}function qa(r,e,t,n){if(r==null)return null;if(n==="valid")r=r*e+Ka([t-e,0]);else if(n==="same")r=r*e;else throw new U(`Unsupport padding mode: ${n}.`);return r}function ub(r,e){return j(()=>(tr(e),e==="channelsFirst"?nt(r,[0,2,3,1]):r))}function pN(r,e){return j(()=>(tr(e),e==="channelsFirst"?nt(r,[0,2,3,4,1]):r))}function Qpe(r,e,t,n=1,o="valid",s,i=1){return j(()=>{if(s==null&&(s=Kn()),tr(s),r.shape.length!==3)throw new U(`The input of a conv1dWithBias operation should be 3, but is ${r.shape.length} instead.`);if(e.shape.length!==3)throw new U(`The kernel for a conv1dWithBias operation should be 3, but is ${e.shape.length} instead`);if(t!=null&&t.shape.length!==1)throw new U(`The bias for a conv1dWithBias operation should be 1, but is ${e.shape.length} instead`);if(s==="channelsFirst"&&(r=nt(r,[0,2,1])),o==="causal")throw new Le("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let a=wc(r,e,n,o==="same"?"same":"valid","NWC",i);return t!=null&&(a=Un(a,t)),a})}function r3(r,e,t,n=[1,1],o="valid",s,i,a=null){return j(()=>{if(s==null&&(s=Kn()),tr(s),r.rank!==3&&r.rank!==4)throw new U(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${r.rank}.`);if(e.rank!==3&&e.rank!==4)throw new U(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${r.rank}.`);let l=ub(r,s);if(o==="causal")throw new Le("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=bs.conv2d({x:l,filter:e,strides:n,pad:o==="same"?"same":"valid",dilations:i,dataFormat:"NHWC",bias:t,activation:a}),s==="channelsFirst"&&(l=nt(l,[0,3,1,2])),l})}function ece(r,e,t,n=[1,1,1],o="valid",s,i){return j(()=>{if(s==null&&(s=Kn()),tr(s),r.rank!==4&&r.rank!==5)throw new U(`conv3dWithBias expects input to be of rank 4 or 5, but received ${r.rank}.`);if(e.rank!==4&&e.rank!==5)throw new U(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${r.rank}.`);let a=pN(r,s);if(o==="causal")throw new Le("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return a=ig(a,e,n,o==="same"?"same":"valid","NDHWC",i),t!=null&&(a=Un(a,t)),s==="channelsFirst"&&(a=nt(a,[0,4,1,2,3])),a})}var Id=class extends He{constructor(e,t){super(t);this.bias=null;this.DEFAULT_KERNEL_INITIALIZER="glorotNormal";this.DEFAULT_BIAS_INITIALIZER="zeros";if(Id.verifyArgs(t),this.rank=e,kr(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new Le(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=cp(t.kernelSize,e,"kernelSize"),this.strides=cp(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,Vn(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,tr(this.dataFormat),this.activation=Ha(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=Dt(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=ir(t.biasConstraint),this.biasRegularizer=Pt(t.biasRegularizer),this.activityRegularizer=Pt(t.activityRegularizer),this.dilationRate=cp(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new U(`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 U(`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 U(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(Yo("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!KT(e.kernelSize,"number",1,3))throw new U(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){let e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:ja(this.activation),useBias:this.useBias,biasInitializer:Kt(this.biasInitializer),biasRegularizer:vt(this.biasRegularizer),activityRegularizer:vt(this.activityRegularizer),biasConstraint:ar(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}},am=class extends Id{constructor(e,t){super(e,t);this.kernel=null;am.verifyArgs(t),this.filters=t.filters,kr(this.filters,"filters"),this.kernelInitializer=Dt(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=ir(t.kernelConstraint),this.kernelRegularizer=Pt(t.kernelRegularizer)}build(e){e=it(e);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new U(`The channel dimension of the input should be defined. Found ${e[t]}`);let n=e[t],o=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",o,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:n}}],this.built=!0}call(e,t){return j(()=>{e=Ve(e);let n,o=this.bias==null?null:this.bias.read(),s=VT(this.activation.getClassName());if(s!=null&&this.rank===2)n=r3(e,this.kernel.read(),o,this.strides,this.padding,this.dataFormat,this.dilationRate,s);else{if(this.rank===1)n=Qpe(e,this.kernel.read(),o,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)n=r3(e,this.kernel.read(),o,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)n=ece(e,this.kernel.read(),o,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new Le("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(n=this.activation.apply(n))}return n})}computeOutputShape(e){e=it(e);let t=[],n=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let s=0;s<n.length;++s){let i=po(n[s],this.kernelSize[s],this.padding,this.strides[s],typeof this.dilationRate=="number"?this.dilationRate:this.dilationRate[s]);t.push(i)}let o=[e[0]];return this.dataFormat==="channelsLast"?(o=o.concat(t),o.push(this.filters)):(o.push(this.filters),o=o.concat(t)),o}getConfig(){let e={filters:this.filters,kernelInitializer:Kt(this.kernelInitializer),kernelRegularizer:vt(this.kernelRegularizer),kernelConstraint:ar(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 U(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}},mN=class extends am{constructor(e){super(2,e);mN.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!KT(e.kernelSize,"number",1,2))throw new U(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}},vd=mN;vd.className="Conv2D";oe.registerClass(vd);var fN=class extends am{constructor(e){super(3,e);fN.verifyArgs(e)}getConfig(){let 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 U(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}},wd=fN;wd.className="Conv3D";oe.registerClass(wd);var pb=class extends vd{constructor(e){super(e);if(this.inputSpec=[new Vt({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new U(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=it(e),e.length!==4)throw new U("Input should have rank 4; Received input shape: "+JSON.stringify(e));let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new U("The channel dimension of the inputs should be defined. Found `None`.");let n=e[t],o=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",o,"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 Vt({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return j(()=>{let n=Ve(e);if(n.shape.length!==4)throw new U(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let o=n.shape,s=o[0],i,a;this.dataFormat==="channelsFirst"?(i=2,a=3):(i=1,a=2);let l=o[i],u=o[a],p=this.kernelSize[0],c=this.kernelSize[1],m=this.strides[0],f=this.strides[1],d=qa(l,m,p,this.padding),h=qa(u,f,c,this.padding),g=[s,d,h,this.filters];this.dataFormat!=="channelsLast"&&(n=nt(n,[0,2,3,1]));let b=_c(n,this.kernel.read(),g,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(b=nt(b,[0,3,1,2])),this.bias!=null&&(b=Un(b,this.bias.read(),this.dataFormat)),this.activation!=null&&(b=this.activation.apply(b)),b})}computeOutputShape(e){e=it(e);let t=e.slice(),n,o,s;this.dataFormat==="channelsFirst"?(n=1,o=2,s=3):(n=3,o=1,s=2);let i=this.kernelSize[0],a=this.kernelSize[1],l=this.strides[0],u=this.strides[1];return t[n]=this.filters,t[o]=qa(t[o],l,i,this.padding),t[s]=qa(t[s],u,a,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};pb.className="Conv2DTranspose";oe.registerClass(pb);var cb=class extends wd{constructor(e){super(e);if(this.inputSpec=[new Vt({ndim:5})],this.padding!=="same"&&this.padding!=="valid")throw new U(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=it(e),e.length!==5)throw new U("Input should have rank 5; Received input shape: "+JSON.stringify(e));let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new U("The channel dimension of the inputs should be defined. Found `None`.");let n=e[t],o=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",o,"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 Vt({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return j(()=>{let n=Ve(e);if(n.shape.length!==5)throw new U(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let o=n.shape,s=o[0],i,a,l;this.dataFormat==="channelsFirst"?(l=2,i=3,a=4):(l=1,i=2,a=3);let u=o[l],p=o[i],c=o[a],m=this.kernelSize[0],f=this.kernelSize[1],d=this.kernelSize[2],h=this.strides[0],g=this.strides[1],b=this.strides[2],y=qa(u,h,m,this.padding),T=qa(p,g,f,this.padding),k=qa(c,b,d,this.padding),I=[s,y,T,k,this.filters];this.dataFormat!=="channelsLast"&&(n=nt(n,[0,2,3,4,1]));let S=ZC(n,this.kernel.read(),I,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(S=nt(S,[0,4,1,2,3])),this.bias!==null&&(S=Un(S,this.bias.read(),this.dataFormat)),this.activation!==null&&(S=this.activation.apply(S)),S})}computeOutputShape(e){e=it(e);let t=e.slice(),n,o,s,i;this.dataFormat==="channelsFirst"?(n=1,o=2,s=3,i=4):(n=4,o=1,s=2,i=3);let a=this.kernelSize[0],l=this.kernelSize[1],u=this.kernelSize[2],p=this.strides[0],c=this.strides[1],m=this.strides[2];return t[n]=this.filters,t[o]=qa(t[o],p,a,this.padding),t[s]=qa(t[s],c,l,this.padding),t[i]=qa(t[i],m,u,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};cb.className="Conv3DTranspose";oe.registerClass(cb);var cN=class extends am{constructor(e,t){super(e,t);this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform";this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform";this.depthwiseKernel=null;this.pointwiseKernel=null;if(t.filters==null)throw new U("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new U("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 U(`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=Dt(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=Pt(t.depthwiseRegularizer),this.depthwiseConstraint=ir(t.depthwiseConstraint),this.pointwiseInitializer=Dt(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Pt(t.pointwiseRegularizer),this.pointwiseConstraint=ir(t.pointwiseConstraint)}build(e){if(e=it(e),e.length<this.rank+2)throw new U(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank+2}, but received input shape: ${JSON.stringify(e)}`);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null||e[t]<0)throw new U(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);let n=e[t],o=this.kernelSize.concat([n,this.depthMultiplier]),s=[];for(let a=0;a<this.rank;++a)s.push(1);s.push(n*this.depthMultiplier,this.filters);let i=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",o,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,i,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",s,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,i,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,i,this.biasConstraint):this.bias=null,this.inputSpec=[new Vt({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return j(()=>{e=Ve(e);let n;if(this.rank===1)throw new Le("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=nt(e,[0,2,3,1])),n=kg(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(n=Un(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),this.dataFormat==="channelsFirst"&&(n=nt(n,[0,3,1,2])),n})}getConfig(){let e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=Kt(this.depthwiseInitializer),e.pointwiseInitializer=Kt(this.pointwiseInitializer),e.depthwiseRegularizer=vt(this.depthwiseRegularizer),e.pointwiseRegularizer=vt(this.pointwiseRegularizer),e.depthwiseConstraint=ar(this.depthwiseConstraint),e.pointwiseConstraint=ar(this.pointwiseConstraint),e}};cN.className="SeparableConv";var mb=class extends cN{constructor(e){super(2,e)}};mb.className="SeparableConv2D";oe.registerClass(mb);var dN=class extends am{constructor(e){super(1,e);dN.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){let e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!KT(e.kernelSize,"number",1,1))throw new U(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}},fb=dN;fb.className="Conv1D";oe.registerClass(fb);var db=class extends He{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 j(()=>{if(e=Ve(e),this.dataFormat==="channelsLast"){let n=Bg(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Bg(n,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let n=Bg(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Bg(n,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}})}getConfig(){let e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};db.className="Cropping2D";oe.registerClass(db);var hb=class extends He{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,tr(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,fz(this.interpolation)}computeOutputShape(e){if(this.dataFormat==="channelsFirst"){let t=e[2]==null?null:this.size[0]*e[2],n=e[3]==null?null:this.size[1]*e[3];return[e[0],e[1],t,n]}else{let t=e[1]==null?null:this.size[0]*e[1],n=e[2]==null?null:this.size[1]*e[2];return[e[0],t,n,e[3]]}}call(e,t){return j(()=>{let n=Ve(e),o=n.shape;if(this.dataFormat==="channelsFirst"){n=nt(n,[0,2,3,1]);let s=this.size[0]*o[2],i=this.size[1]*o[3],a=this.interpolation==="nearest"?n.resizeNearestNeighbor([s,i]):n.resizeBilinear([s,i]);return nt(a,[0,3,1,2])}else{let s=this.size[0]*o[1],i=this.size[1]*o[2];return this.interpolation==="nearest"?n.resizeNearestNeighbor([s,i]):n.resizeBilinear([s,i])}})}getConfig(){let e={size:this.size,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};hb.className="UpSampling2D";oe.registerClass(hb);function tce(r,e,t=[1,1],n="valid",o,s){return j(()=>{o==null&&(o=Kn()),tr(o);let i=ub(r,o);if(r.rank!==4)throw new U(`Input for depthwiseConv2d is required to be 4-D, but is instead ${r.rank}-D`);if(e.rank!==4)throw new U(`depthwiseKernel is required to be 4-D, but is instead ${e.rank}-D`);return i=Ra(i,e,t,n==="same"?"same":"valid","NHWC",s),o==="channelsFirst"&&(i=nt(i,[0,3,1,2])),i})}var gb=class extends Id{constructor(e){super(2,e);this.depthwiseKernel=null;this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=Dt(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=ir(e.depthwiseConstraint),this.depthwiseRegularizer=Pt(e.depthwiseRegularizer)}build(e){if(e=it(e),e.length<4)throw new U(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);let t=this.dataFormat==="channelsFirst"?1:3;if(e[t]==null||e[t]<0)throw new U(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);let n=e[t],o=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",o,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return j(()=>{e=Ve(e);let n=tce(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(n=Un(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),n})}computeOutputShape(e){e=it(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],o=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,s=po(t,this.kernelSize[0],this.padding,this.strides[0]),i=po(n,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],o,s,i]:[e[0],s,i,o]}getConfig(){let e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=Kt(this.depthwiseInitializer),e.depthwiseRegularizer=vt(this.depthwiseRegularizer),e.depthwiseConstraint=ar(this.depthwiseRegularizer),e}};gb.className="DepthwiseConv2D";oe.registerClass(gb);function hN(r,e,t,n){if(Array.isArray(r)){if(e!=null||t!=null)throw new U("When inputs is an array, neither initialState or constants should be provided");n!=null&&(t=r.slice(r.length-n,r.length),r=r.slice(0,r.length-n)),r.length>1&&(e=r.slice(1,r.length)),r=r[0]}function o(s){return s==null||Array.isArray(s)?s:[s]}return e=o(e),t=o(t),{inputs:r,initialState:e,constants:t}}function gN(r,e,t,n=!1,o,s,i=!1,a=!1){return j(()=>{let l=e.shape.length;if(l<3)throw new U(`Input should be at least 3D, but is ${l}D.`);let u=[1,0].concat(Cn(2,l));if(e=nt(e,u),s!=null)throw new Le("The rnn() functoin of the deeplearn.js backend does not support constants yet.");i&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),o!=null&&(o=o.asType("bool").asType("float32"),o.rank===l-1&&(o=Wr(o,-1)),o=nt(o,u)),n&&(e=wr(e,0),o!=null&&(o=wr(o,0)));let p=[],c,m=t,f=e.shape[0],d=Vr(e),h;o!=null&&(h=Vr(o));for(let b=0;b<f;++b){let y=d[b],T=j(()=>r(y,m));if(o==null)c=T[0],m=T[1];else{let k=j(()=>{let I=h[b],S=Br(I).sub(I),N=T[0].mul(I).add(m[0].mul(S)),F=m.map(($,O)=>T[1][O].mul(I).add($.mul(S)));return{output:N,newStates:F}});c=k.output,m=k.newStates}a&&p.push(c)}let g;return a&&(g=xr(p,1)),[c,g,m]})}var bN=class extends He{constructor(e){super(e);let t;if(e.cell==null)throw new U("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new Sd({cells:e.cell}):t=e.cell,t.stateSize==null)throw new U("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 Vt({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;return Cn(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){JT(e)&&(e=e[0]),e=e;let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);let n=t[0],o;if(this.returnSequences?o=[e[0],e[1],n]:o=[e[0],n],this.returnState){let s=[];for(let i of t)s.push([e[0],i]);return[o].concat(s)}else return o}computeMask(e,t){return j(()=>{Array.isArray(t)&&(t=t[0]);let n=this.returnSequences?t:null;if(this.returnState){let o=this.states.map(s=>null);return[n].concat(o)}else return n})}get states(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let n=0;n<e;++n)t.push(null);return t}else return this.states_}set states(e){this.states_=e}build(e){let t=null;if(this.numConstants!=null)throw new Le("Constants support is not implemented in RNN yet.");JT(e)&&(e=e[0]),e=e;let n=this.stateful?e[0]:null,o=e.slice(2);this.inputSpec[0]=new Vt({shape:[n,null,...o]});let s=[e[0]].concat(e.slice(2));if(t!=null)throw new Le("Constants support is not implemented in RNN yet.");this.cell.build(s);let i;if(Array.isArray(this.cell.stateSize)?i=this.cell.stateSize:i=[this.cell.stateSize],this.stateSpec!=null){if(!x.arraysEqual(this.stateSpec.map(a=>a.shape[a.shape.length-1]),i))throw new U(`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=i.map(a=>new Vt({shape:[null,a]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){j(()=>{if(!this.stateful)throw new vo("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape[0];if(n==null)throw new U("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(o=>Rt([n,o])):this.states_=[Rt([n,this.cell.stateSize])];else if(e==null)Be(this.states_),this.keptStates!=null&&(Be(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(o=>Rt([n,o])):this.states_[0]=Rt([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new U(`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()):Be(this.states_);for(let o=0;o<this.states_.length;++o){let s=e[o],i=Array.isArray(this.cell.stateSize)?this.cell.stateSize[o]:this.cell.stateSize,a=[n,i];if(!x.arraysEqual(s.shape,a))throw new U(`State ${o} is incompatible with layer ${this.name}: expected shape=${a}, received shape=${s.shape}`);this.states_[o]=s}}this.states_=this.states_.map(o=>er(o.clone()))})}apply(e,t){let n=t==null?null:t.initialState,o=t==null?null:t.constants;t==null&&(t={});let s=hN(e,n,o,this.numConstants);e=s.inputs,n=s.initialState,o=s.constants;let i=[],a=[];if(n!=null){t.initialState=n,i=i.concat(n),this.stateSpec=[];for(let u of n)this.stateSpec.push(new Vt({shape:u.shape}));a=a.concat(this.stateSpec)}if(o!=null&&(t.constants=o,i=i.concat(o),this.numConstants=o.length),i[0]instanceof jn){let u=[e].concat(i),p=this.inputSpec.concat(a),c=this.inputSpec;this.inputSpec=p;let m=super.apply(u,t);return this.inputSpec=c,m}else return super.apply(e,t)}call(e,t){return j(()=>{let n=t==null?null:t.mask,o=t==null?null:t.training,s=t==null?null:t.initialState;e=Ve(e),s==null&&(this.stateful?s=this.states_:s=this.getInitialState(e));let i=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(s.length!==i)throw new U(`RNN Layer has ${i} state(s) but was passed ${s.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");let a={training:o},u=gN((d,h)=>{let g=this.cell.call([d].concat(h),a);return[g[0],g.slice(1)]},e,s,this.goBackwards,n,null,this.unroll,this.returnSequences),p=u[0],c=u[1],m=u[2];this.stateful&&this.resetStates(m,o);let f=this.returnSequences?c:p;return this.returnState?[f].concat(m):f})}getInitialState(e){return j(()=>{let t=Rt(e.shape);return t=Te(t,[1,2]),t=su(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(n=>n>1?HT(t,[1,n]):t):this.cell.stateSize>1?[HT(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(){let 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);let n=this.cell.getConfig();return this.getClassName()===bN.className&&(t.cell={className:this.cell.getClassName(),config:n}),{...n,...e,...t}}static fromConfig(e,t,n={}){let o=t.cell,s=Hn(o,n);return new e(Object.assign(t,{cell:s}))}},_s=bN;_s.className="RNN";oe.registerClass(_s);var mp=class extends He{},_d=class extends mp{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,kr(this.units,"units"),this.activation=Ha(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Dt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Dt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Dt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Pt(e.kernelRegularizer),this.recurrentRegularizer=Pt(e.recurrentRegularizer),this.biasRegularizer=Pt(e.biasRegularizer),this.kernelConstraint=ir(e.kernelConstraint),this.recurrentConstraint=ir(e.recurrentConstraint),this.biasConstraint=ir(e.biasConstraint),this.dropout=Qc([1,Ka([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Qc([1,Ka([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=it(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 j(()=>{if(e=e,e.length!==2)throw new U(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];let o=t.training==null?!1:t.training;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=iu({ones:()=>Br(e),rate:this.dropout,training:o})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=iu({ones:()=>Br(n),rate:this.recurrentDropout,training:o}));let s,i=this.dropoutMask,a=this.recurrentDropoutMask;i!=null?s=ws(G(e,i),this.kernel.read()):s=ws(e,this.kernel.read()),this.bias!=null&&(s=Un(s,this.bias.read())),a!=null&&(n=G(n,a));let l=ne(s,ws(n,this.recurrentKernel.read()));return this.activation!=null&&(l=this.activation.apply(l)),[l,l]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:ja(this.activation),useBias:this.useBias,kernelInitializer:Kt(this.kernelInitializer),recurrentInitializer:Kt(this.recurrentInitializer),biasInitializer:Kt(this.biasInitializer),kernelRegularizer:vt(this.kernelRegularizer),recurrentRegularizer:vt(this.recurrentRegularizer),biasRegularizer:vt(this.biasRegularizer),activityRegularizer:vt(this.activityRegularizer),kernelConstraint:ar(this.kernelConstraint),recurrentConstraint:ar(this.recurrentConstraint),biasConstraint:ar(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return{...e,...t}}};_d.className="SimpleRNNCell";oe.registerClass(_d);var bb=class extends _s{constructor(e){e.cell=new _d(e),super(e)}call(e,t){return j(()=>{this.cell.dropoutMask!=null&&(Be(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Be(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,o=t==null?null:t.training,s=t==null?null:t.initialState;return super.call(e,{mask:n,training:o,initialState:s})})}static fromConfig(e,t){return new e(t)}};bb.className="SimpleRNN";oe.registerClass(bb);var Cd=class extends mp{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";if(e.resetAfter)throw new U("GRUCell does not support reset_after parameter set to true.");this.units=e.units,kr(this.units,"units"),this.activation=Ha(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Ha(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Dt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Dt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Dt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Pt(e.kernelRegularizer),this.recurrentRegularizer=Pt(e.recurrentRegularizer),this.biasRegularizer=Pt(e.biasRegularizer),this.kernelConstraint=ir(e.kernelConstraint),this.recurrentConstraint=ir(e.recurrentConstraint),this.biasConstraint=ir(e.biasConstraint),this.dropout=Qc([1,Ka([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Qc([1,Ka([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=it(e);let 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 j(()=>{if(e=e,e.length!==2)throw new U(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training==null?!1:t.training,o=e[1];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=iu({ones:()=>Br(e),rate:this.dropout,training:n,count:3})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=iu({ones:()=>Br(o),rate:this.recurrentDropout,training:n,count:3}));let s=this.dropoutMask,i=this.recurrentDropoutMask,a,l,u;0<this.dropout&&this.dropout<1&&(e=G(e,s[0]));let p=ws(e,this.kernel.read());this.useBias&&(p=Un(p,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(o=G(o,i[0]));let c=this.recurrentKernel.read(),[m,f]=Rr(c,[2*this.units,this.units],c.rank-1),d=ws(o,m),[h,g,b]=Rr(p,3,p.rank-1),[y,T]=Rr(d,2,d.rank-1);a=this.recurrentActivation.apply(ne(h,y)),l=this.recurrentActivation.apply(ne(g,T));let k=ws(G(l,o),f);u=this.activation.apply(ne(b,k));let I=ne(G(a,o),G(ne(1,st(a)),u));return[I,I]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:ja(this.activation),recurrentActivation:ja(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Kt(this.kernelInitializer),recurrentInitializer:Kt(this.recurrentInitializer),biasInitializer:Kt(this.biasInitializer),kernelRegularizer:vt(this.kernelRegularizer),recurrentRegularizer:vt(this.recurrentRegularizer),biasRegularizer:vt(this.biasRegularizer),activityRegularizer:vt(this.activityRegularizer),kernelConstraint:ar(this.kernelConstraint),recurrentConstraint:ar(this.recurrentConstraint),biasConstraint:ar(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return{...e,...t}}};Cd.className="GRUCell";oe.registerClass(Cd);var yb=class extends _s{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 Cd(e),super(e)}call(e,t){return j(()=>{this.cell.dropoutMask!=null&&(Be(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Be(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,o=t==null?null:t.training,s=t==null?null:t.initialState;return super.call(e,{mask:n,training:o,initialState:s})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};yb.className="GRU";oe.registerClass(yb);var fp=class extends mp{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,kr(this.units,"units"),this.activation=Ha(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Ha(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Dt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Dt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Dt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=Pt(e.kernelRegularizer),this.recurrentRegularizer=Pt(e.recurrentRegularizer),this.biasRegularizer=Pt(e.biasRegularizer),this.kernelConstraint=ir(e.kernelConstraint),this.recurrentConstraint=ir(e.recurrentConstraint),this.biasConstraint=ir(e.biasConstraint),this.dropout=Qc([1,Ka([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Qc([1,Ka([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 o;e=it(e);let t=e[e.length-1];this.kernel=this.addWeight("kernel",[t,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){let s=this.biasInitializer,i=this.units;n=new(o=class extends uo{apply(l,u){let p=s.apply([i]),c=new tm().apply([i]),m=s.apply([i*2]);return FS(FS(p,c),m)}},o.className="CustomInit",o)}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 j(()=>{let n=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new U(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let o=e[1],s=e[2];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=iu({ones:()=>Br(e),rate:this.dropout,training:n,count:4})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=iu({ones:()=>Br(o),rate:this.recurrentDropout,training:n,count:4}));let i=this.dropoutMask,a=this.recurrentDropoutMask,l,u,p,c;0<this.dropout&&this.dropout<1&&(e=G(e,i[0]));let m=ws(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(o=G(o,a[0])),m=ne(m,ws(o,this.recurrentKernel.read())),this.useBias&&(m=Un(m,this.bias.read()));let[f,d,h,g]=Rr(m,4,m.rank-1);l=this.recurrentActivation.apply(f),u=this.recurrentActivation.apply(d),p=ne(G(u,s),G(l,this.activation.apply(h))),c=this.recurrentActivation.apply(g);let b=G(c,this.activation.apply(p));return[b,b,p]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:ja(this.activation),recurrentActivation:ja(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Kt(this.kernelInitializer),recurrentInitializer:Kt(this.recurrentInitializer),biasInitializer:Kt(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:vt(this.kernelRegularizer),recurrentRegularizer:vt(this.recurrentRegularizer),biasRegularizer:vt(this.biasRegularizer),activityRegularizer:vt(this.activityRegularizer),kernelConstraint:ar(this.kernelConstraint),recurrentConstraint:ar(this.recurrentConstraint),biasConstraint:ar(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return{...e,...t}}};fp.className="LSTMCell";oe.registerClass(fp);var xb=class extends _s{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 fp(e),super(e)}call(e,t){return j(()=>{this.cell.dropoutMask!=null&&(Be(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Be(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,o=t==null?null:t.training,s=t==null?null:t.initialState;return super.call(e,{mask:n,training:o,initialState:s})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};xb.className="LSTM";oe.registerClass(xb);var Sd=class extends mp{constructor(e){super(e);this.cells=e.cells}get stateSize(){let e=[];for(let t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return j(()=>{e=e;let n=e.slice(1),o=[];for(let a of this.cells.slice().reverse())Array.isArray(a.stateSize)?o.push(n.splice(0,a.stateSize.length)):o.push(n.splice(0,1));o.reverse();let s=[],i;for(let a=0;a<this.cells.length;++a){let l=this.cells[a];n=o[a],a===0?i=[e[0]].concat(n):i=[i[0]].concat(n),i=l.call(i,t),s.push(i.slice(1))}n=[];for(let a of s.slice().reverse())n.push(...a);return[i[0]].concat(n)})}build(e){JT(e)&&(e=e[0]),e=e;let t;this.cells.forEach((n,o)=>{Wa(`RNNCell_${o}`,()=>{n.build(e),Array.isArray(n.stateSize)?t=n.stateSize[0]:t=n.stateSize,e=[e[0],t]})}),this.built=!0}getConfig(){let e=super.getConfig(),t=s=>({className:s.getClassName(),config:s.getConfig()}),o={cells:this.cells.map(t)};return{...e,...o}}static fromConfig(e,t,n={}){let o=[];for(let s of t.cells)o.push(Hn(s,n));return new e({cells:o})}get trainableWeights(){if(!this.trainable)return[];let e=[];for(let t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let n of this.cells)t.push(...n.trainableWeights);return t.concat(e)}return e}getWeights(){let e=[];for(let t of this.cells)e.push(...t.weights);return jg(e)}setWeights(e){let t=[];for(let n of this.cells){let o=n.weights.length,s=e.splice(o);for(let i=0;i<n.weights.length;++i)t.push([n.weights[i],s[i]])}gd(t)}};Sd.className="StackedRNNCells";oe.registerClass(Sd);function iu(r){let{ones:e,rate:t,training:n=!1,count:o=1}=r,s=()=>XT(e(),t),i=()=>sp(s,e,n);return!o||o<=1?er(i().clone()):Array(o).fill(void 0).map(i).map(l=>er(l.clone()))}var yN=class extends _s{constructor(e){if(e.unroll)throw new Le("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Le("It is not possible at the moment to stack convolutional cells.");super(e);this.inputSpec=[new Vt({ndim:5})]}call(e,t){return j(()=>{if(this.cell.dropoutMask!=null&&(Be(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Be(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new U("ConvRNN2D cell does not support constants");let n=t==null?null:t.mask,o=t==null?null:t.training,s=t==null?null:t.initialState;return super.call(e,{mask:n,training:o,initialState:s})})}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 j(()=>{let{stateSize:t}=this.cell,n=e.shape,o=this.computeSingleOutputShape(n),s=[o[0],...o.slice(2)],i=Rt(s);return Array.isArray(t)?Array(t.length).fill(i):[i]})}resetStates(e,t=!1){j(()=>{if(!this.stateful)throw new vo("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape,o=this.computeSingleOutputShape(n),s=[o[0],...o.slice(2)];if(n[0]==null)throw new U("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(()=>Rt(s)):this.states_=[Rt(s)];else if(e==null)Be(this.states_),this.keptStates!=null&&(Be(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>Rt(s)):this.states_[0]=Rt(s);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new U(`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()):Be(this.states_);for(let a=0;a<this.states_.length;++a){let l=e[a],u=s;if(!x.arraysEqual(l.shape,u))throw new U(`State ${a} is incompatible with layer ${this.name}: expected shape=${u}, received shape=${l.shape}`);this.states_[a]=l}}this.states_=this.states_.map(a=>er(a.clone()))})}computeSingleOutputShape(e){let{dataFormat:t,filters:n,kernelSize:o,padding:s,strides:i,dilationRate:a}=this.cell,l=t==="channelsFirst",u=e[l?3:2],p=e[l?4:3],c=po(u,o[0],s,i[0],a[0]),m=po(p,o[1],s,i[1],a[1]);return[...e.slice(0,2),...l?[n,c,m]:[c,m,n]]}};yN.className="ConvRNN2D";var Nd=class extends fp{constructor(e){let{filters:t,kernelSize:n,strides:o,padding:s,dataFormat:i,dilationRate:a}=e;super({...e,units:t});this.filters=t,kr(this.filters,"filters"),this.kernelSize=cp(n,2,"kernelSize"),this.kernelSize.forEach(l=>kr(l,"kernelSize")),this.strides=cp(o||1,2,"strides"),this.strides.forEach(l=>kr(l,"strides")),this.padding=s||"valid",Vn(this.padding),this.dataFormat=i||"channelsLast",tr(this.dataFormat),this.dilationRate=cp(a||1,2,"dilationRate"),this.dilationRate.forEach(l=>kr(l,"dilationRate"))}build(e){var a;e=it(e);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new U(`The channel dimension of the input should be defined. Found ${e[t]}`);let n=e[t],o=4,s=this.kernelSize.concat([n,this.filters*o]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);let i=this.kernelSize.concat([this.filters,this.filters*o]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",i,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let l;if(this.unitForgetBias){let u=this.biasInitializer,p=this.filters;l=new(a=class extends uo{apply(m,f){let d=u.apply([p]),h=on([p]),g=u.apply([p*2]);return ad([d,h,g])}},a.className="CustomInit",a)}else l=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*o],null,l,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return j(()=>{if(e.length!==3)throw new U(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training||!1,o=e[0],s=e[1],i=e[2],a=4;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=iu({ones:()=>Br(o),rate:this.dropout,training:n,count:a}));let l=this.dropoutMask,u=(ae,ce,ye)=>!ce||!ce[ye]?ae:G(ce[ye],ae),p=u(o,l,0),c=u(o,l,1),m=u(o,l,2),f=u(o,l,3);0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=iu({ones:()=>Br(s),rate:this.recurrentDropout,training:n,count:a}));let d=this.recurrentDropoutMask,h=u(s,d,0),g=u(s,d,1),b=u(s,d,2),y=u(s,d,3),T=3,[k,I,S,N]=Rr(this.kernel.read(),a,T),[F,$,O,V]=this.useBias?Rr(this.bias.read(),a):[null,null,null,null];p=this.inputConv(p,k,F,this.padding),c=this.inputConv(c,I,$,this.padding),m=this.inputConv(m,S,O,this.padding),f=this.inputConv(f,N,V,this.padding);let[q,W,Y,Z]=Rr(this.recurrentKernel.read(),a,T);h=this.recurrentConv(h,q),g=this.recurrentConv(g,W),b=this.recurrentConv(b,Y),y=this.recurrentConv(y,Z);let J=this.recurrentActivation.apply(ne(p,h)),se=this.recurrentActivation.apply(ne(c,g)),ee=ne(G(se,i),G(J,this.activation.apply(ne(m,b)))),le=G(this.recurrentActivation.apply(ne(f,y)),this.activation.apply(ee));return[le,le,ee]})}getConfig(){let{units:e,...t}=super.getConfig(),n={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return{...t,...n}}inputConv(e,t,n,o){let s=zn(e,t,this.strides,o||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return n?Un(s,n,this.dataFormat):s}recurrentConv(e,t){return zn(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};Nd.className="ConvLSTM2DCell";oe.registerClass(Nd);var Tb=class extends yN{constructor(e){let t=new Nd(e);super({...e,cell:t})}static fromConfig(e,t){return new e(t)}};Tb.className="ConvLSTM2D";oe.registerClass(Tb);var Ad=class extends He{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;let t=e.shape,n=[];for(let o=0;o<this.noiseShape.length;++o)n.push(this.noiseShape[o]==null?t[o]:this.noiseShape[o]);return n}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ve(e);if(0<this.rate&&this.rate<1){let o=t.training==null?!1:t.training,s=this.getNoiseShape(n);return sp(()=>XT(n,this.rate,s,this.seed),()=>n,o)}return e})}getConfig(){let e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}};Ad.className="Dropout";oe.registerClass(Ad);var kb=class extends Ad{constructor(e){super(e);this.inputSpec=[{ndim:3}]}getNoiseShape(e){let t=e.shape;return[t[0],1,t[2]]}};kb.className="SpatialDropout1D";oe.registerClass(kb);var Ib=class extends He{constructor(e){super(e);this.activation=null;this.useBias=!0;this.kernel=null;this.bias=null;this.DEFAULT_KERNEL_INITIALIZER="glorotNormal";this.DEFAULT_BIAS_INITIALIZER="zeros";if(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,kr(this.units,"units"),this.activation=Ha(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=Dt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=Dt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=ir(e.kernelConstraint),this.biasConstraint=ir(e.biasConstraint),this.kernelRegularizer=Pt(e.kernelRegularizer),this.biasRegularizer=Pt(e.biasRegularizer),this.activityRegularizer=Pt(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=it(e);let 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=it(e);let t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ve(e),o=VT(this.activation.getClassName()),s;return o!=null?s=ws(n,this.kernel.read(),o,this.bias?this.bias.read():null):(s=ws(n,this.kernel.read()),this.bias!=null&&(s=Un(s,this.bias.read())),this.activation!=null&&(s=this.activation.apply(s))),s})}getConfig(){let e={units:this.units,activation:ja(this.activation),useBias:this.useBias,kernelInitializer:Kt(this.kernelInitializer),biasInitializer:Kt(this.biasInitializer),kernelRegularizer:vt(this.kernelRegularizer),biasRegularizer:vt(this.biasRegularizer),activityRegularizer:vt(this.activityRegularizer),kernelConstraint:ar(this.kernelConstraint),biasConstraint:ar(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}};Ib.className="Dense";oe.registerClass(Ib);var vb=class extends He{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=it(e);for(let t of e.slice(1))if(t==null)throw new U(`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],vs(e,1)]}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ve(e);if(this.dataFormat==="channelsFirst"&&n.rank>1){let o=[0];for(let s=2;s<n.rank;++s)o.push(s);o.push(1),n=n.transpose(o)}return xz(n)})}getConfig(){let e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);let t=super.getConfig();return Object.assign(e,t),e}};vb.className="Flatten";oe.registerClass(vb);var wb=class extends He{constructor(e){super(e);this.supportsMasking=!0,this.activation=Ha(e.activation)}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ve(e);return this.activation.apply(n)})}getConfig(){let e={activation:ja(this.activation)},t=super.getConfig();return Object.assign(e,t),e}};wb.className="Activation";oe.registerClass(wb);var _b=class extends He{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 j(()=>(e=Ve(e),bz(e,this.n)))}getConfig(){let e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}};_b.className="RepeatVector";oe.registerClass(_b);var Cb=class extends He{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){let n="Total size of new array must be unchanged.",o=t.slice(),s=1,i=null;for(let l=0;l<o.length;++l){let u=o[l];if(this.isUnknown(u))if(i===null)i=l;else throw new U("Can only specifiy one unknown dimension.");else s*=u}let a=vs(e);if(i!==null){if(s===0||a%s!=0)throw new U(n);o[i]=a/s}else if(a!==s)throw new U(n);return o}computeOutputShape(e){let t=!1;for(let n=0;n<e.length;++n)if(this.isUnknown(e[n])){t=!0;break}return t?e.slice(0,1).concat(this.targetShape):e.slice(0,1).concat(this.fixUnknownDimension(e.slice(1),this.targetShape))}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ve(e),o=n.shape,s=o.slice(0,1).concat(this.fixUnknownDimension(o.slice(1),this.targetShape));return n.reshape(s)})}getConfig(){let e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}};Cb.className="Reshape";oe.registerClass(Cb);var Sb=class extends He{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.`);let t=Cn(1,e.dims.length+1);if(!x.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 Vt({ndim:this.dims.length+1})]}computeOutputShape(e){e=it(e);let t=e.slice();return this.dims.forEach((n,o)=>{t[o+1]=e[n]}),t}call(e,t){return nt(Ve(e),this.dimsIncludingBatch)}getConfig(){let e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}};Sb.className="Permute";oe.registerClass(Sb);var Nb=class extends He{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null?this.maskValue=e.maskValue==null?0:e.maskValue:this.maskValue=0}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){let n=Ve(e),o=-1;return Qu(gs(n,this.maskValue),o)}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ve(e),o=-1,s=!0,i=Qu(gs(n,this.maskValue),o,s);return n.mul(i.asType(n.dtype))})}};Nb.className="Masking";oe.registerClass(Nb);var Ab=class extends He{constructor(e){super(e);this.embeddings=null;this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform";if(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($t(e.inputLength))}this.inputDim=e.inputDim,kr(this.inputDim,"inputDim"),this.outputDim=e.outputDim,kr(this.outputDim,"outputDim"),this.embeddingsInitializer=Dt(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=Pt(e.embeddingsRegularizer),this.activityRegularizer=Pt(e.activityRegularizer),this.embeddingsConstraint=ir(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 j(()=>this.maskZero?(e=Ve(e),gs(e,Me(e))):null)}computeOutputShape(e){if(e=it(e),this.inputLength==null)return[...e,this.outputDim];let t=$t(this.inputLength);if(t.length!==e.length-1)throw new U(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let o=0;o<t.length;++o){let s=t[o],i=e[o+1];if(s!=null&&i!=null&&s!==i)throw new U(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);s==null&&(t[n]=i),n++}}return[e[0],...t,this.outputDim]}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ve(e);return n.dtype!=="int32"&&(n=ou(n,"int32")),qT(this.embeddings.read(),n.as1D()).reshape(it(this.computeOutputShape(n.shape)))})}getConfig(){let e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Kt(this.embeddingsInitializer),embeddingsRegularizer:vt(this.embeddingsRegularizer),activityRegularizer:vt(this.activityRegularizer),embeddingsConstraint:ar(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}};Ab.className="Embedding";oe.registerClass(Ab);var dp=class extends He{constructor(e){super(e||{});this.supportsMasking=!0}mergeFunction(e){throw new Le}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;let n=e.slice(0,e.length-t.length);for(let o=0;o<t.length;++o){let s=e[e.length-t.length+o],i=t[o];if(s==null||i==null||s<0||i<0)n.push(null);else if(s===1)n.push(i);else if(i===1)n.push(s);else{if(s!==i)throw new U("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));n.push(s)}}return n}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[it(e)]),e=e,e.length<2)throw new U(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);let t=[];for(let s of e)s!=null&&s[0]!==null&&t.push(s[0]);if(t=Is(t),t.length>1)throw new U(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let n=e[0]==null?null:e[0].slice(1);for(let s=1;s<e.length;++s){let i=e[s]==null?null:e[s].slice(1);n=this.computeElementwiseOpOutputShape(n,i)}let o=e.map(s=>s.length);e.indexOf(null)===-1&&Is(o).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return j(()=>{if(e=e,this.reshapeRequired){let n=[],o=e.map(s=>s.rank);if(o.indexOf(null)===-1){let s=Ka(o);for(let i of e){let a=i.rank;for(let l=0;l<s-a;++l)i=su(i,1);n.push(i)}return this.mergeFunction(n)}else{let s=!1;for(let l of e){let u=l.rank;if(u==null){let p=l.shape,c=p[0],m=p.slice(1).concat([c]),f=l.reshape([c].concat(vs(p.slice(1))));f=nt(f,[1,0]),f=f.reshape(m),n.push(f),s=!0}else if(u>1){let p=Cn(1,u).concat([0]);n.push(nt(l,p)),s=!0}else n.push(l)}let i=this.mergeFunction(n),a=i.rank;if(s){if(a==null){let l=i.shape,u=l.length,p=l[u-1],c=[p].concat(l.slice(0,l.length-1));i=nt(i.reshape([-1,p]),[1,0]).reshape(c)}else if(a>1){let l=[a-1].concat(Cn(0,a-1));i=nt(i,l)}}return i}}else return this.mergeFunction(e)})}computeOutputShape(e){e=e;let t;e[0]==null?t=null:t=e[0].slice(1);for(let o=1;o<e.length;++o){let s=e[o]==null?null:e[o].slice(1);t=this.computeElementwiseOpOutputShape(t,s)}let n=[];for(let o of e)o!=null&&o[0]!==null&&n.push(o[0]);return n=Is(n),n.length===1?t=n.concat(t):t=[null].concat(t),t}computeMask(e,t){return j(()=>{if(t==null)return null;if(!Array.isArray(t))throw new U("`mask` should be an Array");if(!Array.isArray(e))throw new U("`inputs` should be an Array");if(t.length!==e.length)throw new U(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(o=>o==null))return null;t=t.map(o=>o==null?o:Wr(o,0));let n=t[0];for(let o=1;o<t.length-1;++o)n=Xr(n,t[o]);return n})}},Db=class extends dp{constructor(e){super(e)}mergeFunction(e){return j(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=ne(t,e[n]);return t})}};Db.className="Add";oe.registerClass(Db);var Eb=class extends dp{constructor(e){super(e)}mergeFunction(e){return j(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=G(t,e[n]);return t})}};Eb.className="Multiply";oe.registerClass(Eb);var Mb=class extends dp{constructor(e){super(e)}mergeFunction(e){return j(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=ne(t,e[n]);return G(1/e.length,t)})}};Mb.className="Average";oe.registerClass(Mb);var Fb=class extends dp{constructor(e){super(e)}mergeFunction(e){return j(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=Wn(t,e[n]);return t})}};Fb.className="Maximum";oe.registerClass(Fb);var Rb=class extends dp{constructor(e){super(e)}mergeFunction(e){return j(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=Oa(t,e[n]);return t})}};Rb.className="Minimum";oe.registerClass(Rb);var Lb=class extends dp{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 U("A `Concatenate` layer should be called on a list of at least 2 inputs");e=e;let t=!0;for(let o of e)if(o!=null){t=!1;break}if(t)return;let n=[];for(let o=0;o<e.length;++o){let s=e[o].slice();s.splice(this.axis,1);let i=!1;for(let a of n)if(x.arraysEqual(a,s)){i=!0;break}i||n.push(s)}if(n.length>1)throw new U("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return j(()=>ad(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new U("A `Concatenate` layer should be called on a list of inputs.");let t=e,n=t[0].slice(),o=this.axis<0?n.length+this.axis:this.axis;for(let s of t.slice(1)){if(n[o]==null||s[o]==null){n[o]=null;break}n[o]+=s[o]}return n}computeMask(e,t){if(t==null)return null;if(!Array.isArray(t))throw new U("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new U("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new U(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return j(()=>{let n=!0;if(t.forEach(i=>{if(i!=null){n=!1;return}}),n)return null;let o=[];for(let i=0;i<e.length;++i)t[i]==null?o.push(Br(e[i]).asType("bool")):t[i].rank<e[i].rank?o.push(Wr(t[i],-1)):o.push(t[i]);let s=mt(o,this.axis);return kc(s,-1,!1)})}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};Lb.className="Concatenate";oe.registerClass(Lb);function $b(r,e){for(;r<0;)r+=e;return r}function rce(r,e,t){if(r.shape.length>3||e.shape.length>3)throw new Le("batchDot is not implemented for tensors of 4D or higher rank yet");if(x.assert(r.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${r.shape.length}`),x.assert(r.shape.length>=2,()=>`batchDot requires the rank of y to be >= 2, but got ${e.shape.length}`),typeof t=="number"&&(t=[t,t]),r.dtype==="complex64"||e.dtype==="complex64")throw new Le("batchDot is not implemented for complex64-type Tensors yet.");let n=r.shape.length,o=e.shape.length;t==null&&(t=[n-1,o-2]);let s=t;return j(()=>{let i;if(n>o){i=n-o;let l=[];for(let u=0;u<i;++u)l.push(1);e=e.reshape(e.shape.concat(l))}else if(o>n){i=o-n;let l=[];for(let u=0;u<i;++u)l.push(1);r=r.reshape(r.shape.concat(l))}else i=0;let a;if(r.shape.length===2&&e.shape.length===2)s[0]===s[1]?a=r.mul(e).sum(s[0]):a=r.transpose([1,0]).mul(e).sum(s[1]);else{let l=s[0]!==r.shape.length-1,u=s[1]===e.shape.length-1;a=r.matMul(e,l,u)}if(i>0){let l;n>o?l=n+o-3:l=n-1;let u=[];for(let p=l;p<l+i;++p)u.push(p);a=a.squeeze(u)}return a.shape.length===1&&(a=a.expandDims(1)),a})}var Pb=class extends dp{constructor(e){super(e);this.axes=e.axes,this.normalize=e.normalize==null?!1:e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){x.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.");let t=e[0],n=e[1];if(t.length>3||n.length>3)throw new Le("Dot layer does not support tensors of 4D or higher rank yet.");let o=this.interpretAxes(t,n);if(t[o[0]]!==n[o[1]])throw new U(`Dimension incompatibility: ${t[o[0]]} !== ${n[o[1]]}`)}mergeFunction(e){if(e.length!==2)throw new U(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t=e[0],n=e[1],o;return Array.isArray(this.axes)?o=this.axes.map((s,i)=>$b(s,e[i].shape.length)):o=[$b(this.axes,t.shape.length),$b(this.axes,n.shape.length)],this.normalize&&(t=qg(t,o[0]),n=qg(n,o[1])),rce(t,n,o)}interpretAxes(e,t){let n;return Array.isArray(this.axes)?n=this.axes:n=[$b(this.axes,e.length),$b(this.axes,t.length)],n}computeOutputShape(e){x.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.");let t=e[0].slice(),n=e[1].slice();if(t.length>3||n.length>3)throw new Le("Dot layer does not support tensors of 4D or higher rank yet.");let o=this.interpretAxes(t,n);t.splice(o[0],1),n.splice(o[1],1),n.splice(0,1);let s=t.concat(n);return s.length===1&&s.push(1),s}computeMask(e,t){return null}getConfig(){let e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}};Pb.className="Dot";oe.registerClass(Pb);var Bb=class extends He{constructor(e){super(e);this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ve(e);return sp(()=>id(n.shape,0,this.stddev).add(n),()=>n,t.training||!1)})}};Bb.className="GaussianNoise";oe.registerClass(Bb);var Ob=class extends He{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return j(()=>{this.invokeCallHook(e,t);let n=Ve(e);return this.rate>0&&this.rate<1?sp(()=>{let s=Math.sqrt(this.rate/(1-this.rate));return n.mul(id(n.shape,1,s))},()=>n,t.training||!1):n})}};Ob.className="GaussianDropout";oe.registerClass(Ob);var zb=class extends He{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Ve(e).shape}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return j(()=>{if(this.rate<1&&this.rate>0){let n=this._getNoiseShape(e);return sp(()=>{let s=Ve(e),i=1.6732632423543772,a=1.0507009873554805,l=-i*a,u=io(za(n),this.rate);u=ou(u,"float32");let p=((1-this.rate)*(1+this.rate*l**2))**-.5,c=-p*l*this.rate;return s.mul(u).add(u.add(-1).mul(l)).mul(p).add(c)},()=>Ve(e),t.training||!1)}return e})}};zb.className="AlphaDropout";oe.registerClass(zb);function Gb(r,e,t,n,o,s=.001){let i;if(r.rank===2)i=VC(r,e,t,n,o,s);else if(r.rank===3)i=UC(r,e,t,n,o,s);else if(r.rank===4)i=jC(r,e,t,n,o,s);else throw new Le(`batchNormalization is not implemented for array of rank ${r.rank} yet`);return i}function nce(r,e,t,n,o=.001){return j(()=>{let s=Yf(r,n),i=s.mean,a=s.variance;return[Gb(r,i,a,t,e,o),i,a]})}function oce(r,e,t,n,o=.001){return j(()=>{let s=Yf(r,n),i=s.mean,a=s.variance,l=[];for(let d of Cn(0,r.rank))n.indexOf(d)!==-1?l.push(1):l.push(r.shape[d]);let u=i.reshape(l),p=a.reshape(l),c=e==null?null:e.reshape(l),m=t==null?null:t.reshape(l);return[Gb(r,u,p,m,c,o),i,a]})}function sce(r,e,t,n,o=.001){return x.arraysEqual(n.slice().sort(),Cn(0,r.rank-1))?nce(r,e,t,n,o):oce(r,e,t,n,o)}var Wb=class extends He{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=Dt(e.betaInitializer||"zeros"),this.gammaInitializer=Dt(e.gammaInitializer||"ones"),this.movingMeanInitializer=Dt(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=Dt(e.movingVarianceInitializer||"ones"),this.betaConstraint=ir(e.betaConstraint),this.gammaConstraint=ir(e.gammaConstraint),this.betaRegularizer=Pt(e.betaRegularizer),this.gammaRegularizer=Pt(e.gammaRegularizer)}build(e){e=it(e);let t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(n==null)throw new U(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Vt({ndim:e.length,axes:{[t]:n}})];let o=[n];this.scale&&(this.gamma=this.addWeight("gamma",o,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",o,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",o,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",o,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return j(()=>{let n=t.training==null?!1:t.training,o=Ve(e),s=o.shape,i=s.length,a=Cn(0,i),l=this.axis>=0?this.axis:this.axis+i;a.splice(l,1);let u=xs(1,i);u[l]=s[l];let p=a.slice();p.sort();let c=!x.arraysEqual(p,Cn(0,i).slice(0,i-1)),m=()=>{if(c){let y=this.movingMean.read().reshape(u),T=this.movingVariance.read().reshape(u),k=this.center?this.beta.read().reshape(u):null,I=this.scale?this.gamma.read().reshape(u):null;return Gb(o,y,T,k,I,this.epsilon)}else return Gb(o,this.movingMean.read(),this.movingVariance.read(),this.beta==null?null:this.beta.read(),this.gamma==null?null:this.gamma.read(),this.epsilon)};if(!n)return m();let[f,d,h]=sce(o,this.gamma.read(),this.beta.read(),a,this.epsilon),g=(y,T,k)=>{j(()=>{let I=1-k,S=y.read(),N=S.sub(T).mul(I);y.write(S.sub(N))})};return(()=>{g(this.movingMean,d,this.momentum),g(this.movingVariance,h,this.momentum)})(),f})}getConfig(){let e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Kt(this.betaInitializer),gammaInitializer:Kt(this.gammaInitializer),movingMeanInitializer:Kt(this.movingMeanInitializer),movingVarianceInitializer:Kt(this.movingVarianceInitializer),betaRegularizer:vt(this.betaRegularizer),gammaRegularizer:vt(this.gammaRegularizer),betaConstraint:ar(this.betaConstraint),gammaConstraint:ar(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}};Wb.className="BatchNormalization";oe.registerClass(Wb);var Kb=class extends He{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(let 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=Dt(e.betaInitializer||"zeros"),this.gammaInitializer=Dt(e.gammaInitializer||"ones"),this.betaRegularizer=Pt(e.betaRegularizer),this.gammaRegularizer=Pt(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=it(e);let t=e.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let s=0;s<this.axis.length;++s)this.axis[s]<0&&(this.axis[s]+=t);for(let s of this.axis)if(s<0||s>=t)throw new Error(`Invalid axis: ${s}`);if(this.axis.length!==Is(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);let n=this.axis.map(s=>e[s]),o=!0;this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,o):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,o):this.beta=null,this.built=!0}call(e,t){let n=Ve(e),o=n.shape,s=o.length;return j(()=>{let i=!0,{mean:a,variance:l}=Yf(n,this.axis,i),u=xs(1,s);for(let h of this.axis)u[h]=o[h];let p=h=>h!=null&&h.shape.length!==s&&this.axis!==[s-1]?h.reshape(u):h,c=p(this.gamma.read()),m=p(this.beta.read()),f=[],d=[];for(let h=0;h<s;++h)this.axis.indexOf(h)!==-1?(f.push(o[h]),d.push(1)):(f.push(1),d.push(o[h]));return a=a.tile(f),l=l.tile(f),c=c.tile(d),m=m.tile(d),Gb(n,a,l,m,c,this.epsilon)})}getConfig(){let e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Kt(this.betaInitializer),gammaInitializer:Kt(this.gammaInitializer),betaRegularizer:vt(this.betaRegularizer),gammaRegularizer:vt(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}};Kb.className="LayerNormalization";oe.registerClass(Kb);function ace(r,e,t){return j(()=>{if(r.rank!==4)throw new U(`temporalPadding expects input tensor to be 4-D, but received a ${r.rank}-D tensor.`);if(e==null&&(e=[[1,1],[1,1]]),e.length!==2||e[0].length!==2||e[1].length!==2)throw new U("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(t==null&&(t=Kn()),t!=="channelsLast"&&t!=="channelsFirst")throw new U(`Unknown data format: ${t}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let n;return t==="channelsFirst"?n=[[0,0],[0,0],e[0],e[1]]:n=[[0,0],e[0],e[1],[0,0]],kn(r,n)})}var Vb=class extends He{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?Kn():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 U(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,n;if(typeof e.padding[0]=="number")t=[e.padding[0],e.padding[0]],n=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,e.padding[0].length!==2)throw new U(`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 U(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);n=e.padding[1]}this.padding=[t,n]}this.inputSpec=[new Vt({ndim:4})]}computeOutputShape(e){e=it(e);let t,n;return this.dataFormat==="channelsFirst"?(e[2]!=null&&e[2]>=0?t=e[2]+this.padding[0][0]+this.padding[0][1]:t=null,e[3]!=null&&e[3]>=0?n=e[3]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],e[1],t,n]):(e[1]!=null&&e[1]>=0?t=e[1]+this.padding[0][0]+this.padding[0][1]:t=null,e[2]!=null&&e[2]>=0?n=e[2]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],t,n,e[3]])}call(e,t){return j(()=>ace(Ve(e),this.padding,this.dataFormat))}getConfig(){let e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};Vb.className="ZeroPadding2D";oe.registerClass(Vb);function gk(r,e,t,n,o,s){return j(()=>{tr(o),ES(s),Vn(n),t==null&&(t=[1,1]),n==null&&(n="valid"),o==null&&(o=Kn()),s==null&&(s="max"),r=ub(r,o);let i,a=n==="same"?"same":"valid";return s==="max"?i=Xl(r,e,t,a):i=Kl(r,e,t,a),o==="channelsFirst"&&(i=nt(i,[0,3,1,2])),i})}function n3(r,e,t,n,o,s){return j(()=>{tr(o),ES(s),Vn(n),t==null&&(t=[1,1,1]),n==null&&(n="valid"),o==null&&(o=Kn()),s==null&&(s="max"),r=pN(r,o);let i,a=n==="same"?"same":"valid";return s==="max"?i=bg(r,e,t,a):i=og(r,e,t,a),o==="channelsFirst"&&(i=nt(i,[0,4,1,2,3])),i})}var xN=class extends He{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 U(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(kr(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 U(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);kr(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,Vn(this.padding),this.inputSpec=[new Vt({ndim:3})]}computeOutputShape(e){e=it(e);let t=po(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return j(()=>{this.invokeCallHook(e,t),e=su(Ve(e),2);let n=this.poolingFunction(Ve(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Xo(n,[2])})}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}},Ub=class extends xN{constructor(e){super(e)}poolingFunction(e,t,n,o,s){return tr(s),Vn(o),gk(e,t,n,o,s,"max")}};Ub.className="MaxPooling1D";oe.registerClass(Ub);var jb=class extends xN{constructor(e){super(e)}poolingFunction(e,t,n,o,s){return tr(s),Vn(o),gk(e,t,n,o,s,"avg")}};jb.className="AveragePooling1D";oe.registerClass(jb);var TN=class extends He{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 U(`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];kr(this.poolSize,"poolSize"),kr(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,tr(this.dataFormat),Vn(this.padding),this.inputSpec=[new Vt({ndim:4})]}computeOutputShape(e){e=it(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=po(t,this.poolSize[0],this.padding,this.strides[0]),n=po(n,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n]:[e[0],t,n,e[3]]}call(e,t){return j(()=>(this.invokeCallHook(e,t),this.poolingFunction(Ve(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},Hb=class extends TN{constructor(e){super(e)}poolingFunction(e,t,n,o,s){return tr(s),Vn(o),gk(e,t,n,o,s,"max")}};Hb.className="MaxPooling2D";oe.registerClass(Hb);var qb=class extends TN{constructor(e){super(e)}poolingFunction(e,t,n,o,s){return tr(s),Vn(o),gk(e,t,n,o,s,"avg")}};qb.className="AveragePooling2D";oe.registerClass(qb);var kN=class extends He{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 U(`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];kr(this.poolSize,"poolSize"),kr(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,tr(this.dataFormat),Vn(this.padding),this.inputSpec=[new Vt({ndim:5})]}computeOutputShape(e){e=it(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],o=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=po(t,this.poolSize[0],this.padding,this.strides[0]),n=po(n,this.poolSize[1],this.padding,this.strides[1]),o=po(o,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n,o]:[e[0],t,n,o,e[4]]}call(e,t){return j(()=>(this.invokeCallHook(e,t),this.poolingFunction(Ve(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},Xb=class extends kN{constructor(e){super(e)}poolingFunction(e,t,n,o,s){return tr(s),Vn(o),n3(e,t,n,o,s,"max")}};Xb.className="MaxPooling3D";oe.registerClass(Xb);var Yb=class extends kN{constructor(e){super(e)}poolingFunction(e,t,n,o,s){return tr(s),Vn(o),n3(e,t,n,o,s,"avg")}};Yb.className="AveragePooling3D";oe.registerClass(Yb);var IN=class extends He{constructor(e){super(e);this.inputSpec=[new Vt({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Le}},Zb=class extends IN{constructor(e){super(e||{})}call(e,t){return j(()=>{let n=Ve(e);return Ft(n,1)})}};Zb.className="GlobalAveragePooling1D";oe.registerClass(Zb);var Jb=class extends IN{constructor(e){super(e||{})}call(e,t){return j(()=>{let n=Ve(e);return nn(n,1)})}};Jb.className="GlobalMaxPooling1D";oe.registerClass(Jb);var vN=class extends He{constructor(e){super(e);this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,tr(this.dataFormat),this.inputSpec=[new Vt({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Le}getConfig(){let e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},Qb=class extends vN{call(e,t){return j(()=>{let n=Ve(e);return this.dataFormat==="channelsLast"?Ft(n,[1,2]):Ft(n,[2,3])})}};Qb.className="GlobalAveragePooling2D";oe.registerClass(Qb);var ey=class extends vN{call(e,t){return j(()=>{let n=Ve(e);return this.dataFormat==="channelsLast"?nn(n,[1,2]):nn(n,[2,3])})}};ey.className="GlobalMaxPooling2D";oe.registerClass(ey);var wN=class extends He{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(){let e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,n={}){let o=t.layer,s=Hn(o,n);delete t.layer;let i={layer:s};return Object.assign(i,t),new e(i)}},ty=class extends wN{constructor(e){super(e);this.supportsMasking=!0}build(e){if(e=it(e),e.length<3)throw new U(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];let t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){e=it(e);let t=[e[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),o=e[1];return[n[0],o].concat(n.slice(1))}call(e,t){return j(()=>(e=Ve(e),gN((i,a)=>[Ve(this.layer.call(i,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};ty.className="TimeDistributed";oe.registerClass(ty);function ice(r){Ai(mz,"BidirectionalMergeMode",r)}var lce="concat",ry=class extends wN{constructor(e){super(e);let t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=Hn(n),t.goBackwards=t.goBackwards!==!0;let o={};if(o.className=e.layer.getClassName(),o.config=t,this.backwardLayer=Hn(o),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?lce:e.mergeMode,ice(this.mergeMode),e.weights)throw new Le("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){let t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))}computeOutputShape(e){let t=this.forwardLayer.computeOutputShape(e);Array.isArray(t)&&Array.isArray(t[0])||(t=[t]),t=t;let n,o,s;return this.returnState&&(s=t.slice(1)),n=t[0],n=n,this.mergeMode==="concat"?(n[n.length-1]*=2,o=[n]):this.mergeMode==null?o=[n,n.slice()]:o=[n],this.returnState?this.mergeMode==null?o.concat(s).concat(s.slice()):[n].concat(s).concat(s.slice()):Yr(o)}apply(e,t){let n=t==null?null:t.initialState,o=t==null?null:t.constants;t==null&&(t={});let s=hN(e,n,o,this.numConstants);if(e=s.inputs,n=s.initialState,o=s.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(n==null||n.length===0)&&o==null)return super.apply(e,t);let i=[],a=[];if(n!=null){let u=n.length;if(u%2>0)throw new U("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,i.push(...n);let p=n.map(c=>new Vt({shape:c.shape}));this.forwardLayer.stateSpec=p.slice(0,u/2),this.backwardLayer.stateSpec=p.slice(u/2),a.push(...p)}if(o!=null)throw new Le("Support for constants in Bidirectional layers is not implemented yet.");let l=i[0]instanceof jn;for(let u of i)if(u instanceof jn!==l)throw new U("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(l){let u=[e].concat(i),p=this.inputSpec.concat(a),c=this.inputSpec;this.inputSpec=p;let m=super.apply(u,t);return this.inputSpec=c,m}else return super.apply(e,t)}call(e,t){return j(()=>{let n=t.initialState,o,s;if(n==null)o=this.forwardLayer.call(e,t),s=this.backwardLayer.call(e,t);else{let l=n.slice(0,n.length/2),u=n.slice(n.length/2);o=this.forwardLayer.call(e,Object.assign(t,{initialState:l})),s=this.backwardLayer.call(e,Object.assign(t,{initialState:u}))}let i;this.returnState&&(Array.isArray(o)&&(i=o.slice(1).concat(s.slice(1))),o=o[0],s=s[0]),this.returnSequences&&(s=wr(s,1));let a;return this.mergeMode==="concat"?a=ad([o,s]):this.mergeMode==="sum"?a=ne(o,s):this.mergeMode==="ave"?a=G(.5,ne(o,s)):this.mergeMode==="mul"?a=G(o,s):this.mergeMode==null&&(a=[o,s]),this.returnState?this.mergeMode==null?a.concat(i):[a].concat(i):a})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){Wa(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),Wa(this.backwardLayer.name,()=>{this.backwardLayer.build(e)}),this.built=!0}computeMask(e,t){Array.isArray(t)&&(t=t[0]);let n;if(this.returnSequences?this.mergeMode==null?n=[t,t]:n=t:this.mergeMode==null?n=[null,null]:n=null,this.returnState){let s=this.forwardLayer.states.map(i=>null);return Array.isArray(n)?n.concat(s).concat(s):[n].concat(s).concat(s)}else return n}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.forwardLayer!=null&&this.forwardLayer.setFastWeightInitDuringBuild(e),this.backwardLayer!=null&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){let e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){let n=Hn(t.layer);if(delete t.layer,t.numConstants!=null)throw new Le("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");let o=t;return o.layer=n,new e(o)}};ry.className="Bidirectional";oe.registerClass(ry);function uce(r){return new Di(r)}function pce(r){return new ab(r)}function cce(r){return new nb(r)}function mce(r){return new ob(r)}function fce(r){return new sb(r)}function dce(r){return new lb(r)}function hce(r){return new ib(r)}function gce(r){return new fb(r)}function bce(r){return new vd(r)}function yce(r){return new pb(r)}function xce(r){return new wd(r)}function Tce(r){return new cb(r)}function kce(r){return new mb(r)}function Ice(r){return new db(r)}function vce(r){return new hb(r)}function wce(r){return new gb(r)}function _ce(r){return new wb(r)}function Cce(r){return new Ib(r)}function Sce(r){return new Ad(r)}function Nce(r){return new kb(r)}function Ace(r){return new vb(r)}function Dce(r){return new _b(r)}function Ece(r){return new Cb(r)}function Mce(r){return new Sb(r)}function Fce(r){return new Ab(r)}function Rce(r){return new Db(r)}function Lce(r){return new Mb(r)}function $ce(r){return new Lb(r)}function Pce(r){return new Fb(r)}function Bce(r){return new Rb(r)}function Oce(r){return new Eb(r)}function zce(r){return new Pb(r)}function Gce(r){return new Wb(r)}function Wce(r){return new Kb(r)}function Kce(r){return new Vb(r)}function _N(r){return new jb(r)}function Vce(r){return _N(r)}function Uce(r){return _N(r)}function CN(r){return new qb(r)}function jce(r){return CN(r)}function Hce(r){return CN(r)}function SN(r){return new Yb(r)}function qce(r){return SN(r)}function Xce(r){return SN(r)}function Yce(r){return new Zb(r)}function Zce(r){return new Qb(r)}function o3(r){return new Jb(r)}function s3(r){return new ey(r)}function a3(r){return new Ub(r)}function i3(r){return new Hb(r)}function Jce(r){return new Xb(r)}function Qce(r){return new yb(r)}function eme(r){return new Cd(r)}function tme(r){return new xb(r)}function rme(r){return new fp(r)}function nme(r){return new bb(r)}function ome(r){return new _d(r)}function sme(r){return new Tb(r)}function ame(r){return new Nd(r)}function ime(r){return new _s(r)}function lme(r){return new Sd(r)}function ume(r){return new ry(r)}function pme(r){return new ty(r)}var cme=o3,mme=s3,fme=a3,dme=i3;function hme(r){return new Bb(r)}function gme(r){return new Ob(r)}function bme(r){return new zb(r)}function yme(r){return new Nb(r)}var u3={};Ge(u3,{MAPE:()=>Ame,MSE:()=>Mme,binaryAccuracy:()=>xme,binaryCrossentropy:()=>Tme,categoricalAccuracy:()=>Ime,categoricalCrossentropy:()=>vme,cosineProximity:()=>Cme,mape:()=>Dme,meanAbsoluteError:()=>Sme,meanAbsolutePercentageError:()=>Nme,meanSquaredError:()=>Eme,mse:()=>Fme,precision:()=>wme,recall:()=>_me,sparseCategoricalAccuracy:()=>kme});function xme(r,e){return Zg(r,e)}function Tme(r,e){return sk(r,e)}function kme(r,e){return ak(r,e)}function Ime(r,e){return Jg(r,e)}function vme(r,e){return Qg(r,e)}function wme(r,e){return OS(r,e)}function _me(r,e){return Mz(r,e)}function Cme(r,e){return Xg(r,e)}function Sme(r,e){return bd(r,e)}function Nme(r,e){return up(r,e)}function Ame(r,e){return up(r,e)}function Dme(r,e){return up(r,e)}function Eme(r,e){return Mi(r,e)}function Mme(r,e){return Mi(r,e)}function Fme(r,e){return Mi(r,e)}var p3={};Ge(p3,{modelFromJSON:()=>Yz});var c3={};Ge(c3,{l1:()=>Lme,l1l2:()=>Rme,l2:()=>$me});function Rme(r){return new sm(r)}function Lme(r){return Jz(r)}function $me(r){return Qz(r)}var NN=class extends lp{constructor(){super(...arguments);this.model=null}setModel(e){if(!(e instanceof Jo))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function bk(r,e){return r<e}function m3(r,e){return r>e}var AN=class extends NN{constructor(e){super();if(e==null&&(e={}),e.restoreBestWeights)throw new Le("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=bk:this.mode==="max"?this.monitorFunc=m3:this.monitor.indexOf("acc")!==-1?this.monitorFunc=m3:this.monitorFunc=bk,this.monitorFunc===bk&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===bk?Infinity:-Infinity}async onEpochEnd(e,t){await Ei(t);let n=this.getMonitorValue(t);n!=null&&(this.monitorFunc(n-this.minDelta,this.best)?(this.best=n,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0)))}async onTrainEnd(e){this.stoppedEpoch>0&&this.verbose&&console.log(`Epoch ${this.stoppedEpoch}: early stopping.`)}getMonitorValue(e){e==null&&(e={});let 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 Pme(r){return new AN(r)}var Bme={earlyStopping:Pme};var Cs;(function(W){W[W.DT_INVALID=0]="DT_INVALID",W[W.DT_FLOAT=1]="DT_FLOAT",W[W.DT_DOUBLE=2]="DT_DOUBLE",W[W.DT_INT32=3]="DT_INT32",W[W.DT_UINT8=4]="DT_UINT8",W[W.DT_INT16=5]="DT_INT16",W[W.DT_INT8=6]="DT_INT8",W[W.DT_STRING=7]="DT_STRING",W[W.DT_COMPLEX64=8]="DT_COMPLEX64",W[W.DT_INT64=9]="DT_INT64",W[W.DT_BOOL=10]="DT_BOOL",W[W.DT_QINT8=11]="DT_QINT8",W[W.DT_QUINT8=12]="DT_QUINT8",W[W.DT_QINT32=13]="DT_QINT32",W[W.DT_BFLOAT16=14]="DT_BFLOAT16",W[W.DT_FLOAT_REF=101]="DT_FLOAT_REF",W[W.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",W[W.DT_INT32_REF=103]="DT_INT32_REF",W[W.DT_UINT8_REF=104]="DT_UINT8_REF",W[W.DT_INT16_REF=105]="DT_INT16_REF",W[W.DT_INT8_REF=106]="DT_INT8_REF",W[W.DT_STRING_REF=107]="DT_STRING_REF",W[W.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",W[W.DT_INT64_REF=109]="DT_INT64_REF",W[W.DT_BOOL_REF=110]="DT_BOOL_REF",W[W.DT_QINT8_REF=111]="DT_QINT8_REF",W[W.DT_QUINT8_REF=112]="DT_QUINT8_REF",W[W.DT_QINT32_REF=113]="DT_QINT32_REF",W[W.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF"})(Cs||(Cs={}));var f3;(function(e){let r;(function(s){s[s.LEGACY=0]="LEGACY",s[s.V1=1]="V1",s[s.V2=2]="V2"})(r=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))})(f3||(f3={}));var DN={};function Ome(r,e){let t={tfOpName:r,category:"custom",inputs:[],attrs:[],customExecutor:e};DN[r]=t}function yk(r){return DN[r]}function zme(r){delete DN[r]}function _(r,e,t,n,o){let s=e.inputParams[r];if(s&&s.inputIndexStart!==void 0){let a=s.inputIndexStart,l=s.inputIndexEnd===0?void 0:s.inputIndexEnd===void 0?a+1:s.inputIndexEnd;if(s.type==="tensor")return Ur(e.inputNames[s.inputIndexStart],t,n,o);if(s.type==="tensors")return e.inputNames.slice(a,l).map(m=>Ur(m,t,n,o));let u=Ur(e.inputNames.slice(a)[0],t,n,o),p=u.dataSync();return s.type==="number"?p[0]:x.toNestedArray(u.shape,p)}let i=e.attrParams[r];return i&&i.value}function Ur(r,e,t,n){let[o,s]=Xn(r);if(n!=null){let a=n.getHashTableHandleByName(o);if(a!=null)return a}let i=t.currentContextIds.find(a=>!!e[xk(o,a)]);return i!==void 0?e[xk(o,i)][s]:void 0}function d3(r,e,t){return e[xk(r,t.currentContextId)]}function Xa(r,e){let[t,n,o]=Xn(r);return[xk(t,e&&e.currentContextId),n,o]}function xk(r,e){return e?`${r}-${e}`:r}function Xn(r){let e=r.split(":");if(e.length===1)return[r,0,void 0];let t=e[0],n=e.length===3?e[1]:void 0,o=Number(e[e.length-1]);return[t,o,n]}function ny(r,e,t){let n=_("pad",r,e,t);if(n==="explicit"){n=_("explicitPaddings",r,e,t);let o=[[0,0],[0,0],[0,0],[0,0]];for(let s=0;s<4;s++)o[s][0]=n[s*2],o[s][1]=n[s*2+1];return o}return n}function Ya(r){return r.kept?r:jo(r)}var EN={};Ge(EN,{json:()=>Gme});var Gme=[{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},{tfName:"data_format",name:"dataFormat",type:"string",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"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Minimum",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:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];var MN={};Ge(MN,{json:()=>Wme});var Wme=[{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"},{start:1,name:"clipValueMin",type:"number"},{start:2,name:"clipValueMax",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{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}]},{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}]},{tfOpName:"IsNan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];var FN={};Ge(FN,{json:()=>Kme});var Kme=[{tfOpName:"EmptyTensorList",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"maxNumElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]}];var RN={};Ge(RN,{json:()=>Vme});var Vme=[{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:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[],notSupported:!0},{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},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number"}]},{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:[]},{tfName:"dilations",name:"dilations",type:"number[]",notSupported:!0}]},{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:[]},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}];var LN={};Ge(LN,{json:()=>Ume});var Ume=[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}];var $N={};Ge($N,{json:()=>jme});var jme=[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV4",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"T_threshold",name:"threshold",type:"dtype",notSupported:!0},{tfName:"pad_to_max_output_size",name:"padToMaxOutputSize",type:"bool"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];var PN={};Ge(PN,{json:()=>Hme});var Hme=[{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}];var BN={};Ge(BN,{json:()=>qme});var qme=[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}];var ON={};Ge(ON,{json:()=>Xme});var Xme=[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableSize",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"LookupTableSizeV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]}];var zN={};Ge(zN,{json:()=>Yme});var Yme=[{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:"half_pixel_centers",name:"halfPixelCenters",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:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]}];var GN={};Ge(GN,{json:()=>Zme});var Zme=[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SelectV2",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];var WN={};Ge(WN,{json:()=>Jme});var Jme=[{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}]},{tfOpName:"Einsum",category:"matrices",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"equation",name:"equation",type:"string"},{tfName:"N",name:"n",type:"number",defaultValue:2},{tfName:"T",name:"dtype",type:"dtype"}]}];var KN={};Ge(KN,{json:()=>Qme});var Qme=[{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"SparseToDense",category:"normalization",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!0,notSupported:!0}]}];var VN={};Ge(VN,{json:()=>efe});var efe=[{tfOpName:"Bincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}]},{tfOpName:"DenseBincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}],attrs:[{tfName:"binary_output",name:"binaryOutput",type:"bool"}]},{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}];var UN={};Ge(UN,{json:()=>tfe});var tfe=[{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}],attrs:[{tfName:"batch_dims",name:"batchDims",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{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[]"}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]}];var jN={};Ge(jN,{json:()=>rfe});var rfe=[{tfOpName:"SparseFillEmptyRows",category:"sparse",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"denseShape",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}]},{tfOpName:"SparseReshape",category:"sparse",inputs:[{start:0,name:"inputIndices",type:"tensor"},{start:1,name:"inputShape",type:"tensor"},{start:2,name:"newShape",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SparseSegmentMean",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]},{tfOpName:"SparseSegmentSum",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]}];var HN={};Ge(HN,{json:()=>nfe});var nfe=[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}];var qN={};Ge(qN,{json:()=>ofe});var ofe=[{tfOpName:"StringNGrams",category:"string",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"dataSplits",type:"tensor"}],attrs:[{tfName:"separator",name:"separator",type:"string"},{tfName:"ngram_widths",name:"nGramWidths",type:"number[]"},{tfName:"left_pad",name:"leftPad",type:"string"},{tfName:"right_pad",name:"rightPad",type:"string"},{tfName:"pad_width",name:"padWidth",type:"number"},{tfName:"preserve_short_sequences",name:"preserveShortSequences",type:"bool"}],outputs:["ngrams","ngrams_splits"]},{tfOpName:"StringSplit",category:"string",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"delimiter",type:"tensor"}],attrs:[{tfName:"skip_empty",name:"skipEmpty",type:"bool"}],outputs:["indices","values","shape"]},{tfOpName:"StringToHashBucketFast",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"num_buckets",name:"numBuckets",type:"number"}]}];var XN={};Ge(XN,{json:()=>sfe});var sfe=[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"MirrorPad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"mode",name:"mode",type:"string"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]}];var Tk=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let e=[EN,MN,FN,RN,LN,$N,PN,BN,ON,zN,GN,WN,KN,VN,UN,jN,HN,qN,XN],t=[].concat(...e.map(n=>n.json));this.opMappers=t.reduce((n,o)=>(n[o.tfOpName]=o,n),{})}transformGraph(e,t={}){let n=e.node,o=[],s=[],i=[],a=n.reduce((h,g)=>(h[g.name]=this.mapNode(g),g.op.startsWith("Placeholder")?o.push(h[g.name]):g.op==="Const"?s.push(h[g.name]):(g.input==null||g.input.length===0)&&i.push(h[g.name]),h),{}),l=[],u=[],p={},c={};t!=null&&(p=this.mapSignatureEntries(t.inputs),c=this.mapSignatureEntries(t.outputs));let m=Object.keys(a);m.forEach(h=>{let g=a[h];g.inputNames.forEach((b,y)=>{let[T,,k]=Xa(b),I=a[T];if(I.outputs!=null){let S=I.outputs.indexOf(k);if(S!==-1){let N=`${T}:${S}`;g.inputNames[y]=N}}g.inputs.push(I),I.children.push(g)})}),Object.keys(c).length===0?m.forEach(h=>{let g=a[h];g.children.length===0&&u.push(g)}):Object.keys(c).forEach(h=>{let[g]=Xa(h),b=a[g];b!=null&&(b.signatureKey=c[h],u.push(b))}),Object.keys(p).length>0?Object.keys(p).forEach(h=>{let[g]=Xa(h),b=a[g];b&&(b.signatureKey=p[h],l.push(b))}):l=o;let f={};e.library!=null&&e.library.function!=null&&(f=e.library.function.reduce((h,g)=>(h[g.signature.name]=this.mapFunction(g),h),{}));let d={nodes:a,inputs:l,outputs:u,weights:s,placeholders:o,signature:t,functions:f};return i.length>0&&(d.initNodes=i),d}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,n)=>(t[e[n].name]=n,t),{})}mapNode(e){let t=yk(e.op)||this.opMappers[e.op]||{};e.attr==null&&(e.attr={});let n={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(o=>o.startsWith("^")?o.substr(1):o),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return t.inputs!=null&&(n.inputParams=t.inputs.reduce((o,s)=>(o[s.name]={type:s.type,inputIndexStart:s.start,inputIndexEnd:s.end},o),{})),t.attrs!=null&&(n.attrParams=t.attrs.reduce((o,s)=>{let i=s.type,a;switch(s.type){case"string":a=kk(e.attr,s.tfName,s.defaultValue),a===void 0&&!!s.tfDeprecatedName&&(a=kk(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"string[]":a=Nk(e.attr,s.tfName,s.defaultValue),a===void 0&&!!s.tfDeprecatedName&&(a=Nk(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"number":a=vk(e.attr,s.tfName,s.defaultValue||0),a===void 0&&!!s.tfDeprecatedName&&(a=vk(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"number[]":a=Sk(e.attr,s.tfName,s.defaultValue),a===void 0&&!!s.tfDeprecatedName&&(a=Sk(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"bool":a=Ik(e.attr,s.tfName,s.defaultValue),a===void 0&&!!s.tfDeprecatedName&&(a=Ik(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"bool[]":a=Dk(e.attr,s.tfName,s.defaultValue),a===void 0&&!!s.tfDeprecatedName&&(a=Dk(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"shape":a=Ck(e.attr,s.tfName,s.defaultValue),a===void 0&&!!s.tfDeprecatedName&&(a=Ck(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"shape[]":a=Ak(e.attr,s.tfName,s.defaultValue),a===void 0&&!!s.tfDeprecatedName&&(a=Ak(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"dtype":a=wk(e.attr,s.tfName,s.defaultValue),a===void 0&&!!s.tfDeprecatedName&&(a=wk(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"dtype[]":a=_k(e.attr,s.tfName,s.defaultValue),a===void 0&&!!s.tfDeprecatedName&&(a=_k(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"func":a=g3(e.attr,s.tfName,s.defaultValue),a===void 0&&!!s.tfDeprecatedName&&(a=g3(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${s.type} for op: ${e.op}`)}return o[s.name]={value:a,type:i},o},{})),n}mapFunction(e){let t=e.nodeDef,n=[],o=[],s={};t!=null&&(s=t.reduce((c,m)=>(c[m.name]=this.mapNode(m),m.op==="Const"&&o.push(c[m.name]),c),{}));let i=[],a=[];e.signature.inputArg.forEach(c=>{let[m]=Xa(c.name),f={name:m,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:YN(c.type),type:"dtype"}},children:[]};f.signatureKey=c.name,i.push(f),s[m]=f}),Object.keys(s).forEach(c=>{let m=s[c];m.inputNames.forEach((f,d)=>{let[h,,g]=Xa(f),b=s[h];if(b.outputs!=null){let y=b.outputs.indexOf(g);if(y!==-1){let T=`${h}:${y}`;m.inputNames[d]=T}}m.inputs.push(b),b.children.push(m)})});let u=e.ret;e.signature.outputArg.forEach(c=>{let[m,f]=Xa(u[c.name]),d=s[m];d!=null&&(d.defaultOutput=f,a.push(d))});let p=this.mapArgsToSignature(e);return{nodes:s,inputs:i,outputs:a,weights:o,placeholders:n,signature:p}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n),t),{}),outputs:e.signature.outputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n,e.ret),t),{})}}mapArgToTensorInfo(e,t){let n=e.name;return t!=null&&(n=t[n]),{name:n,dtype:e.type}}};function afe(r){let e=X().global;if(typeof e.atob!="undefined")return e.atob(r);if(typeof Buffer!="undefined")return new Buffer(r,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}function h3(r,e){let t=Array.isArray(r)?String.fromCharCode.apply(null,r):afe(r);return e?t:t.toLowerCase()}function kk(r,e,t,n=!1){let o=r[e];return o!=null?h3(o.s,n):t}function Ik(r,e,t){let n=r[e];return n?n.b:t}function vk(r,e,t){let n=r[e]||{},o=n.i!=null?n.i:n.f!=null?n.f:t;return typeof o=="number"?o:parseInt(o,10)}function YN(r){switch(typeof r=="string"&&(r=Cs[r]),r){case Cs.DT_FLOAT:return"float32";case Cs.DT_INT32:case Cs.DT_INT64:case Cs.DT_INT8:case Cs.DT_UINT8:return"int32";case Cs.DT_BOOL:return"bool";case Cs.DT_DOUBLE:return"float32";case Cs.DT_STRING:return"string";default:return null}}function g3(r,e,t){let n=r[e];return n&&n.func?n.func.name:t}function wk(r,e,t){let n=r[e];return n&&n.type?YN(n.type):t}function _k(r,e,t){let n=r[e];return n&&n.list&&n.list.type?n.list.type.map(o=>YN(o)):t}function b3(r){if(!r.unknownRank)return r.dim!=null?r.dim.map(e=>typeof e.size=="number"?e.size:parseInt(e.size,10)):[]}function Ck(r,e,t){let n=r[e];return n&&n.shape?b3(n.shape):t}function Sk(r,e,t){let n=r[e];return n?((n.list.f&&n.list.f.length?n.list.f:n.list.i)||[]).map(o=>typeof o=="number"?o:parseInt(o,10)):t}function Nk(r,e,t,n=!1){let o=r[e];return o&&o.list&&o.list.s?o.list.s.map(s=>h3(s,n)):t}function Ak(r,e,t){let n=r[e];return n&&n.list&&n.list.shape?n.list.shape.map(o=>b3(o)):t}function Dk(r,e,t){let n=r[e];return n&&n.list&&n.list.b?n.list.b:t}var ZN=class{constructor(e,t,n){this.node=e;this.tensorMap=t;this.context=n;this.inputs=[];this.attrs={};this.inputs=e.inputNames.map(o=>this.getInput(o)),e.rawAttrs!=null&&(this.attrs=Object.keys(e.rawAttrs).reduce((o,s)=>(o[s]=this.getAttr(s),o),{}))}getInput(e){return Ur(e,this.tensorMap,this.context)}getAttr(e,t){let n=this.node.rawAttrs[e];if(n.tensor!=null)return Ur(e,this.tensorMap,this.context);if(n.i!=null||n.f!=null)return vk(this.node.rawAttrs,e,t);if(n.s!=null)return kk(this.node.rawAttrs,e,t);if(n.b!=null)return Ik(this.node.rawAttrs,e,t);if(n.shape!=null)return Ck(this.node.rawAttrs,e,t);if(n.type!=null)return wk(this.node.rawAttrs,e,t);if(n.list!=null){if(n.list.i!=null||n.list.f!=null)return Sk(this.node.rawAttrs,e,t);if(n.list.s!=null)return Nk(this.node.rawAttrs,e,t);if(n.list.shape!=null)return Ak(this.node.rawAttrs,e,t);if(n.list.b!=null)return Dk(this.node.rawAttrs,e,t);if(n.list.type!=null)return _k(this.node.rawAttrs,e,t)}return t}};var y3=(r,e,t)=>{switch(r.op){case"BiasAdd":case"AddV2":case"Add":return[ne(_("a",r,e,t),_("b",r,e,t))];case"AddN":return[zC(_("tensors",r,e,t))];case"FloorMod":case"Mod":return[xg(_("a",r,e,t),_("b",r,e,t))];case"Mul":return[G(_("a",r,e,t),_("b",r,e,t))];case"RealDiv":case"Div":return[he(_("a",r,e,t),_("b",r,e,t))];case"DivNoNan":return[pg(_("a",r,e,t),_("b",r,e,t))];case"FloorDiv":return[Tc(_("a",r,e,t),_("b",r,e,t))];case"Sub":return[ge(_("a",r,e,t),_("b",r,e,t))];case"Minimum":return[Oa(_("a",r,e,t),_("b",r,e,t))];case"Maximum":return[Wn(_("a",r,e,t),_("b",r,e,t))];case"Pow":return[In(_("a",r,e,t),_("b",r,e,t))];case"SquaredDifference":return[zc(_("a",r,e,t),_("b",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var x3=(r,e,t)=>{switch(r.op){case"Abs":case"ComplexAbs":return[Ht(_("x",r,e,t))];case"Acos":return[Yh(_("x",r,e,t))];case"Acosh":return[Zh(_("x",r,e,t))];case"Asin":return[Qh(_("x",r,e,t))];case"Asinh":return[eg(_("x",r,e,t))];case"Atan":return[tg(_("x",r,e,t))];case"Atan2":return[rg(_("x",r,e,t),_("y",r,e,t))];case"Atanh":return[ng(_("x",r,e,t))];case"Ceil":return[ag(_("x",r,e,t))];case"Complex":return[ko(_("real",r,e,t),_("imag",r,e,t))];case"Cos":return[jl(_("x",r,e,t))];case"Cosh":return[Cc(_("x",r,e,t))];case"Elu":return[La(_("x",r,e,t))];case"Erf":return[cg(_("x",r,e,t))];case"Exp":return[Fr(_("x",r,e,t))];case"Expm1":return[mg(_("x",r,e,t))];case"Floor":return[Pa(_("x",r,e,t))];case"Log":return[Kr(_("x",r,e,t))];case"Log1p":return[Dc(_("x",r,e,t))];case"Imag":return[Nc(_("x",r,e,t))];case"Neg":return[st(_("x",r,e,t))];case"Reciprocal":return[Tg(_("x",r,e,t))];case"Real":return[rp(_("x",r,e,t))];case"Relu":return[hn(_("x",r,e,t))];case"Round":return[Lc(_("x",r,e,t))];case"Selu":return[Pc(_("x",r,e,t))];case"Sigmoid":return[dn(_("x",r,e,t))];case"Sin":return[Bc(_("x",r,e,t))];case"Sign":return[Ig(_("x",r,e,t))];case"Sinh":return[Oc(_("x",r,e,t))];case"Softplus":return[ds(_("x",r,e,t))];case"Sqrt":return[Lt(_("x",r,e,t))];case"Square":return[je(_("x",r,e,t))];case"Tanh":return[Fa(_("x",r,e,t))];case"Tan":return[Cg(_("x",r,e,t))];case"ClipByValue":return[Gr(_("x",r,e,t),_("clipValueMin",r,e,t),_("clipValueMax",r,e,t))];case"Relu6":return[Rc(_("x",r,e,t))];case"Rsqrt":return[$c(Ur(r.inputNames[0],e,t))];case"Prod":return[Fc(_("x",r,e,t),_("axes",r,e,t))];case"LeakyRelu":return[Hl(_("x",r,e,t),_("alpha",r,e,t))];case"Prelu":return[Zl(_("x",r,e,t),_("alpha",r,e,t))];case"IsNan":return[fg(Ur(r.inputNames[0],e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};function wo(r,e,t=""){if(!(typeof r=="number"||typeof e=="number")){x.assert(r.length===e.length,()=>t+` Shapes ${r} and ${e} must match`);for(let n=0;n<r.length;n++){let o=r[n],s=e[n];x.assert(o<0||s<0||o===s,()=>t+` Shapes ${r} and ${e} must match`)}}}function T3(r){return!(typeof r=="number"||r.some(e=>e<0))}function Dd(r,e,t){let n=Ek(r,t),o=!T3(n);if(o&&e.length===0)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${n}`);if(o&&e.forEach(s=>{n=Ek(s.shape,n)}),!T3(n))throw new Error(`Non-fully-defined elementShape: ${n}`);return n}function Ek(r,e){if(typeof r=="number")return e;if(typeof e=="number")return r;if(r.length!==e.length)throw new Error(`Incompatible ranks during merge: ${r} vs. ${e}`);let t=[];for(let n=0;n<r.length;++n){let o=r[n],s=e[n];if(o>=0&&s>=0&&o!==s)throw new Error(`Incompatible shape during merge: ${r} vs. ${e}`);t[n]=o>=0?o:s}return t}var JN=class{constructor(e,t,n,o,s,i,a){this.name=e;this.dtype=t;this.maxSize=n;this.elementShape=o;this.identicalElementShapes=s;this.dynamicSize=i;this.clearAfterRead=a;this.tensors=[];this.closed_=!1;this.idTensor=be(0),er(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()}`);let 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}`);let n=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},
|
|
because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=t.shape),wo(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);n.tensor=t,er(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((n,o)=>this.write(n,t[o]))}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 o=0;o<this.size();o++)e.push(o)}if(e.length===0)return mn([],[0].concat(this.elementShape));let n=this.readMany(e);return wo(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),xr(n,0)}concat(e){if(!!e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(this.size()===0)return mn([],[0].concat(this.elementShape));let t=[];for(let o=0;o<this.size();o++)t.push(o);let n=this.readMany(t);return wo(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),mt(n,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);if(e.length!==t.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);let n=Math.max(...e);if(!this.dynamicSize&&n>=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(e,Vr(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0,o=e.map(l=>(n+=l,n));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to
|
|
tensor.shape[0], but sum of lengths is
|
|
${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);let s=n===0?0:t.size/n,i=[];j(()=>{t=K(t,[1,n,s]);for(let l=0;l<e.length;++l){let u=l===0?0:o[l-1],p=[0,u,0],c=[1,e[l],s];i[l]=K(Ke(t,p,c),this.elementShape)}return i});let a=[];for(let l=0;l<e.length;l++)a[l]=l;this.writeMany(a,i)}};var im=class{constructor(e,t,n,o=-1){this.tensors=e;this.elementShape=t;this.elementDtype=n;e!=null&&e.forEach(s=>{if(n!==s.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${s.dtype}`);wo(t,s.shape,"TensorList shape mismatch: "),er(s)}),this.idTensor=be(0),this.maxNumElements=o,er(this.idTensor)}get id(){return this.idTensor.id}copy(){return new im([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.id))&&t.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(n!==-1&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);wo(e,this.elementShape,"TensorList shape mismatch: ");let o=Dd(this.elementShape,this.tensors,e);return j(()=>{let s=this.tensors.map(i=>K(i,o));return xr(s,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");let n=Dd(this.elementShape,this.tensors,e),o=this.tensors.pop();return wo(o.shape,e,"TensorList shape mismatch: "),K(o,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(wo(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");er(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(this.maxNumElements!==-1&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);this.tensors.length=e}getItem(e,t,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(this.tensors[e]==null)throw new Error(`element at index ${e} is null.`);wo(this.tensors[e].shape,t,"TensorList shape mismatch: ");let o=Dd(this.elementShape,this.tensors,t);return K(this.tensors[e],o)}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.`);wo(this.elementShape,t.shape,"TensorList shape mismatch: "),er(t),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);wo(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());let o=Dd(this.elementShape,this.tensors,n);return e.length===0?mn([],[0].concat(o)):j(()=>{let s=e.map(i=>K(this.tensors[i],o));return xr(s,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);wo(this.elementShape,t,"TensorList shape mismatch: ");let n=Dd(this.elementShape,this.tensors,t);return this.size()===0?mn([],[0].concat(n)):j(()=>{let o=this.tensors.map(s=>K(s,n));return mt(o,0)})}};function k3(r,e,t){let n=r.dtype;if(r.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${r.shape}`);if(r.dtype!==t)throw new Error(`Invalid data types; op elements ${r.dtype}, but list elements ${t}`);let o=r.shape.slice(1);wo(o,e,"TensorList shape mismatch: ");let s=Vr(r);return new im(s,e,n)}function I3(r,e,t){return new im([],r,e,t)}function v3(r,e,t,n){if(e.length!==r.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${r.shape[0]}`);let o=Math.max(...e);if(n!=null&&n!==-1&&o>=n)throw new Error(`Max index must be < array size (${o} vs. ${n})`);let s=new im([],t,r.dtype,n),i=Vr(r,0);return e.forEach((a,l)=>{s.setItem(a,i[l])}),s}function w3(r,e,t){let n=0,o=e.map(p=>(n+=p,n));if(n!==r.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: ${r.shape}`);let s=r.shape.slice(1),i=Ek(s,t),a=n===0?0:r.size/n,l=j(()=>{let p=[];r=K(r,[1,n,a]);for(let c=0;c<e.length;++c){let m=c===0?0:o[c-1],f=[0,m,0],d=[1,e[c],a];p[c]=K(Ke(r,f,d),i)}return r.dispose(),p}),u=new im([],t,r.dtype,e.length);for(let p=0;p<l.length;p++)u.setItem(p,l[p]);return u}var _3=async(r,e,t)=>{switch(r.op){case"If":case"StatelessIf":{let n=_("thenBranch",r,e,t),o=_("elseBranch",r,e,t),s=_("cond",r,e,t),i=_("args",r,e,t);return(await s.data())[0]?t.functionMap[n].executeFunctionAsync(i,t.tensorArrayMap,t.tensorListMap):t.functionMap[o].executeFunctionAsync(i,t.tensorArrayMap,t.tensorListMap)}case"While":case"StatelessWhile":{let n=_("body",r,e,t),o=_("cond",r,e,t),s=_("args",r,e,t),i=await t.functionMap[o].executeFunctionAsync(s,t.tensorArrayMap,t.tensorListMap),a=s.map(p=>p.id),l=await i[0].data();i.forEach(p=>{!p.kept&&a.indexOf(p.id)===-1&&p.dispose()});let u=s;for(;l[0];){let p=u;u=await t.functionMap[n].executeFunctionAsync(u,t.tensorArrayMap,t.tensorListMap);let c=u.map(f=>f.id);p.forEach(f=>{!f.kept&&a.indexOf(f.id)===-1&&c.indexOf(f.id)===-1&&f.dispose()});let m=await t.functionMap[o].executeFunctionAsync(u,t.tensorArrayMap,t.tensorListMap);l=await m[0].data(),m.forEach(f=>{!f.kept&&a.indexOf(f.id)===-1&&c.indexOf(f.id)===-1&&f.dispose()})}return u}case"LoopCond":{let n=_("pred",r,e,t);return[Ya(n)]}case"Switch":{let n=_("pred",r,e,t),o=_("data",r,e,t);return o.kept||(o=Ya(o)),(await n.data())[0]?[void 0,o]:[o,void 0]}case"Merge":{let n=r.inputNames.find(o=>Ur(o,e,t)!==void 0);if(n){let o=Ur(n,e,t);return[Ya(o)]}return}case"Enter":{let n=_("frameName",r,e,t),o=_("tensor",r,e,t);return t.enterFrame(n),[Ya(o)]}case"Exit":{let n=_("tensor",r,e,t);return t.exitFrame(),[Ya(n)]}case"NextIteration":{let n=_("tensor",r,e,t);return t.nextIteration(),[Ya(n)]}case"TensorArrayV3":{let n=_("size",r,e,t),o=_("dtype",r,e,t),s=_("elementShape",r,e,t),i=_("dynamicSize",r,e,t),a=_("clearAfterRead",r,e,t),l=_("identicalElementShapes",r,e,t),u=_("name",r,e,t),p=new JN(u,o,n,s,l,i,a);return t.addTensorArray(p),[p.idTensor,be(1)]}case"TensorArrayWriteV3":{let n=_("tensorArrayId",r,e,t),o=_("index",r,e,t),s=_("tensor",r,e,t),i=t.getTensorArray(n.id);return i.write(o,s),[i.idTensor]}case"TensorArrayReadV3":{let n=_("tensorArrayId",r,e,t),o=_("index",r,e,t);return[t.getTensorArray(n.id).read(o)]}case"TensorArrayGatherV3":{let n=_("tensorArrayId",r,e,t),o=_("indices",r,e,t),s=_("dtype",r,e,t);return[t.getTensorArray(n.id).gather(o,s)]}case"TensorArrayScatterV3":{let n=_("tensorArrayId",r,e,t),o=_("indices",r,e,t),s=_("tensor",r,e,t),i=t.getTensorArray(n.id);return i.scatter(o,s),[i.idTensor]}case"TensorArrayConcatV3":{let n=_("tensorArrayId",r,e,t),o=t.getTensorArray(n.id),s=_("dtype",r,e,t);return[o.concat(s)]}case"TensorArraySplitV3":{let n=_("tensorArrayId",r,e,t),o=_("tensor",r,e,t),s=_("lengths",r,e,t),i=t.getTensorArray(n.id);return i.split(s,o),[i.idTensor]}case"TensorArraySizeV3":{let n=_("tensorArrayId",r,e,t),o=t.getTensorArray(n.id);return[be(o.size(),"int32")]}case"TensorArrayCloseV3":{let n=_("tensorArrayId",r,e,t),o=t.getTensorArray(n.id);return o.clearAndClose(),[o.idTensor]}case"TensorListSetItem":{let n=_("tensorListId",r,e,t),o=_("index",r,e,t),s=_("tensor",r,e,t),i=t.getTensorList(n.id);return i.setItem(o,s),[i.idTensor]}case"TensorListGetItem":{let n=_("tensorListId",r,e,t),o=_("index",r,e,t),s=_("elementShape",r,e,t),i=_("elementDType",r,e,t);return[t.getTensorList(n.id).getItem(o,s,i)]}case"TensorListScatterV2":case"TensorListScatter":{let n=_("indices",r,e,t),o=_("tensor",r,e,t),s=_("elementShape",r,e,t),i=_("numElements",r,e,t),a=v3(o,n,s,i);return t.addTensorList(a),[a.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let n=_("elementShape",r,e,t),o=_("elementDType",r,e,t),s;r.op==="TensorListReserve"?s="numElements":s="maxNumElements";let i=_(s,r,e,t),a=I3(n,o,i);return t.addTensorList(a),[a.idTensor]}case"TensorListGather":{let n=_("tensorListId",r,e,t),o=_("indices",r,e,t),s=_("elementShape",r,e,t),i=_("elementDType",r,e,t);return[t.getTensorList(n.id).gather(o,i,s)]}case"TensorListStack":{let n=_("tensorListId",r,e,t),o=_("elementShape",r,e,t),s=_("elementDType",r,e,t),i=_("numElements",r,e,t);return[t.getTensorList(n.id).stack(o,s,i)]}case"TensorListFromTensor":{let n=_("tensor",r,e,t),o=_("elementShape",r,e,t),s=_("elementDType",r,e,t),i=k3(n,o,s);return t.addTensorList(i),[i.idTensor]}case"TensorListConcat":{let n=_("tensorListId",r,e,t),o=t.getTensorList(n.id),s=_("dtype",r,e,t),i=_("elementShape",r,e,t);return[o.concat(s,i)]}case"TensorListPushBack":{let n=_("tensorListId",r,e,t),o=_("tensor",r,e,t),s=t.getTensorList(n.id);return s.pushBack(o),[s.idTensor]}case"TensorListPopBack":{let n=_("tensorListId",r,e,t),o=_("elementShape",r,e,t),s=_("elementDType",r,e,t);return[t.getTensorList(n.id).popBack(o,s)]}case"TensorListSplit":{let n=_("tensor",r,e,t),o=_("elementShape",r,e,t),s=_("lengths",r,e,t),i=w3(n,s,o);return t.addTensorList(i),[i.idTensor]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};function C3(r,e,t){let[n,o]=_("fusedOps",r,e,t),s=n==="biasadd",i=!s,a=o==="prelu",l=n==="fusedbatchnorm",u=_("numArgs",r,e,t);if(s){if(a&&u!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!a&&s&&u!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(l)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");let p=_("strides",r,e,t),c=ny(r,e,t),m=_("dataFormat",r,e,t).toUpperCase(),f=_("dilations",r,e,t),[d,h]=_("args",r,e,t);i&&(h=d,d=void 0);let g=_("leakyreluAlpha",r,e,t);return{stride:p,pad:c,dataFormat:m,dilations:f,biasArg:d,preluArg:h,activationFunc:o,leakyreluAlpha:g}}var S3=(r,e,t)=>{switch(r.op){case"Conv1D":{let n=_("stride",r,e,t),o=_("pad",r,e,t),s=_("dataFormat",r,e,t).toUpperCase(),i=_("dilation",r,e,t);return[wc(_("x",r,e,t),_("filter",r,e,t),n,o,s,i)]}case"Conv2D":{let n=_("strides",r,e,t),o=ny(r,e,t),s=_("dataFormat",r,e,t).toUpperCase(),i=_("dilations",r,e,t);return[zn(_("x",r,e,t),_("filter",r,e,t),[n[1],n[2]],o,s,[i[1],i[2]])]}case"_FusedConv2D":{let{stride:n,pad:o,dataFormat:s,dilations:i,biasArg:a,preluArg:l,activationFunc:u,leakyreluAlpha:p}=C3(r,e,t);return[bs.conv2d({x:_("x",r,e,t),filter:_("filter",r,e,t),strides:[n[1],n[2]],pad:o,dataFormat:s,dilations:[i[1],i[2]],bias:a,activation:u,preluActivationWeights:l,leakyreluAlpha:p})]}case"FusedDepthwiseConv2dNative":{let{stride:n,pad:o,dataFormat:s,dilations:i,biasArg:a,preluArg:l,activationFunc:u,leakyreluAlpha:p}=C3(r,e,t);return[bs.depthwiseConv2d({x:_("x",r,e,t),filter:_("filter",r,e,t),strides:[n[1],n[2]],pad:o,dataFormat:s,dilations:[i[1],i[2]],bias:a,activation:u,preluActivationWeights:l,leakyreluAlpha:p})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{let n=_("outputShape",r,e,t),o=_("strides",r,e,t),s=ny(r,e,t);return[_c(_("x",r,e,t),_("filter",r,e,t),n,[o[1],o[2]],s)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{let n=_("strides",r,e,t),o=ny(r,e,t),s=_("dilations",r,e,t),i=_("dataFormat",r,e,t).toUpperCase();return[Ra(_("input",r,e,t),_("filter",r,e,t),[n[1],n[2]],o,i,[s[1],s[2]])]}case"Conv3D":{let n=_("strides",r,e,t),o=_("pad",r,e,t),s=_("dataFormat",r,e,t).toUpperCase(),i=_("dilations",r,e,t);return[ig(_("x",r,e,t),_("filter",r,e,t),[n[1],n[2],n[3]],o,s,[i[1],i[2],i[3]])]}case"AvgPool":{let n=_("strides",r,e,t),o=_("pad",r,e,t),s=_("kernelSize",r,e,t);return[Kl(_("x",r,e,t),[s[1],s[2]],[n[1],n[2]],o)]}case"MaxPool":{let n=_("strides",r,e,t),o=_("pad",r,e,t),s=_("kernelSize",r,e,t);return[Xl(_("x",r,e,t),[s[1],s[2]],[n[1],n[2]],o)]}case"MaxPoolWithArgmax":{let n=_("strides",r,e,t),o=_("pad",r,e,t),s=_("kernelSize",r,e,t),i=_("includeBatchInIndex",r,e,t),{result:a,indexes:l}=uS(_("x",r,e,t),[s[1],s[2]],[n[1],n[2]],o,i);return[a,l]}case"AvgPool3D":{let n=_("strides",r,e,t),o=_("pad",r,e,t),s=_("kernelSize",r,e,t);return[og(_("x",r,e,t),[s[1],s[2],s[3]],[n[1],n[2],n[3]],o)]}case"MaxPool3D":{let n=_("strides",r,e,t),o=_("pad",r,e,t),s=_("kernelSize",r,e,t);return[bg(_("x",r,e,t),[s[1],s[2],s[3]],[n[1],n[2],n[3]],o)]}case"Dilation2D":{let n=_("strides",r,e,t),o=_("pad",r,e,t),s=_("dilations",r,e,t),i=n[1],a=n[2],l=s[1],u=s[2];return[ug(_("x",r,e,t),_("filter",r,e,t),[i,a],o,[l,u],"NHWC")]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var N3=(r,e,t)=>{switch(r.op){case"Fill":{let n=_("shape",r,e,t),o=_("dtype",r,e,t),s=_("value",r,e,t);return[$a(n,s,o)]}case"LinSpace":{let n=_("start",r,e,t),o=_("stop",r,e,t),s=_("num",r,e,t);return[nS(n,o,s)]}case"Multinomial":{let n=_("logits",r,e,t),o=_("numSamples",r,e,t),s=_("seed",r,e,t);return[pS(n,o,s)]}case"OneHot":{let n=_("indices",r,e,t),o=_("depth",r,e,t),s=_("onValue",r,e,t),i=_("offValue",r,e,t);return[Ea(n,o,s,i)]}case"Ones":return[on(_("shape",r,e,t),_("dtype",r,e,t))];case"OnesLike":return[Br(_("x",r,e,t))];case"RandomUniform":return[za(_("shape",r,e,t),_("minval",r,e,t),_("maxval",r,e,t),_("dtype",r,e,t))];case"Range":{let n=_("start",r,e,t),o=_("stop",r,e,t),s=_("step",r,e,t);return[Jl(n,o,s,_("dtype",r,e,t))]}case"TruncatedNormal":{let n=_("shape",r,e,t),o=_("mean",r,e,t),s=_("stdDev",r,e,t),i=_("seed",r,e,t);return[Gc(n,o,s,_("dtype",r,e,t),i)]}case"Zeros":return[Rt(_("shape",r,e,t),_("dtype",r,e,t))];case"ZerosLike":return[Me(_("x",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};function QN(r,e,t){let n=_("boxes",r,e,t),o=_("scores",r,e,t),s=_("maxOutputSize",r,e,t),i=_("iouThreshold",r,e,t),a=_("scoreThreshold",r,e,t),l=_("softNmsSigma",r,e,t);return{boxes:n,scores:o,maxOutputSize:s,iouThreshold:i,scoreThreshold:a,softNmsSigma:l}}var A3=async(r,e,t)=>{switch(r.op){case"NonMaxSuppressionV5":{let{boxes:n,scores:o,maxOutputSize:s,iouThreshold:i,scoreThreshold:a,softNmsSigma:l}=QN(r,e,t),u=await Si.nonMaxSuppressionWithScoreAsync(n,o,s,i,a,l);return[u.selectedIndices,u.selectedScores]}case"NonMaxSuppressionV4":{let{boxes:n,scores:o,maxOutputSize:s,iouThreshold:i,scoreThreshold:a}=QN(r,e,t),l=_("padToMaxOutputSize",r,e,t),u=await Si.nonMaxSuppressionPaddedAsync(n,o,s,i,a,l);return[u.selectedIndices,u.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{let{boxes:n,scores:o,maxOutputSize:s,iouThreshold:i,scoreThreshold:a}=QN(r,e,t);return[await Si.nonMaxSuppressionAsync(n,o,s,i,a)]}case"Where":{let n=ue(_("condition",r,e,t),"bool"),o=[await AT(n)];return n.dispose(),o}case"ListDiff":return dS(_("x",r,e,t),_("y",r,e,t));default:throw TypeError(`Node type ${r.op} is not implemented`)}};var D3=(r,e,t)=>{switch(r.op){case"TopKV2":{let n=_("x",r,e,t),o=_("k",r,e,t),s=_("sorted",r,e,t),i=Sg(n,o,s);return[i.values,i.indices]}case"Unique":{let n=_("x",r,e,t),o=ed(n);return[o.values,o.indices]}case"UniqueV2":{let n=_("x",r,e,t),o=_("axis",r,e,t),s=ed(n,o);return[s.values,s.indices]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var E3=(r,e,t)=>{switch(r.op){case"Const":return e[r.name];case"PlaceholderWithDefault":let n=_("default",r,e,t);return[Ur(r.name,e,t)||n];case"Placeholder":return[Ur(r.name,e,t)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let u=_("x",r,e,t);return[Ya(u)]}case"IdentityN":return _("x",r,e,t).map(u=>Ya(u));case"Snapshot":let o=_("x",r,e,t);return[Ya(o)];case"Shape":return[Zt(_("x",r,e,t).shape,"int32")];case"ShapeN":return _("x",r,e,t).map(u=>Zt(u.shape));case"Size":return[be(_("x",r,e,t).size,"int32")];case"Rank":return[be(_("x",r,e,t).rank,"int32")];case"NoOp":return[be(1)];case"Print":let s=_("x",r,e,t),i=_("data",r,e,t),a=_("message",r,e,t),l=_("summarize",r,e,t);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(a);for(let u=0;u<i.length;u++)console.log(Array.prototype.slice.call(i[u].dataSync()).slice(0,l));return[s];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var eA=class{constructor(e,t){this.keyDType=e;this.valueDType=t;this.handle=be(0),this.tensorMap=new Map,er(this.handle)}get id(){return this.handle.id}clearAndClose(){this.tensorMap.forEach(e=>e.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return be(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);let n=await e.data();return this.tensorMap.forEach(o=>o.dispose()),this.tensorMap.clear(),j(()=>{let o=Vr(t),s=n.length,i=o.length;x.assert(s===i,()=>`The number of elements doesn't match, keys has ${s} elements, the values has ${i} elements.`);for(let a=0;a<s;a++){let l=n[a],u=o[a];er(u),this.tensorMap.set(l,u)}return this.handle})}async find(e,t){this.checkKeyAndValueTensor(e,t);let n=await e.data();return j(()=>{let o=[];for(let s=0;s<n.length;s++){let i=n[s],a=this.findWithDefault(i,t);o.push(a)}return xr(o)})}findWithDefault(e,t){let n=this.tensorMap.get(e);return n!=null?n:t}checkKeyAndValueTensor(e,t){if(e.dtype!==this.keyDType)throw new Error(`Expect key dtype ${this.keyDType}, but got ${e.dtype}`);if(t.dtype!==this.valueDType)throw new Error(`Expect value dtype ${this.valueDType}, but got ${t.dtype}`)}};var M3=async(r,e,t,n)=>{switch(r.op){case"HashTable":case"HashTableV2":{let o=_("keyDType",r,e,t),s=_("valueDType",r,e,t),i=new eA(o,s);return n.addHashTable(r.name,i),[i.handle]}case"LookupTableImport":case"LookupTableImportV2":{let o=_("tableHandle",r,e,t,n),s=_("keys",r,e,t),i=_("values",r,e,t);return[await n.getHashTableById(o.id).import(s,i)]}case"LookupTableFind":case"LookupTableFindV2":{let o=_("tableHandle",r,e,t,n),s=_("keys",r,e,t),i=_("defaultValue",r,e,t);return[await n.getHashTableById(o.id).find(s,i)]}case"LookupTableSize":case"LookupTableSizeV2":{let o=_("tableHandle",r,e,t,n);return[n.getHashTableById(o.id).tensorSize()]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var F3=(r,e,t)=>{switch(r.op){case"ResizeBilinear":{let n=_("images",r,e,t),o=_("size",r,e,t),s=_("alignCorners",r,e,t),i=_("halfPixelCenters",r,e,t);return[Si.resizeBilinear(n,[o[0],o[1]],s,i)]}case"ResizeNearestNeighbor":{let n=_("images",r,e,t),o=_("size",r,e,t),s=_("alignCorners",r,e,t),i=_("halfPixelCenters",r,e,t);return[Si.resizeNearestNeighbor(n,[o[0],o[1]],s,i)]}case"CropAndResize":{let n=_("image",r,e,t),o=_("boxes",r,e,t),s=_("boxInd",r,e,t),i=_("cropSize",r,e,t),a=_("method",r,e,t),l=_("extrapolationValue",r,e,t);return[Si.cropAndResize(n,o,s,i,a,l)]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var R3=(r,e,t)=>{switch(r.op){case"Equal":return[Io(_("a",r,e,t),_("b",r,e,t))];case"NotEqual":return[gs(_("a",r,e,t),_("b",r,e,t))];case"Greater":return[yr(_("a",r,e,t),_("b",r,e,t))];case"GreaterEqual":return[io(_("a",r,e,t),_("b",r,e,t))];case"Less":return[Ac(_("a",r,e,t),_("b",r,e,t))];case"LessEqual":return[lo(_("a",r,e,t),_("b",r,e,t))];case"LogicalAnd":return[Xr(_("a",r,e,t),_("b",r,e,t))];case"LogicalNot":return[ql(_("a",r,e,t))];case"LogicalOr":return[Mc(_("a",r,e,t),_("b",r,e,t))];case"Select":case"SelectV2":return[Wt(_("condition",r,e,t),_("a",r,e,t),_("b",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var L3=(r,e,t)=>{switch(r.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[tt(_("a",r,e,t),_("b",r,e,t),_("transposeA",r,e,t),_("transposeB",r,e,t))];case"Einsum":return[eS(_("equation",r,e,t),..._("tensors",r,e,t))];case"Transpose":return[nt(_("x",r,e,t),_("perm",r,e,t))];case"_FusedMatMul":let[n,o]=_("fusedOps",r,e,t),s=n==="biasadd",i=o==="prelu",a=_("numArgs",r,e,t),l=_("leakyreluAlpha",r,e,t);if(s){if(i&&a!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&a!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}let[u,p]=_("args",r,e,t);return[bs.matMul({a:_("a",r,e,t),b:_("b",r,e,t),transposeA:_("transposeA",r,e,t),transposeB:_("transposeB",r,e,t),bias:u,activation:o,preluActivationWeights:p,leakyreluAlpha:l})];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var $3=(r,e,t)=>{switch(r.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[fs(_("x",r,e,t),_("mean",r,e,t),_("variance",r,e,t),_("offset",r,e,t),_("scale",r,e,t),_("epsilon",r,e,t))];case"FusedBatchNormV3":return[fs(_("x",r,e,t),_("mean",r,e,t),_("variance",r,e,t),_("offset",r,e,t),_("scale",r,e,t),_("epsilon",r,e,t))];case"LRN":return[dg(_("x",r,e,t),_("radius",r,e,t),_("bias",r,e,t),_("alpha",r,e,t),_("beta",r,e,t))];case"Softmax":return[Ql(_("x",r,e,t))];case"LogSoftmax":return[Ec(_("x",r,e,t))];case"SparseToDense":return[DT(_("sparseIndices",r,e,t),_("outputShape",r,e,t),_("sparseValues",r,e,t),_("defaultValue",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var P3=(r,e,t)=>{switch(r.op){case"Max":{let i=_("axis",r,e,t),a=_("keepDims",r,e,t);return[nn(_("x",r,e,t),i,a)]}case"Mean":{let i=_("axis",r,e,t),a=_("keepDims",r,e,t);return[Ft(_("x",r,e,t),i,a)]}case"Min":{let i=_("axis",r,e,t),a=_("keepDims",r,e,t);return[tp(_("x",r,e,t),i,a)]}case"Sum":{let i=_("axis",r,e,t),a=_("keepDims",r,e,t);return[Te(_("x",r,e,t),i,a)]}case"All":{let i=_("axis",r,e,t),a=_("keepDims",r,e,t);return[kc(_("x",r,e,t),i,a)]}case"Any":{let i=_("axis",r,e,t),a=_("keepDims",r,e,t);return[Qu(_("x",r,e,t),i,a)]}case"ArgMax":{let i=_("axis",r,e,t);return[ep(_("x",r,e,t),i)]}case"ArgMin":{let i=_("axis",r,e,t);return[Jh(_("x",r,e,t),i)]}case"Prod":{let i=_("axis",r,e,t),a=_("keepDims",r,e,t);return[Fc(_("x",r,e,t),i,a)]}case"Cumsum":{let i=_("axis",r,e,t),a=_("exclusive",r,e,t),l=_("reverse",r,e,t);return[Sc(_("x",r,e,t),i,a,l)]}case"Bincount":let n=_("x",r,e,t),o=_("weights",r,e,t),s=_("size",r,e,t);return[sg(n,o,s)];case"DenseBincount":{let i=_("x",r,e,t),a=_("weights",r,e,t),l=_("size",r,e,t),u=_("binaryOutput",r,e,t);return[JC(i,a,l,u)]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var B3=(r,e,t)=>{switch(r.op){case"ConcatV2":case"Concat":{let n=_("n",r,e,t),o=_("axis",r,e,t),s=_("tensors",r,e,t);return s=s.slice(0,n),[mt(s,o)]}case"Gather":{let n=_("x",r,e,t),o=_("indices",r,e,t);return[Ba(n,ue(o,"int32"),0)]}case"GatherV2":{let n=_("axis",r,e,t),o=_("batchDims",r,e,t),s=_("x",r,e,t),i=_("indices",r,e,t);return[Ba(s,ue(i,"int32"),n,o)]}case"Reverse":{let n=_("dims",r,e,t),o=[];for(let i=0;i<n.length;i++)n[i]&&o.push(i);let s=_("x",r,e,t);return[wr(s,o)]}case"ReverseV2":{let n=_("axis",r,e,t),o=_("x",r,e,t);return[wr(o,n)]}case"Slice":{let n=_("begin",r,e,t),o=_("size",r,e,t);return[Ke(_("x",r,e,t),n,o)]}case"StridedSlice":{let n=_("begin",r,e,t),o=_("end",r,e,t),s=_("strides",r,e,t),i=_("beginMask",r,e,t),a=_("endMask",r,e,t),l=_("ellipsisMask",r,e,t),u=_("newAxisMask",r,e,t),p=_("shrinkAxisMask",r,e,t),c=_("x",r,e,t);return[_g(c,n,o,s,i,a,l,u,p)]}case"Pack":return j(()=>{let n=_("axis",r,e,t),o=_("tensors",r,e,t),s=o[0].shape,i=Xo(o[0]).shape,a=o.map(l=>{let u=x.arraysEqual(l.shape,s);if(!u&&!x.arraysEqual(Xo(l).shape,i))throw new Error("the input tensors shape does not match");return u?l:K(l,s)});return[xr(a,n)]});case"Unpack":{let n=_("axis",r,e,t),o=_("tensor",r,e,t);return Vr(o,n)}case"Tile":{let n=_("reps",r,e,t);return[qo(_("x",r,e,t),n)]}case"Split":case"SplitV":{let n=_("axis",r,e,t),o=_("numOrSizeSplits",r,e,t),s=_("x",r,e,t);return Rr(s,o,n)}case"ScatterNd":{let n=_("indices",r,e,t),o=_("values",r,e,t),s=_("shape",r,e,t);return[_P(n,o,s)]}case"GatherNd":{let n=_("x",r,e,t),o=_("indices",r,e,t);return[SP(n,o)]}case"SparseToDense":{let n=_("sparseIndices",r,e,t),o=_("outputShape",r,e,t),s=_("sparseValues",r,e,t),i=_("defaultValue",r,e,t);return[DT(n,s,o,s.dtype===i.dtype?i:ue(i,s.dtype))]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var O3=(r,e,t)=>{switch(r.op){case"SparseFillEmptyRows":{let{outputIndices:n,outputValues:o,emptyRowIndicator:s,reverseIndexMap:i}=Ag.sparseFillEmptyRows(_("indices",r,e,t),_("values",r,e,t),_("denseShape",r,e,t),_("defaultValue",r,e,t));return[n,o,s,i]}case"SparseReshape":{let{outputIndices:n,outputShape:o}=Ag.sparseReshape(_("inputIndices",r,e,t),_("inputShape",r,e,t),_("newShape",r,e,t));return[n,o]}case"SparseSegmentMean":return[Ag.sparseSegmentMean(_("data",r,e,t),_("indices",r,e,t),_("segmentIds",r,e,t))];case"SparseSegmentSum":return[Ag.sparseSegmentSum(_("data",r,e,t),_("indices",r,e,t),_("segmentIds",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var z3=(r,e,t)=>{switch(r.op){case"FFT":return[np(_("x",r,e,t))];case"IFFT":return[eu(_("x",r,e,t))];case"RFFT":return[op(_("x",r,e,t))];case"IRFFT":return[Qf(_("x",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var G3=(r,e,t)=>{switch(r.op){case"StringNGrams":{let{nGrams:n,nGramsSplits:o}=OT.stringNGrams(_("data",r,e,t),_("dataSplits",r,e,t),_("separator",r,e,t),_("nGramWidths",r,e,t),_("leftPad",r,e,t),_("rightPad",r,e,t),_("padWidth",r,e,t),_("preserveShortSequences",r,e,t));return[n,o]}case"StringSplit":{let{indices:n,values:o,shape:s}=OT.stringSplit(_("input",r,e,t),_("delimiter",r,e,t),_("skipEmpty",r,e,t));return[n,o,s]}case"StringToHashBucketFast":return[OT.stringToHashBucketFast(_("input",r,e,t),_("numBuckets",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var W3=(r,e,t)=>{switch(r.op){case"Cast":return[ue(_("x",r,e,t),_("dtype",r,e,t))];case"ExpandDims":{let n=_("axis",r,e,t);return[Wr(_("x",r,e,t),n)]}case"Squeeze":{let n=_("axis",r,e,t);return[Xo(_("x",r,e,t),n)]}case"Reshape":return[K(_("x",r,e,t),_("shape",r,e,t))];case"MirrorPad":return[yg(_("x",r,e,t),_("padding",r,e,t),_("mode",r,e,t))];case"PadV2":case"Pad":return[kn(_("x",r,e,t),_("padding",r,e,t),_("constantValue",r,e,t))];case"SpaceToBatchND":{let n=_("blockShape",r,e,t),o=_("paddings",r,e,t);return[Yl(_("x",r,e,t),n,o)]}case"BatchToSpaceND":{let n=_("blockShape",r,e,t),o=_("crops",r,e,t);return[Vl(_("x",r,e,t),n,o)]}case"DepthToSpace":{let n=_("blockSize",r,e,t),o=_("dataFormat",r,e,t).toUpperCase();return[lg(_("x",r,e,t),n,o)]}case"BroadcastTo":return[Ul(_("x",r,e,t),_("shape",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};function tA(r,e,t,n){let o=((s,i,a)=>{switch(s.category){case"arithmetic":return j(()=>y3(s,i,a));case"basic_math":return j(()=>x3(s,i,a));case"control":return _3(s,i,a);case"convolution":return j(()=>S3(s,i,a));case"creation":return j(()=>N3(s,i,a));case"dynamic":return A3(s,i,a);case"evaluation":return j(()=>D3(s,i,a));case"image":return j(()=>F3(s,i,a));case"graph":return j(()=>E3(s,i,a));case"logical":return j(()=>R3(s,i,a));case"matrices":return j(()=>L3(s,i,a));case"normalization":return j(()=>$3(s,i,a));case"reduction":return j(()=>P3(s,i,a));case"slice_join":return j(()=>B3(s,i,a));case"sparse":return j(()=>O3(s,i,a));case"spectral":return j(()=>z3(s,i,a));case"string":return j(()=>G3(s,i,a));case"transformation":return j(()=>W3(s,i,a));case"hash_table":return M3(s,i,a,n);case"custom":let l=yk(s.op);if(l&&l.customExecutor)return l.customExecutor(new ZN(s,i,a));throw TypeError(`Custom op ${s.op} is not registered.`);default:throw TypeError(`Unknown op '${s.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(r,e,t);return x.isPromise(o)?o.then(s=>[].concat(s)):[].concat(o)}var Mk=class{constructor(e={},t={},n={},o={}){this.weightMap=e;this.tensorArrayMap=t;this.tensorListMap=n;this.functionMap=o;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(){let e=[];for(let t=0;t<this.contexts.length-1;t++){let n=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(n))}e.push(""),this._currentContextIds=e}contextIdforContexts(e){return e?e.map(t=>t.id===0&&t.iterationId===0?"":`${t.frameName}-${t.iterationId}`).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(this.contexts&&this.contexts.length>1)this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift();else throw new Error("Cannot exit frame, the context is empty")}nextIteration(){if(this.contexts&&this.contexts.length>0){this.contexts=this.contexts.slice(),this.lastId++;let 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(let t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(let t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}};function rA(r,e,t,n){let o=new Set,s=[],i=null,a=null,l=new Set,u=Object.keys(r).map(m=>Xn(m)[0]),p=[];n!=null&&(p=n.map(m=>Xn(m.name)[0]));let c=[...e];for(;c.length>0;){let m=c.pop();if((nA(m)||pfe(m)||cfe(m))&&i==null&&(i=m,a=i.children.map(f=>f.name).filter(f=>o.has(f))),o.add(m.name),t[m.name]==null&&u.indexOf(m.name)===-1&&p.indexOf(m.name)===-1){if(m.inputs.length===0){s.push(m.name);continue}m.inputs.forEach(f=>{l.has(f.name)||(l.add(f.name),c.push(f))})}}return{inputs:r,outputs:e,usedNodes:o,missingInputs:s,dynamicNode:i,syncInputs:a}}function K3(r,e,t){let{usedNodes:n,inputs:o}=t,s=[],i=Object.keys(o).map(p=>Xn(p)[0]).map(p=>r.nodes[p]),a=r.initNodes;i.forEach(p=>{n.has(p.name)&&s.push(p)}),r.weights.forEach(p=>{n.has(p.name)&&s.push(p)}),a!=null&&a.forEach(p=>{n.has(p.name)&&s.push(p)});let l=new Set,u=[];for(;s.length>0;){let p=s.pop();l.add(p.name),e[p.name]||u.push(p),p.children.forEach(c=>{!l.has(c.name)&&n.has(c.name)&&c.inputs.every(m=>l.has(m.name))&&s.push(c)})}return u}var ife=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],lfe=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],ufe=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"];function nA(r){return ife.indexOf(r.op)>=0}function pfe(r){return lfe.indexOf(r.op)>=0}function cfe(r){return ufe.indexOf(r.op)>=0}var Ed=class{constructor(e,t){this.graph=e;this.parent=t;this.compiledMap=new Map;this._weightMap={};this.SEPERATOR=",";this._functions={};this._functionExecutorMap={};this._outputs=e.outputs,this._inputs=e.inputs,this._initNodes=e.initNodes,this._signature=e.signature,this._functions=e.functions,e.functions!=null&&Object.keys(e.functions).forEach(n=>{this._functionExecutorMap[n]=new Ed(e.functions[n],this)})}get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){let t=Object.keys(e).map(n=>e[n].map(o=>o.id));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(e=>e.signatureKey||e.name)}get outputNodes(){return this._outputs.map(e=>{let 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){let n=e.map(s=>s.name).sort(),o=t.map(s=>s.name).sort();return n.join(this.SEPERATOR)+"--"+o.join(this.SEPERATOR)}compile(e,t){let n=rA(e,t,this.weightMap,this._initNodes),{missingInputs:o,dynamicNode:s,syncInputs:i}=n;if(s!=null)throw new Error(`This execution contains the node '${s.name}', which has the dynamic op '${s.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${i}]`);if(o.length>0){let a=t.map(u=>u.name),l=Object.keys(e);throw new Error(`Cannot compute the outputs [${a}] from the provided inputs [${l}]. Missing the following inputs: [${o}]`)}return K3(this.graph,this.weightMap,n)}execute(e,t){e=this.mapInputs(e);let n=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);let o=n.map(c=>this.graph.nodes[Xn(c)[0]]),s=t.map(c=>Xn(c)[0]),i=s.map(c=>this.graph.nodes[c]);i.length===0&&(i=this._outputs);let a=this.getCompilationKey(o,i),l=this.compiledMap.get(a);l==null&&(l=this.compile(e,i),this.compiledMap.set(a,l));let u={},p={};return j(()=>{let c=new Mk(this.weightMap,u,p,this.functionExecutorMap),m={...this.weightMap};Object.keys(e).forEach(h=>{let[g,b]=Xn(h),y=[];y[b]=e[h],m[g]=y});let f=this.getFrozenTensorIds(m),d={};for(let h=0;h<l.length;h++){let g=l[h];if(!m[g.name]){let b=tA(g,m,c,this._resourceManager);if(x.isPromise(b))throw new Error(`The execution of the op '${g.op}' returned a promise. Please use model.executeAsync() instead.`);m[g.name]=b,this.checkTensorForDisposal(g.name,g,m,c,f,s,d)}}return this.parent==null&&c.dispose(f),t.map(h=>Ur(h,m,c))})}getFrozenTensorIds(e){let t=[].concat.apply([],Object.keys(e).map(n=>e[n]).map(n=>n.map(o=>o.id)));return new Set(t)}checkTensorForDisposal(e,t,n,o,s,i,a){t.category==="control"||i.indexOf(e)!==-1||(n[e].forEach(l=>{l!=null&&(a[l.id]=(a[l.id]||0)+t.children.length)}),t.inputs.forEach(l=>{if(l.category!=="control"){let u=d3(l.name,n,o);u!=null&&u.forEach(p=>{if(p&&!p.kept&&!s.has(p.id)){let c=a[p.id];c===1?(p.dispose(),delete a[p.id]):c!=null&&a[p.id]--}})}}))}async executeAsync(e,t){return this._executeAsync(e,t)}async _executeAsync(e,t,n=!1,o={},s={}){n||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));let i=new Mk(this.weightMap,o,s,this.functionExecutorMap),a=await this.executeWithControlFlow(e,i,t,n),l=t.map(m=>Ur(m,a,i)),u=l.map(m=>m.id),p=Object.keys(e).map(m=>e[m].id),c=new Set([...u,...p,...this.weightIds]);return Object.keys(a).forEach(m=>{a[m].forEach(d=>{d&&!d.kept&&!d.isDisposed&&!c.has(d.id)&&d.dispose()})}),this.parent==null&&i.dispose(c),l}async executeFunctionAsync(e,t,n){let o=e.reduce((s,i,a)=>(s[this.inputs[a].name]=i,s),{});return this._executeAsync(o,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,o){let s=Object.keys(e),i=s.map(T=>this.graph.nodes[Xn(T)[0]]),a=n.map(T=>Xn(T)[0]),l=a.map(T=>this.graph.nodes[T]);l.length===0&&(l=this._outputs);let{usedNodes:u,missingInputs:p,dynamicNode:c,syncInputs:m}=rA(e,l,this.weightMap,this._initNodes),f=[...i,...this.graph.weights,...this._initNodes||[]].map(T=>({node:T,contexts:t.currentContext})),d={...this.weightMap};Object.keys(e).forEach(T=>{let[k,I]=Xn(T),S=[];S[I]=e[T],d[k]=S});let h={},g=this.getFrozenTensorIds(d),b={};for(;f.length>0;){let T=this.processStack(i,f,t,d,b,g,a,h,u);await Promise.all(T)}c==null&&!o&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");let y=l.filter(T=>!nA(T)&&!Ur(T.name,d,t)).map(T=>T.name);if(y.length>0){let T="";throw c!=null&&(T=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${m}]`),new Error(`Cannot compute the outputs [${y}] from the provided inputs [${s}]. Consider providing the following inputs: [${p}]. ${T}`)}return d}processStack(e,t,n,o,s,i,a,l,u){let p=[];for(;t.length>0;){let c=t.pop();n.currentContext=c.contexts;let m="";if(c.node.op==="Enter"&&_("isConstant",c.node,o,n)&&([m]=Xa(c.node.name,n)),o[c.node.name]==null){let f=tA(c.node,o,n,this._resourceManager);m||([m]=Xa(c.node.name,n));let d=n.currentContext;x.isPromise(f)?p.push(f.then(h=>(o[m]=h,n.currentContext=d,this.checkTensorForDisposal(m,c.node,o,n,i,a,l),this.processChildNodes(c.node,t,n,o,s,u),h))):(o[m]=f,this.checkTensorForDisposal(m,c.node,o,n,i,a,l),this.processChildNodes(c.node,t,n,o,s,u))}else this.processChildNodes(c.node,t,n,o,s,u)}return p}processChildNodes(e,t,n,o,s,i){e.children.forEach(a=>{let[l]=Xa(a.name,n);s[l]||!i.has(a.name)||(a.op==="Merge"?a.inputNames.some(u=>!!Ur(u,o,n))&&(s[l]=!0,t.push({contexts:n.currentContext,node:a})):a.inputNames.every(u=>!!Ur(u,o,n))&&(s[l]=!0,t.push({contexts:n.currentContext,node:a})))})}dispose(){Object.keys(this.weightMap).forEach(e=>this.weightMap[e].forEach(t=>t.dispose()))}checkInputShapeAndType(e){Object.keys(e).forEach(t=>{let n=e[t],[o]=Xn(t),s=this.graph.nodes[o];if(s.attrParams.shape&&s.attrParams.shape.value){let i=s.attrParams.shape.value,a=i.length===n.shape.length&&n.shape.every((l,u)=>i[u]===-1||i[u]===l);x.assert(a,()=>`The shape of dict['${s.name}'] provided in model.execute(dict) must be [${i}], but was [${n.shape}]`)}s.attrParams.dtype&&s.attrParams.dtype.value&&x.assert(n.dtype===s.attrParams.dtype.value,()=>`The dtype of dict['${s.name}'] provided in model.execute(dict) must be ${s.attrParams.dtype.value}, but was ${n.dtype}`)})}mapInputs(e){let t={};for(let n in e)if(this._signature!=null&&this._signature.inputs!=null&&this._signature.inputs[n]!=null){let o=this._signature.inputs[n];t[o.name]=e[n]}else t[n]=e[n];return t}checkInputs(e){let t=Object.keys(e).filter(n=>{let[o]=Xn(n);return this.graph.nodes[o]==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=>this._signature!=null&&this._signature.outputs!=null&&this._signature.outputs[t]!=null?this._signature.outputs[t].name:t,{})}checkOutputs(e){e.forEach(t=>{let[n]=Xn(t);if(!this.graph.nodes[n])throw new Error(`The output '${t}' is not found in the graph`)})}};var oA=class{constructor(e={},t={}){this.hashTableNameToHandle=e;this.hashTableMap=t}addHashTable(e,t){this.hashTableNameToHandle[e]=t.handle,this.hashTableMap[t.id]=t}getHashTableHandleByName(e){return this.hashTableNameToHandle[e]}getHashTableById(e){return this.hashTableMap[e]}dispose(){for(let e in this.hashTableMap)this.hashTableMap[e].clearAndClose(),delete this.hashTableMap[e];for(let e in this.hashTableNameToHandle)this.hashTableNameToHandle[e].dispose(),delete this.hashTableNameToHandle[e]}};var mfe="?tfjs-format=file",ffe="model.json",sA=class{constructor(e,t={}){this.modelUrl=e;this.loadOptions=t;this.version="n/a";t==null&&(this.loadOptions={}),this.resourceManager=new oA}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}get metadata(){return this.artifacts.userDefinedMetadata}get modelSignature(){return this.signature}findIOHandler(){let e=this.modelUrl;if(e.load!=null)this.handler=e;else if(this.loadOptions.requestInit!=null)this.handler=fn.browserHTTPRequest(e,this.loadOptions);else{let t=fn.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(fn.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.");let e=await this.handler.load();return this.loadSync(e)}loadSync(e){this.artifacts=e;let t=this.artifacts.modelTopology,n;this.artifacts.userDefinedMetadata!=null&&this.artifacts.userDefinedMetadata.signature!=null?n=this.artifacts.userDefinedMetadata.signature:n=this.artifacts.signature,this.signature=n,this.version=`${t.versions.producer}.${t.versions.minConsumer}`;let o=fn.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new Ed(Tk.Instance.transformGraph(t,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(o),this.executor.resourceManager=this.resourceManager,e.modelInitializer!=null&&e.modelInitializer.node!=null){let s=Tk.Instance.transformGraph(e.modelInitializer);this.initializer=new Ed(s),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializer.executeAsync({},[])}return!0}async save(e,t){if(typeof e=="string"){let n=fn.getSaveHandlers(e);if(n.length===0)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(n.length>1)throw new Error(`Found more than one (${n.length}) save handlers for URL '${e}'`);e=n[0]}if(e.save==null)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return e.save(this.artifacts)}predict(e,t){return this.execute(e,this.outputNodes)}normalizeInputs(e){if(!(e instanceof rt)&&!Array.isArray(e))return e;if(e=Array.isArray(e)?e:[e],e.length!==this.inputNodes.length)throw new Error(`Input tensor count mismatch,the graph model has ${this.inputNodes.length} placeholders, while there are ${e.length} input tensors.`);return this.inputNodes.reduce((t,n,o)=>(t[n]=e[o],t),{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}execute(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let n=this.executor.execute(e,t);return n.length>1?n:n[0]}async executeAsync(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let n=await this.executor.executeAsync(e,t);return n.length>1?n:n[0]}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,n)=>(t[n]=[e[n]],t),{})}dispose(){this.executor.dispose(),this.initializer&&this.initializer.dispose(),this.resourceManager.dispose()}};async function dfe(r,e={}){if(r==null)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");e==null&&(e={}),e.fromTFHub&&r.load==null&&(r.endsWith("/")||(r=r+"/"),r=`${r}${ffe}${mfe}`);let t=new sA(r,e);return await t.load(),t}var hfe="3.7.0";var kA={};Ge(kA,{CSVDataset:()=>ly,Dataset:()=>Fi,FileDataSource:()=>fy,TextLineDataset:()=>ay,URLDataSource:()=>dy,array:()=>CG,csv:()=>$G,func:()=>PG,generator:()=>BG,microphone:()=>zG,version_data:()=>GG,webcam:()=>OG,zip:()=>SG});var _G=Wi(mA());var pG=Wi(mA());function sG(r,e){return Rk(r,e)}function Rk(r,e,t=new Map,n=new Set){if(r==null)return null;if(n.has(r))throw new Error("Circular references are not supported.");if(t.has(r))return t.get(r);let o=e(r);if(o.recurse&&o.value!==null)throw new Error("A deep map function may not return both a value and recurse=true.");if(o.recurse)if(hp(r)){let s=Array.isArray(r)?[]:{};n.add(r);for(let i in r){let a=r[i],l=Rk(a,e,t,n);s[i]=l}return n.delete(r),s}else throw new Error(`Can't recurse into non-iterable type: ${r}`);else return t.set(r,o.value),o.value}function aG(r,e=fA){return iG(r,e)}function iG(r,e,t=new Set){let n=r[0];if(t.has(n))throw new Error("Circular references are not supported.");let o=e(r);if(o.recurse&&o.value!==null)throw new Error("A deep zip function may not return both a value and recurse=true.");if(o.recurse)if(hp(n)){let s=Array.isArray(n)?[]:{};t.add(n);for(let i in n){let a=r.map(u=>u[i]),l=iG(a,e,t);s[i]=l}return t.delete(n),s}else throw new Error(`Can't recurse into non-iterable type: ${n}`);else return o.value}function fA(r){return r===null?null:hp(r[0])?{value:null,recurse:!0}:{value:r,recurse:!1}}async function Lk(r,e){let t=new Map;Rk(r,e,t);for(let o of Array.from(t.keys())){let s=t.get(o);if(x.isPromise(s)){let i=await s;t.set(o,i)}}return Rk(r,e,t)}function hp(r){return r!=null&&!ArrayBuffer.isView(r)&&(Array.isArray(r)||typeof r=="object"&&!(r instanceof rt))}function lG(r){return r==null||Ife(r)||Array.isArray(r)||typeof r=="object"&&r instanceof rt||x.isTypedArray(r)}function Ife(r){return r===null||typeof r!="object"&&typeof r!="function"}function uG(r){return sG(r,vfe)}function vfe(r){return r instanceof rt?{value:r.clone(),recurse:!1}:hp(r)?{value:null,recurse:!0}:{value:r,recurse:!1}}var oy=class{constructor(e){this.capacity=e;this.begin=0;this.end=0;if(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(let t of e)this.push(t)}pop(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);let 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.");let 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.");let t=this.wrap(this.begin+e),n=this.get(t);return this.set(t,this.pop()),n}};var dA=class extends oy{constructor(){super(dA.INITIAL_CAPACITY)}isFull(){return!1}push(e){super.isFull()&&this.expand(),super.push(e)}unshift(e){super.isFull()&&this.expand(),super.unshift(e)}expand(){let e=this.capacity*2,t=new Array(e),n=this.length();for(let o=0;o<n;o++)t[o]=this.get(this.wrap(this.begin+o));this.data=t,this.capacity=e,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=n}},$k=dA;$k.INITIAL_CAPACITY=32;function hA(r){return new fG(r)}function sy(r){return new dG(r)}function cG(r,e){return new bA(r,e)}function mG(r,e=lu.FAIL){return new vG(r,e)}var _r=class{async toArray(){let e=[],t=await this.next();for(;!t.done;)e.push(t.value),t=await this.next();return e}async toArrayForTest(){let e=this.prefetch(100),t=[],n=await e.next();for(;!n.done;)t.push(n.value),n=await e.next();return t}async resolveFully(){let e=await this.next();for(;!e.done;)e=await this.next()}async resolveWhile(e){let t=await this.next(),n=e(t.value);for(;!t.done&&n;)t=await this.next(),n=e(t.value)}handleErrors(e){return new kG(this,e)}filter(e){return new xG(this,e)}map(e){return new TG(this,e)}mapAsync(e){return new gA(this,e)}serialMapAsync(e){return new gA(this,e).serial()}flatmap(e){return new IG(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 yG(this,e,t)}columnMajorBatch(e,t=!0,n=fA){return this.rowMajorBatch(e,t).map(s=>aG(s,n))}concatenate(e,t){return new bA(hA([this,e]),t)}take(e){return e<0||e==null?this:new bG(this,e)}skip(e){return e<0||e==null?this:new gG(this,e)}prefetch(e){return new yA(this,e)}shuffle(e,t){return new wG(this,e,t)}serial(){return new hG(this)}},fG=class extends _r{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};let e=this.items[this.trav];return this.trav++,{value:uG(e),done:!1}}},dG=class extends _r{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}}},hG=class extends _r{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()}},gG=class extends _r{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;){let e=await this.upstream.next();if(e.done)return e;Be(e.value)}return this.upstream.next()}},bG=class extends _r{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()}},yG=class extends _r{constructor(e,t,n=!0){super();this.upstream=e;this.batchSize=t;this.enableSmallLastBatch=n;this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> RowMajorBatch`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){let e=[];for(;e.length<this.batchSize;){let 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}}},xG=class extends _r{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(;;){let e=await this.upstream.next();if(e.done||this.predicate(e.value))return e;Be(e.value)}}},TG=class extends _r{constructor(e,t){super();this.upstream=e;this.transform=t}summary(){return`${this.upstream.summary()} -> Map`}async next(){let e=await this.upstream.next();if(e.done)return{value:null,done:!0};let t=ms.getTensorsInContainer(e.value),n=this.transform(e.value),o=ms.getTensorsInContainer(n);for(let s of t)ms.isTensorInList(s,o)||s.dispose();return{value:n,done:!1}}},kG=class extends _r{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}}}},gA=class extends _r{constructor(e,t){super();this.upstream=e;this.transform=t}summary(){return`${this.upstream.summary()} -> AsyncMap`}async next(){let e=await this.upstream.next();if(e.done)return{value:null,done:!0};let t=ms.getTensorsInContainer(e.value),n=await this.transform(e.value),o=ms.getTensorsInContainer(n);for(let s of t)ms.isTensorInList(s,o)||s.dispose();return{value:n,done:!1}}},Md=class extends _r{constructor(){super();this.outputQueue=new $k,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}}},IG=class extends Md{constructor(e,t){super();this.upstream=e;this.transform=t}summary(){return`${this.upstream.summary()} -> Flatmap`}async pump(){let e=await this.upstream.next();if(e.done)return!1;let t=ms.getTensorsInContainer(e.value),n=this.transform(e.value),o=ms.getTensorsInContainer(n);this.outputQueue.pushAll(n);for(let s of t)ms.isTensorInList(s,o)||s.dispose();return!0}},bA=class extends _r{constructor(e,t){super();this.baseErrorHandler=t;this.lastRead=null;this.iterator=null;this.moreIterators=e}summary(){return"TODO: fill in upstream of chained summaries -> Chained"}async next(){return this.lastRead=this.readFromChain(this.lastRead),this.lastRead}async readFromChain(e){if(await e,this.iterator==null){let n=await this.moreIterators.next();if(n.done)return{value:null,done:!0};this.iterator=n.value,this.baseErrorHandler!=null&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler))}let t=await this.iterator.next();return t.done?(this.iterator=null,this.readFromChain(e)):t}},lu;(function(n){n[n.FAIL=0]="FAIL",n[n.SHORTEST=1]="SHORTEST",n[n.LONGEST=2]="LONGEST"})(lu||(lu={}));var vG=class extends _r{constructor(e,t=0){super();this.iterators=e;this.mismatchMode=t;this.count=0;this.currentPromise=null}summary(){return"{TODO: fill in upstream of zip summaries} -> Zip"}async nextState(e){await e;let t=0,n=0;function o(i){return i instanceof _r?{value:i.next().then(l=>(t++,l.done&&n++,l.value)),recurse:!1}:{value:null,recurse:!0}}let s=await Lk(this.iterators,o);if(t===n)return{value:null,done:!0};if(n>0)switch(this.mismatchMode){case 0:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case 1:return{value:null,done:!0};case 2:default:}return this.count++,{value:s,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}},yA=class extends _r{constructor(e,t){super();this.upstream=e;this.bufferSize=t;this.buffer=new oy(t)}summary(){return`${this.upstream.summary()} -> Prefetch`}refill(){for(;!this.buffer.isFull();){let e=this.upstream.next();this.buffer.push(e)}}next(){return this.refill(),this.buffer.shift()}},wG=class extends yA{constructor(e,t,n){super(e,t);this.upstream=e;this.windowSize=t;this.upstreamExhausted=!1;this.random=pG.alea(n||x.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();){let 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}}};var Fi=class{constructor(){this.size=null}batch(e,t=!0){let n=this;x.assert(e>0,()=>`batchSize needs to be positive, but it is
|
|
${e}`);let o;return this.size===Infinity||this.size==null?o=this.size:t?o=Math.ceil(this.size/e):o=Math.floor(this.size/e),co(async()=>(await n.iterator()).columnMajorBatch(e,t,wfe),o)}concatenate(e){let t=this,n;return this.size===Infinity||e.size===Infinity?n=Infinity:this.size!=null&&e.size!=null?n=this.size+e.size:n=null,co(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){let t=this,n;return this.size===Infinity?n=Infinity:n=null,co(async()=>(await t.iterator()).filter(o=>j(()=>e(o))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){let t=this;return co(async()=>(await t.iterator()).map(n=>j(()=>e(n))),this.size)}mapAsync(e){let t=this;return co(async()=>(await t.iterator()).mapAsync(e),this.size)}prefetch(e){if(e==null)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");let t=this;return co(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){let t=this,n;return this.size!=null&&e>0?n=this.size*e:e===0?n=0:this.size!=null&&(e===void 0||e<0)?n=Infinity:n=null,co(async()=>{let o=sy(async()=>({value:await t.iterator(),done:!1}));return cG(o.take(e))},n)}skip(e){let t=this,n;return this.size!=null&&e>=0&&this.size>=e?n=this.size-e:this.size!=null&&(this.size<e||e===void 0||e<0)?n=0:n=null,co(async()=>(await t.iterator()).skip(e),n)}shuffle(e,t,n=!0){if(e==null||e<0)throw this.size==null?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);let o=this,s=_G.alea(t||x.now().toString());return co(async()=>{let i=s.int32();return n&&(i+=s.int32()),(await o.iterator()).shuffle(e,i.toString())},this.size)}take(e){let t=this,n;return this.size!=null&&this.size>e?n=e:this.size!=null&&this.size<=e?n=this.size:n=null,co(async()=>(await t.iterator()).take(e),n)}async toArray(){if(this.size===Infinity)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===Infinity)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}};Fi.MAX_BUFFER_SIZE=1e4;function co(r,e=null){return new class extends Fi{constructor(){super(...arguments);this.size=e}async iterator(){return r()}}}function CG(r){return co(async()=>hA(r),r.length)}function SG(r){if(!hp(r))throw new Error("The argument to zip() must be an object or array.");let e;if(Array.isArray(r))for(let t=0;t<r.length;t++)e=e==null?r[t].size:Math.min(e,r[t].size);else if(r instanceof Object)for(let t in r)e=e==null?r[t].size:Math.min(e,r[t].size);return co(async()=>{let t=await Lk(r,n=>{if(n instanceof Fi)return{value:n.iterator(),recurse:!1};if(hp(n))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return mG(t,lu.SHORTEST)},e)}function wfe(r){if(r===null)return null;let e=r[0];return lG(e)?{value:_fe(r),recurse:!1}:{value:null,recurse:!0}}function _fe(r){if(r.length===0)throw new Error("Can't make a batch of zero elements.");return r[0]instanceof rt?xr(r):mn(r)}var ay=class extends Fi{constructor(e){super();this.input=e}async iterator(){return(await this.input.iterator()).decodeUTF8().split(`
|
|
`).map(o=>(o.endsWith("\r")&&(o=o.slice(0,-1)),o))}};var Pk='"',iy=Symbol("out"),NG=Symbol("field"),Bk=Symbol("quote"),xA=Symbol("quoteafterquote"),AG=Symbol("quoteinquote"),ly=class extends Fi{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 ay(e),t||(t={}),this.hasHeader=t.hasHeader!==!1,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(x.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(){let 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&&x.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);let t=this.fullColumnNames.reduce((o,s)=>(o[s]=o[s]+1||1,o),{}),n=Object.keys(t).filter(o=>t[o]>1);if(x.assert(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs){for(let o of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(o)===-1)throw new Error('The key "'+o+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){let t=await(await this.base.iterator()).next();if(t.done)throw new Error("No data was found for CSV parsing.");let n=t.value;return this.parseRow(n,!1)}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){let t=this.parseRow(e),n={},o={};for(let s=0;s<this.fullColumnNames.length;s++){let i=this.fullColumnNames[s],a=this.columnConfigs?this.columnConfigs[i]:null;if(!(this.configuredColumnsOnly&&!a)){let l=t[s],u=null;if(l==="")if(a&&a.default!==void 0)u=a.default;else{if(a&&(a.required||a.isLabel))throw new Error(`Required column ${i} is empty in this line: ${e}`);u=void 0}else{let p=Number(l);if(isNaN(p))a&&a.dtype==="bool"?u=this.getBoolean(l):u=l;else if(!a||!a.dtype)u=p;else switch(a.dtype){case"float32":u=p;break;case"int32":u=Math.floor(p);break;case"bool":u=this.getBoolean(l);break;default:u=p}}a&&a.isLabel?o[i]=u:n[i]=u}}return Object.keys(o).length===0?n:{xs:n,ys:o}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){let n=[],o=0,s=e.length,i=iy;for(let a=0;a<s;a++)switch(i){case iy:switch(e.charAt(a)){case Pk:o=a+1,i=Bk;break;case this.delimiter:if(o=a+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),i=iy;break;default:i=NG,o=a;break}break;case NG:switch(e.charAt(a)){case this.delimiter:n.push(e.substring(o,a)),i=iy,o=a+1;break;default:}break;case Bk:switch(e.charAt(a)){case Pk:i=xA;break;default:}break;case xA:switch(e.charAt(a)){case this.delimiter:n.push(e.substring(o,a-1)),i=iy,o=a+1;break;case Pk:i=Bk;break;default:i=AG;break}break;case AG:switch(e.charAt(a)){case Pk:i=Bk;break;default:}break;default:}if(i===xA?n.push(e.substring(o,s-1)):n.push(e.substring(o)),t&&n.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${n}`);return n}};var uy=class extends _r{constructor(e){super();this.microphoneConfig=e;this.isClosed=!1;this.fftSize=e.fftSize||1024;let 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(X().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");let t=new uy(e);return await t.start(),t}async start(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:this.audioTrackConstraints==null?!0:this.audioTrackConstraints,video:!1})}catch(n){throw new Error(`Error thrown while initializing video stream: ${n.message}`)}if(!this.stream)throw new Error("Could not obtain audio from microphone.");let 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}`);let 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)}async next(){if(this.isClosed)return{value:null,done:!0};let e,t,n=await this.getAudioData();if(this.includeSpectrogram){let o=this.flattenQueue(n.freqDataQueue);e=this.getTensorFromAudioDataArray(o,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){let o=this.flattenQueue(n.timeDataQueue);t=this.getTensorFromAudioDataArray(o,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:e,waveform:t},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){let e=[],t=[],n=0;return new Promise(o=>{let s=setInterval(()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-Infinity&&o({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++n===this.numFrames&&(clearInterval(s),o({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){let t=e[0].length,n=new Float32Array(e.length*t);return e.forEach((o,s)=>n.set(o,s*t)),n}getTensorFromAudioDataArray(e,t){let n=new Float32Array(x.sizeFromShape(t));return n.set(e,n.length-e.length),mn(n,t)}};var py=class extends _r{constructor(e,t){super();this.webcamVideoElement=e;this.webcamConfig=t;this.isClosed=!0;this.resize=!1;if(this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=Zt([0],"int32"),this.webcamConfig.centerCrop){let n=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,o=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,s=(1-n)/2,i=(1-o)/2,a=s+n,l=o+i;this.cropBox=Ci([i,s,l,a],[1,4])}else this.cropBox=Ci([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(X().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}let n=new py(e,t);return await n.start(),n}async start(){this.webcamConfig.facingMode&&x.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=gT.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 j(()=>{let t=Wr(ue(e,"float32"),0),n;n=Si.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let o=n.shape;return K(n,o.slice(1))})}async capture(){return(await this.next()).value}stop(){this.stream.getTracks().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.")}};var cy=class{};var Ok=class extends _r{split(e){return new DG(this,e)}},DG=class extends Ok{constructor(e,t){super();this.upstream=e;this.impl=new EG(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},EG=class extends Md{constructor(e,t){super();this.upstream=e;this.separator=t;this.carryover=""}summary(){return`${this.upstream.summary()} -> Split('${this.separator}')`}async pump(){let e=await this.upstream.next();if(e.done)return this.carryover===""?!1:(this.outputQueue.push(this.carryover),this.carryover="",!0);let t=e.value.split(this.separator);t[0]=this.carryover+t[0];for(let n of t.slice(0,-1))this.outputQueue.push(n);return this.carryover=t[t.length-1],!0}};var TA=class extends _r{decodeUTF8(){return new FG(this)}},FG=class extends Ok{constructor(e){super();this.upstream=e;this.impl=new RG(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},RG=class extends Md{constructor(e){super();this.upstream=e;if(X().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:t}=MG();this.decoder=new t("utf8")}}summary(){return`${this.upstream.summary()} -> Utf8`}async pump(){let e=await this.upstream.next(),t;if(e.done)return!1;t=e.value;let n;return X().get("IS_BROWSER")?n=this.decoder.decode(t,{stream:!0}):n=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0}};var my=class extends TA{constructor(e,t={}){super();this.file=e;this.options=t;x.assert(e instanceof Uint8Array||(X().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(){return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?{value:null,done:!0}:{value:await new Promise((t,n)=>{let o=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)t(new Uint8Array(this.file.slice(this.offset,o)));else{let s=new FileReader;s.onload=a=>{let l=s.result;if(l instanceof ArrayBuffer&&(l=new Uint8Array(l)),!(l instanceof Uint8Array))return n(new TypeError("FileReader returned unknown type."));t(l)},s.onabort=a=>n(new Error("Aborted")),s.onerror=a=>n(new Error(a.type));let i=this.file.slice(this.offset,o);s.readAsArrayBuffer(i)}this.offset=o}),done:!1}}};async function LG(r,e={}){let t,n;typeof r=="string"?t=r:(t=r.url,n=Cfe(r));let o=await x.fetch(t,n);if(o.ok){let s=new Uint8Array(await o.arrayBuffer());return new my(s,e)}else throw new Error(o.statusText)}var Cfe=r=>({method:r.method,headers:r.headers,body:r.body,mode:r.mode,credentials:r.credentials,cache:r.cache,redirect:r.redirect,referrer:r.referrer,integrity:r.integrity});function zk(r){return typeof r=="string"&&r.substr(0,7)==="file://"}var fy=class extends cy{constructor(e,t={}){super();this.input=e;this.options=t}async iterator(){if(zk(this.input)&&X().get("IS_NODE")){let e=Ap("fs");this.input=e.readFileSync(this.input.substr(7))}return new my(this.input,this.options)}};var dy=class extends cy{constructor(e,t={}){super();this.url=e;this.fileOptions=t}async iterator(){return zk(this.url)?new fy(this.url,this.fileOptions).iterator():LG(this.url,this.fileOptions)}};function $G(r,e={}){return new ly(new dy(r),e)}function PG(r){let e=sy(r);return co(async()=>e)}function BG(r){return co(async()=>{let e=await r();return sy(()=>e.next())})}async function OG(r,e){return py.create(r,e)}async function zG(r){return uy.create(r)}var GG="3.7.0";function ie(r,e){Array.isArray(r)||(r=[r]),r.forEach(t=>{t!=null&&x.assert(t.dtype!=="complex64",()=>`${e} does not support complex64 tensors in the CPU backend.`)})}var Sfe=gn.whereImpl,IA=class extends ii{constructor(){super();this.blockSize=48;this.firstUse=!0;this.data=new Fu(this,Ma())}nextDataId(){return IA.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,X().get("IS_NODE")&&C.warn(`
|
|
============================
|
|
Hi there \u{1F44B}. 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.
|
|
============================`));let o={id:this.nextDataId()};return this.data.set(o,{values:e,dtype:n,refCount:1}),o}makeTensorInfo(e,t,n){let o;if(t==="string"&&n!=null&&n.length>0&&x.isString(n[0])){let s=n.map(i=>x.encodeString(i));o=this.write(s,e,t)}else o=this.write(n,e,t);return{dataId:o,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){let t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){let t=this.data.get(e);t.refCount--}}move(e,t,n,o,s){this.data.set(e,{values:t,dtype:o,refCount:s})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){let{dtype:t,complexTensorInfos:n}=this.data.get(e);if(t==="complex64"){let o=this.readSync(n.real.dataId),s=this.readSync(n.imag.dataId);return C.mergeRealAndImagArrays(o,s)}return this.data.get(e).values}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(o=>x.decodeString(o))}catch(o){throw new Error("Failed to decode encoded string bytes into utf-8")}return ve(e.shape,e.dtype,n)}makeOutput(e,t,n){let o=this.write(e,t,n);return Ma().makeTensorFromDataId(o,t,n,this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;let{complexTensorInfos:n}=this.data.get(e);n!=null&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){let t=x.now();return e(),{kernelMs:x.now()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){ie([e],"where");let t=this.readSync(e.dataId);return Sfe(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}},hy=IA;hy.nextDataId=0;var gW={};Ge(gW,{addImpl:()=>wA,bincountImpl:()=>Ld,bincountReduceImpl:()=>Gk,ceilImpl:()=>_A,concatImpl:()=>Wk,equalImpl:()=>CA,expImpl:()=>NA,expm1Impl:()=>DA,floorImpl:()=>EA,gatherNdImpl:()=>Kk,gatherV2Impl:()=>Vk,greaterEqualImpl:()=>FA,greaterImpl:()=>MA,lessEqualImpl:()=>LA,lessImpl:()=>RA,linSpaceImpl:()=>Uk,logImpl:()=>$A,maxImpl:()=>jk,maximumImpl:()=>PA,minimumImpl:()=>BA,multiplyImpl:()=>gy,negImpl:()=>OA,notEqualImpl:()=>zA,prodImpl:()=>GA,rangeImpl:()=>Hk,rsqrtImpl:()=>WA,simpleAbsImpl:()=>vA,sliceImpl:()=>KA,sparseFillEmptyRowsImpl:()=>qk,sparseReshapeImpl:()=>Xk,sparseSegmentReductionImpl:()=>Pd,squaredDifferenceImpl:()=>VA,stridedSliceImpl:()=>Yk,stringNGramsImpl:()=>Zk,stringSplitImpl:()=>Jk,stringToHashBucketFastImpl:()=>Qk,subImpl:()=>UA,tileImpl:()=>eI,topKImpl:()=>tI,transposeImpl:()=>$d,uniqueImpl:()=>rI});function vA(r){let e=new Float32Array(r.length);for(let t=0;t<r.length;++t)e[t]=Math.abs(r[t]);return e}var Nfe=r=>{let{x:e}=r.inputs,t=r.backend;ie(e,"abs");let n=new Float32Array(x.sizeFromShape(e.shape)),o=t.data.get(e.dataId).values;return n=vA(o),t.makeOutput(n,e.shape,"float32")},WG={kernelName:Gs,backendName:"cpu",kernelFunc:Nfe};function lt(r){return(e,t,n,o,s)=>{let i=C.assertAndGetBroadcastShape(e,t),a=i.length,l=x.computeStrides(i),u=x.sizeFromShape(i),p=x.getTypedArrayFromDType(s,u),c=e.length,m=t.length,f=x.computeStrides(e),d=x.computeStrides(t),h=C.getBroadcastDims(e,i),g=C.getBroadcastDims(t,i);if(h.length+g.length===0)for(let b=0;b<p.length;++b)p[b]=r(n[b%n.length],o[b%o.length]);else for(let b=0;b<p.length;++b){let y=x.indexToLoc(b,a,l),T=y.slice(-c);h.forEach(N=>T[N]=0);let k=x.locToIndex(T,c,f),I=y.slice(-m);g.forEach(N=>I[N]=0);let S=x.locToIndex(I,m,d);p[b]=r(n[k],o[S])}return[p,i]}}function jr(r){let{inputs:e,backend:t}=r,{real:n,imag:o}=e,s=t.data.get(n.dataId).values,i=t.data.get(o.dataId).values,a=t.makeTensorInfo(n.shape,"complex64"),l=t.data.get(a.dataId);return l.complexTensorInfos={real:t.makeTensorInfo(n.shape,"float32",s),imag:t.makeTensorInfo(o.shape,"float32",i)},a}var KG={kernelName:lc,backendName:"cpu",kernelFunc:jr};function Fd(r,e,t="float32"){if(t==="complex64"){let o=Fd(r,e,"float32"),s=Fd(r,e,"float32");return jr({inputs:{real:o,imag:s},backend:r})}let n=x.makeZerosTypedArray(x.sizeFromShape(e),t);return r.makeTensorInfo(e,t,n)}function bn(r){let{inputs:e,backend:t}=r,{x:n}=e;return t.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}var VG={kernelName:Lo,backendName:"cpu",kernelFunc:bn};function Ss(r){let{inputs:e,backend:t}=r,{input:n}=e,o=t.data.get(n.dataId).complexTensorInfos.real,s=t.data.get(o.dataId).values;return t.makeTensorInfo(o.shape,o.dtype,s)}var UG={kernelName:cc,backendName:"cpu",kernelFunc:Ss};function Ns(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{dtype:s}=n;if(s==="complex64"){if(o.dtype==="complex64")return bn({inputs:{x:o},backend:t});let i=Fd(t,o.shape,o.dtype),a=Ns({inputs:{x:o},backend:t,attrs:{dtype:"float32"}}),l=jr({inputs:{real:a,imag:i},backend:t});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(a),l}if(o.dtype==="complex64"){let i=Ss({inputs:{input:o},backend:t}),a=Ns({inputs:{x:i},backend:t,attrs:{dtype:s}});return t.disposeIntermediateTensorInfo(i),a}if(!x.hasEncodingLoss(o.dtype,s)){let i=bn({inputs:{x:o},backend:t});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(s==="int32"){let i=t.data.get(o.dataId).values,a=Int32Array.from(i);return t.makeTensorInfo(o.shape,"int32",a)}if(s==="bool"){let i=t.data.get(o.dataId).values,a=x.toTypedArray([0],o.dtype),[l,u]=lt((p,c)=>p!==c?1:0)(o.shape,[],i,a,"bool");return t.makeTensorInfo(u,"bool",l)}throw new Error(`Error in Cast: failed to cast ${o.dtype} to ${s}`)}var jG={kernelName:Do,backendName:"cpu",kernelFunc:Ns};function dt(r,e,t,n){return t==null?({inputs:o,backend:s})=>{let{a:i,b:a}=o,l=s;ie([i,a],r);let u=l.data.get(i.dataId).values,p=l.data.get(a.dataId).values,c=i.dtype==="string"?C.fromUint8ToStringArray(u):u,m=i.dtype==="string"?C.fromUint8ToStringArray(p):p,f=n||i.dtype,[d,h]=e(i.shape,a.shape,c,m,f);return l.makeTensorInfo(h,f,d)}:({inputs:o,backend:s})=>{let{a:i,b:a}=o,l=s;if(i.dtype==="complex64"||a.dtype==="complex64"){let u=Ns({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),p=l.data.get(u.dataId),c=p.complexTensorInfos.real,m=p.complexTensorInfos.imag,f=l.data.get(c.dataId).values,d=l.data.get(m.dataId).values,h=Ns({inputs:{x:a},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(h.dataId),b=g.complexTensorInfos.real,y=g.complexTensorInfos.imag,T=l.data.get(b.dataId).values,k=l.data.get(y.dataId).values,[I,S,N]=t(i.shape,a.shape,f,d,T,k),F=l.makeTensorInfo(N,"float32",I),$=l.makeTensorInfo(N,"float32",S),O=jr({inputs:{real:F,imag:$},backend:l});return l.disposeIntermediateTensorInfo(u),l.disposeIntermediateTensorInfo(h),l.disposeIntermediateTensorInfo(F),l.disposeIntermediateTensorInfo($),O}else{let u=l.data.get(i.dataId).values,p=l.data.get(a.dataId).values,c=n||i.dtype,[m,f]=e(i.shape,a.shape,u,p,c);return l.makeTensorInfo(f,c,m)}}}function Rd(r){return(e,t,n,o,s,i)=>{let a=C.assertAndGetBroadcastShape(e,t),l=x.sizeFromShape(a),u=a.length,p=x.computeStrides(a),c=x.getTypedArrayFromDType("float32",l),m=x.getTypedArrayFromDType("float32",l),f=C.getBroadcastDims(e,a),d=C.getBroadcastDims(t,a),h=C.mergeRealAndImagArrays(n,o),g=C.mergeRealAndImagArrays(s,i),b=e.length,y=x.computeStrides(e),T=t.length,k=x.computeStrides(t);if(f.length+d.length===0)for(let I=0;I<c.length;I++){let S=I%h.length,N=I%g.length,F=r(h[S*2],h[S*2+1],g[N*2],g[N*2+1]);c[I]=F.real,m[I]=F.imag}else for(let I=0;I<c.length;I++){let S=x.indexToLoc(I,u,p),N=S.slice(-b);f.forEach(q=>N[q]=0);let F=x.locToIndex(N,b,y),$=S.slice(-T);d.forEach(q=>$[q]=0);let O=x.locToIndex($,T,k),V=r(h[F*2],h[F*2+1],g[O*2],g[O*2+1]);c[I]=V.real,m[I]=V.imag}return[c,m,a]}}var wA=lt((r,e)=>r+e),Afe=Rd((r,e,t,n)=>({real:r+t,imag:e+n})),uu=dt(so,wA,Afe),HG={kernelName:so,backendName:"cpu",kernelFunc:uu};function Ld(r,e,t,n,o){let s=x.sizeFromShape(n),i=x.makeZerosTypedArray(o,t);for(let a=0;a<r.length;a++){let l=r[a];if(l<0)throw new Error("Input x must be non-negative!");l>=o||(s>0?i[l]+=e[a]:i[l]+=1)}return i}function Gk(r,e,t,n=!1){let o=r.shape[0],s=r.shape[1],i=ve([o,t],e.dtype);for(let a=0;a<o;a++)for(let l=0;l<s;l++){let u=r.get(a,l);if(u<0)throw new Error("Input x must be non-negative!");u>=t||(n?i.set(1,a,u):e.size>0?i.set(i.get(a,u)+e.get(a,l),a,u):i.set(i.get(a,u)+1,a,u))}return i}function As(r){return(e,t,n)=>{let o=x.getTypedArrayFromDType(t,e.length);for(let s=0;s<e.length;++s)o[s]=r(e[s],n);return o}}function ze(r,e,t){return({inputs:n,attrs:o,backend:s})=>{let{x:i}=n;if(ie(i,r),i.dtype==="string"||t==="string")throw new Error("unaryKernelFunc does not support string input/output");let a=s,l=a.data.get(i.dataId).values,u=x.sizeFromShape(i.shape),p=t||i.dtype,c=x.getArrayFromDType(p,u);for(let m=0;m<u;++m)c[m]=e(l[m],o);return a.makeTensorInfo(i.shape,p,c)}}function Ds(r,e,t){return({inputs:n,attrs:o,backend:s})=>{let{x:i}=n;if(ie(i,r),i.dtype==="string"||t==="string")throw new Error("unaryKernelFunc does not support string input/output");let a=s,l=a.data.get(i.dataId).values,u=t||i.dtype,p=e(l,u,o);return a.makeTensorInfo(i.shape,u,p)}}var _A=As(r=>Math.ceil(r)),Dfe=Ds(Eo,_A),qG={kernelName:Eo,backendName:"cpu",kernelFunc:Dfe};function Wk(r,e,t,n){let o=x.getArrayFromDType(t,x.sizeFromShape(e));if(n&&t!=="string"){let s=0;r.forEach(i=>{let a=x.sizeFromShape(i.shape);o.set(i.vals,s),s+=a})}else{let s=0;r.forEach(i=>{let a=t==="string"?C.fromUint8ToStringArray(i.vals):i.vals,l=0;for(let u=0;u<i.shape[0];++u){let p=u*e[1]+s;for(let c=0;c<i.shape[1];++c)o[p+c]=a[l++]}s+=i.shape[1]})}return o}var CA=lt((r,e)=>r===e?1:0),SA=dt(Js,CA,null,"bool"),XG={kernelName:Js,backendName:"cpu",kernelFunc:SA};var NA=As(r=>Math.exp(r)),AA=Ds(Mo,NA),YG={kernelName:Mo,backendName:"cpu",kernelFunc:AA};var DA=As(r=>Math.expm1(r)),Efe=Ds(Qs,DA),ZG={kernelName:Qs,backendName:"cpu",kernelFunc:Efe};var EA=As(r=>Math.floor(r)),Mfe=Ds(Fo,EA),JG={kernelName:Fo,backendName:"cpu",kernelFunc:Mfe};function Kk(r,e,t,n,o,s,i,a,l){let u=ve([n,s],t);for(let p=0;p<n;p++){let c=[],m=0;for(let f=0;f<o;f++){let d=r[p*o+f];m+=d*i[f],c.push(d)}if(m<0||m>=l/s)throw new Error(`Invalid indices: ${c} does not index into ${a}`);for(let f=0;f<s;f++)u.values[p*s+f]=e.get(...e.indexToLoc(m*s+f))}return u}function Vk(r,e,t){let n=ve(t,r.dtype);for(let o=0;o<n.size;++o){let i=n.indexToLoc(o).slice(),a=i[0],l=i[2],u=e.locToIndex([a,l]);i[2]=e.values[u];let p=r.locToIndex(i);n.values[o]=r.values[p]}return n}var MA=lt((r,e)=>r>e?1:0),Ffe=dt(ra,MA,null,"bool"),QG={kernelName:ra,backendName:"cpu",kernelFunc:Ffe};var FA=lt((r,e)=>r>=e?1:0),Rfe=dt(Ro,FA,null,"bool"),eW={kernelName:Ro,backendName:"cpu",kernelFunc:Rfe};var RA=lt((r,e)=>r<e?1:0),Lfe=dt(oa,RA,null,"bool"),tW={kernelName:oa,backendName:"cpu",kernelFunc:Lfe};var LA=lt((r,e)=>r<=e?1:0),$fe=dt(sa,LA,null,"bool"),rW={kernelName:sa,backendName:"cpu",kernelFunc:$fe};function Uk(r,e,t){let n=(e-r)/(t-1),o=x.makeZerosTypedArray(t,"float32");o[0]=r;for(let s=1;s<o.length;s++)o[s]=o[s-1]+n;return o}var $A=As(r=>Math.log(r)),Pfe=Ds($o,$A),nW={kernelName:$o,backendName:"cpu",kernelFunc:Pfe};function jk(r,e,t,n){let o=x.getTypedArrayFromDType(n,x.sizeFromShape(t));for(let s=0;s<o.length;++s){let i=s*e,a=r[i];for(let l=0;l<e;++l){let u=r[i+l];(Number.isNaN(u)||u>a)&&(a=u)}o[s]=a}return o}var PA=lt((r,e)=>Math.max(r,e)),Bfe=dt(Po,PA),oW={kernelName:Po,backendName:"cpu",kernelFunc:Bfe};var BA=lt((r,e)=>Math.min(r,e)),Ofe=dt(Bo,BA),sW={kernelName:Bo,backendName:"cpu",kernelFunc:Ofe};var gy=lt((r,e)=>r*e),zfe=Rd((r,e,t,n)=>({real:r*t-e*n,imag:r*n+e*t})),um=dt(Oo,gy,zfe),aW={kernelName:Oo,backendName:"cpu",kernelFunc:um};function OA(r,e,t){let n=x.createScalarValue(-1,t);return gy([],e,n,r,t)}function Gfe(r){let{inputs:e,backend:t}=r,{x:n}=e;ie(n,"neg");let o=t.data.get(n.dataId).values,[s,i]=OA(o,n.shape,n.dtype);return t.makeTensorInfo(i,n.dtype,s)}var iW={kernelName:ca,backendName:"cpu",kernelFunc:Gfe};var zA=lt((r,e)=>r!==e?1:0),Wfe=dt(ma,zA,null,"bool"),lW={kernelName:ma,backendName:"cpu",kernelFunc:Wfe};function $d(r,e,t,n,o){let s=e.length,i=x.sizeFromShape(e),a=x.computeStrides(e),l=x.computeStrides(o),u=x.getTypedArrayFromDType(t,x.sizeFromShape(o));for(let p=0;p<i;++p){let c=x.indexToLoc(p,s,a),m=new Array(c.length);for(let d=0;d<m.length;d++)m[d]=c[n[d]];let f=x.locToIndex(m,s,l);u[f]=r[p]}return u}function Cr(r){let{inputs:e,attrs:t,backend:n}=r,{x:o}=e,{perm:s}=t;ie(o,"transpose");let i=o.shape.length,a=new Array(i);for(let c=0;c<a.length;c++)a[c]=o.shape[s[c]];let l=n.data.get(o.dataId).values,u=$d(l,o.shape,o.dtype,s,a);return{dataId:n.write(u,a,o.dtype),shape:a,dtype:o.dtype}}var uW={kernelName:ps,backendName:"cpu",kernelFunc:Cr};function GA(r,e,t,n){let[o,s]=C.computeOutAndReduceShapes(r,n),i=Mr(e,"int32"),a=x.makeZerosTypedArray(x.sizeFromShape(o),i),l=x.sizeFromShape(s);for(let u=0;u<a.length;++u){let p=u*l,c=1;for(let m=0;m<l;++m)c*=t[p+m];a[u]=c}return{outVals:a,outShape:o,outDtype:i}}function Kfe(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,keepDims:i}=n;ie(o,"prod");let a=o.shape.length,l=x.parseAxisParam(s,o.shape),u=C.getAxesPermutation(l,a),p=l,c=o,m=[];u!=null&&(c=Cr({inputs:{x:o},backend:t,attrs:{perm:u}}),m.push(c),p=C.getInnerMostAxes(p.length,a));let f=t.data.get(c.dataId).values,{outVals:d,outShape:h,outDtype:g}=GA(c.shape,c.dtype,f,p),b=h;return i&&(b=C.expandShapeToKeepDim(h,l)),m.forEach(y=>t.disposeIntermediateTensorInfo(y)),t.makeTensorInfo(b,g,d)}var pW={kernelName:hi,backendName:"cpu",kernelFunc:Kfe};function Hk(r,e,t,n){let o=r===e,s=r<e&&t<0,i=e<r&&t>1;if(o||s||i)return x.makeZerosTypedArray(0,n);let a=Math.abs(Math.ceil((e-r)/t)),l=x.makeZerosTypedArray(a,n);e<r&&t===1&&(t=-1),l[0]=r;for(let u=1;u<l.length;u++)l[u]=l[u-1]+t;return l}var WA=As(r=>1/Math.sqrt(r)),Vfe=Ds(zo,WA),cW={kernelName:zo,backendName:"cpu",kernelFunc:Vfe};function KA(r,e,t,n,o){let s=br.isSliceContinous(n,e,t),i=x.sizeFromShape(t),a=x.computeStrides(n);if(s){let c=br.computeFlatOffset(e,a);return o==="string"?r.slice(c,c+i):r.subarray(c,c+i)}let l=o==="string"?C.fromUint8ToStringArray(r):r,u=ve(n,o,l),p=ve(t,o);for(let c=0;c<p.size;++c){let m=p.indexToLoc(c),f=m.map((d,h)=>d+e[h]);p.set(u.get(...f),...m)}return o==="string"?C.fromStringArrayToUint8(p.values):p.values}function Es(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{begin:s,size:i}=n;ie(o,"slice");let[a,l]=br.parseSliceParams(o,s,i);br.assertParamsValid(o,a,l);let u=t.data.get(o.dataId).values,p=KA(u,a,l,o.shape,o.dtype);return t.makeTensorInfo(l,o.dtype,p)}var mW={kernelName:Ia,backendName:"cpu",kernelFunc:Es};function qk(r,e,t,n,o,s,i){let a=e[0],l=s[0],u=new Array(l),p=new Array(a),c=e[1];if(l===0){if(a!==0)throw new Error(`Received SparseTensor with denseShape[0] = 0 but
|
|
indices.shape[0] = ${a}`);let g=x.getArrayFromDType(t,0),b=x.getArrayFromDType(o,0);return[g,[0,c],b,u,p]}let m=!0,f=0,d=new Array(l).fill(0);for(let g=0;g<a;++g){let b=r[g*c];if(b<0)throw new Error(`indices(${g}, 0) is invalid: ${b} < 0`);if(b>=l)throw new Error(`indices(${g}, 0) is invalid: ${b} >= ${l}`);++d[b],m=m&&b>=f,f=b}let h=!0;for(let g=0;g<l;++g){let b=d[g]===0;u[g]=b,h=h&&!b,d[g]=Math.max(d[g],1),g>0&&(d[g]+=d[g-1])}if(h&&m){let g=r,b=n;for(let y=0;y<a;++y)p[y]=y;return[g,[a,c],b,u,p]}else{let g=d[l-1],b=x.getArrayFromDType(t,g*c),y=x.getArrayFromDType(o,g),T=new Array(l).fill(0);for(let k=0;k<a;++k){let I=r[k*c],S=T[I],N=(I===0?0:d[I-1])+S;T[I]++;for(let F=0;F<c;++F)b[N*c+F]=r[k*c+F];y[N]=n[k],p[k]=N}for(let k=0;k<l;++k)if(T[k]===0){let S=k===0?0:d[k-1];b[S*c+0]=k;for(let N=1;N<c;++N)b[S*c+N]=0;y[S]=i}return[b,[g,c],y,u,p]}}function Xk(r,e,t,n,o){let s=x.sizeFromShape(n),i=e[0],a=o.length,l=[],u=1,p=-1;for(let g=0;g<a;++g){let b=o[g];if(b===-1){if(p!==-1)throw new Error(`only one output dimension may be -1, not both ${p} and ${g}`);p=g,l.push(1)}else{if(b<0)throw new Error(`size ${g} must be non-negative, not ${b}`);u*=b,l.push(b)}}if(p!==-1){if(u<=0)throw new Error("reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero");let g=Math.trunc(s/u);if(u*g!==s)throw new Error(`Input to reshape is a SparseTensor with ${s}
|
|
dense values, but the requested shape requires a multiple of ${u}. inputShape=${n} outputShape= ${l}`);l[p]=g}let c=x.sizeFromShape(l);if(c!==s)throw new Error(`Input to reshape is a tensor with ${s} dense values, but the requested shape has ${c}. inputShape=${n} outputShape=${l}`);let m=n.length,f=[];if(m>0){f[m-1]=1;for(let g=m-2;g>=0;--g)f[g]=f[g+1]*n[g+1]}let d=[];if(a>0){d[a-1]=1;for(let g=a-2;g>=0;--g)d[g]=d[g+1]*l[g+1]}let h=x.getArrayFromDType(t,i*a);for(let g=0;g<i;++g){let b=0;for(let y=0;y<m;++y)b+=r[g*m+y]*f[y];for(let y=0;y<a;++y)h[g*a+y]=Math.trunc(b/d[y]),b%=d[y]}return[h,[i,a],l]}function Pd(r,e,t,n,o,s=!1,i=0){let a=n.length;if(a!==o.length)throw new Error("segmentIds and indices should have same size.");let l=[e[0],r.length/e[0]],u=l[1],c=a>0?o[a-1]+1:0;if(c<0)throw new Error("segment ids must be >= 0");let m=e.slice();m[0]=c;let f=m.reduce((T,k)=>T*k,1),d=x.getArrayFromDType(t,f);if(a===0)return c>0&&d.fill(i),[d,m];if(c<=0)throw new Error("segment ids must be >= 0");let h=0,g=1,b=0,y=o[h];for(;;){let T=0;if(g<a){if(T=o[g],y===T){++g;continue}if(y>=T)throw new Error("segment ids are not increasing")}if(y<0||y>=c)throw new Error(`Segment id ${y} out of range [0, ${c}), possibly because segmentIds input is not sorted.`);y>b&&d.fill(i,b*u,y*u);for(let k=h;k<g;++k){let I=n[k];if(I<0||I>=l[0])throw new Error(`Bad: indices[${k}] == ${n[k]} out of range [0, ${l[0]})`);for(let S=0;S<u;S++)d[y*u+S]+=r[I*u+S]}if(s)for(let k=0;k<u;k++)d[y*u+k]/=g-h;if(h=g,++g,b=y+1,y=T,g>a)break}return b<c&&d.fill(i,b*u,c*u),[d,m]}var VA=lt((r,e)=>{let t=r-e;return t*t}),Ufe=dt(Go,VA),fW={kernelName:Go,backendName:"cpu",kernelFunc:Ufe};function Yk(r,e,t,n){let o=ve(r,e.dtype);for(let s=0;s<o.size;s++){let i=o.indexToLoc(s),a=new Array(i.length);for(let l=0;l<a.length;l++)a[l]=i[l]*t[l]+n[l];o.set(e.get(...a),...i)}return o}var dW=class{constructor(e,t,n,o,s,i){this.separator=x.encodeString(e),this.nGramWidths=t,this.leftPad=x.encodeString(n),this.rightPad=x.encodeString(o),this.padWidth=s,this.preserveShort=i}getPadWidth(e){return Math.min(this.padWidth<0?e-1:this.padWidth,e-1)}getNumNGrams(e,t){let n=this.getPadWidth(t);return Math.max(0,e+2*n-t+1)}createNGrams(e,t,n,o,s,i){for(let a=0;a<s;++a){let l=this.getPadWidth(i),u=Math.max(0,l-a),p=Math.max(0,l-(s-(a+1))),c=i-(u+p),m=t+(u>0?0:a-l),f=0;f+=u*this.leftPad.length;for(let y=0;y<c;++y)f+=e[m+y].length;f+=p*this.rightPad.length,f+=(u+p+c-1)*this.separator.length,n[o+a]=new Uint8Array(f);let h=n[o+a],g=0,b=y=>y.forEach(T=>h[g++]=T);for(let y=0;y<u;++y)b(this.leftPad),b(this.separator);for(let y=0;y<c-1;++y)b(e[m+y]),b(this.separator);if(c>0){b(e[m+c-1]);for(let y=0;y<p;++y)b(this.separator),b(this.rightPad)}else{for(let y=0;y<p-1;++y)b(this.rightPad),b(this.separator);b(this.rightPad)}}}compute(e,t){let n=e.length,o=t.length;if(o>0){let l=t[0];if(l!==0)throw new Error(`First split value must be 0, got ${l}`);for(let u=1;u<o;++u){let p=t[u]>=l;if(p=p&&t[u]<=n,!p)throw new Error(`Invalid split value ${t[u]}, must be in [${l}, ${n}]`);l=t[u]}if(l!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${l}`)}let s=o-1,i=x.getArrayFromDType("int32",o);if(n===0||o===0){let l=new Array(n);for(let u=0;u<=s;++u)i[u]=0;return[l,i]}i[0]=0;for(let l=1;l<=s;++l){let u=t[l]-t[l-1],p=0;this.nGramWidths.forEach(c=>{p+=this.getNumNGrams(u,c)}),this.preserveShort&&u>0&&p===0&&(p=1),i[l]=i[l-1]+p}let a=new Array(i[s]);for(let l=0;l<s;++l){let u=t[l],p=i[l];if(this.nGramWidths.forEach(c=>{let m=t[l+1]-t[l],f=this.getNumNGrams(m,c);this.createNGrams(e,u,a,p,f,c),p+=f}),this.preserveShort&&p===i[l]){let c=t[l+1]-t[l];if(c===0)continue;let m=c+2*this.padWidth,f=1;this.createNGrams(e,u,a,p,f,m)}}return[a,i]}};function Zk(r,e,t,n,o,s,i,a){return new dW(t,n,o,s,i,a).compute(r,e)}function jfe(r,e,t){if(!r.length)return[];if(e.length===0){let s=new Array(r.length);for(let i=0;i<r.length;++i)s[i]=r.subarray(i,i+1);return s}if(e.length===1){let s=e[0],i=[],a=r.indexOf(s);for(;a!==-1;){let l=r.subarray(0,a);(!t||l.length!==0)&&i.push(l),r=r.subarray(a+1),a=r.indexOf(s)}return(!t||r.length!==0)&&i.push(r),i}let n=[],o=0;for(let s=0;s<r.length+1;s++)if(s===r.length||e.indexOf(r[s])!==-1){let i=r.subarray(o,s);(!t||i.length!==0)&&n.push(i),o=s+1}return n}function Jk(r,e,t){let n=r.length,o=[],s=0,i=0,a=new Array(n);for(let m=0;m<n;++m){let f=jfe(r[m],e,t),d=f.length;a[m]=d,s+=d,i=Math.max(i,d),o.push(...f)}let l=x.getArrayFromDType("int32",s*2),u=new Array(s),p=[n,i],c=0;for(let m=0;m<n;++m)for(let f=0;f<a[m];++f)l[c*2]=m,l[c*2+1]=f,u[c]=o[c],++c;return[l,u,p]}function Qk(r,e){let t=x.getArrayFromDType("int32",r.length);for(let n=0;n<r.length;++n)t[n]=x.fingerPrint64(r[n]).modulo(e).getLowBitsUnsigned();return t}var UA=lt((r,e)=>r-e),Hfe=Rd((r,e,t,n)=>({real:r-t,imag:e-n})),by=dt(Wo,UA,Hfe),hW={kernelName:Wo,backendName:"cpu",kernelFunc:by};function eI(r,e){let t=new Array(r.rank);for(let o=0;o<t.length;o++)t[o]=r.shape[o]*e[o];let n=ve(t,r.dtype);for(let o=0;o<n.values.length;++o){let s=n.indexToLoc(o),i=new Array(r.rank);for(let l=0;l<i.length;l++)i[l]=s[l]%r.shape[l];let a=r.locToIndex(i);n.values[o]=r.values[a]}return n}function tI(r,e,t,n,o){let s=e[e.length-1],[i,a]=[r.length/s,s],l=x.getTypedArrayFromDType(t,i*n),u=x.getTypedArrayFromDType("int32",i*n);for(let c=0;c<i;c++){let m=c*a,f=r.subarray(m,m+a),d=[];for(let y=0;y<f.length;y++)d.push({value:f[y],index:y});d.sort((y,T)=>T.value-y.value);let h=c*n,g=l.subarray(h,h+n),b=u.subarray(h,h+n);for(let y=0;y<n;y++)g[y]=d[y].value,b[y]=d[y].index}let p=e.slice();return p[p.length-1]=n,[ve(p,t,l),ve(p,"int32",u)]}function rI(r,e,t,n){let o=x.parseAxisParam(e,t)[0],s=[1,t[0],1];for(let d=0;d<o;d++)s[0]*=t[d];s[1]=t[o];for(let d=o+1;d<t.length;d++)s[2]*=t[d];let i={},a=new Int32Array(t[o]),l=new bt(s,n,r),u=[],p=s[0]===1&&s[2]===1;for(let d=0;d<t[o];d++){let h;if(p)h=r[d].toString();else{let g=[];for(let b=0;b<s[0];b++)for(let y=0;y<s[2];y++)g.push(l.get(b,d,y));h=g.join(",")}if(i[h]!==void 0)a[d]=i[h];else{let g=Object.keys(i).length;i[h]=g,a[d]=g,u.push(d)}}let c=s.slice();c[1]=Object.keys(i).length;let m=new bt(c,n);u.forEach((d,h)=>{for(let g=0;g<s[0];g++)for(let b=0;b<s[2];b++)m.set(l.get(g,d,b),g,h,b)});let f=t.slice();return f[o]=c[1],{outputValues:m.values,outputShape:f,indices:a}}var qfe="3.7.0";jf("cpu",()=>new hy,1);var jA=ze(gl,r=>r>=0?r:Math.exp(r)-1),bW={kernelName:gl,backendName:"cpu",kernelFunc:jA};function HA(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{alpha:s}=n;ie([o],"leakyRelu");let i=x.sizeFromShape(o.shape),a=t.data.get(o.dataId).values,l=x.getTypedArrayFromDType("float32",i);for(let u=0;u<a.length;u++)l[u]=a[u]<0?s*a[u]:a[u];return t.makeTensorInfo(o.shape,"float32",l)}var yW={kernelName:na,backendName:"cpu",kernelFunc:HA};var Xfe=lt((r,e)=>r<0?e*r:r);function qA(r){let{inputs:e,backend:t}=r,{x:n,alpha:o}=e;ie([n,o],"prelu");let s=t.data.get(n.dataId).values,i=t.data.get(o.dataId).values,[a,l]=Xfe(n.shape,o.shape,s,i,n.dtype);return t.makeTensorInfo(l,n.dtype,a)}var xW={kernelName:ga,backendName:"cpu",kernelFunc:qA};var XA=ze(ba,r=>Math.max(0,r)),TW={kernelName:ba,backendName:"cpu",kernelFunc:XA};var YA=ze(xa,r=>Math.min(Math.max(0,r),6)),kW={kernelName:xa,backendName:"cpu",kernelFunc:YA};var ZA=ze(wa,r=>1/(1+Math.exp(-r))),IW={kernelName:wa,backendName:"cpu",kernelFunc:ZA};function Bd(r,e,t,n,o){if(t==="linear")return bn({inputs:{x:e},backend:r});if(t==="relu")return XA({inputs:{x:e},backend:r});if(t==="elu")return jA({inputs:{x:e},backend:r});if(t==="relu6")return YA({inputs:{x:e},backend:r});if(t==="prelu")return qA({inputs:{x:e,alpha:n},backend:r});if(t==="leakyrelu")return HA({inputs:{x:e},backend:r,attrs:{alpha:o}});if(t==="sigmoid")return ZA({inputs:{x:e},backend:r});throw new Error(`Activation ${t} has not been implemented for the CPU backend.`)}function ut(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{shape:s}=n,i=x.sizeFromShape(o.shape),a=x.inferFromImplicitShape(s,i),l=x.sizeFromShape(a);x.assert(i===l,()=>`The new shape (${a}) has ${l} elements and the old shape (${o.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`),t.incRef(o.dataId);let u=t.data.get(o.dataId);if(u.complexTensorInfos!=null){let p=u.complexTensorInfos.real,c=u.complexTensorInfos.imag;p.shape=a,c.shape=a}return{dataId:o.dataId,shape:a,dtype:o.dtype}}var vW={kernelName:gi,backendName:"cpu",kernelFunc:ut};function JA(r){let{inputs:e,backend:t,attrs:n}=r,{a:o,b:s}=e,{transposeA:i,transposeB:a}=n;ie([o,s],"matMul");let l=o.shape.length,u=s.shape.length,p=i?o.shape[l-2]:o.shape[l-1],c=a?s.shape[u-1]:s.shape[u-2],m=i?o.shape[l-1]:o.shape[l-2],f=a?s.shape[u-2]:s.shape[u-1],d=o.shape.slice(0,-2),h=s.shape.slice(0,-2),g=x.sizeFromShape(d),b=x.sizeFromShape(h),y=g===b||g===1||b===1;x.assert(l>=2&&u>=2&&y,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${d}) and (${h}).`);let k=(g>b?o.shape.slice(0,-2):s.shape.slice(0,-2)).concat([m,f]);x.assert(p===c,()=>`Error in matMul: inner shapes (${p}) and (${c}) of Tensors with shapes ${o.shape} and ${s.shape} and transposeA=${i} and transposeB=${a} must match.`);let I=i?[g,p,m]:[g,m,p],S=a?[b,f,c]:[b,c,f],N=ut({inputs:{x:o},backend:t,attrs:{shape:I}}),F=ut({inputs:{x:s},backend:t,attrs:{shape:S}}),$=i?N.shape[1]:N.shape[2],O=i?N.shape[2]:N.shape[1],V=a?F.shape[1]:F.shape[2],q=Math.max(g,b),W=t.data.get(N.dataId).values,Y=t.data.get(F.dataId).values,Z=x.computeStrides(N.shape),J=x.computeStrides(F.shape),[se,ee,le]=i?[Z[0],1,Z[1]]:[Z[0],Z[1],1],[ae,ce,ye]=a?[1,J[1],J[0]]:[J[1],1,J[0]],me=O*V,xe=ve([q,O,V],N.dtype),ke=xe.values,we=t.blockSize;for(let Ne=0;Ne<q;Ne++)for(let Oe=0;Oe<O;Oe+=we)for(let Ee=0;Ee<V;Ee+=we)for(let Ye=0;Ye<$;Ye+=we){let at=Math.min(Oe+we,O),wt=Math.min(Ee+we,V),qt=Math.min(Ye+we,$);for(let Xt=Oe;Xt<at;Xt++)for(let ot=Ee;ot<wt;ot++){let At=0;for(let Et=Ye;Et<qt;Et++){let ur=Math.min(Ne,g-1)*se,ho=Math.min(Ne,b-1)*ye,Nr=W[ur+Xt*ee+Et*le],Zn=Y[Et*ae+ot*ce+ho];At+=Nr*Zn}ke[Ne*me+(Xt*V+ot)]+=At}}return t.disposeIntermediateTensorInfo(N),t.disposeIntermediateTensorInfo(F),t.makeTensorInfo(k,xe.dtype,xe.values)}var wW={kernelName:Us,backendName:"cpu",kernelFunc:JA};function Yfe(r){let{inputs:e,backend:t,attrs:n}=r,{a:o,b:s,bias:i,preluActivationWeights:a}=e,{transposeA:l,transposeB:u,activation:p,leakyreluAlpha:c}=n,m,f,d,h=[];m=JA({inputs:{a:o,b:s},attrs:{transposeA:l,transposeB:u},backend:t}),i&&(f=uu({inputs:{a:m,b:i},backend:t}),h.push(m),m=f),p&&(d=Bd(t,m,p,a,c),h.push(m),m=d);for(let b of h)t.disposeIntermediateTensorInfo(b);return m}var _W={kernelName:ki,backendName:"cpu",kernelFunc:Yfe};var Zfe=ze(ol,r=>Math.acos(r)),CW={kernelName:ol,backendName:"cpu",kernelFunc:Zfe};var Jfe=ze(sl,r=>Math.acosh(r)),SW={kernelName:sl,backendName:"cpu",kernelFunc:Jfe};function Qfe(r){let{inputs:e,backend:t}=r,n=e;ie(e,"addN");let o=n.map(a=>t.data.get(a.dataId).values),s=ve(n[0].shape,n[0].dtype),i=s.values;for(let a=0;a<n.length;a++){let l=o[a];for(let u=0;u<i.length;u++)i[u]+=l[u]}return t.makeTensorInfo(s.shape,s.dtype,s.values)}var NW={kernelName:Ws,backendName:"cpu",kernelFunc:Qfe};function ede(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,keepDims:i}=n;ie(o,"all");let a=x.parseAxisParam(s,o.shape),l=a,u=C.getAxesPermutation(l,o.shape.length),p=o;u!=null&&(p=Cr({inputs:{x:o},backend:t,attrs:{perm:u}}),l=C.getInnerMostAxes(l.length,o.shape.length)),C.assertAxesAreInnerMostDims("all",l,p.shape.length);let[c,m]=C.computeOutAndReduceShapes(p.shape,l),f=x.sizeFromShape(m),d=x.makeZerosTypedArray(x.sizeFromShape(c),p.dtype),h=t.data.get(p.dataId).values;for(let b=0;b<d.length;++b){let y=b*f,T=h[y];for(let k=0;k<f;++k){let I=h[y+k];T=T&&I}d[b]=T}u!=null&&t.disposeIntermediateTensorInfo(p);let g=t.makeTensorInfo(c,p.dtype,d);if(i){let b=C.expandShapeToKeepDim(c,a),y=ut({inputs:{x:g},backend:t,attrs:{shape:b}});return t.disposeIntermediateTensorInfo(g),y}return g}var AW={kernelName:al,backendName:"cpu",kernelFunc:ede};function tde(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,keepDims:i}=n;ie(o,"any");let a=x.parseAxisParam(s,o.shape),l=a,u=C.getAxesPermutation(l,o.shape.length),p=o;u!=null&&(p=Cr({inputs:{x:o},backend:t,attrs:{perm:u}}),l=C.getInnerMostAxes(l.length,o.shape.length)),C.assertAxesAreInnerMostDims("any",l,p.shape.length);let[c,m]=C.computeOutAndReduceShapes(p.shape,l),f=x.sizeFromShape(m),d=x.makeZerosTypedArray(x.sizeFromShape(c),p.dtype),h=t.data.get(p.dataId).values;for(let b=0;b<d.length;++b){let y=b*f,T=h[y];for(let k=0;k<f;++k){let I=h[y+k];T=T||I}d[b]=T}u!=null&&t.disposeIntermediateTensorInfo(p);let g=t.makeTensorInfo(c,p.dtype,d);if(i){let b=C.expandShapeToKeepDim(c,a),y=ut({inputs:{x:g},backend:t,attrs:{shape:b}});return t.disposeIntermediateTensorInfo(g),y}return g}var DW={kernelName:il,backendName:"cpu",kernelFunc:tde};function rde(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s}=n;ie(o,"argMax");let i=x.parseAxisParam(s,o.shape),a=C.getAxesPermutation(i,o.shape.length),l=o,u=[];a!=null&&(l=Cr({inputs:{x:o},backend:t,attrs:{perm:a}}),u.push(l),i=C.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],C.assertAxesAreInnerMostDims("argMax",i,l.shape.length);let[p,c]=C.computeOutAndReduceShapes(l.shape,i),m=x.sizeFromShape(p),f=x.makeZerosTypedArray(m,"int32"),d=x.sizeFromShape(c),h=t.data.get(l.dataId).values;for(let g=0;g<f.length;++g){let b=g*d,y=h[b],T=0;for(let k=0;k<d;++k){let I=h[b+k];I>y&&(y=I,T=k)}f[g]=T}return u.forEach(g=>t.disposeIntermediateTensorInfo(g)),t.makeTensorInfo(p,"int32",f)}var EW={kernelName:Ks,backendName:"cpu",kernelFunc:rde};function nde(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s}=n;ie(o,"argMin");let i=x.parseAxisParam(s,o.shape),a=C.getAxesPermutation(i,o.shape.length),l=o,u=[];a!=null&&(l=Cr({inputs:{x:o},backend:t,attrs:{perm:a}}),u.push(l),i=C.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],C.assertAxesAreInnerMostDims("argMin",i,l.shape.length);let[p,c]=C.computeOutAndReduceShapes(l.shape,i),m=x.sizeFromShape(p),f=x.makeZerosTypedArray(m,"int32"),d=x.sizeFromShape(c),h=t.data.get(l.dataId).values;for(let g=0;g<f.length;++g){let b=g*d,y=h[b],T=0;for(let k=0;k<d;++k){let I=h[b+k];I<y&&(y=I,T=k)}f[g]=T}return u.forEach(g=>t.disposeIntermediateTensorInfo(g)),t.makeTensorInfo(p,"int32",f)}var MW={kernelName:Ru,backendName:"cpu",kernelFunc:nde};var ode=ze(ll,r=>Math.asin(r)),FW={kernelName:ll,backendName:"cpu",kernelFunc:ode};var sde=ze(ul,r=>Math.asinh(r)),RW={kernelName:ul,backendName:"cpu",kernelFunc:sde};var ade=ze(pl,r=>Math.atan(r)),LW={kernelName:pl,backendName:"cpu",kernelFunc:ade};var ide=lt((r,e)=>Math.atan2(r,e)),lde=dt(ml,ide),$W={kernelName:ml,backendName:"cpu",kernelFunc:lde};var ude=ze(cl,r=>Math.atanh(r)),PW={kernelName:cl,backendName:"cpu",kernelFunc:ude};function Od(r,e,t,n,o,s){let i=o.strideHeight,a=o.strideWidth,l=o.dilationHeight,u=o.dilationWidth,p=o.effectiveFilterHeight,c=o.effectiveFilterWidth,m=o.padInfo.top,f=o.padInfo.left,d=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,h=ve(o.outShape,t),g=h.values,b=o.outShape[1]*o.outShape[2]*o.outShape[3],y=o.outShape[2]*o.outShape[3],T=o.outShape[3];for(let k=0;k<o.batchSize;++k){let I=k*b,S=k*n[0];for(let N=0;N<o.inChannels;++N)for(let F=0;F<o.outHeight;++F){let $=F*i-m,O=Math.max(0,$),V=Math.min(o.inHeight,p+$),q=I+F*y;for(let W=0;W<o.outWidth;++W){let Y=W*a-f,Z=Math.max(0,Y),J=Math.min(o.inWidth,c+Y),se=d,ee=0,le=0;for(let ce=O;ce<V;ce+=l){let ye=S+ce*n[1];for(let me=Z;me<J;me+=u){let xe=ye+me*n[2],ke=r[xe+N];s==="max"&&ke>se?se=ke:s==="avg"&&(ee+=ke,le++)}if(isNaN(se))break}let ae=q+W*T+N;g[ae]=s==="avg"?ee/le:se}}}return h}function nI(r,e,t,n,o=!1,s=!1){let i=ve(n.outShape,"int32"),a=n.strideHeight,l=n.strideWidth,u=n.dilationHeight,p=n.dilationWidth,c=n.effectiveFilterHeight,m=n.effectiveFilterWidth,f=n.padInfo.top,d=n.padInfo.left,h=ve(e,t,r);for(let g=0;g<n.batchSize;++g)for(let b=0;b<n.inChannels;++b)for(let y=0;y<n.outHeight;++y){let T=y*a-f,k=T;for(;k<0;)k+=u;let I=Math.min(n.inHeight,c+T);for(let S=0;S<n.outWidth;++S){let N=S*l-d,F=N;for(;F<0;)F+=p;let $=Math.min(n.inWidth,m+N),O=Number.NEGATIVE_INFINITY,V=-1;for(let q=k;q<I;q+=u){let W=q-T;for(let Y=F;Y<$;Y+=p){let Z=Y-N,J=h.get(g,q,Y,b);J>O&&(O=J,o?V=s?((g*n.inHeight+q)*n.inWidth+Y)*n.inChannels+b:(q*n.inWidth+Y)*n.inChannels+b:V=W*m+Z)}}i.set(V,g,y,S,b)}}return i}function oI(r,e,t,n,o,s){let i=o.strideDepth,a=o.strideHeight,l=o.strideWidth,u=o.dilationDepth,p=o.dilationHeight,c=o.dilationWidth,m=o.effectiveFilterDepth,f=o.effectiveFilterHeight,d=o.effectiveFilterWidth,h=o.padInfo.front,g=o.padInfo.top,b=o.padInfo.left,y=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,T=ve(o.outShape,t),k=T.values,I=o.outShape[1]*o.outShape[2]*o.outShape[3]*o.outShape[4],S=o.outShape[2]*o.outShape[3]*o.outShape[4],N=o.outShape[3]*o.outShape[4],F=o.outShape[4];for(let $=0;$<o.batchSize;++$){let O=$*I,V=$*n[0];for(let q=0;q<o.inChannels;++q)for(let W=0;W<o.outDepth;++W){let Y=W*i-h,Z=Y;for(;Z<0;)Z+=u;let J=Math.min(o.inDepth,m+Y),se=O+W*S;for(let ee=0;ee<o.outHeight;++ee){let le=ee*a-g,ae=le;for(;ae<0;)ae+=p;let ce=Math.min(o.inHeight,f+le),ye=se+ee*N;for(let me=0;me<o.outWidth;++me){let xe=me*l-b,ke=xe;for(;ke<0;)ke+=c;let we=Math.min(o.inWidth,d+xe),Ne=ye+me*F,Oe=y,Ee=0,Ye=0;for(let wt=Z;wt<J;wt+=u){let qt=V+wt*n[1];for(let Xt=ae;Xt<ce;Xt+=p){let ot=qt+Xt*n[2];for(let At=ke;At<we;At+=c){let Et=ot+At*n[3],ur=r[Et+q];if(s==="max"&&ur>Oe?Oe=ur:s==="avg"&&(Ee+=ur,Ye++),isNaN(Oe))break}if(isNaN(Oe))break}if(isNaN(Oe))break}let at=Ne+q;k[at]=s==="avg"?Ee/Ye:Oe}}}}return T}function BW(r,e){let t=ve(e.outShape,"int32"),n=e.strideDepth,o=e.strideHeight,s=e.strideWidth,i=e.dilationDepth,a=e.dilationHeight,l=e.dilationWidth,u=e.effectiveFilterDepth,p=e.effectiveFilterHeight,c=e.effectiveFilterWidth,m=e.padInfo.front,f=e.padInfo.top,d=e.padInfo.left;for(let h=0;h<e.batchSize;++h)for(let g=0;g<e.inChannels;++g)for(let b=0;b<e.outDepth;++b){let y=b*n-m,T=y;for(;T<0;)T+=i;let k=Math.min(e.inDepth,u+y);for(let I=0;I<e.outHeight;++I){let S=I*o-f,N=S;for(;N<0;)N+=a;let F=Math.min(e.inHeight,p+S);for(let $=0;$<e.outWidth;++$){let O=$*s-d,V=O;for(;V<0;)V+=l;let q=Math.min(e.inWidth,c+O),W=Number.NEGATIVE_INFINITY,Y=-1;for(let Z=T;Z<k;Z+=i){let J=Z-y;for(let se=N;se<F;se+=a){let ee=se-S;for(let le=V;le<q;le+=l){let ae=le-O,ce=r.get(h,Z,se,le,g);ce>=W&&(W=ce,Y=J*p*c+ee*p+ae)}}}t.set(Y,h,b,I,$,g)}}}return t}function pde(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e;ie(o,"avgPool");let{filterSize:s,strides:i,pad:a,dimRoundingMode:l}=n,u=1;x.assert(C.eitherStridesOrDilationsAreOne(i,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let p=C.computePool2DInfo(o.shape,s,i,u,a,l),c;if(p.filterWidth===1&&p.filterHeight===1&&x.arraysEqual(p.inShape,p.outShape))c=bn({inputs:{x:o},backend:t});else{let m=t.data.get(o.dataId).values,f=x.computeStrides(o.shape),d=Od(m,o.shape,o.dtype,f,p,"avg");c=t.makeTensorInfo(p.outShape,o.dtype,d.values)}return c}var OW={kernelName:Vs,backendName:"cpu",kernelFunc:pde};function cde(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{filterSize:s,strides:i,pad:a,dimRoundingMode:l,dataFormat:u}=n;ie(o,"avgPool3d");let p=C.computePool3DInfo(o.shape,s,i,1,a,l,u),c=t.data.get(o.dataId).values,m=oI(c,o.shape,o.dtype,x.computeStrides(o.shape),p,"avg");return t.makeTensorInfo(m.shape,"float32",m.values)}var zW={kernelName:Lu,backendName:"cpu",kernelFunc:cde};function mde(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,input:s}=e,{filterSize:i,strides:a,pad:l,dimRoundingMode:u}=n;ie([o,s],"avgPool3DGrad");let p=C.computePool3DInfo(s.shape,i,a,1,l,u),c=p.strideDepth,m=p.strideHeight,f=p.strideWidth,d=p.filterDepth,h=p.filterHeight,g=p.filterWidth,b=p.dilationDepth,y=p.dilationHeight,T=p.dilationWidth,k=p.effectiveFilterDepth,I=p.effectiveFilterHeight,S=p.effectiveFilterWidth,N=k-1-p.padInfo.front,F=S-1-p.padInfo.left,$=I-1-p.padInfo.top,O=ve(s.shape,"float32"),V=1/(d*h*g),q=t.bufferSync(o);for(let W=0;W<p.batchSize;++W)for(let Y=0;Y<p.inChannels;++Y)for(let Z=0;Z<p.inDepth;++Z)for(let J=0;J<p.inHeight;++J)for(let se=0;se<p.inWidth;++se){let ee=Z-N,le=J-$,ae=se-F,ce=0;for(let ye=0;ye<k;ye+=b){let me=(ee+ye)/c;if(!(me<0||me>=p.outDepth||Math.floor(me)!==me))for(let xe=0;xe<I;xe+=y){let ke=(le+xe)/m;if(!(ke<0||ke>=p.outHeight||Math.floor(ke)!==ke))for(let we=0;we<S;we+=T){let Ne=(ae+we)/f;if(Ne<0||Ne>=p.outWidth||Math.floor(Ne)!==Ne)continue;ce+=q.get(W,me,ke,Ne,Y)}}}O.set(ce*V,W,Z,J,se,Y)}return t.makeTensorInfo(O.shape,O.dtype,O.values)}var GW={kernelName:af,backendName:"cpu",kernelFunc:mde};function fde(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,input:s}=e,i=s;ie([o,s],"avgPoolGrad");let{filterSize:a,strides:l,pad:u}=n,p=C.computePool2DInfo(i.shape,a,l,1,u),c=p.strideHeight,m=p.strideWidth,f=p.filterHeight,d=p.filterWidth,h=p.dilationHeight,g=p.dilationWidth,b=p.effectiveFilterHeight,y=p.effectiveFilterWidth,T=y-1-p.padInfo.left,k=b-1-p.padInfo.top,I=ve(i.shape,"float32"),S=1/(f*d),N=t.data.get(o.dataId).values,F=ve(o.shape,"float32",N);for(let $=0;$<p.batchSize;++$)for(let O=0;O<p.inChannels;++O)for(let V=0;V<p.inHeight;++V)for(let q=0;q<p.inWidth;++q){let W=V-k,Y=q-T,Z=0;for(let J=0;J<b;J+=h){let se=(W+J)/c;if(!(se<0||se>=p.outHeight||Math.floor(se)!==se))for(let ee=0;ee<y;ee+=g){let le=(Y+ee)/m;if(le<0||le>=p.outWidth||Math.floor(le)!==le)continue;Z+=F.get($,se,le,O)}}I.set(Z*S,$,V,q,O)}return t.makeTensorInfo(I.shape,I.dtype,I.values)}var WW={kernelName:sf,backendName:"cpu",kernelFunc:fde};function dde(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,scale:s,offset:i,mean:a,variance:l}=e;x.assert(a.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),x.assert(i==null||a.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),x.assert(s==null||a.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),ie([o,a,l,s,i],"batchNorm");let{varianceEpsilon:u}=n;u==null&&(u=.001);let p=t.data.get(o.dataId).values,c=t.data.get(a.dataId).values,m=t.data.get(l.dataId).values,f=s?t.data.get(s.dataId).values:new Float32Array([1]),d=i?t.data.get(i.dataId).values:new Float32Array([0]),h=new Float32Array(p.length),g=d.length,b=f.length,y=m.length,T=c.length,k=0,I=0,S=0,N=0;for(let F=0;F<p.length;++F)h[F]=d[k++]+(p[F]-c[I++])*f[S++]/Math.sqrt(m[N++]+u),k>=g&&(k=0),I>=T&&(I=0),S>=b&&(S=0),N>=y&&(N=0);return t.makeTensorInfo(o.shape,o.dtype,h)}var KW={kernelName:ta,backendName:"cpu",kernelFunc:dde};function hde(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{blockShape:s,crops:i}=n;ie([o],"batchToSpaceND");let a=s.reduce((b,y)=>b*y),l=C.getReshaped(o.shape,s,a),u=C.getPermuted(l.length,s.length),p=C.getReshapedPermuted(o.shape,s,a),c=C.getSliceBeginCoords(i,s.length),m=C.getSliceSize(p,i,s.length),f=ut({inputs:{x:o},backend:t,attrs:{shape:l}}),d=Cr({inputs:{x:f},backend:t,attrs:{perm:u}}),h=ut({inputs:{x:d},backend:t,attrs:{shape:p}}),g=Es({inputs:{x:h},backend:t,attrs:{begin:c,size:m}});return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(h),g}var VW={kernelName:$u,backendName:"cpu",kernelFunc:hde};function gde(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,weights:s}=e,{size:i}=n,a=t.data.get(o.dataId).values,l=t.data.get(s.dataId).values,u=Ld(a,l,s.dtype,s.shape,i);return t.makeTensorInfo([i],s.dtype,u)}var UW={kernelName:lf,backendName:"cpu",kernelFunc:gde};var bde=ze(us,(r,e)=>{let t=e;return r>t.clipValueMax?t.clipValueMax:r<t.clipValueMin?t.clipValueMin:r}),jW={kernelName:us,backendName:"cpu",kernelFunc:bde};var yde=r=>{let{x:e}=r.inputs,t=r.backend,n=new Float32Array(x.sizeFromShape(e.shape)),o=t.data.get(e.dataId),s=o.complexTensorInfos.real,i=o.complexTensorInfos.imag,a=t.data.get(s.dataId).values,l=t.data.get(i.dataId).values;for(let u=0;u<a.length;u++){let p=a[u],c=l[u];n[u]=Math.hypot(p,c)}return t.makeOutput(n,e.shape,"float32")},HW={kernelName:Pu,backendName:"cpu",kernelFunc:yde};function Ri(r){let{inputs:e,backend:t}=r,{input:n}=e,o=t.data.get(n.dataId).complexTensorInfos.imag,s=t.data.get(o.dataId).values;return t.makeTensorInfo(o.shape,o.dtype,s)}var qW={kernelName:Tf,backendName:"cpu",kernelFunc:Ri};function gp(r){let{inputs:e,backend:t,attrs:n}=r,{axis:o}=n,s=x.parseAxisParam(o,e[0].shape)[0],i=C.computeOutShape(e.map(h=>h.shape),s);if(x.sizeFromShape(i)===0)return t.makeTensorInfo(i,e[0].dtype,[]);let a=e.filter(h=>x.sizeFromShape(h.shape)>0);if(a.length===1)return bn({inputs:{x:a[0]},backend:t});let l=a.map(h=>h.shape);if(C.assertParamsConsistent(l,s),a[0].dtype==="complex64"){let h=a.map(k=>Ss({inputs:{input:k},backend:t})),g=a.map(k=>Ri({inputs:{input:k},backend:t})),b=gp({inputs:h,backend:t,attrs:{axis:s}}),y=gp({inputs:g,backend:t,attrs:{axis:s}}),T=jr({inputs:{real:b,imag:y},backend:t});return h.forEach(k=>t.disposeIntermediateTensorInfo(k)),g.forEach(k=>t.disposeIntermediateTensorInfo(k)),t.disposeIntermediateTensorInfo(b),t.disposeIntermediateTensorInfo(y),T}let u=a.map(h=>{let g=x.sizeFromShape(h.shape.slice(s));return ut({inputs:{x:h},backend:t,attrs:{shape:[-1,g]}})}),p=u.map(h=>({vals:t.data.get(h.dataId).values,shape:h.shape}));i=C.computeOutShape(u.map(h=>h.shape),1);let c=u[0].shape[0]===1,m=Wk(p,i,e[0].dtype,c),f=C.computeOutShape(a.map(h=>h.shape),s),d=t.makeTensorInfo(f,e[0].dtype,m);return u.forEach(h=>t.disposeIntermediateTensorInfo(h)),d}var XW={kernelName:pi,backendName:"cpu",kernelFunc:gp};function QA(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,filter:s}=e,{strides:i,pad:a,dataFormat:l,dilations:u,dimRoundingMode:p}=n;ie([o,s],"conv2d");let c=C.convertConv2DDataFormat(l),m=C.computeConv2DInfo(o.shape,s.shape,i,u,a,p,!1,c),f=m.filterHeight,d=m.filterWidth,h=m.dilationHeight,g=m.dilationWidth,b=m.padInfo.left,y=m.padInfo.top,T=m.dataFormat==="channelsLast",k=new bt(m.outShape,o.dtype),I=x.computeStrides(o.shape),S=x.computeStrides(s.shape),N=I[0],F=T?I[1]:I[2],$=T?I[2]:1,O=T?1:I[1],V=k.strides[0],q=T?k.strides[1]:k.strides[2],W=T?k.strides[2]:1,Y=T?1:k.strides[1],Z=t.data.get(o.dataId).values,J=t.data.get(s.dataId).values,se=k.values;for(let ee=0;ee<m.batchSize;++ee){let le=ee*N,ae=ee*V;for(let ce=0;ce<m.outHeight;++ce){let ye=ae+ce*q,me=ce*m.strideHeight-y;for(let xe=0;xe<f;++xe){let ke=me+xe*h;if(ke<0||ke>=m.inHeight)continue;let we=xe*S[0],Ne=le+ke*F;for(let Oe=0;Oe<m.outWidth;++Oe){let Ee=ye+Oe*W,Ye=Oe*m.strideWidth-b;for(let at=0;at<d;++at){let wt=Ye+at*g;if(wt<0||wt>=m.inWidth)continue;let qt=we+at*S[1],Xt=Ne+wt*$,ot=qt;for(let At=0;At<m.inChannels;++At){let Et=Z[Xt+At*O];for(let ur=0;ur<m.outChannels;++ur)se[Ee+ur*Y]+=Et*J[ot+ur];ot+=m.outChannels}}}}}}return t.makeTensorInfo(k.shape,k.dtype,se)}var YW={kernelName:js,backendName:"cpu",kernelFunc:QA};function xde(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,dy:s}=e,{strides:i,pad:a,dataFormat:l,dimRoundingMode:u,filterShape:p}=n;ie([o,s],"conv2dBackpropFilter");let c=C.convertConv2DDataFormat(l),m=C.computeConv2DInfo(o.shape,p,i,1,a,u,!1,c),{strideHeight:f,strideWidth:d,filterHeight:h,filterWidth:g}=m,b=m.dataFormat==="channelsLast",y=new bt(m.filterShape,"float32"),T=m.padInfo.left,k=m.padInfo.top,I=t.data.get(o.dataId).values,S=t.data.get(s.dataId).values,N=new bt(o.shape,o.dtype,I),F=new bt(s.shape,s.dtype,S);for(let $=0;$<h;++$){let O=Math.max(0,Math.ceil((k-$)/f)),V=Math.min(m.outHeight,(m.inHeight+k-$)/f);for(let q=0;q<g;++q){let W=Math.max(0,Math.ceil((T-q)/d)),Y=Math.min(m.outWidth,(m.inWidth+T-q)/d);for(let Z=0;Z<m.inChannels;++Z)for(let J=0;J<m.outChannels;++J){let se=0;for(let ee=0;ee<m.batchSize;++ee)for(let le=O;le<V;++le){let ae=$+le*f-k;for(let ce=W;ce<Y;++ce){let ye=q+ce*d-T;b?se+=N.get(ee,ae,ye,Z)*F.get(ee,le,ce,J):se+=N.get(ee,Z,ae,ye)*F.get(ee,J,le,ce)}}y.set(se,$,q,Z,J)}}}return t.makeTensorInfo(y.shape,y.dtype,y.values)}var ZW={kernelName:uf,backendName:"cpu",kernelFunc:xde};function Tde(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,filter:s}=e,{inputShape:i,strides:a,pad:l,dataFormat:u,dimRoundingMode:p}=n;ie([o,s],"conv2dBackpropInput");let c=x.computeStrides(s.shape),m=x.computeStrides(o.shape),f=C.convertConv2DDataFormat(u),d=C.computeConv2DInfo(i,s.shape,a,1,l,p,!1,f),h=new bt(d.inShape,"float32"),g=h.values,b=t.data.get(o.dataId).values,y=t.data.get(s.dataId).values,[T,k,I]=c,{batchSize:S,filterHeight:N,filterWidth:F,inChannels:$,inHeight:O,inWidth:V,outChannels:q,outHeight:W,outWidth:Y,strideHeight:Z,strideWidth:J}=d;f=d.dataFormat;let se=N-1-d.padInfo.top,ee=F-1-d.padInfo.left,le=f==="channelsLast",ae=h.strides[0],ce=le?h.strides[1]:h.strides[2],ye=le?h.strides[2]:1,me=le?1:h.strides[1],xe=m[0],ke=le?m[1]:m[2],we=le?m[2]:1,Ne=le?1:m[1];for(let Oe=0;Oe<S;++Oe)for(let Ee=0;Ee<$;++Ee)for(let Ye=0;Ye<O;++Ye){let at=Ye-se,wt=Math.max(0,Math.ceil(at/Z)),qt=Math.min(W,(N+at)/Z);for(let Xt=0;Xt<V;++Xt){let ot=Xt-ee,At=Math.max(0,Math.ceil(ot/J)),Et=Math.min(Y,(F+ot)/J),ur=0;for(let Nr=wt;Nr<qt;++Nr){let Zn=Nr*Z-at;for(let xn=At;xn<Et;++xn){let es=xn*J-ot,Or=xe*Oe+ke*Nr+we*xn,go=T*(N-1-Zn)+k*(F-1-es)+I*Ee;for(let An=0;An<q;++An){let Jr=b[Or+Ne*An],Jn=y[go+An];ur+=Jr*Jn}}}let ho=ae*Oe+ce*Ye+ye*Xt+me*Ee;g[ho]=ur}}return t.makeTensorInfo(h.shape,h.dtype,h.values)}var JW={kernelName:Hs,backendName:"cpu",kernelFunc:Tde};function kde(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,filter:s}=e,{strides:i,pad:a,dilations:l}=n;ie([o,s],"conv3d");let u=C.computeConv3DInfo(o.shape,s.shape,i,l,a),{filterDepth:p,filterHeight:c,filterWidth:m,dilationDepth:f,dilationHeight:d,dilationWidth:h,padInfo:g}=u,b=g.front,y=g.left,T=g.top,k=new bt(u.outShape,o.dtype),I=t.data.get(o.dataId).values,S=t.data.get(s.dataId).values,N=k.values,F=x.computeStrides(o.shape),$=x.computeStrides(s.shape);for(let O=0;O<u.batchSize;++O){let V=O*F[0],q=O*k.strides[0];for(let W=0;W<u.outDepth;++W){let Y=q+W*k.strides[1],Z=W*u.strideDepth-b;for(let J=0;J<p;++J){let se=Z+J*f;if(se<0||se>=u.inDepth)continue;let ee=J*$[0],le=V+se*F[1];for(let ae=0;ae<u.outHeight;++ae){let ce=Y+ae*k.strides[2],ye=ae*u.strideHeight-T;for(let me=0;me<c;++me){let xe=ye+me*d;if(xe<0||xe>=u.inHeight)continue;let ke=ee+me*$[1],we=le+xe*F[2];for(let Ne=0;Ne<u.outWidth;++Ne){let Oe=ce+Ne*u.outChannels,Ee=Ne*u.strideWidth-y;for(let Ye=0;Ye<m;++Ye){let at=Ee+Ye*h;if(at<0||at>=u.inWidth)continue;let wt=ke+Ye*$[2],qt=we+at*u.inChannels,Xt=wt;for(let ot=0;ot<u.inChannels;++ot){let At=I[qt+ot];for(let Et=0;Et<u.outChannels;++Et)N[Oe+Et]+=At*S[Xt+Et];Xt+=u.outChannels}}}}}}}}return t.makeTensorInfo(k.shape,k.dtype,k.values)}var QW={kernelName:Bu,backendName:"cpu",kernelFunc:kde};function Ide(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,dy:s}=e,{strides:i,pad:a,filterShape:l}=n;ie([o,s],"conv3dBackpropFilterV2");let u=x.computeStrides(o.shape),p=x.computeStrides(s.shape),c=C.computeConv3DInfo(o.shape,l,i,1,a),m=c.strideDepth,f=c.strideHeight,d=c.strideWidth,h=c.filterDepth,g=c.filterHeight,b=c.filterWidth,y=new bt(c.filterShape,"float32"),T=y.values,[k,I,S,N]=y.strides,F=t.data.get(s.dataId).values,[$,O,V,q]=p,W=t.data.get(o.dataId).values,[Y,Z,J,se]=u,ee=c.padInfo.front,le=c.padInfo.left,ae=c.padInfo.top;for(let ce=0;ce<h;++ce){let ye=Math.max(0,Math.ceil((ee-ce)/m)),me=Math.min(c.outDepth,(c.inDepth+ee-ce)/m),xe=ce*k;for(let ke=0;ke<g;++ke){let we=Math.max(0,Math.ceil((ae-ke)/f)),Ne=Math.min(c.outHeight,(c.inHeight+ae-ke)/f),Oe=ke*I+xe;for(let Ee=0;Ee<b;++Ee){let Ye=Math.max(0,Math.ceil((le-Ee)/d)),at=Math.min(c.outWidth,(c.inWidth+le-Ee)/d),wt=Ee*S+Oe;for(let qt=0;qt<c.inChannels;++qt){let Xt=qt*N+wt;for(let ot=0;ot<c.outChannels;++ot){let At=0;for(let Et=0;Et<c.batchSize;++Et){let ur=Et*Y,ho=Et*$;for(let Nr=ye;Nr<me;++Nr){let xn=(ce+Nr*m-ee)*Z+ur,es=Nr*O+ho;for(let Or=we;Or<Ne;++Or){let An=(ke+Or*f-ae)*J+xn,Jr=Or*V+es;for(let Jn=Ye;Jn<at;++Jn){let wp=(Ee+Jn*d-le)*se+An,bu=Jn*q+Jr;At+=W[wp+qt]*F[bu+ot]}}}}T[Xt+ot]=At}}}}}return t.makeTensorInfo(y.shape,y.dtype,y.values)}var eK={kernelName:pf,backendName:"cpu",kernelFunc:Ide};function vde(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,filter:s}=e,{pad:i,strides:a,inputShape:l}=n;ie([o],"conv3dBackpropInputV2");let u=x.computeStrides(o.shape),p=x.computeStrides(s.shape),c=C.computeConv3DInfo(l,s.shape,a,1,i),m=new bt(c.inShape,"float32"),f=m.values,[d,h,g,b]=m.strides,y=t.data.get(o.dataId).values,[T,k,I,S]=u,N=t.data.get(s.dataId).values,[F,$,O,V]=p,{batchSize:q,filterDepth:W,filterHeight:Y,filterWidth:Z,inChannels:J,inDepth:se,inHeight:ee,inWidth:le,outChannels:ae,outDepth:ce,outHeight:ye,outWidth:me,strideDepth:xe,strideHeight:ke,strideWidth:we}=c,Ne=W-1-c.padInfo.front,Oe=Y-1-c.padInfo.top,Ee=Z-1-c.padInfo.left;for(let Ye=0;Ye<q;++Ye)for(let at=0;at<J;++at)for(let wt=0;wt<se;++wt){let qt=wt-Ne,Xt=Math.max(0,Math.ceil(qt/xe)),ot=Math.min(ce,(W+qt)/xe);for(let At=0;At<ee;++At){let Et=At-Oe,ur=Math.max(0,Math.ceil(Et/ke)),ho=Math.min(ye,(Y+Et)/ke);for(let Nr=0;Nr<le;++Nr){let Zn=Nr-Ee,xn=Math.max(0,Math.ceil(Zn/we)),es=Math.min(me,(Z+Zn)/we),Or=0;for(let go=Xt;go<ot;++go){let An=go*xe-qt;for(let Jr=ur;Jr<ho;++Jr){let Jn=Jr*ke-Et;for(let So=xn;So<es;++So){let wp=So*we-Zn,bu=T*Ye+k*go+I*Jr+S*So,ti=F*(W-1-An)+$*(Y-1-Jn)+O*(Z-1-wp)+V*at;for(let Pi=0;Pi<ae;++Pi){let th=y[bu+Pi],_p=N[ti+Pi];Or+=th*_p}}}}f[d*Ye+h*wt+g*At+b*Nr+at]=Or}}}return t.makeTensorInfo(m.shape,m.dtype,m.values)}var tK={kernelName:cf,backendName:"cpu",kernelFunc:vde};var wde=ze(qs,r=>Math.cos(r)),rK={kernelName:qs,backendName:"cpu",kernelFunc:wde};var _de=ze(fl,r=>Math.cosh(r)),nK={kernelName:fl,backendName:"cpu",kernelFunc:_de};function Cde(r){let{inputs:e,backend:t,attrs:n}=r,{image:o,boxes:s,boxInd:i}=e,{cropSize:a,method:l,extrapolationValue:u}=n,[p,c,m,f]=o.shape,d=s.shape[0],[h,g]=a,b=ve([d,h,g,f],"float32"),y=t.data.get(s.dataId).values,T=t.data.get(i.dataId).values,k=t.data.get(o.dataId).values,I=x.computeStrides(o.shape),S=x.computeStrides(b.shape);for(let N=0;N<d;N++){let F=N*4,$=y[F],O=y[F+1],V=y[F+2],q=y[F+3],W=T[N];if(W>=p)continue;let Y=h>1?(V-$)*(c-1)/(h-1):0,Z=g>1?(q-O)*(m-1)/(g-1):0;for(let J=0;J<h;J++){let se=h>1?$*(c-1)+J*Y:.5*($+V)*(c-1);if(se<0||se>c-1){for(let ee=0;ee<g;ee++)for(let le=0;le<f;le++){let ae=le+ee*S[2]+J*S[1]+N*S[0];b.values[ae]=u}continue}if(l==="bilinear"){let ee=Math.floor(se),le=Math.ceil(se),ae=se-ee;for(let ce=0;ce<g;ce++){let ye=g>1?O*(m-1)+ce*Z:.5*(O+q)*(m-1);if(ye<0||ye>m-1){for(let we=0;we<f;we++){let Ne=we+ce*S[2]+J*S[1]+N*S[0];b.values[Ne]=u}continue}let me=Math.floor(ye),xe=Math.ceil(ye),ke=ye-me;for(let we=0;we<f;we++){let Ne=we+me*I[2]+ee*I[1]+W*I[0],Oe=k[Ne];Ne=we+xe*I[2]+ee*I[1]+W*I[0];let Ee=k[Ne];Ne=we+me*I[2]+le*I[1]+W*I[0];let Ye=k[Ne];Ne=we+xe*I[2]+le*I[1]+W*I[0];let at=k[Ne],wt=Oe+(Ee-Oe)*ke,qt=Ye+(at-Ye)*ke;Ne=we+ce*S[2]+J*S[1]+N*S[0],b.values[Ne]=wt+(qt-wt)*ae}}}else for(let ee=0;ee<g;++ee){let le=g>1?O*(m-1)+ee*Z:.5*(O+q)*(m-1);if(le<0||le>m-1){for(let ye=0;ye<f;ye++){let me=ye+ee*S[2]+J*S[1]+N*S[0];b.values[me]=u}continue}let ae=Math.round(le),ce=Math.round(se);for(let ye=0;ye<f;ye++){let me=ye+ae*I[2]+ce*I[1]+W*I[0],xe=ye+ee*S[2]+J*S[1]+N*S[0];b.values[xe]=k[me]}}}}return t.makeTensorInfo(b.shape,b.dtype,b.values)}var oK={kernelName:dl,backendName:"cpu",kernelFunc:Cde};function Sde(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,exclusive:i,reverse:a}=n;ie(o,"cumsum");let l=C.getAxesPermutation([s],o.shape.length),u=o;l!=null&&(u=Cr({inputs:{x:o},backend:t,attrs:{perm:l}}));let p=C.getInnerMostAxes(1,o.shape.length)[0];if(p!==u.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${u.shape.length-1} but got axis=${p}`);let c=Mr(u.dtype,"int32"),m=x.makeZerosTypedArray(x.sizeFromShape(u.shape),c),f=t.data.get(u.dataId).values,d=u.shape[u.shape.length-1],h=a?(b,y)=>b+d-y-1:(b,y)=>b+y;for(let b=0;b<f.length;b+=d)for(let y=0;y<d;y++){let T=h(b,y);if(y===0)m[T]=i?0:f[T];else{let k=h(b,y-1);m[T]=i?f[k]+m[k]:f[T]+m[k]}}let g=t.makeTensorInfo(u.shape,c,m);if(l!=null){let b=C.getUndoAxesPermutation(l),y=Cr({inputs:{x:g},backend:t,attrs:{perm:b}});return t.disposeIntermediateTensorInfo(g),t.disposeIntermediateTensorInfo(u),y}return g}var sK={kernelName:Xs,backendName:"cpu",kernelFunc:Sde};function Nde(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,weights:s}=e,{size:i,binaryOutput:a}=n;if(o.shape.length===1){let l=t.data.get(o.dataId).values,u=t.data.get(s.dataId).values,p=Ld(l,u,s.dtype,s.shape,i);return t.makeTensorInfo([i],s.dtype,p)}else if(o.shape.length===2){let l=t.bufferSync(o),u=t.bufferSync(s),p=Gk(l,u,i,a);return t.makeTensorInfo(p.shape,s.dtype,p.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${o.shape.length}.`)}var aK={kernelName:mf,backendName:"cpu",kernelFunc:Nde};function Ade(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{blockSize:s,dataFormat:i}=n;x.assert(i==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`),x.assert(s>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${s}`);let a=o.shape[0],l=o.shape[1],u=o.shape[2],p=o.shape[3],c=l*s,m=u*s,f=p/(s*s),d=t.data.get(o.dataId).values,h=new Float32Array(a*c*m*f),g=0;for(let b=0;b<a;++b)for(let y=0;y<c;++y){let T=Math.floor(y/s),k=y%s;for(let I=0;I<m;++I){let S=Math.floor(I/s),N=I%s,F=(k*s+N)*f;for(let $=0;$<f;++$){let V=$+F+p*(S+u*(T+l*b));h[g++]=d[V]}}}return t.makeTensorInfo([a,c,m,f],o.dtype,h)}var iK={kernelName:hl,backendName:"cpu",kernelFunc:Ade};function e0(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,filter:s}=e,{strides:i,pad:a,dilations:l,dimRoundingMode:u}=n;ie([o,s],"depthwiseConv2DNative");let p=x.computeStrides(o.shape),c=x.computeStrides(s.shape),m=l;m==null&&(m=[1,1]),x.assert(C.eitherStridesOrDilationsAreOne(i,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${m}'`);let f=C.computeConv2DInfo(o.shape,s.shape,i,m,a,u,!0),{filterHeight:d,filterWidth:h,dilationHeight:g,dilationWidth:b,padInfo:y}=f,T=y.left,k=y.top,I=f.outChannels/f.inChannels,S=new bt(f.outShape,o.dtype),N=t.data.get(o.dataId).values,F=t.data.get(s.dataId).values,$=S.values;for(let O=0;O<f.batchSize;++O){let V=O*p[0],q=O*S.strides[0];for(let W=0;W<f.outHeight;++W){let Y=q+W*S.strides[1],Z=W*f.strideHeight-k;for(let J=0;J<d;++J){let se=Z+J*g;if(se<0||se>=f.inHeight)continue;let ee=J*c[0],le=V+se*p[1];for(let ae=0;ae<f.outWidth;++ae){let ce=Y+ae*S.strides[2],ye=ae*f.strideWidth-T;for(let me=0;me<h;++me){let xe=ye+me*b;if(xe<0||xe>=f.inWidth)continue;let ke=ee+me*c[1],we=le+xe*f.inChannels,Ne=ce,Oe=ke;for(let Ee=0;Ee<f.inChannels;++Ee){let Ye=N[we+Ee];for(let at=0;at<I;++at)$[Ne+at]+=Ye*F[Oe+at];Ne+=I,Oe+=I}}}}}}return t.makeTensorInfo(S.shape,S.dtype,S.values)}var lK={kernelName:Ys,backendName:"cpu",kernelFunc:e0};function Dde(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,dy:s}=e,{strides:i,dilations:a,pad:l,dimRoundingMode:u,filterShape:p}=n;ie([o,s],"depthwiseConv2dNativeBackpropFilter");let c=C.computeConv2DInfo(o.shape,p,i,a,l,u,!0),{strideHeight:m,strideWidth:f,filterHeight:d,filterWidth:h}=c,g=new bt(c.filterShape,"float32"),b=c.padInfo.left,y=c.padInfo.top,T=c.outChannels/c.inChannels,k=t.data.get(o.dataId).values,I=new bt(o.shape,o.dtype,k),S=t.data.get(s.dataId).values,N=new bt(s.shape,s.dtype,S);for(let F=0;F<d;++F){let $=Math.max(0,Math.ceil((y-F)/m)),O=Math.min(c.outHeight,(c.inHeight+y-F)/m);for(let V=0;V<h;++V){let q=Math.max(0,Math.ceil((b-V)/f)),W=Math.min(c.outWidth,(c.inWidth+b-V)/f);for(let Y=0;Y<c.outChannels;++Y){let Z=Math.trunc(Y/T),J=Y%T,se=0;for(let ee=0;ee<c.batchSize;++ee)for(let le=$;le<O;++le){let ae=F+le*m-y;for(let ce=q;ce<W;++ce){let ye=V+ce*f-b;se+=I.get(ee,ae,ye,Z)*N.get(ee,le,ce,Y)}}g.set(se,F,V,Z,J)}}}return t.makeTensorInfo(g.shape,g.dtype,g.values)}var uK={kernelName:ff,backendName:"cpu",kernelFunc:Dde};function Ede(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,filter:s}=e,{strides:i,dilations:a,pad:l,dimRoundingMode:u,inputShape:p}=n;ie([o,s],"depthwiseConv2DNativeBackpropInput");let c=x.computeStrides(o.shape),m=x.computeStrides(s.shape),f=C.computeConv2DInfo(p,s.shape,i,a,l,u,!0),d=new bt(f.inShape,"float32"),h=d.values,[g,b,y]=d.strides,T=t.data.get(o.dataId).values,[k,I,S]=c,N=t.data.get(s.dataId).values,[F,$,O]=m,{batchSize:V,filterHeight:q,filterWidth:W,inChannels:Y,inHeight:Z,inWidth:J,outChannels:se,outHeight:ee,outWidth:le,strideHeight:ae,strideWidth:ce}=f,ye=q-1-f.padInfo.top,me=W-1-f.padInfo.left,xe=se/Y;for(let ke=0;ke<V;++ke)for(let we=0;we<Y;++we)for(let Ne=0;Ne<Z;++Ne){let Oe=Ne-ye,Ee=Math.max(0,Math.ceil(Oe/ae)),Ye=Math.min(ee,(q+Oe)/ae);for(let at=0;at<J;++at){let wt=at-me,qt=Math.max(0,Math.ceil(wt/ce)),Xt=Math.min(le,(W+wt)/ce),ot=0;for(let At=Ee;At<Ye;++At){let Et=At*ae-Oe;for(let ur=qt;ur<Xt;++ur){let ho=ur*ce-wt,Nr=k*ke+I*At+S*ur,Zn=F*(q-1-Et)+$*(W-1-ho)+O*we;for(let xn=0;xn<xe;++xn){let es=we*xe+xn,Or=T[Nr+es],go=N[Zn+xn];ot+=Or*go}}}h[g*ke+b*Ne+y*at+we]=ot}}return t.makeTensorInfo(d.shape,d.dtype,d.values)}var pK={kernelName:df,backendName:"cpu",kernelFunc:Ede};function Mde(r){let{inputs:e,backend:t}=r,{x:n}=e,o=x.sizeFromShape(n.shape),s=t.data.get(n.dataId).values,i=ve([o,o],n.dtype),a=i.values;for(let u=0;u<s.length;u++)a[u*o+u]=s[u];let l=[...n.shape,...n.shape];return t.makeTensorInfo(l,i.dtype,i.values)}var cK={kernelName:hf,backendName:"cpu",kernelFunc:Mde};var mK={kernelName:Ou,backendName:"cpu",kernelFunc:({inputs:r,backend:e,attrs:t})=>{let{x:n,filter:o}=r,{strides:s,pad:i,dilations:a}=t,l=e,u=l.data.get(n.dataId).values,p=n.shape.length,c=l.data.get(o.dataId).values,m=o.shape.length,{batchSize:f,inHeight:d,inWidth:h,inChannels:g,outHeight:b,outWidth:y,padInfo:T,strideHeight:k,strideWidth:I,filterHeight:S,filterWidth:N,dilationHeight:F,dilationWidth:$,outShape:O}=C.computeDilation2DInfo(n.shape,o.shape,s,i,"NHWC",a),V=x.sizeFromShape(O),q=O.length,W=x.getArrayFromDType(n.dtype,V);for(let Z=0;Z<f;++Z)for(let J=0;J<b;++J){let se=J*k-T.top;for(let ee=0;ee<y;++ee){let le=ee*I-T.left;for(let ae=0;ae<g;++ae){let ce=Number.MIN_SAFE_INTEGER;for(let me=0;me<S;++me){let xe=se+me*F;if(xe>=0&&xe<d)for(let ke=0;ke<N;++ke){let we=le+ke*$;if(we>=0&&we<h){let Ne=x.locToIndex([Z,xe,we,ae],p,x.computeStrides(n.shape)),Oe=x.locToIndex([me,ke,ae],m,x.computeStrides(o.shape)),Ee=u[Ne]+c[Oe];Ee>ce&&(ce=Ee)}}}let ye=x.locToIndex([Z,J,ee,ae],q,x.computeStrides(O));W[ye]=ce}}}return{dataId:l.write(x.toTypedArray(W,n.dtype),O,n.dtype),shape:O,dtype:n.dtype}}};var fK={kernelName:zh,backendName:"cpu",kernelFunc:({inputs:r,backend:e,attrs:t})=>{let{x:n,filter:o,dy:s}=r,{strides:i,pad:a,dilations:l}=t,u=e,p=x.toNestedArray(n.shape,u.data.get(n.dataId).values),c=x.toNestedArray(o.shape,u.data.get(o.dataId).values),{batchSize:m,inHeight:f,inWidth:d,inChannels:h,outHeight:g,outWidth:b,padInfo:y,strideHeight:T,strideWidth:k,filterHeight:I,filterWidth:S,dilationHeight:N,dilationWidth:F,outShape:$}=C.computeDilation2DInfo(n.shape,o.shape,i,a,"NHWC",l);x.assert(s.rank===$.length,()=>`Error in ${zh}, dy must have the same rank as output ${$.length}, but got ${s.rank}`);let O=x.toNestedArray($,u.data.get(s.dataId).values),V=x.makeZerosNestedTypedArray(o.shape,o.dtype);for(let W=0;W<m;++W)for(let Y=0;Y<g;++Y){let Z=Y*T-y.top;for(let J=0;J<b;++J){let se=J*k-y.left;for(let ee=0;ee<h;++ee){let le=Number.MIN_SAFE_INTEGER,ae=0,ce=0;for(let ye=0;ye<I;++ye){let me=Z+ye*N;if(me>=0&&me<f)for(let xe=0;xe<S;++xe){let ke=se+xe*F;if(ke>=0&&ke<d){let we=p[W][me][ke][ee]+c[ye][xe][ee];we>le&&(le=we,ae=ye,ce=xe)}}}V[ae][ce][ee]+=O[W][Y][J][ee]}}}return{dataId:u.write(x.toTypedArray(V,n.dtype),o.shape,o.dtype),shape:o.shape,dtype:o.dtype}}};var dK={kernelName:Oh,backendName:"cpu",kernelFunc:({inputs:r,backend:e,attrs:t})=>{let{x:n,filter:o,dy:s}=r,{strides:i,pad:a,dilations:l}=t,u=e,p=x.toNestedArray(n.shape,u.data.get(n.dataId).values),c=x.toNestedArray(o.shape,u.data.get(o.dataId).values),{batchSize:m,inHeight:f,inWidth:d,inChannels:h,outHeight:g,outWidth:b,padInfo:y,strideHeight:T,strideWidth:k,filterHeight:I,filterWidth:S,dilationHeight:N,dilationWidth:F,outShape:$}=C.computeDilation2DInfo(n.shape,o.shape,i,a,"NHWC",l);x.assert(s.rank===$.length,()=>`Error in ${Oh}, dy must have the same rank as output ${$.length}, but got ${s.rank}`);let O=x.toNestedArray($,u.data.get(s.dataId).values),V=x.makeZerosNestedTypedArray(n.shape,n.dtype);for(let W=0;W<m;++W)for(let Y=0;Y<g;++Y){let Z=Y*T-y.top;for(let J=0;J<b;++J){let se=J*k-y.left;for(let ee=0;ee<h;++ee){let le=Number.MIN_SAFE_INTEGER,ae=Z<0?0:Z,ce=se<0?0:se;for(let ye=0;ye<I;++ye){let me=Z+ye*N;if(me>=0&&me<f)for(let xe=0;xe<S;++xe){let ke=se+xe*F;if(ke>=0&&ke<d){let we=p[W][me][ke][ee]+c[ye][xe][ee];we>le&&(le=we,ae=me,ce=ke)}}}V[W][ae][ce][ee]+=O[W][Y][J][ee]}}}return{dataId:u.write(x.toTypedArray(V,n.dtype),n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}};function pu(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,keepDims:i}=n;ie(o,"sum");let a;o.dtype==="bool"?a=Ns({inputs:{x:o},backend:t,attrs:{dtype:"int32"}}):a=bn({inputs:{x:o},backend:t});let l=a.shape.length,u=x.parseAxisParam(s,a.shape),p=C.getAxesPermutation(u,l),c=u,m=a;p!=null&&(m=Cr({inputs:{x:a},backend:t,attrs:{perm:p}}),c=C.getInnerMostAxes(c.length,l)),C.assertAxesAreInnerMostDims("sum",c,m.shape.length);let[f,d]=C.computeOutAndReduceShapes(m.shape,c),h=C.upcastType(m.dtype,"int32"),g=Fd(t,f,h),b=x.sizeFromShape(d),y=t.data.get(g.dataId).values,T=t.data.get(m.dataId).values;for(let k=0;k<y.length;++k){let I=k*b,S=0;for(let N=0;N<b;++N)S+=T[I+N];y[k]=S}if(i){let k=C.expandShapeToKeepDim(g.shape,u),I=g;g=ut({inputs:{x:g},backend:t,attrs:{shape:k}}),t.disposeIntermediateTensorInfo(I)}return t.disposeIntermediateTensorInfo(a),p!=null&&t.disposeIntermediateTensorInfo(m),g}var hK={kernelName:Ca,backendName:"cpu",kernelFunc:pu};function Fde(r){let{inputs:e,backend:t,attrs:n}=r,{equation:o}=n,s=e,{allDims:i,summedDims:a,idDims:l}=C.decodeEinsumEquation(o,s.length);C.checkEinsumDimSizes(i.length,l,s);let{path:u,steps:p}=C.getEinsumComputePath(a,l),c=p.length,m=null,f=i.length,d=[];for(let h=0;h<c;++h){for(let g of p[h]){let{permutationIndices:b,expandDims:y}=C.getEinsumPermutation(f,l[g]),T;C.isIdentityPermutation(b)?T=s[g]:(T=Cr({inputs:{x:s[g]},backend:t,attrs:{perm:b}}),d.push(T));let k=T.shape.slice();for(let I=0;I<y.length;++I)k.splice(y[I],0,1);x.arraysEqual(T.shape,k)||(T=ut({inputs:{x:T},backend:t,attrs:{shape:k}}),d.push(T)),m===null?m=T:(m=um({inputs:{a:T,b:m},backend:t}),d.push(m))}h<c-1&&(u[h]>=0&&(m=pu({inputs:{x:m},backend:t,attrs:{axis:u[h]-(i.length-f),keepDims:!1}}),d.push(m)),f--)}for(let h of d)h!==m&&t.disposeIntermediateTensorInfo(h);return m}var gK={kernelName:gf,backendName:"cpu",kernelFunc:Fde};function Rde(r){let{inputs:e,backend:t}=r,{dy:n,y:o}=e;ie([n,o],"eluGrad");let s=new Float32Array(x.sizeFromShape(o.shape)),i=t.data.get(o.dataId).values,a=t.data.get(n.dataId).values;for(let l=0;l<i.length;++l){let u=i[l];u>=1?s[l]=a[l]:s[l]=a[l]*(u+1)}return t.makeTensorInfo(o.shape,"float32",s)}var bK={kernelName:bf,backendName:"cpu",kernelFunc:Rde};var Lde=C.ERF_P,$de=C.ERF_A1,Pde=C.ERF_A2,Bde=C.ERF_A3,Ode=C.ERF_A4,zde=C.ERF_A5,Gde=ze(bl,r=>{let e=Math.sign(r),t=Math.abs(r),n=1/(1+Lde*t);return e*(1-((((zde*n+Ode)*n+Bde)*n+Pde)*n+$de)*n*Math.exp(-t*t))}),yK={kernelName:bl,backendName:"cpu",kernelFunc:Gde};function zd(r){let{inputs:e,backend:t,attrs:n}=r,{input:o}=e,{dim:s}=n,i=o.shape.length,a=o.shape.slice(),l=s;return s<0&&(x.assert(-(i+1)<=s,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+s+1),a.splice(l,0,1),ut({inputs:{x:o},backend:t,attrs:{shape:a}})}var xK={kernelName:ci,backendName:"cpu",kernelFunc:zd};var Wde=lt((r,e)=>r/e),yy=dt(Zs,Wde),xy={kernelName:Zs,backendName:"cpu",kernelFunc:yy};function sI(r,e,t){let n=r.shape,o=n[0],s=n[1],i=t.data.get(r.dataId),a=i.complexTensorInfos.real,l=i.complexTensorInfos.imag,u=[o,s],p=x.sizeFromShape(u),c=x.getTypedArrayFromDType("float32",p),m=x.getTypedArrayFromDType("float32",p);for(let g=0;g<o;g++){let b=Es({inputs:{x:a},backend:t,attrs:{begin:[g,0],size:[1,s]}}),y=Es({inputs:{x:l},backend:t,attrs:{begin:[g,0],size:[1,s]}}),T=jr({inputs:{real:b,imag:y},backend:t}),{real:k,imag:I}=Kde(T,e,t),S=C.mergeRealAndImagArrays(k,I);for(let N=0;N<s;N++){let F=C.getComplexWithIndex(S,N);c[g*s+N]=F.real,m[g*s+N]=F.imag}t.disposeIntermediateTensorInfo(b),t.disposeIntermediateTensorInfo(y),t.disposeIntermediateTensorInfo(T)}let f=t.makeTensorInfo(u,"float32",c),d=t.makeTensorInfo(u,"float32",m),h=jr({inputs:{real:f,imag:d},backend:t});return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(d),h}function Kde(r,e,t){let n=x.sizeFromShape(r.shape),o=t.data.get(r.dataId),s=t.data.get(o.complexTensorInfos.real.dataId).values,i=t.data.get(o.complexTensorInfos.imag.dataId).values;if(Vde(n)){let a=t0(s,i,n,e,t),l=[r.shape[0],r.shape[1]];if(e){let u=t.makeTensorInfo(l,"float32",a.real),p=t.makeTensorInfo(l,"float32",a.imag),c=t.makeTensorInfo([],"float32",x.createScalarValue(n,"float32")),m=bn({inputs:{x:c},backend:t}),f=xy.kernelFunc({inputs:{a:u,b:c},backend:t}),d=xy.kernelFunc({inputs:{a:p,b:m},backend:t}),h=t.data.get(f.dataId).values,g=t.data.get(d.dataId).values;return t.disposeIntermediateTensorInfo(u),t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(c),t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(d),{real:h,imag:g}}return a}else{let a=C.mergeRealAndImagArrays(s,i),l=Ude(a,n,e);return C.splitRealAndImagArrays(l)}}function Vde(r){return(r&r-1)==0}function t0(r,e,t,n,o){if(t===1)return{real:r,imag:e};let s=C.mergeRealAndImagArrays(r,e),i=t/2,a=C.complexWithEvenIndex(s),l=a.real,u=a.imag,p=[l.length],c=o.makeTensorInfo(p,"float32",l),m=o.makeTensorInfo(p,"float32",u),f=jr({inputs:{real:c,imag:m},backend:o}),d=C.complexWithOddIndex(s),h=d.real,g=d.imag,b=[h.length],y=o.makeTensorInfo(b,"float32",h),T=o.makeTensorInfo(b,"float32",g),k=jr({inputs:{real:y,imag:T},backend:o}),I=t0(l,u,i,n,o),S=I.real,N=I.imag,F=[S.length],$=o.makeTensorInfo(F,"float32",S),O=o.makeTensorInfo(F,"float32",N),V=jr({inputs:{real:$,imag:O},backend:o}),q=t0(h,g,i,n,o),W=q.real,Y=q.imag,Z=[W.length],J=o.makeTensorInfo(Z,"float32",W),se=o.makeTensorInfo(Z,"float32",Y),ee=jr({inputs:{real:J,imag:se},backend:o}),le=C.exponents(t,n),ae=[le.real.length],ce=o.makeTensorInfo(ae,"float32",le.real),ye=o.makeTensorInfo(ae,"float32",le.imag),me=jr({inputs:{real:ce,imag:ye},backend:o}),xe=um({inputs:{a:me,b:ee},backend:o}),ke=uu({inputs:{a:V,b:xe},backend:o}),we=by({inputs:{a:V,b:xe},backend:o}),Ne=Ss({inputs:{input:ke},backend:o}),Oe=Ss({inputs:{input:we},backend:o}),Ee=Ri({inputs:{input:ke},backend:o}),Ye=Ri({inputs:{input:we},backend:o}),at=gp({inputs:[Ne,Oe],backend:o,attrs:{axis:0}}),wt=gp({inputs:[Ee,Ye],backend:o,attrs:{axis:0}}),qt=o.data.get(at.dataId).values,Xt=o.data.get(wt.dataId).values;return o.disposeIntermediateTensorInfo(c),o.disposeIntermediateTensorInfo(m),o.disposeIntermediateTensorInfo(f),o.disposeIntermediateTensorInfo(y),o.disposeIntermediateTensorInfo(T),o.disposeIntermediateTensorInfo(k),o.disposeIntermediateTensorInfo($),o.disposeIntermediateTensorInfo(O),o.disposeIntermediateTensorInfo(V),o.disposeIntermediateTensorInfo(J),o.disposeIntermediateTensorInfo(se),o.disposeIntermediateTensorInfo(ee),o.disposeIntermediateTensorInfo(ce),o.disposeIntermediateTensorInfo(ye),o.disposeIntermediateTensorInfo(me),o.disposeIntermediateTensorInfo(xe),o.disposeIntermediateTensorInfo(ke),o.disposeIntermediateTensorInfo(we),o.disposeIntermediateTensorInfo(Ne),o.disposeIntermediateTensorInfo(Ee),o.disposeIntermediateTensorInfo(Oe),o.disposeIntermediateTensorInfo(Ye),o.disposeIntermediateTensorInfo(at),o.disposeIntermediateTensorInfo(wt),{real:qt,imag:Xt}}function Ude(r,e,t){let n=new Float32Array(e*2);for(let o=0;o<e;o++){let s=0,i=0;for(let a=0;a<e;a++){let l=C.exponent(o*a,e,t),u=C.getComplexWithIndex(r,a);s+=u.real*l.real-u.imag*l.imag,i+=u.real*l.imag+u.imag*l.real}t&&(s/=e,i/=e),C.assignToTypedArray(n,s,i,o)}return n}function jde(r){let{inputs:e,backend:t}=r,{input:n}=e,o=x.sizeFromShape(n.shape),s=n.shape[n.shape.length-1],i=o/s,a=ut({inputs:{x:n},backend:t,attrs:{shape:[i,s]}}),l=sI(a,!1,t),u=ut({inputs:{x:l},backend:t,attrs:{shape:n.shape}});return t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(l),u}var TK={kernelName:yf,backendName:"cpu",kernelFunc:jde};function Ty(r){let{backend:e,attrs:t}=r,{shape:n,value:o,dtype:s}=t,i=s||x.inferDtype(o),a=x.getArrayFromDType(i,x.sizeFromShape(n));return Hde(a,o,i),e.makeTensorInfo(n,i,a)}var kK={kernelName:zu,backendName:"cpu",kernelFunc:Ty};function Hde(r,e,t){r.fill(e)}var IK={kernelName:yl,backendName:"cpu",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{image:n}=r,o=t,s=x.getTypedArrayFromDType(n.dtype,x.sizeFromShape(n.shape)),[i,a,l,u]=n.shape,p=o.data.get(n.dataId).values;for(let m=0;m<i;m++){let f=m*l*a*u;for(let d=0;d<a;d++){let h=d*(l*u);for(let g=0;g<l;g++){let b=g*u;for(let y=0;y<u;y++){let k=[i,d,g,y][2],I=Math.round(l-k),S=f+h+b+y,N=p[S];if(I>=0&&I<l){let F=I*u,$=f+h+F+y;N=p[$]}s[S]=N}}}}return{dataId:o.write(s,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}};var qde=lt((r,e)=>Math.floor(r/e)),Xde=dt(ea,qde,null,"int32"),vK={kernelName:ea,backendName:"cpu",kernelFunc:Xde};function Yde(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,filter:s,bias:i,preluActivationWeights:a}=e,{strides:l,pad:u,dataFormat:p,dilations:c,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=n,h=QA({inputs:{x:o,filter:s},backend:t,attrs:{strides:l,pad:u,dataFormat:p,dilations:c,dimRoundingMode:m}});if(i){let g=h;h=uu({inputs:{a:h,b:i},backend:t}),t.disposeIntermediateTensorInfo(g)}if(f){let g=h;h=Bd(t,h,f,a,d),t.disposeIntermediateTensorInfo(g)}return h}var wK={kernelName:Ii,backendName:"cpu",kernelFunc:Yde};function Zde(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,filter:s,bias:i,preluActivationWeights:a}=e,{strides:l,pad:u,dataFormat:p,dilations:c,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=n,h=e0({inputs:{x:o,filter:s},backend:t,attrs:{strides:l,pad:u,dataFormat:p,dilations:c,dimRoundingMode:m}});if(i){let g=h;h=uu({inputs:{a:h,b:i},backend:t}),t.disposeIntermediateTensorInfo(g)}if(f){let g=h;h=Bd(t,h,f,a,d),t.disposeIntermediateTensorInfo(g)}return h}var _K={kernelName:vi,backendName:"cpu",kernelFunc:Zde};function Jde(r){let{inputs:e,backend:t}=r,{params:n,indices:o}=e,s=x.sizeFromShape(n.shape),i=o.shape,a=i[i.length-1],[l,u,p,c]=C.prepareAndValidate(n,o);if(u===0)return t.makeTensorInfo(l,n.dtype,[]);let m=t.data.get(o.dataId).values,f=t.bufferSync(n),d=Kk(m,f,n.dtype,u,a,p,c,n.shape,s);return t.makeTensorInfo(l,n.dtype,d.values)}var CK={kernelName:xl,backendName:"cpu",kernelFunc:Jde};function Qde(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,indices:s}=e,{axis:i,batchDims:a}=n;ie([o,s],"gatherV2");let l=a;a==null&&(l=0);let u=x.sizeFromShape(s.shape),p=x.parseAxisParam(i,o.shape)[0],c=C.segment_util.collectGatherOpShapeInfo(o,s,p,l),m=ut({inputs:{x:o},backend:t,attrs:{shape:[c.batchSize,c.outerSize,c.dimSize,c.sliceSize]}}),f=ut({inputs:{x:s},backend:t,attrs:{shape:[c.batchSize,u/c.batchSize]}}),d=[c.batchSize,c.outerSize,u/c.batchSize,c.sliceSize],h=t.bufferSync(f),g=t.bufferSync(m),b=Vk(g,h,d);return t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f),t.makeTensorInfo(c.outputShape,b.dtype,b.values)}var SK={kernelName:mi,backendName:"cpu",kernelFunc:Qde};function ehe(r){let{inputs:e,backend:t}=r,{input:n}=e,o=x.sizeFromShape(n.shape),s=n.shape[n.shape.length-1],i=o/s,a=ut({inputs:{x:n},backend:t,attrs:{shape:[i,s]}}),l=sI(a,!0,t),u=ut({inputs:{x:l},backend:t,attrs:{shape:n.shape}});return t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(l),u}var NK={kernelName:xf,backendName:"cpu",kernelFunc:ehe};var the=ze(Tl,r=>Number.isFinite(r)?1:0,"bool"),AK={kernelName:Tl,backendName:"cpu",kernelFunc:the};var rhe=ze(kl,r=>Math.abs(r)===Infinity?1:0,"bool"),DK={kernelName:kl,backendName:"cpu",kernelFunc:rhe};var nhe=ze(Il,r=>Number.isNaN(r)?1:0,"bool"),EK={kernelName:Il,backendName:"cpu",kernelFunc:nhe};function ohe(r){let{backend:e,attrs:t}=r,{start:n,stop:o,num:s}=t,i=Uk(n,o,s);return e.makeTensorInfo([i.length],"float32",i)}var MK={kernelName:kf,backendName:"cpu",kernelFunc:ohe};var she=ze(vl,r=>Math.log1p(r)),FK={kernelName:vl,backendName:"cpu",kernelFunc:she};var ahe=lt((r,e)=>r&&e),ihe=dt(wl,ahe,null,"bool"),RK={kernelName:wl,backendName:"cpu",kernelFunc:ihe};var lhe=ze(uc,r=>r?0:1,"bool"),LK={kernelName:uc,backendName:"cpu",kernelFunc:lhe};var uhe=lt((r,e)=>r||e),phe=dt(pc,uhe,null,"bool"),$K={kernelName:pc,backendName:"cpu",kernelFunc:phe};function che(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{depthRadius:s,bias:i,alpha:a,beta:l}=n;ie(o,"LRN");let u=o.shape[3],p=u-1,c=t.data.get(o.dataId).values,m=x.sizeFromShape(o.shape),f=new Float32Array(m);function d(h){let g=h%u,b=h-g+Math.max(0,g-s),y=h-g+Math.min(g+s,p),T=0;for(;b<=y;b++){let k=c[b];T+=k*k}return T}for(let h=0;h<m;h++){let g=d(h),b=c[h]*Math.pow(i+a*g,-l);f[h]=b}return t.makeTensorInfo(o.shape,o.dtype,f)}var PK={kernelName:Gu,backendName:"cpu",kernelFunc:che};function mhe(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,y:s,dy:i}=e,{depthRadius:a,bias:l,alpha:u,beta:p}=n;ie(i,"LRNGrad");let c=x.sizeFromShape(i.shape),m=i.shape[3],f=t.data.get(i.dataId).values,d=t.data.get(o.dataId).values,h=t.data.get(s.dataId).values,g=new Float32Array(c),b=c;for(let y=0;y<b;y++){let T=y%m,k=y-T+Math.max(0,T-a),I=y-T+Math.min(m,T+a+1),S=0;for(let N=k;N<I;N++)S+=Math.pow(d[N],2);S=u*S+l;for(let N=k;N<I;N++){let F=-2*u*p*d[N]*h[y]/S;y===N&&(F+=Math.pow(S,-p)),F*=f[y],g[N]+=F}}return t.makeTensorInfo(i.shape,o.dtype,g)}var BK={kernelName:If,backendName:"cpu",kernelFunc:mhe};function r0(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{reductionIndices:s,keepDims:i}=n,a=t,l=o.shape,u=l.length,p=x.parseAxisParam(s,l),c=p,m=C.getAxesPermutation(c,u),f=a.data.get(o.dataId).values;if(m!=null){let k=new Array(u);for(let I=0;I<k.length;I++)k[I]=l[m[I]];f=$d(f,l,o.dtype,m,k),c=C.getInnerMostAxes(c.length,u),l=k}ie(o,"max"),C.assertAxesAreInnerMostDims("max",c,u);let[d,h]=C.computeOutAndReduceShapes(l,c),g=x.sizeFromShape(h),b=jk(f,g,d,o.dtype),y=a.write(b,d,o.dtype),T=d;return i&&(T=C.expandShapeToKeepDim(d,p)),{dataId:y,shape:T,dtype:o.dtype}}var OK={kernelName:aa,backendName:"cpu",kernelFunc:r0};function fhe(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e;ie(o,"maxPool");let{filterSize:s,strides:i,pad:a,dimRoundingMode:l}=n,u=1;x.assert(C.eitherStridesOrDilationsAreOne(i,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let p=C.computePool2DInfo(o.shape,s,i,u,a,l),c;if(p.filterWidth===1&&p.filterHeight===1&&x.arraysEqual(p.inShape,p.outShape))c=bn({inputs:{x:o},backend:t});else{let m=t.data.get(o.dataId).values,f=x.computeStrides(o.shape),d=Od(m,o.shape,o.dtype,f,p,"max");c=t.makeTensorInfo(p.outShape,o.dtype,d.values)}return c}var zK={kernelName:ia,backendName:"cpu",kernelFunc:fhe};function dhe(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{filterSize:s,strides:i,pad:a,dimRoundingMode:l,dataFormat:u}=n;ie(o,"maxPool3d");let p=C.computePool3DInfo(o.shape,s,i,1,a,l,u),c=t.data.get(o.dataId).values,m=oI(c,o.shape,o.dtype,x.computeStrides(o.shape),p,"max");return t.makeTensorInfo(m.shape,"float32",m.values)}var GK={kernelName:Wu,backendName:"cpu",kernelFunc:dhe};function hhe(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,input:s}=e,{filterSize:i,strides:a,pad:l,dimRoundingMode:u}=n;ie([o,s],"maxPool3DGrad");let p=C.computePool3DInfo(s.shape,i,a,1,l,u),c=t.bufferSync(s),m=BW(c,p),f=p.strideDepth,d=p.strideHeight,h=p.strideWidth,g=p.dilationDepth,b=p.dilationHeight,y=p.dilationWidth,T=p.effectiveFilterDepth,k=p.effectiveFilterHeight,I=p.effectiveFilterWidth,S=T-1-p.padInfo.front,N=I-1-p.padInfo.left,F=k-1-p.padInfo.top,$=ve(s.shape,"float32"),O=t.bufferSync(o);for(let V=0;V<p.batchSize;++V)for(let q=0;q<p.inChannels;++q)for(let W=0;W<p.inDepth;++W)for(let Y=0;Y<p.inHeight;++Y)for(let Z=0;Z<p.inWidth;++Z){let J=W-S,se=Y-F,ee=Z-N,le=0;for(let ae=0;ae<T;ae+=g){let ce=(J+ae)/f;if(!(ce<0||ce>=p.outDepth||Math.floor(ce)!==ce))for(let ye=0;ye<k;ye+=b){let me=(se+ye)/d;if(!(me<0||me>=p.outHeight||Math.floor(me)!==me))for(let xe=0;xe<I;xe+=y){let ke=(ee+xe)/h;if(ke<0||ke>=p.outWidth||Math.floor(ke)!==ke)continue;let we=T*k*I-1-m.get(V,ce,me,ke,q),Ne=ae*k*I+ye*I+xe,Oe=we===Ne?1:0;if(Oe===0)continue;le+=O.get(V,ce,me,ke,q)*Oe}}}$.set(le,V,W,Y,Z,q)}return t.makeTensorInfo($.shape,$.dtype,$.values)}var WK={kernelName:wf,backendName:"cpu",kernelFunc:hhe};function ghe(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,input:s,output:i}=e,a=s;ie([s,i],"maxPoolGrad");let{filterSize:l,strides:u,pad:p,dimRoundingMode:c}=n,m=C.computePool2DInfo(a.shape,l,u,1,p,c),f=t.data.get(a.dataId).values,d=ve(m.outShape,a.dtype,nI(f,a.shape,a.dtype,m).values),h=m.strideHeight,g=m.strideWidth,b=m.dilationHeight,y=m.dilationWidth,T=m.effectiveFilterHeight,k=m.effectiveFilterWidth,I=k-1-m.padInfo.left,S=T-1-m.padInfo.top,N=ve(a.shape,"float32"),F=t.data.get(o.dataId).values,$=ve(o.shape,"float32",F);for(let O=0;O<m.batchSize;++O)for(let V=0;V<m.inChannels;++V)for(let q=0;q<m.inHeight;++q)for(let W=0;W<m.inWidth;++W){let Y=q-S,Z=W-I,J=0;for(let se=0;se<T;se+=b){let ee=(Y+se)/h;if(!(ee<0||ee>=m.outHeight||Math.floor(ee)!==ee))for(let le=0;le<k;le+=y){let ae=(Z+le)/g;if(ae<0||ae>=m.outWidth||Math.floor(ae)!==ae)continue;let ce=T*k-1-d.get(O,ee,ae,V),ye=se*k+le,me=ce===ye?1:0;if(me===0)continue;J+=$.get(O,ee,ae,V)*me}}N.set(J,O,q,W,V)}return t.makeTensorInfo(N.shape,N.dtype,N.values)}var KK={kernelName:vf,backendName:"cpu",kernelFunc:ghe};function VK(r,e,t,n,o){let s=x.computeStrides(e),i=Od(r,e,t,s,o,"max"),a=nI(r,e,t,o,!0,n);return[i.values,a.values]}var UK={kernelName:_f,backendName:"cpu",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{x:n}=r,{filterSize:o,strides:s,pad:i,includeBatchInIndex:a}=e,l=t;ie(n,"MaxPoolWithArgmax");let u=l.data.get(n.dataId).values,p=C.computePool2DInfo(n.shape,o,s,[1,1],i),[c,m]=VK(u,n.shape,n.dtype,a,p),f=l.write(c,p.outShape,n.dtype),d=l.write(m,p.outShape,n.dtype);return[{dataId:f,shape:p.outShape,dtype:n.dtype},{dataId:d,shape:p.outShape,dtype:"int32"}]}};function bhe(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,keepDims:i}=n,a=x.parseAxisParam(s,o.shape),u=C.computeOutAndReduceShapes(o.shape,a)[1],p=x.sizeFromShape(u),c=[],m=t.makeTensorInfo([],"float32",new Float32Array([p]));c.push(m);let f=Ns({inputs:{x:o},backend:t,attrs:{dtype:"float32"}});c.push(f);let d=yy({inputs:{a:f,b:m},backend:t});c.push(d);let h=pu({inputs:{x:d},backend:t,attrs:{axis:s,keepDims:i}});return c.forEach(g=>t.disposeIntermediateTensorInfo(g)),h}var jK={kernelName:la,backendName:"cpu",kernelFunc:bhe};function yhe(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,keepDims:i}=n;ie(o,"min");let a=x.parseAxisParam(s,o.shape),l=a,u=C.getAxesPermutation(l,o.shape.length),p=o;u!=null&&(p=Cr({inputs:{x:o},backend:t,attrs:{perm:u}}),l=C.getInnerMostAxes(l.length,o.shape.length)),C.assertAxesAreInnerMostDims("min",l,p.shape.length);let[c,m]=C.computeOutAndReduceShapes(p.shape,l),f=x.sizeFromShape(m),d=x.makeZerosTypedArray(x.sizeFromShape(c),p.dtype),h=t.data.get(p.dataId).values;for(let b=0;b<d.length;++b){let y=b*f,T=h[y];for(let k=0;k<f;++k){let I=h[y+k];(Number.isNaN(I)||I<T)&&(T=I)}d[b]=T}u!=null&&t.disposeIntermediateTensorInfo(p);let g=t.makeTensorInfo(c,p.dtype,d);if(i){let b=C.expandShapeToKeepDim(c,a),y=ut({inputs:{x:g},backend:t,attrs:{shape:b}});return t.disposeIntermediateTensorInfo(g),y}return g}var HK={kernelName:ua,backendName:"cpu",kernelFunc:yhe};function xhe(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{paddings:s,mode:i}=n;ie(o,"mirrorPad");let a=s.map((T,k)=>T[0]+o.shape[k]+T[1]),l=s.map(T=>T[0]),u=s.map((T,k)=>T[0]+o.shape[k]),p=i==="reflect"?0:1,c=t.data.get(o.dataId).values,m=o.shape.length,f=x.computeStrides(o.shape),d=x.sizeFromShape(a),h=a.length,g=x.computeStrides(a),b=x.getTypedArrayFromDType(o.dtype,d);for(let T=0;T<d;T++){let k=x.indexToLoc(T,h,g);for(let S=0;S<h;S++)k[S]<l[S]?k[S]=l[S]*2-k[S]-p:k[S]>=u[S]&&(k[S]=(u[S]-1)*2-k[S]+p);k=k.map((S,N)=>S-l[N]);let I=x.locToIndex(k,m,f);b[T]=c[I]}return{dataId:t.write(b,a,o.dtype),shape:a,dtype:o.dtype}}var qK={kernelName:pa,backendName:"cpu",kernelFunc:xhe};var The=lt((r,e)=>{let t=r%e;return r<0&&e<0||r>=0&&e>=0?t:(t+e)%e}),khe=dt(_l,The),XK={kernelName:_l,backendName:"cpu",kernelFunc:khe};var ZK=Wi(Hx());function n0(r){let{inputs:e,backend:t,attrs:n}=r,{logits:o}=e,{dim:s}=n,i=o.shape.length,a=s;if(a===-1&&(a=i-1),a!==i-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${i} and dim was ${a}`);let l=x.parseAxisParam([a],o.shape),u=r0({inputs:{x:o},backend:t,attrs:{reductionIndices:l,keepDims:!1}}),p=C.expandShapeToKeepDim(u.shape,l),c=ut({inputs:{x:u},backend:t,attrs:{shape:p}}),m=by({inputs:{a:o,b:c},backend:t}),f=AA({inputs:{x:m},backend:t}),d=pu({inputs:{x:f},backend:t,attrs:{axis:l,keepDims:!1}}),h=ut({inputs:{x:d},backend:t,attrs:{shape:p}}),g=yy({inputs:{a:f,b:h},backend:t});return t.disposeIntermediateTensorInfo(u),t.disposeIntermediateTensorInfo(c),t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(h),g}var YK={kernelName:Sa,backendName:"cpu",kernelFunc:n0};function Ihe(r){let{inputs:e,backend:t,attrs:n}=r,{logits:o}=e,{numSamples:s,seed:i,normalized:a}=n;ie(o,"multinomial");let l=a?o:n0({inputs:{logits:o},backend:t,attrs:{dim:-1}}),u=l.shape[0],p=l.shape[1],c=t.data.get(l.dataId).values,m=[u,s],f=x.makeZerosTypedArray(x.sizeFromShape(m),"int32");for(let d=0;d<u;++d){let h=d*p,g=new Float32Array(p-1);g[0]=c[h];for(let T=1;T<g.length;++T)g[T]=g[T-1]+c[h+T];let b=ZK.alea(i.toString()),y=d*s;for(let T=0;T<s;++T){let k=b();f[y+T]=g.length;for(let I=0;I<g.length;I++)if(k<g[I]){f[y+T]=I;break}}}return a||t.disposeIntermediateTensorInfo(l),t.makeTensorInfo(m,"int32",f)}var JK={kernelName:Cf,backendName:"cpu",kernelFunc:Ihe};var vhe=gn.nonMaxSuppressionV3Impl;function whe(r){let{inputs:e,backend:t,attrs:n}=r,{boxes:o,scores:s}=e,{maxOutputSize:i,iouThreshold:a,scoreThreshold:l}=n;ie(o,"NonMaxSuppression");let u=t.data.get(o.dataId).values,p=t.data.get(s.dataId).values,{selectedIndices:c}=vhe(u,p,i,a,l);return t.makeTensorInfo([c.length],"int32",new Int32Array(c))}var QK={kernelName:Cl,backendName:"cpu",kernelFunc:whe};var _he=gn.nonMaxSuppressionV4Impl;function Che(r){let{inputs:e,backend:t,attrs:n}=r,{boxes:o,scores:s}=e,{maxOutputSize:i,iouThreshold:a,scoreThreshold:l,padToMaxOutputSize:u}=n;ie(o,"NonMaxSuppressionPadded");let p=t.data.get(o.dataId).values,c=t.data.get(s.dataId).values,{selectedIndices:m,validOutputs:f}=_he(p,c,i,a,l,u);return[t.makeTensorInfo([m.length],"int32",new Int32Array(m)),t.makeTensorInfo([],"int32",new Int32Array([f]))]}var eV={kernelName:Sl,backendName:"cpu",kernelFunc:Che};var She=gn.nonMaxSuppressionV5Impl;function Nhe(r){let{inputs:e,backend:t,attrs:n}=r,{boxes:o,scores:s}=e,{maxOutputSize:i,iouThreshold:a,scoreThreshold:l,softNmsSigma:u}=n;ie(o,"NonMaxSuppressionWithScore");let p=t.data.get(o.dataId).values,c=t.data.get(s.dataId).values,m=i,f=a,d=l,h=u,{selectedIndices:g,selectedScores:b}=She(p,c,m,f,d,h);return[t.makeTensorInfo([g.length],"int32",new Int32Array(g)),t.makeTensorInfo([b.length],"float32",new Float32Array(b))]}var tV={kernelName:Nl,backendName:"cpu",kernelFunc:Nhe};function Ahe(r){let{inputs:e,backend:t,attrs:n}=r,{indices:o}=e,{depth:s,onValue:i,offValue:a}=n;ie(o,"oneHot");let l=x.sizeFromShape(o.shape),u=new Float32Array(l*s);u.fill(a);let p=t.data.get(o.dataId).values;for(let c=0;c<l;++c)p[c]>=0&&p[c]<s&&(u[c*s+p[c]]=i);return t.makeTensorInfo([...o.shape,s],"int32",u)}var rV={kernelName:fa,backendName:"cpu",kernelFunc:Ahe};function ky(r){let{inputs:e,backend:t}=r,{x:n}=e;if(n.dtype==="string")throw new Error("zerosLike is not supported for string tensors");if(n.dtype==="complex64"){let o=Ss({inputs:{input:n},backend:t}),s=ky({inputs:{x:o},backend:t}),i=Ri({inputs:{input:n},backend:t}),a=ky({inputs:{x:i},backend:t}),l=jr({inputs:{real:s,imag:a},backend:t});return t.disposeIntermediateTensorInfo(o),t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(a),l}else return Ty({backend:t,attrs:{shape:n.shape,value:0,dtype:n.dtype}})}var nV={kernelName:Ti,backendName:"cpu",kernelFunc:ky};function oV(r){let{inputs:e,backend:t}=r,{x:n}=e;if(n.dtype==="string")throw new Error("onesLike is not supported for string tensors");if(n.dtype==="complex64"){let o=Ss({inputs:{input:n},backend:t}),s=oV({inputs:{x:o},backend:t}),i=Ri({inputs:{input:n},backend:t}),a=ky({inputs:{x:i},backend:t}),l=jr({inputs:{real:s,imag:a},backend:t});return t.disposeIntermediateTensorInfo(o),t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(a),l}else return Ty({backend:t,attrs:{shape:n.shape,value:1,dtype:n.dtype}})}var sV={kernelName:fi,backendName:"cpu",kernelFunc:oV};function o0(r){let{inputs:e,backend:t,attrs:n}=r,{axis:o}=n;if(e.length===1)return zd({inputs:{input:e[0]},backend:t,attrs:{dim:o}});let s=e[0].shape,i=e[0].dtype;e.forEach(p=>{x.assertShapesMatch(s,p.shape,"All tensors passed to stack must have matching shapes"),x.assert(i===p.dtype,()=>"All tensors passed to stack must have matching dtypes")});let a=[],l=e.map(p=>{let c=zd({inputs:{input:p},backend:t,attrs:{dim:o}});return a.push(c),c}),u=gp({inputs:l,backend:t,attrs:{axis:o}});return a.forEach(p=>t.disposeIntermediateTensorInfo(p)),u}var aV={kernelName:di,backendName:"cpu",kernelFunc:o0};function Dhe(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{paddings:s,constantValue:i}=n;ie(o,"pad");let a=s.map((y,T)=>y[0]+o.shape[T]+y[1]),l=s.map(y=>y[0]),u=t.data.get(o.dataId).values,p=x.sizeFromShape(o.shape),c=o.shape.length,m=x.computeStrides(o.shape),f=x.sizeFromShape(a),d=a.length,h=x.computeStrides(a),g=x.getTypedArrayFromDType(o.dtype,f);i!==0&&g.fill(i);for(let y=0;y<p;y++){let k=x.indexToLoc(y,c,m).map((S,N)=>S+l[N]),I=x.locToIndex(k,d,h);g[I]=u[y]}return{dataId:t.write(g,a,o.dtype),shape:a,dtype:o.dtype}}var aI={kernelName:da,backendName:"cpu",kernelFunc:Dhe};var Ehe=lt((r,e)=>Math.pow(r,e)),Mhe=dt(ha,Ehe),iV={kernelName:ha,backendName:"cpu",kernelFunc:Mhe};function Fhe(r){let{backend:e,attrs:t}=r,{start:n,stop:o,dtype:s,step:i}=t,a=Hk(n,o,i,s);return e.makeTensorInfo([a.length],s,a)}var lV={kernelName:Ku,backendName:"cpu",kernelFunc:Fhe};var Rhe=ze(Al,r=>1/r),uV={kernelName:Al,backendName:"cpu",kernelFunc:Rhe};function Lhe(r){let{inputs:e,backend:t,attrs:n}=r,{images:o}=e,{alignCorners:s,halfPixelCenters:i,size:a}=n;ie(o,"resizeBilinear");let l=x.computeStrides(o.shape),[u,p]=a,[c,m,f,d]=o.shape,h=t.data.get(o.dataId).values,g=new Float32Array(x.sizeFromShape([c,u,p,d])),b=[s&&u>1?m-1:m,s&&p>1?f-1:f],y=[s&&u>1?u-1:u,s&&p>1?p-1:p],T=0,k=b[0]/y[0],I=b[1]/y[1];for(let S=0;S<c;S++)for(let N=0;N<u;N++){let F;i?F=k*(N+.5)-.5:F=k*N;let $=Math.max(0,Math.floor(F)),O=F-$,V=Math.min(m-1,Math.ceil(F)),q=S*l[0]+$*l[1],W=S*l[0]+V*l[1];for(let Y=0;Y<p;Y++){let Z;i?Z=I*(Y+.5)-.5:Z=I*Y;let J=Math.max(0,Math.floor(Z)),se=Z-J,ee=Math.min(f-1,Math.ceil(Z)),le=q+J*l[2],ae=W+J*l[2],ce=q+ee*l[2],ye=W+ee*l[2];for(let me=0;me<d;me++){let xe=h[le+me],ke=h[ae+me],we=h[ce+me],Ne=h[ye+me],Oe=xe+(we-xe)*se,Ee=ke+(Ne-ke)*se,Ye=Oe+(Ee-Oe)*O;g[T++]=Ye}}}return t.makeTensorInfo([c,u,p,d],"float32",g)}var pV={kernelName:ya,backendName:"cpu",kernelFunc:Lhe};function $he(r){let{inputs:e,backend:t,attrs:n}=r,{images:o,dy:s}=e,{alignCorners:i}=n;ie([s,o],"resizeBilinearGrad");let a=x.computeStrides(o.shape),[l,u,p,c]=o.shape,[,m,f]=s.shape,d=new Float32Array(l*u*p*c),h=[i&&m>1?u-1:u,i&&f>1?p-1:p],g=[i&&m>1?m-1:m,i&&f>1?f-1:f],b=h[0]/g[0],y=h[1]/g[1],T=t.data.get(s.dataId).values,k=0;for(let I=0;I<l;I++){let S=I*a[0];for(let N=0;N<m;N++){let F=N*b,$=Math.floor(F),O=Math.min(Math.ceil(F),u-1),V=S+$*a[1],q=S+O*a[1],W=F-$,Y=1-W;for(let Z=0;Z<f;Z++){let J=Z*y,se=Math.floor(J),ee=Math.min(Math.ceil(J),p-1),le=J-se,ae=1-le,ce=V+se*a[2],ye=V+ee*a[2],me=q+se*a[2],xe=q+ee*a[2],ke=Y*ae,we=Y*le,Ne=W*ae,Oe=W*le;for(let Ee=0;Ee<c;Ee++){let Ye=T[k++];d[ce+Ee]+=Ye*ke,d[ye+Ee]+=Ye*we,d[me+Ee]+=Ye*Ne,d[xe+Ee]+=Ye*Oe}}}}return t.makeTensorInfo([l,p,u,c],"float32",d)}var cV={kernelName:Nf,backendName:"cpu",kernelFunc:$he};function Phe(r){let{inputs:e,backend:t,attrs:n}=r,{images:o}=e,{alignCorners:s,halfPixelCenters:i,size:a}=n;ie(o,"resizeNearestNeighbor");let l=x.computeStrides(o.shape),[u,p]=a,[c,m,f,d]=o.shape,h=t.data.get(o.dataId).values,g=new Float32Array(c*u*p*d),b=[s&&u>1?m-1:m,s&&p>1?f-1:f],y=[s&&u>1?u-1:u,s&&p>1?p-1:p],T=b[0]/y[0],k=b[1]/y[1],I=0;for(let S=0;S<c;S++){let N=S*l[0];for(let F=0;F<u;F++){let $=i?T*(F+.5):T*F,O=Math.min(m-1,s?Math.round($):Math.floor($));i&&(O=Math.max(0,O));let V=N+O*l[1];for(let q=0;q<p;q++){let W=i?k*(q+.5):k*q,Y=Math.min(f-1,s?Math.round(W):Math.floor(W));i&&(Y=Math.max(0,Y));let Z=V+Y*l[2];for(let J=0;J<d;J++){let se=h[Z+J];g[I++]=se}}}}return t.makeTensorInfo([c,u,p,d],o.dtype,g)}var mV={kernelName:Vu,backendName:"cpu",kernelFunc:Phe};function Bhe(r){let{inputs:e,backend:t,attrs:n}=r,{images:o,dy:s}=e,{alignCorners:i}=n;ie([s,o],"resizeNearestNeighborGrad");let a=x.computeStrides(o.shape),l=x.computeStrides(s.shape),[u,p,c,m]=o.shape,[,f,d]=s.shape,h=new Float32Array(u*p*c*m),g=t.data.get(s.dataId).values,b=[i&&f>1?p-1:p,i&&d>1?c-1:c],y=[i&&f>1?f-1:f,i&&d>1?d-1:d],T=b[0]/y[0],k=b[1]/y[1],I=1/T,S=1/k,N=Math.ceil(I)*2+2,F=Math.ceil(S)*2+2;for(let $=0;$<u;$++){let O=$*a[0];for(let V=0;V<p;V++){let q=O+V*a[1],W=Math.floor(V*I),Y=Math.floor(W-N/2);for(let Z=0;Z<c;Z++){let J=q+Z*a[2],se=Math.floor(Z*S),ee=Math.floor(se-F/2);for(let le=0;le<m;le++){let ae=0;for(let ce=0;ce<N;ce++){let ye=ce+Y;if(ye<0||ye>=f)continue;let me=O+ye*l[1],xe=ye*T,ke=Math.min(p-1,i?Math.round(xe):Math.floor(xe));if(V===ke)for(let we=0;we<F;we++){let Ne=we+ee;if(Ne<0||Ne>=d)continue;let Oe=me+Ne*l[2],Ee=Ne*k,Ye=Math.min(c-1,i?Math.round(Ee):Math.floor(Ee));Z===Ye&&(ae+=g[Oe+le])}}h[J+le]=ae}}}}return t.makeTensorInfo(o.shape,o.dtype,h)}var fV={kernelName:Sf,backendName:"cpu",kernelFunc:Bhe};function Ohe(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{dims:s}=n;ie(o,"reverse");let i=o.shape.length,a=x.parseAxisParam(s,o.shape);if(i===0)return bn({inputs:{x:o},backend:t});let l=new bt(o.shape,o.dtype),u=t.bufferSync(o);for(let p=0;p<l.size;p++){let c=l.indexToLoc(p),m=c.slice();a.forEach(f=>m[f]=o.shape[f]-1-m[f]),l.set(u.get(...m),...c)}return t.makeTensorInfo(l.shape,l.dtype,l.values)}var dV={kernelName:Ta,backendName:"cpu",kernelFunc:Ohe};var hV={kernelName:Bl,backendName:"cpu",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{image:n}=r,{radians:o,fillValue:s,center:i}=e,a=t,l=x.getTypedArrayFromDType(n.dtype,x.sizeFromShape(n.shape)),[u,p,c,m]=n.shape,[f,d]=C.getImageCenter(i,p,c),h=255,g=Math.sin(o),b=Math.cos(o),y=a.data.get(n.dataId).values;for(let k=0;k<u;k++){let I=k*c*p*m;for(let S=0;S<p;S++){let N=S*(c*m);for(let F=0;F<c;F++){let $=F*m;for(let O=0;O<m;O++){let V=[u,S,F,O],q=V[2],W=V[1],Y=(q-f)*b-(W-d)*g,Z=(q-f)*g+(W-d)*b;Y=Math.round(Y+f),Z=Math.round(Z+d);let J=s;if(typeof s!="number"&&(O===3?J=h:J=s[O]),Y>=0&&Y<c&&Z>=0&&Z<p){let ee=Z*(c*m),le=Y*m,ae=I+ee+le+O;J=y[ae]}let se=I+N+$+O;l[se]=J}}}}return{dataId:a.write(l,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}};var zhe=ze(ka,r=>{let e=Math.floor(r);return r-e<.5?Math.floor(r):r-e>.5?Math.ceil(r):e%2==0?e:e+1}),gV={kernelName:ka,backendName:"cpu",kernelFunc:zhe};function iI(r,e,t,n,o,s,i,a,l,u){let p=[n/o,o],c=r.values,m=e.values;if(n===0)return ve(t,e.dtype);let f=ve(p,e.dtype);f.values.fill(l);for(let d=0;d<s;d++){let h=[],g=0;for(let b=0;b<i;b++){let y=c[d*i+b];h.push(y),g+=y*a[b]}if(g<0||g>=n/o)throw new Error(`Invalid indices: ${h} does not index into ${t}`);for(let b=0;b<o;b++)u?f.values[g*o+b]+=m[d*o+b]:f.values[g*o+b]=e.rank===0?m[0]:m[d*o+b]}return f}function Ghe(r){let{inputs:e,backend:t,attrs:n}=r,{indices:o,updates:s}=e,{shape:i}=n,{sliceRank:a,numUpdates:l,sliceSize:u,strides:p,outputSize:c}=C.calculateShapes(s,o,i),m=!0,f=t.bufferSync(o),d=t.bufferSync(s),h=iI(f,d,i,c,u,l,a,p,0,m);return t.makeTensorInfo(i,h.dtype,h.values)}var bV={kernelName:Dl,backendName:"cpu",kernelFunc:Ghe};function Whe(r){let{inputs:e,backend:t}=r,{condition:n,t:o,e:s}=e;ie([n,o,s],"select");let i=n.shape.length,a=t.data.get(n.dataId).values,l=t.data.get(o.dataId).values,u=t.data.get(s.dataId).values,p=Mr(o.dtype,s.dtype),c=x.makeZerosTypedArray(x.sizeFromShape(o.shape),p),m=0,f=i===0||i>1||o.shape.length===1?1:x.sizeFromShape(o.shape.slice(1));for(let d=0;d<a.length;d++)for(let h=0;h<f;h++)a[d]===1?c[m++]=l[d]:c[m++]=u[d];return t.makeTensorInfo(o.shape,p,c)}var yV={kernelName:bi,backendName:"cpu",kernelFunc:Whe};var Khe=C.SELU_SCALEALPHA,Vhe=C.SELU_SCALE,Uhe=ze(El,r=>r>=0?Vhe*r:Khe*(Math.exp(r)-1)),xV={kernelName:El,backendName:"cpu",kernelFunc:Uhe};var jhe=ze(Fl,r=>r<0?-1:r>0?1:0),TV={kernelName:Fl,backendName:"cpu",kernelFunc:jhe};var Hhe=ze(va,r=>Math.sin(r)),kV={kernelName:va,backendName:"cpu",kernelFunc:Hhe};var qhe=ze(Ml,r=>Math.sinh(r)),IV={kernelName:Ml,backendName:"cpu",kernelFunc:qhe};var Xhe=11920928955078125e-23,vV=Math.log(Xhe)+2,Yhe=ze(Rl,r=>{let e=r>-vV,t=r<vV,n=Math.exp(r),o;return t?o=n:e?o=r:o=Math.log(1+n),o}),wV={kernelName:Rl,backendName:"cpu",kernelFunc:Yhe};function Zhe(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{blockShape:s,paddings:i}=n;ie([o],"spaceToBatchND");let a=x.sizeFromShape(s),l=[[0,0]];l.push(...i);for(let S=1+s.length;S<o.shape.length;++S)l.push([0,0]);let u=aI.kernelFunc({inputs:{x:o},backend:t,attrs:{paddings:l,constantValue:0}}),p=C.getReshaped(u.shape,s,a,!1),c=C.getPermuted(p.length,s.length,!1),m=C.getReshapedPermuted(u.shape,s,a,!1),h=ut({inputs:{x:u},backend:t,attrs:{shape:p}}),y=Cr({inputs:{x:h},backend:t,attrs:{perm:c}}),I=ut({inputs:{x:y},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(u),t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(y),I}var _V={kernelName:Uu,backendName:"cpu",kernelFunc:Zhe};function Jhe(r){let{inputs:e,backend:t}=r,{indices:n,values:o,denseShape:s,defaultValue:i}=e;if(s.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
|
|
${s.shape}`);if(n.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
|
|
${n.shape}`);if(o.shape.length!==1)throw new Error(`Values must be a vector, saw:
|
|
${o.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
|
|
${i.shape}`);let a=t.data.get(n.dataId).values,l=t.data.get(o.dataId).values,u=t.data.get(s.dataId).values,p=t.data.get(i.dataId).values[0],[c,m,f,d,h]=qk(a,n.shape,n.dtype,l,o.dtype,u,p);return[t.makeTensorInfo(m,n.dtype,c),t.makeTensorInfo([m[0]],o.dtype,f),t.makeTensorInfo([d.length],"bool",new Uint8Array(d.map(g=>Number(g)))),t.makeTensorInfo([h.length],n.dtype,new Int32Array(h))]}var CV={kernelName:Af,backendName:"cpu",kernelFunc:Jhe};function Qhe(r){let{inputs:e,backend:t}=r,{inputIndices:n,inputShape:o,newShape:s}=e;if(n.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
|
|
${n.shape}`);if(o.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
|
|
${o.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=Array.from(t.data.get(o.dataId).values),a=t.data.get(n.dataId).values,l=Array.from(t.data.get(s.dataId).values),[u,p,c]=Xk(a,n.shape,n.dtype,i,l);return[t.makeTensorInfo(p,n.dtype,u),t.makeTensorInfo([c.length],s.dtype,new Int32Array(c))]}var SV={kernelName:Df,backendName:"cpu",kernelFunc:Qhe};function ege(r){let{inputs:e,backend:t}=r,{data:n,indices:o,segmentIds:s}=e;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${o.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${s.shape}`);let i=t.data.get(n.dataId).values,a=t.data.get(o.dataId).values,l=t.data.get(s.dataId).values,[u,p]=Pd(i,n.shape,n.dtype,a,l,!0);return t.makeTensorInfo(p,n.dtype,u)}var NV={kernelName:Ef,backendName:"cpu",kernelFunc:ege};function tge(r){let{inputs:e,backend:t}=r,{data:n,indices:o,segmentIds:s}=e;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${o.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${s.shape}`);let i=t.data.get(n.dataId).values,a=t.data.get(o.dataId).values,l=t.data.get(s.dataId).values,[u,p]=Pd(i,n.shape,n.dtype,a,l);return t.makeTensorInfo(p,n.dtype,u)}var AV={kernelName:Mf,backendName:"cpu",kernelFunc:tge};function rge(r){let{inputs:e,backend:t,attrs:n}=r,{sparseIndices:o,sparseValues:s,defaultValue:i}=e,{outputShape:a}=n,{sliceRank:l,numUpdates:u,sliceSize:p,strides:c,outputSize:m}=C.calculateShapes(s,o,a),f=!1,d=t.bufferSync(o),h=t.bufferSync(s),g=t.data.get(i.dataId).values[0],b=iI(d,h,a,m,p,u,l,c,g,f);return t.makeTensorInfo(a,b.dtype,b.values)}var DV={kernelName:Ff,backendName:"cpu",kernelFunc:rge};function nge(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{numOrSizeSplits:s,axis:i}=n,a=x.parseAxisParam(i,o.shape)[0],l=C.prepareSplitSize(o,s,a),u=new Array(o.shape.length).fill(0),p=o.shape.slice();return l.map(c=>{let m=[...p];m[a]=c;let f=Es({inputs:{x:o},backend:t,attrs:{begin:u,size:m}});return u[a]+=c,f})}var EV={kernelName:yi,backendName:"cpu",kernelFunc:nge};var oge=ze(_a,r=>Math.sqrt(r)),MV={kernelName:_a,backendName:"cpu",kernelFunc:oge};var FV={kernelName:ju,backendName:"cpu",kernelFunc:({inputs:r,backend:e})=>{let{x:t}=r,n=e;ie(t,"square");let o=n.data.get(t.dataId).values,s=new Float32Array(o.length);for(let a=0;a<o.length;++a){let l=o[a];s[a]=l*l}return{dataId:n.write(s,t.shape,t.dtype),shape:t.shape,dtype:t.dtype}}};var sge=ze(cs,(r,e)=>{let t=e;return isNaN(r)?NaN:r>0?1:t.alpha}),RV={kernelName:cs,backendName:"cpu",kernelFunc:sge};function age(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{begin:s,end:i,strides:a,beginMask:l,endMask:u,ellipsisMask:p,newAxisMask:c,shrinkAxisMask:m}=n;ie(o,"stridedSlice");let{nonStrided:f,$begin:d,$strides:h,size:g,newShape:b,outShape:y}=br.sliceInfo(o.shape,s,i,a,l,u,p,c,m),T=ut({inputs:{x:o},backend:t,attrs:{shape:b}}),k;if(f){let S=Es({inputs:{x:T},backend:t,attrs:{begin:d,size:g}});k=ut({inputs:{x:S},backend:t,attrs:{shape:y}}),t.disposeIntermediateTensorInfo(S)}else if(y.some(S=>S===0))k=t.makeTensorInfo(y,o.dtype,[]);else{let S=t.bufferSync(T),N=Yk(y,S,h,d);k=t.makeTensorInfo(N.shape,N.dtype,N.values)}let I=ut({inputs:{x:k},backend:t,attrs:{shape:y}});return t.disposeIntermediateTensorInfo(T),t.disposeIntermediateTensorInfo(k),I}var LV={kernelName:Ll,backendName:"cpu",kernelFunc:age};function ige(r){let{inputs:e,backend:t,attrs:n}=r,{separator:o,nGramWidths:s,leftPad:i,rightPad:a,padWidth:l,preserveShortSequences:u}=n,{data:p,dataSplits:c}=e,m=t.data.get(p.dataId).values,f=t.data.get(c.dataId).values,[d,h]=Zk(m,f,o,s,i,a,l,u);return[t.makeTensorInfo([d.length],"string",d),t.makeTensorInfo(c.shape,"int32",h)]}var $V={kernelName:Rf,backendName:"cpu",kernelFunc:ige};function lge(r){let{inputs:e,backend:t,attrs:n}=r,{skipEmpty:o}=n,{input:s,delimiter:i}=e;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(s.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${s.shape}`);if(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);let a=t.data.get(s.dataId).values,l=t.data.get(i.dataId).values[0],[u,p,c]=Jk(a,l,o),m=p.length;return[t.makeTensorInfo([m,2],"int32",u),t.makeTensorInfo([m],"string",p),t.makeTensorInfo([2],"int32",new Int32Array(c))]}var PV={kernelName:Lf,backendName:"cpu",kernelFunc:lge};function uge(r){let{inputs:e,backend:t,attrs:n}=r,{numBuckets:o}=n,{input:s}=e;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(o<=0)throw new Error("Number of buckets must be at least 1");let i=t.data.get(s.dataId).values,a=Qk(i,o);return t.makeTensorInfo(s.shape,"int32",a)}var BV={kernelName:$f,backendName:"cpu",kernelFunc:uge};var pge=ze(Na,r=>Math.tan(r)),OV={kernelName:Na,backendName:"cpu",kernelFunc:pge};var cge=ze(Aa,r=>Math.tanh(r)),zV={kernelName:Aa,backendName:"cpu",kernelFunc:cge};function mge(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{reps:s}=n;ie(o,"tile");let i=eI(t.bufferSync(o),s);return t.makeTensorInfo(i.shape,i.dtype,i.values)}var GV={kernelName:Ko,backendName:"cpu",kernelFunc:mge};function fge(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{k:s,sorted:i}=n;ie(o,"topk");let a=t.data.get(o.dataId).values,[l,u]=tI(a,o.shape,o.dtype,s,i);return[t.makeTensorInfo(l.shape,l.dtype,l.values),t.makeTensorInfo(u.shape,u.dtype,u.values)]}var WV={kernelName:$l,backendName:"cpu",kernelFunc:fge};function dge(r){let{inputs:e,attrs:t,backend:n}=r,{image:o,transforms:s}=e,{interpolation:i,fillMode:a,fillValue:l,outputShape:u}=t,[p,c,m,f]=o.shape,[d,h]=u!=null?u:[c,m],g=[p,d,h,f],b=x.computeStrides(o.shape),y=b[0],T=b[1],k=b[2],I=x.getTypedArrayFromDType(o.dtype,x.sizeFromShape(g));I.fill(l);let S=n.data.get(o.dataId).values,N=n.data.get(s.dataId).values;for(let $=0;$<p;++$){let O=s.shape[0]===1?N:N.subarray($*8,$*8+8);for(let V=0;V<d;++V)for(let q=0;q<h;++q)for(let W=0;W<f;++W){let Y,Z=O[6]*q+O[7]*V+1;if(Z===0)continue;let J=(O[0]*q+O[1]*V+O[2])/Z,se=(O[3]*q+O[4]*V+O[5])/Z,ee=VV(J,m,a),le=VV(se,c,a);switch(i){case"nearest":Y=xge(S,c,m,y,T,k,$,le,ee,W,l);break;case"bilinear":Y=Tge(S,c,m,y,T,k,$,le,ee,W,l);break;default:throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${i}`)}let ae=$*y+V*T+q*k+W;I[ae]=Y}return n.makeTensorInfo(g,o.dtype,I)}return{dataId:n.write(I,g,o.dtype),shape:o.shape,dtype:o.dtype}}var KV={kernelName:Pl,backendName:"cpu",kernelFunc:dge};function VV(r,e,t){switch(t){case"reflect":return hge(r,e);case"wrap":return gge(r,e);case"nearest":return yge(r,e);case"constant":default:return bge(r,e)}}function hge(r,e){let t=r;if(t<0)if(e<=1)t=0;else{let n=2*e;t<n&&(t=n*Math.trunc(-t/n)+t),t=t<-e?t+n:-t-1}else if(t>e-1)if(e<=1)t=0;else{let n=2*e;t-=n*Math.trunc(t/n),t>=e&&(t=n-t-1)}return x.clamp(0,t,e-1)}function gge(r,e){let t=r;if(t<0)if(e<=1)t=0;else{let n=e-1;t+=e*(Math.trunc(-t/n)+1)}else if(t>e-1)if(e<=1)t=0;else{let n=e-1;t-=e*Math.trunc(t/n)}return x.clamp(0,t,e-1)}function bge(r,e){return r}function yge(r,e){return x.clamp(0,r,e-1)}function Iy(r,e,t,n,o,s,i,a,l,u,p){let c=i*n+a*o+l*s+u;return 0<=a&&a<e&&0<=l&&l<t?r[c]:p}function xge(r,e,t,n,o,s,i,a,l,u,p){let c=Math.round(a),m=Math.round(l);return Iy(r,e,t,n,o,s,i,c,m,u,p)}function Tge(r,e,t,n,o,s,i,a,l,u,p){let c=Math.floor(a),m=Math.floor(l),f=c+1,d=m+1,h=(d-l)*Iy(r,e,t,n,o,s,i,c,m,u,p)+(l-m)*Iy(r,e,t,n,o,s,i,c,d,u,p),g=(d-l)*Iy(r,e,t,n,o,s,i,f,m,u,p)+(l-m)*Iy(r,e,t,n,o,s,i,f,d,u,p);return(f-a)*h+(a-c)*g}function kge(r){let{inputs:e,attrs:t,backend:n}=r,{axis:o}=t,{x:s}=e;ie(s,"unique");let i=n.data.get(s.dataId).values,{outputValues:a,outputShape:l,indices:u}=rI(i,o,s.shape,s.dtype);return[n.makeTensorInfo(l,s.dtype,a),n.makeTensorInfo([u.length],"int32",u)]}var UV={kernelName:Pf,backendName:"cpu",kernelFunc:kge};function Ige(r){let{inputs:e,backend:t,attrs:n}=r,{value:o}=e,{axis:s}=n;s<0&&(s+=o.shape.length);let i=o.shape.length,a=o.shape[s],l=new Array(i-1),u=0;for(let f=0;f<i;f++)f!==s&&(l[u++]=o.shape[f]);let p=new Array(i).fill(0),c=o.shape.slice();c[s]=1;let m=new Array(a);for(let f=0;f<m.length;f++){p[s]=f;let d=Es({inputs:{x:o},backend:t,attrs:{begin:p,size:c}});m[f]=ut({inputs:{x:d},backend:t,attrs:{shape:l}}),t.disposeIntermediateTensorInfo(d)}return m}var jV={kernelName:xi,backendName:"cpu",kernelFunc:Ige};function vge(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,segmentIds:s}=e,{numSegments:i}=n;ie(o,"unsortedSegmentSum");let a=o.shape.length,l=s.shape.length,u=[],p=[],c=a-l,m=s;for(let d=0;d<c;++d){let h=zd({inputs:{input:m},backend:t,attrs:{dim:d+1}});m=h,p.push(h)}for(let d=0;d<i;++d){let h=x.createScalarValue(d,"int32"),g=t.makeTensorInfo([],"int32",h),b=SA({inputs:{a:g,b:m},backend:t}),y=Ns({inputs:{x:b},backend:t,attrs:{dtype:"float32"}}),T=um({inputs:{a:y,b:o},backend:t}),k=pu({inputs:{x:T},backend:t,attrs:{axis:0,keepDims:!1}});u.push(k),p.push(g),p.push(b),p.push(y),p.push(T),p.push(k)}let f=o0({inputs:u,backend:t,attrs:{axis:0}});return p.forEach(d=>t.disposeIntermediateTensorInfo(d)),f}var HV={kernelName:Hu,backendName:"cpu",kernelFunc:vge};var wge=[_W,WG,CW,SW,HG,NW,AW,DW,EW,MW,FW,RW,LW,$W,PW,OW,zW,GW,WW,wW,KW,VW,UW,jG,qG,jW,KG,HW,XW,ZW,JW,YW,eK,tK,QW,rK,nK,oK,sK,aK,iK,lK,uK,pK,cK,mK,dK,fK,xy,gK,bW,bK,XG,yK,YG,xK,ZG,TK,kK,IK,JG,vK,wK,_K,CK,SK,QG,eW,VG,NK,qW,AK,DK,EK,yW,tW,rW,MK,nW,FK,RK,LK,$K,PK,BK,oW,zK,GK,WK,KK,UK,OK,jK,HK,sW,qK,XK,JK,aW,iW,QK,eV,tV,lW,rV,sV,aV,aI,iV,xW,pW,lV,UG,uV,TW,kW,vW,pV,cV,mV,fV,dV,hV,gV,cW,bV,yV,xV,IW,TV,kV,IV,mW,YK,wV,_V,CV,SV,NV,AV,DV,EV,MV,FV,fW,RV,LV,$V,PV,BV,hW,hK,OV,zV,GV,WV,uW,KV,UV,jV,HV,nV];for(let r of wge)Bf(r);var eU={};Ge(eU,{assertNotComplex:()=>Za,bindCanvasToFramebuffer:()=>Rge,bindColorTextureToFramebuffer:()=>_y,bindTextureToProgramUniformSampler:()=>x0,bindTextureUnit:()=>ZV,bindVertexBufferToProgramAttribute:()=>lI,callAndCheck:()=>Fe,canBeRepresented:()=>i0,createFragmentShader:()=>u0,createFramebuffer:()=>g0,createProgram:()=>p0,createStaticIndexBuffer:()=>f0,createStaticVertexBuffer:()=>m0,createTexture:()=>d0,createVertexShader:()=>l0,getBatchDim:()=>mu,getExtensionOrThrow:()=>Gd,getFramebufferErrorMessage:()=>JV,getMaxTexturesInShader:()=>I0,getNumChannels:()=>Mge,getProgramUniformLocation:()=>y0,getProgramUniformLocationOrThrow:()=>b0,getRowsCols:()=>fu,getShapeAs3D:()=>Cy,getTextureShapeFromLogicalShape:()=>T0,getWebGLDisjointQueryTimerVersion:()=>v0,getWebGLErrorMessage:()=>YV,getWebGLMaxTextureSize:()=>k0,hasExtension:()=>_o,isCapableOfRenderingToFloatTexture:()=>w0,isDownloadFloatTextureEnabled:()=>_0,isReshapeFree:()=>xp,isWebGLFenceEnabled:()=>S0,isWebGLVersionEnabled:()=>fI,linkProgram:()=>c0,resetMaxTextureSize:()=>Lge,resetMaxTexturesInShader:()=>$ge,unbindColorTextureFromFramebuffer:()=>uI,unbindTextureUnit:()=>Fge,validateFramebuffer:()=>Wd,validateProgram:()=>wy,validateTextureSize:()=>h0});var pm={},s0={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function a0(r,e){pm[r]=e}function Qo(r){if(!(r in pm)){let t=Cge(r);if(t!==null)pm[r]=t;else return console.log("Could not get context for WebGL version",r),null}let e=pm[r];return e.isContextLost()?(delete pm[r],Qo(r)):(e.disable(e.DEPTH_TEST),e.disable(e.STENCIL_TEST),e.disable(e.BLEND),e.disable(e.DITHER),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SAMPLE_COVERAGE),e.enable(e.SCISSOR_TEST),e.enable(e.CULL_FACE),e.cullFace(e.BACK),pm[r])}function _ge(r){if(typeof OffscreenCanvas!="undefined"&&r===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 Cge(r){if(r!==1&&r!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let e=_ge(r);return e.addEventListener("webglcontextlost",t=>{t.preventDefault(),delete pm[r]},!1),r===1?e.getContext("webgl",s0)||e.getContext("experimental-webgl",s0):e.getContext("webgl2",s0)}var bp;(function(t){t[t.DENSE=0]="DENSE",t[t.SHARED_BATCH=1]="SHARED_BATCH"})(bp||(bp={}));var yn;(function(o){o[o.RENDER=0]="RENDER",o[o.UPLOAD=1]="UPLOAD",o[o.PIXELS=2]="PIXELS",o[o.DOWNLOAD=3]="DOWNLOAD"})(yn||(yn={}));var sn;(function(s){s[s.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",s[s.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",s[s.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",s[s.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",s[s.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"})(sn||(sn={}));function cm(r,e){return[e,r]}function qV(r,e){return r*e}function yp(r){let e=x.sizeFromShape(r),t=Math.ceil(e/4);return x.sizeToSquarishShape(t)}function Li(r,e){return[Math.max(1,Math.ceil(e/2)),Math.max(1,Math.ceil(r/2))]}function XV(r,e){let[t,n]=Li(r,e);return t*n*4}function vy(r,e){let t=r,n,o,s,i,a,l,u,p,c,m;return X().getNumber("WEBGL_VERSION")===2?(n=t.R32F,o=t.R16F,s=t.RGBA16F,i=t.RGBA32F,a=t.RED,u=4,p=1,c=t.HALF_FLOAT,m=t.FLOAT):(n=r.RGBA,o=r.RGBA,s=r.RGBA,i=t.RGBA,a=r.RGBA,u=4,p=4,c=e!=null?e.HALF_FLOAT_OES:null,m=r.FLOAT),l=r.RGBA,{internalFormatFloat:n,internalFormatHalfFloat:o,internalFormatPackedHalfFloat:s,internalFormatPackedFloat:i,textureFormatFloat:a,downloadTextureFormat:l,downloadUnpackNumChannels:u,defaultNumChannels:p,textureTypeHalfFloat:c,textureTypeFloat:m}}function Fe(r,e){let t=e();return X().getBool("DEBUG")&&Sge(r),t}function Sge(r){let e=r.getError();if(e!==r.NO_ERROR)throw new Error("WebGL Error: "+YV(r,e))}var Nge=596e-10,Age=65504;function i0(r){return!!(X().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||r===0||Nge<Math.abs(r)&&Math.abs(r)<Age)}function YV(r,e){switch(e){case r.NO_ERROR:return"NO_ERROR";case r.INVALID_ENUM:return"INVALID_ENUM";case r.INVALID_VALUE:return"INVALID_VALUE";case r.INVALID_OPERATION:return"INVALID_OPERATION";case r.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case r.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case r.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return`Unknown error code ${e}`}}function Gd(r,e){return cu(r,()=>r.getExtension(e),'Extension "'+e+'" not supported on this browser.')}function l0(r,e){let t=cu(r,()=>r.createShader(r.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(Fe(r,()=>r.shaderSource(t,e)),Fe(r,()=>r.compileShader(t)),r.getShaderParameter(t,r.COMPILE_STATUS)===!1)throw console.log(r.getShaderInfoLog(t)),new Error("Failed to compile vertex shader.");return t}function u0(r,e){let t=cu(r,()=>r.createShader(r.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(Fe(r,()=>r.shaderSource(t,e)),Fe(r,()=>r.compileShader(t)),r.getShaderParameter(t,r.COMPILE_STATUS)===!1)throw Ege(e,r.getShaderInfoLog(t)),new Error("Failed to compile fragment shader.");return t}var Dge=/ERROR: [0-9]+:([0-9]+):/g;function Ege(r,e){let t=Dge.exec(e);if(t==null){console.log(`Couldn't parse line number in error: ${e}`),console.log(r);return}let n=+t[1],o=r.split(`
|
|
`),s=o.length.toString().length+2,i=o.map((c,m)=>x.rightPad((m+1).toString(),s)+c),a=0;for(let c=0;c<i.length;c++)a=Math.max(i[c].length,a);let l=i.slice(0,n-1),u=i.slice(n-1,n),p=i.slice(n);console.log(l.join(`
|
|
`)),console.log(e.split(`
|
|
`)[0]),console.log(`%c ${x.rightPad(u[0],a)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(p.join(`
|
|
`))}function p0(r){return cu(r,()=>r.createProgram(),"Unable to create WebGLProgram.")}function c0(r,e){if(Fe(r,()=>r.linkProgram(e)),r.getProgramParameter(e,r.LINK_STATUS)===!1)throw console.log(r.getProgramInfoLog(e)),new Error("Failed to link vertex and fragment shaders.")}function wy(r,e){if(Fe(r,()=>r.validateProgram(e)),r.getProgramParameter(e,r.VALIDATE_STATUS)===!1)throw console.log(r.getProgramInfoLog(e)),new Error("Shader program validation failed.")}function m0(r,e){let t=cu(r,()=>r.createBuffer(),"Unable to create WebGLBuffer");return Fe(r,()=>r.bindBuffer(r.ARRAY_BUFFER,t)),Fe(r,()=>r.bufferData(r.ARRAY_BUFFER,e,r.STATIC_DRAW)),t}function f0(r,e){let t=cu(r,()=>r.createBuffer(),"Unable to create WebGLBuffer");return Fe(r,()=>r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,t)),Fe(r,()=>r.bufferData(r.ELEMENT_ARRAY_BUFFER,e,r.STATIC_DRAW)),t}function Mge(){return X().getNumber("WEBGL_VERSION")===2?1:4}function d0(r){return cu(r,()=>r.createTexture(),"Unable to create WebGLTexture.")}function h0(r,e){let t=X().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(r<=0||e<=0){let n=`[${r}x${e}]`;throw new Error("Requested texture size "+n+" is invalid.")}if(r>t||e>t){let n=`[${r}x${e}]`,o=`[${t}x${t}]`;throw new Error("Requested texture size "+n+" greater than WebGL maximum on this browser / GPU "+o+".")}}function g0(r){return cu(r,()=>r.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function lI(r,e,t,n,o,s,i){let a=r.getAttribLocation(e,t);return a===-1?!1:(Fe(r,()=>r.bindBuffer(r.ARRAY_BUFFER,n)),Fe(r,()=>r.vertexAttribPointer(a,o,r.FLOAT,!1,s,i)),Fe(r,()=>r.enableVertexAttribArray(a)),!0)}function ZV(r,e,t){QV(r,t),Fe(r,()=>r.activeTexture(r.TEXTURE0+t)),Fe(r,()=>r.bindTexture(r.TEXTURE_2D,e))}function Fge(r,e){QV(r,e),Fe(r,()=>r.activeTexture(r.TEXTURE0+e)),Fe(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function b0(r,e,t){return cu(r,()=>r.getUniformLocation(e,t),'uniform "'+t+'" not present in program.')}function y0(r,e,t){return r.getUniformLocation(e,t)}function x0(r,e,t,n){Fe(r,()=>ZV(r,e,n)),Fe(r,()=>r.uniform1i(t,n))}function Rge(r){Fe(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,null)),Fe(r,()=>r.viewport(0,0,r.canvas.width,r.canvas.height)),Fe(r,()=>r.scissor(0,0,r.canvas.width,r.canvas.height))}function _y(r,e,t){Fe(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,t)),Fe(r,()=>r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0))}function uI(r,e){Fe(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,e)),Fe(r,()=>r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,null,0))}function Wd(r){let e=r.checkFramebufferStatus(r.FRAMEBUFFER);if(e!==r.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+JV(r,e))}function JV(r,e){switch(e){case r.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case r.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case r.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${e}`}}function cu(r,e,t){let n=Fe(r,()=>e());if(n==null)throw new Error(t);return n}function QV(r,e){let t=r.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,n=e+r.TEXTURE0;if(n<r.TEXTURE0||n>t){let o=`[gl.TEXTURE0, gl.TEXTURE${t}]`;throw new Error(`textureUnit must be in ${o}.`)}}function mu(r,e=2){return x.sizeFromShape(r.slice(0,r.length-e))}function fu(r){if(r.length===0)throw Error("Cannot get rows and columns of an empty shape array.");return[r.length>1?r[r.length-2]:1,r[r.length-1]]}function Cy(r){let e=[1,1,1];return r.length===0||r.length===1&&r[0]===1||(e=[mu(r),...fu(r)]),e}function T0(r,e=!1){let t=X().getNumber("WEBGL_MAX_TEXTURE_SIZE");e&&(t=t*2,r=r.map((o,s)=>s>=r.length-2?x.nearestLargerEven(r[s]):r[s]),r.length===1&&(r=[2,r[0]])),r.length!==2&&(r=x.squeezeShape(r).newShape);let n=x.sizeFromShape(r);if(r.length<=1&&n<=t)return[1,n];if(r.length===2&&r[0]<=t&&r[1]<=t)return r;if(r.length===3&&r[0]*r[1]<=t&&r[2]<=t)return[r[0]*r[1],r[2]];if(r.length===3&&r[0]<=t&&r[1]*r[2]<=t)return[r[0],r[1]*r[2]];if(r.length===4&&r[0]*r[1]*r[2]<=t&&r[3]<=t)return[r[0]*r[1]*r[2],r[3]];if(r.length===4&&r[0]<=t&&r[1]*r[2]*r[3]<=t)return[r[0],r[1]*r[2]*r[3]];if(e){let o=mu(r),s=2,i=2;return r.length&&([s,i]=fu(r)),n=o*(s/2)*(i/2),x.sizeToSquarishShape(n).map(a=>a*2)}return x.sizeToSquarishShape(n)}function pI(r){return r%2==0}function xp(r,e){if(r=r.slice(-2),e=e.slice(-2),x.arraysEqual(r,e)||!r.length||!e.length||r[0]===0||r[1]===0||e[0]===0||e[1]===0)return!0;if(r.length!==e.length){let t=r.slice(-1)[0],n=e.slice(-1)[0];if(t===n||pI(t)&&pI(n)&&(r[0]===1||e[0]===1))return!0}return r[1]===e[1]&&pI(r[0])&&pI(e[0])}var cI,mI;function k0(r){if(cI==null){let e=Qo(r);cI=e.getParameter(e.MAX_TEXTURE_SIZE)}return cI}function Lge(){cI=null}function $ge(){mI=null}function I0(r){if(mI==null){let e=Qo(r);mI=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,mI)}function v0(r){if(r===0)return 0;let e,t=Qo(r);return _o(t,"EXT_disjoint_timer_query_webgl2")&&r===2?e=2:_o(t,"EXT_disjoint_timer_query")?e=1:e=0,e}function _o(r,e){return r.getExtension(e)!=null}function fI(r){try{if(Qo(r)!=null)return!0}catch(e){return console.log("Error when getting WebGL context: ",e),!1}return!1}function w0(r){if(r===0)return!1;let e=Qo(r);if(r===1){if(!_o(e,"OES_texture_float"))return!1}else if(!_o(e,"EXT_color_buffer_float"))return!1;return C0(e)}function _0(r){if(r===0)return!1;let e=Qo(r);if(r===1){if(!_o(e,"OES_texture_float")||!_o(e,"WEBGL_color_buffer_float"))return!1}else{if(_o(e,"EXT_color_buffer_float"))return C0(e);let n="EXT_color_buffer_half_float";if(_o(e,n)){let o=e.getExtension(n);return Pge(e,o)}return!1}return C0(e)}function C0(r){let e=vy(r),t=r.createTexture();r.bindTexture(r.TEXTURE_2D,t);let n=1,o=1;r.texImage2D(r.TEXTURE_2D,0,e.internalFormatFloat,n,o,0,e.textureFormatFloat,e.textureTypeFloat,null);let s=r.createFramebuffer();r.bindFramebuffer(r.FRAMEBUFFER,s),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,t,0);let i=r.checkFramebufferStatus(r.FRAMEBUFFER)===r.FRAMEBUFFER_COMPLETE;return r.bindTexture(r.TEXTURE_2D,null),r.bindFramebuffer(r.FRAMEBUFFER,null),r.deleteTexture(t),r.deleteFramebuffer(s),i}function Pge(r,e){let t=vy(r,e),n=r.createTexture();r.bindTexture(r.TEXTURE_2D,n);let o=1,s=1;r.texImage2D(r.TEXTURE_2D,0,t.internalFormatHalfFloat,o,s,0,t.textureFormatFloat,t.textureTypeHalfFloat,null);let i=r.createFramebuffer();r.bindFramebuffer(r.FRAMEBUFFER,i),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,n,0);let a=r.checkFramebufferStatus(r.FRAMEBUFFER)===r.FRAMEBUFFER_COMPLETE;return r.bindTexture(r.TEXTURE_2D,null),r.bindFramebuffer(r.FRAMEBUFFER,null),r.deleteTexture(n),r.deleteFramebuffer(i),a}function S0(r){return r!==2?!1:Qo(r).fenceSync!=null}function Za(r,e){Array.isArray(r)||(r=[r]),r.forEach(t=>{t!=null&&x.assert(t.dtype!=="complex64",()=>`${e} does not support complex64 tensors in the WebGL backend.`)})}var Ue=X();Ue.registerFlag("HAS_WEBGL",()=>Ue.getNumber("WEBGL_VERSION")>0);Ue.registerFlag("WEBGL_VERSION",()=>fI(2)?2:fI(1)?1:0);Ue.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);Ue.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>Ue.get("WEBGL_VERSION")===2);Ue.registerFlag("WEBGL_CPU_FORWARD",()=>!0);Ue.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);Ue.registerFlag("WEBGL_PACK",()=>Ue.getBool("HAS_WEBGL"));Ue.registerFlag("WEBGL_PACK_NORMALIZATION",()=>Ue.getBool("WEBGL_PACK"));Ue.registerFlag("WEBGL_PACK_CLIP",()=>Ue.getBool("WEBGL_PACK"));Ue.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>Ue.getBool("WEBGL_PACK"));Ue.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>Ue.getBool("WEBGL_PACK"));Ue.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>Ue.getBool("WEBGL_PACK"));Ue.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>Ue.getBool("WEBGL_PACK"));Ue.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>Ue.getBool("WEBGL_PACK"));Ue.registerFlag("WEBGL_PACK_REDUCE",()=>Ue.getBool("WEBGL_PACK"));Ue.registerFlag("WEBGL_LAZILY_UNPACK",()=>Ue.getBool("WEBGL_PACK"));Ue.registerFlag("WEBGL_CONV_IM2COL",()=>Ue.getBool("WEBGL_PACK"));Ue.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>k0(Ue.getNumber("WEBGL_VERSION")));Ue.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>I0(Ue.getNumber("WEBGL_VERSION")));Ue.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let r=Ue.getNumber("WEBGL_VERSION");return r===0?0:v0(r)});Ue.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>Ue.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!yc.isMobile());Ue.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>w0(Ue.getNumber("WEBGL_VERSION")));Ue.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>Ue.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:Ue.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));Ue.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>_0(Ue.getNumber("WEBGL_VERSION")));Ue.registerFlag("WEBGL_FENCE_API_ENABLED",()=>S0(Ue.getNumber("WEBGL_VERSION")));Ue.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>Ue.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);Ue.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",()=>-1,r=>{if(r<0&&r!==-1)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${r}.`)});Ue.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>yc.isMobile()&&Ue.getBool("IS_CHROME")?1:-1,r=>{if(r<0&&r!==-1)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${r}.`)});Ue.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128);function lr(){let r,e,t,n,o,s,i,a,l,u;return X().getNumber("WEBGL_VERSION")===2?(r="#version 300 es",e="in",t="out",n="in",o="texture",s="outputColor",i="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="",u=`
|
|
#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)));
|
|
}
|
|
`):(r="",e="attribute",t="varying",n="varying",o="texture2D",s="gl_FragColor",i="",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));
|
|
}
|
|
`,u=`
|
|
int round(float value) {
|
|
return int(floor(value + 0.5));
|
|
}
|
|
|
|
ivec4 round(vec4 value) {
|
|
return ivec4(floor(value + vec4(0.5)));
|
|
}
|
|
`),{version:r,attribute:e,varyingVs:t,varyingFs:n,texture2D:o,output:s,defineOutput:i,defineSpecialNaN:a,defineSpecialInf:l,defineRound:u}}function Ja(r,e,t="index"){let n=x.computeStrides(e);return n.map((o,s)=>{let i=`int ${r[s]} = ${t} / ${o}`,a=s===n.length-1?`int ${r[s+1]} = ${t} - ${r[s]} * ${o}`:`index -= ${r[s]} * ${o}`;return`${i}; ${a};`}).join("")}function Kd(r){let e=x.computeStrides(r).map(t=>t.toString());return`
|
|
int getFlatIndex(ivec3 coords) {
|
|
return coords.x * ${e[0]} + coords.y * ${e[1]} + coords.z;
|
|
}
|
|
`}var dI=`
|
|
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;
|
|
}
|
|
`;var N0=class{constructor(e){this.variableNames=["A"];this.packedInputs=!1;this.packedOutput=!0;this.outPackingScheme=bp.DENSE;let t=yp(e),n=lr();this.outputShape=e,this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${Ja(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = 4 * (resTexRC.x * ${t[1]} + resTexRC.y);
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
for (int i=0; i<4; i++) {
|
|
int flatIndex = index + i;
|
|
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
|
|
result[i] = getA(rc.x, rc.y, rc.z);
|
|
}
|
|
|
|
${n.output} = result;
|
|
}
|
|
`}};var A0=class{constructor(e){this.variableNames=["A"];this.packedInputs=!0;this.packedOutput=!0;this.outPackingScheme=bp.DENSE;let t=yp(e),n=lr();this.outputShape=e,this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${Ja(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = 4 * (resTexRC.x * ${t[1]} + resTexRC.y);
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
for (int i=0; i<4; i++) {
|
|
int flatIndex = index + i;
|
|
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
|
|
result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));
|
|
}
|
|
|
|
${n.output} = result;
|
|
}
|
|
`}};var D0=class{constructor(e){this.variableNames=["A"];this.outTexUsage=yn.DOWNLOAD;let t=lr();this.outputShape=e,this.userCode=`
|
|
${dI}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}};var E0=class{constructor(e){this.variableNames=["A"];this.packedInputs=!0;this.packedOutput=!1;this.outTexUsage=yn.DOWNLOAD;let t=lr();this.outputShape=e,this.userCode=`
|
|
${dI}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}};var M0=class{constructor(e,t,n=!1){this.variableNames=["A"];let o=lr(),[s,i]=t;this.outputShape=e;let a="result";n&&(a="floor(result * 255. + 0.5)"),this.userCode=`
|
|
${Kd(e)}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
|
|
int flatIndex = getFlatIndex(coords);
|
|
int offset = imod(flatIndex, 4);
|
|
|
|
flatIndex = idiv(flatIndex, 4, 1.);
|
|
|
|
int r = flatIndex / ${i};
|
|
int c = imod(flatIndex, ${i});
|
|
vec2 uv = (vec2(c, r) + halfCR) / vec2(${i}.0, ${s}.0);
|
|
vec4 values = ${o.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];
|
|
}
|
|
|
|
${o.output} = vec4(${a}, 0., 0., 0.);
|
|
}
|
|
`}};var F0=class{constructor(e,t,n=!1){this.variableNames=["A"];this.packedInputs=!1;this.packedOutput=!0;let o=lr(),[s,i]=t;this.outputShape=e;let a="",l="result";n&&(l="floor(result * 255. + 0.5)");for(let u=0;u<=1;u++)for(let p=0;p<=1;p++){let c=u*2+p;a+=`
|
|
localCoords = coords;
|
|
if(localCoords[2] + ${p} < ${e[2]}) {
|
|
localCoords[2] += ${p};
|
|
if(localCoords[1] + ${u} < ${e[1]}) {
|
|
localCoords[1] += ${u};
|
|
|
|
flatIndex = getFlatIndex(localCoords);
|
|
offset = imod(flatIndex, 4);
|
|
|
|
flatIndex = idiv(flatIndex, 4, 1.);
|
|
|
|
r = flatIndex / ${i};
|
|
c = imod(flatIndex, ${i});
|
|
uv = (vec2(c, r) + halfCR) / vec2(${i}.0, ${s}.0);
|
|
values = ${o.texture2D}(A, uv);
|
|
|
|
if(offset == 0) {
|
|
result[${c}] = values[0];
|
|
} else if(offset == 1) {
|
|
result[${c}] = values[1];
|
|
} else if(offset == 2) {
|
|
result[${c}] = values[2];
|
|
} else {
|
|
result[${c}] = values[3];
|
|
}
|
|
}
|
|
}
|
|
`}this.userCode=`
|
|
${Kd(e)}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
int flatIndex, r, c, offset;
|
|
ivec3 localCoords;
|
|
vec2 uv;
|
|
vec4 values;
|
|
|
|
${a}
|
|
|
|
${o.output} = ${l};
|
|
}
|
|
`}};var tU={};Ge(tU,{bindVertexProgramAttributeStreams:()=>W0,createBufferFromOutputTexture:()=>U0,createFloat16MatrixTexture:()=>B0,createFloat16PackedMatrixTexture:()=>G0,createFloat32MatrixTexture:()=>P0,createIndexBuffer:()=>$0,createPackedMatrixTexture:()=>z0,createUnsignedBytesMatrixTexture:()=>O0,createVertexBuffer:()=>L0,createVertexShader:()=>R0,downloadByteEncodedFloatMatrixFromOutputTexture:()=>H0,downloadFloat32MatrixFromBuffer:()=>j0,downloadMatrixFromPackedOutputTexture:()=>X0,downloadPackedMatrixFromBuffer:()=>q0,getInternalFormatForFloat16MatrixTexture:()=>gI,getInternalFormatForFloat16PackedMatrixTexture:()=>xI,getInternalFormatForFloat32MatrixTexture:()=>hI,getInternalFormatForPackedMatrixTexture:()=>yI,getInternalFormatForUnsignedBytesMatrixTexture:()=>bI,uploadDenseMatrixToTexture:()=>K0,uploadPixelDataToTexture:()=>V0});function R0(r){let e=lr(),t=`${e.version}
|
|
precision highp float;
|
|
${e.attribute} vec3 clipSpacePos;
|
|
${e.attribute} vec2 uv;
|
|
${e.varyingVs} vec2 resultUV;
|
|
|
|
void main() {
|
|
gl_Position = vec4(clipSpacePos, 1);
|
|
resultUV = uv;
|
|
}`;return l0(r,t)}function L0(r){let e=new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]);return m0(r,e)}function $0(r){let e=new Uint16Array([0,1,2,2,1,3]);return f0(r,e)}function Sy(r,e,t,n,o,s){h0(e,t);let i=d0(r),a=r.TEXTURE_2D;return Fe(r,()=>r.bindTexture(a,i)),Fe(r,()=>r.texParameteri(a,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE)),Fe(r,()=>r.texParameteri(a,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE)),Fe(r,()=>r.texParameteri(a,r.TEXTURE_MIN_FILTER,r.NEAREST)),Fe(r,()=>r.texParameteri(a,r.TEXTURE_MAG_FILTER,r.NEAREST)),Fe(r,()=>r.texImage2D(a,0,n,e,t,0,o,s,null)),Fe(r,()=>r.bindTexture(r.TEXTURE_2D,null)),i}function hI(r){return r.internalFormatFloat}function P0(r,e,t,n){let[o,s]=cm(e,t);return Sy(r,o,s,hI(n),n.textureFormatFloat,r.FLOAT)}function gI(r){return r.internalFormatHalfFloat}function B0(r,e,t,n){let[o,s]=cm(e,t);return Sy(r,o,s,gI(n),n.textureFormatFloat,n.textureTypeHalfFloat)}function bI(r){return r.downloadTextureFormat}function O0(r,e,t,n){let[o,s]=cm(e,t);return Sy(r,o,s,bI(n),r.RGBA,r.UNSIGNED_BYTE)}function yI(r){return r.internalFormatPackedFloat}function z0(r,e,t,n){let[o,s]=Li(e,t);return Sy(r,o,s,yI(n),r.RGBA,r.FLOAT)}function xI(r){return r.internalFormatPackedHalfFloat}function G0(r,e,t,n){let[o,s]=Li(e,t);return Sy(r,o,s,xI(n),r.RGBA,n.textureTypeHalfFloat)}function W0(r,e,t){let n=0,o=3*4,s=3*4+2*4;return Fe(r,()=>r.bindBuffer(r.ARRAY_BUFFER,t)),lI(r,e,"clipSpacePos",t,3,s,n)&&lI(r,e,"uv",t,2,s,o)}function K0(r,e,t,n,o,s){Fe(r,()=>r.bindTexture(r.TEXTURE_2D,e));let i,a,l;o instanceof Uint8Array?(i=new Uint8Array(t*n*4),a=r.UNSIGNED_BYTE,l=r.RGBA):(i=new Float32Array(t*n*4),a=r.FLOAT,l=s.internalFormatPackedFloat),i.set(o),Fe(r,()=>r.texImage2D(r.TEXTURE_2D,0,l,t,n,0,r.RGBA,a,i)),Fe(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function V0(r,e,t){Fe(r,()=>r.bindTexture(r.TEXTURE_2D,e)),t.data instanceof Uint8Array?Fe(r,()=>r.texImage2D(r.TEXTURE_2D,0,r.RGBA,t.width,t.height,0,r.RGBA,r.UNSIGNED_BYTE,t.data)):Fe(r,()=>r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,t)),Fe(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function U0(r,e,t,n){let o=r.createBuffer();Fe(r,()=>r.bindBuffer(r.PIXEL_PACK_BUFFER,o));let a=4*4*e*t;return Fe(r,()=>r.bufferData(r.PIXEL_PACK_BUFFER,a,r.STREAM_READ)),Fe(r,()=>r.readPixels(0,0,t,e,r.RGBA,r.FLOAT,0)),Fe(r,()=>r.bindBuffer(r.PIXEL_PACK_BUFFER,null)),o}function j0(r,e,t){let n=r,o=new Float32Array(t);return n.bindBuffer(n.PIXEL_PACK_BUFFER,e),n.getBufferSubData(n.PIXEL_PACK_BUFFER,0,o),n.bindBuffer(n.PIXEL_PACK_BUFFER,null),o}function H0(r,e,t,n){let[o,s]=cm(e,t),i=4,a=new Uint8Array(qV(e*t,i));return Fe(r,()=>r.readPixels(0,0,o,s,n.downloadTextureFormat,r.UNSIGNED_BYTE,a)),new Float32Array(a.buffer)}function q0(r,e,t,n,o,s,i,a){let l=r,u=new Float32Array(XV(s,i));return l.bindBuffer(l.PIXEL_PACK_BUFFER,e),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,u),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),u}function X0(r,e,t){let n=new Float32Array(e*t*4);return Fe(r,()=>r.readPixels(0,0,t,e,r.RGBA,r.FLOAT,n)),n}var TI=class{constructor(e){this.outputTexture=null;this.program=null;this.disposed=!1;this.vertexAttrsAreBound=!1;this.itemsToPoll=[];let t=X().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,a0(t,e)):this.gl=Qo(t);let n="WEBGL_color_buffer_float",o="EXT_color_buffer_half_float";if(X().getNumber("WEBGL_VERSION")===1){let s="OES_texture_float",i="OES_texture_half_float";if(this.textureFloatExtension=Gd(this.gl,s),_o(this.gl,i))this.textureHalfFloatExtension=Gd(this.gl,i);else if(X().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),_o(this.gl,o))this.colorBufferHalfFloatExtension=Gd(this.gl,o);else if(X().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",_o(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else if(_o(this.gl,o))this.colorBufferHalfFloatExtension=this.gl.getExtension(o);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=L0(this.gl),this.indexBuffer=$0(this.gl),this.framebuffer=g0(this.gl),this.textureConfig=vy(this.gl,this.textureHalfFloatExtension)}get debug(){return X().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.");let e=this.gl;Fe(e,()=>e.finish()),Fe(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),Fe(e,()=>e.deleteFramebuffer(this.framebuffer)),Fe(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),Fe(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),Fe(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),P0(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),B0(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),O0(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),V0(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,o){this.throwIfDisposed(),K0(this.gl,e,t,n,o,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),G0(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),z0(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(uI(this.gl,this.framebuffer),this.outputTexture=null),Fe(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,()=>H0(this.gl,t,n,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,n,o,s,i){return q0(this.gl,e,t,n,o,s,i,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return j0(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);let o=U0(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),o}createAndWaitForFence(){let e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(X().getBool("WEBGL_FENCE_API_ENABLED")){let o=e,s=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{let i=o.clientWaitSync(s,0,0);return i===o.ALREADY_SIGNALED||i===o.CONDITION_SATISFIED},t=s}else X().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,X().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,()=>X0(this.gl,t,n))}createProgram(e){this.throwIfDisposed();let t=this.gl,n=u0(t,e);this.vertexShader==null&&(this.vertexShader=R0(t));let o=p0(t);return Fe(t,()=>t.attachShader(o,this.vertexShader)),Fe(t,()=>t.attachShader(o,n)),c0(t,o),this.debug&&wy(t,o),this.vertexAttrsAreBound||(this.setProgram(o),this.vertexAttrsAreBound=W0(t,this.program,this.vertexBuffer)),o}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&Fe(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&wy(this.gl,this.program),Fe(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?b0(this.gl,e,t):y0(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),Fe(this.gl,()=>this.gl.getAttribLocation(e,t))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),x0(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();let[o,s]=Li(t,n);this.setOutputMatrixTextureDriver(e,o,s)}setOutputMatrixWriteRegion(e,t,n,o){this.setOutputMatrixWriteRegionDriver(n,e,o,t)}setOutputPackedMatrixWriteRegion(e,t,n,o){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&wy(this.gl,this.program),Wd(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();let e=this.gl;this.debug&&this.debugValidate(),Fe(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),Fe(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=Gd(this.gl,X().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(X().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let n=this.gl,o=this.getQueryTimerExtensionWebGL2(),s=n.createQuery();return n.beginQuery(o.TIME_ELAPSED_EXT,s),s}let e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(X().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let t=this.gl,n=this.getQueryTimerExtensionWebGL2();t.endQuery(n.TIME_ELAPSED_EXT);return}let e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await x.repeatedTry(()=>this.disposed||this.isQueryAvailable(e,X().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,X().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(t===0)return null;if(t===2){let n=this.gl;return n.getQueryParameter(e,n.QUERY_RESULT)/1e6}else{let n=this.getQueryTimerExtensionWebGL1();return n.getQueryObjectEXT(e,n.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(t===0)return!0;if(t===2){let n=this.gl,o=this.getQueryTimerExtensionWebGL2(),s=n.getQueryParameter(e,n.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(o.GPU_DISJOINT_EXT)),s&&!this.disjoint}else{let n=this.getQueryTimerExtensionWebGL1(),o=n.getQueryObjectEXT(e,n.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),o&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){let e=Bge(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=e;++t){let{resolveFn:n}=this.itemsToPoll[t];n()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),!(this.itemsToPoll.length>1)&&x.repeatedTry(()=>(this.pollItems(),this.itemsToPoll.length===0))}bindTextureToFrameBuffer(e){this.throwIfDisposed(),_y(this.gl,e,this.framebuffer),this.debug&&Wd(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(_y(this.gl,this.outputTexture,this.framebuffer),this.debug&&Wd(this.gl)):uI(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);let n=t();return this.unbindTextureToFrameBuffer(),n}setOutputMatrixTextureDriver(e,t,n){this.throwIfDisposed();let o=this.gl;_y(o,e,this.framebuffer),this.debug&&Wd(o),this.outputTexture=e,Fe(o,()=>o.viewport(0,0,t,n)),Fe(o,()=>o.scissor(0,0,t,n))}setOutputMatrixWriteRegionDriver(e,t,n,o){this.throwIfDisposed(),Fe(this.gl,()=>this.gl.scissor(e,t,n,o))}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 Bge(r){let e=0;for(;e<r.length&&r[e]();++e);return e-1}var{getBroadcastDims:rU}=C;function nU(r,e,t,n){let o=[];r.forEach(d=>{let h=x.sizeFromShape(d.shapeInfo.logicalShape);d.shapeInfo.isUniform?o.push(`uniform float ${d.name}${h>1?`[${h}]`:""};`):(o.push(`uniform sampler2D ${d.name};`),o.push(`uniform int offset${d.name};`))});let s=o.join(`
|
|
`),i=r.map(d=>Oge(d,e,n)).join(`
|
|
`),a=e.texShape,l=lr(),u=Wge(l),p,c,m=Uge(l);return e.isPacked?(p=zge(e.logicalShape,a),c=Vge(l)):(p=Gge(e.logicalShape,a),c=Kge(l)),n&&(m+=Xge),[m,u,c,s,p,i,t].join(`
|
|
`)}function Vd(r){let e=r.shapeInfo.logicalShape;switch(e.length){case 0:return ibe(r);case 1:return ube(r);case 2:return cbe(r);case 3:return fbe(r);case 4:return hbe(r);case 5:return gbe(r);case 6:return bbe(r);default:throw new Error(`${e.length}-D input sampling is not yet supported`)}}function oU(r){switch(r.shapeInfo.logicalShape.length){case 0:return abe(r);case 1:return lbe(r);case 2:return pbe(r);case 3:return mbe(r);default:return dbe(r)}}function Oge(r,e,t=!1){let n="";t?n+=oU(r):n+=Vd(r);let o=r.shapeInfo.logicalShape,s=e.logicalShape;return o.length<=s.length&&(t?n+=ybe(r,e):n+=xbe(r,e)),n}function zge(r,e){switch(r.length){case 0:return sU();case 1:return Yge(r,e);case 2:return obe(r,e);case 3:return Jge(r,e);default:return ebe(r,e)}}function Gge(r,e){switch(r.length){case 0:return sU();case 1:return Zge(r,e);case 2:return sbe(r,e);case 3:return Qge(r,e);case 4:return tbe(r,e);case 5:return rbe(r,e);case 6:return nbe(r,e);default:throw new Error(`${r.length}-D output sampling is not yet supported`)}}function Wge(r){return`
|
|
float sampleTexture(sampler2D textureSampler, vec2 uv) {
|
|
return ${r.texture2D}(textureSampler, uv).r;
|
|
}
|
|
`}function Kge(r){return`
|
|
void setOutput(float val) {
|
|
${r.output} = vec4(val, 0, 0, 0);
|
|
}
|
|
`}function Vge(r){return`
|
|
void setOutput(vec4 val) {
|
|
${r.output} = val;
|
|
}
|
|
`}function Uge(r){return`${r.version}
|
|
precision highp float;
|
|
precision highp int;
|
|
precision highp sampler2D;
|
|
${r.varyingFs} vec2 resultUV;
|
|
${r.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;
|
|
${r.defineSpecialNaN}
|
|
${r.defineSpecialInf}
|
|
${r.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);
|
|
}
|
|
|
|
${jge}
|
|
${Hge}
|
|
${qge}
|
|
`}var jge=`
|
|
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);
|
|
}
|
|
`,Hge=`
|
|
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);
|
|
}
|
|
`,qge=`
|
|
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);
|
|
}
|
|
`,Xge=`
|
|
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 sU(){return`
|
|
int getOutputCoords() {
|
|
return 0;
|
|
}
|
|
`}function Yge(r,e){let t=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];return t[0]===1?`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.x * ${t[1]}.0);
|
|
}
|
|
`:t[1]===1?`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.y * ${t[0]}.0);
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
return 2 * (resTexRC.x * ${t[1]} + resTexRC.y);
|
|
}
|
|
`}function Zge(r,e){return e[0]===1?`
|
|
int getOutputCoords() {
|
|
return int(resultUV.x * ${e[1]}.0);
|
|
}
|
|
`:e[1]===1?`
|
|
int getOutputCoords() {
|
|
return int(resultUV.y * ${e[0]}.0);
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${e[0]}, ${e[1]}));
|
|
return resTexRC.x * ${e[1]} + resTexRC.y;
|
|
}
|
|
`}function Jge(r,e){let t=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],n=Math.ceil(r[2]/2),o=n*Math.ceil(r[1]/2);return`
|
|
ivec3 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
|
|
int b = index / ${o};
|
|
index -= b * ${o};
|
|
|
|
int r = 2 * (index / ${n});
|
|
int c = imod(index, ${n}) * 2;
|
|
|
|
return ivec3(b, r, c);
|
|
}
|
|
`}function Qge(r,e){let t=Ja(["r","c","d"],r);return`
|
|
ivec3 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${e[0]}, ${e[1]}));
|
|
int index = resTexRC.x * ${e[1]} + resTexRC.y;
|
|
${t}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}function ebe(r,e){let t=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],n=Math.ceil(r[r.length-1]/2),o=n*Math.ceil(r[r.length-2]/2),s=o,i="",a="b, r, c";for(let l=2;l<r.length-1;l++)s*=r[r.length-l-1],i=`
|
|
int b${l} = index / ${s};
|
|
index -= b${l} * ${s};
|
|
`+i,a=`b${l}, `+a;return`
|
|
ivec${r.length} getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
|
|
${i}
|
|
|
|
int b = index / ${o};
|
|
index -= b * ${o};
|
|
|
|
int r = 2 * (index / ${n});
|
|
int c = imod(index, ${n}) * 2;
|
|
|
|
return ivec${r.length}(${a});
|
|
}
|
|
`}function tbe(r,e){let t=Ja(["r","c","d","d2"],r);return`
|
|
ivec4 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${e[0]}, ${e[1]}));
|
|
int index = resTexRC.x * ${e[1]} + resTexRC.y;
|
|
${t}
|
|
return ivec4(r, c, d, d2);
|
|
}
|
|
`}function rbe(r,e){let t=Ja(["r","c","d","d2","d3"],r);return`
|
|
ivec5 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx * vec2(${e[0]},
|
|
${e[1]}));
|
|
|
|
int index = resTexRC.x * ${e[1]} + resTexRC.y;
|
|
|
|
${t}
|
|
|
|
ivec5 outShape = ivec5(r, c, d, d2, d3);
|
|
return outShape;
|
|
}
|
|
`}function nbe(r,e){let t=Ja(["r","c","d","d2","d3","d4"],r);return`
|
|
ivec6 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${e[0]}, ${e[1]}));
|
|
int index = resTexRC.x * ${e[1]} + resTexRC.y;
|
|
|
|
${t}
|
|
|
|
ivec6 result = ivec6(r, c, d, d2, d3, d4);
|
|
return result;
|
|
}
|
|
`}function obe(r,e){let t=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];if(x.arraysEqual(r,e))return`
|
|
ivec2 getOutputCoords() {
|
|
return 2 * ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));
|
|
}
|
|
`;let n=Math.ceil(r[1]/2);return`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
int r = 2 * (index / ${n});
|
|
int c = imod(index, ${n}) * 2;
|
|
|
|
return ivec2(r, c);
|
|
}
|
|
`}function sbe(r,e){return x.arraysEqual(r,e)?`
|
|
ivec2 getOutputCoords() {
|
|
return ivec2(resultUV.yx * vec2(${e[0]}, ${e[1]}));
|
|
}
|
|
`:r[1]===1?`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${e[0]}, ${e[1]}));
|
|
int index = resTexRC.x * ${e[1]} + resTexRC.y;
|
|
return ivec2(index, 0);
|
|
}
|
|
`:r[0]===1?`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${e[0]}, ${e[1]}));
|
|
int index = resTexRC.x * ${e[1]} + resTexRC.y;
|
|
return ivec2(0, index);
|
|
}
|
|
`:`
|
|
ivec2 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${e[0]}, ${e[1]}));
|
|
int index = resTexRC.x * ${e[1]} + resTexRC.y;
|
|
int r = index / ${r[1]};
|
|
int c = index - r * ${r[1]};
|
|
return ivec2(r, c);
|
|
}
|
|
`}function mm(r){return`offset${r}`}function abe(r){let e=r.name,t="get"+e.charAt(0).toUpperCase()+e.slice(1),n=lr();return`
|
|
vec4 ${t}() {
|
|
return ${n.texture2D}(${e}, halfCR);
|
|
}
|
|
`}function ibe(r){let e=r.name,t="get"+e.charAt(0).toUpperCase()+e.slice(1);if(r.shapeInfo.isUniform)return`float ${t}() {return ${e};}`;let[n,o]=r.shapeInfo.texShape;if(n===1&&o===1)return`
|
|
float ${t}() {
|
|
return sampleTexture(${e}, halfCR);
|
|
}
|
|
`;let[s,i]=r.shapeInfo.texShape,a=mm(e);return`
|
|
float ${t}() {
|
|
vec2 uv = uvFromFlat(${s}, ${i}, ${a});
|
|
return sampleTexture(${e}, uv);
|
|
}
|
|
`}function lbe(r){let e=r.name,t="get"+e.charAt(0).toUpperCase()+e.slice(1),n=r.shapeInfo.texShape,o=[Math.ceil(n[0]/2),Math.ceil(n[1]/2)],s=lr();return`
|
|
vec4 ${t}(int index) {
|
|
vec2 uv = packedUVfrom1D(
|
|
${o[0]}, ${o[1]}, index);
|
|
return ${s.texture2D}(${e}, uv);
|
|
}
|
|
`}function ube(r){let e=r.name,t="get"+e.charAt(0).toUpperCase()+e.slice(1);if(r.shapeInfo.isUniform)return`
|
|
float ${t}(int index) {
|
|
${Ud(r)}
|
|
}
|
|
`;let n=r.shapeInfo.texShape,o=n[0],s=n[1];if(s===1&&o===1)return`
|
|
float ${t}(int index) {
|
|
return sampleTexture(${e}, halfCR);
|
|
}
|
|
`;let i=mm(e);return s===1?`
|
|
float ${t}(int index) {
|
|
vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / ${o}.0);
|
|
return sampleTexture(${e}, uv);
|
|
}
|
|
`:o===1?`
|
|
float ${t}(int index) {
|
|
vec2 uv = vec2((float(index + ${i}) + 0.5) / ${s}.0, 0.5);
|
|
return sampleTexture(${e}, uv);
|
|
}
|
|
`:`
|
|
float ${t}(int index) {
|
|
vec2 uv = uvFromFlat(${o}, ${s}, index + ${i});
|
|
return sampleTexture(${e}, uv);
|
|
}
|
|
`}function pbe(r){let e=r.shapeInfo.logicalShape,t=r.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),o=r.shapeInfo.texShape,s=o[0],i=o[1],a=lr();if(o!=null&&x.arraysEqual(e,o))return`
|
|
vec4 ${n}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${i}.0, ${s}.0);
|
|
|
|
return ${a.texture2D}(${t}, uv);
|
|
}
|
|
`;let l=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],u=Math.ceil(e[1]/2);return`
|
|
vec4 ${n}(int row, int col) {
|
|
vec2 uv = packedUVfrom2D(${u}, ${l[0]}, ${l[1]}, row, col);
|
|
return ${a.texture2D}(${t}, uv);
|
|
}
|
|
`}function cbe(r){let e=r.shapeInfo.logicalShape,t=r.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),o=r.shapeInfo.texShape;if(o!=null&&x.arraysEqual(e,o)){let c=o[0],m=o[1];return`
|
|
float ${n}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${m}.0, ${c}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}let{newShape:s,keptDims:i}=x.squeezeShape(e),a=s;if(a.length<e.length){let c=jd(r,a),m=["row","col"];return`
|
|
${Vd(c)}
|
|
float ${n}(int row, int col) {
|
|
return ${n}(${Hd(m,i)});
|
|
}
|
|
`}if(r.shapeInfo.isUniform)return`
|
|
float ${n}(int row, int col) {
|
|
int index = round(dot(vec2(row, col), vec2(${e[1]}, 1)));
|
|
${Ud(r)}
|
|
}
|
|
`;let l=o[0],u=o[1],p=mm(t);return u===1?`
|
|
float ${n}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${p}), vec3(${e[1]}, 1, 1));
|
|
vec2 uv = vec2(0.5, (index + 0.5) / ${l}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`:l===1?`
|
|
float ${n}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${p}), vec3(${e[1]}, 1, 1));
|
|
vec2 uv = vec2((index + 0.5) / ${u}.0, 0.5);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`:`
|
|
float ${n}(int row, int col) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${e[1]} + col + ${p};
|
|
vec2 uv = uvFromFlat(${l}, ${u}, index);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function mbe(r){let e=r.shapeInfo.logicalShape,t=r.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),o=r.shapeInfo.texShape,s=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)];if(e[0]===1){let c=e.slice(1),m=[1,2],f=jd(r,c),d=["b","row","col"];return`
|
|
${oU(f)}
|
|
vec4 ${n}(int b, int row, int col) {
|
|
return ${n}(${Hd(d,m)});
|
|
}
|
|
`}let i=s[0],a=s[1],l=Math.ceil(e[2]/2),u=l*Math.ceil(e[1]/2),p=lr();return`
|
|
vec4 ${n}(int b, int row, int col) {
|
|
vec2 uv = packedUVfrom3D(
|
|
${i}, ${a}, ${u}, ${l}, b, row, col);
|
|
return ${p.texture2D}(${t}, uv);
|
|
}
|
|
`}function fbe(r){let e=r.shapeInfo.logicalShape,t=r.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),o=e[1]*e[2],s=e[2],{newShape:i,keptDims:a}=x.squeezeShape(e),l=i;if(l.length<e.length){let d=jd(r,l),h=["row","col","depth"];return`
|
|
${Vd(d)}
|
|
float ${n}(int row, int col, int depth) {
|
|
return ${n}(${Hd(h,a)});
|
|
}
|
|
`}if(r.shapeInfo.isUniform)return`
|
|
float ${n}(int row, int col, int depth) {
|
|
int index = round(dot(vec3(row, col, depth),
|
|
vec3(${o}, ${s}, 1)));
|
|
${Ud(r)}
|
|
}
|
|
`;let u=r.shapeInfo.texShape,p=u[0],c=u[1],m=r.shapeInfo.flatOffset;if(c===o&&m==null)return`
|
|
float ${n}(int row, int col, int depth) {
|
|
float texR = float(row);
|
|
float texC = dot(vec2(col, depth), vec2(${s}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${c}.0, ${p}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`;if(c===s&&m==null)return`
|
|
float ${n}(int row, int col, int depth) {
|
|
float texR = dot(vec2(row, col), vec2(${e[1]}, 1));
|
|
float texC = float(depth);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${c}.0, ${p}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`;let f=mm(t);return`
|
|
float ${n}(int row, int col, int depth) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${o} + col * ${s} + depth + ${f};
|
|
vec2 uv = uvFromFlat(${p}, ${c}, index);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function dbe(r){let e=r.shapeInfo.logicalShape,t=e.length,n=r.name,o="get"+n.charAt(0).toUpperCase()+n.slice(1),s=r.shapeInfo.texShape,i=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],a=i[0],l=i[1],u=Math.ceil(e[t-1]/2),p=u*Math.ceil(e[t-2]/2),c="int b, int row, int col",m=`b * ${p} + (row / 2) * ${u} + (col / 2)`;for(let d=2;d<t-1;d++)c=`int b${d}, `+c,p*=e[t-d-1],m=`b${d} * ${p} + `+m;let f=lr();return`
|
|
vec4 ${o}(${c}) {
|
|
int index = ${m};
|
|
int texR = index / ${l};
|
|
int texC = index - texR * ${l};
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${l}, ${a});
|
|
return ${f.texture2D}(${n}, uv);
|
|
}
|
|
`}function hbe(r){let e=r.shapeInfo.logicalShape,t=r.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),o=e[3],s=e[2]*o,i=e[1]*s,{newShape:a,keptDims:l}=x.squeezeShape(e);if(a.length<e.length){let d=jd(r,a),h=["row","col","depth","depth2"];return`
|
|
${Vd(d)}
|
|
float ${n}(int row, int col, int depth, int depth2) {
|
|
return ${n}(${Hd(h,l)});
|
|
}
|
|
`}if(r.shapeInfo.isUniform)return`
|
|
float ${n}(int row, int col, int depth, int depth2) {
|
|
int index = round(dot(vec4(row, col, depth, depth2),
|
|
vec4(${i}, ${s}, ${o}, 1)));
|
|
${Ud(r)}
|
|
}
|
|
`;let u=r.shapeInfo.flatOffset,p=r.shapeInfo.texShape,c=p[0],m=p[1];if(m===i&&u==null)return`
|
|
float ${n}(int row, int col, int depth, int depth2) {
|
|
float texR = float(row);
|
|
float texC =
|
|
dot(vec3(col, depth, depth2),
|
|
vec3(${s}, ${o}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${m}.0, ${c}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`;if(m===o&&u==null)return`
|
|
float ${n}(int row, int col, int depth, int depth2) {
|
|
float texR = dot(vec3(row, col, depth),
|
|
vec3(${e[1]*e[2]}, ${e[2]}, 1));
|
|
float texC = float(depth2);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${m}.0, ${c}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`;let f=mm(t);return`
|
|
float ${n}(int row, int col, int depth, int depth2) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${i} + col * ${s} +
|
|
depth * ${o} + depth2;
|
|
vec2 uv = uvFromFlat(${c}, ${m}, index + ${f});
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function gbe(r){let e=r.shapeInfo.logicalShape,t=r.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),o=e[4],s=e[3]*o,i=e[2]*s,a=e[1]*i,{newShape:l,keptDims:u}=x.squeezeShape(e);if(l.length<e.length){let h=jd(r,l),g=["row","col","depth","depth2","depth3"];return`
|
|
${Vd(h)}
|
|
float ${n}(int row, int col, int depth, int depth2, int depth3) {
|
|
return ${n}(${Hd(g,u)});
|
|
}
|
|
`}if(r.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}, ${i}, ${s}, ${o})) +
|
|
depth3;
|
|
${Ud(r)}
|
|
}
|
|
`;let p=r.shapeInfo.flatOffset,c=r.shapeInfo.texShape,m=c[0],f=c[1];if(f===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(${i}, ${s}, ${o}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${f}.0, ${m}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`;if(f===o&&p==null)return`
|
|
float ${n}(int row, int col, int depth, int depth2, int depth3) {
|
|
float texR = dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${e[1]*e[2]*e[3]},
|
|
${e[2]*e[3]}, ${e[3]}, 1));
|
|
int texC = depth3;
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${f}.0, ${m}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`;let d=mm(t);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 * ${i} + depth * ${s} +
|
|
depth2 * ${o} + depth3 + ${d};
|
|
vec2 uv = uvFromFlat(${m}, ${f}, index);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function bbe(r){let e=r.shapeInfo.logicalShape,t=r.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),{newShape:o,keptDims:s}=x.squeezeShape(e);if(o.length<e.length){let g=jd(r,o),b=["row","col","depth","depth2","depth3","depth4"];return`
|
|
${Vd(g)}
|
|
float ${n}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
return ${n}(${Hd(b,s)});
|
|
}
|
|
`}let i=e[5],a=e[4]*i,l=e[3]*a,u=e[2]*l,p=e[1]*u;if(r.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}, ${u}, ${l}, ${a})) +
|
|
dot(
|
|
vec2(depth3, depth4),
|
|
vec2(${i}, 1)));
|
|
${Ud(r)}
|
|
}
|
|
`;let c=r.shapeInfo.flatOffset,m=r.shapeInfo.texShape,f=m[0],d=m[1];if(d===p&&c==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(${u}, ${l}, ${a}, ${i})) +
|
|
float(depth4);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${d}.0, ${f}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`;if(d===i&&c==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(${e[1]*e[2]*e[3]*e[4]},
|
|
${e[2]*e[3]*e[4]},
|
|
${e[3]*e[4]},
|
|
${e[4]})) + float(depth3);
|
|
int texC = depth4;
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${d}.0, ${f}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`;let h=mm(t);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 * ${u} + depth * ${l} +
|
|
depth2 * ${a} + depth3 * ${i} + depth4 + ${h};
|
|
vec2 uv = uvFromFlat(${f}, ${d}, index);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function Ud(r){let e=r.name,t=x.sizeFromShape(r.shapeInfo.logicalShape);return t<2?`return ${e};`:`
|
|
for (int i = 0; i < ${t}; i++) {
|
|
if (i == index) {
|
|
return ${e}[i];
|
|
}
|
|
}
|
|
`}function ybe(r,e){let t=r.name,n=t.charAt(0).toUpperCase()+t.slice(1),o="get"+n+"AtOutCoords",s=r.shapeInfo.logicalShape.length,i=e.logicalShape.length,a=rU(r.shapeInfo.logicalShape,e.logicalShape),l=Xe(i),u=i-s,p,c=["x","y","z","w","u","v"];s===0?p="":i<2&&a.length>=1?p="coords = 0;":p=a.map(y=>`coords.${c[y+u]} = 0;`).join(`
|
|
`);let m="";i<2&&s>0?m="coords":m=r.shapeInfo.logicalShape.map((y,T)=>`coords.${c[T+u]}`).join(", ");let f="return outputValue;",h=x.sizeFromShape(r.shapeInfo.logicalShape)===1,b=x.sizeFromShape(e.logicalShape)===1;if(s===1&&!h&&!b)f=`
|
|
return vec4(outputValue.xy, outputValue.xy);
|
|
`;else if(h&&!b)i===1?f=`
|
|
return vec4(outputValue.x, outputValue.x, 0., 0.);
|
|
`:f=`
|
|
return vec4(outputValue.x);
|
|
`;else if(a.length){let y=s-2,T=s-1;a.indexOf(y)>-1&&a.indexOf(T)>-1?f="return vec4(outputValue.x);":a.indexOf(y)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":a.indexOf(T)>-1&&(f="return vec4(outputValue.xx, outputValue.zz);")}return`
|
|
vec4 ${o}() {
|
|
${l} coords = getOutputCoords();
|
|
${p}
|
|
vec4 outputValue = get${n}(${m});
|
|
${f}
|
|
}
|
|
`}function xbe(r,e){let t=r.name,n=t.charAt(0).toUpperCase()+t.slice(1),o="get"+n+"AtOutCoords",s=e.texShape,i=r.shapeInfo.texShape,a=r.shapeInfo.logicalShape.length,l=e.logicalShape.length;if(!r.shapeInfo.isUniform&&a===l&&r.shapeInfo.flatOffset==null&&x.arraysEqual(i,s))return`
|
|
float ${o}() {
|
|
return sampleTexture(${t}, resultUV);
|
|
}
|
|
`;let u=Xe(l),p=rU(r.shapeInfo.logicalShape,e.logicalShape),c=l-a,m,f=["x","y","z","w","u","v"];a===0?m="":l<2&&p.length>=1?m="coords = 0;":m=p.map(h=>`coords.${f[h+c]} = 0;`).join(`
|
|
`);let d="";return l<2&&a>0?d="coords":d=r.shapeInfo.logicalShape.map((h,g)=>`coords.${f[g+c]}`).join(", "),`
|
|
float ${o}() {
|
|
${u} coords = getOutputCoords();
|
|
${m}
|
|
return get${n}(${d});
|
|
}
|
|
`}function Xe(r){if(r<=1)return"int";if(r===2)return"ivec2";if(r===3)return"ivec3";if(r===4)return"ivec4";if(r===5)return"ivec5";if(r===6)return"ivec6";throw Error(`GPU for rank ${r} is not yet supported`)}function jd(r,e){let t=JSON.parse(JSON.stringify(r));return t.shapeInfo.logicalShape=e,t}function Hd(r,e){return e.map(t=>r[t]).join(", ")}function aU(r,e,t,n){let o=e.userCode,s=t.map((f,d)=>{let h={logicalShape:f.shape,texShape:f.isUniform?null:f.texData.texShape,isUniform:f.isUniform,isPacked:f.isUniform?!1:f.texData.isPacked,flatOffset:null};return f.texData!=null&&f.texData.slice!=null&&f.texData.slice.flatOffset>0&&(h.flatOffset=f.texData.slice.flatOffset),{name:e.variableNames[d],shapeInfo:h}}),i=s.map(f=>f.shapeInfo),a={logicalShape:n.shape,texShape:n.texData.texShape,isUniform:!1,isPacked:n.texData.isPacked,flatOffset:null},l=nU(s,a,o,e.packedInputs),u=r.createProgram(l),p=null,c=r.getUniformLocation(u,"NAN",!1);X().getNumber("WEBGL_VERSION")===1&&(p=r.getUniformLocation(u,"INFINITY",!1));let m={};for(let f=0;f<e.variableNames.length;f++){let d=e.variableNames[f],h=!1;m[d]=r.getUniformLocation(u,d,h),m[`offset${d}`]=r.getUniformLocation(u,`offset${d}`,h)}return{program:e,source:l,webGLProgram:u,uniformLocations:m,inShapeInfos:i,outShapeInfo:a,infLoc:p,nanLoc:c}}function iU(r,e){if(r.length!==e.length)throw Error(`Binary was compiled with ${r.length} inputs, but was executed with ${e.length} inputs`);r.forEach((t,n)=>{let o=t.logicalShape,s=e[n],i=s.shape;if(!x.arraysEqual(o,i))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${o} and ${i} must match`);if(t.isUniform&&s.isUniform)return;let a=t.texShape,l=s.isUniform?null:s.texData.texShape;if(!x.arraysEqual(a,l))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${a} and ${l} must match`)})}function lU(r,e,t,n,o){iU(e.inShapeInfos,t),iU([e.outShapeInfo],[n]);let s=n.texData.texture,i=n.texData.texShape;n.texData.isPacked?r.setOutputPackedMatrixTexture(s,i[0],i[1]):r.setOutputMatrixTexture(s,i[0],i[1]),r.setProgram(e.webGLProgram),X().getNumber("WEBGL_VERSION")===1&&e.infLoc!==null&&r.gl.uniform1f(e.infLoc,Infinity),e.nanLoc!==null&&r.gl.uniform1f(e.nanLoc,NaN),t.forEach((a,l)=>{let u=e.program.variableNames[l],p=e.uniformLocations[u],c=e.uniformLocations[`offset${u}`];if(p!=null){if(a.isUniform){if(x.sizeFromShape(a.shape)<2)r.gl.uniform1f(p,a.uniformValues[0]);else{let m=a.uniformValues;m instanceof Float32Array||(m=new Float32Array(m)),r.gl.uniform1fv(p,m)}return}a.texData.slice!=null&&c!=null&&r.gl.uniform1i(c,a.texData.slice.flatOffset),r.setInputMatrixTexture(a.texData.texture,p,l)}}),o!=null&&o(r,e.webGLProgram),r.executeProgram()}function uU(r,e,t){let n="";e.concat(t).forEach(i=>{let a=i.texData!=null&&i.texData.slice!=null&&i.texData.slice.flatOffset>0,l=i.isUniform?"uniform":i.texData.texShape;n+=`${i.shape}_${l}_${a}`});let o=r.userCode,s=r.constructor.name;return s+="_"+n+"_"+o,s}var hD={};Ge(hD,{addImpl:()=>Z0,bincountImpl:()=>mU,bincountReduceImpl:()=>fU,ceilImpl:()=>J0,concatImpl:()=>Ay,equalImpl:()=>Q0,expImpl:()=>eD,expm1Impl:()=>tD,floorImpl:()=>rD,gatherNdImpl:()=>dU,gatherV2Impl:()=>hU,greaterEqualImpl:()=>oD,greaterImpl:()=>nD,lessEqualImpl:()=>aD,lessImpl:()=>sD,linSpaceImpl:()=>gU,logImpl:()=>iD,maxImpl:()=>bU,maximumImpl:()=>lD,minimumImpl:()=>uD,multiplyImpl:()=>Dy,negImpl:()=>yU,notEqualImpl:()=>pD,prodImpl:()=>xU,rangeImpl:()=>Ey,rsqrtImpl:()=>mD,simpleAbsImpl:()=>pU,sliceImpl:()=>Yd,sparseFillEmptyRowsImpl:()=>TU,sparseReshapeImpl:()=>kU,sparseSegmentReductionImpl:()=>IU,squaredDifferenceImpl:()=>fD,stridedSliceImpl:()=>vU,stringNGramsImpl:()=>_U,stringSplitImpl:()=>CU,stringToHashBucketFastImpl:()=>SU,subImpl:()=>dD,tileImpl:()=>NU,topKImpl:()=>AU,transposeImpl:()=>cD,uniqueImpl:()=>DU});function du(r,e){Array.isArray(r)||(r=[r]),r.forEach(t=>{t!=null&&x.assert(t.dtype!=="complex64",()=>`${e} does not support complex64 tensors in the CPU backend.`)})}function pU(r){let e=new Float32Array(r.length);for(let t=0;t<r.length;++t)e[t]=Math.abs(r[t]);return e}function fr(r){return(e,t,n,o,s)=>{let i=C.assertAndGetBroadcastShape(e,t),a=i.length,l=x.computeStrides(i),u=x.sizeFromShape(i),p=x.getTypedArrayFromDType(s,u),c=e.length,m=t.length,f=x.computeStrides(e),d=x.computeStrides(t),h=C.getBroadcastDims(e,i),g=C.getBroadcastDims(t,i);if(h.length+g.length===0)for(let b=0;b<p.length;++b)p[b]=r(n[b%n.length],o[b%o.length]);else for(let b=0;b<p.length;++b){let y=x.indexToLoc(b,a,l),T=y.slice(-c);h.forEach(N=>T[N]=0);let k=x.locToIndex(T,c,f),I=y.slice(-m);g.forEach(N=>I[N]=0);let S=x.locToIndex(I,m,d);p[b]=r(n[k],o[S])}return[p,i]}}function qd(r){let{inputs:e,backend:t}=r,{real:n,imag:o}=e,s=t.data.get(n.dataId).values,i=t.data.get(o.dataId).values,a=t.makeTensorInfo(n.shape,"complex64"),l=t.data.get(a.dataId);return l.complexTensorInfos={real:t.makeTensorInfo(n.shape,"float32",s),imag:t.makeTensorInfo(o.shape,"float32",i)},a}function kI(r,e,t="float32"){if(t==="complex64"){let o=kI(r,e,"float32"),s=kI(r,e,"float32");return qd({inputs:{real:o,imag:s},backend:r})}let n=x.makeZerosTypedArray(x.sizeFromShape(e),t);return r.makeTensorInfo(e,t,n)}function Y0(r){let{inputs:e,backend:t}=r,{x:n}=e;return t.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}function cU(r){let{inputs:e,backend:t}=r,{input:n}=e,o=t.data.get(n.dataId).complexTensorInfos.real,s=t.data.get(o.dataId).values;return t.makeTensorInfo(o.shape,o.dtype,s)}function Ny(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{dtype:s}=n;if(s==="complex64"){if(o.dtype==="complex64")return Y0({inputs:{x:o},backend:t});let i=kI(t,o.shape,o.dtype),a=Ny({inputs:{x:o},backend:t,attrs:{dtype:"float32"}}),l=qd({inputs:{real:a,imag:i},backend:t});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(a),l}if(o.dtype==="complex64"){let i=cU({inputs:{input:o},backend:t}),a=Ny({inputs:{x:i},backend:t,attrs:{dtype:s}});return t.disposeIntermediateTensorInfo(i),a}if(!x.hasEncodingLoss(o.dtype,s)){let i=Y0({inputs:{x:o},backend:t});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(s==="int32"){let i=t.data.get(o.dataId).values,a=Int32Array.from(i);return t.makeTensorInfo(o.shape,"int32",a)}if(s==="bool"){let i=t.data.get(o.dataId).values,a=x.toTypedArray([0],o.dtype),[l,u]=fr((p,c)=>p!==c?1:0)(o.shape,[],i,a,"bool");return t.makeTensorInfo(u,"bool",l)}throw new Error(`Error in Cast: failed to cast ${o.dtype} to ${s}`)}function Sr(r,e,t,n){return t==null?({inputs:o,backend:s})=>{let{a:i,b:a}=o,l=s;du([i,a],r);let u=l.data.get(i.dataId).values,p=l.data.get(a.dataId).values,c=i.dtype==="string"?C.fromUint8ToStringArray(u):u,m=i.dtype==="string"?C.fromUint8ToStringArray(p):p,f=n||i.dtype,[d,h]=e(i.shape,a.shape,c,m,f);return l.makeTensorInfo(h,f,d)}:({inputs:o,backend:s})=>{let{a:i,b:a}=o,l=s;if(i.dtype==="complex64"||a.dtype==="complex64"){let u=Ny({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),p=l.data.get(u.dataId),c=p.complexTensorInfos.real,m=p.complexTensorInfos.imag,f=l.data.get(c.dataId).values,d=l.data.get(m.dataId).values,h=Ny({inputs:{x:a},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(h.dataId),b=g.complexTensorInfos.real,y=g.complexTensorInfos.imag,T=l.data.get(b.dataId).values,k=l.data.get(y.dataId).values,[I,S,N]=t(i.shape,a.shape,f,d,T,k),F=l.makeTensorInfo(N,"float32",I),$=l.makeTensorInfo(N,"float32",S),O=qd({inputs:{real:F,imag:$},backend:l});return l.disposeIntermediateTensorInfo(u),l.disposeIntermediateTensorInfo(h),l.disposeIntermediateTensorInfo(F),l.disposeIntermediateTensorInfo($),O}else{let u=l.data.get(i.dataId).values,p=l.data.get(a.dataId).values,c=n||i.dtype,[m,f]=e(i.shape,a.shape,u,p,c);return l.makeTensorInfo(f,c,m)}}}function Xd(r){return(e,t,n,o,s,i)=>{let a=C.assertAndGetBroadcastShape(e,t),l=x.sizeFromShape(a),u=a.length,p=x.computeStrides(a),c=x.getTypedArrayFromDType("float32",l),m=x.getTypedArrayFromDType("float32",l),f=C.getBroadcastDims(e,a),d=C.getBroadcastDims(t,a),h=C.mergeRealAndImagArrays(n,o),g=C.mergeRealAndImagArrays(s,i),b=e.length,y=x.computeStrides(e),T=t.length,k=x.computeStrides(t);if(f.length+d.length===0)for(let I=0;I<c.length;I++){let S=I%h.length,N=I%g.length,F=r(h[S*2],h[S*2+1],g[N*2],g[N*2+1]);c[I]=F.real,m[I]=F.imag}else for(let I=0;I<c.length;I++){let S=x.indexToLoc(I,u,p),N=S.slice(-b);f.forEach(q=>N[q]=0);let F=x.locToIndex(N,b,y),$=S.slice(-T);d.forEach(q=>$[q]=0);let O=x.locToIndex($,T,k),V=r(h[F*2],h[F*2+1],g[O*2],g[O*2+1]);c[I]=V.real,m[I]=V.imag}return[c,m,a]}}var Z0=fr((r,e)=>r+e),Tbe=Xd((r,e,t,n)=>({real:r+t,imag:e+n})),RWr=Sr(so,Z0,Tbe);function mU(r,e,t,n,o){let s=x.sizeFromShape(n),i=x.makeZerosTypedArray(o,t);for(let a=0;a<r.length;a++){let l=r[a];if(l<0)throw new Error("Input x must be non-negative!");l>=o||(s>0?i[l]+=e[a]:i[l]+=1)}return i}function fU(r,e,t,n=!1){let o=r.shape[0],s=r.shape[1],i=ve([o,t],e.dtype);for(let a=0;a<o;a++)for(let l=0;l<s;l++){let u=r.get(a,l);if(u<0)throw new Error("Input x must be non-negative!");u>=t||(n?i.set(1,a,u):e.size>0?i.set(i.get(a,u)+e.get(a,l),a,u):i.set(i.get(a,u)+1,a,u))}return i}function Ms(r){return(e,t,n)=>{let o=x.getTypedArrayFromDType(t,e.length);for(let s=0;s<e.length;++s)o[s]=r(e[s],n);return o}}function Fs(r,e,t){return({inputs:n,attrs:o,backend:s})=>{let{x:i}=n;if(du(i,r),i.dtype==="string"||t==="string")throw new Error("unaryKernelFunc does not support string input/output");let a=s,l=a.data.get(i.dataId).values,u=t||i.dtype,p=e(l,u,o);return a.makeTensorInfo(i.shape,u,p)}}var J0=Ms(r=>Math.ceil(r)),jWr=Fs(Eo,J0);function Ay(r,e,t,n){let o=x.getArrayFromDType(t,x.sizeFromShape(e));if(n&&t!=="string"){let s=0;r.forEach(i=>{let a=x.sizeFromShape(i.shape);o.set(i.vals,s),s+=a})}else{let s=0;r.forEach(i=>{let a=t==="string"?C.fromUint8ToStringArray(i.vals):i.vals,l=0;for(let u=0;u<i.shape[0];++u){let p=u*e[1]+s;for(let c=0;c<i.shape[1];++c)o[p+c]=a[l++]}s+=i.shape[1]})}return o}var Q0=fr((r,e)=>r===e?1:0),QWr=Sr(Js,Q0,null,"bool");var eD=Ms(r=>Math.exp(r)),oKr=Fs(Mo,eD);var tD=Ms(r=>Math.expm1(r)),uKr=Fs(Qs,tD);var rD=Ms(r=>Math.floor(r)),dKr=Fs(Fo,rD);function dU(r,e,t,n,o,s,i,a,l){let u=ve([n,s],t);for(let p=0;p<n;p++){let c=[],m=0;for(let f=0;f<o;f++){let d=r[p*o+f];m+=d*i[f],c.push(d)}if(m<0||m>=l/s)throw new Error(`Invalid indices: ${c} does not index into ${a}`);for(let f=0;f<s;f++)u.values[p*s+f]=e.get(...e.indexToLoc(m*s+f))}return u}function hU(r,e,t){let n=ve(t,r.dtype);for(let o=0;o<n.size;++o){let i=n.indexToLoc(o).slice(),a=i[0],l=i[2],u=e.locToIndex([a,l]);i[2]=e.values[u];let p=r.locToIndex(i);n.values[o]=r.values[p]}return n}var nD=fr((r,e)=>r>e?1:0),vKr=Sr(ra,nD,null,"bool");var oD=fr((r,e)=>r>=e?1:0),NKr=Sr(Ro,oD,null,"bool");var sD=fr((r,e)=>r<e?1:0),FKr=Sr(oa,sD,null,"bool");var aD=fr((r,e)=>r<=e?1:0),BKr=Sr(sa,aD,null,"bool");function gU(r,e,t){let n=(e-r)/(t-1),o=x.makeZerosTypedArray(t,"float32");o[0]=r;for(let s=1;s<o.length;s++)o[s]=o[s-1]+n;return o}var iD=Ms(r=>Math.log(r)),UKr=Fs($o,iD);function bU(r,e,t,n){let o=x.getTypedArrayFromDType(n,x.sizeFromShape(t));for(let s=0;s<o.length;++s){let i=s*e,a=r[i];for(let l=0;l<e;++l){let u=r[i+l];(Number.isNaN(u)||u>a)&&(a=u)}o[s]=a}return o}var lD=fr((r,e)=>Math.max(r,e)),JKr=Sr(Po,lD);var uD=fr((r,e)=>Math.min(r,e)),nVr=Sr(Bo,uD);var Dy=fr((r,e)=>r*e),kbe=Xd((r,e,t,n)=>({real:r*t-e*n,imag:r*n+e*t})),lVr=Sr(Oo,Dy,kbe);function yU(r,e,t){let n=x.createScalarValue(-1,t);return Dy([],e,n,r,t)}var pD=fr((r,e)=>r!==e?1:0),bVr=Sr(ma,pD,null,"bool");function cD(r,e,t,n,o){let s=e.length,i=x.sizeFromShape(e),a=x.computeStrides(e),l=x.computeStrides(o),u=x.getTypedArrayFromDType(t,x.sizeFromShape(o));for(let p=0;p<i;++p){let c=x.indexToLoc(p,s,a),m=new Array(c.length);for(let d=0;d<m.length;d++)m[d]=c[n[d]];let f=x.locToIndex(m,s,l);u[f]=r[p]}return u}function xU(r,e,t,n){let[o,s]=C.computeOutAndReduceShapes(r,n),i=Mr(e,"int32"),a=x.makeZerosTypedArray(x.sizeFromShape(o),i),l=x.sizeFromShape(s);for(let u=0;u<a.length;++u){let p=u*l,c=1;for(let m=0;m<l;++m)c*=t[p+m];a[u]=c}return{outVals:a,outShape:o,outDtype:i}}function Ey(r,e,t,n){let o=r===e,s=r<e&&t<0,i=e<r&&t>1;if(o||s||i)return x.makeZerosTypedArray(0,n);let a=Math.abs(Math.ceil((e-r)/t)),l=x.makeZerosTypedArray(a,n);e<r&&t===1&&(t=-1),l[0]=r;for(let u=1;u<l.length;u++)l[u]=l[u-1]+t;return l}var mD=Ms(r=>1/Math.sqrt(r)),LVr=Fs(zo,mD);function Yd(r,e,t,n,o){let s=br.isSliceContinous(n,e,t),i=x.sizeFromShape(t),a=x.computeStrides(n);if(s){let c=br.computeFlatOffset(e,a);return o==="string"?r.slice(c,c+i):r.subarray(c,c+i)}let l=o==="string"?C.fromUint8ToStringArray(r):r,u=ve(n,o,l),p=ve(t,o);for(let c=0;c<p.size;++c){let m=p.indexToLoc(c),f=m.map((d,h)=>d+e[h]);p.set(u.get(...f),...m)}return o==="string"?C.fromStringArrayToUint8(p.values):p.values}function TU(r,e,t,n,o,s,i){let a=e[0],l=s[0],u=new Array(l),p=new Array(a),c=e[1];if(l===0){if(a!==0)throw new Error(`Received SparseTensor with denseShape[0] = 0 but
|
|
indices.shape[0] = ${a}`);let g=x.getArrayFromDType(t,0),b=x.getArrayFromDType(o,0);return[g,[0,c],b,u,p]}let m=!0,f=0,d=new Array(l).fill(0);for(let g=0;g<a;++g){let b=r[g*c];if(b<0)throw new Error(`indices(${g}, 0) is invalid: ${b} < 0`);if(b>=l)throw new Error(`indices(${g}, 0) is invalid: ${b} >= ${l}`);++d[b],m=m&&b>=f,f=b}let h=!0;for(let g=0;g<l;++g){let b=d[g]===0;u[g]=b,h=h&&!b,d[g]=Math.max(d[g],1),g>0&&(d[g]+=d[g-1])}if(h&&m){let g=r,b=n;for(let y=0;y<a;++y)p[y]=y;return[g,[a,c],b,u,p]}else{let g=d[l-1],b=x.getArrayFromDType(t,g*c),y=x.getArrayFromDType(o,g),T=new Array(l).fill(0);for(let k=0;k<a;++k){let I=r[k*c],S=T[I],N=(I===0?0:d[I-1])+S;T[I]++;for(let F=0;F<c;++F)b[N*c+F]=r[k*c+F];y[N]=n[k],p[k]=N}for(let k=0;k<l;++k)if(T[k]===0){let S=k===0?0:d[k-1];b[S*c+0]=k;for(let N=1;N<c;++N)b[S*c+N]=0;y[S]=i}return[b,[g,c],y,u,p]}}function kU(r,e,t,n,o){let s=x.sizeFromShape(n),i=e[0],a=o.length,l=[],u=1,p=-1;for(let g=0;g<a;++g){let b=o[g];if(b===-1){if(p!==-1)throw new Error(`only one output dimension may be -1, not both ${p} and ${g}`);p=g,l.push(1)}else{if(b<0)throw new Error(`size ${g} must be non-negative, not ${b}`);u*=b,l.push(b)}}if(p!==-1){if(u<=0)throw new Error("reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero");let g=Math.trunc(s/u);if(u*g!==s)throw new Error(`Input to reshape is a SparseTensor with ${s}
|
|
dense values, but the requested shape requires a multiple of ${u}. inputShape=${n} outputShape= ${l}`);l[p]=g}let c=x.sizeFromShape(l);if(c!==s)throw new Error(`Input to reshape is a tensor with ${s} dense values, but the requested shape has ${c}. inputShape=${n} outputShape=${l}`);let m=n.length,f=[];if(m>0){f[m-1]=1;for(let g=m-2;g>=0;--g)f[g]=f[g+1]*n[g+1]}let d=[];if(a>0){d[a-1]=1;for(let g=a-2;g>=0;--g)d[g]=d[g+1]*l[g+1]}let h=x.getArrayFromDType(t,i*a);for(let g=0;g<i;++g){let b=0;for(let y=0;y<m;++y)b+=r[g*m+y]*f[y];for(let y=0;y<a;++y)h[g*a+y]=Math.trunc(b/d[y]),b%=d[y]}return[h,[i,a],l]}function IU(r,e,t,n,o,s=!1,i=0){let a=n.length;if(a!==o.length)throw new Error("segmentIds and indices should have same size.");let l=[e[0],r.length/e[0]],u=l[1],c=a>0?o[a-1]+1:0;if(c<0)throw new Error("segment ids must be >= 0");let m=e.slice();m[0]=c;let f=m.reduce((T,k)=>T*k,1),d=x.getArrayFromDType(t,f);if(a===0)return c>0&&d.fill(i),[d,m];if(c<=0)throw new Error("segment ids must be >= 0");let h=0,g=1,b=0,y=o[h];for(;;){let T=0;if(g<a){if(T=o[g],y===T){++g;continue}if(y>=T)throw new Error("segment ids are not increasing")}if(y<0||y>=c)throw new Error(`Segment id ${y} out of range [0, ${c}), possibly because segmentIds input is not sorted.`);y>b&&d.fill(i,b*u,y*u);for(let k=h;k<g;++k){let I=n[k];if(I<0||I>=l[0])throw new Error(`Bad: indices[${k}] == ${n[k]} out of range [0, ${l[0]})`);for(let S=0;S<u;S++)d[y*u+S]+=r[I*u+S]}if(s)for(let k=0;k<u;k++)d[y*u+k]/=g-h;if(h=g,++g,b=y+1,y=T,g>a)break}return b<c&&d.fill(i,b*u,c*u),[d,m]}var fD=fr((r,e)=>{let t=r-e;return t*t}),XVr=Sr(Go,fD);function vU(r,e,t,n){let o=ve(r,e.dtype);for(let s=0;s<o.size;s++){let i=o.indexToLoc(s),a=new Array(i.length);for(let l=0;l<a.length;l++)a[l]=i[l]*t[l]+n[l];o.set(e.get(...a),...i)}return o}var wU=class{constructor(e,t,n,o,s,i){this.separator=x.encodeString(e),this.nGramWidths=t,this.leftPad=x.encodeString(n),this.rightPad=x.encodeString(o),this.padWidth=s,this.preserveShort=i}getPadWidth(e){return Math.min(this.padWidth<0?e-1:this.padWidth,e-1)}getNumNGrams(e,t){let n=this.getPadWidth(t);return Math.max(0,e+2*n-t+1)}createNGrams(e,t,n,o,s,i){for(let a=0;a<s;++a){let l=this.getPadWidth(i),u=Math.max(0,l-a),p=Math.max(0,l-(s-(a+1))),c=i-(u+p),m=t+(u>0?0:a-l),f=0;f+=u*this.leftPad.length;for(let y=0;y<c;++y)f+=e[m+y].length;f+=p*this.rightPad.length,f+=(u+p+c-1)*this.separator.length,n[o+a]=new Uint8Array(f);let h=n[o+a],g=0,b=y=>y.forEach(T=>h[g++]=T);for(let y=0;y<u;++y)b(this.leftPad),b(this.separator);for(let y=0;y<c-1;++y)b(e[m+y]),b(this.separator);if(c>0){b(e[m+c-1]);for(let y=0;y<p;++y)b(this.separator),b(this.rightPad)}else{for(let y=0;y<p-1;++y)b(this.rightPad),b(this.separator);b(this.rightPad)}}}compute(e,t){let n=e.length,o=t.length;if(o>0){let l=t[0];if(l!==0)throw new Error(`First split value must be 0, got ${l}`);for(let u=1;u<o;++u){let p=t[u]>=l;if(p=p&&t[u]<=n,!p)throw new Error(`Invalid split value ${t[u]}, must be in [${l}, ${n}]`);l=t[u]}if(l!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${l}`)}let s=o-1,i=x.getArrayFromDType("int32",o);if(n===0||o===0){let l=new Array(n);for(let u=0;u<=s;++u)i[u]=0;return[l,i]}i[0]=0;for(let l=1;l<=s;++l){let u=t[l]-t[l-1],p=0;this.nGramWidths.forEach(c=>{p+=this.getNumNGrams(u,c)}),this.preserveShort&&u>0&&p===0&&(p=1),i[l]=i[l-1]+p}let a=new Array(i[s]);for(let l=0;l<s;++l){let u=t[l],p=i[l];if(this.nGramWidths.forEach(c=>{let m=t[l+1]-t[l],f=this.getNumNGrams(m,c);this.createNGrams(e,u,a,p,f,c),p+=f}),this.preserveShort&&p===i[l]){let c=t[l+1]-t[l];if(c===0)continue;let m=c+2*this.padWidth,f=1;this.createNGrams(e,u,a,p,f,m)}}return[a,i]}};function _U(r,e,t,n,o,s,i,a){return new wU(t,n,o,s,i,a).compute(r,e)}function Ibe(r,e,t){if(!r.length)return[];if(e.length===0){let s=new Array(r.length);for(let i=0;i<r.length;++i)s[i]=r.subarray(i,i+1);return s}if(e.length===1){let s=e[0],i=[],a=r.indexOf(s);for(;a!==-1;){let l=r.subarray(0,a);(!t||l.length!==0)&&i.push(l),r=r.subarray(a+1),a=r.indexOf(s)}return(!t||r.length!==0)&&i.push(r),i}let n=[],o=0;for(let s=0;s<r.length+1;s++)if(s===r.length||e.indexOf(r[s])!==-1){let i=r.subarray(o,s);(!t||i.length!==0)&&n.push(i),o=s+1}return n}function CU(r,e,t){let n=r.length,o=[],s=0,i=0,a=new Array(n);for(let m=0;m<n;++m){let f=Ibe(r[m],e,t),d=f.length;a[m]=d,s+=d,i=Math.max(i,d),o.push(...f)}let l=x.getArrayFromDType("int32",s*2),u=new Array(s),p=[n,i],c=0;for(let m=0;m<n;++m)for(let f=0;f<a[m];++f)l[c*2]=m,l[c*2+1]=f,u[c]=o[c],++c;return[l,u,p]}function SU(r,e){let t=x.getArrayFromDType("int32",r.length);for(let n=0;n<r.length;++n)t[n]=x.fingerPrint64(r[n]).modulo(e).getLowBitsUnsigned();return t}var dD=fr((r,e)=>r-e),vbe=Xd((r,e,t,n)=>({real:r-t,imag:e-n})),lUr=Sr(Wo,dD,vbe);function NU(r,e){let t=new Array(r.rank);for(let o=0;o<t.length;o++)t[o]=r.shape[o]*e[o];let n=ve(t,r.dtype);for(let o=0;o<n.values.length;++o){let s=n.indexToLoc(o),i=new Array(r.rank);for(let l=0;l<i.length;l++)i[l]=s[l]%r.shape[l];let a=r.locToIndex(i);n.values[o]=r.values[a]}return n}function AU(r,e,t,n,o){let s=e[e.length-1],[i,a]=[r.length/s,s],l=x.getTypedArrayFromDType(t,i*n),u=x.getTypedArrayFromDType("int32",i*n);for(let c=0;c<i;c++){let m=c*a,f=r.subarray(m,m+a),d=[];for(let y=0;y<f.length;y++)d.push({value:f[y],index:y});d.sort((y,T)=>T.value-y.value);let h=c*n,g=l.subarray(h,h+n),b=u.subarray(h,h+n);for(let y=0;y<n;y++)g[y]=d[y].value,b[y]=d[y].index}let p=e.slice();return p[p.length-1]=n,[ve(p,t,l),ve(p,"int32",u)]}function DU(r,e,t,n){let o=x.parseAxisParam(e,t)[0],s=[1,t[0],1];for(let d=0;d<o;d++)s[0]*=t[d];s[1]=t[o];for(let d=o+1;d<t.length;d++)s[2]*=t[d];let i={},a=new Int32Array(t[o]),l=new bt(s,n,r),u=[],p=s[0]===1&&s[2]===1;for(let d=0;d<t[o];d++){let h;if(p)h=r[d].toString();else{let g=[];for(let b=0;b<s[0];b++)for(let y=0;y<s[2];y++)g.push(l.get(b,d,y));h=g.join(",")}if(i[h]!==void 0)a[d]=i[h];else{let g=Object.keys(i).length;i[h]=g,a[d]=g,u.push(d)}}let c=s.slice();c[1]=Object.keys(i).length;let m=new bt(c,n);u.forEach((d,h)=>{for(let g=0;g<s[0];g++)for(let b=0;b<s[2];b++)m.set(l.get(g,d,b),g,h,b)});let f=t.slice();return f[o]=c[1],{outputValues:m.values,outputShape:f,indices:a}}var{addImpl:EU,bincountImpl:II,bincountReduceImpl:MU,ceilImpl:FU,concatImpl:RU,equalImpl:LU,expImpl:$U,expm1Impl:PU,floorImpl:BU,gatherNdImpl:OU,gatherV2Impl:zU,greaterImpl:GU,greaterEqualImpl:WU,lessImpl:KU,lessEqualImpl:VU,linSpaceImpl:UU,logImpl:jU,maxImpl:HU,maximumImpl:qU,minimumImpl:XU,multiplyImpl:YU,negImpl:ZU,notEqualImpl:JU,prodImpl:QU,rangeImpl:e4,rsqrtImpl:t4,simpleAbsImpl:vI,sliceImpl:r4,sparseFillEmptyRowsImpl:n4,sparseReshapeImpl:o4,sparseSegmentReductionImpl:wI,stridedSliceImpl:s4,stringNGramsImpl:a4,stringSplitImpl:i4,stringToHashBucketFastImpl:l4,subImpl:u4,tileImpl:p4,topKImpl:c4,transposeImpl:fm,uniqueImpl:m4}=hD;function gD(r,e){return["x","y","z","w","u","v"].slice(0,e).map(t=>`${r}.${t}`)}function Ir(r,e){return e===1?[r]:gD(r,e)}function f4(r,e){if(r===1)return"rc";let t="";for(let n=0;n<r;n++)t+=e[n],n<r-1&&(t+=",");return t}var bD=class{constructor(e){this.variableNames=["A"];this.packedInputs=!1;this.packedOutput=!0;this.outputShape=e;let t=e.length;if(t===0)this.userCode=`
|
|
void main() {
|
|
setOutput(vec4(getA(), 0., 0., 0.));
|
|
}
|
|
`;else{let n=Ir("rc",t),o=Xe(t),s=_be(t,e,n),i=Cbe(t,e[e.length-1],e[e.length-2],n),a=Sbe(e,n);this.userCode=`
|
|
void main() {
|
|
${o} rc = getOutputCoords();
|
|
|
|
if(${s}) {
|
|
setOutput(vec4(0));
|
|
} else {
|
|
${i}
|
|
|
|
setOutput(vec4(${a}));
|
|
}
|
|
}
|
|
`}}};function wbe(r,e){let t=[];for(let n=0;n<=1;n++)for(let o=0;o<=1;o++){let s=`${n===0?"r":"rp1"}, ${o===0?"c":"cp1"}`;for(let i=2;i<r;i++)s=`${e[e.length-1-i]},`+s;t.push(s)}return t}function _be(r,e,t){if(r===1)return`rc > ${e[0]}`;let n="";for(let o=r-2;o<r;o++)n+=`${t[o]} >= ${e[o]}`,o<r-1&&(n+="||");return n}function Cbe(r,e,t,n){if(r===1)return"";let o=n.slice(-2);return`
|
|
int r = ${o[0]};
|
|
int c = ${o[1]};
|
|
int rp1 = r + 1;
|
|
int cp1 = c + 1;
|
|
|
|
bool cEdge = cp1 >= ${e};
|
|
bool rEdge = rp1 >= ${t};
|
|
`}function Sbe(r,e){let t=r.length,n=wbe(t,e);return t===1?`getA(rc),
|
|
rc + 1 >= ${r[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]})`}var My=class{constructor(e,t){this.variableNames=["A"];this.packedInputs=!0;this.packedOutput=!0;this.outputShape=e;let n="";for(let o=0;o<4;o++){let s="thisRC = rc;";o%2==1&&(s+="thisRC.z += 1;"),o>1&&(s+="thisRC.y += 1;"),n+=`
|
|
${s}
|
|
${o>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[${o}] =
|
|
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
|
|
${o>0?"}":""}
|
|
`}this.userCode=`
|
|
${Nbe(t)}
|
|
${Kd(e)}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
ivec3 thisRC;
|
|
int rows = ${e[1]};
|
|
int cols = ${e[2]};
|
|
|
|
${n}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};function Nbe(r){return`
|
|
ivec3 inputCoordsFromReshapedOutCoords(int index) {
|
|
${Ja(["r","c","d"],r)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}var yD=class{constructor(e){this.gpgpu=e;this.numUsedTextures=0;this.numFreeTextures=0;this._numBytesAllocated=0;this._numBytesFree=0;this.freeTextures={};this.logEnabled=!1;this.usedTextures={}}acquireTexture(e,t,n){let o=h4(t,n),s=g4(e,o,n);s in this.freeTextures||(this.freeTextures[s]=[]),s in this.usedTextures||(this.usedTextures[s]=[]);let i=d4(e,o,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[s].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=i,this.log();let l=this.freeTextures[s].shift();return this.usedTextures[s].push(l),l}let a;return o===sn.PACKED_2X2_FLOAT32?a=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):o===sn.PACKED_2X2_FLOAT16?a=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):o===sn.UNPACKED_FLOAT32?a=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):o===sn.UNPACKED_FLOAT16?a=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):o===sn.PACKED_4X1_UNSIGNED_BYTE&&(a=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[s].push(a),this.numUsedTextures++,this._numBytesAllocated+=i,this.log(),a}releaseTexture(e,t,n,o){if(this.freeTextures==null)return;let s=h4(n,o),i=g4(t,s,o);i in this.freeTextures||(this.freeTextures[i]=[]);let a=d4(t,s,this.gpgpu.gl,this.gpgpu.textureConfig,o),l=X().get("WEBGL_DELETE_TEXTURE_THRESHOLD");l!==-1&&this._numBytesAllocated>l?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=a):(this.freeTextures[i].push(e),this.numFreeTextures++,this._numBytesFree+=a),this.numUsedTextures--;let u=this.usedTextures[i],p=u.indexOf(e);if(p<0)throw new Error("Cannot release a texture that was never provided by this texture manager");u.splice(p,1),this.log()}log(){if(!this.logEnabled)return;let e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);let 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){for(let e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});for(let 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 Abe(r,e){let t=r;if(e===t.R32F)return 4;if(e===t.R16F)return 2;if(e===t.RGBA32F)return 16;if(e===r.RGBA)return 16;if(e===t.RGBA16F)return 8;throw new Error(`Unknown internal format ${e}`)}function d4(r,e,t,n,o){let s=Dbe(e,n),i;if(o){let[l,u]=Li(r[0],r[1]);i=l*u}else{let[l,u]=cm(r[0],r[1]);i=l*u}let a=Abe(t,s);return i*a}function Dbe(r,e){switch(r){case sn.PACKED_2X2_FLOAT32:return yI(e);case sn.PACKED_2X2_FLOAT16:return xI(e);case sn.UNPACKED_FLOAT32:return hI(e);case sn.UNPACKED_FLOAT16:return gI(e);case sn.PACKED_4X1_UNSIGNED_BYTE:return bI(e);default:throw new Error(`Unknown physical texture type ${r}`)}}function Ebe(r){return X().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?r?sn.PACKED_2X2_FLOAT32:sn.UNPACKED_FLOAT32:r?sn.PACKED_2X2_FLOAT16:sn.UNPACKED_FLOAT16}function h4(r,e){if(r===yn.UPLOAD)return sn.PACKED_2X2_FLOAT32;if(r===yn.RENDER||r==null)return Ebe(e);if(r===yn.DOWNLOAD||r===yn.PIXELS)return sn.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${r}`)}function g4(r,e,t){return`${r[0]}_${r[1]}_${e}_${t}`}var mo=class{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);
|
|
}
|
|
`}},Zr="if (isnan(x)) return x;",b4="return x;",xD="return abs(x);";var y4="return (x >= 0.0) ? x : (exp(x) - 1.0);",x4=Zr+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,T4=Zr+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,Fy="return x;",k4="return 1.0 / (1.0 + exp(-1.0 * x));";var I4="return x;",v4=`
|
|
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;
|
|
`,w4=`
|
|
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;
|
|
`,_4=`
|
|
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;
|
|
`,C4="return 1.0 / (1.0 + exp(-1.0 * x));",Qa=class{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);
|
|
}
|
|
`}};var TD=class{constructor(e){this.variableNames=["A"];this.packedInputs=!0;this.packedOutput=!1;this.outputShape=e;let t=e.length,n=Ir("rc",t),o=Xe(t),s=f4(t,n),i=n.slice(-2),a=t<=1?"rc":`vec2(${i.join(",")})`;this.userCode=`
|
|
void main() {
|
|
${o} rc = getOutputCoords();
|
|
vec4 packedInput = getA(${s});
|
|
|
|
setOutput(getChannel(packedInput, ${a}));
|
|
}
|
|
`}};var Mbe=gn.whereImpl,Fbe=1e-7,Rbe=1e-4,_I={};function Lbe(r){return r in _I||(_I[r]={}),_I[r]}var $be=()=>X().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),Pbe=600;function Bbe(){return X().global.screen==null?1024:X().global.screen.height*X().global.screen.width*window.devicePixelRatio*Pbe/1024/1024}var kD=class extends ii{constructor(e){super();this.pendingRead=new WeakMap;this.pendingDisposal=new WeakSet;this.dataRefCount=new WeakMap;this.numBytesInGPU=0;this.uploadWaitMs=0;this.downloadWaitMs=0;this.lastGlFlushTime=0;this.warnedAboutMemory=!1;this.pendingDeletes=0;this.disposed=!1;if(!X().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){let t=Qo(X().getNumber("WEBGL_VERSION"));this.binaryCache=Lbe(X().getNumber("WEBGL_VERSION")),this.gpgpu=new TI(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 yD(this.gpgpu),this.numMBBeforeWarning=Bbe(),this.texData=new Fu(this,Ma())}nextDataId(){return kD.nextDataId++}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}write(e,t,n){if((X().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||X().getBool("DEBUG"))&&this.checkNumericalProblems(e),n==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let o={id:this.nextDataId()};return this.texData.set(o,{shape:t,dtype:n,values:e,usage:yn.UPLOAD,refCount:1}),o}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){let t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){let t=this.texData.get(e);t.refCount--}}move(e,t,n,o,s){if(X().getBool("DEBUG")&&this.checkNumericalProblems(t),o==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:o,values:t,usage:yn.UPLOAD,refCount:s})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){let t=this.texData.get(e),{values:n,dtype:o,complexTensorInfos:s,slice:i,shape:a,isPacked:l}=t;if(i!=null){let m;l?m=new Qa(a,Fy):m=new mo(a,Fy);let f=this.runWebGLProgram(m,[{dataId:e,shape:a,dtype:o}],o),d=this.readSync(f.dataId);return this.disposeIntermediateTensorInfo(f),d}if(n!=null)return this.convertAndCacheOnCPU(e);if(o==="string")return n;let u=this.activeTimers!=null,p;u&&(p=x.now());let c;if(o==="complex64"){let m=this.readSync(s.real.dataId),f=this.readSync(s.imag.dataId);c=C.mergeRealAndImagArrays(m,f)}else c=this.getValuesFromTexture(e);return u&&(this.downloadWaitMs+=x.now()-p),this.convertAndCacheOnCPU(e,c)}async read(e){if(this.pendingRead.has(e)){let d=this.pendingRead.get(e);return new Promise(h=>d.push(h))}let t=this.texData.get(e),{values:n,shape:o,slice:s,dtype:i,complexTensorInfos:a,isPacked:l}=t;if(s!=null){let d;l?d=new Qa(o,Fy):d=new mo(o,Fy);let h=this.runWebGLProgram(d,[{dataId:e,shape:o,dtype:i}],i),g=this.read(h.dataId);return this.disposeIntermediateTensorInfo(h),g}if(n!=null)return this.convertAndCacheOnCPU(e);if(!X().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&X().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let u=null,p;if(i!=="complex64"&&X().get("WEBGL_BUFFER_SUPPORTED")){p=this.decode(e);let d=this.texData.get(p.dataId);u=this.gpgpu.createBufferFromTexture(d.texture,...yp(o))}this.pendingRead.set(e,[]),i!=="complex64"&&await this.gpgpu.createAndWaitForFence();let c;if(i==="complex64"){let d=await Promise.all([this.read(a.real.dataId),this.read(a.imag.dataId)]),h=d[0],g=d[1];c=C.mergeRealAndImagArrays(h,g)}else if(u==null)c=this.getValuesFromTexture(e);else{let d=x.sizeFromShape(o);c=this.gpgpu.downloadFloat32MatrixFromBuffer(u,d)}p!=null&&this.disposeIntermediateTensorInfo(p);let m=this.convertAndCacheOnCPU(e,c),f=this.pendingRead.get(e);return this.pendingRead.delete(e),f.forEach(d=>d(m)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&Ma().removeDataId(e,this),this.pendingDeletes--),m}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(o=>x.decodeString(o))}catch(o){throw new Error("Failed to decode encoded string bytes into utf-8")}return ve(e.shape,e.dtype,n)}checkNumericalProblems(e){if(e!=null)for(let t=0;t<e.length;t++){let n=e[t];if(!i0(n))throw X().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")?Error(`The value ${n} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`):Error(`The value ${n} cannot be represented on this device.`)}}getValuesFromTexture(e){let{shape:t,dtype:n,isPacked:o}=this.texData.get(e),s=x.sizeFromShape(t);if(X().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){let m=this.decode(e),f=this.texData.get(m.dataId),d=this.gpgpu.downloadMatrixFromPackedTexture(f.texture,...yp(t)).subarray(0,s);return this.disposeIntermediateTensorInfo(m),d}let i=X().getBool("WEBGL_PACK")&&o===!0,a=i?Cy(t):t,l=i?new E0(a):new D0(a),u=this.runWebGLProgram(l,[{shape:a,dtype:n,dataId:e}],"float32"),p=this.texData.get(u.dataId),c=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(p.texture,p.texShape[0],p.texShape[1]).subarray(0,s);return this.disposeIntermediateTensorInfo(u),c}timerAvailable(){return X().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}async time(e){let t=this.activeTimers,n=[],o=!1;this.programTimersStack==null?(this.programTimersStack=n,o=!0):this.activeTimers.push(n),this.activeTimers=n,e();let s=x.flatten(this.activeTimers.map(l=>l.query)).filter(l=>l!=null),i=x.flatten(this.activeTimers.map(l=>l.name)).filter(l=>l!=null);this.activeTimers=t,o&&(this.programTimersStack=null);let a={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};if(X().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){let l=await Promise.all(s);a.kernelMs=x.sum(l),a.getExtraProfileInfo=()=>l.map((u,p)=>({name:i[p],ms:u})).map(u=>`${u.name}: ${u.ms}`).join(", ")}else a.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,a}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return X().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:x.now(),endMs:null}}endTimer(e){return X().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=x.now(),e)}async getQueryTime(e){if(X().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);let t=e;return t.endMs-t.startMs}disposeData(e,t=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(t?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!t&&this.texData.get(e).refCount>0)return!1;if(this.pendingRead.has(e))return this.pendingDisposal.add(e),this.pendingDeletes++,!1;this.releaseGPUData(e);let{complexTensorInfos:n}=this.texData.get(e);return n!=null&&(this.disposeData(n.real.dataId,t),this.disposeData(n.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){let{texture:t,dtype:n,texShape:o,usage:s,isPacked:i,slice:a}=this.texData.get(e),l=a&&a.origDataId||e,u=this.dataRefCount.get(l);u>1?this.dataRefCount.set(l,u-1):(this.dataRefCount.delete(l),t!=null&&(this.numBytesInGPU-=this.computeBytes(o,n),this.textureManager.releaseTexture(t,o,s,i)));let p=this.texData.get(e);p.texture=null,p.texShape=null,p.isPacked=!1,p.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=$be){return X().getBool("WEBGL_CPU_FORWARD")&&e.every(n=>this.texData.get(n.dataId).texture==null&&x.sizeFromShape(n.shape)<t)}getGPGPUContext(){return this.gpgpu}where(e){C.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");let t=e.dataSync();return Mbe(e.shape,t)}packedUnaryOp(e,t,n){let o=new Qa(e.shape,t),s=this.compileAndRun(o,[e],n);return Ma().makeTensorFromDataId(s.dataId,s.shape,s.dtype)}abs(e){if(this.shouldExecuteOnCPU([e])&&e.dtype!=="complex64"){let o=vI(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,o)}if(X().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,xD,e.dtype);let t=new mo(e.shape,xD),n=this.compileAndRun(t,[e]);return Ma().makeTensorFromDataId(n.dataId,n.shape,n.dtype)}makeTensorInfo(e,t,n){let o;if(t==="string"&&n!=null&&n.length>0&&x.isString(n[0])){let s=n.map(i=>x.encodeString(i));o=this.write(s,e,t)}else o=this.write(n,e,t);return this.texData.get(o).usage=null,{dataId:o,shape:e,dtype:t}}makeOutput(e,t,n){let{dataId:o}=this.makeTensorInfo(e,t,n);return Ma().makeTensorFromDataId(o,e,t,this)}unpackTensor(e){let t=new TD(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){let t=new bD(e.shape),n=!0;return this.runWebGLProgram(t,[e],e.dtype,null,n)}packedReshape(e,t){let n=[mu(e.shape),...fu(e.shape)],o={dtype:e.dtype,shape:n,dataId:e.dataId},s=[mu(t),...fu(t)],i=new My(s,n),a=!0,l=this.runWebGLProgram(i,[o],e.dtype,null,a);return{dataId:l.dataId,shape:t,dtype:l.dtype}}decode(e){let t=this.texData.get(e),{isPacked:n,shape:o,dtype:s}=t,i=Cy(o),a;n?a=new A0(i):a=new N0(i);let l=!0,u=this.runWebGLProgram(a,[{shape:i,dtype:s,dataId:e}],s,null,l);return{dtype:s,shape:o,dataId:u.dataId}}runWebGLProgram(e,t,n,o,s=!1){let i=this.makeTensorInfo(e.outputShape,n),a=this.texData.get(i.dataId);if(e.packedOutput&&(a.isPacked=!0),e.outPackingScheme===bp.DENSE){let g=yp(e.outputShape);a.texShape=g.map(b=>b*2)}if(e.outTexUsage!=null&&(a.usage=e.outTexUsage),x.sizeFromShape(i.shape)===0)return a.values=x.getTypedArrayFromDType(i.dtype,0),i;let l=[],u=t.map(g=>{if(g.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let b=this.texData.get(g.dataId);if(b.texture==null){if(!e.packedInputs&&x.sizeFromShape(g.shape)<=X().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:g.shape,texData:null,isUniform:!0,uniformValues:b.values};e.packedInputs&&(b.isPacked=!0,b.shape=g.shape)}else if(!!b.isPacked!=!!e.packedInputs)g=b.isPacked?this.unpackTensor(g):this.packTensor(g),l.push(g),b=this.texData.get(g.dataId);else if(b.isPacked&&!xp(b.shape,g.shape)){let y=g,T=g.shape;g.shape=b.shape,g=this.packedReshape(g,T),l.push(g),b=this.texData.get(g.dataId),y.shape=T}return this.uploadToGPU(g.dataId),{shape:g.shape,texData:b,isUniform:!1}});this.uploadToGPU(i.dataId);let p={shape:i.shape,texData:a,isUniform:!1},c=uU(e,u,p),m=this.getAndSaveBinary(c,()=>aU(this.gpgpu,e,u,p)),f=this.activeTimers!=null,d;f&&(d=this.startTimer()),lU(this.gpgpu,m,u,p,o),l.forEach(g=>this.disposeIntermediateTensorInfo(g)),f&&(d=this.endTimer(d),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(d)}));let h=X().get("WEBGL_FLUSH_THRESHOLD");if(h>0){let g=x.now();g-this.lastGlFlushTime>h&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=g)}if(!X().getBool("WEBGL_LAZILY_UNPACK")&&a.isPacked&&s===!1){let g=this.unpackTensor(i);return this.disposeIntermediateTensorInfo(i),g}return i}compileAndRun(e,t,n,o,s=!1){return n=n||t[0].dtype,this.runWebGLProgram(e,t,n,o,s)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(X().getBool("IS_TEST")||Object.keys(this.binaryCache).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=j(()=>{if(!X().get("WEBGL_RENDER_FLOAT32_ENABLED")){let e=X().getBool("DEBUG");X().set("DEBUG",!1);let t=this.abs(be(1e-8)).dataSync()[0];if(X().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?Fbe:Rbe}uploadToGPU(e){let t=this.texData.get(e),{shape:n,dtype:o,values:s,texture:i,usage:a,isPacked:l}=t;if(i!=null)return;let u=this.activeTimers!=null,p;u&&(p=x.now());let c=t.texShape;if(c==null&&(c=T0(n,l),t.texShape=c),s!=null){let m=Cy(n),f,d=c[1],h=c[0],g=s instanceof Uint8Array;l?([d,h]=Li(c[0],c[1]),f=new F0(m,[h,d],g)):f=new M0(m,[h,d],g);let b=this.makeTensorInfo([h,d],o);g?this.texData.get(b.dataId).usage=yn.PIXELS:this.texData.get(b.dataId).usage=yn.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(b.dataId),d,h,s);let y=!0,T=this.runWebGLProgram(f,[b],o,null,y),k=this.texData.get(T.dataId);t.texture=k.texture,t.texShape=k.texShape,t.isPacked=k.isPacked,t.usage=k.usage,this.disposeIntermediateTensorInfo(b),this.texData.delete(T.dataId),t.values=null,u&&(this.uploadWaitMs+=x.now()-p)}else{let m=this.acquireTexture(c,a,o,l);t.texture=m}}convertAndCacheOnCPU(e,t){let n=this.texData.get(e),{dtype:o}=n;return this.releaseGPUData(e),t!=null&&(n.values=Obe(t,o)),n.values}acquireTexture(e,t,n,o){if(this.numBytesInGPU+=this.computeBytes(e,n),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){let s=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${s} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,o)}computeBytes(e,t){return e[0]*e[1]*x.bytesPerElement(t)}},Ry=kD;Ry.nextDataId=0;function Obe(r,e){if(e==="float32"||e==="complex64")return r;if(e==="int32"||e==="bool"){let t=e==="int32"?new Int32Array(r.length):new Uint8Array(r.length);for(let n=0;n<t.length;++n)t[n]=Math.round(r[n]);return t}else throw new Error(`Unknown dtype ${e}`)}var zbe="3.7.0";function S4(){X().set("WEBGL_FORCE_F16_TEXTURES",!0)}yc.isBrowser()&&jf("webgl",()=>new Ry,2);var bjr={forceHalfFloat:S4};var CI=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`;var Rs=class{constructor(e,t,n){this.variableNames=["A","B"];this.outputShape=C.assertAndGetBroadcastShape(t,n),this.userCode=`
|
|
float binaryOperation(float a, float b) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
float a = getAAtOutCoords();
|
|
float b = getBAtOutCoords();
|
|
setOutput(binaryOperation(a, b));
|
|
}
|
|
`}};var Tp=`
|
|
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;
|
|
`;var ei=class{constructor(e,t,n,o=!1){this.variableNames=["A","B"];this.supportsBroadcasting=!0;this.packedInputs=!0;this.packedOutput=!0;this.outputShape=C.assertAndGetBroadcastShape(t,n);let s=this.outputShape.length,i="";if(o)if(s===0||x.sizeFromShape(this.outputShape)===1)i=`
|
|
result.y = 0.;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else if(i=`
|
|
${Xe(s)} coords = getOutputCoords();
|
|
`,s===1)i+=`
|
|
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else{let l=Ir("coords",s);i+=`
|
|
bool nextRowOutOfBounds =
|
|
(${l[s-2]} + 1) >= ${this.outputShape[s-2]};
|
|
bool nextColOutOfBounds =
|
|
(${l[s-1]} + 1) >= ${this.outputShape[s-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);
|
|
${i}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};function vr(r){let{inputs:e,backend:t}=r,{x:n}=e;return t.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}var N4={kernelName:Lo,backendName:"webgl",kernelFunc:vr};function fo(r){let{inputs:e,backend:t}=r,{real:n,imag:o}=e,s=t.makeTensorInfo(n.shape,"complex64"),i=t.texData.get(s.dataId),a=vr({inputs:{x:n},backend:t}),l=vr({inputs:{x:o},backend:t});return i.complexTensorInfos={real:a,imag:l},s}var A4={kernelName:lc,backendName:"webgl",kernelFunc:fo};var ID="return (a < 0.) ? b * a : a;",vD=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function Gbe(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{alpha:s}=n,i=t.makeTensorInfo([],"float32",x.createScalarValue(s,"float32")),a=X().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ei(vD,o.shape,i.shape):new Rs(ID,o.shape,i.shape),l=t.runWebGLProgram(a,[o,i],o.dtype);return t.disposeIntermediateTensorInfo(i),l}var D4={kernelName:na,backendName:"webgl",kernelFunc:Gbe};var wD="return (a < 0.) ? b * a : a;",_D=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function Wbe(r){let{inputs:e,backend:t}=r,{x:n,alpha:o}=e,s=X().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ei(_D,n.shape,o.shape):new Rs(wD,n.shape,o.shape);return t.runWebGLProgram(s,[n,o],n.dtype)}var E4={kernelName:ga,backendName:"webgl",kernelFunc:Wbe};var SI="if (isnan(x)) return x;",M4=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,F4=`
|
|
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 Ae({opSnippet:r,packedOpSnippet:e,cpuKernelImpl:t,dtype:n}){return({inputs:o,backend:s})=>{let{x:i}=o,a=s,l=n||i.dtype;if(a.shouldExecuteOnCPU([i])&&t!=null){let c=a.texData.get(i.dataId),m=t(c.values,l);return a.makeTensorInfo(i.shape,l,m)}let u=X().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&e!=null,p;return u?p=new Qa(i.shape,e):p=new mo(i.shape,r),a.runWebGLProgram(p,[i],l)}}function Tt({opSnippet:r,packedOpSnippet:e,checkOutOfBounds:t=!1,supportsComplex:n=!1,cpuKernelImpl:o,dtype:s}){return({inputs:i,backend:a})=>{let{a:l,b:u}=i,p=a;if(n&&l.dtype==="complex64"){let d=p.texData.get(l.dataId),h=p.texData.get(u.dataId),[g,b]=[[d.complexTensorInfos.real,h.complexTensorInfos.real],[d.complexTensorInfos.imag,h.complexTensorInfos.imag]].map(T=>{let[k,I]=T,S={dataId:k.dataId,dtype:k.dtype,shape:l.shape},N={dataId:I.dataId,dtype:I.dtype,shape:u.shape},F=new Rs(r,l.shape,u.shape);return p.runWebGLProgram(F,[S,N],Mr(k.dtype,I.dtype))}),y=fo({inputs:{real:g,imag:b},backend:p});return p.disposeIntermediateTensorInfo(g),p.disposeIntermediateTensorInfo(b),y}let c=s||Mr(l.dtype,u.dtype);if((l.dtype==="string"||u.dtype==="string"||p.shouldExecuteOnCPU([l,u]))&&o!=null){let d=p.texData.get(l.dataId).values,h=p.texData.get(u.dataId).values,g=l.dtype==="string"?C.fromUint8ToStringArray(d):d,b=l.dtype==="string"?C.fromUint8ToStringArray(h):h,[y,T]=o(l.shape,u.shape,g,b,c),k=p.makeTensorInfo(T,c),I=p.texData.get(k.dataId);return I.values=y,k}let m=X().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&e!=null,f;return m?f=new ei(e,l.shape,u.shape,t):f=new Rs(r,l.shape,u.shape),p.runWebGLProgram(f,[l,u],c)}}function kp(r,e=!1){if(r==="linear")return e?I4:b4;if(r==="relu")return e?w4:x4;if(r==="elu")return e?v4:y4;if(r==="relu6")return e?_4:T4;if(r==="prelu")return e?_D:wD;if(r==="leakyrelu")return e?vD:ID;if(r==="sigmoid")return e?C4:k4;throw new Error(`Activation ${r} has not been implemented for the WebGL backend.`)}var Ly=class{constructor(e,t,n,o=!1,s=!1,i=!1,a=null,l=!1,u=!1){this.variableNames=["matrixA","matrixB"];this.packedInputs=!0;this.packedOutput=!0;this.outputShape=n;let p=o?e[1]:e[2],c=Math.ceil(p/2),m=o?"i * 2, rc.y":"rc.y, i * 2",f=s?"rc.z, i * 2":"i * 2, rc.z",d=o?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],h=s?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],g="",b="";a&&(l?g=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${a}
|
|
}`:u?g=`vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${a}
|
|
}`:g=`vec4 activation(vec4 x) {
|
|
${a}
|
|
}`,b="result = activation(result);");let y=i?"result += getBiasAtOutCoords();":"";i&&this.variableNames.push("bias"),l&&this.variableNames.push("preluActivationWeights"),u&&this.variableNames.push("leakyreluAlpha");let T="rc.x",k="rc.x";e[0]<t[0]?T=`int(min(float(rc.x), ${e[0]-1}.))`:t[0]<e[0]&&(k=`int(min(float(rc.x), ${t[0]-1}.))`),this.userCode=`
|
|
${g}
|
|
|
|
const float sharedDimension = ${c}.0;
|
|
|
|
vec4 dot2x2ARowBCol(ivec3 rc) {
|
|
vec4 result = vec4(0);
|
|
for (int i = 0; i < ${c}; i++) {
|
|
int batchA = ${T};
|
|
int batchB = ${k};
|
|
vec4 a = getMatrixA(batchA, ${m});
|
|
vec4 b = getMatrixB(batchB, ${f});
|
|
|
|
// These swizzled products need to be separately added.
|
|
// See: https://github.com/tensorflow/tfjs/issues/1735
|
|
result += (${d[0]} * ${h[0]});
|
|
result += (${d[1]} * ${h[1]});
|
|
}
|
|
return result;
|
|
}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
vec4 result = dot2x2ARowBCol(rc);
|
|
|
|
${y}
|
|
|
|
${b}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};var CD={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},NI=class{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"];this.outputShape=C.assertAndGetBroadcastShape(t,n),this.userCode=`
|
|
float binaryOpComplex(
|
|
float areal, float aimag, float breal, float bimag) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
float areal = getARealAtOutCoords();
|
|
float aimag = getAImagAtOutCoords();
|
|
float breal = getBRealAtOutCoords();
|
|
float bimag = getBImagAtOutCoords();
|
|
setOutput(binaryOpComplex(areal, aimag, breal, bimag));
|
|
}
|
|
`}};var R4="return a * b;";function $y(r){let{inputs:e,backend:t}=r,{a:n,b:o}=e,s=C.upcastType(n.dtype,o.dtype);if(n.dtype==="complex64"){let a=t.texData.get(n.dataId),l=t.texData.get(o.dataId),u=new NI(CD.REAL,n.shape,o.shape),p=new NI(CD.IMAG,n.shape,o.shape),c=[{dataId:a.complexTensorInfos.real.dataId,dtype:a.complexTensorInfos.real.dtype,shape:n.shape},{dataId:a.complexTensorInfos.imag.dataId,dtype:a.complexTensorInfos.imag.dtype,shape:n.shape},{dataId:l.complexTensorInfos.real.dataId,dtype:l.complexTensorInfos.real.dtype,shape:o.shape},{dataId:l.complexTensorInfos.imag.dataId,dtype:l.complexTensorInfos.imag.dtype,shape:o.shape}],m=t.runWebGLProgram(u,c,"float32"),f=t.runWebGLProgram(p,c,"float32"),d=fo({inputs:{real:m,imag:f},backend:t});return t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f),d}if(t.shouldExecuteOnCPU([n,o])){let a=t.texData.get(n.dataId),l=t.texData.get(o.dataId),[u,p]=YU(n.shape,o.shape,a.values,l.values,s),c=t.makeTensorInfo(p,s),m=t.texData.get(c.dataId);return m.values=u,c}let i;return X().getBool("WEBGL_PACK_BINARY_OPERATIONS")?i=new ei(R4,n.shape,o.shape):i=new Rs(R4,n.shape,o.shape),t.runWebGLProgram(i,[n,o],s)}var L4={kernelName:Oo,backendName:"webgl",kernelFunc:$y};function $4(r,e,t){let n=[mu(r.shape),...fu(r.shape)],o={dtype:r.dtype,shape:n,dataId:r.dataId},s=[mu(e),...fu(e)],i=new My(s,n),a=!0,l=t.runWebGLProgram(i,[o],r.dtype,null,a);return{dataId:l.dataId,shape:e,dtype:l.dtype}}function de(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{shape:s}=n,i=t,a=x.sizeFromShape(o.shape),l=x.inferFromImplicitShape(s,a),u=x.sizeFromShape(l);x.assert(a===u,()=>`The new shape (${l}) has ${u} elements and the old shape (${o.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`);let p=i.texData.get(o.dataId);return p.isPacked&&!xp(o.shape,l)&&!(p.texture!==null&&xp(p.shape,l))?$4(o,l,i):(i.incRef(o.dataId),{dataId:o.dataId,shape:l,dtype:o.dtype})}var P4={kernelName:gi,backendName:"webgl",kernelFunc:de};var AI=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:o,inSize:s,outSize:i}=e;this.outputShape=[o,i];let a=Math.floor(n/4)*4,l=n%4,u="sumValue += dot(values, ones);";if(t!=null){let c=1/t;u=`sumValue += dot(values * ${x.isInt(c)?c.toPrecision(2):c}, ones);`}let p="";s%n>0&&(p=`
|
|
if (inIdx < 0 || inIdx >= ${s}) {
|
|
return 0.0;
|
|
}
|
|
`),this.userCode=`
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${p}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * ${n};
|
|
|
|
float sumValue = 0.0;
|
|
|
|
for (int i = 0; i < ${a}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
${u}
|
|
}
|
|
|
|
int inIdx = inOffset + ${a};
|
|
if (${l===1}) {
|
|
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
|
|
|
|
${u}
|
|
} else if (${l===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1), 0.0, 0.0);
|
|
|
|
${u}
|
|
} else if (${l===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2), 0.0);
|
|
|
|
${u}
|
|
}
|
|
setOutput(sumValue);
|
|
}
|
|
`}};var SD=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:o,inSize:s,outSize:i}=e;this.outputShape=[o,i];let a="0.0",l="";t==="prod"?a="1.0":t==="min"?(a="1.0 / 1e-20",l="min"):t==="max"&&(a="-1.0 / 1e-20",l="max");let u=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?u="sumValue":t==="prod"?u="prodValue":t==="all"?u="allValue":t==="any"&&(u="anyValue");let p=Math.floor(n/4)*4,c=n%4,m=`
|
|
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 = ${l}(values, minMaxValue);
|
|
if (${t==="min"} || ${t==="max"}) {
|
|
minMaxValue = ${l}(values, minMaxValue);
|
|
bvec4 isNaN = isnan(values);
|
|
if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {
|
|
minMaxValue = vec4(NAN);
|
|
}
|
|
}
|
|
}
|
|
`,f="vec4";t==="all"?(a="1.0",m=`
|
|
bool reducedAllValue = all(values);
|
|
float floatedReducedAllValue = float(reducedAllValue);
|
|
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
|
|
`,f="bvec4"):t==="any"&&(a="0.0",m=`
|
|
bool reducedAnyValue = any(values);
|
|
float floatedReducedAnyValue = float(reducedAnyValue);
|
|
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
|
|
`,f="bvec4");let d="";s%n>0&&(d=`
|
|
if (inIdx < 0 || inIdx >= ${s}) {
|
|
return initializationValue;
|
|
}
|
|
`),this.userCode=`
|
|
const float initializationValue = ${a};
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${d}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * ${n};
|
|
|
|
vec4 minMaxValue = vec4(${a});
|
|
float prodValue = 1.0;
|
|
float sumValue = 0.0;
|
|
float allValue = 1.0;
|
|
float anyValue = 0.0;
|
|
|
|
for (int i = 0; i < ${p}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
${f} values = ${f}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
${m}
|
|
}
|
|
|
|
int inIdx = inOffset + ${p};
|
|
if (${c===1}) {
|
|
${f} values = ${f}(
|
|
getValue(batch, inIdx),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${m}
|
|
} else if (${c===2}) {
|
|
${f} values = ${f}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${m}
|
|
} else if (${c===3}) {
|
|
${f} values = ${f}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
initializationValue
|
|
);
|
|
|
|
${m}
|
|
}
|
|
setOutput(${u});
|
|
}
|
|
`}};function Kbe(r){let e=[];for(;e.length===0||e[e.length-1].outSize!==1;){let t=e.length?e[e.length-1].outSize:r[1],n=C.computeOptimalWindowSize(t);e.push({inSize:t,windowSize:n,outSize:Math.ceil(t/n)})}return e}function Co(r,e,t,n){let o=Kbe(r.shape),s=r;for(let i=0;i<o.length;i++){let{inSize:a,windowSize:l,outSize:u}=o[i],p,c;t==="mean"?p=i===0?new AI({windowSize:l,inSize:a,batchSize:r.shape[0],outSize:u},a):new AI({windowSize:l,inSize:a,batchSize:r.shape[0],outSize:u}):p=new SD({windowSize:l,inSize:a,batchSize:r.shape[0],outSize:u},t),c=s,s=n.runWebGLProgram(p,[s],e),c.dataId!==r.dataId&&n.disposeIntermediateTensorInfo(c)}return s}var ND=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let i=0;i<n.length;i++)n[i]=e[t[i]];this.outputShape=n,this.rank=n.length;let o=Xe(this.rank),s=Vbe(t);this.userCode=`
|
|
void main() {
|
|
${o} resRC = getOutputCoords();
|
|
setOutput(getA(${s}));
|
|
}
|
|
`}};function Vbe(r){let e=r.length;if(e>6)throw Error(`Transpose for rank ${e} is not yet supported`);let t=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],n=new Array(e);for(let o=0;o<r.length;o++)n[r[o]]=t[o];return n.join()}var AD=class{constructor(e,t){this.variableNames=["A"];this.packedInputs=!0;this.packedOutput=!0;let n=new Array(e.length);for(let p=0;p<n.length;p++)n[p]=e[t[p]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let o=Xe(this.rank),s=gD("rc",this.rank),i=new Array(this.rank);for(let p=0;p<t.length;p++)i[t[p]]=s[p];let a=`vec2(${i.slice(-2).join()})`,l=`++${s[this.rank-1]} < ${n[this.rank-1]}`,u=`getChannel(getA(${i.join()}), ${a})`;this.userCode=`
|
|
void main() {
|
|
${o} rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result[0] = ${u};
|
|
if(${l}) {
|
|
result[1] = ${u};
|
|
}
|
|
--${s[this.rank-1]};
|
|
if(++${s[this.rank-2]} < ${n[this.rank-2]}) {
|
|
result[2] = ${u};
|
|
if(${l}) {
|
|
result[3] = ${u};
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};function Ip(r,e,t){let n=X().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new AD(r.shape,e):new ND(r.shape,e);return t.runWebGLProgram(n,[r],r.dtype)}function B4(r,e,t,n){let o=e,s=r.shape.length,i=x.parseAxisParam(o,r.shape),a=i,l=C.getAxesPermutation(a,s),u=l!=null,p=r;u&&(p=Ip(r,l,n),a=C.getInnerMostAxes(a.length,s)),C.assertAxesAreInnerMostDims("sum",a,s);let[c,m]=C.computeOutAndReduceShapes(p.shape,a),f=c;t&&(f=C.expandShapeToKeepDim(c,i));let d=x.sizeFromShape(m),g=x.sizeFromShape(r.shape)/d,b=de({inputs:{x:p},attrs:{shape:[g,d]},backend:n}),y=gc(r.dtype),T=Co(b,y,"sum",n),k=de({inputs:{x:T},attrs:{shape:f},backend:n});return n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(T),u&&n.disposeIntermediateTensorInfo(p),k}function dm(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,keepDims:i}=n;return B4(o,s,i,t)}var O4={kernelName:Ca,backendName:"webgl",kernelFunc:dm};function rr(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{perm:s}=n,i=t,a=o.shape.length,l=new Array(a);for(let p=0;p<l.length;p++)l[p]=o.shape[s[p]];let u;if(i.shouldExecuteOnCPU([o])){let c=i.texData.get(o.dataId).values,m=fm(c,o.shape,o.dtype,s,l);u=i.makeTensorInfo(l,o.dtype);let f=i.texData.get(u.dataId);f.values=m}else u=Ip(o,s,i);return u}var z4={kernelName:ps,backendName:"webgl",kernelFunc:rr};var DD=1e3;function hm({a:r,b:e,transposeA:t,transposeB:n,backend:o,bias:s=null,preluActivationWeights:i=null,leakyreluAlpha:a=0,activation:l=null}){let u=r.shape.length,p=e.shape.length,c=t?r.shape[u-2]:r.shape[u-1],m=n?e.shape[p-1]:e.shape[p-2],f=t?r.shape[u-1]:r.shape[u-2],d=n?e.shape[p-2]:e.shape[p-1],h=r.shape.slice(0,-2),g=e.shape.slice(0,-2),b=x.sizeFromShape(h),y=x.sizeFromShape(g),T=b===y||b===1||y===1;x.assert(u>=2&&p>=2&&T,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${h}) and (${g}).`);let I=(b>y?r.shape.slice(0,-2):e.shape.slice(0,-2)).concat([f,d]);x.assert(c===m,()=>`Error in matMul: inner shapes (${c}) and (${m}) of Tensors with shapes ${r.shape} and ${e.shape} and transposeA=${t} and transposeB=${n} must match.`);let S=t?[b,c,f]:[b,f,c],N=n?[y,d,m]:[y,m,d],F=de({inputs:{x:r},backend:o,attrs:{shape:S}}),$=de({inputs:{x:e},backend:o,attrs:{shape:N}}),O=[F,$],V=Math.max(b,y),q=t?F.shape[1]:F.shape[2],W=s!=null,Y=i!=null,Z=l==="leakyrelu",J=l!=null?kp(l,!0):null,se=W||Y||Z||J!=null,ee;if((f===1||d===1)&&q>DD&&se===!1){let ae=F,ce=$;t&&(ae=rr({inputs:{x:F},backend:o,attrs:{perm:[0,2,1]}}),O.push(ae)),n&&(ce=rr({inputs:{x:$},backend:o,attrs:{perm:[0,2,1]}}),O.push(ce));let ye=d!==1,me=d===1,xe=ae;ye&&(xe=de({inputs:{x:ae},backend:o,attrs:{shape:[V,q,1]}}),O.push(xe));let ke=d===1?2:1,we=ce;me&&(we=de({inputs:{x:ce},backend:o,attrs:{shape:[V,1,q]}}),O.push(we));let Ne=$y({inputs:{a:xe,b:we},backend:o});ee=dm({inputs:{x:Ne},backend:o,attrs:{axis:ke,keepDims:!0}}),O.push(Ne)}else{let ae=Mr(r.dtype,e.dtype),ce=new Ly(S,N,[V,f,d],t,n,W,J,Y,Z),ye=[F,$];if(s!=null&&ye.push(s),Y&&ye.push(i),Z){let me=o.makeTensorInfo([],"float32",x.createScalarValue(a,"float32"));ye.push(me),O.push(me)}ee=o.runWebGLProgram(ce,ye,ae)}let le=de({inputs:{x:ee},backend:o,attrs:{shape:I}});O.push(ee);for(let ae of O)o.disposeIntermediateTensorInfo(ae);return le}function Ube(r){let{inputs:e,backend:t,attrs:n}=r,{a:o,b:s,bias:i,preluActivationWeights:a}=e,{transposeA:l,transposeB:u,activation:p,leakyreluAlpha:c}=n;return hm({a:o,b:s,transposeA:l,transposeB:u,backend:t,bias:i,preluActivationWeights:a,leakyreluAlpha:c,activation:p})}var G4={kernelName:ki,backendName:"webgl",kernelFunc:Ube};var W4="return abs(x);";function jbe(r){let{inputs:e,backend:t}=r,{x:n}=e;if(t.shouldExecuteOnCPU([n])&&n.dtype!=="complex64"){let s=t.texData.get(n.dataId),i=vI(s.values);return t.makeTensorInfo(n.shape,n.dtype,i)}let o;return X().getBool("WEBGL_PACK_UNARY_OPERATIONS")?o=new Qa(n.shape,W4):o=new mo(n.shape,W4),t.runWebGLProgram(o,[n],n.dtype)}var K4={kernelName:Gs,backendName:"webgl",kernelFunc:jbe};var Hbe=Zr+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return acos(x);
|
|
`,qbe=Ae({opSnippet:Hbe}),V4={kernelName:ol,backendName:"webgl",kernelFunc:qbe};var Xbe=Zr+`
|
|
if (x < 1.0) return NAN;
|
|
return log(x + sqrt(x * x - 1.0));`,Ybe=Ae({opSnippet:Xbe}),U4={kernelName:sl,backendName:"webgl",kernelFunc:Ybe};var j4="return a + b;",Zbe=Tt({opSnippet:j4,packedOpSnippet:j4,supportsComplex:!0,cpuKernelImpl:EU}),H4={kernelName:so,backendName:"webgl",kernelFunc:Zbe};var ED=class{constructor(e,t){this.outputShape=[];this.outputShape=e,this.variableNames=t.map((s,i)=>`T${i}`);let n=[];this.variableNames.forEach(s=>{n.push(`float v${s} = get${s}AtOutCoords();`)});let o=this.variableNames.map(s=>`v${s}`).join(" + ");this.userCode=`
|
|
void main() {
|
|
${n.join(`
|
|
`)}
|
|
|
|
float result = ${o};
|
|
setOutput(result);
|
|
}
|
|
`}};var MD=class{constructor(e,t){this.outputShape=[];this.packedInputs=!0;this.packedOutput=!0;this.outputShape=e,this.variableNames=t.map((s,i)=>`T${i}`);let n=[];this.variableNames.forEach(s=>{n.push(`vec4 v${s} = get${s}AtOutCoords();`)});let o=this.variableNames.map(s=>`v${s}`).join(" + ");this.userCode=`
|
|
void main() {
|
|
${n.join(`
|
|
`)}
|
|
|
|
vec4 result = ${o};
|
|
setOutput(result);
|
|
}
|
|
`}};function DI(r){let{inputs:e,backend:t}=r,n=e;if(n.length===1)return vr({inputs:{x:n[0]},backend:t});if(n.length>X().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let l=Math.floor(n.length/2),u=DI({inputs:n.slice(0,l),backend:t}),p=DI({inputs:n.slice(l),backend:t});return DI({inputs:[u,p],backend:t})}let o=n.map(l=>l.dtype).reduce((l,u)=>Mr(l,u)),s=n.map(l=>l.shape),a=X().getBool("WEBGL_PACK")?new MD(n[0].shape,s):new ED(n[0].shape,s);return t.runWebGLProgram(a,n,o)}var q4={kernelName:Ws,backendName:"webgl",kernelFunc:DI};function Jbe(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,keepDims:i}=n,a=o.shape.length,l=x.parseAxisParam(s,o.shape),u=l,p=C.getAxesPermutation(u,a),c=o;p!=null&&(c=rr({inputs:{x:o},backend:t,attrs:{perm:p}}),u=C.getInnerMostAxes(u.length,a)),C.assertAxesAreInnerMostDims("all",u,a);let[m,f]=C.computeOutAndReduceShapes(c.shape,u),d=x.sizeFromShape(f),h=de({inputs:{x:c},backend:t,attrs:{shape:[-1,d]}}),g=Co(h,h.dtype,"all",t),b;if(i){let y=C.expandShapeToKeepDim(m,l);b=de({inputs:{x:g},backend:t,attrs:{shape:y}})}else b=de({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),p!=null&&t.disposeIntermediateTensorInfo(c),b}var X4={kernelName:al,backendName:"webgl",kernelFunc:Jbe};function Qbe(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,keepDims:i}=n,a=o.shape.length,l=x.parseAxisParam(s,o.shape),u=l,p=C.getAxesPermutation(u,a),c=o;p!=null&&(c=rr({inputs:{x:o},backend:t,attrs:{perm:p}}),u=C.getInnerMostAxes(u.length,a)),C.assertAxesAreInnerMostDims("any",u,a);let[m,f]=C.computeOutAndReduceShapes(c.shape,u),d=x.sizeFromShape(f),h=de({inputs:{x:c},backend:t,attrs:{shape:[-1,d]}}),g=Co(h,h.dtype,"any",t),b;if(i){let y=C.expandShapeToKeepDim(m,l);b=de({inputs:{x:g},backend:t,attrs:{shape:y}})}else b=de({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),p!=null&&t.disposeIntermediateTensorInfo(c),b}var Y4={kernelName:il,backendName:"webgl",kernelFunc:Qbe};var FD=class{constructor(e,t,n){this.variableNames=["A"];let{windowSize:o,batchSize:s,outSize:i}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[s,i];let a=t==="max"?">":"<",l=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * ${o};
|
|
|
|
int bestIndex = inOffset;
|
|
float bestValue = getA(batch, bestIndex);
|
|
|
|
for (int i = 0; i < ${o}; i++) {
|
|
int inIdx = ${l};
|
|
float candidate = getA(batch, inIdx);
|
|
if (candidate ${a} bestValue) {
|
|
bestValue = candidate;
|
|
bestIndex = inIdx;
|
|
}
|
|
}
|
|
setOutput(float(bestIndex));
|
|
}
|
|
`}};var RD=class{constructor(e,t,n,o){this.variableNames=["A"];this.packedInputs=!0;this.packedOutput=!0;x.assert(e.length>2,()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`);let s=e[e.length-1],i=Math.ceil(s/t);this.outputShape=e.slice(0,-1),i>1&&this.outputShape.push(i),o||this.variableNames.push("bestIndicesA");let a=this.outputShape,l=a.length,u=Xe(l),p=Ir("coords",l),c,m;if(i===1){m=l+1;let F=Xe(m);c=`
|
|
${F} sourceLocR = ${F}(${p.join()}, 0);
|
|
++${p[l-1]};
|
|
${F} sourceLocG = ${F}(${p.join()}, 0);
|
|
++${p[l-2]};
|
|
${F} sourceLocA = ${F}(${p.join()}, 0);
|
|
--${p[l-1]};
|
|
${F} sourceLocB = ${F}(${p.join()}, 0);
|
|
--${p[l-2]};`}else m=l,c=`
|
|
${u} sourceLocR = coords;
|
|
++${p[l-1]};
|
|
${u} sourceLocG = coords;
|
|
++${p[l-2]};
|
|
${u} sourceLocA = coords;
|
|
--${p[l-1]};
|
|
${u} sourceLocB = coords;
|
|
--${p[l-2]};`;let f=["x","y","z","w","u","v"].slice(0,m),d="."+f[m-1],h=f.map(F=>"int "+F),g=Ir("sourceLocR",m-1).concat("inIdx.r"),b=Ir("sourceLocG",m-1).concat("inIdx.g"),y=Ir("sourceLocB",m-1).concat("inIdx.b"),T=Ir("sourceLocA",m-1).concat("inIdx.a"),k=n==="max"?"greaterThan":"lessThan",I=o?"":`
|
|
inIdx = round(vec4(getBestIndicesAChannel(${g.join()}),
|
|
getBestIndicesAChannel(${b.join()}),
|
|
getBestIndicesAChannel(${y.join()}),
|
|
getBestIndicesAChannel(${T.join()})));`,S=`vec4(
|
|
getAChannel(${g.join()}),
|
|
hasNextCol ? getAChannel(${b.join()}) : 0.,
|
|
hasNextRow ? getAChannel(${y.join()}) : 0.,
|
|
hasNextRow && hasNextCol ? getAChannel(${T.join()}) : 0.)`,N=o?"":`
|
|
float getBestIndicesAChannel(${h.join()}) {
|
|
return getChannel(getBestIndicesA(${f.join()}),
|
|
vec2(${f.slice(-2).join()}));
|
|
}`;this.userCode=`
|
|
float getAChannel(${h.join()}) {
|
|
return getChannel(getA(${f.join()}),
|
|
vec2(${f.slice(-2).join()}));
|
|
}
|
|
${N}
|
|
void main() {
|
|
${u} coords = getOutputCoords();
|
|
bool hasNextCol = ${p[l-1]} < ${a[l-1]-1};
|
|
bool hasNextRow = ${p[l-2]} < ${a[l-2]-1};
|
|
${c}
|
|
ivec4 srcIdx = ivec4(sourceLocR${d}, sourceLocG${d},
|
|
sourceLocB${d}, sourceLocA${d}) * ${t};
|
|
ivec4 inIdx = srcIdx;
|
|
vec4 bestIndex = vec4(inIdx);
|
|
vec4 bestValue = ${S};
|
|
|
|
for (int i = 0; i < ${t}; i++) {
|
|
inIdx = srcIdx;
|
|
${I}
|
|
vec4 candidate = ${S};
|
|
bvec4 nan = isnan(candidate);
|
|
bvec4 replace = bvec4(
|
|
vec4(${k}(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);
|
|
}
|
|
`}};function Z4(r,e,t,n=null){let o=e.shape[0],s=e.shape[1];n!=null&&(o=n.shape[0],s=n.shape[1]);let i=C.computeOptimalWindowSize(s),a={windowSize:i,inSize:s,batchSize:o,outSize:Math.ceil(s/i)},l=new FD(a,t,n==null),u=[e];n!=null&&u.push(n);let p=r.runWebGLProgram(l,u,"int32");if(p.shape[1]===1)return p;let c=Z4(r,e,t,p);return r.disposeIntermediateTensorInfo(p),c}function J4(r,e,t,n=null){let o=n!=null?n.shape:e.shape,s=o[o.length-1],i=C.computeOptimalWindowSize(s),a=new RD(o,i,t,n==null),l=n==null?[e]:[e,n],u=r.runWebGLProgram(a,l,"int32");if(u.shape.length===e.shape.length){let p=J4(r,e,t,u);return r.disposeIntermediateTensorInfo(u),p}return u}function EI(r,e,t,n){let o=[t];if(C.assertAxesAreInnerMostDims("arg"+n.charAt(0).toUpperCase()+n.slice(1),o,e.shape.length),!X().getBool("WEBGL_PACK_REDUCE")||e.shape.length<=2){let s=[],[i,a]=C.computeOutAndReduceShapes(e.shape,o),l=x.sizeFromShape(a),u=de({inputs:{x:e},backend:r,attrs:{shape:[-1,l]}});s.push(u);let p=Z4(r,u,n);s.push(p);let c=de({inputs:{x:p},backend:r,attrs:{shape:i}});return s.forEach(m=>r.disposeIntermediateTensorInfo(m)),c}return J4(r,e,n)}function eye(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s}=n,i=x.parseAxisParam(s,o.shape),a=C.getAxesPermutation(i,o.shape.length),l=o,u=[];a!=null&&(l=rr({inputs:{x:o},backend:t,attrs:{perm:a}}),u.push(l),i=C.getInnerMostAxes(i.length,l.shape.length)),C.assertAxesAreInnerMostDims("argMax",[i[0]],l.shape.length);let p=EI(t,l,i[0],"max");return u.forEach(c=>t.disposeIntermediateTensorInfo(c)),p}var Q4={kernelName:Ks,backendName:"webgl",kernelFunc:eye};function tye(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s}=n,i=x.parseAxisParam(s,o.shape),a=C.getAxesPermutation(i,o.shape.length),l=o,u=[];a!=null&&(l=rr({inputs:{x:o},backend:t,attrs:{perm:a}}),u.push(l),i=C.getInnerMostAxes(i.length,l.shape.length)),C.assertAxesAreInnerMostDims("argMin",[i[0]],l.shape.length);let p=EI(t,l,i[0],"min");return u.forEach(c=>t.disposeIntermediateTensorInfo(c)),p}var ej={kernelName:Ru,backendName:"webgl",kernelFunc:tye};var rye=Zr+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return asin(x);
|
|
`,nye=Ae({opSnippet:rye}),tj={kernelName:ll,backendName:"webgl",kernelFunc:nye};var oye=Zr+"return log(x + sqrt(x * x + 1.0));",sye=Ae({opSnippet:oye}),rj={kernelName:ul,backendName:"webgl",kernelFunc:sye};var aye=Zr+`
|
|
return atan(x);
|
|
`,iye=Ae({opSnippet:aye}),nj={kernelName:pl,backendName:"webgl",kernelFunc:iye};var lye=M4+`
|
|
return atan(a, b);
|
|
`,uye=`
|
|
vec4 result = atan(a, b);
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+F4+`
|
|
return result;
|
|
`,pye=Tt({opSnippet:lye,packedOpSnippet:uye}),oj={kernelName:ml,backendName:"webgl",kernelFunc:pye};var cye=Zr+`
|
|
if ((x < -1.0) || (x > 1.0)) return NAN;
|
|
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,mye=Ae({opSnippet:cye}),sj={kernelName:cl,backendName:"webgl",kernelFunc:mye};var $i=class{constructor(e,t,n,o=!1,s=!1){this.variableNames=["x"];if(t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let i=e.filterWidth,a=e.strideHeight,l=e.strideWidth,u=e.dilationHeight,p=e.dilationWidth,c=e.effectiveFilterHeight,m=e.effectiveFilterWidth,f=e.padInfo.top,d=e.padInfo.left;this.outputShape=e.outShape;let h=t==="avg",g=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,b=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`,y="0.0";if(h||(y="-1.0 / 1e-20"),n){let F=">=";this.userCode=`
|
|
const ivec2 strides = ivec2(${a}, ${l});
|
|
const ivec2 pads = ivec2(${f}, ${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 < ${c};
|
|
wR += ${u}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${m};
|
|
wC += ${p}) {
|
|
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 ${F} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${o?s?g:b:`wR * ${m} + wC`};
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;return}let T="max",k=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(k="avgValue / count");let I=Math.floor(i/4)*4,S=i%4,N=`
|
|
if (${h}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${T}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec2 strides = ivec2(${a}, ${l});
|
|
const ivec2 pads = ivec2(${f}, ${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 < ${c};
|
|
wR += ${u}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${I}; wC += 4) {
|
|
int xC = xCCorner + wC * ${p};
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${p}, d),
|
|
getValue(batch, xR, xC + 2 * ${p}, d),
|
|
getValue(batch, xR, xC + 3 * ${p}, d)
|
|
);
|
|
|
|
${N}
|
|
}
|
|
|
|
int xC = xCCorner + ${I};
|
|
if (${S===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${N}
|
|
} else if (${S===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${p}, d),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${N}
|
|
} else if (${S===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${p}, d),
|
|
getValue(batch, xR, xC + 2 * ${p}, d),
|
|
initializationValue
|
|
);
|
|
|
|
${N}
|
|
}
|
|
}
|
|
setOutput(${k});
|
|
}
|
|
`}},gm=class{constructor(e,t,n,o=!1,s=!1){this.variableNames=["x"];if(t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let i=e.filterWidth,a=e.strideDepth,l=e.strideHeight,u=e.strideWidth,p=e.dilationDepth,c=e.dilationHeight,m=e.dilationWidth,f=e.effectiveFilterDepth,d=e.effectiveFilterHeight,h=e.effectiveFilterWidth,g=e.padInfo.front,b=e.padInfo.top,y=e.padInfo.left;this.outputShape=e.outShape;let T=t==="avg",k="0.0";if(T||(k="-1.0 / 1e-20"),n){let O=">=";this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${a}, ${l}, ${u});
|
|
const ivec3 pads = ivec3(${g}, ${b}, ${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 < ${f};
|
|
wD += ${p}) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${d};
|
|
wR += ${c}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${h};
|
|
wC += ${m}) {
|
|
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 ${O} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${o?s?`(((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} * ${h} +
|
|
wR * ${h} + wC`};
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;return}let I="max",S=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(S="avgValue / count");let N=Math.floor(i/4)*4,F=i%4,$=`
|
|
if (${T}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${I}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${a}, ${l}, ${u});
|
|
const ivec3 pads = ivec3(${g}, ${b}, ${y});
|
|
const float initializationValue = ${k};
|
|
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(${k});
|
|
float avgValue = 0.0;
|
|
count = 0.0;
|
|
|
|
for (int wD = 0; wD < ${f};
|
|
wD += ${p}) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${d};
|
|
wR += ${c}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${N}; wC += 4) {
|
|
int xC = xCCorner + wC * ${m};
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${m}, ch),
|
|
getValue(batch, xD, xR, xC + 2 * ${m}, ch),
|
|
getValue(batch, xD, xR, xC + 3 * ${m}, ch)
|
|
);
|
|
|
|
${$}
|
|
}
|
|
|
|
int xC = xCCorner + ${N};
|
|
if (${F===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${$}
|
|
} else if (${F===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${m}, ch),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${$}
|
|
} else if (${F===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${m}, ch),
|
|
getValue(batch, xD, xR, xC + 2 * ${m}, ch),
|
|
initializationValue
|
|
);
|
|
|
|
${$}
|
|
}
|
|
}
|
|
setOutput(${S});
|
|
}
|
|
}
|
|
`}};function fye(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e;Za(o,"avgPool");let{filterSize:s,strides:i,pad:a,dimRoundingMode:l}=n,u=1;x.assert(C.eitherStridesOrDilationsAreOne(i,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let p=C.computePool2DInfo(o.shape,s,i,u,a,l);if(p.filterWidth===1&&p.filterHeight===1&&x.arraysEqual(p.inShape,p.outShape))return vr({inputs:{x:o},backend:t});let c=new $i(p,"avg",!1);return t.runWebGLProgram(c,[o],"float32")}var aj={kernelName:Vs,backendName:"webgl",kernelFunc:fye};function dye(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{filterSize:s,strides:i,pad:a,dimRoundingMode:l,dataFormat:u}=n,p=[1,1,1],c=C.computePool3DInfo(o.shape,s,i,p,a,l,u),m=new gm(c,"avg",!1);return t.runWebGLProgram(m,[o],"float32")}var ij={kernelName:Lu,backendName:"webgl",kernelFunc:dye};var LD=class{constructor(e){this.variableNames=["dy"];this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,o=e.strideHeight,s=e.strideWidth,i=e.dilationHeight,a=e.dilationWidth,l=e.effectiveFilterHeight,u=e.effectiveFilterWidth,p=l-1-e.padInfo.top,c=u-1-e.padInfo.left,m=1/(t*n);this.userCode=`
|
|
const ivec2 pads = ivec2(${p}, ${c});
|
|
const float avgMultiplier = float(${m});
|
|
|
|
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 < ${l};
|
|
wR += ${i}) {
|
|
float dyR = float(dyRCorner + wR) / ${o}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${u};
|
|
wC+= ${a}) {
|
|
float dyC = float(dyCCorner + wC) / ${s}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(b, idyR, idyC, d);
|
|
|
|
dotProd += dyValue * avgMultiplier;
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},$D=class{constructor(e){this.variableNames=["dy"];this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,o=e.filterWidth,s=e.strideDepth,i=e.strideHeight,a=e.strideWidth,l=e.dilationDepth,u=e.dilationHeight,p=e.dilationWidth,c=e.effectiveFilterDepth,m=e.effectiveFilterHeight,f=e.effectiveFilterWidth,d=c-1-e.padInfo.front,h=m-1-e.padInfo.top,g=f-1-e.padInfo.left,b=1/(t*n*o);this.userCode=`
|
|
const ivec3 pads = ivec3(${d}, ${h}, ${g});
|
|
const float avgMultiplier = float(${b});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyDCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
// Convolve dy(?, ?, ?, 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 < ${c};
|
|
wD += ${l}) {
|
|
float dyD = float(dyDCorner + wD) / ${s}.0;
|
|
|
|
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyD = int(dyD);
|
|
|
|
for (int wR = 0; wR < ${m};
|
|
wR += ${u}) {
|
|
float dyR = float(dyRCorner + wR) / ${i}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
|
|
fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${f};
|
|
wC += ${p}) {
|
|
float dyC = float(dyCCorner + wC) / ${a}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
|
|
|
|
dotProd += dyValue * avgMultiplier;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function hye(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,input:s}=e,i=s,{filterSize:a,strides:l,pad:u,dimRoundingMode:p}=n,c=[1,1,1],m=C.computePool3DInfo(i.shape,a,l,c,u,p),f=new $D(m);return t.runWebGLProgram(f,[o],i.dtype)}var lj={kernelName:af,backendName:"webgl",kernelFunc:hye};function gye(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,input:s}=e,i=s;Za([o,s],"avgPoolGrad");let{filterSize:a,strides:l,pad:u}=n,p=C.computePool2DInfo(i.shape,a,l,1,u),c=new LD(p);return t.runWebGLProgram(c,[o],i.dtype)}var uj={kernelName:sf,backendName:"webgl",kernelFunc:gye};function bye(r){let{inputs:e,backend:t,attrs:n}=r,{a:o,b:s}=e,{transposeA:i,transposeB:a}=n;return hm({a:o,b:s,transposeA:i,transposeB:a,backend:t})}var pj={kernelName:Us,backendName:"webgl",kernelFunc:bye};var PD=class{constructor(e,t,n,o,s,i){this.outputShape=[];this.variableNames=["x","mean","variance"],C.assertAndGetBroadcastShape(e,t),C.assertAndGetBroadcastShape(e,n);let a="0.0";o!=null&&(C.assertAndGetBroadcastShape(e,o),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let l="1.0";s!=null&&(C.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
float x = getXAtOutCoords();
|
|
float mean = getMeanAtOutCoords();
|
|
float variance = getVarianceAtOutCoords();
|
|
float offset = ${a};
|
|
float scale = ${l};
|
|
float inv = scale * inversesqrt(variance + float(${i}));
|
|
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
|
|
}
|
|
`}};var BD=class{constructor(e,t,n,o,s,i){this.packedInputs=!0;this.packedOutput=!0;this.variableNames=["x","mean","variance"],C.assertAndGetBroadcastShape(e,t),C.assertAndGetBroadcastShape(e,n);let a="vec4(0.0)";o!=null&&(C.assertAndGetBroadcastShape(e,o),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");let l="vec4(1.0)";s!=null&&(C.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
vec4 offset = ${a};
|
|
vec4 scale = ${l};
|
|
|
|
vec4 x = getXAtOutCoords();
|
|
vec4 mean = getMeanAtOutCoords();
|
|
vec4 variance = getVarianceAtOutCoords();
|
|
|
|
vec4 inv = scale * inversesqrt(variance + vec4(${i}));
|
|
|
|
setOutput((x - mean) * inv + offset);
|
|
}
|
|
`}};var yye=({inputs:r,backend:e,attrs:t})=>{let{x:n,mean:o,variance:s,offset:i,scale:a}=r;x.assert(o.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),x.assert(i==null||o.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),x.assert(a==null||o.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=t;l==null&&(l=.001);let u=[n,o,s],p=null;i!=null&&(p=i.shape,u.push(i));let c=null;a!=null&&(c=a.shape,u.push(a));let m=X().getBool("WEBGL_PACK_NORMALIZATION")?new BD(n.shape,o.shape,s.shape,p,c,l):new PD(n.shape,o.shape,s.shape,p,c,l);return e.runWebGLProgram(m,u,u[0].dtype)},cj={kernelName:ta,backendName:"webgl",kernelFunc:yye};var OD=class{constructor(e){this.variableNames=["source"];this.outputShape=e,this.rank=e.length;let t=Xe(this.rank),n=`uniform int start[${this.rank}];`,o=xye(this.rank),s,i=e.map((a,l)=>`sourceLoc.${zD[l]} = start[${l}] + coords.${zD[l]};`);s=`
|
|
${t} sourceLoc;
|
|
${t} coords = getOutputCoords();
|
|
${i.join(`
|
|
`)}
|
|
`,this.userCode=`
|
|
${n}
|
|
void main() {
|
|
${s}
|
|
setOutput(getSource(${o}));
|
|
}
|
|
`}getCustomSetupFunc(e){if(e.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${e.length})`);return(t,n)=>{this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(n,"start"),this.startLoc==null)||t.gl.uniform1iv(this.startLoc,e)}}},zD=["x","y","z","w","u","v"];function xye(r){if(r===1)return"sourceLoc";if(r<=6)return zD.slice(0,r).map(e=>"sourceLoc."+e).join(",");throw Error(`Slicing for rank ${r} is not yet supported`)}var GD=class{constructor(e){this.variableNames=["source"];this.packedInputs=!0;this.packedOutput=!0;this.outputShape=e,this.rank=e.length;let t=Xe(this.rank),n=Ir("coords",this.rank),o=Ir("sourceLoc",this.rank),s=this.rank===1?"sourceLoc":`vec2(${o.slice(-2).join()})`,i=`getChannel(getSource(${o.join()}), ${s})`,a=`
|
|
result.x = ${i};
|
|
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
|
|
++${o[this.rank-1]};
|
|
result.y = ${i};
|
|
--${o[this.rank-1]};
|
|
}
|
|
`,l=this.rank===1?"":`
|
|
--${n[this.rank-1]};
|
|
if (++${n[this.rank-2]} < ${e[this.rank-2]}) {
|
|
++${o[this.rank-2]};
|
|
result.z = ${i};
|
|
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
|
|
++${o[this.rank-1]};
|
|
result.w = ${i};
|
|
}
|
|
}
|
|
`,u=this.rank<=4?`sourceLoc = coords +
|
|
${t}(${e.map((p,c)=>`start[${c}]`).join()});`:e.map((p,c)=>`${o[c]} = ${n[c]} + start[${c}];`).join(`
|
|
`);this.userCode=`
|
|
uniform int start[${this.rank}];
|
|
void main() {
|
|
${t} coords = getOutputCoords();
|
|
${t} sourceLoc;
|
|
${u}
|
|
vec4 result = vec4(0.);
|
|
${a}
|
|
${l}
|
|
setOutput(result);
|
|
}
|
|
`}getCustomSetupFunc(e){if(e.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${e.length})`);return(t,n)=>{this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(n,"start"),this.startLoc==null)||t.gl.uniform1iv(this.startLoc,e)}}};function Tye(r,e,t,n){let o=n.texData.get(r.dataId),s=n.makeTensorInfo(t,r.dtype),i=n.texData.get(s.dataId);Object.assign(i,o),i.refCount=1,i.shape=t,i.dtype=r.dtype;let a=br.computeFlatOffset(e,x.computeStrides(r.shape));o.slice&&(a+=o.slice.flatOffset),i.slice={flatOffset:a,origDataId:o.slice&&o.slice.origDataId||r.dataId};let l=n.dataRefCount.get(i.slice.origDataId)||1;return n.dataRefCount.set(i.slice.origDataId,l+1),s}function hu(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{begin:s,size:i}=n,[a,l]=br.parseSliceParams(o,s,i);if(br.assertParamsValid(o,a,l),x.sizeFromShape(l)===0)return t.makeTensorInfo(l,o.dtype,[]);if(t.shouldExecuteOnCPU([o])||o.dtype==="string"){let c=t.texData.get(o.dataId),m=r4(c.values,a,l,o.shape,o.dtype);return t.makeTensorInfo(l,o.dtype,m)}let{isPacked:u}=t.texData.get(o.dataId),p=br.isSliceContinous(o.shape,a,l);if(u||!p){let c=X().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new GD(l):new OD(l),m=c.getCustomSetupFunc(a);return t.runWebGLProgram(c,[o],o.dtype,m)}return t.uploadToGPU(o.dataId),Tye(o,a,l,t)}var mj={kernelName:Ia,backendName:"webgl",kernelFunc:hu};var kye=r=>{let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{blockShape:s,crops:i}=n;x.assert(o.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let a=s.reduce((y,T)=>y*T),l=C.getReshaped(o.shape,s,a),u=C.getPermuted(l.length,s.length),p=C.getReshapedPermuted(o.shape,s,a),c=C.getSliceBeginCoords(i,s.length),m=C.getSliceSize(p,i,s.length),f=[],d=de({inputs:{x:o},backend:t,attrs:{shape:l}}),h=rr({inputs:{x:d},backend:t,attrs:{perm:u}}),g=de({inputs:{x:h},backend:t,attrs:{shape:p}}),b=hu({inputs:{x:g},backend:t,attrs:{begin:c,size:m}});return f.push(d),f.push(h),f.push(g),f.forEach(y=>t.disposeIntermediateTensorInfo(y)),b},fj={kernelName:$u,backendName:"webgl",kernelFunc:kye};function Iye(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,weights:s}=e,{size:i}=n,a=t.readSync(o.dataId),l=t.readSync(s.dataId),u=II(a,l,s.dtype,s.shape,i);return t.makeTensorInfo([i],s.dtype,u)}var dj={kernelName:lf,backendName:"webgl",kernelFunc:Iye};var vye="return float(a != b);",WD=Tt({opSnippet:vye,cpuKernelImpl:JU,dtype:"bool"}),hj={kernelName:ma,backendName:"webgl",kernelFunc:WD};function gu(r){let{inputs:e,backend:t}=r,{input:n}=e,o=t.texData.get(n.dataId);return vr({inputs:{x:o.complexTensorInfos.real},backend:t})}var gj={kernelName:cc,backendName:"webgl",kernelFunc:gu};var wye="return float(int(x));";function bj(r,e){let t=new mo(r.shape,wye),n=e.runWebGLProgram(t,[r],"int32");return{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}function KD(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{dtype:s}=n;if(s==="complex64"){if(o.dtype==="complex64")return vr({inputs:{x:o},backend:t});let i=Rt(o.shape),a=KD({inputs:{x:o},backend:t,attrs:{dtype:"float32"}}),l=fo({inputs:{real:a,imag:i},backend:t});return i.dispose(),t.disposeIntermediateTensorInfo(a),l}if(o.dtype==="complex64"){let i=gu({inputs:{input:o},backend:t}),a=KD({inputs:{x:i},backend:t,attrs:{dtype:s}});return t.disposeIntermediateTensorInfo(i),a}if(!x.hasEncodingLoss(o.dtype,s)){let i=vr({inputs:{x:o},backend:t});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(s==="int32")return bj(o,t);if(s==="bool"){let i=t.makeTensorInfo([],"bool",x.getTypedArrayFromDType("bool",1)),l=WD({inputs:{a:o,b:i},backend:t});return t.disposeIntermediateTensorInfo(i),l}throw new Error(`Error in Cast: failed to cast ${o.dtype} to ${s}`)}var yj={kernelName:Do,backendName:"webgl",kernelFunc:KD};var xj="return ceil(x);",_ye=Ae({opSnippet:xj,packedOpSnippet:xj,cpuKernelImpl:FU}),Tj={kernelName:Eo,backendName:"webgl",kernelFunc:_ye};var VD=class{constructor(e){this.variableNames=["A"];this.outputShape=e,this.userCode=`
|
|
uniform float minVal;
|
|
uniform float maxVal;
|
|
|
|
void main() {
|
|
float value = getAAtOutCoords();
|
|
if (isnan(value)) {
|
|
setOutput(value);
|
|
return;
|
|
}
|
|
|
|
setOutput(clamp(value, minVal, maxVal));
|
|
}
|
|
`}getCustomSetupFunc(e,t){return(n,o)=>{this.minLoc==null&&(this.minLoc=n.getUniformLocationNoThrow(o,"minVal"),this.maxLoc=n.getUniformLocationNoThrow(o,"maxVal")),n.gl.uniform1f(this.minLoc,e),n.gl.uniform1f(this.maxLoc,t)}}};var UD=class{constructor(e){this.variableNames=["A"];this.packedInputs=!0;this.packedOutput=!0;this.outputShape=e,this.userCode=`
|
|
uniform float minVal;
|
|
uniform float maxVal;
|
|
|
|
void main() {
|
|
vec4 value = getAAtOutCoords();
|
|
|
|
if (any(isnan(value))) {
|
|
setOutput(value);
|
|
return;
|
|
}
|
|
|
|
setOutput(clamp(value, vec4(minVal), vec4(maxVal)));
|
|
}
|
|
`}getCustomSetupFunc(e,t){return(n,o)=>{this.minLoc==null&&(this.minLoc=n.getUniformLocationNoThrow(o,"minVal"),this.maxLoc=n.getUniformLocationNoThrow(o,"maxVal")),n.gl.uniform1f(this.minLoc,e),n.gl.uniform1f(this.maxLoc,t)}}};function Cye(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{clipValueMin:s,clipValueMax:i}=n,a;X().getBool("WEBGL_PACK_CLIP")?a=new UD(o.shape):a=new VD(o.shape);let l=a.getCustomSetupFunc(s,i);return t.runWebGLProgram(a,[o],o.dtype,l)}var kj={kernelName:us,backendName:"webgl",kernelFunc:Cye};var jD=class{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))
|
|
);
|
|
}
|
|
`}};function Ij(r,e){return{dataId:e.dataId,dtype:e.dtype,shape:r.shape}}function Sye(r){let{inputs:e,backend:t}=r,{x:n}=e,o=t.texData.get(n.dataId),s=new jD(n.shape),i=[Ij(n,o.complexTensorInfos.real),Ij(n,o.complexTensorInfos.imag)];return t.runWebGLProgram(s,i,i[0].dtype)}var vj={kernelName:Pu,backendName:"webgl",kernelFunc:Sye};var HD=class{constructor(e){this.outputShape=[];this.outputShape=C.computeOutShape(e,1),this.variableNames=e.map((i,a)=>`T${a}`);let t=new Array(e.length-1);t[0]=e[0][1];for(let i=1;i<t.length;i++)t[i]=t[i-1]+e[i][1];let n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let i=1;i<t.length;i++){let a=t[i-1];n.push(`else if (yC < ${t[i]}) setOutput(getT${i}(yR, yC-${a}));`)}let o=t.length,s=t[t.length-1];n.push(`else setOutput(getT${o}(yR, yC-${s}));`),this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int yR = coords.x;
|
|
int yC = coords.y;
|
|
|
|
${n.join(`
|
|
`)}
|
|
}
|
|
`}};var qD=class{constructor(e,t){this.packedInputs=!0;this.packedOutput=!0;this.outputShape=[];this.outputShape=C.computeOutShape(e,t);let n=this.outputShape,o=n.length,s=Xe(o),i=Ir("coords",o),a=["x","y","z","w","u","v"].slice(0,o);this.variableNames=e.map((h,g)=>`T${g}`);let l=new Array(e.length-1);l[0]=e[0][t];for(let h=1;h<l.length;h++)l[h]=l[h-1]+e[h][t];let u=a[t],p=a.slice(-2),c=a.join(),m=`if (${u} < ${l[0]}) {
|
|
return getChannel(
|
|
getT0(${c}), vec2(${p.join()}));
|
|
}`;for(let h=1;h<l.length;h++){let g=l[h-1];m+=`
|
|
if (${u} < ${l[h]} && ${u} >= ${l[h-1]}) {
|
|
return getChannel(
|
|
getT${h}(${MI(a,u,g)}),
|
|
vec2(${MI(p,u,g)}));
|
|
}`}let f=l.length,d=l[l.length-1];m+=`
|
|
return getChannel(
|
|
getT${f}(${MI(a,u,d)}),
|
|
vec2(${MI(p,u,d)}));`,this.userCode=`
|
|
float getValue(${a.map(h=>"int "+h)}) {
|
|
${m}
|
|
}
|
|
|
|
void main() {
|
|
${s} coords = getOutputCoords();
|
|
vec4 result = vec4(getValue(${i}), 0., 0., 0.);
|
|
|
|
${i[o-1]} = ${i[o-1]} + 1;
|
|
if (${i[o-1]} < ${n[o-1]}) {
|
|
result.g = getValue(${i});
|
|
}
|
|
|
|
${i[o-2]} = ${i[o-2]} + 1;
|
|
if (${i[o-2]} < ${n[o-2]}) {
|
|
result.a = getValue(${i});
|
|
}
|
|
|
|
${i[o-1]} = ${i[o-1]} - 1;
|
|
if (${i[o-2]} < ${n[o-2]} &&
|
|
${i[o-1]} < ${n[o-1]}) {
|
|
result.b = getValue(${i});
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};function MI(r,e,t){let n=r.indexOf(e);return r.map((s,i)=>i===n?`${s} - ${t}`:s).join()}function bm(r){let{inputs:e,backend:t}=r,{input:n}=e,o=t.texData.get(n.dataId);return vr({inputs:{x:o.complexTensorInfos.imag},backend:t})}var wj={kernelName:Tf,backendName:"webgl",kernelFunc:bm};function ym(r,e,t){let n=r[0].dtype;if(n==="complex64"){let p=r.map(h=>gu({inputs:{input:h},backend:t})),c=r.map(h=>bm({inputs:{input:h},backend:t})),m=ym(p,e,t),f=ym(c,e,t),d=fo({inputs:{real:m,imag:f},backend:t});return p.forEach(h=>t.disposeIntermediateTensorInfo(h)),c.forEach(h=>t.disposeIntermediateTensorInfo(h)),t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f),d}let o=t.shouldExecuteOnCPU(r);if(n==="string"&&(o=!0),o){let p=r.map(b=>{let y=x.sizeFromShape(b.shape.slice(e));return de({inputs:{x:b},backend:t,attrs:{shape:[-1,y]}})}),c=p.map(b=>({vals:t.readSync(b.dataId),shape:b.shape})),m=C.computeOutShape(p.map(b=>b.shape),1),f=p[0].shape[0]===1,d=RU(c,m,n,f),h=C.computeOutShape(r.map(b=>b.shape),e),g=t.makeTensorInfo(h,n,d);return p.forEach(b=>t.disposeIntermediateTensorInfo(b)),g}if(r.length>X().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let p=Math.floor(r.length/2),c=ym(r.slice(0,p),e,t),m=ym(r.slice(p),e,t),f=ym([c,m],e,t);return t.disposeIntermediateTensorInfo(c),t.disposeIntermediateTensorInfo(m),f}if(X().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&r[0].shape.length>1){let p=new qD(r.map(c=>c.shape),e);return t.runWebGLProgram(p,r,n)}let{tensors2D:s,outShape:i}=Nye(r,e,t),a=new HD(s.map(p=>p.shape)),l=t.runWebGLProgram(a,s,n);s.forEach(p=>t.disposeIntermediateTensorInfo(p));let u=de({inputs:{x:l},attrs:{shape:i},backend:t});return t.disposeIntermediateTensorInfo(l),u}function Nye(r,e,t){let n=C.computeOutShape(r.map(s=>s.shape),e);return{tensors2D:r.map(s=>de({inputs:{x:s},attrs:{shape:[-1,x.sizeFromShape(s.shape.slice(e))]},backend:t})),outShape:n}}function XD(r){let{inputs:e,backend:t,attrs:n}=r,{axis:o}=n,s=x.parseAxisParam(o,e[0].shape)[0],i=C.computeOutShape(e.map(u=>u.shape),s);if(x.sizeFromShape(i)===0)return t.makeTensorInfo(i,e[0].dtype,[]);let a=e.filter(u=>x.sizeFromShape(u.shape)>0);if(a.length===1)return vr({inputs:{x:a[0]},backend:t});let l=a.map(u=>u.shape);return C.assertParamsConsistent(l,s),ym(a,s,t)}var _j={kernelName:pi,backendName:"webgl",kernelFunc:XD};var Py=class{constructor(e,t=!1,n=null,o=!1,s=!1){this.variableNames=["x","W"];this.outputShape=e.outShape;let i=e.padInfo.top,a=e.padInfo.left,l=e.strideHeight,u=e.strideWidth,p=e.dilationHeight,c=e.dilationWidth,m=e.filterHeight,f=e.filterWidth,d=Math.floor(e.inChannels/4)*4,h=e.inChannels%4,g=e.dataFormat==="channelsLast",b=g?1:2,y=g?2:3,T=g?3:1,k="",I="";n&&(o?k=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:s?k=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${n}
|
|
}`:k=`
|
|
float activation(float x) {
|
|
${n}
|
|
}
|
|
`,I="result = activation(result);");let S=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${k}
|
|
|
|
const ivec2 strides = ivec2(${l}, ${u});
|
|
const ivec2 pads = ivec2(${i}, ${a});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d2 = coords[${T}];
|
|
|
|
ivec2 xRCCorner =
|
|
ivec2(coords[${b}], coords[${y}]) * strides - pads;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < ${m}; wR++) {
|
|
int xR = xRCorner + wR * ${p};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${f}; wC++) {
|
|
int xC = xCCorner + wC * ${c};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int d1 = 0; d1 < ${d}; 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 (${g}) {
|
|
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 (${h===1}) {
|
|
|
|
if (${g}) {
|
|
dotProd +=
|
|
getX(batch, xR, xC, ${d}) *
|
|
getW(wR, wC, ${d}, d2);
|
|
} else {
|
|
dotProd +=
|
|
getX(batch, ${d}, xR, xC) *
|
|
getW(wR, wC, ${d}, d2);
|
|
}
|
|
|
|
} else if (${h===2}) {
|
|
vec2 wValues = vec2(
|
|
getW(wR, wC, ${d}, d2),
|
|
getW(wR, wC, ${d} + 1, d2)
|
|
);
|
|
|
|
if (${g}) {
|
|
vec2 xValues = vec2(
|
|
getX(batch, xR, xC, ${d}),
|
|
getX(batch, xR, xC, ${d} + 1)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec2 xValues = vec2(
|
|
getX(batch, ${d}, xR, xC),
|
|
getX(batch, ${d} + 1, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
} else if (${h===3}) {
|
|
vec3 wValues = vec3(
|
|
getW(wR, wC, ${d}, d2),
|
|
getW(wR, wC, ${d} + 1, d2),
|
|
getW(wR, wC, ${d} + 2, d2)
|
|
);
|
|
|
|
if (${g}) {
|
|
vec3 xValues = vec3(
|
|
getX(batch, xR, xC, ${d}),
|
|
getX(batch, xR, xC, ${d} + 1),
|
|
getX(batch, xR, xC, ${d} + 2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec3 xValues = vec3(
|
|
getX(batch, ${d}, xR, xC),
|
|
getX(batch, ${d} + 1, xR, xC),
|
|
getX(batch, ${d} + 2, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
|
|
float result = dotProd;
|
|
${S}
|
|
${I}
|
|
setOutput(result);
|
|
}
|
|
`}},YD=class{constructor(e){this.variableNames=["x","W"];this.outputShape=e.outShape;let t=e.padInfo.front,n=e.padInfo.top,o=e.padInfo.left,s=e.strideDepth,i=e.strideHeight,a=e.strideWidth,l=e.dilationDepth,u=e.dilationHeight,p=e.dilationWidth,c=e.filterDepth,m=e.filterHeight,f=e.filterWidth,d=Math.floor(e.inChannels/4)*4,h=e.inChannels%4;this.userCode=`
|
|
const ivec3 strides = ivec3(${s}, ${i}, ${a});
|
|
const ivec3 pads = ivec3(${t}, ${n}, ${o});
|
|
|
|
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 < ${c}; wF++) {
|
|
int xF = xFCorner + wF * ${l};
|
|
|
|
if (xF < 0 || xF >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${m}; wR++) {
|
|
int xR = xRCorner + wR * ${u};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${f}; wC++) {
|
|
int xC = xCCorner + wC * ${p};
|
|
|
|
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 (${h===1}) {
|
|
dotProd +=
|
|
getX(batch, xF, xR, xC, ${d}) *
|
|
getW(wF, wR, wC, ${d}, d2);
|
|
} else if (${h===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 (${h===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);
|
|
}
|
|
`}};var ZD=class{constructor(e,t,n){this.variableNames=["A"];this.packedInputs=!0;this.packedOutput=!0;this.outputShape=e;let{filterWidth:o,inChannels:s,strideWidth:i,strideHeight:a,padInfo:l,outWidth:u,dilationWidth:p,dilationHeight:c,dataFormat:m}=n,{left:f,top:d}=l,h=s*o,g=lr(),b=m==="channelsLast",y=b?0:1,T=b?1:2,k="";for(let I=0;I<=1;I++)for(let S=0;S<=1;S++)k+=`
|
|
blockIndex = rc.y + ${S};
|
|
pos = rc.x + ${I};
|
|
|
|
if(blockIndex < ${e[1]} && pos < ${e[0]}) {
|
|
offsetY = int(blockIndex / (${u})) * ${a} - ${d};
|
|
d0 = offsetY + ${c} * (pos / ${h});
|
|
|
|
if(d0 < ${t[y]} && d0 >= 0) {
|
|
|
|
offsetX = int(mod(float(blockIndex), ${u}.) * ${i}. - ${f}.);
|
|
d1 = offsetX + ${p} * (int(mod(float(pos), ${h}.) / ${s}.));
|
|
|
|
if(d1 < ${t[T]} && d1 >= 0) {
|
|
|
|
ch = int(mod(float(pos), ${s}.));
|
|
|
|
if (${b}) {
|
|
innerDims = vec2(d1, ch);
|
|
result[${I*2+S}] = getChannel(
|
|
getA(d0, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
} else {
|
|
innerDims = vec2(d0, d1);
|
|
result[${I*2+S}] = 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;
|
|
|
|
${k}
|
|
|
|
${g.output} = result;
|
|
}
|
|
`}};function FI({x:r,filter:e,convInfo:t,backend:n,bias:o=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:a=null}){let l=r.shape,u=n.texData.get(r.dataId),p=t.inChannels,c=l[0]*l[1]*l[2],m=t.outChannels,f=t.dataFormat==="channelsLast",d=!1,h=!1,g,b=[],y=(c===1||m===1)&&p>DD,T=l[2]%2!=0&&!!u.isPacked;if(y||!X().getBool("WEBGL_LAZILY_UNPACK")||!X().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!T){let k=f?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],I=de({inputs:{x:r},backend:n,attrs:{shape:[1,k,t.inChannels]}}),S=de({inputs:{x:e},backend:n,attrs:{shape:[1,t.inChannels,t.outChannels]}}),N=hm({a:I,b:S,transposeA:d,transposeB:h,backend:n,bias:o,activation:a,preluActivationWeights:s,leakyreluAlpha:i});g=de({inputs:{x:N},backend:n,attrs:{shape:t.outShape}}),b.push(I),b.push(S),b.push(N)}else{let k=f?l[0]*l[1]*(l[2]+1):l[0]*l[2]*(l[3]+1),I={dataId:r.dataId,shape:[1,k,t.inChannels],dtype:r.dtype},S=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,x.assert(xp(u.shape,I.shape),()=>`packed reshape ${u.shape} to ${I.shape} isn't free`);let N=de({inputs:{x:e},backend:n,attrs:{shape:[1,t.inChannels,t.outChannels]}});b.push(N);let F=hm({a:I,b:N,backend:n,transposeA:d,transposeB:h,bias:o,activation:a,preluActivationWeights:s,leakyreluAlpha:i}),$=n.texData.get(F.dataId);x.assert($.isPacked,()=>"batchMatMul result is expected to be packed"),u.shape=S,$.shape=t.outShape,g=vr({inputs:{x:F},backend:n}),g.shape=t.outShape,b.push(F)}for(let k of b)n.disposeIntermediateTensorInfo(k);return g}function RI({x:r,filter:e,convInfo:t,backend:n,bias:o=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:a=null}){let{filterWidth:l,filterHeight:u,inChannels:p,outWidth:c,outHeight:m,dataFormat:f}=t,d=f==="channelsLast",h=l*u*p,g=m*c,b=[h,g],y=!0,T=!1,k=[],I=de({inputs:{x:r},backend:n,attrs:{shape:r.shape.slice(1)}}),S=de({inputs:{x:e},backend:n,attrs:{shape:[1,h,x.sizeFromShape(e.shape)/h]}});k.push(I),k.push(S);let N=new ZD(b,I.shape,t),F=n.runWebGLProgram(N,[I],"float32"),$=de({inputs:{x:F},backend:n,attrs:{shape:[1,b[0],b[1]]}});k.push(F),k.push($);let O=o!=null,V=s!=null,q=a==="leakyrelu",W=a?kp(a,!0):null,Y=new Ly($.shape,S.shape,[1,g,t.outChannels],y,T,O,W,V,q),Z=[$,S];if(o&&Z.push(o),V&&Z.push(s),q){let le=n.makeTensorInfo([],"float32",x.createScalarValue(i,"float32"));Z.push(le),k.push(le)}let J=n.runWebGLProgram(Y,Z,"float32"),se=d?[1,m,c,t.outChannels]:[1,t.outChannels,m,c],ee=de({inputs:{x:J},backend:n,attrs:{shape:se}});k.push(J);for(let le of k)n.disposeIntermediateTensorInfo(le);return ee}function Aye(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,filter:s}=e,{strides:i,pad:a,dataFormat:l,dilations:u,dimRoundingMode:p}=n,c=C.convertConv2DDataFormat(l),m=C.computeConv2DInfo(o.shape,s.shape,i,u,a,p,!1,c),f;if(m.filterHeight===1&&m.filterWidth===1&&m.dilationHeight===1&&m.dilationWidth===1&&m.strideHeight===1&&m.strideWidth===1&&(m.padInfo.type==="SAME"||m.padInfo.type==="VALID"))f=FI({x:o,filter:s,convInfo:m,backend:t});else if(X().getBool("WEBGL_CONV_IM2COL")&&o.shape[0]===1)f=RI({x:o,filter:s,convInfo:m,backend:t});else{let h=new Py(m);f=t.runWebGLProgram(h,[o,s],"float32")}let d=de({inputs:{x:f},backend:t,attrs:{shape:m.outShape}});return t.disposeIntermediateTensorInfo(f),d}var Cj={kernelName:js,backendName:"webgl",kernelFunc:Aye};var JD=class{constructor(e){this.variableNames=["x","dy"];this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,o=e.padInfo.top,s=e.padInfo.left,i=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} - ${o};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${n} - ${s};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
if (${i}) {
|
|
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);
|
|
}
|
|
`}},QD=class{constructor(e){this.variableNames=["dy","W"];this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,o=e.strideHeight,s=e.strideWidth,i=e.dataFormat==="channelsLast",a=t-1-e.padInfo.top,l=n-1-e.padInfo.left,u=i?1:2,p=i?2:3,c=i?3:1;this.userCode=`
|
|
const ivec2 pads = ivec2(${a}, ${l});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d1 = coords[${c}];
|
|
|
|
ivec2 dyCorner = ivec2(coords[${u}], coords[${p}]) - 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) / ${o}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
int wRPerm = ${t} - 1 - wR;
|
|
|
|
for (int wC = 0; wC < ${n}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${s}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = ${n} - 1 - wC;
|
|
|
|
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
|
|
|
|
if (${i}) {
|
|
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);
|
|
}
|
|
`}},e1=class{constructor(e){this.variableNames=["x","dy"];this.outputShape=e.filterShape;let t=e.strideDepth,n=e.strideHeight,o=e.strideWidth,s=e.padInfo.front,i=e.padInfo.top,a=e.padInfo.left;this.userCode=`
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int wF = coords.x;
|
|
int wR = coords.y;
|
|
int wC = coords.z;
|
|
int d1 = coords.w;
|
|
int d2 = coords.u;
|
|
|
|
float dotProd = 0.0;
|
|
|
|
for (int b = 0; b < ${e.batchSize}; b++) {
|
|
for (int yF = 0; yF < ${e.outDepth}; yF++) {
|
|
int xF = wF + yF * ${t} - ${s};
|
|
|
|
if (xF < 0 || xF >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yR = 0; yR < ${e.outHeight}; yR++) {
|
|
int xR = wR + yR * ${n} - ${i};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${o} - ${a};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float dyValue = getDy(b, yF, yR, yC, d2);
|
|
float xValue = getX(b, xF, xR, xC, d1);
|
|
dotProd += (xValue * dyValue);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},t1=class{constructor(e){this.variableNames=["dy","W"];this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,o=e.filterWidth,s=e.strideDepth,i=e.strideHeight,a=e.strideWidth,l=t-1-e.padInfo.front,u=n-1-e.padInfo.top,p=o-1-e.padInfo.left;this.userCode=`
|
|
const ivec3 pads = ivec3(${l}, ${u}, ${p});
|
|
|
|
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) / ${s}.0;
|
|
|
|
if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyF = int(dyF);
|
|
|
|
int wFPerm = ${t} - 1 - wF;
|
|
|
|
for (int wR = 0; wR < ${n}; wR++) {
|
|
float dyR = float(dyRCorner + wR) / ${i}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
|
|
fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
int wRPerm = ${n} - 1 - wR;
|
|
|
|
for (int wC = 0; wC < ${o}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${a}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = ${o} - 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);
|
|
}
|
|
`}};function Dye(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,dy:s}=e,{strides:i,pad:a,dataFormat:l,dimRoundingMode:u,filterShape:p}=n,c=C.convertConv2DDataFormat(l),m=C.computeConv2DInfo(o.shape,p,i,1,a,u,!1,c),f=new JD(m);return t.runWebGLProgram(f,[o,s],"float32")}var Sj={kernelName:uf,backendName:"webgl",kernelFunc:Dye};function Eye(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,filter:s}=e,{inputShape:i,strides:a,pad:l,dataFormat:u,dimRoundingMode:p}=n,c=C.convertConv2DDataFormat(u),m=C.computeConv2DInfo(i,s.shape,a,1,l,p,!1,c),f=new QD(m);return t.runWebGLProgram(f,[o,s],"float32")}var Nj={kernelName:Hs,backendName:"webgl",kernelFunc:Eye};function Mye(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,filter:s}=e,{strides:i,pad:a,dilations:l}=n,u=C.computeConv3DInfo(o.shape,s.shape,i,l,a),p=new YD(u);return t.runWebGLProgram(p,[o,s],"float32")}var Aj={kernelName:Bu,backendName:"webgl",kernelFunc:Mye};function Fye(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,dy:s}=e,{strides:i,pad:a,filterShape:l}=n,u=C.computeConv3DInfo(o.shape,l,i,1,a),p=new e1(u);return t.runWebGLProgram(p,[o,s],"float32")}var Dj={kernelName:pf,backendName:"webgl",kernelFunc:Fye};function Rye(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,filter:s}=e,{pad:i,strides:a,inputShape:l}=n,u=C.computeConv3DInfo(l,s.shape,a,1,i),p=new t1(u);return t.runWebGLProgram(p,[o,s],"float32")}var Ej={kernelName:cf,backendName:"webgl",kernelFunc:Rye};var Lye=SI+`
|
|
return cos(x);
|
|
`,$ye=Ae({opSnippet:Lye}),Mj={kernelName:qs,backendName:"webgl",kernelFunc:$ye};var Pye=`
|
|
float e2x = exp(-x);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`,Bye=Ae({opSnippet:Pye}),Fj={kernelName:fl,backendName:"webgl",kernelFunc:Bye};var r1=class{constructor(e,t,n,o,s){this.variableNames=["Image","Boxes","BoxInd"];this.outputShape=[];let[i,a,l,u]=e,[p]=t,[c,m]=n;this.outputShape=[p,c,m,u];let f=o==="bilinear"?1:0,[d,h]=[`${a-1}.0`,`${l-1}.0`],[g,b,y]=c>1?[`${(a-1)/(c-1)}`,"(y2-y1) * height_ratio",`y1*${d} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${d}`],[T,k,I]=m>1?[`${(l-1)/(m-1)}`,"(x2-x1) * width_ratio",`x1*${h} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${h}`];this.userCode=`
|
|
const float height_ratio = float(${g});
|
|
const float width_ratio = float(${T});
|
|
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 >= ${i}) {
|
|
return;
|
|
}
|
|
|
|
float height_scale = ${b};
|
|
float width_scale = ${k};
|
|
|
|
float in_y = ${y};
|
|
if( in_y < 0.0 || in_y > ${d} ) {
|
|
setOutput(float(${s}));
|
|
return;
|
|
}
|
|
float in_x = ${I};
|
|
if( in_x < 0.0 || in_x > ${h} ) {
|
|
setOutput(float(${s}));
|
|
return;
|
|
}
|
|
|
|
vec2 sourceFracIndexCR = vec2(in_x,in_y);
|
|
if(${f} == 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);
|
|
}
|
|
}
|
|
`}};var Oye=r=>{let{inputs:e,backend:t,attrs:n}=r,{image:o,boxes:s,boxInd:i}=e,{cropSize:a,method:l,extrapolationValue:u}=n,p=new r1(o.shape,s.shape,a,l,u);return t.runWebGLProgram(p,[o,s,i],"float32")},Rj={kernelName:dl,backendName:"webgl",kernelFunc:Oye};var LI=class{constructor(e,t,n){this.variableNames=["x"];this.outputShape=e;let o=e.length,s=t?"0.0":`getX(${Lj(o,"coords")})`,i=e[e.length-1],a="",l="";t?(a=n?`end != ${i-1}`:"end != 0",l=n?"end + 1":"end - 1"):(a=n?`end + pow2 < ${i}`:"end >= pow2",l=n?"end + pow2":"end - pow2"),this.userCode=`
|
|
uniform float index;
|
|
void main() {
|
|
${Xe(o)} coords = getOutputCoords();
|
|
int end = ${$j(o,"coords")};
|
|
float val = ${s};
|
|
int pow2 = int(pow(2.0, index));
|
|
if (${a}) {
|
|
int idx = ${l};
|
|
${$j(o,"coords")} = idx;
|
|
val += getX(${Lj(o,"coords")});
|
|
}
|
|
setOutput(val);
|
|
}
|
|
`}getCustomSetupFunc(e){return(t,n)=>{this.index==null&&(this.index=t.getUniformLocation(n,"index")),t.gl.uniform1f(this.index,e)}}};function Lj(r,e){if(r===1)return`${e}`;if(r===2)return`${e}.x, ${e}.y`;if(r===3)return`${e}.x, ${e}.y, ${e}.z`;if(r===4)return`${e}.x, ${e}.y, ${e}.z, ${e}.w`;throw Error(`Cumulative sum for rank ${r} is not yet supported`)}function $j(r,e){if(r===1)return`${e}`;if(r===2)return`${e}.y`;if(r===3)return`${e}.z`;if(r===4)return`${e}.w`;throw Error(`Cumulative sum for rank ${r} is not yet supported`)}function zye(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,exclusive:i,reverse:a}=n,l=o.shape.length,u=C.getAxesPermutation([s],l),p=o;u!=null&&(p=rr({inputs:{x:o},backend:t,attrs:{perm:u}}));let c=C.getInnerMostAxes(1,l)[0];if(c!==l-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${o.shape.length-1} but got axis=${s}`);let m=p.shape[c],f=vr({inputs:{x:p},backend:t});for(let d=0;d<=Math.ceil(Math.log2(m))-1;d++){let h=new LI(p.shape,!1,a),g=h.getCustomSetupFunc(d),b=f;f=t.runWebGLProgram(h,[f],f.dtype,g),t.disposeIntermediateTensorInfo(b)}if(i){let d=new LI(p.shape,i,a),h=f;f=t.runWebGLProgram(d,[f],f.dtype),t.disposeIntermediateTensorInfo(h)}if(u!=null){let d=C.getUndoAxesPermutation(u),h=rr({inputs:{x:f},backend:t,attrs:{perm:d}});return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(p),h}return f}var Pj={kernelName:Xs,backendName:"webgl",kernelFunc:zye};function Gye(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,weights:s}=e,{size:i,binaryOutput:a}=n;if(o.shape.length===1){let l=t.readSync(o.dataId),u=t.readSync(s.dataId),p=II(l,u,s.dtype,s.shape,i);return t.makeTensorInfo([i],s.dtype,p)}else if(o.shape.length===2){let l=t.bufferSync(o),u=t.bufferSync(s),p=MU(l,u,i,a);return t.makeTensorInfo(p.shape,s.dtype,p.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${o.shape.length}.`)}var Bj={kernelName:mf,backendName:"webgl",kernelFunc:Gye};var n1=class{constructor(e,t,n){this.variableNames=["x"];this.outputShape=[];this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int h = ${this.getHeightCoordString()};
|
|
int w = ${this.getWidthCoordString()};
|
|
int d = ${this.getDepthCoordString()};
|
|
|
|
int in_h = h / ${t};
|
|
int offset_h = imod(h, ${t});
|
|
int in_w = w / ${t};
|
|
int offset_w = imod(w, ${t});
|
|
int offset_d = (offset_h * ${t} + offset_w) *
|
|
${this.getOutputDepthSize()};
|
|
int in_d = d + offset_d;
|
|
|
|
float result = ${this.getInputSamplingString()};
|
|
setOutput(result);
|
|
}
|
|
`}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}};function Wye(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{blockSize:s,dataFormat:i}=n;x.assert(s>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${s}`);let a=o.shape[0],l=i==="NHWC"?o.shape[1]:o.shape[2],u=i==="NHWC"?o.shape[2]:o.shape[3],p=i==="NHWC"?o.shape[3]:o.shape[1],c=l*s,m=u*s,f=p/(s*s),d=i==="NHWC"?[a,c,m,f]:[a,f,c,m],h=new n1(d,s,i);return t.runWebGLProgram(h,[o],o.dtype)}var Oj={kernelName:hl,backendName:"webgl",kernelFunc:Wye};var By=class{constructor(e,t=!1,n=null,o=!1,s=!1){this.variableNames=["x","W"];this.outputShape=e.outShape;let i=e.inHeight,a=e.inWidth,l=e.padInfo.top,u=e.padInfo.left,p=e.strideHeight,c=e.strideWidth,m=e.dilationHeight,f=e.dilationWidth,d=e.filterHeight,h=e.filterWidth,g=e.outChannels/e.inChannels,b="",y="";n&&(o?b=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:s?b=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${n}
|
|
}`:b=`
|
|
float activation(float x) {
|
|
${n}
|
|
}
|
|
`,y="result = activation(result);");let T=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${b}
|
|
|
|
const ivec2 strides = ivec2(${p}, ${c});
|
|
const ivec2 pads = ivec2(${l}, ${u});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int d2 = coords.w;
|
|
int d1 = d2 / ${g};
|
|
int q = d2 - d1 * ${g};
|
|
|
|
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 < ${d}; wR++) {
|
|
int xR = xRCorner + wR * ${m};
|
|
|
|
if (xR < 0 || xR >= ${i}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${h}; wC++) {
|
|
int xC = xCCorner + wC * ${f};
|
|
|
|
if (xC < 0 || xC >= ${a}) {
|
|
continue;
|
|
}
|
|
|
|
float xVal = getX(batch, xR, xC, d1);
|
|
float wVal = getW(wR, wC, d1, q);
|
|
dotProd += xVal * wVal;
|
|
}
|
|
}
|
|
|
|
float result = dotProd;
|
|
${T}
|
|
${y}
|
|
setOutput(result);
|
|
}
|
|
`}};var Oy=class{constructor(e,t=!1,n=null,o=!1,s=!1){this.variableNames=["x","W"];this.packedInputs=!0;this.packedOutput=!0;this.outputShape=e.outShape;let i=e.outChannels/e.inChannels,a=e.inHeight,l=e.inWidth,u=e.padInfo.top,p=e.padInfo.left,c=e.strideHeight,m=e.strideWidth,f=e.dilationHeight,d=e.dilationWidth,h=e.filterHeight,g=e.filterWidth,b=g,y=`
|
|
int xR; int xC; int xCOffset;
|
|
vec4 wTexel; vec4 previous; vec4 final;`;for(let S=0;S<g;S++)y+=`
|
|
vec4 xTexelC${S*2};
|
|
int xTexelC${S*2}Ready;
|
|
vec4 xC${S};`;for(let S=0;S<h;S++){for(let N=0;N<g;N++)y+=`
|
|
xTexelC${N*2} = vec4(0.0);
|
|
xTexelC${N*2}Ready = 0;
|
|
xC${N} = vec4(0.0);`;y+=`
|
|
xR = xRCorner + ${S*f};
|
|
if (xR >=0 && xR < ${a}) {
|
|
`;for(let N=0;N<(b+1)/2;N++){let F=N*2,$=F*d;if(y+=`
|
|
xC = xCCorner + ${$};
|
|
`,m===1){if(F<g&&(p%2==1?(y+=`
|
|
xCOffset = xC + 1;
|
|
if (xCOffset >= 0 && xCOffset < ${l} && xTexelC${$}Ready == 0) {
|
|
xTexelC${$} = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= ${l}) {
|
|
xTexelC${$}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${$}Ready = 1;
|
|
}
|
|
`,d===1&&$>0?y+=`
|
|
xC${F} = vec4(xTexelC${$-2}.zw, xTexelC${$}.xy);
|
|
`:y+=`
|
|
xCOffset = xC + 1 - 2;
|
|
|
|
if (xCOffset >= 0 && xCOffset < ${l}) {
|
|
previous = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= ${l}) {
|
|
previous.zw = vec2(0.0);
|
|
}
|
|
|
|
xC${F} = vec4(previous.zw, xTexelC${$}.xy);
|
|
} else {
|
|
xC${F} = vec4(0.0, 0.0, xTexelC${$}.xy);
|
|
}
|
|
`):y+=`
|
|
if (xC >= 0 && xC < ${l} && xTexelC${$}Ready == 0) {
|
|
xTexelC${$} = getX(batch, xR, xC, d1);
|
|
if (xC + 1 >= ${l}) {
|
|
xTexelC${$}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${$}Ready = 1;
|
|
}
|
|
|
|
xC${F} = xTexelC${$};
|
|
`,$+1<g)){let O=p%2==0?x.nearestLargerEven(d):d;d%2==0&&p%2==1||d%2!=0&&p%2!=1?(y+=`
|
|
xCOffset = xC + ${p%2} + ${O};
|
|
|
|
if (xCOffset >= 0 && xCOffset < ${l} && xTexelC${$+2}Ready == 0) {
|
|
xTexelC${$+2} = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= ${l}) {
|
|
xTexelC${$+2}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${$+2}Ready = 1;
|
|
}
|
|
`,d>1&&(y+=`
|
|
xCOffset -= 2;
|
|
if (xCOffset >= 0 && xCOffset < ${l} && xTexelC${$}Ready == 0) {
|
|
xTexelC${$} = getX(batch, xR, xCOffset, d1);
|
|
xTexelC${$}Ready = 1;
|
|
}
|
|
`),y+=`
|
|
xC${F+1} = vec4(xTexelC${$}.zw, xTexelC${$+2}.xy);
|
|
`):O===1?y+=`
|
|
xC${F+1} = xTexelC${$};
|
|
`:y+=`
|
|
xCOffset = xC + ${O};
|
|
|
|
if (xCOffset >= 0 && xCOffset < ${l} && xTexelC${$+2}Ready == 0) {
|
|
xTexelC${$+2} = getX(batch, xR, xCOffset, d1);
|
|
if (xCOffset + 1 >= ${l}) {
|
|
xTexelC${$+2}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${$+2}Ready = 1;
|
|
}
|
|
|
|
xC${F+1} = xTexelC${$+2};
|
|
`}}else $<g&&(p%2==1?(y+=`
|
|
xCOffset = xC + 1 - ${m};
|
|
if(xCOffset >= 0 && xCOffset < ${l} && xTexelC${$}Ready == 0) {
|
|
xTexelC${$} = getX(batch, xR, xCOffset, d1);
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= ${l}) {
|
|
xTexelC${$}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${$}Ready = 1;
|
|
}
|
|
|
|
if(xC + 1 >= 0 && xC + 1 < ${l} && xTexelC${$+2}Ready == 0) {
|
|
xTexelC${$+2} = getX(batch, xR, xC + 1, d1);
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xC + 2 >= ${l}) {
|
|
xTexelC${$+2}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${$+2}Ready = 1;
|
|
}
|
|
|
|
xC${F} = vec4(xTexelC${$}.zw, xTexelC${$+2}.zw);
|
|
`,$+1<g&&(y+=`
|
|
final = vec4(0.0);
|
|
xCOffset = xC + 1 + ${m};
|
|
if(xCOffset >= 0 && xCOffset < ${l}) {
|
|
final = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
xC${F+1} = vec4(xTexelC${$+2}.xy, final.xy);
|
|
`)):(y+=`
|
|
if(xC >= 0 && xC < ${l} && xTexelC${$}Ready == 0) {
|
|
xTexelC${$} = getX(batch, xR, xC, d1);
|
|
if (xC + 1 >= ${l}) {
|
|
xTexelC${$}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${$}Ready = 1;
|
|
}
|
|
|
|
xCOffset = xC + ${m};
|
|
if(xCOffset >= 0 && xCOffset < ${l} && xTexelC${$+2}Ready == 0) {
|
|
xTexelC${$+2} = getX(batch, xR, xCOffset, d1);
|
|
if (xCOffset + 1 >= ${l}) {
|
|
xTexelC${$+2}.zw = vec2(0.);
|
|
}
|
|
xTexelC${$+2}Ready = 1;
|
|
}
|
|
|
|
xC${F} = vec4(
|
|
xTexelC${$}.xy, xTexelC${$+2}.xy);
|
|
`,$+1<g&&(y+=`
|
|
xC${F+1} = vec4(xTexelC${$}.zw, xTexelC${$+2}.zw);
|
|
`)));F<g&&(y+=`
|
|
wTexel = getW(${S}, ${$}, d1, q);
|
|
dotProd += xC${F} * vec4(wTexel.xz, wTexel.xz);
|
|
`,$+1<g&&(y+=`
|
|
wTexel = getW(${S}, ${$+1}, d1, q);
|
|
dotProd += xC${F+1} * vec4(wTexel.xz, wTexel.xz);
|
|
`))}y+=`
|
|
}
|
|
`}let T="",k="";n&&(o?T=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:s?T=`vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${n}
|
|
}`:T=`vec4 activation(vec4 x) {
|
|
${n}
|
|
}`,k="result = activation(result);");let I=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${T}
|
|
|
|
const ivec2 strides = ivec2(${c}, ${m});
|
|
const ivec2 pads = ivec2(${u}, ${p});
|
|
|
|
void main() {
|
|
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int d2 = coords.w;
|
|
int d1 = d2 / ${i};
|
|
int q = d2 - d1 * ${i};
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
//intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
|
|
vec4 dotProd = vec4(0.000000000000001);
|
|
|
|
${y}
|
|
|
|
vec4 result = dotProd - vec4(0.000000000000001);
|
|
${I}
|
|
${k}
|
|
setOutput(result);
|
|
}
|
|
`}};function Kye(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,filter:s}=e,{strides:i,pad:a,dilations:l,dimRoundingMode:u}=n,p=l;p==null&&(p=[1,1]),x.assert(C.eitherStridesOrDilationsAreOne(i,p),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${p}'`);let c=C.computeConv2DInfo(o.shape,s.shape,i,p,a,u,!0),m;return X().getBool("WEBGL_PACK_DEPTHWISECONV")&&c.strideWidth<=2&&c.outChannels/c.inChannels==1?m=new Oy(c):m=new By(c),t.runWebGLProgram(m,[o,s],"float32")}var zj={kernelName:Ys,backendName:"webgl",kernelFunc:Kye};var o1=class{constructor(e){this.variableNames=["x","dy"];this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,o=e.padInfo.top,s=e.padInfo.left,i=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 * ${i} + 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} - ${o};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${n} - ${s};
|
|
|
|
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);
|
|
}
|
|
`}},s1=class{constructor(e){this.variableNames=["dy","W"];this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,o=e.strideHeight,s=e.strideWidth,i=t-1-e.padInfo.top,a=n-1-e.padInfo.left,l=e.outChannels/e.inChannels;this.userCode=`
|
|
const ivec2 pads = ivec2(${i}, ${a});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d1 = coords[3];
|
|
ivec2 dyCorner = coords.yz - pads;
|
|
int dyRCorner = dyCorner.x;
|
|
int dyCCorner = dyCorner.y;
|
|
|
|
float dotProd = 0.0;
|
|
|
|
for (int wR = 0; wR < ${t}; wR++) {
|
|
float dyR = float(dyRCorner + wR) / ${o}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
int wRPerm = ${t} - 1 - wR;
|
|
|
|
for (int wC = 0; wC < ${n}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${s}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = ${n} - 1 - wC;
|
|
|
|
// TO DO: Vec4 over the channelMul
|
|
for (int dm = 0; dm < ${l}; dm++) {
|
|
int d2 = d1 * ${l} + dm;
|
|
float xValue = getDy(batch, idyR, idyC, d2);
|
|
float wValue = getW(wRPerm, wCPerm, d1, dm);
|
|
dotProd += xValue * wValue;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function Vye(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,dy:s}=e,{strides:i,dilations:a,pad:l,dimRoundingMode:u,filterShape:p}=n,c=C.computeConv2DInfo(o.shape,p,i,a,l,u,!0),m=new o1(c);return t.runWebGLProgram(m,[o,s],"float32")}var Gj={kernelName:ff,backendName:"webgl",kernelFunc:Vye};function Uye(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,filter:s}=e,{strides:i,dilations:a,pad:l,dimRoundingMode:u,inputShape:p}=n,c=C.computeConv2DInfo(p,s.shape,i,a,l,u,!0),m=new s1(c);return t.runWebGLProgram(m,[o,s],"float32")}var Wj={kernelName:df,backendName:"webgl",kernelFunc:Uye};var a1=class{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);
|
|
}
|
|
`}};function jye(r){let{inputs:e,backend:t}=r,{x:n}=e,o=[...n.shape,...n.shape],s=x.sizeFromShape(n.shape),i=de({inputs:{x:n},backend:t,attrs:{shape:[s]}}),a=new a1(s),l=t.runWebGLProgram(a,[i],i.dtype),u=de({inputs:{x:l},backend:t,attrs:{shape:o}});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(l),u}var Kj={kernelName:hf,backendName:"webgl",kernelFunc:jye};var i1=class{constructor(e){this.variableNames=["x","W"];this.outputShape=e.outShape;let{inHeight:t,inWidth:n,padInfo:o,strideHeight:s,strideWidth:i,filterHeight:a,filterWidth:l,dilationHeight:u,dilationWidth:p}=e,{top:c,left:m}=o;this.userCode=`
|
|
const ivec2 strides = ivec2(${s}, ${i});
|
|
const ivec2 pads = ivec2(${c}, ${m});
|
|
const float neg_infinity = -3.4e38;
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int d1 = coords.w;
|
|
ivec2 outTopLeftCorner =
|
|
coords.yz * strides - pads;
|
|
int hBeg = outTopLeftCorner.x;
|
|
int wBeg = outTopLeftCorner.y;
|
|
|
|
float curVal = neg_infinity;
|
|
for (int h = 0; h < ${a}; h++) {
|
|
int hIn = hBeg + h * ${u};
|
|
|
|
if (hIn >= 0 && hIn < ${t}) {
|
|
for (int w = 0; w < ${l}; w++) {
|
|
int wIn = wBeg + w * ${p};
|
|
|
|
if (wIn >= 0 && wIn < ${n}) {
|
|
float xVal = getX(batch, hIn, wIn, d1);
|
|
float wVal = getW(h, w, d1);
|
|
|
|
float val = xVal + wVal;
|
|
if (val > curVal) {
|
|
curVal = val;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
float result = curVal;
|
|
setOutput(result);
|
|
}
|
|
`}};function Hye(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,filter:s}=e,{strides:i,pad:a,dilations:l}=n,u=C.computeDilation2DInfo(o.shape,s.shape,i,a,"NHWC",l),p,c=new i1(u);p=t.runWebGLProgram(c,[o,s],"float32");let m=de({inputs:{x:p},backend:t,attrs:{shape:u.outShape}});return t.disposeIntermediateTensorInfo(p),m}var Vj={kernelName:Ou,backendName:"webgl",kernelFunc:Hye};function qye(r){let{inputs:e,backend:t,attrs:n}=r,{equation:o}=n,s=e,{allDims:i,summedDims:a,idDims:l}=C.decodeEinsumEquation(o,s.length);C.checkEinsumDimSizes(i.length,l,s);let{path:u,steps:p}=C.getEinsumComputePath(a,l),c=p.length,m=null,f=i.length,d=[];for(let h=0;h<c;++h){for(let g of p[h]){let{permutationIndices:b,expandDims:y}=C.getEinsumPermutation(f,l[g]),T;C.isIdentityPermutation(b)?T=s[g]:(T=rr({inputs:{x:s[g]},backend:t,attrs:{perm:b}}),d.push(T));let k=T.shape.slice();for(let I=0;I<y.length;++I)k.splice(y[I],0,1);x.arraysEqual(T.shape,k)||(T=de({inputs:{x:T},backend:t,attrs:{shape:k}}),d.push(T)),m===null?m=T:(m=$y({inputs:{a:T,b:m},backend:t}),d.push(m))}h<c-1&&(u[h]>=0&&(m=dm({inputs:{x:m},backend:t,attrs:{axis:u[h]-(i.length-f),keepDims:!1}}),d.push(m)),f--)}for(let h of d)h!==m&&t.disposeIntermediateTensorInfo(h);return m}var Uj={kernelName:gf,backendName:"webgl",kernelFunc:qye};var Xye="return (x >= 0.0) ? x : (exp(x) - 1.0);",Yye=`
|
|
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;
|
|
`,Zye=Ae({opSnippet:Xye,packedOpSnippet:Yye}),jj={kernelName:gl,backendName:"webgl",kernelFunc:Zye};var Jye="return (b >= 1.0) ? a : a * (b + 1.0);",Qye=`
|
|
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
|
|
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
|
|
`,exe=r=>{let{inputs:e,backend:t}=r,{dy:n,y:o}=e,s=X().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ei(Qye,n.shape,o.shape):new Rs(Jye,n.shape,o.shape);return t.runWebGLProgram(s,[n,o],n.dtype)},Hj={kernelName:bf,backendName:"webgl",kernelFunc:exe};var txe=`
|
|
return vec4(equal(a, b));
|
|
`,rxe="return float(a == b);",nxe=Tt({opSnippet:rxe,packedOpSnippet:txe,dtype:"bool",cpuKernelImpl:LU}),qj={kernelName:Js,backendName:"webgl",kernelFunc:nxe};var oxe=`
|
|
// Error function is calculated approximately with elementary function.
|
|
// See "Handbook of Mathematical Functions with Formulas,
|
|
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
|
|
float p = ${C.ERF_P};
|
|
float a1 = ${C.ERF_A1};
|
|
float a2 = ${C.ERF_A2};
|
|
float a3 = ${C.ERF_A3};
|
|
float a4 = ${C.ERF_A4};
|
|
float a5 = ${C.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));
|
|
`,sxe=Ae({opSnippet:oxe}),Xj={kernelName:bl,backendName:"webgl",kernelFunc:sxe};var Yj="return exp(x);",l1=Ae({opSnippet:Yj,packedOpSnippet:Yj,cpuKernelImpl:$U}),Zj={kernelName:Mo,backendName:"webgl",kernelFunc:l1};function $I(r){let{inputs:e,attrs:t,backend:n}=r,{dim:o}=t,{input:s}=e,i=s.shape.length,a=s.shape.slice(),l=o;return o<0&&(x.assert(-(i+1)<=o,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+o+1),a.splice(l,0,1),de({inputs:{x:s},backend:n,attrs:{shape:a}})}var Jj={kernelName:ci,backendName:"webgl",kernelFunc:$I};var Qj="return exp(x) - 1.0;",axe=Ae({opSnippet:Qj,packedOpSnippet:Qj,cpuKernelImpl:PU}),eH={kernelName:Qs,backendName:"webgl",kernelFunc:axe};var PI=class{constructor(e,t,n){this.variableNames=["real","imag"];let o=t[1];this.outputShape=t;let s=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,i=n?`${o}.0`:"1.0",a;if(e==="real")a="return real * expR - imag * expI;";else if(e==="imag")a="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);this.userCode=`
|
|
const float exponentMultiplier = ${s};
|
|
|
|
float unaryOpComplex(float real, float expR, float imag, float expI) {
|
|
${a}
|
|
}
|
|
|
|
float mulMatDFT(int batch, int index) {
|
|
float indexRatio = float(index) / float(${o});
|
|
float exponentMultiplierTimesIndexRatio =
|
|
exponentMultiplier * indexRatio;
|
|
|
|
float result = 0.0;
|
|
|
|
for (int i = 0; i < ${o}; 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) / ${i};
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
setOutput(mulMatDFT(coords[0], coords[1]));
|
|
}
|
|
`}};function BI(r,e,t){let n=t.texData.get(r.dataId),o=x.sizeFromShape(r.shape),s=r.shape[r.shape.length-1],i=o/s,a=de({inputs:{x:r},backend:t,attrs:{shape:[i,s]}}),l=a.shape,u=new PI("real",l,e),p=new PI("imag",l,e),c=[{dataId:n.complexTensorInfos.real.dataId,dtype:n.complexTensorInfos.real.dtype,shape:l},{dataId:n.complexTensorInfos.imag.dataId,dtype:n.complexTensorInfos.imag.dtype,shape:l}],m=t.runWebGLProgram(u,c,"float32"),f=t.runWebGLProgram(p,c,"float32"),d=fo({inputs:{real:m,imag:f},backend:t});t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f);let h=de({inputs:{x:d},backend:t,attrs:{shape:r.shape}});return t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(d),h}function ixe(r){let{inputs:e,backend:t}=r,{input:n}=e;return BI(n,!1,t)}var tH={kernelName:yf,backendName:"webgl",kernelFunc:ixe};var u1=class{constructor(e,t){this.outputShape=[];this.variableNames=["x"],this.outputShape=e,this.userCode=`
|
|
uniform float value;
|
|
void main() {
|
|
// Input can be obtained from uniform value.
|
|
setOutput(value);
|
|
}
|
|
`}getCustomSetupFunc(e){return(t,n)=>{this.valueLoc==null&&(this.valueLoc=t.getUniformLocationNoThrow(n,"value")),t.gl.uniform1f(this.valueLoc,e)}}};function zy(r){let{backend:e,attrs:t}=r,{shape:n,value:o}=t,{dtype:s}=t;if(s=s||x.inferDtype(o),s==="string"){let i=x.getArrayFromDType(s,x.sizeFromShape(n));return i.fill(o),e.makeTensorInfo(n,s,i)}else{let i=new u1(n,o),a=i.getCustomSetupFunc(o);return e.runWebGLProgram(i,[],s,a)}}var rH={kernelName:zu,backendName:"webgl",kernelFunc:zy};var p1=class{constructor(e){this.variableNames=["Image"];this.outputShape=[];let 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);
|
|
}
|
|
`}};var nH={kernelName:yl,backendName:"webgl",kernelFunc:({inputs:r,backend:e})=>{let{image:t}=r,n=e,o=new p1(t.shape);return n.runWebGLProgram(o,[t],t.dtype)}};var oH="return floor(x);",lxe=Ae({opSnippet:oH,packedOpSnippet:oH,cpuKernelImpl:BU}),sH={kernelName:Fo,backendName:"webgl",kernelFunc:lxe};var uxe=`
|
|
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;
|
|
}
|
|
`,pxe=`
|
|
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);
|
|
`,cxe=Tt({opSnippet:uxe,packedOpSnippet:pxe,dtype:"int32"}),aH={kernelName:ea,backendName:"webgl",kernelFunc:cxe};var c1=class{constructor(e){this.variableNames=["A"];let t=lr(),[n,o]=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(${o}.0, ${n}.0);
|
|
|
|
vec4 values = ${t.texture2D}(A, uv);
|
|
float value;
|
|
if (depth == 0) {
|
|
value = values.r;
|
|
} else if (depth == 1) {
|
|
value = values.g;
|
|
} else if (depth == 2) {
|
|
value = values.b;
|
|
} else if (depth == 3) {
|
|
value = values.a;
|
|
}
|
|
|
|
setOutput(floor(value * 255.0 + 0.5));
|
|
}
|
|
`}};var m1=class{constructor(e){this.variableNames=["A"];this.packedInputs=!1;this.packedOutput=!0;let t=lr(),[n,o]=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(${o}.0, ${n}.0);
|
|
vec4 values = ${t.texture2D}(A, uv);
|
|
float value;
|
|
if (depth == 0) {
|
|
value = values.r;
|
|
} else if (depth == 1) {
|
|
value = values.g;
|
|
} else if (depth == 2) {
|
|
value = values.b;
|
|
} else if (depth == 3) {
|
|
value = values.a;
|
|
}
|
|
|
|
result[row * 2 + col] = floor(value * 255.0 + 0.5);
|
|
}
|
|
}
|
|
|
|
${t.output} = result;
|
|
}
|
|
`}};var iH={kernelName:Gh,backendName:"webgl",kernelFunc:mxe},Zd;function mxe(r){let{inputs:e,backend:t,attrs:n}=r,{pixels:o}=e,{numChannels:s}=n,i=typeof HTMLVideoElement!="undefined"&&o instanceof HTMLVideoElement,a=typeof HTMLImageElement!="undefined"&&o instanceof HTMLImageElement,[l,u]=i?[o.videoWidth,o.videoHeight]:[o.width,o.height],p=[u,l],c=[u,l,s];(a||i)&&(Zd==null&&(Zd=document.createElement("canvas").getContext("2d")),Zd.canvas.width=l,Zd.canvas.height=u,Zd.drawImage(o,0,0,l,u),o=Zd.canvas);let m=t.makeTensorInfo(p,"int32");t.texData.get(m.dataId).usage=yn.PIXELS,t.gpgpu.uploadPixelDataToTexture(t.getTexture(m.dataId),o);let f=X().getBool("WEBGL_PACK")?new m1(c):new c1(c),d=t.runWebGLProgram(f,[m],"int32");return t.disposeData(m.dataId),d}function fxe(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,filter:s,bias:i,preluActivationWeights:a}=e,{strides:l,pad:u,dataFormat:p,dilations:c,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=n,h=C.convertConv2DDataFormat(p),g=C.computeConv2DInfo(o.shape,s.shape,l,c,u,m,!1,h),b,y=[];if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))b=FI({x:o,filter:s,convInfo:g,backend:t,bias:i,activation:f,preluActivationWeights:a,leakyreluAlpha:d});else if(X().getBool("WEBGL_CONV_IM2COL")&&o.shape[0]===1)b=RI({x:o,filter:s,convInfo:g,backend:t,bias:i,activation:f,preluActivationWeights:a,leakyreluAlpha:d});else{let k=i!=null,I=a!=null,S=f==="leakyrelu",N=f?kp(f,!1):null,F=new Py(g,k,N,I,S),$=[o,s];if(i&&$.push(i),a&&$.push(a),S){let O=t.makeTensorInfo([],"float32",x.createScalarValue(d,"float32"));$.push(O),y.push(O)}b=t.runWebGLProgram(F,$,"float32")}let T=de({inputs:{x:b},backend:t,attrs:{shape:g.outShape}});return y.push(b),y.forEach(k=>t.disposeIntermediateTensorInfo(k)),T}var lH={kernelName:Ii,backendName:"webgl",kernelFunc:fxe};function dxe(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,filter:s,bias:i,preluActivationWeights:a}=e,{strides:l,pad:u,dilations:p,dimRoundingMode:c,activation:m,leakyreluAlpha:f}=n,d=[],h=p;h==null&&(h=[1,1]),x.assert(C.eitherStridesOrDilationsAreOne(l,h),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${h}'`);let g=C.computeConv2DInfo(o.shape,s.shape,l,h,u,c,!0),b=X().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,y=m?kp(m,b):null,T=[o,s],k=i!=null,I=a!=null,S=m==="leakyrelu";if(k&&T.push(i),I&&T.push(a),S){let $=t.makeTensorInfo([],"float32",x.createScalarValue(f,"float32"));T.push($),d.push($)}let N;b?N=new Oy(g,k,y,I,S):N=new By(g,k,y,I,S);let F=t.runWebGLProgram(N,T,"float32");return d.forEach($=>t.disposeIntermediateTensorInfo($)),F}var uH={kernelName:vi,backendName:"webgl",kernelFunc:dxe};var f1=class{constructor(e,t,n){this.sliceDim=e;this.strides=t;this.variableNames=["x","indices"];this.outputShape=n;let o=Xe(t.length),s=Xe(n.length),i=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
|
|
${o} strides = ${o}(${this.strides});
|
|
void main() {
|
|
${s} coords = getOutputCoords();
|
|
int flattenIndex = 0;
|
|
for (int j = 0; j < ${this.sliceDim}; j++) {
|
|
int index = round(getIndices(coords[0], j));
|
|
flattenIndex += index * ${i};
|
|
}
|
|
setOutput(getX(flattenIndex, coords[1]));
|
|
}
|
|
`}};function hxe(r){let{inputs:e,backend:t}=r,{params:n,indices:o}=e,s=o.shape,i=s[s.length-1],a=x.sizeFromShape(n.shape),[l,u,p,c]=C.prepareAndValidate(n,o),m=de({inputs:{x:o},backend:t,attrs:{shape:[u,i]}}),f=de({inputs:{x:n},backend:t,attrs:{shape:[x.sizeFromShape(n.shape)/p,p]}});if(t.shouldExecuteOnCPU([n,o])||n.dtype==="string"){let b=t.readSync(o.dataId),y=t.bufferSync(n),T=OU(b,y,n.dtype,u,i,p,c,n.shape,a);return t.makeTensorInfo(l,n.dtype,T.values)}let d=new f1(i,c,[u,p]),h=t.runWebGLProgram(d,[f,m],f.dtype),g=de({inputs:{x:h},backend:t,attrs:{shape:l}});return t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(h),g}var pH={kernelName:xl,backendName:"webgl",kernelFunc:hxe};var d1=class{constructor(e,t){this.variableNames=["A","indices"];this.outputShape=t,this.rank=t.length;let n=Xe(this.rank),o=gxe(e,2);this.userCode=`
|
|
void main() {
|
|
${n} resRC = getOutputCoords();
|
|
setOutput(getA(${o}));
|
|
}
|
|
`}};function gxe(r,e){let t=["resRC.x","resRC.y","resRC.z","resRC.w"],n=[];for(let o=0;o<r.length;o++)o===2?n.push("int(getIndices(resRC.x, resRC.z))"):n.push(`${t[o]}`);return n.join()}function bxe(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,indices:s}=e,{axis:i,batchDims:a}=n,l=x.parseAxisParam(i,o.shape)[0],u=C.segment_util.collectGatherOpShapeInfo(o,s,l,a),p=x.sizeFromShape(s.shape),c=[],m=de({inputs:{x:o},backend:t,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),f=de({inputs:{x:s},backend:t,attrs:{shape:[u.batchSize,p/u.batchSize]}});c.push(m),c.push(f);let d=[u.batchSize,u.outerSize,p/u.batchSize,u.sliceSize];if(t.shouldExecuteOnCPU([o,s])||o.dtype==="string"){let y=t.bufferSync(f),T=t.bufferSync(m),k=zU(T,y,d);return c.forEach(I=>t.disposeIntermediateTensorInfo(I)),t.makeTensorInfo(u.outputShape,k.dtype,k.values)}let h=new d1(m.shape,d),g=t.runWebGLProgram(h,[m,f],m.dtype);c.push(g);let b=de({inputs:{x:g},backend:t,attrs:{shape:u.outputShape}});return c.forEach(y=>t.disposeIntermediateTensorInfo(y)),b}var cH={kernelName:mi,backendName:"webgl",kernelFunc:bxe};var yxe="return float(a > b);",xxe=`
|
|
return vec4(greaterThan(a, b));
|
|
`,Txe=Tt({opSnippet:yxe,packedOpSnippet:xxe,cpuKernelImpl:GU,dtype:"bool"}),mH={kernelName:ra,backendName:"webgl",kernelFunc:Txe};var kxe="return float(a >= b);",Ixe=`
|
|
return vec4(greaterThanEqual(a, b));
|
|
`,vxe=Tt({opSnippet:kxe,packedOpSnippet:Ixe,dtype:"bool",cpuKernelImpl:WU}),fH={kernelName:Ro,backendName:"webgl",kernelFunc:vxe};function wxe(r){let{inputs:e,backend:t}=r,{input:n}=e;return BI(n,!0,t)}var dH={kernelName:xf,backendName:"webgl",kernelFunc:wxe};var _xe="return float(!isnan(x) && !isinf(x));",Cxe=Ae({opSnippet:_xe,dtype:"bool"}),hH={kernelName:Tl,backendName:"webgl",kernelFunc:Cxe};var Sxe="return float(isinf(x));",Nxe=Ae({opSnippet:Sxe,dtype:"bool"}),gH={kernelName:kl,backendName:"webgl",kernelFunc:Nxe};var Axe="return float(isnan(x));",Dxe=Ae({opSnippet:Axe,dtype:"bool"}),bH={kernelName:Il,backendName:"webgl",kernelFunc:Dxe};var Exe="return float(a < b);",Mxe=`
|
|
return vec4(lessThan(a, b));
|
|
`,Fxe=Tt({opSnippet:Exe,packedOpSnippet:Mxe,cpuKernelImpl:KU,dtype:"bool"}),yH={kernelName:oa,backendName:"webgl",kernelFunc:Fxe};var Rxe="return float(a <= b);",Lxe=`
|
|
return vec4(lessThanEqual(a, b));
|
|
`,$xe=Tt({opSnippet:Rxe,packedOpSnippet:Lxe,cpuKernelImpl:VU,dtype:"bool"}),xH={kernelName:sa,backendName:"webgl",kernelFunc:$xe};function Pxe(r){let{backend:e,attrs:t}=r,{start:n,stop:o,num:s}=t,i=UU(n,o,s);return e.makeTensorInfo([i.length],"float32",i)}var TH={kernelName:kf,backendName:"webgl",kernelFunc:Pxe};var Bxe=`if (x < 0.0) return NAN;
|
|
return log(x);`,Oxe=`
|
|
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;
|
|
`,zxe=Ae({opSnippet:Bxe,packedOpSnippet:Oxe,cpuKernelImpl:jU}),kH={kernelName:$o,backendName:"webgl",kernelFunc:zxe};var Gxe="return log(1.0 + x);",Wxe=Ae({opSnippet:Gxe}),IH={kernelName:vl,backendName:"webgl",kernelFunc:Wxe};var Kxe="return float(a >= 1.0 && b >= 1.0);",Vxe=`
|
|
return vec4(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) *
|
|
vec4(greaterThanEqual(b, vec4(1.0))));
|
|
`,Uxe=Tt({opSnippet:Kxe,packedOpSnippet:Vxe,dtype:"bool"}),vH={kernelName:wl,backendName:"webgl",kernelFunc:Uxe};var jxe="return float(!(x >= 1.0));",Hxe=Ae({opSnippet:jxe}),wH={kernelName:uc,backendName:"webgl",kernelFunc:Hxe};var qxe="return float(a >= 1.0 || b >= 1.0);",Xxe=`
|
|
return min(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) +
|
|
vec4(greaterThanEqual(b, vec4(1.0))),
|
|
vec4(1.0));
|
|
`,Yxe=Tt({opSnippet:qxe,packedOpSnippet:Xxe,dtype:"bool"}),_H={kernelName:pc,backendName:"webgl",kernelFunc:Yxe};var h1=class{constructor(e,t,n,o,s){this.variableNames=["x"];this.outputShape=[];let i=t,a=e[3]-1;this.outputShape=e;let l,u=`float(${n}) + float(${o}) * sum`;s===.5?l=`inversesqrt(${u})`:s===1?l=`1.0/(${u})`:l=`exp(log(${u}) * float(-${s}));`,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 = -${i}; j <= ${i}; j++) {
|
|
int idx = d + j;
|
|
if (idx >= 0 && idx <= ${a}) {
|
|
float z = getX(b, r, c, idx);
|
|
sum += z * z;
|
|
}
|
|
}
|
|
float val = x * ${l};
|
|
setOutput(val);
|
|
}
|
|
`}};var g1=class{constructor(e,t,n,o,s){this.variableNames=["x"];this.outputShape=[];this.packedInputs=!0;this.packedOutput=!0;let i=t,a=e[3]-1;this.outputShape=e;let l,u=`float(${n}) + float(${o}) * sum`;s===.5?l=`inversesqrt(${u})`:s===1?l=`1.0/(${u})`:l=`exp(log(${u}) * float(-${s}));`,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 - ${i};
|
|
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 = - ${i}; j <= ${i}; j++) {
|
|
ivec2 idx = depth + j;
|
|
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
|
|
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${a}));
|
|
|
|
bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
|
|
bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
|
|
|
|
if(depthInRange || depthPlusOneInRange){
|
|
vec4 z = vec4(0.);
|
|
vec4 xFragAtCurrentDepth;
|
|
z.xz = cache.xy;
|
|
if(depthPlusOneInRange && hasNextCol){
|
|
xFragAtCurrentDepth = idx.y != d ?
|
|
getX(b, r, c, idx.y) : xFragAtOutputCoords;
|
|
z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
|
|
if(hasNextRow){
|
|
z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
|
|
}
|
|
}
|
|
cache.xy = z.yw;
|
|
sum += z * z;
|
|
}
|
|
}
|
|
vec4 result = xAtOutputCoords * ${l};
|
|
setOutput(result);
|
|
}
|
|
`}};var Zxe=r=>{let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{depthRadius:s,bias:i,alpha:a,beta:l}=n,u=X().getBool("WEBGL_PACK_NORMALIZATION")?new g1(o.shape,s,i,a,l):new h1(o.shape,s,i,a,l);return t.runWebGLProgram(u,[o],o.dtype)},CH={kernelName:Gu,backendName:"webgl",kernelFunc:Zxe};var b1=class{constructor(e,t,n,o,s){this.variableNames=["inputImage","outputImage","dy"];this.outputShape=[];this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=o,this.beta=s,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(${o}) * norm + float(${n});
|
|
|
|
for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
|
|
if (k < depthBegin){
|
|
continue;
|
|
}
|
|
else if (k >= depthBegin && k < depthEnd){
|
|
float dyi = -2.0 * float(${o})
|
|
* float(${s})
|
|
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
|
|
/ norm;
|
|
if (k == d) {
|
|
dyi += pow(norm, -1.0 * ${s});
|
|
}
|
|
if (k == coords[3]) {
|
|
dyi *= getDy(b, r, c, d);
|
|
result += dyi;
|
|
}
|
|
}
|
|
else {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};var Jxe=r=>{let{inputs:e,backend:t,attrs:n}=r,{x:o,y:s,dy:i}=e,{depthRadius:a,bias:l,alpha:u,beta:p}=n,c=new b1(o.shape,a,l,u,p);return t.runWebGLProgram(c,[o,s,i],o.dtype)},SH={kernelName:If,backendName:"webgl",kernelFunc:Jxe};function NH(r,e,t,n){let o=x.sizeFromShape(e),i=x.sizeFromShape(r.shape)/o,a=de({inputs:{x:r},attrs:{shape:[i,o]},backend:n}),l=Co(a,r.dtype,"max",n),u=de({inputs:{x:l},attrs:{shape:t},backend:n});return n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(l),u}function y1(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{reductionIndices:s,keepDims:i}=n,a=o.shape.length,l=x.parseAxisParam(s,o.shape),u=l,p=C.getAxesPermutation(u,a),c=p!=null,m=t.shouldExecuteOnCPU([o]),f=o;if(c){if(m){let T=t.texData.get(f.dataId).values,k=new Array(a);for(let N=0;N<k.length;N++)k[N]=o.shape[p[N]];let I=fm(T,o.shape,o.dtype,p,k);f=t.makeTensorInfo(k,o.dtype);let S=t.texData.get(f.dataId);S.values=I}else f=Ip(o,p,t);u=C.getInnerMostAxes(u.length,a)}C.assertAxesAreInnerMostDims("max",u,a);let[d,h]=C.computeOutAndReduceShapes(f.shape,u),g=d;i&&(g=C.expandShapeToKeepDim(d,l));let b;if(m){let T=t.texData.get(f.dataId).values,k=HU(T,x.sizeFromShape(h),g,o.dtype);b=t.makeTensorInfo(g,o.dtype);let I=t.texData.get(b.dataId);I.values=k}else b=NH(f,h,g,t);return c&&t.disposeIntermediateTensorInfo(f),b}var AH={kernelName:aa,backendName:"webgl",kernelFunc:y1};var Qxe=CI+`
|
|
return max(a, b);
|
|
`,eTe=`
|
|
vec4 result = vec4(max(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+Tp+`
|
|
return result;
|
|
`,tTe=Tt({opSnippet:Qxe,packedOpSnippet:eTe,cpuKernelImpl:qU}),DH={kernelName:Po,backendName:"webgl",kernelFunc:tTe};function rTe(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e;Za(o,"maxPool");let{filterSize:s,strides:i,pad:a,dimRoundingMode:l}=n,u=1;x.assert(C.eitherStridesOrDilationsAreOne(i,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let p=C.computePool2DInfo(o.shape,s,i,u,a,l);if(p.filterWidth===1&&p.filterHeight===1&&x.arraysEqual(p.inShape,p.outShape))return vr({inputs:{x:o},backend:t});let c=new $i(p,"max",!1);return t.runWebGLProgram(c,[o],o.dtype)}var EH={kernelName:ia,backendName:"webgl",kernelFunc:rTe};function nTe(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{filterSize:s,strides:i,pad:a,dataFormat:l,dimRoundingMode:u}=n,p=[1,1,1],c=C.computePool3DInfo(o.shape,s,i,p,a,u,l),m=new gm(c,"max",!1);return t.runWebGLProgram(m,[o],o.dtype)}var MH={kernelName:Wu,backendName:"webgl",kernelFunc:nTe};var x1=class{constructor(e){this.variableNames=["dy","maxPos"];this.outputShape=e.inShape;let t=e.strideHeight,n=e.strideWidth,o=e.dilationHeight,s=e.effectiveFilterHeight,i=e.effectiveFilterWidth,a=s-1-e.padInfo.top,l=i-1-e.padInfo.left,u=s*i-1;this.userCode=`
|
|
const ivec2 pads = ivec2(${a}, ${l});
|
|
|
|
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 < ${s};
|
|
wR += ${o}) {
|
|
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 < ${i}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${n}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(b, idyR, idyC, d);
|
|
int maxPosValue = ${u} - int(getMaxPos(b, idyR, idyC, d));
|
|
|
|
// Get the current value, check it against the value from the
|
|
// position matrix.
|
|
int curPosValue = wR * ${i} + wC;
|
|
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
|
|
|
dotProd += dyValue * mask;
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},T1=class{constructor(e){this.variableNames=["dy","maxPos"];this.outputShape=e.inShape;let t=e.strideDepth,n=e.strideHeight,o=e.strideWidth,s=e.dilationDepth,i=e.dilationHeight,a=e.dilationWidth,l=e.effectiveFilterDepth,u=e.effectiveFilterHeight,p=e.effectiveFilterWidth,c=l-1-e.padInfo.front,m=u-1-e.padInfo.top,f=p-1-e.padInfo.left,d=l*u*p-1;this.userCode=`
|
|
const ivec3 pads = ivec3(${c}, ${m}, ${f});
|
|
|
|
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 < ${l};
|
|
wD += ${s}) {
|
|
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 < ${u};
|
|
wR += ${i}) {
|
|
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 < ${p};
|
|
wC += ${a}) {
|
|
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);
|
|
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 * ${u} * ${p} +
|
|
wR * ${p} + wC;
|
|
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
|
|
|
dotProd += dyValue * mask;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function oTe(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,input:s}=e,i=s,{filterSize:a,strides:l,pad:u,dimRoundingMode:p}=n,c=[1,1,1],m=C.computePool3DInfo(i.shape,a,l,c,u,p),f=new gm(m,"max",!0),d=t.runWebGLProgram(f,[i],i.dtype),h=new T1(m),g=t.runWebGLProgram(h,[o,d],i.dtype);return t.disposeIntermediateTensorInfo(d),g}var FH={kernelName:wf,backendName:"webgl",kernelFunc:oTe};function sTe(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,input:s,output:i}=e,a=s;Za([s,i],"maxPoolGrad");let{filterSize:l,strides:u,pad:p,dimRoundingMode:c}=n,m=C.computePool2DInfo(a.shape,l,u,1,p,c),f=!0,d=new $i(m,"max",f),h=t.runWebGLProgram(d,[a],a.dtype),g=new x1(m),b=t.runWebGLProgram(g,[o,h],a.dtype);return t.disposeIntermediateTensorInfo(h),b}var RH={kernelName:vf,backendName:"webgl",kernelFunc:sTe};function LH(r,e,t,n){let o=new $i(t,"max",!1),s=n.runWebGLProgram(o,[r],"float32");o=new $i(t,"max",!0,!0,e);let i=n.runWebGLProgram(o,[r],"float32");return[s,i]}var $H={kernelName:_f,backendName:"webgl",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{x:n}=r,{filterSize:o,strides:s,pad:i,includeBatchInIndex:a}=e,l=t;x.assert(n.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${n.shape.length}.`);let u=[1,1];x.assert(C.eitherStridesOrDilationsAreOne(s,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${u}'`);let p=C.computePool2DInfo(n.shape,o,s,u,i),[c,m]=LH(n,a,p,l);return[c,m]}};function PH(r,e,t,n){let o=x.sizeFromShape(e),i=x.sizeFromShape(r.shape)/o,a=de({inputs:{x:r},attrs:{shape:[i,o]},backend:n}),l=Co(a,"float32","mean",n),u=de({inputs:{x:l},attrs:{shape:t},backend:n});return n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(l),u}var BH={kernelName:la,backendName:"webgl",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{x:n}=r,{keepDims:o,axis:s}=e,i=t,a=n.shape.length,l=x.parseAxisParam(s,n.shape),u=l,p=C.getAxesPermutation(u,a),c=p!=null,m=i.shouldExecuteOnCPU([n]),f=[],d=n;if(c){if(m){let k=i.texData.get(d.dataId).values,I=new Array(a);for(let F=0;F<I.length;F++)I[F]=n.shape[p[F]];let S=fm(k,n.shape,n.dtype,p,I);d=i.makeTensorInfo(I,n.dtype);let N=i.texData.get(d.dataId);N.values=S}else d=Ip(n,p,i);f.push(d),u=C.getInnerMostAxes(u.length,a)}C.assertAxesAreInnerMostDims("sum",u,a);let[h,g]=C.computeOutAndReduceShapes(d.shape,u),b=h;o&&(b=C.expandShapeToKeepDim(h,l));let y=PH(d,g,b,i);for(let T of f)i.disposeIntermediateTensorInfo(T);return y}};function aTe(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,keepDims:i}=n,a=o.shape.length,l=x.parseAxisParam(s,o.shape),u=l,p=C.getAxesPermutation(u,a),c=o;p!=null&&(c=rr({inputs:{x:o},backend:t,attrs:{perm:p}}),u=C.getInnerMostAxes(u.length,o.shape.length)),C.assertAxesAreInnerMostDims("min",u,a);let[m,f]=C.computeOutAndReduceShapes(c.shape,u),d=x.sizeFromShape(f),h=de({inputs:{x:c},backend:t,attrs:{shape:[-1,d]}}),g=Co(h,h.dtype,"min",t),b;if(i){let y=C.expandShapeToKeepDim(m,l);b=de({inputs:{x:g},backend:t,attrs:{shape:y}})}else b=de({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),p!=null&&t.disposeIntermediateTensorInfo(c),b}var OH={kernelName:ua,backendName:"webgl",kernelFunc:aTe};var iTe=CI+`
|
|
return min(a, b);
|
|
`,lTe=`
|
|
vec4 result = vec4(min(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+Tp+`
|
|
return result;
|
|
`,uTe=Tt({opSnippet:iTe,packedOpSnippet:lTe,cpuKernelImpl:XU}),zH={kernelName:Bo,backendName:"webgl",kernelFunc:uTe};var k1=class{constructor(e,t,n){this.variableNames=["x"];this.outputShape=t.map((p,c)=>p[0]+e[c]+p[1]);let o=e.length,s=Xe(o),i=t.map(p=>p[0]).join(","),a=t.map((p,c)=>p[0]+e[c]).join(","),l=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,o),u=n==="reflect"?0:1;if(o===1){this.userCode=`
|
|
int start = ${i};
|
|
int end = ${a};
|
|
|
|
void main() {
|
|
int outC = getOutputCoords();
|
|
if (outC < start) {
|
|
outC = start * 2 - outC - ${u};
|
|
} else if(outC >= end) {
|
|
outC = (end - 1) * 2 - outC + ${u};
|
|
}
|
|
setOutput(getX(outC - start));
|
|
}
|
|
`;return}this.userCode=`
|
|
${s} start = ${s}(${i});
|
|
${s} end = ${s}(${a});
|
|
|
|
void main() {
|
|
${s} outC = getOutputCoords();
|
|
for (int i = 0; i < ${o}; i++) {
|
|
if (outC[i] < start[i]) {
|
|
outC[i] = start[i] * 2 - outC[i] - ${u};
|
|
} else if(outC[i] >= end[i]) {
|
|
outC[i] = (end[i] - 1) * 2 - outC[i] + ${u};
|
|
}
|
|
}
|
|
${s} coords = outC - start;
|
|
setOutput(getX(${l}));
|
|
}
|
|
`}};var I1=class{constructor(e,t,n){this.variableNames=["x"];this.packedInputs=!0;this.packedOutput=!0;this.outputShape=t.map((d,h)=>d[0]+e[h]+d[1]);let o=e.length,s=Xe(o),i=t.map(d=>d[0]).join(","),a=t.map((d,h)=>d[0]+e[h]).join(","),l=Ir("rc",o),u=Ir("source",o),p=`${l[o-1]} < ${this.outputShape[o-1]}`,c=o===1?"source":`vec2(${u.slice(-2).join()})`,m=n==="reflect"?0:1,f="";if(o===1){let d=`
|
|
${s} source = rc;
|
|
if (source < start) {
|
|
source = start * 2 - source - ${m};
|
|
} else if (source >= end) {
|
|
source = (end - 1) * 2 - source + ${m};
|
|
}
|
|
source -= start;
|
|
`;f=`
|
|
${s} rc = outputLoc;
|
|
${d}
|
|
result[0] = getChannel(getX(${u.join()}), ${c});
|
|
${l[o-1]} += 1;
|
|
if(${p}) {
|
|
${d}
|
|
result[1] = getChannel(getX(${u.join()}), ${c});
|
|
}
|
|
`}else{let d=`
|
|
${s} source = rc;
|
|
${s} lt = ${s}(lessThan(source, start));
|
|
${s} gte = ${s}(greaterThanEqual(source, end));
|
|
${s} orig = 1 - (lt + gte);
|
|
source = orig * source +
|
|
lt * (start * 2 - source - ${m}) +
|
|
gte * ((end - 1) * 2 - source + ${m});
|
|
source -= start;
|
|
`;f=`
|
|
${s} rc = outputLoc;
|
|
${d}
|
|
result[0] = getChannel(getX(${u.join()}), ${c});
|
|
${l[o-1]} += 1;
|
|
if(${p}) {
|
|
${d}
|
|
result[1] = getChannel(getX(${u.join()}), ${c});
|
|
}
|
|
rc = outputLoc;
|
|
${l[o-2]} += 1;
|
|
if(${l[o-2]} < ${this.outputShape[o-2]}) {
|
|
${d}
|
|
result[2] = getChannel(getX(${u.join()}), ${c});
|
|
${l[o-1]} += 1;
|
|
if(${p}) {
|
|
${d}
|
|
result[3] = getChannel(getX(${u.join()}), ${c});
|
|
}
|
|
}
|
|
`}this.userCode=`
|
|
const ${s} start = ${s}(${i});
|
|
const ${s} end = ${s}(${a});
|
|
|
|
void main() {
|
|
${s} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${f}
|
|
setOutput(result);
|
|
}
|
|
`}};var pTe=({inputs:r,backend:e,attrs:t})=>{let{x:n}=r,{paddings:o,mode:s}=t,i=X().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new I1(n.shape,o,s):new k1(n.shape,o,s);return e.runWebGLProgram(i,[n],n.dtype)},GH={kernelName:pa,backendName:"webgl",kernelFunc:pTe};var cTe=`if (b == 0.0) return NAN;
|
|
return mod(a, b);`,mTe=`
|
|
vec4 result = mod(a, b);
|
|
vec4 isNaN = vec4(equal(b, vec4(0.0)));
|
|
`+Tp+`
|
|
return result;
|
|
`,fTe=Tt({opSnippet:cTe,packedOpSnippet:mTe}),WH={kernelName:_l,backendName:"webgl",kernelFunc:fTe};var v1=class{constructor(e,t,n){this.variableNames=["probs"];this.outputShape=[e,n],this.userCode=`
|
|
uniform float seed;
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
|
|
float r = random(seed);
|
|
float cdf = 0.0;
|
|
|
|
for (int i = 0; i < ${t-1}; i++) {
|
|
cdf += getProbs(batch, i);
|
|
|
|
if (r < cdf) {
|
|
setOutput(float(i));
|
|
return;
|
|
}
|
|
}
|
|
|
|
// If no other event happened, last event happened.
|
|
setOutput(float(${t-1}));
|
|
}
|
|
`}getCustomSetupFunc(e){return(t,n)=>{this.seedLoc==null&&(this.seedLoc=t.getUniformLocation(n,"seed")),t.gl.uniform1f(this.seedLoc,e)}}};var dTe=`
|
|
if (a == b) {
|
|
return 1.0;
|
|
};
|
|
return a / b;`,hTe=`
|
|
// 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;
|
|
`,w1=Tt({opSnippet:dTe,packedOpSnippet:hTe,checkOutOfBounds:!0}),KH={kernelName:Zs,backendName:"webgl",kernelFunc:w1};var VH="return a - b;",_1=Tt({opSnippet:VH,packedOpSnippet:VH,supportsComplex:!0,cpuKernelImpl:u4}),UH={kernelName:Wo,backendName:"webgl",kernelFunc:_1};function C1(r){let{inputs:e,backend:t,attrs:n}=r,{logits:o}=e,{dim:s}=n,i=x.parseAxisParam([s],o.shape),a=y1({inputs:{x:o},backend:t,attrs:{reductionIndices:i,keepDims:!1}}),l=C.expandShapeToKeepDim(a.shape,i),u=de({inputs:{x:a},backend:t,attrs:{shape:l}}),p=_1({inputs:{a:o,b:u},backend:t}),c=l1({inputs:{x:p},backend:t}),m=dm({inputs:{x:c},backend:t,attrs:{axis:i,keepDims:!1}}),f=de({inputs:{x:m},backend:t,attrs:{shape:l}}),d=w1({inputs:{a:c,b:f},backend:t});return t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(u),t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(c),t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f),d}var jH={kernelName:Sa,backendName:"webgl",kernelFunc:C1};function gTe(r){let{inputs:e,backend:t,attrs:n}=r,{logits:o}=e,{numSamples:s,seed:i,normalized:a}=n,l=a?o:C1({inputs:{logits:o},backend:t,attrs:{dim:o.shape.length-1}}),u=l.shape[0],p=l.shape[1],c=new v1(u,p,s),m=c.getCustomSetupFunc(i),f=t.runWebGLProgram(c,[l],"int32",m);return a||t.disposeIntermediateTensorInfo(l),f}var HH={kernelName:Cf,backendName:"webgl",kernelFunc:gTe};var qH="return -x;";function bTe(r){let{inputs:e,backend:t}=r,{x:n}=e;if(t.shouldExecuteOnCPU([n])){let s=t.texData.get(n.dataId),[i,a]=ZU(s.values,n.shape,n.dtype);return t.makeTensorInfo(a,n.dtype,i)}let o;return X().getBool("WEBGL_PACK_UNARY_OPERATIONS")?o=new Qa(n.shape,qH):o=new mo(n.shape,qH),t.runWebGLProgram(o,[n],n.dtype)}var XH={kernelName:ca,backendName:"webgl",kernelFunc:bTe};var yTe=gn.nonMaxSuppressionV3Impl;function xTe(r){C.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:e,backend:t,attrs:n}=r,{boxes:o,scores:s}=e,{maxOutputSize:i,iouThreshold:a,scoreThreshold:l}=n,u=t.readSync(o.dataId),p=t.readSync(s.dataId),{selectedIndices:c}=yTe(u,p,i,a,l);return t.makeTensorInfo([c.length],"int32",new Int32Array(c))}var YH={kernelName:Cl,backendName:"webgl",kernelFunc:xTe};var TTe=gn.nonMaxSuppressionV4Impl;function kTe(r){C.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:e,backend:t,attrs:n}=r,{boxes:o,scores:s}=e,{maxOutputSize:i,iouThreshold:a,scoreThreshold:l,padToMaxOutputSize:u}=n,p=t.readSync(o.dataId),c=t.readSync(s.dataId),{selectedIndices:m,validOutputs:f}=TTe(p,c,i,a,l,u);return[t.makeTensorInfo([m.length],"int32",new Int32Array(m)),t.makeTensorInfo([],"int32",new Int32Array([f]))]}var ZH={kernelName:Sl,backendName:"webgl",kernelFunc:kTe};var ITe=gn.nonMaxSuppressionV5Impl;function vTe(r){C.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:e,backend:t,attrs:n}=r,{boxes:o,scores:s}=e,{maxOutputSize:i,iouThreshold:a,scoreThreshold:l,softNmsSigma:u}=n,p=t.readSync(o.dataId),c=t.readSync(s.dataId),m=i,f=a,d=l,h=u,{selectedIndices:g,selectedScores:b}=ITe(p,c,m,f,d,h);return[t.makeTensorInfo([g.length],"int32",new Int32Array(g)),t.makeTensorInfo([b.length],"float32",new Float32Array(b))]}var JH={kernelName:Nl,backendName:"webgl",kernelFunc:vTe};var S1=class{constructor(e,t,n,o){this.variableNames=["indices"];this.outputShape=[e,t],this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int index = round(getIndices(coords.x));
|
|
setOutput(mix(float(${o}), float(${n}),
|
|
float(index == coords.y)));
|
|
}
|
|
`}};var wTe=r=>{let{inputs:e,backend:t,attrs:n}=r,{indices:o}=e,{depth:s,onValue:i,offValue:a}=n,l=x.sizeFromShape(o.shape),u=new S1(l,s,i,a),p=de({inputs:{x:o},backend:t,attrs:{shape:[l]}}),c=t.runWebGLProgram(u,[p],o.dtype);t.disposeIntermediateTensorInfo(p);let m=[...o.shape,s],f=de({inputs:{x:c},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(c),f},QH={kernelName:fa,backendName:"webgl",kernelFunc:wTe};function Gy(r){let{inputs:e,backend:t}=r,{x:n}=e;if(n.dtype==="complex64"){let o=gu({inputs:{input:n},backend:t}),s=Gy({inputs:{x:o},backend:t}),i=bm({inputs:{input:n},backend:t}),a=Gy({inputs:{x:i},backend:t}),l=fo({inputs:{real:s,imag:a},backend:t});return t.disposeIntermediateTensorInfo(o),t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(a),l}else return zy({attrs:{shape:n.shape,dtype:n.dtype,value:n.dtype==="string"?"":0},backend:t})}var eq={kernelName:Ti,backendName:"webgl",kernelFunc:Gy};function tq(r){let{inputs:e,backend:t}=r,{x:n}=e;if(n.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(n.dtype==="complex64"){let o=gu({inputs:{input:n},backend:t}),s=tq({inputs:{x:o},backend:t}),i=bm({inputs:{input:n},backend:t}),a=Gy({inputs:{x:i},backend:t}),l=fo({inputs:{real:s,imag:a},backend:t});return t.disposeIntermediateTensorInfo(o),t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(a),l}else return zy({attrs:{shape:n.shape,dtype:n.dtype,value:1},backend:t})}var rq={kernelName:fi,backendName:"webgl",kernelFunc:tq};function _Te(r){let{inputs:e,backend:t,attrs:n}=r,{axis:o}=n;if(e.length===1)return $I({inputs:{input:e[0]},backend:t,attrs:{dim:o}});let s=e[0].shape,i=e[0].dtype;e.forEach(p=>{x.assertShapesMatch(s,p.shape,"All tensors passed to stack must have matching shapes"),x.assert(i===p.dtype,()=>"All tensors passed to stack must have matching dtypes")});let a=[],l=e.map(p=>{let c=$I({inputs:{input:p},backend:t,attrs:{dim:o}});return a.push(c),c}),u=XD({inputs:l,backend:t,attrs:{axis:o}});return a.forEach(p=>t.disposeIntermediateTensorInfo(p)),u}var nq={kernelName:di,backendName:"webgl",kernelFunc:_Te};var N1=class{constructor(e,t,n){this.variableNames=["x"];this.outputShape=t.map((u,p)=>u[0]+e[p]+u[1]);let o=e.length,s=Xe(o),i=t.map(u=>u[0]).join(","),a=t.map((u,p)=>u[0]+e[p]).join(","),l=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,o);if(o===1){this.userCode=`
|
|
int start = ${i};
|
|
int end = ${a};
|
|
uniform float value;
|
|
|
|
void main() {
|
|
int outC = getOutputCoords();
|
|
if (outC < start || outC >= end) {
|
|
setOutput(value);
|
|
} else {
|
|
setOutput(getX(outC - start));
|
|
}
|
|
}
|
|
`;return}this.userCode=`
|
|
${s} start = ${s}(${i});
|
|
${s} end = ${s}(${a});
|
|
uniform float value;
|
|
|
|
void main() {
|
|
${s} outC = getOutputCoords();
|
|
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
|
|
setOutput(value);
|
|
} else {
|
|
${s} coords = outC - start;
|
|
setOutput(getX(${l}));
|
|
}
|
|
}
|
|
`}getCustomSetupFunc(e){return(t,n)=>{this.valueLoc==null&&(this.valueLoc=t.getUniformLocationNoThrow(n,"value")),t.gl.uniform1f(this.valueLoc,e)}}};var A1=class{constructor(e,t,n){this.variableNames=["x"];this.packedInputs=!0;this.packedOutput=!0;this.outputShape=t.map((h,g)=>h[0]+e[g]+h[1]);let o=e.length,s=Xe(o),i=t.map(h=>h[0]).join(","),a=t.map((h,g)=>h[0]+e[g]).join(","),l=Ir("rc",o),u=Ir("source",o),p=`${l[o-1]} < ${this.outputShape[o-1]}`,c=o===1?"source":`vec2(${u.slice(-2).join()})`,m=[`${s} rc = outputLoc;`,`${l[o-1]} += 1;
|
|
if(${p}) {
|
|
`,o===1?"":`}
|
|
rc = outputLoc;
|
|
${l[o-2]} += 1;
|
|
if(${l[o-2]} < ${this.outputShape[o-2]}) {`,o===1?"":` ${l[o-1]} += 1;
|
|
if(${p}) {`],f=o===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",d="";for(let h=0,g=o===1?2:4;h<g;h++)d+=`
|
|
${m[h]}
|
|
if (${f}) {
|
|
result[${h}] = float(value);
|
|
} else {
|
|
${s} source = rc - start;
|
|
result[${h}] = getChannel(getX(${u.join()}), ${c});
|
|
}
|
|
`;d+=o===1?"} ":"}}",this.userCode=`
|
|
const ${s} start = ${s}(${i});
|
|
const ${s} end = ${s}(${a});
|
|
uniform float value;
|
|
|
|
void main() {
|
|
${s} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${d}
|
|
setOutput(result);
|
|
}
|
|
`}getCustomSetupFunc(e){return(t,n)=>{this.valueLoc==null&&(this.valueLoc=t.getUniformLocationNoThrow(n,"value")),t.gl.uniform1f(this.valueLoc,e)}}};var D1=r=>{let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{paddings:s,constantValue:i}=n,a=X().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new A1(o.shape,s,i):new N1(o.shape,s,i),l=a.getCustomSetupFunc(i);return t.runWebGLProgram(a,[o],o.dtype,l)},oq={kernelName:da,backendName:"webgl",kernelFunc:D1};var CTe=`
|
|
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);
|
|
`,STe=`
|
|
// 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));
|
|
`+Tp+`
|
|
return result;
|
|
`,NTe=Tt({opSnippet:CTe,packedOpSnippet:STe}),sq={kernelName:ha,backendName:"webgl",kernelFunc:NTe};function ATe(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,keepDims:i}=n,a=o.shape.length,l=[],u=x.parseAxisParam(s,o.shape),p=u,c=C.getAxesPermutation(p,a),m=o;c!=null&&(m=rr({inputs:{x:o},backend:t,attrs:{perm:c}}),p=C.getInnerMostAxes(p.length,a),l.push(m)),C.assertAxesAreInnerMostDims("prod",p,a);let f;if(t.shouldExecuteOnCPU([m])){let d=t.texData.get(m.dataId).values,{outVals:h,outShape:g,outDtype:b}=QU(m.shape,m.dtype,d,p);f=t.makeTensorInfo(g,b,h)}else{let[d,h]=C.computeOutAndReduceShapes(m.shape,p),g=x.sizeFromShape(h),b=de({inputs:{x:m},backend:t,attrs:{shape:[-1,g]}}),y=gc(o.dtype),T=Co(b,y,"prod",t);f=de({inputs:{x:T},backend:t,attrs:{shape:d}}),l.push(b),l.push(T)}if(i){l.push(f);let d=C.expandShapeToKeepDim(f.shape,u);f=de({inputs:{x:f},backend:t,attrs:{shape:d}})}return l.forEach(d=>t.disposeIntermediateTensorInfo(d)),f}var aq={kernelName:hi,backendName:"webgl",kernelFunc:ATe};var E1=r=>{let{backend:e,attrs:t}=r,{start:n,stop:o,step:s,dtype:i}=t,a=e4(n,o,s,i);return e.makeTensorInfo([a.length],i,a)},iq={kernelName:Ku,backendName:"webgl",kernelFunc:E1};var DTe="return 1.0 / x;",ETe=Ae({opSnippet:DTe}),lq={kernelName:Al,backendName:"webgl",kernelFunc:ETe};var MTe=Zr+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,FTe=`
|
|
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;
|
|
`,RTe=Ae({opSnippet:MTe,packedOpSnippet:FTe}),uq={kernelName:ba,backendName:"webgl",kernelFunc:RTe};var LTe=Zr+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,$Te=`
|
|
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;
|
|
`,PTe=Ae({opSnippet:LTe,packedOpSnippet:$Te}),pq={kernelName:xa,backendName:"webgl",kernelFunc:PTe};var M1=class{constructor(e,t,n,o,s){this.variableNames=["A"];this.outputShape=[];let[i,a,l,u]=e;this.outputShape=[i,t,n,u];let p=[o&&t>1?a-1:a,o&&n>1?l-1:l],c=[o&&t>1?t-1:t,o&&n>1?n-1:n],m;s?m="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":m="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
|
${p[0]/c[0]},
|
|
${p[1]/c[1]});
|
|
const vec2 inputShapeRC = vec2(${a}.0, ${l}.0);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
ivec2 yRC = coords.yz;
|
|
|
|
// Fractional source index.
|
|
vec2 sourceFracIndexRC = ${m};
|
|
|
|
// Compute the four integer indices.
|
|
ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));
|
|
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);
|
|
}
|
|
`}};var F1=class{constructor(e,t,n,o,s){this.variableNames=["A"];this.packedInputs=!0;this.packedOutput=!0;this.outputShape=[];let[i,a,l,u]=e;this.outputShape=[i,t,n,u];let p=[o&&t>1?a-1:a,o&&n>1?l-1:l],c=[o&&t>1?t-1:t,o&&n>1?n-1:n],m;s?m="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":m="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec3 effectiveInputOverOutputRatioRC = vec3(
|
|
${p[0]/c[0]},
|
|
${p[1]/c[1]},
|
|
${p[1]/c[1]});
|
|
const vec3 inputShapeRC = vec3(${a}.0, ${l}.0,
|
|
${l}.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 = ${m};
|
|
|
|
// Compute the four integer indices.
|
|
ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));
|
|
ivec3 sourceCeilRC = ivec3(
|
|
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
|
|
|
|
// Should we calculate next column and row elements in 2x2 packed cell.
|
|
bool hasNextCol = d < ${u-1};
|
|
bool hasNextRow = coords.z < ${n-1};
|
|
|
|
// In parallel, construct four corners for all four components in
|
|
// packed 2x2 cell.
|
|
vec4 topLeft = vec4(
|
|
getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);
|
|
|
|
vec4 bottomLeft = vec4(
|
|
getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);
|
|
|
|
vec4 topRight = vec4(
|
|
getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);
|
|
|
|
vec4 bottomRight = vec4(
|
|
getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);
|
|
|
|
vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
|
|
|
|
vec4 top = mix(topLeft, topRight, fracRC.yyzz);
|
|
vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
|
|
vec4 newValue = mix(top, bottom, fracRC.x);
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`}};function BTe(r){let{inputs:e,backend:t,attrs:n}=r,{images:o}=e,{alignCorners:s,halfPixelCenters:i,size:a}=n,[l,u]=a,p=X().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new F1(o.shape,l,u,s,i):new M1(o.shape,l,u,s,i);return t.runWebGLProgram(p,[o],"float32")}var cq={kernelName:ya,backendName:"webgl",kernelFunc:BTe};var R1=class{constructor(e,t,n){this.variableNames=["dy"];this.outputShape=[];this.outputShape=t;let[,o,s]=t,[,i,a]=e,l=[n&&i>1?o-1:o,n&&a>1?s-1:s],u=[n&&i>1?i-1:i,n&&a>1?a-1:a],p=l[0]/u[0],c=l[1]/u[1],m=1/p,f=1/c,d=Math.ceil(m)*2+2,h=Math.ceil(f)*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(${p});
|
|
const float widthScale = float(${c});
|
|
|
|
const float invHeightScale = float(${m});
|
|
const float invWidthScale = float(${f});
|
|
|
|
const int winHeight = int(${d});
|
|
const int winWidth = int(${h});
|
|
|
|
// 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 >= ${i}) {
|
|
continue;
|
|
}
|
|
|
|
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
|
|
int dyC = dyCOffset + startDyC;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyC < 0 || dyC >= ${a}) {
|
|
continue;
|
|
}
|
|
|
|
float dxR = float(dyR) * heightScale;
|
|
int topDxRIndex = int(floor(dxR));
|
|
int bottomDxRIndex = int(min(ceil(dxR), ${o-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), ${s-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);
|
|
}
|
|
`}};function OTe(r){let{inputs:e,backend:t,attrs:n}=r,{images:o,dy:s}=e,{alignCorners:i}=n,a=new R1(s.shape,o.shape,i);return t.runWebGLProgram(a,[s],s.dtype)}var mq={kernelName:Nf,backendName:"webgl",kernelFunc:OTe};var L1=class{constructor(e,t,n,o,s){this.variableNames=["A"];this.outputShape=[];let[i,a,l,u]=e;this.outputShape=[i,t,n,u];let p=[o&&t>1?a-1:a,o&&n>1?l-1:l],c=[o&&t>1?t-1:t,o&&n>1?n-1:n],m=o?"0.5":"0.0",f;s?f="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":f="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
|
${p[0]/c[0]},
|
|
${p[1]/c[1]});
|
|
const vec2 inputShapeRC = vec2(${a}.0, ${l}.0);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
ivec2 yRC = coords.yz;
|
|
|
|
// Fractional source index.
|
|
vec2 sourceFracIndexRC = ${f};
|
|
|
|
// Compute the coordinators of nearest neighbor point.
|
|
ivec2 sourceNearestRC = ivec2(
|
|
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${m})));
|
|
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`}};var $1=class{constructor(e,t,n,o,s){this.variableNames=["A"];this.packedInputs=!0;this.packedOutput=!0;this.outputShape=[];let[i,a,l,u]=e;this.outputShape=[i,t,n,u];let p=[o&&t>1?a-1:a,o&&n>1?l-1:l],c=[o&&t>1?t-1:t,o&&n>1?n-1:n],m=o?"0.5":"0.0",f;s?f="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":f="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec3 effectiveInputOverOutputRatioRC = vec3(
|
|
${p[0]/c[0]},
|
|
${p[1]/c[1]},
|
|
${p[1]/c[1]});
|
|
const vec3 inputShapeRC = vec3(${a}.0, ${l}.0,
|
|
${l}.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 = ${f};
|
|
|
|
// Compute the coordinators of nearest neighbor point.
|
|
ivec3 sourceNearestRC = ivec3(
|
|
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${m})));
|
|
|
|
// Should we calculate next column and row elements in 2x2 packed cell.
|
|
bool hasNextCol = d < ${u-1};
|
|
bool hasNextRow = coords.z < ${n-1};
|
|
|
|
vec4 newValue = vec4(
|
|
getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`}};function zTe(r){let{inputs:e,backend:t,attrs:n}=r,{images:o}=e,{alignCorners:s,halfPixelCenters:i,size:a}=n,[l,u]=a,p=X().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new $1(o.shape,l,u,s,i):new L1(o.shape,l,u,s,i);return t.runWebGLProgram(p,[o],o.dtype)}var fq={kernelName:Vu,backendName:"webgl",kernelFunc:zTe};var P1=class{constructor(e,t,n){this.variableNames=["dy"];this.outputShape=[];this.outputShape=t;let[,o,s]=t,[,i,a]=e,l=[n&&i>1?o-1:o,n&&a>1?s-1:s],u=[n&&i>1?i-1:i,n&&a>1?a-1:a],p=l[0]/u[0],c=l[1]/u[1],m=1/p,f=1/c,d=Math.ceil(m)*2+2,h=Math.ceil(f)*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(${p});
|
|
const float widthScale = float(${c});
|
|
|
|
const float invHeightScale = float(${m});
|
|
const float invWidthScale = float(${f});
|
|
|
|
const int winHeight = int(${d});
|
|
const int winWidth = int(${h});
|
|
|
|
// 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 >= ${i}) {
|
|
continue;
|
|
}
|
|
|
|
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
|
|
int dyC = dyCOffset + startDyC;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyC < 0 || dyC >= ${a}) {
|
|
continue;
|
|
}
|
|
|
|
float sourceFracRow =
|
|
float(${l[0]}) *
|
|
(float(dyR) / float(${u[0]}));
|
|
|
|
float sourceFracCol =
|
|
float(${l[1]}) *
|
|
(float(dyC) / float(${u[1]}));
|
|
|
|
int sourceNearestRow = int(min(
|
|
float(int(${o}) - 1),
|
|
${n} ? float(round(sourceFracRow)) :
|
|
float(floor(sourceFracRow))));
|
|
|
|
int sourceNearestCol = int(min(
|
|
float(int(${s}) - 1),
|
|
${n} ? float(round(sourceFracCol)) :
|
|
float(floor(sourceFracCol))));
|
|
|
|
if (r == sourceNearestRow && c == sourceNearestCol) {
|
|
accumulator += getDy(b, dyR, dyC, d);
|
|
}
|
|
}
|
|
}
|
|
// End loop over dy
|
|
|
|
setOutput(accumulator);
|
|
}
|
|
`}};function GTe(r){let{inputs:e,backend:t,attrs:n}=r,{images:o,dy:s}=e,{alignCorners:i}=n,a=new P1(s.shape,o.shape,i);return t.runWebGLProgram(a,[s],s.dtype)}var dq={kernelName:Sf,backendName:"webgl",kernelFunc:GTe};var B1=class{constructor(e,t){this.variableNames=["x"];let n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=e,n===1){this.userCode=`
|
|
void main() {
|
|
int coord = getOutputCoords();
|
|
setOutput(getX(${e[0]} - coord - 1));
|
|
}
|
|
`;return}let o=a=>t.indexOf(a)!==-1&&e[a]!==1?`${e[a]} - coords[${a}] - 1`:`coords[${a}]`,s=e.map((a,l)=>o(l)).join(","),i=Xe(n);this.userCode=`
|
|
void main() {
|
|
${i} coords = getOutputCoords();
|
|
setOutput(getX(${s}));
|
|
}
|
|
`}};var O1=class{constructor(e,t){this.variableNames=["x"];this.packedInputs=!0;this.packedOutput=!0;let n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=e;let o=Ir("rc",n),s=`${o[n-1]} + 1 < ${this.outputShape[n-1]}`,i=`${o[n-2]} + 1 < ${this.outputShape[n-2]}`,a=Xe(n);n===1?this.userCode=`
|
|
void main(){
|
|
int rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result.r = getChannel(getX(${e[0]} - rc - 1),
|
|
${e[0]} - rc - 1);
|
|
if(${s}){
|
|
result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),
|
|
${e[0]} - (rc + 1) - 1);
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`:this.userCode=`
|
|
void main() {
|
|
${a} rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result.r = ${l(o.slice())};
|
|
if(${s}){
|
|
result.g = ${u(o.slice())};
|
|
}
|
|
if(${i}) {
|
|
result.b = ${p(o.slice())};
|
|
if(${s}) {
|
|
result.a = ${c(o.slice())};
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`;function l(d){return m(d)}function u(d){return d[n-1]="("+d[n-1]+" + 1)",m(d)}function p(d){return d[n-2]="("+d[n-2]+" + 1)",m(d)}function c(d){return d[n-1]="("+d[n-1]+" + 1)",d[n-2]="("+d[n-2]+" + 1)",m(d)}function m(d){let h=e.map((y,T)=>f(T,d)),g=h.join(","),b=h.slice(-2).join(",");return`getChannel(getX(${g}), vec2(${b}))`}function f(d,h){return t.indexOf(d)!==-1&&e[d]!==1?`${e[d]} - ${h[d]} - 1`:`${h[d]}`}}};function WTe(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{dims:s}=n,i=o.shape.length,a=x.parseAxisParam(s,o.shape);if(i===0)return vr({inputs:{x:o},backend:t});let l=X().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new O1(o.shape,a):new B1(o.shape,a);return t.runWebGLProgram(l,[o],o.dtype)}var hq={kernelName:Ta,backendName:"webgl",kernelFunc:WTe};var z1=class{constructor(e,t){this.variableNames=["Image"];this.outputShape=[];let n=e[1],o=e[2];this.outputShape=e;let s="";typeof t=="number"?s=`float outputValue = ${t.toFixed(2)};`:s=`
|
|
vec3 fill = vec3(${t.join(",")});
|
|
float outputValue = fill[coords[3]];`,this.userCode=`
|
|
uniform vec4 params;
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int x = coords[2];
|
|
int y = coords[1];
|
|
float coordXFloat = (float(x) - params[0]) * params[3] -
|
|
(float(y) - params[1]) * params[2];
|
|
float coordYFloat = (float(x) - params[0]) * params[2] +
|
|
(float(y) - params[1]) * params[3];
|
|
int coordX = int(round(coordXFloat + params[0]));
|
|
int coordY = int(round(coordYFloat + params[1]));
|
|
${s}
|
|
if(coordX >= 0 && coordX < ${o} && coordY >= 0 && coordY < ${n}) {
|
|
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
|
|
}
|
|
setOutput(outputValue);
|
|
}
|
|
`}getCustomSetupFunc(e,t,n,o){return(s,i)=>{this.paramsLoc==null&&(this.paramsLoc=s.getUniformLocationNoThrow(i,"params")),s.gl.uniform4f(this.paramsLoc,e,t,n,o)}}};var gq={kernelName:Bl,backendName:"webgl",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{image:n}=r,{radians:o,fillValue:s,center:i}=e,a=t,l=new z1(n.shape,s),[u,p]=C.getImageCenter(i,n.shape[1],n.shape[2]),c=l.getCustomSetupFunc(u,p,Math.sin(o),Math.cos(o));return a.runWebGLProgram(l,[n],n.dtype,c)}};var KTe=`
|
|
// 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;
|
|
}
|
|
}
|
|
`,VTe=Ae({opSnippet:KTe}),bq={kernelName:ka,backendName:"webgl",kernelFunc:VTe};var UTe="return inversesqrt(x);",jTe=Ae({opSnippet:UTe,cpuKernelImpl:t4}),yq={kernelName:zo,backendName:"webgl",kernelFunc:jTe};var Wy=class{constructor(e,t,n,o,s,i,a=!0){this.variableNames=["updates","indices","defaultValue"];this.outputShape=i;let l=Xe(s.length),u=Xe(i.length),p="";n===1?p="i":n===2&&(p="i, j");let c=`getIndices(${p})`,m="";o===1?m="i":o===2&&(m="i, coords[1]");let f=`getUpdates(${m})`,d=t>1?"strides[j]":"strides";this.userCode=`
|
|
${l} strides = ${l}(${s});
|
|
|
|
void main() {
|
|
${u} 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(${c});
|
|
flattenedIndex += index * ${d};
|
|
}
|
|
if (flattenedIndex == coords[0]) {
|
|
sum += ${f};
|
|
found = true;
|
|
}
|
|
}
|
|
setOutput(mix(getDefaultValue(), sum, float(found)));
|
|
}
|
|
`}};function HTe(r){let{inputs:e,backend:t,attrs:n}=r,{indices:o,updates:s}=e,{shape:i}=n,{sliceRank:a,numUpdates:l,sliceSize:u,strides:p,outputSize:c}=C.calculateShapes(s,o,i),m=[c/u,u];if(c===0)return t.makeTensorInfo(i,o.dtype);let f=de({inputs:{x:o},backend:t,attrs:{shape:[l,a]}}),d=de({inputs:{x:s},backend:t,attrs:{shape:[l,u]}}),h=t.makeTensorInfo([],"float32",new Float32Array([0])),g=new Wy(l,a,f.shape.length,d.shape.length,p,m),b=t.runWebGLProgram(g,[d,f,h],d.dtype),y=de({inputs:{x:b},backend:t,attrs:{shape:i}});return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(b),t.disposeIntermediateTensorInfo(h),y}var xq={kernelName:Dl,backendName:"webgl",kernelFunc:HTe};var G1=class{constructor(e,t,n){this.variableNames=["c","a","b"];this.outputShape=t;let o,s;if(n>4)throw Error(`Where for rank ${n} is not yet supported`);if(n===1)s="resRC",o="resRC";else{let a=["resRC.x","resRC.y","resRC.z","resRC.w"],l=[],u=[];for(let p=0;p<t.length;p++)u.push(`${a[p]}`),p<e&&l.push(`${a[p]}`);o=l.join(),s=u.join()}let i=Xe(n);this.userCode=`
|
|
void main() {
|
|
${i} resRC = getOutputCoords();
|
|
float cVal = getC(${o});
|
|
if (cVal >= 1.0) {
|
|
setOutput(getA(${s}));
|
|
} else {
|
|
setOutput(getB(${s}));
|
|
}
|
|
}
|
|
`}};function qTe(r){let{inputs:e,backend:t}=r,{condition:n,t:o,e:s}=e,i=new G1(n.shape.length,o.shape,o.shape.length);return t.runWebGLProgram(i,[n,o,s],Mr(o.dtype,s.dtype))}var Tq={kernelName:bi,backendName:"webgl",kernelFunc:qTe};var XTe=`
|
|
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
|
|
// see: https://arxiv.org/abs/1706.02515
|
|
float scaleAlpha = ${C.SELU_SCALEALPHA};
|
|
float scale = ${C.SELU_SCALE};
|
|
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
|
|
`,YTe=Ae({opSnippet:XTe}),kq={kernelName:El,backendName:"webgl",kernelFunc:YTe};var ZTe="return 1.0 / (1.0 + exp(-1.0 * x));",JTe=Ae({opSnippet:ZTe}),Iq={kernelName:wa,backendName:"webgl",kernelFunc:JTe};var QTe=`
|
|
if (isnan(x)) { return 0.0; }
|
|
return sign(x);
|
|
`,eke=Ae({opSnippet:QTe}),vq={kernelName:Fl,backendName:"webgl",kernelFunc:eke};var tke=SI+`
|
|
return sin(x);
|
|
`,rke=Ae({opSnippet:tke}),wq={kernelName:va,backendName:"webgl",kernelFunc:rke};var nke=`
|
|
float e2x = exp(x);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`,oke=Ae({opSnippet:nke}),_q={kernelName:Ml,backendName:"webgl",kernelFunc:oke};var ske=`
|
|
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;
|
|
`,ake=Ae({opSnippet:ske}),Cq={kernelName:Rl,backendName:"webgl",kernelFunc:ake};var ike=r=>{let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{blockShape:s,paddings:i}=n;x.assert(o.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let a=s.reduce((b,y)=>b*y),l=[[0,0]];l.push(...i);for(let b=1+s.length;b<o.shape.length;++b)l.push([0,0]);let u=[],p=D1({inputs:{x:o},backend:t,attrs:{paddings:l,constantValue:0}}),c=C.getReshaped(p.shape,s,a,!1),m=C.getPermuted(c.length,s.length,!1),f=C.getReshapedPermuted(p.shape,s,a,!1),d=de({inputs:{x:p},backend:t,attrs:{shape:c}}),h=rr({inputs:{x:d},backend:t,attrs:{perm:m}}),g=de({inputs:{x:h},backend:t,attrs:{shape:f}});return u.push(p),u.push(d),u.push(h),u.forEach(b=>t.disposeIntermediateTensorInfo(b)),g},Sq={kernelName:Uu,backendName:"webgl",kernelFunc:ike};function lke(r){let{inputs:e,backend:t}=r,{indices:n,values:o,denseShape:s,defaultValue:i}=e;if(s.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
|
|
${s.shape}`);if(n.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
|
|
${n.shape}`);if(o.shape.length!==1)throw new Error(`Values must be a vector, saw:
|
|
${o.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
|
|
${i.shape}`);let a=t.readSync(n.dataId),l=t.readSync(o.dataId),u=t.readSync(s.dataId),p=t.readSync(i.dataId)[0],[c,m,f,d,h]=n4(a,n.shape,n.dtype,l,o.dtype,u,p);return[t.makeTensorInfo(m,n.dtype,c),t.makeTensorInfo([m[0]],o.dtype,f),t.makeTensorInfo([d.length],"bool",new Uint8Array(d.map(g=>Number(g)))),t.makeTensorInfo([h.length],n.dtype,new Int32Array(h))]}var Nq={kernelName:Af,backendName:"webgl",kernelFunc:lke};function uke(r){let{inputs:e,backend:t}=r,{inputIndices:n,inputShape:o,newShape:s}=e;if(n.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${n.shape}`);if(o.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${o.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=Array.from(t.readSync(o.dataId)),a=t.readSync(n.dataId),l=Array.from(t.readSync(s.dataId)),[u,p,c]=o4(a,n.shape,n.dtype,i,l);return[t.makeTensorInfo(p,n.dtype,u),t.makeTensorInfo([c.length],s.dtype,new Int32Array(c))]}var Aq={kernelName:Df,backendName:"webgl",kernelFunc:uke};function pke(r){let{inputs:e,backend:t}=r,{data:n,indices:o,segmentIds:s}=e;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${o.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${s.shape}`);let i=t.readSync(n.dataId),a=t.readSync(o.dataId),l=t.readSync(s.dataId),[u,p]=wI(i,n.shape,n.dtype,a,l,!0);return t.makeTensorInfo(p,n.dtype,u)}var Dq={kernelName:Ef,backendName:"webgl",kernelFunc:pke};function cke(r){let{inputs:e,backend:t}=r,{data:n,indices:o,segmentIds:s}=e;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(o.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${o.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${s.shape}`);let i=t.readSync(n.dataId),a=t.readSync(o.dataId),l=t.readSync(s.dataId),[u,p]=wI(i,n.shape,n.dtype,a,l);return t.makeTensorInfo(p,n.dtype,u)}var Eq={kernelName:Mf,backendName:"webgl",kernelFunc:cke};function mke(r){let{inputs:e,backend:t,attrs:n}=r,{sparseIndices:o,sparseValues:s,defaultValue:i}=e,{outputShape:a}=n,{sliceRank:l,numUpdates:u,strides:p,outputSize:c}=C.calculateShapes(s,o,a),m=!1,f=new Wy(u,l,o.shape.length,s.shape.length,p,[c,1],m),d=t.runWebGLProgram(f,[s,o,i],s.dtype),h=de({inputs:{x:d},backend:t,attrs:{shape:a}});return t.disposeIntermediateTensorInfo(d),h}var Mq={kernelName:Ff,backendName:"webgl",kernelFunc:mke};function fke(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{numOrSizeSplits:s,axis:i}=n,a=x.parseAxisParam(i,o.shape)[0],l=C.prepareSplitSize(o,s,a),u=o.shape.length,p=new Array(u).fill(0),c=o.shape.slice();return l.map(m=>{let f=[...c];f[a]=m;let d=hu({inputs:{x:o},backend:t,attrs:{begin:p,size:f}});return p[a]+=m,d})}var Fq={kernelName:yi,backendName:"webgl",kernelFunc:fke};var dke="return sqrt(x);",hke=Ae({opSnippet:dke}),Rq={kernelName:_a,backendName:"webgl",kernelFunc:hke};var gke="return x * x;",bke=Ae({opSnippet:gke}),Lq={kernelName:ju,backendName:"webgl",kernelFunc:bke};var $q="return (a - b) * (a - b);",yke=Tt({opSnippet:$q,packedOpSnippet:$q}),Pq={kernelName:Go,backendName:"webgl",kernelFunc:yke};function xke({inputs:r,attrs:e,backend:t}){let{x:n}=r,o=Zr+`
|
|
return x > 0.0 ? 1.0 : float(${e.alpha});
|
|
`,s=new mo(n.shape,o);return t.runWebGLProgram(s,[n],n.dtype)}var Bq={kernelName:cs,backendName:"webgl",kernelFunc:xke};var W1=class{constructor(e,t,n){this.variableNames=["x"];this.outputShape=n;let o=n.length,s=Xe(n.length),i=Xe(n.length),a="";if(o===1)a="coords * strides + begin";else{let l=0;a=n.map((u,p)=>(l++,n.length===1?`coords * strides[${p}] + begin[${p}]`:`coords[${l-1}] * strides[${p}] + begin[${p}]`)).join(",")}this.userCode=`
|
|
${s} begin = ${s}(${e});
|
|
${s} strides = ${s}(${t});
|
|
|
|
void main() {
|
|
${i} coords = getOutputCoords();
|
|
setOutput(getX(${a}));
|
|
}
|
|
`}};function Tke(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{begin:s,end:i,strides:a,beginMask:l,endMask:u,ellipsisMask:p,newAxisMask:c,shrinkAxisMask:m}=n,{nonStrided:f,$begin:d,$strides:h,size:g,newShape:b,outShape:y}=br.sliceInfo(o.shape,s,i,a,l,u,p,c,m),T=de({inputs:{x:o},backend:t,attrs:{shape:b}}),k;if(f){let S=hu({inputs:{x:T},backend:t,attrs:{begin:d,size:g}});k=de({inputs:{x:S},backend:t,attrs:{shape:y}}),t.disposeIntermediateTensorInfo(S)}else if(y.some(S=>S===0))k=t.makeTensorInfo(y,o.dtype,[]);else if(t.shouldExecuteOnCPU([T])){let F=t.texData.get(T.dataId).values,$=ve(T.shape,T.dtype,F),O=s4(y,$,h,d);k=t.makeTensorInfo(y,T.dtype,O.values)}else{let N=new W1(d,h,y);k=t.runWebGLProgram(N,[T],T.dtype)}let I=de({inputs:{x:k},backend:t,attrs:{shape:y}});return t.disposeIntermediateTensorInfo(T),t.disposeIntermediateTensorInfo(k),I}var Oq={kernelName:Ll,backendName:"webgl",kernelFunc:Tke};function kke(r){let{inputs:e,backend:t,attrs:n}=r,{separator:o,nGramWidths:s,leftPad:i,rightPad:a,padWidth:l,preserveShortSequences:u}=n,{data:p,dataSplits:c}=e,m=t.readSync(p.dataId),f=t.readSync(c.dataId),[d,h]=a4(m,f,o,s,i,a,l,u);return[t.makeTensorInfo([d.length],"string",d),t.makeTensorInfo(c.shape,"int32",h)]}var zq={kernelName:Rf,backendName:"webgl",kernelFunc:kke};function Ike(r){let{inputs:e,backend:t,attrs:n}=r,{skipEmpty:o}=n,{input:s,delimiter:i}=e;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(s.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${s.shape}`);if(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);let a=t.readSync(s.dataId),l=t.readSync(i.dataId)[0],[u,p,c]=i4(a,l,o),m=p.length;return[t.makeTensorInfo([m,2],"int32",u),t.makeTensorInfo([m],"string",p),t.makeTensorInfo([2],"int32",new Int32Array(c))]}var Gq={kernelName:Lf,backendName:"webgl",kernelFunc:Ike};function vke(r){let{inputs:e,backend:t,attrs:n}=r,{numBuckets:o}=n,{input:s}=e;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(o<=0)throw new Error("Number of buckets must be at least 1");let i=t.readSync(s.dataId),a=l4(i,o);return t.makeTensorInfo(s.shape,"int32",a)}var Wq={kernelName:$f,backendName:"webgl",kernelFunc:vke};var wke="return tan(x);",_ke=Ae({opSnippet:wke}),Kq={kernelName:Na,backendName:"webgl",kernelFunc:_ke};var Cke=`
|
|
float e2x = exp(-2.0 * abs(x));
|
|
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
|
|
`,Ske=Ae({opSnippet:Cke}),Vq={kernelName:Aa,backendName:"webgl",kernelFunc:Ske};var K1=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let i=0;i<n.length;i++)n[i]=e[i]*t[i];this.outputShape=n,this.rank=n.length;let o=Xe(this.rank),s=Nke(e);this.userCode=`
|
|
void main() {
|
|
${o} resRC = getOutputCoords();
|
|
setOutput(getA(${s}));
|
|
}
|
|
`}};function Nke(r){let e=r.length;if(e>5)throw Error(`Tile for rank ${e} is not yet supported`);if(e===1)return`imod(resRC, ${r[0]})`;let t=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],n=[];for(let o=0;o<r.length;o++)n.push(`imod(${t[o]}, ${r[o]})`);return n.join()}function V1(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{reps:s}=n;if(o.dtype==="string"||o.shape.length>5){let l=t.readSync(o.dataId),u=o.dtype==="string"?l.map(m=>x.decodeString(m)):l,p=ve(o.shape,o.dtype,u),c=p4(p,s);return t.makeTensorInfo(c.shape,c.dtype,c.values)}let i=new K1(o.shape,s);return t.runWebGLProgram(i,[o],o.dtype)}var Uq={kernelName:Ko,backendName:"webgl",kernelFunc:V1};function Ake(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{k:s,sorted:i}=n,a=t.readSync(o.dataId),[l,u]=c4(a,o.shape,o.dtype,s,i);return[t.makeTensorInfo(l.shape,l.dtype,l.values),t.makeTensorInfo(u.shape,u.dtype,u.values)]}var jq={kernelName:$l,backendName:"webgl",kernelFunc:Ake};var U1=class{constructor(e,t,n,o,s,i){this.variableNames=["Image","Transforms"];this.outputShape=i;let a=n==="nearest"?1:2,l;switch(o){case"constant":l=1;break;case"reflect":l=2;break;case"wrap":l=3;break;case"nearest":l=4;break;default:l=1;break}this.userCode=`
|
|
float mapCoord(float outCoord, float len) {
|
|
float inCoord = outCoord;
|
|
if(${l} == 2) {
|
|
if (inCoord < 0.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz2 = 2.0 * len;
|
|
if (inCoord < sz2) {
|
|
inCoord = sz2 * float(int(float(-inCoord / sz2))) +
|
|
inCoord;
|
|
}
|
|
inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;
|
|
}
|
|
} else if (inCoord > len - 1.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz2 = 2.0 * len;
|
|
inCoord -= sz2 * float(int(float(inCoord / sz2)));
|
|
if (inCoord >= len) {
|
|
inCoord = sz2 - inCoord - 1.0;
|
|
}
|
|
}
|
|
}
|
|
return clamp(inCoord, 0.0, len - 1.0);
|
|
} else if (${l} == 3) {
|
|
if (inCoord < 0.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz = len - 1.0;
|
|
inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);
|
|
}
|
|
} else if (inCoord > len - 1.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz = len - 1.0;
|
|
inCoord -= len * float(int(float(inCoord / sz)));
|
|
}
|
|
}
|
|
return clamp(inCoord, 0.0, len - 1.0);
|
|
} else if (${l} == 4) {
|
|
return clamp(outCoord, 0.0, len - 1.0);
|
|
} else {
|
|
return outCoord;
|
|
}
|
|
}
|
|
|
|
float readWithFillValue(int batch, int coordY, int coordX,
|
|
int channel) {
|
|
float outputValue;
|
|
if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) {
|
|
outputValue = getImage(batch, coordY, coordX, channel);
|
|
} else {
|
|
outputValue = float(${s});
|
|
}
|
|
return outputValue;
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
float outputValue;
|
|
int batch = coords[0];
|
|
int x = coords[2];
|
|
int y = coords[1];
|
|
int channel = coords[3];
|
|
float xf = float(x);
|
|
float yf = float(y);
|
|
float a1 = getTransforms(batch, 0);
|
|
float a2 = getTransforms(batch, 1);
|
|
float a3 = getTransforms(batch, 2);
|
|
float b1 = getTransforms(batch, 3);
|
|
float b2 = getTransforms(batch, 4);
|
|
float b3 = getTransforms(batch, 5);
|
|
float c1 = getTransforms(batch, 6);
|
|
float c2 = getTransforms(batch, 7);
|
|
float projection = c1 * xf + c2 * yf + 1.0;
|
|
if (projection == 0.0) {
|
|
outputValue = float(${s});
|
|
} else {
|
|
float inX = (a1 * xf + a2 * yf + a3) / projection;
|
|
float inY = (b1 * xf + b2 * yf + b3) / projection;
|
|
float mapX = mapCoord(inX, float(${t}));
|
|
float mapY = mapCoord(inY, float(${e}));
|
|
|
|
if (${a} == 1) {
|
|
int coordY = int(round(mapY));
|
|
int coordX = int(round(mapX));
|
|
outputValue = readWithFillValue(batch, coordY, coordX,
|
|
channel);
|
|
} else {
|
|
float yFloor = floor(mapY);
|
|
float xFloor = floor(mapX);
|
|
float yCeil = yFloor + 1.0;
|
|
float xCeil = xFloor + 1.0;
|
|
float valueYFloor = (xCeil - mapX) *
|
|
readWithFillValue(batch, int(yFloor), int(xFloor), channel) +
|
|
(mapX - xFloor) *
|
|
readWithFillValue(batch, int(yFloor), int(xCeil), channel);
|
|
float valueYCeil = (xCeil - mapX) *
|
|
readWithFillValue(batch, int(yCeil), int(xFloor), channel) +
|
|
(mapX - xFloor) *
|
|
readWithFillValue(batch, int(yCeil), int(xCeil), channel);
|
|
outputValue = (yCeil - mapY) * valueYFloor +
|
|
(mapY - yFloor) * valueYCeil;
|
|
}
|
|
}
|
|
setOutput(outputValue);
|
|
}
|
|
`}};function Dke(r){let{inputs:e,backend:t,attrs:n}=r,{image:o,transforms:s}=e,{interpolation:i,fillMode:a,fillValue:l,outputShape:u}=n,[p,c,m,f]=o.shape,[d,h]=u!=null?u:[c,m],g=[p,d,h,f],b=new U1(c,m,i,a,l,g);return t.runWebGLProgram(b,[o,s],"float32")}var Hq={kernelName:Pl,backendName:"webgl",kernelFunc:Dke};function Eke(r){let{inputs:e,attrs:t,backend:n}=r,{axis:o}=t,{x:s}=e;Za(s,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let i=n.readSync(s.dataId),{outputValues:a,outputShape:l,indices:u}=m4(i,o,s.shape,s.dtype);return[n.makeTensorInfo(l,s.dtype,a),n.makeTensorInfo([u.length],"int32",u)]}var qq={kernelName:Pf,backendName:"webgl",kernelFunc:Eke};function Mke(r){let{inputs:e,backend:t,attrs:n}=r,{value:o}=e,{axis:s}=n;s<0&&(s+=o.shape.length);let i=o,a=i.shape.length,l=o.shape[s],u=new Array(a-1),p=0;for(let h=0;h<a;h++)h!==s&&(u[p++]=i.shape[h]);let c=[],m=new Array(a).fill(0),f=i.shape.slice();f[s]=1;let d=new Array(l);for(let h=0;h<d.length;h++){m[s]=h;let g=hu({inputs:{x:i},backend:t,attrs:{begin:m,size:f}}),b=de({inputs:{x:g},backend:t,attrs:{shape:u}});d[h]=b,c.push(g)}return c.forEach(h=>t.disposeIntermediateTensorInfo(h)),d}var Xq={kernelName:xi,backendName:"webgl",kernelFunc:Mke};var j1=class{constructor(e,t){this.variableNames=["x","segmentIds"];let n=e.windowSize,o=e.batchSize,s=e.inSize,i=e.numSegments,a=i*Math.ceil(s/n);this.outputShape=[o,a];let l="0.0",u="sumValue",p=Math.floor(n/4)*4,c=n%4,m=`
|
|
sumValue += dot(values, segFilter);
|
|
`,f="";s%n>0&&(f=`
|
|
if (inIdx < 0 || inIdx >= ${s}) {
|
|
return initializationValue;
|
|
}
|
|
`);let d="";s%n>0&&(d=`
|
|
if (inIdx < 0 || inIdx >= ${s}) {
|
|
return -1.0;
|
|
}
|
|
`),this.userCode=`
|
|
const float initializationValue = ${l};
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${f}
|
|
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(
|
|
${i})) * float(${n}));
|
|
int currentSeg = int(mod(float(outIdx), float(${i})));
|
|
|
|
float sumValue = 0.0;
|
|
|
|
for (int i = 0; i < ${p}; 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
|
|
);
|
|
|
|
${m}
|
|
}
|
|
|
|
int inIdx = inOffset + ${p};
|
|
if (${c===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
|
|
);
|
|
|
|
${m}
|
|
} else if (${c===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
|
|
);
|
|
|
|
${m}
|
|
} else if (${c===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
|
|
);
|
|
|
|
${m}
|
|
}
|
|
setOutput(${u});
|
|
}
|
|
`}};function Fke(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,segmentIds:s}=e,{numSegments:i}=n,a=o.shape.length,l=[],u=0,p=C.getAxesPermutation([u],a),c=o;p!=null&&(c=rr({inputs:{x:o},backend:t,attrs:{perm:p}}),l.push(c),u=C.getInnerMostAxes(1,a)[0]);let m=C.segment_util.computeOutShape(c.shape,u,i),f=x.sizeFromShape([c.shape[u]]),d=de({inputs:{x:c},backend:t,attrs:{shape:[-1,f]}});l.push(d);let h=gc(o.dtype),g=(k,I,S,N,F)=>{let $=k.shape[0],O=k.shape[1],V=C.segment_util.segOpComputeOptimalWindowSize(O,F),q={windowSize:V,inSize:O,batchSize:$,numSegments:F},W=new j1(q,I),Y=t.compileAndRun(W,[k,S],N);if(l.push(Y),Y.shape[1]===F)return Y;let Z=E1({backend:t,attrs:{start:0,stop:F,step:1,dtype:"float32"}}),J=V1({inputs:{x:Z},backend:t,attrs:{reps:[O/V]}});return l.push(Z),l.push(J),g(Y,I,J,N,F)},b=g(d,"unsortedSegmentSum",s,h,i),y=de({inputs:{x:b},backend:t,attrs:{shape:m}}),T=y;if(p!=null){l.push(y);let k=C.getUndoAxesPermutation(p);T=rr({inputs:{x:T},backend:t,attrs:{perm:k}})}return l.forEach(k=>t.disposeIntermediateTensorInfo(k)),T}var Yq={kernelName:Hu,backendName:"webgl",kernelFunc:Fke};var Rke=[CH,SH,G4,K4,V4,U4,H4,q4,X4,Y4,Q4,ej,tj,rj,oj,nj,sj,ij,aj,lj,uj,pj,cj,fj,dj,yj,Tj,kj,vj,A4,_j,Sj,Nj,Cj,Dj,Ej,Aj,Mj,Fj,Rj,Pj,Bj,Oj,Gj,Wj,zj,Kj,Vj,Uj,jj,Hj,qj,Xj,Zj,Jj,eH,tH,rH,nH,sH,aH,iH,lH,uH,pH,cH,mH,fH,N4,dH,wj,hH,gH,bH,D4,yH,xH,TH,IH,kH,vH,wH,_H,AH,MH,EH,FH,RH,$H,DH,BH,OH,zH,GH,WH,HH,L4,XH,YH,ZH,JH,hj,QH,rq,nq,oq,sq,E4,aq,iq,gj,KH,lq,pq,uq,P4,cq,mq,fq,dq,hq,gq,bq,yq,xq,Tq,kq,Iq,vq,wq,_q,mj,jH,Cq,Sq,Nq,Aq,Dq,Eq,Mq,Fq,Rq,Lq,Pq,Bq,Oq,zq,Gq,Wq,UH,O4,Kq,Vq,Uq,jq,Hq,z4,qq,Xq,Yq,eq];for(let r of Rke)Bf(r);var nr;(function(s){s[s.float32=0]="float32",s[s.int32=1]="int32",s[s.bool=2]="bool",s[s.string=3]="string",s[s.complex64=4]="complex64"})(nr||(nr={}));var vp;(function(i){i[i.linear=0]="linear",i[i.relu=1]="relu",i[i.relu6=2]="relu6",i[i.prelu=3]="prelu",i[i.leakyrelu=4]="leakyrelu",i[i.sigmoid=5]="sigmoid"})(vp||(vp={}));var Zq;function Lke(r){Zq=r.wasm.cwrap(ki,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function $ke(r){let{inputs:e,backend:t,attrs:n}=r,{a:o,b:s,bias:i,preluActivationWeights:a}=e;if(o.dtype!=="float32"||s.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:l,transposeB:u,activation:p,leakyreluAlpha:c}=n,m=t.dataIdMap.get(o.dataId).id,f=t.dataIdMap.get(s.dataId).id,d=0;if(i!=null){let F=t.dataIdMap.get(i.dataId);if(F.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${F.shape.length}.`);d=F.id}let h=a==null?0:t.dataIdMap.get(a.dataId).id,g=vp[p];if(g==null)throw new Error(`${p} activation not yet supported for FusedConv2D in the wasm backend.`);let b=l?o.shape[2]:o.shape[1],y=u?s.shape[1]:s.shape[2],T=o.shape[0],k=t.makeOutput([T,b,y],o.dtype),I=t.dataIdMap.get(k.dataId).id,S=new Uint8Array(new Int32Array(o.shape).buffer),N=new Uint8Array(new Int32Array(s.shape).buffer);return Zq(m,S,o.shape.length,f,N,s.shape.length,l,u,g,d,h,c||0,I),k}var Jq={kernelName:ki,backendName:"wasm",setupFunc:Lke,kernelFunc:$ke};function Bt(r){let e;function t(o){e=o.wasm.cwrap(r,null,["number","number"])}function n(o){let{backend:s,inputs:{x:i}}=o,a=s.dataIdMap.get(i.dataId).id,l=s.makeOutput(i.shape,i.dtype),u=s.dataIdMap.get(l.dataId).id;return x.sizeFromShape(l.shape)===0||e(a,u),l}return{kernelName:r,backendName:"wasm",setupFunc:t,kernelFunc:n}}var Qq=Bt(Gs);function Ot(r,e,t){let n;function o(i){n=i.wasm.cwrap(r,null,["number","array","number","number","array","number","number","number"])}function s(i){let{backend:a,inputs:l}=i,{a:u,b:p}=l,c=a.dataIdMap.get(u.dataId).id,m=a.dataIdMap.get(p.dataId).id,f=t!=null?t:u.dtype,d=C.assertAndGetBroadcastShape(u.shape,p.shape),h=a.makeOutput(d,f);if(x.sizeFromShape(d)===0)return h;let g=new Uint8Array(new Int32Array(u.shape).buffer),b=new Uint8Array(new Int32Array(p.shape).buffer),y=a.dataIdMap.get(h.dataId).id,T=()=>n(c,g,u.shape.length,m,b,p.shape.length,nr[u.dtype],y);if(e&&u.dtype==="float32")return T(),h;let k=C.getBroadcastDims(u.shape,d),I=C.getBroadcastDims(p.shape,d),S=k.every((F,$)=>F===$),N=I.every((F,$)=>F===$);if(S&&N)return T(),h;throw new Error(`Broadcasting along outer dims is not yet supported for ${u.dtype} ${r}.`)}return{kernelName:r,backendName:"wasm",setupFunc:o,kernelFunc:s}}var Pke=!0,e6=Ot(so,Pke);var t6;function Bke(r){t6=r.wasm.cwrap(Ws,null,["array","number","number","number"])}function Oke(r){let{inputs:e,backend:t}=r,n=t.makeOutput(e[0].shape,e[0].dtype);if(x.sizeFromShape(n.shape)===0)return n;let o=e.map(a=>t.dataIdMap.get(a.dataId).id),s=new Uint8Array(new Int32Array(o).buffer),i=t.dataIdMap.get(n.dataId).id;return t6(s,o.length,nr[n.dtype],i),n}var r6={kernelName:Ws,backendName:"wasm",setupFunc:Bke,kernelFunc:Oke};function xm(r){let{inputs:{x:e},backend:t}=r,n=t.makeOutput(e.shape,e.dtype),o=t.typedArrayFromHeap(e);return t.typedArrayFromHeap(n).set(o),n}var n6={kernelName:Lo,backendName:"wasm",kernelFunc:xm};var o6;function zke(r){o6=r.wasm.cwrap(ps,null,["number","array","number","number","number","array","number"])}function Jd(r){let{inputs:e,backend:t,attrs:n}=r,[o,s]=Wke(e.x.shape,n.perm),i=!0;for(let d=0;d<s.length;d++)s[d]!==d&&(i=!1);let a=Gke(e.x.shape,n.perm),l={dataId:e.x.dataId,shape:o,dtype:e.x.dtype};if(i){let d=xm({inputs:e,backend:t});return d.shape=a,d}let u=t.makeOutput(a,l.dtype),p=t.dataIdMap.get(l.dataId).id,c=t.dataIdMap.get(u.dataId).id,m=new Uint8Array(new Int32Array(s).buffer),f=new Uint8Array(new Int32Array(l.shape).buffer);return o6(p,f,l.shape.length,nr[l.dtype],c,m,s.length),u}function Gke(r,e){let t=new Array(r.length);for(let n=0;n<t.length;n++)t[n]=r[e[n]];return t}function Wke(r,e){let t=[],n=[];for(let o=0;o<r.length;++o)r[o]!==1&&t.push(r[o]),r[e[o]]!==1&&n.push(e[o]);for(let o=0;o<n.length;++o){let s=-1;for(let i=0;i<n.length;++i)n[i]>=o&&(s===-1||n[s]>n[i])&&(s=i);n[s]=o}return[t,n]}var s6={kernelName:ps,backendName:"wasm",kernelFunc:Jd,setupFunc:zke};function Yn(r,e,t){let n=r.shape,o=r.shape.length,s=x.parseAxisParam(e,n),i=s,a=C.getAxesPermutation(i,o),l=null,u=!1;if(a!=null){let p=new Array(o);for(let f=0;f<p.length;f++)p[f]=n[a[f]];i=C.getInnerMostAxes(i.length,o),l=Jd({inputs:{x:r},attrs:{perm:a},backend:t});let c=t.dataIdMap.get(r.dataId).id;t.dataIdMap.get(l.dataId).id!==c&&(u=!0)}return{transposed:l,originalAxes:s,axes:i,inputWasTransposed:u}}var a6;function Kke(r){a6=r.wasm.cwrap(al,null,["number, number, number"])}function Vke(r){let{backend:e,inputs:t,attrs:n}=r,{axis:o,keepDims:s}=n,{x:i}=t,l=e.dataIdMap.get(i.dataId).id,u=i,{transposed:p,axes:c,originalAxes:m,inputWasTransposed:f}=Yn(i,o,e);if(f){let T=e.dataIdMap.get(p.dataId).id;u=p,l=T}let d=u.shape.length;C.assertAxesAreInnerMostDims("all",c,d);let[h,g]=C.computeOutAndReduceShapes(u.shape,c),b=x.sizeFromShape(g),y=e.makeOutput(h,i.dtype);if(x.sizeFromShape(u.shape)!==0){let T=e.dataIdMap.get(y.dataId).id;a6(l,b,T)}if(f&&e.disposeData(p.dataId),s){let T=C.expandShapeToKeepDim(y.shape,m);y.shape=T}return y}var i6={kernelName:al,backendName:"wasm",setupFunc:Kke,kernelFunc:Vke};var l6;function Uke(r){l6=r.wasm.cwrap(il,null,["number, number, number"])}function jke(r){let{backend:e,inputs:t,attrs:n}=r,{axis:o,keepDims:s}=n,{x:i}=t,l=e.dataIdMap.get(i.dataId).id,u=i,{transposed:p,axes:c,originalAxes:m,inputWasTransposed:f}=Yn(i,o,e);if(f){let T=e.dataIdMap.get(p.dataId).id;u=p,l=T}let d=u.shape.length;C.assertAxesAreInnerMostDims("any",c,d);let[h,g]=C.computeOutAndReduceShapes(u.shape,c),b=x.sizeFromShape(g),y=e.makeOutput(h,i.dtype);if(x.sizeFromShape(u.shape)!==0){let T=e.dataIdMap.get(y.dataId).id;l6(l,b,T)}if(f&&e.disposeData(p.dataId),s){let T=C.expandShapeToKeepDim(y.shape,m);y.shape=T}return y}var u6={kernelName:il,backendName:"wasm",setupFunc:Uke,kernelFunc:jke};var p6;function Hke(r){p6=r.wasm.cwrap(Ks,null,["number","number","number","number","number"])}function qke(r){let{backend:e,inputs:t,attrs:n}=r,{axis:o}=n,{x:s}=t,i=e.dataIdMap.get(s.dataId).id,a=i,l=s,{transposed:u,axes:p,inputWasTransposed:c}=Yn(s,o,e);if(c){let b=e.dataIdMap.get(u.dataId).id;b!==i&&(l=u,a=b)}let m=l.shape.slice(0,-1),f=e.makeOutput(m,"int32"),d=e.dataIdMap.get(f.dataId).id,h=x.sizeFromShape(f.shape),g=l.shape[p[0]];return p6(a,nr[l.dtype],h,g,d),c&&e.disposeData(u.dataId),f}var c6={kernelName:Ks,backendName:"wasm",kernelFunc:qke,setupFunc:Hke};var m6;function Xke(r){m6=r.wasm.cwrap(Vs,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Yke(r){let{inputs:e,attrs:t,backend:n}=r,o=e.x,s=n.dataIdMap.get(o.dataId).id,{filterSize:i,strides:a,pad:l,dimRoundingMode:u}=t,p=C.computePool2DInfo(o.shape,i,a,1,l,u),c=p.filterHeight,m=p.filterWidth,f=p.padInfo.top,d=p.padInfo.right,h=p.padInfo.bottom,g=p.padInfo.left,b=p.strideHeight,y=p.strideWidth,T=p.inChannels;if(p.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${p.dataFormat}'. Please use 'channelsLast'.`);if(p.dilationWidth!==1||p.dilationHeight!==1)throw new Error(`was backend only supports average pooling with dilation = [1, 1], got [${p.dilationHeight}, ${p.dilationWidth}].`);let k=n.makeOutput(p.outShape,"float32"),I=n.dataIdMap.get(k.dataId).id;return m6(s,o.shape[0],o.shape[1],o.shape[2],c,m,f,d,h,g,b,y,T,I),k}var f6={kernelName:Vs,backendName:"wasm",setupFunc:Xke,kernelFunc:Yke};function Nn(r){let{inputs:e,attrs:t}=r,{x:n}=e,{shape:o}=t,s=x.sizeFromShape(n.shape),i=x.inferFromImplicitShape(o,s);return x.assert(s===x.sizeFromShape(i),()=>`new shape: ${i}, old shape: ${n.shape}. New shape and old shape must have the same number of elements.`),r.backend.incRef(n.dataId),{dataId:n.dataId,shape:i,dtype:n.dtype}}var d6={kernelName:gi,backendName:"wasm",kernelFunc:Nn};var h6;function Zke(r){h6=r.wasm.cwrap(Us,null,["number","array","number","number","array","number","number","number","number"])}function Jke(r){let{inputs:e,backend:t,attrs:n}=r,{a:o,b:s}=e,{transposeA:i,transposeB:a}=n;if(o.dtype!=="float32"||s.dtype!=="float32")throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");let l=o.shape.length,u=s.shape.length,p=i?o.shape[l-2]:o.shape[l-1],c=a?s.shape[u-1]:s.shape[u-2],m=i?o.shape[l-1]:o.shape[l-2],f=a?s.shape[u-2]:s.shape[u-1],d=o.shape.slice(0,-2),h=s.shape.slice(0,-2),g=x.sizeFromShape(d),b=x.sizeFromShape(h),y=g===b||g===1||b===1;x.assert(l>=2&&u>=2&&y,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${d}) and (${h}).`);let k=(g>b?o.shape.slice(0,-2):s.shape.slice(0,-2)).concat([m,f]);x.assert(p===c,()=>`Error in matMul: inner shapes (${p}) and (${c}) of Tensors with shapes ${o.shape} and ${s.shape} and transposeA=${i} and transposeB=${a} must match.`);let I=i?[g,p,m]:[g,m,p],S=a?[b,f,c]:[b,c,f],N=Nn({inputs:{x:o},backend:t,attrs:{shape:I}}),F=Nn({inputs:{x:s},backend:t,attrs:{shape:S}}),$=t.dataIdMap.get(N.dataId).id,O=t.dataIdMap.get(F.dataId).id,V=i?N.shape[2]:N.shape[1],q=a?F.shape[1]:F.shape[2],W=Math.max(g,b),Y=t.makeOutput([W,V,q],N.dtype),Z=t.dataIdMap.get(Y.dataId).id,J=new Uint8Array(new Int32Array(N.shape).buffer),se=new Uint8Array(new Int32Array(F.shape).buffer);return h6($,J,N.shape.length,O,se,F.shape.length,i,a,Z),t.disposeData(N.dataId),t.disposeData(F.dataId),Y.shape=k,Y}var g6={kernelName:Us,backendName:"wasm",setupFunc:Zke,kernelFunc:Jke};function Tm(r){let{inputs:{x:e},attrs:{dtype:t},backend:n}=r,o=n.makeOutput(e.shape,t),s=n.typedArrayFromHeap(e);return n.typedArrayFromHeap(o).set(s),o}var b6={kernelName:Do,backendName:"wasm",kernelFunc:Tm};var y6=Bt(Eo);var x6;function Qke(r){x6=r.wasm.cwrap(us,null,["number","number","number","number"])}function eIe(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{clipValueMin:s,clipValueMax:i}=n,a=t.dataIdMap.get(o.dataId).id,l=t.makeOutput(o.shape,o.dtype),u=t.dataIdMap.get(l.dataId).id;return x6(a,s,i,u),l}var T6={kernelName:us,backendName:"wasm",setupFunc:Qke,kernelFunc:eIe};function H1(r){let{inputs:e,backend:t}=r,n=x.parseAxisParam(r.attrs.axis,e[0].shape)[0],o=C.computeOutShape(e.map(f=>f.shape),n),s=e.filter(f=>x.sizeFromShape(f.shape)>0);if(s.length===1)return xm({inputs:{x:s[0]},backend:t});let i=t.makeOutput(o,e[0].dtype);if(x.sizeFromShape(o)===0)return i;let a=s.map(f=>f.shape);if(C.assertParamsConsistent(a,n),s[0].dtype==="string"){let f=s.map(T=>{let k=x.sizeFromShape(T.shape.slice(n));return Nn({inputs:{x:T},backend:t,attrs:{shape:[-1,k]}})}),d=f.map(T=>({vals:t.readSync(T.dataId),shape:T.shape}));o=C.computeOutShape(f.map(T=>T.shape),1);let h=f[0].shape[0]===1,g=Ay(d,o,e[0].dtype,h),b=C.computeOutShape(s.map(T=>T.shape),n);i.shape=b;let y=t.dataIdMap.get(i.dataId);return y.stringBytes=C.fromStringArrayToUint8(g),f.forEach(T=>t.disposeData(T.dataId)),i}let l=x.sizeFromShape(s[0].shape.slice(0,n)),u=0,p=s.map(f=>{let d=x.sizeFromShape(f.shape.slice(n));return u+=d,d}),c=s.map(f=>t.typedArrayFromHeap(f)),m=t.typedArrayFromHeap(i);for(let f=0;f<l;f++){let d=f*u;for(let h=0;h<c.length;h++){let g=p[h],b=f*g,y=c[h].subarray(b,b+g);m.set(y,d),d+=g}}return i}var k6={kernelName:pi,backendName:"wasm",kernelFunc:H1};var I6;function tIe(r){I6=r.wasm.cwrap(js,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function rIe(r){let{inputs:e,attrs:t,backend:n}=r,{x:o,filter:s}=e,i=n.dataIdMap.get(o.dataId).id,a=n.dataIdMap.get(s.dataId).id,{strides:l,dilations:u,pad:p,dimRoundingMode:c,dataFormat:m}=t,f=C.convertConv2DDataFormat(m),d=C.computeConv2DInfo(o.shape,s.shape,l,u,p,c,!1,f),h=d.filterHeight,g=d.filterWidth,b=d.padInfo.top,y=d.padInfo.right,T=d.padInfo.bottom,k=d.padInfo.left,I=d.dilationHeight,S=d.dilationWidth,N=d.strideHeight,F=d.strideWidth,$=d.inChannels,O=d.outChannels,V=d.padInfo.type==="SAME"?1:0;if(d.dataFormat!=="channelsLast")throw new Error(`wasm backend Conv2D does not support dataFormat:'${d.dataFormat}'. Please use 'channelsLast'.`);let q=n.makeOutput(d.outShape,"float32"),W=n.dataIdMap.get(q.dataId).id;return I6(i,o.shape[0],o.shape[1],o.shape[2],a,h,g,b,y,T,k,V,I,S,N,F,$,O,W),q}var v6={kernelName:js,backendName:"wasm",setupFunc:tIe,kernelFunc:rIe};var w6;function nIe(r){w6=r.wasm.cwrap(Hs,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function oIe(r){let{backend:e,inputs:t,attrs:n}=r,{dy:o,filter:s}=t,{strides:i,pad:a,dataFormat:l,dimRoundingMode:u,inputShape:p}=n,c=1,m=C.convertConv2DDataFormat(l),f=C.computeConv2DInfo(p,s.shape,i,c,a,u,!1,m),{batchSize:d,filterHeight:h,filterWidth:g,inChannels:b,inHeight:y,inWidth:T,outChannels:k,outHeight:I,outWidth:S,strideHeight:N,strideWidth:F}=f,$=h-1-f.padInfo.top,O=g-1-f.padInfo.left,V=f.dataFormat==="channelsLast",q=x.computeStrides(f.inShape),W=x.computeStrides(o.shape),[Y,Z,J]=x.computeStrides(s.shape),se=q[0],ee=V?q[1]:q[2],le=V?q[2]:1,ae=V?1:q[1],ce=W[0],ye=V?W[1]:W[2],me=V?W[2]:1,xe=V?1:W[1],ke=e.makeOutput(f.inShape,"float32"),we=e.dataIdMap.get(ke.dataId).id,Ne=e.dataIdMap.get(o.dataId).id,Oe=e.dataIdMap.get(s.dataId).id;return w6(Ne,Oe,d,h,g,y,T,b,I,S,k,N,F,$,O,Y,Z,J,se,ee,le,ae,ce,ye,me,xe,we),ke}var _6={kernelName:Hs,backendName:"wasm",setupFunc:nIe,kernelFunc:oIe};var C6=Bt(qs);var q1;(function(t){t[t.bilinear=0]="bilinear",t[t.nearest=1]="nearest"})(q1||(q1={}));var S6;function sIe(r){S6=r.wasm.cwrap(dl,null,["number","number","number","number","array","number","number","number","number","number"])}function aIe(r){let{backend:e,inputs:t,attrs:n}=r,{method:o,extrapolationValue:s,cropSize:i}=n,{image:a,boxes:l,boxInd:u}=t,p=l.shape[0],[c,m]=i,f=[p,c,m,a.shape[3]],d=e.dataIdMap.get(a.dataId),h;a.dtype!=="float32"&&(h=Tm({backend:e,inputs:{x:a},attrs:{dtype:"float32"}}),d=e.dataIdMap.get(h.dataId));let g=d.id,b=e.dataIdMap.get(l.dataId).id,y=e.dataIdMap.get(u.dataId).id,T=e.makeOutput(f,"float32"),k=e.dataIdMap.get(T.dataId).id,I=new Uint8Array(new Int32Array(a.shape).buffer);return S6(g,b,y,p,I,c,m,q1[o],s,k),h!=null&&e.disposeData(h.dataId),T}var N6={kernelName:dl,backendName:"wasm",setupFunc:sIe,kernelFunc:aIe};var A6;function iIe(r){A6=r.wasm.cwrap(Xs,null,["number","number","number","number","number","number"])}function lIe(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,exclusive:i,reverse:a}=n,l=o.shape.length;x.assert(o.dtype==="float32"||o.dtype==="int32",()=>`cumsum does not support ${o.dtype} tensors in the WASM backend`);let u=C.getAxesPermutation([s],l),p=o;u!==null&&(p=Jd({inputs:{x:o},attrs:{perm:u},backend:t}));let c=C.getInnerMostAxes(1,l)[0];C.assertAxesAreInnerMostDims("cumsum",[c],l);let m=t.makeOutput(p.shape,p.dtype),f=p.shape[c],d=t.dataIdMap.get(p.dataId).id,h=t.dataIdMap.get(m.dataId).id;A6(d,i?1:0,a?1:0,f,h,nr[o.dtype]);let g=m;if(u!==null){let b=C.getUndoAxesPermutation(u);g=Jd({inputs:{x:m},attrs:{perm:b},backend:t}),t.disposeData(p.dataId),t.disposeData(m.dataId)}return g}var D6={kernelName:Xs,backendName:"wasm",setupFunc:iIe,kernelFunc:lIe};var E6;function uIe(r){E6=r.wasm.cwrap(hl,null,["number","number","number","array","number","array","array","number","number"])}function pIe(r){let{backend:e,inputs:t,attrs:n}=r,{x:o}=t,{blockSize:s,dataFormat:i}=n;x.assert(s>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${s}`);let a=o.shape[0],l=i==="NHWC"?o.shape[1]:o.shape[2],u=i==="NHWC"?o.shape[2]:o.shape[3],p=i==="NHWC"?o.shape[3]:o.shape[1],c=l*s,m=u*s,f=p/(s*s),d=i==="NHWC"?[a,c,m,f]:[a,f,c,m],h=e.makeOutput(d,"float32"),b=e.dataIdMap.get(o.dataId).id,y=new Uint8Array(new Int32Array(x.computeStrides(o.shape)).buffer),T=new Uint8Array(new Int32Array(d).buffer),k=new Uint8Array(new Int32Array(x.computeStrides(d)).buffer),I=e.dataIdMap.get(h.dataId).id;return E6(b,s,i==="NHWC"?1:0,y,o.shape.length-1,T,k,d.length,I),h}var M6={kernelName:hl,backendName:"wasm",setupFunc:uIe,kernelFunc:pIe};var F6;function cIe(r){F6=r.wasm.cwrap(Ys,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function mIe(r){let{inputs:e,attrs:t,backend:n}=r,{x:o,filter:s}=e,i=n.dataIdMap.get(o.dataId).id,a=n.dataIdMap.get(s.dataId).id,{strides:l,dilations:u,pad:p,dimRoundingMode:c}=t,m=u==null?[1,1]:u,f=C.computeConv2DInfo(o.shape,s.shape,l,m,p,c,!0),d=f.filterHeight,h=f.filterWidth,g=f.padInfo.top,b=f.padInfo.right,y=f.padInfo.bottom,T=f.padInfo.left,k=f.dilationHeight,I=f.dilationWidth,S=f.strideHeight,N=f.strideWidth,F=f.inChannels,$=f.outChannels,O=f.padInfo.type==="SAME"?1:0;if(f.dataFormat!=="channelsLast")throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${f.dataFormat}'. Please use 'channelsLast'.`);let V=n.makeOutput(f.outShape,"float32"),q=n.dataIdMap.get(V.dataId).id;return F6(i,o.shape[0],o.shape[1],o.shape[2],a,d,h,g,b,y,T,O,k,I,S,N,F,$,q),V}var R6={kernelName:Ys,backendName:"wasm",setupFunc:cIe,kernelFunc:mIe};var fIe=!1,L6=Ot(Js,fIe,"bool");var $6=Bt(Mo);function OI(r){let{inputs:e,attrs:t,backend:n}=r,{input:o}=e,{dim:s}=t,i=o.shape.length,a=o.shape.slice(),l=s;return s<0&&(x.assert(-(i+1)<=s,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+s+1),a.splice(l,0,1),Nn({inputs:{x:o},backend:n,attrs:{shape:a}})}var P6={kernelName:ci,backendName:"wasm",kernelFunc:OI};function dIe(r){let{attrs:{shape:e,value:t,dtype:n},backend:o}=r,s=o.makeOutput(e,n);return o.typedArrayFromHeap(s).fill(t),s}var B6={kernelName:zu,backendName:"wasm",kernelFunc:dIe};var O6;function hIe(r){O6=r.wasm.cwrap(yl,null,["number","number","number","number","number","number"])}function gIe(r){let{inputs:e,backend:t}=r,{image:n}=e,o=t.makeOutput(n.shape,n.dtype),s=t.dataIdMap.get(n.dataId).id,i=t.dataIdMap.get(o.dataId).id,[a,l,u,p]=n.shape;return O6(s,a,l,u,p,i),o}var z6={kernelName:yl,backendName:"wasm",kernelFunc:gIe,setupFunc:hIe};var G6=Bt(Fo);var bIe=!1,W6=Ot(ea,bIe);var K6;function yIe(r){K6=r.wasm.cwrap(ta,null,["number","number","number","number","number","number","number"])}function xIe(r){let{backend:e,inputs:t,attrs:n}=r,{varianceEpsilon:o}=n,{x:s,mean:i,variance:a,offset:l,scale:u}=t,p=e.dataIdMap.get(s.dataId).id,c=e.dataIdMap.get(i.dataId).id,m=e.dataIdMap.get(a.dataId).id,f=l!=null?e.dataIdMap.get(l.dataId).id:0,d=u!=null?e.dataIdMap.get(u.dataId).id:0,h=e.makeOutput(s.shape,s.dtype);if(x.sizeFromShape(s.shape)===0)return h;let g=e.dataIdMap.get(h.dataId).id;return K6(p,c,m,f,d,o,g),h}var V6={kernelName:ta,backendName:"wasm",setupFunc:yIe,kernelFunc:xIe};var U6;function TIe(r){U6=r.wasm.cwrap(Ii,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function kIe(r){let{inputs:e,attrs:t,backend:n}=r,{x:o,filter:s,bias:i,preluActivationWeights:a}=e,{strides:l,pad:u,dilations:p,dataFormat:c,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=t,h=C.computeConv2DInfo(o.shape,s.shape,l,p,u,m),g=vp[f];if(g==null)throw new Error(`${f} activation not yet supported for FusedConv2D in the wasm backend.`);let b=n.dataIdMap.get(o.dataId).id,y=n.dataIdMap.get(s.dataId).id,T=h.outChannels,k=0;if(i!=null){let me=n.dataIdMap.get(i.dataId);if(me.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${me.shape.length}.`);if(me.shape[0]!==T)throw new Error(`FusedConv2D bias shape (${me.shape}) does not match the number of output channels (${T})`);k=me.id}let I=h.filterHeight,S=h.filterWidth,N=h.padInfo.top,F=h.padInfo.right,$=h.padInfo.bottom,O=h.padInfo.left,V=h.dilationHeight,q=h.dilationWidth,W=h.strideHeight,Y=h.strideWidth,Z=h.inChannels,J=h.padInfo.type==="SAME"?1:0,se=h.batchSize,ee=h.inHeight,le=h.inWidth;if(c!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${c}'. Please use 'NHWC'.`);let ae=n.makeOutput(h.outShape,"float32"),ce=n.dataIdMap.get(ae.dataId).id,ye=a==null?0:n.dataIdMap.get(a.dataId).id;return U6(b,se,ee,le,y,I,S,k,N,F,$,O,J,V,q,W,Y,Z,T,g,ye,d||0,ce),ae}var j6={kernelName:Ii,backendName:"wasm",setupFunc:TIe,kernelFunc:kIe};var H6;function IIe(r){H6=r.wasm.cwrap(vi,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function vIe(r){let{inputs:e,attrs:t,backend:n}=r,{x:o,filter:s,bias:i,preluActivationWeights:a}=e,{strides:l,pad:u,dilations:p,dataFormat:c,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=t,h=C.computeConv2DInfo(o.shape,s.shape,l,p,u,m,!0),g=vp[f];if(g==null)throw new Error(`${f} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);let b=n.dataIdMap.get(o.dataId).id,y=n.dataIdMap.get(s.dataId).id,T=h.outChannels,k=0;if(i!=null){let me=n.dataIdMap.get(i.dataId);if(me.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${me.shape.length}.`);if(me.shape[0]!==T)throw new Error(`FusedDepthwiseConv2D bias shape (${me.shape}) does not match the number of output channels (${T})`);k=me.id}let I=h.filterHeight,S=h.filterWidth,N=h.padInfo.top,F=h.padInfo.right,$=h.padInfo.bottom,O=h.padInfo.left,V=h.dilationHeight,q=h.dilationWidth,W=h.strideHeight,Y=h.strideWidth,Z=h.inChannels,J=h.padInfo.type==="SAME"?1:0,se=h.batchSize,ee=h.inHeight,le=h.inWidth;if(c!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${c}'. Please use 'NHWC'.`);let ae=n.makeOutput(h.outShape,"float32"),ce=n.dataIdMap.get(ae.dataId).id,ye=a==null?0:n.dataIdMap.get(a.dataId).id;return H6(b,se,ee,le,y,I,S,k,N,F,$,O,J,V,q,W,Y,Z,T,g,ye,d||0,ce),ae}var q6={kernelName:vi,backendName:"wasm",setupFunc:IIe,kernelFunc:vIe};var X6;function wIe(r){X6=r.wasm.cwrap(xl,null,["number","number","number","number","number","number","array","number"])}function _Ie(r){let{backend:e,inputs:t}=r,{params:n,indices:o}=t,[s,i,a,l]=bT.prepareAndValidate(n,o),u=e.makeOutput(s,n.dtype);if(i===0)return u;let p=o.shape,c=p[p.length-1],f=e.dataIdMap.get(n.dataId).id,h=e.dataIdMap.get(o.dataId).id,g=new Uint8Array(new Int32Array(l).buffer),b=e.dataIdMap.get(u.dataId).id;return X6(f,nr[n.dtype],h,i,c,a,g,b),u}var Y6={kernelName:xl,backendName:"wasm",setupFunc:wIe,kernelFunc:_Ie};var Z6;function CIe(r){Z6=r.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function SIe(r){let{backend:e,inputs:t,attrs:n}=r,{x:o,indices:s}=t,{axis:i,batchDims:a}=n,l=x.parseAxisParam(i,o.shape)[0],u=C.segment_util.collectGatherOpShapeInfo(o,s,l,a),p=Nn({inputs:{x:o},attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]},backend:e}),c=x.sizeFromShape(s.shape),m=Nn({inputs:{x:s},attrs:{shape:[u.batchSize,c/u.batchSize]},backend:e}),f=[u.batchSize,u.outerSize,c/u.batchSize,u.sliceSize],d=e.makeOutput(f,o.dtype);if(x.sizeFromShape(o.shape)===0)return d;let h=p.shape.length-1,b=e.dataIdMap.get(p.dataId).id,T=e.dataIdMap.get(m.dataId).id,k=e.dataIdMap.get(d.dataId).id,I=new Uint8Array(new Int32Array(x.computeStrides(p.shape)).buffer),S=new Uint8Array(new Int32Array(x.computeStrides(f)).buffer);return Z6(b,nr[o.dtype],I,h,T,u.batchSize,S,k),e.disposeData(p.dataId),e.disposeData(m.dataId),d.shape=u.outputShape,d}var J6={kernelName:mi,backendName:"wasm",setupFunc:CIe,kernelFunc:SIe};var NIe=!1,Q6=Ot(ra,NIe,"bool");var AIe=!1,e8=Ot(Ro,AIe,"bool");var t8;function DIe(r){t8=r.wasm.cwrap(na,null,["number","number","number"])}function EIe(r){let{inputs:{x:e},attrs:{alpha:t},backend:n}=r,o=n.dataIdMap.get(e.dataId).id,s=n.makeOutput(e.shape,e.dtype);if(x.sizeFromShape(e.shape)!==0){let i=n.dataIdMap.get(s.dataId).id;t8(o,t,i)}return s}var r8={kernelName:na,backendName:"wasm",setupFunc:DIe,kernelFunc:EIe};var MIe=!1,n8=Ot(oa,MIe,"bool");var FIe=!1,o8=Ot(sa,FIe,"bool");var s8=Bt($o);var RIe=!1,a8=Ot(wl,RIe,"bool");var i8;function LIe(r){i8=r.wasm.cwrap(aa,null,["number, number, number"])}function $Ie(r){let{backend:e,inputs:t,attrs:n}=r,{reductionIndices:o,keepDims:s}=n,{x:i}=t,l=e.dataIdMap.get(i.dataId).id,u=i,{transposed:p,axes:c,originalAxes:m,inputWasTransposed:f}=Yn(i,o,e);if(f){let T=e.dataIdMap.get(p.dataId).id;u=p,l=T}let d=u.shape.length;C.assertAxesAreInnerMostDims("max",c,d);let[h,g]=C.computeOutAndReduceShapes(u.shape,c),b=x.sizeFromShape(g),y=e.makeOutput(h,i.dtype);if(x.sizeFromShape(u.shape)!==0){let T=e.dataIdMap.get(y.dataId).id;i8(l,b,T)}if(f&&e.disposeData(p.dataId),s){let T=C.expandShapeToKeepDim(y.shape,m);y.shape=T}return y}var l8={kernelName:aa,backendName:"wasm",setupFunc:LIe,kernelFunc:$Ie};var PIe=!1,u8=Ot(Po,PIe);var p8;function BIe(r){p8=r.wasm.cwrap(ia,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function OIe(r){let{inputs:e,attrs:t,backend:n}=r,o=e.x,s=n.dataIdMap.get(o.dataId).id,{filterSize:i,strides:a,pad:l,dimRoundingMode:u}=t,p=C.computePool2DInfo(o.shape,i,a,1,l,u),c=p.filterHeight,m=p.filterWidth,f=p.padInfo.top,d=p.padInfo.right,h=p.padInfo.bottom,g=p.padInfo.left,b=p.dilationHeight,y=p.dilationWidth,T=p.strideHeight,k=p.strideWidth,I=p.inChannels,S=p.outChannels;if(p.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${p.dataFormat}'. Please use 'channelsLast'.`);let N=n.makeOutput(p.outShape,"float32"),F=n.dataIdMap.get(N.dataId).id;return p8(s,o.shape[0],o.shape[1],o.shape[2],c,m,f,d,h,g,b,y,T,k,I,S,F),N}var c8={kernelName:ia,backendName:"wasm",setupFunc:BIe,kernelFunc:OIe};var m8;function zIe(r){m8=r.wasm.cwrap(la,null,["number, number, number"])}function GIe(r){let{backend:e,inputs:t,attrs:n}=r,{axis:o,keepDims:s}=n,{x:i}=t,a=e.dataIdMap.get(i.dataId).id,l=a,u=i,{transposed:p,axes:c,originalAxes:m,inputWasTransposed:f}=Yn(i,o,e),d=c;if(f){let k=e.dataIdMap.get(p.dataId).id;k!==a&&(u=p,l=k,d=C.getInnerMostAxes(d.length,u.shape.length))}C.assertAxesAreInnerMostDims("mean",d,u.shape.length);let[h,g]=C.computeOutAndReduceShapes(u.shape,d),b=x.sizeFromShape(g),y=u;u.dtype!=="float32"&&(y=Tm({backend:e,inputs:{x:u},attrs:{dtype:"float32"}}),l=e.dataIdMap.get(y.dataId).id);let T=e.makeOutput(h,"float32");if(x.sizeFromShape(u.shape)!==0){let k=e.dataIdMap.get(T.dataId).id;m8(l,b,k)}if(f&&e.disposeData(p.dataId),s){let k=C.expandShapeToKeepDim(T.shape,m);T.shape=k}return u.dtype!=="float32"&&e.disposeData(y.dataId),T}var f8={kernelName:la,backendName:"wasm",setupFunc:zIe,kernelFunc:GIe};var d8;function WIe(r){d8=r.wasm.cwrap(ua,null,["number, number, number"])}function KIe(r){let{backend:e,inputs:t,attrs:n}=r,{axis:o,keepDims:s}=n,{x:i}=t,a=e.dataIdMap.get(i.dataId).id,l=a,u=i,{transposed:p,axes:c,originalAxes:m,inputWasTransposed:f}=Yn(i,o,e);if(f){let T=e.dataIdMap.get(p.dataId).id;T!==a&&(u=p,l=T)}let d=u.shape.length;C.assertAxesAreInnerMostDims("min",c,d);let[h,g]=C.computeOutAndReduceShapes(u.shape,c),b=x.sizeFromShape(g),y=e.makeOutput(h,u.dtype);if(x.sizeFromShape(u.shape)!==0){let T=e.dataIdMap.get(y.dataId).id;d8(l,b,T)}if(f&&e.disposeData(p.dataId),s){let T=C.expandShapeToKeepDim(y.shape,m);y.shape=T}return y}var h8={kernelName:ua,backendName:"wasm",setupFunc:WIe,kernelFunc:KIe};var VIe=!1,g8=Ot(Bo,VIe);var X1;(function(t){t[t.reflect=0]="reflect",t[t.symmetric=1]="symmetric"})(X1||(X1={}));var b8;function UIe(r){b8=r.wasm.cwrap(pa,null,["number","array","number","number","array","array","number","number"])}function jIe(r){let{inputs:{x:e},backend:t,attrs:{paddings:n,mode:o}}=r,s=n.map((d,h)=>d[0]+e.shape[h]+d[1]),i=t.dataIdMap.get(e.dataId).id,a=t.makeOutput(s,e.dtype),l=t.dataIdMap.get(a.dataId).id,u=new Uint8Array(new Int32Array(e.shape).buffer),p=n.map(d=>d[0]),c=n.map(d=>d[1]),m=new Uint8Array(new Int32Array(p).buffer),f=new Uint8Array(new Int32Array(c).buffer);return b8(i,u,e.shape.length,nr[e.dtype],m,f,X1[o],l),a}var y8={kernelName:pa,backendName:"wasm",kernelFunc:jIe,setupFunc:UIe};var HIe=!0,x8=Ot(Oo,HIe);var T8=Bt(ca);function Qd(r,e){let t=new Int32Array(r.wasm.HEAPU8.buffer,e,4),n=t[0],o=t[1],s=t[2],i=t[3];return r.wasm._free(e),{pSelectedIndices:n,selectedSize:o,pSelectedScores:s,pValidOutputs:i}}var k8;function qIe(r){k8=r.wasm.cwrap(Cl,"number",["number","number","number","number","number"])}function XIe(r){let{backend:e,inputs:t,attrs:n}=r,{iouThreshold:o,maxOutputSize:s,scoreThreshold:i}=n,{boxes:a,scores:l}=t,u=e.dataIdMap.get(a.dataId).id,p=e.dataIdMap.get(l.dataId).id,c=k8(u,p,s,o,i),{pSelectedIndices:m,selectedSize:f,pSelectedScores:d,pValidOutputs:h}=Qd(e,c);return e.wasm._free(d),e.wasm._free(h),e.makeOutput([f],"int32",m)}var I8={kernelName:Cl,backendName:"wasm",setupFunc:qIe,kernelFunc:XIe};var v8;function YIe(r){v8=r.wasm.cwrap(Sl,"number",["number","number","number","number","number","bool"])}function ZIe(r){let{backend:e,inputs:t,attrs:n}=r,{iouThreshold:o,maxOutputSize:s,scoreThreshold:i,padToMaxOutputSize:a}=n,{boxes:l,scores:u}=t,p=e.dataIdMap.get(l.dataId).id,c=e.dataIdMap.get(u.dataId).id,m=v8(p,c,s,o,i,a),{pSelectedIndices:f,selectedSize:d,pSelectedScores:h,pValidOutputs:g}=Qd(e,m);e.wasm._free(h);let b=e.makeOutput([d],"int32",f),y=e.makeOutput([],"int32",g);return[b,y]}var w8={kernelName:Sl,backendName:"wasm",setupFunc:YIe,kernelFunc:ZIe};var _8;function JIe(r){_8=r.wasm.cwrap(Nl,"number",["number","number","number","number","number","number"])}function QIe(r){let{backend:e,inputs:t,attrs:n}=r,{iouThreshold:o,maxOutputSize:s,scoreThreshold:i,softNmsSigma:a}=n,{boxes:l,scores:u}=t,p=e.dataIdMap.get(l.dataId).id,c=e.dataIdMap.get(u.dataId).id,m=_8(p,c,s,o,i,a),{pSelectedIndices:f,selectedSize:d,pSelectedScores:h,pValidOutputs:g}=Qd(e,m);e.wasm._free(g);let b=e.makeOutput([d],"int32",f),y=e.makeOutput([d],"float32",h);return[b,y]}var C8={kernelName:Nl,backendName:"wasm",setupFunc:JIe,kernelFunc:QIe};var eve=!1,S8=Ot(ma,eve,"bool");var N8;function tve(r){N8=r.wasm.cwrap(fa,null,["number","number","number","number","number"])}function rve(r){let{inputs:e,backend:t,attrs:n}=r,{indices:o}=e,{depth:s,onValue:i,offValue:a}=n,l=t.makeOutput([...o.shape,s],"int32"),u=t.dataIdMap.get(l.dataId).id,c=t.dataIdMap.get(o.dataId).id;return N8(c,s,i,a,u),l}var A8={kernelName:fa,backendName:"wasm",setupFunc:tve,kernelFunc:rve};function nve(r){let{inputs:{x:e},backend:t}=r,n=t.makeOutput(e.shape,e.dtype);return t.typedArrayFromHeap(n).fill(1),n}var D8={kernelName:fi,backendName:"wasm",kernelFunc:nve};function ove(r){let{inputs:e,backend:t,attrs:n}=r,{axis:o}=n;if(e.length===1)return OI({inputs:{input:e[0]},backend:t,attrs:{dim:o}});let s=e[0].shape,i=e[0].dtype;e.forEach(p=>{x.assertShapesMatch(s,p.shape,"All tensors passed to stack must have matching shapes"),x.assert(i===p.dtype,()=>"All tensors passed to stack must have matching dtypes")});let a=[],l=e.map(p=>{let c=OI({inputs:{input:p},backend:t,attrs:{dim:o}});return a.push(c),c}),u=H1({inputs:l,backend:t,attrs:{axis:o}});return a.forEach(p=>t.disposeData(p.dataId)),u}var E8={kernelName:di,backendName:"wasm",kernelFunc:ove};var M8;function sve(r){M8=r.wasm.cwrap(da,null,["number","array","number","number","array","array","number","number"])}function ave(r){let{inputs:{x:e},backend:t,attrs:{paddings:n,constantValue:o}}=r,s=n.map((d,h)=>d[0]+e.shape[h]+d[1]),i=t.dataIdMap.get(e.dataId).id,a=t.makeOutput(s,e.dtype),l=t.dataIdMap.get(a.dataId).id,u=new Uint8Array(new Int32Array(e.shape).buffer),p=n.map(d=>d[0]),c=n.map(d=>d[1]),m=new Uint8Array(new Int32Array(p).buffer),f=new Uint8Array(new Int32Array(c).buffer);return M8(i,u,e.shape.length,nr[e.dtype],m,f,o,l),a}var F8={kernelName:da,backendName:"wasm",kernelFunc:ave,setupFunc:sve};var ive=!1,R8=Ot(ha,ive);var L8;function lve(r){L8=r.wasm.cwrap(ga,null,["number","number","number"])}function uve(r){let{inputs:e,backend:t}=r,{x:n,alpha:o}=e,s=t.dataIdMap.get(n.dataId).id,i=t.dataIdMap.get(o.dataId).id,a=t.makeOutput(n.shape,"float32"),l=t.dataIdMap.get(a.dataId).id;return L8(s,i,l),a}var $8={kernelName:ga,backendName:"wasm",setupFunc:lve,kernelFunc:uve};var P8;function pve(r){P8=r.wasm.cwrap(hi,null,["number","number","number","number"])}function cve(r){let{backend:e,inputs:t,attrs:n}=r,{axis:o,keepDims:s}=n,{x:i}=t,a=e.dataIdMap.get(i.dataId).id,l=a,u=i,{transposed:p,axes:c,originalAxes:m,inputWasTransposed:f}=Yn(i,o,e),d=c;if(f){let T=e.dataIdMap.get(p.dataId).id;T!==a&&(u=p,l=T,d=C.getInnerMostAxes(d.length,u.shape.length))}C.assertAxesAreInnerMostDims("prod",d,u.shape.length);let[h,g]=C.computeOutAndReduceShapes(u.shape,d),b=x.sizeFromShape(g),y=e.makeOutput(h,u.dtype);if(x.sizeFromShape(u.shape)!==0){let T=e.dataIdMap.get(y.dataId).id;P8(l,b,nr[y.dtype],T)}if(f&&e.disposeData(p.dataId),s){let T=C.expandShapeToKeepDim(y.shape,m);y.shape=T}return y}var B8={kernelName:hi,backendName:"wasm",setupFunc:pve,kernelFunc:cve};var mve=r=>{let{backend:e,attrs:t}=r,{start:n,stop:o,step:s,dtype:i}=t,a=Ey(n,o,s,i),l=e.makeOutput([a.length],i);return e.typedArrayFromHeap(l).set(a),l},O8={kernelName:Ku,backendName:"wasm",kernelFunc:mve};var fve=!0,z8=Ot(Zs,fve);var G8=Bt(ba);var W8=Bt(xa);var K8;function dve(r){K8=r.wasm.cwrap(ya,null,["number","number","number","number","number","number","number","number","number","number"])}function hve(r){let{backend:e,inputs:t,attrs:n}=r,{images:o}=t,{alignCorners:s,halfPixelCenters:i,size:a}=n,[l,u]=a,[p,c,m,f]=o.shape,d=[p,l,u,f],h=e.dataIdMap.get(o.dataId),g;h.dtype!=="float32"&&(g=Tm({backend:e,inputs:{x:o},attrs:{dtype:"float32"}}),h=e.dataIdMap.get(g.dataId));let b=h.id,y=e.makeOutput(d,"float32");if(x.sizeFromShape(o.shape)===0)return y;let T=e.dataIdMap.get(y.dataId).id;return K8(b,p,c,m,f,l,u,s?1:0,i?1:0,T),g!=null&&e.disposeData(g.dataId),y}var V8={kernelName:ya,backendName:"wasm",setupFunc:dve,kernelFunc:hve};var U8;function gve(r){U8=r.wasm.cwrap(Ta,null,["number","array","number","array","number","number"])}function bve(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{dims:s}=n,i=x.parseAxisParam(s,o.shape);if(o.shape.length===0)return xm({inputs:{x:o},backend:t});let a=t.makeOutput(o.shape,o.dtype),l=t.dataIdMap.get(o.dataId).id,u=t.dataIdMap.get(a.dataId).id,p=new Uint8Array(new Int32Array(i).buffer),c=new Uint8Array(new Int32Array(o.shape).buffer);U8(l,p,i.length,c,o.shape.length,u);let m=Nn({inputs:{x:a},attrs:{shape:o.shape},backend:t});return t.disposeData(a.dataId),m}var j8={kernelName:Ta,backendName:"wasm",kernelFunc:bve,setupFunc:gve};var H8;function yve(r){H8=r.wasm.cwrap(Bl,null,["number","number","number","number","number","number","number","number","array","number","number"])}function xve(r){let{inputs:e,backend:t,attrs:n}=r,{image:o}=e,{radians:s,fillValue:i,center:a}=n,l=t.makeOutput(o.shape,o.dtype),u=t.dataIdMap.get(o.dataId).id,p=t.dataIdMap.get(l.dataId).id,[c,m,f,d]=o.shape,[h,g]=C.getImageCenter(a,m,f),b=i===0,y=255,T=typeof i=="number"?[i,i,i,b?0:y]:[...i,y],k=new Uint8Array(new Int32Array(T).buffer);return H8(u,c,m,f,d,s,h,g,k,T.length,p),l}var q8={kernelName:Bl,backendName:"wasm",kernelFunc:xve,setupFunc:yve};var X8=Bt(ka);var Y8=Bt(zo);var Z8;function Tve(r){Z8=r.wasm.cwrap(Dl,null,["number","number","number","number","number","number","array","number","number"])}function kve(r){let{backend:e,inputs:t,attrs:n}=r,{indices:o,updates:s}=t,{shape:i}=n,a=e.makeOutput(i,s.dtype);if(x.sizeFromShape(i)===0)return a;let{sliceRank:l,numUpdates:u,sliceSize:p,strides:c,outputSize:m}=xT.calculateShapes(s,o,i),d=e.dataIdMap.get(o.dataId).id,g=e.dataIdMap.get(s.dataId).id,b=new Uint8Array(new Int32Array(c).buffer),y=e.dataIdMap.get(a.dataId).id;return Z8(d,g,nr[s.dtype],l,u,p,b,m,y),a}var J8={kernelName:Dl,backendName:"wasm",setupFunc:Tve,kernelFunc:kve};var Q8;function Ive(r){Q8=r.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function vve(r){let{inputs:e,backend:t}=r,{condition:n,t:o,e:s}=e,i=t.dataIdMap.get(n.dataId).id,a=t.dataIdMap.get(o.dataId).id,l=t.dataIdMap.get(s.dataId).id,u=t.makeOutput(o.shape,o.dtype),p=t.dataIdMap.get(u.dataId).id,c=n.shape.length,m=o.shape.length,f=c===0||c>1||m===1?1:x.sizeFromShape(o.shape.slice(1));return Q8(i,a,l,f,p),u}var e5={kernelName:bi,backendName:"wasm",kernelFunc:vve,setupFunc:Ive};var t5;function wve(r){t5=r.wasm.cwrap(wa,null,["number","number"])}function _ve(r){let{backend:e,inputs:{x:t}}=r,n=e.dataIdMap.get(t.dataId).id,o=e.makeOutput(t.shape,t.dtype),s=e.dataIdMap.get(o.dataId).id;return x.sizeFromShape(o.shape)===0||t5(n,s),o}var r5={kernelName:"Sigmoid",backendName:"wasm",setupFunc:wve,kernelFunc:_ve};var n5=Bt(va);function km(r){let{inputs:{x:e},attrs:{begin:t,size:n},backend:o}=r,[s,i]=br.parseSliceParams(e,t,n),a=br.isSliceContinous(e.shape,s,i),l=o.readSync(e.dataId),u=o.makeOutput(i,e.dtype),p=x.computeStrides(e.shape),c=o.dataIdMap.get(u.dataId);if(a){let d=br.computeFlatOffset(s,p);return e.dtype==="string"?c.stringBytes=l.slice(d,d+x.sizeFromShape(i)):o.typedArrayFromHeap(u).set(l.subarray(d,d+x.sizeFromShape(i))),u}if(e.dtype==="string"){let d=Yd(l,s,i,e.shape,e.dtype);return c.stringBytes=d,u}let m=o.typedArrayFromHeap(u),f=e.shape.length;if(f===2)Cve(l,p[0],m,s,i);else if(f===3)Sve(l,p[0],p[1],m,s,i);else if(f===4)Nve(l,p[0],p[1],p[2],m,s,i);else{let d=Yd(l,s,i,e.shape,e.dtype);m.set(d)}return u}function Cve(r,e,t,n,o){let s=0,i=n[0],a=n[1],l=i+o[0];for(let u=i;u<l;u++){let p=u*e+a;t.set(r.subarray(p,p+o[1]),s),s+=o[1]}}function Sve(r,e,t,n,o,s){let i=0,a=o[0],l=o[1],u=o[2],p=a+s[0],c=l+s[1];for(let m=a;m<p;m++)for(let f=l;f<c;f++){let d=m*e+f*t+u;n.set(r.subarray(d,d+s[2]),i),i+=s[2]}}function Nve(r,e,t,n,o,s,i){let a=0,l=s[0],u=s[1],p=s[2],c=l+i[0],m=u+i[1],f=p+i[2],d=s[3];for(let h=l;h<c;h++)for(let g=u;g<m;g++)for(let b=p;b<f;b++){let y=h*e+g*t+b*n+d;o.set(r.subarray(y,y+i[3]),a),a+=i[3]}}var o5={kernelName:Ia,backendName:"wasm",kernelFunc:km};var s5;function Ave(r){s5=r.wasm.cwrap(Sa,null,["number","number","number","number"])}function Dve(r){let{backend:e,inputs:{logits:t},attrs:{dim:n}}=r,o=e.dataIdMap.get(t.dataId).id,s=e.makeOutput(t.shape,t.dtype),i=e.dataIdMap.get(s.dataId).id,a=t.shape[n],l=x.sizeFromShape(t.shape)/a;return x.sizeFromShape(s.shape)===0||s5(o,i,a,l),s}var a5={kernelName:Sa,backendName:"wasm",setupFunc:Ave,kernelFunc:Dve};function Eve(r){let{inputs:e,attrs:t,backend:n}=r,{x:o}=e,{numOrSizeSplits:s,axis:i}=t,a=x.parseAxisParam(i,o.shape)[0],l=C.prepareSplitSize(o,s,a),u=new Array(o.shape.length).fill(0),p=o.shape.slice();return l.map(c=>{let m=[...p];m[a]=c;let f=km({inputs:{x:o},attrs:{begin:u,size:m},backend:n});return u[a]+=c,f})}var i5={kernelName:yi,backendName:"wasm",kernelFunc:Eve};var l5=Bt(_a);var u5=Bt(ju);var Mve=!0,p5=Ot(Go,Mve);var c5;function Fve(r){c5=r.wasm.cwrap(cs,null,["number","number","number"])}function Rve(r){let{backend:e,inputs:t,attrs:n}=r,{alpha:o}=n,{x:s}=t,i=e.dataIdMap.get(s.dataId).id,a=e.makeOutput(s.shape,s.dtype),l=e.dataIdMap.get(a.dataId).id;return c5(i,o,l),a}var m5={kernelName:cs,backendName:"wasm",setupFunc:Fve,kernelFunc:Rve};var f5;function Lve(r){f5=r.wasm.cwrap(Ll,null,["number","array","number","array","array","array","array","array","number","number"])}function $ve(r){let{backend:e,inputs:t,attrs:n}=r,{x:o}=t,{begin:s,end:i,strides:a}=n;a==null&&(a=new Array(s.length));let{beginMask:l,endMask:u,ellipsisMask:p,newAxisMask:c,shrinkAxisMask:m}=n,f=C.slice_util.maskToAxes(p);if(f.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(p!==0&&c!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(p!==0&&m!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");let d=o.shape.length-s.length,h=C.slice_util.maskToAxes(c),g=o.shape.slice();h.forEach(V=>{s[V]=0,i[V]=1,g.splice(V,0,1)});let b=Nn({inputs:{x:o},attrs:{shape:g},backend:e}),{begin:y,end:T,strides:k}=C.slice_util.getNormalizedAxes(b.shape,f,d,s,i,a,l,u,p);s=y,i=T,a=k;let I=C.slice_util.maskToAxes(m);I.forEach(V=>{i[V]=s[V]+1,a[V]=1});let S=C.slice_util.computeOutShape(s,i,a),N=S.filter((V,q)=>I.indexOf(q)===-1);if(a.every(V=>V===1)){let V=km({inputs:{x:b},attrs:{begin:s,size:S},backend:e});e.disposeData(b.dataId);let q=Nn({inputs:{x:V},attrs:{shape:N},backend:e});return e.disposeData(V.dataId),q}let $=e.makeOutput(N,"float32");if(!N.some(V=>V===0)){let V=e.dataIdMap.get(b.dataId).id,q=new Uint8Array(new Int32Array(x.computeStrides(b.shape)).buffer),W=new Uint8Array(new Int32Array(s).buffer),Y=new Uint8Array(new Int32Array(i).buffer),Z=new Uint8Array(new Int32Array(a).buffer),J=new Uint8Array(new Int32Array(N).buffer),se=new Uint8Array(new Int32Array(x.computeStrides(N)).buffer),ee=e.dataIdMap.get($.dataId).id;f5(V,q,b.shape.length,W,Y,Z,J,se,N.length,ee)}e.disposeData(b.dataId);let O=Nn({inputs:{x:$},attrs:{shape:N},backend:e});return e.disposeData($.dataId),O}var d5={kernelName:Ll,backendName:"wasm",setupFunc:Lve,kernelFunc:$ve};var Pve=!0,h5=Ot(Wo,Pve);var g5;function Bve(r){g5=r.wasm.cwrap(Ca,null,["number, number, number"])}function Ove(r){let{backend:e,inputs:t,attrs:n}=r,{axis:o,keepDims:s}=n,{x:i}=t,a=e.dataIdMap.get(i.dataId).id,l=a,u=i,{transposed:p,axes:c,originalAxes:m,inputWasTransposed:f}=Yn(i,o,e),d=c;if(f){let T=e.dataIdMap.get(p.dataId).id;T!==a&&(u=p,l=T,d=C.getInnerMostAxes(d.length,u.shape.length))}C.assertAxesAreInnerMostDims("sum",d,u.shape.length);let[h,g]=C.computeOutAndReduceShapes(u.shape,d),b=x.sizeFromShape(g),y=e.makeOutput(h,u.dtype);if(x.sizeFromShape(u.shape)!==0){let T=e.dataIdMap.get(y.dataId).id;g5(l,b,T)}if(f&&e.disposeData(p.dataId),s){let T=C.expandShapeToKeepDim(y.shape,m);y.shape=T}return y}var b5={kernelName:Ca,backendName:"wasm",setupFunc:Bve,kernelFunc:Ove};var y5=Bt(Na);var x5=Bt(Aa);var T5;function zve(r){T5=r.wasm.cwrap(Ko,null,["number","array","number","array","number","number"])}function Gve(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,s=t.dataIdMap.get(o.dataId).id,{reps:i}=n,a=new Array(o.shape.length);for(let m=0;m<a.length;m++)a[m]=o.shape[m]*i[m];let l=new Uint8Array(new Int32Array(o.shape).buffer),u=new Uint8Array(new Int32Array(a).buffer),p=t.makeOutput(a,o.dtype),c=t.dataIdMap.get(p.dataId).id;return T5(s,l,o.shape.length,u,a.length,nr[p.dtype],c),p}var k5={kernelName:Ko,backendName:"wasm",setupFunc:zve,kernelFunc:Gve};var I5;function Wve(r){I5=r.wasm.cwrap($l,null,["number","array","number","number","number","bool","number","number"])}var Kve=({inputs:r,backend:e,attrs:t})=>{let{x:n}=r,{k:o,sorted:s}=t,i=e.dataIdMap.get(n.dataId).id,a=new Uint8Array(new Int32Array(n.shape).buffer),l=n.shape.slice();l[l.length-1]=o;let u=e.makeOutput(l,n.dtype),p=e.dataIdMap.get(u.dataId).id,c=e.makeOutput(l,"int32"),m=e.dataIdMap.get(c.dataId).id;return I5(i,a,n.shape.length,nr[n.dtype],o,s,p,m),[u,c]},v5={kernelName:$l,backendName:"wasm",setupFunc:Wve,kernelFunc:Kve};var w5;function Vve(r){w5=r.wasm.cwrap(Pl,null,["number","number","bool","number","number","number","number","number","number","array","number","number","number","number","number"])}function Uve(r){let{backend:e,inputs:t,attrs:n}=r,{image:o,transforms:s}=t,{interpolation:i,fillMode:a,fillValue:l,outputShape:u}=n,[p,c,m,f]=o.shape,[d,h]=u!=null?u:[c,m],g=[p,d,h,f],b=new Uint8Array(new Int32Array(x.computeStrides(o.shape)).buffer),y=e.makeOutput(g,o.dtype),T=e.dataIdMap.get(y.dataId).id,I=e.dataIdMap.get(o.dataId).id,N=e.dataIdMap.get(s.dataId).id,F=i==="nearest"?1:2,$;switch(a){case"constant":$=1;break;case"reflect":$=2;break;case"wrap":$=3;break;case"nearest":$=4;break;default:$=1;break}return w5(I,N,s.shape[0]>1,p,d,h,f,m,c,b,o.shape.length-1,F,$,l,T),y}var _5={kernelName:Pl,backendName:"wasm",setupFunc:Vve,kernelFunc:Uve};function jve(r){let{inputs:e,backend:t,attrs:n}=r,{value:o}=e,{axis:s}=n;s<0&&(s+=o.shape.length);let i=o.shape[s],a=o.shape.length,l=new Array(a-1),u=0;for(let f=0;f<a;f++)f!==s&&(l[u++]=o.shape[f]);let p=new Array(i),c=new Array(a).fill(0),m=o.shape.slice();m[s]=1;for(let f=0;f<p.length;f++)c[s]=f,p[f]=km({inputs:{x:o},attrs:{begin:c,size:m},backend:t});return p.map(({dataId:f,dtype:d})=>({dataId:f,dtype:d,shape:l}))}var C5={kernelName:xi,backendName:"wasm",kernelFunc:jve};function Hve(r){let{inputs:{x:e},backend:t}=r,n=t.makeOutput(e.shape,e.dtype);return t.typedArrayFromHeap(n).fill(0),n}var S5={kernelName:Ti,backendName:"wasm",kernelFunc:Hve};var qve=[Qq,e6,r6,i6,u6,c6,f6,g6,b6,y6,T6,k6,v6,_6,C6,N6,D6,M6,R6,L6,$6,P6,B6,z6,G6,W6,Jq,V6,j6,q6,Y6,J6,Q6,e8,n6,r8,n8,o8,s8,a8,l8,u8,c8,f8,h8,g8,y8,x8,T8,I8,w8,C8,S8,A8,D8,E8,F8,R8,$8,B8,O8,z8,G8,W8,d6,V8,j8,q8,Y8,X8,J8,e5,r5,n5,o5,a5,i5,l5,u5,p5,m5,d5,h5,b5,y5,x5,k5,v5,_5,s6,C5,S5];for(let r of qve)Bf(r);var Y1=X();Y1.registerFlag("WASM_HAS_SIMD_SUPPORT",async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,9,1,7,0,65,0,253,15,26,11])));Y1.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(Y1.get("IS_NODE"))return!1;try{return new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch(r){return!1}});var tE=Wi(D5());var E5='var Module={};function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;this.alert=threadAlert;Module["instantiateWasm"]=function(info,receiveInstance){var instance=new WebAssembly.Instance(Module["wasmModule"],info);Module["wasmModule"]=null;receiveInstance(instance);return instance.exports};function moduleLoaded(){}this.onmessage=function(e){try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;if(typeof e.data.urlOrBlob==="string"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module).then(function(instance){Module=instance;moduleLoaded()})}else if(e.data.cmd==="objectTransfer"){Module["PThread"].receiveObjectTransfer(e.data)}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0);var max=e.data.stackBase;var top=e.data.stackBase+e.data.stackSize;Module["establishStackSpace"](top,max);Module["_emscripten_tls_init"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].setThreadStatus(Module["_pthread_self"](),1);try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);if(!Module["getNoExitRuntime"]())Module["PThread"].threadExit(result)}catch(ex){if(ex==="Canceled!"){Module["PThread"].threadCancel()}else if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["getNoExitRuntime"]()){}else{Module["PThread"].threadExit(ex.status)}}else{Module["PThread"].threadExit(-2);throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["PThread"].threadCancel()}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex&&ex.stack)err(ex.stack);throw ex}};if(typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string"){self={location:{href:__filename}};var onmessage=this.onmessage;var nodeWorkerThreads=require("worker_threads");global.Worker=nodeWorkerThreads.Worker;var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",function(data){onmessage({data:data})});var nodeFS=require("fs");var nodeRead=function(filename){return nodeFS.readFileSync(filename,"utf8")};function globalEval(x){global.require=require;global.Module=Module;eval.call(null,x)}importScripts=function(f){globalEval(nodeRead(f))};postMessage=function(msg){parentPort.postMessage(msg)};if(typeof performance==="undefined"){performance={now:function(){return Date.now()}}}}';var F5=Wi(M5());var WI=class extends ii{constructor(e){super();this.wasm=e;this.dataIdNextNumber=1;this.wasm.tfjs.init(),this.dataIdMap=new Fu(this,Ma())}write(e,t,n){let o={id:this.dataIdNextNumber++};return this.move(o,e,t,n,1),o}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){let t=x.now();return e(),{kernelMs:x.now()-t}}move(e,t,n,o,s){let i=this.dataIdNextNumber++;if(o==="string"){let p=t;this.dataIdMap.set(e,{id:i,stringBytes:p,shape:n,dtype:o,memoryOffset:null,refCount:s});return}let a=x.sizeFromShape(n),l=a*x.bytesPerElement(o),u=this.wasm._malloc(l);this.dataIdMap.set(e,{id:i,memoryOffset:u,shape:n,dtype:o,refCount:s}),this.wasm.tfjs.registerTensor(i,a,u),t!=null&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,l),u)}async read(e){return this.readSync(e)}readSync(e){let{memoryOffset:t,dtype:n,shape:o,stringBytes:s}=this.dataIdMap.get(e);if(n==="string")return s;let i=this.wasm.HEAPU8.slice(t,t+x.sizeFromShape(o)*x.bytesPerElement(n));return Yve(i.buffer,n)}disposeData(e,t=!1){if(this.dataIdMap.has(e)){let n=this.dataIdMap.get(e);if(n.refCount--,!t&&n.refCount>0)return!1;this.wasm._free(n.memoryOffset),this.wasm.tfjs.disposeData(n.id),this.dataIdMap.delete(e)}return!0}refCount(e){return this.dataIdMap.has(e)?this.dataIdMap.get(e).refCount:0}incRef(e){let t=this.dataIdMap.get(e);t!=null&&t.refCount++}floatPrecision(){return 32}getMemoryOffset(e){return this.dataIdMap.get(e).memoryOffset}dispose(){this.wasm.tfjs.dispose(),"PThread"in this.wasm&&this.wasm.PThread.terminateAllThreads(),this.wasm=null}memory(){return{unreliable:!1}}makeOutput(e,t,n){let o;if(n==null)o=this.write(null,e,t);else{let s=this.dataIdNextNumber++;o={id:s},this.dataIdMap.set(o,{id:s,memoryOffset:n,shape:e,dtype:t,refCount:1});let i=x.sizeFromShape(e);this.wasm.tfjs.registerTensor(s,i,n)}return{dataId:o,shape:e,dtype:t}}typedArrayFromHeap({shape:e,dtype:t,dataId:n}){let o=this.wasm.HEAPU8.buffer,{memoryOffset:s}=this.dataIdMap.get(n),i=x.sizeFromShape(e);switch(t){case"float32":return new Float32Array(o,s,i);case"int32":return new Int32Array(o,s,i);case"bool":return new Uint8Array(o,s,i);default:throw new Error(`Unknown dtype ${t}`)}}};function Xve(r){return(e,t)=>(x.fetch(r,{credentials:"same-origin"}).then(n=>{n.ok||e.env.a(`failed to load wasm binary file at '${r}'`),n.arrayBuffer().then(o=>{WebAssembly.instantiate(o,e).then(s=>{t(s.instance,s.module)})})}),{})}function R5(r,e,t){if(KI!=null)return KI;let n="tfjs-backend-wasm.wasm";return r&&e?n="tfjs-backend-wasm-threaded-simd.wasm":r&&(n="tfjs-backend-wasm-simd.wasm"),Vy!=null&&Vy[n]!=null?Vy[n]:t+n}async function L5(){let[r,e]=await Promise.all([X().getAsync("WASM_HAS_SIMD_SUPPORT"),X().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((t,n)=>{let o={};o.locateFile=(a,l)=>{if(a.endsWith(".worker.js")){let u=E5,p=new Blob([u],{type:"application/javascript"});return URL.createObjectURL(p)}return a.endsWith(".wasm")?R5(r,e,Ky!=null?Ky:l):l+a},rE&&(o.instantiateWasm=Xve(R5(r,e,Ky!=null?Ky:"")));let s=!1;o.onAbort=()=>{if(s||Uy)return;Uy=!0,n({message:"Make sure the server can serve the `.wasm` file relative to the bundled js file. For more details see https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers"})};let i;e&&r&&KI==null?(o.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+tE.default.toString()],{type:"text/javascript"}),i=(0,tE.default)(o)):i=(0,F5.default)(o),i.then(a=>{s=!0,Uy=!1;let l=null;a.tfjs={init:a.cwrap("init",null,[]),registerTensor:a.cwrap("register_tensor",null,["number","number","number"]),disposeData:a.cwrap("dispose_data",l,["number"]),dispose:a.cwrap("dispose",l,[])},t({wasm:a})})})}function Yve(r,e){switch(e){case"float32":return new Float32Array(r);case"int32":return new Int32Array(r);case"bool":return new Uint8Array(r);default:throw new Error(`Unknown dtype ${e}`)}}var Zve=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],KI=null,Ky=null,Vy={},Uy=!1,rE=!1;function Jve(r,e=!1){if(OC("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),Uy)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");KI=r,rE=e}function Qve(r,e=!1){if(Uy)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPaths()` before you call `tf.setBackend()` or `tf.ready()`");if(typeof r=="string")Ky=r;else{Vy=r;let t=Zve.filter(n=>Vy[n]==null);if(t.length>0)throw new Error(`There were no entries found for the following binaries: ${t.join(",")}. Please either call setWasmPaths with a map providing a path for each binary, or with a string indicating the directory where all the binaries can be found.`)}rE=e}var ewe="3.7.0";var twe=2;jf("wasm",async()=>{let{wasm:r}=await L5();return new WI(r)},twe);var XAn={tfjs:hE,"tfjs-core":gE,"tfjs-data":bE,"tfjs-layers":yE,"tfjs-converter":xE,"tfjs-backend-cpu":TE,"tfjs-backend-webgl":kE,"tfjs-backend-wasm":IE};export{DE as Abs,EE as Acos,ME as Acosh,Qp as AdadeltaOptimizer,ec as AdagradOptimizer,tc as AdamOptimizer,rc as AdamaxOptimizer,bx as Add,FE as AddN,RE as All,LE as Any,$E as ArgMax,PE as ArgMin,BE as Asin,OE as Asinh,zE as Atan,WE as Atan2,GE as Atanh,KE as AvgPool,VE as AvgPool3D,bwe as AvgPool3DGrad,gwe as AvgPoolGrad,WI as BackendWasm,UE as BatchMatMul,jE as BatchToSpaceND,HE as Bincount,ywe as BroadcastTo,NN as Callback,$S as CallbackList,yx as Cast,qE as Ceil,XE as ClipByValue,YE as Complex,ZE as ComplexAbs,JE as Concat,QE as Conv2D,e2 as Conv2DBackpropFilter,t2 as Conv2DBackpropInput,r2 as Conv3D,xwe as Conv3DBackpropFilterV2,n2 as Conv3DBackpropInputV2,o2 as Cos,s2 as Cosh,i2 as CropAndResize,a2 as Cumsum,BS as CustomCallback,vE as DataStorage,l2 as DenseBincount,u2 as DepthToSpace,p2 as DepthwiseConv2dNative,c2 as DepthwiseConv2dNativeBackpropFilter,m2 as DepthwiseConv2dNativeBackpropInput,f2 as Diag,d2 as Dilation2D,kwe as Dilation2DBackpropFilter,Twe as Dilation2DBackpropInput,xw as ENV,AN as EarlyStopping,g2 as Einsum,b2 as Elu,Iwe as EluGrad,gx as Environment,x2 as Equal,y2 as Erf,T2 as Exp,k2 as ExpandDims,I2 as Expm1,v2 as FFT,w2 as Fill,_2 as FlipLeftRight,C2 as Floor,S2 as FloorDiv,Iw as FromPixels,N2 as FusedBatchNorm,ww as FusedConv2D,_w as FusedDepthwiseConv2D,TI as GPGPUContext,D2 as GatherNd,A2 as GatherV2,sA as GraphModel,E2 as Greater,M2 as GreaterEqual,PS as History,F2 as IFFT,xx as Identity,R2 as Imag,Vt as InputSpec,L2 as IsFinite,$2 as IsInf,P2 as IsNan,dx as KernelBackend,H2 as LRN,wwe as LRNGrad,QT as LayerVariable,Jo as LayersModel,B2 as LeakyRelu,O2 as Less,z2 as LessEqual,G2 as LinSpace,W2 as Log,K2 as Log1p,vwe as LogSoftmax,V2 as LogicalAnd,U2 as LogicalNot,j2 as LogicalOr,hy as MathBackendCPU,Ry as MathBackendWebGL,q2 as Max,Y2 as MaxPool,Z2 as MaxPool3D,Cwe as MaxPool3DGrad,_we as MaxPoolGrad,J2 as MaxPoolWithArgmax,X2 as Maximum,Q2 as Mean,eM as Min,tM as Minimum,rM as MirrorPad,nM as Mod,nc as MomentumOptimizer,oM as Multinomial,sM as Multiply,aM as Neg,lM as NonMaxSuppressionV3,uM as NonMaxSuppressionV4,pM as NonMaxSuppressionV5,iM as NotEqual,zF as OP_SCOPE_SUFFIX,mM as OneHot,cM as OnesLike,ro as Optimizer,fM as Pack,dM as PadV2,Swe as Pool,hM as Pow,gM as Prelu,bM as Prod,oc as RMSPropOptimizer,_s as RNN,yM as Range,Rw as Rank,xM as Real,h2 as RealDiv,TM as Reciprocal,gr as Reduction,kM as Relu,_M as Relu6,IM as Reshape,wM as ResizeBilinear,Awe as ResizeBilinearGrad,vM as ResizeNearestNeighbor,Nwe as ResizeNearestNeighborGrad,CM as Reverse,pF as RotateWithOffset,SM as Round,NM as Rsqrt,tl as SGDOptimizer,AM as ScatterNd,DM as Select,EM as Selu,kd as Sequential,$M as Sigmoid,LM as Sign,FM as Sin,RM as Sinh,MM as Slice,WM as Softmax,PM as Softplus,zM as SpaceToBatchND,KM as SparseFillEmptyRows,VM as SparseReshape,UM as SparseSegmentMean,jM as SparseSegmentSum,HM as SparseToDense,GM as SplitV,BM as Sqrt,Dwe as Square,qM as SquaredDifference,uF as Step,XM as StridedSlice,YM as StringNGrams,ZM as StringSplit,JM as StringToHashBucketFast,QM as Sub,OM as Sum,jn as SymbolicTensor,eF as Tan,tF as Tanh,Yt as Tensor,Pp as TensorBuffer,Tx as Tile,rF as TopK,nF as Transform,oF as Transpose,sF as Unique,aF as Unpack,iF as UnsortedSegmentSum,Cu as Variable,lF as ZerosLike,vw as _FusedMatMul,un as abs,EY as acos,FY as acosh,Re as add,LY as addN,PY as all,OY as any,GY as argMax,KY as argMin,UY as asin,HY as asinh,XY as atan,ZY as atan2,QY as atanh,c_ as avgPool,u9 as avgPool3d,RAe as backend,t$ as backend_util,h9 as basicLSTMCell,Wp as batchNorm,x9 as batchNorm2d,k9 as batchNorm3d,v9 as batchNorm4d,m_ as batchToSpaceND,f_ as bincount,_je as booleanMaskAsync,Ch as broadcastTo,TR as browser,Ln as buffer,Bme as callbacks,ft as cast,S9 as ceil,A9 as clipByValue,Os as clone,ss as complex,Dr as concat,E9 as concat1d,F9 as concat2d,L9 as concat3d,P9 as concat4d,iz as constraints,z9 as conv1d,Kp as conv2d,K9 as conv2dTranspose,U9 as conv3d,q9 as conv3dTranspose,Pwe as copyRegisteredKernels,Y9 as cos,J9 as cosh,Zx as cosineWindow,eZ as cumsum,$n as customGrad,kA as data,rZ as denseBincount,wY as deprecationWarn,oZ as depthToSpace,Sh as depthwiseConv2d,zme as deregisterOp,PF as device_util,iZ as diag,uZ as dilation2d,kAe as disableDeprecationWarnings,$r as dispose,IAe as disposeVariables,ct as div,hZ as divNoNan,bZ as dot,PHe as dropout,xZ as einsum,g_ as elu,TAe as enableDebugMode,xAe as enableProdMode,uL as enclosingPowerOfTwo,vAe as engine,Ze as env,h_ as equal,IZ as erf,zs as exp,Nu as expandDims,CZ as expm1,b_ as eye,Eh as fft,Vp as fill,EAe as findBackend,MAe as findBackendFactory,y_ as floor,i_ as floorDiv,S4 as forceHalfFloat,gL as fused,x_ as gather,vHe as gatherND,IR as gather_util,AAe as getBackend,Cw as getGradient,bh as getKernel,kx as getKernelsForBackend,tU as gpgpu_util,XZ as grad,YZ as grads,qm as greater,T_ as greaterEqual,Qm as ifft,Ah as imag,iZe as image,VHe as inTopKAsync,Sz as initializers,HS as input,gR as io,H_ as irfft,LZ as isFinite,PZ as isInf,OZ as isNaN,zR as keep,r$ as kernel_impls,l3 as layers,k_ as leakyRelu,WZ as less,Dh as lessEqual,cZe as linalg,VZ as linspace,dfe as loadGraphModel,Zpe as loadLayersModel,jZ as localResponseNormalization,Au as log,I_ as log1p,rJ as logSigmoid,iJ as logSoftmax,C_ as logSumExp,Xm as logicalAnd,S_ as logicalNot,N_ as logicalOr,yJ as logicalXor,kZe as losses,gt as matMul,yR as math,Yi as max,A_ as maxPool,kJ as maxPool3d,vJ as maxPoolWithArgmax,D_ as maximum,Ym as mean,wAe as memory,CJ as meshgrid,u3 as metrics,Ux as min,E_ as minimum,DJ as mirrorPad,MJ as mod,Xpe as model,p3 as models,LJ as moments,Zje as movingAverage,fe as mul,PJ as multiRNNCell,OJ as multinomial,Ao as neg,zte as nextFrame,Yx as norm,M_ as notEqual,Lx as oneHot,Qi as ones,WJ as onesLike,E as op,VJ as outerProduct,el as pad,HJ as pad1d,XJ as pad2d,ZJ as pad3d,QJ as pad4d,oQ as pool,Du as pow,R_ as prelu,Qw as print,lQ as prod,_Ae as profile,pQ as rand,yQ as randomGamma,TQ as randomNormal,V_ as randomUniform,jp as range,NAe as ready,Jm as real,wQ as reciprocal,FAe as registerBackend,Jpe as registerCallbackConstructor,Rwe as registerGradient,a7 as registerKernel,Ome as registerOp,c3 as regularizers,Hp as relu,U_ as relu6,DAe as removeBackend,te as reshape,as as reverse,AQ as reverse1d,EQ as reverse2d,FQ as reverse3d,LQ as reverse4d,Mh as rfft,j_ as round,BQ as rsqrt,Je as scalar,aHe as scatterND,wR as scatter_util,zQ as selu,WQ as separableConv2d,Ype as sequential,LR as serialization,SAe as setBackend,LAe as setPlatform,Jve as setWasmPath,Qve as setWasmPaths,a0 as setWebGLContext,VQ as setdiff1dAsync,gW as shared,Xi as sigmoid,jQ as sign,H9e as signal,qQ as sin,YQ as sinh,kt as slice,JQ as slice1d,eee as slice2d,ree as slice3d,oee as slice4d,Bx as slice_util,aee as softmax,w_ as softplus,F_ as spaceToBatchND,CZe as sparse,gHe as sparseToDense,W9e as spectral,Eu as split,To as sqrt,pn as square,q_ as squaredDifference,Fh as squeeze,Mu as stack,X_ as step,yee as stridedSlice,DZe as string,We as sub,It as sum,k7 as sumOutType,Tee as tan,Wx as tanh,Vi as tensor,Pn as tensor1d,qp as tensor2d,n_ as tensor3d,kee as tensor4d,Iee as tensor5d,vee as tensor6d,$F as tensor_util,OR as test_util,mr as tidy,Nh as tile,CAe as time,_ee as topk,Ant as train,_h as transpose,See as truncatedNormal,Aee as unique,$we as unregisterGradient,Lwe as unregisterKernel,Eee as unsortedSegmentSum,Rh as unstack,Wm as upcastType,_F as util,ZZ as valueAndGrad,JZ as valueAndGrads,Fee as variable,v_ as variableGrads,XAn as version,hfe as version_converter,vY as version_core,qfe as version_cpu,tb as version_layers,ewe as version_wasm,zbe as version_webgl,bjr as webgl,eU as webgl_util,ai as where,Y_ as whereAsync,Ji as zeros,qr as zerosLike};
|
|
/**
|
|
* @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
|
|
* Copyright 2021 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 2021 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
|
|
*
|
|
* https://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 See the LICENSE file. */
|
|
//# sourceMappingURL=tfjs.esm.js.map
|