mirror of https://github.com/vladmandic/human
4461 lines
1.1 MiB
4461 lines
1.1 MiB
|
|
/*
|
|
Human library
|
|
homepage: <https://github.com/vladmandic/human>
|
|
author: <https://github.com/vladmandic>'
|
|
*/
|
|
var YW=Object.create;var Ig=Object.defineProperty;var ZW=Object.getOwnPropertyDescriptor;var JW=Object.getOwnPropertyNames;var QW=Object.getPrototypeOf,ej=Object.prototype.hasOwnProperty;var tj=r=>Ig(r,"__esModule",{value:!0});var Lc=r=>{if(typeof require!="undefined")return require(r);throw new Error('Dynamic require of "'+r+'" is not supported')};var Ut=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),je=(r,e)=>{for(var t in e)Ig(r,t,{get:e[t],enumerable:!0})},rj=(r,e,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of JW(e))!ej.call(r,n)&&n!=="default"&&Ig(r,n,{get:()=>e[n],enumerable:!(t=ZW(e,n))||t.enumerable});return r},nu=r=>rj(tj(Ig(r!=null?YW(QW(r)):{},"default",r&&r.__esModule&&"default"in r?{get:()=>r.default,enumerable:!0}:{value:r,enumerable:!0})),r);var A1=Ut((nie,E1)=>{E1.exports=Gt;var so=null;try{so=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 Gt(r,e,t){this.low=r|0,this.high=e|0,this.unsigned=!!t}Gt.prototype.__isLong__;Object.defineProperty(Gt.prototype,"__isLong__",{value:!0});function $n(r){return(r&&r.__isLong__)===!0}Gt.isLong=$n;var w1={},_1={};function uu(r,e){var t,n,o;return e?(r>>>=0,(o=0<=r&&r<256)&&(n=_1[r],n)?n:(t=Wt(r,(r|0)<0?-1:0,!0),o&&(_1[r]=t),t)):(r|=0,(o=-128<=r&&r<128)&&(n=w1[r],n)?n:(t=Wt(r,r<0?-1:0,!1),o&&(w1[r]=t),t))}Gt.fromInt=uu;function io(r,e){if(isNaN(r))return e?cu:ao;if(e){if(r<0)return cu;if(r>=v1)return T1}else{if(r<=-C1)return Rn;if(r+1>=C1)return N1}return r<0?io(-r,e).neg():Wt(r%Cp|0,r/Cp|0,e)}Gt.fromNumber=io;function Wt(r,e,t){return new Gt(r,e,t)}Gt.fromBits=Wt;var Eg=Math.pow;function Hw(r,e,t){if(r.length===0)throw Error("empty string");if(r==="NaN"||r==="Infinity"||r==="+Infinity"||r==="-Infinity")return ao;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 Hw(r.substring(1),e,t).neg();for(var o=io(Eg(t,8)),s=ao,a=0;a<r.length;a+=8){var i=Math.min(8,r.length-a),l=parseInt(r.substring(a,a+i),t);if(i<8){var u=io(Eg(t,i));s=s.mul(u).add(io(l))}else s=s.mul(o),s=s.add(io(l))}return s.unsigned=e,s}Gt.fromString=Hw;function Cs(r,e){return typeof r=="number"?io(r,e):typeof r=="string"?Hw(r,e):Wt(r.low,r.high,typeof e=="boolean"?e:r.unsigned)}Gt.fromValue=Cs;var k1=1<<16,Ej=1<<24,Cp=k1*k1,v1=Cp*Cp,C1=v1/2,I1=uu(Ej),ao=uu(0);Gt.ZERO=ao;var cu=uu(0,!0);Gt.UZERO=cu;var Ip=uu(1);Gt.ONE=Ip;var S1=uu(1,!0);Gt.UONE=S1;var Kw=uu(-1);Gt.NEG_ONE=Kw;var N1=Wt(4294967295|0,2147483647|0,!1);Gt.MAX_VALUE=N1;var T1=Wt(4294967295|0,4294967295|0,!0);Gt.MAX_UNSIGNED_VALUE=T1;var Rn=Wt(0,2147483648|0,!1);Gt.MIN_VALUE=Rn;var we=Gt.prototype;we.toInt=function(){return this.unsigned?this.low>>>0:this.low};we.toNumber=function(){return this.unsigned?(this.high>>>0)*Cp+(this.low>>>0):this.high*Cp+(this.low>>>0)};we.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(Rn)){var t=io(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=io(Eg(e,6),this.unsigned),a=this,i="";;){var l=a.div(s),u=a.sub(l.mul(s)).toInt()>>>0,c=u.toString(e);if(a=l,a.isZero())return c+i;for(;c.length<6;)c="0"+c;i=""+c+i}};we.getHighBits=function(){return this.high};we.getHighBitsUnsigned=function(){return this.high>>>0};we.getLowBits=function(){return this.low};we.getLowBitsUnsigned=function(){return this.low>>>0};we.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Rn)?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};we.isZero=function(){return this.high===0&&this.low===0};we.eqz=we.isZero;we.isNegative=function(){return!this.unsigned&&this.high<0};we.isPositive=function(){return this.unsigned||this.high>=0};we.isOdd=function(){return(this.low&1)==1};we.isEven=function(){return(this.low&1)==0};we.equals=function(e){return $n(e)||(e=Cs(e)),this.unsigned!==e.unsigned&&this.high>>>31==1&&e.high>>>31==1?!1:this.high===e.high&&this.low===e.low};we.eq=we.equals;we.notEquals=function(e){return!this.eq(e)};we.neq=we.notEquals;we.ne=we.notEquals;we.lessThan=function(e){return this.comp(e)<0};we.lt=we.lessThan;we.lessThanOrEqual=function(e){return this.comp(e)<=0};we.lte=we.lessThanOrEqual;we.le=we.lessThanOrEqual;we.greaterThan=function(e){return this.comp(e)>0};we.gt=we.greaterThan;we.greaterThanOrEqual=function(e){return this.comp(e)>=0};we.gte=we.greaterThanOrEqual;we.ge=we.greaterThanOrEqual;we.compare=function(e){if($n(e)||(e=Cs(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};we.comp=we.compare;we.negate=function(){return!this.unsigned&&this.eq(Rn)?Rn:this.not().add(Ip)};we.neg=we.negate;we.add=function(e){$n(e)||(e=Cs(e));var t=this.high>>>16,n=this.high&65535,o=this.low>>>16,s=this.low&65535,a=e.high>>>16,i=e.high&65535,l=e.low>>>16,u=e.low&65535,c=0,p=0,m=0,f=0;return f+=s+u,m+=f>>>16,f&=65535,m+=o+l,p+=m>>>16,m&=65535,p+=n+i,c+=p>>>16,p&=65535,c+=t+a,c&=65535,Wt(m<<16|f,c<<16|p,this.unsigned)};we.subtract=function(e){return $n(e)||(e=Cs(e)),this.add(e.neg())};we.sub=we.subtract;we.multiply=function(e){if(this.isZero())return ao;if($n(e)||(e=Cs(e)),so){var t=so.mul(this.low,this.high,e.low,e.high);return Wt(t,so.get_high(),this.unsigned)}if(e.isZero())return ao;if(this.eq(Rn))return e.isOdd()?Rn:ao;if(e.eq(Rn))return this.isOdd()?Rn:ao;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(I1)&&e.lt(I1))return io(this.toNumber()*e.toNumber(),this.unsigned);var n=this.high>>>16,o=this.high&65535,s=this.low>>>16,a=this.low&65535,i=e.high>>>16,l=e.high&65535,u=e.low>>>16,c=e.low&65535,p=0,m=0,f=0,d=0;return d+=a*c,f+=d>>>16,d&=65535,f+=s*c,m+=f>>>16,f&=65535,f+=a*u,m+=f>>>16,f&=65535,m+=o*c,p+=m>>>16,m&=65535,m+=s*u,p+=m>>>16,m&=65535,m+=a*l,p+=m>>>16,m&=65535,p+=n*c+o*u+s*l+a*i,p&=65535,Wt(f<<16|d,p<<16|m,this.unsigned)};we.mul=we.multiply;we.divide=function(e){if($n(e)||(e=Cs(e)),e.isZero())throw Error("division by zero");if(so){if(!this.unsigned&&this.high===-2147483648&&e.low===-1&&e.high===-1)return this;var t=(this.unsigned?so.div_u:so.div_s)(this.low,this.high,e.low,e.high);return Wt(t,so.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?cu:ao;var n,o,s;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return cu;if(e.gt(this.shru(1)))return S1;s=cu}else{if(this.eq(Rn)){if(e.eq(Ip)||e.eq(Kw))return Rn;if(e.eq(Rn))return Ip;var a=this.shr(1);return n=a.div(e).shl(1),n.eq(ao)?e.isNegative()?Ip:Kw:(o=this.sub(e.mul(n)),s=n.add(o.div(e)),s)}else if(e.eq(Rn))return this.unsigned?cu:ao;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=ao}for(o=this;o.gte(e);){n=Math.max(1,Math.floor(o.toNumber()/e.toNumber()));for(var i=Math.ceil(Math.log(n)/Math.LN2),l=i<=48?1:Eg(2,i-48),u=io(n),c=u.mul(e);c.isNegative()||c.gt(o);)n-=l,u=io(n,this.unsigned),c=u.mul(e);u.isZero()&&(u=Ip),s=s.add(u),o=o.sub(c)}return s};we.div=we.divide;we.modulo=function(e){if($n(e)||(e=Cs(e)),so){var t=(this.unsigned?so.rem_u:so.rem_s)(this.low,this.high,e.low,e.high);return Wt(t,so.get_high(),this.unsigned)}return this.sub(this.div(e).mul(e))};we.mod=we.modulo;we.rem=we.modulo;we.not=function(){return Wt(~this.low,~this.high,this.unsigned)};we.and=function(e){return $n(e)||(e=Cs(e)),Wt(this.low&e.low,this.high&e.high,this.unsigned)};we.or=function(e){return $n(e)||(e=Cs(e)),Wt(this.low|e.low,this.high|e.high,this.unsigned)};we.xor=function(e){return $n(e)||(e=Cs(e)),Wt(this.low^e.low,this.high^e.high,this.unsigned)};we.shiftLeft=function(e){return $n(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?Wt(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):Wt(0,this.low<<e-32,this.unsigned)};we.shl=we.shiftLeft;we.shiftRight=function(e){return $n(e)&&(e=e.toInt()),(e&=63)===0?this:e<32?Wt(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):Wt(this.high>>e-32,this.high>=0?0:-1,this.unsigned)};we.shr=we.shiftRight;we.shiftRightUnsigned=function(e){if($n(e)&&(e=e.toInt()),e&=63,e===0)return this;var t=this.high;if(e<32){var n=this.low;return Wt(n>>>e|t<<32-e,t>>>e,this.unsigned)}else return e===32?Wt(t,0,this.unsigned):Wt(t>>>e-32,0,this.unsigned)};we.shru=we.shiftRightUnsigned;we.shr_u=we.shiftRightUnsigned;we.toSigned=function(){return this.unsigned?Wt(this.low,this.high,!1):this};we.toUnsigned=function(){return this.unsigned?this:Wt(this.low,this.high,!0)};we.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()};we.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]};we.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]};Gt.fromBytes=function(e,t,n){return n?Gt.fromBytesLE(e,t):Gt.fromBytesBE(e,t)};Gt.fromBytesLE=function(e,t){return new Gt(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)};Gt.fromBytesBE=function(e,t){return new Gt(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)}});var fT=Ut(()=>{});var XT=Ut((KT,J_)=>{(function(r,e,t){function n(i){var l=this,u=a();l.next=function(){var c=2091639*l.s0+l.c*23283064365386963e-26;return l.s0=l.s1,l.s1=l.s2,l.s2=c-(l.c=c|0)},l.c=1,l.s0=u(" "),l.s1=u(" "),l.s2=u(" "),l.s0-=u(i),l.s0<0&&(l.s0+=1),l.s1-=u(i),l.s1<0&&(l.s1+=1),l.s2-=u(i),l.s2<0&&(l.s2+=1),u=null}function o(i,l){return l.c=i.c,l.s0=i.s0,l.s1=i.s1,l.s2=i.s2,l}function s(i,l){var u=new n(i),c=l&&l.state,p=u.next;return p.int32=function(){return u.next()*4294967296|0},p.double=function(){return p()+(p()*2097152|0)*11102230246251565e-32},p.quick=p,c&&(typeof c=="object"&&o(c,u),p.state=function(){return o(u,{})}),p}function a(){var i=4022871197,l=function(u){u=u.toString();for(var c=0;c<u.length;c++){i+=u.charCodeAt(c);var p=.02519603282416938*i;i=p>>>0,p-=i,p*=i,i=p>>>0,p-=i,i+=p*4294967296}return(i>>>0)*23283064365386963e-26};return l}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.alea=s})(KT,typeof J_=="object"&&J_,typeof define=="function"&&define)});var ZT=Ut((YT,Q_)=>{(function(r,e,t){function n(a){var i=this,l="";i.x=0,i.y=0,i.z=0,i.w=0,i.next=function(){var c=i.x^i.x<<11;return i.x=i.y,i.y=i.z,i.z=i.w,i.w^=i.w>>>19^c^c>>>8},a===(a|0)?i.x=a:l+=a;for(var u=0;u<l.length+64;u++)i.x^=l.charCodeAt(u)|0,i.next()}function o(a,i){return i.x=a.x,i.y=a.y,i.z=a.z,i.w=a.w,i}function s(a,i){var l=new n(a),u=i&&i.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var p=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=l.next,c.quick=c,u&&(typeof u=="object"&&o(u,l),c.state=function(){return o(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xor128=s})(YT,typeof Q_=="object"&&Q_,typeof define=="function"&&define)});var QT=Ut((JT,ek)=>{(function(r,e,t){function n(a){var i=this,l="";i.next=function(){var c=i.x^i.x>>>2;return i.x=i.y,i.y=i.z,i.z=i.w,i.w=i.v,(i.d=i.d+362437|0)+(i.v=i.v^i.v<<4^(c^c<<1))|0},i.x=0,i.y=0,i.z=0,i.w=0,i.v=0,a===(a|0)?i.x=a:l+=a;for(var u=0;u<l.length+64;u++)i.x^=l.charCodeAt(u)|0,u==l.length&&(i.d=i.x<<10^i.x>>>4),i.next()}function o(a,i){return i.x=a.x,i.y=a.y,i.z=a.z,i.w=a.w,i.v=a.v,i.d=a.d,i}function s(a,i){var l=new n(a),u=i&&i.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var p=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=l.next,c.quick=c,u&&(typeof u=="object"&&o(u,l),c.state=function(){return o(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xorwow=s})(JT,typeof ek=="object"&&ek,typeof define=="function"&&define)});var tE=Ut((eE,tk)=>{(function(r,e,t){function n(a){var i=this;i.next=function(){var u=i.x,c=i.i,p,m,f;return p=u[c],p^=p>>>7,m=p^p<<24,p=u[c+1&7],m^=p^p>>>10,p=u[c+3&7],m^=p^p>>>3,p=u[c+4&7],m^=p^p<<7,p=u[c+7&7],p=p^p<<13,m^=p^p<<9,u[c]=m,i.i=c+1&7,m};function l(u,c){var p,m,f=[];if(c===(c|0))m=f[0]=c;else for(c=""+c,p=0;p<c.length;++p)f[p&7]=f[p&7]<<15^c.charCodeAt(p)+f[p+1&7]<<13;for(;f.length<8;)f.push(0);for(p=0;p<8&&f[p]===0;++p);for(p==8?m=f[7]=-1:m=f[p],u.x=f,u.i=0,p=256;p>0;--p)u.next()}l(i,a)}function o(a,i){return i.x=a.x.slice(),i.i=a.i,i}function s(a,i){a==null&&(a=+new Date);var l=new n(a),u=i&&i.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var p=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=l.next,c.quick=c,u&&(u.x&&o(u,l),c.state=function(){return o(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xorshift7=s})(eE,typeof tk=="object"&&tk,typeof define=="function"&&define)});var nE=Ut((rE,rk)=>{(function(r,e,t){function n(a){var i=this;i.next=function(){var u=i.w,c=i.X,p=i.i,m,f;return i.w=u=u+1640531527|0,f=c[p+34&127],m=c[p=p+1&127],f^=f<<13,m^=m<<17,f^=f>>>15,m^=m>>>12,f=c[p]=f^m,i.i=p,f+(u^u>>>16)|0};function l(u,c){var p,m,f,d,h,g=[],x=128;for(c===(c|0)?(m=c,c=null):(c=c+"\0",m=0,x=Math.max(x,c.length)),f=0,d=-32;d<x;++d)c&&(m^=c.charCodeAt((d+32)%c.length)),d===0&&(h=m),m^=m<<10,m^=m>>>15,m^=m<<4,m^=m>>>13,d>=0&&(h=h+1640531527|0,p=g[d&127]^=m+h,f=p==0?f+1:0);for(f>=128&&(g[(c&&c.length||0)&127]=-1),f=127,d=4*128;d>0;--d)m=g[f+34&127],p=g[f=f+1&127],m^=m<<13,p^=p<<17,m^=m>>>15,p^=p>>>12,g[f]=m^p;u.w=h,u.X=g,u.i=f}l(i,a)}function o(a,i){return i.i=a.i,i.w=a.w,i.X=a.X.slice(),i}function s(a,i){a==null&&(a=+new Date);var l=new n(a),u=i&&i.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var p=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=l.next,c.quick=c,u&&(u.X&&o(u,l),c.state=function(){return o(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xor4096=s})(rE,typeof rk=="object"&&rk,typeof define=="function"&&define)});var sE=Ut((oE,nk)=>{(function(r,e,t){function n(a){var i=this,l="";i.next=function(){var c=i.b,p=i.c,m=i.d,f=i.a;return c=c<<25^c>>>7^p,p=p-m|0,m=m<<24^m>>>8^f,f=f-c|0,i.b=c=c<<20^c>>>12^p,i.c=p=p-m|0,i.d=m<<16^p>>>16^f,i.a=f-c|0},i.a=0,i.b=0,i.c=2654435769|0,i.d=1367130551,a===Math.floor(a)?(i.a=a/4294967296|0,i.b=a|0):l+=a;for(var u=0;u<l.length+20;u++)i.b^=l.charCodeAt(u)|0,i.next()}function o(a,i){return i.a=a.a,i.b=a.b,i.c=a.c,i.d=a.d,i}function s(a,i){var l=new n(a),u=i&&i.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var p=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=l.next,c.quick=c,u&&(typeof u=="object"&&o(u,l),c.state=function(){return o(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.tychei=s})(oE,typeof nk=="object"&&nk,typeof define=="function"&&define)});var ok=Ut(()=>{});var iE=Ut((kve,Yg)=>{(function(r,e){var t=this,n=256,o=6,s=52,a="random",i=e.pow(n,o),l=e.pow(2,s),u=l*2,c=n-1,p;function m(w,_,C){var A=[];_=_==!0?{entropy:!0}:_||{};var D=g(h(_.entropy?[w,b(r)]:w==null?x():w,3),A),$=new f(A),R=function(){for(var M=$.g(o),G=i,j=0;M<l;)M=(M+j)*n,G*=n,j=$.g(1);for(;M>=u;)M/=2,G/=2,j>>>=1;return(M+j)/G};return R.int32=function(){return $.g(4)|0},R.quick=function(){return $.g(4)/4294967296},R.double=R,g(b($.S),r),(_.pass||C||function(M,G,j,U){return U&&(U.S&&d(U,$),M.state=function(){return d($,{})}),j?(e[a]=M,G):M})(R,D,"global"in _?_.global:this==e,_.state)}e["seed"+a]=m;function f(w){var _,C=w.length,A=this,D=0,$=A.i=A.j=0,R=A.S=[];for(C||(w=[C++]);D<n;)R[D]=D++;for(D=0;D<n;D++)R[D]=R[$=c&$+w[D%C]+(_=R[D])],R[$]=_;(A.g=function(M){for(var G,j=0,U=A.i,q=A.j,H=A.S;M--;)G=H[U=c&U+1],j=j*n+H[c&(H[U]=H[q=c&q+G])+(H[q]=G)];return A.i=U,A.j=q,j})(n)}function d(w,_){return _.i=w.i,_.j=w.j,_.S=w.S.slice(),_}function h(w,_){var C=[],A=typeof w,D;if(_&&A=="object")for(D in w)try{C.push(h(w[D],_-1))}catch($){}return C.length?C:A=="string"?w:w+"\0"}function g(w,_){for(var C=w+"",A,D=0;D<C.length;)_[c&D]=c&(A^=_[c&D]*19)+C.charCodeAt(D++);return b(_)}function x(){try{var w;return p&&(w=p.randomBytes)?w=w(n):(w=new Uint8Array(n),(t.crypto||t.msCrypto).getRandomValues(w)),b(w)}catch(A){var _=t.navigator,C=_&&_.plugins;return[+new Date,t,C,t.screen,b(r)]}}function b(w){return String.fromCharCode.apply(0,w)}if(g(e.random(),r),typeof Yg=="object"&&Yg.exports){Yg.exports=m;try{p=ok()}catch(w){}}else typeof define=="function"&&define.amd&&define(function(){return m})})([],Math)});var sk=Ut((vve,aE)=>{var SH=XT(),NH=ZT(),TH=QT(),EH=tE(),AH=nE(),DH=sE(),$u=iE();$u.alea=SH;$u.xor128=NH;$u.xorwow=TH;$u.xorshift7=EH;$u.xor4096=AH;$u.tychei=DH;aE.exports=$u});var am=Ut(()=>{});var bz=Ut(()=>{});var wz=Ut(()=>{});var _z=Ut((py,CC)=>{var vC=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 ee.buffer!=He&&cr(ee.buffer),pt}function n(){return ee.buffer!=He&&cr(ee.buffer),ft}function o(){return ee.buffer!=He&&cr(ee.buffer),tr}function s(){return ee.buffer!=He&&cr(ee.buffer),gn}function a(){return ee.buffer!=He&&cr(ee.buffer),Qn}var i=typeof e!="undefined"?e:{},l,u;i.ready=new Promise(function(N,F){l=N,u=F});var c={},p;for(p in i)i.hasOwnProperty(p)&&(c[p]=i[p]);var m=[],f="./this.program",d=function(N,F){throw F},h=!1,g=!1,x=!1,b=!1;h=typeof window=="object",g=typeof importScripts=="function",x=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",b=!h&&!x&&!g;var w=i.ENVIRONMENT_IS_PTHREAD||!1;w&&(He=i.buffer);var _="";function C(N){return i.locateFile?i.locateFile(N,_):_+N}var A,D,$,R,M,G;if(x){g?_=am().dirname(_)+"/":_=__dirname+"/",A=function(F,V){return M||(M=Lc("fs")),G||(G=am()),F=G.normalize(F),M.readFileSync(F,V?null:"utf8")},$=function(F){var V=A(F,!0);return V.buffer||(V=new Uint8Array(V)),fe(V.buffer),V},process.argv.length>1&&(f=process.argv[1].replace(/\\/g,"/")),m=process.argv.slice(2),process.on("uncaughtException",function(N){if(!(N instanceof qm))throw N}),process.on("unhandledRejection",Ai),d=function(N){process.exit(N)},i.inspect=function(){return"[Emscripten Module object]"};var j;try{j=bz()}catch(N){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),N}global.Worker=j.Worker}else b?(typeof read!="undefined"&&(A=function(F){return read(F)}),$=function(F){var V;return typeof readbuffer=="function"?new Uint8Array(readbuffer(F)):(V=read(F,"binary"),fe(typeof V=="object"),V)},typeof scriptArgs!="undefined"?m=scriptArgs:typeof arguments!="undefined"&&(m=arguments),typeof quit=="function"&&(d=function(N){quit(N)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(h||g)&&(g?_=self.location.href:typeof document!="undefined"&&document.currentScript&&(_=document.currentScript.src),typeof r!="undefined"&&r&&(_=r),_.indexOf("blob:")!==0?_=_.substr(0,_.lastIndexOf("/")+1):_="",x?(A=function(F,V){return M||(M=Lc("fs")),G||(G=am()),F=G.normalize(F),M.readFileSync(F,V?null:"utf8")},$=function(F){var V=A(F,!0);return V.buffer||(V=new Uint8Array(V)),fe(V.buffer),V}):(A=function(N){var F=new XMLHttpRequest;return F.open("GET",N,!1),F.send(null),F.responseText},g&&($=function(N){var F=new XMLHttpRequest;return F.open("GET",N,!1),F.responseType="arraybuffer",F.send(null),new Uint8Array(F.response)}),D=function(N,F,V){var K=new XMLHttpRequest;K.open("GET",N,!0),K.responseType="arraybuffer",K.onload=function(){if(K.status==200||K.status==0&&K.response){F(K.response);return}V()},K.onerror=V,K.send(null)}),R=function(N){document.title=N});x&&typeof performance=="undefined"&&(global.performance=wz().performance);var U=i.print||console.log.bind(console),q=i.printErr||console.warn.bind(console);for(p in c)c.hasOwnProperty(p)&&(i[p]=c[p]);c=null,i.arguments&&(m=i.arguments),i.thisProgram&&(f=i.thisProgram),i.quit&&(d=i.quit);var H=Atomics.load,X=Atomics.store,ne=Atomics.compareExchange,Y;i.wasmBinary&&(Y=i.wasmBinary);var re=i.noExitRuntime||!0;typeof WebAssembly!="object"&&Ai("no native wasm support detected");var ee,ie,me=!1,ae;function fe(N,F){N||Ai("Assertion failed: "+F)}function he(N){var F=i["_"+N];return fe(F,"Cannot call unknown function "+N+", make sure it is exported"),F}function xe(N,F,V,K,be){var ge={string:function(Zr){var Mc=0;if(Zr!=null&&Zr!==0){var OS=(Zr.length<<2)+1;Mc=Fc(OS),Xe(Zr,Mc,OS)}return Mc},array:function(Zr){var Mc=Fc(Zr.length);return Et(Zr,Mc),Mc}};function ye(Zr){return F==="string"?Ce(Zr):F==="boolean"?Boolean(Zr):Zr}var Ee=he(N),kt=[],Ir=0;if(K)for(var br=0;br<K.length;br++){var il=ge[V[br]];il?(Ir===0&&(Ir=Um()),kt[br]=il(K[br])):kt[br]=K[br]}var Pc=Ee.apply(null,kt);return Pc=ye(Pc),Ir!==0&&Rc(Ir),Pc}function _e(N,F,V,K){V=V||[];var be=V.every(function(ye){return ye==="number"}),ge=F!=="string";return ge&&be&&!K?he(N):function(){return xe(N,F,V,arguments,K)}}function $e(N,F,V){for(var K=F+V,be="";!(F>=K);){var ge=N[F++];if(!ge)return be;if(!(ge&128)){be+=String.fromCharCode(ge);continue}var ye=N[F++]&63;if((ge&224)==192){be+=String.fromCharCode((ge&31)<<6|ye);continue}var Ee=N[F++]&63;if((ge&240)==224?ge=(ge&15)<<12|ye<<6|Ee:ge=(ge&7)<<18|ye<<12|Ee<<6|N[F++]&63,ge<65536)be+=String.fromCharCode(ge);else{var kt=ge-65536;be+=String.fromCharCode(55296|kt>>10,56320|kt&1023)}}return be}function Ce(N,F){return N?$e(n(),N,F):""}function We(N,F,V,K){if(!(K>0))return 0;for(var be=V,ge=V+K-1,ye=0;ye<N.length;++ye){var Ee=N.charCodeAt(ye);if(Ee>=55296&&Ee<=57343){var kt=N.charCodeAt(++ye);Ee=65536+((Ee&1023)<<10)|kt&1023}if(Ee<=127){if(V>=ge)break;F[V++]=Ee}else if(Ee<=2047){if(V+1>=ge)break;F[V++]=192|Ee>>6,F[V++]=128|Ee&63}else if(Ee<=65535){if(V+2>=ge)break;F[V++]=224|Ee>>12,F[V++]=128|Ee>>6&63,F[V++]=128|Ee&63}else{if(V+3>=ge)break;F[V++]=240|Ee>>18,F[V++]=128|Ee>>12&63,F[V++]=128|Ee>>6&63,F[V++]=128|Ee&63}}return F[V]=0,V-be}function Xe(N,F,V){return We(N,n(),F,V)}function lt(N){for(var F=0,V=0;V<N.length;++V){var K=N.charCodeAt(V);K>=55296&&K<=57343&&(K=65536+((K&1023)<<10)|N.charCodeAt(++V)&1023),K<=127?++F:K<=2047?F+=2:K<=65535?F+=3:F+=4}return F}function Et(N,F){t().set(N,F)}function At(N,F){return N%F>0&&(N+=F-N%F),N}var He,pt,ft,Vt,En,tr,gn,Gr,Qn;function cr(N){He=N,i.HEAP8=pt=new Int8Array(N),i.HEAP16=Vt=new Int16Array(N),i.HEAP32=tr=new Int32Array(N),i.HEAPU8=ft=new Uint8Array(N),i.HEAPU16=En=new Uint16Array(N),i.HEAPU32=gn=new Uint32Array(N),i.HEAPF32=Gr=new Float32Array(N),i.HEAPF64=Qn=new Float64Array(N)}var An=i.INITIAL_MEMORY||16777216;if(w)ee=i.wasmMemory,He=i.buffer;else if(i.wasmMemory)ee=i.wasmMemory;else if(ee=new WebAssembly.Memory({initial:An/65536,maximum:2147483648/65536,shared:!0}),!(ee.buffer instanceof SharedArrayBuffer))throw q("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"),x&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");ee&&(He=ee.buffer),An=He.byteLength,cr(He);var Yr,Cr=[],xn=[],Gn=[],Jl=[],tl=[],Ks=!1,Ti=!1;w||xn.push({func:function(){yg()}});function Pm(){if(!w){if(i.preRun)for(typeof i.preRun=="function"&&(i.preRun=[i.preRun]);i.preRun.length;)sg(i.preRun.shift());Ec(Cr)}}function Ql(){Ks=!0,!w&&Ec(xn)}function fb(){w||Ec(Gn)}function og(){w||(Ti=!0)}function yn(){if(!w){if(i.postRun)for(typeof i.postRun=="function"&&(i.postRun=[i.postRun]);i.postRun.length;)db(i.postRun.shift());Ec(tl)}}function sg(N){Cr.unshift(N)}function db(N){tl.unshift(N)}var Ei=0,rl=null,eu=null;function hb(N){fe(!w,"addRunDependency cannot be used in a pthread worker"),Ei++,i.monitorRunDependencies&&i.monitorRunDependencies(Ei)}function gb(N){if(Ei--,i.monitorRunDependencies&&i.monitorRunDependencies(Ei),Ei==0&&(rl!==null&&(clearInterval(rl),rl=null),eu)){var F=eu;eu=null,F()}}i.preloadedImages={},i.preloadedAudios={};function Ai(N){i.onAbort&&i.onAbort(N),w&&console.error("Pthread aborting at "+new Error().stack),N+="",q(N),me=!0,ae=1,N="abort("+N+"). Build with -s ASSERTIONS=1 for more info.";var F=new WebAssembly.RuntimeError(N);throw u(F),F}function ig(N,F){return String.prototype.startsWith?N.startsWith(F):N.indexOf(F)===0}var Tc="data:application/octet-stream;base64,";function ag(N){return ig(N,Tc)}var xb="file://";function lg(N){return ig(N,xb)}var bn="tfjs-backend-wasm-threaded-simd.wasm";ag(bn)||(bn=C(bn));function ug(N){try{if(N==bn&&Y)return new Uint8Array(Y);if($)return $(N);throw"both async and sync fetching of the wasm failed"}catch(F){Ai(F)}}function yb(){if(!Y&&(h||g)){if(typeof fetch=="function"&&!lg(bn))return fetch(bn,{credentials:"same-origin"}).then(function(N){if(!N.ok)throw"failed to load wasm binary file at '"+bn+"'";return N.arrayBuffer()}).catch(function(){return ug(bn)});if(D)return new Promise(function(N,F){D(bn,function(V){N(new Uint8Array(V))},F)})}return Promise.resolve().then(function(){return ug(bn)})}function bb(){var N={a:uw};function F(ye,Ee){var kt=ye.exports;if(i.asm=kt,Yr=i.asm.F,ie=Ee,!w){var Ir=Ae.unusedWorkers.length;Ae.unusedWorkers.forEach(function(br){Ae.loadWasmModuleToWorker(br,function(){--Ir||gb("wasm-instantiate")})})}}w||hb("wasm-instantiate");function V(ye){F(ye.instance,ye.module)}function K(ye){return yb().then(function(Ee){return WebAssembly.instantiate(Ee,N)}).then(ye,function(Ee){q("failed to asynchronously prepare wasm: "+Ee),Ai(Ee)})}function be(){return!Y&&typeof WebAssembly.instantiateStreaming=="function"&&!ag(bn)&&!lg(bn)&&typeof fetch=="function"?fetch(bn,{credentials:"same-origin"}).then(function(ye){var Ee=WebAssembly.instantiateStreaming(ye,N);return Ee.then(V,function(kt){return q("wasm streaming compile failed: "+kt),q("falling back to ArrayBuffer instantiation"),K(V)})}):K(V)}if(i.instantiateWasm)try{var ge=i.instantiateWasm(N,F);return ge}catch(ye){return q("Module.instantiateWasm callback failed with error: "+ye),!1}return be().catch(u),{}}var wb={9816:function(){throw"Canceled!"},9834:function(N,F){setTimeout(function(){ES(N,F)},0)}};function cg(){Ae.initRuntime()}function Ec(N){for(;N.length>0;){var F=N.shift();if(typeof F=="function"){F(i);continue}var V=F.func;typeof V=="number"?F.arg===void 0?Yr.get(V)():Yr.get(V)(F.arg):V(F.arg===void 0?null:F.arg)}}function Mm(N,F){if(N<=0||N>t().length||N&!0||F<0)return-28;if(F==0)return 0;F>=2147483647&&(F=Infinity);var V=Atomics.load(o(),Oc>>2),K=0;if(V==N){var be=Atomics.compareExchange(o(),Oc>>2,V,0);if(be==V&&(--F,K=1,F<=0))return 1}var ge=Atomics.notify(o(),N>>2,F);if(ge>=0)return ge+K;throw"Atomics.notify returned an unexpected value "+ge}i._emscripten_futex_wake=Mm;function _b(N){if(w)throw"Internal Error! killThread() can only ever be called from main application thread!";if(!N)throw"Internal Error! Null pthread_ptr in killThread!";o()[N+12>>2]=0;var F=Ae.pthreads[N];F.worker.terminate(),Ae.freeThreadData(F),Ae.runningWorkers.splice(Ae.runningWorkers.indexOf(F.worker),1),F.worker.pthread=void 0}function kb(N){if(w)throw"Internal Error! cancelThread() can only ever be called from main application thread!";if(!N)throw"Internal Error! Null pthread_ptr in cancelThread!";var F=Ae.pthreads[N];F.worker.postMessage({cmd:"cancel"})}function vb(N){if(w)throw"Internal Error! cleanupThread() can only ever be called from main application thread!";if(!N)throw"Internal Error! Null pthread_ptr in cleanupThread!";var F=Ae.pthreads[N];if(F){o()[N+12>>2]=0;var V=F.worker;Ae.returnWorkerToPool(V)}}var Ae={unusedWorkers:[],runningWorkers:[],initMainThreadBlock:function(){for(var N=Math.min(4,Math.max(1,(navigator.hardwareConcurrency||1)/2)),F=0;F<N;++F)Ae.allocateUnusedWorker()},initRuntime:function(){for(var N=ru(228),F=0;F<228/4;++F)s()[N/4+F]=0;o()[N+12>>2]=N;var V=N+152;o()[V>>2]=V;for(var K=ru(512),F=0;F<128;++F)s()[K/4+F]=0;Atomics.store(s(),N+100>>2,K),Atomics.store(s(),N+40>>2,N),Fw(N,!g,1),TS(N)},initWorker:function(){},pthreads:{},threadExitHandlers:[],setThreadStatus:function(){},runExitHandlers:function(){for(;Ae.threadExitHandlers.length>0;)Ae.threadExitHandlers.pop()();w&&$c()&&NS()},runExitHandlersAndDeinitThread:function(N,F){Atomics.store(s(),N+56>>2,1),Atomics.store(s(),N+60>>2,0),Ae.runExitHandlers(),Atomics.store(s(),N+4>>2,F),Atomics.store(s(),N+0>>2,1),Mm(N+0,2147483647),Fw(0,0,0)},threadExit:function(N){var F=$c();F&&(Ae.runExitHandlersAndDeinitThread(F,N),w&&postMessage({cmd:"exit"}))},threadCancel:function(){Ae.runExitHandlersAndDeinitThread($c(),-1),postMessage({cmd:"cancelDone"})},terminateAllThreads:function(){for(var N in Ae.pthreads){var F=Ae.pthreads[N];F&&F.worker&&Ae.returnWorkerToPool(F.worker)}Ae.pthreads={};for(var V=0;V<Ae.unusedWorkers.length;++V){var K=Ae.unusedWorkers[V];K.terminate()}Ae.unusedWorkers=[];for(var V=0;V<Ae.runningWorkers.length;++V){var K=Ae.runningWorkers[V],F=K.pthread;Ae.freeThreadData(F),K.terminate()}Ae.runningWorkers=[]},freeThreadData:function(N){if(!!N){if(N.threadInfoStruct){var F=o()[N.threadInfoStruct+100>>2];o()[N.threadInfoStruct+100>>2]=0,jm(F),jm(N.threadInfoStruct)}N.threadInfoStruct=0,N.allocatedOwnStack&&N.stackBase&&jm(N.stackBase),N.stackBase=0,N.worker&&(N.worker.pthread=null)}},returnWorkerToPool:function(N){Ae.runWithoutMainThreadQueuedCalls(function(){delete Ae.pthreads[N.pthread.threadInfoStruct],Ae.unusedWorkers.push(N),Ae.runningWorkers.splice(Ae.runningWorkers.indexOf(N),1),Ae.freeThreadData(N.pthread),N.pthread=void 0})},runWithoutMainThreadQueuedCalls:function(N){o()[FS>>2]=0;try{N()}finally{o()[FS>>2]=1}},receiveObjectTransfer:function(N){},loadWasmModuleToWorker:function(N,F){N.onmessage=function(V){var K=V.data,be=K.cmd;if(N.pthread&&(Ae.currentProxiedOperationCallerThread=N.pthread.threadInfoStruct),K.targetThread&&K.targetThread!=$c()){var ge=Ae.pthreads[K.targetThread];ge?ge.worker.postMessage(V.data,K.transferList):console.error('Internal error! Worker sent a message "'+be+'" to target pthread '+K.targetThread+", but that thread no longer exists!"),Ae.currentProxiedOperationCallerThread=void 0;return}if(be==="processQueuedMainThreadWork")$w();else if(be==="spawnThread")gg(V.data);else if(be==="cleanupThread")vb(K.thread);else if(be==="killThread")_b(K.thread);else if(be==="cancelThread")kb(K.thread);else if(be==="loaded")N.loaded=!0,F&&F(N),N.runPthread&&(N.runPthread(),delete N.runPthread);else if(be==="print")U("Thread "+K.threadId+": "+K.text);else if(be==="printErr")q("Thread "+K.threadId+": "+K.text);else if(be==="alert")alert("Thread "+K.threadId+": "+K.text);else if(be==="exit"){var ye=N.pthread&&Atomics.load(s(),N.pthread.threadInfoStruct+64>>2);ye&&Ae.returnWorkerToPool(N)}else if(be==="exitProcess")try{XW(K.returnCode)}catch(Ee){if(Ee instanceof qm)return;throw Ee}else be==="cancelDone"?Ae.returnWorkerToPool(N):be==="objectTransfer"?Ae.receiveObjectTransfer(V.data):V.data.target==="setimmediate"?N.postMessage(V.data):q("worker sent an unknown command "+be);Ae.currentProxiedOperationCallerThread=void 0},N.onerror=function(V){q("pthread sent an error! "+V.filename+":"+V.lineno+": "+V.message)},x&&(N.on("message",function(V){N.onmessage({data:V})}),N.on("error",function(V){N.onerror(V)}),N.on("exit",function(V){})),N.postMessage({cmd:"load",urlOrBlob:i.mainScriptUrlOrBlob||r,wasmMemory:ee,wasmModule:ie})},allocateUnusedWorker:function(){var N=C("tfjs-backend-wasm-threaded-simd.worker.js");Ae.unusedWorkers.push(new Worker(N))},getNewWorker:function(){return Ae.unusedWorkers.length==0&&(Ae.allocateUnusedWorker(),Ae.loadWasmModuleToWorker(Ae.unusedWorkers[0])),Ae.unusedWorkers.length>0?Ae.unusedWorkers.pop():null},busySpinWait:function(N){for(var F=performance.now()+N;performance.now()<F;);}};function Cb(N,F){$S(N,F),Rc(N)}i.establishStackSpace=Cb;function Ib(){return re}i.getNoExitRuntime=Ib;function Sb(N,F){return Yr.get(N)(F)}i.invokeEntryPoint=Sb;function Nb(N,F,V,K){Ai("Assertion failed: "+Ce(N)+", at: "+[F?Ce(F):"unknown filename",V,K?Ce(K):"unknown function"])}function Tb(N,F){var V=_main(N,F)}var tu;x?tu=function(){var N=process.hrtime();return N[0]*1e3+N[1]/1e6}:w?tu=function(){return performance.now()-i.__performance_now_clock_drift}:typeof dateNow!="undefined"?tu=dateNow:tu=function(){return performance.now()};function Eb(N){return o()[IS()>>2]=N,N}function Ab(N,F){if(w)return nl(1,1,N,F)}function Db(N,F){if(N==F)postMessage({cmd:"processQueuedMainThreadWork"});else if(w)postMessage({targetThread:N,cmd:"processThreadQueue"});else{var V=Ae.pthreads[N],K=V&&V.worker;if(!K)return;K.postMessage({cmd:"processThreadQueue"})}return 1}function $b(){Ai()}function Rb(N,F,V){var K=Lb(F,V);return wb[N].apply(null,K)}function Fb(N,F){}function Ob(N,F,V){if(N<=0||N>t().length||N&!0)return-28;if(h){if(Atomics.load(o(),N>>2)!=F)return-6;for(var be=performance.now(),ge=be+V,ye=Atomics.exchange(o(),Oc>>2,N);;){if(be=performance.now(),be>ge)return ye=Atomics.exchange(o(),Oc>>2,0),-73;if(ye=Atomics.exchange(o(),Oc>>2,0),ye==0)break;if($w(),Atomics.load(o(),N>>2)!=F)return-6;ye=Atomics.exchange(o(),Oc>>2,N)}return 0}else{var K=Atomics.wait(o(),N>>2,F,V);if(K==="timed-out")return-73;if(K==="not-equal")return-6;if(K==="ok")return 0;throw"Atomics.wait returned an unexpected value "+K}}function Pb(N,F,V){n().copyWithin(N,F,F+V)}function Mb(){return x?Lc("os").cpus().length:navigator.hardwareConcurrency}function nl(N,F){for(var V=arguments.length-2,K=Um(),be=V,ge=Fc(be*8),ye=ge>>3,Ee=0;Ee<V;Ee++){var kt=arguments[2+Ee];a()[ye+Ee]=kt}var Ir=DS(N,be,ge,F);return Rc(K),Ir}var Lm=[],zm=[];function Lb(N,F){zm.length=0;var V;for(F>>=2;V=n()[N++];){var K=V<105;K&&F&1&&F++,zm.push(K?a()[F++>>1]:o()[F]),++F}return zm}function zb(N,F,V){Lm.length=F;for(var K=V>>3,be=0;be<F;be++)Lm[be]=a()[K+be];var ge=N<0,ye=ge?wb[-N-1]:lw[N];return ye.apply(null,Lm)}function Bb(){return n().length}function Vb(N){try{return ee.grow(N-He.byteLength+65535>>>16),cr(ee.buffer),1}catch(F){}}function Gb(N){var F=Bb();if(N<=F)return!1;var V=2147483648;if(N>V)return!1;for(var K=1;K<=4;K*=2){var be=F*(1+.2/K);be=Math.min(be,N+100663296);var ge=Math.min(V,At(Math.max(N,be),65536)),ye=Vb(ge);if(ye)return!0}return!1}var Qe={inEventHandler:0,removeAllEventListeners:function(){for(var N=Qe.eventHandlers.length-1;N>=0;--N)Qe._removeHandler(N);Qe.eventHandlers=[],Qe.deferredCalls=[]},registerRemoveEventListeners:function(){Qe.removeEventListenersRegistered||(Jl.push(Qe.removeAllEventListeners),Qe.removeEventListenersRegistered=!0)},deferredCalls:[],deferCall:function(N,F,V){function K(ye,Ee){if(ye.length!=Ee.length)return!1;for(var kt in ye)if(ye[kt]!=Ee[kt])return!1;return!0}for(var be in Qe.deferredCalls){var ge=Qe.deferredCalls[be];if(ge.targetFunction==N&&K(ge.argsList,V))return}Qe.deferredCalls.push({targetFunction:N,precedence:F,argsList:V}),Qe.deferredCalls.sort(function(ye,Ee){return ye.precedence<Ee.precedence})},removeDeferredCalls:function(N){for(var F=0;F<Qe.deferredCalls.length;++F)Qe.deferredCalls[F].targetFunction==N&&(Qe.deferredCalls.splice(F,1),--F)},canPerformEventHandlerRequests:function(){return Qe.inEventHandler&&Qe.currentEventHandler.allowsDeferredCalls},runDeferredCalls:function(){if(!!Qe.canPerformEventHandlerRequests())for(var N=0;N<Qe.deferredCalls.length;++N){var F=Qe.deferredCalls[N];Qe.deferredCalls.splice(N,1),--N,F.targetFunction.apply(null,F.argsList)}},eventHandlers:[],removeAllHandlersOnTarget:function(N,F){for(var V=0;V<Qe.eventHandlers.length;++V)Qe.eventHandlers[V].target==N&&(!F||F==Qe.eventHandlers[V].eventTypeString)&&Qe._removeHandler(V--)},_removeHandler:function(N){var F=Qe.eventHandlers[N];F.target.removeEventListener(F.eventTypeString,F.eventListenerFunc,F.useCapture),Qe.eventHandlers.splice(N,1)},registerOrRemoveHandler:function(N){var F=function(be){++Qe.inEventHandler,Qe.currentEventHandler=N,Qe.runDeferredCalls(),N.handlerFunc(be),Qe.runDeferredCalls(),--Qe.inEventHandler};if(N.callbackfunc)N.eventListenerFunc=F,N.target.addEventListener(N.eventTypeString,F,N.useCapture),Qe.eventHandlers.push(N),Qe.registerRemoveEventListeners();else for(var V=0;V<Qe.eventHandlers.length;++V)Qe.eventHandlers[V].target==N.target&&Qe.eventHandlers[V].eventTypeString==N.eventTypeString&&Qe._removeHandler(V--)},queueEventHandlerOnThread_iiii:function(N,F,V,K,be){var ge=Um(),ye=Fc(12);o()[ye>>2]=V,o()[ye+4>>2]=K,o()[ye+8>>2]=be,Rw(0,N,637534208,F,K,ye),Rc(ge)},getTargetThreadForEventCallback:function(N){switch(N){case 1:return 0;case 2:return Ae.currentProxiedOperationCallerThread;default:return N}},getNodeNameForTarget:function(N){return N?N==window?"#window":N==screen?"#screen":N&&N.nodeName?N.nodeName:"":""},fullscreenEnabled:function(){return document.fullscreenEnabled||document.webkitFullscreenEnabled}};function Wb(N){var F=lt(N)+1,V=ru(F);return Xe(N,V,F),V}function jb(N,F,V,K){var be=Um(),ge=Fc(12),ye=0;F&&(ye=Wb(F)),o()[ge>>2]=ye,o()[ge+4>>2]=V,o()[ge+8>>2]=K,Rw(0,N,657457152,0,ye,ge),Rc(be)}function Ub(N,F,V,K){F=F?Ce(F):"",jb(N,F,V,K)}function qb(N){return N>2?Ce(N):N}var Hb=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];function Kb(N){N=qb(N);var F=Hb[N]||(typeof document!="undefined"?document.querySelector(N):void 0);return F}function Bm(N){return Kb(N)}function pg(N,F,V){var K=Bm(N);if(!K)return-4;if(K.canvasSharedPtr&&(o()[K.canvasSharedPtr>>2]=F,o()[K.canvasSharedPtr+4>>2]=V),K.offscreenCanvas||!K.controlTransferredOffscreen){K.offscreenCanvas&&(K=K.offscreenCanvas);var be=!1;if(K.GLctxObject&&K.GLctxObject.GLctx){var ge=K.GLctxObject.GLctx.getParameter(2978);be=ge[0]===0&&ge[1]===0&&ge[2]===K.width&&ge[3]===K.height}K.width=F,K.height=V,be&&K.GLctxObject.GLctx.viewport(0,0,F,V)}else if(K.canvasSharedPtr){var ye=o()[K.canvasSharedPtr+8>>2];return Ub(ye,N,F,V),1}else return-4;return 0}function mg(N,F,V){return w?nl(2,1,N,F,V):pg(N,F,V)}function Xb(N,F,V){var K=Bm(N);return K?pg(N,F,V):mg(N,F,V)}function Yb(N){}function Zb(N,F){}function Jb(N){var F=N.getExtension("ANGLE_instanced_arrays");if(F)return N.vertexAttribDivisor=function(V,K){F.vertexAttribDivisorANGLE(V,K)},N.drawArraysInstanced=function(V,K,be,ge){F.drawArraysInstancedANGLE(V,K,be,ge)},N.drawElementsInstanced=function(V,K,be,ge,ye){F.drawElementsInstancedANGLE(V,K,be,ge,ye)},1}function Qb(N){var F=N.getExtension("OES_vertex_array_object");if(F)return N.createVertexArray=function(){return F.createVertexArrayOES()},N.deleteVertexArray=function(V){F.deleteVertexArrayOES(V)},N.bindVertexArray=function(V){F.bindVertexArrayOES(V)},N.isVertexArray=function(V){return F.isVertexArrayOES(V)},1}function ew(N){var F=N.getExtension("WEBGL_draw_buffers");if(F)return N.drawBuffers=function(V,K){F.drawBuffersWEBGL(V,K)},1}function tw(N){return!!(N.multiDrawWebgl=N.getExtension("WEBGL_multi_draw"))}var dt={counter:1,buffers:[],programs:[],framebuffers:[],renderbuffers:[],textures:[],uniforms:[],shaders:[],vaos:[],contexts:{},offscreenCanvases:{},timerQueriesEXT:[],programInfos:{},stringCache:{},unpackAlignment:4,recordError:function(F){dt.lastError||(dt.lastError=F)},getNewId:function(N){for(var F=dt.counter++,V=N.length;V<F;V++)N[V]=null;return F},getSource:function(N,F,V,K){for(var be="",ge=0;ge<F;++ge){var ye=K?o()[K+ge*4>>2]:-1;be+=Ce(o()[V+ge*4>>2],ye<0?void 0:ye)}return be},createContext:function(N,F){var V=N.getContext("webgl",F);if(!V)return 0;var K=dt.registerContext(V,F);return K},registerContext:function(N,F){var V=ru(8);o()[V+4>>2]=$c();var K={handle:V,attributes:F,version:F.majorVersion,GLctx:N};return N.canvas&&(N.canvas.GLctxObject=K),dt.contexts[V]=K,(typeof F.enableExtensionsByDefault=="undefined"||F.enableExtensionsByDefault)&&dt.initExtensions(K),V},makeContextCurrent:function(N){return dt.currentContext=dt.contexts[N],i.ctx=ol=dt.currentContext&&dt.currentContext.GLctx,!(N&&!ol)},getContext:function(N){return dt.contexts[N]},deleteContext:function(N){dt.currentContext===dt.contexts[N]&&(dt.currentContext=null),typeof Qe=="object"&&Qe.removeAllHandlersOnTarget(dt.contexts[N].GLctx.canvas),dt.contexts[N]&&dt.contexts[N].GLctx.canvas&&(dt.contexts[N].GLctx.canvas.GLctxObject=void 0),jm(dt.contexts[N].handle),dt.contexts[N]=null},initExtensions:function(N){if(N||(N=dt.currentContext),!N.initExtensionsDone){N.initExtensionsDone=!0;var F=N.GLctx;Jb(F),Qb(F),ew(F),F.disjointTimerQueryExt=F.getExtension("EXT_disjoint_timer_query"),tw(F);var V=F.getSupportedExtensions()||[];V.forEach(function(K){K.indexOf("lose_context")<0&&K.indexOf("debug")<0&&F.getExtension(K)})}},populateUniformTable:function(N){for(var F=dt.programs[N],V=dt.programInfos[N]={uniforms:{},maxUniformLength:0,maxAttributeLength:-1,maxUniformBlockNameLength:-1},K=V.uniforms,be=ol.getProgramParameter(F,35718),ge=0;ge<be;++ge){var ye=ol.getActiveUniform(F,ge),Ee=ye.name;V.maxUniformLength=Math.max(V.maxUniformLength,Ee.length+1),Ee.slice(-1)=="]"&&(Ee=Ee.slice(0,Ee.lastIndexOf("[")));var kt=ol.getUniformLocation(F,Ee);if(kt){var Ir=dt.getNewId(dt.uniforms);K[Ee]=[ye.size,Ir],dt.uniforms[Ir]=kt;for(var br=1;br<ye.size;++br){var il=Ee+"["+br+"]";kt=ol.getUniformLocation(F,il),Ir=dt.getNewId(dt.uniforms),dt.uniforms[Ir]=kt}}}}},rw=["default","low-power","high-performance"];function nw(N,F){var V=F>>2,K=o()[V+(24>>2)],be={alpha:!!o()[V+(0>>2)],depth:!!o()[V+(4>>2)],stencil:!!o()[V+(8>>2)],antialias:!!o()[V+(12>>2)],premultipliedAlpha:!!o()[V+(16>>2)],preserveDrawingBuffer:!!o()[V+(20>>2)],powerPreference:rw[K],failIfMajorPerformanceCaveat:!!o()[V+(28>>2)],majorVersion:o()[V+(32>>2)],minorVersion:o()[V+(36>>2)],enableExtensionsByDefault:o()[V+(40>>2)],explicitSwapControl:o()[V+(44>>2)],proxyContextToMainThread:o()[V+(48>>2)],renderViaOffscreenBackBuffer:o()[V+(52>>2)]},ge=Bm(N);if(!ge||be.explicitSwapControl)return 0;var ye=dt.createContext(ge,be);return ye}function ow(N,F){return nw(N,F)}var Ac={mappings:{},buffers:[null,[],[]],printChar:function(N,F){var V=Ac.buffers[N];F===0||F===10?((N===1?U:q)($e(V,0)),V.length=0):V.push(F)},varargs:void 0,get:function(){Ac.varargs+=4;var N=o()[Ac.varargs-4>>2];return N},getStr:function(N){var F=Ce(N);return F},get64:function(N,F){return N}};function fg(N){return w?nl(3,1,N):0}function dg(N,F,V,K,be){if(w)return nl(4,1,N,F,V,K,be)}function hg(N,F,V,K){if(w)return nl(5,1,N,F,V,K);for(var be=0,ge=0;ge<V;ge++){for(var ye=o()[F+ge*8>>2],Ee=o()[F+(ge*8+4)>>2],kt=0;kt<Ee;kt++)Ac.printChar(N,n()[ye+kt]);be+=Ee}return o()[K>>2]=be,0}function sw(N){var F=Ae.threadExitHandlers.pop();N&&F()}function iw(N,F){Ae.threadExitHandlers.push(function(){Yr.get(N)(F)})}function gg(N){if(w)throw"Internal Error! spawnThread() can only ever be called from main application thread!";var F=Ae.getNewWorker();if(F.pthread!==void 0)throw"Internal error!";if(!N.pthread_ptr)throw"Internal error, no pthread ptr!";Ae.runningWorkers.push(F);for(var V=ru(128*4),K=0;K<128;++K)o()[V+K*4>>2]=0;var be=N.stackBase+N.stackSize,ge=Ae.pthreads[N.pthread_ptr]={worker:F,stackBase:N.stackBase,stackSize:N.stackSize,allocatedOwnStack:N.allocatedOwnStack,threadInfoStruct:N.pthread_ptr},ye=ge.threadInfoStruct>>2;Atomics.store(s(),ye+(64>>2),N.detached),Atomics.store(s(),ye+(100>>2),V),Atomics.store(s(),ye+(40>>2),ge.threadInfoStruct),Atomics.store(s(),ye+(80>>2),N.stackSize),Atomics.store(s(),ye+(76>>2),be),Atomics.store(s(),ye+(104>>2),N.stackSize),Atomics.store(s(),ye+(104+8>>2),be),Atomics.store(s(),ye+(104+12>>2),N.detached);var Ee=SS(),kt=Ee+40;Atomics.store(s(),ye+(172>>2),kt),F.pthread=ge;var Ir={cmd:"run",start_routine:N.startRoutine,arg:N.arg,threadInfoStruct:N.pthread_ptr,stackBase:N.stackBase,stackSize:N.stackSize};F.runPthread=function(){Ir.time=performance.now(),F.postMessage(Ir,N.transferList)},F.loaded&&(F.runPthread(),delete F.runPthread)}function aw(N,F,V,K){if(typeof SharedArrayBuffer=="undefined")return q("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;if(!N)return q("pthread_create called with a null thread pointer!"),28;var be=[],ge=0;if(w&&(be.length===0||ge))return AS(687865856,N,F,V,K);if(ge)return ge;var ye=0,Ee=0,kt=0;F&&F!=-1?(ye=o()[F>>2],ye+=81920,Ee=o()[F+8>>2],kt=o()[F+12>>2]!==0):ye=2097152;var Ir=Ee==0;Ir?Ee=RS(16,ye):(Ee-=ye,fe(Ee>0));for(var br=ru(228),il=0;il<228>>2;++il)s()[(br>>2)+il]=0;o()[N>>2]=br,o()[br+12>>2]=br;var Pc=br+152;o()[Pc>>2]=Pc;var Zr={stackBase:Ee,stackSize:ye,allocatedOwnStack:Ir,detached:kt,startRoutine:V,pthread_ptr:br,arg:K,transferList:be};return w?(Zr.cmd="spawnThread",postMessage(Zr,be)):gg(Zr),0}function xg(N){if(w)return nl(6,1,N);switch(N){case 30:return 16384;case 85:var F=2147483648;return F/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 Eb(28),-1}w||Ae.initMainThreadBlock();var ol,lw=[null,Ab,mg,fg,dg,hg,xg],uw={e:Nb,r:Tb,x:Db,b:$b,y:Rb,j:Fb,c:Ob,d:Mm,f:tu,p:Pb,z:Mb,u:zb,q:Gb,v:Xb,i:Yb,t:Zb,w:ow,m:fg,n:dg,g:hg,o:cg,a:ee||i.wasmMemory,k:sw,l:iw,h:aw,s:xg},CS=bb(),yg=i.___wasm_call_ctors=function(){return(yg=i.___wasm_call_ctors=i.asm.A).apply(null,arguments)},cw=i._init=function(){return(cw=i._init=i.asm.B).apply(null,arguments)},pw=i._register_tensor=function(){return(pw=i._register_tensor=i.asm.C).apply(null,arguments)},mw=i._dispose_data=function(){return(mw=i._dispose_data=i.asm.D).apply(null,arguments)},fw=i._dispose=function(){return(fw=i._dispose=i.asm.E).apply(null,arguments)},dw=i._Abs=function(){return(dw=i._Abs=i.asm.G).apply(null,arguments)},hw=i._Add=function(){return(hw=i._Add=i.asm.H).apply(null,arguments)},gw=i._AddN=function(){return(gw=i._AddN=i.asm.I).apply(null,arguments)},xw=i._All=function(){return(xw=i._All=i.asm.J).apply(null,arguments)},yw=i._Any=function(){return(yw=i._Any=i.asm.K).apply(null,arguments)},bw=i._ArgMax=function(){return(bw=i._ArgMax=i.asm.L).apply(null,arguments)},ww=i._AvgPool=function(){return(ww=i._AvgPool=i.asm.M).apply(null,arguments)},_w=i._BatchMatMul=function(){return(_w=i._BatchMatMul=i.asm.N).apply(null,arguments)},kw=i._Ceil=function(){return(kw=i._Ceil=i.asm.O).apply(null,arguments)},vw=i._ClipByValue=function(){return(vw=i._ClipByValue=i.asm.P).apply(null,arguments)},Cw=i._Conv2D=function(){return(Cw=i._Conv2D=i.asm.Q).apply(null,arguments)},Iw=i._Conv2DBackpropInput=function(){return(Iw=i._Conv2DBackpropInput=i.asm.R).apply(null,arguments)},Sw=i._Cos=function(){return(Sw=i._Cos=i.asm.S).apply(null,arguments)},Nw=i._CropAndResize=function(){return(Nw=i._CropAndResize=i.asm.T).apply(null,arguments)},Tw=i._Cumsum=function(){return(Tw=i._Cumsum=i.asm.U).apply(null,arguments)},Ew=i._DepthToSpace=function(){return(Ew=i._DepthToSpace=i.asm.V).apply(null,arguments)},Aw=i._DepthwiseConv2dNative=function(){return(Aw=i._DepthwiseConv2dNative=i.asm.W).apply(null,arguments)},bg=i._Equal=function(){return(bg=i._Equal=i.asm.X).apply(null,arguments)},wg=i._Exp=function(){return(wg=i._Exp=i.asm.Y).apply(null,arguments)},_g=i._FlipLeftRight=function(){return(_g=i._FlipLeftRight=i.asm.Z).apply(null,arguments)},Vm=i._Floor=function(){return(Vm=i._Floor=i.asm._).apply(null,arguments)},Dc=i._FloorDiv=function(){return(Dc=i._FloorDiv=i.asm.$).apply(null,arguments)},Dw=i._FusedBatchNorm=function(){return(Dw=i._FusedBatchNorm=i.asm.aa).apply(null,arguments)},Gm=i._FusedConv2D=function(){return(Gm=i._FusedConv2D=i.asm.ba).apply(null,arguments)},Z=i._FusedDepthwiseConv2D=function(){return(Z=i._FusedDepthwiseConv2D=i.asm.ca).apply(null,arguments)},se=i._Gather=function(){return(se=i._Gather=i.asm.da).apply(null,arguments)},ve=i._GatherNd=function(){return(ve=i._GatherNd=i.asm.ea).apply(null,arguments)},ut=i._Greater=function(){return(ut=i._Greater=i.asm.fa).apply(null,arguments)},rr=i._GreaterEqual=function(){return(rr=i._GreaterEqual=i.asm.ga).apply(null,arguments)},jt=i._LeakyRelu=function(){return(jt=i._LeakyRelu=i.asm.ha).apply(null,arguments)},rt=i._Less=function(){return(rt=i._Less=i.asm.ia).apply(null,arguments)},nt=i._LessEqual=function(){return(nt=i._LessEqual=i.asm.ja).apply(null,arguments)},Dr=i._Log=function(){return(Dr=i._Log=i.asm.ka).apply(null,arguments)},Di=i._LogicalAnd=function(){return(Di=i._LogicalAnd=i.asm.la).apply(null,arguments)},$i=i._Max=function(){return($i=i._Max=i.asm.ma).apply(null,arguments)},kg=i._MaxPool=function(){return(kg=i._MaxPool=i.asm.na).apply(null,arguments)},Wm=i._Maximum=function(){return(Wm=i._Maximum=i.asm.oa).apply(null,arguments)},Dn=i._Mean=function(){return(Dn=i._Mean=i.asm.pa).apply(null,arguments)},sl=i._Min=function(){return(sl=i._Min=i.asm.qa).apply(null,arguments)},vg=i._Minimum=function(){return(vg=i._Minimum=i.asm.ra).apply(null,arguments)},lW=i._MirrorPad=function(){return(lW=i._MirrorPad=i.asm.sa).apply(null,arguments)},uW=i._Multiply=function(){return(uW=i._Multiply=i.asm.ta).apply(null,arguments)},cW=i._Neg=function(){return(cW=i._Neg=i.asm.ua).apply(null,arguments)},pW=i._NonMaxSuppressionV3=function(){return(pW=i._NonMaxSuppressionV3=i.asm.va).apply(null,arguments)},mW=i._NonMaxSuppressionV4=function(){return(mW=i._NonMaxSuppressionV4=i.asm.wa).apply(null,arguments)},fW=i._NonMaxSuppressionV5=function(){return(fW=i._NonMaxSuppressionV5=i.asm.xa).apply(null,arguments)},dW=i._NotEqual=function(){return(dW=i._NotEqual=i.asm.ya).apply(null,arguments)},hW=i._OneHot=function(){return(hW=i._OneHot=i.asm.za).apply(null,arguments)},gW=i._PadV2=function(){return(gW=i._PadV2=i.asm.Aa).apply(null,arguments)},xW=i._Pow=function(){return(xW=i._Pow=i.asm.Ba).apply(null,arguments)},yW=i._Prelu=function(){return(yW=i._Prelu=i.asm.Ca).apply(null,arguments)},bW=i._Prod=function(){return(bW=i._Prod=i.asm.Da).apply(null,arguments)},wW=i._RealDiv=function(){return(wW=i._RealDiv=i.asm.Ea).apply(null,arguments)},_W=i._Relu=function(){return(_W=i._Relu=i.asm.Fa).apply(null,arguments)},kW=i._Relu6=function(){return(kW=i._Relu6=i.asm.Ga).apply(null,arguments)},vW=i._ResizeBilinear=function(){return(vW=i._ResizeBilinear=i.asm.Ha).apply(null,arguments)},CW=i._Reverse=function(){return(CW=i._Reverse=i.asm.Ia).apply(null,arguments)},IW=i._RotateWithOffset=function(){return(IW=i._RotateWithOffset=i.asm.Ja).apply(null,arguments)},SW=i._Round=function(){return(SW=i._Round=i.asm.Ka).apply(null,arguments)},NW=i._Rsqrt=function(){return(NW=i._Rsqrt=i.asm.La).apply(null,arguments)},TW=i._ScatterNd=function(){return(TW=i._ScatterNd=i.asm.Ma).apply(null,arguments)},EW=i._SelectV2=function(){return(EW=i._SelectV2=i.asm.Na).apply(null,arguments)},AW=i._Sigmoid=function(){return(AW=i._Sigmoid=i.asm.Oa).apply(null,arguments)},DW=i._Sin=function(){return(DW=i._Sin=i.asm.Pa).apply(null,arguments)},$W=i._Softmax=function(){return($W=i._Softmax=i.asm.Qa).apply(null,arguments)},RW=i._Sqrt=function(){return(RW=i._Sqrt=i.asm.Ra).apply(null,arguments)},FW=i._Square=function(){return(FW=i._Square=i.asm.Sa).apply(null,arguments)},OW=i._SquaredDifference=function(){return(OW=i._SquaredDifference=i.asm.Ta).apply(null,arguments)},PW=i._Step=function(){return(PW=i._Step=i.asm.Ua).apply(null,arguments)},MW=i._StridedSlice=function(){return(MW=i._StridedSlice=i.asm.Va).apply(null,arguments)},LW=i._Sub=function(){return(LW=i._Sub=i.asm.Wa).apply(null,arguments)},zW=i._Sum=function(){return(zW=i._Sum=i.asm.Xa).apply(null,arguments)},BW=i._Tan=function(){return(BW=i._Tan=i.asm.Ya).apply(null,arguments)},VW=i._Tanh=function(){return(VW=i._Tanh=i.asm.Za).apply(null,arguments)},GW=i._Tile=function(){return(GW=i._Tile=i.asm._a).apply(null,arguments)},WW=i._TopK=function(){return(WW=i._TopK=i.asm.$a).apply(null,arguments)},jW=i._Transform=function(){return(jW=i._Transform=i.asm.ab).apply(null,arguments)},UW=i._Transpose=function(){return(UW=i._Transpose=i.asm.bb).apply(null,arguments)},qW=i.__FusedMatMul=function(){return(qW=i.__FusedMatMul=i.asm.cb).apply(null,arguments)},ru=i._malloc=function(){return(ru=i._malloc=i.asm.db).apply(null,arguments)},jm=i._free=function(){return(jm=i._free=i.asm.eb).apply(null,arguments)},IS=i.___errno_location=function(){return(IS=i.___errno_location=i.asm.fb).apply(null,arguments)},SS=i._emscripten_get_global_libc=function(){return(SS=i._emscripten_get_global_libc=i.asm.gb).apply(null,arguments)},$c=i._pthread_self=function(){return($c=i._pthread_self=i.asm.hb).apply(null,arguments)},NS=i.___pthread_tsd_run_dtors=function(){return(NS=i.___pthread_tsd_run_dtors=i.asm.ib).apply(null,arguments)},$w=i._emscripten_main_thread_process_queued_calls=function(){return($w=i._emscripten_main_thread_process_queued_calls=i.asm.jb).apply(null,arguments)},HW=i._emscripten_current_thread_process_queued_calls=function(){return(HW=i._emscripten_current_thread_process_queued_calls=i.asm.kb).apply(null,arguments)},TS=i._emscripten_register_main_browser_thread_id=function(){return(TS=i._emscripten_register_main_browser_thread_id=i.asm.lb).apply(null,arguments)},ES=i.__emscripten_do_dispatch_to_thread=function(){return(ES=i.__emscripten_do_dispatch_to_thread=i.asm.mb).apply(null,arguments)},AS=i._emscripten_sync_run_in_main_thread_4=function(){return(AS=i._emscripten_sync_run_in_main_thread_4=i.asm.nb).apply(null,arguments)},DS=i._emscripten_run_in_main_runtime_thread_js=function(){return(DS=i._emscripten_run_in_main_runtime_thread_js=i.asm.ob).apply(null,arguments)},Rw=i.__emscripten_call_on_thread=function(){return(Rw=i.__emscripten_call_on_thread=i.asm.pb).apply(null,arguments)},KW=i._emscripten_tls_init=function(){return(KW=i._emscripten_tls_init=i.asm.qb).apply(null,arguments)},Fw=i.__emscripten_thread_init=function(){return(Fw=i.__emscripten_thread_init=i.asm.rb).apply(null,arguments)},Um=i.stackSave=function(){return(Um=i.stackSave=i.asm.sb).apply(null,arguments)},Rc=i.stackRestore=function(){return(Rc=i.stackRestore=i.asm.tb).apply(null,arguments)},Fc=i.stackAlloc=function(){return(Fc=i.stackAlloc=i.asm.ub).apply(null,arguments)},$S=i._emscripten_stack_set_limits=function(){return($S=i._emscripten_stack_set_limits=i.asm.vb).apply(null,arguments)},RS=i._memalign=function(){return(RS=i._memalign=i.asm.wb).apply(null,arguments)},FS=i.__emscripten_allow_main_runtime_queued_calls=9808,Oc=i.__emscripten_main_thread_futex=11432;i.cwrap=_e,i.PThread=Ae,i.PThread=Ae,i.wasmMemory=ee,i.ExitStatus=qm;var Cg;function qm(N){this.name="ExitStatus",this.message="Program terminated with exit("+N+")",this.status=N}eu=function N(){Cg||Ow(),Cg||(eu=N)};function Ow(N){if(N=N||m,Ei>0)return;if(w){l(i),Ql(),postMessage({cmd:"loaded"});return}if(Pm(),Ei>0)return;function F(){Cg||(Cg=!0,i.calledRun=!0,!me&&(Ql(),fb(),l(i),i.onRuntimeInitialized&&i.onRuntimeInitialized(),yn()))}i.setStatus?(i.setStatus("Running..."),setTimeout(function(){setTimeout(function(){i.setStatus("")},1),F()},1)):F()}i.run=Ow;function XW(N,F){if(!(F&&re&&N===0)){if(!F&&w)throw postMessage({cmd:"exitProcess",returnCode:N}),new qm(N);re||(Ae.terminateAllThreads(),ae=N,og(),i.onExit&&i.onExit(N),me=!0),d(N,new qm(N))}}if(i.preInit)for(typeof i.preInit=="function"&&(i.preInit=[i.preInit]);i.preInit.length>0;)i.preInit.pop()();return w&&(re=!1,Ae.initWorker()),Ow(),e.ready}}();typeof py=="object"&&typeof CC=="object"?CC.exports=vC:typeof define=="function"&&define.amd?define([],function(){return vC}):typeof py=="object"&&(py.WasmBackendModuleThreadedSimd=vC)});var vz=Ut((my,SC)=>{var IC=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(Z,se){n=Z,o=se});var s={},a;for(a in t)t.hasOwnProperty(a)&&(s[a]=t[a]);var i=[],l="./this.program",u=function(Z,se){throw se},c=!1,p=!1,m=!1,f=!1;c=typeof window=="object",p=typeof importScripts=="function",m=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",f=!c&&!m&&!p;var d="";function h(Z){return t.locateFile?t.locateFile(Z,d):d+Z}var g,x,b,w,_,C;m?(p?d=am().dirname(d)+"/":d=__dirname+"/",g=function(se,ve){return _||(_=Lc("fs")),C||(C=am()),se=C.normalize(se),_.readFileSync(se,ve?null:"utf8")},b=function(se){var ve=g(se,!0);return ve.buffer||(ve=new Uint8Array(ve)),U(ve.buffer),ve},process.argv.length>1&&(l=process.argv[1].replace(/\\/g,"/")),i=process.argv.slice(2),process.on("uncaughtException",function(Z){if(!(Z instanceof Dw))throw Z}),process.on("unhandledRejection",Ks),u=function(Z){process.exit(Z)},t.inspect=function(){return"[Emscripten Module object]"}):f?(typeof read!="undefined"&&(g=function(se){return read(se)}),b=function(se){var ve;return typeof readbuffer=="function"?new Uint8Array(readbuffer(se)):(ve=read(se,"binary"),U(typeof ve=="object"),ve)},typeof scriptArgs!="undefined"?i=scriptArgs:typeof arguments!="undefined"&&(i=arguments),typeof quit=="function"&&(u=function(Z){quit(Z)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(c||p)&&(p?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(Z){var se=new XMLHttpRequest;return se.open("GET",Z,!1),se.send(null),se.responseText},p&&(b=function(Z){var se=new XMLHttpRequest;return se.open("GET",Z,!1),se.responseType="arraybuffer",se.send(null),new Uint8Array(se.response)}),x=function(Z,se,ve){var ut=new XMLHttpRequest;ut.open("GET",Z,!0),ut.responseType="arraybuffer",ut.onload=function(){if(ut.status==200||ut.status==0&&ut.response){se(ut.response);return}ve()},ut.onerror=ve,ut.send(null)},w=function(Z){document.title=Z});var A=t.print||console.log.bind(console),D=t.printErr||console.warn.bind(console);for(a in s)s.hasOwnProperty(a)&&(t[a]=s[a]);s=null,t.arguments&&(i=t.arguments),t.thisProgram&&(l=t.thisProgram),t.quit&&(u=t.quit);var $;t.wasmBinary&&($=t.wasmBinary);var R=t.noExitRuntime||!0;typeof WebAssembly!="object"&&Ks("no native wasm support detected");var M,G=!1,j;function U(Z,se){Z||Ks("Assertion failed: "+se)}function q(Z){var se=t["_"+Z];return U(se,"Cannot call unknown function "+Z+", make sure it is exported"),se}function H(Z,se,ve,ut,rr){var jt={string:function(Dn){var sl=0;if(Dn!=null&&Dn!==0){var vg=(Dn.length<<2)+1;sl=Vm(vg),ie(Dn,sl,vg)}return sl},array:function(Dn){var sl=Vm(Dn.length);return me(Dn,sl),sl}};function rt(Dn){return se==="string"?re(Dn):se==="boolean"?Boolean(Dn):Dn}var nt=q(Z),Dr=[],Di=0;if(ut)for(var $i=0;$i<ut.length;$i++){var kg=jt[ve[$i]];kg?(Di===0&&(Di=wg()),Dr[$i]=kg(ut[$i])):Dr[$i]=ut[$i]}var Wm=nt.apply(null,Dr);return Wm=rt(Wm),Di!==0&&_g(Di),Wm}function X(Z,se,ve,ut){ve=ve||[];var rr=ve.every(function(rt){return rt==="number"}),jt=se!=="string";return jt&&rr&&!ut?q(Z):function(){return H(Z,se,ve,arguments,ut)}}var ne=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function Y(Z,se,ve){for(var ut=se+ve,rr=se;Z[rr]&&!(rr>=ut);)++rr;if(rr-se>16&&Z.subarray&&ne)return ne.decode(Z.subarray(se,rr));for(var jt="";se<rr;){var rt=Z[se++];if(!(rt&128)){jt+=String.fromCharCode(rt);continue}var nt=Z[se++]&63;if((rt&224)==192){jt+=String.fromCharCode((rt&31)<<6|nt);continue}var Dr=Z[se++]&63;if((rt&240)==224?rt=(rt&15)<<12|nt<<6|Dr:rt=(rt&7)<<18|nt<<12|Dr<<6|Z[se++]&63,rt<65536)jt+=String.fromCharCode(rt);else{var Di=rt-65536;jt+=String.fromCharCode(55296|Di>>10,56320|Di&1023)}}return jt}function re(Z,se){return Z?Y(xe,Z,se):""}function ee(Z,se,ve,ut){if(!(ut>0))return 0;for(var rr=ve,jt=ve+ut-1,rt=0;rt<Z.length;++rt){var nt=Z.charCodeAt(rt);if(nt>=55296&&nt<=57343){var Dr=Z.charCodeAt(++rt);nt=65536+((nt&1023)<<10)|Dr&1023}if(nt<=127){if(ve>=jt)break;se[ve++]=nt}else if(nt<=2047){if(ve+1>=jt)break;se[ve++]=192|nt>>6,se[ve++]=128|nt&63}else if(nt<=65535){if(ve+2>=jt)break;se[ve++]=224|nt>>12,se[ve++]=128|nt>>6&63,se[ve++]=128|nt&63}else{if(ve+3>=jt)break;se[ve++]=240|nt>>18,se[ve++]=128|nt>>12&63,se[ve++]=128|nt>>6&63,se[ve++]=128|nt&63}}return se[ve]=0,ve-rr}function ie(Z,se,ve){return ee(Z,xe,se,ve)}function me(Z,se){he.set(Z,se)}function ae(Z,se){return Z%se>0&&(Z+=se-Z%se),Z}var fe,he,xe,_e,$e,Ce,We,Xe,lt;function Et(Z){fe=Z,t.HEAP8=he=new Int8Array(Z),t.HEAP16=_e=new Int16Array(Z),t.HEAP32=Ce=new Int32Array(Z),t.HEAPU8=xe=new Uint8Array(Z),t.HEAPU16=$e=new Uint16Array(Z),t.HEAPU32=We=new Uint32Array(Z),t.HEAPF32=Xe=new Float32Array(Z),t.HEAPF64=lt=new Float64Array(Z)}var At=t.INITIAL_MEMORY||16777216,He,pt=[],ft=[],Vt=[],En=[],tr=!1;ft.push({func:function(){cg()}});function gn(){if(t.preRun)for(typeof t.preRun=="function"&&(t.preRun=[t.preRun]);t.preRun.length;)An(t.preRun.shift());rl(pt)}function Gr(){tr=!0,rl(ft)}function Qn(){rl(Vt)}function cr(){if(t.postRun)for(typeof t.postRun=="function"&&(t.postRun=[t.postRun]);t.postRun.length;)Yr(t.postRun.shift());rl(En)}function An(Z){pt.unshift(Z)}function Yr(Z){En.unshift(Z)}var Cr=0,xn=null,Gn=null;function Jl(Z){Cr++,t.monitorRunDependencies&&t.monitorRunDependencies(Cr)}function tl(Z){if(Cr--,t.monitorRunDependencies&&t.monitorRunDependencies(Cr),Cr==0&&(xn!==null&&(clearInterval(xn),xn=null),Gn)){var se=Gn;Gn=null,se()}}t.preloadedImages={},t.preloadedAudios={};function Ks(Z){t.onAbort&&t.onAbort(Z),Z+="",D(Z),G=!0,j=1,Z="abort("+Z+"). Build with -s ASSERTIONS=1 for more info.";var se=new WebAssembly.RuntimeError(Z);throw o(se),se}function Ti(Z,se){return String.prototype.startsWith?Z.startsWith(se):Z.indexOf(se)===0}var Pm="data:application/octet-stream;base64,";function Ql(Z){return Ti(Z,Pm)}var fb="file://";function og(Z){return Ti(Z,fb)}var yn="tfjs-backend-wasm.wasm";Ql(yn)||(yn=h(yn));function sg(Z){try{if(Z==yn&&$)return new Uint8Array($);if(b)return b(Z);throw"both async and sync fetching of the wasm failed"}catch(se){Ks(se)}}function db(){if(!$&&(c||p)){if(typeof fetch=="function"&&!og(yn))return fetch(yn,{credentials:"same-origin"}).then(function(Z){if(!Z.ok)throw"failed to load wasm binary file at '"+yn+"'";return Z.arrayBuffer()}).catch(function(){return sg(yn)});if(x)return new Promise(function(Z,se){x(yn,function(ve){Z(new Uint8Array(ve))},se)})}return Promise.resolve().then(function(){return sg(yn)})}function Ei(){var Z={a:bb};function se(rt,nt){var Dr=rt.exports;t.asm=Dr,M=t.asm.i,Et(M.buffer),He=t.asm.o,tl("wasm-instantiate")}Jl("wasm-instantiate");function ve(rt){se(rt.instance)}function ut(rt){return db().then(function(nt){return WebAssembly.instantiate(nt,Z)}).then(rt,function(nt){D("failed to asynchronously prepare wasm: "+nt),Ks(nt)})}function rr(){return!$&&typeof WebAssembly.instantiateStreaming=="function"&&!Ql(yn)&&!og(yn)&&typeof fetch=="function"?fetch(yn,{credentials:"same-origin"}).then(function(rt){var nt=WebAssembly.instantiateStreaming(rt,Z);return nt.then(ve,function(Dr){return D("wasm streaming compile failed: "+Dr),D("falling back to ArrayBuffer instantiation"),ut(ve)})}):ut(ve)}if(t.instantiateWasm)try{var jt=t.instantiateWasm(Z,se);return jt}catch(rt){return D("Module.instantiateWasm callback failed with error: "+rt),!1}return rr().catch(o),{}}function rl(Z){for(;Z.length>0;){var se=Z.shift();if(typeof se=="function"){se(t);continue}var ve=se.func;typeof ve=="number"?se.arg===void 0?He.get(ve)():He.get(ve)(se.arg):ve(se.arg===void 0?null:se.arg)}}function eu(){Ks()}function hb(Z,se,ve){xe.copyWithin(Z,se,se+ve)}function gb(){return xe.length}function Ai(Z){try{return M.grow(Z-fe.byteLength+65535>>>16),Et(M.buffer),1}catch(se){}}function ig(Z){var se=gb(),ve=2147483648;if(Z>ve)return!1;for(var ut=1;ut<=4;ut*=2){var rr=se*(1+.2/ut);rr=Math.min(rr,Z+100663296);var jt=Math.min(ve,ae(Math.max(Z,rr),65536)),rt=Ai(jt);if(rt)return!0}return!1}var Tc={mappings:{},buffers:[null,[],[]],printChar:function(Z,se){var ve=Tc.buffers[Z];se===0||se===10?((Z===1?A:D)(Y(ve,0)),ve.length=0):ve.push(se)},varargs:void 0,get:function(){Tc.varargs+=4;var Z=Ce[Tc.varargs-4>>2];return Z},getStr:function(Z){var se=re(Z);return se},get64:function(Z,se){return Z}};function ag(Z){return 0}function xb(Z,se,ve,ut,rr){}function lg(Z,se,ve,ut){for(var rr=0,jt=0;jt<ve;jt++){for(var rt=Ce[se+jt*8>>2],nt=Ce[se+(jt*8+4)>>2],Dr=0;Dr<nt;Dr++)Tc.printChar(Z,xe[rt+Dr]);rr+=nt}return Ce[ut>>2]=rr,0}function bn(){return 6}function ug(Z){return Ce[bg()>>2]=Z,Z}function yb(Z){switch(Z){case 30:return 16384;case 85:var se=2147483648;return se/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 ug(28),-1}var bb={a:eu,d:hb,e:ig,f:ag,c:xb,b:lg,g:bn,h:yb},wb=Ei(),cg=t.___wasm_call_ctors=function(){return(cg=t.___wasm_call_ctors=t.asm.j).apply(null,arguments)},Ec=t._init=function(){return(Ec=t._init=t.asm.k).apply(null,arguments)},Mm=t._register_tensor=function(){return(Mm=t._register_tensor=t.asm.l).apply(null,arguments)},_b=t._dispose_data=function(){return(_b=t._dispose_data=t.asm.m).apply(null,arguments)},kb=t._dispose=function(){return(kb=t._dispose=t.asm.n).apply(null,arguments)},vb=t._Abs=function(){return(vb=t._Abs=t.asm.p).apply(null,arguments)},Ae=t._Add=function(){return(Ae=t._Add=t.asm.q).apply(null,arguments)},Cb=t._AddN=function(){return(Cb=t._AddN=t.asm.r).apply(null,arguments)},Ib=t._All=function(){return(Ib=t._All=t.asm.s).apply(null,arguments)},Sb=t._Any=function(){return(Sb=t._Any=t.asm.t).apply(null,arguments)},Nb=t._ArgMax=function(){return(Nb=t._ArgMax=t.asm.u).apply(null,arguments)},Tb=t._AvgPool=function(){return(Tb=t._AvgPool=t.asm.v).apply(null,arguments)},tu=t._BatchMatMul=function(){return(tu=t._BatchMatMul=t.asm.w).apply(null,arguments)},Eb=t._Ceil=function(){return(Eb=t._Ceil=t.asm.x).apply(null,arguments)},Ab=t._ClipByValue=function(){return(Ab=t._ClipByValue=t.asm.y).apply(null,arguments)},Db=t._Conv2D=function(){return(Db=t._Conv2D=t.asm.z).apply(null,arguments)},$b=t._Conv2DBackpropInput=function(){return($b=t._Conv2DBackpropInput=t.asm.A).apply(null,arguments)},Rb=t._Cos=function(){return(Rb=t._Cos=t.asm.B).apply(null,arguments)},Fb=t._CropAndResize=function(){return(Fb=t._CropAndResize=t.asm.C).apply(null,arguments)},Ob=t._Cumsum=function(){return(Ob=t._Cumsum=t.asm.D).apply(null,arguments)},Pb=t._DepthToSpace=function(){return(Pb=t._DepthToSpace=t.asm.E).apply(null,arguments)},Mb=t._DepthwiseConv2dNative=function(){return(Mb=t._DepthwiseConv2dNative=t.asm.F).apply(null,arguments)},nl=t._Equal=function(){return(nl=t._Equal=t.asm.G).apply(null,arguments)},Lm=t._Exp=function(){return(Lm=t._Exp=t.asm.H).apply(null,arguments)},zm=t._FlipLeftRight=function(){return(zm=t._FlipLeftRight=t.asm.I).apply(null,arguments)},Lb=t._Floor=function(){return(Lb=t._Floor=t.asm.J).apply(null,arguments)},zb=t._FloorDiv=function(){return(zb=t._FloorDiv=t.asm.K).apply(null,arguments)},Bb=t._FusedBatchNorm=function(){return(Bb=t._FusedBatchNorm=t.asm.L).apply(null,arguments)},Vb=t._FusedConv2D=function(){return(Vb=t._FusedConv2D=t.asm.M).apply(null,arguments)},Gb=t._FusedDepthwiseConv2D=function(){return(Gb=t._FusedDepthwiseConv2D=t.asm.N).apply(null,arguments)},Qe=t._Gather=function(){return(Qe=t._Gather=t.asm.O).apply(null,arguments)},Wb=t._GatherNd=function(){return(Wb=t._GatherNd=t.asm.P).apply(null,arguments)},jb=t._Greater=function(){return(jb=t._Greater=t.asm.Q).apply(null,arguments)},Ub=t._GreaterEqual=function(){return(Ub=t._GreaterEqual=t.asm.R).apply(null,arguments)},qb=t._LeakyRelu=function(){return(qb=t._LeakyRelu=t.asm.S).apply(null,arguments)},Hb=t._Less=function(){return(Hb=t._Less=t.asm.T).apply(null,arguments)},Kb=t._LessEqual=function(){return(Kb=t._LessEqual=t.asm.U).apply(null,arguments)},Bm=t._Log=function(){return(Bm=t._Log=t.asm.V).apply(null,arguments)},pg=t._LogicalAnd=function(){return(pg=t._LogicalAnd=t.asm.W).apply(null,arguments)},mg=t._Max=function(){return(mg=t._Max=t.asm.X).apply(null,arguments)},Xb=t._MaxPool=function(){return(Xb=t._MaxPool=t.asm.Y).apply(null,arguments)},Yb=t._Maximum=function(){return(Yb=t._Maximum=t.asm.Z).apply(null,arguments)},Zb=t._Mean=function(){return(Zb=t._Mean=t.asm._).apply(null,arguments)},Jb=t._Min=function(){return(Jb=t._Min=t.asm.$).apply(null,arguments)},Qb=t._Minimum=function(){return(Qb=t._Minimum=t.asm.aa).apply(null,arguments)},ew=t._MirrorPad=function(){return(ew=t._MirrorPad=t.asm.ba).apply(null,arguments)},tw=t._Multiply=function(){return(tw=t._Multiply=t.asm.ca).apply(null,arguments)},dt=t._Neg=function(){return(dt=t._Neg=t.asm.da).apply(null,arguments)},rw=t._NonMaxSuppressionV3=function(){return(rw=t._NonMaxSuppressionV3=t.asm.ea).apply(null,arguments)},nw=t._NonMaxSuppressionV4=function(){return(nw=t._NonMaxSuppressionV4=t.asm.fa).apply(null,arguments)},ow=t._NonMaxSuppressionV5=function(){return(ow=t._NonMaxSuppressionV5=t.asm.ga).apply(null,arguments)},Ac=t._NotEqual=function(){return(Ac=t._NotEqual=t.asm.ha).apply(null,arguments)},fg=t._OneHot=function(){return(fg=t._OneHot=t.asm.ia).apply(null,arguments)},dg=t._PadV2=function(){return(dg=t._PadV2=t.asm.ja).apply(null,arguments)},hg=t._Pow=function(){return(hg=t._Pow=t.asm.ka).apply(null,arguments)},sw=t._Prelu=function(){return(sw=t._Prelu=t.asm.la).apply(null,arguments)},iw=t._Prod=function(){return(iw=t._Prod=t.asm.ma).apply(null,arguments)},gg=t._RealDiv=function(){return(gg=t._RealDiv=t.asm.na).apply(null,arguments)},aw=t._Relu=function(){return(aw=t._Relu=t.asm.oa).apply(null,arguments)},xg=t._Relu6=function(){return(xg=t._Relu6=t.asm.pa).apply(null,arguments)},ol=t._ResizeBilinear=function(){return(ol=t._ResizeBilinear=t.asm.qa).apply(null,arguments)},lw=t._Reverse=function(){return(lw=t._Reverse=t.asm.ra).apply(null,arguments)},uw=t._RotateWithOffset=function(){return(uw=t._RotateWithOffset=t.asm.sa).apply(null,arguments)},CS=t._Round=function(){return(CS=t._Round=t.asm.ta).apply(null,arguments)},yg=t._Rsqrt=function(){return(yg=t._Rsqrt=t.asm.ua).apply(null,arguments)},cw=t._ScatterNd=function(){return(cw=t._ScatterNd=t.asm.va).apply(null,arguments)},pw=t._SelectV2=function(){return(pw=t._SelectV2=t.asm.wa).apply(null,arguments)},mw=t._Sigmoid=function(){return(mw=t._Sigmoid=t.asm.xa).apply(null,arguments)},fw=t._Sin=function(){return(fw=t._Sin=t.asm.ya).apply(null,arguments)},dw=t._Softmax=function(){return(dw=t._Softmax=t.asm.za).apply(null,arguments)},hw=t._Sqrt=function(){return(hw=t._Sqrt=t.asm.Aa).apply(null,arguments)},gw=t._Square=function(){return(gw=t._Square=t.asm.Ba).apply(null,arguments)},xw=t._SquaredDifference=function(){return(xw=t._SquaredDifference=t.asm.Ca).apply(null,arguments)},yw=t._Step=function(){return(yw=t._Step=t.asm.Da).apply(null,arguments)},bw=t._StridedSlice=function(){return(bw=t._StridedSlice=t.asm.Ea).apply(null,arguments)},ww=t._Sub=function(){return(ww=t._Sub=t.asm.Fa).apply(null,arguments)},_w=t._Sum=function(){return(_w=t._Sum=t.asm.Ga).apply(null,arguments)},kw=t._Tan=function(){return(kw=t._Tan=t.asm.Ha).apply(null,arguments)},vw=t._Tanh=function(){return(vw=t._Tanh=t.asm.Ia).apply(null,arguments)},Cw=t._Tile=function(){return(Cw=t._Tile=t.asm.Ja).apply(null,arguments)},Iw=t._TopK=function(){return(Iw=t._TopK=t.asm.Ka).apply(null,arguments)},Sw=t._Transform=function(){return(Sw=t._Transform=t.asm.La).apply(null,arguments)},Nw=t._Transpose=function(){return(Nw=t._Transpose=t.asm.Ma).apply(null,arguments)},Tw=t.__FusedMatMul=function(){return(Tw=t.__FusedMatMul=t.asm.Na).apply(null,arguments)},Ew=t._malloc=function(){return(Ew=t._malloc=t.asm.Oa).apply(null,arguments)},Aw=t._free=function(){return(Aw=t._free=t.asm.Pa).apply(null,arguments)},bg=t.___errno_location=function(){return(bg=t.___errno_location=t.asm.Qa).apply(null,arguments)},wg=t.stackSave=function(){return(wg=t.stackSave=t.asm.Ra).apply(null,arguments)},_g=t.stackRestore=function(){return(_g=t.stackRestore=t.asm.Sa).apply(null,arguments)},Vm=t.stackAlloc=function(){return(Vm=t.stackAlloc=t.asm.Ta).apply(null,arguments)};t.cwrap=X;var Dc;function Dw(Z){this.name="ExitStatus",this.message="Program terminated with exit("+Z+")",this.status=Z}Gn=function Z(){Dc||Gm(),Dc||(Gn=Z)};function Gm(Z){if(Z=Z||i,Cr>0||(gn(),Cr>0))return;function se(){Dc||(Dc=!0,t.calledRun=!0,!G&&(Gr(),Qn(),n(t),t.onRuntimeInitialized&&t.onRuntimeInitialized(),cr()))}t.setStatus?(t.setStatus("Running..."),setTimeout(function(){setTimeout(function(){t.setStatus("")},1),se()},1)):se()}if(t.run=Gm,t.preInit)for(typeof t.preInit=="function"&&(t.preInit=[t.preInit]);t.preInit.length>0;)t.preInit.pop()();return Gm(),e.ready}}();typeof my=="object"&&typeof SC=="object"?SC.exports=IC:typeof define=="function"&&define.amd?define([],function(){return IC}):typeof my=="object"&&(my.WasmBackendModule=IC)});var pG=Ut((cG,uS)=>{(function(r,e,t){function n(i){var l=this,u=a();l.next=function(){var c=2091639*l.s0+l.c*23283064365386963e-26;return l.s0=l.s1,l.s1=l.s2,l.s2=c-(l.c=c|0)},l.c=1,l.s0=u(" "),l.s1=u(" "),l.s2=u(" "),l.s0-=u(i),l.s0<0&&(l.s0+=1),l.s1-=u(i),l.s1<0&&(l.s1+=1),l.s2-=u(i),l.s2<0&&(l.s2+=1),u=null}function o(i,l){return l.c=i.c,l.s0=i.s0,l.s1=i.s1,l.s2=i.s2,l}function s(i,l){var u=new n(i),c=l&&l.state,p=u.next;return p.int32=function(){return u.next()*4294967296|0},p.double=function(){return p()+(p()*2097152|0)*11102230246251565e-32},p.quick=p,c&&(typeof c=="object"&&o(c,u),p.state=function(){return o(u,{})}),p}function a(){var i=4022871197,l=function(u){u=String(u);for(var c=0;c<u.length;c++){i+=u.charCodeAt(c);var p=.02519603282416938*i;i=p>>>0,p-=i,p*=i,i=p>>>0,p-=i,i+=p*4294967296}return(i>>>0)*23283064365386963e-26};return l}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.alea=s})(cG,typeof uS=="object"&&uS,typeof define=="function"&&define)});var fG=Ut((mG,cS)=>{(function(r,e,t){function n(a){var i=this,l="";i.x=0,i.y=0,i.z=0,i.w=0,i.next=function(){var c=i.x^i.x<<11;return i.x=i.y,i.y=i.z,i.z=i.w,i.w^=i.w>>>19^c^c>>>8},a===(a|0)?i.x=a:l+=a;for(var u=0;u<l.length+64;u++)i.x^=l.charCodeAt(u)|0,i.next()}function o(a,i){return i.x=a.x,i.y=a.y,i.z=a.z,i.w=a.w,i}function s(a,i){var l=new n(a),u=i&&i.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var p=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=l.next,c.quick=c,u&&(typeof u=="object"&&o(u,l),c.state=function(){return o(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xor128=s})(mG,typeof cS=="object"&&cS,typeof define=="function"&&define)});var hG=Ut((dG,pS)=>{(function(r,e,t){function n(a){var i=this,l="";i.next=function(){var c=i.x^i.x>>>2;return i.x=i.y,i.y=i.z,i.z=i.w,i.w=i.v,(i.d=i.d+362437|0)+(i.v=i.v^i.v<<4^(c^c<<1))|0},i.x=0,i.y=0,i.z=0,i.w=0,i.v=0,a===(a|0)?i.x=a:l+=a;for(var u=0;u<l.length+64;u++)i.x^=l.charCodeAt(u)|0,u==l.length&&(i.d=i.x<<10^i.x>>>4),i.next()}function o(a,i){return i.x=a.x,i.y=a.y,i.z=a.z,i.w=a.w,i.v=a.v,i.d=a.d,i}function s(a,i){var l=new n(a),u=i&&i.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var p=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=l.next,c.quick=c,u&&(typeof u=="object"&&o(u,l),c.state=function(){return o(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xorwow=s})(dG,typeof pS=="object"&&pS,typeof define=="function"&&define)});var xG=Ut((gG,mS)=>{(function(r,e,t){function n(a){var i=this;i.next=function(){var u=i.x,c=i.i,p,m,f;return p=u[c],p^=p>>>7,m=p^p<<24,p=u[c+1&7],m^=p^p>>>10,p=u[c+3&7],m^=p^p>>>3,p=u[c+4&7],m^=p^p<<7,p=u[c+7&7],p=p^p<<13,m^=p^p<<9,u[c]=m,i.i=c+1&7,m};function l(u,c){var p,m,f=[];if(c===(c|0))m=f[0]=c;else for(c=""+c,p=0;p<c.length;++p)f[p&7]=f[p&7]<<15^c.charCodeAt(p)+f[p+1&7]<<13;for(;f.length<8;)f.push(0);for(p=0;p<8&&f[p]===0;++p);for(p==8?m=f[7]=-1:m=f[p],u.x=f,u.i=0,p=256;p>0;--p)u.next()}l(i,a)}function o(a,i){return i.x=a.x.slice(),i.i=a.i,i}function s(a,i){a==null&&(a=+new Date);var l=new n(a),u=i&&i.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var p=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=l.next,c.quick=c,u&&(u.x&&o(u,l),c.state=function(){return o(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xorshift7=s})(gG,typeof mS=="object"&&mS,typeof define=="function"&&define)});var bG=Ut((yG,fS)=>{(function(r,e,t){function n(a){var i=this;i.next=function(){var u=i.w,c=i.X,p=i.i,m,f;return i.w=u=u+1640531527|0,f=c[p+34&127],m=c[p=p+1&127],f^=f<<13,m^=m<<17,f^=f>>>15,m^=m>>>12,f=c[p]=f^m,i.i=p,f+(u^u>>>16)|0};function l(u,c){var p,m,f,d,h,g=[],x=128;for(c===(c|0)?(m=c,c=null):(c=c+"\0",m=0,x=Math.max(x,c.length)),f=0,d=-32;d<x;++d)c&&(m^=c.charCodeAt((d+32)%c.length)),d===0&&(h=m),m^=m<<10,m^=m>>>15,m^=m<<4,m^=m>>>13,d>=0&&(h=h+1640531527|0,p=g[d&127]^=m+h,f=p==0?f+1:0);for(f>=128&&(g[(c&&c.length||0)&127]=-1),f=127,d=4*128;d>0;--d)m=g[f+34&127],p=g[f=f+1&127],m^=m<<13,p^=p<<17,m^=m>>>15,p^=p>>>12,g[f]=m^p;u.w=h,u.X=g,u.i=f}l(i,a)}function o(a,i){return i.i=a.i,i.w=a.w,i.X=a.X.slice(),i}function s(a,i){a==null&&(a=+new Date);var l=new n(a),u=i&&i.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var p=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=l.next,c.quick=c,u&&(u.X&&o(u,l),c.state=function(){return o(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xor4096=s})(yG,typeof fS=="object"&&fS,typeof define=="function"&&define)});var _G=Ut((wG,dS)=>{(function(r,e,t){function n(a){var i=this,l="";i.next=function(){var c=i.b,p=i.c,m=i.d,f=i.a;return c=c<<25^c>>>7^p,p=p-m|0,m=m<<24^m>>>8^f,f=f-c|0,i.b=c=c<<20^c>>>12^p,i.c=p=p-m|0,i.d=m<<16^p>>>16^f,i.a=f-c|0},i.a=0,i.b=0,i.c=2654435769|0,i.d=1367130551,a===Math.floor(a)?(i.a=a/4294967296|0,i.b=a|0):l+=a;for(var u=0;u<l.length+20;u++)i.b^=l.charCodeAt(u)|0,i.next()}function o(a,i){return i.a=a.a,i.b=a.b,i.c=a.c,i.d=a.d,i}function s(a,i){var l=new n(a),u=i&&i.state,c=function(){return(l.next()>>>0)/4294967296};return c.double=function(){do var p=l.next()>>>11,m=(l.next()>>>0)/4294967296,f=(p+m)/(1<<21);while(f===0);return f},c.int32=l.next,c.quick=c,u&&(typeof u=="object"&&o(u,l),c.state=function(){return o(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.tychei=s})(wG,typeof dS=="object"&&dS,typeof define=="function"&&define)});var vG=Ut((kG,ib)=>{(function(r,e,t){var n=256,o=6,s=52,a="random",i=t.pow(n,o),l=t.pow(2,s),u=l*2,c=n-1,p;function m(w,_,C){var A=[];_=_==!0?{entropy:!0}:_||{};var D=g(h(_.entropy?[w,b(e)]:w==null?x():w,3),A),$=new f(A),R=function(){for(var M=$.g(o),G=i,j=0;M<l;)M=(M+j)*n,G*=n,j=$.g(1);for(;M>=u;)M/=2,G/=2,j>>>=1;return(M+j)/G};return R.int32=function(){return $.g(4)|0},R.quick=function(){return $.g(4)/4294967296},R.double=R,g(b($.S),e),(_.pass||C||function(M,G,j,U){return U&&(U.S&&d(U,$),M.state=function(){return d($,{})}),j?(t[a]=M,G):M})(R,D,"global"in _?_.global:this==t,_.state)}function f(w){var _,C=w.length,A=this,D=0,$=A.i=A.j=0,R=A.S=[];for(C||(w=[C++]);D<n;)R[D]=D++;for(D=0;D<n;D++)R[D]=R[$=c&$+w[D%C]+(_=R[D])],R[$]=_;(A.g=function(M){for(var G,j=0,U=A.i,q=A.j,H=A.S;M--;)G=H[U=c&U+1],j=j*n+H[c&(H[U]=H[q=c&q+G])+(H[q]=G)];return A.i=U,A.j=q,j})(n)}function d(w,_){return _.i=w.i,_.j=w.j,_.S=w.S.slice(),_}function h(w,_){var C=[],A=typeof w,D;if(_&&A=="object")for(D in w)try{C.push(h(w[D],_-1))}catch($){}return C.length?C:A=="string"?w:w+"\0"}function g(w,_){for(var C=w+"",A,D=0;D<C.length;)_[c&D]=c&(A^=_[c&D]*19)+C.charCodeAt(D++);return b(_)}function x(){try{var w;return p&&(w=p.randomBytes)?w=w(n):(w=new Uint8Array(n),(r.crypto||r.msCrypto).getRandomValues(w)),b(w)}catch(A){var _=r.navigator,C=_&&_.plugins;return[+new Date,r,C,r.screen,b(e)]}}function b(w){return String.fromCharCode.apply(0,w)}if(g(t.random(),e),typeof ib=="object"&&ib.exports){ib.exports=m;try{p=ok()}catch(w){}}else typeof define=="function"&&define.amd?define(function(){return m}):t["seed"+a]=m})(typeof self!="undefined"?self:kG,[],Math)});var hS=Ut((dHt,CG)=>{var $se=pG(),Rse=fG(),Fse=hG(),Ose=xG(),Pse=bG(),Mse=_G(),Nc=vG();Nc.alea=$se;Nc.xor128=Rse;Nc.xorwow=Fse;Nc.xorshift7=Ose;Nc.xor4096=Pse;Nc.tychei=Mse;CG.exports=Nc});var JG=Ut(()=>{});var Hm={};je(Hm,{bin:()=>qS,browser:()=>JS,default:()=>nj,dependencies:()=>ZS,description:()=>LS,devDependencies:()=>XS,jsdelivr:()=>GS,license:()=>KS,main:()=>BS,miniprogram:()=>US,module:()=>VS,name:()=>PS,private:()=>zS,repository:()=>HS,scripts:()=>YS,types:()=>jS,unpkg:()=>WS,version:()=>MS});var PS="@tensorflow/tfjs",MS="3.7.0",LS="An open-source machine learning framework.",zS=!1,BS="dist/tf.node.js",VS="dist/index.js",GS="dist/tf.min.js",WS="dist/tf.min.js",jS="dist/index.d.ts",US="dist/miniprogram",qS={"tfjs-custom-module":"dist/tools/custom_module/cli.js"},HS={type:"git",url:"https://github.com/tensorflow/tfjs.git"},KS="Apache-2.0",XS={"@babel/core":"^7.9.0","@babel/polyfill":"^7.10.4","@babel/preset-env":"^7.9.5","@rollup/plugin-commonjs":"^11.0.2","@rollup/plugin-node-resolve":"^7.1.1","@rollup/plugin-typescript":"^3.0.0","@types/argparse":"^1.0.38","@types/jasmine":"2.8.7","@types/node":"~10.17.50","@types/shelljs":"^0.8.4","@types/yargs":"^15.0.7","clang-format":"~1.2.2",commander:"~2.14.1",jasmine:"3.1.0","jasmine-core":"~3.1.0",karma:"~6.3.2","karma-browserstack-launcher":"~1.6.0","karma-chrome-launcher":"~2.2.0","karma-firefox-launcher":"~1.1.0","karma-jasmine":"~1.1.1","karma-typescript":"~5.5.1","karma-typescript-es6-transform":"^5.5.1","npm-run-all":"~4.1.3",rimraf:"~2.6.2",rollup:"~2.3.2","rollup-plugin-babel":"^4.4.0","rollup-plugin-terser":"~7.0.2","rollup-plugin-visualizer":"~4.2.2",shelljs:"~0.8.1","ts-node":"~8.8.2",tslint:"~5.11.0","tslint-no-circular-imports":"~0.5.0",typescript:"3.5.3",yalc:"1.0.0-pre.50"},YS={build:"tsc && yarn build-cli && yarn bundle","build-ci":"tsc && yarn build-cli && yarn bundle-ci",bundle:"rollup -c","bundle-ci":"rollup -c --ci","build-core":"cd ../tfjs-core && yarn && yarn build","build-core-ci":"cd ../tfjs-core && yarn && yarn build-ci","build-layers":"cd ../tfjs-layers && yarn && yarn build","build-layers-ci":"cd ../tfjs-layers && yarn && yarn build-ci","build-converter":"cd ../tfjs-converter && yarn && yarn build","build-converter-ci":"cd ../tfjs-converter && yarn && yarn build-ci","build-data":"cd ../tfjs-data && yarn && yarn build","build-data-ci":"cd ../tfjs-data && yarn && yarn build-ci","build-backend-cpu":"cd ../tfjs-backend-cpu && yarn && yarn build","build-backend-cpu-ci":"cd ../tfjs-backend-cpu && yarn && yarn build-ci","build-backend-webgl":"cd ../tfjs-backend-webgl && yarn && yarn build","build-backend-webgl-ci":"cd ../tfjs-backend-webgl && yarn && yarn build-ci","build-deps":"yarn build-core && yarn build-layers && yarn build-converter && yarn build-data && yarn build-backend-cpu && yarn build-backend-webgl","build-deps-ci":"yarn build-core-ci && yarn build-layers-ci && yarn build-converter-ci && yarn build-data-ci && yarn build-backend-cpu-ci && yarn build-backend-webgl-ci","build-cli":"tsc --project ./tools/custom_module/tsconfig.json && chmod +x ./dist/tools/custom_module/cli.js","run-custom-build":"ts-node -s ./tools/custom_module/cli.ts","build-npm":"./scripts/build-npm.sh","link-local":"yalc link","publish-local":"yarn build-npm && yalc push","publish-npm":"npm publish",lint:"tslint -p . -t verbose",coverage:"KARMA_COVERAGE=1 karma start --browsers='Chrome' --singleRun",test:"yarn && yarn build-deps && yarn build && karma start","test-dev":"karma start","test-tools":"ts-node --project ./tools/custom_module/tsconfig.json run_tools_tests.ts","test-ci":"./scripts/test-ci.sh"},ZS={"@tensorflow/tfjs-backend-cpu":"3.7.0","@tensorflow/tfjs-backend-webgl":"3.7.0","@tensorflow/tfjs-converter":"3.7.0","@tensorflow/tfjs-core":"3.7.0","@tensorflow/tfjs-data":"3.7.0","@tensorflow/tfjs-layers":"3.7.0",argparse:"^1.0.10",chalk:"^4.1.0","core-js":"3","regenerator-runtime":"^0.13.5",yargs:"^16.0.3"},JS={"node-fetch":!1,util:!1,crypto:!1},nj={name:PS,version:MS,description:LS,private:zS,main:BS,module:VS,jsdelivr:GS,unpkg:WS,types:jS,miniprogram:US,bin:qS,repository:HS,license:KS,devDependencies:XS,scripts:YS,dependencies:ZS,browser:JS};var Km={};je(Km,{browser:()=>gN,default:()=>oj,dependencies:()=>hN,description:()=>tN,devDependencies:()=>fN,engines:()=>cN,jsdelivr:()=>oN,"jsnext:main":()=>aN,license:()=>mN,main:()=>nN,miniprogram:()=>uN,module:()=>lN,name:()=>QS,private:()=>rN,repository:()=>pN,scripts:()=>dN,sideEffects:()=>xN,types:()=>iN,unpkg:()=>sN,version:()=>eN});var QS="@tensorflow/tfjs-core",eN="3.7.0",tN="Hardware-accelerated JavaScript library for machine intelligence",rN=!1,nN="dist/tf-core.node.js",oN="dist/tf-core.min.js",sN="dist/tf-core.min.js",iN="dist/index.d.ts",aN="dist/index.js",lN="dist/index.js",uN="dist/miniprogram",cN={yarn:">= 1.3.2"},pN={type:"git",url:"https://github.com/tensorflow/tfjs-core.git"},mN="Apache-2.0",fN={"@bazel/bazelisk":"^1.3.0","@bazel/typescript":"^0.27.8","@rollup/plugin-commonjs":"^11.0.2","@rollup/plugin-node-resolve":"^7.1.1","@rollup/plugin-typescript":"^3.0.0","@tensorflow/tfjs-backend-cpu":"link:../tfjs-backend-cpu","@types/jasmine":"~3.0.0","@types/node":"~9.6.0","@types/node-fetch":"~2.1.2","clang-format":"~1.2.4",jasmine:"~3.1.0","jasmine-core":"~3.1.0",karma:"6.3.2","karma-browserstack-launcher":"~1.6.0","karma-chrome-launcher":"~3.1.0","karma-jasmine":"~4.0.1","karma-typescript":"~5.5.1","npm-run-all":"~4.1.3",rimraf:"~2.6.2",rollup:"~2.3.2","rollup-plugin-terser":"~5.3.0","rollup-plugin-visualizer":"~3.3.2",shelljs:"~0.8.3","ts-node":"~8.8.2",tslint:"~5.11.0","tslint-no-circular-imports":"~0.5.0",typescript:"3.5.3",yalc:"~1.0.0-pre.21",yargs:"~13.2.2"},dN={"build-ci":"./scripts/enumerate-tests.js --ci && tsc && yarn bundle-ci && yarn build-test-snippets",build:"node ./scripts/enumerate-tests.js && tsc && yarn bundle",bundle:"rollup -c","bundle-ci":"rollup -c --ci","build-npm":"./scripts/build-npm.sh","build-deps":"yarn build && yarn build-cpu-backend","build-cpu-backend":"cd ../tfjs-backend-cpu && yarn && yarn build","build-cpu-backend-ci":"cd ../tfjs-backend-cpu && yarn && yarn build-ci","build:bazel":"bazelisk build //...","build-test-snippets":"yarn tsc --project ./scripts/test_snippets/tsconfig.json","format-all":"clang-format -i -style=Google --glob=src/**/*.ts","link-local":"yalc link","publish-local":"rimraf dist/ && yarn build && rollup -c && yalc push","publish-npm":"npm publish",lint:"tslint -p . -t verbose",coverage:"KARMA_COVERAGE=1 karma start --browsers='Chrome' --singleRun",test:"yarn && yarn build-deps && karma start","test-dev":"karma start","test-ci":"./scripts/test-ci.sh","test-webworker":"karma start --worker","run-browserstack":"karma start --browserstack","test-bundle-size":"./scripts/test-bundle-size.js","test-node":"rimraf dist/ && yarn build-deps && yarn build && ts-node --transpile-only --skip-ignore -P tsconfig.test.json dist/test_node.js","test-node-dev":"tsc && ts-node --transpile-only --skip-ignore -P tsconfig.test.json dist/test_node.js","test-node-ci":"ts-node --transpile-only -P tsconfig.test.json dist/test_node.js","test-async-backends":"rimraf dist/ && yarn build && ts-node --transpile-only -P tsconfig.test.json dist/test_async_backends.js","test-async-backends-ci":"ts-node --transpile-only -P tsconfig.test.json dist/test_async_backends.js","test-snippets":"yarn build && yarn build-cpu-backend && ts-node -P tsconfig.test.json ./scripts/test_snippets/test_snippets.ts","test-snippets-ci":"ts-node -P tsconfig.test.json ./scripts/test_snippets/test_snippets.ts"},hN={"@types/long":"^4.0.1","@types/offscreencanvas":"~2019.3.0","@types/seedrandom":"2.4.27","@types/webgl-ext":"0.0.30",long:"4.0.0","node-fetch":"~2.6.1",seedrandom:"2.4.3"},gN={"node-fetch":!1,util:!1,crypto:!1,worker_threads:!1},xN=["./dist/index.js","./dist/engine.js","./dist/tensor.js","./dist/base_side_effects.js","./dist/flags.js","./dist/platforms/*.js","./dist/register_all_gradients.js","./dist/public/chained_ops/*.js","./dist/io/*.js"],oj={name:QS,version:eN,description:tN,private:rN,main:nN,jsdelivr:oN,unpkg:sN,types:iN,"jsnext:main":aN,module:lN,miniprogram:uN,engines:cN,repository:pN,license:mN,devDependencies:fN,scripts:dN,dependencies:hN,browser:gN,sideEffects:xN};var Xm={};je(Xm,{browser:()=>FN,default:()=>sj,dependencies:()=>RN,description:()=>wN,devDependencies:()=>AN,jsdelivr:()=>vN,"jsnext:main":()=>SN,license:()=>EN,main:()=>kN,miniprogram:()=>TN,module:()=>NN,name:()=>yN,peerDependencies:()=>$N,private:()=>_N,scripts:()=>DN,types:()=>IN,unpkg:()=>CN,version:()=>bN});var yN="@tensorflow/tfjs-data",bN="3.7.0",wN="TensorFlow Data API in JavaScript",_N=!1,kN="dist/tf-data.node.js",vN="dist/tf-data.min.js",CN="dist/tf-data.min.js",IN="dist/index.d.ts",SN="dist/index.js",NN="dist/index.js",TN="dist/miniprogram",EN="Apache-2.0",AN={"@rollup/plugin-commonjs":"^11.0.2","@rollup/plugin-node-resolve":"^7.1.1","@rollup/plugin-typescript":"^3.0.0","@tensorflow/tfjs-backend-cpu":"3.7.0","@tensorflow/tfjs-core":"3.7.0","@tensorflow/tfjs-layers":"3.7.0","@types/jasmine":"~2.5.53","@types/seedrandom":"^2.4.27","@types/utf8":"~2.1.6","clang-format":"~1.2.2","http-server":"~0.12.3",jasmine:"3.1.0","jasmine-core":"~3.1.0",karma:"~6.3.1","karma-chrome-launcher":"~2.2.0","karma-firefox-launcher":"~1.1.0","karma-jasmine":"~1.1.1","karma-typescript":"~5.5.1","karma-typescript-es6-transform":"^5.0.2",nyc:"^15.1.0",rimraf:"~2.6.2",rollup:"~2.3.2","rollup-plugin-terser":"~7.0.2","rollup-plugin-visualizer":"~3.3.2","ts-node":"~7.0.0",tslint:"~6.1.3","tslint-no-circular-imports":"^0.7.0",typescript:"3.5.3",yalc:"^1.0.0-pre.50"},DN={build:"tsc && yarn bundle","build-ci":"tsc && yarn bundle-ci",bundle:"rollup -c","bundle-ci":"rollup -c --ci","build-core":"cd ../tfjs-core && yarn && yarn build","build-core-ci":"cd ../tfjs-core && yarn && yarn build-ci","build-layers":"cd ../tfjs-layers && yarn && yarn build","build-backend-cpu":"cd ../tfjs-backend-cpu && yarn && yarn build","build-backend-cpu-ci":"cd ../tfjs-backend-cpu && yarn && yarn build-ci","build-layers-ci":"cd ../tfjs-layers && yarn && yarn build-ci","build-deps":"yarn build-core && yarn build-layers && yarn build-backend-cpu","build-deps-ci":"yarn build-core-ci && yarn build-layers-ci && yarn build-backend-cpu-ci","build-npm":"./scripts/build-npm.sh","link-local":"yalc link","publish-local":"rimraf dist/ && yarn build-npm && yalc push","publish-npm":"npm publish",test:"yarn && yarn build-deps && yarn build && ts-node --transpile-only --project tsconfig.test.json src/test_node.ts","test-dev":"tsc && ts-node --transpile-only --project tsconfig.test.json src/test_node.ts","test-browsers":"karma start --browsers='Chrome,Firefox'","test-ci":"ts-node --transpile-only --skip-ignore -P tsconfig.test.json src/test_node.ts","test-snippets":"yarn && yarn build-deps && yarn build && ts-node --skip-ignore --project tsconfig.test.json ./scripts/test_snippets.ts","test-snippets-ci":"ts-node --skip-ignore --project tsconfig.test.json ./scripts/test_snippets.ts",coverage:"yarn nyc yarn ts-node --transpile-only -P tsconfig.test.json src/test_node.ts",lint:"tslint -p . -t verbose"},$N={"@tensorflow/tfjs-core":"3.7.0",seedrandom:"~2.4.3"},RN={"@types/node-fetch":"^2.1.2","node-fetch":"~2.6.1"},FN={fs:!1,"node-fetch":!1,string_decoder:!1,crypto:!1},sj={name:yN,version:bN,description:wN,private:_N,main:kN,jsdelivr:vN,unpkg:CN,types:IN,"jsnext:main":SN,module:NN,miniprogram:TN,license:EN,devDependencies:AN,scripts:DN,peerDependencies:$N,dependencies:RN,browser:FN};var Ym={};je(Ym,{default:()=>ij,description:()=>MN,devDependencies:()=>HN,jsdelivr:()=>jN,"jsnext:main":()=>GN,license:()=>LN,main:()=>BN,miniprogram:()=>qN,module:()=>WN,name:()=>ON,peerDependencies:()=>XN,private:()=>zN,scripts:()=>KN,types:()=>VN,unpkg:()=>UN,version:()=>PN});var ON="@tensorflow/tfjs-layers",PN="3.7.0",MN="TensorFlow layers API in JavaScript",LN="Apache-2.0 AND MIT",zN=!1,BN="dist/tf-layers.node.js",VN="dist/index.d.ts",GN="dist/index.js",WN="dist/index.js",jN="dist/tf-layers.min.js",UN="dist/tf-layers.min.js",qN="dist/miniprogram",HN={"@babel/polyfill":"^7.8.7","@rollup/plugin-commonjs":"^11.0.2","@rollup/plugin-node-resolve":"^7.1.1","@rollup/plugin-typescript":"^3.0.0","@tensorflow/tfjs-backend-cpu":"3.7.0","@tensorflow/tfjs-backend-webgl":"3.7.0","@tensorflow/tfjs-core":"3.7.0","@types/jasmine":"~2.5.53","clang-format":"~1.2.2","http-server":"~0.12.3",jasmine:"~3.1.0","jasmine-core":"~3.1.0",karma:"~6.3.1","karma-browserstack-launcher":"~1.6.0","karma-chrome-launcher":"~2.2.0","karma-firefox-launcher":"~1.1.0","karma-jasmine":"~1.1.1","karma-typescript":"~5.5.1","karma-typescript-es6-transform":"^5.0.2",rimraf:"~2.6.2",rollup:"~2.3.2","rollup-plugin-terser":"~7.0.2","rollup-plugin-visualizer":"~3.3.2","ts-node":"~8.8.2",tslint:"~6.1.3","tslint-no-circular-imports":"^0.7.0",typescript:"3.5.3",yalc:"~1.0.0-pre.50"},KN={prep:"yarn install && yarn build-ci",build:"tsc && yarn bundle","build-ci":"tsc && yarn bundle-ci",bundle:"rollup -c","bundle-ci":"rollup -c --ci","build-core":"cd ../tfjs-core && yarn && yarn build","build-backend-cpu":"cd ../tfjs-backend-cpu && yarn && yarn build","build-backend-cpu-ci":"cd ../tfjs-backend-cpu && yarn && yarn build-ci","build-backend-webgl":"cd ../tfjs-backend-webgl && yarn && yarn build","build-backend-webgl-ci":"cd ../tfjs-backend-webgl && yarn && yarn build-ci","build-core-ci":"cd ../tfjs-core && yarn && yarn build-ci","build-deps":"yarn build-core && yarn build-backend-cpu && yarn build-backend-webgl","build-deps-ci":"yarn build-core-ci && yarn build-backend-cpu-ci && yarn build-backend-webgl-ci","build-npm":"./scripts/build-npm.sh",format:"./tools/clang_format_ts.sh","link-local":"yalc link","publish-local":"yarn build-npm && yalc push","publish-npm":"npm publish",coverage:"KARMA_COVERAGE=1 karma start --browsers='Chrome' --singleRun",test:"yarn && yarn build-deps && karma start","test-dev":"karma start","test-ci":"./scripts/test-ci.sh","test-snippets":"yarn && yarn build-deps && yarn build && ts-node --skip-ignore -s ./scripts/test_snippets.ts","test-snippets-ci":"ts-node --skip-ignore -s ./scripts/test_snippets.ts","run-browserstack":"karma start --browsers='bs_chrome_mac' --singleRun --reporters='dots,karma-typescript'",lint:"tslint -p . -t verbose"},XN={"@tensorflow/tfjs-core":"3.7.0"},ij={name:ON,version:PN,description:MN,license:LN,private:zN,main:BN,types:VN,"jsnext:main":GN,module:WN,jsdelivr:jN,unpkg:UN,miniprogram:qN,devDependencies:HN,scripts:KN,peerDependencies:XN};var Zm={};je(Zm,{default:()=>aj,description:()=>JN,devDependencies:()=>u1,jsdelivr:()=>o1,"jsnext:main":()=>e1,license:()=>a1,main:()=>QN,miniprogram:()=>s1,module:()=>t1,name:()=>YN,peerDependencies:()=>l1,repository:()=>i1,scripts:()=>c1,types:()=>r1,unpkg:()=>n1,version:()=>ZN});var YN="@tensorflow/tfjs-converter",ZN="3.7.0",JN="Tensorflow model converter for javascript",QN="dist/tf-converter.node.js",e1="dist/index.js",t1="dist/index.js",r1="dist/index.d.ts",n1="dist/tf-converter.min.js",o1="dist/tf-converter.min.js",s1="dist/miniprogram",i1={type:"git",url:"https://github.com/tensorflow/tfjs-converter.git"},a1="Apache-2.0",l1={"@tensorflow/tfjs-core":"3.7.0"},u1={"@rollup/plugin-commonjs":"^11.0.2","@rollup/plugin-node-resolve":"^7.1.1","@rollup/plugin-replace":"^2.3.3","@rollup/plugin-typescript":"^3.0.0","@tensorflow/tfjs-backend-cpu":"3.7.0","@tensorflow/tfjs-core":"3.7.0","@types/argparse":"^1.0.38","@types/deep-equal":"^1.0.1","@types/jasmine":"~2.8.6","@types/long":"~3.0.32","@types/node-fetch":"1.6.9",ajv:"~6.3.0",argparse:"^1.0.10","babel-core":"~6.26.3","babel-plugin-external-helpers":"~6.22.0","babel-preset-env":"~1.7.0","clang-format":"~1.2.2",copyfiles:"~1.2.0","deep-equal":"^1.0.1","jasmine-core":"~3.5.0","node-fetch":"~2.6.1",opn:"~5.1.0",protobufjs:"~6.8.6",rimraf:"~2.6.2",rollup:"~2.3.2","rollup-plugin-terser":"~7.0.2","rollup-plugin-visualizer":"~3.3.2","ts-morph":"^7.1.3","ts-node":"~8.8.2",tslint:"~6.1.3","tslint-no-circular-imports":"~0.7.0",typescript:"3.5.3",yalc:"~1.0.0-pre.50"},c1={build:"yarn gen-json --test && yarn gen-kernel2ops && tsc && yarn bundle","build-ci":"yarn gen-json --test && yarn gen-kernel2ops && tsc && yarn bundle-ci",bundle:"rollup -c","bundle-ci":"rollup -c --ci","build-core":"cd ../tfjs-core && yarn && yarn build","build-backend-cpu":"cd ../tfjs-backend-cpu && yarn && yarn build","build-backend-cpu-ci":"cd ../tfjs-backend-cpu && yarn && yarn build-ci","build-core-ci":"cd ../tfjs-core && yarn && yarn build-ci","build-deps":"yarn build-core && yarn build-backend-cpu","build-deps-ci":"yarn build-core-ci && yarn build-backend-cpu","build-npm":"./scripts/build-npm.sh","link-local":"yalc link","publish-local":"yarn build-npm && yalc push","publish-npm":"npm publish",test:"yarn && yarn build-deps && yarn build && yarn gen-json --test && yarn gen-kernel2ops && ts-node --transpile-only -P tsconfig.test.json src/run_tests.ts","test-ci":"ts-node --transpile-only --skip-ignore -P tsconfig.test.json src/run_tests.ts","test-dev":"tsc && ts-node --transpile-only -P tsconfig.test.json src/run_tests.ts","test-snippets":"yarn && yarn build-deps && yarn build && ts-node --skip-ignore -s ./scripts/test_snippets.ts","test-snippets-ci":"ts-node --skip-ignore -s ./scripts/test_snippets.ts",lint:"tslint -p . -t verbose","make-version":"sh -c ./scripts/make-version","gen-doc":"ts-node -s ./scripts/gen_doc.ts","gen-json":"ts-node -s ./scripts/gen_json.ts","model-summary":"ts-node -s ./tools/model_summary.ts",pb2json:"ts-node -s ./tools/pb2json_converter.ts","build-pip-package":"yarn gen-json --test && cd python && ./build-pip-package.sh --test /tmp/tfjs-pips","run-python-tests":"yarn gen-json --test && cd python && ./run-python-tests.sh","gen-kernel2ops":"ts-node -s scripts/kernels_to_ops.ts --out metadata/kernel2op.json"},aj={name:YN,version:ZN,description:JN,main:QN,"jsnext:main":e1,module:t1,types:r1,unpkg:n1,jsdelivr:o1,miniprogram:s1,repository:i1,license:a1,peerDependencies:l1,devDependencies:u1,scripts:c1};var lj=1e-7,uj=1e-4,al=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}},Xs=class{refCount(e){return eo("refCount")}incRef(e){return eo("incRef")}timerAvailable(){return!0}time(e){return eo("time")}read(e){return eo("read")}readSync(e){return eo("readSync")}numDataIds(){return eo("numDataIds")}disposeData(e,t){return eo("disposeData")}write(e,t,n){return eo("write")}move(e,t,n,o,s){return eo("move")}memory(){return eo("memory")}floatPrecision(){return eo("floatPrecision")}epsilon(){return this.floatPrecision()===32?lj:uj}dispose(){return eo("dispose")}};function eo(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 p1(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 cj(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 zc(r,e,t){return Math.max(r,Math.min(e,t))}function pj(r){return r%2==0?r:r+1}function mj(r){let e=0;for(let t=0;t<r.length;t++)e+=r[t];return e}function fj(r,e){let t=Math.random();return e*t+(1-t)*r}function dj(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 E(r,e){if(!r)throw new Error(typeof e=="string"?e:e())}function $t(r,e,t=""){E(en(r,e),()=>t+` Shapes ${r} and ${e} must match`)}function Wn(r){E(r!=null,()=>"The input to the tensor constructor must be a non-null value.")}function Ao(r,e=[],t=!1){if(e==null&&(e=[]),Array.isArray(r)||pr(r)&&!t)for(let n=0;n<r.length;++n)Ao(r[n],e,t);else e.push(r);return e}function ot(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 hj(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 st(r){return r%1==0}function gj(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 xj(r){let e=Math.ceil(Math.sqrt(r));return[e,Math.ceil(r/e)]}function yj(r){let e=new Uint32Array(r);for(let t=0;t<r;++t)e[t]=t;return p1(e),e}function ou(r,e){return e<=r.length?r:r+" ".repeat(e-r.length)}function bj(r,e=n=>0,t){return new Promise((n,o)=>{let s=0,a=()=>{if(r()){n();return}s++;let i=e(s);if(t!=null&&s>=t){o();return}setTimeout(a,i)};a()})}function wj(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 ar(r,e){let t=e.length;return r=r==null?e.map((n,o)=>o):[].concat(r),E(r.every(n=>n>=-t&&n<t),()=>`All values in axis param must be in range [-${t}, ${t}) but got axis ${r}`),E(r.every(n=>st(n)),()=>`All values in axis param must be integers but got axis ${r}`),r.map(n=>n<0?t+n:n)}function Pw(r,e){let t=[],n=[],o=e!=null&&Array.isArray(e)&&e.length===0,s=e==null||o?null:ar(e,r).sort(),a=0;for(let i=0;i<r.length;++i){if(s!=null){if(s[a]===i&&r[i]!==1)throw new Error(`Can't squeeze axis ${i} since its dim '${r[i]}' is not 1`);(s[a]==null||s[a]>i)&&r[i]===1&&(t.push(r[i]),n.push(i)),s[a]<=i&&a++}r[i]!==1&&(t.push(r[i]),n.push(i))}return{newShape:t,keptDims:n}}function Mw(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 Lw(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 zw(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 _j(r,e){return!(e==="complex64"||e==="float32"&&r!=="complex64"||e==="int32"&&r!=="float32"&&r!=="complex64"||e==="bool"&&r==="bool")}function pr(r){return r instanceof Float32Array||r instanceof Int32Array||r instanceof Uint8Array}function Sg(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 Vw(r){if(r==null)return 0;let e=0;return r.forEach(t=>e+=t.length),e}function Do(r){return typeof r=="string"||r instanceof String}function m1(r){return typeof r=="boolean"}function f1(r){return typeof r=="number"}function Bc(r){return Array.isArray(r)?Bc(r[0]):r instanceof Float32Array?"float32":r instanceof Int32Array||r instanceof Uint8Array?"int32":f1(r)?"float32":Do(r)?"string":m1(r)?"bool":"float32"}function Ys(r){return!!(r&&r.constructor&&r.call&&r.apply)}function Vc(r,e){for(let t=e;t<r;++t)if(r%t==0)return t;return r}function Zs(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 d1(r,e,t,n=!1){let o=new Array;if(e.length===1){let s=e[0]*(n?2:1);for(let a=0;a<s;a++)o[a]=t[r+a]}else{let s=e[0],a=e.slice(1),i=a.reduce((l,u)=>l*u)*(n?2:1);for(let l=0;l<s;l++)o[l]=d1(r+l*i,a,t,n)}return o}function su(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 d1(0,r,e,t)}function Jm(r,e){let t=Gc(r,e);for(let n=0;n<t.length;n++)t[n]=1;return t}function Gc(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 kj(r,e){let t=r.reduce((n,o)=>n*o,1);if(e==null||e==="float32")return su(r,new Float32Array(t));if(e==="int32")return su(r,new Int32Array(t));if(e==="bool")return su(r,new Uint8Array(t));throw new Error(`Unknown data type ${e}`)}function Qm(r){r.forEach(e=>{E(Number.isInteger(e)&&e>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${r}].`)})}function vj(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 Cj(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 ef(r){return r&&r.then&&typeof r.then=="function"}var h1="tfjsflags",Ng=class{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=Ij,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(ef(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);h1 in e&&e[h1].split(",").forEach(n=>{let[o,s]=n.split(":");this.urlFlags[o]=Nj(o,s)})}};function Ij(r){let e={};return r.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(t,...n)=>(Sj(e,n[0],n[1]),n.join("="))),e}function Sj(r,e,t){r[decodeURIComponent(e)]=decodeURIComponent(t||"")}function Nj(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 W(){return Gw}var Gw=null;function g1(r){Gw=r}var Ww;function jw(){if(Ww==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");Ww=r}return Ww}function Tj(){let r=jw();return r._tfGlobals==null&&(r._tfGlobals=new Map),r._tfGlobals}function tf(r,e){let t=Tj();if(t.has(r))return t.get(r);{let n=e();return t.set(r,n),t.get(r)}}var Js="Abs",Ri="Acos",Fi="Acosh",jn="Add",$o="AddN",Oi="All",Pi="Any",Ro="ArgMax",ll="ArgMin",Mi="Asin",Li="Asinh",zi="Atan",Bi="Atanh",Vi="Atan2",Fo="AvgPool",Wc="AvgPoolGrad",ul="AvgPool3D",jc="AvgPool3DGrad",Oo="BatchMatMul",cl="BatchToSpaceND",Uc="Bincount",x1="BroadcastTo",to="Cast",Po="Ceil",ro="ClipByValue",qc="Complex",pl="ComplexAbs",Qs="Concat",Mo="Conv2D",Hc="Conv2DBackpropFilter",Lo="Conv2DBackpropInput",ml="Conv3D",Kc="Conv3DBackpropFilterV2",Xc="Conv3DBackpropInputV2",zo="Cos",Gi="Cosh",Bo="Cumsum",Wi="CropAndResize",Yc="DenseBincount",ji="DepthToSpace",Vo="DepthwiseConv2dNative",Zc="DepthwiseConv2dNativeBackpropFilter",Jc="DepthwiseConv2dNativeBackpropInput",Qc="Diag",fl="Dilation2D",rf="Dilation2DBackpropInput",nf="Dilation2DBackpropFilter",Go="RealDiv",ep="Einsum",Ui="Elu",tp="EluGrad",qi="Erf",Hi="Equal",Wo="Exp",ei="ExpandDims",Ki="Expm1",rp="FFT",dl="Fill",Xi="FlipLeftRight",jo="Floor",Uo="FloorDiv",qo="FusedBatchNorm",ti="GatherV2",Yi="GatherNd",Zi="Greater",Ho="GreaterEqual",no="Identity",np="IFFT",op="Imag",Ji="IsFinite",Qi="IsInf",ea="IsNan",Ko="LeakyRelu",ta="Less",ra="LessEqual",sp="LinSpace",Xo="Log",na="Log1p",oa="LogicalAnd",iu="LogicalNot",au="LogicalOr",y1="LogSoftmax",hl="LRN",ip="LRNGrad",Yo="Max",Zo="Maximum",Jo="MaxPool",ap="MaxPoolGrad",gl="MaxPool3D",lp="MaxPool3DGrad",up="MaxPoolWithArgmax",Qo="Mean",es="Min",ts="Minimum",rs="MirrorPad",sa="Mod",cp="Multinomial",ns="Multiply",ri="Neg",ia="NotEqual",aa="NonMaxSuppressionV3",la="NonMaxSuppressionV4",ua="NonMaxSuppressionV5",ni="OnesLike",os="OneHot",oi="Pack",ss="PadV2",Xse="Pool",is="Pow",as="Prelu",ca="Prod",xl="Range",pp="Real",pa="Reciprocal",ls="Relu",si="Reshape",yl="ResizeNearestNeighbor",mp="ResizeNearestNeighborGrad",us="ResizeBilinear",fp="ResizeBilinearGrad",cs="Relu6",ps="Reverse",ms="Round",fs="Rsqrt",ma="ScatterNd",ii="Select",fa="Selu",ai="Slice",ds="Sin",da="Sinh",ha="Sign",hs="Sigmoid",ga="Softplus",gs="Sqrt",xs="Sum",bl="SpaceToBatchND",li="SplitV",ys="Softmax",dp="SparseFillEmptyRows",hp="SparseReshape",gp="SparseSegmentMean",xp="SparseSegmentSum",yp="SparseToDense",bs="SquaredDifference",wl="Square",xa="StridedSlice",bp="StringNGrams",wp="StringSplit",_p="StringToHashBucketFast",ws="Sub",_s="Tan",ks="Tanh",Un="Tile",ya="TopK",ba="Transform",vs="Transpose",kp="Unique",ui="Unpack",_l="UnsortedSegmentSum",ci="ZerosLike",oo="Step",of="FromPixels",wa="RotateWithOffset",pi="_FusedMatMul",mi="FusedConv2D",fi="FusedDepthwiseConv2D";var vp=tf("kernelRegistry",()=>new Map),sf=tf("gradRegistry",()=>new Map);function af(r,e){let t=qw(r,e);return vp.get(t)}function Uw(r){return sf.get(r)}function Tg(r){let e=vp.entries(),t=[];for(;;){let{done:n,value:o}=e.next();if(n)break;let[s,a]=o,[i]=s.split("_");i===r&&t.push(a)}return t}function lu(r){let{kernelName:e,backendName:t}=r,n=qw(e,t);vp.has(n)&&console.warn(`The kernel '${e}' for backend '${t}' is already registered`),vp.set(n,r)}function b1(r){let{kernelName:e}=r;sf.has(e)&&W().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${e}'`),sf.set(e,r)}function Qse(r,e){let t=qw(r,e);if(!vp.has(t))throw new Error(`The kernel '${r}' for backend '${e}' is not registered`);vp.delete(t)}function eie(r){if(!sf.has(r))throw new Error(`The gradient '${r}' for backend is not registered`);sf.delete(r)}function tie(r,e){Tg(r).forEach(n=>{let o=Object.assign({},n,{backendName:e});lu(o)})}function qw(r,e){return`${e}_${r}`}var y={};je(y,{arraysEqual:()=>en,assert:()=>E,assertNonNegativeIntegerDimensions:()=>Qm,assertNonNull:()=>Wn,assertShapesMatch:()=>$t,bytesFromStringArray:()=>Vw,bytesPerElement:()=>Sg,checkConversionForErrors:()=>zw,clamp:()=>zc,computeStrides:()=>Zs,createScalarValue:()=>Oj,createShuffledIndices:()=>yj,decodeString:()=>Np,distSquared:()=>dj,encodeString:()=>vl,fetch:()=>Mj,fingerPrint64:()=>Fj,flatten:()=>Ao,getArrayFromDType:()=>Lw,getTypedArrayFromDType:()=>Mw,hasEncodingLoss:()=>_j,hexToLong:()=>lf,indexToLoc:()=>Cj,inferDtype:()=>Bc,inferFromImplicitShape:()=>wj,isBoolean:()=>m1,isFunction:()=>Ys,isInt:()=>st,isNumber:()=>f1,isPromise:()=>ef,isScalarShape:()=>hj,isString:()=>Do,isTypedArray:()=>pr,isValidDtype:()=>Bw,locToIndex:()=>vj,makeOnesTypedArray:()=>Jm,makeZerosNestedTypedArray:()=>kj,makeZerosTypedArray:()=>Gc,nearestDivisor:()=>Vc,nearestLargerEven:()=>pj,now:()=>fu,parseAxisParam:()=>ar,randUniform:()=>fj,repeatedTry:()=>bj,rightPad:()=>ou,shuffle:()=>p1,shuffleCombo:()=>cj,sizeFromShape:()=>ot,sizeToSquarishShape:()=>xj,squeezeShape:()=>Pw,sum:()=>mj,tanh:()=>gj,toNestedArray:()=>su,toTypedArray:()=>Sp});var D1=nu(A1());var pu=D1.default||D1;function lf(r){return pu.fromString(r,!0,16)}var $1=lf("c3a5c85c97cb3127"),mu=lf("b492b66fbe98f273"),tn=lf("9ae16a3b2f90404f");function Xw(r){return r.xor(r.shru(47))}function R1(r,e,t){let n=r.slice(e,e+t);return pu.fromBytes(Array.from(n),!0,!0)}function Mt(r,e){return R1(r,e,8)}function F1(r,e){return R1(r,e,4)}function Sr(r,e){return e===0?r:r.shru(e).or(r.shl(64-e))}function kl(r,e,t=lf("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 Aj(r,e,t,n,o,s){o=o.add(r),s=Sr(s.add(o).add(n),21);let a=o;return o=o.add(e),o=o.add(t),s=s.add(Sr(o,44)),[o.add(n),s.add(a)]}function Ag(r,e,t,n){return Aj(Mt(r,e),Mt(r,e+8),Mt(r,e+16),Mt(r,e+24),t,n)}function Dj(r,e=r.length){if(e>=8){let t=tn.add(e*2),n=Mt(r,0).add(tn),o=Mt(r,e-8),s=Sr(o,37).mul(t).add(n),a=Sr(n,25).add(o).mul(t);return kl(s,a,t)}if(e>=4){let t=tn.add(e*2),n=F1(r,0);return kl(n.shl(3).add(e),F1(r,e-4),t)}if(e>0){let t=r[0],n=r[e>>1],o=r[e-1],s=t+(n<<8),a=e+(o<<2);return Xw(tn.mul(s).xor($1.mul(a))).mul(tn)}return tn}function $j(r,e=r.length){let t=tn.add(e*2),n=Mt(r,0).mul(mu),o=Mt(r,8),s=Mt(r,e-8).mul(t),a=Mt(r,e-16).mul(tn);return kl(Sr(n.add(o),43).add(Sr(s,30)).add(a),n.add(Sr(o.add(tn),18)).add(s),t)}function Rj(r,e=r.length){let t=tn.add(e*2),n=Mt(r,0).mul(tn),o=Mt(r,8),s=Mt(r,e-8).mul(t),a=Mt(r,e-16).mul(tn),i=Sr(n.add(o),43).add(Sr(s,30)).add(a),l=kl(i,n.add(Sr(o.add(tn),18)).add(s),t),u=Mt(r,16).mul(t),c=Mt(r,24),p=i.add(Mt(r,e-32)).mul(t),m=l.add(Mt(r,e-24)).mul(t);return kl(Sr(u.add(c),43).add(Sr(p,30)).add(m),u.add(Sr(c.add(n),18)).add(p),t)}function Fj(r,e=r.length){let t=pu.fromNumber(81,!0);if(e<=32)return e<=16?Dj(r,e):$j(r,e);if(e<=64)return Rj(r,e);let n=t,o=t.mul(mu).add(113),s=Xw(o.mul(tn).add(113)).mul(tn),a=[pu.UZERO,pu.UZERO],i=[pu.UZERO,pu.UZERO];n=n.mul(tn).add(Mt(r,0));let l=0,u=(e-1>>6)*64,c=u+(e-1&63)-63;do n=Sr(n.add(o).add(a[0]).add(Mt(r,l+8)),37).mul(mu),o=Sr(o.add(a[1]).add(Mt(r,l+48)),42).mul(mu),n=n.xor(i[1]),o=o.add(a[0]).add(Mt(r,l+40)),s=Sr(s.add(i[0]),33).mul(mu),a=Ag(r,l,a[1].mul(mu),n.add(i[0])),i=Ag(r,l+32,s.add(i[1]),o.add(Mt(r,l+16))),[s,n]=[n,s],l+=64;while(l!==u);let p=mu.add(s.and(255).shl(1));return l=c,i[0]=i[0].add(e-1&63),a[0]=a[0].add(i[0]),i[0]=i[0].add(a[0]),n=Sr(n.add(o).add(a[0]).add(Mt(r,l+8)),37).mul(p),o=Sr(o.add(a[1]).add(Mt(r,l+48)),42).mul(p),n=n.xor(i[1].mul(9)),o=o.add(a[0].mul(9).add(Mt(r,l+40))),s=Sr(s.add(i[0]),33).mul(p),a=Ag(r,l,a[1].mul(p),n.add(i[0])),i=Ag(r,l+32,s.add(i[1]),o.add(Mt(r,l+16))),[s,n]=[n,s],kl(kl(a[0],i[0],p).add(Xw(o).mul($1)).add(s),kl(a[1],i[1],p).add(n),p)}function Oj(r,e){return e==="string"?vl(r):Sp([r],e)}function Pj(r,e){return r instanceof Float32Array&&e==="float32"||r instanceof Int32Array&&e==="int32"||r instanceof Uint8Array&&e==="bool"}function Sp(r,e){if(e==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(r)&&(r=Ao(r)),W().getBool("DEBUG")&&zw(r,e),Pj(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 fu(){return W().platform.now()}function Mj(r,e){return W().platform.fetch(r,e)}function vl(r,e="utf-8"){return e=e||"utf-8",W().platform.encode(r,e)}function Np(r,e="utf-8"){return e=e||"utf-8",W().platform.decode(r,e)}var Yw=class{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new O1)}profileKernel(e,t,n){let o,s=()=>{o=n()},a,i=fu();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(s);else{s();for(let u of o)u.dataSync();a=Promise.resolve({kernelMs:fu()-i})}if(W().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let u=0;u<o.length;u++){let c=o[u];c.data().then(p=>{Lj(p,c.dtype,e)})}return{kernelName:e,outputs:o,inputs:t,timeMs:a.then(u=>u.kernelMs),extraInfo:a.then(u=>u.getExtraProfileInfo!=null?u.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:n,timeMs:o,inputs:s,extraInfo:a}=e;n.forEach(i=>{Promise.all([i.data(),o,a]).then(l=>{this.logger.logKernelProfile(t,i,l[0],l[1],s,l[2])})})}};function Lj(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 O1=class{logKernelProfile(e,t,n,o,s,a){let i=typeof o=="number"?ou(`${o}ms`,9):o.error,l=ou(e,25),u=t.rank,c=t.size,p=ou(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${i} %c${u}D ${p} %c${c} %c${m} %c${a}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function P1(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],c=u.inputs;for(let p in c){let m=c[p],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 a={};for(let l=r.length-1;l>=0;l--){let u=r[l],c=u.inputs;for(let p=0;p<u.outputs.length;p++)if(s[u.outputs[p].id]){for(let m in c)s[c[m].id]=!0,a[u.id]=!0;break}}let i=[];for(let l=0;l<r.length;l++){let u=r[l];if(o[u.id]&&a[u.id]){let c={};for(let m in u.inputs){let f=u.inputs[m];n[f.id]&&(c[m]=f)}let p=Object.assign({},u);p.inputs=c,p.outputs=u.outputs,i.push(p)}}return i}function M1(r,e,t,n){for(let o=e.length-1;o>=0;o--){let s=e[o],a=[];if(s.outputs.forEach(l=>{let u=r[l.id];u!=null?a.push(u):a.push(null)}),s.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);let i=s.gradient(a);for(let l in s.inputs){if(!(l in i))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(i)}.`);let u=t(()=>i[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 c=s.inputs[l];if(!en(u.shape,c.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 '${c.shape}'`);if(r[c.id]==null)r[c.id]=u;else{let p=r[c.id];r[c.id]=n(p,u),p.dispose()}}}}var L1=20,uf=3,Zw=7;function z1(r,e,t,n){let o=Zs(e),s=zj(r,e,t,o),a=e.length,i=Dg(r,e,t,o,s),l=["Tensor"];return n&&(l.push(` dtype: ${t}`),l.push(` rank: ${a}`),l.push(` shape: [${e}]`),l.push(" values:")),l.push(i.map(u=>" "+u).join(`
|
|
`)),l.join(`
|
|
`)}function zj(r,e,t,n){let o=ot(e),s=n[n.length-1],a=new Array(s).fill(0),i=e.length,l=t==="complex64"?pf(r):r;if(i>1)for(let u=0;u<o/s;u++){let c=u*s;for(let p=0;p<s;p++)a[p]=Math.max(a[p],cf(l[c+p],0,t).length)}return a}function cf(r,e,t){let n;return Array.isArray(r)?n=`${parseFloat(r[0].toFixed(Zw))} + ${parseFloat(r[1].toFixed(Zw))}j`:Do(r)?n=`'${r}'`:t==="bool"?n=B1(r):n=parseFloat(r.toFixed(Zw)).toString(),ou(n,e)}function B1(r){return r===0?"false":"true"}function Dg(r,e,t,n,o,s=!0){let a=t==="complex64"?2:1,i=e[0],l=e.length;if(l===0){if(t==="complex64"){let h=pf(r);return[cf(h[0],0,t)]}return t==="bool"?[B1(r[0])]:[r[0].toString()]}if(l===1){if(i>L1){let g=uf*a,x=Array.from(r.slice(0,g)),b=Array.from(r.slice((i-uf)*a,i*a));return t==="complex64"&&(x=pf(x),b=pf(b)),["["+x.map((w,_)=>cf(w,o[_],t)).join(", ")+", ..., "+b.map((w,_)=>cf(w,o[i-uf+_],t)).join(", ")+"]"]}let h=t==="complex64"?pf(r):Array.from(r);return["["+h.map((g,x)=>cf(g,o[x],t)).join(", ")+"]"]}let u=e.slice(1),c=n.slice(1),p=n[0]*a,m=[];if(i>L1){for(let h=0;h<uf;h++){let g=h*p,x=g+p;m.push(...Dg(r.slice(g,x),u,t,c,o,!1))}m.push("...");for(let h=i-uf;h<i;h++){let g=h*p,x=g+p;m.push(...Dg(r.slice(g,x),u,t,c,o,h===i-1))}}else for(let h=0;h<i;h++){let g=h*p,x=g+p;m.push(...Dg(r.slice(g,x),u,t,c,o,h===i-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 pf(r){let e=[];for(let t=0;t<r.length;t+=2)e.push([r[t],r[t+1]]);return e}var ct=class{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=ot(e),n!=null){let o=n.length;E(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||Lw(t,this.size),this.strides=Zs(e)}set(e,...t){t.length===0&&(t=[0]),E(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 di().makeTensor(this.values,this.shape,this.dtype)}},di=null,Tp=null,Bj=null;function V1(r){di=r}function G1(r){Tp=r}function W1(r){Bj=r}var Me=class{constructor(e,t,n,o){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=ot(e),this.strides=Zs(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 Tp.buffer(this.shape,this.dtype,e)}bufferSync(){return Tp.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return su(this.shape,e,this.dtype==="complex64")}arraySync(){return su(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();let e=di().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(n=>Np(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=di().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Np(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 di().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(di().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Tp.print(this,e)}clone(){return this.throwIfDisposed(),Tp.clone(this)}toString(e=!1){let t=this.dataSync();return z1(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Tp.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),di().makeVariable(this,e,t,n)}};Object.defineProperty(Me,Symbol.hasInstance,{value:r=>!!r&&r.data!=null&&r.dataSync!=null&&r.throwIfDisposed!=null});function O(){return tf("Tensor",()=>Me)}O();var Cl=class extends Me{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`);di().disposeTensor(this),this.dataId=e.dataId,di().incRef(this,null)}dispose(){di().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(Cl,Symbol.hasInstance,{value:r=>r instanceof Me&&r.assign!=null&&r.assign instanceof Function});var lo={};je(lo,{assertTypesMatch:()=>n_,getTensorsInContainer:()=>mf,isTensorInList:()=>Gj,makeTypesMatch:()=>Ue});var Jw;(function(r){r.R0="R0",r.R1="R1",r.R2="R2",r.R3="R3",r.R4="R4",r.R5="R5",r.R6="R6"})(Jw||(Jw={}));var Qw;(function(r){r.float32="float32",r.int32="int32",r.bool="int32",r.complex64="complex64"})(Qw||(Qw={}));var e_;(function(r){r.float32="float32",r.int32="int32",r.bool="bool",r.complex64="complex64"})(e_||(e_={}));var t_;(function(r){r.float32="float32",r.int32="float32",r.bool="float32",r.complex64="complex64"})(t_||(t_={}));var r_;(function(r){r.float32="complex64",r.int32="complex64",r.bool="complex64",r.complex64="complex64"})(r_||(r_={}));var Vj={float32:t_,int32:Qw,bool:e_,complex64:r_};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 Vj[r][e]}function du(r){return mr(r,"int32")}function Ue(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 n_(r,e){E(r.dtype===e.dtype,()=>`The dtypes of the first(${r.dtype}) and second(${e.dtype}) input must match`)}function Gj(r,e){return e.some(t=>t.id===r.id)}function mf(r){let e=[],t=new Set;return j1(r,e,t),e}function j1(r,e,t){if(r==null)return;if(r instanceof Me){e.push(r);return}if(!Wj(r))return;let n=r;for(let o in n){let s=n[o];t.has(s)||(t.add(s),j1(s,e,t))}}function Wj(r){return Array.isArray(r)||typeof r=="object"}function o_(r){return r.kernelName!=null}var s_=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()}},hu=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new s_}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 Yw(this.backendInstance),!0}setupRegisteredKernels(){Tg(this.backendName).forEach(t=>{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){Tg(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 Xs)&&typeof n.then=="function"){let o=++this.pendingBackendInitId,s=n.then(a=>o<this.pendingBackendInitId?!1:(this.registry[e]=a,this.pendingBackendInit=null,!0)).catch(a=>(o<this.pendingBackendInitId||(this.pendingBackendInit=null,console.warn(`Initialization of backend ${e} failed`),console.warn(a.stack||a.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),a=o.refCount(t);o.disposeData(t,!0),n.backend=e,e.move(t,s,n.shape,n.dtype,a),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 hu.nextTensorId++}nextVariableId(){return hu.nextVariableId++}clone(e){let t=T.runKernel(no,{x:e}),n={x:e},o=a=>({x:()=>{let i="float32",l={x:a},u={dtype:i};return T.runKernel(to,l,u)}}),s=[];return this.addTapeNode(this.state.activeScope.name,n,[t],o,s,{}),t}runKernel(e,t,n){if(!(af(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 a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=o-t-s-a;if(i>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${i} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[],o=this.isTapeOn(),s=this.state.numBytes,a=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let i;this.backendName==null&&this.backend;let l,u=o_(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(o_(e)){let{kernelName:d,inputs:h,attrs:g}=e;this.backendName==null&&this.backend;let x=af(d,this.backendName);E(x!=null,()=>`Cannot find registered kernel '${d}' for backend '${this.backendName}'`),i=()=>{let b=this.backend.numDataIds();l=x.kernelFunc({inputs:h,attrs:g,backend:this.backend});let w=Array.isArray(l)?l:[l];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(d,b,w);let _=w.map(C=>{if(C.rank!=null)return C;let{dataId:A,shape:D,dtype:$}=C;return this.makeTensorFromDataId(A,D,$)});if(o){let C=this.getTensorsForGradient(d,h,_);n=this.saveTensorsForBackwardMode(C)}return _}}else{let{forwardFunc:d}=e,h=g=>{!o||(n=g.map(x=>this.keep(this.clone(x))))};i=()=>{let g=this.backend.numDataIds();l=this.tidy(()=>d(this.backend,h));let x=Array.isArray(l)?l:[l];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(u,g,x),x}}let{inputs:c,attrs:p}=e,m=o_(e)?null:e.backwardsFunc,f;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=i():(f=this.profiler.profileKernel(u,c,()=>i()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(f),t=f.outputs)}),o&&this.addTapeNode(u,c,t,m,n,p),this.state.profiling&&this.state.activeProfile.kernels.push({name:u,bytesAdded:this.state.numBytes-s,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-a,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(c).map(d=>c[d]!=null?c[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=Uw(e);if(o!=null){let s=o.inputsToSave||[],a=o.outputsToSave||[],i;o.saveAllInputs?(E(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),i=Object.keys(t).map(u=>t[u])):i=s.map(u=>t[u]);let l=n.filter((u,c)=>a[c]);return i.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"&&Do(e[0])&&(s=e.map(l=>vl(l)));let a=o.write(s,t,n),i=new Me(t,n,a,this.nextTensorId());if(this.trackTensor(i,o),n==="string"){let l=this.state.tensorInfo.get(a),u=Vw(s);this.state.numBytes+=u-l.bytes,l.bytes=u}return i}makeTensorFromDataId(e,t,n,o){n=n||"float32";let s=new Me(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 Cl(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*Sg(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 Cl||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*Sg(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,a){let i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:s},l=Uw(e);l!=null&&(o=l.gradFunc),o!=null&&(i.gradient=u=>(u=u.map((c,p)=>{if(c==null){let m=n[p],f=Gc(m.size,m.dtype);return this.makeTensor(f,m.shape,m.dtype)}return c}),o(u.length>1?u:u[0],s,a))),this.state.activeTape.push(i)}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=mf(e),n=new Set(t.map(s=>s.id));for(let s=0;s<this.state.activeScope.track.length;s++){let a=this.state.activeScope.track[s];!a.kept&&!n.has(a.id)&&a.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(E(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));E(s instanceof Me,()=>"The result y returned by f() must be a tensor.");let a=P1(this.state.activeTape,t,s);if(!o&&a.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 i={};i[s.id]=n==null?jj(s.shape):n,M1(i,a,u=>this.tidy(u),Uj);let l=t.map(u=>i[u.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(u=>{for(let c of u.saved)c.dispose()}),this.state.activeTape=null),{value:s,grads:l}})}customGrad(e){return E(Ys(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{E(t.every(i=>i instanceof Me),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n,o={};t.forEach((i,l)=>{o[l]=i});let s=(i,l)=>(n=e(...t,l),E(n.value instanceof Me,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),E(Ys(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),a=(i,l)=>{let u=n.gradFunc(i,l),c=Array.isArray(u)?u:[u];E(c.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),E(c.every(m=>m instanceof Me),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");let p={};return c.forEach((m,f)=>{p[f]=()=>m}),p};return this.runKernelFunc({forwardFunc:s,backwardsFunc:a,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=fu(),n=await this.backend.time(e);return n.wallMs=fu()-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 s_;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}};hu.nextTensorId=0;hu.nextVariableId=0;function jj(r){let e=Jm(ot(r),"float32");return T.makeTensor(e,r,"float32")}function i_(){let r=jw();if(r._tfengine==null){let e=new Ng(r);r._tfengine=new hu(e)}return g1(r._tfengine.ENV),V1(()=>r._tfengine),r._tfengine}var T=i_();function Uj(r,e){let t={a:r,b:e};return T.runKernel(jn,t)}var gu={};je(gu,{isBrowser:()=>a_,isMobile:()=>Hj});function qj(){return typeof navigator!="undefined"&&navigator!=null}function Hj(r){if(r||qj()){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 a_(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var Is=W();Is.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.")});Is.registerFlag("IS_BROWSER",()=>a_());Is.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Is.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Is.registerFlag("PROD",()=>!1);Is.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Is.getBool("DEBUG"));Is.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Is.registerFlag("IS_TEST",()=>!1);Is.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);Is.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);function Fr(r,e){let t=r;if(pr(r))return e==="string"?[]:[r.length];if(!Array.isArray(r))return[];let n=[];for(;Array.isArray(t)||pr(t)&&e!=="string";)n.push(t.length),t=t[0];return Array.isArray(r)&&W().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&U1(r,n,[]),n}function U1(r,e,t){if(t=t||[],!Array.isArray(r)&&!pr(r)){E(e.length===0,()=>`Element arr[${t.join("][")}] is a primitive, but should be an array/TypedArray of ${e[0]} elements`);return}E(e.length>0,()=>`Element arr[${t.join("][")}] should be a primitive, but is an array of ${r.length} elements`),E(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)U1(r[o],n,t.concat(o))}function q1(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 k(r,e,t,n="numeric"){if(r instanceof Me)return q1(n,r.dtype,e,t),r;let o=Bc(r);if(o!=="string"&&["bool","int32","float32"].indexOf(n)>=0&&(o=n),q1(n,o,e,t),r==null||!pr(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=Fr(r,o);!pr(r)&&!Array.isArray(r)&&(r=[r]);let i=o!=="string"?Sp(r,o):Ao(r,[],!0);return T.makeTensor(i,s,o)}function _a(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,a)=>k(s,`${e}[${a}]`,t,n))}var H1="__op";function S(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+H1;let o=(...s)=>{T.startScope(t);try{let a=n(...s);return ef(a)&&console.error("Cannot return a Promise inside of tidy."),T.endScope(a),a}catch(a){throw T.endScope(null),a}};return Object.defineProperty(o,"name",{value:t,configurable:!0}),o}function Kj(r,e){let t=k(r,"real","complex"),n=k(e,"imag","complex");$t(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 T.runKernel(qc,o)}var Fn=S({complex_:Kj});function rn(r,e,t,n){if(n==null&&(n=Bc(r)),n==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!pr(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){Qm(e);let o=ot(e),s=ot(t);E(o===s,()=>`Based on the provided shape, [${e}], the tensor should have ${o} values but has ${s}`);for(let a=0;a<t.length;++a){let i=t[a],l=a===t.length-1?i!==ot(e.slice(a)):!0;E(t[a]===e[a]||!l,()=>`Error creating a new Tensor. Inferred shape (${t}) does not match the provided shape (${e}). `)}}return!pr(r)&&!Array.isArray(r)&&(r=[r]),e=e||t,r=n!=="string"?Sp(r,n):Ao(r,[],!0),T.makeTensor(r,e,n)}function Nr(r,e,t){let n=Fr(r,t);return rn(r,e,n,t)}var ff={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};var $g=4;async function K1(r,e){let t=[],n=[],o=Array.isArray(r)?r.map(a=>a.name):Object.keys(r);for(let a=0;a<o.length;++a){let i=o[a],l=Array.isArray(r)?r[a].tensor:r[i];if(l.dtype!=="float32"&&l.dtype!=="int32"&&l.dtype!=="bool"&&l.dtype!=="string"&&l.dtype!=="complex64")throw new Error(`Unsupported dtype in weight '${i}': ${l.dtype}`);let u={name:i,shape:l.shape,dtype:l.dtype};if(l.dtype==="string"){let c=new Promise(async p=>{let m=await l.bytes(),f=m.reduce((g,x)=>g+x.length,0)+$g*m.length,d=new Uint8Array(f),h=0;for(let g=0;g<m.length;g++){let x=m[g],b=new Uint8Array(new Uint32Array([x.length]).buffer);d.set(b,h),h+=$g,d.set(x,h),h+=x.length}p(d)});n.push(c)}else n.push(l.data());e!=null&&(u.group=e),t.push(u)}let s=await Promise.all(n);return{data:Xj(s),specs:t}}function Rg(r,e){let t={},n,o=0;for(let s of e){let a=s.name,i=s.dtype,l=s.shape,u=ot(l),c;if("quantization"in s){let p=s.quantization;if(p.dtype==="uint8"||p.dtype==="uint16"){if(!("min"in p&&"scale"in p))throw new Error(`Weight ${s.name} with quantization ${p.dtype} doesn't have corresponding metadata min and scale.`)}else if(p.dtype==="float16"){if(i!=="float32")throw new Error(`Weight ${s.name} is quantized with ${p.dtype} which only supports weights of type float32 not ${i}.`)}else throw new Error(`Weight ${s.name} has unknown quantization dtype ${p.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);let m=ff[p.dtype],f=r.slice(o,o+u*m),d=p.dtype==="uint8"?new Uint8Array(f):new Uint16Array(f);if(i==="float32")if(p.dtype==="uint8"||p.dtype==="uint16"){c=new Float32Array(d.length);for(let h=0;h<d.length;h++){let g=d[h];c[h]=g*p.scale+p.min}}else if(p.dtype==="float16")n===void 0&&(n=Qj()),c=n(d);else throw new Error(`Unsupported quantization type ${p.dtype} for weight type float32.`);else if(i==="int32"){if(p.dtype!=="uint8"&&p.dtype!=="uint16")throw new Error(`Unsupported quantization type ${p.dtype} for weight type int32.`);c=new Int32Array(d.length);for(let h=0;h<d.length;h++){let g=d[h];c[h]=Math.round(g*p.scale+p.min)}}else throw new Error(`Unsupported dtype in weight '${a}': ${i}`);o+=u*m}else if(i==="string"){let p=ot(s.shape);c=[];for(let m=0;m<p;m++){let f=new Uint32Array(r.slice(o,o+$g))[0];o+=$g;let d=new Uint8Array(r.slice(o,o+f));c.push(d),o+=f}}else{let p=ff[i],m=r.slice(o,o+u*p);if(i==="float32")c=new Float32Array(m);else if(i==="int32")c=new Int32Array(m);else if(i==="bool")c=new Uint8Array(m);else if(i==="complex64"){c=new Float32Array(m);let f=new Float32Array(c.length/2),d=new Float32Array(c.length/2);for(let x=0;x<f.length;x++)f[x]=c[x*2],d[x]=c[x*2+1];let h=Nr(f,l,"float32"),g=Nr(d,l,"float32");t[a]=Fn(h,g),h.dispose(),g.dispose()}else throw new Error(`Unsupported dtype in weight '${a}': ${i}`);o+=u*p}i!=="complex64"&&(t[a]=Nr(c,l,i))}return t}function Xj(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 l_=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function X1(r){return l_?Buffer.byteLength(r):new Blob([r]).size}function Y1(r){if(l_)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 Z1(r){if(l_){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 Ep(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 u_(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 hi(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:X1(JSON.stringify(r.modelTopology)),weightSpecsBytes:r.weightSpecs==null?0:X1(JSON.stringify(r.weightSpecs)),weightDataBytes:r.weightData==null?0:r.weightData.byteLength}}function Yj(){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 Zj(){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 Jj(){let r=new Uint32Array(64);for(let e=0;e<64;e++)r[e]=1024;return r[0]=r[32]=0,r}function Qj(){let r=Yj(),e=Zj(),t=Jj();return n=>{let o=new ArrayBuffer(4*n.length),s=new Uint32Array(o);for(let a=0;a<n.length;a++){let i=n[a],l=r[t[i>>10]+(i&1023)]+e[i>>10];s[a]=l}return new Float32Array(o)}}var Nt=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Nt.instance==null&&(Nt.instance=new Nt),Nt.instance}static registerSaveRouter(e){Nt.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Nt.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Nt.getHandlers(e,"save")}static getLoadHandlers(e,t){return Nt.getHandlers(e,"load",t)}static getHandlers(e,t,n){let o=[];return(t==="load"?Nt.getInstance().loadRouters:Nt.getInstance().saveRouters).forEach(a=>{let i=a(e,n);i!==null&&o.push(i)}),o}},J1=r=>Nt.registerSaveRouter(r),Q1=r=>Nt.registerLoadRouter(r),eT=r=>Nt.getSaveHandlers(r),tT=(r,e)=>Nt.getLoadHandlers(r,e);var c_="tensorflowjs",p_=1,xu="models_store",Il="model_info_store";function rT(){if(!W().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 m_(r){let e=r.result;e.createObjectStore(xu,{keyPath:"modelPath"}),e.createObjectStore(Il,{keyPath:"modelPath"})}var ka=class{constructor(e){if(this.indexedDB=rT(),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(c_,p_);s.onupgradeneeded=()=>m_(s),s.onsuccess=()=>{let a=s.result;if(t==null){let i=a.transaction(xu,"readonly"),u=i.objectStore(xu).get(this.modelPath);u.onsuccess=()=>{if(u.result==null)return a.close(),o(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));n(u.result.modelArtifacts)},u.onerror=c=>(a.close(),o(u.error)),i.oncomplete=()=>a.close()}else{let i=hi(t),l=a.transaction(Il,"readwrite"),u=l.objectStore(Il),c=u.put({modelPath:this.modelPath,modelArtifactsInfo:i}),p;c.onsuccess=()=>{p=a.transaction(xu,"readwrite");let f=p.objectStore(xu).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:i});f.onsuccess=()=>n({modelArtifactsInfo:i}),f.onerror=d=>{u=l.objectStore(Il);let h=u.delete(this.modelPath);h.onsuccess=()=>(a.close(),o(f.error)),h.onerror=g=>(a.close(),o(f.error))}},c.onerror=m=>(a.close(),o(c.error)),l.oncomplete=()=>{p==null?a.close():p.oncomplete=()=>a.close()}}},s.onerror=a=>o(s.error)})}};ka.URL_SCHEME="indexeddb://";var nT=r=>W().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(ka.URL_SCHEME)?e4(r.slice(ka.URL_SCHEME.length)):null;Nt.registerSaveRouter(nT);Nt.registerLoadRouter(nT);function e4(r){return new ka(r)}function t4(r){return r.startsWith(ka.URL_SCHEME)?r.slice(ka.URL_SCHEME.length):r}var f_=class{constructor(){this.indexedDB=rT()}async listModels(){return new Promise((e,t)=>{let n=this.indexedDB.open(c_,p_);n.onupgradeneeded=()=>m_(n),n.onsuccess=()=>{let o=n.result,s=o.transaction(Il,"readonly"),i=s.objectStore(Il).getAll();i.onsuccess=()=>{let l={};for(let u of i.result)l[u.modelPath]=u.modelArtifactsInfo;e(l)},i.onerror=l=>(o.close(),t(i.error)),s.oncomplete=()=>o.close()},n.onerror=o=>t(n.error)})}async removeModel(e){return e=t4(e),new Promise((t,n)=>{let o=this.indexedDB.open(c_,p_);o.onupgradeneeded=()=>m_(o),o.onsuccess=()=>{let s=o.result,a=s.transaction(Il,"readwrite"),i=a.objectStore(Il),l=i.get(e),u;l.onsuccess=()=>{if(l.result==null)return s.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{let c=i.delete(e),p=()=>{u=s.transaction(xu,"readwrite");let f=u.objectStore(xu).delete(e);f.onsuccess=()=>t(l.result.modelArtifactsInfo),f.onerror=d=>n(l.error)};c.onsuccess=p,c.onerror=m=>(p(),s.close(),n(l.error))}},l.onerror=c=>(s.close(),n(l.error)),a.oncomplete=()=>{u==null?s.close():u.oncomplete=()=>s.close()}},o.onerror=s=>n(o.error)})}};var va="/",Ap="tensorflowjs_models",oT="info",r4="model_topology",n4="weight_specs",o4="weight_data",s4="model_metadata";function sT(r){return{info:[Ap,r,oT].join(va),topology:[Ap,r,r4].join(va),weightSpecs:[Ap,r,n4].join(va),weightData:[Ap,r,o4].join(va),modelMetadata:[Ap,r,s4].join(va)}}function i4(r){let e=r.split(va);if(e.length<3)throw new Error(`Invalid key format: ${r}`);return e.slice(1,e.length-1).join(va)}function a4(r){return r.startsWith(Ca.URL_SCHEME)?r.slice(Ca.URL_SCHEME.length):r}var Ca=class{constructor(e){if(!W().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=sT(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=hi(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,Y1(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 i=JSON.parse(s);t.format=i.format,t.generatedBy=i.generatedBy,t.convertedBy=i.convertedBy,i.signature!=null&&(t.signature=i.signature),i.userDefinedMetadata!=null&&(t.userDefinedMetadata=i.userDefinedMetadata),i.modelInitializer!=null&&(t.modelInitializer=i.modelInitializer)}let a=this.LS.getItem(this.keys.weightData);if(a==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=Z1(a),t}};Ca.URL_SCHEME="localstorage://";var iT=r=>W().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(Ca.URL_SCHEME)?l4(r.slice(Ca.URL_SCHEME.length)):null;Nt.registerSaveRouter(iT);Nt.registerLoadRouter(iT);function l4(r){return new Ca(r)}var d_=class{constructor(){E(W().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),E(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=Ap+va,n=va+oT;for(let o=0;o<this.LS.length;++o){let s=this.LS.key(o);if(s.startsWith(t)&&s.endsWith(n)){let a=i4(s);e[a]=JSON.parse(this.LS.getItem(s))}}return e}async removeModel(e){e=a4(e);let t=sT(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 Dp="://",nn=class{constructor(){this.managers={}}static getInstance(){return nn.instance==null&&(nn.instance=new nn),nn.instance}static registerManager(e,t){E(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(Dp)&&(e=e.slice(0,e.indexOf(Dp))),E(e.length>0,()=>"scheme must not be an empty string.");let n=nn.getInstance();E(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 Fg(r){if(r.indexOf(Dp)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${nn.getSchemes().join(",")}`);return{scheme:r.split(Dp)[0],path:r.split(Dp)[1]}}async function aT(r,e,t=!1){E(r!==e,()=>`Old path and new path are the same: '${r}'`);let n=Nt.getLoadHandlers(r);E(n.length>0,()=>`Copying failed because no load handler is found for source URL ${r}.`),E(n.length<2,()=>`Copying failed because more than one (${n.length}) load handlers for source URL ${r}.`);let o=n[0],s=Nt.getSaveHandlers(e);E(s.length>0,()=>`Copying failed because no save handler is found for destination URL ${e}.`),E(s.length<2,()=>`Copying failed because more than one (${n.length}) save handlers for destination URL ${e}.`);let a=s[0],i=Fg(r).scheme,l=Fg(r).path,u=i===Fg(r).scheme,c=await o.load();t&&u&&await nn.getManager(i).removeModel(l);let p=await a.save(c);return t&&!u&&await nn.getManager(i).removeModel(l),p.modelArtifactsInfo}async function lT(){let r=nn.getSchemes(),e={};for(let t of r){let n=await nn.getManager(t).listModels();for(let o in n){let s=t+Dp+o;e[s]=n[o]}}return e}async function uT(r){let e=Fg(r);return nn.getManager(e.scheme).removeModel(e.path)}async function cT(r,e){return aT(r,e,!1)}async function pT(r,e){return aT(r,e,!0)}var mT=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(W().get("IS_BROWSER")){W().setPlatform("browser",new mT);try{nn.registerManager(Ca.URL_SCHEME,new d_)}catch(r){}try{nn.registerManager(ka.URL_SCHEME,new f_)}catch(r){}}var u4={importFetch:()=>fT()},h_;var dT=class{constructor(){this.util=Lc("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return W().global.fetch!=null?W().global.fetch(e,t):(h_==null&&(h_=u4.importFetch()),h_(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)}};W().get("IS_NODE")&&W().setPlatform("node",new dT);function Ie(r,e="float32",t){return e=e||"float32",Qm(r),new ct(r,e,t)}function c4(r,e){let t=k(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 T.runKernel(to,n,o)}var oe=S({cast_:c4});function p4(r){let t={x:k(r,"x","clone","string_or_numeric")};return T.runKernel(no,t)}var qn=S({clone_:p4});function g_(r,e=!1){console.log(r.toString(e))}i_();var m4={buffer:Ie,cast:oe,clone:qn,print:g_};G1(m4);var Or={};je(Or,{browserFiles:()=>xT,browserHTTPRequest:()=>wT,concatenateArrayBuffers:()=>Ep,copyModel:()=>cT,decodeWeights:()=>Rg,encodeWeights:()=>K1,fromMemory:()=>kT,getLoadHandlers:()=>tT,getModelArtifactsInfoForJSON:()=>hi,getSaveHandlers:()=>eT,http:()=>Mg,isHTTPScheme:()=>Pg,listModels:()=>lT,loadWeights:()=>yT,moveModel:()=>pT,registerLoadRouter:()=>Q1,registerSaveRouter:()=>J1,removeModel:()=>uT,weightsLoaderFactory:()=>b_,withSaveHandler:()=>vT});var f4="model",d4=".json",h4=".weights.bin";function hT(r){return new Promise(e=>setTimeout(e)).then(r)}var Sl=class{constructor(e){if(!W().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Sl.URL_SCHEME)&&(e=e.slice(Sl.URL_SCHEME.length)),(e==null||e.length===0)&&(e=f4),this.modelTopologyFileName=e+d4,this.weightDataFileName=e+h4}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"})),a=this.jsonAnchor==null?document.createElement("a"):this.jsonAnchor;if(a.download=this.modelTopologyFileName,a.href=s,await hT(()=>a.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){let i=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;i.download=this.weightDataFileName,i.href=t,await hT(()=>i.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:hi(e)}}}};Sl.URL_SCHEME="downloads://";var gT=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=a=>{let i=JSON.parse(a.target.result),l=i.modelTopology;if(l==null){o(new Error(`modelTopology field is missing from file ${e.name}`));return}t.length===0&&n({modelTopology:l});let u=i.weightsManifest;if(u==null){o(new Error(`weightManifest field is missing from file ${e.name}`));return}let c;try{c=this.checkManifestAndWeightFiles(u,t)}catch(d){o(d);return}let p=[],m=[],f=[];u.forEach(d=>{d.paths.forEach(h=>{m.push(h),f.push(null)}),p.push(...d.weights)}),u.forEach(d=>{d.paths.forEach(h=>{let g=new FileReader;g.onload=x=>{let b=x.target.result,w=m.indexOf(h);if(f[w]=b,f.indexOf(null)===-1){let _={modelTopology:l,weightSpecs:p,weightData:Ep(f),format:i.format,generatedBy:i.generatedBy,convertedBy:i.convertedBy};i.signature!=null&&(_.signature=i.signature),i.userDefinedMetadata!=null&&(_.userDefinedMetadata=i.userDefinedMetadata),i.modelInitializer!=null&&(_.modelInitializer=i.modelInitializer),n(_)}},g.onerror=x=>o(`Failed to weights data from file of path '${h}'.`),g.readAsArrayBuffer(c[h])})})},s.onerror=a=>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(a=>u_(a.name)),s={};for(let a of e)a.paths.forEach(i=>{let l=u_(i);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[i]=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}},g4=r=>W().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(Sl.URL_SCHEME)?x4(r.slice(Sl.URL_SCHEME.length)):null;Nt.registerSaveRouter(g4);function x4(r="model"){return new Sl(r)}function xT(r){return new gT(r)}function x_(r,e,t,n){a(r),t=t==null?0:t,n=n==null?1:n,i(t,n);let o=0,s=l=>(l.then(u=>{let c=t+ ++o/r.length*(n-t);return e(c),u}),l);function a(l){E(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function i(l,u){E(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),E(u>=0&&u<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${u}`),E(u>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${u}`)}return Promise.all(r.map(s))}async function y_(r,e){e==null&&(e={});let t=e.fetchFunc==null?W().platform.fetch:e.fetchFunc,n=r.map(p=>t(p,e.requestInit,{isBinary:!0})),o=0,s=.5,i=(e.onProgress==null?await Promise.all(n):await x_(n,e.onProgress,o,s)).map(p=>p.arrayBuffer()),l=.5,u=1;return e.onProgress==null?await Promise.all(i):await x_(i,e.onProgress,l,u)}async function yT(r,e="",t,n){return b_(a=>y_(a,{requestInit:n}))(r,e,t)}function b_(r){return async(e,t="",n)=>{let o=e.map(()=>!1),s={},a=n!=null?n.map(()=>!1):[],i=[];if(e.forEach((f,d)=>{let h=0;f.weights.forEach(g=>{let x="quantization"in g?g.quantization.dtype:g.dtype,b=ff[x]*ot(g.shape),w=()=>{o[d]=!0,s[d]==null&&(s[d]=[]),s[d].push({manifestEntry:g,groupOffset:h,sizeBytes:b})};n!=null?n.forEach((_,C)=>{_===g.name&&(w(),a[C]=!0)}):w(),i.push(g.name),h+=b})}),!a.every(f=>f)){let f=n.filter((d,h)=>!a[h]);throw new Error(`Could not find weights in manifest with names: ${f.join(", ")}.
|
|
Manifest JSON has weights with names: ${i.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 c=await r(u),p={},m=0;return l.forEach(f=>{let d=e[f].paths.length,h=0;for(let _=0;_<d;_++)h+=c[m+_].byteLength;let g=new ArrayBuffer(h),x=new Uint8Array(g),b=0;for(let _=0;_<d;_++){let C=new Uint8Array(c[m+_]);x.set(C,b),b+=C.byteLength}s[f].forEach(_=>{let C=g.slice(_.groupOffset,_.groupOffset+_.sizeBytes),A=Rg(C,[_.manifestEntry]);for(let D in A)p[D]=A[D]}),m+=d}),p}}var y4="application/octet-stream",b4="application/json",Og=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?(E(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=W().platform.fetch,E(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&E(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:b4}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:y4}),"model.weights.bin");let s=await this.fetch(this.path,t);if(s.ok)return{modelArtifactsInfo:hi(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,a=t.convertedBy,i=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 c,p;o!=null&&([c,p]=await this.loadWeights(o));let m={modelTopology:n,weightSpecs:c,weightData:p,generatedBy:s,convertedBy:a,format:i};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]=w4(t),s=this.weightPathPrefix||n,a=[];for(let c of e)a.push(...c.weights);let i=[],l=[];for(let c of e)for(let p of c.paths)this.weightUrlConverter!=null?l.push(this.weightUrlConverter(p)):i.push(s+p+o);this.weightUrlConverter&&i.push(...await Promise.all(l));let u=await y_(i,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[a,Ep(u)]}};Og.URL_SCHEME_REGEX=/^https?:\/\//;function w4(r){let e=r.lastIndexOf("/"),t=r.lastIndexOf("?"),n=r.substring(0,e),o=t>e?r.substring(t):"";return[n+"/",o]}function Pg(r){return r.match(Og.URL_SCHEME_REGEX)!=null}var bT=(r,e)=>{if(typeof fetch=="undefined"&&(e==null||e.fetchFunc==null))return null;{let t=!0;if(Array.isArray(r)?t=r.every(n=>Pg(n)):t=Pg(r),t)return Mg(r,e)}return null};Nt.registerSaveRouter(bT);Nt.registerLoadRouter(bT);function Mg(r,e){return new Og(r,e)}function wT(r,e){return Mg(r,e)}var Lg=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},_T=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function kT(r,e,t,n){return arguments.length===1?r.modelTopology!=null||r.weightSpecs!=null?new Lg(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 Lg({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 Lg({modelTopology:r,weightSpecs:e,weightData:t,trainingConfig:n}))}function vT(r){return new _T(r)}var IT={};je(IT,{confusionMatrix:()=>CT});function _4(r,e,t=!1,n=!1){let o=k(r,"a","matMul"),s=k(e,"b","matMul");[o,s]=Ue(o,s);let a={a:o,b:s},i={transposeA:t,transposeB:n};return T.runKernel(Oo,a,i)}var Be=S({matMul_:_4});function k4(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:k(r,"indices","oneHot","int32")},a={depth:e,onValue:t,offValue:n};return T.runKernel(os,s,a)}var Ss=S({oneHot_:k4});function v4(r,e){let t=k(r,"x","transpose");if(e==null&&(e=t.shape.map((s,a)=>a).reverse()),E(t.rank===e.length,()=>`Error in transpose: rank of input ${t.rank} must match length of perm ${e}.`),e.forEach(s=>{E(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 T.runKernel(vs,n,o)}var qe=S({transpose_:v4});function C4(r,e,t){let n=k(r,"labels","confusionMatrix"),o=k(e,"predictions","confusionMatrix");E(t==null||t>0&&Number.isInteger(t),()=>`If provided, numClasses must be a positive integer, but got ${t}`),E(n.rank===1,()=>`Expected the rank of labels to be 1, but got ${n.rank}`),E(o.rank===1,()=>`Expected the rank of predictions to be 1, but got ${o.rank}`),E(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.`),E(t>0&&Number.isInteger(t),()=>`numClasses is required to be a positive integer, but got ${t}`);let s=Ss(oe(n,"int32"),t),a=Ss(oe(o,"int32"),t),i=qe(s),l=Be(i,a);return oe(l,"int32")}var CT=S({confusionMatrix_:C4});var zg={};je(zg,{fromPixels:()=>D4,fromPixelsAsync:()=>E4,toPixels:()=>A4});function w_(r,e,t){if(Wn(r),e!=null&&e.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let n=Fr(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 rn(r,e,n,t)}var $p;function ST(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,a=!1,i=!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)a=!0;else if(typeof ImageBitmap!="undefined"&&r instanceof ImageBitmap)i=!0;else throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${r.constructor.name}`);if(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(af(of,T.backendName)!=null){let d={pixels:r},h={numChannels:e};return T.runKernel(of,d,h)}let[u,c]=o?[r.videoWidth,r.videoHeight]:[r.width,r.height],p;a?p=r.getContext("2d").getImageData(0,0,u,c).data:n||t?p=r.data:(s||o||i)&&($p==null&&($p=document.createElement("canvas").getContext("2d")),$p.canvas.width=u,$p.canvas.height=c,$p.drawImage(r,0,0,u,c),p=$p.getImageData(0,0,u,c).data);let m;if(e===4)m=new Int32Array(p);else{let d=u*c;m=new Int32Array(d*e);for(let h=0;h<d;h++)for(let g=0;g<e;++g)m[h*e+g]=p[h*4+g]}return w_(m,[c,u,e],"int32")}function I4(r){return r!=null&&r.data instanceof Uint8Array}function S4(){return typeof window!="undefined"&&typeof ImageBitmap!="undefined"&&window.hasOwnProperty("createImageBitmap")}function N4(r){return r!=null&&r.width!==0&&r.height!==0}function T4(r){return S4()&&!(r instanceof ImageBitmap)&&N4(r)&&!I4(r)}async function E4(r,e=3){let t=null;if(W().getBool("WRAP_TO_IMAGEBITMAP")&&T4(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 ST(t,e)}async function A4(r,e){let t=k(r,"img","toPixels");if(!(r instanceof Me)){let u=t;t=oe(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 a=await t.data(),i=t.dtype==="float32"?255:1,l=new Uint8ClampedArray(o*n*4);for(let u=0;u<n*o;++u){let c=[0,0,0,255];for(let m=0;m<s;m++){let f=a[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?(c[0]=f*i,c[1]=f*i,c[2]=f*i):c[m]=f*i}let p=u*4;l[p+0]=Math.round(c[0]),l[p+1]=Math.round(c[1]),l[p+2]=Math.round(c[2]),l[p+3]=Math.round(c[3])}if(e!=null){e.width=o,e.height=n;let u=e.getContext("2d"),c=new ImageData(l,o,n);u.putImageData(c,0,0)}return t!==r&&t.dispose(),l}var D4=S({fromPixels_:ST});var Bg={};je(Bg,{prepareAndValidate:()=>NT});function NT(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(ot(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],a=1;for(let p=0;p<o.length-1;++p)a*=o[p];let i=r.shape,l=o.slice();l.pop();let u=1;for(let p=s;p<t;++p)u*=i[p],l.push(i[p]);let c=[...Zs(r.shape).map(p=>p/u),1].slice(0,s);return[l,a,u,c]}var Gg={};je(Gg,{calculateShapes:()=>TT,validateInput:()=>Vg,validateUpdateShape:()=>__});function __(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 a=0;a<o;++a)if(t.shape[a]!==e.shape[a])throw new Error(s+` updates.shape[${a}] (${t.shape[a]}) != indices.shape[${a}] (${e.shape[a]}).`);for(let a=0;a<t.rank-o;++a)if(t.shape[a+o]!==r[a+n])throw new Error(s+` updates.shape[${a+o}] (${t.shape[a+o]}) != shape[${a+o}] (${r[a+o]})`)}function Vg(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}`)}__(t,e,r)}function TT(r,e,t){let n=e.shape.length,o=n>1?e.shape[n-1]:1,s=t.length,a=1;for(let p=o;p<s;++p)a*=t[p];let i=o<1?1:o,l=ot(e.shape)/i,u=[...Zs(t.slice(0,o)),1],c=ot(t);return{sliceRank:o,numUpdates:l,sliceSize:a,strides:u,outputSize:c}}var lr={};je(lr,{assertParamsValid:()=>$4,computeFlatOffset:()=>F4,computeOutShape:()=>ET,getNormalizedAxes:()=>RT,isSliceContinous:()=>R4,maskToAxes:()=>Wg,parseSliceParams:()=>k_,sliceInfo:()=>O4,startForAxis:()=>MT,startIndicesWithElidedDims:()=>FT,stopForAxis:()=>LT,stopIndicesWithElidedDims:()=>OT,stridesForAxis:()=>PT,stridesWithElidedDims:()=>AT});function $4(r,e,t){let n=r.shape.length;E(n===e.length,()=>`Error in slice${n}D: Length of begin ${e} must match the rank of the array (${n}).`),E(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)E(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 Wg(r){let e=[],t=0;for(;r>0;)r&1&&e.push(t),r/=2,t++;return e}function ET(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 AT(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 DT(r,e,t){return t<=r?t:t-(e-1)}function $T(r,e){let t=[];for(let n=0;n<r;n++)t.push(e+n);return t}function RT(r,e,t,n,o,s,a,i,l){let u=r.length,c=new Array(u),p=new Array(u),m=new Array(u);if(e.length&&t>0){let f=e[0],d=t+1;c=FT(a,f,d,n,r),p=OT(i,f,d,o,r),m=AT(s,f,d,r)}else for(let f=0;f<u;f++)c[f]=MT(a,n,s,r,f,l),p[f]=LT(i,o,s,r,f,l),m[f]=PT(s,f,l);return{begin:c,end:p,strides:m}}function FT(r,e,t,n,o){let s=[...o],a=$T(t,e);for(let i=0;i<s.length;i++)if(a.indexOf(i)>-1)s[i]=0;else{let l=DT(e,t,i),u=n[l];r&1<<l&&(u=0),s[i]=u}return s}function OT(r,e,t,n,o){let s=[...o],a=$T(t,e);for(let i=0;i<s.length;i++)if(a.indexOf(i)>-1)s[i]=Number.MAX_SAFE_INTEGER;else{let l=DT(e,t,i),u=n[l];r&1<<l&&(u=Number.MAX_SAFE_INTEGER),s[i]=u}for(let i=0;i<s.length;i++){let l=o[i];s[i]<0&&(s[i]+=l),s[i]=zc(0,s[i],o[i])}return s}function PT(r,e,t){let n=r[e];return(t&1<<e||n==null)&&(n=1),n}function MT(r,e,t,n,o,s){let a=e[o],i=t[o]||1;(r&1<<o||s&1<<o||a==null)&&(i>0?a=Number.MIN_SAFE_INTEGER:a=Number.MAX_SAFE_INTEGER);let l=n[o];return a<0&&(a+=l),a=zc(0,a,l-1),a}function LT(r,e,t,n,o,s){let a=e[o],i=t[o]||1;(r&1<<o||s&1<<o||a==null)&&(i>0?a=Number.MAX_SAFE_INTEGER:a=Number.MIN_SAFE_INTEGER);let l=n[o];return a<0&&(a+=l),i>0?a=zc(0,a,l):a=zc(-1,a,l-1),a}function R4(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 F4(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 k_(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(a=>{E(a!==-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((a,i)=>a>=0?a:(E(a===-1,()=>`Negative size values should be exactly -1 but got ${a} for the slice() size at index ${i}.`),r.shape[i]-n[i])),[n,s]}function O4(r,e,t,n,o,s,a,i,l){let u=e.slice(),c=t.slice(),p=n;n==null&&(p=new Array(u.length));let m=Wg(a);if(m.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(a!==0&&i!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(a!==0&&l!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");let f=r.length-u.length,d=Wg(i),h=r.slice();d.forEach(D=>{u[D]=0,c[D]=1,h.splice(D,0,1)});let{begin:g,end:x,strides:b}=RT(h,m,f,u,c,p,o,s,a);u=g,c=x,p=b;let w=Wg(l);w.forEach(D=>{c[D]=u[D]+1,p[D]=1});let _=ET(u,c,p),C=_.filter((D,$)=>w.indexOf($)===-1);return{nonStrided:p.every(D=>D===1),$begin:u,$end:c,$strides:p,size:_,newShape:h,outShape:C}}var Q={};je(Q,{Serializable:()=>jg,SerializationMap:()=>Ia,registerClass:()=>wn});var jg=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},Ia=class{constructor(){this.classNameMap={}}static getMap(){return Ia.instance==null&&(Ia.instance=new Ia),Ia.instance}static register(e){Ia.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function wn(r){E(r.className!=null,()=>"Class being registered does not have the static className property defined."),E(typeof r.className=="string",()=>"className is required to be a string, but got type "+typeof r.className),E(r.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),Ia.register(r)}var GT={};je(GT,{TEST_EPSILON_FLOAT16:()=>zT,encodeStrings:()=>VT,expectArrayBuffersEqual:()=>V4,expectArraysClose:()=>M4,expectArraysEqual:()=>z4,expectNumbersClose:()=>BT,expectPromiseToFail:()=>L4,expectValuesInRange:()=>B4,testEpsilon:()=>Ug});var P4=.001,zT=.1;function M4(r,e,t){return t==null&&(t=Ug()),v_(r,e,(n,o)=>C_(n,o,t))}function Ug(){return T.backend.floatPrecision()===32?P4:zT}function v_(r,e,t){let n=!0;if((pr(r)||pr(e))&&(n=!1),pr(r)&&pr(e)&&(n=!0),n){let a=r.constructor.name,i=e.constructor.name;if(a!==i)throw new Error(`Arrays are of different type. Actual: ${a}. Expected: ${i}`)}if(Array.isArray(r)&&Array.isArray(e)){let a=Fr(r),i=Fr(e);if(!en(a,i))throw new Error(`Arrays have different shapes. Actual: [${a}]. Expected: [${i}]`)}let o=pr(r)?r:Ao(r),s=pr(e)?e:Ao(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 a=0;a<s.length;++a){let i=o[a],l=s[a];if(!t(i,l))throw new Error(`Arrays differ: actual[${a}] = ${i}, expected[${a}] = ${l}.
|
|
Actual: ${o}.
|
|
Expected: ${s}.`)}}function L4(r,e){r().then(()=>e.fail(),()=>e())}function z4(r,e){let t=typeof e=="string"||typeof e=="number"||typeof e=="boolean"?[e]:e;return Do(r)||Do(r[0])||Do(e)||Do(e[0])?v_(r,t,(n,o)=>n==o):v_(r,e,(n,o)=>C_(n,o,0))}function BT(r,e,t){if(t==null&&(t=Ug()),!C_(r,e,t))throw new Error(`Numbers differ: actual === ${r}, expected === ${e}`)}function C_(r,e,t){return!isFinite(r)&&!isFinite(e)?!0:!(isNaN(r)||isNaN(e)||Math.abs(r-e)>t)}function B4(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 V4(r,e){expect(new Float32Array(r)).toEqual(new Float32Array(e))}function VT(r){for(let e=0;e<r.length;e++){let t=r[e];Array.isArray(t)?VT(t):r[e]=vl(t)}return r}var G4="3.7.0";function Rue(){W().set("PROD",!0)}function Fue(){W().set("DEBUG",!0)}function Oue(){W().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function I_(r){W().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(r+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}W1(I_);function Pue(){T.disposeVariables()}function Ns(){return T}function df(){return T.memory()}function Mue(r){return T.profile(r)}function B(r,e){return T.tidy(r,e)}function De(r){mf(r).forEach(t=>t.dispose())}function Rt(r){return T.keep(r)}function Lue(r){return T.time(r)}function W4(r){return T.setBackend(r)}function zue(){return T.ready()}function Bue(){return T.backendName}function Vue(r){T.removeBackend(r)}function Gue(r){return T.findBackend(r)}function Wue(r){return T.findBackendFactory(r)}function Rp(r,e,t=1){return T.registerBackend(r,e,t)}function WT(){return T.backend}function jue(r,e){W().setPlatform(r,e)}function j4(r,e){let t=k(r,"a","add"),n=k(e,"b","add");[t,n]=Ue(t,n);let o={a:t,b:n};return T.runKernel(jn,o)}var J=S({add_:j4});function U4(r,e){let t=k(r,"a","floorDiv"),n=k(e,"b","floorDiv");[t,n]=Ue(t,n);let o={a:t,b:n};return T.runKernel(Uo,o)}var yu=S({floorDiv_:U4});function q4(r,e){let t=k(r,"a","div"),n=k(e,"b","div");if([t,n]=Ue(t,n),t.dtype==="int32"&&n.dtype==="int32")return yu(t,n);let o={a:t,b:n},s={};return T.runKernel(Go,o,s)}var ue=S({div_:q4});function H4(r,e){let t=k(r,"a","mul"),n=k(e,"b","mul");[t,n]=Ue(t,n);let o={a:t,b:n};return T.runKernel(ns,o)}var P=S({mul_:H4});function K4(r){let e=k(r,"x","abs");if(e.dtype==="complex64"){let t={x:e};return T.runKernel(pl,t)}else{let t={x:e};return T.runKernel(Js,t)}}var Tt=S({abs_:K4});function X4(r){let t={x:k(r,"x","acos")};return T.runKernel(Ri,t)}var hf=S({acos_:X4});function Y4(r){let t={x:k(r,"x","acosh")};return T.runKernel(Fi,t)}var gf=S({acosh_:Y4});function Z4(r){E(Array.isArray(r),()=>"The argument passed to tf.addN() must be a list of tensors"),E(r.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${r.length}`);let e=r.map((o,s)=>k(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 T.runKernel($o,n)}var S_=S({addN_:Z4});function J4(r,e=null,t=!1){let o={x:k(r,"x","all","bool")},s={axis:e,keepDims:t};return T.runKernel(Oi,o,s)}var bu=S({all_:J4});function Q4(r,e=null,t=!1){let o={x:k(r,"x","any","bool")},s={axis:e,keepDims:t};return T.runKernel(Pi,o,s)}var Nl=S({any_:Q4});function eU(r,e=0){let n={x:k(r,"x","argMax")},o={axis:e};return T.runKernel(Ro,n,o)}var Tl=S({argMax_:eU});function tU(r,e=0){let n={x:k(r,"x","argMin")},o={axis:e};return T.runKernel(ll,n,o)}var xf=S({argMin_:tU});function rU(r){let t={x:k(r,"x","asin")};return T.runKernel(Mi,t)}var yf=S({asin_:rU});function nU(r){let t={x:k(r,"x","asinh")};return T.runKernel(Li,t)}var bf=S({asinh_:nU});function oU(r){let t={x:k(r,"x","atan")};return T.runKernel(zi,t)}var wf=S({atan_:oU});function sU(r,e){let t=k(r,"a","atan2"),n=k(e,"b","atan2");[t,n]=Ue(t,n);let o={a:t,b:n};return T.runKernel(Vi,o)}var _f=S({atan2_:sU});function iU(r){let t={x:k(r,"x","atanh")};return T.runKernel(Bi,t)}var kf=S({atanh_:iU});function aU(r,e,t,n,o="NHWC",s){let a=r[3],i=[...e,a],l=UT(o);return wu(r,i,t,s,n,null,null,l)}function N_(r,e,t,n,o,s,a="channelsLast"){let[i,l]=qg(e),u;if(a==="channelsLast")u=[i,l,r[3],r[3]];else if(a==="channelsFirst")u=[i,l,r[1],r[1]];else throw new Error(`Unknown dataFormat ${a}`);return wu(r,u,t,n,o,s,!1,a)}function lU(r,e,t,n,o,s,a="NDHWC"){let[i,l,u]=E_(e),c,p;if(a==="NDHWC")p="channelsLast",c=[i,l,u,r[4],r[4]];else if(a==="NCDHW")p="channelsFirst",c=[i,l,u,r[1],r[1]];else throw new Error(`Unknown dataFormat ${a}`);return jT(r,c,t,n,o,!1,p,s)}function wu(r,e,t,n,o,s,a=!1,i="channelsLast"){let[l,u,c,p]=[-1,-1,-1,-1];if(i==="channelsLast")[l,u,c,p]=r;else if(i==="channelsFirst")[l,p,u,c]=r;else throw new Error(`Unknown dataFormat ${i}`);let[m,f,,d]=e,[h,g]=qg(t),[x,b]=qg(n),w=Fp(m,x),_=Fp(f,b),{padInfo:C,outHeight:A,outWidth:D}=pU(o,u,c,h,g,w,_,s,i),$=a?d*p:d,R;return i==="channelsFirst"?R=[l,$,A,D]:i==="channelsLast"&&(R=[l,A,D,$]),{batchSize:l,dataFormat:i,inHeight:u,inWidth:c,inChannels:p,outHeight:A,outWidth:D,outChannels:$,padInfo:C,strideHeight:h,strideWidth:g,filterHeight:m,filterWidth:f,effectiveFilterHeight:w,effectiveFilterWidth:_,dilationHeight:x,dilationWidth:b,inShape:r,outShape:R,filterShape:e}}function jT(r,e,t,n,o,s=!1,a="channelsLast",i){let[l,u,c,p,m]=[-1,-1,-1,-1,-1];if(a==="channelsLast")[l,u,c,p,m]=r;else if(a==="channelsFirst")[l,m,u,c,p]=r;else throw new Error(`Unknown dataFormat ${a}`);let[f,d,h,,g]=e,[x,b,w]=E_(t),[_,C,A]=E_(n),D=Fp(f,_),$=Fp(d,C),R=Fp(h,A),{padInfo:M,outDepth:G,outHeight:j,outWidth:U}=mU(o,u,c,p,x,b,w,D,$,R,i),q=s?g*m:g,H;return a==="channelsFirst"?H=[l,q,G,j,U]:a==="channelsLast"&&(H=[l,G,j,U,q]),{batchSize:l,dataFormat:a,inDepth:u,inHeight:c,inWidth:p,inChannels:m,outDepth:G,outHeight:j,outWidth:U,outChannels:q,padInfo:M,strideDepth:x,strideHeight:b,strideWidth:w,filterDepth:f,filterHeight:d,filterWidth:h,effectiveFilterDepth:D,effectiveFilterHeight:$,effectiveFilterWidth:R,dilationDepth:_,dilationHeight:C,dilationWidth:A,inShape:r,outShape:H,filterShape:e}}function uU(r,e,t,n,o){n==null&&(n=T_(r,e,t));let s=r[0],a=r[1],i=_u((s-e+2*n)/t+1,o),l=_u((a-e+2*n)/t+1,o);return[i,l]}function cU(r,e,t,n,o,s){o==null&&(o=T_(r,e,n));let a=r[0],i=r[1],l=r[2],u=_u((a-e+2*o)/n+1,s),c=_u((i-e+2*o)/n+1,s),p=_u((l-e+2*o)/n+1,s);return[u,c,p,t]}function T_(r,e,t,n=1){let o=Fp(e,n);return Math.floor((r[0]*(t-1)-t+o)/2)}function qg(r){return typeof r=="number"?[r,r,r]:r.length===2?[r[0],r[1],1]:r}function E_(r){return typeof r=="number"?[r,r,r]:r}function Fp(r,e){return e<=1?r:r+(r-1)*(e-1)}function pU(r,e,t,n,o,s,a,i,l){let u,c,p;if(typeof r=="number"){u={top:r,bottom:r,left:r,right:r,type:r===0?"VALID":"NUMBER"};let f=uU([e,t],s,n,r,i);c=f[0],p=f[1]}else if(r==="same"){c=Math.ceil(e/n),p=Math.ceil(t/o);let m=Math.max(0,(c-1)*n+s-e),f=Math.max(0,(p-1)*o+a-t),d=Math.floor(m/2),h=m-d,g=Math.floor(f/2),x=f-g;u={top:d,bottom:h,left:g,right:x,type:"SAME"}}else if(r==="valid")u={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((e-s+1)/n),p=Math.ceil((t-a+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"},c=_u((e-s+m+f)/n+1,i),p=_u((t-a+d+h)/o+1,i)}else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:u,outHeight:c,outWidth:p}}function mU(r,e,t,n,o,s,a,i,l,u,c){let p,m,f,d;if(typeof r=="number"){p={top:r,bottom:r,left:r,right:r,front:r,back:r,type:r===0?"VALID":"NUMBER"};let g=cU([e,t,n,1],i,1,o,r,c);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/a);let h=(m-1)*o+i-e,g=(f-1)*s+l-t,x=(d-1)*a+u-n,b=Math.floor(h/2),w=h-b,_=Math.floor(g/2),C=g-_,A=Math.floor(x/2),D=x-A;p={top:_,bottom:C,left:A,right:D,front:b,back:w,type:"SAME"}}else if(r==="valid")p={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},m=Math.ceil((e-i+1)/o),f=Math.ceil((t-l+1)/s),d=Math.ceil((n-u+1)/a);else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:p,outDepth:m,outHeight:f,outWidth:d}}function _u(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 Hn(r){let[e,t,n]=qg(r);return e===1&&t===1&&n===1}function Tr(r,e){return Hn(r)||Hn(e)}function UT(r){if(r==="NHWC")return"channelsLast";if(r==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${r}`)}function fU(r,e){let n={x:k(r,"x","reshape","string_or_numeric")},o={shape:e};return T.runKernel(si,n,o)}var L=S({reshape_:fU});function dU(r,e,t,n,o){let s=k(r,"x","avgPool","float32"),a=1;E(Tr(t,a),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${t} and dilations '${a}'`);let i=s,l=!1;s.rank===3&&(l=!0,i=L(s,[1,s.shape[0],s.shape[1],s.shape[2]])),E(i.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`),o!=null&&E(st(n),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`);let u={x:i},c={filterSize:e,strides:t,pad:n,dimRoundingMode:o},p=T.runKernel(Fo,u,c);return p=oe(p,s.dtype),l?L(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Sa=S({avgPool_:dU});function hU(r,e,t,n,o,s="NDHWC"){let a=k(r,"x","avgPool3d","float32"),i=a,l=!1;a.rank===4&&(l=!0,i=L(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),E(i.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${i.rank}.`),E(s==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),o!=null&&E(st(n),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`);let u={x:i},c={filterSize:e,strides:t,pad:n,dimRoundingMode:o,dataFormat:s},p=T.runKernel(ul,u,c);return p=oe(p,i.dtype),l?L(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var vf=S({avgPool3d_:hU});function gU(r,e=0){E(r.length>=1,()=>"Pass at least one tensor to concat");let t=_a(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 qn(t[0]);let n=t,o={axis:e};return T.runKernel(Qs,n,o)}var et=S({concat_:gU});function xU(r){let t={x:k(r,"x","sigmoid")};return T.runKernel(hs,t)}var Pr=S({sigmoid_:xU});function yU(r,e,t){let n=k(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 T.runKernel(ai,o,s)}var Fe=S({slice_:yU});function bU(r){let t={x:k(r,"x","tanh")};return T.runKernel(ks,t)}var Ts=S({tanh_:bU});function wU(r,e,t,n,o,s){let a=k(r,"forgetBias","basicLSTMCell"),i=k(e,"lstmKernel","basicLSTMCell"),l=k(t,"lstmBias","basicLSTMCell"),u=k(n,"data","basicLSTMCell"),c=k(o,"c","basicLSTMCell"),p=k(s,"h","basicLSTMCell"),m=et([u,p],1),f=Be(m,i),d=J(f,l),h=d.shape[0],g=d.shape[1]/4,x=[h,g],b=Fe(d,[0,0],x),w=Fe(d,[0,g],x),_=Fe(d,[0,g*2],x),C=Fe(d,[0,g*3],x),A=J(P(Pr(b),Ts(w)),P(c,Pr(J(a,_)))),D=P(Ts(A),Pr(C));return[A,D]}var _U=S({basicLSTMCell_:wU});function kU(r,e,t){let n=k(r,"x","batchToSpaceND"),o=e.reduce((i,l)=>i*l);E(n.rank>=1+e.length,()=>`input rank is ${n.rank} but should be > than blockShape.length ${e.length}`),E(t.length===e.length,()=>`crops.length is ${t.length} but should be equal to blockShape.length ${e.length}`),E(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},a={blockShape:e,crops:t};return T.runKernel(cl,s,a)}var Na=S({batchToSpaceND_:kU});function qT(r){let e;return r.rank===0||r.rank===1?e=L(r,[1,1,1,r.size]):r.rank===2?e=L(r,[1,1,r.shape[0],r.shape[1]]):r.rank===3?e=L(r,[1,r.shape[0],r.shape[1],r.shape[2]]):e=r,e}function vU(r,e,t,n,o,s){s==null&&(s=.001);let a=k(r,"x","batchNorm"),i=k(e,"mean","batchNorm"),l=k(t,"variance","batchNorm"),u;o!=null&&(u=k(o,"scale","batchNorm"));let c;n!=null&&(c=k(n,"offset","batchNorm")),E(i.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),E(c==null||i.rank===c.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),E(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let m={x:qT(a),scale:u,offset:c,mean:i,variance:l},f={varianceEpsilon:s},d=T.runKernel(qo,m,f);return L(d,a.shape)}var uo=S({batchNorm_:vU});function CU(r,e,t,n,o,s){let a=k(r,"x","batchNorm"),i=k(e,"mean","batchNorm"),l=k(t,"variance","batchNorm"),u;o!=null&&(u=k(o,"scale","batchNorm"));let c;return n!=null&&(c=k(n,"offset","batchNorm")),E(a.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${a.rank}.`),E(i.rank===2||i.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`),E(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&E(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),c!=null&&E(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${c.rank}.`),uo(a,i,l,c,u,s)}var A_=S({batchNorm2d_:CU});function IU(r,e,t,n,o,s){let a=k(r,"x","batchNorm"),i=k(e,"mean","batchNorm"),l=k(t,"variance","batchNorm"),u;o!=null&&(u=k(o,"scale","batchNorm"));let c;return n!=null&&(c=k(n,"offset","batchNorm")),E(a.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${a.rank}.`),E(i.rank===3||i.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`),E(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&E(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),c!=null&&E(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${c.rank}.`),uo(a,i,l,c,u,s)}var D_=S({batchNorm3d_:IU});function SU(r,e,t,n,o,s){let a=k(r,"x","batchNorm"),i=k(e,"mean","batchNorm"),l=k(t,"variance","batchNorm"),u;o!=null&&(u=k(o,"scale","batchNorm"));let c;return n!=null&&(c=k(n,"offset","batchNorm")),E(a.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${a.rank}.`),E(i.rank===4||i.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`),E(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),u!=null&&E(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`),c!=null&&E(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${c.rank}.`),uo(a,i,l,c,u,s)}var $_=S({batchNorm4d_:SU});function NU(r,e,t){let n=k(r,"x","bincount"),o=k(e,"weights","bincount");E(n.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${n.dtype}`),E(t>=0,()=>`size must be non-negative, but got ${t}.`),E(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},a={size:t};return T.runKernel(Uc,s,a)}var Cf=S({bincount_:NU});function TU(r,e){let t=k(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=L(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,c)=>u>1?c:-1).filter(u=>u>=0).length===0)return qn(t);let i={x:t},l={reps:s};return T.runKernel(Un,i,l)}var Ta=S({broadcastTo_:TU});function EU(r){let t={x:k(r,"x","ceil")};return T.runKernel(Po,t)}var If=S({ceil_:EU});function AU(r,e,t){let n=k(r,"x","clipByValue");E(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 T.runKernel(ro,o,s)}var fr=S({clipByValue_:AU});function DU(r){return et(r,0)}var R_=S({concat1d_:DU});function $U(r,e){return et(r,e)}var F_=S({concat2d_:$U});function RU(r,e){return et(r,e)}var O_=S({concat3d_:RU});function FU(r,e){return et(r,e)}var P_=S({concat4d_:FU});function OU(r,e,t,n,o="NHWC",s=[1,1],a){let i=k(r,"x","conv2d"),l=k(e,"filter","conv2d"),u=i,c=!1;i.rank===3&&(c=!0,u=L(i,[1,i.shape[0],i.shape[1],i.shape[2]])),E(u.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`),E(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),a!=null&&E(st(n),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${n}.`);let p=o==="NHWC"?u.shape[3]:u.shape[1];E(p===l.shape[2],()=>`Error in conv2d: depth of input (${p}) must match input depth for filter ${l.shape[2]}.`),E(Tr(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:a},d=T.runKernel(Mo,m,f);return c?L(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var on=S({conv2d_:OU});function PU(r,e,t,n,o="NWC",s=1,a){let i=k(r,"x","conv1d"),l=k(e,"filter","conv1d"),u=i,c=!1;i.rank===2&&(c=!0,u=L(i,[1,i.shape[0],i.shape[1]])),E(u.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`),E(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),a!=null&&E(st(n),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${n}.`),E(u.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`),E(Tr(t,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${t} and dilation '${s}'`),E(o==="NWC",()=>`Error in conv1d: got dataFormat of ${o} but only NWC is currently supported.`);let p=L(l,[1,l.shape[0],l.shape[1],l.shape[2]]),m=L(u,[u.shape[0],1,u.shape[1],u.shape[2]]),g=on(m,p,[1,t],n,"NHWC",[1,s],a);return c?L(g,[g.shape[2],g.shape[3]]):L(g,[g.shape[0],g.shape[2],g.shape[3]])}var ku=S({conv1d_:PU});function MU(r,e,t,n,o,s="NHWC",a){E(r.length===e.rank,()=>`Length of inShape (${r.length}) and rank of dy (${e.rank}) must match`);let i=r,l=e,u=!1;e.rank===3&&(u=!0,l=L(e,[1,e.shape[0],e.shape[1],e.shape[2]]),i=[1,r[0],r[1],r[2]]),E(i.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`),E(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),E(t.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${t.rank}`);let c=s==="NHWC"?i[3]:i[1],p=s==="NHWC"?l.shape[3]:l.shape[1];E(c===t.shape[2],()=>`Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${t.shape[2]}.`),E(p===t.shape[3],()=>`Error in conv2dDerInput: depth of output (${p}) must match output depth for filter ${t.shape[3]}.`),a!=null&&E(st(o),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);let m={dy:l,filter:t},f={strides:n,pad:o,dataFormat:s,dimRoundingMode:a,inputShape:i},d=T.runKernel(Lo,m,f);return u?L(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Op=S({conv2DBackpropInput_:MU});function LU(r,e,t,n,o,s){let a=k(r,"x","conv2dTranspose"),i=k(e,"filter","conv2dTranspose");return Op(t,a,i,n,o,"NHWC",s)}var vu=S({conv2dTranspose_:LU});function zU(r,e,t,n,o="NDHWC",s=[1,1,1]){let a=k(r,"x","conv3d"),i=k(e,"filter","conv3d"),l=a,u=!1;a.rank===4&&(u=!0,l=L(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),E(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),E(i.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`),E(l.shape[4]===i.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${i.shape[3]}.`),E(Tr(t,s),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`),E(o==="NDHWC",()=>`Error in conv3d: got dataFormat of ${o} but only NDHWC is currently supported.`);let c={x:l,filter:i},p={strides:t,pad:n,dataFormat:o,dilations:s},m=T.runKernel(ml,c,p);return u?L(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}var Sf=S({conv3d_:zU});function BU(r,e,t,n,o){E(r.length===e.rank,()=>`Length of inShape (${r.length}) and rank of dy (${e.rank}) must match`);let s=r,a=e,i=!1;e.rank===4&&(i=!0,a=L(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=a.shape[4];E(s.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`),E(a.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${a.rank}`),E(t.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${t.rank}`),E(l===t.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${t.shape[3]}.`),E(u===t.shape[4],()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${t.shape[4]}.`);let c={dy:a,filter:t},p={pad:o,strides:n,inputShape:s},m=T.runKernel(Xc,c,p);return i?L(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}var Hg=S({conv3DBackpropInput_:BU});function VU(r,e,t,n,o){let s=k(r,"x","conv3dTranspose"),a=k(e,"filter","conv3dTranspose");return Hg(t,s,a,n,o)}var M_=S({conv3dTranspose_:VU});function GU(r){let t={x:k(r,"x","cos")};return T.runKernel(zo,t)}var Ea=S({cos_:GU});function WU(r){let t={x:k(r,"x","cosh")};return T.runKernel(Gi,t)}var Cu=S({cosh_:WU});function jU(r,e=0,t=!1,n=!1){let s={x:k(r,"x","cumsum")},a={axis:e,exclusive:t,reverse:n};return T.runKernel(Bo,s,a)}var Iu=S({cumsum_:jU});function UU(r,e,t,n=!1){let o=k(r,"x","denseBincount"),s=k(e,"weights","denseBincount");E(o.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${o.dtype}`),E(o.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${o.rank}.`),E(t>=0,()=>`size must be non-negative, but got ${t}.`),E(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 a={x:o,weights:s},i={size:t,binaryOutput:n};return T.runKernel(Yc,a,i)}var L_=S({denseBincount_:UU});function qU(r,e,t="NHWC"){let n=k(r,"x","depthToSpace"),o=t==="NHWC"?n.shape[1]:n.shape[2],s=t==="NHWC"?n.shape[2]:n.shape[3],a=t==="NHWC"?n.shape[3]:n.shape[1];E(o*e>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${o} and ${e} for depthToSpace with input shape
|
|
${n.shape}`),E(s*e>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${s} and ${e} for depthToSpace with input shape
|
|
${n.shape}`),E(a%(e*e)==0,()=>`Dimension size must be evenly divisible by ${e*e} but is ${a} for depthToSpace with input shape ${n.shape}`);let i={x:n},l={blockSize:e,dataFormat:t};return T.runKernel(ji,i,l)}var Nf=S({depthToSpace_:qU});function HU(r,e,t,n,o="NHWC",s=[1,1],a){let i=k(r,"x","depthwiseConv2d"),l=k(e,"filter","depthwiseConv2d"),u=i,c=!1;i.rank===3&&(c=!0,u=L(i,[1,i.shape[0],i.shape[1],i.shape[2]])),E(u.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),E(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),E(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]}.`),a!=null&&E(st(n),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${n}.`);let p={x:u,filter:l},m={strides:t,pad:n,dataFormat:o,dilations:s,dimRoundingMode:a},f=T.runKernel(Vo,p,m);return c?L(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Es=S({depthwiseConv2d_:HU});function KU(r){let t={x:k(r,"x","diag")};return T.runKernel(Qc,t)}var XU=S({diag_:KU});function YU(r,e,t,n,o=[1,1],s="NHWC"){let a=k(r,"x","dilation2d"),i=k(e,"filter","dilation2d");E(a.rank===3||a.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${a.rank}.`),E(i.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`),E(s==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);let l=a,u=!1;a.rank===3&&(l=L(a,[1,a.shape[0],a.shape[1],a.shape[2]]),u=!0);let c={x:l,filter:i},p={strides:t,pad:n,dilations:o},m=T.runKernel(fl,c,p);return u?L(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Tf=S({dilation2d_:YU});function ZU(r,e){let t=r.length,n=[];for(let o=0;o<t;o++){let s=t-1-o,a=r[s]||1;(e[e.length-1-o]||1)>1&&a===1&&n.unshift(s)}return n}function vt(r,e){let t=[];for(let n=0;n<e.length;n++){let o=r[r.length-n-1],s=e.length-n-1,a=e[s];(o==null||o===1&&a>1)&&t.unshift(s)}return t}function Ve(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 a=e[e.length-o-1];if(a==null&&(a=1),s===1)t.unshift(a);else if(a===1)t.unshift(s);else if(s!==a){let i=`Operands could not be broadcast together with shapes ${r} and ${e}.`;throw Error(i)}else t.unshift(s)}return t}function JU(r,e){let t=k(r,"a","equal","string_or_numeric"),n=k(e,"b","equal","string_or_numeric");[t,n]=Ue(t,n),Ve(t.shape,n.shape);let o={a:t,b:n};return T.runKernel(Hi,o)}var On=S({equal_:JU});function QU(r,e,t){let n=k(e,"a","where"),o=k(t,"b","where"),s=k(r,"condition","where","bool"),a=Ve(Ve(s.shape,n.shape),o.shape),i=Ta(s,a),l=Ta(n,a),u=Ta(o,a),c={condition:i,t:l,e:u};return T.runKernel(ii,c)}var Ct=S({where_:QU});function eq(r){let t={x:k(r,"x","zerosLike")};return T.runKernel(ci,t)}var Se=S({zerosLike_:eq});function tq(r,e){let t=k(r,"a","div"),n=k(e,"b","div");[t,n]=Ue(t,n);let o=ue(t,n),s=Se(o),a=On(n,s);return Ct(a,s,o)}var Ef=S({divNoNan_:tq});function rq(r,e){let t=k(r,"t1","dot"),n=k(e,"t2","dot");E((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(E(o===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${o} and ${s}.`),t.rank===1&&n.rank===1){let a=L(t,[1,-1]),i=L(n,[-1,1]),l=Be(a,i);return L(l,[])}else if(t.rank===1&&n.rank===2){let a=L(t,[1,-1]),i=L(n,[n.shape[0],n.shape[1]]),l=Be(a,i);return L(l,[l.size])}else if(t.rank===2&&n.rank===1){let a=L(n,[-1,1]),i=Be(t,a);return L(i,[i.size])}else{let a=L(n,[n.shape[0],n.shape[1]]);return Be(t,a)}}var z_=S({dot_:rq});function nq(r,...e){let t=e.map((o,s)=>k(o,`tensors${s}`,"einsum")),n={equation:r};return T.runKernel(ep,t,n)}var B_=S({einsum_:nq});function oq(r){let t={x:k(r,"x","elu")};return T.runKernel(Ui,t)}var As=S({elu_:oq});function sq(r){let e=k(r,"x","erf");E(e.dtype==="int32"||e.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),e.dtype==="int32"&&(e=oe(e,"float32"));let t={x:e};return T.runKernel(qi,t)}var Af=S({erf_:sq});function iq(r){let t={x:k(r,"x","exp")};return T.runKernel(Wo,t)}var nr=S({exp_:iq});function aq(r,e=0){let t=k(r,"x","expandDims","string_or_numeric");E(e<=t.rank,()=>"Axis must be <= rank of the tensor");let n={input:t},o={dim:e};return T.runKernel(ei,n,o)}var dr=S({expandDims_:aq});function lq(r){let t={x:k(r,"x","expm1")};return T.runKernel(Ki,t)}var Df=S({expm1_:lq});function uq(r,e){let t=k(r,"x","tile","string_or_numeric");E(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 T.runKernel(Un,n,o)}var Kn=S({tile_:uq});function cq(r,e,t,n="float32"){e==null&&(e=r);let o=Ie([r,e],n),s=r<=e?r:e;for(let i=0;i<s;++i)o.set(1,i,i);let a=L(o.toTensor(),[r,e]);if(t==null)return a;if(t.length===1)return Kn(dr(a,0),[t[0],1,1]);if(t.length===2)return Kn(dr(dr(a,0),0),[t[0],t[1],1,1]);if(t.length===3)return Kn(dr(dr(dr(a,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 Pp=S({eye_:cq});function Ds(r,e,t){let n={shape:r,value:e,dtype:t};return T.runKernel(dl,{},n)}function pq(r){let t={x:k(r,"x","floor")};return T.runKernel(jo,t)}var $s=S({floor_:pq});function mq(r,e,t=0,n=0){let o=k(r,"x","gather"),s=k(e,"indices","gather","int32"),a={x:o,indices:s},i={axis:t,batchDims:n};return T.runKernel(ti,a,i)}var co=S({gather_:mq});function fq(r,e){let t=k(r,"a","greater","string_or_numeric"),n=k(e,"b","greater","string_or_numeric");[t,n]=Ue(t,n),Ve(t.shape,n.shape);let o={a:t,b:n};return T.runKernel(Zi,o)}var qt=S({greater_:fq});function dq(r,e){let t=k(r,"a","greaterEqual","string_or_numeric"),n=k(e,"b","greaterEqual","string_or_numeric");[t,n]=Ue(t,n),Ve(t.shape,n.shape);let o={a:t,b:n};return T.runKernel(Ho,o)}var _n=S({greaterEqual_:dq});function hq(r){let t={input:k(r,"input","imag")};return T.runKernel(op,t)}var Su=S({imag_:hq});function gq(r){let t={x:k(r,"x","isFinite")};return T.runKernel(Ji,t)}var V_=S({isFinite_:gq});function xq(r){let t={x:k(r,"x","isInf")};return T.runKernel(Qi,t)}var G_=S({isInf_:xq});function yq(r){let t={x:k(r,"x","isNaN")};return T.runKernel(ea,t)}var $f=S({isNaN_:yq});function bq(r,e=.2){let n={x:k(r,"x","leakyRelu")},o={alpha:e};return T.runKernel(Ko,n,o)}var Aa=S({leakyRelu_:bq});function wq(r,e){let t=k(r,"a","less","string_or_numeric"),n=k(e,"b","less","string_or_numeric");[t,n]=Ue(t,n),Ve(t.shape,n.shape);let o={a:t,b:n};return T.runKernel(ta,o)}var Nu=S({less_:wq});function _q(r,e){let t=k(r,"a","lessEqual","string_or_numeric"),n=k(e,"b","lessEqual","string_or_numeric");[t,n]=Ue(t,n),Ve(t.shape,n.shape);let o={a:t,b:n};return T.runKernel(ra,o)}var kn=S({lessEqual_:_q});function W_(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 T.runKernel(sp,{},n)}function kq(r,e=5,t=1,n=1,o=.5){let s=k(r,"x","localResponseNormalization");E(s.rank===4||s.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
|
|
rank ${s.rank}.`),E(st(e),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${e}.`);let a=s,i=!1;s.rank===3&&(i=!0,a=L(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let l={x:a},u={depthRadius:e,bias:t,alpha:n,beta:o},c=T.runKernel(hl,l,u);return i?L(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var Rf=S({localResponseNormalization_:kq});function vq(r){let t={x:k(r,"x","log")};return T.runKernel(Xo,t)}var hr=S({log_:vq});function Cq(r){let t={x:k(r,"x","log1p")};return T.runKernel(na,t)}var Tu=S({log1p_:Cq});function Iq(r){return E(Ys(r),()=>"The f passed in grad(f) must be a function"),(e,t)=>{let n=k(e,"x","tf.grad","string_or_numeric"),o=t!=null?k(t,"dy","tf.grad"):null;return T.tidy(()=>{let{value:s,grads:a}=T.gradients(()=>r(n),[n],o);return o!=null&&$t(s.shape,o.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Xg(a),a[0]})}}function Sq(r){return E(Ys(r),()=>"The f passed in grads(f) must be a function"),(e,t)=>{E(Array.isArray(e),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let n=_a(e,"args","tf.grads","string_or_numeric"),o=t!=null?k(t,"dy","tf.grads"):null;return T.tidy(()=>{let{value:s,grads:a}=T.gradients(()=>r(...n),n,o);return o!=null&&$t(s.shape,o.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Xg(a),a})}}function Nq(r){return E(Ys(r),()=>"The f passed in valueAndGrad(f) must be a function"),(e,t)=>{E(e instanceof Me,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),E(t==null||t instanceof Me,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:n,value:o}=T.gradients(()=>r(e),[e],t);return Xg(n),{grad:n[0],value:o}}}function Tq(r){return E(Ys(r),()=>"The f passed in valueAndGrads(f) must be a function"),(e,t)=>{E(Array.isArray(e)&&e.every(o=>o instanceof Me),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),E(t==null||t instanceof Me,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let n=T.gradients(()=>r(...e),e,t);return t!=null&&$t(n.value.shape,t.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Xg(n.grads),n}}function Kg(r,e){E(Ys(r),()=>"The f passed in variableGrads(f) must be a function"),E(e==null||Array.isArray(e)&&e.every(u=>u instanceof Cl),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let t=e!=null;if(!t){e=[];for(let u in T.registeredVariables)e.push(T.registeredVariables[u])}let n=t?e.filter(u=>!u.trainable):null,o=e.length;e=e.filter(u=>u.trainable),E(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:a,grads:i}=T.gradients(r,e,null,s);E(i.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()."),E(a.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`);let l={};return e.forEach((u,c)=>{i[c]!=null&&(l[u.name]=i[c])}),n!=null&&n.forEach(u=>l[u.name]=null),{value:a,grads:l}}function sn(r){return T.customGrad(r)}function Xg(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 Eq(r){let t={x:k(r,"x","neg")};return T.runKernel(ri,t)}var Ke=S({neg_:Eq});function Aq(r){let t={x:k(r,"x","softplus")};return T.runKernel(ga,t)}var po=S({softplus_:Aq});function Dq(r){let e=k(r,"x","logSigmoid");return sn(n=>({value:Ke(po(Ke(n))),gradFunc:a=>P(a,Pr(Ke(n)))}))(e)}var j_=S({logSigmoid_:Dq});function $q(r,e=null,t=!1){let o={x:k(r,"x","max")},s={reductionIndices:e,keepDims:t};return T.runKernel(Yo,o,s)}var Er=S({max_:$q});function Rq(r,e){let t=k(r,"a","sub"),n=k(e,"b","sub");[t,n]=Ue(t,n);let o={a:t,b:n};return T.runKernel(ws,o)}var ce=S({sub_:Rq});function Fq(r,e=null,t=!1){let n=k(r,"x","sum");n.dtype==="bool"&&(n=oe(n,"int32"));let o={x:n},s={axis:e,keepDims:t};return T.runKernel(xs,o,s)}var de=S({sum_:Fq});function Oq(r,e=-1){let t=k(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 sn((o,s)=>{let a=!0,i=Er(o,e,!0),l=ce(o,i),u=ce(oe(l,"float32"),hr(de(nr(l),e,a)));return s([u]),{value:u,gradFunc:(p,m)=>{let[f]=m,d=!0,h=nr(f);return ce(p,P(de(p,e,d),h))}}})(t)}var Eu=S({logSoftmax_:Oq});function U_(r,e){for(let t=0;t<r.length;++t)if(r[r.length-t-1]!==e-1-t)return!1;return!0}function HT(r,e,t){let n=r.length+e.length,o=[],s=0,a=0;for(let i=0;i<n;i++)t.indexOf(i)===-1?o.push(r[s++]):o.push(e[a++]);return o}function q_(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 mo(r,e){let t=e.map(n=>1);return HT(r,t,e)}function Pq(r,e,t){E(U_(e,t),()=>`${r} supports only inner-most axes for now. Got axes ${e} and rank-${t} input.`)}function H_(r,e){if(U_(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 Ff(r){return r.map((e,t)=>[t,e]).sort((e,t)=>e[1]-t[1]).map(e=>e[0])}function Mq(r,e){let t=[];for(let n=e-r;n<e;++n)t.push(n);return t}function Lq(r,e=null,t=!1){let n=k(r,"x","logSumExp"),o=ar(e,n.shape),s=Er(n,o,!0),a=ce(n,s),i=nr(a),l=de(i,o),u=hr(l),c=J(L(s,u.shape),u);if(t){let p=mo(c.shape,o);return L(c,p)}return c}var Of=S({logSumExp_:Lq});function zq(r,e){let t=k(r,"a","logicalAnd","bool"),n=k(e,"b","logicalAnd","bool");Ve(t.shape,n.shape);let o={a:t,b:n};return T.runKernel(oa,o)}var _r=S({logicalAnd_:zq});function Bq(r){let t={x:k(r,"x","logicalNot","bool")};return T.runKernel(iu,t)}var Da=S({logicalNot_:Bq});function Vq(r,e){let t=k(r,"a","logicalOr","bool"),n=k(e,"b","logicalOr","bool");Ve(t.shape,n.shape);let o={a:t,b:n};return T.runKernel(au,o)}var Au=S({logicalOr_:Vq});function Gq(r,e){let t=k(r,"a","logicalXor","bool"),n=k(e,"b","logicalXor","bool");return Ve(t.shape,n.shape),_r(Au(r,e),Da(_r(r,e)))}var K_=S({logicalXor_:Gq});function Wq(r,e,t,n,o){let s=k(r,"x","maxPool"),a=1,i=s,l=!1;s.rank===3&&(l=!0,i=L(s,[1,s.shape[0],s.shape[1],s.shape[2]])),E(i.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),E(Tr(t,a),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${t} and dilations '${a}'`),o!=null&&E(st(n),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`);let u={x:i},c={filterSize:e,strides:t,pad:n,dimRoundingMode:o},p=T.runKernel(Jo,u,c);return l?L(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var $a=S({maxPool_:Wq});function jq(r,e=[1,1,1],t,n,o,s="NDHWC"){let a=k(r,"x","maxPool3d"),i=a,l=!1;a.rank===4&&(l=!0,i=L(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),E(i.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`),E(s==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),o!=null&&E(st(n),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${o} but got pad ${n}.`);let u={x:i},c={filterSize:e,strides:t,pad:n,dimRoundingMode:o,dataFormat:s},p=T.runKernel(gl,u,c);return l?L(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var Pf=S({maxPool3d_:jq});function Uq(r,e,t,n,o=!1){let a={x:k(r,"x","maxPoolWithArgmax")},i={filterSize:e,strides:t,pad:n,includeBatchInIndex:o},l=T.runKernel(up,a,i);return{result:l[0],indexes:l[1]}}var X_=S({maxPoolWithArgmax_:Uq});function qq(r,e){let t=k(r,"a","maximum"),n=k(e,"b","maximum");[t,n]=Ue(t,n),t.dtype==="bool"&&(t=oe(t,"int32"),n=oe(n,"int32")),Ve(t.shape,n.shape);let o={a:t,b:n};return T.runKernel(Zo,o)}var an=S({maximum_:qq});function Hq(r,e=null,t=!1){let o={x:k(r,"x","mean")},s={axis:e,keepDims:t};return T.runKernel(Qo,o,s)}var ht=S({mean_:Hq});function gt(r,e="float32"){if(e==="complex64"){let n=gt(r,"float32"),o=gt(r,"float32");return Fn(n,o)}let t=Gc(ot(r),e);return T.makeTensor(t,r,e)}function or(r,e="float32"){if(e==="complex64"){let n=or(r,"float32"),o=gt(r,"float32");return Fn(n,o)}let t=Jm(ot(r),e);return T.makeTensor(t,r,e)}function Kq(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=k(r,"x","meshgrid",r instanceof Me?r.dtype:"float32");if(e===void 0)return[n];let o=k(e,"y","meshgrid",e instanceof Me?e.dtype:"float32"),s=ot(n.shape),a=ot(o.shape);return t==="xy"?(n=L(n,[1,-1]),o=L(o,[-1,1]),[Be(or([a,1],n.dtype),n),Be(o,or([1,s],o.dtype))]):(n=L(n,[-1,1]),o=L(o,[1,-1]),[Be(n,or([1,a],n.dtype)),Be(or([s,1],o.dtype),o)])}function Xq(r,e=null,t=!1){let o={x:k(r,"x","min")},s={axis:e,keepDims:t};return T.runKernel(es,o,s)}var El=S({min_:Xq});function Yq(r,e){let t=k(r,"a","minimum"),n=k(e,"b","minimum");[t,n]=Ue(t,n),t.dtype==="bool"&&(t=oe(t,"int32"),n=oe(n,"int32")),Ve(t.shape,n.shape);let o={a:t,b:n};return T.runKernel(ts,o)}var Rs=S({minimum_:Yq});function Zq(r,e,t){E(t==="reflect"||t==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${t}.`);let n=k(r,"x","mirrorPad");if(n.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");E(e.length===n.rank,()=>`Padding doesn't match input. Must be ${n.rank}. Got ${e.length}.`);let o=t==="reflect"?1:0;for(let i=0;i<n.rank;i++)E(e[i].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),E(e[i][0]>=0&&e[i][0]<=n.shape[i]-o&&e[i][1]>=0&&e[i][1]<=n.shape[i]-o,()=>`Padding in dimension ${i} cannot be greater than or equal to ${n.shape[i]-o} or less than 0 for input of shape ${n.shape}`);let s={paddings:e,mode:t},a={x:n};return T.runKernel(rs,a,s)}var Mf=S({mirrorPad_:Zq});function Jq(r,e){let t=k(r,"a","mod"),n=k(e,"b","mod");[t,n]=Ue(t,n);let o={a:t,b:n};return T.runKernel(sa,o)}var Lf=S({mod_:Jq});function Qq(r){let e=k(r,"x","square"),t={};return T.runKernel("Square",{x:e},t)}var Le=S({square_:Qq});function eH(r,e=null,t=!1){r=k(r,"x","moments");let n=ar(e,r.shape),o=ht(r,n,t),s=o.shape;t||(s=mo(o.shape,n));let a=Le(ce(oe(r,"float32"),L(o,s))),i=ht(a,n,t);return{mean:o,variance:i}}var Mp=S({moments_:eH});function tH(r,e,t,n){let o=k(e,"data","multiRNNCell"),s=_a(t,"c","multiRNNCell"),a=_a(n,"h","multiRNNCell"),i=o,l=[];for(let p=0;p<r.length;p++){let m=r[p](i,s[p],a[p]);l.push(m[0]),l.push(m[1]),i=m[1]}let u=[],c=[];for(let p=0;p<l.length;p+=2)u.push(l[p]),c.push(l[p+1]);return[u,c]}var rH=S({multiRNNCell_:tH});function nH(r,e,t,n=!1){let o=k(r,"logits","multinomial"),s=o.size,a=o.rank;if(s<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${s}.`);if(a>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${a}`);t=t||Math.random();let l={logits:a===1?L(o,[1,-1]):o},u={numSamples:e,seed:t,normalized:n},c=T.runKernel(cp,l,u);return a===1?L(c,[c.size]):c}var Y_=S({multinomial_:nH});function oH(r,e){let t=k(r,"a","notEqual","string_or_numeric"),n=k(e,"b","notEqual","string_or_numeric");[t,n]=Ue(t,n),Ve(t.shape,n.shape);let o={a:t,b:n};return T.runKernel(ia,o)}var fo=S({notEqual_:oH});function sH(r){let t={x:k(r,"x","onesLike")};return T.runKernel(ni,t)}var ur=S({onesLike_:sH});function iH(r,e){let t=k(r,"v1","outerProduct"),n=k(e,"v2","outerProduct");E(t.rank===1&&n.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${t.rank} and ${n.rank}.`);let o=L(t,[-1,1]),s=L(n,[1,-1]);return Be(o,s)}var aH=S({outerProduct_:iH});function lH(r,e,t=0){let n=k(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 T.runKernel(ss,s,o)}var Wr=S({pad_:lH});function uH(r,e,t=0){return E(e.length===2,()=>"Invalid number of paddings. Must be length of 2."),Wr(r,[e],t)}var cH=S({pad1d_:uH});function pH(r,e,t=0){return E(e.length===2&&e[0].length===2&&e[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Wr(r,e,t)}var mH=S({pad2d_:pH});function fH(r,e,t=0){return E(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."),Wr(r,e,t)}var dH=S({pad3d_:fH});function hH(r,e,t=0){return E(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."),Wr(r,e,t)}var gH=S({pad4d_:hH});function xH(r,e,t){let n=k(r,"x","spaceToBatchND");E(n.rank>=1+e.length,()=>`input rank ${n.rank} should be > than [blockShape] ${e.length}`),E(t.length===e.length,()=>`paddings.shape[0] ${t.length} must be equal to [blockShape] ${e.length}`),E(n.shape.reduce((a,i,l)=>l>0&&l<=e.length?a&&(i+t[l-1][0]+t[l-1][1])%e[l-1]==0:a,!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 T.runKernel(bl,o,s)}var Ra=S({spaceToBatchND_:xH});function yH(r,e,t,n,o,s){o==null&&(o=[1,1]),s==null&&(s=1),n===0&&(n="valid");let a=k(r,"x","maxPool"),i=a,l=!1;a.rank===3&&(l=!0,i=L(a,[1,a.shape[0],a.shape[1],a.shape[2]])),E(Tr(s,o),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${o}'`);let u=N_(i.shape,e,s,o,n),c=[u.dilationHeight,u.dilationWidth],p;n==="same"?p=wH([u.filterHeight,u.filterWidth],c):p=[[0,0],[0,0]];let m=c[0]===1&&c[1]===1,[f,d]=bH([u.inHeight,u.inWidth],c,p),h=m?n:"valid",g=m?i:Ra(i,c,f),b=(t==="avg"?()=>Sa(g,e,s,h):()=>$a(g,e,s,h))(),w=m?b:Na(b,c,d);return l?L(w,[w.shape[1],w.shape[2],w.shape[3]]):w}function bH(r,e,t){let n=t.map(c=>c[0]),o=t.map(c=>c[1]),s=r.concat(n,o),a=e.map((c,p)=>(c-s[p]%c)%c),i=o.map((c,p)=>c+a[p]),l=e.map((c,p)=>[n[p],i[p]]),u=e.map((c,p)=>[0,a[p]]);return[l,u]}function wH(r,e){let n=r.map((a,i)=>a+(a-1)*(e[i]-1)).map(a=>a-1),o=n.map(a=>Math.floor(a/2)),s=n.map((a,i)=>a-o[i]);return n.map((a,i)=>[o[i],s[i]])}var Z_=S({pool_:yH});function _H(r,e){let t=k(r,"base","pow"),n=k(e,"exp","pow");[t,n]=Ue(t,n);let o={a:t,b:n};return T.runKernel(is,o)}var jr=S({pow_:_H});function kH(r,e){let t=k(r,"x","prelu"),n=k(e,"alpha","prelu"),o={x:t,alpha:n};return T.runKernel(as,o)}var Fa=S({prelu_:kH});function vH(r,e=null,t=!1){let n=k(r,"x","prod");n.dtype==="bool"&&(n=oe(n,"int32"));let o={x:n},s={axis:e,keepDims:t};return T.runKernel(ca,o,s)}var Du=S({prod_:vH});function CH(r,e,t){let n=ot(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 T.makeTensor(o,r,t)}var IH=S({rand_:CH});var Zg=nu(sk());var Lp=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 a=s||Math.random();this.random=Zg.alea(a.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,a;do o=2*this.random()-1,s=2*this.random()-1,a=o*o+s*s;while(a>=1||a===0);let i=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*o*i,t=this.mean+this.stdDev*s*i,(!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}},ik=class{constructor(e,t,n,o){this.alpha=e,this.beta=1/t,this.dtype=n;let s=o||Math.random();this.randu=Zg.alea(s.toString()),this.randn=new Lp(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,a;for(;;){do o=this.randn.nextValue(),a=1+this.c*o;while(a<=0);if(a*=a*a,e=o*o,t=1-.331*e*e,n=.5*e+this.d*(1-a+Math.log(a)),s=this.randu(),s<t||Math.log(s)<n)break}return a=1/this.beta*this.d*a,this.alpha<1&&(a*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(a)}convertValue(e){return this.dtype==="float32"?e:Math.round(e)}},ak=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=Zg.alea(o)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function $H(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 ik(e,t,n,o),a=Ie(r,n);for(let i=0;i<a.values.length;i++)a.values[i]=s.nextValue();return a.toTensor()}var RH=S({randomGamma_:$H});function FH(r,e=0,t=1,n,o){if(n!=null&&n==="bool")throw new Error(`Unsupported data type ${n}`);let s=new Lp(e,t,n,!1,o),a=Ie(r,n);for(let i=0;i<a.values.length;i++)a.values[i]=s.nextValue();return a.toTensor()}var Jg=S({randomNormal_:FH});function OH(r,e=0,t=1,n="float32",o){let s=Ie(r,n),a=new ak(e,t,null,o);for(let i=0;i<s.values.length;i++)s.values[i]=a.nextValue();return s.toTensor()}var Fs=S({randomUniform_:OH});function Oa(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 T.runKernel(xl,{},o)}function PH(r){let t={input:k(r,"input","real")};return T.runKernel(pp,t)}var Al=S({real_:PH});function MH(r){let t={x:k(r,"x","reciprocal")};return T.runKernel(pa,t)}var zf=S({reciprocal_:MH});function LH(r){let t={x:k(r,"x","relu")};return T.runKernel(ls,t)}var Mr=S({relu_:LH});function zH(r){let t={x:k(r,"x","relu6")};return T.runKernel(cs,t)}var Ru=S({relu6_:zH});function BH(r,e){let n={x:k(r,"x","reverse")},o={dims:e};return T.runKernel(ps,n,o)}var Jt=S({reverse_:BH});function VH(r){let e=k(r,"x","reverse");return E(e.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${e.rank}.`),Jt(e,0)}var GH=S({reverse1d_:VH});function WH(r,e){let t=k(r,"x","reverse");return E(t.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${t.rank}.`),Jt(t,e)}var jH=S({reverse2d_:WH});function UH(r,e){let t=k(r,"x","reverse");return E(t.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${t.rank}.`),Jt(t,e)}var qH=S({reverse3d_:UH});function HH(r,e){let t=k(r,"x","reverse");return E(t.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${t.rank}.`),Jt(t,e)}var KH=S({reverse4d_:HH});function XH(r){let t={x:k(r,"x","round")};return T.runKernel(ms,t)}var Fu=S({round_:XH});function YH(r){let t={x:k(r,"x","rsqrt")};return T.runKernel(fs,t)}var Ou=S({rsqrt_:YH});function pe(r,e){if((pr(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"&&pr(r)&&!(r instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return rn(r,[],[],e)}function ZH(r){let t={x:k(r,"x","selu")};return T.runKernel(fa,t)}var Pu=S({selu_:ZH});function JH(r,e,t,n,o,s=[1,1],a="NHWC"){let i=k(r,"x","separableConv2d"),l=k(e,"depthwiseFilter","separableConv2d"),u=k(t,"pointwiseFilter","separableConv2d"),c=i,p=!1;if(i.rank===3&&(p=!0,c=L(i,[1,i.shape[0],i.shape[1],i.shape[2]])),a==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");E(c.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`),E(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),E(u.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),E(u.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`),E(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];E(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=Es(c,l,n,o,a,s),g=on(d,u,1,"valid",a);return p?L(g,[g.shape[1],g.shape[2],g.shape[3]]):g}var Bf=S({separableConv2d_:JH});async function QH(r,e){let t=k(r,"x","setdiff1d"),n=k(e,"y","setdiff1d");E(t.dtype===n.dtype,()=>`x and y should have the same dtype, but got x (${t.dtype}) and y (${n.dtype}).`),E(t.rank===1,()=>`x should be 1D tensor, but got x (${t.shape}).`),E(n.rank===1,()=>`y should be 1D tensor, but got y (${n.shape}).`);let o=await t.data(),s=await n.data(),a=new Set(s),i=0;for(let c=0;c<o.length;c++)a.has(o[c])||i++;let l=new ct([i],t.dtype),u=new ct([i],"int32");for(let c=0,p=0;c<o.length;c++)a.has(o[c])||(l.values[p]=o[c],u.values[p]=c,p++);return[l.toTensor(),u.toTensor()]}var lk=QH;function eK(r){let t={x:k(r,"x","sign")};return T.runKernel(ha,t)}var Vf=S({sign_:eK});function tK(r){let t={x:k(r,"x","sin")};return T.runKernel(ds,t)}var Mu=S({sin_:tK});function rK(r){let t={x:k(r,"x","sinh")};return T.runKernel(da,t)}var Lu=S({sinh_:rK});function nK(r,e,t){let n=k(r,"x","slice1d");return E(n.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${n.rank} tensor`),Fe(n,[e],[t])}var Gf=S({slice1d_:nK});function oK(r,e,t){let n=k(r,"x","slice2d");return E(n.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${n.rank} tensor`),Fe(n,e,t)}var Qg=S({slice2d_:oK});function sK(r,e,t){let n=k(r,"x","slice3d");return E(n.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${n.rank} tensor`),Fe(n,e,t)}var Wf=S({slice3d_:sK});function iK(r,e,t){let n=k(r,"x","slice4d");return E(n.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${n.rank} tensor`),Fe(n,e,t)}var zp=S({slice4d_:iK});function aK(r,e=-1){let t=k(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 T.runKernel(ys,n,o)}var Pa=S({softmax_:aK});function lK(r){E(r.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${r.dtype}.`);let e={input:r};return T.runKernel(rp,e)}var Ma=S({fft_:lK});function uK(r){E(r.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${r.dtype}.`);let e={input:r};return T.runKernel(np,e)}var gi=S({ifft_:uK});function cK(r){let e=r.shape[r.shape.length-1],t=r.size/e,n;if(e<=2){let o=L(r,[t,e]);n=gi(o)}else{let o=[t,2*(e-1)],s=L(Al(r),[t,e]),a=L(Su(r),[t,e]),i=Jt(Fe(s,[0,1],[t,e-2]),1),l=P(Jt(Fe(a,[0,1],[t,e-2]),1),pe(-1)),u=et([s,i],1),c=et([a,l],1),p=L(Fn(u,c),[o[0],o[1]]);n=gi(p)}if(n=Al(n),r.rank===3&&r.shape[0]!==0){let o=n,s=r.shape[0];n=L(n,[s,n.shape[0]/s,n.shape[1]]),o.dispose()}return n}var zu=S({irfft_:cK});function pK(r,e,t=0){let o={x:k(r,"x","split")},s={numOrSizeSplits:e,axis:t};return T.runKernel(li,o,s)}var sr=S({split_:pK});function mK(r,e){E(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=Fe(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=et([r,gt(d)],r.shape.length-1),t=e}else o=r;let s=Se(o),a=L(Fn(o,s),[n,t]),i=Ma(a),l=Math.floor(t/2)+1,u=Al(i),c=Su(i),p=sr(u,[l,t-l],u.shape.length-1),m=sr(c,[l,t-l],c.shape.length-1),f=o.shape.slice();return f[o.shape.length-1]=l,L(Fn(p[0],m[0]),f)}var La=S({rfft_:mK});function fK(r){let t={x:k(r,"x","sqrt")};return T.runKernel(gs,t)}var xt=S({sqrt_:fK});function dK(r,e){let t=k(r,"a","squaredDifference"),n=k(e,"b","squaredDifference");[t,n]=Ue(t,n),Ve(t.shape,n.shape);let o={a:t,b:n},s={};return T.runKernel(bs,o,s)}var Bu=S({squaredDifference_:dK});function hK(r,e){let t=k(r,"x","squeeze");return L(t,Pw(t.shape,e).newShape)}var Pn=S({squeeze_:hK});function gK(r,e=0){let t=_a(r,"tensors","stack","string_or_numeric");E(t.length>=1,()=>"Pass at least one tensor to tf.stack"),t.length>0&&E(e<=t[0].rank,()=>"Axis must be <= rank of the tensor");let n=t,o={axis:e};return T.runKernel(oi,n,o)}var Ht=S({stack_:gK});function xK(r,e=0){let n={x:k(r,"x","step")},o={alpha:e};return T.runKernel(oo,n,o)}var Os=S({step_:xK});function yK(r,e,t,n,o=0,s=0,a=0,i=0,l=0){let c={x:k(r,"x","stridedSlice","string_or_numeric")},p={begin:e,end:t,strides:n,beginMask:o,endMask:s,ellipsisMask:a,newAxisMask:i,shrinkAxisMask:l};return T.runKernel(xa,c,p)}var jf=S({stridedSlice_:yK});function bK(r){let t={x:k(r,"x","tan")};return T.runKernel(_s,t)}var Uf=S({tan_:bK});function Dt(r,e){Wn(r);let t=Fr(r,e);if(t.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return rn(r,null,t,e)}function xi(r,e,t){if(Wn(r),e!=null&&e.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let n=Fr(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 rn(r,e,n,t)}function wK(r,e,t){if(Wn(r),e!=null&&e.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let n=Fr(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 rn(r,e,n,t)}function _K(r,e,t){if(Wn(r),e!=null&&e.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let n=Fr(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 rn(r,e,n,t)}function kK(r,e,t){if(Wn(r),e!=null&&e.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let n=Fr(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,rn(r,e,n,t)}function vK(r,e=1,t=!0){let n=k(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},a={k:e,sorted:t},[i,l]=T.runKernel(ya,s,a);return{values:i,indices:l}}var qf=S({topk_:vK});function CK(r,e=0,t=1,n,o){if(n!=null&&n==="bool")throw new Error("Unsupported data type $ { dtype }");let s=new Lp(e,t,n,!0,o),a=Ie(r,n);for(let i=0;i<a.values.length;i++)a.values[i]=s.nextValue();return a.toTensor()}var Vu=S({truncatedNormal_:CK});function IK(r,e=0){let t=k(r,"x","unique","string_or_numeric");E(t.rank>0,()=>"The input tensor must be at least 1D");let n={x:t},o={axis:e},[s,a]=T.runKernel(kp,n,o);return{values:s,indices:a}}var Bp=S({unique_:IK});function SK(r,e,t){let n=k(r,"x","unsortedSegmentSum"),o=k(e,"segmentIds","unsortedSegmentSum","int32");E(st(t),()=>"numSegments must be of dtype int");let s={x:n,segmentIds:o},a={numSegments:t};return T.runKernel(_l,s,a)}var Hf=S({unsortedSegmentSum_:SK});function NK(r,e=0){let t=k(r,"x","unstack","string_or_numeric");E(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 T.runKernel(ui,n,o)}var gr=S({unstack_:NK});function uk(r,e=!0,t,n){return T.makeVariable(r,e,t,n)}function ex(r,e){let t=[];for(let s=0;s<e.length;s++)e[s]&&t.push(s);let n=Ie(r,"int32"),o=Ie([t.length,r.length],"int32");for(let s=0;s<t.length;s++){let a=n.indexToLoc(t[s]),i=s*r.length;o.values.set(a,i)}return o.toTensor()}async function TK(r){let e=k(r,"condition","whereAsync","bool"),t=await e.data(),n=ex(e.shape,t);return r!==e&&e.dispose(),n}var Kf=TK;async function EK(r,e,t){let n=k(r,"tensor","boolMask"),o=k(e,"mask","boolMask","bool"),s=t==null?0:t,a=o.rank,i=n.shape;E(a>0,()=>"mask cannot be scalar"),$t(i.slice(s,s+a),o.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let h=s;h<s+a;h++)l*=i[h];let u=i.slice(0,s).concat([l],i.slice(s+a)),c=L(n,u),p=L(o,[-1]),m=await Kf(p),f=Pn(m,[1]),d=co(c,f,s);return r!==n&&n.dispose(),e!==o&&o.dispose(),f.dispose(),c.dispose(),p.dispose(),m.dispose(),d}var vNe=EK;function AK(r,e="euclidean",t=null,n=!1){r=k(r,"x","norm");let o=lE(r,e,t),s=o.shape;if(n){let a=ar(t,r.shape);s=mo(o.shape,a)}return L(o,s)}function lE(r,e,t=null){if(r.rank===0)return Tt(r);if(r.rank!==1&&t===null)return lE(L(r,[-1]),e,t);if(r.rank===1||typeof t=="number"||Array.isArray(t)&&t.length===1){if(e===1)return de(Tt(r),t);if(e===Infinity)return Er(Tt(r),t);if(e===-Infinity)return El(Tt(r),t);if(e==="euclidean"||e===2)return xt(de(jr(Tt(r),pe(2,"int32")),t));throw new Error(`Error in norm: invalid ord value: ${e}`)}if(Array.isArray(t)&&t.length===2){if(e===1)return Er(de(Tt(r),t[0]),t[1]-1);if(e===Infinity)return Er(de(Tt(r),t[1]),t[0]);if(e===-Infinity)return El(de(Tt(r),t[1]),t[0]);if(e==="fro"||e==="euclidean")return xt(de(Le(r),t));throw new Error(`Error in norm: invalid ord value: ${e}`)}throw new Error(`Error in norm: invalid axis: ${t}`)}var Vp=S({norm_:AK});function DK(r,e,t,n,o=!0){let s=k(r,"v","movingAverage"),a=k(e,"x","movingAverage"),i=k(t,"decay","movingAverage");n_(s,a),E(en(s.shape,a.shape),()=>"Shape mismatch in v and x");let l=pe(1),u=ce(l,i),c=P(ce(a,s),u);if(o){E(n!=null,()=>"When using zeroDebias: true, step is required.");let p=k(n,"step","movingAverage");c=ue(c,ce(l,jr(i,p)))}return J(s,c)}var XNe=S({movingAverage_:DK});function $K(r,e,t){let n=k(r,"indices","scatterND","int32"),o=k(e,"updates","scatterND");Vg(o,n,t);let s={indices:n,updates:o},a={shape:t};return T.runKernel(ma,s,a)}var uE=S({scatterND_:$K});function cE(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 a=e.size;if(!(e.rank===0||e.rank===1&&a===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 RK(r,e,t,n=0){let o=k(r,"sparseIndices","sparseToDense","int32"),s=k(e,"sparseValues","sparseToDense"),a=k(n,"defaultValue","sparseToDense",s.dtype);cE(o,s,t,a);let i={sparseIndices:o,sparseValues:s,defaultValue:a},l={outputShape:t};return T.runKernel(yp,i,l)}var tx=S({sparseToDense_:RK});function FK(r,e){let t=k(e,"indices","gatherND","int32"),o={params:k(r,"x","gatherND","string_or_numeric"),indices:t};return T.runKernel(Yi,o)}var pE=S({gatherND_:FK});function mE(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 OK(r,e,t,n){let o=k(r,"x","dropout");if(E(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.`),E(e>=0&&e<1,()=>`rate must be a float in the range [0, 1), but got ${e}.`),e===0)return r instanceof Me?o.clone():o;let s=mE(o,t),a=1-e,i=ue($s(J(Fs(s,0,1,"float32",n),a)),a);return P(o,i)}var fE=S({dropout_:OK});function dE(r){return Math.floor(Math.pow(2,Math.ceil(Math.log(r)/Math.log(2))))}function rx(r,e,t){let n=1-r%2,o=new Float32Array(r);for(let s=0;s<r;++s){let a=2*Math.PI*s/(r+n-1);o[s]=e-t*Math.cos(a)}return Dt(o,"float32")}async function PK(r,e,t=1){let n=k(r,"predictions","inTopK"),o=k(e,"targets","inTopK");E(n.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${n.rank}`),E(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}`),$t(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];E(t>0&&t<=s,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${s}), but got ${t}`);let a=await n.data(),i=await o.data(),[l,u]=[a.length/s,s],c=Mw("bool",l);for(let p=0;p<l;p++){let m=p*u,f=a.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),c[p]=0;for(let h=0;h<t;h++)if(d[h].index===i[p]){c[p]=1;break}}return r!==n&&n.dispose(),e!==o&&o.dispose(),Nr(c,o.shape,"bool")}var R1e=PK;var ho={};je(ho,{conv2d:()=>hE,depthwiseConv2d:()=>gE,matMul:()=>xE});function MK(r,e,t,n,o,s="NHWC",a){let i=r;r.rank===3&&(i=L(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let l=e;l.rank===3&&(l=L(e,[1,e.shape[0],e.shape[1],e.shape[2]])),E(i.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`),E(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),E(t.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${t}.`);let u=s==="NHWC"?i.shape[3]:i.shape[1],c=s==="NHWC"?l.shape[3]:l.shape[1];E(u===t[2],()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${t[2]}.`),E(c===t[3],()=>`Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${t[3]}).`),a!=null&&E(st(o),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);let p={x:i,dy:l},m={strides:n,pad:o,dataFormat:s,dimRoundingMode:a,filterShape:t};return T.runKernel(Hc,p,m)}var Gp=S({conv2DBackpropFilter_:MK});function Gu(r,e,t){if(t==null||t==="linear")return r;if(t==="relu")return P(r,Os(e));throw new Error(`Cannot compute gradient for fused activation ${t}.`)}function Wu(r,e){let t=e,n=vt(r.shape,e.shape);return n.length>0&&(t=de(t,n)),L(t,r.shape)}function ju(r,e,t,n){if(e==="linear")return r;if(e==="relu")return Mr(r);if(e==="elu")return As(r);if(e==="relu6")return Ru(r);if(e==="prelu")return Fa(r,t);if(e==="leakyrelu")return Aa(r,n);if(e==="sigmoid")return Pr(r);throw new Error(`Unknown fused activation ${e}.`)}var Uu=(r,e)=>!(r>0)||e==="linear";function LK({x:r,filter:e,strides:t,pad:n,dataFormat:o="NHWC",dilations:s=[1,1],dimRoundingMode:a,bias:i,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:c}){if(l=l||"linear",Uu(T.state.gradientDepth,l)===!1){let C=on(r,e,t,n,o,s,a);return i!=null&&(C=J(C,i)),ju(C,l,u,c)}let p=k(r,"x","conv2d"),m=k(e,"filter","conv2d"),f=p,d=!1;p.rank===3&&(d=!0,f=L(p,[1,p.shape[0],p.shape[1],p.shape[2]])),E(f.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${f.rank}.`),E(m.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${m.rank}.`),a!=null&&E(st(n),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${n}.`),E(f.shape[3]===m.shape[2],()=>`Error in conv2d: depth of input (${f.shape[3]}) must match input depth for filter ${m.shape[2]}.`),E(Tr(t,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`),E(o==="NHWC",()=>`Error in conv2d: got dataFormat of ${o} but only NHWC is currently supported.`);let h=wu(f.shape,m.shape,t,s,n,a),g;i!=null&&(g=k(i,"bias","fused conv2d"),[g]=Ue(g,p),Ve(h.outShape,g.shape));let x;u!=null&&(x=k(u,"prelu weights","fused conv2d"));let b=(C,A)=>{let[D,$,R,M]=A,G=Gu(C,R,l);E(Hn(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let j=Op($.shape,G,D,t,n),U=Gp($,G,D.shape,t,n),q=[j,U];if(M!=null){let H=Wu(M,G);q.push(H)}return q},w={x:f,filter:m,bias:g,preluActivationWeights:x},_={strides:t,pad:n,dataFormat:o,dilations:s,dimRoundingMode:a,activation:l,leakyreluAlpha:c};return i==null?sn((A,D,$)=>{let R=T.runKernel(mi,w,_);return $([D,A,R]),d&&(R=L(R,[R.shape[1],R.shape[2],R.shape[3]])),{value:R,gradFunc:b}})(f,m):sn((A,D,$,R)=>{let M=T.runKernel(mi,w,_);return R([D,A,M,$]),d&&(M=L(M,[M.shape[1],M.shape[2],M.shape[3]])),{value:M,gradFunc:b}})(f,m,g)}var hE=S({fusedConv2d_:LK});function zK(r,e,t,n,o,s=[1,1],a){let i=r;r.rank===3&&(i=L(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let l=e;l.rank===3&&(l=L(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u={x:i,dy:l},c={strides:n,pad:o,dimRoundingMode:a,dilations:s,filterShape:t};return T.runKernel(Zc,u,c)}var nx=S({depthwiseConv2dNativeBackpropFilter_:zK});function BK(r,e,t,n,o,s=[1,1],a){let i=e,l=!1;e.rank===3&&(l=!0,i=L(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u={dy:i,filter:t},c={strides:n,pad:o,dimRoundingMode:a,dilations:s,inputShape:r},p=T.runKernel(Jc,u,c);return l?L(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var ox=S({depthwiseConv2dNativeBackpropInput_:BK});function VK({x:r,filter:e,strides:t,pad:n,dataFormat:o="NHWC",dilations:s=[1,1],dimRoundingMode:a,bias:i,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:c}){if(Uu(T.state.gradientDepth,l)===!1){let C=Es(r,e,t,n,o,s,a);return i!=null&&(C=J(C,i)),ju(C,l,u,c)}let p=k(r,"x","depthwiseConv2d"),m=k(e,"filter","depthwiseConv2d"),f=p,d=!1;p.rank===3&&(d=!0,f=L(p,[1,p.shape[0],p.shape[1],p.shape[2]])),E(f.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${f.rank}.`),E(m.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${m.rank}.`),E(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]),E(Tr(t,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`),a!=null&&E(st(n),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${a} but got pad ${n}.`);let h=wu(f.shape,m.shape,t,s,n,a,!0),g;i!=null&&(g=k(i,"bias","fused conv2d"),[g]=Ue(g,p),Ve(h.outShape,g.shape));let x;u!=null&&(x=k(u,"prelu weights","fused depthwiseConv2d"));let b=(C,A)=>{E(Hn(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);let[D,$,R,M]=A,G=Gu(C,R,l),j=ox($.shape,G,D,t,n,s,a),U=nx($,G,D.shape,t,n,s,a);if(M!=null){let q=Wu(g,G);return[j,U,q]}return[j,U]},w={x:f,filter:m,bias:g,preluActivationWeights:x},_={strides:t,pad:n,dataFormat:o,dilations:s,dimRoundingMode:a,activation:l,leakyreluAlpha:c};return i==null?sn((A,D,$)=>{let R=T.runKernel(fi,w,_);return $([D,A,R]),d&&(R=L(R,[R.shape[1],R.shape[2],R.shape[3]])),{value:R,gradFunc:b}})(f,m):sn((A,D,$,R)=>{let M=T.runKernel(fi,w,_);return R([D,A,M,$]),d&&(M=L(M,[M.shape[1],M.shape[2],M.shape[3]])),{value:M,gradFunc:b}})(f,m,g)}var gE=S({fusedDepthwiseConv2d_:VK});function GK({a:r,b:e,transposeA:t=!1,transposeB:n=!1,bias:o,activation:s="linear",preluActivationWeights:a,leakyreluAlpha:i}){if(Uu(T.state.gradientDepth,s)===!1){let M=Be(r,e,t,n);return o!=null&&(M=J(M,o)),ju(M,s,a,i)}let l=k(r,"a","fused matMul"),u=k(e,"b","fused matMul");[l,u]=Ue(l,u);let c=t?l.shape[l.rank-2]:l.shape[l.rank-1],p=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=ot(d),x=ot(h);E(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}.`),E(en(d,h),()=>`Error in fused matMul: outer dimensions (${d}) and (${h}) of Tensors with shapes ${l.shape} and ${u.shape} must match.`),E(c===p,()=>`Error in fused matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${t} and transposeB=${n} must match.`);let b=l.shape.slice(0,-2).concat([m,f]),w=t?L(l,[g,c,m]):L(l,[g,m,c]),_=n?L(u,[x,f,p]):L(u,[x,p,f]),C;o!=null&&(C=k(o,"bias","fused matMul"),[C]=Ue(C,l),Ve(b,C.shape));let A;a!=null&&(A=k(a,"prelu weights","fused matMul"));let D=(M,G)=>{let[j,U,q,H]=G,X=Gu(L(M,q.shape),q,s),ne,Y;if(!t&&!n?(ne=Be(X,U,!1,!0),Y=Be(j,X,!0,!1)):!t&&n?(ne=Be(X,U,!1,!1),Y=Be(X,j,!0,!1)):t&&!n?(ne=Be(U,X,!1,!0),Y=Be(j,X,!1,!1)):(ne=Be(U,X,!0,!0),Y=Be(X,j,!0,!0)),o!=null){let re=Wu(H,X);return[ne,Y,re]}else return[ne,Y]},$={a:w,b:_,bias:C,preluActivationWeights:A},R={transposeA:t,transposeB:n,activation:s,leakyreluAlpha:i};return o==null?sn((G,j,U)=>{let q=T.runKernel(pi,$,R);return U([G,j,q]),{value:L(q,b),gradFunc:D}})(w,_):sn((G,j,U,q)=>{let H=T.runKernel(pi,$,R);return q([G,j,H,U]),{value:L(H,b),gradFunc:D}})(w,_,C)}var xE=S({fusedMatMul_:GK});function WK(r){return rx(r,.54,.46)}var yE=S({hammingWindow_:WK});function jK(r){return rx(r,.5,.5)}var sx=S({hannWindow_:jK});function UK(r,e,t,n=!1,o=0){let s=0,a=[];for(;s+e<=r.size;)a.push(Fe(r,s,e)),s+=t;if(n)for(;s<r.size;){let i=s+e-r.size,l=et([Fe(r,s,e-i),Ds([i],o)]);a.push(l),s+=t}return a.length===0?xi([],[0,e]):L(et(a),[a.length,e])}var ix=S({frame_:UK});function qK(r,e,t,n,o=sx){n==null&&(n=dE(e));let s=ix(r,e,t),a=P(s,o(e));return La(a,n)}var bE=S({stft_:qK});function HK(r,e,t,n,o="bilinear",s=0){let a=k(r,"image","cropAndResize"),i=k(e,"boxes","cropAndResize","float32"),l=k(t,"boxInd","cropAndResize","int32"),u=i.shape[0];E(a.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${a.rank}.`),E(i.rank===2&&i.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${i.shape}.`),E(l.rank===1&&l.shape[0]===u,()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${i.shape}.`),E(n.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${n.length}.`),E(n[0]>=1&&n[1]>=1,()=>`cropSize must be atleast [1,1], but was ${n}`),E(o==="bilinear"||o==="nearest",()=>`method must be bilinear or nearest, but was ${o}`);let c={image:a,boxes:i,boxInd:l},p={method:o,extrapolationValue:s,cropSize:n};return T.runKernel(Wi,c,p)}var wE=S({cropAndResize_:HK});function KK(r){let e=k(r,"image","flipLeftRight","float32");E(e.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${e.rank}.`);let t={image:e};return T.runKernel(Xi,t,{})}var _E=S({flipLeftRight_:KK});function XK(r,e,t=0,n=.5){let o=k(r,"image","rotateWithOffset","float32");E(o.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${o.rank}.`);let s={image:o},a={radians:e,fillValue:t,center:n};return T.runKernel(wa,s,a)}var kE=S({rotateWithOffset_:XK});function go(r,e,t,n,o,s){n==null&&(n=.5),o==null&&(o=Number.NEGATIVE_INFINITY),s==null&&(s=0);let a=r.shape[0];return t=Math.min(t,a),E(0<=n&&n<=1,()=>`iouThreshold must be in [0, 1], but was '${n}'`),E(r.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${r.rank}'`),E(r.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${r.shape[1]}`),E(e.rank===1,()=>"scores must be a 1D tensor"),E(e.shape[0]===a,()=>`scores has incompatible shape with boxes. Expected ${a}, but was ${e.shape[0]}`),E(0<=s&&s<=1,()=>`softNmsSigma must be in [0, 1], but was '${s}'`),{maxOutputSize:t,iouThreshold:n,scoreThreshold:o,softNmsSigma:s}}function YK(r,e,t,n=.5,o=Number.NEGATIVE_INFINITY){let s=k(r,"boxes","nonMaxSuppression"),a=k(e,"scores","nonMaxSuppression"),i=go(s,a,t,n,o);t=i.maxOutputSize,n=i.iouThreshold,o=i.scoreThreshold;let l={maxOutputSize:t,iouThreshold:n,scoreThreshold:o};return T.runKernel(aa,{boxes:s,scores:a},l)}var vE=S({nonMaxSuppression_:YK});function CE(r,e,t){let n=ZK(r,e,t),o=n<0?-(n+1):n;r.splice(o,0,e)}function ZK(r,e,t){return QK(r,e,t||JK)}function JK(r,e){return r>e?1:r<e?-1:0}function QK(r,e,t){let n=0,o=r.length,s=0,a=!1;for(;n<o;){s=n+(o-n>>>1);let i=t(e,r[s]);i>0?n=s+1:(o=s,a=!i)}return a?n:-n-1}function ax(r,e,t,n,o){return ck(r,e,t,n,o,0)}function lx(r,e,t,n,o,s){return ck(r,e,t,n,o,0,!1,s,!0)}function ux(r,e,t,n,o,s){return ck(r,e,t,n,o,s,!0)}function ck(r,e,t,n,o,s,a=!1,i=!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(IE);let c=s>0?-.5/s:0,p=[],m=[];for(;p.length<t&&u.length>0;){let g=u.pop(),{score:x,boxIndex:b,suppressBeginIndex:w}=g;if(x<o)break;let _=!1;for(let C=p.length-1;C>=w;--C){let A=e6(r,b,p[C]);if(A>=n){_=!0;break}if(g.score=g.score*t6(n,c,A),g.score<=o)break}g.suppressBeginIndex=p.length,_||(g.score===x?(p.push(b),m.push(g.score)):g.score>o&&CE(u,g,IE))}let f=p.length,d=t-f;i&&d>0&&(p.push(...new Array(d).fill(0)),m.push(...new Array(d).fill(0)));let h={selectedIndices:p};return a&&(h.selectedScores=m),l&&(h.validOutputs=f),h}function e6(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]),a=Math.min(n[1],n[3]),i=Math.max(n[0],n[2]),l=Math.max(n[1],n[3]),u=Math.min(o[0],o[2]),c=Math.min(o[1],o[3]),p=Math.max(o[0],o[2]),m=Math.max(o[1],o[3]),f=(i-s)*(l-a),d=(p-u)*(m-c);if(f<=0||d<=0)return 0;let h=Math.max(s,u),g=Math.max(a,c),x=Math.min(i,p),b=Math.min(l,m),w=Math.max(x-h,0)*Math.max(b-g,0);return w/(f+d-w)}function t6(r,e,t){let n=Math.exp(e*t*t);return t<=r?n:0}function IE(r,e){return r.score-e.score||r.score===e.score&&e.boxIndex-r.boxIndex}async function r6(r,e,t,n=.5,o=Number.NEGATIVE_INFINITY){let s=k(r,"boxes","nonMaxSuppressionAsync"),a=k(e,"scores","nonMaxSuppressionAsync"),i=go(s,a,t,n,o);t=i.maxOutputSize,n=i.iouThreshold,o=i.scoreThreshold;let l=await Promise.all([s.data(),a.data()]),u=l[0],c=l[1],{selectedIndices:p}=ax(u,c,t,n,o);return s!==r&&s.dispose(),a!==e&&a.dispose(),Dt(p,"int32")}var SE=r6;function n6(r,e,t,n=.5,o=Number.NEGATIVE_INFINITY,s=0){let a=k(r,"boxes","nonMaxSuppression"),i=k(e,"scores","nonMaxSuppression"),l=go(a,i,t,n,o,s);t=l.maxOutputSize,n=l.iouThreshold,o=l.scoreThreshold,s=l.softNmsSigma;let u={boxes:a,scores:i},c={maxOutputSize:t,iouThreshold:n,scoreThreshold:o,softNmsSigma:s},p=T.runKernel(ua,u,c);return{selectedIndices:p[0],selectedScores:p[1]}}var NE=S({nonMaxSuppressionWithScore_:n6});async function o6(r,e,t,n=.5,o=Number.NEGATIVE_INFINITY,s=0){let a=k(r,"boxes","nonMaxSuppressionAsync"),i=k(e,"scores","nonMaxSuppressionAsync"),l=go(a,i,t,n,o,s);t=l.maxOutputSize,n=l.iouThreshold,o=l.scoreThreshold,s=l.softNmsSigma;let u=await Promise.all([a.data(),i.data()]),c=u[0],p=u[1],{selectedIndices:m,selectedScores:f}=ux(c,p,t,n,o,s);return a!==r&&a.dispose(),i!==e&&i.dispose(),{selectedIndices:Dt(m,"int32"),selectedScores:Dt(f)}}var TE=o6;function s6(r,e,t,n=.5,o=Number.NEGATIVE_INFINITY,s=!1){let a=k(r,"boxes","nonMaxSuppression"),i=k(e,"scores","nonMaxSuppression"),l=go(a,i,t,n,o,null),u=l.maxOutputSize,c=l.iouThreshold,p=l.scoreThreshold,m={boxes:a,scores:i},f={maxOutputSize:u,iouThreshold:c,scoreThreshold:p,padToMaxOutputSize:s},d=T.runKernel(la,m,f);return{selectedIndices:d[0],validOutputs:d[1]}}var EE=S({nonMaxSuppressionPadded_:s6});async function i6(r,e,t,n=.5,o=Number.NEGATIVE_INFINITY,s=!1){let a=k(r,"boxes","nonMaxSuppressionAsync"),i=k(e,"scores","nonMaxSuppressionAsync"),l=go(a,i,t,n,o,null),u=l.maxOutputSize,c=l.iouThreshold,p=l.scoreThreshold,[m,f]=await Promise.all([a.data(),i.data()]),{selectedIndices:d,validOutputs:h}=lx(m,f,u,c,p,s);return a!==r&&a.dispose(),i!==e&&i.dispose(),{selectedIndices:Dt(d,"int32"),validOutputs:pe(h,"int32")}}var AE=i6;function a6(r,e,t=!1,n=!1){let o=k(r,"images","resizeBilinear");E(o.rank===3||o.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${o.rank}.`),E(e.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${e}.`),E(n===!1||t===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let s=o,a=!1;o.rank===3&&(a=!0,s=L(o,[1,o.shape[0],o.shape[1],o.shape[2]]));let[]=e,i={images:s},l={alignCorners:t,halfPixelCenters:n,size:e},u=T.runKernel(us,i,l);return a?L(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var cx=S({resizeBilinear_:a6});function l6(r,e,t=!1,n=!1){let o=k(r,"images","resizeNearestNeighbor");E(o.rank===3||o.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${o.rank}.`),E(e.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${e}.`),E(o.dtype==="float32"||o.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),E(n===!1||t===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let s=o,a=!1;o.rank===3&&(a=!0,s=L(o,[1,o.shape[0],o.shape[1],o.shape[2]]));let[]=e,i={images:s},l={alignCorners:t,halfPixelCenters:n,size:e},u=T.runKernel(yl,i,l);return a?L(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var px=S({resizeNearestNeighbor_:l6});function u6(r,e="binary",t=!1,n=.5){let o=k(r,"image","threshold"),s=.2989,a=.587,i=.114,l=o.shape[0]*o.shape[1],u=P(Dt([n]),255),c,p,m,f;if(E(o.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${o.rank}.`),E(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]}.`),E(o.dtype==="int32"||o.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${o.dtype}.`),E(e==="otsu"||e==="binary",()=>`Method must be binary or otsu, but was ${e}`),o.shape[2]===3){[c,p,m]=sr(o,[1,1,1],-1);let g=P(c,s),x=P(p,a),b=P(m,i);f=J(J(g,x),b)}else f=r;if(e==="otsu"){let g=Cf(oe(Fu(f),"int32"),Nr([]),256);u=c6(g,l)}let d=t?kn(f,u):qt(f,u);return oe(P(d,255),"int32")}function c6(r,e){let t=Dt([-1]),n=Dt([0]),o=Dt([0]),s,a,i,l,u,c;for(let p=0;p<r.size-1;p++){s=Fe(r,0,p+1),a=Fe(r,p+1),u=ue(de(s),e),c=ue(de(a),e);let m=de(P(s,Oa(0,s.size)));i=ue(m,de(s));let f=Ds(a.shape,s.size),d=J(Oa(0,a.size),f),h=P(a,d);l=ue(de(h),de(a));let g=ce(i,l),x=ce(i,l),b=P(u,c);o=P(P(b,g),x);let w=qt(o,n);n=Ct(w,o,n),t=Ct(w,Dt([p]),t)}return t}var DE=S({threshold_:u6});function p6(r,e,t="nearest",n="constant",o=0,s){let a=k(r,"image","transform","float32"),i=k(e,"transforms","transform","float32");E(a.rank===4,()=>`Error in transform: image must be rank 4,but got rank ${a.rank}.`),E(i.rank===2&&(i.shape[0]===a.shape[0]||i.shape[0]===1)&&i.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),E(s==null||s.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${s}.`);let l={image:a,transforms:i},u={interpolation:t,fillMode:n,fillValue:o,outputShape:s};return T.runKernel(ba,l,u)}var $E=S({transform_:p6});function m6(r,e,t){E(e%1==0,()=>`bandPart(): numLower must be an integer, got ${e}.`),E(t%1==0,()=>`bandPart(): numUpper must be an integer, got ${t}.`);let n=k(r,"a","bandPart");E(n.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${n.rank}.`);let o=n.shape,[s,a]=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<=a))throw new Error(`bandPart(): numUpper (${t}) must not be greater than the number of columns (${a}).`);e<0&&(e=s),t<0&&(t=a);let i=L(Oa(0,s,1,"int32"),[-1,1]),l=Oa(0,a,1,"int32"),u=ce(i,l),c=_r(kn(u,pe(+e,"int32")),_n(u,pe(-t,"int32"))),p=gt([s,a],n.dtype);return L(Ht(gr(L(n,[-1,s,a])).map(m=>Ct(c,m,p))),o)}var RE=S({bandPart_:m6});function f6(r){let e;if(Array.isArray(r)){e=!1,E(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)E(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=sr(r,r.shape[0],0).map(o=>Pn(o,[0]));E(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(T.tidy(()=>{let s=n[o];if(o>0)for(let a=0;a<o;++a){let i=P(de(P(t[a],s)),t[a]);s=ce(s,i)}return ue(s,Vp(s,"euclidean"))}));return e?Ht(t,0):t}var FE=S({gramSchmidt_:f6});function d6(r,e=!1){if(E(r.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${r.rank}`),r.rank===2)return OE(r,e);{let t=r.shape.slice(0,r.shape.length-2).reduce((l,u)=>l*u),n=gr(L(r,[t,r.shape[r.shape.length-2],r.shape[r.shape.length-1]]),0),o=[],s=[];n.forEach(l=>{let[u,c]=OE(l,e);o.push(u),s.push(c)});let a=L(Ht(o,0),r.shape),i=L(Ht(s,0),r.shape);return[a,i]}}function OE(r,e=!1){return T.tidy(()=>{E(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=Pp(t),s=qn(r),a=xi([[1]],[1,1]),i=qn(a),l=t>=n?n:t;for(let u=0;u<l;++u){let c=s,p=i,m=o;[i,s,o]=T.tidy(()=>{let f=Fe(s,[u,u],[t-u,1]),d=Vp(f),h=Fe(s,[u,u],[1,1]),g=Ct(qt(h,0),xi([[-1]]),xi([[1]])),x=ce(h,P(g,d)),b=ue(f,x);b.shape[0]===1?i=qn(a):i=et([a,Fe(b,[1,0],[b.shape[0]-1,b.shape[1]])],0);let w=Ke(ue(Be(g,x),d)),_=Fe(s,[u,0],[t-u,n]),C=P(w,i),A=qe(i);if(u===0)s=ce(_,Be(C,Be(A,_)));else{let R=ce(_,Be(C,Be(A,_)));s=et([Fe(s,[0,0],[u,n]),R],0)}let D=qe(C),$=Fe(o,[0,u],[t,o.shape[1]-u]);if(u===0)o=ce($,Be(Be($,i),D));else{let R=ce($,Be(Be($,i),D));o=et([Fe(o,[0,0],[t,u]),R],1)}return[i,s,o]}),De([c,p,m])}return!e&&t>n&&(o=Fe(o,[0,0],[t,n]),s=Fe(s,[0,0],[n,n])),[o,s]})}var PE=S({qr_:d6});var Kt;(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"})(Kt||(Kt={}));function h6(r,e,t=Kt.SUM_BY_NONZERO_WEIGHTS){let n=k(r,"losses","computeWeightedLoss"),o=null;e!=null&&(o=k(e,"weights","computeWeightedLoss"));let s=o==null?n:P(n,o);if(t===Kt.NONE)return s;if(t===Kt.SUM)return de(s);if(t===Kt.MEAN){if(o==null)return ht(s);{let a=n.size/o.size,i=ue(de(s),de(o));return a>1?ue(i,pe(a)):i}}if(t===Kt.SUM_BY_NONZERO_WEIGHTS){if(o==null)return ue(de(s),pe(n.size));{let a=P(o,or(n.shape)),i=oe(de(fo(a,pe(0))),"float32");return ue(de(s),i)}}throw Error(`Unknown reduction: ${t}`)}var Lr=S({computeWeightedLoss_:h6});function g6(r,e,t,n=Kt.SUM_BY_NONZERO_WEIGHTS){let o=k(r,"labels","absoluteDifference"),s=k(e,"predictions","absoluteDifference"),a=null;t!=null&&(a=k(t,"weights","absoluteDifference")),$t(o.shape,s.shape,"Error in absoluteDifference: ");let i=Tt(ce(o,s));return Lr(i,a,n)}var ME=S({absoluteDifference_:g6});function x6(r,e,t,n,o=Kt.SUM_BY_NONZERO_WEIGHTS){let s=k(r,"labels","cosineDistance"),a=k(e,"predictions","cosineDistance"),i=null;n!=null&&(i=k(n,"weights","cosineDistance")),$t(s.shape,a.shape,"Error in cosineDistance: ");let l=pe(1),u=ce(l,de(P(s,a),t,!0));return Lr(u,i,o)}var LE=S({cosineDistance_:x6});function y6(r,e,t,n=Kt.SUM_BY_NONZERO_WEIGHTS){let o=k(r,"labels","hingeLoss"),s=k(e,"predictions","hingeLoss"),a=null;t!=null&&(a=k(t,"weights","hingeLoss")),$t(o.shape,s.shape,"Error in hingeLoss: ");let i=pe(1);o=ce(P(pe(2),o),i);let l=Mr(ce(i,P(o,s)));return Lr(l,a,n)}var zE=S({hingeLoss_:y6});function b6(r,e,t,n=1,o=Kt.SUM_BY_NONZERO_WEIGHTS){let s=k(r,"labels","huberLoss"),a=k(e,"predictions","huberLoss"),i=null;t!=null&&(i=k(t,"weights","huberLoss")),$t(s.shape,a.shape,"Error in huberLoss: ");let l=pe(n),u=Tt(ce(a,s)),c=Rs(u,l),p=ce(u,c),m=J(P(pe(.5),Le(c)),P(l,p));return Lr(m,i,o)}var BE=S({huberLoss_:b6});function w6(r,e,t,n=1e-7,o=Kt.SUM_BY_NONZERO_WEIGHTS){let s=k(r,"labels","logLoss"),a=k(e,"predictions","logLoss"),i=null;t!=null&&(i=k(t,"weights","logLoss")),$t(s.shape,a.shape,"Error in logLoss: ");let l=pe(1),u=pe(n),c=Ke(P(s,hr(J(a,u)))),p=P(ce(l,s),hr(J(ce(l,a),u))),m=ce(c,p);return Lr(m,i,o)}var VE=S({logLoss_:w6});function _6(r,e,t,n=Kt.SUM_BY_NONZERO_WEIGHTS){let o=k(r,"labels","meanSquaredError"),s=k(e,"predictions","meanSquaredError"),a=null;t!=null&&(a=k(t,"weights","meanSquaredError")),$t(o.shape,s.shape,"Error in meanSquaredError: ");let i=Bu(o,s);return Lr(i,a,n)}var GE=S({meanSquaredError_:_6});function k6(r,e){let t=k(r,"labels","sigmoidCrossEntropyWithLogits"),n=k(e,"logits","sigmoidCrossEntropyWithLogits");$t(t.shape,n.shape,"Error in sigmoidCrossEntropyWithLogits: ");let o=Mr(n),s=P(n,t),a=Tu(nr(Ke(Tt(n))));return J(ce(o,s),a)}function v6(r,e,t,n=0,o=Kt.SUM_BY_NONZERO_WEIGHTS){let s=k(r,"multiClassLabels","sigmoidCrossEntropy"),a=k(e,"logits","sigmoidCrossEntropy"),i=null;if(t!=null&&(i=k(t,"weights","sigmoidCrossEntropy")),$t(s.shape,a.shape,"Error in sigmoidCrossEntropy: "),n>0){let u=pe(n),c=pe(1),p=pe(.5);s=J(P(s,ce(c,u)),P(p,u))}let l=k6(s,a);return Lr(l,i,o)}var WE=S({sigmoidCrossEntropy_:v6});function C6(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 sn((o,s,a)=>{let l=Of(s,[t],!0),u=ce(oe(s,"float32"),l);a([o,u]);let c=Ke(P(u,o));return{value:de(c,[t]),gradFunc:(f,d)=>{let[h,g]=d,x=mo(f.shape,[t]);return[P(L(f,x),ce(oe(h,"float32"),nr(g))),P(L(f,x),ce(nr(g),oe(h,"float32")))]}}})(r,e)}function I6(r,e,t,n=0,o=Kt.SUM_BY_NONZERO_WEIGHTS){let s=k(r,"onehotLabels","softmaxCrossEntropy"),a=k(e,"logits","softmaxCrossEntropy"),i=null;if(t!=null&&(i=k(t,"weights","softmaxCrossEntropy")),$t(s.shape,a.shape,"Error in softmaxCrossEntropy: "),n>0){let u=pe(n),c=pe(1),p=pe(s.shape[1]);s=J(P(s,ce(c,u)),ue(u,p))}let l=C6(s,a);return Lr(l,i,o)}var jE=S({softmaxCrossEntropy_:I6});function S6(r,e,t,n){let o=k(r,"indices","sparseFillEmptyRows"),s=k(e,"values","sparseFillEmptyRows"),a=k(t,"denseShape","sparseFillEmptyRows"),i=k(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(a.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${a.shape}`);if(i.rank!==0)throw new Error(`Default value should be a scalar but received shape ${i.shape}`);let l={indices:o,values:s,denseShape:a,defaultValue:i},u=T.runKernel(dp,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}var UE=S({sparseFillEmptyRows_:S6});function N6(r,e,t){let n=k(r,"inputIndices","sparseReshape"),o=k(e,"inputShape","sparseReshape"),s=k(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 a={inputIndices:n,inputShape:o,newShape:s},i=T.runKernel(hp,a);return{outputIndices:i[0],outputShape:i[1]}}var qE=S({sparseReshape_:N6});function T6(r,e,t){let n=k(r,"data","sparseSegmentMean"),o=k(e,"indices","sparseSegmentMean"),s=k(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 a={data:n,indices:o,segmentIds:s};return T.runKernel(gp,a)}var HE=S({sparseSegmentMean_:T6});function E6(r,e,t){let n=k(r,"data","sparseSegmentSum"),o=k(e,"indices","sparseSegmentSum"),s=k(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 a={data:n,indices:o,segmentIds:s};return T.runKernel(xp,a)}var KE=S({sparseSegmentSum_:E6});function A6(r,e,t,n,o,s,a,i){let l=k(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=k(e,"dataSplits","stringNGrams");if(u.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let c={separator:t,nGramWidths:n,leftPad:o,rightPad:s,padWidth:a,preserveShortSequences:i},p={data:l,dataSplits:u},m=T.runKernel(bp,p,c);return{nGrams:m[0],nGramsSplits:m[1]}}var XE=S({stringNGrams_:A6});function D6(r,e,t=!0){let n=k(r,"input","stringSplit","string"),o=k(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},a={input:n,delimiter:o},i=T.runKernel(wp,a,s);return{indices:i[0],values:i[1],shape:i[2]}}var YE=S({stringSplit_:D6});function $6(r,e){let t=k(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 T.runKernel(_p,o,n)}var ZE=S({stringToHashBucketFast_:$6});var qRe={fft:Ma,ifft:gi,rfft:La,irfft:zu},ZRe={hammingWindow:yE,hannWindow:sx,frame:ix,stft:bE},yi={flipLeftRight:_E,resizeNearestNeighbor:px,resizeBilinear:cx,rotateWithOffset:kE,cropAndResize:wE,nonMaxSuppression:vE,nonMaxSuppressionAsync:SE,nonMaxSuppressionWithScore:NE,nonMaxSuppressionWithScoreAsync:TE,nonMaxSuppressionPadded:EE,nonMaxSuppressionPaddedAsync:AE,threshold:DE,transform:$E},JE={bandPart:RE,gramSchmidt:FE,qr:PE},vFe={absoluteDifference:ME,computeWeightedLoss:Lr,cosineDistance:LE,hingeLoss:zE,huberLoss:BE,logLoss:VE,meanSquaredError:GE,sigmoidCrossEntropy:WE,softmaxCrossEntropy:jE},Xf={sparseFillEmptyRows:UE,sparseReshape:qE,sparseSegmentMean:HE,sparseSegmentSum:KE},mx={stringNGrams:XE,stringSplit:YE,stringToHashBucketFast:ZE};var Ur=class extends jg{minimize(e,t=!1,n){let{value:o,grads:s}=this.computeGradients(e,n);if(n!=null){let a=n.map(i=>({name:i.name,tensor:s[i.name]}));this.applyGradients(a)}else this.applyGradients(s);return De(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 Kg(e,t)}dispose(){this.iterations_!=null&&De(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:pe(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(Ur,Symbol.hasInstance,{value:r=>r.minimize!=null&&r.computeGradients!=null&&r.applyGradients!=null});var qu=class extends Ur{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=T.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,o)=>{let s=T.registeredVariables[n],a=!1;this.accumulatedGrads[o]==null&&(this.accumulatedGrads[o]={originalName:`${n}/accum_grad`,variable:B(()=>Se(s).variable(a))}),this.accumulatedUpdates[o]==null&&(this.accumulatedUpdates[o]={originalName:`${n}/accum_var`,variable:B(()=>Se(s).variable(a))});let i=Array.isArray(e)?e[o].tensor:e[n];if(i==null)return;let l=this.accumulatedGrads[o].variable,u=this.accumulatedUpdates[o].variable;B(()=>{let c=J(P(l,this.rho),P(Le(i),1-this.rho)),p=P(ue(xt(J(u,this.epsilon)),xt(J(l,this.epsilon))),i),m=J(P(u,this.rho),P(Le(p),1-this.rho));l.assign(c),u.assign(m);let f=J(P(p,-this.learningRate),s);s.assign(f)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(De(this.accumulatedGrads.map(e=>e.variable)),De(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)}};qu.className="Adadelta";wn(qu);var Hu=class extends Ur{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=T.registeredVariables[n];if(this.accumulatedGrads[o]==null){let l=!1;this.accumulatedGrads[o]={originalName:`${n}/accumulator`,variable:B(()=>Ds(s.shape,this.initialAccumulatorValue).variable(l))}}let a=Array.isArray(e)?e[o].tensor:e[n];if(a==null)return;let i=this.accumulatedGrads[o].variable;B(()=>{let l=J(i,Le(a));i.assign(l);let u=J(P(ue(a,xt(J(l,T.backend.epsilon()))),-this.learningRate),s);s.assign(u)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&De(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)}};Hu.className="Adagrad";wn(Hu);var Ku=class extends Ur{constructor(e,t,n,o=null){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=o,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],B(()=>{this.accBeta1=pe(t).variable(),this.accBeta2=pe(n).variable()}),o==null&&(this.epsilon=T.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);B(()=>{let n=ce(1,this.accBeta1),o=ce(1,this.accBeta2);t.forEach((s,a)=>{let i=T.registeredVariables[s],l=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${s}/m`,variable:B(()=>Se(i).variable(l))}),this.accumulatedSecondMoment[a]==null&&(this.accumulatedSecondMoment[a]={originalName:`${s}/v`,variable:B(()=>Se(i).variable(l))});let u=Array.isArray(e)?e[a].tensor:e[s];if(u==null)return;let c=this.accumulatedFirstMoment[a].variable,p=this.accumulatedSecondMoment[a].variable,m=J(P(c,this.beta1),P(u,1-this.beta1)),f=J(P(p,this.beta2),P(Le(u),1-this.beta2)),d=ue(m,n),h=ue(f,o);c.assign(m),p.assign(f);let g=J(P(ue(d,J(xt(h),this.epsilon)),-this.learningRate),i);i.assign(g)}),this.accBeta1.assign(P(this.accBeta1,this.beta1)),this.accBeta2.assign(P(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&De(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&De(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),B(()=>{this.accBeta1.assign(jr(this.beta1,this.iterations_+1)),this.accBeta2.assign(jr(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)}};Ku.className="Adam";wn(Ku);var Xu=class extends Ur{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=[],B(()=>{this.iteration=pe(0).variable(),this.accBeta1=pe(t).variable()}),o==null&&(this.epsilon=T.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);B(()=>{let n=ce(1,this.accBeta1),o=ue(-this.learningRate,J(P(this.iteration,this.decay),1));t.forEach((s,a)=>{let i=T.registeredVariables[s],l=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${s}/m`,variable:Se(i).variable(l)}),this.accumulatedWeightedInfNorm[a]==null&&(this.accumulatedWeightedInfNorm[a]={originalName:`${s}/v`,variable:Se(i).variable(l)});let u=Array.isArray(e)?e[a].tensor:e[s];if(u==null)return;let c=this.accumulatedFirstMoment[a].variable,p=this.accumulatedWeightedInfNorm[a].variable,m=J(P(c,this.beta1),P(u,1-this.beta1)),f=P(p,this.beta2),d=Tt(u),h=an(f,d);c.assign(m),p.assign(h);let g=J(P(ue(o,n),ue(m,J(h,this.epsilon))),i);i.assign(g)}),this.iteration.assign(J(this.iteration,1)),this.accBeta1.assign(P(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&De(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&De(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)}};Xu.className="Adamax";wn(Xu);var za=class extends Ur{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 a=T.registeredVariables[n];B(()=>{let i=J(P(this.c,s),a);a.assign(i)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=Rt(pe(-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)}};za.className="SGD";wn(za);var Yu=class extends za{constructor(e,t,n=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=pe(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,o)=>{let s=T.registeredVariables[n];if(this.accumulations[o]==null){let l=!1;this.accumulations[o]={originalName:`${n}/momentum`,variable:B(()=>Se(s).variable(l))}}let a=this.accumulations[o].variable,i=Array.isArray(e)?e[o].tensor:e[n];i!=null&&B(()=>{let l,u=J(P(this.m,a),i);this.useNesterov?l=J(P(this.c,J(i,P(u,this.m))),s):l=J(P(this.c,u),s),a.assign(u),s.assign(l)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&De(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)}};Yu.className="Momentum";wn(Yu);var Zu=class extends Ur{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=T.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=T.registeredVariables[n],a=!1;this.accumulatedMeanSquares[o]==null&&(this.accumulatedMeanSquares[o]={originalName:`${n}/rms`,variable:B(()=>Se(s).variable(a))}),this.accumulatedMoments[o]==null&&(this.accumulatedMoments[o]={originalName:`${n}/momentum`,variable:B(()=>Se(s).variable(a))}),this.accumulatedMeanGrads[o]==null&&this.centered&&(this.accumulatedMeanGrads[o]={originalName:`${n}/mg`,variable:B(()=>Se(s).variable(a))});let i=Array.isArray(e)?e[o].tensor:e[n];if(i==null)return;let l=this.accumulatedMeanSquares[o].variable,u=this.accumulatedMoments[o].variable;B(()=>{let c=J(P(l,this.decay),P(Le(i),1-this.decay));if(this.centered){let p=this.accumulatedMeanGrads[o].variable,m=J(P(p,this.decay),P(i,1-this.decay)),f=ue(P(i,this.learningRate),xt(ce(c,J(Le(m),this.epsilon)))),d=J(P(u,this.momentum),f);l.assign(c),p.assign(m),u.assign(d);let h=ce(s,d);s.assign(h)}else{let p=J(P(l,this.decay),P(Le(i),1-this.decay)),m=J(P(u,this.momentum),ue(P(i,this.learningRate),xt(J(p,this.epsilon))));l.assign(p),u.assign(m);let f=ce(s,m);s.assign(f)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&De(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&De(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&De(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)}};Zu.className="RMSProp";wn(Zu);var Ba=class{static sgd(e){return new za(e)}static momentum(e,t,n=!1){return new Yu(e,t,n)}static rmsprop(e,t=.9,n=0,o=null,s=!1){return new Zu(e,t,n,o,s)}static adam(e=.001,t=.9,n=.999,o=null){return new Ku(e,t,n,o)}static adadelta(e=.001,t=.95,n=null){return new qu(e,t,n)}static adamax(e=.002,t=.9,n=.999,o=null,s=0){return new Xu(e,t,n,o,s)}static adagrad(e,t=.1){return new Hu(e,t)}};var Ju={sgd:Ba.sgd,momentum:Ba.momentum,adadelta:Ba.adadelta,adagrad:Ba.adagrad,rmsprop:Ba.rmsprop,adamax:Ba.adamax,adam:Ba.adam};var R6=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:r=>r())();function Yf(){return new Promise(r=>R6(()=>r()))}var I={};je(I,{ERF_A1:()=>j6,ERF_A2:()=>U6,ERF_A3:()=>q6,ERF_A4:()=>H6,ERF_A5:()=>K6,ERF_P:()=>W6,PARALLELIZE_THRESHOLD:()=>fx,SELU_SCALE:()=>mk,SELU_SCALEALPHA:()=>pk,applyActivation:()=>ju,assertAndGetBroadcastShape:()=>Ve,assertAxesAreInnerMostDims:()=>Pq,assertParamsConsistent:()=>F6,assignToTypedArray:()=>r5,axesAreInnerMostDims:()=>U_,calculateShapes:()=>TT,checkEinsumDimSizes:()=>l5,combineLocations:()=>HT,complexWithEvenIndex:()=>Q6,complexWithOddIndex:()=>e5,computeConv2DInfo:()=>wu,computeConv3DInfo:()=>jT,computeDefaultPad:()=>T_,computeDilation2DInfo:()=>aU,computeOptimalWindowSize:()=>P6,computeOutAndReduceShapes:()=>q_,computeOutShape:()=>O6,computePool2DInfo:()=>N_,computePool3DInfo:()=>lU,convertConv2DDataFormat:()=>UT,decodeEinsumEquation:()=>i5,eitherStridesOrDilationsAreOne:()=>Tr,expandShapeToKeepDim:()=>mo,exponent:()=>o5,exponents:()=>n5,fromStringArrayToUint8:()=>x5,fromUint8ToStringArray:()=>g5,getAxesPermutation:()=>H_,getBroadcastDims:()=>ZU,getComplexWithIndex:()=>t5,getEinsumComputePath:()=>u5,getEinsumPermutation:()=>a5,getFusedBiasGradient:()=>Wu,getFusedDyActivation:()=>Gu,getImageCenter:()=>M6,getInnerMostAxes:()=>Mq,getPermuted:()=>z6,getReductionAxes:()=>vt,getReshaped:()=>L6,getReshapedPermuted:()=>B6,getSliceBeginCoords:()=>V6,getSliceSize:()=>G6,getUndoAxesPermutation:()=>Ff,isIdentityPermutation:()=>c5,log:()=>Y6,mergeRealAndImagArrays:()=>Z6,prepareAndValidate:()=>NT,prepareSplitSize:()=>m5,segment_util:()=>dk,shouldFuse:()=>Uu,slice_util:()=>lr,splitRealAndImagArrays:()=>J6,tupleValuesAreOne:()=>Hn,upcastType:()=>mr,validateInput:()=>Vg,validateUpdateShape:()=>__,warn:()=>X6});function F6(r,e){let t=r[0].length;r.forEach((o,s)=>{E(o.length===t,()=>`Error in concat${t}D: rank of tensors[${s}] must be the same as the rank of the rest (${t})`)}),E(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 a=0;a<t;a++)E(a===e||o[a]===n[a],()=>`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 O6(r,e){let t=r[0].slice();for(let n=1;n<r.length;n++)t[e]+=r[n][e];return t}var fx=30;function P6(r){return r<=fx?r:Vc(r,Math.floor(Math.sqrt(r)))}function M6(r,e,t){let n=t*(typeof r=="number"?r:r[0]),o=e*(typeof r=="number"?r:r[1]);return[n,o]}function L6(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 a=0;a<s;++a)o=o.concat([r[a+1]/e[a],e[a]]);o=o.concat(r.slice(s+1))}return o}function z6(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 a=1;a<r;++a)a>=e*2+1||a%2==1?s.push(a):o.push(a);n.push(...o),n.push(0),n.push(...s)}return n}function B6(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 V6(r,e){let t=[0];for(let n=0;n<e;++n)t.push(r[n][0]);return t}function G6(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 pk=1.7580993408473768,mk=1.0507009873554805;var W6=.3275911,j6=.254829592,U6=-.284496736,q6=1.421413741,H6=-1.453152027,K6=1.061405429;function X6(...r){W().getBool("IS_TEST")||console.warn(...r)}function Y6(...r){W().getBool("IS_TEST")||console.log(...r)}function Z6(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 J6(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 Q6(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 e5(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 t5(r,e){let t=r[e*2],n=r[e*2+1];return{real:t,imag:n}}function r5(r,e,t,n){r[n*2]=e,r[n*2+1]=t}function n5(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 o5(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 fk="->",s5=/->/g,QE=",",eA="...";function i5(r,e){r=r.replace(/\s/g,"");let t=(r.length-r.replace(s5,"").length)/fk.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 ("${fk}").`);let[n,o]=r.split(fk);E(n.indexOf(eA)===-1,()=>`The ellipsis notation ("${eA}") is not supported yet.`);let s=n.split(QE),a=s.length;if(e!==a)throw new Error(`Expected ${a} input tensors, received ${e}`);if(a>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");let i=[];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.`);i.indexOf(f)===-1&&i.push(f)}for(let m=0;m<n.length;++m){let f=n[m];i.indexOf(f)===-1&&f!==QE&&i.push(f)}let l=new Array(s.length);for(let m=0;m<a;++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(i.indexOf(s[m][f]))}let u=i.length,c=o.length,p=[];for(let m=c;m<u;++m)p.push(m);return{allDims:i,summedDims:p,idDims:l}}function a5(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 l5(r,e,t){let n=new Array(r);for(let o=0;o<t.length;++o){let s=t[o].shape;for(let a=0;a<e[o].length;++a)n[e[o][a]]===void 0?n[e[o][a]]=s[a]:E(n[e[o][a]]===s[a],()=>`Expected dimension ${n[e[o][a]]} at axis ${a} of input shaped ${JSON.stringify(s)}, but got dimension ${s[a]}`)}}function u5(r,e){let t=r,n=[],o=0;r.length===0&&t.push(-1),o=r.length+1;for(let a=0;a<o;++a)n.push([]);let s=[];for(let a=0;a<t.length;++a){let i=t[a],l=p5(e,i);for(let u of l)s.indexOf(u)===-1&&(n[a].push(u),s.push(u))}return{path:t,steps:n}}function c5(r){return r.every((e,t)=>e===t)}function p5(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 m5(r,e,t=0){let n=[];if(typeof e=="number")E(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((a,i)=>(i===-1&&(a+=1),a),0);E(o<=1,()=>"There should be only one negative value in split array.");let s=e.indexOf(-1);if(s!==-1){let a=e.reduce((i,l)=>l>0?i+l:i);e[s]=r.shape[t]-a}E(r.shape[t]===e.reduce((a,i)=>a+i),()=>"The sum of sizes must match the size of the axis dimension."),n=e}return n}var dk={};je(dk,{collectGatherOpShapeInfo:()=>h5,computeOutShape:()=>d5,segOpComputeOptimalWindowSize:()=>f5});function f5(r,e){let t=!1,n;for(r<=fx?(n=r,t=!0):n=Vc(r,Math.floor(Math.sqrt(r)));!t;)n>e||n===r?t=!0:n=Vc(r,n+1);return n}function d5(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 h5(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 p=0;p<n;++p)if(r.shape[p]!==e.shape[p])throw new Error(`x.shape[${p}]: ${r.shape[p]} should be equal to indices.shape[${p}]: ${e.shape[p]}.`);let a=r.shape[t],i=[],l=1,u=1,c=1;for(let p=0;p<n;++p)i.push(r.shape[p]),l*=r.shape[p];for(let p=n;p<t;p++)i.push(r.shape[p]),u*=r.shape[p];for(let p=n;p<o;p++)i.push(e.shape[p]);for(let p=t+1;p<s;p++)i.push(r.shape[p]),c*=r.shape[p];return{batchSize:l,sliceSize:c,outerSize:u,dimSize:a,outputShape:i}}function g5(r){try{return r.map(e=>Np(e))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function x5(r){return r.map(e=>vl(e))}var zr={};je(zr,{nonMaxSuppressionV3Impl:()=>ax,nonMaxSuppressionV4Impl:()=>lx,nonMaxSuppressionV5Impl:()=>ux,whereImpl:()=>ex});function te(r,e){Array.isArray(r)||(r=[r]),r.forEach(t=>{t!=null&&y.assert(t.dtype!=="complex64",()=>`${e} does not support complex64 tensors in the CPU backend.`)})}var y5=zr.whereImpl,Qu=class extends Xs{constructor(){super();this.blockSize=48,this.firstUse=!0,this.data=new al(this,Ns())}nextDataId(){return Qu.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,W().get("IS_NODE")&&I.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&&y.isString(n[0])){let s=n.map(a=>y.encodeString(a));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 I.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=>y.decodeString(o))}catch(o){throw new Error("Failed to decode encoded string bytes into utf-8")}return Ie(e.shape,e.dtype,n)}makeOutput(e,t,n){let o=this.write(e,t,n);return Ns().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=y.now();return e(),{kernelMs:y.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){te([e],"where");let t=this.readSync(e.dataId);return y5(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};Qu.nextDataId=0;var Tx={};je(Tx,{addImpl:()=>gk,bincountImpl:()=>Up,bincountReduceImpl:()=>dx,ceilImpl:()=>xk,concatImpl:()=>ec,equalImpl:()=>yk,expImpl:()=>wk,expm1Impl:()=>kk,floorImpl:()=>vk,gatherNdImpl:()=>hx,gatherV2Impl:()=>gx,greaterEqualImpl:()=>Ik,greaterImpl:()=>Ck,lessEqualImpl:()=>Nk,lessImpl:()=>Sk,linSpaceImpl:()=>xx,logImpl:()=>Tk,maxImpl:()=>yx,maximumImpl:()=>Ek,minimumImpl:()=>Ak,multiplyImpl:()=>Zf,negImpl:()=>Dk,notEqualImpl:()=>$k,prodImpl:()=>Rk,rangeImpl:()=>rc,rsqrtImpl:()=>Fk,simpleAbsImpl:()=>hk,sliceImpl:()=>nc,sparseFillEmptyRowsImpl:()=>bx,sparseReshapeImpl:()=>wx,sparseSegmentReductionImpl:()=>Hp,squaredDifferenceImpl:()=>Ok,stridedSliceImpl:()=>_x,stringNGramsImpl:()=>kx,stringSplitImpl:()=>vx,stringToHashBucketFastImpl:()=>Cx,subImpl:()=>Pk,tileImpl:()=>Ix,topKImpl:()=>Sx,transposeImpl:()=>qp,uniqueImpl:()=>Nx});function hk(r){let e=new Float32Array(r.length);for(let t=0;t<r.length;++t)e[t]=Math.abs(r[t]);return e}var b5=r=>{let{x:e}=r.inputs,t=r.backend;te(e,"abs");let n=new Float32Array(y.sizeFromShape(e.shape)),o=t.data.get(e.dataId).values;return n=hk(o),t.makeOutput(n,e.shape,"float32")},tA={kernelName:Js,backendName:"cpu",kernelFunc:b5};function Ze(r){return(e,t,n,o,s)=>{let a=I.assertAndGetBroadcastShape(e,t),i=a.length,l=y.computeStrides(a),u=y.sizeFromShape(a),c=y.getTypedArrayFromDType(s,u),p=e.length,m=t.length,f=y.computeStrides(e),d=y.computeStrides(t),h=I.getBroadcastDims(e,a),g=I.getBroadcastDims(t,a);if(h.length+g.length===0)for(let x=0;x<c.length;++x)c[x]=r(n[x%n.length],o[x%o.length]);else for(let x=0;x<c.length;++x){let b=y.indexToLoc(x,i,l),w=b.slice(-p);h.forEach(D=>w[D]=0);let _=y.locToIndex(w,p,f),C=b.slice(-m);g.forEach(D=>C[D]=0);let A=y.locToIndex(C,m,d);c[x]=r(n[_],o[A])}return[c,a]}}function xr(r){let{inputs:e,backend:t}=r,{real:n,imag:o}=e,s=t.data.get(n.dataId).values,a=t.data.get(o.dataId).values,i=t.makeTensorInfo(n.shape,"complex64"),l=t.data.get(i.dataId);return l.complexTensorInfos={real:t.makeTensorInfo(n.shape,"float32",s),imag:t.makeTensorInfo(o.shape,"float32",a)},i}var rA={kernelName:qc,backendName:"cpu",kernelFunc:xr};function Wp(r,e,t="float32"){if(t==="complex64"){let o=Wp(r,e,"float32"),s=Wp(r,e,"float32");return xr({inputs:{real:o,imag:s},backend:r})}let n=y.makeZerosTypedArray(y.sizeFromShape(e),t);return r.makeTensorInfo(e,t,n)}function Br(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 nA={kernelName:no,backendName:"cpu",kernelFunc:Br};function xo(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 oA={kernelName:pp,backendName:"cpu",kernelFunc:xo};function yo(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{dtype:s}=n;if(s==="complex64"){if(o.dtype==="complex64")return Br({inputs:{x:o},backend:t});let a=Wp(t,o.shape,o.dtype),i=yo({inputs:{x:o},backend:t,attrs:{dtype:"float32"}}),l=xr({inputs:{real:i,imag:a},backend:t});return t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),l}if(o.dtype==="complex64"){let a=xo({inputs:{input:o},backend:t}),i=yo({inputs:{x:a},backend:t,attrs:{dtype:s}});return t.disposeIntermediateTensorInfo(a),i}if(!y.hasEncodingLoss(o.dtype,s)){let a=Br({inputs:{x:o},backend:t});return{dataId:a.dataId,shape:a.shape,dtype:s}}if(s==="int32"){let a=t.data.get(o.dataId).values,i=Int32Array.from(a);return t.makeTensorInfo(o.shape,"int32",i)}if(s==="bool"){let a=t.data.get(o.dataId).values,i=y.toTypedArray([0],o.dtype),[l,u]=Ze((c,p)=>c!==p?1:0)(o.shape,[],a,i,"bool");return t.makeTensorInfo(u,"bool",l)}throw new Error(`Error in Cast: failed to cast ${o.dtype} to ${s}`)}var sA={kernelName:to,backendName:"cpu",kernelFunc:yo};function tt(r,e,t,n){return t==null?({inputs:o,backend:s})=>{let{a,b:i}=o,l=s;te([a,i],r);let u=l.data.get(a.dataId).values,c=l.data.get(i.dataId).values,p=a.dtype==="string"?I.fromUint8ToStringArray(u):u,m=a.dtype==="string"?I.fromUint8ToStringArray(c):c,f=n||a.dtype,[d,h]=e(a.shape,i.shape,p,m,f);return l.makeTensorInfo(h,f,d)}:({inputs:o,backend:s})=>{let{a,b:i}=o,l=s;if(a.dtype==="complex64"||i.dtype==="complex64"){let u=yo({inputs:{x:a},backend:l,attrs:{dtype:"complex64"}}),c=l.data.get(u.dataId),p=c.complexTensorInfos.real,m=c.complexTensorInfos.imag,f=l.data.get(p.dataId).values,d=l.data.get(m.dataId).values,h=yo({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(h.dataId),x=g.complexTensorInfos.real,b=g.complexTensorInfos.imag,w=l.data.get(x.dataId).values,_=l.data.get(b.dataId).values,[C,A,D]=t(a.shape,i.shape,f,d,w,_),$=l.makeTensorInfo(D,"float32",C),R=l.makeTensorInfo(D,"float32",A),M=xr({inputs:{real:$,imag:R},backend:l});return l.disposeIntermediateTensorInfo(u),l.disposeIntermediateTensorInfo(h),l.disposeIntermediateTensorInfo($),l.disposeIntermediateTensorInfo(R),M}else{let u=l.data.get(a.dataId).values,c=l.data.get(i.dataId).values,p=n||a.dtype,[m,f]=e(a.shape,i.shape,u,c,p);return l.makeTensorInfo(f,p,m)}}}function jp(r){return(e,t,n,o,s,a)=>{let i=I.assertAndGetBroadcastShape(e,t),l=y.sizeFromShape(i),u=i.length,c=y.computeStrides(i),p=y.getTypedArrayFromDType("float32",l),m=y.getTypedArrayFromDType("float32",l),f=I.getBroadcastDims(e,i),d=I.getBroadcastDims(t,i),h=I.mergeRealAndImagArrays(n,o),g=I.mergeRealAndImagArrays(s,a),x=e.length,b=y.computeStrides(e),w=t.length,_=y.computeStrides(t);if(f.length+d.length===0)for(let C=0;C<p.length;C++){let A=C%h.length,D=C%g.length,$=r(h[A*2],h[A*2+1],g[D*2],g[D*2+1]);p[C]=$.real,m[C]=$.imag}else for(let C=0;C<p.length;C++){let A=y.indexToLoc(C,u,c),D=A.slice(-x);f.forEach(j=>D[j]=0);let $=y.locToIndex(D,x,b),R=A.slice(-w);d.forEach(j=>R[j]=0);let M=y.locToIndex(R,w,_),G=r(h[$*2],h[$*2+1],g[M*2],g[M*2+1]);p[C]=G.real,m[C]=G.imag}return[p,m,i]}}var gk=Ze((r,e)=>r+e),w5=jp((r,e,t,n)=>({real:r+t,imag:e+n})),Va=tt(jn,gk,w5),iA={kernelName:jn,backendName:"cpu",kernelFunc:Va};function Up(r,e,t,n,o){let s=y.sizeFromShape(n),a=y.makeZerosTypedArray(o,t);for(let i=0;i<r.length;i++){let l=r[i];if(l<0)throw new Error("Input x must be non-negative!");l>=o||(s>0?a[l]+=e[i]:a[l]+=1)}return a}function dx(r,e,t,n=!1){let o=r.shape[0],s=r.shape[1],a=Ie([o,t],e.dtype);for(let i=0;i<o;i++)for(let l=0;l<s;l++){let u=r.get(i,l);if(u<0)throw new Error("Input x must be non-negative!");u>=t||(n?a.set(1,i,u):e.size>0?a.set(a.get(i,u)+e.get(i,l),i,u):a.set(a.get(i,u)+1,i,u))}return a}function bo(r){return(e,t,n)=>{let o=y.getTypedArrayFromDType(t,e.length);for(let s=0;s<e.length;++s)o[s]=r(e[s],n);return o}}function Re(r,e,t){return({inputs:n,attrs:o,backend:s})=>{let{x:a}=n;if(te(a,r),a.dtype==="string"||t==="string")throw new Error("unaryKernelFunc does not support string input/output");let i=s,l=i.data.get(a.dataId).values,u=y.sizeFromShape(a.shape),c=t||a.dtype,p=y.getArrayFromDType(c,u);for(let m=0;m<u;++m)p[m]=e(l[m],o);return i.makeTensorInfo(a.shape,c,p)}}function wo(r,e,t){return({inputs:n,attrs:o,backend:s})=>{let{x:a}=n;if(te(a,r),a.dtype==="string"||t==="string")throw new Error("unaryKernelFunc does not support string input/output");let i=s,l=i.data.get(a.dataId).values,u=t||a.dtype,c=e(l,u,o);return i.makeTensorInfo(a.shape,u,c)}}var xk=bo(r=>Math.ceil(r)),_5=wo(Po,xk),aA={kernelName:Po,backendName:"cpu",kernelFunc:_5};function ec(r,e,t,n){let o=y.getArrayFromDType(t,y.sizeFromShape(e));if(n&&t!=="string"){let s=0;r.forEach(a=>{let i=y.sizeFromShape(a.shape);o.set(a.vals,s),s+=i})}else{let s=0;r.forEach(a=>{let i=t==="string"?I.fromUint8ToStringArray(a.vals):a.vals,l=0;for(let u=0;u<a.shape[0];++u){let c=u*e[1]+s;for(let p=0;p<a.shape[1];++p)o[c+p]=i[l++]}s+=a.shape[1]})}return o}var yk=Ze((r,e)=>r===e?1:0),bk=tt(Hi,yk,null,"bool"),lA={kernelName:Hi,backendName:"cpu",kernelFunc:bk};var wk=bo(r=>Math.exp(r)),_k=wo(Wo,wk),uA={kernelName:Wo,backendName:"cpu",kernelFunc:_k};var kk=bo(r=>Math.expm1(r)),k5=wo(Ki,kk),cA={kernelName:Ki,backendName:"cpu",kernelFunc:k5};var vk=bo(r=>Math.floor(r)),v5=wo(jo,vk),pA={kernelName:jo,backendName:"cpu",kernelFunc:v5};function hx(r,e,t,n,o,s,a,i,l){let u=Ie([n,s],t);for(let c=0;c<n;c++){let p=[],m=0;for(let f=0;f<o;f++){let d=r[c*o+f];m+=d*a[f],p.push(d)}if(m<0||m>=l/s)throw new Error(`Invalid indices: ${p} does not index into ${i}`);for(let f=0;f<s;f++)u.values[c*s+f]=e.get(...e.indexToLoc(m*s+f))}return u}function gx(r,e,t){let n=Ie(t,r.dtype);for(let o=0;o<n.size;++o){let a=n.indexToLoc(o).slice(),i=a[0],l=a[2],u=e.locToIndex([i,l]);a[2]=e.values[u];let c=r.locToIndex(a);n.values[o]=r.values[c]}return n}var Ck=Ze((r,e)=>r>e?1:0),C5=tt(Zi,Ck,null,"bool"),mA={kernelName:Zi,backendName:"cpu",kernelFunc:C5};var Ik=Ze((r,e)=>r>=e?1:0),I5=tt(Ho,Ik,null,"bool"),fA={kernelName:Ho,backendName:"cpu",kernelFunc:I5};var Sk=Ze((r,e)=>r<e?1:0),S5=tt(ta,Sk,null,"bool"),dA={kernelName:ta,backendName:"cpu",kernelFunc:S5};var Nk=Ze((r,e)=>r<=e?1:0),N5=tt(ra,Nk,null,"bool"),hA={kernelName:ra,backendName:"cpu",kernelFunc:N5};function xx(r,e,t){let n=(e-r)/(t-1),o=y.makeZerosTypedArray(t,"float32");o[0]=r;for(let s=1;s<o.length;s++)o[s]=o[s-1]+n;return o}var Tk=bo(r=>Math.log(r)),T5=wo(Xo,Tk),gA={kernelName:Xo,backendName:"cpu",kernelFunc:T5};function yx(r,e,t,n){let o=y.getTypedArrayFromDType(n,y.sizeFromShape(t));for(let s=0;s<o.length;++s){let a=s*e,i=r[a];for(let l=0;l<e;++l){let u=r[a+l];(Number.isNaN(u)||u>i)&&(i=u)}o[s]=i}return o}var Ek=Ze((r,e)=>Math.max(r,e)),E5=tt(Zo,Ek),xA={kernelName:Zo,backendName:"cpu",kernelFunc:E5};var Ak=Ze((r,e)=>Math.min(r,e)),A5=tt(ts,Ak),yA={kernelName:ts,backendName:"cpu",kernelFunc:A5};var Zf=Ze((r,e)=>r*e),D5=jp((r,e,t,n)=>({real:r*t-e*n,imag:r*n+e*t})),tc=tt(ns,Zf,D5),bA={kernelName:ns,backendName:"cpu",kernelFunc:tc};function Dk(r,e,t){let n=y.createScalarValue(-1,t);return Zf([],e,n,r,t)}function $5(r){let{inputs:e,backend:t}=r,{x:n}=e;te(n,"neg");let o=t.data.get(n.dataId).values,[s,a]=Dk(o,n.shape,n.dtype);return t.makeTensorInfo(a,n.dtype,s)}var wA={kernelName:ri,backendName:"cpu",kernelFunc:$5};var $k=Ze((r,e)=>r!==e?1:0),R5=tt(ia,$k,null,"bool"),_A={kernelName:ia,backendName:"cpu",kernelFunc:R5};function qp(r,e,t,n,o){let s=e.length,a=y.sizeFromShape(e),i=y.computeStrides(e),l=y.computeStrides(o),u=y.getTypedArrayFromDType(t,y.sizeFromShape(o));for(let c=0;c<a;++c){let p=y.indexToLoc(c,s,i),m=new Array(p.length);for(let d=0;d<m.length;d++)m[d]=p[n[d]];let f=y.locToIndex(m,s,l);u[f]=r[c]}return u}function Qt(r){let{inputs:e,attrs:t,backend:n}=r,{x:o}=e,{perm:s}=t;te(o,"transpose");let a=o.shape.length,i=new Array(a);for(let p=0;p<i.length;p++)i[p]=o.shape[s[p]];let l=n.data.get(o.dataId).values,u=qp(l,o.shape,o.dtype,s,i);return{dataId:n.write(u,i,o.dtype),shape:i,dtype:o.dtype}}var kA={kernelName:vs,backendName:"cpu",kernelFunc:Qt};function Rk(r,e,t,n){let[o,s]=I.computeOutAndReduceShapes(r,n),a=mr(e,"int32"),i=y.makeZerosTypedArray(y.sizeFromShape(o),a),l=y.sizeFromShape(s);for(let u=0;u<i.length;++u){let c=u*l,p=1;for(let m=0;m<l;++m)p*=t[c+m];i[u]=p}return{outVals:i,outShape:o,outDtype:a}}function F5(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,keepDims:a}=n;te(o,"prod");let i=o.shape.length,l=y.parseAxisParam(s,o.shape),u=I.getAxesPermutation(l,i),c=l,p=o,m=[];u!=null&&(p=Qt({inputs:{x:o},backend:t,attrs:{perm:u}}),m.push(p),c=I.getInnerMostAxes(c.length,i));let f=t.data.get(p.dataId).values,{outVals:d,outShape:h,outDtype:g}=Rk(p.shape,p.dtype,f,c),x=h;return a&&(x=I.expandShapeToKeepDim(h,l)),m.forEach(b=>t.disposeIntermediateTensorInfo(b)),t.makeTensorInfo(x,g,d)}var vA={kernelName:ca,backendName:"cpu",kernelFunc:F5};function rc(r,e,t,n){let o=r===e,s=r<e&&t<0,a=e<r&&t>1;if(o||s||a)return y.makeZerosTypedArray(0,n);let i=Math.abs(Math.ceil((e-r)/t)),l=y.makeZerosTypedArray(i,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 Fk=bo(r=>1/Math.sqrt(r)),O5=wo(fs,Fk),CA={kernelName:fs,backendName:"cpu",kernelFunc:O5};function nc(r,e,t,n,o){let s=lr.isSliceContinous(n,e,t),a=y.sizeFromShape(t),i=y.computeStrides(n);if(s){let p=lr.computeFlatOffset(e,i);return o==="string"?r.slice(p,p+a):r.subarray(p,p+a)}let l=o==="string"?I.fromUint8ToStringArray(r):r,u=Ie(n,o,l),c=Ie(t,o);for(let p=0;p<c.size;++p){let m=c.indexToLoc(p),f=m.map((d,h)=>d+e[h]);c.set(u.get(...f),...m)}return o==="string"?I.fromStringArrayToUint8(c.values):c.values}function _o(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{begin:s,size:a}=n;te(o,"slice");let[i,l]=lr.parseSliceParams(o,s,a);lr.assertParamsValid(o,i,l);let u=t.data.get(o.dataId).values,c=nc(u,i,l,o.shape,o.dtype);return t.makeTensorInfo(l,o.dtype,c)}var IA={kernelName:ai,backendName:"cpu",kernelFunc:_o};function bx(r,e,t,n,o,s,a){let i=e[0],l=s[0],u=new Array(l),c=new Array(i),p=e[1];if(l===0){if(i!==0)throw new Error(`Received SparseTensor with denseShape[0] = 0 but
|
|
indices.shape[0] = ${i}`);let g=y.getArrayFromDType(t,0),x=y.getArrayFromDType(o,0);return[g,[0,p],x,u,c]}let m=!0,f=0,d=new Array(l).fill(0);for(let g=0;g<i;++g){let x=r[g*p];if(x<0)throw new Error(`indices(${g}, 0) is invalid: ${x} < 0`);if(x>=l)throw new Error(`indices(${g}, 0) is invalid: ${x} >= ${l}`);++d[x],m=m&&x>=f,f=x}let h=!0;for(let g=0;g<l;++g){let x=d[g]===0;u[g]=x,h=h&&!x,d[g]=Math.max(d[g],1),g>0&&(d[g]+=d[g-1])}if(h&&m){let g=r,x=n;for(let b=0;b<i;++b)c[b]=b;return[g,[i,p],x,u,c]}else{let g=d[l-1],x=y.getArrayFromDType(t,g*p),b=y.getArrayFromDType(o,g),w=new Array(l).fill(0);for(let _=0;_<i;++_){let C=r[_*p],A=w[C],D=(C===0?0:d[C-1])+A;w[C]++;for(let $=0;$<p;++$)x[D*p+$]=r[_*p+$];b[D]=n[_],c[_]=D}for(let _=0;_<l;++_)if(w[_]===0){let A=_===0?0:d[_-1];x[A*p+0]=_;for(let D=1;D<p;++D)x[A*p+D]=0;b[A]=a}return[x,[g,p],b,u,c]}}function wx(r,e,t,n,o){let s=y.sizeFromShape(n),a=e[0],i=o.length,l=[],u=1,c=-1;for(let g=0;g<i;++g){let x=o[g];if(x===-1){if(c!==-1)throw new Error(`only one output dimension may be -1, not both ${c} and ${g}`);c=g,l.push(1)}else{if(x<0)throw new Error(`size ${g} must be non-negative, not ${x}`);u*=x,l.push(x)}}if(c!==-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[c]=g}let p=y.sizeFromShape(l);if(p!==s)throw new Error(`Input to reshape is a tensor with ${s} dense values, but the requested shape has ${p}. 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(i>0){d[i-1]=1;for(let g=i-2;g>=0;--g)d[g]=d[g+1]*l[g+1]}let h=y.getArrayFromDType(t,a*i);for(let g=0;g<a;++g){let x=0;for(let b=0;b<m;++b)x+=r[g*m+b]*f[b];for(let b=0;b<i;++b)h[g*i+b]=Math.trunc(x/d[b]),x%=d[b]}return[h,[a,i],l]}function Hp(r,e,t,n,o,s=!1,a=0){let i=n.length;if(i!==o.length)throw new Error("segmentIds and indices should have same size.");let l=[e[0],r.length/e[0]],u=l[1],p=i>0?o[i-1]+1:0;if(p<0)throw new Error("segment ids must be >= 0");let m=e.slice();m[0]=p;let f=m.reduce((w,_)=>w*_,1),d=y.getArrayFromDType(t,f);if(i===0)return p>0&&d.fill(a),[d,m];if(p<=0)throw new Error("segment ids must be >= 0");let h=0,g=1,x=0,b=o[h];for(;;){let w=0;if(g<i){if(w=o[g],b===w){++g;continue}if(b>=w)throw new Error("segment ids are not increasing")}if(b<0||b>=p)throw new Error(`Segment id ${b} out of range [0, ${p}), possibly because segmentIds input is not sorted.`);b>x&&d.fill(a,x*u,b*u);for(let _=h;_<g;++_){let C=n[_];if(C<0||C>=l[0])throw new Error(`Bad: indices[${_}] == ${n[_]} out of range [0, ${l[0]})`);for(let A=0;A<u;A++)d[b*u+A]+=r[C*u+A]}if(s)for(let _=0;_<u;_++)d[b*u+_]/=g-h;if(h=g,++g,x=b+1,b=w,g>i)break}return x<p&&d.fill(a,x*u,p*u),[d,m]}var Ok=Ze((r,e)=>{let t=r-e;return t*t}),P5=tt(bs,Ok),SA={kernelName:bs,backendName:"cpu",kernelFunc:P5};function _x(r,e,t,n){let o=Ie(r,e.dtype);for(let s=0;s<o.size;s++){let a=o.indexToLoc(s),i=new Array(a.length);for(let l=0;l<i.length;l++)i[l]=a[l]*t[l]+n[l];o.set(e.get(...i),...a)}return o}var NA=class{constructor(e,t,n,o,s,a){this.separator=y.encodeString(e),this.nGramWidths=t,this.leftPad=y.encodeString(n),this.rightPad=y.encodeString(o),this.padWidth=s,this.preserveShort=a}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,a){for(let i=0;i<s;++i){let l=this.getPadWidth(a),u=Math.max(0,l-i),c=Math.max(0,l-(s-(i+1))),p=a-(u+c),m=t+(u>0?0:i-l),f=0;f+=u*this.leftPad.length;for(let b=0;b<p;++b)f+=e[m+b].length;f+=c*this.rightPad.length,f+=(u+c+p-1)*this.separator.length,n[o+i]=new Uint8Array(f);let h=n[o+i],g=0,x=b=>b.forEach(w=>h[g++]=w);for(let b=0;b<u;++b)x(this.leftPad),x(this.separator);for(let b=0;b<p-1;++b)x(e[m+b]),x(this.separator);if(p>0){x(e[m+p-1]);for(let b=0;b<c;++b)x(this.separator),x(this.rightPad)}else{for(let b=0;b<c-1;++b)x(this.rightPad),x(this.separator);x(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 c=t[u]>=l;if(c=c&&t[u]<=n,!c)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,a=y.getArrayFromDType("int32",o);if(n===0||o===0){let l=new Array(n);for(let u=0;u<=s;++u)a[u]=0;return[l,a]}a[0]=0;for(let l=1;l<=s;++l){let u=t[l]-t[l-1],c=0;this.nGramWidths.forEach(p=>{c+=this.getNumNGrams(u,p)}),this.preserveShort&&u>0&&c===0&&(c=1),a[l]=a[l-1]+c}let i=new Array(a[s]);for(let l=0;l<s;++l){let u=t[l],c=a[l];if(this.nGramWidths.forEach(p=>{let m=t[l+1]-t[l],f=this.getNumNGrams(m,p);this.createNGrams(e,u,i,c,f,p),c+=f}),this.preserveShort&&c===a[l]){let p=t[l+1]-t[l];if(p===0)continue;let m=p+2*this.padWidth,f=1;this.createNGrams(e,u,i,c,f,m)}}return[i,a]}};function kx(r,e,t,n,o,s,a,i){return new NA(t,n,o,s,a,i).compute(r,e)}function M5(r,e,t){if(!r.length)return[];if(e.length===0){let s=new Array(r.length);for(let a=0;a<r.length;++a)s[a]=r.subarray(a,a+1);return s}if(e.length===1){let s=e[0],a=[],i=r.indexOf(s);for(;i!==-1;){let l=r.subarray(0,i);(!t||l.length!==0)&&a.push(l),r=r.subarray(i+1),i=r.indexOf(s)}return(!t||r.length!==0)&&a.push(r),a}let n=[],o=0;for(let s=0;s<r.length+1;s++)if(s===r.length||e.indexOf(r[s])!==-1){let a=r.subarray(o,s);(!t||a.length!==0)&&n.push(a),o=s+1}return n}function vx(r,e,t){let n=r.length,o=[],s=0,a=0,i=new Array(n);for(let m=0;m<n;++m){let f=M5(r[m],e,t),d=f.length;i[m]=d,s+=d,a=Math.max(a,d),o.push(...f)}let l=y.getArrayFromDType("int32",s*2),u=new Array(s),c=[n,a],p=0;for(let m=0;m<n;++m)for(let f=0;f<i[m];++f)l[p*2]=m,l[p*2+1]=f,u[p]=o[p],++p;return[l,u,c]}function Cx(r,e){let t=y.getArrayFromDType("int32",r.length);for(let n=0;n<r.length;++n)t[n]=y.fingerPrint64(r[n]).modulo(e).getLowBitsUnsigned();return t}var Pk=Ze((r,e)=>r-e),L5=jp((r,e,t,n)=>({real:r-t,imag:e-n})),Jf=tt(ws,Pk,L5),TA={kernelName:ws,backendName:"cpu",kernelFunc:Jf};function Ix(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=Ie(t,r.dtype);for(let o=0;o<n.values.length;++o){let s=n.indexToLoc(o),a=new Array(r.rank);for(let l=0;l<a.length;l++)a[l]=s[l]%r.shape[l];let i=r.locToIndex(a);n.values[o]=r.values[i]}return n}function Sx(r,e,t,n,o){let s=e[e.length-1],[a,i]=[r.length/s,s],l=y.getTypedArrayFromDType(t,a*n),u=y.getTypedArrayFromDType("int32",a*n);for(let p=0;p<a;p++){let m=p*i,f=r.subarray(m,m+i),d=[];for(let b=0;b<f.length;b++)d.push({value:f[b],index:b});d.sort((b,w)=>w.value-b.value);let h=p*n,g=l.subarray(h,h+n),x=u.subarray(h,h+n);for(let b=0;b<n;b++)g[b]=d[b].value,x[b]=d[b].index}let c=e.slice();return c[c.length-1]=n,[Ie(c,t,l),Ie(c,"int32",u)]}function Nx(r,e,t,n){let o=y.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 a={},i=new Int32Array(t[o]),l=new ct(s,n,r),u=[],c=s[0]===1&&s[2]===1;for(let d=0;d<t[o];d++){let h;if(c)h=r[d].toString();else{let g=[];for(let x=0;x<s[0];x++)for(let b=0;b<s[2];b++)g.push(l.get(x,d,b));h=g.join(",")}if(a[h]!==void 0)i[d]=a[h];else{let g=Object.keys(a).length;a[h]=g,i[d]=g,u.push(d)}}let p=s.slice();p[1]=Object.keys(a).length;let m=new ct(p,n);u.forEach((d,h)=>{for(let g=0;g<s[0];g++)for(let x=0;x<s[2];x++)m.set(l.get(g,d,x),g,h,x)});let f=t.slice();return f[o]=p[1],{outputValues:m.values,outputShape:f,indices:i}}var Mk="3.7.0";Rp("cpu",()=>new Qu,1);var Lk=Re(Ui,r=>r>=0?r:Math.exp(r)-1),EA={kernelName:Ui,backendName:"cpu",kernelFunc:Lk};function zk(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{alpha:s}=n;te([o],"leakyRelu");let a=y.sizeFromShape(o.shape),i=t.data.get(o.dataId).values,l=y.getTypedArrayFromDType("float32",a);for(let u=0;u<i.length;u++)l[u]=i[u]<0?s*i[u]:i[u];return t.makeTensorInfo(o.shape,"float32",l)}var AA={kernelName:Ko,backendName:"cpu",kernelFunc:zk};var z5=Ze((r,e)=>r<0?e*r:r);function Bk(r){let{inputs:e,backend:t}=r,{x:n,alpha:o}=e;te([n,o],"prelu");let s=t.data.get(n.dataId).values,a=t.data.get(o.dataId).values,[i,l]=z5(n.shape,o.shape,s,a,n.dtype);return t.makeTensorInfo(l,n.dtype,i)}var DA={kernelName:as,backendName:"cpu",kernelFunc:Bk};var Vk=Re(ls,r=>Math.max(0,r)),$A={kernelName:ls,backendName:"cpu",kernelFunc:Vk};var Gk=Re(cs,r=>Math.min(Math.max(0,r),6)),RA={kernelName:cs,backendName:"cpu",kernelFunc:Gk};var Wk=Re(hs,r=>1/(1+Math.exp(-r))),FA={kernelName:hs,backendName:"cpu",kernelFunc:Wk};function Kp(r,e,t,n,o){if(t==="linear")return Br({inputs:{x:e},backend:r});if(t==="relu")return Vk({inputs:{x:e},backend:r});if(t==="elu")return Lk({inputs:{x:e},backend:r});if(t==="relu6")return Gk({inputs:{x:e},backend:r});if(t==="prelu")return Bk({inputs:{x:e,alpha:n},backend:r});if(t==="leakyrelu")return zk({inputs:{x:e},backend:r,attrs:{alpha:o}});if(t==="sigmoid")return Wk({inputs:{x:e},backend:r});throw new Error(`Activation ${t} has not been implemented for the CPU backend.`)}function Je(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{shape:s}=n,a=y.sizeFromShape(o.shape),i=y.inferFromImplicitShape(s,a),l=y.sizeFromShape(i);y.assert(a===l,()=>`The new shape (${i}) has ${l} elements and the old shape (${o.shape}) has ${a} 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 c=u.complexTensorInfos.real,p=u.complexTensorInfos.imag;c.shape=i,p.shape=i}return{dataId:o.dataId,shape:i,dtype:o.dtype}}var OA={kernelName:si,backendName:"cpu",kernelFunc:Je};function jk(r){let{inputs:e,backend:t,attrs:n}=r,{a:o,b:s}=e,{transposeA:a,transposeB:i}=n;te([o,s],"matMul");let l=o.shape.length,u=s.shape.length,c=a?o.shape[l-2]:o.shape[l-1],p=i?s.shape[u-1]:s.shape[u-2],m=a?o.shape[l-1]:o.shape[l-2],f=i?s.shape[u-2]:s.shape[u-1],d=o.shape.slice(0,-2),h=s.shape.slice(0,-2),g=y.sizeFromShape(d),x=y.sizeFromShape(h),b=g===x||g===1||x===1;y.assert(l>=2&&u>=2&&b,()=>`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 _=(g>x?o.shape.slice(0,-2):s.shape.slice(0,-2)).concat([m,f]);y.assert(c===p,()=>`Error in matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${o.shape} and ${s.shape} and transposeA=${a} and transposeB=${i} must match.`);let C=a?[g,c,m]:[g,m,c],A=i?[x,f,p]:[x,p,f],D=Je({inputs:{x:o},backend:t,attrs:{shape:C}}),$=Je({inputs:{x:s},backend:t,attrs:{shape:A}}),R=a?D.shape[1]:D.shape[2],M=a?D.shape[2]:D.shape[1],G=i?$.shape[1]:$.shape[2],j=Math.max(g,x),U=t.data.get(D.dataId).values,q=t.data.get($.dataId).values,H=y.computeStrides(D.shape),X=y.computeStrides($.shape),[ne,Y,re]=a?[H[0],1,H[1]]:[H[0],H[1],1],[ee,ie,me]=i?[1,X[1],X[0]]:[X[1],1,X[0]],ae=M*G,fe=Ie([j,M,G],D.dtype),he=fe.values,xe=t.blockSize;for(let _e=0;_e<j;_e++)for(let $e=0;$e<M;$e+=xe)for(let Ce=0;Ce<G;Ce+=xe)for(let We=0;We<R;We+=xe){let Xe=Math.min($e+xe,M),lt=Math.min(Ce+xe,G),Et=Math.min(We+xe,R);for(let At=$e;At<Xe;At++)for(let He=Ce;He<lt;He++){let pt=0;for(let ft=We;ft<Et;ft++){let Vt=Math.min(_e,g-1)*ne,En=Math.min(_e,x-1)*me,tr=U[Vt+At*Y+ft*re],gn=q[ft*ee+He*ie+En];pt+=tr*gn}he[_e*ae+(At*G+He)]+=pt}}return t.disposeIntermediateTensorInfo(D),t.disposeIntermediateTensorInfo($),t.makeTensorInfo(_,fe.dtype,fe.values)}var PA={kernelName:Oo,backendName:"cpu",kernelFunc:jk};function B5(r){let{inputs:e,backend:t,attrs:n}=r,{a:o,b:s,bias:a,preluActivationWeights:i}=e,{transposeA:l,transposeB:u,activation:c,leakyreluAlpha:p}=n,m,f,d,h=[];m=jk({inputs:{a:o,b:s},attrs:{transposeA:l,transposeB:u},backend:t}),a&&(f=Va({inputs:{a:m,b:a},backend:t}),h.push(m),m=f),c&&(d=Kp(t,m,c,i,p),h.push(m),m=d);for(let x of h)t.disposeIntermediateTensorInfo(x);return m}var MA={kernelName:pi,backendName:"cpu",kernelFunc:B5};var V5=Re(Ri,r=>Math.acos(r)),LA={kernelName:Ri,backendName:"cpu",kernelFunc:V5};var G5=Re(Fi,r=>Math.acosh(r)),zA={kernelName:Fi,backendName:"cpu",kernelFunc:G5};function W5(r){let{inputs:e,backend:t}=r,n=e;te(e,"addN");let o=n.map(i=>t.data.get(i.dataId).values),s=Ie(n[0].shape,n[0].dtype),a=s.values;for(let i=0;i<n.length;i++){let l=o[i];for(let u=0;u<a.length;u++)a[u]+=l[u]}return t.makeTensorInfo(s.shape,s.dtype,s.values)}var BA={kernelName:$o,backendName:"cpu",kernelFunc:W5};function j5(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,keepDims:a}=n;te(o,"all");let i=y.parseAxisParam(s,o.shape),l=i,u=I.getAxesPermutation(l,o.shape.length),c=o;u!=null&&(c=Qt({inputs:{x:o},backend:t,attrs:{perm:u}}),l=I.getInnerMostAxes(l.length,o.shape.length)),I.assertAxesAreInnerMostDims("all",l,c.shape.length);let[p,m]=I.computeOutAndReduceShapes(c.shape,l),f=y.sizeFromShape(m),d=y.makeZerosTypedArray(y.sizeFromShape(p),c.dtype),h=t.data.get(c.dataId).values;for(let x=0;x<d.length;++x){let b=x*f,w=h[b];for(let _=0;_<f;++_){let C=h[b+_];w=w&&C}d[x]=w}u!=null&&t.disposeIntermediateTensorInfo(c);let g=t.makeTensorInfo(p,c.dtype,d);if(a){let x=I.expandShapeToKeepDim(p,i),b=Je({inputs:{x:g},backend:t,attrs:{shape:x}});return t.disposeIntermediateTensorInfo(g),b}return g}var VA={kernelName:Oi,backendName:"cpu",kernelFunc:j5};function U5(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,keepDims:a}=n;te(o,"any");let i=y.parseAxisParam(s,o.shape),l=i,u=I.getAxesPermutation(l,o.shape.length),c=o;u!=null&&(c=Qt({inputs:{x:o},backend:t,attrs:{perm:u}}),l=I.getInnerMostAxes(l.length,o.shape.length)),I.assertAxesAreInnerMostDims("any",l,c.shape.length);let[p,m]=I.computeOutAndReduceShapes(c.shape,l),f=y.sizeFromShape(m),d=y.makeZerosTypedArray(y.sizeFromShape(p),c.dtype),h=t.data.get(c.dataId).values;for(let x=0;x<d.length;++x){let b=x*f,w=h[b];for(let _=0;_<f;++_){let C=h[b+_];w=w||C}d[x]=w}u!=null&&t.disposeIntermediateTensorInfo(c);let g=t.makeTensorInfo(p,c.dtype,d);if(a){let x=I.expandShapeToKeepDim(p,i),b=Je({inputs:{x:g},backend:t,attrs:{shape:x}});return t.disposeIntermediateTensorInfo(g),b}return g}var GA={kernelName:Pi,backendName:"cpu",kernelFunc:U5};function q5(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s}=n;te(o,"argMax");let a=y.parseAxisParam(s,o.shape),i=I.getAxesPermutation(a,o.shape.length),l=o,u=[];i!=null&&(l=Qt({inputs:{x:o},backend:t,attrs:{perm:i}}),u.push(l),a=I.getInnerMostAxes(a.length,l.shape.length)),a=[a[0]],I.assertAxesAreInnerMostDims("argMax",a,l.shape.length);let[c,p]=I.computeOutAndReduceShapes(l.shape,a),m=y.sizeFromShape(c),f=y.makeZerosTypedArray(m,"int32"),d=y.sizeFromShape(p),h=t.data.get(l.dataId).values;for(let g=0;g<f.length;++g){let x=g*d,b=h[x],w=0;for(let _=0;_<d;++_){let C=h[x+_];C>b&&(b=C,w=_)}f[g]=w}return u.forEach(g=>t.disposeIntermediateTensorInfo(g)),t.makeTensorInfo(c,"int32",f)}var WA={kernelName:Ro,backendName:"cpu",kernelFunc:q5};function H5(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s}=n;te(o,"argMin");let a=y.parseAxisParam(s,o.shape),i=I.getAxesPermutation(a,o.shape.length),l=o,u=[];i!=null&&(l=Qt({inputs:{x:o},backend:t,attrs:{perm:i}}),u.push(l),a=I.getInnerMostAxes(a.length,l.shape.length)),a=[a[0]],I.assertAxesAreInnerMostDims("argMin",a,l.shape.length);let[c,p]=I.computeOutAndReduceShapes(l.shape,a),m=y.sizeFromShape(c),f=y.makeZerosTypedArray(m,"int32"),d=y.sizeFromShape(p),h=t.data.get(l.dataId).values;for(let g=0;g<f.length;++g){let x=g*d,b=h[x],w=0;for(let _=0;_<d;++_){let C=h[x+_];C<b&&(b=C,w=_)}f[g]=w}return u.forEach(g=>t.disposeIntermediateTensorInfo(g)),t.makeTensorInfo(c,"int32",f)}var jA={kernelName:ll,backendName:"cpu",kernelFunc:H5};var K5=Re(Mi,r=>Math.asin(r)),UA={kernelName:Mi,backendName:"cpu",kernelFunc:K5};var X5=Re(Li,r=>Math.asinh(r)),qA={kernelName:Li,backendName:"cpu",kernelFunc:X5};var Y5=Re(zi,r=>Math.atan(r)),HA={kernelName:zi,backendName:"cpu",kernelFunc:Y5};var Z5=Ze((r,e)=>Math.atan2(r,e)),J5=tt(Vi,Z5),KA={kernelName:Vi,backendName:"cpu",kernelFunc:J5};var Q5=Re(Bi,r=>Math.atanh(r)),XA={kernelName:Bi,backendName:"cpu",kernelFunc:Q5};function Xp(r,e,t,n,o,s){let a=o.strideHeight,i=o.strideWidth,l=o.dilationHeight,u=o.dilationWidth,c=o.effectiveFilterHeight,p=o.effectiveFilterWidth,m=o.padInfo.top,f=o.padInfo.left,d=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,h=Ie(o.outShape,t),g=h.values,x=o.outShape[1]*o.outShape[2]*o.outShape[3],b=o.outShape[2]*o.outShape[3],w=o.outShape[3];for(let _=0;_<o.batchSize;++_){let C=_*x,A=_*n[0];for(let D=0;D<o.inChannels;++D)for(let $=0;$<o.outHeight;++$){let R=$*a-m,M=Math.max(0,R),G=Math.min(o.inHeight,c+R),j=C+$*b;for(let U=0;U<o.outWidth;++U){let q=U*i-f,H=Math.max(0,q),X=Math.min(o.inWidth,p+q),ne=d,Y=0,re=0;for(let ie=M;ie<G;ie+=l){let me=A+ie*n[1];for(let ae=H;ae<X;ae+=u){let fe=me+ae*n[2],he=r[fe+D];s==="max"&&he>ne?ne=he:s==="avg"&&(Y+=he,re++)}if(isNaN(ne))break}let ee=j+U*w+D;g[ee]=s==="avg"?Y/re:ne}}}return h}function Ex(r,e,t,n,o=!1,s=!1){let a=Ie(n.outShape,"int32"),i=n.strideHeight,l=n.strideWidth,u=n.dilationHeight,c=n.dilationWidth,p=n.effectiveFilterHeight,m=n.effectiveFilterWidth,f=n.padInfo.top,d=n.padInfo.left,h=Ie(e,t,r);for(let g=0;g<n.batchSize;++g)for(let x=0;x<n.inChannels;++x)for(let b=0;b<n.outHeight;++b){let w=b*i-f,_=w;for(;_<0;)_+=u;let C=Math.min(n.inHeight,p+w);for(let A=0;A<n.outWidth;++A){let D=A*l-d,$=D;for(;$<0;)$+=c;let R=Math.min(n.inWidth,m+D),M=Number.NEGATIVE_INFINITY,G=-1;for(let j=_;j<C;j+=u){let U=j-w;for(let q=$;q<R;q+=c){let H=q-D,X=h.get(g,j,q,x);X>M&&(M=X,o?G=s?((g*n.inHeight+j)*n.inWidth+q)*n.inChannels+x:(j*n.inWidth+q)*n.inChannels+x:G=U*m+H)}}a.set(G,g,b,A,x)}}return a}function Ax(r,e,t,n,o,s){let a=o.strideDepth,i=o.strideHeight,l=o.strideWidth,u=o.dilationDepth,c=o.dilationHeight,p=o.dilationWidth,m=o.effectiveFilterDepth,f=o.effectiveFilterHeight,d=o.effectiveFilterWidth,h=o.padInfo.front,g=o.padInfo.top,x=o.padInfo.left,b=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,w=Ie(o.outShape,t),_=w.values,C=o.outShape[1]*o.outShape[2]*o.outShape[3]*o.outShape[4],A=o.outShape[2]*o.outShape[3]*o.outShape[4],D=o.outShape[3]*o.outShape[4],$=o.outShape[4];for(let R=0;R<o.batchSize;++R){let M=R*C,G=R*n[0];for(let j=0;j<o.inChannels;++j)for(let U=0;U<o.outDepth;++U){let q=U*a-h,H=q;for(;H<0;)H+=u;let X=Math.min(o.inDepth,m+q),ne=M+U*A;for(let Y=0;Y<o.outHeight;++Y){let re=Y*i-g,ee=re;for(;ee<0;)ee+=c;let ie=Math.min(o.inHeight,f+re),me=ne+Y*D;for(let ae=0;ae<o.outWidth;++ae){let fe=ae*l-x,he=fe;for(;he<0;)he+=p;let xe=Math.min(o.inWidth,d+fe),_e=me+ae*$,$e=b,Ce=0,We=0;for(let lt=H;lt<X;lt+=u){let Et=G+lt*n[1];for(let At=ee;At<ie;At+=c){let He=Et+At*n[2];for(let pt=he;pt<xe;pt+=p){let ft=He+pt*n[3],Vt=r[ft+j];if(s==="max"&&Vt>$e?$e=Vt:s==="avg"&&(Ce+=Vt,We++),isNaN($e))break}if(isNaN($e))break}if(isNaN($e))break}let Xe=_e+j;_[Xe]=s==="avg"?Ce/We:$e}}}}return w}function YA(r,e){let t=Ie(e.outShape,"int32"),n=e.strideDepth,o=e.strideHeight,s=e.strideWidth,a=e.dilationDepth,i=e.dilationHeight,l=e.dilationWidth,u=e.effectiveFilterDepth,c=e.effectiveFilterHeight,p=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 x=0;x<e.outDepth;++x){let b=x*n-m,w=b;for(;w<0;)w+=a;let _=Math.min(e.inDepth,u+b);for(let C=0;C<e.outHeight;++C){let A=C*o-f,D=A;for(;D<0;)D+=i;let $=Math.min(e.inHeight,c+A);for(let R=0;R<e.outWidth;++R){let M=R*s-d,G=M;for(;G<0;)G+=l;let j=Math.min(e.inWidth,p+M),U=Number.NEGATIVE_INFINITY,q=-1;for(let H=w;H<_;H+=a){let X=H-b;for(let ne=D;ne<$;ne+=i){let Y=ne-A;for(let re=G;re<j;re+=l){let ee=re-M,ie=r.get(h,H,ne,re,g);ie>=U&&(U=ie,q=X*c*p+Y*c+ee)}}}t.set(q,h,x,C,R,g)}}}return t}function e8(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e;te(o,"avgPool");let{filterSize:s,strides:a,pad:i,dimRoundingMode:l}=n,u=1;y.assert(I.eitherStridesOrDilationsAreOne(a,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let c=I.computePool2DInfo(o.shape,s,a,u,i,l),p;if(c.filterWidth===1&&c.filterHeight===1&&y.arraysEqual(c.inShape,c.outShape))p=Br({inputs:{x:o},backend:t});else{let m=t.data.get(o.dataId).values,f=y.computeStrides(o.shape),d=Xp(m,o.shape,o.dtype,f,c,"avg");p=t.makeTensorInfo(c.outShape,o.dtype,d.values)}return p}var ZA={kernelName:Fo,backendName:"cpu",kernelFunc:e8};function t8(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{filterSize:s,strides:a,pad:i,dimRoundingMode:l,dataFormat:u}=n;te(o,"avgPool3d");let c=I.computePool3DInfo(o.shape,s,a,1,i,l,u),p=t.data.get(o.dataId).values,m=Ax(p,o.shape,o.dtype,y.computeStrides(o.shape),c,"avg");return t.makeTensorInfo(m.shape,"float32",m.values)}var JA={kernelName:ul,backendName:"cpu",kernelFunc:t8};function r8(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,input:s}=e,{filterSize:a,strides:i,pad:l,dimRoundingMode:u}=n;te([o,s],"avgPool3DGrad");let c=I.computePool3DInfo(s.shape,a,i,1,l,u),p=c.strideDepth,m=c.strideHeight,f=c.strideWidth,d=c.filterDepth,h=c.filterHeight,g=c.filterWidth,x=c.dilationDepth,b=c.dilationHeight,w=c.dilationWidth,_=c.effectiveFilterDepth,C=c.effectiveFilterHeight,A=c.effectiveFilterWidth,D=_-1-c.padInfo.front,$=A-1-c.padInfo.left,R=C-1-c.padInfo.top,M=Ie(s.shape,"float32"),G=1/(d*h*g),j=t.bufferSync(o);for(let U=0;U<c.batchSize;++U)for(let q=0;q<c.inChannels;++q)for(let H=0;H<c.inDepth;++H)for(let X=0;X<c.inHeight;++X)for(let ne=0;ne<c.inWidth;++ne){let Y=H-D,re=X-R,ee=ne-$,ie=0;for(let me=0;me<_;me+=x){let ae=(Y+me)/p;if(!(ae<0||ae>=c.outDepth||Math.floor(ae)!==ae))for(let fe=0;fe<C;fe+=b){let he=(re+fe)/m;if(!(he<0||he>=c.outHeight||Math.floor(he)!==he))for(let xe=0;xe<A;xe+=w){let _e=(ee+xe)/f;if(_e<0||_e>=c.outWidth||Math.floor(_e)!==_e)continue;ie+=j.get(U,ae,he,_e,q)}}}M.set(ie*G,U,H,X,ne,q)}return t.makeTensorInfo(M.shape,M.dtype,M.values)}var QA={kernelName:jc,backendName:"cpu",kernelFunc:r8};function n8(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,input:s}=e,a=s;te([o,s],"avgPoolGrad");let{filterSize:i,strides:l,pad:u}=n,c=I.computePool2DInfo(a.shape,i,l,1,u),p=c.strideHeight,m=c.strideWidth,f=c.filterHeight,d=c.filterWidth,h=c.dilationHeight,g=c.dilationWidth,x=c.effectiveFilterHeight,b=c.effectiveFilterWidth,w=b-1-c.padInfo.left,_=x-1-c.padInfo.top,C=Ie(a.shape,"float32"),A=1/(f*d),D=t.data.get(o.dataId).values,$=Ie(o.shape,"float32",D);for(let R=0;R<c.batchSize;++R)for(let M=0;M<c.inChannels;++M)for(let G=0;G<c.inHeight;++G)for(let j=0;j<c.inWidth;++j){let U=G-_,q=j-w,H=0;for(let X=0;X<x;X+=h){let ne=(U+X)/p;if(!(ne<0||ne>=c.outHeight||Math.floor(ne)!==ne))for(let Y=0;Y<b;Y+=g){let re=(q+Y)/m;if(re<0||re>=c.outWidth||Math.floor(re)!==re)continue;H+=$.get(R,ne,re,M)}}C.set(H*A,R,G,j,M)}return t.makeTensorInfo(C.shape,C.dtype,C.values)}var e2={kernelName:Wc,backendName:"cpu",kernelFunc:n8};function o8(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,scale:s,offset:a,mean:i,variance:l}=e;y.assert(i.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),y.assert(a==null||i.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),y.assert(s==null||i.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),te([o,i,l,s,a],"batchNorm");let{varianceEpsilon:u}=n;u==null&&(u=.001);let c=t.data.get(o.dataId).values,p=t.data.get(i.dataId).values,m=t.data.get(l.dataId).values,f=s?t.data.get(s.dataId).values:new Float32Array([1]),d=a?t.data.get(a.dataId).values:new Float32Array([0]),h=new Float32Array(c.length),g=d.length,x=f.length,b=m.length,w=p.length,_=0,C=0,A=0,D=0;for(let $=0;$<c.length;++$)h[$]=d[_++]+(c[$]-p[C++])*f[A++]/Math.sqrt(m[D++]+u),_>=g&&(_=0),C>=w&&(C=0),A>=x&&(A=0),D>=b&&(D=0);return t.makeTensorInfo(o.shape,o.dtype,h)}var t2={kernelName:qo,backendName:"cpu",kernelFunc:o8};function s8(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{blockShape:s,crops:a}=n;te([o],"batchToSpaceND");let i=s.reduce((x,b)=>x*b),l=I.getReshaped(o.shape,s,i),u=I.getPermuted(l.length,s.length),c=I.getReshapedPermuted(o.shape,s,i),p=I.getSliceBeginCoords(a,s.length),m=I.getSliceSize(c,a,s.length),f=Je({inputs:{x:o},backend:t,attrs:{shape:l}}),d=Qt({inputs:{x:f},backend:t,attrs:{perm:u}}),h=Je({inputs:{x:d},backend:t,attrs:{shape:c}}),g=_o({inputs:{x:h},backend:t,attrs:{begin:p,size:m}});return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(h),g}var r2={kernelName:cl,backendName:"cpu",kernelFunc:s8};function i8(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,weights:s}=e,{size:a}=n,i=t.data.get(o.dataId).values,l=t.data.get(s.dataId).values,u=Up(i,l,s.dtype,s.shape,a);return t.makeTensorInfo([a],s.dtype,u)}var n2={kernelName:Uc,backendName:"cpu",kernelFunc:i8};var a8=Re(ro,(r,e)=>{let t=e;return r>t.clipValueMax?t.clipValueMax:r<t.clipValueMin?t.clipValueMin:r}),o2={kernelName:ro,backendName:"cpu",kernelFunc:a8};var l8=r=>{let{x:e}=r.inputs,t=r.backend,n=new Float32Array(y.sizeFromShape(e.shape)),o=t.data.get(e.dataId),s=o.complexTensorInfos.real,a=o.complexTensorInfos.imag,i=t.data.get(s.dataId).values,l=t.data.get(a.dataId).values;for(let u=0;u<i.length;u++){let c=i[u],p=l[u];n[u]=Math.hypot(c,p)}return t.makeOutput(n,e.shape,"float32")},s2={kernelName:pl,backendName:"cpu",kernelFunc:l8};function bi(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 i2={kernelName:op,backendName:"cpu",kernelFunc:bi};function Dl(r){let{inputs:e,backend:t,attrs:n}=r,{axis:o}=n,s=y.parseAxisParam(o,e[0].shape)[0],a=I.computeOutShape(e.map(h=>h.shape),s);if(y.sizeFromShape(a)===0)return t.makeTensorInfo(a,e[0].dtype,[]);let i=e.filter(h=>y.sizeFromShape(h.shape)>0);if(i.length===1)return Br({inputs:{x:i[0]},backend:t});let l=i.map(h=>h.shape);if(I.assertParamsConsistent(l,s),i[0].dtype==="complex64"){let h=i.map(_=>xo({inputs:{input:_},backend:t})),g=i.map(_=>bi({inputs:{input:_},backend:t})),x=Dl({inputs:h,backend:t,attrs:{axis:s}}),b=Dl({inputs:g,backend:t,attrs:{axis:s}}),w=xr({inputs:{real:x,imag:b},backend:t});return h.forEach(_=>t.disposeIntermediateTensorInfo(_)),g.forEach(_=>t.disposeIntermediateTensorInfo(_)),t.disposeIntermediateTensorInfo(x),t.disposeIntermediateTensorInfo(b),w}let u=i.map(h=>{let g=y.sizeFromShape(h.shape.slice(s));return Je({inputs:{x:h},backend:t,attrs:{shape:[-1,g]}})}),c=u.map(h=>({vals:t.data.get(h.dataId).values,shape:h.shape}));a=I.computeOutShape(u.map(h=>h.shape),1);let p=u[0].shape[0]===1,m=ec(c,a,e[0].dtype,p),f=I.computeOutShape(i.map(h=>h.shape),s),d=t.makeTensorInfo(f,e[0].dtype,m);return u.forEach(h=>t.disposeIntermediateTensorInfo(h)),d}var a2={kernelName:Qs,backendName:"cpu",kernelFunc:Dl};function Uk(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,filter:s}=e,{strides:a,pad:i,dataFormat:l,dilations:u,dimRoundingMode:c}=n;te([o,s],"conv2d");let p=I.convertConv2DDataFormat(l),m=I.computeConv2DInfo(o.shape,s.shape,a,u,i,c,!1,p),f=m.filterHeight,d=m.filterWidth,h=m.dilationHeight,g=m.dilationWidth,x=m.padInfo.left,b=m.padInfo.top,w=m.dataFormat==="channelsLast",_=new ct(m.outShape,o.dtype),C=y.computeStrides(o.shape),A=y.computeStrides(s.shape),D=C[0],$=w?C[1]:C[2],R=w?C[2]:1,M=w?1:C[1],G=_.strides[0],j=w?_.strides[1]:_.strides[2],U=w?_.strides[2]:1,q=w?1:_.strides[1],H=t.data.get(o.dataId).values,X=t.data.get(s.dataId).values,ne=_.values;for(let Y=0;Y<m.batchSize;++Y){let re=Y*D,ee=Y*G;for(let ie=0;ie<m.outHeight;++ie){let me=ee+ie*j,ae=ie*m.strideHeight-b;for(let fe=0;fe<f;++fe){let he=ae+fe*h;if(he<0||he>=m.inHeight)continue;let xe=fe*A[0],_e=re+he*$;for(let $e=0;$e<m.outWidth;++$e){let Ce=me+$e*U,We=$e*m.strideWidth-x;for(let Xe=0;Xe<d;++Xe){let lt=We+Xe*g;if(lt<0||lt>=m.inWidth)continue;let Et=xe+Xe*A[1],At=_e+lt*R,He=Et;for(let pt=0;pt<m.inChannels;++pt){let ft=H[At+pt*M];for(let Vt=0;Vt<m.outChannels;++Vt)ne[Ce+Vt*q]+=ft*X[He+Vt];He+=m.outChannels}}}}}}return t.makeTensorInfo(_.shape,_.dtype,ne)}var l2={kernelName:Mo,backendName:"cpu",kernelFunc:Uk};function u8(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,dy:s}=e,{strides:a,pad:i,dataFormat:l,dimRoundingMode:u,filterShape:c}=n;te([o,s],"conv2dBackpropFilter");let p=I.convertConv2DDataFormat(l),m=I.computeConv2DInfo(o.shape,c,a,1,i,u,!1,p),{strideHeight:f,strideWidth:d,filterHeight:h,filterWidth:g}=m,x=m.dataFormat==="channelsLast",b=new ct(m.filterShape,"float32"),w=m.padInfo.left,_=m.padInfo.top,C=t.data.get(o.dataId).values,A=t.data.get(s.dataId).values,D=new ct(o.shape,o.dtype,C),$=new ct(s.shape,s.dtype,A);for(let R=0;R<h;++R){let M=Math.max(0,Math.ceil((_-R)/f)),G=Math.min(m.outHeight,(m.inHeight+_-R)/f);for(let j=0;j<g;++j){let U=Math.max(0,Math.ceil((w-j)/d)),q=Math.min(m.outWidth,(m.inWidth+w-j)/d);for(let H=0;H<m.inChannels;++H)for(let X=0;X<m.outChannels;++X){let ne=0;for(let Y=0;Y<m.batchSize;++Y)for(let re=M;re<G;++re){let ee=R+re*f-_;for(let ie=U;ie<q;++ie){let me=j+ie*d-w;x?ne+=D.get(Y,ee,me,H)*$.get(Y,re,ie,X):ne+=D.get(Y,H,ee,me)*$.get(Y,X,re,ie)}}b.set(ne,R,j,H,X)}}}return t.makeTensorInfo(b.shape,b.dtype,b.values)}var u2={kernelName:Hc,backendName:"cpu",kernelFunc:u8};function c8(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,filter:s}=e,{inputShape:a,strides:i,pad:l,dataFormat:u,dimRoundingMode:c}=n;te([o,s],"conv2dBackpropInput");let p=y.computeStrides(s.shape),m=y.computeStrides(o.shape),f=I.convertConv2DDataFormat(u),d=I.computeConv2DInfo(a,s.shape,i,1,l,c,!1,f),h=new ct(d.inShape,"float32"),g=h.values,x=t.data.get(o.dataId).values,b=t.data.get(s.dataId).values,[w,_,C]=p,{batchSize:A,filterHeight:D,filterWidth:$,inChannels:R,inHeight:M,inWidth:G,outChannels:j,outHeight:U,outWidth:q,strideHeight:H,strideWidth:X}=d;f=d.dataFormat;let ne=D-1-d.padInfo.top,Y=$-1-d.padInfo.left,re=f==="channelsLast",ee=h.strides[0],ie=re?h.strides[1]:h.strides[2],me=re?h.strides[2]:1,ae=re?1:h.strides[1],fe=m[0],he=re?m[1]:m[2],xe=re?m[2]:1,_e=re?1:m[1];for(let $e=0;$e<A;++$e)for(let Ce=0;Ce<R;++Ce)for(let We=0;We<M;++We){let Xe=We-ne,lt=Math.max(0,Math.ceil(Xe/H)),Et=Math.min(U,(D+Xe)/H);for(let At=0;At<G;++At){let He=At-Y,pt=Math.max(0,Math.ceil(He/X)),ft=Math.min(q,($+He)/X),Vt=0;for(let tr=lt;tr<Et;++tr){let gn=tr*H-Xe;for(let Gr=pt;Gr<ft;++Gr){let Qn=Gr*X-He,cr=fe*$e+he*tr+xe*Gr,An=w*(D-1-gn)+_*($-1-Qn)+C*Ce;for(let Yr=0;Yr<j;++Yr){let Cr=x[cr+_e*Yr],xn=b[An+Yr];Vt+=Cr*xn}}}let En=ee*$e+ie*We+me*At+ae*Ce;g[En]=Vt}}return t.makeTensorInfo(h.shape,h.dtype,h.values)}var c2={kernelName:Lo,backendName:"cpu",kernelFunc:c8};function p8(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,filter:s}=e,{strides:a,pad:i,dilations:l}=n;te([o,s],"conv3d");let u=I.computeConv3DInfo(o.shape,s.shape,a,l,i),{filterDepth:c,filterHeight:p,filterWidth:m,dilationDepth:f,dilationHeight:d,dilationWidth:h,padInfo:g}=u,x=g.front,b=g.left,w=g.top,_=new ct(u.outShape,o.dtype),C=t.data.get(o.dataId).values,A=t.data.get(s.dataId).values,D=_.values,$=y.computeStrides(o.shape),R=y.computeStrides(s.shape);for(let M=0;M<u.batchSize;++M){let G=M*$[0],j=M*_.strides[0];for(let U=0;U<u.outDepth;++U){let q=j+U*_.strides[1],H=U*u.strideDepth-x;for(let X=0;X<c;++X){let ne=H+X*f;if(ne<0||ne>=u.inDepth)continue;let Y=X*R[0],re=G+ne*$[1];for(let ee=0;ee<u.outHeight;++ee){let ie=q+ee*_.strides[2],me=ee*u.strideHeight-w;for(let ae=0;ae<p;++ae){let fe=me+ae*d;if(fe<0||fe>=u.inHeight)continue;let he=Y+ae*R[1],xe=re+fe*$[2];for(let _e=0;_e<u.outWidth;++_e){let $e=ie+_e*u.outChannels,Ce=_e*u.strideWidth-b;for(let We=0;We<m;++We){let Xe=Ce+We*h;if(Xe<0||Xe>=u.inWidth)continue;let lt=he+We*R[2],Et=xe+Xe*u.inChannels,At=lt;for(let He=0;He<u.inChannels;++He){let pt=C[Et+He];for(let ft=0;ft<u.outChannels;++ft)D[$e+ft]+=pt*A[At+ft];At+=u.outChannels}}}}}}}}return t.makeTensorInfo(_.shape,_.dtype,_.values)}var p2={kernelName:ml,backendName:"cpu",kernelFunc:p8};function m8(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,dy:s}=e,{strides:a,pad:i,filterShape:l}=n;te([o,s],"conv3dBackpropFilterV2");let u=y.computeStrides(o.shape),c=y.computeStrides(s.shape),p=I.computeConv3DInfo(o.shape,l,a,1,i),m=p.strideDepth,f=p.strideHeight,d=p.strideWidth,h=p.filterDepth,g=p.filterHeight,x=p.filterWidth,b=new ct(p.filterShape,"float32"),w=b.values,[_,C,A,D]=b.strides,$=t.data.get(s.dataId).values,[R,M,G,j]=c,U=t.data.get(o.dataId).values,[q,H,X,ne]=u,Y=p.padInfo.front,re=p.padInfo.left,ee=p.padInfo.top;for(let ie=0;ie<h;++ie){let me=Math.max(0,Math.ceil((Y-ie)/m)),ae=Math.min(p.outDepth,(p.inDepth+Y-ie)/m),fe=ie*_;for(let he=0;he<g;++he){let xe=Math.max(0,Math.ceil((ee-he)/f)),_e=Math.min(p.outHeight,(p.inHeight+ee-he)/f),$e=he*C+fe;for(let Ce=0;Ce<x;++Ce){let We=Math.max(0,Math.ceil((re-Ce)/d)),Xe=Math.min(p.outWidth,(p.inWidth+re-Ce)/d),lt=Ce*A+$e;for(let Et=0;Et<p.inChannels;++Et){let At=Et*D+lt;for(let He=0;He<p.outChannels;++He){let pt=0;for(let ft=0;ft<p.batchSize;++ft){let Vt=ft*q,En=ft*R;for(let tr=me;tr<ae;++tr){let Gr=(ie+tr*m-Y)*H+Vt,Qn=tr*M+En;for(let cr=xe;cr<_e;++cr){let Yr=(he+cr*f-ee)*X+Gr,Cr=cr*G+Qn;for(let xn=We;xn<Xe;++xn){let Jl=(Ce+xn*d-re)*ne+Yr,tl=xn*j+Cr;pt+=U[Jl+Et]*$[tl+He]}}}}w[At+He]=pt}}}}}return t.makeTensorInfo(b.shape,b.dtype,b.values)}var m2={kernelName:Kc,backendName:"cpu",kernelFunc:m8};function f8(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,filter:s}=e,{pad:a,strides:i,inputShape:l}=n;te([o],"conv3dBackpropInputV2");let u=y.computeStrides(o.shape),c=y.computeStrides(s.shape),p=I.computeConv3DInfo(l,s.shape,i,1,a),m=new ct(p.inShape,"float32"),f=m.values,[d,h,g,x]=m.strides,b=t.data.get(o.dataId).values,[w,_,C,A]=u,D=t.data.get(s.dataId).values,[$,R,M,G]=c,{batchSize:j,filterDepth:U,filterHeight:q,filterWidth:H,inChannels:X,inDepth:ne,inHeight:Y,inWidth:re,outChannels:ee,outDepth:ie,outHeight:me,outWidth:ae,strideDepth:fe,strideHeight:he,strideWidth:xe}=p,_e=U-1-p.padInfo.front,$e=q-1-p.padInfo.top,Ce=H-1-p.padInfo.left;for(let We=0;We<j;++We)for(let Xe=0;Xe<X;++Xe)for(let lt=0;lt<ne;++lt){let Et=lt-_e,At=Math.max(0,Math.ceil(Et/fe)),He=Math.min(ie,(U+Et)/fe);for(let pt=0;pt<Y;++pt){let ft=pt-$e,Vt=Math.max(0,Math.ceil(ft/he)),En=Math.min(me,(q+ft)/he);for(let tr=0;tr<re;++tr){let gn=tr-Ce,Gr=Math.max(0,Math.ceil(gn/xe)),Qn=Math.min(ae,(H+gn)/xe),cr=0;for(let An=At;An<He;++An){let Yr=An*fe-Et;for(let Cr=Vt;Cr<En;++Cr){let xn=Cr*he-ft;for(let Gn=Gr;Gn<Qn;++Gn){let Jl=Gn*xe-gn,tl=w*We+_*An+C*Cr+A*Gn,Ks=$*(U-1-Yr)+R*(q-1-xn)+M*(H-1-Jl)+G*Xe;for(let Ti=0;Ti<ee;++Ti){let Pm=b[tl+Ti],Ql=D[Ks+Ti];cr+=Pm*Ql}}}}f[d*We+h*lt+g*pt+x*tr+Xe]=cr}}}return t.makeTensorInfo(m.shape,m.dtype,m.values)}var f2={kernelName:Xc,backendName:"cpu",kernelFunc:f8};var d8=Re(zo,r=>Math.cos(r)),d2={kernelName:zo,backendName:"cpu",kernelFunc:d8};var h8=Re(Gi,r=>Math.cosh(r)),h2={kernelName:Gi,backendName:"cpu",kernelFunc:h8};function g8(r){let{inputs:e,backend:t,attrs:n}=r,{image:o,boxes:s,boxInd:a}=e,{cropSize:i,method:l,extrapolationValue:u}=n,[c,p,m,f]=o.shape,d=s.shape[0],[h,g]=i,x=Ie([d,h,g,f],"float32"),b=t.data.get(s.dataId).values,w=t.data.get(a.dataId).values,_=t.data.get(o.dataId).values,C=y.computeStrides(o.shape),A=y.computeStrides(x.shape);for(let D=0;D<d;D++){let $=D*4,R=b[$],M=b[$+1],G=b[$+2],j=b[$+3],U=w[D];if(U>=c)continue;let q=h>1?(G-R)*(p-1)/(h-1):0,H=g>1?(j-M)*(m-1)/(g-1):0;for(let X=0;X<h;X++){let ne=h>1?R*(p-1)+X*q:.5*(R+G)*(p-1);if(ne<0||ne>p-1){for(let Y=0;Y<g;Y++)for(let re=0;re<f;re++){let ee=re+Y*A[2]+X*A[1]+D*A[0];x.values[ee]=u}continue}if(l==="bilinear"){let Y=Math.floor(ne),re=Math.ceil(ne),ee=ne-Y;for(let ie=0;ie<g;ie++){let me=g>1?M*(m-1)+ie*H:.5*(M+j)*(m-1);if(me<0||me>m-1){for(let xe=0;xe<f;xe++){let _e=xe+ie*A[2]+X*A[1]+D*A[0];x.values[_e]=u}continue}let ae=Math.floor(me),fe=Math.ceil(me),he=me-ae;for(let xe=0;xe<f;xe++){let _e=xe+ae*C[2]+Y*C[1]+U*C[0],$e=_[_e];_e=xe+fe*C[2]+Y*C[1]+U*C[0];let Ce=_[_e];_e=xe+ae*C[2]+re*C[1]+U*C[0];let We=_[_e];_e=xe+fe*C[2]+re*C[1]+U*C[0];let Xe=_[_e],lt=$e+(Ce-$e)*he,Et=We+(Xe-We)*he;_e=xe+ie*A[2]+X*A[1]+D*A[0],x.values[_e]=lt+(Et-lt)*ee}}}else for(let Y=0;Y<g;++Y){let re=g>1?M*(m-1)+Y*H:.5*(M+j)*(m-1);if(re<0||re>m-1){for(let me=0;me<f;me++){let ae=me+Y*A[2]+X*A[1]+D*A[0];x.values[ae]=u}continue}let ee=Math.round(re),ie=Math.round(ne);for(let me=0;me<f;me++){let ae=me+ee*C[2]+ie*C[1]+U*C[0],fe=me+Y*A[2]+X*A[1]+D*A[0];x.values[fe]=_[ae]}}}}return t.makeTensorInfo(x.shape,x.dtype,x.values)}var g2={kernelName:Wi,backendName:"cpu",kernelFunc:g8};function x8(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,exclusive:a,reverse:i}=n;te(o,"cumsum");let l=I.getAxesPermutation([s],o.shape.length),u=o;l!=null&&(u=Qt({inputs:{x:o},backend:t,attrs:{perm:l}}));let c=I.getInnerMostAxes(1,o.shape.length)[0];if(c!==u.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${u.shape.length-1} but got axis=${c}`);let p=mr(u.dtype,"int32"),m=y.makeZerosTypedArray(y.sizeFromShape(u.shape),p),f=t.data.get(u.dataId).values,d=u.shape[u.shape.length-1],h=i?(x,b)=>x+d-b-1:(x,b)=>x+b;for(let x=0;x<f.length;x+=d)for(let b=0;b<d;b++){let w=h(x,b);if(b===0)m[w]=a?0:f[w];else{let _=h(x,b-1);m[w]=a?f[_]+m[_]:f[w]+m[_]}}let g=t.makeTensorInfo(u.shape,p,m);if(l!=null){let x=I.getUndoAxesPermutation(l),b=Qt({inputs:{x:g},backend:t,attrs:{perm:x}});return t.disposeIntermediateTensorInfo(g),t.disposeIntermediateTensorInfo(u),b}return g}var x2={kernelName:Bo,backendName:"cpu",kernelFunc:x8};function y8(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,weights:s}=e,{size:a,binaryOutput:i}=n;if(o.shape.length===1){let l=t.data.get(o.dataId).values,u=t.data.get(s.dataId).values,c=Up(l,u,s.dtype,s.shape,a);return t.makeTensorInfo([a],s.dtype,c)}else if(o.shape.length===2){let l=t.bufferSync(o),u=t.bufferSync(s),c=dx(l,u,a,i);return t.makeTensorInfo(c.shape,s.dtype,c.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${o.shape.length}.`)}var y2={kernelName:Yc,backendName:"cpu",kernelFunc:y8};function b8(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{blockSize:s,dataFormat:a}=n;y.assert(a==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${a}`),y.assert(s>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${s}`);let i=o.shape[0],l=o.shape[1],u=o.shape[2],c=o.shape[3],p=l*s,m=u*s,f=c/(s*s),d=t.data.get(o.dataId).values,h=new Float32Array(i*p*m*f),g=0;for(let x=0;x<i;++x)for(let b=0;b<p;++b){let w=Math.floor(b/s),_=b%s;for(let C=0;C<m;++C){let A=Math.floor(C/s),D=C%s,$=(_*s+D)*f;for(let R=0;R<f;++R){let G=R+$+c*(A+u*(w+l*x));h[g++]=d[G]}}}return t.makeTensorInfo([i,p,m,f],o.dtype,h)}var b2={kernelName:ji,backendName:"cpu",kernelFunc:b8};function qk(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,filter:s}=e,{strides:a,pad:i,dilations:l,dimRoundingMode:u}=n;te([o,s],"depthwiseConv2DNative");let c=y.computeStrides(o.shape),p=y.computeStrides(s.shape),m=l;m==null&&(m=[1,1]),y.assert(I.eitherStridesOrDilationsAreOne(a,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${m}'`);let f=I.computeConv2DInfo(o.shape,s.shape,a,m,i,u,!0),{filterHeight:d,filterWidth:h,dilationHeight:g,dilationWidth:x,padInfo:b}=f,w=b.left,_=b.top,C=f.outChannels/f.inChannels,A=new ct(f.outShape,o.dtype),D=t.data.get(o.dataId).values,$=t.data.get(s.dataId).values,R=A.values;for(let M=0;M<f.batchSize;++M){let G=M*c[0],j=M*A.strides[0];for(let U=0;U<f.outHeight;++U){let q=j+U*A.strides[1],H=U*f.strideHeight-_;for(let X=0;X<d;++X){let ne=H+X*g;if(ne<0||ne>=f.inHeight)continue;let Y=X*p[0],re=G+ne*c[1];for(let ee=0;ee<f.outWidth;++ee){let ie=q+ee*A.strides[2],me=ee*f.strideWidth-w;for(let ae=0;ae<h;++ae){let fe=me+ae*x;if(fe<0||fe>=f.inWidth)continue;let he=Y+ae*p[1],xe=re+fe*f.inChannels,_e=ie,$e=he;for(let Ce=0;Ce<f.inChannels;++Ce){let We=D[xe+Ce];for(let Xe=0;Xe<C;++Xe)R[_e+Xe]+=We*$[$e+Xe];_e+=C,$e+=C}}}}}}return t.makeTensorInfo(A.shape,A.dtype,A.values)}var w2={kernelName:Vo,backendName:"cpu",kernelFunc:qk};function w8(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,dy:s}=e,{strides:a,dilations:i,pad:l,dimRoundingMode:u,filterShape:c}=n;te([o,s],"depthwiseConv2dNativeBackpropFilter");let p=I.computeConv2DInfo(o.shape,c,a,i,l,u,!0),{strideHeight:m,strideWidth:f,filterHeight:d,filterWidth:h}=p,g=new ct(p.filterShape,"float32"),x=p.padInfo.left,b=p.padInfo.top,w=p.outChannels/p.inChannels,_=t.data.get(o.dataId).values,C=new ct(o.shape,o.dtype,_),A=t.data.get(s.dataId).values,D=new ct(s.shape,s.dtype,A);for(let $=0;$<d;++$){let R=Math.max(0,Math.ceil((b-$)/m)),M=Math.min(p.outHeight,(p.inHeight+b-$)/m);for(let G=0;G<h;++G){let j=Math.max(0,Math.ceil((x-G)/f)),U=Math.min(p.outWidth,(p.inWidth+x-G)/f);for(let q=0;q<p.outChannels;++q){let H=Math.trunc(q/w),X=q%w,ne=0;for(let Y=0;Y<p.batchSize;++Y)for(let re=R;re<M;++re){let ee=$+re*m-b;for(let ie=j;ie<U;++ie){let me=G+ie*f-x;ne+=C.get(Y,ee,me,H)*D.get(Y,re,ie,q)}}g.set(ne,$,G,H,X)}}}return t.makeTensorInfo(g.shape,g.dtype,g.values)}var _2={kernelName:Zc,backendName:"cpu",kernelFunc:w8};function _8(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,filter:s}=e,{strides:a,dilations:i,pad:l,dimRoundingMode:u,inputShape:c}=n;te([o,s],"depthwiseConv2DNativeBackpropInput");let p=y.computeStrides(o.shape),m=y.computeStrides(s.shape),f=I.computeConv2DInfo(c,s.shape,a,i,l,u,!0),d=new ct(f.inShape,"float32"),h=d.values,[g,x,b]=d.strides,w=t.data.get(o.dataId).values,[_,C,A]=p,D=t.data.get(s.dataId).values,[$,R,M]=m,{batchSize:G,filterHeight:j,filterWidth:U,inChannels:q,inHeight:H,inWidth:X,outChannels:ne,outHeight:Y,outWidth:re,strideHeight:ee,strideWidth:ie}=f,me=j-1-f.padInfo.top,ae=U-1-f.padInfo.left,fe=ne/q;for(let he=0;he<G;++he)for(let xe=0;xe<q;++xe)for(let _e=0;_e<H;++_e){let $e=_e-me,Ce=Math.max(0,Math.ceil($e/ee)),We=Math.min(Y,(j+$e)/ee);for(let Xe=0;Xe<X;++Xe){let lt=Xe-ae,Et=Math.max(0,Math.ceil(lt/ie)),At=Math.min(re,(U+lt)/ie),He=0;for(let pt=Ce;pt<We;++pt){let ft=pt*ee-$e;for(let Vt=Et;Vt<At;++Vt){let En=Vt*ie-lt,tr=_*he+C*pt+A*Vt,gn=$*(j-1-ft)+R*(U-1-En)+M*xe;for(let Gr=0;Gr<fe;++Gr){let Qn=xe*fe+Gr,cr=w[tr+Qn],An=D[gn+Gr];He+=cr*An}}}h[g*he+x*_e+b*Xe+xe]=He}}return t.makeTensorInfo(d.shape,d.dtype,d.values)}var k2={kernelName:Jc,backendName:"cpu",kernelFunc:_8};function k8(r){let{inputs:e,backend:t}=r,{x:n}=e,o=y.sizeFromShape(n.shape),s=t.data.get(n.dataId).values,a=Ie([o,o],n.dtype),i=a.values;for(let u=0;u<s.length;u++)i[u*o+u]=s[u];let l=[...n.shape,...n.shape];return t.makeTensorInfo(l,a.dtype,a.values)}var v2={kernelName:Qc,backendName:"cpu",kernelFunc:k8};var C2={kernelName:fl,backendName:"cpu",kernelFunc:({inputs:r,backend:e,attrs:t})=>{let{x:n,filter:o}=r,{strides:s,pad:a,dilations:i}=t,l=e,u=l.data.get(n.dataId).values,c=n.shape.length,p=l.data.get(o.dataId).values,m=o.shape.length,{batchSize:f,inHeight:d,inWidth:h,inChannels:g,outHeight:x,outWidth:b,padInfo:w,strideHeight:_,strideWidth:C,filterHeight:A,filterWidth:D,dilationHeight:$,dilationWidth:R,outShape:M}=I.computeDilation2DInfo(n.shape,o.shape,s,a,"NHWC",i),G=y.sizeFromShape(M),j=M.length,U=y.getArrayFromDType(n.dtype,G);for(let H=0;H<f;++H)for(let X=0;X<x;++X){let ne=X*_-w.top;for(let Y=0;Y<b;++Y){let re=Y*C-w.left;for(let ee=0;ee<g;++ee){let ie=Number.MIN_SAFE_INTEGER;for(let ae=0;ae<A;++ae){let fe=ne+ae*$;if(fe>=0&&fe<d)for(let he=0;he<D;++he){let xe=re+he*R;if(xe>=0&&xe<h){let _e=y.locToIndex([H,fe,xe,ee],c,y.computeStrides(n.shape)),$e=y.locToIndex([ae,he,ee],m,y.computeStrides(o.shape)),Ce=u[_e]+p[$e];Ce>ie&&(ie=Ce)}}}let me=y.locToIndex([H,X,Y,ee],j,y.computeStrides(M));U[me]=ie}}}return{dataId:l.write(y.toTypedArray(U,n.dtype),M,n.dtype),shape:M,dtype:n.dtype}}};var I2={kernelName:nf,backendName:"cpu",kernelFunc:({inputs:r,backend:e,attrs:t})=>{let{x:n,filter:o,dy:s}=r,{strides:a,pad:i,dilations:l}=t,u=e,c=y.toNestedArray(n.shape,u.data.get(n.dataId).values),p=y.toNestedArray(o.shape,u.data.get(o.dataId).values),{batchSize:m,inHeight:f,inWidth:d,inChannels:h,outHeight:g,outWidth:x,padInfo:b,strideHeight:w,strideWidth:_,filterHeight:C,filterWidth:A,dilationHeight:D,dilationWidth:$,outShape:R}=I.computeDilation2DInfo(n.shape,o.shape,a,i,"NHWC",l);y.assert(s.rank===R.length,()=>`Error in ${nf}, dy must have the same rank as output ${R.length}, but got ${s.rank}`);let M=y.toNestedArray(R,u.data.get(s.dataId).values),G=y.makeZerosNestedTypedArray(o.shape,o.dtype);for(let U=0;U<m;++U)for(let q=0;q<g;++q){let H=q*w-b.top;for(let X=0;X<x;++X){let ne=X*_-b.left;for(let Y=0;Y<h;++Y){let re=Number.MIN_SAFE_INTEGER,ee=0,ie=0;for(let me=0;me<C;++me){let ae=H+me*D;if(ae>=0&&ae<f)for(let fe=0;fe<A;++fe){let he=ne+fe*$;if(he>=0&&he<d){let xe=c[U][ae][he][Y]+p[me][fe][Y];xe>re&&(re=xe,ee=me,ie=fe)}}}G[ee][ie][Y]+=M[U][q][X][Y]}}}return{dataId:u.write(y.toTypedArray(G,n.dtype),o.shape,o.dtype),shape:o.shape,dtype:o.dtype}}};var S2={kernelName:rf,backendName:"cpu",kernelFunc:({inputs:r,backend:e,attrs:t})=>{let{x:n,filter:o,dy:s}=r,{strides:a,pad:i,dilations:l}=t,u=e,c=y.toNestedArray(n.shape,u.data.get(n.dataId).values),p=y.toNestedArray(o.shape,u.data.get(o.dataId).values),{batchSize:m,inHeight:f,inWidth:d,inChannels:h,outHeight:g,outWidth:x,padInfo:b,strideHeight:w,strideWidth:_,filterHeight:C,filterWidth:A,dilationHeight:D,dilationWidth:$,outShape:R}=I.computeDilation2DInfo(n.shape,o.shape,a,i,"NHWC",l);y.assert(s.rank===R.length,()=>`Error in ${rf}, dy must have the same rank as output ${R.length}, but got ${s.rank}`);let M=y.toNestedArray(R,u.data.get(s.dataId).values),G=y.makeZerosNestedTypedArray(n.shape,n.dtype);for(let U=0;U<m;++U)for(let q=0;q<g;++q){let H=q*w-b.top;for(let X=0;X<x;++X){let ne=X*_-b.left;for(let Y=0;Y<h;++Y){let re=Number.MIN_SAFE_INTEGER,ee=H<0?0:H,ie=ne<0?0:ne;for(let me=0;me<C;++me){let ae=H+me*D;if(ae>=0&&ae<f)for(let fe=0;fe<A;++fe){let he=ne+fe*$;if(he>=0&&he<d){let xe=c[U][ae][he][Y]+p[me][fe][Y];xe>re&&(re=xe,ee=ae,ie=he)}}}G[U][ee][ie][Y]+=M[U][q][X][Y]}}}return{dataId:u.write(y.toTypedArray(G,n.dtype),n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}};function Ga(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,keepDims:a}=n;te(o,"sum");let i;o.dtype==="bool"?i=yo({inputs:{x:o},backend:t,attrs:{dtype:"int32"}}):i=Br({inputs:{x:o},backend:t});let l=i.shape.length,u=y.parseAxisParam(s,i.shape),c=I.getAxesPermutation(u,l),p=u,m=i;c!=null&&(m=Qt({inputs:{x:i},backend:t,attrs:{perm:c}}),p=I.getInnerMostAxes(p.length,l)),I.assertAxesAreInnerMostDims("sum",p,m.shape.length);let[f,d]=I.computeOutAndReduceShapes(m.shape,p),h=I.upcastType(m.dtype,"int32"),g=Wp(t,f,h),x=y.sizeFromShape(d),b=t.data.get(g.dataId).values,w=t.data.get(m.dataId).values;for(let _=0;_<b.length;++_){let C=_*x,A=0;for(let D=0;D<x;++D)A+=w[C+D];b[_]=A}if(a){let _=I.expandShapeToKeepDim(g.shape,u),C=g;g=Je({inputs:{x:g},backend:t,attrs:{shape:_}}),t.disposeIntermediateTensorInfo(C)}return t.disposeIntermediateTensorInfo(i),c!=null&&t.disposeIntermediateTensorInfo(m),g}var N2={kernelName:xs,backendName:"cpu",kernelFunc:Ga};function v8(r){let{inputs:e,backend:t,attrs:n}=r,{equation:o}=n,s=e,{allDims:a,summedDims:i,idDims:l}=I.decodeEinsumEquation(o,s.length);I.checkEinsumDimSizes(a.length,l,s);let{path:u,steps:c}=I.getEinsumComputePath(i,l),p=c.length,m=null,f=a.length,d=[];for(let h=0;h<p;++h){for(let g of c[h]){let{permutationIndices:x,expandDims:b}=I.getEinsumPermutation(f,l[g]),w;I.isIdentityPermutation(x)?w=s[g]:(w=Qt({inputs:{x:s[g]},backend:t,attrs:{perm:x}}),d.push(w));let _=w.shape.slice();for(let C=0;C<b.length;++C)_.splice(b[C],0,1);y.arraysEqual(w.shape,_)||(w=Je({inputs:{x:w},backend:t,attrs:{shape:_}}),d.push(w)),m===null?m=w:(m=tc({inputs:{a:w,b:m},backend:t}),d.push(m))}h<p-1&&(u[h]>=0&&(m=Ga({inputs:{x:m},backend:t,attrs:{axis:u[h]-(a.length-f),keepDims:!1}}),d.push(m)),f--)}for(let h of d)h!==m&&t.disposeIntermediateTensorInfo(h);return m}var T2={kernelName:ep,backendName:"cpu",kernelFunc:v8};function C8(r){let{inputs:e,backend:t}=r,{dy:n,y:o}=e;te([n,o],"eluGrad");let s=new Float32Array(y.sizeFromShape(o.shape)),a=t.data.get(o.dataId).values,i=t.data.get(n.dataId).values;for(let l=0;l<a.length;++l){let u=a[l];u>=1?s[l]=i[l]:s[l]=i[l]*(u+1)}return t.makeTensorInfo(o.shape,"float32",s)}var E2={kernelName:tp,backendName:"cpu",kernelFunc:C8};var I8=I.ERF_P,S8=I.ERF_A1,N8=I.ERF_A2,T8=I.ERF_A3,E8=I.ERF_A4,A8=I.ERF_A5,D8=Re(qi,r=>{let e=Math.sign(r),t=Math.abs(r),n=1/(1+I8*t);return e*(1-((((A8*n+E8)*n+T8)*n+N8)*n+S8)*n*Math.exp(-t*t))}),A2={kernelName:qi,backendName:"cpu",kernelFunc:D8};function Yp(r){let{inputs:e,backend:t,attrs:n}=r,{input:o}=e,{dim:s}=n,a=o.shape.length,i=o.shape.slice(),l=s;return s<0&&(y.assert(-(a+1)<=s,()=>`Axis must be in the interval [${-(a+1)}, ${a}]`),l=a+s+1),i.splice(l,0,1),Je({inputs:{x:o},backend:t,attrs:{shape:i}})}var D2={kernelName:ei,backendName:"cpu",kernelFunc:Yp};var $8=Ze((r,e)=>r/e),Qf=tt(Go,$8),ed={kernelName:Go,backendName:"cpu",kernelFunc:Qf};function Dx(r,e,t){let n=r.shape,o=n[0],s=n[1],a=t.data.get(r.dataId),i=a.complexTensorInfos.real,l=a.complexTensorInfos.imag,u=[o,s],c=y.sizeFromShape(u),p=y.getTypedArrayFromDType("float32",c),m=y.getTypedArrayFromDType("float32",c);for(let g=0;g<o;g++){let x=_o({inputs:{x:i},backend:t,attrs:{begin:[g,0],size:[1,s]}}),b=_o({inputs:{x:l},backend:t,attrs:{begin:[g,0],size:[1,s]}}),w=xr({inputs:{real:x,imag:b},backend:t}),{real:_,imag:C}=R8(w,e,t),A=I.mergeRealAndImagArrays(_,C);for(let D=0;D<s;D++){let $=I.getComplexWithIndex(A,D);p[g*s+D]=$.real,m[g*s+D]=$.imag}t.disposeIntermediateTensorInfo(x),t.disposeIntermediateTensorInfo(b),t.disposeIntermediateTensorInfo(w)}let f=t.makeTensorInfo(u,"float32",p),d=t.makeTensorInfo(u,"float32",m),h=xr({inputs:{real:f,imag:d},backend:t});return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(d),h}function R8(r,e,t){let n=y.sizeFromShape(r.shape),o=t.data.get(r.dataId),s=t.data.get(o.complexTensorInfos.real.dataId).values,a=t.data.get(o.complexTensorInfos.imag.dataId).values;if(F8(n)){let i=Hk(s,a,n,e,t),l=[r.shape[0],r.shape[1]];if(e){let u=t.makeTensorInfo(l,"float32",i.real),c=t.makeTensorInfo(l,"float32",i.imag),p=t.makeTensorInfo([],"float32",y.createScalarValue(n,"float32")),m=Br({inputs:{x:p},backend:t}),f=ed.kernelFunc({inputs:{a:u,b:p},backend:t}),d=ed.kernelFunc({inputs:{a:c,b:m},backend:t}),h=t.data.get(f.dataId).values,g=t.data.get(d.dataId).values;return t.disposeIntermediateTensorInfo(u),t.disposeIntermediateTensorInfo(c),t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(d),{real:h,imag:g}}return i}else{let i=I.mergeRealAndImagArrays(s,a),l=O8(i,n,e);return I.splitRealAndImagArrays(l)}}function F8(r){return(r&r-1)==0}function Hk(r,e,t,n,o){if(t===1)return{real:r,imag:e};let s=I.mergeRealAndImagArrays(r,e),a=t/2,i=I.complexWithEvenIndex(s),l=i.real,u=i.imag,c=[l.length],p=o.makeTensorInfo(c,"float32",l),m=o.makeTensorInfo(c,"float32",u),f=xr({inputs:{real:p,imag:m},backend:o}),d=I.complexWithOddIndex(s),h=d.real,g=d.imag,x=[h.length],b=o.makeTensorInfo(x,"float32",h),w=o.makeTensorInfo(x,"float32",g),_=xr({inputs:{real:b,imag:w},backend:o}),C=Hk(l,u,a,n,o),A=C.real,D=C.imag,$=[A.length],R=o.makeTensorInfo($,"float32",A),M=o.makeTensorInfo($,"float32",D),G=xr({inputs:{real:R,imag:M},backend:o}),j=Hk(h,g,a,n,o),U=j.real,q=j.imag,H=[U.length],X=o.makeTensorInfo(H,"float32",U),ne=o.makeTensorInfo(H,"float32",q),Y=xr({inputs:{real:X,imag:ne},backend:o}),re=I.exponents(t,n),ee=[re.real.length],ie=o.makeTensorInfo(ee,"float32",re.real),me=o.makeTensorInfo(ee,"float32",re.imag),ae=xr({inputs:{real:ie,imag:me},backend:o}),fe=tc({inputs:{a:ae,b:Y},backend:o}),he=Va({inputs:{a:G,b:fe},backend:o}),xe=Jf({inputs:{a:G,b:fe},backend:o}),_e=xo({inputs:{input:he},backend:o}),$e=xo({inputs:{input:xe},backend:o}),Ce=bi({inputs:{input:he},backend:o}),We=bi({inputs:{input:xe},backend:o}),Xe=Dl({inputs:[_e,$e],backend:o,attrs:{axis:0}}),lt=Dl({inputs:[Ce,We],backend:o,attrs:{axis:0}}),Et=o.data.get(Xe.dataId).values,At=o.data.get(lt.dataId).values;return o.disposeIntermediateTensorInfo(p),o.disposeIntermediateTensorInfo(m),o.disposeIntermediateTensorInfo(f),o.disposeIntermediateTensorInfo(b),o.disposeIntermediateTensorInfo(w),o.disposeIntermediateTensorInfo(_),o.disposeIntermediateTensorInfo(R),o.disposeIntermediateTensorInfo(M),o.disposeIntermediateTensorInfo(G),o.disposeIntermediateTensorInfo(X),o.disposeIntermediateTensorInfo(ne),o.disposeIntermediateTensorInfo(Y),o.disposeIntermediateTensorInfo(ie),o.disposeIntermediateTensorInfo(me),o.disposeIntermediateTensorInfo(ae),o.disposeIntermediateTensorInfo(fe),o.disposeIntermediateTensorInfo(he),o.disposeIntermediateTensorInfo(xe),o.disposeIntermediateTensorInfo(_e),o.disposeIntermediateTensorInfo(Ce),o.disposeIntermediateTensorInfo($e),o.disposeIntermediateTensorInfo(We),o.disposeIntermediateTensorInfo(Xe),o.disposeIntermediateTensorInfo(lt),{real:Et,imag:At}}function O8(r,e,t){let n=new Float32Array(e*2);for(let o=0;o<e;o++){let s=0,a=0;for(let i=0;i<e;i++){let l=I.exponent(o*i,e,t),u=I.getComplexWithIndex(r,i);s+=u.real*l.real-u.imag*l.imag,a+=u.real*l.imag+u.imag*l.real}t&&(s/=e,a/=e),I.assignToTypedArray(n,s,a,o)}return n}function P8(r){let{inputs:e,backend:t}=r,{input:n}=e,o=y.sizeFromShape(n.shape),s=n.shape[n.shape.length-1],a=o/s,i=Je({inputs:{x:n},backend:t,attrs:{shape:[a,s]}}),l=Dx(i,!1,t),u=Je({inputs:{x:l},backend:t,attrs:{shape:n.shape}});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(l),u}var $2={kernelName:rp,backendName:"cpu",kernelFunc:P8};function td(r){let{backend:e,attrs:t}=r,{shape:n,value:o,dtype:s}=t,a=s||y.inferDtype(o),i=y.getArrayFromDType(a,y.sizeFromShape(n));return M8(i,o,a),e.makeTensorInfo(n,a,i)}var R2={kernelName:dl,backendName:"cpu",kernelFunc:td};function M8(r,e,t){r.fill(e)}var F2={kernelName:Xi,backendName:"cpu",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{image:n}=r,o=t,s=y.getTypedArrayFromDType(n.dtype,y.sizeFromShape(n.shape)),[a,i,l,u]=n.shape,c=o.data.get(n.dataId).values;for(let m=0;m<a;m++){let f=m*l*i*u;for(let d=0;d<i;d++){let h=d*(l*u);for(let g=0;g<l;g++){let x=g*u;for(let b=0;b<u;b++){let _=[a,d,g,b][2],C=Math.round(l-_),A=f+h+x+b,D=c[A];if(C>=0&&C<l){let $=C*u,R=f+h+$+b;D=c[R]}s[A]=D}}}}return{dataId:o.write(s,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}};var L8=Ze((r,e)=>Math.floor(r/e)),z8=tt(Uo,L8,null,"int32"),O2={kernelName:Uo,backendName:"cpu",kernelFunc:z8};function B8(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,filter:s,bias:a,preluActivationWeights:i}=e,{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=n,h=Uk({inputs:{x:o,filter:s},backend:t,attrs:{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:m}});if(a){let g=h;h=Va({inputs:{a:h,b:a},backend:t}),t.disposeIntermediateTensorInfo(g)}if(f){let g=h;h=Kp(t,h,f,i,d),t.disposeIntermediateTensorInfo(g)}return h}var P2={kernelName:mi,backendName:"cpu",kernelFunc:B8};function V8(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,filter:s,bias:a,preluActivationWeights:i}=e,{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=n,h=qk({inputs:{x:o,filter:s},backend:t,attrs:{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:m}});if(a){let g=h;h=Va({inputs:{a:h,b:a},backend:t}),t.disposeIntermediateTensorInfo(g)}if(f){let g=h;h=Kp(t,h,f,i,d),t.disposeIntermediateTensorInfo(g)}return h}var M2={kernelName:fi,backendName:"cpu",kernelFunc:V8};function G8(r){let{inputs:e,backend:t}=r,{params:n,indices:o}=e,s=y.sizeFromShape(n.shape),a=o.shape,i=a[a.length-1],[l,u,c,p]=I.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=hx(m,f,n.dtype,u,i,c,p,n.shape,s);return t.makeTensorInfo(l,n.dtype,d.values)}var L2={kernelName:Yi,backendName:"cpu",kernelFunc:G8};function W8(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,indices:s}=e,{axis:a,batchDims:i}=n;te([o,s],"gatherV2");let l=i;i==null&&(l=0);let u=y.sizeFromShape(s.shape),c=y.parseAxisParam(a,o.shape)[0],p=I.segment_util.collectGatherOpShapeInfo(o,s,c,l),m=Je({inputs:{x:o},backend:t,attrs:{shape:[p.batchSize,p.outerSize,p.dimSize,p.sliceSize]}}),f=Je({inputs:{x:s},backend:t,attrs:{shape:[p.batchSize,u/p.batchSize]}}),d=[p.batchSize,p.outerSize,u/p.batchSize,p.sliceSize],h=t.bufferSync(f),g=t.bufferSync(m),x=gx(g,h,d);return t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f),t.makeTensorInfo(p.outputShape,x.dtype,x.values)}var z2={kernelName:ti,backendName:"cpu",kernelFunc:W8};function j8(r){let{inputs:e,backend:t}=r,{input:n}=e,o=y.sizeFromShape(n.shape),s=n.shape[n.shape.length-1],a=o/s,i=Je({inputs:{x:n},backend:t,attrs:{shape:[a,s]}}),l=Dx(i,!0,t),u=Je({inputs:{x:l},backend:t,attrs:{shape:n.shape}});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(l),u}var B2={kernelName:np,backendName:"cpu",kernelFunc:j8};var U8=Re(Ji,r=>Number.isFinite(r)?1:0,"bool"),V2={kernelName:Ji,backendName:"cpu",kernelFunc:U8};var q8=Re(Qi,r=>Math.abs(r)===Infinity?1:0,"bool"),G2={kernelName:Qi,backendName:"cpu",kernelFunc:q8};var H8=Re(ea,r=>Number.isNaN(r)?1:0,"bool"),W2={kernelName:ea,backendName:"cpu",kernelFunc:H8};function K8(r){let{backend:e,attrs:t}=r,{start:n,stop:o,num:s}=t,a=xx(n,o,s);return e.makeTensorInfo([a.length],"float32",a)}var j2={kernelName:sp,backendName:"cpu",kernelFunc:K8};var X8=Re(na,r=>Math.log1p(r)),U2={kernelName:na,backendName:"cpu",kernelFunc:X8};var Y8=Ze((r,e)=>r&&e),Z8=tt(oa,Y8,null,"bool"),q2={kernelName:oa,backendName:"cpu",kernelFunc:Z8};var J8=Re(iu,r=>r?0:1,"bool"),H2={kernelName:iu,backendName:"cpu",kernelFunc:J8};var Q8=Ze((r,e)=>r||e),eX=tt(au,Q8,null,"bool"),K2={kernelName:au,backendName:"cpu",kernelFunc:eX};function tX(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{depthRadius:s,bias:a,alpha:i,beta:l}=n;te(o,"LRN");let u=o.shape[3],c=u-1,p=t.data.get(o.dataId).values,m=y.sizeFromShape(o.shape),f=new Float32Array(m);function d(h){let g=h%u,x=h-g+Math.max(0,g-s),b=h-g+Math.min(g+s,c),w=0;for(;x<=b;x++){let _=p[x];w+=_*_}return w}for(let h=0;h<m;h++){let g=d(h),x=p[h]*Math.pow(a+i*g,-l);f[h]=x}return t.makeTensorInfo(o.shape,o.dtype,f)}var X2={kernelName:hl,backendName:"cpu",kernelFunc:tX};function rX(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,y:s,dy:a}=e,{depthRadius:i,bias:l,alpha:u,beta:c}=n;te(a,"LRNGrad");let p=y.sizeFromShape(a.shape),m=a.shape[3],f=t.data.get(a.dataId).values,d=t.data.get(o.dataId).values,h=t.data.get(s.dataId).values,g=new Float32Array(p),x=p;for(let b=0;b<x;b++){let w=b%m,_=b-w+Math.max(0,w-i),C=b-w+Math.min(m,w+i+1),A=0;for(let D=_;D<C;D++)A+=Math.pow(d[D],2);A=u*A+l;for(let D=_;D<C;D++){let $=-2*u*c*d[D]*h[b]/A;b===D&&($+=Math.pow(A,-c)),$*=f[b],g[D]+=$}}return t.makeTensorInfo(a.shape,o.dtype,g)}var Y2={kernelName:ip,backendName:"cpu",kernelFunc:rX};function Kk(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{reductionIndices:s,keepDims:a}=n,i=t,l=o.shape,u=l.length,c=y.parseAxisParam(s,l),p=c,m=I.getAxesPermutation(p,u),f=i.data.get(o.dataId).values;if(m!=null){let _=new Array(u);for(let C=0;C<_.length;C++)_[C]=l[m[C]];f=qp(f,l,o.dtype,m,_),p=I.getInnerMostAxes(p.length,u),l=_}te(o,"max"),I.assertAxesAreInnerMostDims("max",p,u);let[d,h]=I.computeOutAndReduceShapes(l,p),g=y.sizeFromShape(h),x=yx(f,g,d,o.dtype),b=i.write(x,d,o.dtype),w=d;return a&&(w=I.expandShapeToKeepDim(d,c)),{dataId:b,shape:w,dtype:o.dtype}}var Z2={kernelName:Yo,backendName:"cpu",kernelFunc:Kk};function nX(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e;te(o,"maxPool");let{filterSize:s,strides:a,pad:i,dimRoundingMode:l}=n,u=1;y.assert(I.eitherStridesOrDilationsAreOne(a,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let c=I.computePool2DInfo(o.shape,s,a,u,i,l),p;if(c.filterWidth===1&&c.filterHeight===1&&y.arraysEqual(c.inShape,c.outShape))p=Br({inputs:{x:o},backend:t});else{let m=t.data.get(o.dataId).values,f=y.computeStrides(o.shape),d=Xp(m,o.shape,o.dtype,f,c,"max");p=t.makeTensorInfo(c.outShape,o.dtype,d.values)}return p}var J2={kernelName:Jo,backendName:"cpu",kernelFunc:nX};function oX(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{filterSize:s,strides:a,pad:i,dimRoundingMode:l,dataFormat:u}=n;te(o,"maxPool3d");let c=I.computePool3DInfo(o.shape,s,a,1,i,l,u),p=t.data.get(o.dataId).values,m=Ax(p,o.shape,o.dtype,y.computeStrides(o.shape),c,"max");return t.makeTensorInfo(m.shape,"float32",m.values)}var Q2={kernelName:gl,backendName:"cpu",kernelFunc:oX};function sX(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,input:s}=e,{filterSize:a,strides:i,pad:l,dimRoundingMode:u}=n;te([o,s],"maxPool3DGrad");let c=I.computePool3DInfo(s.shape,a,i,1,l,u),p=t.bufferSync(s),m=YA(p,c),f=c.strideDepth,d=c.strideHeight,h=c.strideWidth,g=c.dilationDepth,x=c.dilationHeight,b=c.dilationWidth,w=c.effectiveFilterDepth,_=c.effectiveFilterHeight,C=c.effectiveFilterWidth,A=w-1-c.padInfo.front,D=C-1-c.padInfo.left,$=_-1-c.padInfo.top,R=Ie(s.shape,"float32"),M=t.bufferSync(o);for(let G=0;G<c.batchSize;++G)for(let j=0;j<c.inChannels;++j)for(let U=0;U<c.inDepth;++U)for(let q=0;q<c.inHeight;++q)for(let H=0;H<c.inWidth;++H){let X=U-A,ne=q-$,Y=H-D,re=0;for(let ee=0;ee<w;ee+=g){let ie=(X+ee)/f;if(!(ie<0||ie>=c.outDepth||Math.floor(ie)!==ie))for(let me=0;me<_;me+=x){let ae=(ne+me)/d;if(!(ae<0||ae>=c.outHeight||Math.floor(ae)!==ae))for(let fe=0;fe<C;fe+=b){let he=(Y+fe)/h;if(he<0||he>=c.outWidth||Math.floor(he)!==he)continue;let xe=w*_*C-1-m.get(G,ie,ae,he,j),_e=ee*_*C+me*C+fe,$e=xe===_e?1:0;if($e===0)continue;re+=M.get(G,ie,ae,he,j)*$e}}}R.set(re,G,U,q,H,j)}return t.makeTensorInfo(R.shape,R.dtype,R.values)}var eD={kernelName:lp,backendName:"cpu",kernelFunc:sX};function iX(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,input:s,output:a}=e,i=s;te([s,a],"maxPoolGrad");let{filterSize:l,strides:u,pad:c,dimRoundingMode:p}=n,m=I.computePool2DInfo(i.shape,l,u,1,c,p),f=t.data.get(i.dataId).values,d=Ie(m.outShape,i.dtype,Ex(f,i.shape,i.dtype,m).values),h=m.strideHeight,g=m.strideWidth,x=m.dilationHeight,b=m.dilationWidth,w=m.effectiveFilterHeight,_=m.effectiveFilterWidth,C=_-1-m.padInfo.left,A=w-1-m.padInfo.top,D=Ie(i.shape,"float32"),$=t.data.get(o.dataId).values,R=Ie(o.shape,"float32",$);for(let M=0;M<m.batchSize;++M)for(let G=0;G<m.inChannels;++G)for(let j=0;j<m.inHeight;++j)for(let U=0;U<m.inWidth;++U){let q=j-A,H=U-C,X=0;for(let ne=0;ne<w;ne+=x){let Y=(q+ne)/h;if(!(Y<0||Y>=m.outHeight||Math.floor(Y)!==Y))for(let re=0;re<_;re+=b){let ee=(H+re)/g;if(ee<0||ee>=m.outWidth||Math.floor(ee)!==ee)continue;let ie=w*_-1-d.get(M,Y,ee,G),me=ne*_+re,ae=ie===me?1:0;if(ae===0)continue;X+=R.get(M,Y,ee,G)*ae}}D.set(X,M,j,U,G)}return t.makeTensorInfo(D.shape,D.dtype,D.values)}var tD={kernelName:ap,backendName:"cpu",kernelFunc:iX};function rD(r,e,t,n,o){let s=y.computeStrides(e),a=Xp(r,e,t,s,o,"max"),i=Ex(r,e,t,o,!0,n);return[a.values,i.values]}var nD={kernelName:up,backendName:"cpu",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{x:n}=r,{filterSize:o,strides:s,pad:a,includeBatchInIndex:i}=e,l=t;te(n,"MaxPoolWithArgmax");let u=l.data.get(n.dataId).values,c=I.computePool2DInfo(n.shape,o,s,[1,1],a),[p,m]=rD(u,n.shape,n.dtype,i,c),f=l.write(p,c.outShape,n.dtype),d=l.write(m,c.outShape,n.dtype);return[{dataId:f,shape:c.outShape,dtype:n.dtype},{dataId:d,shape:c.outShape,dtype:"int32"}]}};function aX(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,keepDims:a}=n,i=y.parseAxisParam(s,o.shape),u=I.computeOutAndReduceShapes(o.shape,i)[1],c=y.sizeFromShape(u),p=[],m=t.makeTensorInfo([],"float32",new Float32Array([c]));p.push(m);let f=yo({inputs:{x:o},backend:t,attrs:{dtype:"float32"}});p.push(f);let d=Qf({inputs:{a:f,b:m},backend:t});p.push(d);let h=Ga({inputs:{x:d},backend:t,attrs:{axis:s,keepDims:a}});return p.forEach(g=>t.disposeIntermediateTensorInfo(g)),h}var oD={kernelName:Qo,backendName:"cpu",kernelFunc:aX};function lX(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,keepDims:a}=n;te(o,"min");let i=y.parseAxisParam(s,o.shape),l=i,u=I.getAxesPermutation(l,o.shape.length),c=o;u!=null&&(c=Qt({inputs:{x:o},backend:t,attrs:{perm:u}}),l=I.getInnerMostAxes(l.length,o.shape.length)),I.assertAxesAreInnerMostDims("min",l,c.shape.length);let[p,m]=I.computeOutAndReduceShapes(c.shape,l),f=y.sizeFromShape(m),d=y.makeZerosTypedArray(y.sizeFromShape(p),c.dtype),h=t.data.get(c.dataId).values;for(let x=0;x<d.length;++x){let b=x*f,w=h[b];for(let _=0;_<f;++_){let C=h[b+_];(Number.isNaN(C)||C<w)&&(w=C)}d[x]=w}u!=null&&t.disposeIntermediateTensorInfo(c);let g=t.makeTensorInfo(p,c.dtype,d);if(a){let x=I.expandShapeToKeepDim(p,i),b=Je({inputs:{x:g},backend:t,attrs:{shape:x}});return t.disposeIntermediateTensorInfo(g),b}return g}var sD={kernelName:es,backendName:"cpu",kernelFunc:lX};function uX(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{paddings:s,mode:a}=n;te(o,"mirrorPad");let i=s.map((w,_)=>w[0]+o.shape[_]+w[1]),l=s.map(w=>w[0]),u=s.map((w,_)=>w[0]+o.shape[_]),c=a==="reflect"?0:1,p=t.data.get(o.dataId).values,m=o.shape.length,f=y.computeStrides(o.shape),d=y.sizeFromShape(i),h=i.length,g=y.computeStrides(i),x=y.getTypedArrayFromDType(o.dtype,d);for(let w=0;w<d;w++){let _=y.indexToLoc(w,h,g);for(let A=0;A<h;A++)_[A]<l[A]?_[A]=l[A]*2-_[A]-c:_[A]>=u[A]&&(_[A]=(u[A]-1)*2-_[A]+c);_=_.map((A,D)=>A-l[D]);let C=y.locToIndex(_,m,f);x[w]=p[C]}return{dataId:t.write(x,i,o.dtype),shape:i,dtype:o.dtype}}var iD={kernelName:rs,backendName:"cpu",kernelFunc:uX};var cX=Ze((r,e)=>{let t=r%e;return r<0&&e<0||r>=0&&e>=0?t:(t+e)%e}),pX=tt(sa,cX),aD={kernelName:sa,backendName:"cpu",kernelFunc:pX};var uD=nu(sk());function Xk(r){let{inputs:e,backend:t,attrs:n}=r,{logits:o}=e,{dim:s}=n,a=o.shape.length,i=s;if(i===-1&&(i=a-1),i!==a-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${a} and dim was ${i}`);let l=y.parseAxisParam([i],o.shape),u=Kk({inputs:{x:o},backend:t,attrs:{reductionIndices:l,keepDims:!1}}),c=I.expandShapeToKeepDim(u.shape,l),p=Je({inputs:{x:u},backend:t,attrs:{shape:c}}),m=Jf({inputs:{a:o,b:p},backend:t}),f=_k({inputs:{x:m},backend:t}),d=Ga({inputs:{x:f},backend:t,attrs:{axis:l,keepDims:!1}}),h=Je({inputs:{x:d},backend:t,attrs:{shape:c}}),g=Qf({inputs:{a:f,b:h},backend:t});return t.disposeIntermediateTensorInfo(u),t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(h),g}var lD={kernelName:ys,backendName:"cpu",kernelFunc:Xk};function mX(r){let{inputs:e,backend:t,attrs:n}=r,{logits:o}=e,{numSamples:s,seed:a,normalized:i}=n;te(o,"multinomial");let l=i?o:Xk({inputs:{logits:o},backend:t,attrs:{dim:-1}}),u=l.shape[0],c=l.shape[1],p=t.data.get(l.dataId).values,m=[u,s],f=y.makeZerosTypedArray(y.sizeFromShape(m),"int32");for(let d=0;d<u;++d){let h=d*c,g=new Float32Array(c-1);g[0]=p[h];for(let w=1;w<g.length;++w)g[w]=g[w-1]+p[h+w];let x=uD.alea(a.toString()),b=d*s;for(let w=0;w<s;++w){let _=x();f[b+w]=g.length;for(let C=0;C<g.length;C++)if(_<g[C]){f[b+w]=C;break}}}return i||t.disposeIntermediateTensorInfo(l),t.makeTensorInfo(m,"int32",f)}var cD={kernelName:cp,backendName:"cpu",kernelFunc:mX};var fX=zr.nonMaxSuppressionV3Impl;function dX(r){let{inputs:e,backend:t,attrs:n}=r,{boxes:o,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:l}=n;te(o,"NonMaxSuppression");let u=t.data.get(o.dataId).values,c=t.data.get(s.dataId).values,{selectedIndices:p}=fX(u,c,a,i,l);return t.makeTensorInfo([p.length],"int32",new Int32Array(p))}var pD={kernelName:aa,backendName:"cpu",kernelFunc:dX};var hX=zr.nonMaxSuppressionV4Impl;function gX(r){let{inputs:e,backend:t,attrs:n}=r,{boxes:o,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:l,padToMaxOutputSize:u}=n;te(o,"NonMaxSuppressionPadded");let c=t.data.get(o.dataId).values,p=t.data.get(s.dataId).values,{selectedIndices:m,validOutputs:f}=hX(c,p,a,i,l,u);return[t.makeTensorInfo([m.length],"int32",new Int32Array(m)),t.makeTensorInfo([],"int32",new Int32Array([f]))]}var mD={kernelName:la,backendName:"cpu",kernelFunc:gX};var xX=zr.nonMaxSuppressionV5Impl;function yX(r){let{inputs:e,backend:t,attrs:n}=r,{boxes:o,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:l,softNmsSigma:u}=n;te(o,"NonMaxSuppressionWithScore");let c=t.data.get(o.dataId).values,p=t.data.get(s.dataId).values,m=a,f=i,d=l,h=u,{selectedIndices:g,selectedScores:x}=xX(c,p,m,f,d,h);return[t.makeTensorInfo([g.length],"int32",new Int32Array(g)),t.makeTensorInfo([x.length],"float32",new Float32Array(x))]}var fD={kernelName:ua,backendName:"cpu",kernelFunc:yX};function bX(r){let{inputs:e,backend:t,attrs:n}=r,{indices:o}=e,{depth:s,onValue:a,offValue:i}=n;te(o,"oneHot");let l=y.sizeFromShape(o.shape),u=new Float32Array(l*s);u.fill(i);let c=t.data.get(o.dataId).values;for(let p=0;p<l;++p)c[p]>=0&&c[p]<s&&(u[p*s+c[p]]=a);return t.makeTensorInfo([...o.shape,s],"int32",u)}var dD={kernelName:os,backendName:"cpu",kernelFunc:bX};function rd(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=xo({inputs:{input:n},backend:t}),s=rd({inputs:{x:o},backend:t}),a=bi({inputs:{input:n},backend:t}),i=rd({inputs:{x:a},backend:t}),l=xr({inputs:{real:s,imag:i},backend:t});return t.disposeIntermediateTensorInfo(o),t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),l}else return td({backend:t,attrs:{shape:n.shape,value:0,dtype:n.dtype}})}var hD={kernelName:ci,backendName:"cpu",kernelFunc:rd};function gD(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=xo({inputs:{input:n},backend:t}),s=gD({inputs:{x:o},backend:t}),a=bi({inputs:{input:n},backend:t}),i=rd({inputs:{x:a},backend:t}),l=xr({inputs:{real:s,imag:i},backend:t});return t.disposeIntermediateTensorInfo(o),t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),l}else return td({backend:t,attrs:{shape:n.shape,value:1,dtype:n.dtype}})}var xD={kernelName:ni,backendName:"cpu",kernelFunc:gD};function Yk(r){let{inputs:e,backend:t,attrs:n}=r,{axis:o}=n;if(e.length===1)return Yp({inputs:{input:e[0]},backend:t,attrs:{dim:o}});let s=e[0].shape,a=e[0].dtype;e.forEach(c=>{y.assertShapesMatch(s,c.shape,"All tensors passed to stack must have matching shapes"),y.assert(a===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=e.map(c=>{let p=Yp({inputs:{input:c},backend:t,attrs:{dim:o}});return i.push(p),p}),u=Dl({inputs:l,backend:t,attrs:{axis:o}});return i.forEach(c=>t.disposeIntermediateTensorInfo(c)),u}var yD={kernelName:oi,backendName:"cpu",kernelFunc:Yk};function wX(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{paddings:s,constantValue:a}=n;te(o,"pad");let i=s.map((b,w)=>b[0]+o.shape[w]+b[1]),l=s.map(b=>b[0]),u=t.data.get(o.dataId).values,c=y.sizeFromShape(o.shape),p=o.shape.length,m=y.computeStrides(o.shape),f=y.sizeFromShape(i),d=i.length,h=y.computeStrides(i),g=y.getTypedArrayFromDType(o.dtype,f);a!==0&&g.fill(a);for(let b=0;b<c;b++){let _=y.indexToLoc(b,p,m).map((A,D)=>A+l[D]),C=y.locToIndex(_,d,h);g[C]=u[b]}return{dataId:t.write(g,i,o.dtype),shape:i,dtype:o.dtype}}var $x={kernelName:ss,backendName:"cpu",kernelFunc:wX};var _X=Ze((r,e)=>Math.pow(r,e)),kX=tt(is,_X),bD={kernelName:is,backendName:"cpu",kernelFunc:kX};function vX(r){let{backend:e,attrs:t}=r,{start:n,stop:o,dtype:s,step:a}=t,i=rc(n,o,a,s);return e.makeTensorInfo([i.length],s,i)}var wD={kernelName:xl,backendName:"cpu",kernelFunc:vX};var CX=Re(pa,r=>1/r),_D={kernelName:pa,backendName:"cpu",kernelFunc:CX};function IX(r){let{inputs:e,backend:t,attrs:n}=r,{images:o}=e,{alignCorners:s,halfPixelCenters:a,size:i}=n;te(o,"resizeBilinear");let l=y.computeStrides(o.shape),[u,c]=i,[p,m,f,d]=o.shape,h=t.data.get(o.dataId).values,g=new Float32Array(y.sizeFromShape([p,u,c,d])),x=[s&&u>1?m-1:m,s&&c>1?f-1:f],b=[s&&u>1?u-1:u,s&&c>1?c-1:c],w=0,_=x[0]/b[0],C=x[1]/b[1];for(let A=0;A<p;A++)for(let D=0;D<u;D++){let $;a?$=_*(D+.5)-.5:$=_*D;let R=Math.max(0,Math.floor($)),M=$-R,G=Math.min(m-1,Math.ceil($)),j=A*l[0]+R*l[1],U=A*l[0]+G*l[1];for(let q=0;q<c;q++){let H;a?H=C*(q+.5)-.5:H=C*q;let X=Math.max(0,Math.floor(H)),ne=H-X,Y=Math.min(f-1,Math.ceil(H)),re=j+X*l[2],ee=U+X*l[2],ie=j+Y*l[2],me=U+Y*l[2];for(let ae=0;ae<d;ae++){let fe=h[re+ae],he=h[ee+ae],xe=h[ie+ae],_e=h[me+ae],$e=fe+(xe-fe)*ne,Ce=he+(_e-he)*ne,We=$e+(Ce-$e)*M;g[w++]=We}}}return t.makeTensorInfo([p,u,c,d],"float32",g)}var kD={kernelName:us,backendName:"cpu",kernelFunc:IX};function SX(r){let{inputs:e,backend:t,attrs:n}=r,{images:o,dy:s}=e,{alignCorners:a}=n;te([s,o],"resizeBilinearGrad");let i=y.computeStrides(o.shape),[l,u,c,p]=o.shape,[,m,f]=s.shape,d=new Float32Array(l*u*c*p),h=[a&&m>1?u-1:u,a&&f>1?c-1:c],g=[a&&m>1?m-1:m,a&&f>1?f-1:f],x=h[0]/g[0],b=h[1]/g[1],w=t.data.get(s.dataId).values,_=0;for(let C=0;C<l;C++){let A=C*i[0];for(let D=0;D<m;D++){let $=D*x,R=Math.floor($),M=Math.min(Math.ceil($),u-1),G=A+R*i[1],j=A+M*i[1],U=$-R,q=1-U;for(let H=0;H<f;H++){let X=H*b,ne=Math.floor(X),Y=Math.min(Math.ceil(X),c-1),re=X-ne,ee=1-re,ie=G+ne*i[2],me=G+Y*i[2],ae=j+ne*i[2],fe=j+Y*i[2],he=q*ee,xe=q*re,_e=U*ee,$e=U*re;for(let Ce=0;Ce<p;Ce++){let We=w[_++];d[ie+Ce]+=We*he,d[me+Ce]+=We*xe,d[ae+Ce]+=We*_e,d[fe+Ce]+=We*$e}}}}return t.makeTensorInfo([l,c,u,p],"float32",d)}var vD={kernelName:fp,backendName:"cpu",kernelFunc:SX};function NX(r){let{inputs:e,backend:t,attrs:n}=r,{images:o}=e,{alignCorners:s,halfPixelCenters:a,size:i}=n;te(o,"resizeNearestNeighbor");let l=y.computeStrides(o.shape),[u,c]=i,[p,m,f,d]=o.shape,h=t.data.get(o.dataId).values,g=new Float32Array(p*u*c*d),x=[s&&u>1?m-1:m,s&&c>1?f-1:f],b=[s&&u>1?u-1:u,s&&c>1?c-1:c],w=x[0]/b[0],_=x[1]/b[1],C=0;for(let A=0;A<p;A++){let D=A*l[0];for(let $=0;$<u;$++){let R=a?w*($+.5):w*$,M=Math.min(m-1,s?Math.round(R):Math.floor(R));a&&(M=Math.max(0,M));let G=D+M*l[1];for(let j=0;j<c;j++){let U=a?_*(j+.5):_*j,q=Math.min(f-1,s?Math.round(U):Math.floor(U));a&&(q=Math.max(0,q));let H=G+q*l[2];for(let X=0;X<d;X++){let ne=h[H+X];g[C++]=ne}}}}return t.makeTensorInfo([p,u,c,d],o.dtype,g)}var CD={kernelName:yl,backendName:"cpu",kernelFunc:NX};function TX(r){let{inputs:e,backend:t,attrs:n}=r,{images:o,dy:s}=e,{alignCorners:a}=n;te([s,o],"resizeNearestNeighborGrad");let i=y.computeStrides(o.shape),l=y.computeStrides(s.shape),[u,c,p,m]=o.shape,[,f,d]=s.shape,h=new Float32Array(u*c*p*m),g=t.data.get(s.dataId).values,x=[a&&f>1?c-1:c,a&&d>1?p-1:p],b=[a&&f>1?f-1:f,a&&d>1?d-1:d],w=x[0]/b[0],_=x[1]/b[1],C=1/w,A=1/_,D=Math.ceil(C)*2+2,$=Math.ceil(A)*2+2;for(let R=0;R<u;R++){let M=R*i[0];for(let G=0;G<c;G++){let j=M+G*i[1],U=Math.floor(G*C),q=Math.floor(U-D/2);for(let H=0;H<p;H++){let X=j+H*i[2],ne=Math.floor(H*A),Y=Math.floor(ne-$/2);for(let re=0;re<m;re++){let ee=0;for(let ie=0;ie<D;ie++){let me=ie+q;if(me<0||me>=f)continue;let ae=M+me*l[1],fe=me*w,he=Math.min(c-1,a?Math.round(fe):Math.floor(fe));if(G===he)for(let xe=0;xe<$;xe++){let _e=xe+Y;if(_e<0||_e>=d)continue;let $e=ae+_e*l[2],Ce=_e*_,We=Math.min(p-1,a?Math.round(Ce):Math.floor(Ce));H===We&&(ee+=g[$e+re])}}h[X+re]=ee}}}}return t.makeTensorInfo(o.shape,o.dtype,h)}var ID={kernelName:mp,backendName:"cpu",kernelFunc:TX};function EX(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{dims:s}=n;te(o,"reverse");let a=o.shape.length,i=y.parseAxisParam(s,o.shape);if(a===0)return Br({inputs:{x:o},backend:t});let l=new ct(o.shape,o.dtype),u=t.bufferSync(o);for(let c=0;c<l.size;c++){let p=l.indexToLoc(c),m=p.slice();i.forEach(f=>m[f]=o.shape[f]-1-m[f]),l.set(u.get(...m),...p)}return t.makeTensorInfo(l.shape,l.dtype,l.values)}var SD={kernelName:ps,backendName:"cpu",kernelFunc:EX};var ND={kernelName:wa,backendName:"cpu",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{image:n}=r,{radians:o,fillValue:s,center:a}=e,i=t,l=y.getTypedArrayFromDType(n.dtype,y.sizeFromShape(n.shape)),[u,c,p,m]=n.shape,[f,d]=I.getImageCenter(a,c,p),h=255,g=Math.sin(o),x=Math.cos(o),b=i.data.get(n.dataId).values;for(let _=0;_<u;_++){let C=_*p*c*m;for(let A=0;A<c;A++){let D=A*(p*m);for(let $=0;$<p;$++){let R=$*m;for(let M=0;M<m;M++){let G=[u,A,$,M],j=G[2],U=G[1],q=(j-f)*x-(U-d)*g,H=(j-f)*g+(U-d)*x;q=Math.round(q+f),H=Math.round(H+d);let X=s;if(typeof s!="number"&&(M===3?X=h:X=s[M]),q>=0&&q<p&&H>=0&&H<c){let Y=H*(p*m),re=q*m,ee=C+Y+re+M;X=b[ee]}let ne=C+D+R+M;l[ne]=X}}}}return{dataId:i.write(l,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}};var AX=Re(ms,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}),TD={kernelName:ms,backendName:"cpu",kernelFunc:AX};function Rx(r,e,t,n,o,s,a,i,l,u){let c=[n/o,o],p=r.values,m=e.values;if(n===0)return Ie(t,e.dtype);let f=Ie(c,e.dtype);f.values.fill(l);for(let d=0;d<s;d++){let h=[],g=0;for(let x=0;x<a;x++){let b=p[d*a+x];h.push(b),g+=b*i[x]}if(g<0||g>=n/o)throw new Error(`Invalid indices: ${h} does not index into ${t}`);for(let x=0;x<o;x++)u?f.values[g*o+x]+=m[d*o+x]:f.values[g*o+x]=e.rank===0?m[0]:m[d*o+x]}return f}function DX(r){let{inputs:e,backend:t,attrs:n}=r,{indices:o,updates:s}=e,{shape:a}=n,{sliceRank:i,numUpdates:l,sliceSize:u,strides:c,outputSize:p}=I.calculateShapes(s,o,a),m=!0,f=t.bufferSync(o),d=t.bufferSync(s),h=Rx(f,d,a,p,u,l,i,c,0,m);return t.makeTensorInfo(a,h.dtype,h.values)}var ED={kernelName:ma,backendName:"cpu",kernelFunc:DX};function $X(r){let{inputs:e,backend:t}=r,{condition:n,t:o,e:s}=e;te([n,o,s],"select");let a=n.shape.length,i=t.data.get(n.dataId).values,l=t.data.get(o.dataId).values,u=t.data.get(s.dataId).values,c=mr(o.dtype,s.dtype),p=y.makeZerosTypedArray(y.sizeFromShape(o.shape),c),m=0,f=a===0||a>1||o.shape.length===1?1:y.sizeFromShape(o.shape.slice(1));for(let d=0;d<i.length;d++)for(let h=0;h<f;h++)i[d]===1?p[m++]=l[d]:p[m++]=u[d];return t.makeTensorInfo(o.shape,c,p)}var AD={kernelName:ii,backendName:"cpu",kernelFunc:$X};var RX=I.SELU_SCALEALPHA,FX=I.SELU_SCALE,OX=Re(fa,r=>r>=0?FX*r:RX*(Math.exp(r)-1)),DD={kernelName:fa,backendName:"cpu",kernelFunc:OX};var PX=Re(ha,r=>r<0?-1:r>0?1:0),$D={kernelName:ha,backendName:"cpu",kernelFunc:PX};var MX=Re(ds,r=>Math.sin(r)),RD={kernelName:ds,backendName:"cpu",kernelFunc:MX};var LX=Re(da,r=>Math.sinh(r)),FD={kernelName:da,backendName:"cpu",kernelFunc:LX};var zX=11920928955078125e-23,OD=Math.log(zX)+2,BX=Re(ga,r=>{let e=r>-OD,t=r<OD,n=Math.exp(r),o;return t?o=n:e?o=r:o=Math.log(1+n),o}),PD={kernelName:ga,backendName:"cpu",kernelFunc:BX};function VX(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{blockShape:s,paddings:a}=n;te([o],"spaceToBatchND");let i=y.sizeFromShape(s),l=[[0,0]];l.push(...a);for(let A=1+s.length;A<o.shape.length;++A)l.push([0,0]);let u=$x.kernelFunc({inputs:{x:o},backend:t,attrs:{paddings:l,constantValue:0}}),c=I.getReshaped(u.shape,s,i,!1),p=I.getPermuted(c.length,s.length,!1),m=I.getReshapedPermuted(u.shape,s,i,!1),h=Je({inputs:{x:u},backend:t,attrs:{shape:c}}),b=Qt({inputs:{x:h},backend:t,attrs:{perm:p}}),C=Je({inputs:{x:b},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(u),t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(b),C}var MD={kernelName:bl,backendName:"cpu",kernelFunc:VX};function GX(r){let{inputs:e,backend:t}=r,{indices:n,values:o,denseShape:s,defaultValue:a}=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(a.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
|
|
${a.shape}`);let i=t.data.get(n.dataId).values,l=t.data.get(o.dataId).values,u=t.data.get(s.dataId).values,c=t.data.get(a.dataId).values[0],[p,m,f,d,h]=bx(i,n.shape,n.dtype,l,o.dtype,u,c);return[t.makeTensorInfo(m,n.dtype,p),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 LD={kernelName:dp,backendName:"cpu",kernelFunc:GX};function WX(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 a=Array.from(t.data.get(o.dataId).values),i=t.data.get(n.dataId).values,l=Array.from(t.data.get(s.dataId).values),[u,c,p]=wx(i,n.shape,n.dtype,a,l);return[t.makeTensorInfo(c,n.dtype,u),t.makeTensorInfo([p.length],s.dtype,new Int32Array(p))]}var zD={kernelName:hp,backendName:"cpu",kernelFunc:WX};function jX(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 a=t.data.get(n.dataId).values,i=t.data.get(o.dataId).values,l=t.data.get(s.dataId).values,[u,c]=Hp(a,n.shape,n.dtype,i,l,!0);return t.makeTensorInfo(c,n.dtype,u)}var BD={kernelName:gp,backendName:"cpu",kernelFunc:jX};function UX(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 a=t.data.get(n.dataId).values,i=t.data.get(o.dataId).values,l=t.data.get(s.dataId).values,[u,c]=Hp(a,n.shape,n.dtype,i,l);return t.makeTensorInfo(c,n.dtype,u)}var VD={kernelName:xp,backendName:"cpu",kernelFunc:UX};function qX(r){let{inputs:e,backend:t,attrs:n}=r,{sparseIndices:o,sparseValues:s,defaultValue:a}=e,{outputShape:i}=n,{sliceRank:l,numUpdates:u,sliceSize:c,strides:p,outputSize:m}=I.calculateShapes(s,o,i),f=!1,d=t.bufferSync(o),h=t.bufferSync(s),g=t.data.get(a.dataId).values[0],x=Rx(d,h,i,m,c,u,l,p,g,f);return t.makeTensorInfo(i,x.dtype,x.values)}var GD={kernelName:yp,backendName:"cpu",kernelFunc:qX};function HX(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{numOrSizeSplits:s,axis:a}=n,i=y.parseAxisParam(a,o.shape)[0],l=I.prepareSplitSize(o,s,i),u=new Array(o.shape.length).fill(0),c=o.shape.slice();return l.map(p=>{let m=[...c];m[i]=p;let f=_o({inputs:{x:o},backend:t,attrs:{begin:u,size:m}});return u[i]+=p,f})}var WD={kernelName:li,backendName:"cpu",kernelFunc:HX};var KX=Re(gs,r=>Math.sqrt(r)),jD={kernelName:gs,backendName:"cpu",kernelFunc:KX};var UD={kernelName:wl,backendName:"cpu",kernelFunc:({inputs:r,backend:e})=>{let{x:t}=r,n=e;te(t,"square");let o=n.data.get(t.dataId).values,s=new Float32Array(o.length);for(let i=0;i<o.length;++i){let l=o[i];s[i]=l*l}return{dataId:n.write(s,t.shape,t.dtype),shape:t.shape,dtype:t.dtype}}};var XX=Re(oo,(r,e)=>{let t=e;return isNaN(r)?NaN:r>0?1:t.alpha}),qD={kernelName:oo,backendName:"cpu",kernelFunc:XX};function YX(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{begin:s,end:a,strides:i,beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:m}=n;te(o,"stridedSlice");let{nonStrided:f,$begin:d,$strides:h,size:g,newShape:x,outShape:b}=lr.sliceInfo(o.shape,s,a,i,l,u,c,p,m),w=Je({inputs:{x:o},backend:t,attrs:{shape:x}}),_;if(f){let A=_o({inputs:{x:w},backend:t,attrs:{begin:d,size:g}});_=Je({inputs:{x:A},backend:t,attrs:{shape:b}}),t.disposeIntermediateTensorInfo(A)}else if(b.some(A=>A===0))_=t.makeTensorInfo(b,o.dtype,[]);else{let A=t.bufferSync(w),D=_x(b,A,h,d);_=t.makeTensorInfo(D.shape,D.dtype,D.values)}let C=Je({inputs:{x:_},backend:t,attrs:{shape:b}});return t.disposeIntermediateTensorInfo(w),t.disposeIntermediateTensorInfo(_),C}var HD={kernelName:xa,backendName:"cpu",kernelFunc:YX};function ZX(r){let{inputs:e,backend:t,attrs:n}=r,{separator:o,nGramWidths:s,leftPad:a,rightPad:i,padWidth:l,preserveShortSequences:u}=n,{data:c,dataSplits:p}=e,m=t.data.get(c.dataId).values,f=t.data.get(p.dataId).values,[d,h]=kx(m,f,o,s,a,i,l,u);return[t.makeTensorInfo([d.length],"string",d),t.makeTensorInfo(p.shape,"int32",h)]}var KD={kernelName:bp,backendName:"cpu",kernelFunc:ZX};function JX(r){let{inputs:e,backend:t,attrs:n}=r,{skipEmpty:o}=n,{input:s,delimiter:a}=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(a.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${a.shape}`);let i=t.data.get(s.dataId).values,l=t.data.get(a.dataId).values[0],[u,c,p]=vx(i,l,o),m=c.length;return[t.makeTensorInfo([m,2],"int32",u),t.makeTensorInfo([m],"string",c),t.makeTensorInfo([2],"int32",new Int32Array(p))]}var XD={kernelName:wp,backendName:"cpu",kernelFunc:JX};function QX(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 a=t.data.get(s.dataId).values,i=Cx(a,o);return t.makeTensorInfo(s.shape,"int32",i)}var YD={kernelName:_p,backendName:"cpu",kernelFunc:QX};var e7=Re(_s,r=>Math.tan(r)),ZD={kernelName:_s,backendName:"cpu",kernelFunc:e7};var t7=Re(ks,r=>Math.tanh(r)),JD={kernelName:ks,backendName:"cpu",kernelFunc:t7};function r7(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{reps:s}=n;te(o,"tile");let a=Ix(t.bufferSync(o),s);return t.makeTensorInfo(a.shape,a.dtype,a.values)}var QD={kernelName:Un,backendName:"cpu",kernelFunc:r7};function n7(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{k:s,sorted:a}=n;te(o,"topk");let i=t.data.get(o.dataId).values,[l,u]=Sx(i,o.shape,o.dtype,s,a);return[t.makeTensorInfo(l.shape,l.dtype,l.values),t.makeTensorInfo(u.shape,u.dtype,u.values)]}var e$={kernelName:ya,backendName:"cpu",kernelFunc:n7};function o7(r){let{inputs:e,attrs:t,backend:n}=r,{image:o,transforms:s}=e,{interpolation:a,fillMode:i,fillValue:l,outputShape:u}=t,[c,p,m,f]=o.shape,[d,h]=u!=null?u:[p,m],g=[c,d,h,f],x=y.computeStrides(o.shape),b=x[0],w=x[1],_=x[2],C=y.getTypedArrayFromDType(o.dtype,y.sizeFromShape(g));C.fill(l);let A=n.data.get(o.dataId).values,D=n.data.get(s.dataId).values;for(let R=0;R<c;++R){let M=s.shape[0]===1?D:D.subarray(R*8,R*8+8);for(let G=0;G<d;++G)for(let j=0;j<h;++j)for(let U=0;U<f;++U){let q,H=M[6]*j+M[7]*G+1;if(H===0)continue;let X=(M[0]*j+M[1]*G+M[2])/H,ne=(M[3]*j+M[4]*G+M[5])/H,Y=r$(X,m,i),re=r$(ne,p,i);switch(a){case"nearest":q=u7(A,p,m,b,w,_,R,re,Y,U,l);break;case"bilinear":q=c7(A,p,m,b,w,_,R,re,Y,U,l);break;default:throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${a}`)}let ee=R*b+G*w+j*_+U;C[ee]=q}return n.makeTensorInfo(g,o.dtype,C)}return{dataId:n.write(C,g,o.dtype),shape:o.shape,dtype:o.dtype}}var t$={kernelName:ba,backendName:"cpu",kernelFunc:o7};function r$(r,e,t){switch(t){case"reflect":return s7(r,e);case"wrap":return i7(r,e);case"nearest":return l7(r,e);case"constant":default:return a7(r,e)}}function s7(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 y.clamp(0,t,e-1)}function i7(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 y.clamp(0,t,e-1)}function a7(r,e){return r}function l7(r,e){return y.clamp(0,r,e-1)}function nd(r,e,t,n,o,s,a,i,l,u,c){let p=a*n+i*o+l*s+u;return 0<=i&&i<e&&0<=l&&l<t?r[p]:c}function u7(r,e,t,n,o,s,a,i,l,u,c){let p=Math.round(i),m=Math.round(l);return nd(r,e,t,n,o,s,a,p,m,u,c)}function c7(r,e,t,n,o,s,a,i,l,u,c){let p=Math.floor(i),m=Math.floor(l),f=p+1,d=m+1,h=(d-l)*nd(r,e,t,n,o,s,a,p,m,u,c)+(l-m)*nd(r,e,t,n,o,s,a,p,d,u,c),g=(d-l)*nd(r,e,t,n,o,s,a,f,m,u,c)+(l-m)*nd(r,e,t,n,o,s,a,f,d,u,c);return(f-i)*h+(i-p)*g}function p7(r){let{inputs:e,attrs:t,backend:n}=r,{axis:o}=t,{x:s}=e;te(s,"unique");let a=n.data.get(s.dataId).values,{outputValues:i,outputShape:l,indices:u}=Nx(a,o,s.shape,s.dtype);return[n.makeTensorInfo(l,s.dtype,i),n.makeTensorInfo([u.length],"int32",u)]}var n$={kernelName:kp,backendName:"cpu",kernelFunc:p7};function m7(r){let{inputs:e,backend:t,attrs:n}=r,{value:o}=e,{axis:s}=n;s<0&&(s+=o.shape.length);let a=o.shape.length,i=o.shape[s],l=new Array(a-1),u=0;for(let f=0;f<a;f++)f!==s&&(l[u++]=o.shape[f]);let c=new Array(a).fill(0),p=o.shape.slice();p[s]=1;let m=new Array(i);for(let f=0;f<m.length;f++){c[s]=f;let d=_o({inputs:{x:o},backend:t,attrs:{begin:c,size:p}});m[f]=Je({inputs:{x:d},backend:t,attrs:{shape:l}}),t.disposeIntermediateTensorInfo(d)}return m}var o$={kernelName:ui,backendName:"cpu",kernelFunc:m7};function f7(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,segmentIds:s}=e,{numSegments:a}=n;te(o,"unsortedSegmentSum");let i=o.shape.length,l=s.shape.length,u=[],c=[],p=i-l,m=s;for(let d=0;d<p;++d){let h=Yp({inputs:{input:m},backend:t,attrs:{dim:d+1}});m=h,c.push(h)}for(let d=0;d<a;++d){let h=y.createScalarValue(d,"int32"),g=t.makeTensorInfo([],"int32",h),x=bk({inputs:{a:g,b:m},backend:t}),b=yo({inputs:{x},backend:t,attrs:{dtype:"float32"}}),w=tc({inputs:{a:b,b:o},backend:t}),_=Ga({inputs:{x:w},backend:t,attrs:{axis:0,keepDims:!1}});u.push(_),c.push(g),c.push(x),c.push(b),c.push(w),c.push(_)}let f=Yk({inputs:u,backend:t,attrs:{axis:0}});return c.forEach(d=>t.disposeIntermediateTensorInfo(d)),f}var s$={kernelName:_l,backendName:"cpu",kernelFunc:f7};var d7=[MA,tA,LA,zA,iA,BA,VA,GA,WA,jA,UA,qA,HA,KA,XA,ZA,JA,QA,e2,PA,t2,r2,n2,sA,aA,o2,rA,s2,a2,u2,c2,l2,m2,f2,p2,d2,h2,g2,x2,y2,b2,w2,_2,k2,v2,C2,S2,I2,ed,T2,EA,E2,lA,A2,uA,D2,cA,$2,R2,F2,pA,O2,P2,M2,L2,z2,mA,fA,nA,B2,i2,V2,G2,W2,AA,dA,hA,j2,gA,U2,q2,H2,K2,X2,Y2,xA,J2,Q2,eD,tD,nD,Z2,oD,sD,yA,iD,aD,cD,bA,wA,pD,mD,fD,_A,dD,xD,yD,$x,bD,DA,vA,wD,oA,_D,$A,RA,OA,kD,vD,CD,ID,SD,ND,TD,CA,ED,AD,DD,FA,$D,RD,FD,IA,lD,PD,MD,LD,zD,BD,VD,GD,WD,jD,UD,SA,qD,HD,KD,XD,YD,TA,N2,ZD,JD,QD,e$,kA,t$,n$,o$,s$,hD];for(let r of d7)lu(r);var m$={};je(m$,{assertNotComplex:()=>Ps,bindCanvasToFramebuffer:()=>C7,bindColorTextureToFramebuffer:()=>id,bindTextureToProgramUniformSampler:()=>pv,bindTextureUnit:()=>u$,bindVertexBufferToProgramAttribute:()=>Fx,callAndCheck:()=>Ne,canBeRepresented:()=>Qk,createFragmentShader:()=>tv,createFramebuffer:()=>lv,createProgram:()=>rv,createStaticIndexBuffer:()=>sv,createStaticVertexBuffer:()=>ov,createTexture:()=>iv,createVertexShader:()=>ev,getBatchDim:()=>ja,getExtensionOrThrow:()=>Zp,getFramebufferErrorMessage:()=>c$,getMaxTexturesInShader:()=>dv,getNumChannels:()=>k7,getProgramUniformLocation:()=>cv,getProgramUniformLocationOrThrow:()=>uv,getRowsCols:()=>Ua,getShapeAs3D:()=>ad,getTextureShapeFromLogicalShape:()=>mv,getWebGLDisjointQueryTimerVersion:()=>hv,getWebGLErrorMessage:()=>l$,getWebGLMaxTextureSize:()=>fv,hasExtension:()=>Mn,isCapableOfRenderingToFloatTexture:()=>gv,isDownloadFloatTextureEnabled:()=>xv,isReshapeFree:()=>Fl,isWebGLFenceEnabled:()=>bv,isWebGLVersionEnabled:()=>zx,linkProgram:()=>nv,resetMaxTextureSize:()=>I7,resetMaxTexturesInShader:()=>S7,unbindColorTextureFromFramebuffer:()=>Ox,unbindTextureUnit:()=>v7,validateFramebuffer:()=>Jp,validateProgram:()=>sd,validateTextureSize:()=>av});var oc={},Zk={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Jk(r,e){oc[r]=e}function Xn(r){if(!(r in oc)){let t=g7(r);if(t!==null)oc[r]=t;else return console.log("Could not get context for WebGL version",r),null}let e=oc[r];return e.isContextLost()?(delete oc[r],Xn(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),oc[r])}function h7(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 g7(r){if(r!==1&&r!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let e=h7(r);return e.addEventListener("webglcontextlost",t=>{t.preventDefault(),delete oc[r]},!1),r===1?e.getContext("webgl",Zk)||e.getContext("experimental-webgl",Zk):e.getContext("webgl2",Zk)}var $l;(function(r){r[r.DENSE=0]="DENSE",r[r.SHARED_BATCH=1]="SHARED_BATCH"})($l||($l={}));var Vr;(function(r){r[r.RENDER=0]="RENDER",r[r.UPLOAD=1]="UPLOAD",r[r.PIXELS=2]="PIXELS",r[r.DOWNLOAD=3]="DOWNLOAD"})(Vr||(Vr={}));var Ar;(function(r){r[r.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",r[r.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",r[r.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",r[r.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",r[r.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"})(Ar||(Ar={}));function sc(r,e){return[e,r]}function i$(r,e){return r*e}function Rl(r){let e=y.sizeFromShape(r),t=Math.ceil(e/4);return y.sizeToSquarishShape(t)}function wi(r,e){return[Math.max(1,Math.ceil(e/2)),Math.max(1,Math.ceil(r/2))]}function a$(r,e){let[t,n]=wi(r,e);return t*n*4}function od(r,e){let t=r,n,o,s,a,i,l,u,c,p,m;return W().getNumber("WEBGL_VERSION")===2?(n=t.R32F,o=t.R16F,s=t.RGBA16F,a=t.RGBA32F,i=t.RED,u=4,c=1,p=t.HALF_FLOAT,m=t.FLOAT):(n=r.RGBA,o=r.RGBA,s=r.RGBA,a=t.RGBA,i=r.RGBA,u=4,c=4,p=e!=null?e.HALF_FLOAT_OES:null,m=r.FLOAT),l=r.RGBA,{internalFormatFloat:n,internalFormatHalfFloat:o,internalFormatPackedHalfFloat:s,internalFormatPackedFloat:a,textureFormatFloat:i,downloadTextureFormat:l,downloadUnpackNumChannels:u,defaultNumChannels:c,textureTypeHalfFloat:p,textureTypeFloat:m}}function Ne(r,e){let t=e();return W().getBool("DEBUG")&&x7(r),t}function x7(r){let e=r.getError();if(e!==r.NO_ERROR)throw new Error("WebGL Error: "+l$(r,e))}var y7=596e-10,b7=65504;function Qk(r){return!!(W().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||r===0||y7<Math.abs(r)&&Math.abs(r)<b7)}function l$(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 Zp(r,e){return Wa(r,()=>r.getExtension(e),'Extension "'+e+'" not supported on this browser.')}function ev(r,e){let t=Wa(r,()=>r.createShader(r.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(Ne(r,()=>r.shaderSource(t,e)),Ne(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 tv(r,e){let t=Wa(r,()=>r.createShader(r.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(Ne(r,()=>r.shaderSource(t,e)),Ne(r,()=>r.compileShader(t)),r.getShaderParameter(t,r.COMPILE_STATUS)===!1)throw _7(e,r.getShaderInfoLog(t)),new Error("Failed to compile fragment shader.");return t}var w7=/ERROR: [0-9]+:([0-9]+):/g;function _7(r,e){let t=w7.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,a=o.map((p,m)=>y.rightPad((m+1).toString(),s)+p),i=0;for(let p=0;p<a.length;p++)i=Math.max(a[p].length,i);let l=a.slice(0,n-1),u=a.slice(n-1,n),c=a.slice(n);console.log(l.join(`
|
|
`)),console.log(e.split(`
|
|
`)[0]),console.log(`%c ${y.rightPad(u[0],i)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(c.join(`
|
|
`))}function rv(r){return Wa(r,()=>r.createProgram(),"Unable to create WebGLProgram.")}function nv(r,e){if(Ne(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 sd(r,e){if(Ne(r,()=>r.validateProgram(e)),r.getProgramParameter(e,r.VALIDATE_STATUS)===!1)throw console.log(r.getProgramInfoLog(e)),new Error("Shader program validation failed.")}function ov(r,e){let t=Wa(r,()=>r.createBuffer(),"Unable to create WebGLBuffer");return Ne(r,()=>r.bindBuffer(r.ARRAY_BUFFER,t)),Ne(r,()=>r.bufferData(r.ARRAY_BUFFER,e,r.STATIC_DRAW)),t}function sv(r,e){let t=Wa(r,()=>r.createBuffer(),"Unable to create WebGLBuffer");return Ne(r,()=>r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,t)),Ne(r,()=>r.bufferData(r.ELEMENT_ARRAY_BUFFER,e,r.STATIC_DRAW)),t}function k7(){return W().getNumber("WEBGL_VERSION")===2?1:4}function iv(r){return Wa(r,()=>r.createTexture(),"Unable to create WebGLTexture.")}function av(r,e){let t=W().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 lv(r){return Wa(r,()=>r.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function Fx(r,e,t,n,o,s,a){let i=r.getAttribLocation(e,t);return i===-1?!1:(Ne(r,()=>r.bindBuffer(r.ARRAY_BUFFER,n)),Ne(r,()=>r.vertexAttribPointer(i,o,r.FLOAT,!1,s,a)),Ne(r,()=>r.enableVertexAttribArray(i)),!0)}function u$(r,e,t){p$(r,t),Ne(r,()=>r.activeTexture(r.TEXTURE0+t)),Ne(r,()=>r.bindTexture(r.TEXTURE_2D,e))}function v7(r,e){p$(r,e),Ne(r,()=>r.activeTexture(r.TEXTURE0+e)),Ne(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function uv(r,e,t){return Wa(r,()=>r.getUniformLocation(e,t),'uniform "'+t+'" not present in program.')}function cv(r,e,t){return r.getUniformLocation(e,t)}function pv(r,e,t,n){Ne(r,()=>u$(r,e,n)),Ne(r,()=>r.uniform1i(t,n))}function C7(r){Ne(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,null)),Ne(r,()=>r.viewport(0,0,r.canvas.width,r.canvas.height)),Ne(r,()=>r.scissor(0,0,r.canvas.width,r.canvas.height))}function id(r,e,t){Ne(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,t)),Ne(r,()=>r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0))}function Ox(r,e){Ne(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,e)),Ne(r,()=>r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,null,0))}function Jp(r){let e=r.checkFramebufferStatus(r.FRAMEBUFFER);if(e!==r.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+c$(r,e))}function c$(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 Wa(r,e,t){let n=Ne(r,()=>e());if(n==null)throw new Error(t);return n}function p$(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 ja(r,e=2){return y.sizeFromShape(r.slice(0,r.length-e))}function Ua(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 ad(r){let e=[1,1,1];return r.length===0||r.length===1&&r[0]===1||(e=[ja(r),...Ua(r)]),e}function mv(r,e=!1){let t=W().getNumber("WEBGL_MAX_TEXTURE_SIZE");e&&(t=t*2,r=r.map((o,s)=>s>=r.length-2?y.nearestLargerEven(r[s]):r[s]),r.length===1&&(r=[2,r[0]])),r.length!==2&&(r=y.squeezeShape(r).newShape);let n=y.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=ja(r),s=2,a=2;return r.length&&([s,a]=Ua(r)),n=o*(s/2)*(a/2),y.sizeToSquarishShape(n).map(i=>i*2)}return y.sizeToSquarishShape(n)}function Px(r){return r%2==0}function Fl(r,e){if(r=r.slice(-2),e=e.slice(-2),y.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||Px(t)&&Px(n)&&(r[0]===1||e[0]===1))return!0}return r[1]===e[1]&&Px(r[0])&&Px(e[0])}var Mx,Lx;function fv(r){if(Mx==null){let e=Xn(r);Mx=e.getParameter(e.MAX_TEXTURE_SIZE)}return Mx}function I7(){Mx=null}function S7(){Lx=null}function dv(r){if(Lx==null){let e=Xn(r);Lx=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Lx)}function hv(r){if(r===0)return 0;let e,t=Xn(r);return Mn(t,"EXT_disjoint_timer_query_webgl2")&&r===2?e=2:Mn(t,"EXT_disjoint_timer_query")?e=1:e=0,e}function Mn(r,e){return r.getExtension(e)!=null}function zx(r){try{if(Xn(r)!=null)return!0}catch(e){return console.log("Error when getting WebGL context: ",e),!1}return!1}function gv(r){if(r===0)return!1;let e=Xn(r);if(r===1){if(!Mn(e,"OES_texture_float"))return!1}else if(!Mn(e,"EXT_color_buffer_float"))return!1;return yv(e)}function xv(r){if(r===0)return!1;let e=Xn(r);if(r===1){if(!Mn(e,"OES_texture_float")||!Mn(e,"WEBGL_color_buffer_float"))return!1}else{if(Mn(e,"EXT_color_buffer_float"))return yv(e);let n="EXT_color_buffer_half_float";if(Mn(e,n)){let o=e.getExtension(n);return N7(e,o)}return!1}return yv(e)}function yv(r){let e=od(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 a=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),a}function N7(r,e){let t=od(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 a=r.createFramebuffer();r.bindFramebuffer(r.FRAMEBUFFER,a),r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,n,0);let i=r.checkFramebufferStatus(r.FRAMEBUFFER)===r.FRAMEBUFFER_COMPLETE;return r.bindTexture(r.TEXTURE_2D,null),r.bindFramebuffer(r.FRAMEBUFFER,null),r.deleteTexture(n),r.deleteFramebuffer(a),i}function bv(r){return r!==2?!1:Xn(r).fenceSync!=null}function Ps(r,e){Array.isArray(r)||(r=[r]),r.forEach(t=>{t!=null&&y.assert(t.dtype!=="complex64",()=>`${e} does not support complex64 tensors in the WebGL backend.`)})}var Pe=W();Pe.registerFlag("HAS_WEBGL",()=>Pe.getNumber("WEBGL_VERSION")>0);Pe.registerFlag("WEBGL_VERSION",()=>zx(2)?2:zx(1)?1:0);Pe.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);Pe.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>Pe.get("WEBGL_VERSION")===2);Pe.registerFlag("WEBGL_CPU_FORWARD",()=>!0);Pe.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);Pe.registerFlag("WEBGL_PACK",()=>Pe.getBool("HAS_WEBGL"));Pe.registerFlag("WEBGL_PACK_NORMALIZATION",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_PACK_CLIP",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_PACK_REDUCE",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_LAZILY_UNPACK",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_CONV_IM2COL",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>fv(Pe.getNumber("WEBGL_VERSION")));Pe.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>dv(Pe.getNumber("WEBGL_VERSION")));Pe.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let r=Pe.getNumber("WEBGL_VERSION");return r===0?0:hv(r)});Pe.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>Pe.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!gu.isMobile());Pe.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>gv(Pe.getNumber("WEBGL_VERSION")));Pe.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>Pe.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:Pe.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));Pe.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>xv(Pe.getNumber("WEBGL_VERSION")));Pe.registerFlag("WEBGL_FENCE_API_ENABLED",()=>bv(Pe.getNumber("WEBGL_VERSION")));Pe.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>Pe.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);Pe.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}.`)});Pe.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>gu.isMobile()&&Pe.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}.`)});Pe.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128);function Lt(){let r,e,t,n,o,s,a,i,l,u;return W().getNumber("WEBGL_VERSION")===2?(r="#version 300 es",e="in",t="out",n="in",o="texture",s="outputColor",a="out vec4 outputColor;",i=`
|
|
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",a="",i=`
|
|
#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:a,defineSpecialNaN:i,defineSpecialInf:l,defineRound:u}}function Ms(r,e,t="index"){let n=y.computeStrides(e);return n.map((o,s)=>{let a=`int ${r[s]} = ${t} / ${o}`,i=s===n.length-1?`int ${r[s+1]} = ${t} - ${r[s]} * ${o}`:`index -= ${r[s]} * ${o}`;return`${a}; ${i};`}).join("")}function Qp(r){let e=y.computeStrides(r).map(t=>t.toString());return`
|
|
int getFlatIndex(ivec3 coords) {
|
|
return coords.x * ${e[0]} + coords.y * ${e[1]} + coords.z;
|
|
}
|
|
`}var Bx=`
|
|
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 wv=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=$l.DENSE;let t=Rl(e),n=Lt();this.outputShape=e,this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${Ms(["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 _v=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=$l.DENSE;let t=Rl(e),n=Lt();this.outputShape=e,this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${Ms(["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 kv=class{constructor(e){this.variableNames=["A"],this.outTexUsage=Vr.DOWNLOAD;let t=Lt();this.outputShape=e,this.userCode=`
|
|
${Bx}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}};var vv=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Vr.DOWNLOAD;let t=Lt();this.outputShape=e,this.userCode=`
|
|
${Bx}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}};var Cv=class{constructor(e,t,n=!1){this.variableNames=["A"];let o=Lt(),[s,a]=t;this.outputShape=e;let i="result";n&&(i="floor(result * 255. + 0.5)"),this.userCode=`
|
|
${Qp(e)}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
|
|
int flatIndex = getFlatIndex(coords);
|
|
int offset = imod(flatIndex, 4);
|
|
|
|
flatIndex = idiv(flatIndex, 4, 1.);
|
|
|
|
int r = flatIndex / ${a};
|
|
int c = imod(flatIndex, ${a});
|
|
vec2 uv = (vec2(c, r) + halfCR) / vec2(${a}.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(${i}, 0., 0., 0.);
|
|
}
|
|
`}};var Iv=class{constructor(e,t,n=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let o=Lt(),[s,a]=t;this.outputShape=e;let i="",l="result";n&&(l="floor(result * 255. + 0.5)");for(let u=0;u<=1;u++)for(let c=0;c<=1;c++){let p=u*2+c;i+=`
|
|
localCoords = coords;
|
|
if(localCoords[2] + ${c} < ${e[2]}) {
|
|
localCoords[2] += ${c};
|
|
if(localCoords[1] + ${u} < ${e[1]}) {
|
|
localCoords[1] += ${u};
|
|
|
|
flatIndex = getFlatIndex(localCoords);
|
|
offset = imod(flatIndex, 4);
|
|
|
|
flatIndex = idiv(flatIndex, 4, 1.);
|
|
|
|
r = flatIndex / ${a};
|
|
c = imod(flatIndex, ${a});
|
|
uv = (vec2(c, r) + halfCR) / vec2(${a}.0, ${s}.0);
|
|
values = ${o.texture2D}(A, uv);
|
|
|
|
if(offset == 0) {
|
|
result[${p}] = values[0];
|
|
} else if(offset == 1) {
|
|
result[${p}] = values[1];
|
|
} else if(offset == 2) {
|
|
result[${p}] = values[2];
|
|
} else {
|
|
result[${p}] = values[3];
|
|
}
|
|
}
|
|
}
|
|
`}this.userCode=`
|
|
${Qp(e)}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
int flatIndex, r, c, offset;
|
|
ivec3 localCoords;
|
|
vec2 uv;
|
|
vec4 values;
|
|
|
|
${i}
|
|
|
|
${o.output} = ${l};
|
|
}
|
|
`}};var f$={};je(f$,{bindVertexProgramAttributeStreams:()=>Fv,createBufferFromOutputTexture:()=>Mv,createFloat16MatrixTexture:()=>Av,createFloat16PackedMatrixTexture:()=>Rv,createFloat32MatrixTexture:()=>Ev,createIndexBuffer:()=>Tv,createPackedMatrixTexture:()=>$v,createUnsignedBytesMatrixTexture:()=>Dv,createVertexBuffer:()=>Nv,createVertexShader:()=>Sv,downloadByteEncodedFloatMatrixFromOutputTexture:()=>zv,downloadFloat32MatrixFromBuffer:()=>Lv,downloadMatrixFromPackedOutputTexture:()=>Vv,downloadPackedMatrixFromBuffer:()=>Bv,getInternalFormatForFloat16MatrixTexture:()=>Gx,getInternalFormatForFloat16PackedMatrixTexture:()=>Ux,getInternalFormatForFloat32MatrixTexture:()=>Vx,getInternalFormatForPackedMatrixTexture:()=>jx,getInternalFormatForUnsignedBytesMatrixTexture:()=>Wx,uploadDenseMatrixToTexture:()=>Ov,uploadPixelDataToTexture:()=>Pv});function Sv(r){let e=Lt(),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 ev(r,t)}function Nv(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 ov(r,e)}function Tv(r){let e=new Uint16Array([0,1,2,2,1,3]);return sv(r,e)}function ld(r,e,t,n,o,s){av(e,t);let a=iv(r),i=r.TEXTURE_2D;return Ne(r,()=>r.bindTexture(i,a)),Ne(r,()=>r.texParameteri(i,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE)),Ne(r,()=>r.texParameteri(i,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE)),Ne(r,()=>r.texParameteri(i,r.TEXTURE_MIN_FILTER,r.NEAREST)),Ne(r,()=>r.texParameteri(i,r.TEXTURE_MAG_FILTER,r.NEAREST)),Ne(r,()=>r.texImage2D(i,0,n,e,t,0,o,s,null)),Ne(r,()=>r.bindTexture(r.TEXTURE_2D,null)),a}function Vx(r){return r.internalFormatFloat}function Ev(r,e,t,n){let[o,s]=sc(e,t);return ld(r,o,s,Vx(n),n.textureFormatFloat,r.FLOAT)}function Gx(r){return r.internalFormatHalfFloat}function Av(r,e,t,n){let[o,s]=sc(e,t);return ld(r,o,s,Gx(n),n.textureFormatFloat,n.textureTypeHalfFloat)}function Wx(r){return r.downloadTextureFormat}function Dv(r,e,t,n){let[o,s]=sc(e,t);return ld(r,o,s,Wx(n),r.RGBA,r.UNSIGNED_BYTE)}function jx(r){return r.internalFormatPackedFloat}function $v(r,e,t,n){let[o,s]=wi(e,t);return ld(r,o,s,jx(n),r.RGBA,r.FLOAT)}function Ux(r){return r.internalFormatPackedHalfFloat}function Rv(r,e,t,n){let[o,s]=wi(e,t);return ld(r,o,s,Ux(n),r.RGBA,n.textureTypeHalfFloat)}function Fv(r,e,t){let n=0,o=3*4,s=3*4+2*4;return Ne(r,()=>r.bindBuffer(r.ARRAY_BUFFER,t)),Fx(r,e,"clipSpacePos",t,3,s,n)&&Fx(r,e,"uv",t,2,s,o)}function Ov(r,e,t,n,o,s){Ne(r,()=>r.bindTexture(r.TEXTURE_2D,e));let a,i,l;o instanceof Uint8Array?(a=new Uint8Array(t*n*4),i=r.UNSIGNED_BYTE,l=r.RGBA):(a=new Float32Array(t*n*4),i=r.FLOAT,l=s.internalFormatPackedFloat),a.set(o),Ne(r,()=>r.texImage2D(r.TEXTURE_2D,0,l,t,n,0,r.RGBA,i,a)),Ne(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function Pv(r,e,t){Ne(r,()=>r.bindTexture(r.TEXTURE_2D,e)),t.data instanceof Uint8Array?Ne(r,()=>r.texImage2D(r.TEXTURE_2D,0,r.RGBA,t.width,t.height,0,r.RGBA,r.UNSIGNED_BYTE,t.data)):Ne(r,()=>r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,t)),Ne(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function Mv(r,e,t,n){let o=r.createBuffer();Ne(r,()=>r.bindBuffer(r.PIXEL_PACK_BUFFER,o));let i=4*4*e*t;return Ne(r,()=>r.bufferData(r.PIXEL_PACK_BUFFER,i,r.STREAM_READ)),Ne(r,()=>r.readPixels(0,0,t,e,r.RGBA,r.FLOAT,0)),Ne(r,()=>r.bindBuffer(r.PIXEL_PACK_BUFFER,null)),o}function Lv(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 zv(r,e,t,n){let[o,s]=sc(e,t),a=4,i=new Uint8Array(i$(e*t,a));return Ne(r,()=>r.readPixels(0,0,o,s,n.downloadTextureFormat,r.UNSIGNED_BYTE,i)),new Float32Array(i.buffer)}function Bv(r,e,t,n,o,s,a,i){let l=r,u=new Float32Array(a$(s,a));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 Vv(r,e,t){let n=new Float32Array(e*t*4);return Ne(r,()=>r.readPixels(0,0,t,e,r.RGBA,r.FLOAT,n)),n}var qx=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];let t=W().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,Jk(t,e)):this.gl=Xn(t);let n="WEBGL_color_buffer_float",o="EXT_color_buffer_half_float";if(W().getNumber("WEBGL_VERSION")===1){let s="OES_texture_float",a="OES_texture_half_float";if(this.textureFloatExtension=Zp(this.gl,s),Mn(this.gl,a))this.textureHalfFloatExtension=Zp(this.gl,a);else if(W().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),Mn(this.gl,o))this.colorBufferHalfFloatExtension=Zp(this.gl,o);else if(W().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",Mn(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else if(Mn(this.gl,o))this.colorBufferHalfFloatExtension=this.gl.getExtension(o);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=Nv(this.gl),this.indexBuffer=Tv(this.gl),this.framebuffer=lv(this.gl),this.textureConfig=od(this.gl,this.textureHalfFloatExtension)}get debug(){return W().getBool("DEBUG")}dispose(){if(this.disposed)return;this.program!=null&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),this.outputTexture!=null&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");let e=this.gl;Ne(e,()=>e.finish()),Ne(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),Ne(e,()=>e.deleteFramebuffer(this.framebuffer)),Ne(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),Ne(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),Ne(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),Ev(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),Av(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),Dv(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),Pv(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,o){this.throwIfDisposed(),Ov(this.gl,e,t,n,o,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),Rv(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),$v(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(Ox(this.gl,this.framebuffer),this.outputTexture=null),Ne(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,()=>zv(this.gl,t,n,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,n,o,s,a){return Bv(this.gl,e,t,n,o,s,a,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return Lv(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);let o=Mv(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(W().getBool("WEBGL_FENCE_API_ENABLED")){let o=e,s=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{let a=o.clientWaitSync(s,0,0);return a===o.ALREADY_SIGNALED||a===o.CONDITION_SATISFIED},t=s}else W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,()=>Vv(this.gl,t,n))}createProgram(e){this.throwIfDisposed();let t=this.gl,n=tv(t,e);this.vertexShader==null&&(this.vertexShader=Sv(t));let o=rv(t);return Ne(t,()=>t.attachShader(o,this.vertexShader)),Ne(t,()=>t.attachShader(o,n)),nv(t,o),this.debug&&sd(t,o),this.vertexAttrsAreBound||(this.setProgram(o),this.vertexAttrsAreBound=Fv(t,this.program,this.vertexBuffer)),o}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&Ne(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&sd(this.gl,this.program),Ne(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?uv(this.gl,e,t):cv(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),Ne(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(),pv(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();let[o,s]=wi(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&&sd(this.gl,this.program),Jp(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();let e=this.gl;this.debug&&this.debugValidate(),Ne(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),Ne(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=Zp(this.gl,W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){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(W().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 y.repeatedTry(()=>this.disposed||this.isQueryAvailable(e,W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(t===0)return null;if(t===2){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=T7(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)&&y.repeatedTry(()=>(this.pollItems(),this.itemsToPoll.length===0))}bindTextureToFrameBuffer(e){this.throwIfDisposed(),id(this.gl,e,this.framebuffer),this.debug&&Jp(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(id(this.gl,this.outputTexture,this.framebuffer),this.debug&&Jp(this.gl)):Ox(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;id(o,e,this.framebuffer),this.debug&&Jp(o),this.outputTexture=e,Ne(o,()=>o.viewport(0,0,t,n)),Ne(o,()=>o.scissor(0,0,t,n))}setOutputMatrixWriteRegionDriver(e,t,n,o){this.throwIfDisposed(),Ne(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 T7(r){let e=0;for(;e<r.length&&r[e]();++e);return e-1}var{getBroadcastDims:d$}=I;function h$(r,e,t,n){let o=[];r.forEach(d=>{let h=y.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(`
|
|
`),a=r.map(d=>E7(d,e,n)).join(`
|
|
`),i=e.texShape,l=Lt(),u=$7(l),c,p,m=O7(l);return e.isPacked?(c=A7(e.logicalShape,i),p=F7(l)):(c=D7(e.logicalShape,i),p=R7(l)),n&&(m+=z7),[m,u,p,s,c,a,t].join(`
|
|
`)}function em(r){let e=r.shapeInfo.logicalShape;switch(e.length){case 0:return Z7(r);case 1:return Q7(r);case 2:return tY(r);case 3:return nY(r);case 4:return sY(r);case 5:return iY(r);case 6:return aY(r);default:throw new Error(`${e.length}-D input sampling is not yet supported`)}}function g$(r){switch(r.shapeInfo.logicalShape.length){case 0:return Y7(r);case 1:return J7(r);case 2:return eY(r);case 3:return rY(r);default:return oY(r)}}function E7(r,e,t=!1){let n="";t?n+=g$(r):n+=em(r);let o=r.shapeInfo.logicalShape,s=e.logicalShape;return o.length<=s.length&&(t?n+=lY(r,e):n+=uY(r,e)),n}function A7(r,e){switch(r.length){case 0:return x$();case 1:return B7(r,e);case 2:return K7(r,e);case 3:return G7(r,e);default:return j7(r,e)}}function D7(r,e){switch(r.length){case 0:return x$();case 1:return V7(r,e);case 2:return X7(r,e);case 3:return W7(r,e);case 4:return U7(r,e);case 5:return q7(r,e);case 6:return H7(r,e);default:throw new Error(`${r.length}-D output sampling is not yet supported`)}}function $7(r){return`
|
|
float sampleTexture(sampler2D textureSampler, vec2 uv) {
|
|
return ${r.texture2D}(textureSampler, uv).r;
|
|
}
|
|
`}function R7(r){return`
|
|
void setOutput(float val) {
|
|
${r.output} = vec4(val, 0, 0, 0);
|
|
}
|
|
`}function F7(r){return`
|
|
void setOutput(vec4 val) {
|
|
${r.output} = val;
|
|
}
|
|
`}function O7(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);
|
|
}
|
|
|
|
${P7}
|
|
${M7}
|
|
${L7}
|
|
`}var P7=`
|
|
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);
|
|
}
|
|
`,M7=`
|
|
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);
|
|
}
|
|
`,L7=`
|
|
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);
|
|
}
|
|
`,z7=`
|
|
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 x$(){return`
|
|
int getOutputCoords() {
|
|
return 0;
|
|
}
|
|
`}function B7(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 V7(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 G7(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 W7(r,e){let t=Ms(["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 j7(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,a="",i="b, r, c";for(let l=2;l<r.length-1;l++)s*=r[r.length-l-1],a=`
|
|
int b${l} = index / ${s};
|
|
index -= b${l} * ${s};
|
|
`+a,i=`b${l}, `+i;return`
|
|
ivec${r.length} getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
|
|
${a}
|
|
|
|
int b = index / ${o};
|
|
index -= b * ${o};
|
|
|
|
int r = 2 * (index / ${n});
|
|
int c = imod(index, ${n}) * 2;
|
|
|
|
return ivec${r.length}(${i});
|
|
}
|
|
`}function U7(r,e){let t=Ms(["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 q7(r,e){let t=Ms(["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 H7(r,e){let t=Ms(["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 K7(r,e){let t=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];if(y.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 X7(r,e){return y.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 ic(r){return`offset${r}`}function Y7(r){let e=r.name,t="get"+e.charAt(0).toUpperCase()+e.slice(1),n=Lt();return`
|
|
vec4 ${t}() {
|
|
return ${n.texture2D}(${e}, halfCR);
|
|
}
|
|
`}function Z7(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,a]=r.shapeInfo.texShape,i=ic(e);return`
|
|
float ${t}() {
|
|
vec2 uv = uvFromFlat(${s}, ${a}, ${i});
|
|
return sampleTexture(${e}, uv);
|
|
}
|
|
`}function J7(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=Lt();return`
|
|
vec4 ${t}(int index) {
|
|
vec2 uv = packedUVfrom1D(
|
|
${o[0]}, ${o[1]}, index);
|
|
return ${s.texture2D}(${e}, uv);
|
|
}
|
|
`}function Q7(r){let e=r.name,t="get"+e.charAt(0).toUpperCase()+e.slice(1);if(r.shapeInfo.isUniform)return`
|
|
float ${t}(int index) {
|
|
${tm(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 a=ic(e);return s===1?`
|
|
float ${t}(int index) {
|
|
vec2 uv = vec2(0.5, (float(index + ${a}) + 0.5) / ${o}.0);
|
|
return sampleTexture(${e}, uv);
|
|
}
|
|
`:o===1?`
|
|
float ${t}(int index) {
|
|
vec2 uv = vec2((float(index + ${a}) + 0.5) / ${s}.0, 0.5);
|
|
return sampleTexture(${e}, uv);
|
|
}
|
|
`:`
|
|
float ${t}(int index) {
|
|
vec2 uv = uvFromFlat(${o}, ${s}, index + ${a});
|
|
return sampleTexture(${e}, uv);
|
|
}
|
|
`}function eY(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],a=o[1],i=Lt();if(o!=null&&y.arraysEqual(e,o))return`
|
|
vec4 ${n}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${a}.0, ${s}.0);
|
|
|
|
return ${i.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 ${i.texture2D}(${t}, uv);
|
|
}
|
|
`}function tY(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&&y.arraysEqual(e,o)){let p=o[0],m=o[1];return`
|
|
float ${n}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${m}.0, ${p}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}let{newShape:s,keptDims:a}=y.squeezeShape(e),i=s;if(i.length<e.length){let p=rm(r,i),m=["row","col"];return`
|
|
${em(p)}
|
|
float ${n}(int row, int col) {
|
|
return ${n}(${nm(m,a)});
|
|
}
|
|
`}if(r.shapeInfo.isUniform)return`
|
|
float ${n}(int row, int col) {
|
|
int index = round(dot(vec2(row, col), vec2(${e[1]}, 1)));
|
|
${tm(r)}
|
|
}
|
|
`;let l=o[0],u=o[1],c=ic(t);return u===1?`
|
|
float ${n}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${c}), 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, ${c}), 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 + ${c};
|
|
vec2 uv = uvFromFlat(${l}, ${u}, index);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function rY(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 p=e.slice(1),m=[1,2],f=rm(r,p),d=["b","row","col"];return`
|
|
${g$(f)}
|
|
vec4 ${n}(int b, int row, int col) {
|
|
return ${n}(${nm(d,m)});
|
|
}
|
|
`}let a=s[0],i=s[1],l=Math.ceil(e[2]/2),u=l*Math.ceil(e[1]/2),c=Lt();return`
|
|
vec4 ${n}(int b, int row, int col) {
|
|
vec2 uv = packedUVfrom3D(
|
|
${a}, ${i}, ${u}, ${l}, b, row, col);
|
|
return ${c.texture2D}(${t}, uv);
|
|
}
|
|
`}function nY(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:a,keptDims:i}=y.squeezeShape(e),l=a;if(l.length<e.length){let d=rm(r,l),h=["row","col","depth"];return`
|
|
${em(d)}
|
|
float ${n}(int row, int col, int depth) {
|
|
return ${n}(${nm(h,i)});
|
|
}
|
|
`}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)));
|
|
${tm(r)}
|
|
}
|
|
`;let u=r.shapeInfo.texShape,c=u[0],p=u[1],m=r.shapeInfo.flatOffset;if(p===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(${p}.0, ${c}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`;if(p===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(${p}.0, ${c}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`;let f=ic(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(${c}, ${p}, index);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function oY(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,a=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],i=a[0],l=a[1],u=Math.ceil(e[t-1]/2),c=u*Math.ceil(e[t-2]/2),p="int b, int row, int col",m=`b * ${c} + (row / 2) * ${u} + (col / 2)`;for(let d=2;d<t-1;d++)p=`int b${d}, `+p,c*=e[t-d-1],m=`b${d} * ${c} + `+m;let f=Lt();return`
|
|
vec4 ${o}(${p}) {
|
|
int index = ${m};
|
|
int texR = index / ${l};
|
|
int texC = index - texR * ${l};
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${l}, ${i});
|
|
return ${f.texture2D}(${n}, uv);
|
|
}
|
|
`}function sY(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,a=e[1]*s,{newShape:i,keptDims:l}=y.squeezeShape(e);if(i.length<e.length){let d=rm(r,i),h=["row","col","depth","depth2"];return`
|
|
${em(d)}
|
|
float ${n}(int row, int col, int depth, int depth2) {
|
|
return ${n}(${nm(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(${a}, ${s}, ${o}, 1)));
|
|
${tm(r)}
|
|
}
|
|
`;let u=r.shapeInfo.flatOffset,c=r.shapeInfo.texShape,p=c[0],m=c[1];if(m===a&&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, ${p}.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, ${p}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`;let f=ic(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 * ${a} + col * ${s} +
|
|
depth * ${o} + depth2;
|
|
vec2 uv = uvFromFlat(${p}, ${m}, index + ${f});
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function iY(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,a=e[2]*s,i=e[1]*a,{newShape:l,keptDims:u}=y.squeezeShape(e);if(l.length<e.length){let h=rm(r,l),g=["row","col","depth","depth2","depth3"];return`
|
|
${em(h)}
|
|
float ${n}(int row, int col, int depth, int depth2, int depth3) {
|
|
return ${n}(${nm(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(${i}, ${a}, ${s}, ${o})) +
|
|
depth3;
|
|
${tm(r)}
|
|
}
|
|
`;let c=r.shapeInfo.flatOffset,p=r.shapeInfo.texShape,m=p[0],f=p[1];if(f===i&&c==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(${a}, ${s}, ${o}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${f}.0, ${m}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`;if(f===o&&c==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=ic(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 * ${i} + col * ${a} + depth * ${s} +
|
|
depth2 * ${o} + depth3 + ${d};
|
|
vec2 uv = uvFromFlat(${m}, ${f}, index);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function aY(r){let e=r.shapeInfo.logicalShape,t=r.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),{newShape:o,keptDims:s}=y.squeezeShape(e);if(o.length<e.length){let g=rm(r,o),x=["row","col","depth","depth2","depth3","depth4"];return`
|
|
${em(g)}
|
|
float ${n}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
return ${n}(${nm(x,s)});
|
|
}
|
|
`}let a=e[5],i=e[4]*a,l=e[3]*i,u=e[2]*l,c=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(${c}, ${u}, ${l}, ${i})) +
|
|
dot(
|
|
vec2(depth3, depth4),
|
|
vec2(${a}, 1)));
|
|
${tm(r)}
|
|
}
|
|
`;let p=r.shapeInfo.flatOffset,m=r.shapeInfo.texShape,f=m[0],d=m[1];if(d===c&&p==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}, ${i}, ${a})) +
|
|
float(depth4);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${d}.0, ${f}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`;if(d===a&&p==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=ic(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 * ${c} + col * ${u} + depth * ${l} +
|
|
depth2 * ${i} + depth3 * ${a} + depth4 + ${h};
|
|
vec2 uv = uvFromFlat(${f}, ${d}, index);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function tm(r){let e=r.name,t=y.sizeFromShape(r.shapeInfo.logicalShape);return t<2?`return ${e};`:`
|
|
for (int i = 0; i < ${t}; i++) {
|
|
if (i == index) {
|
|
return ${e}[i];
|
|
}
|
|
}
|
|
`}function lY(r,e){let t=r.name,n=t.charAt(0).toUpperCase()+t.slice(1),o="get"+n+"AtOutCoords",s=r.shapeInfo.logicalShape.length,a=e.logicalShape.length,i=d$(r.shapeInfo.logicalShape,e.logicalShape),l=Ge(a),u=a-s,c,p=["x","y","z","w","u","v"];s===0?c="":a<2&&i.length>=1?c="coords = 0;":c=i.map(b=>`coords.${p[b+u]} = 0;`).join(`
|
|
`);let m="";a<2&&s>0?m="coords":m=r.shapeInfo.logicalShape.map((b,w)=>`coords.${p[w+u]}`).join(", ");let f="return outputValue;",h=y.sizeFromShape(r.shapeInfo.logicalShape)===1,x=y.sizeFromShape(e.logicalShape)===1;if(s===1&&!h&&!x)f=`
|
|
return vec4(outputValue.xy, outputValue.xy);
|
|
`;else if(h&&!x)a===1?f=`
|
|
return vec4(outputValue.x, outputValue.x, 0., 0.);
|
|
`:f=`
|
|
return vec4(outputValue.x);
|
|
`;else if(i.length){let b=s-2,w=s-1;i.indexOf(b)>-1&&i.indexOf(w)>-1?f="return vec4(outputValue.x);":i.indexOf(b)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":i.indexOf(w)>-1&&(f="return vec4(outputValue.xx, outputValue.zz);")}return`
|
|
vec4 ${o}() {
|
|
${l} coords = getOutputCoords();
|
|
${c}
|
|
vec4 outputValue = get${n}(${m});
|
|
${f}
|
|
}
|
|
`}function uY(r,e){let t=r.name,n=t.charAt(0).toUpperCase()+t.slice(1),o="get"+n+"AtOutCoords",s=e.texShape,a=r.shapeInfo.texShape,i=r.shapeInfo.logicalShape.length,l=e.logicalShape.length;if(!r.shapeInfo.isUniform&&i===l&&r.shapeInfo.flatOffset==null&&y.arraysEqual(a,s))return`
|
|
float ${o}() {
|
|
return sampleTexture(${t}, resultUV);
|
|
}
|
|
`;let u=Ge(l),c=d$(r.shapeInfo.logicalShape,e.logicalShape),p=l-i,m,f=["x","y","z","w","u","v"];i===0?m="":l<2&&c.length>=1?m="coords = 0;":m=c.map(h=>`coords.${f[h+p]} = 0;`).join(`
|
|
`);let d="";return l<2&&i>0?d="coords":d=r.shapeInfo.logicalShape.map((h,g)=>`coords.${f[g+p]}`).join(", "),`
|
|
float ${o}() {
|
|
${u} coords = getOutputCoords();
|
|
${m}
|
|
return get${n}(${d});
|
|
}
|
|
`}function Ge(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 rm(r,e){let t=JSON.parse(JSON.stringify(r));return t.shapeInfo.logicalShape=e,t}function nm(r,e){return e.map(t=>r[t]).join(", ")}function y$(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}}),a=s.map(f=>f.shapeInfo),i={logicalShape:n.shape,texShape:n.texData.texShape,isUniform:!1,isPacked:n.texData.isPacked,flatOffset:null},l=h$(s,i,o,e.packedInputs),u=r.createProgram(l),c=null,p=r.getUniformLocation(u,"NAN",!1);W().getNumber("WEBGL_VERSION")===1&&(c=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:a,outShapeInfo:i,infLoc:c,nanLoc:p}}function b$(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],a=s.shape;if(!y.arraysEqual(o,a))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${o} and ${a} must match`);if(t.isUniform&&s.isUniform)return;let i=t.texShape,l=s.isUniform?null:s.texData.texShape;if(!y.arraysEqual(i,l))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${l} must match`)})}function w$(r,e,t,n,o){b$(e.inShapeInfos,t),b$([e.outShapeInfo],[n]);let s=n.texData.texture,a=n.texData.texShape;n.texData.isPacked?r.setOutputPackedMatrixTexture(s,a[0],a[1]):r.setOutputMatrixTexture(s,a[0],a[1]),r.setProgram(e.webGLProgram),W().getNumber("WEBGL_VERSION")===1&&e.infLoc!==null&&r.gl.uniform1f(e.infLoc,Infinity),e.nanLoc!==null&&r.gl.uniform1f(e.nanLoc,NaN),t.forEach((i,l)=>{let u=e.program.variableNames[l],c=e.uniformLocations[u],p=e.uniformLocations[`offset${u}`];if(c!=null){if(i.isUniform){if(y.sizeFromShape(i.shape)<2)r.gl.uniform1f(c,i.uniformValues[0]);else{let m=i.uniformValues;m instanceof Float32Array||(m=new Float32Array(m)),r.gl.uniform1fv(c,m)}return}i.texData.slice!=null&&p!=null&&r.gl.uniform1i(p,i.texData.slice.flatOffset),r.setInputMatrixTexture(i.texData.texture,c,l)}}),o!=null&&o(r,e.webGLProgram),r.executeProgram()}function _$(r,e,t){let n="";e.concat(t).forEach(a=>{let i=a.texData!=null&&a.texData.slice!=null&&a.texData.slice.flatOffset>0,l=a.isUniform?"uniform":a.texData.texShape;n+=`${a.shape}_${l}_${i}`});let o=r.userCode,s=r.constructor.name;return s+="_"+n+"_"+o,s}var{addImpl:k$,bincountImpl:Hx,bincountReduceImpl:v$,ceilImpl:C$,concatImpl:I$,equalImpl:S$,expImpl:N$,expm1Impl:T$,floorImpl:E$,gatherNdImpl:A$,gatherV2Impl:D$,greaterImpl:$$,greaterEqualImpl:R$,lessImpl:F$,lessEqualImpl:O$,linSpaceImpl:P$,logImpl:M$,maxImpl:L$,maximumImpl:z$,minimumImpl:B$,multiplyImpl:V$,negImpl:G$,notEqualImpl:W$,prodImpl:j$,rangeImpl:U$,rsqrtImpl:q$,simpleAbsImpl:Kx,sliceImpl:H$,sparseFillEmptyRowsImpl:K$,sparseReshapeImpl:X$,sparseSegmentReductionImpl:Xx,stridedSliceImpl:Y$,stringNGramsImpl:Z$,stringSplitImpl:J$,stringToHashBucketFastImpl:Q$,subImpl:eR,tileImpl:tR,topKImpl:rR,transposeImpl:ac,uniqueImpl:nR}=Tx;function Gv(r,e){return["x","y","z","w","u","v"].slice(0,e).map(t=>`${r}.${t}`)}function Xt(r,e){return e===1?[r]:Gv(r,e)}function oR(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 Wv=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=Xt("rc",t),o=Ge(t),s=pY(t,e,n),a=mY(t,e[e.length-1],e[e.length-2],n),i=fY(e,n);this.userCode=`
|
|
void main() {
|
|
${o} rc = getOutputCoords();
|
|
|
|
if(${s}) {
|
|
setOutput(vec4(0));
|
|
} else {
|
|
${a}
|
|
|
|
setOutput(vec4(${i}));
|
|
}
|
|
}
|
|
`}}};function cY(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 a=2;a<r;a++)s=`${e[e.length-1-a]},`+s;t.push(s)}return t}function pY(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 mY(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 fY(r,e){let t=r.length,n=cY(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 ud=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=`
|
|
${dY(t)}
|
|
${Qp(e)}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
ivec3 thisRC;
|
|
int rows = ${e[1]};
|
|
int cols = ${e[2]};
|
|
|
|
${n}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};function dY(r){return`
|
|
ivec3 inputCoordsFromReshapedOutCoords(int index) {
|
|
${Ms(["r","c","d"],r)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}var jv=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=iR(t,n),s=aR(e,o,n);s in this.freeTextures||(this.freeTextures[s]=[]),s in this.usedTextures||(this.usedTextures[s]=[]);let a=sR(e,o,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[s].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=a,this.log();let l=this.freeTextures[s].shift();return this.usedTextures[s].push(l),l}let i;return o===Ar.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):o===Ar.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):o===Ar.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):o===Ar.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):o===Ar.PACKED_4X1_UNSIGNED_BYTE&&(i=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[s].push(i),this.numUsedTextures++,this._numBytesAllocated+=a,this.log(),i}releaseTexture(e,t,n,o){if(this.freeTextures==null)return;let s=iR(n,o),a=aR(t,s,o);a in this.freeTextures||(this.freeTextures[a]=[]);let i=sR(t,s,this.gpgpu.gl,this.gpgpu.textureConfig,o),l=W().get("WEBGL_DELETE_TEXTURE_THRESHOLD");l!==-1&&this._numBytesAllocated>l?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=i):(this.freeTextures[a].push(e),this.numFreeTextures++,this._numBytesFree+=i),this.numUsedTextures--;let u=this.usedTextures[a],c=u.indexOf(e);if(c<0)throw new Error("Cannot release a texture that was never provided by this texture manager");u.splice(c,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 hY(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 sR(r,e,t,n,o){let s=gY(e,n),a;if(o){let[l,u]=wi(r[0],r[1]);a=l*u}else{let[l,u]=sc(r[0],r[1]);a=l*u}let i=hY(t,s);return a*i}function gY(r,e){switch(r){case Ar.PACKED_2X2_FLOAT32:return jx(e);case Ar.PACKED_2X2_FLOAT16:return Ux(e);case Ar.UNPACKED_FLOAT32:return Vx(e);case Ar.UNPACKED_FLOAT16:return Gx(e);case Ar.PACKED_4X1_UNSIGNED_BYTE:return Wx(e);default:throw new Error(`Unknown physical texture type ${r}`)}}function xY(r){return W().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?r?Ar.PACKED_2X2_FLOAT32:Ar.UNPACKED_FLOAT32:r?Ar.PACKED_2X2_FLOAT16:Ar.UNPACKED_FLOAT16}function iR(r,e){if(r===Vr.UPLOAD)return Ar.PACKED_2X2_FLOAT32;if(r===Vr.RENDER||r==null)return xY(e);if(r===Vr.DOWNLOAD||r===Vr.PIXELS)return Ar.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${r}`)}function aR(r,e,t){return`${r[0]}_${r[1]}_${e}_${t}`}var vn=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);
|
|
}
|
|
`}},kr="if (isnan(x)) return x;",lR="return x;",Uv="return abs(x);";var uR="return (x >= 0.0) ? x : (exp(x) - 1.0);",cR=kr+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,pR=kr+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,cd="return x;",mR="return 1.0 / (1.0 + exp(-1.0 * x));";var fR="return x;",dR=`
|
|
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;
|
|
`,hR=`
|
|
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;
|
|
`,gR=`
|
|
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;
|
|
`,xR="return 1.0 / (1.0 + exp(-1.0 * x));",Ls=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 qv=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;let t=e.length,n=Xt("rc",t),o=Ge(t),s=oR(t,n),a=n.slice(-2),i=t<=1?"rc":`vec2(${a.join(",")})`;this.userCode=`
|
|
void main() {
|
|
${o} rc = getOutputCoords();
|
|
vec4 packedInput = getA(${s});
|
|
|
|
setOutput(getChannel(packedInput, ${i}));
|
|
}
|
|
`}};var yY=zr.whereImpl,bY=1e-7,wY=1e-4,Yx={};function _Y(r){return r in Yx||(Yx[r]={}),Yx[r]}var kY=W().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),vY=600;function CY(){return W().global.screen==null?1024:W().global.screen.height*W().global.screen.width*window.devicePixelRatio*vY/1024/1024}var lc=class extends Xs{constructor(e){super();if(this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!W().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){let t=Xn(W().getNumber("WEBGL_VERSION"));this.binaryCache=_Y(W().getNumber("WEBGL_VERSION")),this.gpgpu=new qx(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 jv(this.gpgpu),this.numMBBeforeWarning=CY(),this.texData=new al(this,Ns())}nextDataId(){return lc.nextDataId++}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}write(e,t,n){if((W().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||W().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:Vr.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(W().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:Vr.UPLOAD,refCount:s})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){let t=this.texData.get(e),{values:n,dtype:o,complexTensorInfos:s,slice:a,shape:i,isPacked:l}=t;if(a!=null){let m;l?m=new Ls(i,cd):m=new vn(i,cd);let f=this.runWebGLProgram(m,[{dataId:e,shape:i,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,c;u&&(c=y.now());let p;if(o==="complex64"){let m=this.readSync(s.real.dataId),f=this.readSync(s.imag.dataId);p=I.mergeRealAndImagArrays(m,f)}else p=this.getValuesFromTexture(e);return u&&(this.downloadWaitMs+=y.now()-c),this.convertAndCacheOnCPU(e,p)}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:a,complexTensorInfos:i,isPacked:l}=t;if(s!=null){let d;l?d=new Ls(o,cd):d=new vn(o,cd);let h=this.runWebGLProgram(d,[{dataId:e,shape:o,dtype:a}],a),g=this.read(h.dataId);return this.disposeIntermediateTensorInfo(h),g}if(n!=null)return this.convertAndCacheOnCPU(e);if(!W().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&W().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let u=null,c;if(a!=="complex64"&&W().get("WEBGL_BUFFER_SUPPORTED")){c=this.decode(e);let d=this.texData.get(c.dataId);u=this.gpgpu.createBufferFromTexture(d.texture,...Rl(o))}this.pendingRead.set(e,[]),a!=="complex64"&&await this.gpgpu.createAndWaitForFence();let p;if(a==="complex64"){let d=await Promise.all([this.read(i.real.dataId),this.read(i.imag.dataId)]),h=d[0],g=d[1];p=I.mergeRealAndImagArrays(h,g)}else if(u==null)p=this.getValuesFromTexture(e);else{let d=y.sizeFromShape(o);p=this.gpgpu.downloadFloat32MatrixFromBuffer(u,d)}c!=null&&this.disposeIntermediateTensorInfo(c);let m=this.convertAndCacheOnCPU(e,p),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)&&Ns().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=>y.decodeString(o))}catch(o){throw new Error("Failed to decode encoded string bytes into utf-8")}return Ie(e.shape,e.dtype,n)}checkNumericalProblems(e){if(e!=null)for(let t=0;t<e.length;t++){let n=e[t];if(!Qk(n))throw W().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=y.sizeFromShape(t);if(W().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){let m=this.decode(e),f=this.texData.get(m.dataId),d=this.gpgpu.downloadMatrixFromPackedTexture(f.texture,...Rl(t)).subarray(0,s);return this.disposeIntermediateTensorInfo(m),d}let a=W().getBool("WEBGL_PACK")&&o===!0,i=a?ad(t):t,l=a?new vv(i):new kv(i),u=this.runWebGLProgram(l,[{shape:i,dtype:n,dataId:e}],"float32"),c=this.texData.get(u.dataId),p=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(c.texture,c.texShape[0],c.texShape[1]).subarray(0,s);return this.disposeIntermediateTensorInfo(u),p}timerAvailable(){return W().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=y.flatten(this.activeTimers.map(l=>l.query)).filter(l=>l!=null),a=y.flatten(this.activeTimers.map(l=>l.name)).filter(l=>l!=null);this.activeTimers=t,o&&(this.programTimersStack=null);let i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};if(W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){let l=await Promise.all(s);i.kernelMs=y.sum(l),i.getExtraProfileInfo=()=>l.map((u,c)=>({name:a[c],ms:u})).map(u=>`${u.name}: ${u.ms}`).join(", ")}else i.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,i}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:y.now(),endMs:null}}endTimer(e){return W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=y.now(),e)}async getQueryTime(e){if(W().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:a,slice:i}=this.texData.get(e),l=i&&i.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,a)));let c=this.texData.get(e);c.texture=null,c.texShape=null,c.isPacked=!1,c.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=kY){return W().getBool("WEBGL_CPU_FORWARD")&&e.every(n=>this.texData.get(n.dataId).texture==null&&y.sizeFromShape(n.shape)<t)}getGPGPUContext(){return this.gpgpu}where(e){I.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");let t=e.dataSync();return yY(e.shape,t)}packedUnaryOp(e,t,n){let o=new Ls(e.shape,t),s=this.compileAndRun(o,[e],n);return Ns().makeTensorFromDataId(s.dataId,s.shape,s.dtype)}abs(e){if(this.shouldExecuteOnCPU([e])&&e.dtype!=="complex64"){let o=Kx(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,o)}if(W().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Uv,e.dtype);let t=new vn(e.shape,Uv),n=this.compileAndRun(t,[e]);return Ns().makeTensorFromDataId(n.dataId,n.shape,n.dtype)}makeTensorInfo(e,t,n){let o;if(t==="string"&&n!=null&&n.length>0&&y.isString(n[0])){let s=n.map(a=>y.encodeString(a));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 Ns().makeTensorFromDataId(o,e,t,this)}unpackTensor(e){let t=new qv(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){let t=new Wv(e.shape),n=!0;return this.runWebGLProgram(t,[e],e.dtype,null,n)}packedReshape(e,t){let n=[ja(e.shape),...Ua(e.shape)],o={dtype:e.dtype,shape:n,dataId:e.dataId},s=[ja(t),...Ua(t)],a=new ud(s,n),i=!0,l=this.runWebGLProgram(a,[o],e.dtype,null,i);return{dataId:l.dataId,shape:t,dtype:l.dtype}}decode(e){let t=this.texData.get(e),{isPacked:n,shape:o,dtype:s}=t,a=ad(o),i;n?i=new _v(a):i=new wv(a);let l=!0,u=this.runWebGLProgram(i,[{shape:a,dtype:s,dataId:e}],s,null,l);return{dtype:s,shape:o,dataId:u.dataId}}runWebGLProgram(e,t,n,o,s=!1){let a=this.makeTensorInfo(e.outputShape,n),i=this.texData.get(a.dataId);if(e.packedOutput&&(i.isPacked=!0),e.outPackingScheme===$l.DENSE){let g=Rl(e.outputShape);i.texShape=g.map(x=>x*2)}if(e.outTexUsage!=null&&(i.usage=e.outTexUsage),y.sizeFromShape(a.shape)===0)return i.values=y.getTypedArrayFromDType(a.dtype,0),a;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 x=this.texData.get(g.dataId);if(x.texture==null){if(!e.packedInputs&&y.sizeFromShape(g.shape)<=W().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:g.shape,texData:null,isUniform:!0,uniformValues:x.values};e.packedInputs&&(x.isPacked=!0,x.shape=g.shape)}else if(!!x.isPacked!=!!e.packedInputs)g=x.isPacked?this.unpackTensor(g):this.packTensor(g),l.push(g),x=this.texData.get(g.dataId);else if(x.isPacked&&!Fl(x.shape,g.shape)){let b=g,w=g.shape;g.shape=x.shape,g=this.packedReshape(g,w),l.push(g),x=this.texData.get(g.dataId),b.shape=w}return this.uploadToGPU(g.dataId),{shape:g.shape,texData:x,isUniform:!1}});this.uploadToGPU(a.dataId);let c={shape:a.shape,texData:i,isUniform:!1},p=_$(e,u,c),m=this.getAndSaveBinary(p,()=>y$(this.gpgpu,e,u,c)),f=this.activeTimers!=null,d;f&&(d=this.startTimer()),w$(this.gpgpu,m,u,c,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=W().get("WEBGL_FLUSH_THRESHOLD");if(h>0){let g=y.now();g-this.lastGlFlushTime>h&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=g)}if(!W().getBool("WEBGL_LAZILY_UNPACK")&&i.isPacked&&s===!1){let g=this.unpackTensor(a);return this.disposeIntermediateTensorInfo(a),g}return a}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||(W().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=B(()=>{if(!W().get("WEBGL_RENDER_FLOAT32_ENABLED")){let e=W().getBool("DEBUG");W().set("DEBUG",!1);let t=this.abs(pe(1e-8)).dataSync()[0];if(W().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?bY:wY}uploadToGPU(e){let t=this.texData.get(e),{shape:n,dtype:o,values:s,texture:a,usage:i,isPacked:l}=t;if(a!=null)return;let u=this.activeTimers!=null,c;u&&(c=y.now());let p=t.texShape;if(p==null&&(p=mv(n,l),t.texShape=p),s!=null){let m=ad(n),f,d=p[1],h=p[0],g=s instanceof Uint8Array;l?([d,h]=wi(p[0],p[1]),f=new Iv(m,[h,d],g)):f=new Cv(m,[h,d],g);let x=this.makeTensorInfo([h,d],o);g?this.texData.get(x.dataId).usage=Vr.PIXELS:this.texData.get(x.dataId).usage=Vr.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(x.dataId),d,h,s);let b=!0,w=this.runWebGLProgram(f,[x],o,null,b),_=this.texData.get(w.dataId);t.texture=_.texture,t.texShape=_.texShape,t.isPacked=_.isPacked,t.usage=_.usage,this.disposeIntermediateTensorInfo(x),this.texData.delete(w.dataId),t.values=null,u&&(this.uploadWaitMs+=y.now()-c)}else{let m=this.acquireTexture(p,i,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=IY(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]*y.bytesPerElement(t)}};lc.nextDataId=0;function IY(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 Hv="3.7.0";function yR(){W().set("WEBGL_FORCE_F16_TEXTURES",!0)}gu.isBrowser()&&Rp("webgl",()=>new lc,2);var bJe={forceHalfFloat:yR};var Zx=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`;var ko=class{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=I.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 Ol=`
|
|
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 zs=class{constructor(e,t,n,o=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=I.assertAndGetBroadcastShape(t,n);let s=this.outputShape.length,a="";if(o)if(s===0||y.sizeFromShape(this.outputShape)===1)a=`
|
|
result.y = 0.;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else if(a=`
|
|
${Ge(s)} coords = getOutputCoords();
|
|
`,s===1)a+=`
|
|
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else{let l=Xt("coords",s);a+=`
|
|
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);
|
|
${a}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};function Yt(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 bR={kernelName:no,backendName:"webgl",kernelFunc:Yt};function Cn(r){let{inputs:e,backend:t}=r,{real:n,imag:o}=e,s=t.makeTensorInfo(n.shape,"complex64"),a=t.texData.get(s.dataId),i=Yt({inputs:{x:n},backend:t}),l=Yt({inputs:{x:o},backend:t});return a.complexTensorInfos={real:i,imag:l},s}var wR={kernelName:qc,backendName:"webgl",kernelFunc:Cn};var Kv="return (a < 0.) ? b * a : a;",Xv=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function SY(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{alpha:s}=n,a=t.makeTensorInfo([],"float32",y.createScalarValue(s,"float32")),i=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new zs(Xv,o.shape,a.shape):new ko(Kv,o.shape,a.shape),l=t.runWebGLProgram(i,[o,a],o.dtype);return t.disposeIntermediateTensorInfo(a),l}var _R={kernelName:Ko,backendName:"webgl",kernelFunc:SY};var Yv="return (a < 0.) ? b * a : a;",Zv=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function NY(r){let{inputs:e,backend:t}=r,{x:n,alpha:o}=e,s=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new zs(Zv,n.shape,o.shape):new ko(Yv,n.shape,o.shape);return t.runWebGLProgram(s,[n,o],n.dtype)}var kR={kernelName:as,backendName:"webgl",kernelFunc:NY};var Jx="if (isnan(x)) return x;",vR=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,CR=`
|
|
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 ke({opSnippet:r,packedOpSnippet:e,cpuKernelImpl:t,dtype:n}){return({inputs:o,backend:s})=>{let{x:a}=o,i=s,l=n||a.dtype;if(i.shouldExecuteOnCPU([a])&&t!=null){let p=i.texData.get(a.dataId),m=t(p.values,l);return i.makeTensorInfo(a.shape,l,m)}let u=W().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&e!=null,c;return u?c=new Ls(a.shape,e):c=new vn(a.shape,r),i.runWebGLProgram(c,[a],l)}}function it({opSnippet:r,packedOpSnippet:e,checkOutOfBounds:t=!1,supportsComplex:n=!1,cpuKernelImpl:o,dtype:s}){return({inputs:a,backend:i})=>{let{a:l,b:u}=a,c=i;if(n&&l.dtype==="complex64"){let d=c.texData.get(l.dataId),h=c.texData.get(u.dataId),[g,x]=[[d.complexTensorInfos.real,h.complexTensorInfos.real],[d.complexTensorInfos.imag,h.complexTensorInfos.imag]].map(w=>{let[_,C]=w,A={dataId:_.dataId,dtype:_.dtype,shape:l.shape},D={dataId:C.dataId,dtype:C.dtype,shape:u.shape},$=new ko(r,l.shape,u.shape);return c.runWebGLProgram($,[A,D],mr(_.dtype,C.dtype))}),b=Cn({inputs:{real:g,imag:x},backend:c});return c.disposeIntermediateTensorInfo(g),c.disposeIntermediateTensorInfo(x),b}let p=s||mr(l.dtype,u.dtype);if((l.dtype==="string"||u.dtype==="string"||c.shouldExecuteOnCPU([l,u]))&&o!=null){let d=c.texData.get(l.dataId).values,h=c.texData.get(u.dataId).values,g=l.dtype==="string"?I.fromUint8ToStringArray(d):d,x=l.dtype==="string"?I.fromUint8ToStringArray(h):h,[b,w]=o(l.shape,u.shape,g,x,p),_=c.makeTensorInfo(w,p),C=c.texData.get(_.dataId);return C.values=b,_}let m=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&e!=null,f;return m?f=new zs(e,l.shape,u.shape,t):f=new ko(r,l.shape,u.shape),c.runWebGLProgram(f,[l,u],p)}}function Pl(r,e=!1){if(r==="linear")return e?fR:lR;if(r==="relu")return e?hR:cR;if(r==="elu")return e?dR:uR;if(r==="relu6")return e?gR:pR;if(r==="prelu")return e?Zv:Yv;if(r==="leakyrelu")return e?Xv:Kv;if(r==="sigmoid")return e?xR:mR;throw new Error(`Activation ${r} has not been implemented for the WebGL backend.`)}var pd=class{constructor(e,t,n,o=!1,s=!1,a=!1,i=null,l=!1,u=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n;let c=o?e[1]:e[2],p=Math.ceil(c/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="",x="";i&&(l?g=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${i}
|
|
}`:u?g=`vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${i}
|
|
}`:g=`vec4 activation(vec4 x) {
|
|
${i}
|
|
}`,x="result = activation(result);");let b=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),l&&this.variableNames.push("preluActivationWeights"),u&&this.variableNames.push("leakyreluAlpha");let w="rc.x",_="rc.x";e[0]<t[0]?w=`int(min(float(rc.x), ${e[0]-1}.))`:t[0]<e[0]&&(_=`int(min(float(rc.x), ${t[0]-1}.))`),this.userCode=`
|
|
${g}
|
|
|
|
const float sharedDimension = ${p}.0;
|
|
|
|
vec4 dot2x2ARowBCol(ivec3 rc) {
|
|
vec4 result = vec4(0);
|
|
for (int i = 0; i < ${p}; i++) {
|
|
int batchA = ${w};
|
|
int batchB = ${_};
|
|
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);
|
|
|
|
${b}
|
|
|
|
${x}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};var Jv={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},Qx=class{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=I.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 IR="return a * b;";function md(r){let{inputs:e,backend:t}=r,{a:n,b:o}=e,s=I.upcastType(n.dtype,o.dtype);if(n.dtype==="complex64"){let i=t.texData.get(n.dataId),l=t.texData.get(o.dataId),u=new Qx(Jv.REAL,n.shape,o.shape),c=new Qx(Jv.IMAG,n.shape,o.shape),p=[{dataId:i.complexTensorInfos.real.dataId,dtype:i.complexTensorInfos.real.dtype,shape:n.shape},{dataId:i.complexTensorInfos.imag.dataId,dtype:i.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,p,"float32"),f=t.runWebGLProgram(c,p,"float32"),d=Cn({inputs:{real:m,imag:f},backend:t});return t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f),d}if(t.shouldExecuteOnCPU([n,o])){let i=t.texData.get(n.dataId),l=t.texData.get(o.dataId),[u,c]=V$(n.shape,o.shape,i.values,l.values,s),p=t.makeTensorInfo(c,s),m=t.texData.get(p.dataId);return m.values=u,p}let a;return W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?a=new zs(IR,n.shape,o.shape):a=new ko(IR,n.shape,o.shape),t.runWebGLProgram(a,[n,o],s)}var SR={kernelName:ns,backendName:"webgl",kernelFunc:md};function NR(r,e,t){let n=[ja(r.shape),...Ua(r.shape)],o={dtype:r.dtype,shape:n,dataId:r.dataId},s=[ja(e),...Ua(e)],a=new ud(s,n),i=!0,l=t.runWebGLProgram(a,[o],r.dtype,null,i);return{dataId:l.dataId,shape:e,dtype:l.dtype}}function le(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{shape:s}=n,a=t,i=y.sizeFromShape(o.shape),l=y.inferFromImplicitShape(s,i),u=y.sizeFromShape(l);y.assert(i===u,()=>`The new shape (${l}) has ${u} elements and the old shape (${o.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`);let c=a.texData.get(o.dataId);return c.isPacked&&!Fl(o.shape,l)&&!(c.texture!==null&&Fl(c.shape,l))?NR(o,l,a):(a.incRef(o.dataId),{dataId:o.dataId,shape:l,dtype:o.dtype})}var TR={kernelName:si,backendName:"webgl",kernelFunc:le};var ey=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:o,inSize:s,outSize:a}=e;this.outputShape=[o,a];let i=Math.floor(n/4)*4,l=n%4,u="sumValue += dot(values, ones);";if(t!=null){let p=1/t;u=`sumValue += dot(values * ${y.isInt(p)?p.toPrecision(2):p}, ones);`}let c="";s%n>0&&(c=`
|
|
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) {
|
|
${c}
|
|
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 < ${i}; 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 + ${i};
|
|
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 Qv=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:o,inSize:s,outSize:a}=e;this.outputShape=[o,a];let i="0.0",l="";t==="prod"?i="1.0":t==="min"?(i="1.0 / 1e-20",l="min"):t==="max"&&(i="-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 c=Math.floor(n/4)*4,p=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"?(i="1.0",m=`
|
|
bool reducedAllValue = all(values);
|
|
float floatedReducedAllValue = float(reducedAllValue);
|
|
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
|
|
`,f="bvec4"):t==="any"&&(i="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 = ${i};
|
|
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(${i});
|
|
float prodValue = 1.0;
|
|
float sumValue = 0.0;
|
|
float allValue = 1.0;
|
|
float anyValue = 0.0;
|
|
|
|
for (int i = 0; i < ${c}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
${f} values = ${f}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
${m}
|
|
}
|
|
|
|
int inIdx = inOffset + ${c};
|
|
if (${p===1}) {
|
|
${f} values = ${f}(
|
|
getValue(batch, inIdx),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${m}
|
|
} else if (${p===2}) {
|
|
${f} values = ${f}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${m}
|
|
} else if (${p===3}) {
|
|
${f} values = ${f}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
initializationValue
|
|
);
|
|
|
|
${m}
|
|
}
|
|
setOutput(${u});
|
|
}
|
|
`}};function TY(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=I.computeOptimalWindowSize(t);e.push({inSize:t,windowSize:n,outSize:Math.ceil(t/n)})}return e}function Ln(r,e,t,n){let o=TY(r.shape),s=r;for(let a=0;a<o.length;a++){let{inSize:i,windowSize:l,outSize:u}=o[a],c,p;t==="mean"?c=a===0?new ey({windowSize:l,inSize:i,batchSize:r.shape[0],outSize:u},i):new ey({windowSize:l,inSize:i,batchSize:r.shape[0],outSize:u}):c=new Qv({windowSize:l,inSize:i,batchSize:r.shape[0],outSize:u},t),p=s,s=n.runWebGLProgram(c,[s],e),p.dataId!==r.dataId&&n.disposeIntermediateTensorInfo(p)}return s}var e0=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let a=0;a<n.length;a++)n[a]=e[t[a]];this.outputShape=n,this.rank=n.length;let o=Ge(this.rank),s=EY(t);this.userCode=`
|
|
void main() {
|
|
${o} resRC = getOutputCoords();
|
|
setOutput(getA(${s}));
|
|
}
|
|
`}};function EY(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 t0=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let n=new Array(e.length);for(let c=0;c<n.length;c++)n[c]=e[t[c]];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=Ge(this.rank),s=Gv("rc",this.rank),a=new Array(this.rank);for(let c=0;c<t.length;c++)a[t[c]]=s[c];let i=`vec2(${a.slice(-2).join()})`,l=`++${s[this.rank-1]} < ${n[this.rank-1]}`,u=`getChannel(getA(${a.join()}), ${i})`;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 Ml(r,e,t){let n=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new t0(r.shape,e):new e0(r.shape,e);return t.runWebGLProgram(n,[r],r.dtype)}function ER(r,e,t,n){let o=e,s=r.shape.length,a=y.parseAxisParam(o,r.shape),i=a,l=I.getAxesPermutation(i,s),u=l!=null,c=r;u&&(c=Ml(r,l,n),i=I.getInnerMostAxes(i.length,s)),I.assertAxesAreInnerMostDims("sum",i,s);let[p,m]=I.computeOutAndReduceShapes(c.shape,i),f=p;t&&(f=I.expandShapeToKeepDim(p,a));let d=y.sizeFromShape(m),g=y.sizeFromShape(r.shape)/d,x=le({inputs:{x:c},attrs:{shape:[g,d]},backend:n}),b=du(r.dtype),w=Ln(x,b,"sum",n),_=le({inputs:{x:w},attrs:{shape:f},backend:n});return n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(w),u&&n.disposeIntermediateTensorInfo(c),_}function uc(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,keepDims:a}=n;return ER(o,s,a,t)}var AR={kernelName:xs,backendName:"webgl",kernelFunc:uc};function Ft(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{perm:s}=n,a=t,i=o.shape.length,l=new Array(i);for(let c=0;c<l.length;c++)l[c]=o.shape[s[c]];let u;if(a.shouldExecuteOnCPU([o])){let p=a.texData.get(o.dataId).values,m=ac(p,o.shape,o.dtype,s,l);u=a.makeTensorInfo(l,o.dtype);let f=a.texData.get(u.dataId);f.values=m}else u=Ml(o,s,a);return u}var DR={kernelName:vs,backendName:"webgl",kernelFunc:Ft};var r0=1e3;function cc({a:r,b:e,transposeA:t,transposeB:n,backend:o,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:i=0,activation:l=null}){let u=r.shape.length,c=e.shape.length,p=t?r.shape[u-2]:r.shape[u-1],m=n?e.shape[c-1]:e.shape[c-2],f=t?r.shape[u-1]:r.shape[u-2],d=n?e.shape[c-2]:e.shape[c-1],h=r.shape.slice(0,-2),g=e.shape.slice(0,-2),x=y.sizeFromShape(h),b=y.sizeFromShape(g),w=x===b||x===1||b===1;y.assert(u>=2&&c>=2&&w,()=>`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 C=(x>b?r.shape.slice(0,-2):e.shape.slice(0,-2)).concat([f,d]);y.assert(p===m,()=>`Error in matMul: inner shapes (${p}) and (${m}) of Tensors with shapes ${r.shape} and ${e.shape} and transposeA=${t} and transposeB=${n} must match.`);let A=t?[x,p,f]:[x,f,p],D=n?[b,d,m]:[b,m,d],$=le({inputs:{x:r},backend:o,attrs:{shape:A}}),R=le({inputs:{x:e},backend:o,attrs:{shape:D}}),M=[$,R],G=Math.max(x,b),j=t?$.shape[1]:$.shape[2],U=s!=null,q=a!=null,H=l==="leakyrelu",X=l!=null?Pl(l,!0):null,ne=U||q||H||X!=null,Y;if((f===1||d===1)&&j>r0&&ne===!1){let ee=$,ie=R;t&&(ee=Ft({inputs:{x:$},backend:o,attrs:{perm:[0,2,1]}}),M.push(ee)),n&&(ie=Ft({inputs:{x:R},backend:o,attrs:{perm:[0,2,1]}}),M.push(ie));let me=d!==1,ae=d===1,fe=ee;me&&(fe=le({inputs:{x:ee},backend:o,attrs:{shape:[G,j,1]}}),M.push(fe));let he=d===1?2:1,xe=ie;ae&&(xe=le({inputs:{x:ie},backend:o,attrs:{shape:[G,1,j]}}),M.push(xe));let _e=md({inputs:{a:fe,b:xe},backend:o});Y=uc({inputs:{x:_e},backend:o,attrs:{axis:he,keepDims:!0}}),M.push(_e)}else{let ee=mr(r.dtype,e.dtype),ie=new pd(A,D,[G,f,d],t,n,U,X,q,H),me=[$,R];if(s!=null&&me.push(s),q&&me.push(a),H){let ae=o.makeTensorInfo([],"float32",y.createScalarValue(i,"float32"));me.push(ae),M.push(ae)}Y=o.runWebGLProgram(ie,me,ee)}let re=le({inputs:{x:Y},backend:o,attrs:{shape:C}});M.push(Y);for(let ee of M)o.disposeIntermediateTensorInfo(ee);return re}function AY(r){let{inputs:e,backend:t,attrs:n}=r,{a:o,b:s,bias:a,preluActivationWeights:i}=e,{transposeA:l,transposeB:u,activation:c,leakyreluAlpha:p}=n;return cc({a:o,b:s,transposeA:l,transposeB:u,backend:t,bias:a,preluActivationWeights:i,leakyreluAlpha:p,activation:c})}var $R={kernelName:pi,backendName:"webgl",kernelFunc:AY};var RR="return abs(x);";function DY(r){let{inputs:e,backend:t}=r,{x:n}=e;if(t.shouldExecuteOnCPU([n])&&n.dtype!=="complex64"){let s=t.texData.get(n.dataId),a=Kx(s.values);return t.makeTensorInfo(n.shape,n.dtype,a)}let o;return W().getBool("WEBGL_PACK_UNARY_OPERATIONS")?o=new Ls(n.shape,RR):o=new vn(n.shape,RR),t.runWebGLProgram(o,[n],n.dtype)}var FR={kernelName:Js,backendName:"webgl",kernelFunc:DY};var $Y=kr+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return acos(x);
|
|
`,RY=ke({opSnippet:$Y}),OR={kernelName:Ri,backendName:"webgl",kernelFunc:RY};var FY=kr+`
|
|
if (x < 1.0) return NAN;
|
|
return log(x + sqrt(x * x - 1.0));`,OY=ke({opSnippet:FY}),PR={kernelName:Fi,backendName:"webgl",kernelFunc:OY};var MR="return a + b;",PY=it({opSnippet:MR,packedOpSnippet:MR,supportsComplex:!0,cpuKernelImpl:k$}),LR={kernelName:jn,backendName:"webgl",kernelFunc:PY};var n0=class{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((s,a)=>`T${a}`);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 o0=class{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((s,a)=>`T${a}`);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 ty(r){let{inputs:e,backend:t}=r,n=e;if(n.length===1)return Yt({inputs:{x:n[0]},backend:t});if(n.length>W().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let l=Math.floor(n.length/2),u=ty({inputs:n.slice(0,l),backend:t}),c=ty({inputs:n.slice(l),backend:t});return ty({inputs:[u,c],backend:t})}let o=n.map(l=>l.dtype).reduce((l,u)=>mr(l,u)),s=n.map(l=>l.shape),i=W().getBool("WEBGL_PACK")?new o0(n[0].shape,s):new n0(n[0].shape,s);return t.runWebGLProgram(i,n,o)}var zR={kernelName:$o,backendName:"webgl",kernelFunc:ty};function MY(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,keepDims:a}=n,i=o.shape.length,l=y.parseAxisParam(s,o.shape),u=l,c=I.getAxesPermutation(u,i),p=o;c!=null&&(p=Ft({inputs:{x:o},backend:t,attrs:{perm:c}}),u=I.getInnerMostAxes(u.length,i)),I.assertAxesAreInnerMostDims("all",u,i);let[m,f]=I.computeOutAndReduceShapes(p.shape,u),d=y.sizeFromShape(f),h=le({inputs:{x:p},backend:t,attrs:{shape:[-1,d]}}),g=Ln(h,h.dtype,"all",t),x;if(a){let b=I.expandShapeToKeepDim(m,l);x=le({inputs:{x:g},backend:t,attrs:{shape:b}})}else x=le({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),c!=null&&t.disposeIntermediateTensorInfo(p),x}var BR={kernelName:Oi,backendName:"webgl",kernelFunc:MY};function LY(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,keepDims:a}=n,i=o.shape.length,l=y.parseAxisParam(s,o.shape),u=l,c=I.getAxesPermutation(u,i),p=o;c!=null&&(p=Ft({inputs:{x:o},backend:t,attrs:{perm:c}}),u=I.getInnerMostAxes(u.length,i)),I.assertAxesAreInnerMostDims("any",u,i);let[m,f]=I.computeOutAndReduceShapes(p.shape,u),d=y.sizeFromShape(f),h=le({inputs:{x:p},backend:t,attrs:{shape:[-1,d]}}),g=Ln(h,h.dtype,"any",t),x;if(a){let b=I.expandShapeToKeepDim(m,l);x=le({inputs:{x:g},backend:t,attrs:{shape:b}})}else x=le({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),c!=null&&t.disposeIntermediateTensorInfo(p),x}var VR={kernelName:Pi,backendName:"webgl",kernelFunc:LY};var s0=class{constructor(e,t,n){this.variableNames=["A"];let{windowSize:o,batchSize:s,outSize:a}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[s,a];let i=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 ${i} bestValue) {
|
|
bestValue = candidate;
|
|
bestIndex = inIdx;
|
|
}
|
|
}
|
|
setOutput(float(bestIndex));
|
|
}
|
|
`}};var i0=class{constructor(e,t,n,o){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,y.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],a=Math.ceil(s/t);this.outputShape=e.slice(0,-1),a>1&&this.outputShape.push(a),o||this.variableNames.push("bestIndicesA");let i=this.outputShape,l=i.length,u=Ge(l),c=Xt("coords",l),p,m;if(a===1){m=l+1;let $=Ge(m);p=`
|
|
${$} sourceLocR = ${$}(${c.join()}, 0);
|
|
++${c[l-1]};
|
|
${$} sourceLocG = ${$}(${c.join()}, 0);
|
|
++${c[l-2]};
|
|
${$} sourceLocA = ${$}(${c.join()}, 0);
|
|
--${c[l-1]};
|
|
${$} sourceLocB = ${$}(${c.join()}, 0);
|
|
--${c[l-2]};`}else m=l,p=`
|
|
${u} sourceLocR = coords;
|
|
++${c[l-1]};
|
|
${u} sourceLocG = coords;
|
|
++${c[l-2]};
|
|
${u} sourceLocA = coords;
|
|
--${c[l-1]};
|
|
${u} sourceLocB = coords;
|
|
--${c[l-2]};`;let f=["x","y","z","w","u","v"].slice(0,m),d="."+f[m-1],h=f.map($=>"int "+$),g=Xt("sourceLocR",m-1).concat("inIdx.r"),x=Xt("sourceLocG",m-1).concat("inIdx.g"),b=Xt("sourceLocB",m-1).concat("inIdx.b"),w=Xt("sourceLocA",m-1).concat("inIdx.a"),_=n==="max"?"greaterThan":"lessThan",C=o?"":`
|
|
inIdx = round(vec4(getBestIndicesAChannel(${g.join()}),
|
|
getBestIndicesAChannel(${x.join()}),
|
|
getBestIndicesAChannel(${b.join()}),
|
|
getBestIndicesAChannel(${w.join()})));`,A=`vec4(
|
|
getAChannel(${g.join()}),
|
|
hasNextCol ? getAChannel(${x.join()}) : 0.,
|
|
hasNextRow ? getAChannel(${b.join()}) : 0.,
|
|
hasNextRow && hasNextCol ? getAChannel(${w.join()}) : 0.)`,D=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()}));
|
|
}
|
|
${D}
|
|
void main() {
|
|
${u} coords = getOutputCoords();
|
|
bool hasNextCol = ${c[l-1]} < ${i[l-1]-1};
|
|
bool hasNextRow = ${c[l-2]} < ${i[l-2]-1};
|
|
${p}
|
|
ivec4 srcIdx = ivec4(sourceLocR${d}, sourceLocG${d},
|
|
sourceLocB${d}, sourceLocA${d}) * ${t};
|
|
ivec4 inIdx = srcIdx;
|
|
vec4 bestIndex = vec4(inIdx);
|
|
vec4 bestValue = ${A};
|
|
|
|
for (int i = 0; i < ${t}; i++) {
|
|
inIdx = srcIdx;
|
|
${C}
|
|
vec4 candidate = ${A};
|
|
bvec4 nan = isnan(candidate);
|
|
bvec4 replace = bvec4(
|
|
vec4(${_}(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 GR(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 a=I.computeOptimalWindowSize(s),i={windowSize:a,inSize:s,batchSize:o,outSize:Math.ceil(s/a)},l=new s0(i,t,n==null),u=[e];n!=null&&u.push(n);let c=r.runWebGLProgram(l,u,"int32");if(c.shape[1]===1)return c;let p=GR(r,e,t,c);return r.disposeIntermediateTensorInfo(c),p}function WR(r,e,t,n=null){let o=n!=null?n.shape:e.shape,s=o[o.length-1],a=I.computeOptimalWindowSize(s),i=new i0(o,a,t,n==null),l=n==null?[e]:[e,n],u=r.runWebGLProgram(i,l,"int32");if(u.shape.length===e.shape.length){let c=WR(r,e,t,u);return r.disposeIntermediateTensorInfo(u),c}return u}function ry(r,e,t,n){let o=[t];if(I.assertAxesAreInnerMostDims("arg"+n.charAt(0).toUpperCase()+n.slice(1),o,e.shape.length),!W().getBool("WEBGL_PACK_REDUCE")||e.shape.length<=2){let s=[],[a,i]=I.computeOutAndReduceShapes(e.shape,o),l=y.sizeFromShape(i),u=le({inputs:{x:e},backend:r,attrs:{shape:[-1,l]}});s.push(u);let c=GR(r,u,n);s.push(c);let p=le({inputs:{x:c},backend:r,attrs:{shape:a}});return s.forEach(m=>r.disposeIntermediateTensorInfo(m)),p}return WR(r,e,n)}function zY(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s}=n,a=y.parseAxisParam(s,o.shape),i=I.getAxesPermutation(a,o.shape.length),l=o,u=[];i!=null&&(l=Ft({inputs:{x:o},backend:t,attrs:{perm:i}}),u.push(l),a=I.getInnerMostAxes(a.length,l.shape.length)),I.assertAxesAreInnerMostDims("argMax",[a[0]],l.shape.length);let c=ry(t,l,a[0],"max");return u.forEach(p=>t.disposeIntermediateTensorInfo(p)),c}var jR={kernelName:Ro,backendName:"webgl",kernelFunc:zY};function BY(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s}=n,a=y.parseAxisParam(s,o.shape),i=I.getAxesPermutation(a,o.shape.length),l=o,u=[];i!=null&&(l=Ft({inputs:{x:o},backend:t,attrs:{perm:i}}),u.push(l),a=I.getInnerMostAxes(a.length,l.shape.length)),I.assertAxesAreInnerMostDims("argMin",[a[0]],l.shape.length);let c=ry(t,l,a[0],"min");return u.forEach(p=>t.disposeIntermediateTensorInfo(p)),c}var UR={kernelName:ll,backendName:"webgl",kernelFunc:BY};var VY=kr+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return asin(x);
|
|
`,GY=ke({opSnippet:VY}),qR={kernelName:Mi,backendName:"webgl",kernelFunc:GY};var WY=kr+"return log(x + sqrt(x * x + 1.0));",jY=ke({opSnippet:WY}),HR={kernelName:Li,backendName:"webgl",kernelFunc:jY};var UY=kr+`
|
|
return atan(x);
|
|
`,qY=ke({opSnippet:UY}),KR={kernelName:zi,backendName:"webgl",kernelFunc:qY};var HY=vR+`
|
|
return atan(a, b);
|
|
`,KY=`
|
|
vec4 result = atan(a, b);
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+CR+`
|
|
return result;
|
|
`,XY=it({opSnippet:HY,packedOpSnippet:KY}),XR={kernelName:Vi,backendName:"webgl",kernelFunc:XY};var YY=kr+`
|
|
if ((x < -1.0) || (x > 1.0)) return NAN;
|
|
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,ZY=ke({opSnippet:YY}),YR={kernelName:Bi,backendName:"webgl",kernelFunc:ZY};var _i=class{constructor(e,t,n,o=!1,s=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,i=e.strideHeight,l=e.strideWidth,u=e.dilationHeight,c=e.dilationWidth,p=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`,x=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`,b="0.0";if(h||(b="-1.0 / 1e-20"),n){let $=">=";this.userCode=`
|
|
const ivec2 strides = ivec2(${i}, ${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 < ${p};
|
|
wR += ${u}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${m};
|
|
wC += ${c}) {
|
|
int xC = xCCorner + wC;
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float value = getX(batch, xR, xC, d);
|
|
|
|
// If a min / max value has already been found, use it. If not,
|
|
// use the current value.
|
|
float currMinMaxValue = mix(
|
|
value, minMaxValue, minMaxValueFound);
|
|
if (value ${$} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${o?s?g:x:`wR * ${m} + wC`};
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;return}let w="max",_=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(_="avgValue / count");let C=Math.floor(a/4)*4,A=a%4,D=`
|
|
if (${h}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${w}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec2 strides = ivec2(${i}, ${l});
|
|
const ivec2 pads = ivec2(${f}, ${d});
|
|
const float initializationValue = ${b};
|
|
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(${b});
|
|
float avgValue = 0.0;
|
|
count = 0.0;
|
|
|
|
for (int wR = 0; wR < ${p};
|
|
wR += ${u}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${C}; wC += 4) {
|
|
int xC = xCCorner + wC * ${c};
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${c}, d),
|
|
getValue(batch, xR, xC + 2 * ${c}, d),
|
|
getValue(batch, xR, xC + 3 * ${c}, d)
|
|
);
|
|
|
|
${D}
|
|
}
|
|
|
|
int xC = xCCorner + ${C};
|
|
if (${A===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${D}
|
|
} else if (${A===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${c}, d),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${D}
|
|
} else if (${A===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${c}, d),
|
|
getValue(batch, xR, xC + 2 * ${c}, d),
|
|
initializationValue
|
|
);
|
|
|
|
${D}
|
|
}
|
|
}
|
|
setOutput(${_});
|
|
}
|
|
`}},pc=class{constructor(e,t,n,o=!1,s=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,i=e.strideDepth,l=e.strideHeight,u=e.strideWidth,c=e.dilationDepth,p=e.dilationHeight,m=e.dilationWidth,f=e.effectiveFilterDepth,d=e.effectiveFilterHeight,h=e.effectiveFilterWidth,g=e.padInfo.front,x=e.padInfo.top,b=e.padInfo.left;this.outputShape=e.outShape;let w=t==="avg",_="0.0";if(w||(_="-1.0 / 1e-20"),n){let M=">=";this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${i}, ${l}, ${u});
|
|
const ivec3 pads = ivec3(${g}, ${x}, ${b});
|
|
|
|
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 += ${c}) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${d};
|
|
wR += ${p}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${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 ${M} 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 C="max",A=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(A="avgValue / count");let D=Math.floor(a/4)*4,$=a%4,R=`
|
|
if (${w}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${C}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${i}, ${l}, ${u});
|
|
const ivec3 pads = ivec3(${g}, ${x}, ${b});
|
|
const float initializationValue = ${_};
|
|
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(${_});
|
|
float avgValue = 0.0;
|
|
count = 0.0;
|
|
|
|
for (int wD = 0; wD < ${f};
|
|
wD += ${c}) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${d};
|
|
wR += ${p}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${D}; 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)
|
|
);
|
|
|
|
${R}
|
|
}
|
|
|
|
int xC = xCCorner + ${D};
|
|
if (${$===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${R}
|
|
} else if (${$===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${m}, ch),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${R}
|
|
} else if (${$===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
|
|
);
|
|
|
|
${R}
|
|
}
|
|
}
|
|
setOutput(${A});
|
|
}
|
|
}
|
|
`}};function JY(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e;Ps(o,"avgPool");let{filterSize:s,strides:a,pad:i,dimRoundingMode:l}=n,u=1;y.assert(I.eitherStridesOrDilationsAreOne(a,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let c=I.computePool2DInfo(o.shape,s,a,u,i,l);if(c.filterWidth===1&&c.filterHeight===1&&y.arraysEqual(c.inShape,c.outShape))return Yt({inputs:{x:o},backend:t});let p=new _i(c,"avg",!1);return t.runWebGLProgram(p,[o],"float32")}var ZR={kernelName:Fo,backendName:"webgl",kernelFunc:JY};function QY(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{filterSize:s,strides:a,pad:i,dimRoundingMode:l,dataFormat:u}=n,c=[1,1,1],p=I.computePool3DInfo(o.shape,s,a,c,i,l,u),m=new pc(p,"avg",!1);return t.runWebGLProgram(m,[o],"float32")}var JR={kernelName:ul,backendName:"webgl",kernelFunc:QY};var a0=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,o=e.strideHeight,s=e.strideWidth,a=e.dilationHeight,i=e.dilationWidth,l=e.effectiveFilterHeight,u=e.effectiveFilterWidth,c=l-1-e.padInfo.top,p=u-1-e.padInfo.left,m=1/(t*n);this.userCode=`
|
|
const ivec2 pads = ivec2(${c}, ${p});
|
|
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 += ${a}) {
|
|
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+= ${i}) {
|
|
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);
|
|
}
|
|
`}},l0=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,o=e.filterWidth,s=e.strideDepth,a=e.strideHeight,i=e.strideWidth,l=e.dilationDepth,u=e.dilationHeight,c=e.dilationWidth,p=e.effectiveFilterDepth,m=e.effectiveFilterHeight,f=e.effectiveFilterWidth,d=p-1-e.padInfo.front,h=m-1-e.padInfo.top,g=f-1-e.padInfo.left,x=1/(t*n*o);this.userCode=`
|
|
const ivec3 pads = ivec3(${d}, ${h}, ${g});
|
|
const float avgMultiplier = float(${x});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyDCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
|
|
// dx(xD, xR, xC, ch).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
|
|
for (int wD = 0; wD < ${p};
|
|
wD += ${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) / ${a}.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 += ${c}) {
|
|
float dyC = float(dyCCorner + wC) / ${i}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
|
|
|
|
dotProd += dyValue * avgMultiplier;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function e9(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,input:s}=e,a=s,{filterSize:i,strides:l,pad:u,dimRoundingMode:c}=n,p=[1,1,1],m=I.computePool3DInfo(a.shape,i,l,p,u,c),f=new l0(m);return t.runWebGLProgram(f,[o],a.dtype)}var QR={kernelName:jc,backendName:"webgl",kernelFunc:e9};function t9(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,input:s}=e,a=s;Ps([o,s],"avgPoolGrad");let{filterSize:i,strides:l,pad:u}=n,c=I.computePool2DInfo(a.shape,i,l,1,u),p=new a0(c);return t.runWebGLProgram(p,[o],a.dtype)}var eF={kernelName:Wc,backendName:"webgl",kernelFunc:t9};function r9(r){let{inputs:e,backend:t,attrs:n}=r,{a:o,b:s}=e,{transposeA:a,transposeB:i}=n;return cc({a:o,b:s,transposeA:a,transposeB:i,backend:t})}var tF={kernelName:Oo,backendName:"webgl",kernelFunc:r9};var u0=class{constructor(e,t,n,o,s,a){this.outputShape=[],this.variableNames=["x","mean","variance"],I.assertAndGetBroadcastShape(e,t),I.assertAndGetBroadcastShape(e,n);let i="0.0";o!=null&&(I.assertAndGetBroadcastShape(e,o),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let l="1.0";s!=null&&(I.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 = ${i};
|
|
float scale = ${l};
|
|
float inv = scale * inversesqrt(variance + float(${a}));
|
|
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
|
|
}
|
|
`}};var c0=class{constructor(e,t,n,o,s,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],I.assertAndGetBroadcastShape(e,t),I.assertAndGetBroadcastShape(e,n);let i="vec4(0.0)";o!=null&&(I.assertAndGetBroadcastShape(e,o),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let l="vec4(1.0)";s!=null&&(I.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale"),l="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
vec4 offset = ${i};
|
|
vec4 scale = ${l};
|
|
|
|
vec4 x = getXAtOutCoords();
|
|
vec4 mean = getMeanAtOutCoords();
|
|
vec4 variance = getVarianceAtOutCoords();
|
|
|
|
vec4 inv = scale * inversesqrt(variance + vec4(${a}));
|
|
|
|
setOutput((x - mean) * inv + offset);
|
|
}
|
|
`}};var n9=({inputs:r,backend:e,attrs:t})=>{let{x:n,mean:o,variance:s,offset:a,scale:i}=r;y.assert(o.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),y.assert(a==null||o.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),y.assert(i==null||o.shape.length===i.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],c=null;a!=null&&(c=a.shape,u.push(a));let p=null;i!=null&&(p=i.shape,u.push(i));let m=W().getBool("WEBGL_PACK_NORMALIZATION")?new c0(n.shape,o.shape,s.shape,c,p,l):new u0(n.shape,o.shape,s.shape,c,p,l);return e.runWebGLProgram(m,u,u[0].dtype)},rF={kernelName:qo,backendName:"webgl",kernelFunc:n9};var p0=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=Ge(this.rank),n=`uniform int start[${this.rank}];`,o=o9(this.rank),s,a=e.map((i,l)=>`sourceLoc.${m0[l]} = start[${l}] + coords.${m0[l]};`);s=`
|
|
${t} sourceLoc;
|
|
${t} coords = getOutputCoords();
|
|
${a.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)}}},m0=["x","y","z","w","u","v"];function o9(r){if(r===1)return"sourceLoc";if(r<=6)return m0.slice(0,r).map(e=>"sourceLoc."+e).join(",");throw Error(`Slicing for rank ${r} is not yet supported`)}var f0=class{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;let t=Ge(this.rank),n=Xt("coords",this.rank),o=Xt("sourceLoc",this.rank),s=this.rank===1?"sourceLoc":`vec2(${o.slice(-2).join()})`,a=`getChannel(getSource(${o.join()}), ${s})`,i=`
|
|
result.x = ${a};
|
|
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
|
|
++${o[this.rank-1]};
|
|
result.y = ${a};
|
|
--${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 = ${a};
|
|
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
|
|
++${o[this.rank-1]};
|
|
result.w = ${a};
|
|
}
|
|
}
|
|
`,u=this.rank<=4?`sourceLoc = coords +
|
|
${t}(${e.map((c,p)=>`start[${p}]`).join()});`:e.map((c,p)=>`${o[p]} = ${n[p]} + start[${p}];`).join(`
|
|
`);this.userCode=`
|
|
uniform int start[${this.rank}];
|
|
void main() {
|
|
${t} coords = getOutputCoords();
|
|
${t} sourceLoc;
|
|
${u}
|
|
vec4 result = vec4(0.);
|
|
${i}
|
|
${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 s9(r,e,t,n){let o=n.texData.get(r.dataId),s=n.makeTensorInfo(t,r.dtype),a=n.texData.get(s.dataId);Object.assign(a,o),a.refCount=1,a.shape=t,a.dtype=r.dtype;let i=lr.computeFlatOffset(e,y.computeStrides(r.shape));o.slice&&(i+=o.slice.flatOffset),a.slice={flatOffset:i,origDataId:o.slice&&o.slice.origDataId||r.dataId};let l=n.dataRefCount.get(a.slice.origDataId)||1;return n.dataRefCount.set(a.slice.origDataId,l+1),s}function qa(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{begin:s,size:a}=n,[i,l]=lr.parseSliceParams(o,s,a);if(lr.assertParamsValid(o,i,l),y.sizeFromShape(l)===0)return t.makeTensorInfo(l,o.dtype,[]);if(t.shouldExecuteOnCPU([o])||o.dtype==="string"){let p=t.texData.get(o.dataId),m=H$(p.values,i,l,o.shape,o.dtype);return t.makeTensorInfo(l,o.dtype,m)}let{isPacked:u}=t.texData.get(o.dataId),c=lr.isSliceContinous(o.shape,i,l);if(u||!c){let p=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new f0(l):new p0(l),m=p.getCustomSetupFunc(i);return t.runWebGLProgram(p,[o],o.dtype,m)}return t.uploadToGPU(o.dataId),s9(o,i,l,t)}var nF={kernelName:ai,backendName:"webgl",kernelFunc:qa};var i9=r=>{let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{blockShape:s,crops:a}=n;y.assert(o.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let i=s.reduce((b,w)=>b*w),l=I.getReshaped(o.shape,s,i),u=I.getPermuted(l.length,s.length),c=I.getReshapedPermuted(o.shape,s,i),p=I.getSliceBeginCoords(a,s.length),m=I.getSliceSize(c,a,s.length),f=[],d=le({inputs:{x:o},backend:t,attrs:{shape:l}}),h=Ft({inputs:{x:d},backend:t,attrs:{perm:u}}),g=le({inputs:{x:h},backend:t,attrs:{shape:c}}),x=qa({inputs:{x:g},backend:t,attrs:{begin:p,size:m}});return f.push(d),f.push(h),f.push(g),f.forEach(b=>t.disposeIntermediateTensorInfo(b)),x},oF={kernelName:cl,backendName:"webgl",kernelFunc:i9};function a9(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,weights:s}=e,{size:a}=n,i=t.readSync(o.dataId),l=t.readSync(s.dataId),u=Hx(i,l,s.dtype,s.shape,a);return t.makeTensorInfo([a],s.dtype,u)}var sF={kernelName:Uc,backendName:"webgl",kernelFunc:a9};var l9="return float(a != b);",d0=it({opSnippet:l9,cpuKernelImpl:W$,dtype:"bool"}),iF={kernelName:ia,backendName:"webgl",kernelFunc:d0};function Ha(r){let{inputs:e,backend:t}=r,{input:n}=e,o=t.texData.get(n.dataId);return Yt({inputs:{x:o.complexTensorInfos.real},backend:t})}var aF={kernelName:pp,backendName:"webgl",kernelFunc:Ha};var u9="return float(int(x));";function lF(r,e){let t=new vn(r.shape,u9),n=e.runWebGLProgram(t,[r],"int32");return{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}function h0(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{dtype:s}=n;if(s==="complex64"){if(o.dtype==="complex64")return Yt({inputs:{x:o},backend:t});let a=gt(o.shape),i=h0({inputs:{x:o},backend:t,attrs:{dtype:"float32"}}),l=Cn({inputs:{real:i,imag:a},backend:t});return a.dispose(),t.disposeIntermediateTensorInfo(i),l}if(o.dtype==="complex64"){let a=Ha({inputs:{input:o},backend:t}),i=h0({inputs:{x:a},backend:t,attrs:{dtype:s}});return t.disposeIntermediateTensorInfo(a),i}if(!y.hasEncodingLoss(o.dtype,s)){let a=Yt({inputs:{x:o},backend:t});return{dataId:a.dataId,shape:a.shape,dtype:s}}if(s==="int32")return lF(o,t);if(s==="bool"){let a=t.makeTensorInfo([],"bool",y.getTypedArrayFromDType("bool",1)),l=d0({inputs:{a:o,b:a},backend:t});return t.disposeIntermediateTensorInfo(a),l}throw new Error(`Error in Cast: failed to cast ${o.dtype} to ${s}`)}var uF={kernelName:to,backendName:"webgl",kernelFunc:h0};var cF="return ceil(x);",c9=ke({opSnippet:cF,packedOpSnippet:cF,cpuKernelImpl:C$}),pF={kernelName:Po,backendName:"webgl",kernelFunc:c9};var g0=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 x0=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 p9(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{clipValueMin:s,clipValueMax:a}=n,i;W().getBool("WEBGL_PACK_CLIP")?i=new x0(o.shape):i=new g0(o.shape);let l=i.getCustomSetupFunc(s,a);return t.runWebGLProgram(i,[o],o.dtype,l)}var mF={kernelName:ro,backendName:"webgl",kernelFunc:p9};var y0=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 fF(r,e){return{dataId:e.dataId,dtype:e.dtype,shape:r.shape}}function m9(r){let{inputs:e,backend:t}=r,{x:n}=e,o=t.texData.get(n.dataId),s=new y0(n.shape),a=[fF(n,o.complexTensorInfos.real),fF(n,o.complexTensorInfos.imag)];return t.runWebGLProgram(s,a,a[0].dtype)}var dF={kernelName:pl,backendName:"webgl",kernelFunc:m9};var b0=class{constructor(e){this.outputShape=[],this.outputShape=I.computeOutShape(e,1),this.variableNames=e.map((a,i)=>`T${i}`);let t=new Array(e.length-1);t[0]=e[0][1];for(let a=1;a<t.length;a++)t[a]=t[a-1]+e[a][1];let n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let a=1;a<t.length;a++){let i=t[a-1];n.push(`else if (yC < ${t[a]}) setOutput(getT${a}(yR, yC-${i}));`)}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 w0=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=I.computeOutShape(e,t);let n=this.outputShape,o=n.length,s=Ge(o),a=Xt("coords",o),i=["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=i[t],c=i.slice(-2),p=i.join(),m=`if (${u} < ${l[0]}) {
|
|
return getChannel(
|
|
getT0(${p}), vec2(${c.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}(${ny(i,u,g)}),
|
|
vec2(${ny(c,u,g)}));
|
|
}`}let f=l.length,d=l[l.length-1];m+=`
|
|
return getChannel(
|
|
getT${f}(${ny(i,u,d)}),
|
|
vec2(${ny(c,u,d)}));`,this.userCode=`
|
|
float getValue(${i.map(h=>"int "+h)}) {
|
|
${m}
|
|
}
|
|
|
|
void main() {
|
|
${s} coords = getOutputCoords();
|
|
vec4 result = vec4(getValue(${a}), 0., 0., 0.);
|
|
|
|
${a[o-1]} = ${a[o-1]} + 1;
|
|
if (${a[o-1]} < ${n[o-1]}) {
|
|
result.g = getValue(${a});
|
|
}
|
|
|
|
${a[o-2]} = ${a[o-2]} + 1;
|
|
if (${a[o-2]} < ${n[o-2]}) {
|
|
result.a = getValue(${a});
|
|
}
|
|
|
|
${a[o-1]} = ${a[o-1]} - 1;
|
|
if (${a[o-2]} < ${n[o-2]} &&
|
|
${a[o-1]} < ${n[o-1]}) {
|
|
result.b = getValue(${a});
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};function ny(r,e,t){let n=r.indexOf(e);return r.map((s,a)=>a===n?`${s} - ${t}`:s).join()}function mc(r){let{inputs:e,backend:t}=r,{input:n}=e,o=t.texData.get(n.dataId);return Yt({inputs:{x:o.complexTensorInfos.imag},backend:t})}var hF={kernelName:op,backendName:"webgl",kernelFunc:mc};function fc(r,e,t){let n=r[0].dtype;if(n==="complex64"){let c=r.map(h=>Ha({inputs:{input:h},backend:t})),p=r.map(h=>mc({inputs:{input:h},backend:t})),m=fc(c,e,t),f=fc(p,e,t),d=Cn({inputs:{real:m,imag:f},backend:t});return c.forEach(h=>t.disposeIntermediateTensorInfo(h)),p.forEach(h=>t.disposeIntermediateTensorInfo(h)),t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f),d}let o=t.shouldExecuteOnCPU(r);if(n==="string"&&(o=!0),o){let c=r.map(x=>{let b=y.sizeFromShape(x.shape.slice(e));return le({inputs:{x},backend:t,attrs:{shape:[-1,b]}})}),p=c.map(x=>({vals:t.readSync(x.dataId),shape:x.shape})),m=I.computeOutShape(c.map(x=>x.shape),1),f=c[0].shape[0]===1,d=I$(p,m,n,f),h=I.computeOutShape(r.map(x=>x.shape),e),g=t.makeTensorInfo(h,n,d);return c.forEach(x=>t.disposeIntermediateTensorInfo(x)),g}if(r.length>W().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let c=Math.floor(r.length/2),p=fc(r.slice(0,c),e,t),m=fc(r.slice(c),e,t),f=fc([p,m],e,t);return t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(m),f}if(W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&r[0].shape.length>1){let c=new w0(r.map(p=>p.shape),e);return t.runWebGLProgram(c,r,n)}let{tensors2D:s,outShape:a}=f9(r,e,t),i=new b0(s.map(c=>c.shape)),l=t.runWebGLProgram(i,s,n);s.forEach(c=>t.disposeIntermediateTensorInfo(c));let u=le({inputs:{x:l},attrs:{shape:a},backend:t});return t.disposeIntermediateTensorInfo(l),u}function f9(r,e,t){let n=I.computeOutShape(r.map(s=>s.shape),e);return{tensors2D:r.map(s=>le({inputs:{x:s},attrs:{shape:[-1,y.sizeFromShape(s.shape.slice(e))]},backend:t})),outShape:n}}function _0(r){let{inputs:e,backend:t,attrs:n}=r,{axis:o}=n,s=y.parseAxisParam(o,e[0].shape)[0],a=I.computeOutShape(e.map(u=>u.shape),s);if(y.sizeFromShape(a)===0)return t.makeTensorInfo(a,e[0].dtype,[]);let i=e.filter(u=>y.sizeFromShape(u.shape)>0);if(i.length===1)return Yt({inputs:{x:i[0]},backend:t});let l=i.map(u=>u.shape);return I.assertParamsConsistent(l,s),fc(i,s,t)}var gF={kernelName:Qs,backendName:"webgl",kernelFunc:_0};var fd=class{constructor(e,t=!1,n=null,o=!1,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let a=e.padInfo.top,i=e.padInfo.left,l=e.strideHeight,u=e.strideWidth,c=e.dilationHeight,p=e.dilationWidth,m=e.filterHeight,f=e.filterWidth,d=Math.floor(e.inChannels/4)*4,h=e.inChannels%4,g=e.dataFormat==="channelsLast",x=g?1:2,b=g?2:3,w=g?3:1,_="",C="";n&&(o?_=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:s?_=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${n}
|
|
}`:_=`
|
|
float activation(float x) {
|
|
${n}
|
|
}
|
|
`,C="result = activation(result);");let A=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${_}
|
|
|
|
const ivec2 strides = ivec2(${l}, ${u});
|
|
const ivec2 pads = ivec2(${a}, ${i});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d2 = coords[${w}];
|
|
|
|
ivec2 xRCCorner =
|
|
ivec2(coords[${x}], coords[${b}]) * 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 * ${c};
|
|
|
|
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 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;
|
|
${A}
|
|
${C}
|
|
setOutput(result);
|
|
}
|
|
`}},k0=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,a=e.strideHeight,i=e.strideWidth,l=e.dilationDepth,u=e.dilationHeight,c=e.dilationWidth,p=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}, ${a}, ${i});
|
|
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 < ${p}; 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 * ${c};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int d1 = 0; d1 < ${d}; d1 += 4) {
|
|
vec4 xValues = vec4(
|
|
getX(batch, xF, xR, xC, d1),
|
|
getX(batch, xF, xR, xC, d1 + 1),
|
|
getX(batch, xF, xR, xC, d1 + 2),
|
|
getX(batch, xF, xR, xC, d1 + 3)
|
|
);
|
|
vec4 wValues = vec4(
|
|
getW(wF, wR, wC, d1, d2),
|
|
getW(wF, wR, wC, d1 + 1, d2),
|
|
getW(wF, wR, wC, d1 + 2, d2),
|
|
getW(wF, wR, wC, d1 + 3, d2)
|
|
);
|
|
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
if (${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 v0=class{constructor(e,t,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;let{filterWidth:o,inChannels:s,strideWidth:a,strideHeight:i,padInfo:l,outWidth:u,dilationWidth:c,dilationHeight:p,dataFormat:m}=n,{left:f,top:d}=l,h=s*o,g=Lt(),x=m==="channelsLast",b=x?0:1,w=x?1:2,_="";for(let C=0;C<=1;C++)for(let A=0;A<=1;A++)_+=`
|
|
blockIndex = rc.y + ${A};
|
|
pos = rc.x + ${C};
|
|
|
|
if(blockIndex < ${e[1]} && pos < ${e[0]}) {
|
|
offsetY = int(blockIndex / (${u})) * ${i} - ${d};
|
|
d0 = offsetY + ${p} * (pos / ${h});
|
|
|
|
if(d0 < ${t[b]} && d0 >= 0) {
|
|
|
|
offsetX = int(mod(float(blockIndex), ${u}.) * ${a}. - ${f}.);
|
|
d1 = offsetX + ${c} * (int(mod(float(pos), ${h}.) / ${s}.));
|
|
|
|
if(d1 < ${t[w]} && d1 >= 0) {
|
|
|
|
ch = int(mod(float(pos), ${s}.));
|
|
|
|
if (${x}) {
|
|
innerDims = vec2(d1, ch);
|
|
result[${C*2+A}] = getChannel(
|
|
getA(d0, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
} else {
|
|
innerDims = vec2(d0, d1);
|
|
result[${C*2+A}] = getChannel(
|
|
getA(ch, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
`;this.userCode=`
|
|
void main() {
|
|
ivec2 rc = getOutputCoords();
|
|
|
|
vec4 result = vec4(0);
|
|
|
|
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
|
|
vec2 innerDims;
|
|
|
|
${_}
|
|
|
|
${g.output} = result;
|
|
}
|
|
`}};function oy({x:r,filter:e,convInfo:t,backend:n,bias:o=null,preluActivationWeights:s=null,leakyreluAlpha:a=0,activation:i=null}){let l=r.shape,u=n.texData.get(r.dataId),c=t.inChannels,p=l[0]*l[1]*l[2],m=t.outChannels,f=t.dataFormat==="channelsLast",d=!1,h=!1,g,x=[],b=(p===1||m===1)&&c>r0,w=l[2]%2!=0&&!!u.isPacked;if(b||!W().getBool("WEBGL_LAZILY_UNPACK")||!W().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!w){let _=f?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],C=le({inputs:{x:r},backend:n,attrs:{shape:[1,_,t.inChannels]}}),A=le({inputs:{x:e},backend:n,attrs:{shape:[1,t.inChannels,t.outChannels]}}),D=cc({a:C,b:A,transposeA:d,transposeB:h,backend:n,bias:o,activation:i,preluActivationWeights:s,leakyreluAlpha:a});g=le({inputs:{x:D},backend:n,attrs:{shape:t.outShape}}),x.push(C),x.push(A),x.push(D)}else{let _=f?l[0]*l[1]*(l[2]+1):l[0]*l[2]*(l[3]+1),C={dataId:r.dataId,shape:[1,_,t.inChannels],dtype:r.dtype},A=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,y.assert(Fl(u.shape,C.shape),()=>`packed reshape ${u.shape} to ${C.shape} isn't free`);let D=le({inputs:{x:e},backend:n,attrs:{shape:[1,t.inChannels,t.outChannels]}});x.push(D);let $=cc({a:C,b:D,backend:n,transposeA:d,transposeB:h,bias:o,activation:i,preluActivationWeights:s,leakyreluAlpha:a}),R=n.texData.get($.dataId);y.assert(R.isPacked,()=>"batchMatMul result is expected to be packed"),u.shape=A,R.shape=t.outShape,g=Yt({inputs:{x:$},backend:n}),g.shape=t.outShape,x.push($)}for(let _ of x)n.disposeIntermediateTensorInfo(_);return g}function sy({x:r,filter:e,convInfo:t,backend:n,bias:o=null,preluActivationWeights:s=null,leakyreluAlpha:a=0,activation:i=null}){let{filterWidth:l,filterHeight:u,inChannels:c,outWidth:p,outHeight:m,dataFormat:f}=t,d=f==="channelsLast",h=l*u*c,g=m*p,x=[h,g],b=!0,w=!1,_=[],C=le({inputs:{x:r},backend:n,attrs:{shape:r.shape.slice(1)}}),A=le({inputs:{x:e},backend:n,attrs:{shape:[1,h,y.sizeFromShape(e.shape)/h]}});_.push(C),_.push(A);let D=new v0(x,C.shape,t),$=n.runWebGLProgram(D,[C],"float32"),R=le({inputs:{x:$},backend:n,attrs:{shape:[1,x[0],x[1]]}});_.push($),_.push(R);let M=o!=null,G=s!=null,j=i==="leakyrelu",U=i?Pl(i,!0):null,q=new pd(R.shape,A.shape,[1,g,t.outChannels],b,w,M,U,G,j),H=[R,A];if(o&&H.push(o),G&&H.push(s),j){let re=n.makeTensorInfo([],"float32",y.createScalarValue(a,"float32"));H.push(re),_.push(re)}let X=n.runWebGLProgram(q,H,"float32"),ne=d?[1,m,p,t.outChannels]:[1,t.outChannels,m,p],Y=le({inputs:{x:X},backend:n,attrs:{shape:ne}});_.push(X);for(let re of _)n.disposeIntermediateTensorInfo(re);return Y}function d9(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,filter:s}=e,{strides:a,pad:i,dataFormat:l,dilations:u,dimRoundingMode:c}=n,p=I.convertConv2DDataFormat(l),m=I.computeConv2DInfo(o.shape,s.shape,a,u,i,c,!1,p),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=oy({x:o,filter:s,convInfo:m,backend:t});else if(W().getBool("WEBGL_CONV_IM2COL")&&o.shape[0]===1)f=sy({x:o,filter:s,convInfo:m,backend:t});else{let h=new fd(m);f=t.runWebGLProgram(h,[o,s],"float32")}let d=le({inputs:{x:f},backend:t,attrs:{shape:m.outShape}});return t.disposeIntermediateTensorInfo(f),d}var xF={kernelName:Mo,backendName:"webgl",kernelFunc:d9};var C0=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,a=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 (${a}) {
|
|
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);
|
|
}
|
|
`}},I0=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,o=e.strideHeight,s=e.strideWidth,a=e.dataFormat==="channelsLast",i=t-1-e.padInfo.top,l=n-1-e.padInfo.left,u=a?1:2,c=a?2:3,p=a?3:1;this.userCode=`
|
|
const ivec2 pads = ivec2(${i}, ${l});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d1 = coords[${p}];
|
|
|
|
ivec2 dyCorner = ivec2(coords[${u}], coords[${c}]) - pads;
|
|
int dyRCorner = dyCorner.x;
|
|
int dyCCorner = dyCorner.y;
|
|
|
|
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < ${t}; wR++) {
|
|
float dyR = float(dyRCorner + wR) / ${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 (${a}) {
|
|
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);
|
|
}
|
|
`}},S0=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,a=e.padInfo.top,i=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} - ${a};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${o} - ${i};
|
|
|
|
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);
|
|
}
|
|
`}},N0=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,o=e.filterWidth,s=e.strideDepth,a=e.strideHeight,i=e.strideWidth,l=t-1-e.padInfo.front,u=n-1-e.padInfo.top,c=o-1-e.padInfo.left;this.userCode=`
|
|
const ivec3 pads = ivec3(${l}, ${u}, ${c});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int d1 = coords.u;
|
|
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyFCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
float dotProd = 0.0;
|
|
for (int wF = 0; wF < ${t}; wF++) {
|
|
float dyF = float(dyFCorner + wF) / ${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) / ${a}.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) / ${i}.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 h9(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,dy:s}=e,{strides:a,pad:i,dataFormat:l,dimRoundingMode:u,filterShape:c}=n,p=I.convertConv2DDataFormat(l),m=I.computeConv2DInfo(o.shape,c,a,1,i,u,!1,p),f=new C0(m);return t.runWebGLProgram(f,[o,s],"float32")}var yF={kernelName:Hc,backendName:"webgl",kernelFunc:h9};function g9(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,filter:s}=e,{inputShape:a,strides:i,pad:l,dataFormat:u,dimRoundingMode:c}=n,p=I.convertConv2DDataFormat(u),m=I.computeConv2DInfo(a,s.shape,i,1,l,c,!1,p),f=new I0(m);return t.runWebGLProgram(f,[o,s],"float32")}var bF={kernelName:Lo,backendName:"webgl",kernelFunc:g9};function x9(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,filter:s}=e,{strides:a,pad:i,dilations:l}=n,u=I.computeConv3DInfo(o.shape,s.shape,a,l,i),c=new k0(u);return t.runWebGLProgram(c,[o,s],"float32")}var wF={kernelName:ml,backendName:"webgl",kernelFunc:x9};function y9(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,dy:s}=e,{strides:a,pad:i,filterShape:l}=n,u=I.computeConv3DInfo(o.shape,l,a,1,i),c=new S0(u);return t.runWebGLProgram(c,[o,s],"float32")}var _F={kernelName:Kc,backendName:"webgl",kernelFunc:y9};function b9(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,filter:s}=e,{pad:a,strides:i,inputShape:l}=n,u=I.computeConv3DInfo(l,s.shape,i,1,a),c=new N0(u);return t.runWebGLProgram(c,[o,s],"float32")}var kF={kernelName:Xc,backendName:"webgl",kernelFunc:b9};var w9=Jx+`
|
|
return cos(x);
|
|
`,_9=ke({opSnippet:w9}),vF={kernelName:zo,backendName:"webgl",kernelFunc:_9};var k9=`
|
|
float e2x = exp(-x);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`,v9=ke({opSnippet:k9}),CF={kernelName:Gi,backendName:"webgl",kernelFunc:v9};var T0=class{constructor(e,t,n,o,s){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[a,i,l,u]=e,[c]=t,[p,m]=n;this.outputShape=[c,p,m,u];let f=o==="bilinear"?1:0,[d,h]=[`${i-1}.0`,`${l-1}.0`],[g,x,b]=p>1?[`${(i-1)/(p-1)}`,"(y2-y1) * height_ratio",`y1*${d} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${d}`],[w,_,C]=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(${w});
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int y = coords[1];
|
|
int x = coords[2];
|
|
int d = coords[3];
|
|
|
|
// get box vals
|
|
float y1 = getBoxes(b,0);
|
|
float x1 = getBoxes(b,1);
|
|
float y2 = getBoxes(b,2);
|
|
float x2 = getBoxes(b,3);
|
|
|
|
// get image in batch index
|
|
int bInd = round(getBoxInd(b));
|
|
if(bInd < 0 || bInd >= ${a}) {
|
|
return;
|
|
}
|
|
|
|
float height_scale = ${x};
|
|
float width_scale = ${_};
|
|
|
|
float in_y = ${b};
|
|
if( in_y < 0.0 || in_y > ${d} ) {
|
|
setOutput(float(${s}));
|
|
return;
|
|
}
|
|
float in_x = ${C};
|
|
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 C9=r=>{let{inputs:e,backend:t,attrs:n}=r,{image:o,boxes:s,boxInd:a}=e,{cropSize:i,method:l,extrapolationValue:u}=n,c=new T0(o.shape,s.shape,i,l,u);return t.runWebGLProgram(c,[o,s,a],"float32")},IF={kernelName:Wi,backendName:"webgl",kernelFunc:C9};var iy=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=e;let o=e.length,s=t?"0.0":`getX(${SF(o,"coords")})`,a=e[e.length-1],i="",l="";t?(i=n?`end != ${a-1}`:"end != 0",l=n?"end + 1":"end - 1"):(i=n?`end + pow2 < ${a}`:"end >= pow2",l=n?"end + pow2":"end - pow2"),this.userCode=`
|
|
uniform float index;
|
|
void main() {
|
|
${Ge(o)} coords = getOutputCoords();
|
|
int end = ${NF(o,"coords")};
|
|
float val = ${s};
|
|
int pow2 = int(pow(2.0, index));
|
|
if (${i}) {
|
|
int idx = ${l};
|
|
${NF(o,"coords")} = idx;
|
|
val += getX(${SF(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 SF(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 NF(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 I9(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,exclusive:a,reverse:i}=n,l=o.shape.length,u=I.getAxesPermutation([s],l),c=o;u!=null&&(c=Ft({inputs:{x:o},backend:t,attrs:{perm:u}}));let p=I.getInnerMostAxes(1,l)[0];if(p!==l-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${o.shape.length-1} but got axis=${s}`);let m=c.shape[p],f=Yt({inputs:{x:c},backend:t});for(let d=0;d<=Math.ceil(Math.log2(m))-1;d++){let h=new iy(c.shape,!1,i),g=h.getCustomSetupFunc(d),x=f;f=t.runWebGLProgram(h,[f],f.dtype,g),t.disposeIntermediateTensorInfo(x)}if(a){let d=new iy(c.shape,a,i),h=f;f=t.runWebGLProgram(d,[f],f.dtype),t.disposeIntermediateTensorInfo(h)}if(u!=null){let d=I.getUndoAxesPermutation(u),h=Ft({inputs:{x:f},backend:t,attrs:{perm:d}});return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(c),h}return f}var TF={kernelName:Bo,backendName:"webgl",kernelFunc:I9};function S9(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,weights:s}=e,{size:a,binaryOutput:i}=n;if(o.shape.length===1){let l=t.readSync(o.dataId),u=t.readSync(s.dataId),c=Hx(l,u,s.dtype,s.shape,a);return t.makeTensorInfo([a],s.dtype,c)}else if(o.shape.length===2){let l=t.bufferSync(o),u=t.bufferSync(s),c=v$(l,u,a,i);return t.makeTensorInfo(c.shape,s.dtype,c.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${o.shape.length}.`)}var EF={kernelName:Yc,backendName:"webgl",kernelFunc:S9};var E0=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 N9(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{blockSize:s,dataFormat:a}=n;y.assert(s>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${s}`);let i=o.shape[0],l=a==="NHWC"?o.shape[1]:o.shape[2],u=a==="NHWC"?o.shape[2]:o.shape[3],c=a==="NHWC"?o.shape[3]:o.shape[1],p=l*s,m=u*s,f=c/(s*s),d=a==="NHWC"?[i,p,m,f]:[i,f,p,m],h=new E0(d,s,a);return t.runWebGLProgram(h,[o],o.dtype)}var AF={kernelName:ji,backendName:"webgl",kernelFunc:N9};var dd=class{constructor(e,t=!1,n=null,o=!1,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let a=e.inHeight,i=e.inWidth,l=e.padInfo.top,u=e.padInfo.left,c=e.strideHeight,p=e.strideWidth,m=e.dilationHeight,f=e.dilationWidth,d=e.filterHeight,h=e.filterWidth,g=e.outChannels/e.inChannels,x="",b="";n&&(o?x=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:s?x=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${n}
|
|
}`:x=`
|
|
float activation(float x) {
|
|
${n}
|
|
}
|
|
`,b="result = activation(result);");let w=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${x}
|
|
|
|
const ivec2 strides = ivec2(${c}, ${p});
|
|
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 >= ${a}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${h}; wC++) {
|
|
int xC = xCCorner + wC * ${f};
|
|
|
|
if (xC < 0 || xC >= ${i}) {
|
|
continue;
|
|
}
|
|
|
|
float xVal = getX(batch, xR, xC, d1);
|
|
float wVal = getW(wR, wC, d1, q);
|
|
dotProd += xVal * wVal;
|
|
}
|
|
}
|
|
|
|
float result = dotProd;
|
|
${w}
|
|
${b}
|
|
setOutput(result);
|
|
}
|
|
`}};var hd=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 a=e.outChannels/e.inChannels,i=e.inHeight,l=e.inWidth,u=e.padInfo.top,c=e.padInfo.left,p=e.strideHeight,m=e.strideWidth,f=e.dilationHeight,d=e.dilationWidth,h=e.filterHeight,g=e.filterWidth,x=g,b=`
|
|
int xR; int xC; int xCOffset;
|
|
vec4 wTexel; vec4 previous; vec4 final;`;for(let A=0;A<g;A++)b+=`
|
|
vec4 xTexelC${A*2};
|
|
int xTexelC${A*2}Ready;
|
|
vec4 xC${A};`;for(let A=0;A<h;A++){for(let D=0;D<g;D++)b+=`
|
|
xTexelC${D*2} = vec4(0.0);
|
|
xTexelC${D*2}Ready = 0;
|
|
xC${D} = vec4(0.0);`;b+=`
|
|
xR = xRCorner + ${A*f};
|
|
if (xR >=0 && xR < ${i}) {
|
|
`;for(let D=0;D<(x+1)/2;D++){let $=D*2,R=$*d;if(b+=`
|
|
xC = xCCorner + ${R};
|
|
`,m===1){if($<g&&(c%2==1?(b+=`
|
|
xCOffset = xC + 1;
|
|
if (xCOffset >= 0 && xCOffset < ${l} && xTexelC${R}Ready == 0) {
|
|
xTexelC${R} = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= ${l}) {
|
|
xTexelC${R}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${R}Ready = 1;
|
|
}
|
|
`,d===1&&R>0?b+=`
|
|
xC${$} = vec4(xTexelC${R-2}.zw, xTexelC${R}.xy);
|
|
`:b+=`
|
|
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${$} = vec4(previous.zw, xTexelC${R}.xy);
|
|
} else {
|
|
xC${$} = vec4(0.0, 0.0, xTexelC${R}.xy);
|
|
}
|
|
`):b+=`
|
|
if (xC >= 0 && xC < ${l} && xTexelC${R}Ready == 0) {
|
|
xTexelC${R} = getX(batch, xR, xC, d1);
|
|
if (xC + 1 >= ${l}) {
|
|
xTexelC${R}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${R}Ready = 1;
|
|
}
|
|
|
|
xC${$} = xTexelC${R};
|
|
`,R+1<g)){let M=c%2==0?y.nearestLargerEven(d):d;d%2==0&&c%2==1||d%2!=0&&c%2!=1?(b+=`
|
|
xCOffset = xC + ${c%2} + ${M};
|
|
|
|
if (xCOffset >= 0 && xCOffset < ${l} && xTexelC${R+2}Ready == 0) {
|
|
xTexelC${R+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${R+2}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${R+2}Ready = 1;
|
|
}
|
|
`,d>1&&(b+=`
|
|
xCOffset -= 2;
|
|
if (xCOffset >= 0 && xCOffset < ${l} && xTexelC${R}Ready == 0) {
|
|
xTexelC${R} = getX(batch, xR, xCOffset, d1);
|
|
xTexelC${R}Ready = 1;
|
|
}
|
|
`),b+=`
|
|
xC${$+1} = vec4(xTexelC${R}.zw, xTexelC${R+2}.xy);
|
|
`):M===1?b+=`
|
|
xC${$+1} = xTexelC${R};
|
|
`:b+=`
|
|
xCOffset = xC + ${M};
|
|
|
|
if (xCOffset >= 0 && xCOffset < ${l} && xTexelC${R+2}Ready == 0) {
|
|
xTexelC${R+2} = getX(batch, xR, xCOffset, d1);
|
|
if (xCOffset + 1 >= ${l}) {
|
|
xTexelC${R+2}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${R+2}Ready = 1;
|
|
}
|
|
|
|
xC${$+1} = xTexelC${R+2};
|
|
`}}else R<g&&(c%2==1?(b+=`
|
|
xCOffset = xC + 1 - ${m};
|
|
if(xCOffset >= 0 && xCOffset < ${l} && xTexelC${R}Ready == 0) {
|
|
xTexelC${R} = getX(batch, xR, xCOffset, d1);
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= ${l}) {
|
|
xTexelC${R}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${R}Ready = 1;
|
|
}
|
|
|
|
if(xC + 1 >= 0 && xC + 1 < ${l} && xTexelC${R+2}Ready == 0) {
|
|
xTexelC${R+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${R+2}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${R+2}Ready = 1;
|
|
}
|
|
|
|
xC${$} = vec4(xTexelC${R}.zw, xTexelC${R+2}.zw);
|
|
`,R+1<g&&(b+=`
|
|
final = vec4(0.0);
|
|
xCOffset = xC + 1 + ${m};
|
|
if(xCOffset >= 0 && xCOffset < ${l}) {
|
|
final = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
xC${$+1} = vec4(xTexelC${R+2}.xy, final.xy);
|
|
`)):(b+=`
|
|
if(xC >= 0 && xC < ${l} && xTexelC${R}Ready == 0) {
|
|
xTexelC${R} = getX(batch, xR, xC, d1);
|
|
if (xC + 1 >= ${l}) {
|
|
xTexelC${R}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${R}Ready = 1;
|
|
}
|
|
|
|
xCOffset = xC + ${m};
|
|
if(xCOffset >= 0 && xCOffset < ${l} && xTexelC${R+2}Ready == 0) {
|
|
xTexelC${R+2} = getX(batch, xR, xCOffset, d1);
|
|
if (xCOffset + 1 >= ${l}) {
|
|
xTexelC${R+2}.zw = vec2(0.);
|
|
}
|
|
xTexelC${R+2}Ready = 1;
|
|
}
|
|
|
|
xC${$} = vec4(
|
|
xTexelC${R}.xy, xTexelC${R+2}.xy);
|
|
`,R+1<g&&(b+=`
|
|
xC${$+1} = vec4(xTexelC${R}.zw, xTexelC${R+2}.zw);
|
|
`)));$<g&&(b+=`
|
|
wTexel = getW(${A}, ${R}, d1, q);
|
|
dotProd += xC${$} * vec4(wTexel.xz, wTexel.xz);
|
|
`,R+1<g&&(b+=`
|
|
wTexel = getW(${A}, ${R+1}, d1, q);
|
|
dotProd += xC${$+1} * vec4(wTexel.xz, wTexel.xz);
|
|
`))}b+=`
|
|
}
|
|
`}let w="",_="";n&&(o?w=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:s?w=`vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${n}
|
|
}`:w=`vec4 activation(vec4 x) {
|
|
${n}
|
|
}`,_="result = activation(result);");let C=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${w}
|
|
|
|
const ivec2 strides = ivec2(${p}, ${m});
|
|
const ivec2 pads = ivec2(${u}, ${c});
|
|
|
|
void main() {
|
|
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int d2 = coords.w;
|
|
int d1 = d2 / ${a};
|
|
int q = d2 - d1 * ${a};
|
|
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);
|
|
|
|
${b}
|
|
|
|
vec4 result = dotProd - vec4(0.000000000000001);
|
|
${C}
|
|
${_}
|
|
setOutput(result);
|
|
}
|
|
`}};function T9(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,filter:s}=e,{strides:a,pad:i,dilations:l,dimRoundingMode:u}=n,c=l;c==null&&(c=[1,1]),y.assert(I.eitherStridesOrDilationsAreOne(a,c),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${c}'`);let p=I.computeConv2DInfo(o.shape,s.shape,a,c,i,u,!0),m;return W().getBool("WEBGL_PACK_DEPTHWISECONV")&&p.strideWidth<=2&&p.outChannels/p.inChannels==1?m=new hd(p):m=new dd(p),t.runWebGLProgram(m,[o,s],"float32")}var DF={kernelName:Vo,backendName:"webgl",kernelFunc:T9};var A0=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,a=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 * ${a} + 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);
|
|
}
|
|
`}},D0=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,o=e.strideHeight,s=e.strideWidth,a=t-1-e.padInfo.top,i=n-1-e.padInfo.left,l=e.outChannels/e.inChannels;this.userCode=`
|
|
const ivec2 pads = ivec2(${a}, ${i});
|
|
|
|
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 E9(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,dy:s}=e,{strides:a,dilations:i,pad:l,dimRoundingMode:u,filterShape:c}=n,p=I.computeConv2DInfo(o.shape,c,a,i,l,u,!0),m=new A0(p);return t.runWebGLProgram(m,[o,s],"float32")}var $F={kernelName:Zc,backendName:"webgl",kernelFunc:E9};function A9(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,filter:s}=e,{strides:a,dilations:i,pad:l,dimRoundingMode:u,inputShape:c}=n,p=I.computeConv2DInfo(c,s.shape,a,i,l,u,!0),m=new D0(p);return t.runWebGLProgram(m,[o,s],"float32")}var RF={kernelName:Jc,backendName:"webgl",kernelFunc:A9};var $0=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 D9(r){let{inputs:e,backend:t}=r,{x:n}=e,o=[...n.shape,...n.shape],s=y.sizeFromShape(n.shape),a=le({inputs:{x:n},backend:t,attrs:{shape:[s]}}),i=new $0(s),l=t.runWebGLProgram(i,[a],a.dtype),u=le({inputs:{x:l},backend:t,attrs:{shape:o}});return t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(l),u}var FF={kernelName:Qc,backendName:"webgl",kernelFunc:D9};var R0=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:n,padInfo:o,strideHeight:s,strideWidth:a,filterHeight:i,filterWidth:l,dilationHeight:u,dilationWidth:c}=e,{top:p,left:m}=o;this.userCode=`
|
|
const ivec2 strides = ivec2(${s}, ${a});
|
|
const ivec2 pads = ivec2(${p}, ${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 < ${i}; h++) {
|
|
int hIn = hBeg + h * ${u};
|
|
|
|
if (hIn >= 0 && hIn < ${t}) {
|
|
for (int w = 0; w < ${l}; w++) {
|
|
int wIn = wBeg + w * ${c};
|
|
|
|
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 $9(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,filter:s}=e,{strides:a,pad:i,dilations:l}=n,u=I.computeDilation2DInfo(o.shape,s.shape,a,i,"NHWC",l),c,p=new R0(u);c=t.runWebGLProgram(p,[o,s],"float32");let m=le({inputs:{x:c},backend:t,attrs:{shape:u.outShape}});return t.disposeIntermediateTensorInfo(c),m}var OF={kernelName:fl,backendName:"webgl",kernelFunc:$9};function R9(r){let{inputs:e,backend:t,attrs:n}=r,{equation:o}=n,s=e,{allDims:a,summedDims:i,idDims:l}=I.decodeEinsumEquation(o,s.length);I.checkEinsumDimSizes(a.length,l,s);let{path:u,steps:c}=I.getEinsumComputePath(i,l),p=c.length,m=null,f=a.length,d=[];for(let h=0;h<p;++h){for(let g of c[h]){let{permutationIndices:x,expandDims:b}=I.getEinsumPermutation(f,l[g]),w;I.isIdentityPermutation(x)?w=s[g]:(w=Ft({inputs:{x:s[g]},backend:t,attrs:{perm:x}}),d.push(w));let _=w.shape.slice();for(let C=0;C<b.length;++C)_.splice(b[C],0,1);y.arraysEqual(w.shape,_)||(w=le({inputs:{x:w},backend:t,attrs:{shape:_}}),d.push(w)),m===null?m=w:(m=md({inputs:{a:w,b:m},backend:t}),d.push(m))}h<p-1&&(u[h]>=0&&(m=uc({inputs:{x:m},backend:t,attrs:{axis:u[h]-(a.length-f),keepDims:!1}}),d.push(m)),f--)}for(let h of d)h!==m&&t.disposeIntermediateTensorInfo(h);return m}var PF={kernelName:ep,backendName:"webgl",kernelFunc:R9};var F9="return (x >= 0.0) ? x : (exp(x) - 1.0);",O9=`
|
|
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;
|
|
`,P9=ke({opSnippet:F9,packedOpSnippet:O9}),MF={kernelName:Ui,backendName:"webgl",kernelFunc:P9};var M9="return (b >= 1.0) ? a : a * (b + 1.0);",L9=`
|
|
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
|
|
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
|
|
`,z9=r=>{let{inputs:e,backend:t}=r,{dy:n,y:o}=e,s=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new zs(L9,n.shape,o.shape):new ko(M9,n.shape,o.shape);return t.runWebGLProgram(s,[n,o],n.dtype)},LF={kernelName:tp,backendName:"webgl",kernelFunc:z9};var B9=`
|
|
return vec4(equal(a, b));
|
|
`,V9="return float(a == b);",G9=it({opSnippet:V9,packedOpSnippet:B9,dtype:"bool",cpuKernelImpl:S$}),zF={kernelName:Hi,backendName:"webgl",kernelFunc:G9};var W9=`
|
|
// Error function is calculated approximately with elementary function.
|
|
// See "Handbook of Mathematical Functions with Formulas,
|
|
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
|
|
float p = ${I.ERF_P};
|
|
float a1 = ${I.ERF_A1};
|
|
float a2 = ${I.ERF_A2};
|
|
float a3 = ${I.ERF_A3};
|
|
float a4 = ${I.ERF_A4};
|
|
float a5 = ${I.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));
|
|
`,j9=ke({opSnippet:W9}),BF={kernelName:qi,backendName:"webgl",kernelFunc:j9};var VF="return exp(x);",F0=ke({opSnippet:VF,packedOpSnippet:VF,cpuKernelImpl:N$}),GF={kernelName:Wo,backendName:"webgl",kernelFunc:F0};function ay(r){let{inputs:e,attrs:t,backend:n}=r,{dim:o}=t,{input:s}=e,a=s.shape.length,i=s.shape.slice(),l=o;return o<0&&(y.assert(-(a+1)<=o,()=>`Axis must be in the interval [${-(a+1)}, ${a}]`),l=a+o+1),i.splice(l,0,1),le({inputs:{x:s},backend:n,attrs:{shape:i}})}var WF={kernelName:ei,backendName:"webgl",kernelFunc:ay};var jF="return exp(x) - 1.0;",U9=ke({opSnippet:jF,packedOpSnippet:jF,cpuKernelImpl:T$}),UF={kernelName:Ki,backendName:"webgl",kernelFunc:U9};var ly=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}`,a=n?`${o}.0`:"1.0",i;if(e==="real")i="return real * expR - imag * expI;";else if(e==="imag")i="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) {
|
|
${i}
|
|
}
|
|
|
|
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) / ${a};
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
setOutput(mulMatDFT(coords[0], coords[1]));
|
|
}
|
|
`}};function uy(r,e,t){let n=t.texData.get(r.dataId),o=y.sizeFromShape(r.shape),s=r.shape[r.shape.length-1],a=o/s,i=le({inputs:{x:r},backend:t,attrs:{shape:[a,s]}}),l=i.shape,u=new ly("real",l,e),c=new ly("imag",l,e),p=[{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,p,"float32"),f=t.runWebGLProgram(c,p,"float32"),d=Cn({inputs:{real:m,imag:f},backend:t});t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f);let h=le({inputs:{x:d},backend:t,attrs:{shape:r.shape}});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(d),h}function q9(r){let{inputs:e,backend:t}=r,{input:n}=e;return uy(n,!1,t)}var qF={kernelName:rp,backendName:"webgl",kernelFunc:q9};var O0=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 gd(r){let{backend:e,attrs:t}=r,{shape:n,value:o}=t,{dtype:s}=t;if(s=s||y.inferDtype(o),s==="string"){let a=y.getArrayFromDType(s,y.sizeFromShape(n));return a.fill(o),e.makeTensorInfo(n,s,a)}else{let a=new O0(n,o),i=a.getCustomSetupFunc(o);return e.runWebGLProgram(a,[],s,i)}}var HF={kernelName:dl,backendName:"webgl",kernelFunc:gd};var P0=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 KF={kernelName:Xi,backendName:"webgl",kernelFunc:({inputs:r,backend:e})=>{let{image:t}=r,n=e,o=new P0(t.shape);return n.runWebGLProgram(o,[t],t.dtype)}};var XF="return floor(x);",H9=ke({opSnippet:XF,packedOpSnippet:XF,cpuKernelImpl:E$}),YF={kernelName:jo,backendName:"webgl",kernelFunc:H9};var K9=`
|
|
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;
|
|
}
|
|
`,X9=`
|
|
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);
|
|
`,Y9=it({opSnippet:K9,packedOpSnippet:X9,dtype:"int32"}),ZF={kernelName:Uo,backendName:"webgl",kernelFunc:Y9};var M0=class{constructor(e){this.variableNames=["A"];let t=Lt(),[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 L0=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=Lt(),[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 JF={kernelName:of,backendName:"webgl",kernelFunc:Z9},om;function Z9(r){let{inputs:e,backend:t,attrs:n}=r,{pixels:o}=e,{numChannels:s}=n,a=typeof HTMLVideoElement!="undefined"&&o instanceof HTMLVideoElement,i=typeof HTMLImageElement!="undefined"&&o instanceof HTMLImageElement,[l,u]=a?[o.videoWidth,o.videoHeight]:[o.width,o.height],c=[u,l],p=[u,l,s];(i||a)&&(om==null&&(om=document.createElement("canvas").getContext("2d")),om.canvas.width=l,om.canvas.height=u,om.drawImage(o,0,0,l,u),o=om.canvas);let m=t.makeTensorInfo(c,"int32");t.texData.get(m.dataId).usage=Vr.PIXELS,t.gpgpu.uploadPixelDataToTexture(t.getTexture(m.dataId),o);let f=W().getBool("WEBGL_PACK")?new L0(p):new M0(p),d=t.runWebGLProgram(f,[m],"int32");return t.disposeData(m.dataId),d}function J9(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,filter:s,bias:a,preluActivationWeights:i}=e,{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=n,h=I.convertConv2DDataFormat(c),g=I.computeConv2DInfo(o.shape,s.shape,l,p,u,m,!1,h),x,b=[];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"))x=oy({x:o,filter:s,convInfo:g,backend:t,bias:a,activation:f,preluActivationWeights:i,leakyreluAlpha:d});else if(W().getBool("WEBGL_CONV_IM2COL")&&o.shape[0]===1)x=sy({x:o,filter:s,convInfo:g,backend:t,bias:a,activation:f,preluActivationWeights:i,leakyreluAlpha:d});else{let _=a!=null,C=i!=null,A=f==="leakyrelu",D=f?Pl(f,!1):null,$=new fd(g,_,D,C,A),R=[o,s];if(a&&R.push(a),i&&R.push(i),A){let M=t.makeTensorInfo([],"float32",y.createScalarValue(d,"float32"));R.push(M),b.push(M)}x=t.runWebGLProgram($,R,"float32")}let w=le({inputs:{x},backend:t,attrs:{shape:g.outShape}});return b.push(x),b.forEach(_=>t.disposeIntermediateTensorInfo(_)),w}var QF={kernelName:mi,backendName:"webgl",kernelFunc:J9};function Q9(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,filter:s,bias:a,preluActivationWeights:i}=e,{strides:l,pad:u,dilations:c,dimRoundingMode:p,activation:m,leakyreluAlpha:f}=n,d=[],h=c;h==null&&(h=[1,1]),y.assert(I.eitherStridesOrDilationsAreOne(l,h),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${h}'`);let g=I.computeConv2DInfo(o.shape,s.shape,l,h,u,p,!0),x=W().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,b=m?Pl(m,x):null,w=[o,s],_=a!=null,C=i!=null,A=m==="leakyrelu";if(_&&w.push(a),C&&w.push(i),A){let R=t.makeTensorInfo([],"float32",y.createScalarValue(f,"float32"));w.push(R),d.push(R)}let D;x?D=new hd(g,_,b,C,A):D=new dd(g,_,b,C,A);let $=t.runWebGLProgram(D,w,"float32");return d.forEach(R=>t.disposeIntermediateTensorInfo(R)),$}var eO={kernelName:fi,backendName:"webgl",kernelFunc:Q9};var z0=class{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;let o=Ge(t.length),s=Ge(n.length),a=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 * ${a};
|
|
}
|
|
setOutput(getX(flattenIndex, coords[1]));
|
|
}
|
|
`}};function eZ(r){let{inputs:e,backend:t}=r,{params:n,indices:o}=e,s=o.shape,a=s[s.length-1],i=y.sizeFromShape(n.shape),[l,u,c,p]=I.prepareAndValidate(n,o),m=le({inputs:{x:o},backend:t,attrs:{shape:[u,a]}}),f=le({inputs:{x:n},backend:t,attrs:{shape:[y.sizeFromShape(n.shape)/c,c]}});if(t.shouldExecuteOnCPU([n,o])||n.dtype==="string"){let x=t.readSync(o.dataId),b=t.bufferSync(n),w=A$(x,b,n.dtype,u,a,c,p,n.shape,i);return t.makeTensorInfo(l,n.dtype,w.values)}let d=new z0(a,p,[u,c]),h=t.runWebGLProgram(d,[f,m],f.dtype),g=le({inputs:{x:h},backend:t,attrs:{shape:l}});return t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(h),g}var tO={kernelName:Yi,backendName:"webgl",kernelFunc:eZ};var B0=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let n=Ge(this.rank),o=tZ(e,2);this.userCode=`
|
|
void main() {
|
|
${n} resRC = getOutputCoords();
|
|
setOutput(getA(${o}));
|
|
}
|
|
`}};function tZ(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 rZ(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,indices:s}=e,{axis:a,batchDims:i}=n,l=y.parseAxisParam(a,o.shape)[0],u=I.segment_util.collectGatherOpShapeInfo(o,s,l,i),c=y.sizeFromShape(s.shape),p=[],m=le({inputs:{x:o},backend:t,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),f=le({inputs:{x:s},backend:t,attrs:{shape:[u.batchSize,c/u.batchSize]}});p.push(m),p.push(f);let d=[u.batchSize,u.outerSize,c/u.batchSize,u.sliceSize];if(t.shouldExecuteOnCPU([o,s])||o.dtype==="string"){let b=t.bufferSync(f),w=t.bufferSync(m),_=D$(w,b,d);return p.forEach(C=>t.disposeIntermediateTensorInfo(C)),t.makeTensorInfo(u.outputShape,_.dtype,_.values)}let h=new B0(m.shape,d),g=t.runWebGLProgram(h,[m,f],m.dtype);p.push(g);let x=le({inputs:{x:g},backend:t,attrs:{shape:u.outputShape}});return p.forEach(b=>t.disposeIntermediateTensorInfo(b)),x}var rO={kernelName:ti,backendName:"webgl",kernelFunc:rZ};var nZ="return float(a > b);",oZ=`
|
|
return vec4(greaterThan(a, b));
|
|
`,sZ=it({opSnippet:nZ,packedOpSnippet:oZ,cpuKernelImpl:$$,dtype:"bool"}),nO={kernelName:Zi,backendName:"webgl",kernelFunc:sZ};var iZ="return float(a >= b);",aZ=`
|
|
return vec4(greaterThanEqual(a, b));
|
|
`,lZ=it({opSnippet:iZ,packedOpSnippet:aZ,dtype:"bool",cpuKernelImpl:R$}),oO={kernelName:Ho,backendName:"webgl",kernelFunc:lZ};function uZ(r){let{inputs:e,backend:t}=r,{input:n}=e;return uy(n,!0,t)}var sO={kernelName:np,backendName:"webgl",kernelFunc:uZ};var cZ="return float(!isnan(x) && !isinf(x));",pZ=ke({opSnippet:cZ,dtype:"bool"}),iO={kernelName:Ji,backendName:"webgl",kernelFunc:pZ};var mZ="return float(isinf(x));",fZ=ke({opSnippet:mZ,dtype:"bool"}),aO={kernelName:Qi,backendName:"webgl",kernelFunc:fZ};var dZ="return float(isnan(x));",hZ=ke({opSnippet:dZ,dtype:"bool"}),lO={kernelName:ea,backendName:"webgl",kernelFunc:hZ};var gZ="return float(a < b);",xZ=`
|
|
return vec4(lessThan(a, b));
|
|
`,yZ=it({opSnippet:gZ,packedOpSnippet:xZ,cpuKernelImpl:F$,dtype:"bool"}),uO={kernelName:ta,backendName:"webgl",kernelFunc:yZ};var bZ="return float(a <= b);",wZ=`
|
|
return vec4(lessThanEqual(a, b));
|
|
`,_Z=it({opSnippet:bZ,packedOpSnippet:wZ,cpuKernelImpl:O$,dtype:"bool"}),cO={kernelName:ra,backendName:"webgl",kernelFunc:_Z};function kZ(r){let{backend:e,attrs:t}=r,{start:n,stop:o,num:s}=t,a=P$(n,o,s);return e.makeTensorInfo([a.length],"float32",a)}var pO={kernelName:sp,backendName:"webgl",kernelFunc:kZ};var vZ=`if (x < 0.0) return NAN;
|
|
return log(x);`,CZ=`
|
|
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;
|
|
`,IZ=ke({opSnippet:vZ,packedOpSnippet:CZ,cpuKernelImpl:M$}),mO={kernelName:Xo,backendName:"webgl",kernelFunc:IZ};var SZ="return log(1.0 + x);",NZ=ke({opSnippet:SZ}),fO={kernelName:na,backendName:"webgl",kernelFunc:NZ};var TZ="return float(a >= 1.0 && b >= 1.0);",EZ=`
|
|
return vec4(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) *
|
|
vec4(greaterThanEqual(b, vec4(1.0))));
|
|
`,AZ=it({opSnippet:TZ,packedOpSnippet:EZ,dtype:"bool"}),dO={kernelName:oa,backendName:"webgl",kernelFunc:AZ};var DZ="return float(!(x >= 1.0));",$Z=ke({opSnippet:DZ}),hO={kernelName:iu,backendName:"webgl",kernelFunc:$Z};var RZ="return float(a >= 1.0 || b >= 1.0);",FZ=`
|
|
return min(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) +
|
|
vec4(greaterThanEqual(b, vec4(1.0))),
|
|
vec4(1.0));
|
|
`,OZ=it({opSnippet:RZ,packedOpSnippet:FZ,dtype:"bool"}),gO={kernelName:au,backendName:"webgl",kernelFunc:OZ};var V0=class{constructor(e,t,n,o,s){this.variableNames=["x"],this.outputShape=[];let a=t,i=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 = -${a}; j <= ${a}; j++) {
|
|
int idx = d + j;
|
|
if (idx >= 0 && idx <= ${i}) {
|
|
float z = getX(b, r, c, idx);
|
|
sum += z * z;
|
|
}
|
|
}
|
|
float val = x * ${l};
|
|
setOutput(val);
|
|
}
|
|
`}};var G0=class{constructor(e,t,n,o,s){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let a=t,i=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 - ${a};
|
|
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 = - ${a}; j <= ${a}; j++) {
|
|
ivec2 idx = depth + j;
|
|
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
|
|
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${i}));
|
|
|
|
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 PZ=r=>{let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{depthRadius:s,bias:a,alpha:i,beta:l}=n,u=W().getBool("WEBGL_PACK_NORMALIZATION")?new G0(o.shape,s,a,i,l):new V0(o.shape,s,a,i,l);return t.runWebGLProgram(u,[o],o.dtype)},xO={kernelName:hl,backendName:"webgl",kernelFunc:PZ};var W0=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 MZ=r=>{let{inputs:e,backend:t,attrs:n}=r,{x:o,y:s,dy:a}=e,{depthRadius:i,bias:l,alpha:u,beta:c}=n,p=new W0(o.shape,i,l,u,c);return t.runWebGLProgram(p,[o,s,a],o.dtype)},yO={kernelName:ip,backendName:"webgl",kernelFunc:MZ};function bO(r,e,t,n){let o=y.sizeFromShape(e),a=y.sizeFromShape(r.shape)/o,i=le({inputs:{x:r},attrs:{shape:[a,o]},backend:n}),l=Ln(i,r.dtype,"max",n),u=le({inputs:{x:l},attrs:{shape:t},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),u}function j0(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{reductionIndices:s,keepDims:a}=n,i=o.shape.length,l=y.parseAxisParam(s,o.shape),u=l,c=I.getAxesPermutation(u,i),p=c!=null,m=t.shouldExecuteOnCPU([o]),f=o;if(p){if(m){let w=t.texData.get(f.dataId).values,_=new Array(i);for(let D=0;D<_.length;D++)_[D]=o.shape[c[D]];let C=ac(w,o.shape,o.dtype,c,_);f=t.makeTensorInfo(_,o.dtype);let A=t.texData.get(f.dataId);A.values=C}else f=Ml(o,c,t);u=I.getInnerMostAxes(u.length,i)}I.assertAxesAreInnerMostDims("max",u,i);let[d,h]=I.computeOutAndReduceShapes(f.shape,u),g=d;a&&(g=I.expandShapeToKeepDim(d,l));let x;if(m){let w=t.texData.get(f.dataId).values,_=L$(w,y.sizeFromShape(h),g,o.dtype);x=t.makeTensorInfo(g,o.dtype);let C=t.texData.get(x.dataId);C.values=_}else x=bO(f,h,g,t);return p&&t.disposeIntermediateTensorInfo(f),x}var wO={kernelName:Yo,backendName:"webgl",kernelFunc:j0};var LZ=Zx+`
|
|
return max(a, b);
|
|
`,zZ=`
|
|
vec4 result = vec4(max(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+Ol+`
|
|
return result;
|
|
`,BZ=it({opSnippet:LZ,packedOpSnippet:zZ,cpuKernelImpl:z$}),_O={kernelName:Zo,backendName:"webgl",kernelFunc:BZ};function VZ(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e;Ps(o,"maxPool");let{filterSize:s,strides:a,pad:i,dimRoundingMode:l}=n,u=1;y.assert(I.eitherStridesOrDilationsAreOne(a,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let c=I.computePool2DInfo(o.shape,s,a,u,i,l);if(c.filterWidth===1&&c.filterHeight===1&&y.arraysEqual(c.inShape,c.outShape))return Yt({inputs:{x:o},backend:t});let p=new _i(c,"max",!1);return t.runWebGLProgram(p,[o],o.dtype)}var kO={kernelName:Jo,backendName:"webgl",kernelFunc:VZ};function GZ(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{filterSize:s,strides:a,pad:i,dataFormat:l,dimRoundingMode:u}=n,c=[1,1,1],p=I.computePool3DInfo(o.shape,s,a,c,i,u,l),m=new pc(p,"max",!1);return t.runWebGLProgram(m,[o],o.dtype)}var vO={kernelName:gl,backendName:"webgl",kernelFunc:GZ};var U0=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,n=e.strideWidth,o=e.dilationHeight,s=e.effectiveFilterHeight,a=e.effectiveFilterWidth,i=s-1-e.padInfo.top,l=a-1-e.padInfo.left,u=s*a-1;this.userCode=`
|
|
const ivec2 pads = ivec2(${i}, ${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 < ${a}; 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 * ${a} + wC;
|
|
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
|
|
|
dotProd += dyValue * mask;
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},q0=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,n=e.strideHeight,o=e.strideWidth,s=e.dilationDepth,a=e.dilationHeight,i=e.dilationWidth,l=e.effectiveFilterDepth,u=e.effectiveFilterHeight,c=e.effectiveFilterWidth,p=l-1-e.padInfo.front,m=u-1-e.padInfo.top,f=c-1-e.padInfo.left,d=l*u*c-1;this.userCode=`
|
|
const ivec3 pads = ivec3(${p}, ${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 += ${a}) {
|
|
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 < ${c};
|
|
wC += ${i}) {
|
|
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} * ${c} +
|
|
wR * ${c} + wC;
|
|
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
|
|
|
dotProd += dyValue * mask;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function WZ(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,input:s}=e,a=s,{filterSize:i,strides:l,pad:u,dimRoundingMode:c}=n,p=[1,1,1],m=I.computePool3DInfo(a.shape,i,l,p,u,c),f=new pc(m,"max",!0),d=t.runWebGLProgram(f,[a],a.dtype),h=new q0(m),g=t.runWebGLProgram(h,[o,d],a.dtype);return t.disposeIntermediateTensorInfo(d),g}var CO={kernelName:lp,backendName:"webgl",kernelFunc:WZ};function jZ(r){let{inputs:e,backend:t,attrs:n}=r,{dy:o,input:s,output:a}=e,i=s;Ps([s,a],"maxPoolGrad");let{filterSize:l,strides:u,pad:c,dimRoundingMode:p}=n,m=I.computePool2DInfo(i.shape,l,u,1,c,p),f=!0,d=new _i(m,"max",f),h=t.runWebGLProgram(d,[i],i.dtype),g=new U0(m),x=t.runWebGLProgram(g,[o,h],i.dtype);return t.disposeIntermediateTensorInfo(h),x}var IO={kernelName:ap,backendName:"webgl",kernelFunc:jZ};function SO(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 a=n.runWebGLProgram(o,[r],"float32");return[s,a]}var NO={kernelName:up,backendName:"webgl",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{x:n}=r,{filterSize:o,strides:s,pad:a,includeBatchInIndex:i}=e,l=t;y.assert(n.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${n.shape.length}.`);let u=[1,1];y.assert(I.eitherStridesOrDilationsAreOne(s,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${u}'`);let c=I.computePool2DInfo(n.shape,o,s,u,a),[p,m]=SO(n,i,c,l);return[p,m]}};function TO(r,e,t,n){let o=y.sizeFromShape(e),a=y.sizeFromShape(r.shape)/o,i=le({inputs:{x:r},attrs:{shape:[a,o]},backend:n}),l=Ln(i,"float32","mean",n),u=le({inputs:{x:l},attrs:{shape:t},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),u}var EO={kernelName:Qo,backendName:"webgl",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{x:n}=r,{keepDims:o,axis:s}=e,a=t,i=n.shape.length,l=y.parseAxisParam(s,n.shape),u=l,c=I.getAxesPermutation(u,i),p=c!=null,m=a.shouldExecuteOnCPU([n]),f=[],d=n;if(p){if(m){let _=a.texData.get(d.dataId).values,C=new Array(i);for(let $=0;$<C.length;$++)C[$]=n.shape[c[$]];let A=ac(_,n.shape,n.dtype,c,C);d=a.makeTensorInfo(C,n.dtype);let D=a.texData.get(d.dataId);D.values=A}else d=Ml(n,c,a);f.push(d),u=I.getInnerMostAxes(u.length,i)}I.assertAxesAreInnerMostDims("sum",u,i);let[h,g]=I.computeOutAndReduceShapes(d.shape,u),x=h;o&&(x=I.expandShapeToKeepDim(h,l));let b=TO(d,g,x,a);for(let w of f)a.disposeIntermediateTensorInfo(w);return b}};function UZ(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,keepDims:a}=n,i=o.shape.length,l=y.parseAxisParam(s,o.shape),u=l,c=I.getAxesPermutation(u,i),p=o;c!=null&&(p=Ft({inputs:{x:o},backend:t,attrs:{perm:c}}),u=I.getInnerMostAxes(u.length,o.shape.length)),I.assertAxesAreInnerMostDims("min",u,i);let[m,f]=I.computeOutAndReduceShapes(p.shape,u),d=y.sizeFromShape(f),h=le({inputs:{x:p},backend:t,attrs:{shape:[-1,d]}}),g=Ln(h,h.dtype,"min",t),x;if(a){let b=I.expandShapeToKeepDim(m,l);x=le({inputs:{x:g},backend:t,attrs:{shape:b}})}else x=le({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),c!=null&&t.disposeIntermediateTensorInfo(p),x}var AO={kernelName:es,backendName:"webgl",kernelFunc:UZ};var qZ=Zx+`
|
|
return min(a, b);
|
|
`,HZ=`
|
|
vec4 result = vec4(min(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+Ol+`
|
|
return result;
|
|
`,KZ=it({opSnippet:qZ,packedOpSnippet:HZ,cpuKernelImpl:B$}),DO={kernelName:ts,backendName:"webgl",kernelFunc:KZ};var H0=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((c,p)=>c[0]+e[p]+c[1]);let o=e.length,s=Ge(o),a=t.map(c=>c[0]).join(","),i=t.map((c,p)=>c[0]+e[p]).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 = ${a};
|
|
int end = ${i};
|
|
|
|
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}(${a});
|
|
${s} end = ${s}(${i});
|
|
|
|
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 K0=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=Ge(o),a=t.map(d=>d[0]).join(","),i=t.map((d,h)=>d[0]+e[h]).join(","),l=Xt("rc",o),u=Xt("source",o),c=`${l[o-1]} < ${this.outputShape[o-1]}`,p=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()}), ${p});
|
|
${l[o-1]} += 1;
|
|
if(${c}) {
|
|
${d}
|
|
result[1] = getChannel(getX(${u.join()}), ${p});
|
|
}
|
|
`}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()}), ${p});
|
|
${l[o-1]} += 1;
|
|
if(${c}) {
|
|
${d}
|
|
result[1] = getChannel(getX(${u.join()}), ${p});
|
|
}
|
|
rc = outputLoc;
|
|
${l[o-2]} += 1;
|
|
if(${l[o-2]} < ${this.outputShape[o-2]}) {
|
|
${d}
|
|
result[2] = getChannel(getX(${u.join()}), ${p});
|
|
${l[o-1]} += 1;
|
|
if(${c}) {
|
|
${d}
|
|
result[3] = getChannel(getX(${u.join()}), ${p});
|
|
}
|
|
}
|
|
`}this.userCode=`
|
|
const ${s} start = ${s}(${a});
|
|
const ${s} end = ${s}(${i});
|
|
|
|
void main() {
|
|
${s} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${f}
|
|
setOutput(result);
|
|
}
|
|
`}};var XZ=({inputs:r,backend:e,attrs:t})=>{let{x:n}=r,{paddings:o,mode:s}=t,a=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new K0(n.shape,o,s):new H0(n.shape,o,s);return e.runWebGLProgram(a,[n],n.dtype)},$O={kernelName:rs,backendName:"webgl",kernelFunc:XZ};var YZ=`if (b == 0.0) return NAN;
|
|
return mod(a, b);`,ZZ=`
|
|
vec4 result = mod(a, b);
|
|
vec4 isNaN = vec4(equal(b, vec4(0.0)));
|
|
`+Ol+`
|
|
return result;
|
|
`,JZ=it({opSnippet:YZ,packedOpSnippet:ZZ}),RO={kernelName:sa,backendName:"webgl",kernelFunc:JZ};var X0=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 QZ=`
|
|
if (a == b) {
|
|
return 1.0;
|
|
};
|
|
return a / b;`,eJ=`
|
|
// 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;
|
|
`,Y0=it({opSnippet:QZ,packedOpSnippet:eJ,checkOutOfBounds:!0}),FO={kernelName:Go,backendName:"webgl",kernelFunc:Y0};var OO="return a - b;",Z0=it({opSnippet:OO,packedOpSnippet:OO,supportsComplex:!0,cpuKernelImpl:eR}),PO={kernelName:ws,backendName:"webgl",kernelFunc:Z0};function J0(r){let{inputs:e,backend:t,attrs:n}=r,{logits:o}=e,{dim:s}=n,a=y.parseAxisParam([s],o.shape),i=j0({inputs:{x:o},backend:t,attrs:{reductionIndices:a,keepDims:!1}}),l=I.expandShapeToKeepDim(i.shape,a),u=le({inputs:{x:i},backend:t,attrs:{shape:l}}),c=Z0({inputs:{a:o,b:u},backend:t}),p=F0({inputs:{x:c},backend:t}),m=uc({inputs:{x:p},backend:t,attrs:{axis:a,keepDims:!1}}),f=le({inputs:{x:m},backend:t,attrs:{shape:l}}),d=Y0({inputs:{a:p,b:f},backend:t});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(u),t.disposeIntermediateTensorInfo(c),t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f),d}var MO={kernelName:ys,backendName:"webgl",kernelFunc:J0};function tJ(r){let{inputs:e,backend:t,attrs:n}=r,{logits:o}=e,{numSamples:s,seed:a,normalized:i}=n,l=i?o:J0({inputs:{logits:o},backend:t,attrs:{dim:o.shape.length-1}}),u=l.shape[0],c=l.shape[1],p=new X0(u,c,s),m=p.getCustomSetupFunc(a),f=t.runWebGLProgram(p,[l],"int32",m);return i||t.disposeIntermediateTensorInfo(l),f}var LO={kernelName:cp,backendName:"webgl",kernelFunc:tJ};var zO="return -x;";function rJ(r){let{inputs:e,backend:t}=r,{x:n}=e;if(t.shouldExecuteOnCPU([n])){let s=t.texData.get(n.dataId),[a,i]=G$(s.values,n.shape,n.dtype);return t.makeTensorInfo(i,n.dtype,a)}let o;return W().getBool("WEBGL_PACK_UNARY_OPERATIONS")?o=new Ls(n.shape,zO):o=new vn(n.shape,zO),t.runWebGLProgram(o,[n],n.dtype)}var BO={kernelName:ri,backendName:"webgl",kernelFunc:rJ};var nJ=zr.nonMaxSuppressionV3Impl;function oJ(r){I.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:a,iouThreshold:i,scoreThreshold:l}=n,u=t.readSync(o.dataId),c=t.readSync(s.dataId),{selectedIndices:p}=nJ(u,c,a,i,l);return t.makeTensorInfo([p.length],"int32",new Int32Array(p))}var VO={kernelName:aa,backendName:"webgl",kernelFunc:oJ};var sJ=zr.nonMaxSuppressionV4Impl;function iJ(r){I.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:a,iouThreshold:i,scoreThreshold:l,padToMaxOutputSize:u}=n,c=t.readSync(o.dataId),p=t.readSync(s.dataId),{selectedIndices:m,validOutputs:f}=sJ(c,p,a,i,l,u);return[t.makeTensorInfo([m.length],"int32",new Int32Array(m)),t.makeTensorInfo([],"int32",new Int32Array([f]))]}var GO={kernelName:la,backendName:"webgl",kernelFunc:iJ};var aJ=zr.nonMaxSuppressionV5Impl;function lJ(r){I.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:a,iouThreshold:i,scoreThreshold:l,softNmsSigma:u}=n,c=t.readSync(o.dataId),p=t.readSync(s.dataId),m=a,f=i,d=l,h=u,{selectedIndices:g,selectedScores:x}=aJ(c,p,m,f,d,h);return[t.makeTensorInfo([g.length],"int32",new Int32Array(g)),t.makeTensorInfo([x.length],"float32",new Float32Array(x))]}var WO={kernelName:ua,backendName:"webgl",kernelFunc:lJ};var Q0=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 uJ=r=>{let{inputs:e,backend:t,attrs:n}=r,{indices:o}=e,{depth:s,onValue:a,offValue:i}=n,l=y.sizeFromShape(o.shape),u=new Q0(l,s,a,i),c=le({inputs:{x:o},backend:t,attrs:{shape:[l]}}),p=t.runWebGLProgram(u,[c],o.dtype);t.disposeIntermediateTensorInfo(c);let m=[...o.shape,s],f=le({inputs:{x:p},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(p),f},jO={kernelName:os,backendName:"webgl",kernelFunc:uJ};function xd(r){let{inputs:e,backend:t}=r,{x:n}=e;if(n.dtype==="complex64"){let o=Ha({inputs:{input:n},backend:t}),s=xd({inputs:{x:o},backend:t}),a=mc({inputs:{input:n},backend:t}),i=xd({inputs:{x:a},backend:t}),l=Cn({inputs:{real:s,imag:i},backend:t});return t.disposeIntermediateTensorInfo(o),t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),l}else return gd({attrs:{shape:n.shape,dtype:n.dtype,value:n.dtype==="string"?"":0},backend:t})}var UO={kernelName:ci,backendName:"webgl",kernelFunc:xd};function qO(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=Ha({inputs:{input:n},backend:t}),s=qO({inputs:{x:o},backend:t}),a=mc({inputs:{input:n},backend:t}),i=xd({inputs:{x:a},backend:t}),l=Cn({inputs:{real:s,imag:i},backend:t});return t.disposeIntermediateTensorInfo(o),t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),l}else return gd({attrs:{shape:n.shape,dtype:n.dtype,value:1},backend:t})}var HO={kernelName:ni,backendName:"webgl",kernelFunc:qO};function cJ(r){let{inputs:e,backend:t,attrs:n}=r,{axis:o}=n;if(e.length===1)return ay({inputs:{input:e[0]},backend:t,attrs:{dim:o}});let s=e[0].shape,a=e[0].dtype;e.forEach(c=>{y.assertShapesMatch(s,c.shape,"All tensors passed to stack must have matching shapes"),y.assert(a===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=e.map(c=>{let p=ay({inputs:{input:c},backend:t,attrs:{dim:o}});return i.push(p),p}),u=_0({inputs:l,backend:t,attrs:{axis:o}});return i.forEach(c=>t.disposeIntermediateTensorInfo(c)),u}var KO={kernelName:oi,backendName:"webgl",kernelFunc:cJ};var eC=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((u,c)=>u[0]+e[c]+u[1]);let o=e.length,s=Ge(o),a=t.map(u=>u[0]).join(","),i=t.map((u,c)=>u[0]+e[c]).join(","),l=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,o);if(o===1){this.userCode=`
|
|
int start = ${a};
|
|
int end = ${i};
|
|
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}(${a});
|
|
${s} end = ${s}(${i});
|
|
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 tC=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=Ge(o),a=t.map(h=>h[0]).join(","),i=t.map((h,g)=>h[0]+e[g]).join(","),l=Xt("rc",o),u=Xt("source",o),c=`${l[o-1]} < ${this.outputShape[o-1]}`,p=o===1?"source":`vec2(${u.slice(-2).join()})`,m=[`${s} rc = outputLoc;`,`${l[o-1]} += 1;
|
|
if(${c}) {
|
|
`,o===1?"":`}
|
|
rc = outputLoc;
|
|
${l[o-2]} += 1;
|
|
if(${l[o-2]} < ${this.outputShape[o-2]}) {`,o===1?"":` ${l[o-1]} += 1;
|
|
if(${c}) {`],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()}), ${p});
|
|
}
|
|
`;d+=o===1?"} ":"}}",this.userCode=`
|
|
const ${s} start = ${s}(${a});
|
|
const ${s} end = ${s}(${i});
|
|
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 rC=r=>{let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{paddings:s,constantValue:a}=n,i=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new tC(o.shape,s,a):new eC(o.shape,s,a),l=i.getCustomSetupFunc(a);return t.runWebGLProgram(i,[o],o.dtype,l)},XO={kernelName:ss,backendName:"webgl",kernelFunc:rC};var pJ=`
|
|
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);
|
|
`,mJ=`
|
|
// 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));
|
|
`+Ol+`
|
|
return result;
|
|
`,fJ=it({opSnippet:pJ,packedOpSnippet:mJ}),YO={kernelName:is,backendName:"webgl",kernelFunc:fJ};function dJ(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,keepDims:a}=n,i=o.shape.length,l=[],u=y.parseAxisParam(s,o.shape),c=u,p=I.getAxesPermutation(c,i),m=o;p!=null&&(m=Ft({inputs:{x:o},backend:t,attrs:{perm:p}}),c=I.getInnerMostAxes(c.length,i),l.push(m)),I.assertAxesAreInnerMostDims("prod",c,i);let f;if(t.shouldExecuteOnCPU([m])){let d=t.texData.get(m.dataId).values,{outVals:h,outShape:g,outDtype:x}=j$(m.shape,m.dtype,d,c);f=t.makeTensorInfo(g,x,h)}else{let[d,h]=I.computeOutAndReduceShapes(m.shape,c),g=y.sizeFromShape(h),x=le({inputs:{x:m},backend:t,attrs:{shape:[-1,g]}}),b=du(o.dtype),w=Ln(x,b,"prod",t);f=le({inputs:{x:w},backend:t,attrs:{shape:d}}),l.push(x),l.push(w)}if(a){l.push(f);let d=I.expandShapeToKeepDim(f.shape,u);f=le({inputs:{x:f},backend:t,attrs:{shape:d}})}return l.forEach(d=>t.disposeIntermediateTensorInfo(d)),f}var ZO={kernelName:ca,backendName:"webgl",kernelFunc:dJ};var nC=r=>{let{backend:e,attrs:t}=r,{start:n,stop:o,step:s,dtype:a}=t,i=U$(n,o,s,a);return e.makeTensorInfo([i.length],a,i)},JO={kernelName:xl,backendName:"webgl",kernelFunc:nC};var hJ="return 1.0 / x;",gJ=ke({opSnippet:hJ}),QO={kernelName:pa,backendName:"webgl",kernelFunc:gJ};var xJ=kr+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,yJ=`
|
|
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;
|
|
`,bJ=ke({opSnippet:xJ,packedOpSnippet:yJ}),eP={kernelName:ls,backendName:"webgl",kernelFunc:bJ};var wJ=kr+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,_J=`
|
|
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;
|
|
`,kJ=ke({opSnippet:wJ,packedOpSnippet:_J}),tP={kernelName:cs,backendName:"webgl",kernelFunc:kJ};var oC=class{constructor(e,t,n,o,s){this.variableNames=["A"],this.outputShape=[];let[a,i,l,u]=e;this.outputShape=[a,t,n,u];let c=[o&&t>1?i-1:i,o&&n>1?l-1:l],p=[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(
|
|
${c[0]/p[0]},
|
|
${c[1]/p[1]});
|
|
const vec2 inputShapeRC = vec2(${i}.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 sC=class{constructor(e,t,n,o,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,i,l,u]=e;this.outputShape=[a,t,n,u];let c=[o&&t>1?i-1:i,o&&n>1?l-1:l],p=[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(
|
|
${c[0]/p[0]},
|
|
${c[1]/p[1]},
|
|
${c[1]/p[1]});
|
|
const vec3 inputShapeRC = vec3(${i}.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 vJ(r){let{inputs:e,backend:t,attrs:n}=r,{images:o}=e,{alignCorners:s,halfPixelCenters:a,size:i}=n,[l,u]=i,c=W().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new sC(o.shape,l,u,s,a):new oC(o.shape,l,u,s,a);return t.runWebGLProgram(c,[o],"float32")}var rP={kernelName:us,backendName:"webgl",kernelFunc:vJ};var iC=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,o,s]=t,[,a,i]=e,l=[n&&a>1?o-1:o,n&&i>1?s-1:s],u=[n&&a>1?a-1:a,n&&i>1?i-1:i],c=l[0]/u[0],p=l[1]/u[1],m=1/c,f=1/p,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(${c});
|
|
const float widthScale = float(${p});
|
|
|
|
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 >= ${a}) {
|
|
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 >= ${i}) {
|
|
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 CJ(r){let{inputs:e,backend:t,attrs:n}=r,{images:o,dy:s}=e,{alignCorners:a}=n,i=new iC(s.shape,o.shape,a);return t.runWebGLProgram(i,[s],s.dtype)}var nP={kernelName:fp,backendName:"webgl",kernelFunc:CJ};var aC=class{constructor(e,t,n,o,s){this.variableNames=["A"],this.outputShape=[];let[a,i,l,u]=e;this.outputShape=[a,t,n,u];let c=[o&&t>1?i-1:i,o&&n>1?l-1:l],p=[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(
|
|
${c[0]/p[0]},
|
|
${c[1]/p[1]});
|
|
const vec2 inputShapeRC = vec2(${i}.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 lC=class{constructor(e,t,n,o,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,i,l,u]=e;this.outputShape=[a,t,n,u];let c=[o&&t>1?i-1:i,o&&n>1?l-1:l],p=[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(
|
|
${c[0]/p[0]},
|
|
${c[1]/p[1]},
|
|
${c[1]/p[1]});
|
|
const vec3 inputShapeRC = vec3(${i}.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 IJ(r){let{inputs:e,backend:t,attrs:n}=r,{images:o}=e,{alignCorners:s,halfPixelCenters:a,size:i}=n,[l,u]=i,c=W().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new lC(o.shape,l,u,s,a):new aC(o.shape,l,u,s,a);return t.runWebGLProgram(c,[o],o.dtype)}var oP={kernelName:yl,backendName:"webgl",kernelFunc:IJ};var uC=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,o,s]=t,[,a,i]=e,l=[n&&a>1?o-1:o,n&&i>1?s-1:s],u=[n&&a>1?a-1:a,n&&i>1?i-1:i],c=l[0]/u[0],p=l[1]/u[1],m=1/c,f=1/p,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(${c});
|
|
const float widthScale = float(${p});
|
|
|
|
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 >= ${a}) {
|
|
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 >= ${i}) {
|
|
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 SJ(r){let{inputs:e,backend:t,attrs:n}=r,{images:o,dy:s}=e,{alignCorners:a}=n,i=new uC(s.shape,o.shape,a);return t.runWebGLProgram(i,[s],s.dtype)}var sP={kernelName:mp,backendName:"webgl",kernelFunc:SJ};var cC=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=i=>t.indexOf(i)!==-1&&e[i]!==1?`${e[i]} - coords[${i}] - 1`:`coords[${i}]`,s=e.map((i,l)=>o(l)).join(","),a=Ge(n);this.userCode=`
|
|
void main() {
|
|
${a} coords = getOutputCoords();
|
|
setOutput(getX(${s}));
|
|
}
|
|
`}};var pC=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=Xt("rc",n),s=`${o[n-1]} + 1 < ${this.outputShape[n-1]}`,a=`${o[n-2]} + 1 < ${this.outputShape[n-2]}`,i=Ge(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() {
|
|
${i} rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result.r = ${l(o.slice())};
|
|
if(${s}){
|
|
result.g = ${u(o.slice())};
|
|
}
|
|
if(${a}) {
|
|
result.b = ${c(o.slice())};
|
|
if(${s}) {
|
|
result.a = ${p(o.slice())};
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`;function l(d){return m(d)}function u(d){return d[n-1]="("+d[n-1]+" + 1)",m(d)}function c(d){return d[n-2]="("+d[n-2]+" + 1)",m(d)}function p(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((b,w)=>f(w,d)),g=h.join(","),x=h.slice(-2).join(",");return`getChannel(getX(${g}), vec2(${x}))`}function f(d,h){return t.indexOf(d)!==-1&&e[d]!==1?`${e[d]} - ${h[d]} - 1`:`${h[d]}`}}};function NJ(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{dims:s}=n,a=o.shape.length,i=y.parseAxisParam(s,o.shape);if(a===0)return Yt({inputs:{x:o},backend:t});let l=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new pC(o.shape,i):new cC(o.shape,i);return t.runWebGLProgram(l,[o],o.dtype)}var iP={kernelName:ps,backendName:"webgl",kernelFunc:NJ};var mC=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,a)=>{this.paramsLoc==null&&(this.paramsLoc=s.getUniformLocationNoThrow(a,"params")),s.gl.uniform4f(this.paramsLoc,e,t,n,o)}}};var aP={kernelName:wa,backendName:"webgl",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{image:n}=r,{radians:o,fillValue:s,center:a}=e,i=t,l=new mC(n.shape,s),[u,c]=I.getImageCenter(a,n.shape[1],n.shape[2]),p=l.getCustomSetupFunc(u,c,Math.sin(o),Math.cos(o));return i.runWebGLProgram(l,[n],n.dtype,p)}};var TJ=`
|
|
// 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;
|
|
}
|
|
}
|
|
`,EJ=ke({opSnippet:TJ}),lP={kernelName:ms,backendName:"webgl",kernelFunc:EJ};var AJ="return inversesqrt(x);",DJ=ke({opSnippet:AJ,cpuKernelImpl:q$}),uP={kernelName:fs,backendName:"webgl",kernelFunc:DJ};var yd=class{constructor(e,t,n,o,s,a,i=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;let l=Ge(s.length),u=Ge(a.length),c="";n===1?c="i":n===2&&(c="i, j");let p=`getIndices(${c})`,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(${p});
|
|
flattenedIndex += index * ${d};
|
|
}
|
|
if (flattenedIndex == coords[0]) {
|
|
sum += ${f};
|
|
found = true;
|
|
}
|
|
}
|
|
setOutput(mix(getDefaultValue(), sum, float(found)));
|
|
}
|
|
`}};function $J(r){let{inputs:e,backend:t,attrs:n}=r,{indices:o,updates:s}=e,{shape:a}=n,{sliceRank:i,numUpdates:l,sliceSize:u,strides:c,outputSize:p}=I.calculateShapes(s,o,a),m=[p/u,u];if(p===0)return t.makeTensorInfo(a,o.dtype);let f=le({inputs:{x:o},backend:t,attrs:{shape:[l,i]}}),d=le({inputs:{x:s},backend:t,attrs:{shape:[l,u]}}),h=t.makeTensorInfo([],"float32",new Float32Array([0])),g=new yd(l,i,f.shape.length,d.shape.length,c,m),x=t.runWebGLProgram(g,[d,f,h],d.dtype),b=le({inputs:{x},backend:t,attrs:{shape:a}});return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(x),t.disposeIntermediateTensorInfo(h),b}var cP={kernelName:ma,backendName:"webgl",kernelFunc:$J};var fC=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 i=["resRC.x","resRC.y","resRC.z","resRC.w"],l=[],u=[];for(let c=0;c<t.length;c++)u.push(`${i[c]}`),c<e&&l.push(`${i[c]}`);o=l.join(),s=u.join()}let a=Ge(n);this.userCode=`
|
|
void main() {
|
|
${a} resRC = getOutputCoords();
|
|
float cVal = getC(${o});
|
|
if (cVal >= 1.0) {
|
|
setOutput(getA(${s}));
|
|
} else {
|
|
setOutput(getB(${s}));
|
|
}
|
|
}
|
|
`}};function RJ(r){let{inputs:e,backend:t}=r,{condition:n,t:o,e:s}=e,a=new fC(n.shape.length,o.shape,o.shape.length);return t.runWebGLProgram(a,[n,o,s],mr(o.dtype,s.dtype))}var pP={kernelName:ii,backendName:"webgl",kernelFunc:RJ};var FJ=`
|
|
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
|
|
// see: https://arxiv.org/abs/1706.02515
|
|
float scaleAlpha = ${I.SELU_SCALEALPHA};
|
|
float scale = ${I.SELU_SCALE};
|
|
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
|
|
`,OJ=ke({opSnippet:FJ}),mP={kernelName:fa,backendName:"webgl",kernelFunc:OJ};var PJ="return 1.0 / (1.0 + exp(-1.0 * x));",MJ=ke({opSnippet:PJ}),fP={kernelName:hs,backendName:"webgl",kernelFunc:MJ};var LJ=`
|
|
if (isnan(x)) { return 0.0; }
|
|
return sign(x);
|
|
`,zJ=ke({opSnippet:LJ}),dP={kernelName:ha,backendName:"webgl",kernelFunc:zJ};var BJ=Jx+`
|
|
return sin(x);
|
|
`,VJ=ke({opSnippet:BJ}),hP={kernelName:ds,backendName:"webgl",kernelFunc:VJ};var GJ=`
|
|
float e2x = exp(x);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`,WJ=ke({opSnippet:GJ}),gP={kernelName:da,backendName:"webgl",kernelFunc:WJ};var jJ=`
|
|
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;
|
|
`,UJ=ke({opSnippet:jJ}),xP={kernelName:ga,backendName:"webgl",kernelFunc:UJ};var qJ=r=>{let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{blockShape:s,paddings:a}=n;y.assert(o.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let i=s.reduce((x,b)=>x*b),l=[[0,0]];l.push(...a);for(let x=1+s.length;x<o.shape.length;++x)l.push([0,0]);let u=[],c=rC({inputs:{x:o},backend:t,attrs:{paddings:l,constantValue:0}}),p=I.getReshaped(c.shape,s,i,!1),m=I.getPermuted(p.length,s.length,!1),f=I.getReshapedPermuted(c.shape,s,i,!1),d=le({inputs:{x:c},backend:t,attrs:{shape:p}}),h=Ft({inputs:{x:d},backend:t,attrs:{perm:m}}),g=le({inputs:{x:h},backend:t,attrs:{shape:f}});return u.push(c),u.push(d),u.push(h),u.forEach(x=>t.disposeIntermediateTensorInfo(x)),g},yP={kernelName:bl,backendName:"webgl",kernelFunc:qJ};function HJ(r){let{inputs:e,backend:t}=r,{indices:n,values:o,denseShape:s,defaultValue:a}=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(a.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
|
|
${a.shape}`);let i=t.readSync(n.dataId),l=t.readSync(o.dataId),u=t.readSync(s.dataId),c=t.readSync(a.dataId)[0],[p,m,f,d,h]=K$(i,n.shape,n.dtype,l,o.dtype,u,c);return[t.makeTensorInfo(m,n.dtype,p),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 bP={kernelName:dp,backendName:"webgl",kernelFunc:HJ};function KJ(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 a=Array.from(t.readSync(o.dataId)),i=t.readSync(n.dataId),l=Array.from(t.readSync(s.dataId)),[u,c,p]=X$(i,n.shape,n.dtype,a,l);return[t.makeTensorInfo(c,n.dtype,u),t.makeTensorInfo([p.length],s.dtype,new Int32Array(p))]}var wP={kernelName:hp,backendName:"webgl",kernelFunc:KJ};function XJ(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 a=t.readSync(n.dataId),i=t.readSync(o.dataId),l=t.readSync(s.dataId),[u,c]=Xx(a,n.shape,n.dtype,i,l,!0);return t.makeTensorInfo(c,n.dtype,u)}var _P={kernelName:gp,backendName:"webgl",kernelFunc:XJ};function YJ(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 a=t.readSync(n.dataId),i=t.readSync(o.dataId),l=t.readSync(s.dataId),[u,c]=Xx(a,n.shape,n.dtype,i,l);return t.makeTensorInfo(c,n.dtype,u)}var kP={kernelName:xp,backendName:"webgl",kernelFunc:YJ};function ZJ(r){let{inputs:e,backend:t,attrs:n}=r,{sparseIndices:o,sparseValues:s,defaultValue:a}=e,{outputShape:i}=n,{sliceRank:l,numUpdates:u,strides:c,outputSize:p}=I.calculateShapes(s,o,i),m=!1,f=new yd(u,l,o.shape.length,s.shape.length,c,[p,1],m),d=t.runWebGLProgram(f,[s,o,a],s.dtype),h=le({inputs:{x:d},backend:t,attrs:{shape:i}});return t.disposeIntermediateTensorInfo(d),h}var vP={kernelName:yp,backendName:"webgl",kernelFunc:ZJ};function JJ(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{numOrSizeSplits:s,axis:a}=n,i=y.parseAxisParam(a,o.shape)[0],l=I.prepareSplitSize(o,s,i),u=o.shape.length,c=new Array(u).fill(0),p=o.shape.slice();return l.map(m=>{let f=[...p];f[i]=m;let d=qa({inputs:{x:o},backend:t,attrs:{begin:c,size:f}});return c[i]+=m,d})}var CP={kernelName:li,backendName:"webgl",kernelFunc:JJ};var QJ="return sqrt(x);",eQ=ke({opSnippet:QJ}),IP={kernelName:gs,backendName:"webgl",kernelFunc:eQ};var tQ="return x * x;",rQ=ke({opSnippet:tQ}),SP={kernelName:wl,backendName:"webgl",kernelFunc:rQ};var NP="return (a - b) * (a - b);",nQ=it({opSnippet:NP,packedOpSnippet:NP}),TP={kernelName:bs,backendName:"webgl",kernelFunc:nQ};function oQ({inputs:r,attrs:e,backend:t}){let{x:n}=r,o=kr+`
|
|
return x > 0.0 ? 1.0 : float(${e.alpha});
|
|
`,s=new vn(n.shape,o);return t.runWebGLProgram(s,[n],n.dtype)}var EP={kernelName:oo,backendName:"webgl",kernelFunc:oQ};var dC=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;let o=n.length,s=Ge(n.length),a=Ge(n.length),i="";if(o===1)i="coords * strides + begin";else{let l=0;i=n.map((u,c)=>(l++,n.length===1?`coords * strides[${c}] + begin[${c}]`:`coords[${l-1}] * strides[${c}] + begin[${c}]`)).join(",")}this.userCode=`
|
|
${s} begin = ${s}(${e});
|
|
${s} strides = ${s}(${t});
|
|
|
|
void main() {
|
|
${a} coords = getOutputCoords();
|
|
setOutput(getX(${i}));
|
|
}
|
|
`}};function sQ(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{begin:s,end:a,strides:i,beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:m}=n,{nonStrided:f,$begin:d,$strides:h,size:g,newShape:x,outShape:b}=lr.sliceInfo(o.shape,s,a,i,l,u,c,p,m),w=le({inputs:{x:o},backend:t,attrs:{shape:x}}),_;if(f){let A=qa({inputs:{x:w},backend:t,attrs:{begin:d,size:g}});_=le({inputs:{x:A},backend:t,attrs:{shape:b}}),t.disposeIntermediateTensorInfo(A)}else if(b.some(A=>A===0))_=t.makeTensorInfo(b,o.dtype,[]);else if(t.shouldExecuteOnCPU([w])){let $=t.texData.get(w.dataId).values,R=Ie(w.shape,w.dtype,$),M=Y$(b,R,h,d);_=t.makeTensorInfo(b,w.dtype,M.values)}else{let D=new dC(d,h,b);_=t.runWebGLProgram(D,[w],w.dtype)}let C=le({inputs:{x:_},backend:t,attrs:{shape:b}});return t.disposeIntermediateTensorInfo(w),t.disposeIntermediateTensorInfo(_),C}var AP={kernelName:xa,backendName:"webgl",kernelFunc:sQ};function iQ(r){let{inputs:e,backend:t,attrs:n}=r,{separator:o,nGramWidths:s,leftPad:a,rightPad:i,padWidth:l,preserveShortSequences:u}=n,{data:c,dataSplits:p}=e,m=t.readSync(c.dataId),f=t.readSync(p.dataId),[d,h]=Z$(m,f,o,s,a,i,l,u);return[t.makeTensorInfo([d.length],"string",d),t.makeTensorInfo(p.shape,"int32",h)]}var DP={kernelName:bp,backendName:"webgl",kernelFunc:iQ};function aQ(r){let{inputs:e,backend:t,attrs:n}=r,{skipEmpty:o}=n,{input:s,delimiter:a}=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(a.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${a.shape}`);let i=t.readSync(s.dataId),l=t.readSync(a.dataId)[0],[u,c,p]=J$(i,l,o),m=c.length;return[t.makeTensorInfo([m,2],"int32",u),t.makeTensorInfo([m],"string",c),t.makeTensorInfo([2],"int32",new Int32Array(p))]}var $P={kernelName:wp,backendName:"webgl",kernelFunc:aQ};function lQ(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 a=t.readSync(s.dataId),i=Q$(a,o);return t.makeTensorInfo(s.shape,"int32",i)}var RP={kernelName:_p,backendName:"webgl",kernelFunc:lQ};var uQ="return tan(x);",cQ=ke({opSnippet:uQ}),FP={kernelName:_s,backendName:"webgl",kernelFunc:cQ};var pQ=`
|
|
float e2x = exp(-2.0 * abs(x));
|
|
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
|
|
`,mQ=ke({opSnippet:pQ}),OP={kernelName:ks,backendName:"webgl",kernelFunc:mQ};var hC=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let a=0;a<n.length;a++)n[a]=e[a]*t[a];this.outputShape=n,this.rank=n.length;let o=Ge(this.rank),s=fQ(e);this.userCode=`
|
|
void main() {
|
|
${o} resRC = getOutputCoords();
|
|
setOutput(getA(${s}));
|
|
}
|
|
`}};function fQ(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 gC(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=>y.decodeString(m)):l,c=Ie(o.shape,o.dtype,u),p=tR(c,s);return t.makeTensorInfo(p.shape,p.dtype,p.values)}let a=new hC(o.shape,s);return t.runWebGLProgram(a,[o],o.dtype)}var PP={kernelName:Un,backendName:"webgl",kernelFunc:gC};function dQ(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{k:s,sorted:a}=n,i=t.readSync(o.dataId),[l,u]=rR(i,o.shape,o.dtype,s,a);return[t.makeTensorInfo(l.shape,l.dtype,l.values),t.makeTensorInfo(u.shape,u.dtype,u.values)]}var MP={kernelName:ya,backendName:"webgl",kernelFunc:dQ};var xC=class{constructor(e,t,n,o,s,a){this.variableNames=["Image","Transforms"],this.outputShape=a;let i=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 (${i} == 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 hQ(r){let{inputs:e,backend:t,attrs:n}=r,{image:o,transforms:s}=e,{interpolation:a,fillMode:i,fillValue:l,outputShape:u}=n,[c,p,m,f]=o.shape,[d,h]=u!=null?u:[p,m],g=[c,d,h,f],x=new xC(p,m,a,i,l,g);return t.runWebGLProgram(x,[o,s],"float32")}var LP={kernelName:ba,backendName:"webgl",kernelFunc:hQ};function gQ(r){let{inputs:e,attrs:t,backend:n}=r,{axis:o}=t,{x:s}=e;Ps(s,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let a=n.readSync(s.dataId),{outputValues:i,outputShape:l,indices:u}=nR(a,o,s.shape,s.dtype);return[n.makeTensorInfo(l,s.dtype,i),n.makeTensorInfo([u.length],"int32",u)]}var zP={kernelName:kp,backendName:"webgl",kernelFunc:gQ};function xQ(r){let{inputs:e,backend:t,attrs:n}=r,{value:o}=e,{axis:s}=n;s<0&&(s+=o.shape.length);let a=o,i=a.shape.length,l=o.shape[s],u=new Array(i-1),c=0;for(let h=0;h<i;h++)h!==s&&(u[c++]=a.shape[h]);let p=[],m=new Array(i).fill(0),f=a.shape.slice();f[s]=1;let d=new Array(l);for(let h=0;h<d.length;h++){m[s]=h;let g=qa({inputs:{x:a},backend:t,attrs:{begin:m,size:f}}),x=le({inputs:{x:g},backend:t,attrs:{shape:u}});d[h]=x,p.push(g)}return p.forEach(h=>t.disposeIntermediateTensorInfo(h)),d}var BP={kernelName:ui,backendName:"webgl",kernelFunc:xQ};var yC=class{constructor(e,t){this.variableNames=["x","segmentIds"];let n=e.windowSize,o=e.batchSize,s=e.inSize,a=e.numSegments,i=a*Math.ceil(s/n);this.outputShape=[o,i];let l="0.0",u="sumValue",c=Math.floor(n/4)*4,p=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(
|
|
${a})) * float(${n}));
|
|
int currentSeg = int(mod(float(outIdx), float(${a})));
|
|
|
|
float sumValue = 0.0;
|
|
|
|
for (int i = 0; i < ${c}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
|
|
);
|
|
|
|
${m}
|
|
}
|
|
|
|
int inIdx = inOffset + ${c};
|
|
if (${p===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
0,
|
|
0,
|
|
0
|
|
);
|
|
|
|
${m}
|
|
} else if (${p===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
|
|
0,
|
|
0
|
|
);
|
|
|
|
${m}
|
|
} else if (${p===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
initializationValue
|
|
);
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
|
|
0
|
|
);
|
|
|
|
${m}
|
|
}
|
|
setOutput(${u});
|
|
}
|
|
`}};function yQ(r){let{inputs:e,backend:t,attrs:n}=r,{x:o,segmentIds:s}=e,{numSegments:a}=n,i=o.shape.length,l=[],u=0,c=I.getAxesPermutation([u],i),p=o;c!=null&&(p=Ft({inputs:{x:o},backend:t,attrs:{perm:c}}),l.push(p),u=I.getInnerMostAxes(1,i)[0]);let m=I.segment_util.computeOutShape(p.shape,u,a),f=y.sizeFromShape([p.shape[u]]),d=le({inputs:{x:p},backend:t,attrs:{shape:[-1,f]}});l.push(d);let h=du(o.dtype),g=(_,C,A,D,$)=>{let R=_.shape[0],M=_.shape[1],G=I.segment_util.segOpComputeOptimalWindowSize(M,$),j={windowSize:G,inSize:M,batchSize:R,numSegments:$},U=new yC(j,C),q=t.compileAndRun(U,[_,A],D);if(l.push(q),q.shape[1]===$)return q;let H=nC({backend:t,attrs:{start:0,stop:$,step:1,dtype:"float32"}}),X=gC({inputs:{x:H},backend:t,attrs:{reps:[M/G]}});return l.push(H),l.push(X),g(q,C,X,D,$)},x=g(d,"unsortedSegmentSum",s,h,a),b=le({inputs:{x},backend:t,attrs:{shape:m}}),w=b;if(c!=null){l.push(b);let _=I.getUndoAxesPermutation(c);w=Ft({inputs:{x:w},backend:t,attrs:{perm:_}})}return l.forEach(_=>t.disposeIntermediateTensorInfo(_)),w}var VP={kernelName:_l,backendName:"webgl",kernelFunc:yQ};var bQ=[xO,yO,$R,FR,OR,PR,LR,zR,BR,VR,jR,UR,qR,HR,XR,KR,YR,JR,ZR,QR,eF,tF,rF,oF,sF,uF,pF,mF,dF,wR,gF,yF,bF,xF,_F,kF,wF,vF,CF,IF,TF,EF,AF,$F,RF,DF,FF,OF,PF,MF,LF,zF,BF,GF,WF,UF,qF,HF,KF,YF,ZF,JF,QF,eO,tO,rO,nO,oO,bR,sO,hF,iO,aO,lO,_R,uO,cO,pO,fO,mO,dO,hO,gO,wO,vO,kO,CO,IO,NO,_O,EO,AO,DO,$O,RO,LO,SR,BO,VO,GO,WO,iF,jO,HO,KO,XO,YO,kR,ZO,JO,aF,FO,QO,tP,eP,TR,rP,nP,oP,sP,iP,aP,lP,uP,cP,pP,mP,fP,dP,hP,gP,nF,MO,xP,yP,bP,wP,_P,kP,vP,CP,IP,SP,TP,EP,AP,DP,$P,RP,PO,AR,FP,OP,PP,MP,LP,DR,zP,BP,VP,UO];for(let r of bQ)lu(r);var Ot;(function(r){r[r.float32=0]="float32",r[r.int32=1]="int32",r[r.bool=2]="bool",r[r.string=3]="string",r[r.complex64=4]="complex64"})(Ot||(Ot={}));var Ll;(function(r){r[r.linear=0]="linear",r[r.relu=1]="relu",r[r.relu6=2]="relu6",r[r.prelu=3]="prelu",r[r.leakyrelu=4]="leakyrelu",r[r.sigmoid=5]="sigmoid"})(Ll||(Ll={}));var GP;function wQ(r){GP=r.wasm.cwrap(pi,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function _Q(r){let{inputs:e,backend:t,attrs:n}=r,{a:o,b:s,bias:a,preluActivationWeights:i}=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:c,leakyreluAlpha:p}=n,m=t.dataIdMap.get(o.dataId).id,f=t.dataIdMap.get(s.dataId).id,d=0;if(a!=null){let $=t.dataIdMap.get(a.dataId);if($.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${$.shape.length}.`);d=$.id}let h=i==null?0:t.dataIdMap.get(i.dataId).id,g=Ll[c];if(g==null)throw new Error(`${c} activation not yet supported for FusedConv2D in the wasm backend.`);let x=l?o.shape[2]:o.shape[1],b=u?s.shape[1]:s.shape[2],w=o.shape[0],_=t.makeOutput([w,x,b],o.dtype),C=t.dataIdMap.get(_.dataId).id,A=new Uint8Array(new Int32Array(o.shape).buffer),D=new Uint8Array(new Int32Array(s.shape).buffer);return GP(m,A,o.shape.length,f,D,s.shape.length,l,u,g,d,h,p||0,C),_}var WP={kernelName:pi,backendName:"wasm",setupFunc:wQ,kernelFunc:_Q};function yt(r){let e;function t(o){e=o.wasm.cwrap(r,null,["number","number"])}function n(o){let{backend:s,inputs:{x:a}}=o,i=s.dataIdMap.get(a.dataId).id,l=s.makeOutput(a.shape,a.dtype),u=s.dataIdMap.get(l.dataId).id;return y.sizeFromShape(l.shape)===0||e(i,u),l}return{kernelName:r,backendName:"wasm",setupFunc:t,kernelFunc:n}}var jP=yt(Js);function bt(r,e,t){let n;function o(a){n=a.wasm.cwrap(r,null,["number","array","number","number","array","number","number","number"])}function s(a){let{backend:i,inputs:l}=a,{a:u,b:c}=l,p=i.dataIdMap.get(u.dataId).id,m=i.dataIdMap.get(c.dataId).id,f=t!=null?t:u.dtype,d=I.assertAndGetBroadcastShape(u.shape,c.shape),h=i.makeOutput(d,f);if(y.sizeFromShape(d)===0)return h;let g=new Uint8Array(new Int32Array(u.shape).buffer),x=new Uint8Array(new Int32Array(c.shape).buffer),b=i.dataIdMap.get(h.dataId).id,w=()=>n(p,g,u.shape.length,m,x,c.shape.length,Ot[u.dtype],b);if(e&&u.dtype==="float32")return w(),h;let _=I.getBroadcastDims(u.shape,d),C=I.getBroadcastDims(c.shape,d),A=_.every(($,R)=>$===R),D=C.every(($,R)=>$===R);if(A&&D)return w(),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 kQ=!0,UP=bt(jn,kQ);var qP;function vQ(r){qP=r.wasm.cwrap($o,null,["array","number","number","number"])}function CQ(r){let{inputs:e,backend:t}=r,n=t.makeOutput(e[0].shape,e[0].dtype);if(y.sizeFromShape(n.shape)===0)return n;let o=e.map(i=>t.dataIdMap.get(i.dataId).id),s=new Uint8Array(new Int32Array(o).buffer),a=t.dataIdMap.get(n.dataId).id;return qP(s,o.length,Ot[n.dtype],a),n}var HP={kernelName:$o,backendName:"wasm",setupFunc:vQ,kernelFunc:CQ};function dc(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 KP={kernelName:no,backendName:"wasm",kernelFunc:dc};var XP;function IQ(r){XP=r.wasm.cwrap(vs,null,["number","array","number","number","number","array","number"])}function sm(r){let{inputs:e,backend:t,attrs:n}=r,[o,s]=NQ(e.x.shape,n.perm),a=!0;for(let d=0;d<s.length;d++)s[d]!==d&&(a=!1);let i=SQ(e.x.shape,n.perm),l={dataId:e.x.dataId,shape:o,dtype:e.x.dtype};if(a){let d=dc({inputs:e,backend:t});return d.shape=i,d}let u=t.makeOutput(i,l.dtype),c=t.dataIdMap.get(l.dataId).id,p=t.dataIdMap.get(u.dataId).id,m=new Uint8Array(new Int32Array(s).buffer),f=new Uint8Array(new Int32Array(l.shape).buffer);return XP(c,f,l.shape.length,Ot[l.dtype],p,m,s.length),u}function SQ(r,e){let t=new Array(r.length);for(let n=0;n<t.length;n++)t[n]=r[e[n]];return t}function NQ(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 a=0;a<n.length;++a)n[a]>=o&&(s===-1||n[s]>n[a])&&(s=a);n[s]=o}return[t,n]}var YP={kernelName:vs,backendName:"wasm",kernelFunc:sm,setupFunc:IQ};function ln(r,e,t){let n=r.shape,o=r.shape.length,s=y.parseAxisParam(e,n),a=s,i=I.getAxesPermutation(a,o),l=null,u=!1;if(i!=null){let c=new Array(o);for(let f=0;f<c.length;f++)c[f]=n[i[f]];a=I.getInnerMostAxes(a.length,o),l=sm({inputs:{x:r},attrs:{perm:i},backend:t});let p=t.dataIdMap.get(r.dataId).id;t.dataIdMap.get(l.dataId).id!==p&&(u=!0)}return{transposed:l,originalAxes:s,axes:a,inputWasTransposed:u}}var ZP;function TQ(r){ZP=r.wasm.cwrap(Oi,null,["number, number, number"])}function EQ(r){let{backend:e,inputs:t,attrs:n}=r,{axis:o,keepDims:s}=n,{x:a}=t,l=e.dataIdMap.get(a.dataId).id,u=a,{transposed:c,axes:p,originalAxes:m,inputWasTransposed:f}=ln(a,o,e);if(f){let w=e.dataIdMap.get(c.dataId).id;u=c,l=w}let d=u.shape.length;I.assertAxesAreInnerMostDims("all",p,d);let[h,g]=I.computeOutAndReduceShapes(u.shape,p),x=y.sizeFromShape(g),b=e.makeOutput(h,a.dtype);if(y.sizeFromShape(u.shape)!==0){let w=e.dataIdMap.get(b.dataId).id;ZP(l,x,w)}if(f&&e.disposeData(c.dataId),s){let w=I.expandShapeToKeepDim(b.shape,m);b.shape=w}return b}var JP={kernelName:Oi,backendName:"wasm",setupFunc:TQ,kernelFunc:EQ};var QP;function AQ(r){QP=r.wasm.cwrap(Pi,null,["number, number, number"])}function DQ(r){let{backend:e,inputs:t,attrs:n}=r,{axis:o,keepDims:s}=n,{x:a}=t,l=e.dataIdMap.get(a.dataId).id,u=a,{transposed:c,axes:p,originalAxes:m,inputWasTransposed:f}=ln(a,o,e);if(f){let w=e.dataIdMap.get(c.dataId).id;u=c,l=w}let d=u.shape.length;I.assertAxesAreInnerMostDims("any",p,d);let[h,g]=I.computeOutAndReduceShapes(u.shape,p),x=y.sizeFromShape(g),b=e.makeOutput(h,a.dtype);if(y.sizeFromShape(u.shape)!==0){let w=e.dataIdMap.get(b.dataId).id;QP(l,x,w)}if(f&&e.disposeData(c.dataId),s){let w=I.expandShapeToKeepDim(b.shape,m);b.shape=w}return b}var eM={kernelName:Pi,backendName:"wasm",setupFunc:AQ,kernelFunc:DQ};var tM;function $Q(r){tM=r.wasm.cwrap(Ro,null,["number","number","number","number","number"])}function RQ(r){let{backend:e,inputs:t,attrs:n}=r,{axis:o}=n,{x:s}=t,a=e.dataIdMap.get(s.dataId).id,i=a,l=s,{transposed:u,axes:c,inputWasTransposed:p}=ln(s,o,e);if(p){let x=e.dataIdMap.get(u.dataId).id;x!==a&&(l=u,i=x)}let m=l.shape.slice(0,-1),f=e.makeOutput(m,"int32"),d=e.dataIdMap.get(f.dataId).id,h=y.sizeFromShape(f.shape),g=l.shape[c[0]];return tM(i,Ot[l.dtype],h,g,d),p&&e.disposeData(u.dataId),f}var rM={kernelName:Ro,backendName:"wasm",kernelFunc:RQ,setupFunc:$Q};var nM;function FQ(r){nM=r.wasm.cwrap(Fo,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function OQ(r){let{inputs:e,attrs:t,backend:n}=r,o=e.x,s=n.dataIdMap.get(o.dataId).id,{filterSize:a,strides:i,pad:l,dimRoundingMode:u}=t,c=I.computePool2DInfo(o.shape,a,i,1,l,u),p=c.filterHeight,m=c.filterWidth,f=c.padInfo.top,d=c.padInfo.right,h=c.padInfo.bottom,g=c.padInfo.left,x=c.strideHeight,b=c.strideWidth,w=c.inChannels;if(c.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);if(c.dilationWidth!==1||c.dilationHeight!==1)throw new Error(`was backend only supports average pooling with dilation = [1, 1], got [${c.dilationHeight}, ${c.dilationWidth}].`);let _=n.makeOutput(c.outShape,"float32"),C=n.dataIdMap.get(_.dataId).id;return nM(s,o.shape[0],o.shape[1],o.shape[2],p,m,f,d,h,g,x,b,w,C),_}var oM={kernelName:Fo,backendName:"wasm",setupFunc:FQ,kernelFunc:OQ};function qr(r){let{inputs:e,attrs:t}=r,{x:n}=e,{shape:o}=t,s=y.sizeFromShape(n.shape),a=y.inferFromImplicitShape(o,s);return y.assert(s===y.sizeFromShape(a),()=>`new shape: ${a}, 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:a,dtype:n.dtype}}var sM={kernelName:si,backendName:"wasm",kernelFunc:qr};var iM;function PQ(r){iM=r.wasm.cwrap(Oo,null,["number","array","number","number","array","number","number","number","number"])}function MQ(r){let{inputs:e,backend:t,attrs:n}=r,{a:o,b:s}=e,{transposeA:a,transposeB:i}=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,c=a?o.shape[l-2]:o.shape[l-1],p=i?s.shape[u-1]:s.shape[u-2],m=a?o.shape[l-1]:o.shape[l-2],f=i?s.shape[u-2]:s.shape[u-1],d=o.shape.slice(0,-2),h=s.shape.slice(0,-2),g=y.sizeFromShape(d),x=y.sizeFromShape(h),b=g===x||g===1||x===1;y.assert(l>=2&&u>=2&&b,()=>`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 _=(g>x?o.shape.slice(0,-2):s.shape.slice(0,-2)).concat([m,f]);y.assert(c===p,()=>`Error in matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${o.shape} and ${s.shape} and transposeA=${a} and transposeB=${i} must match.`);let C=a?[g,c,m]:[g,m,c],A=i?[x,f,p]:[x,p,f],D=qr({inputs:{x:o},backend:t,attrs:{shape:C}}),$=qr({inputs:{x:s},backend:t,attrs:{shape:A}}),R=t.dataIdMap.get(D.dataId).id,M=t.dataIdMap.get($.dataId).id,G=a?D.shape[2]:D.shape[1],j=i?$.shape[1]:$.shape[2],U=Math.max(g,x),q=t.makeOutput([U,G,j],D.dtype),H=t.dataIdMap.get(q.dataId).id,X=new Uint8Array(new Int32Array(D.shape).buffer),ne=new Uint8Array(new Int32Array($.shape).buffer);return iM(R,X,D.shape.length,M,ne,$.shape.length,a,i,H),t.disposeData(D.dataId),t.disposeData($.dataId),q.shape=_,q}var aM={kernelName:Oo,backendName:"wasm",setupFunc:PQ,kernelFunc:MQ};function hc(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 lM={kernelName:to,backendName:"wasm",kernelFunc:hc};var uM=yt(Po);var cM;function LQ(r){cM=r.wasm.cwrap(ro,null,["number","number","number","number"])}function zQ(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{clipValueMin:s,clipValueMax:a}=n,i=t.dataIdMap.get(o.dataId).id,l=t.makeOutput(o.shape,o.dtype),u=t.dataIdMap.get(l.dataId).id;return cM(i,s,a,u),l}var pM={kernelName:ro,backendName:"wasm",setupFunc:LQ,kernelFunc:zQ};function bC(r){let{inputs:e,backend:t}=r,n=y.parseAxisParam(r.attrs.axis,e[0].shape)[0],o=I.computeOutShape(e.map(f=>f.shape),n),s=e.filter(f=>y.sizeFromShape(f.shape)>0);if(s.length===1)return dc({inputs:{x:s[0]},backend:t});let a=t.makeOutput(o,e[0].dtype);if(y.sizeFromShape(o)===0)return a;let i=s.map(f=>f.shape);if(I.assertParamsConsistent(i,n),s[0].dtype==="string"){let f=s.map(w=>{let _=y.sizeFromShape(w.shape.slice(n));return qr({inputs:{x:w},backend:t,attrs:{shape:[-1,_]}})}),d=f.map(w=>({vals:t.readSync(w.dataId),shape:w.shape}));o=I.computeOutShape(f.map(w=>w.shape),1);let h=f[0].shape[0]===1,g=ec(d,o,e[0].dtype,h),x=I.computeOutShape(s.map(w=>w.shape),n);a.shape=x;let b=t.dataIdMap.get(a.dataId);return b.stringBytes=I.fromStringArrayToUint8(g),f.forEach(w=>t.disposeData(w.dataId)),a}let l=y.sizeFromShape(s[0].shape.slice(0,n)),u=0,c=s.map(f=>{let d=y.sizeFromShape(f.shape.slice(n));return u+=d,d}),p=s.map(f=>t.typedArrayFromHeap(f)),m=t.typedArrayFromHeap(a);for(let f=0;f<l;f++){let d=f*u;for(let h=0;h<p.length;h++){let g=c[h],x=f*g,b=p[h].subarray(x,x+g);m.set(b,d),d+=g}}return a}var mM={kernelName:Qs,backendName:"wasm",kernelFunc:bC};var fM;function BQ(r){fM=r.wasm.cwrap(Mo,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function VQ(r){let{inputs:e,attrs:t,backend:n}=r,{x:o,filter:s}=e,a=n.dataIdMap.get(o.dataId).id,i=n.dataIdMap.get(s.dataId).id,{strides:l,dilations:u,pad:c,dimRoundingMode:p,dataFormat:m}=t,f=I.convertConv2DDataFormat(m),d=I.computeConv2DInfo(o.shape,s.shape,l,u,c,p,!1,f),h=d.filterHeight,g=d.filterWidth,x=d.padInfo.top,b=d.padInfo.right,w=d.padInfo.bottom,_=d.padInfo.left,C=d.dilationHeight,A=d.dilationWidth,D=d.strideHeight,$=d.strideWidth,R=d.inChannels,M=d.outChannels,G=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 j=n.makeOutput(d.outShape,"float32"),U=n.dataIdMap.get(j.dataId).id;return fM(a,o.shape[0],o.shape[1],o.shape[2],i,h,g,x,b,w,_,G,C,A,D,$,R,M,U),j}var dM={kernelName:Mo,backendName:"wasm",setupFunc:BQ,kernelFunc:VQ};var hM;function GQ(r){hM=r.wasm.cwrap(Lo,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 WQ(r){let{backend:e,inputs:t,attrs:n}=r,{dy:o,filter:s}=t,{strides:a,pad:i,dataFormat:l,dimRoundingMode:u,inputShape:c}=n,p=1,m=I.convertConv2DDataFormat(l),f=I.computeConv2DInfo(c,s.shape,a,p,i,u,!1,m),{batchSize:d,filterHeight:h,filterWidth:g,inChannels:x,inHeight:b,inWidth:w,outChannels:_,outHeight:C,outWidth:A,strideHeight:D,strideWidth:$}=f,R=h-1-f.padInfo.top,M=g-1-f.padInfo.left,G=f.dataFormat==="channelsLast",j=y.computeStrides(f.inShape),U=y.computeStrides(o.shape),[q,H,X]=y.computeStrides(s.shape),ne=j[0],Y=G?j[1]:j[2],re=G?j[2]:1,ee=G?1:j[1],ie=U[0],me=G?U[1]:U[2],ae=G?U[2]:1,fe=G?1:U[1],he=e.makeOutput(f.inShape,"float32"),xe=e.dataIdMap.get(he.dataId).id,_e=e.dataIdMap.get(o.dataId).id,$e=e.dataIdMap.get(s.dataId).id;return hM(_e,$e,d,h,g,b,w,x,C,A,_,D,$,R,M,q,H,X,ne,Y,re,ee,ie,me,ae,fe,xe),he}var gM={kernelName:Lo,backendName:"wasm",setupFunc:GQ,kernelFunc:WQ};var xM=yt(zo);var wC;(function(r){r[r.bilinear=0]="bilinear",r[r.nearest=1]="nearest"})(wC||(wC={}));var yM;function jQ(r){yM=r.wasm.cwrap(Wi,null,["number","number","number","number","array","number","number","number","number","number"])}function UQ(r){let{backend:e,inputs:t,attrs:n}=r,{method:o,extrapolationValue:s,cropSize:a}=n,{image:i,boxes:l,boxInd:u}=t,c=l.shape[0],[p,m]=a,f=[c,p,m,i.shape[3]],d=e.dataIdMap.get(i.dataId),h;i.dtype!=="float32"&&(h=hc({backend:e,inputs:{x:i},attrs:{dtype:"float32"}}),d=e.dataIdMap.get(h.dataId));let g=d.id,x=e.dataIdMap.get(l.dataId).id,b=e.dataIdMap.get(u.dataId).id,w=e.makeOutput(f,"float32"),_=e.dataIdMap.get(w.dataId).id,C=new Uint8Array(new Int32Array(i.shape).buffer);return yM(g,x,b,c,C,p,m,wC[o],s,_),h!=null&&e.disposeData(h.dataId),w}var bM={kernelName:Wi,backendName:"wasm",setupFunc:jQ,kernelFunc:UQ};var wM;function qQ(r){wM=r.wasm.cwrap(Bo,null,["number","number","number","number","number","number"])}function HQ(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{axis:s,exclusive:a,reverse:i}=n,l=o.shape.length;y.assert(o.dtype==="float32"||o.dtype==="int32",()=>`cumsum does not support ${o.dtype} tensors in the WASM backend`);let u=I.getAxesPermutation([s],l),c=o;u!==null&&(c=sm({inputs:{x:o},attrs:{perm:u},backend:t}));let p=I.getInnerMostAxes(1,l)[0];I.assertAxesAreInnerMostDims("cumsum",[p],l);let m=t.makeOutput(c.shape,c.dtype),f=c.shape[p],d=t.dataIdMap.get(c.dataId).id,h=t.dataIdMap.get(m.dataId).id;wM(d,a?1:0,i?1:0,f,h,Ot[o.dtype]);let g=m;if(u!==null){let x=I.getUndoAxesPermutation(u);g=sm({inputs:{x:m},attrs:{perm:x},backend:t}),t.disposeData(c.dataId),t.disposeData(m.dataId)}return g}var _M={kernelName:Bo,backendName:"wasm",setupFunc:qQ,kernelFunc:HQ};var kM;function KQ(r){kM=r.wasm.cwrap(ji,null,["number","number","number","array","number","array","array","number","number"])}function XQ(r){let{backend:e,inputs:t,attrs:n}=r,{x:o}=t,{blockSize:s,dataFormat:a}=n;y.assert(s>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${s}`);let i=o.shape[0],l=a==="NHWC"?o.shape[1]:o.shape[2],u=a==="NHWC"?o.shape[2]:o.shape[3],c=a==="NHWC"?o.shape[3]:o.shape[1],p=l*s,m=u*s,f=c/(s*s),d=a==="NHWC"?[i,p,m,f]:[i,f,p,m],h=e.makeOutput(d,"float32"),x=e.dataIdMap.get(o.dataId).id,b=new Uint8Array(new Int32Array(y.computeStrides(o.shape)).buffer),w=new Uint8Array(new Int32Array(d).buffer),_=new Uint8Array(new Int32Array(y.computeStrides(d)).buffer),C=e.dataIdMap.get(h.dataId).id;return kM(x,s,a==="NHWC"?1:0,b,o.shape.length-1,w,_,d.length,C),h}var vM={kernelName:ji,backendName:"wasm",setupFunc:KQ,kernelFunc:XQ};var CM;function YQ(r){CM=r.wasm.cwrap(Vo,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function ZQ(r){let{inputs:e,attrs:t,backend:n}=r,{x:o,filter:s}=e,a=n.dataIdMap.get(o.dataId).id,i=n.dataIdMap.get(s.dataId).id,{strides:l,dilations:u,pad:c,dimRoundingMode:p}=t,m=u==null?[1,1]:u,f=I.computeConv2DInfo(o.shape,s.shape,l,m,c,p,!0),d=f.filterHeight,h=f.filterWidth,g=f.padInfo.top,x=f.padInfo.right,b=f.padInfo.bottom,w=f.padInfo.left,_=f.dilationHeight,C=f.dilationWidth,A=f.strideHeight,D=f.strideWidth,$=f.inChannels,R=f.outChannels,M=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 G=n.makeOutput(f.outShape,"float32"),j=n.dataIdMap.get(G.dataId).id;return CM(a,o.shape[0],o.shape[1],o.shape[2],i,d,h,g,x,b,w,M,_,C,A,D,$,R,j),G}var IM={kernelName:Vo,backendName:"wasm",setupFunc:YQ,kernelFunc:ZQ};var JQ=!1,SM=bt(Hi,JQ,"bool");var NM=yt(Wo);function cy(r){let{inputs:e,attrs:t,backend:n}=r,{input:o}=e,{dim:s}=t,a=o.shape.length,i=o.shape.slice(),l=s;return s<0&&(y.assert(-(a+1)<=s,()=>`Axis must be in the interval [${-(a+1)}, ${a}]`),l=a+s+1),i.splice(l,0,1),qr({inputs:{x:o},backend:n,attrs:{shape:i}})}var TM={kernelName:ei,backendName:"wasm",kernelFunc:cy};function QQ(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 EM={kernelName:dl,backendName:"wasm",kernelFunc:QQ};var AM;function eee(r){AM=r.wasm.cwrap(Xi,null,["number","number","number","number","number","number"])}function tee(r){let{inputs:e,backend:t}=r,{image:n}=e,o=t.makeOutput(n.shape,n.dtype),s=t.dataIdMap.get(n.dataId).id,a=t.dataIdMap.get(o.dataId).id,[i,l,u,c]=n.shape;return AM(s,i,l,u,c,a),o}var DM={kernelName:Xi,backendName:"wasm",kernelFunc:tee,setupFunc:eee};var $M=yt(jo);var ree=!1,RM=bt(Uo,ree);var FM;function nee(r){FM=r.wasm.cwrap(qo,null,["number","number","number","number","number","number","number"])}function oee(r){let{backend:e,inputs:t,attrs:n}=r,{varianceEpsilon:o}=n,{x:s,mean:a,variance:i,offset:l,scale:u}=t,c=e.dataIdMap.get(s.dataId).id,p=e.dataIdMap.get(a.dataId).id,m=e.dataIdMap.get(i.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(y.sizeFromShape(s.shape)===0)return h;let g=e.dataIdMap.get(h.dataId).id;return FM(c,p,m,f,d,o,g),h}var OM={kernelName:qo,backendName:"wasm",setupFunc:nee,kernelFunc:oee};var PM;function see(r){PM=r.wasm.cwrap(mi,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 iee(r){let{inputs:e,attrs:t,backend:n}=r,{x:o,filter:s,bias:a,preluActivationWeights:i}=e,{strides:l,pad:u,dilations:c,dataFormat:p,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=t,h=I.computeConv2DInfo(o.shape,s.shape,l,c,u,m),g=Ll[f];if(g==null)throw new Error(`${f} activation not yet supported for FusedConv2D in the wasm backend.`);let x=n.dataIdMap.get(o.dataId).id,b=n.dataIdMap.get(s.dataId).id,w=h.outChannels,_=0;if(a!=null){let ae=n.dataIdMap.get(a.dataId);if(ae.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${ae.shape.length}.`);if(ae.shape[0]!==w)throw new Error(`FusedConv2D bias shape (${ae.shape}) does not match the number of output channels (${w})`);_=ae.id}let C=h.filterHeight,A=h.filterWidth,D=h.padInfo.top,$=h.padInfo.right,R=h.padInfo.bottom,M=h.padInfo.left,G=h.dilationHeight,j=h.dilationWidth,U=h.strideHeight,q=h.strideWidth,H=h.inChannels,X=h.padInfo.type==="SAME"?1:0,ne=h.batchSize,Y=h.inHeight,re=h.inWidth;if(p!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);let ee=n.makeOutput(h.outShape,"float32"),ie=n.dataIdMap.get(ee.dataId).id,me=i==null?0:n.dataIdMap.get(i.dataId).id;return PM(x,ne,Y,re,b,C,A,_,D,$,R,M,X,G,j,U,q,H,w,g,me,d||0,ie),ee}var MM={kernelName:mi,backendName:"wasm",setupFunc:see,kernelFunc:iee};var LM;function aee(r){LM=r.wasm.cwrap(fi,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 lee(r){let{inputs:e,attrs:t,backend:n}=r,{x:o,filter:s,bias:a,preluActivationWeights:i}=e,{strides:l,pad:u,dilations:c,dataFormat:p,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=t,h=I.computeConv2DInfo(o.shape,s.shape,l,c,u,m,!0),g=Ll[f];if(g==null)throw new Error(`${f} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);let x=n.dataIdMap.get(o.dataId).id,b=n.dataIdMap.get(s.dataId).id,w=h.outChannels,_=0;if(a!=null){let ae=n.dataIdMap.get(a.dataId);if(ae.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${ae.shape.length}.`);if(ae.shape[0]!==w)throw new Error(`FusedDepthwiseConv2D bias shape (${ae.shape}) does not match the number of output channels (${w})`);_=ae.id}let C=h.filterHeight,A=h.filterWidth,D=h.padInfo.top,$=h.padInfo.right,R=h.padInfo.bottom,M=h.padInfo.left,G=h.dilationHeight,j=h.dilationWidth,U=h.strideHeight,q=h.strideWidth,H=h.inChannels,X=h.padInfo.type==="SAME"?1:0,ne=h.batchSize,Y=h.inHeight,re=h.inWidth;if(p!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);let ee=n.makeOutput(h.outShape,"float32"),ie=n.dataIdMap.get(ee.dataId).id,me=i==null?0:n.dataIdMap.get(i.dataId).id;return LM(x,ne,Y,re,b,C,A,_,D,$,R,M,X,G,j,U,q,H,w,g,me,d||0,ie),ee}var zM={kernelName:fi,backendName:"wasm",setupFunc:aee,kernelFunc:lee};var BM;function uee(r){BM=r.wasm.cwrap(Yi,null,["number","number","number","number","number","number","array","number"])}function cee(r){let{backend:e,inputs:t}=r,{params:n,indices:o}=t,[s,a,i,l]=Bg.prepareAndValidate(n,o),u=e.makeOutput(s,n.dtype);if(a===0)return u;let c=o.shape,p=c[c.length-1],f=e.dataIdMap.get(n.dataId).id,h=e.dataIdMap.get(o.dataId).id,g=new Uint8Array(new Int32Array(l).buffer),x=e.dataIdMap.get(u.dataId).id;return BM(f,Ot[n.dtype],h,a,p,i,g,x),u}var VM={kernelName:Yi,backendName:"wasm",setupFunc:uee,kernelFunc:cee};var GM;function pee(r){GM=r.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function mee(r){let{backend:e,inputs:t,attrs:n}=r,{x:o,indices:s}=t,{axis:a,batchDims:i}=n,l=y.parseAxisParam(a,o.shape)[0],u=I.segment_util.collectGatherOpShapeInfo(o,s,l,i),c=qr({inputs:{x:o},attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]},backend:e}),p=y.sizeFromShape(s.shape),m=qr({inputs:{x:s},attrs:{shape:[u.batchSize,p/u.batchSize]},backend:e}),f=[u.batchSize,u.outerSize,p/u.batchSize,u.sliceSize],d=e.makeOutput(f,o.dtype);if(y.sizeFromShape(o.shape)===0)return d;let h=c.shape.length-1,x=e.dataIdMap.get(c.dataId).id,w=e.dataIdMap.get(m.dataId).id,_=e.dataIdMap.get(d.dataId).id,C=new Uint8Array(new Int32Array(y.computeStrides(c.shape)).buffer),A=new Uint8Array(new Int32Array(y.computeStrides(f)).buffer);return GM(x,Ot[o.dtype],C,h,w,u.batchSize,A,_),e.disposeData(c.dataId),e.disposeData(m.dataId),d.shape=u.outputShape,d}var WM={kernelName:ti,backendName:"wasm",setupFunc:pee,kernelFunc:mee};var fee=!1,jM=bt(Zi,fee,"bool");var dee=!1,UM=bt(Ho,dee,"bool");var qM;function hee(r){qM=r.wasm.cwrap(Ko,null,["number","number","number"])}function gee(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(y.sizeFromShape(e.shape)!==0){let a=n.dataIdMap.get(s.dataId).id;qM(o,t,a)}return s}var HM={kernelName:Ko,backendName:"wasm",setupFunc:hee,kernelFunc:gee};var xee=!1,KM=bt(ta,xee,"bool");var yee=!1,XM=bt(ra,yee,"bool");var YM=yt(Xo);var bee=!1,ZM=bt(oa,bee,"bool");var JM;function wee(r){JM=r.wasm.cwrap(Yo,null,["number, number, number"])}function _ee(r){let{backend:e,inputs:t,attrs:n}=r,{reductionIndices:o,keepDims:s}=n,{x:a}=t,l=e.dataIdMap.get(a.dataId).id,u=a,{transposed:c,axes:p,originalAxes:m,inputWasTransposed:f}=ln(a,o,e);if(f){let w=e.dataIdMap.get(c.dataId).id;u=c,l=w}let d=u.shape.length;I.assertAxesAreInnerMostDims("max",p,d);let[h,g]=I.computeOutAndReduceShapes(u.shape,p),x=y.sizeFromShape(g),b=e.makeOutput(h,a.dtype);if(y.sizeFromShape(u.shape)!==0){let w=e.dataIdMap.get(b.dataId).id;JM(l,x,w)}if(f&&e.disposeData(c.dataId),s){let w=I.expandShapeToKeepDim(b.shape,m);b.shape=w}return b}var QM={kernelName:Yo,backendName:"wasm",setupFunc:wee,kernelFunc:_ee};var kee=!1,eL=bt(Zo,kee);var tL;function vee(r){tL=r.wasm.cwrap(Jo,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Cee(r){let{inputs:e,attrs:t,backend:n}=r,o=e.x,s=n.dataIdMap.get(o.dataId).id,{filterSize:a,strides:i,pad:l,dimRoundingMode:u}=t,c=I.computePool2DInfo(o.shape,a,i,1,l,u),p=c.filterHeight,m=c.filterWidth,f=c.padInfo.top,d=c.padInfo.right,h=c.padInfo.bottom,g=c.padInfo.left,x=c.dilationHeight,b=c.dilationWidth,w=c.strideHeight,_=c.strideWidth,C=c.inChannels,A=c.outChannels;if(c.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);let D=n.makeOutput(c.outShape,"float32"),$=n.dataIdMap.get(D.dataId).id;return tL(s,o.shape[0],o.shape[1],o.shape[2],p,m,f,d,h,g,x,b,w,_,C,A,$),D}var rL={kernelName:Jo,backendName:"wasm",setupFunc:vee,kernelFunc:Cee};var nL;function Iee(r){nL=r.wasm.cwrap(Qo,null,["number, number, number"])}function See(r){let{backend:e,inputs:t,attrs:n}=r,{axis:o,keepDims:s}=n,{x:a}=t,i=e.dataIdMap.get(a.dataId).id,l=i,u=a,{transposed:c,axes:p,originalAxes:m,inputWasTransposed:f}=ln(a,o,e),d=p;if(f){let _=e.dataIdMap.get(c.dataId).id;_!==i&&(u=c,l=_,d=I.getInnerMostAxes(d.length,u.shape.length))}I.assertAxesAreInnerMostDims("mean",d,u.shape.length);let[h,g]=I.computeOutAndReduceShapes(u.shape,d),x=y.sizeFromShape(g),b=u;u.dtype!=="float32"&&(b=hc({backend:e,inputs:{x:u},attrs:{dtype:"float32"}}),l=e.dataIdMap.get(b.dataId).id);let w=e.makeOutput(h,"float32");if(y.sizeFromShape(u.shape)!==0){let _=e.dataIdMap.get(w.dataId).id;nL(l,x,_)}if(f&&e.disposeData(c.dataId),s){let _=I.expandShapeToKeepDim(w.shape,m);w.shape=_}return u.dtype!=="float32"&&e.disposeData(b.dataId),w}var oL={kernelName:Qo,backendName:"wasm",setupFunc:Iee,kernelFunc:See};var sL;function Nee(r){sL=r.wasm.cwrap(es,null,["number, number, number"])}function Tee(r){let{backend:e,inputs:t,attrs:n}=r,{axis:o,keepDims:s}=n,{x:a}=t,i=e.dataIdMap.get(a.dataId).id,l=i,u=a,{transposed:c,axes:p,originalAxes:m,inputWasTransposed:f}=ln(a,o,e);if(f){let w=e.dataIdMap.get(c.dataId).id;w!==i&&(u=c,l=w)}let d=u.shape.length;I.assertAxesAreInnerMostDims("min",p,d);let[h,g]=I.computeOutAndReduceShapes(u.shape,p),x=y.sizeFromShape(g),b=e.makeOutput(h,u.dtype);if(y.sizeFromShape(u.shape)!==0){let w=e.dataIdMap.get(b.dataId).id;sL(l,x,w)}if(f&&e.disposeData(c.dataId),s){let w=I.expandShapeToKeepDim(b.shape,m);b.shape=w}return b}var iL={kernelName:es,backendName:"wasm",setupFunc:Nee,kernelFunc:Tee};var Eee=!1,aL=bt(ts,Eee);var _C;(function(r){r[r.reflect=0]="reflect",r[r.symmetric=1]="symmetric"})(_C||(_C={}));var lL;function Aee(r){lL=r.wasm.cwrap(rs,null,["number","array","number","number","array","array","number","number"])}function Dee(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]),a=t.dataIdMap.get(e.dataId).id,i=t.makeOutput(s,e.dtype),l=t.dataIdMap.get(i.dataId).id,u=new Uint8Array(new Int32Array(e.shape).buffer),c=n.map(d=>d[0]),p=n.map(d=>d[1]),m=new Uint8Array(new Int32Array(c).buffer),f=new Uint8Array(new Int32Array(p).buffer);return lL(a,u,e.shape.length,Ot[e.dtype],m,f,_C[o],l),i}var uL={kernelName:rs,backendName:"wasm",kernelFunc:Dee,setupFunc:Aee};var $ee=!0,cL=bt(ns,$ee);var pL=yt(ri);function im(r,e){let t=new Int32Array(r.wasm.HEAPU8.buffer,e,4),n=t[0],o=t[1],s=t[2],a=t[3];return r.wasm._free(e),{pSelectedIndices:n,selectedSize:o,pSelectedScores:s,pValidOutputs:a}}var mL;function Ree(r){mL=r.wasm.cwrap(aa,"number",["number","number","number","number","number"])}function Fee(r){let{backend:e,inputs:t,attrs:n}=r,{iouThreshold:o,maxOutputSize:s,scoreThreshold:a}=n,{boxes:i,scores:l}=t,u=e.dataIdMap.get(i.dataId).id,c=e.dataIdMap.get(l.dataId).id,p=mL(u,c,s,o,a),{pSelectedIndices:m,selectedSize:f,pSelectedScores:d,pValidOutputs:h}=im(e,p);return e.wasm._free(d),e.wasm._free(h),e.makeOutput([f],"int32",m)}var fL={kernelName:aa,backendName:"wasm",setupFunc:Ree,kernelFunc:Fee};var dL;function Oee(r){dL=r.wasm.cwrap(la,"number",["number","number","number","number","number","bool"])}function Pee(r){let{backend:e,inputs:t,attrs:n}=r,{iouThreshold:o,maxOutputSize:s,scoreThreshold:a,padToMaxOutputSize:i}=n,{boxes:l,scores:u}=t,c=e.dataIdMap.get(l.dataId).id,p=e.dataIdMap.get(u.dataId).id,m=dL(c,p,s,o,a,i),{pSelectedIndices:f,selectedSize:d,pSelectedScores:h,pValidOutputs:g}=im(e,m);e.wasm._free(h);let x=e.makeOutput([d],"int32",f),b=e.makeOutput([],"int32",g);return[x,b]}var hL={kernelName:la,backendName:"wasm",setupFunc:Oee,kernelFunc:Pee};var gL;function Mee(r){gL=r.wasm.cwrap(ua,"number",["number","number","number","number","number","number"])}function Lee(r){let{backend:e,inputs:t,attrs:n}=r,{iouThreshold:o,maxOutputSize:s,scoreThreshold:a,softNmsSigma:i}=n,{boxes:l,scores:u}=t,c=e.dataIdMap.get(l.dataId).id,p=e.dataIdMap.get(u.dataId).id,m=gL(c,p,s,o,a,i),{pSelectedIndices:f,selectedSize:d,pSelectedScores:h,pValidOutputs:g}=im(e,m);e.wasm._free(g);let x=e.makeOutput([d],"int32",f),b=e.makeOutput([d],"float32",h);return[x,b]}var xL={kernelName:ua,backendName:"wasm",setupFunc:Mee,kernelFunc:Lee};var zee=!1,yL=bt(ia,zee,"bool");var bL;function Bee(r){bL=r.wasm.cwrap(os,null,["number","number","number","number","number"])}function Vee(r){let{inputs:e,backend:t,attrs:n}=r,{indices:o}=e,{depth:s,onValue:a,offValue:i}=n,l=t.makeOutput([...o.shape,s],"int32"),u=t.dataIdMap.get(l.dataId).id,p=t.dataIdMap.get(o.dataId).id;return bL(p,s,a,i,u),l}var wL={kernelName:os,backendName:"wasm",setupFunc:Bee,kernelFunc:Vee};function Gee(r){let{inputs:{x:e},backend:t}=r,n=t.makeOutput(e.shape,e.dtype);return t.typedArrayFromHeap(n).fill(1),n}var _L={kernelName:ni,backendName:"wasm",kernelFunc:Gee};function Wee(r){let{inputs:e,backend:t,attrs:n}=r,{axis:o}=n;if(e.length===1)return cy({inputs:{input:e[0]},backend:t,attrs:{dim:o}});let s=e[0].shape,a=e[0].dtype;e.forEach(c=>{y.assertShapesMatch(s,c.shape,"All tensors passed to stack must have matching shapes"),y.assert(a===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=e.map(c=>{let p=cy({inputs:{input:c},backend:t,attrs:{dim:o}});return i.push(p),p}),u=bC({inputs:l,backend:t,attrs:{axis:o}});return i.forEach(c=>t.disposeData(c.dataId)),u}var kL={kernelName:oi,backendName:"wasm",kernelFunc:Wee};var vL;function jee(r){vL=r.wasm.cwrap(ss,null,["number","array","number","number","array","array","number","number"])}function Uee(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]),a=t.dataIdMap.get(e.dataId).id,i=t.makeOutput(s,e.dtype),l=t.dataIdMap.get(i.dataId).id,u=new Uint8Array(new Int32Array(e.shape).buffer),c=n.map(d=>d[0]),p=n.map(d=>d[1]),m=new Uint8Array(new Int32Array(c).buffer),f=new Uint8Array(new Int32Array(p).buffer);return vL(a,u,e.shape.length,Ot[e.dtype],m,f,o,l),i}var CL={kernelName:ss,backendName:"wasm",kernelFunc:Uee,setupFunc:jee};var qee=!1,IL=bt(is,qee);var SL;function Hee(r){SL=r.wasm.cwrap(as,null,["number","number","number"])}function Kee(r){let{inputs:e,backend:t}=r,{x:n,alpha:o}=e,s=t.dataIdMap.get(n.dataId).id,a=t.dataIdMap.get(o.dataId).id,i=t.makeOutput(n.shape,"float32"),l=t.dataIdMap.get(i.dataId).id;return SL(s,a,l),i}var NL={kernelName:as,backendName:"wasm",setupFunc:Hee,kernelFunc:Kee};var TL;function Xee(r){TL=r.wasm.cwrap(ca,null,["number","number","number","number"])}function Yee(r){let{backend:e,inputs:t,attrs:n}=r,{axis:o,keepDims:s}=n,{x:a}=t,i=e.dataIdMap.get(a.dataId).id,l=i,u=a,{transposed:c,axes:p,originalAxes:m,inputWasTransposed:f}=ln(a,o,e),d=p;if(f){let w=e.dataIdMap.get(c.dataId).id;w!==i&&(u=c,l=w,d=I.getInnerMostAxes(d.length,u.shape.length))}I.assertAxesAreInnerMostDims("prod",d,u.shape.length);let[h,g]=I.computeOutAndReduceShapes(u.shape,d),x=y.sizeFromShape(g),b=e.makeOutput(h,u.dtype);if(y.sizeFromShape(u.shape)!==0){let w=e.dataIdMap.get(b.dataId).id;TL(l,x,Ot[b.dtype],w)}if(f&&e.disposeData(c.dataId),s){let w=I.expandShapeToKeepDim(b.shape,m);b.shape=w}return b}var EL={kernelName:ca,backendName:"wasm",setupFunc:Xee,kernelFunc:Yee};var Zee=r=>{let{backend:e,attrs:t}=r,{start:n,stop:o,step:s,dtype:a}=t,i=rc(n,o,s,a),l=e.makeOutput([i.length],a);return e.typedArrayFromHeap(l).set(i),l},AL={kernelName:xl,backendName:"wasm",kernelFunc:Zee};var Jee=!0,DL=bt(Go,Jee);var $L=yt(ls);var RL=yt(cs);var FL;function Qee(r){FL=r.wasm.cwrap(us,null,["number","number","number","number","number","number","number","number","number","number"])}function ete(r){let{backend:e,inputs:t,attrs:n}=r,{images:o}=t,{alignCorners:s,halfPixelCenters:a,size:i}=n,[l,u]=i,[c,p,m,f]=o.shape,d=[c,l,u,f],h=e.dataIdMap.get(o.dataId),g;h.dtype!=="float32"&&(g=hc({backend:e,inputs:{x:o},attrs:{dtype:"float32"}}),h=e.dataIdMap.get(g.dataId));let x=h.id,b=e.makeOutput(d,"float32");if(y.sizeFromShape(o.shape)===0)return b;let w=e.dataIdMap.get(b.dataId).id;return FL(x,c,p,m,f,l,u,s?1:0,a?1:0,w),g!=null&&e.disposeData(g.dataId),b}var OL={kernelName:us,backendName:"wasm",setupFunc:Qee,kernelFunc:ete};var PL;function tte(r){PL=r.wasm.cwrap(ps,null,["number","array","number","array","number","number"])}function rte(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,{dims:s}=n,a=y.parseAxisParam(s,o.shape);if(o.shape.length===0)return dc({inputs:{x:o},backend:t});let i=t.makeOutput(o.shape,o.dtype),l=t.dataIdMap.get(o.dataId).id,u=t.dataIdMap.get(i.dataId).id,c=new Uint8Array(new Int32Array(a).buffer),p=new Uint8Array(new Int32Array(o.shape).buffer);PL(l,c,a.length,p,o.shape.length,u);let m=qr({inputs:{x:i},attrs:{shape:o.shape},backend:t});return t.disposeData(i.dataId),m}var ML={kernelName:ps,backendName:"wasm",kernelFunc:rte,setupFunc:tte};var LL;function nte(r){LL=r.wasm.cwrap(wa,null,["number","number","number","number","number","number","number","number","array","number","number"])}function ote(r){let{inputs:e,backend:t,attrs:n}=r,{image:o}=e,{radians:s,fillValue:a,center:i}=n,l=t.makeOutput(o.shape,o.dtype),u=t.dataIdMap.get(o.dataId).id,c=t.dataIdMap.get(l.dataId).id,[p,m,f,d]=o.shape,[h,g]=I.getImageCenter(i,m,f),x=a===0,b=255,w=typeof a=="number"?[a,a,a,x?0:b]:[...a,b],_=new Uint8Array(new Int32Array(w).buffer);return LL(u,p,m,f,d,s,h,g,_,w.length,c),l}var zL={kernelName:wa,backendName:"wasm",kernelFunc:ote,setupFunc:nte};var BL=yt(ms);var VL=yt(fs);var GL;function ste(r){GL=r.wasm.cwrap(ma,null,["number","number","number","number","number","number","array","number","number"])}function ite(r){let{backend:e,inputs:t,attrs:n}=r,{indices:o,updates:s}=t,{shape:a}=n,i=e.makeOutput(a,s.dtype);if(y.sizeFromShape(a)===0)return i;let{sliceRank:l,numUpdates:u,sliceSize:c,strides:p,outputSize:m}=Gg.calculateShapes(s,o,a),d=e.dataIdMap.get(o.dataId).id,g=e.dataIdMap.get(s.dataId).id,x=new Uint8Array(new Int32Array(p).buffer),b=e.dataIdMap.get(i.dataId).id;return GL(d,g,Ot[s.dtype],l,u,c,x,m,b),i}var WL={kernelName:ma,backendName:"wasm",setupFunc:ste,kernelFunc:ite};var jL;function ate(r){jL=r.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function lte(r){let{inputs:e,backend:t}=r,{condition:n,t:o,e:s}=e,a=t.dataIdMap.get(n.dataId).id,i=t.dataIdMap.get(o.dataId).id,l=t.dataIdMap.get(s.dataId).id,u=t.makeOutput(o.shape,o.dtype),c=t.dataIdMap.get(u.dataId).id,p=n.shape.length,m=o.shape.length,f=p===0||p>1||m===1?1:y.sizeFromShape(o.shape.slice(1));return jL(a,i,l,f,c),u}var UL={kernelName:ii,backendName:"wasm",kernelFunc:lte,setupFunc:ate};var qL;function ute(r){qL=r.wasm.cwrap(hs,null,["number","number"])}function cte(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 y.sizeFromShape(o.shape)===0||qL(n,s),o}var HL={kernelName:"Sigmoid",backendName:"wasm",setupFunc:ute,kernelFunc:cte};var KL=yt(ds);function gc(r){let{inputs:{x:e},attrs:{begin:t,size:n},backend:o}=r,[s,a]=lr.parseSliceParams(e,t,n),i=lr.isSliceContinous(e.shape,s,a),l=o.readSync(e.dataId),u=o.makeOutput(a,e.dtype),c=y.computeStrides(e.shape),p=o.dataIdMap.get(u.dataId);if(i){let d=lr.computeFlatOffset(s,c);return e.dtype==="string"?p.stringBytes=l.slice(d,d+y.sizeFromShape(a)):o.typedArrayFromHeap(u).set(l.subarray(d,d+y.sizeFromShape(a))),u}if(e.dtype==="string"){let d=nc(l,s,a,e.shape,e.dtype);return p.stringBytes=d,u}let m=o.typedArrayFromHeap(u),f=e.shape.length;if(f===2)pte(l,c[0],m,s,a);else if(f===3)mte(l,c[0],c[1],m,s,a);else if(f===4)fte(l,c[0],c[1],c[2],m,s,a);else{let d=nc(l,s,a,e.shape,e.dtype);m.set(d)}return u}function pte(r,e,t,n,o){let s=0,a=n[0],i=n[1],l=a+o[0];for(let u=a;u<l;u++){let c=u*e+i;t.set(r.subarray(c,c+o[1]),s),s+=o[1]}}function mte(r,e,t,n,o,s){let a=0,i=o[0],l=o[1],u=o[2],c=i+s[0],p=l+s[1];for(let m=i;m<c;m++)for(let f=l;f<p;f++){let d=m*e+f*t+u;n.set(r.subarray(d,d+s[2]),a),a+=s[2]}}function fte(r,e,t,n,o,s,a){let i=0,l=s[0],u=s[1],c=s[2],p=l+a[0],m=u+a[1],f=c+a[2],d=s[3];for(let h=l;h<p;h++)for(let g=u;g<m;g++)for(let x=c;x<f;x++){let b=h*e+g*t+x*n+d;o.set(r.subarray(b,b+a[3]),i),i+=a[3]}}var XL={kernelName:ai,backendName:"wasm",kernelFunc:gc};var YL;function dte(r){YL=r.wasm.cwrap(ys,null,["number","number","number","number"])}function hte(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),a=e.dataIdMap.get(s.dataId).id,i=t.shape[n],l=y.sizeFromShape(t.shape)/i;return y.sizeFromShape(s.shape)===0||YL(o,a,i,l),s}var ZL={kernelName:ys,backendName:"wasm",setupFunc:dte,kernelFunc:hte};function gte(r){let{inputs:e,attrs:t,backend:n}=r,{x:o}=e,{numOrSizeSplits:s,axis:a}=t,i=y.parseAxisParam(a,o.shape)[0],l=I.prepareSplitSize(o,s,i),u=new Array(o.shape.length).fill(0),c=o.shape.slice();return l.map(p=>{let m=[...c];m[i]=p;let f=gc({inputs:{x:o},attrs:{begin:u,size:m},backend:n});return u[i]+=p,f})}var JL={kernelName:li,backendName:"wasm",kernelFunc:gte};var QL=yt(gs);var ez=yt(wl);var xte=!0,tz=bt(bs,xte);var rz;function yte(r){rz=r.wasm.cwrap(oo,null,["number","number","number"])}function bte(r){let{backend:e,inputs:t,attrs:n}=r,{alpha:o}=n,{x:s}=t,a=e.dataIdMap.get(s.dataId).id,i=e.makeOutput(s.shape,s.dtype),l=e.dataIdMap.get(i.dataId).id;return rz(a,o,l),i}var nz={kernelName:oo,backendName:"wasm",setupFunc:yte,kernelFunc:bte};var oz;function wte(r){oz=r.wasm.cwrap(xa,null,["number","array","number","array","array","array","array","array","number","number"])}function _te(r){let{backend:e,inputs:t,attrs:n}=r,{x:o}=t,{begin:s,end:a,strides:i}=n;i==null&&(i=new Array(s.length));let{beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:m}=n,f=I.slice_util.maskToAxes(c);if(f.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(c!==0&&p!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(c!==0&&m!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");let d=o.shape.length-s.length,h=I.slice_util.maskToAxes(p),g=o.shape.slice();h.forEach(G=>{s[G]=0,a[G]=1,g.splice(G,0,1)});let x=qr({inputs:{x:o},attrs:{shape:g},backend:e}),{begin:b,end:w,strides:_}=I.slice_util.getNormalizedAxes(x.shape,f,d,s,a,i,l,u,c);s=b,a=w,i=_;let C=I.slice_util.maskToAxes(m);C.forEach(G=>{a[G]=s[G]+1,i[G]=1});let A=I.slice_util.computeOutShape(s,a,i),D=A.filter((G,j)=>C.indexOf(j)===-1);if(i.every(G=>G===1)){let G=gc({inputs:{x},attrs:{begin:s,size:A},backend:e});e.disposeData(x.dataId);let j=qr({inputs:{x:G},attrs:{shape:D},backend:e});return e.disposeData(G.dataId),j}let R=e.makeOutput(D,"float32");if(!D.some(G=>G===0)){let G=e.dataIdMap.get(x.dataId).id,j=new Uint8Array(new Int32Array(y.computeStrides(x.shape)).buffer),U=new Uint8Array(new Int32Array(s).buffer),q=new Uint8Array(new Int32Array(a).buffer),H=new Uint8Array(new Int32Array(i).buffer),X=new Uint8Array(new Int32Array(D).buffer),ne=new Uint8Array(new Int32Array(y.computeStrides(D)).buffer),Y=e.dataIdMap.get(R.dataId).id;oz(G,j,x.shape.length,U,q,H,X,ne,D.length,Y)}e.disposeData(x.dataId);let M=qr({inputs:{x:R},attrs:{shape:D},backend:e});return e.disposeData(R.dataId),M}var sz={kernelName:xa,backendName:"wasm",setupFunc:wte,kernelFunc:_te};var kte=!0,iz=bt(ws,kte);var az;function vte(r){az=r.wasm.cwrap(xs,null,["number, number, number"])}function Cte(r){let{backend:e,inputs:t,attrs:n}=r,{axis:o,keepDims:s}=n,{x:a}=t,i=e.dataIdMap.get(a.dataId).id,l=i,u=a,{transposed:c,axes:p,originalAxes:m,inputWasTransposed:f}=ln(a,o,e),d=p;if(f){let w=e.dataIdMap.get(c.dataId).id;w!==i&&(u=c,l=w,d=I.getInnerMostAxes(d.length,u.shape.length))}I.assertAxesAreInnerMostDims("sum",d,u.shape.length);let[h,g]=I.computeOutAndReduceShapes(u.shape,d),x=y.sizeFromShape(g),b=e.makeOutput(h,u.dtype);if(y.sizeFromShape(u.shape)!==0){let w=e.dataIdMap.get(b.dataId).id;az(l,x,w)}if(f&&e.disposeData(c.dataId),s){let w=I.expandShapeToKeepDim(b.shape,m);b.shape=w}return b}var lz={kernelName:xs,backendName:"wasm",setupFunc:vte,kernelFunc:Cte};var uz=yt(_s);var cz=yt(ks);var pz;function Ite(r){pz=r.wasm.cwrap(Un,null,["number","array","number","array","number","number"])}function Ste(r){let{inputs:e,backend:t,attrs:n}=r,{x:o}=e,s=t.dataIdMap.get(o.dataId).id,{reps:a}=n,i=new Array(o.shape.length);for(let m=0;m<i.length;m++)i[m]=o.shape[m]*a[m];let l=new Uint8Array(new Int32Array(o.shape).buffer),u=new Uint8Array(new Int32Array(i).buffer),c=t.makeOutput(i,o.dtype),p=t.dataIdMap.get(c.dataId).id;return pz(s,l,o.shape.length,u,i.length,Ot[c.dtype],p),c}var mz={kernelName:Un,backendName:"wasm",setupFunc:Ite,kernelFunc:Ste};var fz;function Nte(r){fz=r.wasm.cwrap(ya,null,["number","array","number","number","number","bool","number","number"])}var Tte=({inputs:r,backend:e,attrs:t})=>{let{x:n}=r,{k:o,sorted:s}=t,a=e.dataIdMap.get(n.dataId).id,i=new Uint8Array(new Int32Array(n.shape).buffer),l=n.shape.slice();l[l.length-1]=o;let u=e.makeOutput(l,n.dtype),c=e.dataIdMap.get(u.dataId).id,p=e.makeOutput(l,"int32"),m=e.dataIdMap.get(p.dataId).id;return fz(a,i,n.shape.length,Ot[n.dtype],o,s,c,m),[u,p]},dz={kernelName:ya,backendName:"wasm",setupFunc:Nte,kernelFunc:Tte};var hz;function Ete(r){hz=r.wasm.cwrap(ba,null,["number","number","bool","number","number","number","number","number","number","array","number","number","number","number","number"])}function Ate(r){let{backend:e,inputs:t,attrs:n}=r,{image:o,transforms:s}=t,{interpolation:a,fillMode:i,fillValue:l,outputShape:u}=n,[c,p,m,f]=o.shape,[d,h]=u!=null?u:[p,m],g=[c,d,h,f],x=new Uint8Array(new Int32Array(y.computeStrides(o.shape)).buffer),b=e.makeOutput(g,o.dtype),w=e.dataIdMap.get(b.dataId).id,C=e.dataIdMap.get(o.dataId).id,D=e.dataIdMap.get(s.dataId).id,$=a==="nearest"?1:2,R;switch(i){case"constant":R=1;break;case"reflect":R=2;break;case"wrap":R=3;break;case"nearest":R=4;break;default:R=1;break}return hz(C,D,s.shape[0]>1,c,d,h,f,m,p,x,o.shape.length-1,$,R,l,w),b}var gz={kernelName:ba,backendName:"wasm",setupFunc:Ete,kernelFunc:Ate};function Dte(r){let{inputs:e,backend:t,attrs:n}=r,{value:o}=e,{axis:s}=n;s<0&&(s+=o.shape.length);let a=o.shape[s],i=o.shape.length,l=new Array(i-1),u=0;for(let f=0;f<i;f++)f!==s&&(l[u++]=o.shape[f]);let c=new Array(a),p=new Array(i).fill(0),m=o.shape.slice();m[s]=1;for(let f=0;f<c.length;f++)p[s]=f,c[f]=gc({inputs:{x:o},attrs:{begin:p,size:m},backend:t});return c.map(({dataId:f,dtype:d})=>({dataId:f,dtype:d,shape:l}))}var xz={kernelName:ui,backendName:"wasm",kernelFunc:Dte};function $te(r){let{inputs:{x:e},backend:t}=r,n=t.makeOutput(e.shape,e.dtype);return t.typedArrayFromHeap(n).fill(0),n}var yz={kernelName:ci,backendName:"wasm",kernelFunc:$te};var Rte=[jP,UP,HP,JP,eM,rM,oM,aM,lM,uM,pM,mM,dM,gM,xM,bM,_M,vM,IM,SM,NM,TM,EM,DM,$M,RM,WP,OM,MM,zM,VM,WM,jM,UM,KP,HM,KM,XM,YM,ZM,QM,eL,rL,oL,iL,aL,uL,cL,pL,fL,hL,xL,yL,wL,_L,kL,CL,IL,NL,EL,AL,DL,$L,RL,sM,OL,ML,zL,VL,BL,WL,UL,HL,KL,XL,ZL,JL,QL,ez,tz,nz,sz,iz,lz,uz,cz,mz,dz,gz,YP,xz,yz];for(let r of Rte)lu(r);var kC=W();kC.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])));kC.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(kC.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 NC=nu(_z());var kz='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 Cz=nu(vz());var fy=class extends Xs{constructor(e){super();this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.init(),this.dataIdMap=new al(this,Ns())}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=y.now();return e(),{kernelMs:y.now()-t}}move(e,t,n,o,s){let a=this.dataIdNextNumber++;if(o==="string"){let c=t;this.dataIdMap.set(e,{id:a,stringBytes:c,shape:n,dtype:o,memoryOffset:null,refCount:s});return}let i=y.sizeFromShape(n),l=i*y.bytesPerElement(o),u=this.wasm._malloc(l);this.dataIdMap.set(e,{id:a,memoryOffset:u,shape:n,dtype:o,refCount:s}),this.wasm.tfjs.registerTensor(a,i,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 a=this.wasm.HEAPU8.slice(t,t+y.sizeFromShape(o)*y.bytesPerElement(n));return Ote(a.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 a=y.sizeFromShape(e);this.wasm.tfjs.registerTensor(s,a,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),a=y.sizeFromShape(e);switch(t){case"float32":return new Float32Array(o,s,a);case"int32":return new Int32Array(o,s,a);case"bool":return new Uint8Array(o,s,a);default:throw new Error(`Unknown dtype ${t}`)}}};function Fte(r){return(e,t)=>(y.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 Iz(r,e,t){if(dy!=null)return dy;let n="tfjs-backend-wasm.wasm";return r&&e?n="tfjs-backend-wasm-threaded-simd.wasm":r&&(n="tfjs-backend-wasm-simd.wasm"),wd!=null&&wd[n]!=null?wd[n]:t+n}async function Sz(){let[r,e]=await Promise.all([W().getAsync("WASM_HAS_SIMD_SUPPORT"),W().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((t,n)=>{let o={};o.locateFile=(i,l)=>{if(i.endsWith(".worker.js")){let u=kz,c=new Blob([u],{type:"application/javascript"});return URL.createObjectURL(c)}return i.endsWith(".wasm")?Iz(r,e,bd!=null?bd:l):l+i},TC&&(o.instantiateWasm=Fte(Iz(r,e,bd!=null?bd:"")));let s=!1;o.onAbort=()=>{if(s||_d)return;_d=!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 a;e&&r&&dy==null?(o.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+NC.default.toString()],{type:"text/javascript"}),a=(0,NC.default)(o)):a=(0,Cz.default)(o),a.then(i=>{s=!0,_d=!1;let l=null;i.tfjs={init:i.cwrap("init",null,[]),registerTensor:i.cwrap("register_tensor",null,["number","number","number"]),disposeData:i.cwrap("dispose_data",l,["number"]),dispose:i.cwrap("dispose",l,[])},t({wasm:i})})})}function Ote(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 Pte=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],dy=null,bd=null,wd={},_d=!1,TC=!1;function Mte(r,e=!1){if(I_("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),_d)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");dy=r,TC=e}function Lte(r,e=!1){if(_d)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")bd=r;else{wd=r;let t=Pte.filter(n=>wd[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.`)}TC=e}var EC="3.7.0";var zte=2;Rp("wasm",async()=>{let{wasm:r}=await Sz();return new fy(r)},zte);O().prototype.abs=function(){return this.throwIfDisposed(),Tt(this)};O().prototype.acos=function(){return this.throwIfDisposed(),hf(this)};O().prototype.acosh=function(){return this.throwIfDisposed(),gf(this)};O().prototype.add=function(r){return this.throwIfDisposed(),J(this,r)};O().prototype.all=function(r,e){return this.throwIfDisposed(),bu(this,r,e)};O().prototype.any=function(r,e){return this.throwIfDisposed(),Nl(this,r,e)};O().prototype.argMax=function(r){return this.throwIfDisposed(),Tl(this,r)};O().prototype.argMin=function(r){return this.throwIfDisposed(),xf(this,r)};O().prototype.asScalar=function(){return this.throwIfDisposed(),E(this.size===1,()=>"The array must have only 1 element."),L(this,[])};O().prototype.asType=function(r){return this.throwIfDisposed(),oe(this,r)};O().prototype.as1D=function(){return this.throwIfDisposed(),L(this,[this.size])};O().prototype.as2D=function(r,e){return this.throwIfDisposed(),L(this,[r,e])};O().prototype.as3D=function(r,e,t){return this.throwIfDisposed(),L(this,[r,e,t])};O().prototype.as4D=function(r,e,t,n){return this.throwIfDisposed(),L(this,[r,e,t,n])};O().prototype.as5D=function(r,e,t,n,o){return this.throwIfDisposed(),L(this,[r,e,t,n,o])};O().prototype.asin=function(){return this.throwIfDisposed(),yf(this)};O().prototype.asinh=function(){return this.throwIfDisposed(),bf(this)};O().prototype.atan=function(){return this.throwIfDisposed(),wf(this)};O().prototype.atan2=function(r){return this.throwIfDisposed(),_f(this,r)};O().prototype.atanh=function(){return this.throwIfDisposed(),kf(this)};O().prototype.avgPool=function(r,e,t,n){return this.throwIfDisposed(),Sa(this,r,e,t,n)};O().prototype.batchToSpaceND=function(r,e){return this.throwIfDisposed(),Na(this,r,e)};O().prototype.batchNorm=function(r,e,t,n,o){return this.throwIfDisposed(),uo(this,r,e,t,n,o)};O().prototype.broadcastTo=function(r){return this.throwIfDisposed(),Ta(this,r)};O().prototype.cast=function(r){return this.throwIfDisposed(),oe(this,r)};O().prototype.ceil=function(){return this.throwIfDisposed(),If(this)};O().prototype.clipByValue=function(r,e){return this.throwIfDisposed(),fr(this,r,e)};O().prototype.concat=function(r,e){return this.throwIfDisposed(),r instanceof Me&&(r=[r]),et([this,...r],e)};O().prototype.conv1d=function(r,e,t,n,o,s){return this.throwIfDisposed(),ku(this,r,e,t,n,o,s)};O().prototype.conv2dTranspose=function(r,e,t,n,o){return this.throwIfDisposed(),vu(this,r,e,t,n,o)};O().prototype.conv2d=function(r,e,t,n,o,s){return this.throwIfDisposed(),on(this,r,e,t,n,o,s)};O().prototype.cos=function(){return this.throwIfDisposed(),Ea(this)};O().prototype.cosh=function(){return this.throwIfDisposed(),Cu(this)};O().prototype.cumsum=function(r,e,t){return this.throwIfDisposed(),Iu(this,r,e,t)};O().prototype.depthToSpace=function(r,e){return this.throwIfDisposed(),Nf(this,r,e)};O().prototype.depthwiseConv2d=function(r,e,t,n,o,s){return this.throwIfDisposed(),Es(this,r,e,t,n,o,s)};O().prototype.dilation2d=function(r,e,t,n,o){return this.throwIfDisposed(),Tf(this,r,e,t,n,o)};O().prototype.divNoNan=function(r){return this.throwIfDisposed(),Ef(this,r)};O().prototype.div=function(r){return this.throwIfDisposed(),ue(this,r)};O().prototype.dot=function(r){return this.throwIfDisposed(),z_(this,r)};O().prototype.elu=function(){return this.throwIfDisposed(),As(this)};O().prototype.equal=function(r){return this.throwIfDisposed(),On(this,r)};O().prototype.erf=function(){return this.throwIfDisposed(),Af(this)};O().prototype.exp=function(){return this.throwIfDisposed(),nr(this)};O().prototype.expandDims=function(r){return this.throwIfDisposed(),dr(this,r)};O().prototype.expm1=function(){return this.throwIfDisposed(),Df(this)};O().prototype.fft=function(){return this.throwIfDisposed(),Ma(this)};O().prototype.flatten=function(){return this.throwIfDisposed(),L(this,[this.size])};O().prototype.floor=function(){return this.throwIfDisposed(),$s(this)};O().prototype.floorDiv=function(r){return this.throwIfDisposed(),yu(this,r)};O().prototype.gather=function(r,e){return this.throwIfDisposed(),co(this,r,e)};O().prototype.greaterEqual=function(r){return this.throwIfDisposed(),_n(this,r)};O().prototype.greater=function(r){return this.throwIfDisposed(),qt(this,r)};O().prototype.ifft=function(){return this.throwIfDisposed(),gi(this)};O().prototype.irfft=function(){return this.throwIfDisposed(),zu(this)};O().prototype.isFinite=function(){return this.throwIfDisposed(),V_(this)};O().prototype.isInf=function(){return this.throwIfDisposed(),G_(this)};O().prototype.isNaN=function(){return this.throwIfDisposed(),$f(this)};O().prototype.leakyRelu=function(r){return this.throwIfDisposed(),Aa(this,r)};O().prototype.lessEqual=function(r){return this.throwIfDisposed(),kn(this,r)};O().prototype.less=function(r){return this.throwIfDisposed(),Nu(this,r)};O().prototype.localResponseNormalization=function(r,e,t,n){return this.throwIfDisposed(),Rf(this,r,e,t,n)};O().prototype.logSigmoid=function(){return this.throwIfDisposed(),j_(this)};O().prototype.logSoftmax=function(r){return this.throwIfDisposed(),Eu(this,r)};O().prototype.logSumExp=function(r,e){return this.throwIfDisposed(),Of(this,r,e)};O().prototype.log=function(){return this.throwIfDisposed(),hr(this)};O().prototype.log1p=function(){return this.throwIfDisposed(),Tu(this)};O().prototype.logicalAnd=function(r){return this.throwIfDisposed(),_r(this,r)};O().prototype.logicalNot=function(){return this.throwIfDisposed(),Da(this)};O().prototype.logicalOr=function(r){return this.throwIfDisposed(),Au(this,r)};O().prototype.logicalXor=function(r){return this.throwIfDisposed(),K_(this,r)};O().prototype.matMul=function(r,e,t){return this.throwIfDisposed(),Be(this,r,e,t)};O().prototype.maxPool=function(r,e,t,n){return this.throwIfDisposed(),$a(this,r,e,t,n)};O().prototype.max=function(r,e){return this.throwIfDisposed(),Er(this,r,e)};O().prototype.maximum=function(r){return this.throwIfDisposed(),an(this,r)};O().prototype.mean=function(r,e){return this.throwIfDisposed(),ht(this,r,e)};O().prototype.min=function(r,e){return this.throwIfDisposed(),El(this,r,e)};O().prototype.minimum=function(r){return this.throwIfDisposed(),Rs(this,r)};O().prototype.mirrorPad=function(r,e){return this.throwIfDisposed(),Mf(this,r,e)};O().prototype.mod=function(r){return this.throwIfDisposed(),Lf(this,r)};O().prototype.mul=function(r){return this.throwIfDisposed(),P(this,r)};O().prototype.neg=function(){return this.throwIfDisposed(),Ke(this)};O().prototype.norm=function(r,e,t){return this.throwIfDisposed(),Vp(this,r,e,t)};O().prototype.notEqual=function(r){return this.throwIfDisposed(),fo(this,r)};O().prototype.oneHot=function(r,e=1,t=0){return this.throwIfDisposed(),Ss(this,r,e,t)};O().prototype.onesLike=function(){return this.throwIfDisposed(),ur(this)};O().prototype.pad=function(r,e){return this.throwIfDisposed(),Wr(this,r,e)};O().prototype.pool=function(r,e,t,n,o){return this.throwIfDisposed(),Z_(this,r,e,t,n,o)};O().prototype.pow=function(r){return this.throwIfDisposed(),jr(this,r)};O().prototype.prelu=function(r){return this.throwIfDisposed(),Fa(this,r)};O().prototype.prod=function(r,e){return this.throwIfDisposed(),Du(this,r,e)};O().prototype.reciprocal=function(){return this.throwIfDisposed(),zf(this)};O().prototype.relu=function(){return this.throwIfDisposed(),Mr(this)};O().prototype.relu6=function(){return this.throwIfDisposed(),Ru(this)};O().prototype.reshapeAs=function(r){return this.throwIfDisposed(),L(this,r.shape)};O().prototype.reshape=function(r){return this.throwIfDisposed(),L(this,r)};O().prototype.resizeBilinear=function(r,e,t){return this.throwIfDisposed(),cx(this,r,e,t)};O().prototype.resizeNearestNeighbor=function(r,e,t){return this.throwIfDisposed(),px(this,r,e,t)};O().prototype.reverse=function(r){return this.throwIfDisposed(),Jt(this,r)};O().prototype.rfft=function(){return this.throwIfDisposed(),La(this)};O().prototype.round=function(){return this.throwIfDisposed(),Fu(this)};O().prototype.rsqrt=function(){return this.throwIfDisposed(),Ou(this)};O().prototype.selu=function(){return this.throwIfDisposed(),Pu(this)};O().prototype.separableConv2d=function(r,e,t,n,o,s){return this.throwIfDisposed(),Bf(this,r,e,t,n,o,s)};O().prototype.sigmoid=function(){return this.throwIfDisposed(),Pr(this)};O().prototype.sign=function(){return this.throwIfDisposed(),Vf(this)};O().prototype.sin=function(){return this.throwIfDisposed(),Mu(this)};O().prototype.sinh=function(){return this.throwIfDisposed(),Lu(this)};O().prototype.slice=function(r,e){return this.throwIfDisposed(),Fe(this,r,e)};O().prototype.softmax=function(r){return this.throwIfDisposed(),Pa(this,r)};O().prototype.softplus=function(){return this.throwIfDisposed(),po(this)};O().prototype.spaceToBatchND=function(r,e){return this.throwIfDisposed(),Ra(this,r,e)};O().prototype.split=function(r,e){return this.throwIfDisposed(),sr(this,r,e)};O().prototype.sqrt=function(){return this.throwIfDisposed(),xt(this)};O().prototype.square=function(){return this.throwIfDisposed(),Le(this)};O().prototype.squaredDifference=function(r){return this.throwIfDisposed(),Bu(this,r)};O().prototype.squeeze=function(r){return this.throwIfDisposed(),Pn(this,r)};O().prototype.stack=function(r,e){this.throwIfDisposed();let t=r instanceof Me?[this,r]:[this,...r];return Ht(t,e)};O().prototype.step=function(r){return this.throwIfDisposed(),Os(this,r)};O().prototype.stridedSlice=function(r,e,t,n,o,s,a,i){return this.throwIfDisposed(),jf(this,r,e,t,n,o,s,a,i)};O().prototype.sub=function(r){return this.throwIfDisposed(),ce(this,r)};O().prototype.sum=function(r,e){return this.throwIfDisposed(),de(this,r,e)};O().prototype.tan=function(){return this.throwIfDisposed(),Uf(this)};O().prototype.tanh=function(){return this.throwIfDisposed(),Ts(this)};O().prototype.tile=function(r){return this.throwIfDisposed(),Kn(this,r)};O().prototype.toBool=function(){return this.throwIfDisposed(),oe(this,"bool")};O().prototype.toFloat=function(){return this.throwIfDisposed(),oe(this,"float32")};O().prototype.toInt=function(){return this.throwIfDisposed(),oe(this,"int32")};O().prototype.topk=function(r,e){return this.throwIfDisposed(),qf(this,r,e)};O().prototype.transpose=function(r){return this.throwIfDisposed(),qe(this,r)};O().prototype.unique=function(r){return this.throwIfDisposed(),Bp(this,r)};O().prototype.unsortedSegmentSum=function(r,e){return this.throwIfDisposed(),Hf(this,r,e)};O().prototype.unstack=function(r){return this.throwIfDisposed(),gr(this,r)};O().prototype.where=function(r,e){return this.throwIfDisposed(),Ct(r,this,e)};O().prototype.zerosLike=function(){return this.throwIfDisposed(),Se(this)};var hy={kernelName:Js,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>P(r,Os(oe(t,"float32"),-1))}}};var Nz={kernelName:Ri,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let n=Le(oe(t,"float32")),o=xt(ce(pe(1),n));return Ke(ue(r,o))}}}};var Tz={kernelName:Fi,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let n=xt(ce(Le(oe(t,"float32")),1));return ue(r,n)}}}};var Ez={kernelName:jn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,n]=e,o=Ve(t.shape,n.shape);return{a:()=>{let i=r,l=vt(t.shape,o);return l.length>0&&(i=de(i,l)),L(i,t.shape)},b:()=>{let i=r,l=vt(n.shape,o);return l.length>0&&(i=de(i,l)),L(i,n.shape)}}}};var Az={kernelName:$o,saveAllInputs:!0,gradFunc:(r,e)=>{let t={};return e.forEach((n,o)=>{t[o]=()=>r.clone()}),t}};var Dz={kernelName:Ro,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>Se(t)}}};var $z={kernelName:ll,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>Se(t)}}};var Rz={kernelName:Mi,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>ue(r,xt(ce(pe(1),Le(oe(t,"float32")))))}}};var Fz={kernelName:Li,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let n=xt(J(pe(1),Le(oe(t,"float32"))));return ue(r,n)}}}};var Oz={kernelName:Vi,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,n]=e,o=Ve(t.shape,n.shape);return{a:()=>{let i=J(Le(t),Le(n)),l=P(r,ue(n,i)),u=vt(t.shape,o);return u.length>0&&(l=de(l,u)),L(l,t.shape)},b:()=>{let i=J(Le(t),Le(n)),l=Ke(P(r,ue(t,i))),u=vt(n.shape,o);return u.length>0&&(l=de(l,u)),L(l,n.shape)}}}};var Pz={kernelName:zi,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>ue(r,J(Le(oe(t,"float32")),1))}}};var Mz={kernelName:Bi,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>ue(r,ce(pe(1),Le(oe(t,"float32"))))}}};function Bte(r,e,t,n,o,s){let a=k(r,"dy","avgPool3dGrad"),i=k(e,"input","avgPool3dGrad"),l=a,u=i,c=!1;i.rank===4&&(c=!0,l=L(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]]),u=L(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),E(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),E(u.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`),s!=null&&E(st(o),()=>`Error in avgPool3dGrad: pad must be an integer when using, dimRoundingMode ${s} but got pad ${o}.`);let p={dy:l,input:u},m={filterSize:t,strides:n,pad:o,dimRoundingMode:s},f=T.runKernel(jc,p,m);return c?L(f,[f.shape[1],f.shape[2],f.shape[3],f.shape[4]]):f}var Lz=S({avgPool3dGrad_:Bte});var zz={kernelName:ul,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[n]=e,{filterSize:o,strides:s,pad:a,dimRoundingMode:i}=t;return{x:()=>Lz(r,n,o,s,a,i)}}};function Vte(r,e,t,n,o){let s=k(r,"dy","avgPoolGrad"),a=k(e,"input","avgPoolGrad");E(a.rank===s.rank,()=>`Rank of input (${a.rank}) does not match rank of dy (${s.rank})`);let i=a,l=s,u=!1;a.rank===3&&(u=!0,i=L(a,[1,a.shape[0],a.shape[1],a.shape[2]]),l=L(s,[1,s.shape[0],s.shape[1],s.shape[2]])),E(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),E(i.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${i.rank}.`);let c={dy:l,input:i},p={filterSize:t,strides:n,pad:o},m=T.runKernel(Wc,c,p);return u?L(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Bz=S({avgPoolGrad_:Vte});var Vz={kernelName:Fo,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[n]=e,{filterSize:o,strides:s,pad:a}=t;return{x:()=>Bz(r,n,o,s,a)}}};var Gz={kernelName:Oo,inputsToSave:["a","b"],gradFunc:(r,e,t)=>{let[n,o]=e,{transposeA:s,transposeB:a}=t;return!s&&!a?{a:()=>Be(r,o,!1,!0),b:()=>Be(n,r,!0,!1)}:!s&&a?{a:()=>Be(r,o,!1,!1),b:()=>Be(r,n,!0,!1)}:s&&!a?{a:()=>Be(o,r,!1,!0),b:()=>Be(n,r,!1,!1)}:{a:()=>Be(o,r,!0,!0),b:()=>Be(r,n,!0,!0)}}};var Wz={kernelName:cl,gradFunc:(r,e,t)=>{let{blockShape:n,crops:o}=t;return{x:()=>Ra(r,n,o)}}};var jz={kernelName:x1,gradFunc:(r,e,t)=>{let n=t,o=n.inputShape,s=n.shape,a=Array.from(s);for(let l=o.length-1;l>=0;l--)if(o[l]===s[l])a[l]=1;else if(o[l]!==1)throw new Error(`broadcastTo(): [${o}] cannot be broadcast to [${s}].`);let i=[];for(let l=0;l<a.length;l++)a[l]>1&&i.push(l);return{x:()=>de(r,i,!0)}}};var Uz={kernelName:to,gradFunc:r=>({x:()=>r.clone()})};var qz={kernelName:Po,gradFunc:r=>({x:()=>Se(r)})};var Hz={kernelName:ro,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[n]=e,{clipValueMin:o,clipValueMax:s}=t;return{x:()=>Ct(_r(_n(n,o),kn(n,s)),r,Se(r))}}};var Kz={kernelName:pl,inputsToSave:["x"],gradFunc:hy.gradFunc};var Xz={kernelName:Qs,saveAllInputs:!0,gradFunc:(r,e,t)=>{let n=e.map(l=>l.shape),{axis:o}=t,s=ar(o,e[0].shape)[0],a=n.map(l=>l[s]);return sr(r,a,s).map(l=>()=>l)}};var Yz={kernelName:Mo,inputsToSave:["x","filter"],gradFunc:(r,e,t)=>{let[n,o]=e,{dilations:s,strides:a,pad:i,dataFormat:l}=t;return E(Hn(s),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`),{x:()=>Op(n.shape,r,o,a,i,l),filter:()=>Gp(n,r,o.shape,a,i,l)}}};var Zz={kernelName:Lo,inputsToSave:["dy","filter"],gradFunc:(r,e,t)=>{let[n,o]=e,{strides:s,pad:a,dataFormat:i,dimRoundingMode:l}=t;return{dy:()=>on(r,o,s,a,i,1,l),filter:()=>Gp(r,n,o.shape,s,a,i,l)}}};function Gte(r,e,t,n,o){let s=r;r.rank===4&&(s=L(r,[1,r.shape[0],r.shape[1],r.shape[2],r.shape[3]]));let a=e;a.rank===4&&(a=L(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]])),E(s.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${s.shape}.`),E(a.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${a.shape}.`),E(t.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${t}.`),E(s.shape[4]===t[3],()=>`Error in conv3dDerFilter: depth of input ${s.shape[4]}) must match input depth in filter (${t[3]}.`),E(a.shape[4]===t[4],()=>`Error in conv3dDerFilter: depth of dy (${a.shape[4]}) must match output depth for filter (${t[4]}).`);let i={x:s,dy:a},l={strides:n,pad:o,filterShape:t};return T.runKernel(Kc,i,l)}var Jz=S({conv3DBackpropFilter_:Gte});var Qz={kernelName:ml,inputsToSave:["x","filter"],gradFunc:(r,e,t)=>{let{dilations:n,strides:o,pad:s}=t;E(Hn(n),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${n}'`);let[a,i]=e;return{x:()=>Hg(a.shape,r,i,o,s),filter:()=>Jz(a,r,i.shape,o,s)}}};var e3={kernelName:zo,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>P(Ke(Mu(oe(t,"float32"))),r)}}};var t3={kernelName:Gi,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>P(Lu(oe(t,"float32")),r)}}};var r3={kernelName:Bo,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[n]=e,{axis:o,exclusive:s,reverse:a}=t;return{x:()=>{let i=H_([o],n.rank),l=Iu(r,o,s,!a);return i!=null&&(l=qe(l,i)),l}}}};var n3={kernelName:Vo,inputsToSave:["x","filter"],gradFunc:(r,e,t)=>{let{dilations:n,strides:o,pad:s,dimRoundingMode:a}=t,i=n==null?[1,1]:n;E(Hn(i),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${i}'`);let[l,u]=e;return E(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),E(u.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${u.rank}.`),E(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]}.`),E(Tr(o,i),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${i}'.`),a!=null&&E(st(s),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`),{x:()=>ox(l.shape,r,u,o,s,n,a),filter:()=>nx(l,r,u.shape,o,s,n,a)}}};var o3={kernelName:fl,inputsToSave:["x","filter"],gradFunc:(r,e,t)=>{let[n,o]=e,s={x:n,filter:o,dy:r},a={x:n,filter:o,dy:r};return{x:()=>T.runKernel(rf,s,t),filter:()=>T.runKernel(nf,a,t)}}};var s3={kernelName:Ui,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e,n={dy:r,y:t};return{x:()=>T.runKernel(tp,n)}}};var i3={kernelName:qi,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e,n=P(nr(Ke(Le(t))),2/Math.sqrt(Math.PI));return{x:()=>P(r,n)}}};var a3={kernelName:Wo,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e;return{x:()=>P(r,t)}}};var l3={kernelName:ei,inputsToSave:["input"],gradFunc:(r,e)=>{let[t]=e;return{input:()=>L(r,t.shape)}}};var u3={kernelName:Ki,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>P(r,nr(t))}}};var c3={kernelName:jo,gradFunc:r=>({x:()=>Se(r)})};var p3={kernelName:Uo,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,n]=e,o=Ve(t.shape,n.shape);return{a:()=>{let i=ue(r,oe(n,"float32")),l=vt(t.shape,o);return l.length>0?L(de(i,l),t.shape):i},b:()=>{let i=P(r,oe(t,"float32")),l=vt(n.shape,o);l.length>0&&(i=L(de(i,l),n.shape));let u=Le(n);return Ke(ue(i,oe(u,"float32")))}}}};var m3={kernelName:qo,inputsToSave:["x","mean","variance","scale"],gradFunc:(r,e,t)=>{let{varianceEpsilon:n}=t,[o,s,a,i]=e,l=i==null?pe(1):i,u=vt(s.shape,o.shape),c=[];if(s.rank===1){for(let _=0;_<o.shape.length-1;++_)c.push(o.shape[_]);c.push(1)}let p=ce(o,s),m=P(r,l),f=Ou(J(a,pe(n))),d=P(P(P(f,f),f),pe(-.5));return{x:()=>s.rank===1?L(P(P(r,Kn(L(f,[1,1,1,s.shape[0]]),c)),l),o.shape):L(P(P(r,f),l),o.shape),mean:()=>{let _=P(P(f,pe(-1)),m);return s.rank===1&&(_=de(_,u)),L(_,s.shape)},variance:()=>{let _=P(P(d,p),m);return s.rank===1&&(_=de(_,u)),L(_,s.shape)},scale:()=>{let _=P(p,f),C=P(r,_);return s.rank===1&&(C=de(C,u)),L(C,s.shape)},offset:()=>{let _=r;return s.rank===1&&(_=de(_,u)),L(_,s.shape)}}}};var f3={kernelName:ti,inputsToSave:["x","indices"],gradFunc:(r,e,t)=>{let[n,o]=e,{axis:s}=t,a=ar(s,n.shape)[0];return{x:()=>{let l=n.shape,u=o.size,c=l.slice(0,a),p=c.length,m=l.slice(s,l.length).slice(1),f=m.length,d=d3(0,p),h=d3(p+1,p+1+f),g=h3([c,[u],m]),x=L(r,g),b=L(o,[u]),w=h3([[p],d,h]),_=qe(x,w),C=Hf(_,b,n.shape[a]),A=Ff(w);return C=qe(C,A),C},indices:()=>o}}};function d3(r,e){let t=[];for(let n=r;n<e;++n)t.push(n);return t}function h3(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 g3={kernelName:Ho,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,n]=e;return{a:()=>Se(t),b:()=>Se(n)}}};var x3={kernelName:no,gradFunc:r=>({x:()=>oe(r,"float32")})};var y3={kernelName:Ji,gradFunc:r=>({x:()=>Se(r)})};var b3={kernelName:Qi,gradFunc:r=>({x:()=>Se(r)})};var w3={kernelName:ea,gradFunc:r=>({x:()=>Se(r)})};var _3={kernelName:Ko,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[n]=e,{alpha:o}=t,s=qt(n,0);return{x:()=>Ct(s,r,P(r,o))}}};var k3={kernelName:na,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>ue(r,J(t,1))}}};var v3={kernelName:Xo,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>ue(r,oe(t,"float32"))}}};var C3={kernelName:y1,inputsToSave:[],outputsToSave:[!0],gradFunc:(r,e,t)=>{let[n]=e,{axis:o}=t;return{logits:()=>{let s=!0,a=nr(n);return ce(r,P(de(r,o,s),a))}}}};function Wte(r,e,t,n=5,o=1,s=1,a=.5){let i={x:r,y:e,dy:t},l={depthRadius:n,bias:o,alpha:s,beta:a};return T.runKernel(ip,i,l)}var I3=S({localResponseNormalizationBackprop_:Wte});var S3={kernelName:hl,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let[n,o]=e,{depthRadius:s,bias:a,alpha:i,beta:l}=t;return{x:()=>I3(n,o,r,s,a,i,l)}}};function gy(r,e,t,n){return e.rank<t.rank&&(e=L(e,mo(e.shape,n))),r.rank<t.rank&&(r=L(r,mo(r.shape,n))),{x:()=>P(r,oe(On(t,e),r.dtype))}}var AC={kernelName:Yo,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let n=t,{reductionIndices:o}=n,s=e[0],a=e[1],i=ar(o,s.shape),l=gy(r,a,s,i);return{x:()=>l.x()}}};var N3={kernelName:Zo,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,n]=e;return{a:()=>P(r,oe(_n(t,n),"float32")),b:()=>P(r,oe(Nu(t,n),"float32"))}}};function jte(r,e,t,n,o,s,a){let i=k(r,"dy","maxPool3dGrad"),l=k(e,"input","maxPool3dGrad"),u=k(t,"output","maxPool3dGrad"),c=i,p=l,m=u,f=!1;l.rank===4&&(f=!0,c=L(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),p=L(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),m=L(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]])),E(c.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`),E(p.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${p.rank}.`),E(m.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${m.rank}.`),a!=null&&E(st(s),()=>`Error in maxPool3dGrad: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`);let d={dy:c,input:p,output:m},h={filterSize:n,strides:o,pad:s,dimRoundingMode:a},g=T.runKernel(lp,d,h);return f?L(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var T3=S({maxPool3dGrad_:jte});var E3={kernelName:gl,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let[n,o]=e,{filterSize:s,strides:a,pad:i,dimRoundingMode:l}=t;return{x:()=>T3(r,n,o,s,a,i,l)}}};function Ute(r,e,t,n,o,s,a){let i=k(r,"dy","maxPoolGrad"),l=k(e,"input","maxPoolGrad"),u=k(t,"output","maxPoolGrad");E(l.rank===i.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${i.rank})`),E(i.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${i.rank}.`),E(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),a!=null&&E(st(s),()=>`Error in maxPoolGrad: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`);let c={dy:i,input:l,output:u},p={filterSize:n,strides:o,pad:s,dimRoundingMode:a};return T.runKernel(ap,c,p)}var A3=S({maxPoolGrad_:Ute});var D3={kernelName:Jo,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let[n,o]=e,{filterSize:s,strides:a,pad:i}=t;return{x:()=>A3(r,n,o,s,a,i)}}};var $3={kernelName:Qo,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[n]=e,{axis:o}=t,s=ar(o,n.shape),i=q_(n.shape,s)[1],l=ot(i);return{x:()=>{let c=n.shape.slice();s.forEach(f=>{c[f]=1});let p=L(r,c);return ue(P(p,or(n.shape,"float32")),l)}}}};var R3={kernelName:es,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let n=t,{axis:o}=n,[s,a]=e,i=ar(o,s.shape),l=gy(r,a,s,i);return{x:()=>l.x()}}};var F3={kernelName:ts,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,n]=e;return{a:()=>P(r,oe(kn(t,n),"float32")),b:()=>P(r,oe(qt(t,n),"float32"))}}};var O3={kernelName:rs,inputsToSave:["x"],gradFunc:(r,e,t)=>{let n=e[0],{paddings:o}=t,s=o.map(a=>a[0]);return{x:()=>Fe(r,s,n.shape)}}};var P3={kernelName:sa,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,n]=e,o=Ve(t.shape,n.shape);return{a:()=>{let i=vt(t.shape,o);return i.length>0?L(de(r,i),t.shape):r},b:()=>{let i=P(r,Ke($s(ue(t,n)))),l=vt(n.shape,o);return l.length>0?L(de(i,l),n.shape):i}}}};var M3={kernelName:ns,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,n]=e,o=Ve(t.shape,n.shape);return{a:()=>{let i=P(r,oe(n,"float32")),l=vt(t.shape,o);return l.length>0?L(de(i,l),t.shape):i},b:()=>{let i=P(r,oe(t,"float32")),l=vt(n.shape,o);return l.length>0?L(de(i,l),n.shape):i}}}};var L3={kernelName:ri,gradFunc:r=>({x:()=>Ke(r)})};var z3={kernelName:os,inputsToSave:["indices"],gradFunc:(r,e)=>{let t=e[0];return{indices:()=>gt(t.shape,"float32")}}};var B3={kernelName:ni,gradFunc:r=>({x:()=>Se(r)})};var V3={kernelName:oi,saveAllInputs:!0,gradFunc:(r,e,t)=>{let{axis:n}=t;return gr(r,n).map(s=>()=>s)}};var DC={kernelName:ss,inputsToSave:["x"],gradFunc:(r,e,t)=>{let n=e[0],{paddings:o}=t,s=o.map(a=>a[0]);return{x:()=>Fe(r,s,n.shape)}}};var G3={kernelName:is,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(r,e)=>{let[t,n,o]=e,s=t,a=n,i=Ve(s.shape,a.shape);return{a:()=>{let c=oe(a,"float32"),p=P(r,P(c,jr(s,ce(c,pe(1))))),m=vt(s.shape,i);return m.length>0&&(p=de(p,m)),L(p,s.shape)},b:()=>{let c=qt(s,0),p=Ct(c,hr(s),Se(s)),m=P(r,P(o,p)),f=vt(a.shape,i);return f.length>0&&(m=de(m,f)),L(m,a.shape)}}}};var W3={kernelName:as,inputsToSave:["x","alpha"],gradFunc:(r,e)=>{let[t,n]=e,o=qt(t,0);return{x:()=>Ct(o,r,P(r,n)),alpha:()=>{let s=Ct(o,Se(r),P(r,t)),a=vt(n.shape,r.shape);return a.length>0&&(s=de(s,a)),L(s,n.shape)}}}};var j3={kernelName:Go,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,n]=e,o=Ve(t.shape,n.shape);return{a:()=>{let i=ue(r,oe(n,"float32")),l=vt(t.shape,o);return l.length>0?L(de(i,l),t.shape):i},b:()=>{let i=P(r,oe(t,"float32")),l=vt(n.shape,o);l.length>0&&(i=L(de(i,l),n.shape));let u=Le(n);return Ke(ue(i,oe(u,"float32")))}}}};var U3={kernelName:pa,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>ue(r,Ke(Le(t)))}}};var q3={kernelName:cs,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e,n=P(kn(t,6),Os(t));return{x:()=>P(r,oe(n,"float32"))}}};var H3={kernelName:ls,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>P(r,oe(Os(t),"float32"))}}};var K3={kernelName:si,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>L(r,t.shape)}}};var X3={kernelName:us,inputsToSave:["images"],gradFunc:(r,e,t)=>{let[n]=e,o={dy:r,images:n};return{images:()=>T.runKernel(fp,o,t)}}};var Y3={kernelName:yl,inputsToSave:["images"],gradFunc:(r,e,t)=>{let[n]=e,o={dy:r,images:n};return{images:()=>T.runKernel(mp,o,t)}}};var Z3={kernelName:ps,gradFunc:(r,e,t)=>{let{dims:n}=t,o=ar(n,r.shape);return{x:()=>Jt(r,o)}}};var J3={kernelName:ms,gradFunc:r=>({x:()=>Se(r)})};var Q3={kernelName:fs,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>Ke(ue(r,P(jr(t,1.5),2)))}}};var eB={kernelName:ii,inputsToSave:["condition"],gradFunc:(r,e)=>{let[t]=e;return{condition:()=>oe(Se(t),"float32"),t:()=>P(r,oe(t,r.dtype)),e:()=>P(r,oe(Da(t),r.dtype))}}};var tB={kernelName:fa,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let n=qt(t,pe(0)),o=pe(pk),s=pe(mk),a=P(r,s),i=P(P(r,o),nr(oe(t,"float32")));return Ct(n,a,i)}}}};var rB={kernelName:hs,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e;return{x:()=>P(r,P(t,ce(pe(1),t)))}}};var nB={kernelName:ha,gradFunc:r=>({x:()=>Se(r)})};var oB={kernelName:ds,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>P(Ea(oe(t,"float32")),r)}}};var sB={kernelName:da,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>P(Cu(oe(t,"float32")),r)}}};var iB={kernelName:ai,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[n]=e,{begin:o,size:s}=t,a=n.shape,[i,l]=k_(n,o,s),u=[];for(let c=0;c<r.rank;c++)u.push([i[c],a[c]-i[c]-l[c]]);return{x:()=>Wr(r,u)}}};var aB={kernelName:ys,outputsToSave:[!0],gradFunc:(r,e,t)=>{let[n]=e,{dim:o}=t,s=!0,a=P(r,n);return{logits:()=>ce(a,P(de(a,[o],s),n))}}};var lB={kernelName:ga,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>P(r,Pr(t))}}};var $C={kernelName:bl,gradFunc:(r,e,t)=>{let{blockShape:n,paddings:o}=t;return{x:()=>Na(r,n,o)}}};var RC={kernelName:li,gradFunc:(r,e,t)=>{let{axis:n}=t;return{x:()=>et(r,n)}}};var uB={kernelName:gs,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>ue(r,P(xt(oe(t,"float32")),2))}}};var cB={kernelName:wl,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>P(r,P(oe(t,"float32"),2))}}};var pB={kernelName:bs,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,n]=e,o=pe(2);return{a:()=>P(r,P(o,ce(t,n))),b:()=>P(r,P(o,ce(n,t)))}}};var mB={kernelName:oo,gradFunc:r=>({x:()=>Se(r)})};var fB={kernelName:ws,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,n]=e,o=Ve(t.shape,n.shape);return{a:()=>{let i=r,l=vt(t.shape,o);return l.length>0&&(i=de(i,l)),L(i,t.shape)},b:()=>{let i=r,l=vt(n.shape,o);return l.length>0&&(i=de(i,l)),L(Ke(i),n.shape)}}}};var dB={kernelName:xs,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[n]=e,o=n.shape.slice(),{axis:s}=t;ar(s,n.shape).forEach(u=>{o[u]=1});let i=L(r,o),l=P(i,or(n.shape,"float32"));return{x:()=>l}}};var hB={kernelName:_s,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>ue(r,Le(Ea(t)))}}};var gB={kernelName:ks,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e;return{x:()=>P(ce(pe(1),Le(t)),r)}}};var xB={kernelName:Un,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[n]=e,{reps:o}=t;return{x:()=>{let a=Se(n);if(n.rank===1)for(let i=0;i<o[0];++i)a=J(a,Fe(r,[i*n.shape[0]],[n.shape[0]]));else if(n.rank===2)for(let i=0;i<o[0];++i)for(let l=0;l<o[1];++l)a=J(a,Fe(r,[i*n.shape[0],l*n.shape[1]],[n.shape[0],n.shape[1]]));else if(n.rank===3)for(let i=0;i<o[0];++i)for(let l=0;l<o[1];++l)for(let u=0;u<o[2];++u)a=J(a,Fe(r,[i*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 i=0;i<o[0];++i)for(let l=0;l<o[1];++l)for(let u=0;u<o[2];++u)for(let c=0;c<o[3];++c)a=J(a,Fe(r,[i*n.shape[0],l*n.shape[1],u*n.shape[2],c*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 a}}}};var yB={kernelName:vs,gradFunc:(r,e,t)=>{let n=t,{perm:o}=n,s=Ff(o);return{x:()=>qe(r,s)}}};var bB={kernelName:ui,gradFunc:(r,e,t)=>{let n=t,{axis:o}=n;return{value:()=>Ht(r,o)}}};var wB={kernelName:_l,inputsToSave:["segmentIds"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>qte(r,t)}}};function qte(r,e){let t=an(e,Se(e)),n=co(r,t),o=_n(e,pe(0,"int32")),s=n.rank-o.rank;for(let i=0;i<s;++i)o=dr(o,i+1);o=_r(o,or(n.shape,"bool"));let a=Se(n);return Ct(o,n,a)}var _B={kernelName:ci,gradFunc:r=>({x:()=>Se(r)})};var Hte=[hy,Nz,Tz,Ez,Az,Dz,$z,Rz,Fz,Oz,Pz,Mz,zz,Vz,Gz,Wz,jz,Uz,qz,Hz,Kz,Xz,Zz,Yz,Qz,e3,t3,r3,n3,o3,j3,s3,i3,a3,l3,u3,p3,c3,m3,f3,g3,x3,y3,b3,w3,_3,k3,v3,C3,S3,AC,AC,N3,E3,D3,$3,R3,F3,O3,P3,M3,L3,z3,B3,V3,DC,DC,G3,W3,U3,q3,H3,K3,X3,Y3,Z3,J3,Q3,eB,tB,rB,nB,oB,sB,iB,aB,lB,$C,$C,RC,RC,uB,pB,cB,mB,fB,dB,hB,gB,xB,yB,bB,wB,_B];for(let r of Hte)b1(r);var NB={};je(NB,{maxNorm:()=>Xte,minMaxNorm:()=>Jte,nonNeg:()=>Zte,unitNorm:()=>Yte});var FC;function ir(){return FC==null&&(FC=WT().epsilon()),FC}function un(){return"channelsLast"}var zn=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,zn.prototype)}},Hr=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Hr.prototype)}},z=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,z.prototype)}},Te=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Te.prototype)}},kd=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,kd.prototype)}};function vo(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 Yn(r,e){if(!r)throw new kd(e)}function OC(r,e){let t=0;for(let n of r)n===e&&t++;return t}function vr(r){return r.length===1?r[0]:r}function wt(r){return Array.isArray(r)?r:[r]}function Co(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 Ka(r){return r.length<=1||r.indexOf("_")===-1?r:r.replace(/[_]+(\w|$)/g,(e,t)=>t.toUpperCase())}var Io={};function lm(r){if(r==null)return null;let e={};return e.className=r.getClassName(),e.config=r.getConfig(),e}function PC(r){if(!(r==null||typeof r!="object"))if(Array.isArray(r))r.forEach(e=>PC(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:PC(n))}}}function ki(r,e={},t={},n="object",o=!1){if(typeof r=="string"){let s=r,a;if(s in t)a=t[s];else if(s in Io)a=Io[s];else if(a=e[s],a==null)throw new z(`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 a}else{let s=r;if(s.className==null||s.config==null)throw new z(`${n}: Improper config format: ${JSON.stringify(s)}.
|
|
'className' and 'config' must set.`);let a=s.className,i,l;if(a in t?[i,l]=t[a]:a in Io?[i,l]=Io.className:a in e&&([i,l]=e[a]),i==null)throw new z(`Unknown ${n}: ${a}. 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(Io))u[f]=Io[f];for(let f of Object.keys(t))u[f]=t[f];let c=s.config;c.customObjects=u;let p=Object.assign({},Io);for(let f of Object.keys(t))Io[f]=t[f];PC(s.config);let m=l(i,s.config,t,o);return Io=Object.assign({},p),m}else{let u=Object.assign({},Io);for(let p of Object.keys(t))Io[p]=t[p];let c=new i(s.config);return Io=Object.assign({},u),c}}}function Kte(r,e){return r<e?-1:r>e?1:0}function vd(r,e){return-1*Kte(r,e)}function So(r){if(r==null)return r;let e=[];for(let t of r)e.indexOf(t)===-1&&e.push(t);return e}function kB(r){if(r==null)throw new z(`Invalid value in obj: ${JSON.stringify(r)}`);for(let e in r)if(r.hasOwnProperty(e))return!1;return!0}function vi(r,e,t){if(t!=null&&r.indexOf(t)<0)throw new z(`${t} is not a valid ${e}. Valid values are ${r} or null/undefined.`)}function xy(r,e,t=0,n=Infinity){return Yn(t>=0),Yn(n>=t),Array.isArray(r)&&r.length>=t&&r.length<=n&&r.every(o=>typeof o===e)}function Zt(r,e){Array.isArray(r)?(y.assert(r.length>0,()=>`${e} is unexpectedly an empty array.`),r.forEach((t,n)=>Zt(t,`element ${n+1} of ${e}`))):y.assert(Number.isInteger(r)&&r>0,()=>`Expected ${e} to be a positive integer, but got ${vB(r)}.`)}function vB(r){return r===null?"null":Array.isArray(r)?"["+r.map(e=>vB(e)).join(",")+"]":typeof r=="string"?`"${r}"`:`${r}`}function CB(r,e){let t=y.now(),n;return(...s)=>{let a=y.now();return a-t<e||(t=a,n=r(...s)),n}}function yy(r){return r==="relu"?"relu":r==="linear"?"linear":r==="elu"?"elu":null}function MC(r,e){return B(()=>xt(de(P(r,r),e,!0)))}var um=class extends Q.Serializable{getConfig(){return{}}},Cd=class extends um{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 B(()=>{let t=MC(e,this.axis),n=fr(t,0,this.maxValue);return P(e,ue(n,J(ir(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};Cd.className="MaxNorm";Q.registerClass(Cd);var Id=class extends um{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return B(()=>ue(e,J(ir(),MC(e,this.axis))))}getConfig(){return{axis:this.axis}}};Id.className="UnitNorm";Q.registerClass(Id);var Sd=class extends um{apply(e){return Mr(e)}};Sd.className="NonNeg";Q.registerClass(Sd);var Nd=class extends um{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 B(()=>{let t=MC(e,this.axis),n=J(P(this.rate,fr(t,this.minValue,this.maxValue)),P(1-this.rate,t));return P(e,ue(n,J(ir(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};Nd.className="MinMaxNorm";Q.registerClass(Nd);var IB={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function zt(r){return lm(r)}function SB(r,e={}){return ki(r,Q.SerializationMap.getMap().classNameMap,e,"constraint")}function Bt(r){if(r==null)return null;if(typeof r=="string"){let t={className:r in IB?IB[r]:r,config:{}};return SB(t)}else return r instanceof um?r:SB(r)}function Xte(r){return new Cd(r)}function Yte(r){return new Id(r)}function Zte(){return new Sd}function Jte(r){return new Nd(r)}var HB={};je(HB,{constant:()=>ire,glorotNormal:()=>fre,glorotUniform:()=>mre,heNormal:()=>dre,heUniform:()=>hre,identity:()=>cre,leCunNormal:()=>gre,leCunUniform:()=>xre,ones:()=>sre,orthogonal:()=>yre,randomNormal:()=>lre,randomUniform:()=>are,truncatedNormal:()=>ure,varianceScaling:()=>pre,zeros:()=>ore});var TB=["channelsFirst","channelsLast"],EB=["nearest","bilinear"],AB=["valid","same","causal"],DB=["max","avg"],$B=["sum","mul","concat","ave"];var cm=new Map;function Pt(r){vi(TB,"DataFormat",r)}function RB(r){vi(EB,"InterpolationFormat",r)}function cn(r){vi(AB,"PaddingMode",r)}function LC(r){vi(DB,"PoolMode",r)}var Td=[],FB="/";function Bs(r,e){Td.push(r);try{let t=e();return Td.pop(),t}catch(t){throw Td.pop(),t}}function Qte(){return Td.length===0?"":Td.join(FB)+FB}function by(r){if(!OB(r))throw new Error("Not a valid tensor name: '"+r+"'");return Qte()+r}function wy(r){if(!OB(r))throw new Error("Not a valid tensor name: '"+r+"'");cm.has(r)||cm.set(r,0);let e=cm.get(r);if(cm.set(r,cm.get(r)+1),e>0){let t=`${r}_${e}`;return cm.set(t,1),t}else return r}var ere=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function OB(r){return!!r.match(ere)}function PB(r){return r===parseInt(r.toString(),10)}function No(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 xc(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 Vs(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 Kr(r,e){if(e<r)throw new z(`end (${e}) < begin (${r}) is forbidden.`);let t=[];for(let n=r;n<e;++n)t.push(n);return t}function Xa(r,e){return r.asType(e)}function Ya(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 MB(r,e){return B(()=>{if(r.shape.length!==2)throw new z(`repeat() expects a rank-2 tensor, but received a rank-${r.shape.length} tensor.`);let t=Ya(r,1);return _y(t,[1,e,1])})}function LB(r){let e=[No(r.shape)];return r.reshape(e)}function zB(r){if(r.rank<=1)throw new z(`batchFlatten requires a minimum rank of 2. Got rank: ${r.rank}.`);let e=[r.shape[0],No(r.shape,1)];return r.reshape(e)}function Za(r,e,t){return B(()=>{switch(r.rank){case 1:return Gf(r,e,t);case 2:return Qg(r,[e,0],[t,r.shape[1]]);case 3:return Wf(r,[e,0,0],[t,r.shape[1],r.shape[2]]);case 4:return zp(r,[e,0,0,0],[t,r.shape[1],r.shape[2],r.shape[3]]);case 5:return Fe(r,[e,0,0,0,0],[t,r.shape[1],r.shape[2],r.shape[3],r.shape[4]]);case 6:return Fe(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 z(`sliceAlongFirstAxis() received an unsupported tensor rank: ${r.rank}`)}})}function zC(r,e,t){return B(()=>{switch(r.rank){case 1:return Gf(r,e,t);case 2:return Qg(r,[0,e],[r.shape[0],t]);case 3:return Wf(r,[0,0,e],[r.shape[0],r.shape[1],t]);case 4:return zp(r,[0,0,0,e],[r.shape[0],r.shape[1],r.shape[2],t]);default:throw new z(`sliceAlongLastAxis() received an unsupported tensor rank: ${r.rank}`)}})}function Ed(r,e,t,n){return B(()=>{switch(r.rank){case 1:return Gf(r,e,t);case 2:switch(n){case 1:return Za(r,e,t);case 2:return zC(r,e,t);default:throw new z(`The axis is not within the rank of the tensor ${n}`)}case 3:switch(n){case 1:return Za(r,e,t);case 2:return Wf(r,[0,e,0],[r.shape[0],t,r.shape[2]]);case 3:return zC(r,e,t);default:throw new z(`The axis is not within the rank of the tensor ${n}`)}case 4:switch(n){case 1:return Za(r,e,t);case 2:return zp(r,[0,e,0,0],[r.shape[0],t,r.shape[2],r.shape[3]]);case 3:return zp(r,[0,0,e,0],[r.shape[0],r.shape[1],t,r.shape[3]]);case 4:return zC(r,e,t);default:throw new z(`The axis is not within the rank of the tensor ${n}`)}default:throw new z(`sliceAlongLastAxis() received an unsupported tensor rank: ${r.rank}`)}})}function pm(r,e=-1){let t;return e<0&&(t=r[0].rank,t!==0?e=t:e=0),e===r[0].rank&&(e=-1),et(r,e)}function BC(r,e){switch(r.rank){case 1:return R_([r,e]);case 2:return F_([r,e],0);case 3:return O_([r,e],0);case 4:return P_([r,e],0);default:throw new z(`concatAlongFirstAxis() received an unsupported tensor rank: ${r.rank}`)}}function _y(r,e){if(Array.isArray(e)||(e=[e]),r.rank!==e.length)throw new z(`The length of input n (${e.length}) does not match the number of dimensions in input x (${r.rank})`);return Kn(r,e)}function mm(r,e=0,t=1,n,o){return Jg(r,e,t,n,o)}function To(r,e,t,n){if(r.rank<2||e.rank<2)throw new Te(`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 Te(`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 ho.matMul({a:r,b:e,transposeA:o,transposeB:s,bias:n?VC(r.rank,n,un()):null,activation:t})}else{let o=r.shape.slice(),s=o.pop();r=r.reshape([-1,s]);let a=e.shape.slice(),i=a.pop(),l=a.pop(),u=[...a,i],c=Array.from({length:e.rank},(d,h)=>h===0?e.rank-2:h<=e.rank-2?h-1:h);e=e.transpose(c).reshape([l,-1]);let p=[...o,...u],m=!1,f=!1;return ho.matMul({a:r,b:e,transposeA:m,transposeB:f,bias:n?VC(r.rank,n,un()):null,activation:t}).reshape(p)}}function ky(r,e,t){return B(()=>(Array.isArray(e)?e=Dt(e,"int32"):e=e.toInt(),co(r,e,t)))}function yc(r){return P(r,r)}function VC(r,e,t){let n=e.shape;if(e.rank!==1&&e.rank!==r)throw new z(`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 z(`Unsupported input rank by biasAdd: ${e.rank}`)}function pn(r,e,t){return B(()=>(t==null&&(t=un()),Pt(t),r.add(VC(r.rank,e,t))))}function BB(r,e=1){if(e!==1)throw new Te(`Support for alpha values other than 1 (${e}) is not implemented yet.`);return As(r)}function VB(r){return B(()=>ue(r,Tt(r).add(1)))}function vy(r,e,t,n){return B(()=>fE(r,e,t,n))}function GB(r){return B(()=>{let e=J(.5,P(.2,r));return fr(e,0,1)})}function zl(r,e,t=!1){return t?r():e()}var WB=["fanIn","fanOut","fanAvg"],jB=["normal","uniform","truncatedNormal"];function tre(r){vi(WB,"FanMode",r)}function rre(r){vi(jB,"Distribution",r)}var In=class extends Q.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},Ad=class extends In{apply(e,t){return gt(e,t)}};Ad.className="Zeros";Q.registerClass(Ad);var bc=class extends In{apply(e,t){return or(e,t)}};bc.className="Ones";Q.registerClass(bc);var Dd=class extends In{constructor(e){super();if(typeof e!="object")throw new z(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new z(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return B(()=>P(pe(this.value),or(e,t)))}getConfig(){return{value:this.value}}};Dd.className="Constant";Q.registerClass(Dd);var $d=class extends In{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 Fs(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}};$d.className="RandomUniform";Q.registerClass($d);var Rd=class extends In{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 Te(`randomNormal does not support dType ${t}.`);return mm(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};Rd.className="RandomNormal";Q.registerClass(Rd);var Fd=class extends In{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 Te(`truncatedNormal does not support dType ${t}.`);return Vu(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};Fd.className="TruncatedNormal";Q.registerClass(Fd);var Od=class extends In{constructor(e){super();this.gain=e.gain!=null?e.gain:1}apply(e,t){return B(()=>{if(e.length!==2||e[0]!==e[1])throw new z("Identity matrix initializer can only be used for 2D square matrices.");return P(this.gain,Pp(e[0]))})}getConfig(){return{gain:this.gain}}};Od.className="Identity";Q.registerClass(Od);function nre(r,e="channelsLast"){let t,n;if(Pt(e),r.length===2)t=r[0],n=r[1];else if([3,4,5].indexOf(r.length)!==-1){if(e==="channelsFirst"){let o=No(r,2);t=r[1]*o,n=r[0]*o}else if(e==="channelsLast"){let o=No(r,0,r.length-2);t=r[r.length-2]*o,n=r[r.length-1]*o}}else{let o=No(r);t=Math.sqrt(o),n=Math.sqrt(o)}return[t,n]}var Xr=class extends In{constructor(e){super();if(e.scale<0)throw new z(`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,tre(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,rre(this.distribution),this.seed=e.seed}apply(e,t){let n=nre(e),o=n[0],s=n[1],a=this.scale;if(this.mode==="fanIn"?a/=Math.max(1,o):this.mode==="fanOut"?a/=Math.max(1,s):a/=Math.max(1,(o+s)/2),this.distribution==="normal"){let i=Math.sqrt(a);if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Te(`${this.getClassName()} does not support dType ${t}.`);return Vu(e,0,i,t,this.seed)}else{let i=Math.sqrt(3*a);return Fs(e,-i,i,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};Xr.className="VarianceScaling";Q.registerClass(Xr);var fm=class extends Xr{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Xr.className}};fm.className="GlorotUniform";Q.registerClass(fm);var dm=class extends Xr{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Xr.className}};dm.className="GlorotNormal";Q.registerClass(dm);var hm=class extends Xr{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Xr.className}};hm.className="HeNormal";Q.registerClass(hm);var gm=class extends Xr{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Xr.className}};gm.className="HeUniform";Q.registerClass(gm);var xm=class extends Xr{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Xr.className}};xm.className="LeCunNormal";Q.registerClass(xm);var ym=class extends Xr{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Xr.className}};ym.className="LeCunNormal";Q.registerClass(ym);var Pd=class extends In{constructor(e){super();if(this.DEFAULT_GAIN=1,this.gain=e.gain==null?this.DEFAULT_GAIN:e.gain,this.seed=e.seed,this.seed!=null)throw new Te("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return B(()=>{if(e.length<2)throw new Te("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=mm(n,0,1,"float32"),s=JE.gramSchmidt(o);return e[0]>e[1]&&(s=s.transpose()),P(this.gain,s)})}getConfig(){return{gain:this.gain,seed:this.seed}}};Pd.className="Orthogonal";Q.registerClass(Pd);var UB={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 qB(r,e={}){return ki(r,Q.SerializationMap.getMap().classNameMap,e,"initializer")}function It(r){return lm(r)}function mt(r){if(typeof r=="string"){let e=r in UB?UB[r]:r;if(e==="GlorotNormal")return new dm;if(e==="GlorotUniform")return new fm;if(e==="HeNormal")return new hm;if(e==="HeUniform")return new gm;if(e==="LeCunNormal")return new xm;if(e==="LeCunUniform")return new ym;{let t={};return t.className=e,t.config={},qB(t)}}else return r instanceof In?r:qB(r)}function ore(){return new Ad}function sre(){return new bc}function ire(r){return new Dd(r)}function are(r){return new $d(r)}function lre(r){return new Rd(r)}function ure(r){return new Fd(r)}function cre(r){return new Od(r)}function pre(r){return new Xr(r)}function mre(r){return new fm(r)}function fre(r){return new dm(r)}function dre(r){return new hm(r)}function hre(r){return new gm(r)}function gre(r){return new xm(r)}function xre(r){return new ym(r)}function yre(r){return new Pd(r)}var TV={};je(TV,{Layer:()=>ze,RNN:()=>Bn,RNNCell:()=>Kl,activation:()=>Vne,add:()=>Yne,alphaDropout:()=>Roe,average:()=>Zne,averagePooling1d:()=>TI,averagePooling2d:()=>EI,averagePooling3d:()=>AI,avgPool1d:()=>ioe,avgPool2d:()=>loe,avgPool3d:()=>coe,avgPooling1d:()=>aoe,avgPooling2d:()=>uoe,avgPooling3d:()=>poe,batchNormalization:()=>noe,bidirectional:()=>Ioe,concatenate:()=>Jne,conv1d:()=>$ne,conv2d:()=>Rne,conv2dTranspose:()=>Fne,conv3d:()=>One,conv3dTranspose:()=>Pne,convLstm2d:()=>_oe,convLstm2dCell:()=>koe,cropping2D:()=>Lne,dense:()=>Gne,depthwiseConv2d:()=>Bne,dot:()=>roe,dropout:()=>Wne,elu:()=>Sne,embedding:()=>Xne,flatten:()=>Une,gaussianDropout:()=>$oe,gaussianNoise:()=>Doe,globalAveragePooling1d:()=>moe,globalAveragePooling2d:()=>foe,globalMaxPool1d:()=>Noe,globalMaxPool2d:()=>Toe,globalMaxPooling1d:()=>CV,globalMaxPooling2d:()=>IV,gru:()=>hoe,gruCell:()=>goe,input:()=>eI,inputLayer:()=>Ine,layerNormalization:()=>ooe,leakyReLU:()=>Tne,lstm:()=>xoe,lstmCell:()=>yoe,masking:()=>Foe,maxPool1d:()=>Eoe,maxPool2d:()=>Aoe,maxPooling1d:()=>SV,maxPooling2d:()=>NV,maxPooling3d:()=>doe,maximum:()=>Qne,minimum:()=>eoe,multiply:()=>toe,permute:()=>Kne,prelu:()=>Ene,reLU:()=>Nne,repeatVector:()=>qne,reshape:()=>Hne,rnn:()=>voe,separableConv2d:()=>Mne,simpleRNN:()=>boe,simpleRNNCell:()=>woe,softmax:()=>Ane,spatialDropout1d:()=>jne,stackedRNNCells:()=>Coe,thresholdedReLU:()=>Dne,timeDistributed:()=>Soe,upSampling2d:()=>zne,zeroPadding2d:()=>soe});var bre=0;function Cy(){return bre++}var Iy={};function Bl(r=""){return r in Iy||(Iy[r]=0),Iy[r]+=1,r+Iy[r].toString()}function Sy(r){return Array.isArray(r)&&Array.isArray(r[0])}function bm(r){return r.length===0?[]:Array.isArray(r[0])?r:[r]}function Oe(r){let e;if(Array.isArray(r)){if(r.length!==1)throw new z(`Expected Tensor length to be 1; got ${r.length}`);e=r[0]}else e=r;return e}function Ye(r){if(Array.isArray(r)&&Array.isArray(r[0])){if(r.length===1)return r=r,r[0];throw new z(`Expected exactly 1 Shape; got ${r.length}`)}else return r}function wm(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 KB="Variable",Ny=class{constructor(e,t="float32",n=KB,o=!0,s=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=Cy(),n=n==null?KB:n,this.originalName=by(n),this.name=wy(this.originalName),this.trainable_=o,this.constraint=s,this.val=uk(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),wre(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 wre(r,e){if(r.shape.toString()!==e.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(r.shape)+" vs. "+JSON.stringify(e.shape))}function Md(r){return r.map(e=>e.read())}function _m(r){r.forEach(e=>{e[0].write(e[1])})}var St=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||{}}},mn=class{constructor(e,t,n,o,s,a,i){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=o,this.callArgs=s,this.outputTensorIndex=i,this.id=Cy(),a!=null&&(this.originalName=by(a),this.name=wy(this.originalName)),this.rank=t.length}},_re=0,Vl=class{constructor(e,t){this.callArgs=t,this.id=_re++,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}}},kre=0,ze=class extends Q.Serializable{constructor(e={}){super();this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=kre++,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=Co(n)+"_"+Bl(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 Hr(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new z(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return vr(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return vr(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new zn(`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 zn(`Layer ${this.name} is not connected, no input to return.`);return vr(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new zn(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new zn(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return vr(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=wt(e),this.inputSpec==null||this.inputSpec.length===0)return;let t=wt(this.inputSpec);if(e.length!==t.length)throw new z(`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 a=o.rank;if(s.ndim!=null&&a!==s.ndim)throw new z(`Input ${n} is incompatible with layer ${this.name}: expected ndim=${s.ndim}, found ndim=${a}`);if(s.maxNDim!=null&&a>s.maxNDim)throw new z(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${s.maxNDim}, found ndim=${a}`);if(s.minNDim!=null&&a<s.minNDim)throw new z(`Input ${n} is incompatible with layer ${this.name}: expected min_ndim=${s.minNDim}, found ndim=${a}.`);if(s.dtype!=null&&o.dtype!==s.dtype)throw new z(`Input ${n} is incompatible with layer ${this.name} : expected dtype=${s.dtype}, found dtype=${o.dtype}.`);if(s.axes){let i=o.shape;for(let l in s.axes){let u=Number(l),c=s.axes[l],p=u>=0?i[u]:i[i.length+u];if(c!=null&&[c,null].indexOf(p)===-1)throw new z(`Input ${n} is incompatible with layer ${this.name}: expected axis ${u} of input shape to have value ${c} but got shape ${i}.`)}}if(s.shape!=null)for(let i=0;i<s.shape.length;++i){let l=s.shape[i],u=o.shape[i];if(l!=null&&u!=null&&l!==u)throw new z(`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=wt(e),o=!0;for(let a of n)if(!(a instanceof mn)){o=!1;break}let s=!0;for(let a of n)if(a instanceof mn){s=!1;break}if(o===s)throw new z("Arguments to apply() must be all SymbolicTensors or all Tensors");return Bs(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);let a=[];for(let i of wt(e))a.push(i.shape);this.build(vr(a)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&s&&(this._refCount=1)}if(this.assertInputCompatibility(e),s){let a=this.call(e,t),i=wt(a),l=[];for(let u of i)n.indexOf(u)!==-1&&(u=u.clone()),l.push(u);if(a=vr(l),this.activityRegularizer!=null)throw new Te("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return a}else{let a=vre(e),i=this.computeOutputShape(a),l,u=Cre(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?a[0]:a),i!=null&&i.length>0&&Array.isArray(i[0])?l=i.map((c,p)=>new mn(u,c,this,wt(e),t,this.name,p)):l=new mn(u,i,this,wt(e),t,this.name),this.addInboundNode(e,l,null,null,a,i,t),this._refCount++,this.activityRegularizer!=null)throw new Te("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 zn(`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 zn(`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 Hr(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return wm(this.weights)}build(e){this.built=!0}getWeights(e=!1){return Md(e?this.trainableWeights:this.weights)}setWeights(e){B(()=>{let t=this.weights;if(t.length!==e.length)throw new z(`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=Md(t);for(let s=0;s<o.length;++s){let a=o[s],i=t[s],l=e[s];if(!y.arraysEqual(a.shape,l.shape))throw new z(`Layer weight shape ${a.shape} not compatible with provided weight shape ${l.shape}`);n.push([i,l])}_m(n)})}addWeight(e,t,n,o,s,a,i){if(this._addedWeightNames.indexOf(e)!==-1)throw new z(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),n==null&&(n="float32"),this.fastWeightInitDuringBuild&&(o=mt("zeros"));let l=o.apply(t,n),u=new Ny(l,n,e,a,i);return l.dispose(),s!=null&&this.addLoss(()=>s.apply(u.read())),a==null&&(a=!0),a?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=wt(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,a,i=null){let l=wt(e);t=wt(t),n=wt(n),o=wt(o),s=bm(s),a=bm(a);let u=[],c=[],p=[];for(let m of l)u.push(m.sourceLayer),c.push(m.nodeIndex),p.push(m.tensorIndex);new Vl({outboundLayer:this,inboundLayers:u,nodeIndices:c,tensorIndices:p,inputTensors:l,outputTensors:t,inputMasks:n,outputMasks:o,inputShapes:s,outputShapes:a},i);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 vre(r){r=wt(r);let e=[];for(let t of r)e.push(t.shape);return vr(e)}function Cre(r){return"float32"}function GC(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 a=n.inputTensors[s],i=n.inboundLayers[s],l=n.nodeIndices[s],u=GC(a,i,l);for(let c of u)o.indexOf(c)===-1&&o.push(c)}return o}}}var Ci=class extends ze{constructor(e){super({dtype:e.dtype,name:e.name!=null?e.name:Bl("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 z("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 z("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(e.batchSize!=null)throw new z("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 mn(this.dtype,this.batchInputShape,this,[],{},this.name);o.nodeIndex=0,o.tensorIndex=0,new Vl({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[o],outputTensors:[o],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new z(`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}}};Ci.className="InputLayer";Q.registerClass(Ci);function Ty(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 z("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 Ci({batchInputShape:e,name:r.name,dtype:t,sparse:r.sparse}).inboundNodes[0].outputTensors[0]}async function Ii(r){if(r==null)return;let e=[],t=[],n=[];for(let o in r){let s=r[o];if(typeof s!="number"){let a=s;e.push(a.data()),t.push(o),n.push(a)}}if(e.length>0){let o=await Promise.all(e);for(let s=0;s<o.length;++s)r[t[s]]=o[s][0];De(n)}}function Ey(r){if(r!=null)for(let e in r){let t=r[e];typeof t!="number"&&t.dispose()}}var XB;(function(r){r[r.SILENT=0]="SILENT",r[r.VERBOSE=1]="VERBOSE"})(XB||(XB={}));var Ire=125,Gl=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){}},WC=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)}},YB=class extends Gl{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 a;o in this.totals?a=this.totals[o]:this.totals[o]=0;let i=B(()=>J(this.totals[o],P(s,n)));this.totals[o]=i,a!=null&&a.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:B(()=>{let o=P(ue(1,this.seen),this.totals[n]);t[n]=o,this.totals[n].dispose(),Rt(t[n])}))}},jC=class extends Gl{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 a=this.history[s];for(let i=0;i<a.length;++i)if(typeof a[i]!="number"){let l=a[i];e.push(l.data()),t.push(s),n.push(i)}}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]}},UC=class extends Gl{constructor(e,t){super();if(this.currentEpoch=0,this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=Ire),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");y.isNumber(this.yieldEvery)&&(this.maybeWait=CB(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 Ii(n),o.push(this.yield(e,t,n))),o.push(Yf()),await Promise.all(o)}async onEpochBegin(e,t){this.currentEpoch=e,this.epochBegin!=null&&(await Ii(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){let n=[];this.epochEnd!=null&&(await Ii(t),n.push(this.epochEnd(e,t))),this.yieldEvery==="epoch"&&n.push(Yf()),await Promise.all(n)}async onBatchBegin(e,t){this.batchBegin!=null&&(await Ii(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){let n=[];this.batchEnd!=null&&(await Ii(t),n.push(this.batchEnd(e,t))),this.yieldEvery==="batch"?n.push(Yf()):y.isNumber(this.yieldEvery)&&n.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(n)}async onTrainBegin(e){this.trainBegin!=null&&(await Ii(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await Ii(e),await this.trainEnd(e))}};function Ay(r,e){return r==null&&(r={}),r instanceof Gl?[r]:Array.isArray(r)&&r[0]instanceof Gl?r:wt(r).map(n=>new UC(n,e))}var Sn=class{constructor(){}static registerCallbackConstructor(e,t){y.assert(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),Sn.checkForDuplicate(t),Sn.constructors[e]==null&&(Sn.constructors[e]=[]),Sn.constructors[e].push(t)}static checkForDuplicate(e){for(let t in Sn.constructors)Sn.constructors[+t].forEach(o=>{if(o===e)throw new z("Duplicate callback constructor.")})}static clear(){Sn.constructors={}}static createCallbacks(e){let t=[];for(let n in Sn.constructors){let o=+n;e>=o&&t.push(...Sn.constructors[o])}return t.map(n=>new n)}};Sn.constructors={};function Dy(r,e,t,n,o,s,a,i,l){let u=new jC,c=[new YB,...Sn.createCallbacks(e)];r!=null&&c.push(...r),c.push(u);let p=new WC(c);return p.setParams({epochs:t,initialEpoch:n,samples:o,steps:s,batchSize:a,verbose:e,doValidation:i,metrics:l}),{callbackList:p,history:u}}function fn(r,e={},t=!1){return ki(r,Q.SerializationMap.getMap().classNameMap,e,"layer",t)}function Ld(r,e){return B(()=>{r.dtype!=="float32"&&(r=r.asType("float32"));let t=de(yc(r),e,!0),n=Ds(t.shape,ir()),o=xt(an(t,n));return ue(r,o)})}function Si(r,e){return B(()=>ht(yc(ce(e,r)),-1))}function km(r,e){return B(()=>ht(Tt(ce(e,r)),-1))}function Wl(r,e){return B(()=>{let t=ce(r,e),n=fr(Tt(r),ir(),Number.MAX_VALUE),o=Tt(ue(t,n));return P(100,ht(o,-1))})}function Sre(r,e){return B(()=>{let t=fr(e,ir(),Number.MAX_VALUE),n=hr(J(1,t)),o=fr(r,ir(),Number.MAX_VALUE),s=hr(J(1,o));return ht(yc(ce(n,s)),-1)})}function Nre(r,e){return B(()=>{let t=an(0,ce(1,P(r,e)));return ht(yc(t),-1)})}function Tre(r,e){return B(()=>{let t=an(0,ce(1,P(r,e)));return ht(t,-1)})}function Ere(r,e){return B(()=>{let t=de(P(r,e),-1),n=Er(P(ce(1,r),e),-1);return an(0,J(1,ce(n,t)))})}function Are(r,e){return B(()=>{let t=Math.log(2),n=ce(e,r),o=ce(J(n,po(P(-2,n))),t);return ht(o,-1)})}function wc(r,e,t=!1){return B(()=>{if(t)e=Pa(e);else{let n=de(e,e.shape.length-1,!0);e=ue(e,n)}return e=fr(e,ir(),1-ir()),Ke(de(P(r.toFloat(),hr(e)),e.shape.length-1))})}function vm(r,e,t=!1){return B(()=>{let n=$s(LB(r)).toInt();e=fr(e,ir(),1-ir());let o=e.shape,s=Ss(n,o[o.length-1]).reshape(o);return wc(s,e,t)})}function Dre(r,e){if(!y.arraysEqual(r.shape,e.shape))throw new z(`logits and labels must have the same shape, but got shapes ${JSON.stringify(r.shape)} and ${JSON.stringify(e.shape)}`);return B(()=>{let t=e.relu(),n=e.abs().neg();return t.sub(e.mul(r)).add(n.exp().log1p())})}function Cm(r,e){return B(()=>{let t;return t=fr(e,ir(),1-ir()),t=hr(ue(t,ce(1,t))),ht(Dre(r,t),-1)})}function $re(r,e){return B(()=>{let t=fr(r,ir(),1),n=fr(e,ir(),1);return de(P(r,hr(ue(t,n))),-1)})}function Rre(r,e){return B(()=>{let t=hr(J(ir(),e));return ht(ce(e,P(r,t)),-1)})}function zd(r,e){return B(()=>{let t=Ld(r,-1),n=Ld(e,-1),o=P(t,n);return Ke(de(o,-1))})}var Bd={meanSquaredError:Si,meanAbsoluteError:km,meanAbsolutePercentageError:Wl,meanSquaredLogarithmicError:Sre,squaredHinge:Nre,hinge:Tre,categoricalHinge:Ere,logcosh:Are,categoricalCrossentropy:wc,sparseCategoricalCrossentropy:vm,binaryCrossentropy:Cm,kullbackLeiblerDivergence:$re,poisson:Rre,cosineProximity:zd};function $y(r){if(typeof r=="string"){if(r in Bd)return Bd[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 z(e)}else return r}function Vd(r,e){return B(()=>{let t=P(.5,ur(e)),n=Xa(qt(e,t),r.dtype);return ht(On(r,n),-1)})}function Gd(r,e){return B(()=>Xa(On(Tl(r,-1),Tl(e,-1)),"float32"))}function ZB(r,e){return B(()=>_r(r.equal(1),e.equal(1)).sum().cast("float32"))}function Fre(r,e){return B(()=>_r(r.equal(1),e.equal(0)).sum().cast("float32"))}function Ore(r,e){return B(()=>_r(r.equal(0),e.equal(1)).sum().cast("float32"))}function qC(r,e){return B(()=>{let t=ZB(r,e),n=Ore(r,e),o=t.add(n);return Ct(qt(o,0),t.div(o),0).cast("float32")})}function JB(r,e){return B(()=>{let t=ZB(r,e),n=Fre(r,e),o=t.add(n);return Ct(qt(o,0),t.div(o),0).cast("float32")})}function Ry(r,e){return Cm(r,e)}function Fy(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)),On(r,e).asType("float32")}var Pre=Si,Mre=Si,Lre=km,zre=km,Bre=Wl,Vre=Wl,Wd=wc,Gre=zd,HC=vm,Oy={binaryAccuracy:Vd,categoricalAccuracy:Gd,precision:qC,categoricalCrossentropy:Wd,sparseCategoricalCrossentropy:HC,mse:Pre,MSE:Mre,mae:Lre,MAE:zre,mape:Bre,MAPE:Vre,cosine:Gre};function QB(r){if(typeof r=="string"&&r in Oy)return Oy[r];if(typeof r!="string"&&r!=null)return r;throw new z(`Unknown metric ${r}`)}function jd(r){if(Yn(r!==null,`Unknown LossOrMetricFn ${r}`),typeof r=="string")return r;{let e;for(let t of Object.keys(Bd))if(Bd[t]===r){e=t;break}if(e!==void 0)return e;for(let t of Object.keys(Oy))if(Oy[t]===r){e=t;break}return e!==void 0?e:r.name}}function eV(r){let e={Adagrad:()=>Ju.adagrad(.01),Adadelta:()=>Ju.adadelta(1,.95,ir()),Adam:()=>Ju.adam(.001,.9,.999,ir()),Adamax:()=>Ju.adamax(.002,.9,.999,ir(),0),RMSProp:()=>Ju.rmsprop(.001,.9,0,ir()),SGD:()=>Ju.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 z(`Unknown Optimizer ${r}`)}var tV=1*1024*1024;function KC(r,e,t=!1){if(r==null||typeof r!="object"||Object.getPrototypeOf(r)!==Object.prototype||!XC(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>tV&&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 <= ${tV}.`)}}function XC(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"||!XC(r[t]))return!1;return!0}else if(Array.isArray(r)){for(let e of r)if(!XC(e))return!1;return!0}else return!1;else{let e=typeof r;return e==="string"||e==="number"||e==="boolean"}}function rV(r,e,t,n=console.log){let o=jre(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(c=>Math.floor(e*c)));let a;if(!o){s.push("Receives inputs"),a=[];for(let c in r.nodesByDepth)a.push(...r.nodesByDepth[c])}n("_".repeat(e)),Py(s,t,n),n("=".repeat(e));let i=r.layers;for(let c=0;c<i.length;++c)o?Ure(i[c],t,n):qre(i[c],t,a,n),n((c===i.length-1?"=":"_").repeat(e));r.checkTrainableWeightsConsistency();let l=Wre(r),u=wm(r.nonTrainableWeights);n(`Total params: ${l+u}`),n(`Trainable params: ${l}`),n(`Non-trainable params: ${u}`),n("_".repeat(e))}function Wre(r){let e;return r.collectedTrainableWeights!=null?e=wm(r.collectedTrainableWeights):e=wm(r.trainableWeights),e}function jre(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 a of o.inboundNodes)if(n.indexOf(a)!==-1)if(s){e=!1;break}else s=!0;if(!e)break}return e}function Py(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 Ure(r,e,t){let n;try{n=JSON.stringify(r.outputShape)}catch(i){n="multiple"}let o=r.name,s=r.getClassName(),a=[`${o} (${s})`,n,r.countParams().toString()];Py(a,e,t)}function qre(r,e,t,n){let o;try{o=JSON.stringify(r.outputShape)}catch(c){o="multiple"}let s=[];for(let c of r.inboundNodes)if(!(t!=null&&t.length>0&&t.indexOf(c)===-1))for(let p=0;p<c.inboundLayers.length;++p){let m=c.inboundLayers[p].name,f=c.nodeIndices[p],d=c.tensorIndices[p];s.push(`${m}[${f}][${d}]`)}let a=r.name,i=r.getClassName(),l=s.length===0?"":s[0],u=[`${a} (${i})`,o,r.countParams().toString(),l];Py(u,e,n);for(let c=1;c<s.length;++c)Py(["","","",s[c]],e,n)}function nV(r,e,t){return(r==="inboundNodes"||r==="outputLayers"||r==="inputLayers")&&e===0&&typeof t=="string"}function _c(r,e){if(r===null)return null;if(typeof r=="string")return Ka(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];nV(e,o,s)?t.push(s):t.push(_c(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=Ka(n);t[s]=_c(o,s)}}return t}}function My(r,e){if(r==null)return null;if(typeof r=="string")return Co(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];nV(e,o,s)?t.push(s):t.push(My(s,e))}return t}else{let t={};for(let n of Object.keys(r)){let o=r[n],s=Co(n);(n==="name"||n==="className")&&typeof o=="string"?t[s]=o:t[s]=My(o,n)}return t}}var Ud="3.7.0";function Hre(r,e){if(r.dtype==null||r.dtype===e.dtype)return e;try{return oe(e,r.dtype)}catch(t){throw new z(`The dtype of the feed (${e.dtype}) can not be cast to the dtype of the key '${r.name}' (${r.dtype}).`)}}var Gs=class{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof Gs)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]=Hre(e,t),this.name2Id[e.name]=e.id,n!=null&&(this.id2Mask[e.id]=n);else throw new z(`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 mn){if(this.id2Value[e.id]==null)throw new z(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}else{let t=this.name2Id[e];if(t==null)throw new z(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof mn){if(this.id2Value[e.id]==null)throw new z(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}else{let t=this.name2Id[e];if(t==null)throw new z(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){this.id2Mask!=null&&De(this.id2Mask)}},YC={},oV={};function kc(r,e,t,n){let o=t==null?!1:t.training,s=Array.isArray(r),a=s?r:[r],i=a.map(d=>d.name),l=[],u=e.names();for(let d of i)u.indexOf(d)!==-1?l.push(e.getValue(d)):l.push(null);n!=null&&(n.maxNumTensors=-Infinity,n.minNumTensors=Infinity);let c=i.join(",")+"|"+e.names().join(","),p,m;if(YC[c]==null){let d=Kre(a,e);p=d.sorted,m=d.recipientCounts,YC[c]=p,oV[c]=m}p=YC[c],m={},o||Object.assign(m,oV[c]);let f=new Gs(e);for(let d=0;d<p.length;++d){if(n!=null){let R=df().numTensors;R>n.maxNumTensors&&(n.maxNumTensors=R),R<n.minNumTensors&&(n.minNumTensors=R)}let h=p[d],g=h.sourceLayer;if(g instanceof Ci)continue;let x=[],b=[],w=[],_=!1;for(let R of h.inputs){let M=f.getValue(R),G=f.getMask(R);x.push(M),b.push(G),G!=null&&(_=!0),o||(m[R.name]--,m[R.name]===0&&!e.hasKey(R)&&i.indexOf(R.name)===-1&&!M.isDisposed&&R.sourceLayer.stateful!==!0&&w.push(M))}_&&(t=t||{},t.mask=b[0]);let C=wt(g.apply(x,t)),A=null;g.supportsMasking&&(A=g.computeMask(x,b));let D=Yre(h),$=Array.isArray(D)?D:[D];for(let R=0;R<$.length;++R){f.hasKey($[R])||f.add($[R],C[R],Array.isArray(A)?A[0]:A);let M=i.indexOf($[R].name);M!==-1&&(l[M]=C[R])}o||De(w)}return f.disposeMasks(),s?l:l[0]}function Kre(r,e){y.assert(r!=null&&r.length>0,()=>"Expected at least one fetch, got none");let t=[],n={};if(r.length===1){let o=sV(r[0],e);t=o.sorted,n=o.recipientMap}else{let o=new Set;for(let s of r){let{sorted:a,recipientMap:i}=sV(s,e);for(let l of a)o.has(l.name)||(t.push(l),o.add(l.name));for(let l in i)n[l]==null&&(n[l]=new Set),i[l].forEach(u=>n[l].add(u))}}return{sorted:t,recipientCounts:Xre(n)}}function Xre(r){let e={};for(let t in r)e[t]=r[t].size;return e}function sV(r,e){let t=new Set,n=[],o={};for(let i of e.names())t.add(i);let s=[],a=[];for(s.push(r);s.length>0;){let i=s[s.length-1];if(t.has(i.name)){s.pop();continue}let l=a[a.length-1]===s.length-1;if(i.inputs.length===0||l)s.pop(),n.push(i),t.add(i.name),l&&a.pop();else{a.push(s.length-1);for(let u of i.inputs)o[u.name]==null&&(o[u.name]=new Set),o[u.name].add(i.name),!t.has(u.name)&&s.push(u)}}return{sorted:n,recipientMap:o}}function Yre(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 Zn=class extends ze{constructor(e){super({});if(this.containerNodes=new Set,this.name=e.name,this.name==null){let b=this.getClassName().toLowerCase();this.name=Bl(b)}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],So(this.inputs).length!==this.inputs.length)throw new z(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(b=>b.name)}`);So(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(b=>b.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(let b of this.outputs){let w=b.sourceLayer,_=b.nodeIndex,C=b.tensorIndex;this.outputLayers.push(w),this.outputLayersNodeIndices.push(_),this.outputLayersTensorIndices.push(C)}for(let b of this.inputs){let w=b.sourceLayer,_=b.nodeIndex,C=b.tensorIndex;Yn(_===0,"input layer has >1 nodes"),Yn(C===0,"input layer has >1 tensors"),this.inputLayers.push(w),this.inputLayersNodeIndices.push(_),this.inputLayersTensorIndices.push(C)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let b=0;b<this.inputLayers.length;b++){let w=this.inputLayers[b];if(!(w instanceof Ci))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${b} (0-based) originates from layer type ${w.getClassName()}.`);this.inputNames.push(w.name),this.feedInputShapes.push(w.batchInputShape),this.feedInputNames.push(w.name)}for(let b of this.outputLayers)this.outputNames.push(b.name);this.internalInputShapes=this.inputs.map(b=>b.shape),this.internalOutputShapes=this.outputs.map(b=>b.shape);let t={},n={},o={},s={},a={},i=[],l=(b,w,_,C,A,D)=>{(C==null||A==null||D==null)&&(C=b.sourceLayer,A=b.nodeIndex,D=b.tensorIndex);let $=C.inboundNodes[A];if(_.indexOf($)!==-1)throw new Hr(`The tensor ${b.name} at layer "${C.name}" is part of a cycle.`);if(w.indexOf($)!==-1)return;this.containerNodes.add(Zn.nodeKey(C,A)),C.id in a||(a[C.id]=Object.keys(a).length),_.indexOf($)===-1&&_.push($);let R=$.inboundLayers.length;for(let M=0;M<R;M++){let G=$.inputTensors[M],j=$.inboundLayers[M],U=$.nodeIndices[M],q=$.tensorIndices[M];l(G,w,_,j,U,q)}for(w.push($);_.indexOf($)>=0;)_.splice(_.indexOf($),1);i.push($)},u=[],c=[];for(let b of this.outputs)l(b,u,c);let p=i.slice().reverse();for(let b of p){n[b.id]=b,b.id in t||(t[b.id]=0);let w=t[b.id],_=o[b.outboundLayer.id]==null?0:o[b.outboundLayer.id];w=Math.max(w,_),o[b.outboundLayer.id]=w,s[b.outboundLayer.id]=b.outboundLayer,t[b.id]=w;for(let C=0;C<b.inboundLayers.length;C++){let A=b.inboundLayers[C],D=b.nodeIndices[C],$=A.inboundNodes[D],R=t[$.id]==null?0:t[$.id];t[$.id]=Math.max(w+1,R),n[$.id]=$}}let m={};for(let b in t){let w=t[b];w in m||(m[w]=[]),m[w].push(n[b])}let f={};for(let b in o){let w=o[b];w in f||(f[w]=[]),f[w].push(s[b])}let d=Object.keys(f).map(b=>parseInt(b,10)).sort(vd);this.layers=[];for(let b of d){let w=f[b];w.sort((_,C)=>{let A=a[_.id],D=a[C.id];return A<D?-1:A>D?1:0});for(let _ of w)_ instanceof Zn&&this.internalContainerRefs.push(_),this.layers.push(_)}this.layersByDepth=f,d=Object.keys(m).map(b=>parseInt(b,10)).sort(vd);let h=this.inputs.slice(),g=[];for(let b of d)for(let w of m[b]){let _=w.outboundLayer;if(_!=null){for(let C of w.inputTensors)if(h.indexOf(C)===-1)throw new Hr(`Graph disconnected: cannot obtain value for tensor ${C} at layer "${_.name}". The following previous layers were accessed without issue: ${g}`);for(let C of w.outputTensors)h.push(C);g.push(_.name)}}this.nodesByDepth=m;let x=this.layers.map(b=>b.name);for(let b of x){let w=x.filter(_=>_===b).length;if(w!==1)throw new Hr(`The name "${b}" is used ${w} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(x))}this.outboundNodes=[],this.inboundNodes=[],new Vl({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(b=>null),outputMasks:this.outputs.map(b=>null),inputShapes:this.inputs.map(b=>b.shape),outputShapes:this.outputs.map(b=>b.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 z("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 a of this.layers)for(let i of a.weights){if(n[i.originalName]!=null)throw new z(`Duplicate weight name: ${i.originalName}`);n[i.originalName]=i,o++}let s=[];for(let a in e){let i=a;if(n[a]==null){let l=a.split("/");i=l.slice(0,-2).concat([l[l.length-1]]).join("/")}if(n[i]!=null)s.push([n[i],e[a]]);else if(t)throw new z(`Provided weight data has no target variable: ${a}`);delete n[i]}if(t){let a=[];for(let i in n)a.push(i);if(a.length>0)throw new z(`${a.length} of ${o} weights are not set: ${a}`)}_m(s)}updatedConfig(){let e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${Ud}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){let n=My(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return B(()=>{e=wt(e);let n=new Gs;for(let o=0;o<this.inputs.length;++o)n.add(this.inputs[o],e[o]);return kc(this.outputs,n,t)})}computeMask(e,t){return B(()=>{e=wt(e);let n;return t==null?n=vo(null,e.length):n=wt(t),this.runInternalGraph(e,n)[1]})}computeOutputShape(e){let t=bm(e);if(t.length!==this.inputLayers.length)throw new z(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);let n={};for(let i=0;i<t.length;i++){let l=this.inputLayers[i],u=t[i],c=l.name+"_0_0";n[c]=u}let o=Object.keys(this.nodesByDepth).map(i=>parseInt(i,10)).sort(vd);if(o.length>1)for(let i of o){let l=this.nodesByDepth[i];for(let u of l){let c=u.outboundLayer;if(this.inputLayers.map(h=>h.id).indexOf(c.id)!==-1)continue;let p=[];for(let h=0;h<u.inboundLayers.length;h++){let g=u.inboundLayers[h],x=u.nodeIndices[h],b=u.tensorIndices[h],w=`${g.name}_${x}_${b}`,_=n[w];p.push(_)}let m=c.computeOutputShape(vr(p)),f=bm(m),d=c.inboundNodes.indexOf(u);for(let h=0;h<f.length;h++){let g=`${c.name}_${d}_${h}`;n[g]=f[h]}}}let s=[],a=[];for(let i=0;i<this.outputLayers.length;i++){let l=this.outputLayers[i],u=this.outputLayersNodeIndices[i],c=this.outputLayersTensorIndices[i],p=`${l.name}_${u}_${c}`;a.push(p)}for(let i=0;i<a.length;i++){let l=a[i];Yn(l in n),s.push(n[l])}return vr(s)}runInternalGraph(e,t){t==null&&(t=vo(null,e.length));let n={};for(let l=0;l<this.inputs.length;++l){let u=this.inputs[l],c=e[l],p=t[l];n[u.id]=[c,p]}let o=Object.keys(this.nodesByDepth).map(l=>parseInt(l,10)).sort(vd);for(let l of o){let u=this.nodesByDepth[l];for(let c of u){let p=c.outboundLayer,m=c.inputTensors,f=c.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,x,b,w;if(c.callArgs!=null&&(h=c.callArgs),d.length===1){let[_,C]=d[0];h.mask==null&&(h.mask=C),b=wt(p.call(_,h)),w=wt(p.computeMask(_,C)),g=[_],x=[C]}else g=d.map(_=>_[0]),x=d.map(_=>_[1]),h.mask==null&&(h.mask=x),b=wt(p.call(g,h)),w=wt(p.computeMask(g,x));if(p.activityRegularizer)throw new Te("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let _=0;_<f.length;++_){let C=f[_],A=b[_],D=w[_];n[C.id]=[A,D]}}}}let s=[],a=[],i=[];for(let l of this.outputs){Yn(l.id in n,`Could not compute output ${l.name} : ${l.id}`);let[u,c]=n[l.id];i.push(u.shape),s.push(u),a.push(c)}return[s,a,i]}buildNodeConversionMap(e){let t={},n;for(let o of this.layers){n=o instanceof Zn?1:0;for(let s=0;s<o.inboundNodes.length;s++){let a=Zn.nodeKey(o,s);this.containerNodes.has(a)&&(t[a]=n,n+=1)}}return t}getLayer(e,t){if(t!=null){if(this.layers.length<=t)throw new z(`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 z("Provide either a layer name or layer index");for(let n of this.layers)if(n.name===e)return n;throw new z(`No such layer: ${e}`)}calculateLosses(){return B(()=>{let e=[];for(let t of this.layers)for(let n=0;n<t.inboundNodes.length;++n){let o=Zn.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 a of this.layers){let i=a.getClassName(),l=a.getConfig(),u=[];for(let p=0;p<a.inboundNodes.length;p++){let m=a.inboundNodes[p],f=Zn.nodeKey(a,p),d={};if(this.containerNodes.has(f)){if(m.callArgs)try{JSON.stringify(m.callArgs),d=m.callArgs}catch(h){console.warn(`Layer ${a.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 x=m.inboundLayers[g],b=m.nodeIndices[g],w=m.tensorIndices[g],_=Zn.nodeKey(x,b),C=t[_];C==null&&(C=0),h.push([x.name,C,w,d])}u.push(h)}}}let c={};c.name=a.name,c.className=i,c.config=l,c.inboundNodes=u,n.push(c)}e.layers=n;let o=[];for(let a=0;a<this.inputLayers.length;a++){let i=this.inputLayers[a],l=this.inputLayersNodeIndices[a],u=Zn.nodeKey(i,l);if(!this.containerNodes.has(u))continue;let c=t[u];c==null&&(c=0);let p=this.inputLayersTensorIndices[a];o.push([i.name,c,p])}e.inputLayers=o;let s=[];for(let a=0;a<this.outputLayers.length;a++){let i=this.outputLayers[a],l=this.outputLayersNodeIndices[a],u=Zn.nodeKey(i,l);if(!this.containerNodes.has(u))continue;let c=t[u];c==null&&(c=0);let p=this.outputLayersTensorIndices[a];s.push([i.name,c,p])}return e.outputLayers=s,e}static fromConfig(e,t,n={},o=!1){let s={},a={};function i(g,x){g.name in a?a[g.name].push(x):a[g.name]=[x]}function l(g,x){let b=[],w;for(let _ of x){let C=_[0],A=_[1],D=_[2];if(w=_[3]==null?{}:_[3],!(C in s)){i(g,x);return}let $=s[C];if($.inboundNodes.length<=A){i(g,x);return}let R=$.inboundNodes[A];b.push(R.outputTensors[D])}b.length>0&&g.apply(vr(b),w)}function u(g){let x=g.name,b=fn(g,t.customObjects!=null?t.customObjects:{});b.setFastWeightInitDuringBuild(o),s[x]=b,g.inboundNodes.forEach(_=>{if(!(_ instanceof Array))throw new z(`Corrupted configuration, expected array for nodeData: ${_}`);i(b,_)})}let c=t.name,p=t.layers;for(let g of p)u(g);for(;!kB(a);)for(let g of p){let x=s[g.name];if(x.name in a){let b=a[x.name];delete a[x.name];for(let w of b)l(x,w)}}let m=[],f=[],d=t.inputLayers;for(let g of d){let x=g[0],b=g[1],w=g[2];Yn(x in s);let C=s[x].inboundNodes[b].outputTensors;m.push(C[w])}let h=t.outputLayers;for(let g of h){let x=g[0],b=g[1],w=g[2];Yn(x in s);let C=s[x].inboundNodes[b].outputTensors;f.push(C[w])}return new e({inputs:m,outputs:f,name:c})}get stateful(){if(this._stateful)throw new z("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(){B(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}};function Zre(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 Ly(r,e){return Zre(r,e,"classWeight")}async function zy(r,e,t,n){if(e!=null||n!=null)throw new Error("Support sampleWeight is not implemented yet");if(t!=null){let o=B(()=>{if(r.shape.length===1)return r.clone();if(r.shape.length===2)if(r.shape[1]>1){let i=1;return r.argMax(i)}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());De(o);let a=[];return s.forEach(i=>{if(t[i]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${i} exists in the data but not in classWeight`);a.push(t[i])}),Dt(a,"float32")}else return null}function iV(r,e){return P(r,e)}var Jre=32;function aV(r,e){let t,n,o=e;t=o.xs,n=o.ys,y.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=lV("input",r.inputNames,t),a=lV("output",r.outputNames,n),i=s[0].shape[0];y.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)})`),y.assert(a.length===r.outputs.length,()=>`LayersModel has ${r.outputs.length} outputs, but the dataset provides ${a.length} outputs. (Expected output keys: ${JSON.stringify(r.outputNames)})`);for(let l=0;l<s.length;l++)y.assert(s[l].shape[0]===i,()=>`Batch size mismatch: input ${r.inputNames[l]} has ${s[l].shape[0]}; expected ${i} based on input ${r.inputNames[0]}.`);for(let l=0;l<a.length;l++)y.assert(a[l].shape[0]===i,()=>`Batch size mismatch: output ${r.outputNames[l]} has ${a[l].shape[0]}; expected ${i} based on input ${r.inputNames[0]}.`);return{xs:s,ys:a}}function lV(r,e,t){if(t instanceof Me)return[t];if(Array.isArray(t))return y.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 z(`The feature data generated by the dataset lacks the required ${r} key '${o}'.`);n.push(t[o])}return n}}function Qre(r){if(r.length===3)throw new Te("Validation with sample weights is not implemented yet.");return{xs:r[0],ys:r[1]}}async function uV(r,e,t){let n=t.batchesPerEpoch!=null;if(y.assert(r.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),y.assert(t!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),y.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}`),y.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}`),y.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,a;if(o)if(cV(t.validationData))y.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=Qre(t.validationData);s=g.xs,a=g.ys}let i=r.makeTrainFunction(),l=r.getDedupedMetricsNames(),u;o?u=l.slice().concat(l.map(g=>"val_"+g)):u=l.slice();let c=Ay(t.callbacks,t.yieldEvery),p=t.verbose==null?1:t.verbose,{callbackList:m,history:f}=Dy(c,p,t.epochs,null,null,ene(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 x=0,b=0;for(n||(h=await e.iterator());n?x<t.batchesPerEpoch:!0;){let w=await h.next();if(n&&w.done){console.warn(`You provided \`batchesPerEpoch\` as ${t.batchesPerEpoch}, but your dataset iterator ran out of data after ${x} 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(w.value!=null){let{xs:_,ys:C}=aV(r,w.value),A={};A.batch=b,A.size=_[0].shape[0],await m.onBatchBegin(b,A);let D=[];if(t.classWeight!=null){let M=Ly(t.classWeight,r.outputNames);for(let G=0;G<M.length;++G)D.push(await zy(C[G],null,M[G]))}let $=_.concat(C).concat(D),R=i($);De($);for(let M=0;M<l.length;++M){let G=l[M],j=R[M];A[G]=j,Rt(j)}await m.onBatchEnd(b,A),Ey(A),b++,x++}if(n?x>=t.batchesPerEpoch:w.done){if(o){let _;cV(t.validationData)?_=wt(await r.evaluateDataset(t.validationData,{batches:t.validationBatches})):_=wt(r.evaluate(s,a,{batchSize:t.validationBatchSize==null?Jre:t.validationBatchSize,verbose:0}));for(let C=0;C<r.metricsNames.length;++C)g[`val_${r.metricsNames[C]}`]=_[C]}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 ene(r,e){let t=null;return e.batchesPerEpoch!=null?t=e.batchesPerEpoch:Number.isFinite(r.size)&&(t=r.size),t}function cV(r){return typeof r.iterator=="function"}function tne(r){return typeof r.next=="function"}async function pV(r,e,t){t=t||{};let n=t.batches!=null,o=r.testFunction,s=[];if(t.verbose>0)throw new Te("Verbose mode is not implemented yet.");y.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 a=tne(e)?e:await e.iterator(),i=0,l=0;for(;n?l<t.batches:!0;){let u=await a.next();if(s=B(()=>{if(u.value){let{xs:c,ys:p}=aV(r,u.value),m=c.concat(p),f=B(()=>o(m));if(De(m),l===0)for(let h=0;h<f.length;++h)s.push(pe(0));let d=m[0].shape[0];for(let h=0;h<f.length;++h){let g=f[h],x=s[h];s[h]=B(()=>J(s[h],P(d,g))),l>0&&De(x)}De(f),i+=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 c=s[u];s[u]=ue(s[u],i),De(c)}return vr(s)}function By(r){y.assert(r>0&&Number.isInteger(r),()=>`batchSize is required to be a positive integer, but got ${r}`)}function Im(r,e,t){return r==null?[null]:Array.isArray(r)?r.map(n=>Za(n,e,t-e)):Za(r,e,t-e)}function Vy(r,e){return B(()=>r==null?null:Array.isArray(r)?r.map(t=>Vy(t,e)):ky(r,e.dtype==="int32"?e:e.toInt()))}function Gy(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 rne(r,e,t,n,o,s,a,i,l,u,c,p,m,f,d){o==null&&(o=32),s==null&&(s=1),c==null&&(c=!0),m==null&&(m=0);let h=!1;if(l!=null&&u!=null&&(h=!0),d!=null&&(h=!0,f==null))throw new z("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"),x;g!=null&&(x=Kr(0,g)),a==null&&(a=1);let{callbackList:b,history:w}=Dy(i,a,s,m,g,f,o,h,p);b.setModel(r),r.history=w,await b.onTrainBegin(),r.stopTraining_=!1;for(let _=m;_<s;++_){await b.onEpochBegin(_);let C={};if(f!=null)throw new Te("stepsPerEpoch mode is not implemented yet.");{if(c==="batch")throw new Te("batch shuffling is not implemneted yet");c&&y.shuffle(x);let A=Dt(x),D=Gy(g,o);for(let $=0;$<D.length;++$){let R={};if(await b.onBatchBegin($,R),B(()=>{let M=D[$][0],G=D[$][1],j=Za(A,M,G-M);R.batch=$,R.size=G-M;let U=Vy(t,j),q=e(U);for(let H=0;H<n.length;++H){let X=n[H],ne=q[H];R[X]=ne,Rt(ne)}if($===D.length-1&&h){let H=r.testLoop(l,u,o);for(let X=0;X<n.length;++X){let ne=n[X],Y=H[X];Rt(Y),C["val_"+ne]=Y}}}),await b.onBatchEnd($,R),Ey(R),r.stopTraining_)break}A.dispose()}if(await b.onEpochEnd(_,C),r.stopTraining_)break}return await b.onTrainEnd(),await r.history.syncData(),r.history}async function mV(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,a,i,l,u,c;try{let p=n.batchSize==null?32:n.batchSize;By(p);let m=!1,f=await r.standardizeUserData(e,t,n.sampleWeight,n.classWeight,m,p);o=f[0],s=f[1],c=f[2];let d=!1,h;if(n.validationData!=null&&n.validationData.length>0){if(d=!0,n.validationData.length===2)a=n.validationData[0],i=n.validationData[1];else throw n.validationData.length===3?new Te("validationData including sample weights is not supported yet."):new z(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${n.validationData} is invalid.`);let D=!0,$=await r.standardizeUserData(a,i,null,null,D,p);l=$[0],u=$[1],h=l.concat(u)}else if(n.validationSplit!=null&&n.validationSplit>0&&n.validationSplit<1){d=!0;let D=Math.floor(o[0].shape[0]*(1-n.validationSplit)),$=o[0].shape[0];l=Im(o,D,$),o=Im(o,0,D),u=Im(s,D,$),s=Im(s,0,D),h=l.concat(u)}else n.validationSteps!=null&&(d=!0);let g=o.concat(s).concat(c);r.checkTrainableWeightsConsistency();let x=r.makeTrainFunction(),b=r.getDedupedMetricsNames(),w,_;d?(r.makeTestFunction(),w=r.testFunction,_=b.slice().concat(b.map(D=>"val_"+D))):(w=null,h=[],_=b.slice());let C=Ay(n.callbacks,n.yieldEvery);return await rne(r,x,g,b,p,n.epochs,n.verbose,C,w,h,n.shuffle,_,n.initialEpoch,null,null)}finally{r.isTraining=!1,jl(o,e),jl(s,t),jl(l,a),jl(u,i),c!=null&&De(c)}}function ZC(r){let e=[];r instanceof Me&&(r=[r]);for(let t=0;t<r.length;++t){let n=r[t];if(n.rank===1)e.push(Ya(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 jl(r,e){if(r==null)return;let t=[];if(e instanceof Me)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 Me)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 nne(r){return r instanceof Me}function JC(r){return Array.isArray(r)}function fV(r){return!nne(r)&&!JC(r)}function dV(r,e,t,n=!0,o=""){if(e==null||e.length===0){if(r!=null){let a=!1;if(JC(r)&&r.length>0)a=!0;else if(fV(r)){for(let i in r)if(r.hasOwnProperty(i)){a=!0;break}}else a=!0;if(a)throw new z(`Error when checking model ${o} expected no data, but got ${r}`)}return[]}if(r==null)return e.map(a=>null);let s;if(fV(r)){r=r,s=[];for(let a of e){if(r[a]==null)throw new z(`No data provided for "${a}". Need data for each key in: ${e}`);s.push(r[a])}}else if(JC(r)){if(r=r,r.length!==e.length)throw new z(`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 z(`The model ${o} expects ${e.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${r.shape}`);s=[r]}if(s=ZC(s),t!=null)for(let a=0;a<e.length;++a){if(t[a]==null)continue;let i=s[a];if(i.shape.length!==t[a].length)throw new z(`Error when checking ${o}: expected ${e[a]} to have ${t[a].length} dimension(s). but got array with shape ${i.shape}`);for(let l=0;l<t[a].length;++l){if(l===0&&!n)continue;let u=i.shape[l],c=t[a][l];if(c!=null&&c>=0&&u!==c)throw new z(`Error when checking ${o}: expected ${e[a]} to have shape [${t[a]}], but got array with shape [${i.shape}].`)}}return s}function one(r,e,t){let n=So(r.map(s=>s.shape[0]));n.sort();let o=So(e.map(s=>s.shape[0]));if(o.sort(),n.length>1)throw new z(`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 z(`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&&!y.arraysEqual(n,o))throw new z(`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 sne(r,e,t){let n=[Si,Cm,wc];for(let o=0;o<r.length;++o){let s=r[o],a=e[o],i=t[o];if(a!=null){if(a===wc&&s.shape[s.shape.length-1]===1)throw new z(`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(a)!==-1){let l=s.shape.slice(1),u=i.slice(1);for(let c=0;c<l.length;++c){let p=l[c],m=u[c];if(m!=null&&p!==m)throw new z(`A target Tensor with shape ${s.shape} was passed for an output of shape ${i}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}function hV(r,e,t,n=!0,o=""){let s;if(Array.isArray(r)){if(r.length!==e.length)throw new z(`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 z(`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 a=0;a<e.length;++a){if(t[a]==null)continue;let i=s[a];if(i.shape.length!==t[a].length)throw new z(`Error when checking ${o}: expected ${e[a]} to have ${t[a].length} dimension(s), but got array with shape ${JSON.stringify(i.shape)}`);for(let l=0;l<t[a].length;++l){if(l===0&&!n)continue;let u=i.shape[l],c=t[a][l];if(c!=null&&c!==u)throw new z(`Error when checking ${o}: expected ${e[a]} to have shape ${JSON.stringify(t[a])} but got array with shape ${JSON.stringify(i.shape)}.`)}}}function ine(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 ane="layers-model",Jn=class extends Zn{constructor(e){super(e);this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new z("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).");rV(this,e,t,n)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=eV(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Ur))throw new z("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 a in e.loss)if(this.outputNames.indexOf(a)===-1)throw new z(`Unknown entry in loss dictionary: "${a}". Only expected the following keys: ${this.outputNames}`);for(let a of this.outputNames)e.loss[a]==null&&console.warn(`Output "${a}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${a} during training`),t.push($y(e.loss[a]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new z(`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(i=>$y(i))}else{let a=$y(e.loss);this.outputs.forEach(i=>{t.push(a)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let a=0;a<this.outputs.length;++a){let i=this.internalOutputShapes[a],l=this.outputNames[a];this.feedOutputNames.push(l),this.feedOutputShapes.push(i),this.feedLossFns.push(this.lossFunctions[a])}let n=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],Bs("loss",()=>{for(let a=0;a<this.outputs.length;++a){if(n.indexOf(a)!==-1)continue;let i=this.lossFunctions[a];this.outputs.length>1&&(this.metricsTensors.push([i,a]),this.metricsNames.push(this.outputNames[a]+"_loss"))}});let o=ine(e.metrics,this.outputNames),s=(a,i,l)=>{this.outputNames.length>1&&(i=this.outputNames[a]+"_"+i),this.metricsNames.push(i),this.metricsTensors.push([l,a])};Bs("metric",()=>{for(let a=0;a<this.outputs.length;++a){if(n.indexOf(a)!==-1)continue;let i=o[a];(u=>{let c="",p,m,f;for(let d of u){if(typeof d=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(d)!==-1){let g=this.internalOutputShapes[a];g[g.length-1]===1||this.lossFunctions[a]===Cm?["accuracy","acc"].indexOf(d)!==-1?m=Vd:["crossentropy","ce"].indexOf(d)!==-1&&(m=Ry):this.lossFunctions[a]===vm?["accuracy","acc"].indexOf(d)!==-1?m=Fy:["crossentropy","ce"].indexOf(d)!==-1&&(m=HC):["accuracy","acc"].indexOf(d)!==-1?m=Gd:["crossentropy","ce"].indexOf(d)!==-1&&(m=Wd);let x;["accuracy","acc"].indexOf(d)!==-1?x="acc":["crossentropy","ce"].indexOf(d)!==-1&&(x="ce"),f=m,p=c+x}else f=QB(d),p=c+jd(d);let h;Bs(p,()=>{h=f}),s(a,p,h)}})(i)}}),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;By(o);let s=!0,a=this.standardizeUserDataXY(e,t,s,o);try{let i=a[0].concat(a[1]);this.makeTestFunction();let l=this.testFunction,u=this.testLoop(l,i,o,n.verbose,n.steps);return vr(u)}finally{jl(a[0],e),jl(a[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),pV(this,e,t)}checkNumSamples(e,t,n,o="steps"){let s;if(n!=null){if(s=null,t!=null)throw new z(`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 z(`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 z("`outputs` is an empty Array, which is not allowed.");let n=Array.isArray(t),o=n?t:[t],s=this.retrieveSymbolicTensors(o),a=new Gs;if(e instanceof Me&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new z(`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)a.add(this.inputs[l],e[l])}else for(let l of this.inputs){let u=e[l.name];if(u==null)throw new z(`No value is provided for the model's input ${l.name}`);a.add(l,u)}let i=kc(s,a);return n?i:i[0]}retrieveSymbolicTensors(e){let t=vo(null,e.length),n=e.length;for(let o of this.layers){let s=Array.isArray(o.output)?o.output:[o.output],a=s.map(i=>i.name);for(let i=0;i<e.length;++i){let l=a.indexOf(e[i]);if(l!==-1&&(t[i]=s[l],n--),n===0)break}if(n===0)break}if(n>0){let o=[];throw t.forEach((s,a)=>{s==null&&o.push(e[a])}),new z(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(o)}`)}return t}predictLoop(e,t=32,n=!1){return B(()=>{let o=this.checkNumSamples(e);if(n)throw new Te("Verbose predictLoop() is not implemented yet.");let s=Gy(o,t),a=this.outputs.map(i=>[]);for(let i=0;i<s.length;++i)B(()=>{let u=s[i][0],c=s[i][1],p=Im(e,u,c),m=[];if(Array.isArray(p))for(let d=0;d<p.length;++d)m.push({key:this.inputs[d],value:p[d]});else m.push({key:this.inputs[0],value:p});let f=new Gs(m);return kc(this.outputs,f)}).forEach((u,c)=>a[c].push(u));return vr(a.map(i=>et(i,0)))})}predict(e,t={}){let n=ZC(e);hV(n,this.inputNames,this.feedInputShapes,!1);try{let o=t.batchSize==null?32:t.batchSize;return By(o),this.predictLoop(n,o)}finally{jl(n,e)}}predictOnBatch(e){hV(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 Hr("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");let s=[];for(let a=0;a<this.feedOutputShapes.length;++a){let i=this.feedOutputShapes[a];this.feedLossFns[a]===vm?s.push(i.slice(0,i.length-1).concat([1])):s.push(i)}if(e=dV(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=dV(t,this.feedOutputNames,s,!1,"target"),one(e,t,null),sne(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&o!=null&&o>0&&e[0].shape[0]%o!=0)throw new z(`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,a){let[i,l]=this.standardizeUserDataXY(e,t,s,a);if(n!=null)throw new Error("sample weight is not supported yet.");let u=null;if(o!=null){let c=Ly(o,this.outputNames);u=[];for(let p=0;p<c.length;++p)u.push(await zy(l[p],null,c[p]))}return[i,l,u]}testLoop(e,t,n,o=0,s){return B(()=>{let a=this.checkNumSamples(t,n,s,"steps"),i=[];if(o>0)throw new Te("Verbose mode is not implemented yet.");if(s!=null)throw new Te("steps mode in testLoop() is not implemented yet");{let l=Gy(a,n),u=Dt(Kr(0,a));for(let c=0;c<l.length;++c){let p=l[c][0],m=l[c][1],f=Za(u,p,m-p),d=Vy(t,f),h=e(d);if(c===0)for(let g=0;g<h.length;++g)i.push(pe(0));for(let g=0;g<h.length;++g){let x=h[g];i[g]=J(i[g],P(m-p,x))}}for(let c=0;c<i.length;++c)i[c]=ue(i[c],a)}return i})}getDedupedMetricsNames(){let e=this.metricsNames,t=[];for(let n=0;n<e.length;++n){let o=e[n],s=o;OC(e,o)>1&&(s+=`_${OC(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),a=[],i=()=>{let p=[];for(let h=0;h<this.inputs.length;++h)p.push({key:this.inputs[h],value:n[h]});let m=new Gs(p),f=kc(this.outputs,m,{training:!0}),d;for(let h=0;h<this.lossFunctions.length;++h){let x=this.lossFunctions[h](o[h],f[h]);s[h]!=null&&(x=iV(x,s[h]));let b=ht(x);t.push(b),h===0?d=x:d=J(d,x)}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 x=this.metricsTensors[h][0],b=this.metricsTensors[h][1];g=ht(x(o[b],f[b]))}Rt(g),a.push(g)}return d=ht(d),this.calculateLosses().forEach(h=>{d=J(d,h)}),d},l=this.collectedTrainableWeights.map(p=>p.read()),u=!0;return[this.optimizer_.minimize(i,u,l)].concat(a)}}makeTestFunction(){this.testFunction=e=>B(()=>{let t=[],n,o=e.slice(0,this.inputs.length),s=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=[];for(let u=0;u<this.inputs.length;++u)a.push({key:this.inputs[u],value:o[u]});let i=new Gs(a),l=kc(this.outputs,i);for(let u=0;u<this.lossFunctions.length;++u){let c=this.lossFunctions[u],p=ht(c(s[u],l[u]));u===0?n=p:n=J(n,p),t.push(n)}for(let u=0;u<this.metricsTensors.length;++u){let c=this.metricsTensors[u][0],p=this.metricsTensors[u][1],m=ht(c(s[p],l[p]));t.push(m)}return t})}async fit(e,t,n={}){return mV(this,e,t,n)}async fitDataset(e,t){return uV(this,e,t)}async trainOnBatch(e,t){let n=await this.standardizeUserData(e,t),o=n[0],s=n[1],i=this.makeTrainFunction()(o.concat(s)),l=[];for(let u of i){let c=await u.data();l.push(c[0])}return De(i),vr(l)}getNamedWeights(e){let t=[],n=e!=null&&e.trainableOnly,o=n?this.trainableWeights:this.weights,s=this.getWeights(n);for(let a=0;a<o.length;++a)n&&!o[a].trainable||t.push({name:o[a].originalName,tensor:s[a]});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=df().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-df().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=Co(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=>Co(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]=Co(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[Co(jd(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>Co(jd(e)));{let e={};for(let t in this.metrics)e[t]=Co(jd(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=_c(e.optimizer_config),n=fn(t),o;if(typeof e.loss=="string")o=Ka(e.loss);else if(Array.isArray(e.loss))o=e.loss.map(a=>Ka(a));else if(e.loss!=null){o={};for(let a in e.loss)o[a]=Ka(e.loss[a])}let s;if(Array.isArray(e.metrics))s=e.metrics.map(a=>Ka(a));else if(e.metrics!=null){s={};for(let a in e.metrics)s[a]=Ka(e.metrics[a])}this.compile({loss:o,metrics:s,optimizer:n})}async save(e,t){if(typeof e=="string"){let u=Or.getSaveHandlers(e);if(u.length===0)throw new z(`Cannot find any save handlers for URL '${e}'`);if(u.length>1)throw new z(`Found more than one (${u.length}) save handlers for URL '${e}'`);e=u[0]}if(e.save==null)throw new z("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");let n=await Or.encodeWeights(this.getNamedWeights(t)),o=!1,s=null,i={modelTopology:this.toJSON(s,o),format:ane,generatedBy:`TensorFlow.js tfjs-layers v${Ud}`,convertedBy:null};if((t==null?!1:t.includeOptimizer)&&this.optimizer!=null){i.trainingConfig=this.getTrainingConfig();let u="optimizer",{data:c,specs:p}=await Or.encodeWeights(await this.optimizer.getWeights(),u);n.specs.push(...p),n.data=Or.concatenateArrayBuffers([n.data,c])}if(this.userDefinedMetadata!=null){let u=!0;KC(this.userDefinedMetadata,this.name,u),i.userDefinedMetadata=this.userDefinedMetadata}return i.weightData=n.data,i.weightSpecs=n.specs,e.save(i)}setUserDefinedMetadata(e){KC(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};Jn.className="Model";Q.registerClass(Jn);var QC=class extends Jn{};QC.className="Functional";Q.registerClass(QC);async function gV(r,e){"modelTopology"in r||(r={modelTopology:r}),r=r;let t=r.modelTopology;t.model_config!=null&&(t=t.model_config);let n=_c(t),o=fn(n,e);if(r.weightsManifest!=null){let s=await Or.loadWeights(r.weightsManifest,r.pathPrefix,o.weights.map(i=>i.originalName)),a={};for(let i of o.weights)a[i.originalName]=s[i.originalName];o.loadWeights(a),De(s)}return o}async function xV(r,e){if(e==null&&(e={}),typeof r=="string"){let t=Or.getLoadHandlers(r,e);if(t.length===0)t.push(Or.browserHTTPRequest(r,e));else if(t.length>1)throw new z(`Found more than one (${t.length}) load handlers for URL '${r}'`);r=t[0]}return lne(r,void 0,e)}async function lne(r,e,t){if(t==null&&(t={}),r.load==null)throw new z("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,a=n.weightData!=null&&n.weightSpecs!=null&&s,i=fn(_c(o),e,a),l=n.trainingConfig;if(l!=null&&i.loadTrainingConfig(l),n.userDefinedMetadata!=null&&i.setUserDefinedMetadata(n.userDefinedMetadata),n.weightData!=null){if(n.weightSpecs==null)throw new z("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");let{modelWeights:u,optimizerWeights:c}=une(n.weightData,n.weightSpecs);i.loadWeights(u,s),i.optimizer!=null&&c.length>0&&await i.optimizer.setWeights(c),De(u),De(c.map(p=>p.tensor))}return i}function une(r,e){let t=Or.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 Ja=class extends Jn{constructor(e){super({inputs:[],outputs:[]});if(e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:Bl("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 z(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){let t=e instanceof Ja||e instanceof Jn,n;if(t){if(n=e,n.outputs.length!==1)throw new z("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 z("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 z("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");let o=Ty({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 z(`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 z("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=GC(this.outputs[0])}this.inboundNodes=[],new Vl({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:vo(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(Ye(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 Jn({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 Hr("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 Hr("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 Hr("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 Hr("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,a={};if(t instanceof Array){if(t[0].className==null||t[0].className==="Merge")throw new z("Legacy serialization format not supported yet.");s=t}else y.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,a=t;let i=new e(a);if(!(i instanceof Ja))throw new Te(`Sequential.fromConfig called on non-Sequential input: ${i}`);for(let l of s){let c=fn(l,void 0,o);o&&c.setFastWeightInitDuringBuild(!0),i.add(c)}return i}set stopTraining(e){if(this.model==null)throw new z("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 z("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}}};Ja.className="Sequential";Q.registerClass(Ja);function cne(r){return new Jn(r)}function pne(r){return new Ja(r)}function mne(r,e){return e==null&&(e={}),xV(r,e)}function eI(r){return Ty(r)}function fne(r,e){Sn.registerCallbackConstructor(r,e)}var dn=class extends Q.Serializable{getConfig(){return{}}},tI=class extends dn{apply(e,t=1){return BB(e,t)}};tI.className="elu";Q.registerClass(tI);var rI=class extends dn{apply(e){return Pu(e)}};rI.className="selu";Q.registerClass(rI);var nI=class extends dn{apply(e){return Mr(e)}};nI.className="relu";Q.registerClass(nI);var oI=class extends dn{apply(e){return B(()=>Rs(6,Mr(e)))}};oI.className="relu6";Q.registerClass(oI);var sI=class extends dn{apply(e){return e}};sI.className="linear";Q.registerClass(sI);var iI=class extends dn{apply(e){return Pr(e)}};iI.className="sigmoid";Q.registerClass(iI);var aI=class extends dn{apply(e){return GB(e)}};aI.className="hardSigmoid";Q.registerClass(aI);var lI=class extends dn{apply(e){return po(e)}};lI.className="softplus";Q.registerClass(lI);var uI=class extends dn{apply(e){return VB(e)}};uI.className="softsign";Q.registerClass(uI);var cI=class extends dn{apply(e){return Ts(e)}};cI.className="tanh";Q.registerClass(cI);var qd=class extends dn{apply(e,t=-1){return Pa(e,t)}};qd.className="softmax";Q.registerClass(qd);var pI=class extends dn{apply(e,t=-1){return Eu(e,t)}};pI.className="logSoftmax";Q.registerClass(pI);var mI=class extends dn{apply(e,t=1){return B(()=>Pr(e.mul(t)).mul(e))}};mI.className="swish";Q.registerClass(mI);var fI=class extends dn{apply(e){return B(()=>P(e,Ts(po(e))))}};fI.className="mish";Q.registerClass(fI);function Ws(r){return r.getClassName()}function dI(r,e={}){return ki(r,Q.SerializationMap.getMap().classNameMap,e,"activation")}function js(r){if(r==null){let e={};return e.className="linear",e.config={},dI(e)}if(typeof r=="string"){let e={};return e.className=r,e.config={},dI(e)}else return r instanceof dn?r:dI(r)}function hI(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 gI=class extends Q.Serializable{},vc=class extends gI{constructor(e){super();hI(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 B(()=>{let t=gt([1]);return this.hasL1&&(t=J(t,de(P(this.l1,Tt(e))))),this.hasL2&&(t=J(t,de(P(this.l2,yc(e))))),t.asScalar()})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}};vc.className="L1L2";Q.registerClass(vc);function yV(r){return hI(r),new vc({l1:r!=null?r.l1:null,l2:0})}function bV(r){return hI(r),new vc({l2:r!=null?r.l2:null,l1:0})}var wV={l1l2:"L1L2"};function at(r){return lm(r)}function _V(r,e={}){return ki(r,Q.SerializationMap.getMap().classNameMap,e,"regularizer")}function _t(r){if(r==null)return null;if(typeof r=="string"){let t={className:r in wV?wV[r]:r,config:{}};return _V(t)}else return r instanceof gI?r:_V(r)}var Hd=class extends ze{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=Oe(e);let n=Mr(e);return this.maxValue!=null&&(n=fr(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){let e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}};Hd.className="ReLU";Q.registerClass(Hd);var Kd=class extends ze{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=Oe(e);return Aa(n,this.alpha)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};Kd.className="LeakyReLU";Q.registerClass(Kd);var Xd=class extends ze{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=mt(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=_t(e.alphaRegularizer),this.alphaConstraint=Bt(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 z(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=Ye(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 St({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=Oe(e),Fa(e,this.alpha.read())}getConfig(){let e={alphaInitializer:It(this.alphaInitializer),alphaRegularizer:at(this.alphaRegularizer),alphaConstraint:zt(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}};Xd.className="PReLU";Q.registerClass(Xd);var Yd=class extends ze{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA=1,e==null&&(e={}),e.alpha!=null&&e.alpha!==this.DEFAULT_ALPHA)throw new Te(`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=Oe(e);return As(n)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};Yd.className="ELU";Q.registerClass(Yd);var Zd=class extends ze{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=Oe(e);return n.mul(Xa(n.greater(this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){let e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}};Zd.className="ThresholdedReLU";Q.registerClass(Zd);var Jd=class extends ze{constructor(e){super(e==null?{}:e);this.DEFAULT_AXIS=1,e==null&&(e={}),this.softmax=new qd().apply,this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis}call(e,t){let n=Oe(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}};Jd.className="Softmax";Q.registerClass(Jd);function Ul(r,e,t){if(typeof r=="number")return vo(r,e);if(r.length!==e)throw new z(`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(!PB(o))throw new z(`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 Nn(r,e,t,n,o=1){if(r==null)return r;let s=e+(e-1)*(o-1),a;return t==="same"?a=r:a=r-s+1,Math.floor((a+n-1)/n)}function Us(r,e,t,n){if(r==null)return null;if(n==="valid")r=r*e+Vs([t-e,0]);else if(n==="same")r=r*e;else throw new z(`Unsupport padding mode: ${n}.`);return r}function Qd(r,e){return B(()=>(Pt(e),e==="channelsFirst"?qe(r,[0,2,3,1]):r))}function xI(r,e){return B(()=>(Pt(e),e==="channelsFirst"?qe(r,[0,2,3,4,1]):r))}function dne(r,e,t,n=1,o="valid",s,a=1){return B(()=>{if(s==null&&(s=un()),Pt(s),r.shape.length!==3)throw new z(`The input of a conv1dWithBias operation should be 3, but is ${r.shape.length} instead.`);if(e.shape.length!==3)throw new z(`The kernel for a conv1dWithBias operation should be 3, but is ${e.shape.length} instead`);if(t!=null&&t.shape.length!==1)throw new z(`The bias for a conv1dWithBias operation should be 1, but is ${e.shape.length} instead`);if(s==="channelsFirst"&&(r=qe(r,[0,2,1])),o==="causal")throw new Te("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let i=ku(r,e,n,o==="same"?"same":"valid","NWC",a);return t!=null&&(i=pn(i,t)),i})}function kV(r,e,t,n=[1,1],o="valid",s,a,i=null){return B(()=>{if(s==null&&(s=un()),Pt(s),r.rank!==3&&r.rank!==4)throw new z(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${r.rank}.`);if(e.rank!==3&&e.rank!==4)throw new z(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${r.rank}.`);let l=Qd(r,s);if(o==="causal")throw new Te("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=ho.conv2d({x:l,filter:e,strides:n,pad:o==="same"?"same":"valid",dilations:a,dataFormat:"NHWC",bias:t,activation:i}),s==="channelsFirst"&&(l=qe(l,[0,3,1,2])),l})}function hne(r,e,t,n=[1,1,1],o="valid",s,a){return B(()=>{if(s==null&&(s=un()),Pt(s),r.rank!==4&&r.rank!==5)throw new z(`conv3dWithBias expects input to be of rank 4 or 5, but received ${r.rank}.`);if(e.rank!==4&&e.rank!==5)throw new z(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${r.rank}.`);let i=xI(r,s);if(o==="causal")throw new Te("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return i=Sf(i,e,n,o==="same"?"same":"valid","NDHWC",a),t!=null&&(i=pn(i,t)),s==="channelsFirst"&&(i=qe(i,[0,4,1,2,3])),i})}var Sm=class extends ze{constructor(e,t){super(t);if(this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",Sm.verifyArgs(t),this.rank=e,Zt(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new Te(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=Ul(t.kernelSize,e,"kernelSize"),this.strides=Ul(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,cn(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,Pt(this.dataFormat),this.activation=js(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=mt(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Bt(t.biasConstraint),this.biasRegularizer=_t(t.biasRegularizer),this.activityRegularizer=_t(t.activityRegularizer),this.dilationRate=Ul(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new z(`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 z(`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 z(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(Yn("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!xy(e.kernelSize,"number",1,3))throw new z(`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:Ws(this.activation),useBias:this.useBias,biasInitializer:It(this.biasInitializer),biasRegularizer:at(this.biasRegularizer),activityRegularizer:at(this.activityRegularizer),biasConstraint:zt(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}},Cc=class extends Sm{constructor(e,t){super(e,t);this.kernel=null,Cc.verifyArgs(t),this.filters=t.filters,Zt(this.filters,"filters"),this.kernelInitializer=mt(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Bt(t.kernelConstraint),this.kernelRegularizer=_t(t.kernelRegularizer)}build(e){e=Ye(e);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new z(`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 B(()=>{e=Oe(e);let n,o=this.bias==null?null:this.bias.read(),s=yy(this.activation.getClassName());if(s!=null&&this.rank===2)n=kV(e,this.kernel.read(),o,this.strides,this.padding,this.dataFormat,this.dilationRate,s);else{if(this.rank===1)n=dne(e,this.kernel.read(),o,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)n=kV(e,this.kernel.read(),o,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)n=hne(e,this.kernel.read(),o,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new Te("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(n=this.activation.apply(n))}return n})}computeOutputShape(e){e=Ye(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 a=Nn(n[s],this.kernelSize[s],this.padding,this.strides[s],typeof this.dilationRate=="number"?this.dilationRate:this.dilationRate[s]);t.push(a)}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:It(this.kernelInitializer),kernelRegularizer:at(this.kernelRegularizer),kernelConstraint:zt(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 z(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}},ql=class extends Cc{constructor(e){super(2,e);ql.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!xy(e.kernelSize,"number",1,2))throw new z(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}};ql.className="Conv2D";Q.registerClass(ql);var Hl=class extends Cc{constructor(e){super(3,e);Hl.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 z(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}};Hl.className="Conv3D";Q.registerClass(Hl);var eh=class extends ql{constructor(e){super(e);if(this.inputSpec=[new St({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new z(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=Ye(e),e.length!==4)throw new z("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 z("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 St({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return B(()=>{let n=Oe(e);if(n.shape.length!==4)throw new z(`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],a,i;this.dataFormat==="channelsFirst"?(a=2,i=3):(a=1,i=2);let l=o[a],u=o[i],c=this.kernelSize[0],p=this.kernelSize[1],m=this.strides[0],f=this.strides[1],d=Us(l,m,c,this.padding),h=Us(u,f,p,this.padding),g=[s,d,h,this.filters];this.dataFormat!=="channelsLast"&&(n=qe(n,[0,2,3,1]));let x=vu(n,this.kernel.read(),g,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(x=qe(x,[0,3,1,2])),this.bias!=null&&(x=pn(x,this.bias.read(),this.dataFormat)),this.activation!=null&&(x=this.activation.apply(x)),x})}computeOutputShape(e){e=Ye(e);let t=e.slice(),n,o,s;this.dataFormat==="channelsFirst"?(n=1,o=2,s=3):(n=3,o=1,s=2);let a=this.kernelSize[0],i=this.kernelSize[1],l=this.strides[0],u=this.strides[1];return t[n]=this.filters,t[o]=Us(t[o],l,a,this.padding),t[s]=Us(t[s],u,i,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};eh.className="Conv2DTranspose";Q.registerClass(eh);var th=class extends Hl{constructor(e){super(e);if(this.inputSpec=[new St({ndim:5})],this.padding!=="same"&&this.padding!=="valid")throw new z(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=Ye(e),e.length!==5)throw new z("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 z("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 St({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return B(()=>{let n=Oe(e);if(n.shape.length!==5)throw new z(`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],a,i,l;this.dataFormat==="channelsFirst"?(l=2,a=3,i=4):(l=1,a=2,i=3);let u=o[l],c=o[a],p=o[i],m=this.kernelSize[0],f=this.kernelSize[1],d=this.kernelSize[2],h=this.strides[0],g=this.strides[1],x=this.strides[2],b=Us(u,h,m,this.padding),w=Us(c,g,f,this.padding),_=Us(p,x,d,this.padding),C=[s,b,w,_,this.filters];this.dataFormat!=="channelsLast"&&(n=qe(n,[0,2,3,4,1]));let A=M_(n,this.kernel.read(),C,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(A=qe(A,[0,4,1,2,3])),this.bias!==null&&(A=pn(A,this.bias.read(),this.dataFormat)),this.activation!==null&&(A=this.activation.apply(A)),A})}computeOutputShape(e){e=Ye(e);let t=e.slice(),n,o,s,a;this.dataFormat==="channelsFirst"?(n=1,o=2,s=3,a=4):(n=4,o=1,s=2,a=3);let i=this.kernelSize[0],l=this.kernelSize[1],u=this.kernelSize[2],c=this.strides[0],p=this.strides[1],m=this.strides[2];return t[n]=this.filters,t[o]=Us(t[o],c,i,this.padding),t[s]=Us(t[s],p,l,this.padding),t[a]=Us(t[a],m,u,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};th.className="Conv3DTranspose";Q.registerClass(th);var yI=class extends Cc{constructor(e,t){super(e,t);if(this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,t.filters==null)throw new z("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new z("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 z(`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=mt(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=_t(t.depthwiseRegularizer),this.depthwiseConstraint=Bt(t.depthwiseConstraint),this.pointwiseInitializer=mt(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=_t(t.pointwiseRegularizer),this.pointwiseConstraint=Bt(t.pointwiseConstraint)}build(e){if(e=Ye(e),e.length<this.rank+2)throw new z(`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 z(`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 i=0;i<this.rank;++i)s.push(1);s.push(n*this.depthMultiplier,this.filters);let a=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",o,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,a,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",s,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,a,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,a,this.biasConstraint):this.bias=null,this.inputSpec=[new St({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return B(()=>{e=Oe(e);let n;if(this.rank===1)throw new Te("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=qe(e,[0,2,3,1])),n=Bf(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(n=pn(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),this.dataFormat==="channelsFirst"&&(n=qe(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=It(this.depthwiseInitializer),e.pointwiseInitializer=It(this.pointwiseInitializer),e.depthwiseRegularizer=at(this.depthwiseRegularizer),e.pointwiseRegularizer=at(this.pointwiseRegularizer),e.depthwiseConstraint=zt(this.depthwiseConstraint),e.pointwiseConstraint=zt(this.pointwiseConstraint),e}};yI.className="SeparableConv";var rh=class extends yI{constructor(e){super(2,e)}};rh.className="SeparableConv2D";Q.registerClass(rh);var Ic=class extends Cc{constructor(e){super(1,e);Ic.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"&&!xy(e.kernelSize,"number",1,1))throw new z(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}};Ic.className="Conv1D";Q.registerClass(Ic);var nh=class extends ze{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 B(()=>{if(e=Oe(e),this.dataFormat==="channelsLast"){let n=Ed(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Ed(n,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let n=Ed(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Ed(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}};nh.className="Cropping2D";Q.registerClass(nh);var oh=class extends ze{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,Pt(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,RB(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 B(()=>{let n=Oe(e),o=n.shape;if(this.dataFormat==="channelsFirst"){n=qe(n,[0,2,3,1]);let s=this.size[0]*o[2],a=this.size[1]*o[3],i=this.interpolation==="nearest"?n.resizeNearestNeighbor([s,a]):n.resizeBilinear([s,a]);return qe(i,[0,3,1,2])}else{let s=this.size[0]*o[1],a=this.size[1]*o[2];return this.interpolation==="nearest"?n.resizeNearestNeighbor([s,a]):n.resizeBilinear([s,a])}})}getConfig(){let e={size:this.size,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};oh.className="UpSampling2D";Q.registerClass(oh);function gne(r,e,t=[1,1],n="valid",o,s){return B(()=>{o==null&&(o=un()),Pt(o);let a=Qd(r,o);if(r.rank!==4)throw new z(`Input for depthwiseConv2d is required to be 4-D, but is instead ${r.rank}-D`);if(e.rank!==4)throw new z(`depthwiseKernel is required to be 4-D, but is instead ${e.rank}-D`);return a=Es(a,e,t,n==="same"?"same":"valid","NHWC",s),o==="channelsFirst"&&(a=qe(a,[0,3,1,2])),a})}var sh=class extends Sm{constructor(e){super(2,e);this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=mt(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Bt(e.depthwiseConstraint),this.depthwiseRegularizer=_t(e.depthwiseRegularizer)}build(e){if(e=Ye(e),e.length<4)throw new z(`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 z(`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 B(()=>{e=Oe(e);let n=gne(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(n=pn(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),n})}computeOutputShape(e){e=Ye(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=Nn(t,this.kernelSize[0],this.padding,this.strides[0]),a=Nn(n,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],o,s,a]:[e[0],s,a,o]}getConfig(){let e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=It(this.depthwiseInitializer),e.depthwiseRegularizer=at(this.depthwiseRegularizer),e.depthwiseConstraint=zt(this.depthwiseRegularizer),e}};sh.className="DepthwiseConv2D";Q.registerClass(sh);function bI(r,e,t,n){if(Array.isArray(r)){if(e!=null||t!=null)throw new z("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 wI(r,e,t,n=!1,o,s,a=!1,i=!1){return B(()=>{let l=e.shape.length;if(l<3)throw new z(`Input should be at least 3D, but is ${l}D.`);let u=[1,0].concat(Kr(2,l));if(e=qe(e,u),s!=null)throw new Te("The rnn() functoin of the deeplearn.js backend does not support constants yet.");a&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),o!=null&&(o=o.asType("bool").asType("float32"),o.rank===l-1&&(o=dr(o,-1)),o=qe(o,u)),n&&(e=Jt(e,0),o!=null&&(o=Jt(o,0)));let c=[],p,m=t,f=e.shape[0],d=gr(e),h;o!=null&&(h=gr(o));for(let x=0;x<f;++x){let b=d[x],w=B(()=>r(b,m));if(o==null)p=w[0],m=w[1];else{let _=B(()=>{let C=h[x],A=ur(C).sub(C),D=w[0].mul(C).add(m[0].mul(A)),$=m.map((R,M)=>w[1][M].mul(C).add(R.mul(A)));return{output:D,newStates:$}});p=_.output,m=_.newStates}i&&c.push(p)}let g;return i&&(g=Ht(c,1)),[p,g,m]})}var Bn=class extends ze{constructor(e){super(e);let t;if(e.cell==null)throw new z("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new Em({cells:e.cell}):t=e.cell,t.stateSize==null)throw new z("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=e.returnSequences==null?!1:e.returnSequences,this.returnState=e.returnState==null?!1:e.returnState,this.goBackwards=e.goBackwards==null?!1:e.goBackwards,this._stateful=e.stateful==null?!1:e.stateful,this.unroll=e.unroll==null?!1:e.unroll,this.supportsMasking=!0,this.inputSpec=[new St({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;return Kr(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){Sy(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 a of t)s.push([e[0],a]);return[o].concat(s)}else return o}computeMask(e,t){return B(()=>{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 Te("Constants support is not implemented in RNN yet.");Sy(e)&&(e=e[0]),e=e;let n=this.stateful?e[0]:null,o=e.slice(2);this.inputSpec[0]=new St({shape:[n,null,...o]});let s=[e[0]].concat(e.slice(2));if(t!=null)throw new Te("Constants support is not implemented in RNN yet.");this.cell.build(s);let a;if(Array.isArray(this.cell.stateSize)?a=this.cell.stateSize:a=[this.cell.stateSize],this.stateSpec!=null){if(!y.arraysEqual(this.stateSpec.map(i=>i.shape[i.shape.length-1]),a))throw new z(`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=a.map(i=>new St({shape:[null,i]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){B(()=>{if(!this.stateful)throw new zn("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape[0];if(n==null)throw new z("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=>gt([n,o])):this.states_=[gt([n,this.cell.stateSize])];else if(e==null)De(this.states_),this.keptStates!=null&&(De(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(o=>gt([n,o])):this.states_[0]=gt([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new z(`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()):De(this.states_);for(let o=0;o<this.states_.length;++o){let s=e[o],a=Array.isArray(this.cell.stateSize)?this.cell.stateSize[o]:this.cell.stateSize,i=[n,a];if(!y.arraysEqual(s.shape,i))throw new z(`State ${o} is incompatible with layer ${this.name}: expected shape=${i}, received shape=${s.shape}`);this.states_[o]=s}}this.states_=this.states_.map(o=>Rt(o.clone()))})}apply(e,t){let n=t==null?null:t.initialState,o=t==null?null:t.constants;t==null&&(t={});let s=bI(e,n,o,this.numConstants);e=s.inputs,n=s.initialState,o=s.constants;let a=[],i=[];if(n!=null){t.initialState=n,a=a.concat(n),this.stateSpec=[];for(let u of n)this.stateSpec.push(new St({shape:u.shape}));i=i.concat(this.stateSpec)}if(o!=null&&(t.constants=o,a=a.concat(o),this.numConstants=o.length),a[0]instanceof mn){let u=[e].concat(a),c=this.inputSpec.concat(i),p=this.inputSpec;this.inputSpec=c;let m=super.apply(u,t);return this.inputSpec=p,m}else return super.apply(e,t)}call(e,t){return B(()=>{let n=t==null?null:t.mask,o=t==null?null:t.training,s=t==null?null:t.initialState;e=Oe(e),s==null&&(this.stateful?s=this.states_:s=this.getInitialState(e));let a=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(s.length!==a)throw new z(`RNN Layer has ${a} 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 i={training:o},u=wI((d,h)=>{let g=this.cell.call([d].concat(h),i);return[g[0],g.slice(1)]},e,s,this.goBackwards,n,null,this.unroll,this.returnSequences),c=u[0],p=u[1],m=u[2];this.stateful&&this.resetStates(m,o);let f=this.returnSequences?p:c;return this.returnState?[f].concat(m):f})}getInitialState(e){return B(()=>{let t=gt(e.shape);return t=de(t,[1,2]),t=Ya(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(n=>n>1?_y(t,[1,n]):t):this.cell.stateSize>1?[_y(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}),Object.assign({},n,e,t)}static fromConfig(e,t,n={}){let o=t.cell,s=fn(o,n);return new e(Object.assign(t,{cell:s}))}};Bn.className="RNN";Q.registerClass(Bn);var Kl=class extends ze{},Nm=class extends Kl{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,Zt(this.units,"units"),this.activation=js(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=mt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=mt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=mt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=_t(e.kernelRegularizer),this.recurrentRegularizer=_t(e.recurrentRegularizer),this.biasRegularizer=_t(e.biasRegularizer),this.kernelConstraint=Bt(e.kernelConstraint),this.recurrentConstraint=Bt(e.recurrentConstraint),this.biasConstraint=Bt(e.biasConstraint),this.dropout=xc([1,Vs([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=xc([1,Vs([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Ye(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 B(()=>{if(e=e,e.length!==2)throw new z(`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=Qa({ones:()=>ur(e),rate:this.dropout,training:o})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Qa({ones:()=>ur(n),rate:this.recurrentDropout,training:o}));let s,a=this.dropoutMask,i=this.recurrentDropoutMask;a!=null?s=To(P(e,a),this.kernel.read()):s=To(e,this.kernel.read()),this.bias!=null&&(s=pn(s,this.bias.read())),i!=null&&(n=P(n,i));let l=J(s,To(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:Ws(this.activation),useBias:this.useBias,kernelInitializer:It(this.kernelInitializer),recurrentInitializer:It(this.recurrentInitializer),biasInitializer:It(this.biasInitializer),kernelRegularizer:at(this.kernelRegularizer),recurrentRegularizer:at(this.recurrentRegularizer),biasRegularizer:at(this.biasRegularizer),activityRegularizer:at(this.activityRegularizer),kernelConstraint:zt(this.kernelConstraint),recurrentConstraint:zt(this.recurrentConstraint),biasConstraint:zt(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign({},e,t)}};Nm.className="SimpleRNNCell";Q.registerClass(Nm);var ih=class extends Bn{constructor(e){e.cell=new Nm(e),super(e)}call(e,t){return B(()=>{this.cell.dropoutMask!=null&&(De(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(De(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)}};ih.className="SimpleRNN";Q.registerClass(ih);var Tm=class extends Kl{constructor(e){super(e);if(this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new z("GRUCell does not support reset_after parameter set to true.");this.units=e.units,Zt(this.units,"units"),this.activation=js(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=js(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=mt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=mt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=mt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=_t(e.kernelRegularizer),this.recurrentRegularizer=_t(e.recurrentRegularizer),this.biasRegularizer=_t(e.biasRegularizer),this.kernelConstraint=Bt(e.kernelConstraint),this.recurrentConstraint=Bt(e.recurrentConstraint),this.biasConstraint=Bt(e.biasConstraint),this.dropout=xc([1,Vs([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=xc([1,Vs([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Ye(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 B(()=>{if(e=e,e.length!==2)throw new z(`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=Qa({ones:()=>ur(e),rate:this.dropout,training:n,count:3})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Qa({ones:()=>ur(o),rate:this.recurrentDropout,training:n,count:3}));let s=this.dropoutMask,a=this.recurrentDropoutMask,i,l,u;0<this.dropout&&this.dropout<1&&(e=P(e,s[0]));let c=To(e,this.kernel.read());this.useBias&&(c=pn(c,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(o=P(o,a[0]));let p=this.recurrentKernel.read(),[m,f]=sr(p,[2*this.units,this.units],p.rank-1),d=To(o,m),[h,g,x]=sr(c,3,c.rank-1),[b,w]=sr(d,2,d.rank-1);i=this.recurrentActivation.apply(J(h,b)),l=this.recurrentActivation.apply(J(g,w));let _=To(P(l,o),f);u=this.activation.apply(J(x,_));let C=J(P(i,o),P(J(1,Ke(i)),u));return[C,C]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Ws(this.activation),recurrentActivation:Ws(this.recurrentActivation),useBias:this.useBias,kernelInitializer:It(this.kernelInitializer),recurrentInitializer:It(this.recurrentInitializer),biasInitializer:It(this.biasInitializer),kernelRegularizer:at(this.kernelRegularizer),recurrentRegularizer:at(this.recurrentRegularizer),biasRegularizer:at(this.biasRegularizer),activityRegularizer:at(this.activityRegularizer),kernelConstraint:zt(this.kernelConstraint),recurrentConstraint:zt(this.recurrentConstraint),biasConstraint:zt(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign({},e,t)}};Tm.className="GRUCell";Q.registerClass(Tm);var ah=class extends Bn{constructor(e){e.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Tm(e),super(e)}call(e,t){return B(()=>{this.cell.dropoutMask!=null&&(De(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(De(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)}};ah.className="GRU";Q.registerClass(ah);var Xl=class extends Kl{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,Zt(this.units,"units"),this.activation=js(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=js(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=mt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=mt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=mt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=_t(e.kernelRegularizer),this.recurrentRegularizer=_t(e.recurrentRegularizer),this.biasRegularizer=_t(e.biasRegularizer),this.kernelConstraint=Bt(e.kernelConstraint),this.recurrentConstraint=Bt(e.recurrentConstraint),this.biasConstraint=Bt(e.biasConstraint),this.dropout=xc([1,Vs([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=xc([1,Vs([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;e=Ye(e);let n=e[e.length-1];this.kernel=this.addWeight("kernel",[n,this.units*4],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*4],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint);let o;if(this.useBias){if(this.unitForgetBias){let s=this.biasInitializer,a=this.units;o=new(t=class extends In{apply(l,u){let c=s.apply([a]),p=new bc().apply([a]),m=s.apply([a*2]);return BC(BC(c,p),m)}},t.className="CustomInit",t)}else o=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,o,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return B(()=>{let n=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new z(`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=Qa({ones:()=>ur(e),rate:this.dropout,training:n,count:4})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Qa({ones:()=>ur(o),rate:this.recurrentDropout,training:n,count:4}));let a=this.dropoutMask,i=this.recurrentDropoutMask,l,u,c,p;0<this.dropout&&this.dropout<1&&(e=P(e,a[0]));let m=To(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(o=P(o,i[0])),m=J(m,To(o,this.recurrentKernel.read())),this.useBias&&(m=pn(m,this.bias.read()));let[f,d,h,g]=sr(m,4,m.rank-1);l=this.recurrentActivation.apply(f),u=this.recurrentActivation.apply(d),c=J(P(u,s),P(l,this.activation.apply(h))),p=this.recurrentActivation.apply(g);let x=P(p,this.activation.apply(c));return[x,x,c]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Ws(this.activation),recurrentActivation:Ws(this.recurrentActivation),useBias:this.useBias,kernelInitializer:It(this.kernelInitializer),recurrentInitializer:It(this.recurrentInitializer),biasInitializer:It(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:at(this.kernelRegularizer),recurrentRegularizer:at(this.recurrentRegularizer),biasRegularizer:at(this.biasRegularizer),activityRegularizer:at(this.activityRegularizer),kernelConstraint:zt(this.kernelConstraint),recurrentConstraint:zt(this.recurrentConstraint),biasConstraint:zt(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign({},e,t)}};Xl.className="LSTMCell";Q.registerClass(Xl);var lh=class extends Bn{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 Xl(e),super(e)}call(e,t){return B(()=>{this.cell.dropoutMask!=null&&(De(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(De(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)}};lh.className="LSTM";Q.registerClass(lh);var Em=class extends Kl{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 B(()=>{e=e;let n=e.slice(1),o=[];for(let i of this.cells.slice().reverse())Array.isArray(i.stateSize)?o.push(n.splice(0,i.stateSize.length)):o.push(n.splice(0,1));o.reverse();let s=[],a;for(let i=0;i<this.cells.length;++i){let l=this.cells[i];n=o[i],i===0?a=[e[0]].concat(n):a=[a[0]].concat(n),a=l.call(a,t),s.push(a.slice(1))}n=[];for(let i of s.slice().reverse())n.push(...i);return[a[0]].concat(n)})}build(e){Sy(e)&&(e=e[0]),e=e;let t;this.cells.forEach((n,o)=>{Bs(`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 Object.assign({},e,o)}static fromConfig(e,t,n={}){let o=[];for(let s of t.cells)o.push(fn(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 Md(e)}setWeights(e){let t=[];for(let n of this.cells){let o=n.weights.length,s=e.splice(o);for(let a=0;a<n.weights.length;++a)t.push([n.weights[a],s[a]])}_m(t)}};Em.className="StackedRNNCells";Q.registerClass(Em);function Qa(r){let{ones:e,rate:t,training:n=!1,count:o=1}=r,s=()=>vy(e(),t),a=()=>zl(s,e,n);return!o||o<=1?Rt(a().clone()):Array(o).fill(void 0).map(a).map(l=>Rt(l.clone()))}var xne=function(r,e){var t={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&e.indexOf(n)<0&&(t[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,n=Object.getOwnPropertySymbols(r);o<n.length;o++)e.indexOf(n[o])<0&&Object.prototype.propertyIsEnumerable.call(r,n[o])&&(t[n[o]]=r[n[o]]);return t};var _I=class extends Bn{constructor(e){if(e.unroll)throw new Te("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Te("It is not possible at the moment to stack convolutional cells.");super(e);this.inputSpec=[new St({ndim:5})]}call(e,t){return B(()=>{if(this.cell.dropoutMask!=null&&(De(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(De(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new z("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 B(()=>{let{stateSize:t}=this.cell,n=e.shape,o=this.computeSingleOutputShape(n),s=[o[0],...o.slice(2)],a=gt(s);return Array.isArray(t)?Array(t.length).fill(a):[a]})}resetStates(e,t=!1){B(()=>{if(!this.stateful)throw new zn("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 z("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(()=>gt(s)):this.states_=[gt(s)];else if(e==null)De(this.states_),this.keptStates!=null&&(De(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>gt(s)):this.states_[0]=gt(s);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new z(`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()):De(this.states_);for(let i=0;i<this.states_.length;++i){let l=e[i],u=s;if(!y.arraysEqual(l.shape,u))throw new z(`State ${i} is incompatible with layer ${this.name}: expected shape=${u}, received shape=${l.shape}`);this.states_[i]=l}}this.states_=this.states_.map(i=>Rt(i.clone()))})}computeSingleOutputShape(e){let{dataFormat:t,filters:n,kernelSize:o,padding:s,strides:a,dilationRate:i}=this.cell,l=t==="channelsFirst",u=e[l?3:2],c=e[l?4:3],p=Nn(u,o[0],s,a[0],i[0]),m=Nn(c,o[1],s,a[1],i[1]);return[...e.slice(0,2),...l?[n,p,m]:[p,m,n]]}};_I.className="ConvRNN2D";var Am=class extends Xl{constructor(e){let{filters:t,kernelSize:n,strides:o,padding:s,dataFormat:a,dilationRate:i}=e;super(Object.assign({},e,{units:t}));this.filters=t,Zt(this.filters,"filters"),this.kernelSize=Ul(n,2,"kernelSize"),this.kernelSize.forEach(l=>Zt(l,"kernelSize")),this.strides=Ul(o||1,2,"strides"),this.strides.forEach(l=>Zt(l,"strides")),this.padding=s||"valid",cn(this.padding),this.dataFormat=a||"channelsLast",Pt(this.dataFormat),this.dilationRate=Ul(i||1,2,"dilationRate"),this.dilationRate.forEach(l=>Zt(l,"dilationRate"))}build(e){var t;e=Ye(e);let n=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[n]==null)throw new z(`The channel dimension of the input should be defined. Found ${e[n]}`);let o=e[n],s=4,a=this.kernelSize.concat([o,this.filters*s]);this.kernel=this.addWeight("kernel",a,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);let i=this.kernelSize.concat([this.filters,this.filters*s]);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,c=this.filters;l=new(t=class extends In{apply(m,f){let d=u.apply([c]),h=or([c]),g=u.apply([c*2]);return pm([d,h,g])}},t.className="CustomInit",t)}else l=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*s],null,l,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return B(()=>{if(e.length!==3)throw new z(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training||!1,o=e[0],s=e[1],a=e[2],i=4;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Qa({ones:()=>ur(o),rate:this.dropout,training:n,count:i}));let l=this.dropoutMask,u=(ee,ie,me)=>!ie||!ie[me]?ee:P(ie[me],ee),c=u(o,l,0),p=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=Qa({ones:()=>ur(s),rate:this.recurrentDropout,training:n,count:i}));let d=this.recurrentDropoutMask,h=u(s,d,0),g=u(s,d,1),x=u(s,d,2),b=u(s,d,3),w=3,[_,C,A,D]=sr(this.kernel.read(),i,w),[$,R,M,G]=this.useBias?sr(this.bias.read(),i):[null,null,null,null];c=this.inputConv(c,_,$,this.padding),p=this.inputConv(p,C,R,this.padding),m=this.inputConv(m,A,M,this.padding),f=this.inputConv(f,D,G,this.padding);let[j,U,q,H]=sr(this.recurrentKernel.read(),i,w);h=this.recurrentConv(h,j),g=this.recurrentConv(g,U),x=this.recurrentConv(x,q),b=this.recurrentConv(b,H);let X=this.recurrentActivation.apply(J(c,h)),ne=this.recurrentActivation.apply(J(p,g)),Y=J(P(ne,a),P(X,this.activation.apply(J(m,x)))),re=P(this.recurrentActivation.apply(J(f,b)),this.activation.apply(Y));return[re,re,Y]})}getConfig(){let e=super.getConfig(),{units:t}=e,n=xne(e,["units"]),o={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign({},n,o)}inputConv(e,t,n,o){let s=on(e,t,this.strides,o||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return n?pn(s,n,this.dataFormat):s}recurrentConv(e,t){return on(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};Am.className="ConvLSTM2DCell";Q.registerClass(Am);var uh=class extends _I{constructor(e){let t=new Am(e);super(Object.assign({},e,{cell:t}))}static fromConfig(e,t){return new e(t)}};uh.className="ConvLSTM2D";Q.registerClass(uh);var Dm=class extends ze{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 B(()=>{this.invokeCallHook(e,t);let n=Oe(e);if(0<this.rate&&this.rate<1){let o=t.training==null?!1:t.training,s=this.getNoiseShape(n);return zl(()=>vy(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()}};Dm.className="Dropout";Q.registerClass(Dm);var ch=class extends Dm{constructor(e){super(e);this.inputSpec=[{ndim:3}]}getNoiseShape(e){let t=e.shape;return[t[0],1,t[2]]}};ch.className="SpatialDropout1D";Q.registerClass(ch);var ph=class extends ze{constructor(e){super(e);if(this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.batchInputShape==null&&e.inputShape==null&&e.inputDim!=null){let t=null;e.batchSize!=null&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,Zt(this.units,"units"),this.activation=js(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=mt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=mt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Bt(e.kernelConstraint),this.biasConstraint=Bt(e.biasConstraint),this.kernelRegularizer=_t(e.kernelRegularizer),this.biasRegularizer=_t(e.biasRegularizer),this.activityRegularizer=_t(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=Ye(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=Ye(e);let t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return B(()=>{this.invokeCallHook(e,t);let n=Oe(e),o=yy(this.activation.getClassName()),s;return o!=null?s=To(n,this.kernel.read(),o,this.bias?this.bias.read():null):(s=To(n,this.kernel.read()),this.bias!=null&&(s=pn(s,this.bias.read())),this.activation!=null&&(s=this.activation.apply(s))),s})}getConfig(){let e={units:this.units,activation:Ws(this.activation),useBias:this.useBias,kernelInitializer:It(this.kernelInitializer),biasInitializer:It(this.biasInitializer),kernelRegularizer:at(this.kernelRegularizer),biasRegularizer:at(this.biasRegularizer),activityRegularizer:at(this.activityRegularizer),kernelConstraint:zt(this.kernelConstraint),biasConstraint:zt(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}};ph.className="Dense";Q.registerClass(ph);var mh=class extends ze{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=Ye(e);for(let t of e.slice(1))if(t==null)throw new z(`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],No(e,1)]}call(e,t){return B(()=>{this.invokeCallHook(e,t);let n=Oe(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 zB(n)})}getConfig(){let e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);let t=super.getConfig();return Object.assign(e,t),e}};mh.className="Flatten";Q.registerClass(mh);var fh=class extends ze{constructor(e){super(e);this.supportsMasking=!0,this.activation=js(e.activation)}call(e,t){return B(()=>{this.invokeCallHook(e,t);let n=Oe(e);return this.activation.apply(n)})}getConfig(){let e={activation:Ws(this.activation)},t=super.getConfig();return Object.assign(e,t),e}};fh.className="Activation";Q.registerClass(fh);var dh=class extends ze{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 B(()=>(e=Oe(e),MB(e,this.n)))}getConfig(){let e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}};dh.className="RepeatVector";Q.registerClass(dh);var hh=class extends ze{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,a=null;for(let l=0;l<o.length;++l){let u=o[l];if(this.isUnknown(u))if(a===null)a=l;else throw new z("Can only specifiy one unknown dimension.");else s*=u}let i=No(e);if(a!==null){if(s===0||i%s!=0)throw new z(n);o[a]=i/s}else if(i!==s)throw new z(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 B(()=>{this.invokeCallHook(e,t);let n=Oe(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}};hh.className="Reshape";Q.registerClass(hh);var gh=class extends ze{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=Kr(1,e.dims.length+1);if(!y.arraysEqual(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new St({ndim:this.dims.length+1})]}computeOutputShape(e){e=Ye(e);let t=e.slice();return this.dims.forEach((n,o)=>{t[o+1]=e[n]}),t}call(e,t){return qe(Oe(e),this.dimsIncludingBatch)}getConfig(){let e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}};gh.className="Permute";Q.registerClass(gh);var xh=class extends ze{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=Oe(e),o=-1;return Nl(fo(n,this.maskValue),o)}call(e,t){return B(()=>{this.invokeCallHook(e,t);let n=Oe(e),o=-1,s=!0,a=Nl(fo(n,this.maskValue),o,s);return n.mul(a.asType(n.dtype))})}};xh.className="Masking";Q.registerClass(xh);var yh=class extends ze{constructor(e){super(e);if(this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",e.batchInputShape==null&&e.inputShape==null){let t=null;e.batchSize!=null&&(t=e.batchSize),e.inputLength==null?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(wt(e.inputLength))}this.inputDim=e.inputDim,Zt(this.inputDim,"inputDim"),this.outputDim=e.outputDim,Zt(this.outputDim,"outputDim"),this.embeddingsInitializer=mt(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=_t(e.embeddingsRegularizer),this.activityRegularizer=_t(e.activityRegularizer),this.embeddingsConstraint=Bt(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 B(()=>this.maskZero?(e=Oe(e),fo(e,Se(e))):null)}computeOutputShape(e){if(e=Ye(e),this.inputLength==null)return[...e,this.outputDim];let t=wt(this.inputLength);if(t.length!==e.length-1)throw new z(`"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],a=e[o+1];if(s!=null&&a!=null&&s!==a)throw new z(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);s==null&&(t[n]=a),n++}}return[e[0],...t,this.outputDim]}call(e,t){return B(()=>{this.invokeCallHook(e,t);let n=Oe(e);return n.dtype!=="int32"&&(n=Xa(n,"int32")),ky(this.embeddings.read(),n.as1D()).reshape(Ye(this.computeOutputShape(n.shape)))})}getConfig(){let e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:It(this.embeddingsInitializer),embeddingsRegularizer:at(this.embeddingsRegularizer),activityRegularizer:at(this.activityRegularizer),embeddingsConstraint:zt(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}};yh.className="Embedding";Q.registerClass(yh);var Yl=class extends ze{constructor(e){super(e||{});this.supportsMasking=!0}mergeFunction(e){throw new Te}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],a=t[o];if(s==null||a==null||s<0||a<0)n.push(null);else if(s===1)n.push(a);else if(a===1)n.push(s);else{if(s!==a)throw new z("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=[Ye(e)]),e=e,e.length<2)throw new z(`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=So(t),t.length>1)throw new z(`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 a=e[s]==null?null:e[s].slice(1);n=this.computeElementwiseOpOutputShape(n,a)}let o=e.map(s=>s.length);e.indexOf(null)===-1&&So(o).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return B(()=>{if(e=e,this.reshapeRequired){let n=[],o=e.map(s=>s.rank);if(o.indexOf(null)===-1){let s=Vs(o);for(let a of e){let i=a.rank;for(let l=0;l<s-i;++l)a=Ya(a,1);n.push(a)}return this.mergeFunction(n)}else{let s=!1;for(let l of e){let u=l.rank;if(u==null){let c=l.shape,p=c[0],m=c.slice(1).concat([p]),f=l.reshape([p].concat(No(c.slice(1))));f=qe(f,[1,0]),f=f.reshape(m),n.push(f),s=!0}else if(u>1){let c=Kr(1,u).concat([0]);n.push(qe(l,c)),s=!0}else n.push(l)}let a=this.mergeFunction(n),i=a.rank;if(s){if(i==null){let l=a.shape,u=l.length,c=l[u-1],p=[c].concat(l.slice(0,l.length-1));a=qe(a.reshape([-1,c]),[1,0]).reshape(p)}else if(i>1){let l=[i-1].concat(Kr(0,i-1));a=qe(a,l)}}return a}}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=So(n),n.length===1?t=n.concat(t):t=[null].concat(t),t}computeMask(e,t){return B(()=>{if(t==null)return null;if(!Array.isArray(t))throw new z("`mask` should be an Array");if(!Array.isArray(e))throw new z("`inputs` should be an Array");if(t.length!==e.length)throw new z(`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:dr(o,0));let n=t[0];for(let o=1;o<t.length-1;++o)n=_r(n,t[o]);return n})}},bh=class extends Yl{constructor(e){super(e)}mergeFunction(e){return B(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=J(t,e[n]);return t})}};bh.className="Add";Q.registerClass(bh);var wh=class extends Yl{constructor(e){super(e)}mergeFunction(e){return B(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=P(t,e[n]);return t})}};wh.className="Multiply";Q.registerClass(wh);var _h=class extends Yl{constructor(e){super(e)}mergeFunction(e){return B(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=J(t,e[n]);return P(1/e.length,t)})}};_h.className="Average";Q.registerClass(_h);var kh=class extends Yl{constructor(e){super(e)}mergeFunction(e){return B(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=an(t,e[n]);return t})}};kh.className="Maximum";Q.registerClass(kh);var vh=class extends Yl{constructor(e){super(e)}mergeFunction(e){return B(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=Rs(t,e[n]);return t})}};vh.className="Minimum";Q.registerClass(vh);var Ch=class extends Yl{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 z("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 a=!1;for(let i of n)if(y.arraysEqual(i,s)){a=!0;break}a||n.push(s)}if(n.length>1)throw new z("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return B(()=>pm(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new z("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 z("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new z("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new z(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return B(()=>{let n=!0;if(t.forEach(a=>{if(a!=null){n=!1;return}}),n)return null;let o=[];for(let a=0;a<e.length;++a)t[a]==null?o.push(ur(e[a]).asType("bool")):t[a].rank<e[a].rank?o.push(dr(t[a],-1)):o.push(t[a]);let s=et(o,this.axis);return bu(s,-1,!1)})}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};Ch.className="Concatenate";Q.registerClass(Ch);function Ih(r,e){for(;r<0;)r+=e;return r}function yne(r,e,t){if(r.shape.length>3||e.shape.length>3)throw new Te("batchDot is not implemented for tensors of 4D or higher rank yet");if(y.assert(r.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${r.shape.length}`),y.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 Te("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 B(()=>{let a;if(n>o){a=n-o;let l=[];for(let u=0;u<a;++u)l.push(1);e=e.reshape(e.shape.concat(l))}else if(o>n){a=o-n;let l=[];for(let u=0;u<a;++u)l.push(1);r=r.reshape(r.shape.concat(l))}else a=0;let i;if(r.shape.length===2&&e.shape.length===2)s[0]===s[1]?i=r.mul(e).sum(s[0]):i=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;i=r.matMul(e,l,u)}if(a>0){let l;n>o?l=n+o-3:l=n-1;let u=[];for(let c=l;c<l+a;++c)u.push(c);i=i.squeeze(u)}return i.shape.length===1&&(i=i.expandDims(1)),i})}var Sh=class extends Yl{constructor(e){super(e);this.axes=e.axes,this.normalize=e.normalize==null?!1:e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){y.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 Te("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 z(`Dimension incompatibility: ${t[o[0]]} !== ${n[o[1]]}`)}mergeFunction(e){if(e.length!==2)throw new z(`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,a)=>Ih(s,e[a].shape.length)):o=[Ih(this.axes,t.shape.length),Ih(this.axes,n.shape.length)],this.normalize&&(t=Ld(t,o[0]),n=Ld(n,o[1])),yne(t,n,o)}interpretAxes(e,t){let n;return Array.isArray(this.axes)?n=this.axes:n=[Ih(this.axes,e.length),Ih(this.axes,t.length)],n}computeOutputShape(e){y.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 Te("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}};Sh.className="Dot";Q.registerClass(Sh);var Nh=class extends ze{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 B(()=>{this.invokeCallHook(e,t);let n=Oe(e);return zl(()=>mm(n.shape,0,this.stddev).add(n),()=>n,t.training||!1)})}};Nh.className="GaussianNoise";Q.registerClass(Nh);var Th=class extends ze{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 B(()=>{this.invokeCallHook(e,t);let n=Oe(e);return this.rate>0&&this.rate<1?zl(()=>{let s=Math.sqrt(this.rate/(1-this.rate));return n.mul(mm(n.shape,1,s))},()=>n,t.training||!1):n})}};Th.className="GaussianDropout";Q.registerClass(Th);var Eh=class extends ze{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Oe(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 B(()=>{if(this.rate<1&&this.rate>0){let n=this._getNoiseShape(e);return zl(()=>{let s=Oe(e),a=1.6732632423543772,i=1.0507009873554805,l=-a*i,u=_n(Fs(n),this.rate);u=Xa(u,"float32");let c=((1-this.rate)*(1+this.rate*l**2))**-.5,p=-c*l*this.rate;return s.mul(u).add(u.add(-1).mul(l)).mul(c).add(p)},()=>Oe(e),t.training||!1)}return e})}};Eh.className="AlphaDropout";Q.registerClass(Eh);function Ah(r,e,t,n,o,s=.001){let a;if(r.rank===2)a=A_(r,e,t,n,o,s);else if(r.rank===3)a=D_(r,e,t,n,o,s);else if(r.rank===4)a=$_(r,e,t,n,o,s);else throw new Te(`batchNormalization is not implemented for array of rank ${r.rank} yet`);return a}function bne(r,e,t,n,o=.001){return B(()=>{let s=Mp(r,n),a=s.mean,i=s.variance;return[Ah(r,a,i,t,e,o),a,i]})}function wne(r,e,t,n,o=.001){return B(()=>{let s=Mp(r,n),a=s.mean,i=s.variance,l=[];for(let d of Kr(0,r.rank))n.indexOf(d)!==-1?l.push(1):l.push(r.shape[d]);let u=a.reshape(l),c=i.reshape(l),p=e==null?null:e.reshape(l),m=t==null?null:t.reshape(l);return[Ah(r,u,c,m,p,o),a,i]})}function _ne(r,e,t,n,o=.001){return y.arraysEqual(n.slice().sort(),Kr(0,r.rank-1))?bne(r,e,t,n,o):wne(r,e,t,n,o)}var Dh=class extends ze{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=mt(e.betaInitializer||"zeros"),this.gammaInitializer=mt(e.gammaInitializer||"ones"),this.movingMeanInitializer=mt(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=mt(e.movingVarianceInitializer||"ones"),this.betaConstraint=Bt(e.betaConstraint),this.gammaConstraint=Bt(e.gammaConstraint),this.betaRegularizer=_t(e.betaRegularizer),this.gammaRegularizer=_t(e.gammaRegularizer)}build(e){e=Ye(e);let t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(n==null)throw new z(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new St({ndim:e.length,axes:{[t]: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 B(()=>{let n=t.training==null?!1:t.training,o=Oe(e),s=o.shape,a=s.length,i=Kr(0,a),l=this.axis>=0?this.axis:this.axis+a;i.splice(l,1);let u=vo(1,a);u[l]=s[l];let c=i.slice();c.sort();let p=!y.arraysEqual(c,Kr(0,a).slice(0,a-1)),m=()=>{if(p){let b=this.movingMean.read().reshape(u),w=this.movingVariance.read().reshape(u),_=this.center?this.beta.read().reshape(u):null,C=this.scale?this.gamma.read().reshape(u):null;return Ah(o,b,w,_,C,this.epsilon)}else return Ah(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]=_ne(o,this.gamma.read(),this.beta.read(),i,this.epsilon),g=(b,w,_)=>{B(()=>{let C=1-_,A=b.read(),D=A.sub(w).mul(C);b.write(A.sub(D))})};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:It(this.betaInitializer),gammaInitializer:It(this.gammaInitializer),movingMeanInitializer:It(this.movingMeanInitializer),movingVarianceInitializer:It(this.movingVarianceInitializer),betaRegularizer:at(this.betaRegularizer),gammaRegularizer:at(this.gammaRegularizer),betaConstraint:zt(this.betaConstraint),gammaConstraint:zt(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}};Dh.className="BatchNormalization";Q.registerClass(Dh);var $h=class extends ze{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=mt(e.betaInitializer||"zeros"),this.gammaInitializer=mt(e.gammaInitializer||"ones"),this.betaRegularizer=_t(e.betaRegularizer),this.gammaRegularizer=_t(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=Ye(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!==So(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=Oe(e),o=n.shape,s=o.length;return B(()=>{let a=!0,{mean:i,variance:l}=Mp(n,this.axis,a),u=vo(1,s);for(let h of this.axis)u[h]=o[h];let c=h=>h!=null&&h.shape.length!==s&&this.axis!==[s-1]?h.reshape(u):h,p=c(this.gamma.read()),m=c(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 i=i.tile(f),l=l.tile(f),p=p.tile(d),m=m.tile(d),Ah(n,i,l,m,p,this.epsilon)})}getConfig(){let e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:It(this.betaInitializer),gammaInitializer:It(this.gammaInitializer),betaRegularizer:at(this.betaRegularizer),gammaRegularizer:at(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}};$h.className="LayerNormalization";Q.registerClass($h);function kne(r,e,t){return B(()=>{if(r.rank!==4)throw new z(`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 z("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(t==null&&(t=un()),t!=="channelsLast"&&t!=="channelsFirst")throw new z(`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]],Wr(r,n)})}var Rh=class extends ze{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?un():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 z(`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 z(`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 z(`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 St({ndim:4})]}computeOutputShape(e){e=Ye(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 B(()=>kne(Oe(e),this.padding,this.dataFormat))}getConfig(){let e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};Rh.className="ZeroPadding2D";Q.registerClass(Rh);function Wy(r,e,t,n,o,s){return B(()=>{Pt(o),LC(s),cn(n),t==null&&(t=[1,1]),n==null&&(n="valid"),o==null&&(o=un()),s==null&&(s="max"),r=Qd(r,o);let a,i=n==="same"?"same":"valid";return s==="max"?a=$a(r,e,t,i):a=Sa(r,e,t,i),o==="channelsFirst"&&(a=qe(a,[0,3,1,2])),a})}function vV(r,e,t,n,o,s){return B(()=>{Pt(o),LC(s),cn(n),t==null&&(t=[1,1,1]),n==null&&(n="valid"),o==null&&(o=un()),s==null&&(s="max"),r=xI(r,o);let a,i=n==="same"?"same":"valid";return s==="max"?a=Pf(r,e,t,i):a=vf(r,e,t,i),o==="channelsFirst"&&(a=qe(a,[0,4,1,2,3])),a})}var kI=class extends ze{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 z(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(Zt(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 z(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);Zt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,cn(this.padding),this.inputSpec=[new St({ndim:3})]}computeOutputShape(e){e=Ye(e);let t=Nn(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return B(()=>{this.invokeCallHook(e,t),e=Ya(Oe(e),2);let n=this.poolingFunction(Oe(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Pn(n,[2])})}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}},Fh=class extends kI{constructor(e){super(e)}poolingFunction(e,t,n,o,s){return Pt(s),cn(o),Wy(e,t,n,o,s,"max")}};Fh.className="MaxPooling1D";Q.registerClass(Fh);var Oh=class extends kI{constructor(e){super(e)}poolingFunction(e,t,n,o,s){return Pt(s),cn(o),Wy(e,t,n,o,s,"avg")}};Oh.className="AveragePooling1D";Q.registerClass(Oh);var vI=class extends ze{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 z(`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];Zt(this.poolSize,"poolSize"),Zt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Pt(this.dataFormat),cn(this.padding),this.inputSpec=[new St({ndim:4})]}computeOutputShape(e){e=Ye(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=Nn(t,this.poolSize[0],this.padding,this.strides[0]),n=Nn(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 B(()=>(this.invokeCallHook(e,t),this.poolingFunction(Oe(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}},Ph=class extends vI{constructor(e){super(e)}poolingFunction(e,t,n,o,s){return Pt(s),cn(o),Wy(e,t,n,o,s,"max")}};Ph.className="MaxPooling2D";Q.registerClass(Ph);var Mh=class extends vI{constructor(e){super(e)}poolingFunction(e,t,n,o,s){return Pt(s),cn(o),Wy(e,t,n,o,s,"avg")}};Mh.className="AveragePooling2D";Q.registerClass(Mh);var CI=class extends ze{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 z(`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];Zt(this.poolSize,"poolSize"),Zt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Pt(this.dataFormat),cn(this.padding),this.inputSpec=[new St({ndim:5})]}computeOutputShape(e){e=Ye(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=Nn(t,this.poolSize[0],this.padding,this.strides[0]),n=Nn(n,this.poolSize[1],this.padding,this.strides[1]),o=Nn(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 B(()=>(this.invokeCallHook(e,t),this.poolingFunction(Oe(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}},Lh=class extends CI{constructor(e){super(e)}poolingFunction(e,t,n,o,s){return Pt(s),cn(o),vV(e,t,n,o,s,"max")}};Lh.className="MaxPooling3D";Q.registerClass(Lh);var zh=class extends CI{constructor(e){super(e)}poolingFunction(e,t,n,o,s){return Pt(s),cn(o),vV(e,t,n,o,s,"avg")}};zh.className="AveragePooling3D";Q.registerClass(zh);var II=class extends ze{constructor(e){super(e);this.inputSpec=[new St({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Te}},Bh=class extends II{constructor(e){super(e||{})}call(e,t){return B(()=>{let n=Oe(e);return ht(n,1)})}};Bh.className="GlobalAveragePooling1D";Q.registerClass(Bh);var Vh=class extends II{constructor(e){super(e||{})}call(e,t){return B(()=>{let n=Oe(e);return Er(n,1)})}};Vh.className="GlobalMaxPooling1D";Q.registerClass(Vh);var SI=class extends ze{constructor(e){super(e);this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Pt(this.dataFormat),this.inputSpec=[new St({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Te}getConfig(){let e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},Gh=class extends SI{call(e,t){return B(()=>{let n=Oe(e);return this.dataFormat==="channelsLast"?ht(n,[1,2]):ht(n,[2,3])})}};Gh.className="GlobalAveragePooling2D";Q.registerClass(Gh);var Wh=class extends SI{call(e,t){return B(()=>{let n=Oe(e);return this.dataFormat==="channelsLast"?Er(n,[1,2]):Er(n,[2,3])})}};Wh.className="GlobalMaxPooling2D";Q.registerClass(Wh);var NI=class extends ze{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=fn(o,n);delete t.layer;let a={layer:s};return Object.assign(a,t),new e(a)}},jh=class extends NI{constructor(e){super(e);this.supportsMasking=!0}build(e){if(e=Ye(e),e.length<3)throw new z(`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=Ye(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 B(()=>(e=Oe(e),wI((a,i)=>[Oe(this.layer.call(a,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};jh.className="TimeDistributed";Q.registerClass(jh);function vne(r){vi($B,"BidirectionalMergeMode",r)}var Cne="concat",Uh=class extends NI{constructor(e){super(e);let t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=fn(n),t.goBackwards=t.goBackwards!==!0;let o={};if(o.className=e.layer.getClassName(),o.config=t,this.backwardLayer=fn(o),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?Cne:e.mergeMode,vne(this.mergeMode),e.weights)throw new Te("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()):vr(o)}apply(e,t){let n=t==null?null:t.initialState,o=t==null?null:t.constants;t==null&&(t={});let s=bI(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 a=[],i=[];if(n!=null){let u=n.length;if(u%2>0)throw new z("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,a.push(...n);let c=n.map(p=>new St({shape:p.shape}));this.forwardLayer.stateSpec=c.slice(0,u/2),this.backwardLayer.stateSpec=c.slice(u/2),i.push(...c)}if(o!=null)throw new Te("Support for constants in Bidirectional layers is not implemented yet.");let l=a[0]instanceof mn;for(let u of a)if(u instanceof mn!==l)throw new z("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(a),c=this.inputSpec.concat(i),p=this.inputSpec;this.inputSpec=c;let m=super.apply(u,t);return this.inputSpec=p,m}else return super.apply(e,t)}call(e,t){return B(()=>{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 a;this.returnState&&(Array.isArray(o)&&(a=o.slice(1).concat(s.slice(1))),o=o[0],s=s[0]),this.returnSequences&&(s=Jt(s,1));let i;return this.mergeMode==="concat"?i=pm([o,s]):this.mergeMode==="sum"?i=J(o,s):this.mergeMode==="ave"?i=P(.5,J(o,s)):this.mergeMode==="mul"?i=P(o,s):this.mergeMode==null&&(i=[o,s]),this.returnState?this.mergeMode==null?i.concat(a):[i].concat(a):i})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){Bs(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),Bs(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(a=>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=fn(t.layer);if(delete t.layer,t.numConstants!=null)throw new Te("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");let o=t;return o.layer=n,new e(o)}};Uh.className="Bidirectional";Q.registerClass(Uh);function Ine(r){return new Ci(r)}function Sne(r){return new Yd(r)}function Nne(r){return new Hd(r)}function Tne(r){return new Kd(r)}function Ene(r){return new Xd(r)}function Ane(r){return new Jd(r)}function Dne(r){return new Zd(r)}function $ne(r){return new Ic(r)}function Rne(r){return new ql(r)}function Fne(r){return new eh(r)}function One(r){return new Hl(r)}function Pne(r){return new th(r)}function Mne(r){return new rh(r)}function Lne(r){return new nh(r)}function zne(r){return new oh(r)}function Bne(r){return new sh(r)}function Vne(r){return new fh(r)}function Gne(r){return new ph(r)}function Wne(r){return new Dm(r)}function jne(r){return new ch(r)}function Une(r){return new mh(r)}function qne(r){return new dh(r)}function Hne(r){return new hh(r)}function Kne(r){return new gh(r)}function Xne(r){return new yh(r)}function Yne(r){return new bh(r)}function Zne(r){return new _h(r)}function Jne(r){return new Ch(r)}function Qne(r){return new kh(r)}function eoe(r){return new vh(r)}function toe(r){return new wh(r)}function roe(r){return new Sh(r)}function noe(r){return new Dh(r)}function ooe(r){return new $h(r)}function soe(r){return new Rh(r)}function TI(r){return new Oh(r)}function ioe(r){return TI(r)}function aoe(r){return TI(r)}function EI(r){return new Mh(r)}function loe(r){return EI(r)}function uoe(r){return EI(r)}function AI(r){return new zh(r)}function coe(r){return AI(r)}function poe(r){return AI(r)}function moe(r){return new Bh(r)}function foe(r){return new Gh(r)}function CV(r){return new Vh(r)}function IV(r){return new Wh(r)}function SV(r){return new Fh(r)}function NV(r){return new Ph(r)}function doe(r){return new Lh(r)}function hoe(r){return new ah(r)}function goe(r){return new Tm(r)}function xoe(r){return new lh(r)}function yoe(r){return new Xl(r)}function boe(r){return new ih(r)}function woe(r){return new Nm(r)}function _oe(r){return new uh(r)}function koe(r){return new Am(r)}function voe(r){return new Bn(r)}function Coe(r){return new Em(r)}function Ioe(r){return new Uh(r)}function Soe(r){return new jh(r)}var Noe=CV,Toe=IV,Eoe=SV,Aoe=NV;function Doe(r){return new Nh(r)}function $oe(r){return new Th(r)}function Roe(r){return new Eh(r)}function Foe(r){return new xh(r)}var EV={};je(EV,{MAPE:()=>Uoe,MSE:()=>Koe,binaryAccuracy:()=>Ooe,binaryCrossentropy:()=>Poe,categoricalAccuracy:()=>Loe,categoricalCrossentropy:()=>zoe,cosineProximity:()=>Goe,mape:()=>qoe,meanAbsoluteError:()=>Woe,meanAbsolutePercentageError:()=>joe,meanSquaredError:()=>Hoe,mse:()=>Xoe,precision:()=>Boe,recall:()=>Voe,sparseCategoricalAccuracy:()=>Moe});function Ooe(r,e){return Vd(r,e)}function Poe(r,e){return Ry(r,e)}function Moe(r,e){return Fy(r,e)}function Loe(r,e){return Gd(r,e)}function zoe(r,e){return Wd(r,e)}function Boe(r,e){return qC(r,e)}function Voe(r,e){return JB(r,e)}function Goe(r,e){return zd(r,e)}function Woe(r,e){return km(r,e)}function joe(r,e){return Wl(r,e)}function Uoe(r,e){return Wl(r,e)}function qoe(r,e){return Wl(r,e)}function Hoe(r,e){return Si(r,e)}function Koe(r,e){return Si(r,e)}function Xoe(r,e){return Si(r,e)}var AV={};je(AV,{modelFromJSON:()=>gV});var DV={};je(DV,{l1:()=>Zoe,l1l2:()=>Yoe,l2:()=>Joe});function Yoe(r){return new vc(r)}function Zoe(r){return yV(r)}function Joe(r){return bV(r)}var DI=class extends Gl{constructor(){super(...arguments);this.model=null}setModel(e){if(!(e instanceof Jn))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function jy(r,e){return r<e}function $V(r,e){return r>e}var $I=class extends DI{constructor(e){super();if(e==null&&(e={}),e.restoreBestWeights)throw new Te("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=jy:this.mode==="max"?this.monitorFunc=$V:this.monitor.indexOf("acc")!==-1?this.monitorFunc=$V:this.monitorFunc=jy,this.monitorFunc===jy&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===jy?Infinity:-Infinity}async onEpochEnd(e,t){await Ii(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 Qoe(r){return new $I(r)}var ese={earlyStopping:Qoe};var Eo;(function(r){r[r.DT_INVALID=0]="DT_INVALID",r[r.DT_FLOAT=1]="DT_FLOAT",r[r.DT_DOUBLE=2]="DT_DOUBLE",r[r.DT_INT32=3]="DT_INT32",r[r.DT_UINT8=4]="DT_UINT8",r[r.DT_INT16=5]="DT_INT16",r[r.DT_INT8=6]="DT_INT8",r[r.DT_STRING=7]="DT_STRING",r[r.DT_COMPLEX64=8]="DT_COMPLEX64",r[r.DT_INT64=9]="DT_INT64",r[r.DT_BOOL=10]="DT_BOOL",r[r.DT_QINT8=11]="DT_QINT8",r[r.DT_QUINT8=12]="DT_QUINT8",r[r.DT_QINT32=13]="DT_QINT32",r[r.DT_BFLOAT16=14]="DT_BFLOAT16",r[r.DT_FLOAT_REF=101]="DT_FLOAT_REF",r[r.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",r[r.DT_INT32_REF=103]="DT_INT32_REF",r[r.DT_UINT8_REF=104]="DT_UINT8_REF",r[r.DT_INT16_REF=105]="DT_INT16_REF",r[r.DT_INT8_REF=106]="DT_INT8_REF",r[r.DT_STRING_REF=107]="DT_STRING_REF",r[r.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",r[r.DT_INT64_REF=109]="DT_INT64_REF",r[r.DT_BOOL_REF=110]="DT_BOOL_REF",r[r.DT_QINT8_REF=111]="DT_QINT8_REF",r[r.DT_QUINT8_REF=112]="DT_QUINT8_REF",r[r.DT_QINT32_REF=113]="DT_QINT32_REF",r[r.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF"})(Eo||(Eo={}));var RV;(function(r){let e;(function(t){t[t.LEGACY=0]="LEGACY",t[t.V1=1]="V1",t[t.V2=2]="V2"})(e=r.CheckpointFormatVersion||(r.CheckpointFormatVersion={}))})(RV||(RV={}));var RI={};function tse(r,e){let t={tfOpName:r,category:"custom",inputs:[],attrs:[],customExecutor:e};RI[r]=t}function Uy(r){return RI[r]}function rse(r){delete RI[r]}function v(r,e,t,n,o){let s=e.inputParams[r];if(s&&s.inputIndexStart!==void 0){let i=s.inputIndexStart,l=s.inputIndexEnd===0?void 0:s.inputIndexEnd===void 0?i+1:s.inputIndexEnd;if(s.type==="tensor")return yr(e.inputNames[s.inputIndexStart],t,n,o);if(s.type==="tensors")return e.inputNames.slice(i,l).map(m=>yr(m,t,n,o));let u=yr(e.inputNames.slice(i)[0],t,n,o),c=u.dataSync();return s.type==="number"?c[0]:y.toNestedArray(u.shape,c)}let a=e.attrParams[r];return a&&a.value}function yr(r,e,t,n){let[o,s]=hn(r);if(n!=null){let i=n.getHashTableHandleByName(o);if(i!=null)return i}let a=t.currentContextIds.find(i=>!!e[qy(o,i)]);return a!==void 0?e[qy(o,a)][s]:void 0}function FV(r,e,t){return e[qy(r,t.currentContextId)]}function qs(r,e){let[t,n,o]=hn(r);return[qy(t,e&&e.currentContextId),n,o]}function qy(r,e){return e?`${r}-${e}`:r}function hn(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 qh(r,e,t){let n=v("pad",r,e,t);if(n==="explicit"){n=v("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 Hs(r){return r.kept?r:qn(r)}var FI={};je(FI,{json:()=>nse});var nse=[{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 OI={};je(OI,{json:()=>ose});var ose=[{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 PI={};je(PI,{json:()=>sse});var sse=[{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 MI={};je(MI,{json:()=>ise});var ise=[{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 LI={};je(LI,{json:()=>ase});var ase=[{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 zI={};je(zI,{json:()=>lse});var lse=[{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 BI={};je(BI,{json:()=>use});var use=[{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 VI={};je(VI,{json:()=>cse});var cse=[{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 GI={};je(GI,{json:()=>pse});var pse=[{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 WI={};je(WI,{json:()=>mse});var mse=[{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 jI={};je(jI,{json:()=>fse});var fse=[{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 UI={};je(UI,{json:()=>dse});var dse=[{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 qI={};je(qI,{json:()=>hse});var hse=[{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 HI={};je(HI,{json:()=>gse});var gse=[{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 KI={};je(KI,{json:()=>xse});var xse=[{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 XI={};je(XI,{json:()=>yse});var yse=[{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 YI={};je(YI,{json:()=>bse});var bse=[{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 ZI={};je(ZI,{json:()=>wse});var wse=[{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 JI={};je(JI,{json:()=>_se});var _se=[{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 Hy=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let e=[FI,OI,PI,MI,LI,zI,BI,VI,GI,WI,jI,UI,qI,HI,KI,XI,YI,ZI,JI],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=[],a=[],i=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)&&a.push(h[g.name]),h),{}),l=[],u=[],c={},p={};t!=null&&(c=this.mapSignatureEntries(t.inputs),p=this.mapSignatureEntries(t.outputs));let m=Object.keys(i);m.forEach(h=>{let g=i[h];g.inputNames.forEach((x,b)=>{let[w,,_]=qs(x),C=i[w];if(C.outputs!=null){let A=C.outputs.indexOf(_);if(A!==-1){let D=`${w}:${A}`;g.inputNames[b]=D}}g.inputs.push(C),C.children.push(g)})}),Object.keys(p).length===0?m.forEach(h=>{let g=i[h];g.children.length===0&&u.push(g)}):Object.keys(p).forEach(h=>{let[g]=qs(h),x=i[g];x!=null&&(x.signatureKey=p[h],u.push(x))}),Object.keys(c).length>0?Object.keys(c).forEach(h=>{let[g]=qs(h),x=i[g];x&&(x.signatureKey=c[h],l.push(x))}):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:i,inputs:l,outputs:u,weights:s,placeholders:o,signature:t,functions:f};return a.length>0&&(d.initNodes=a),d}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,n)=>(t[e[n].name]=n,t),{})}mapNode(e){let t=Uy(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 a=s.type,i;switch(s.type){case"string":i=Ky(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=Ky(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"string[]":i=tb(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=tb(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"number":i=Yy(e.attr,s.tfName,s.defaultValue||0),i===void 0&&!!s.tfDeprecatedName&&(i=Yy(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"number[]":i=eb(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=eb(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"bool":i=Xy(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=Xy(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"bool[]":i=nb(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=nb(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"shape":i=Qy(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=Qy(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"shape[]":i=rb(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=rb(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"dtype":i=Zy(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=Zy(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"dtype[]":i=Jy(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=Jy(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"func":i=PV(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=PV(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:i,type:a},o},{})),n}mapFunction(e){let t=e.nodeDef,n=[],o=[],s={};t!=null&&(s=t.reduce((p,m)=>(p[m.name]=this.mapNode(m),m.op==="Const"&&o.push(p[m.name]),p),{}));let a=[],i=[];e.signature.inputArg.forEach(p=>{let[m]=qs(p.name),f={name:m,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:QI(p.type),type:"dtype"}},children:[]};f.signatureKey=p.name,a.push(f),s[m]=f}),Object.keys(s).forEach(p=>{let m=s[p];m.inputNames.forEach((f,d)=>{let[h,,g]=qs(f),x=s[h];if(x.outputs!=null){let b=x.outputs.indexOf(g);if(b!==-1){let w=`${h}:${b}`;m.inputNames[d]=w}}m.inputs.push(x),x.children.push(m)})});let u=e.ret;e.signature.outputArg.forEach(p=>{let[m,f]=qs(u[p.name]),d=s[m];d!=null&&(d.defaultOutput=f,i.push(d))});let c=this.mapArgsToSignature(e);return{nodes:s,inputs:a,outputs:i,weights:o,placeholders:n,signature:c}}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 kse(r){let e=W().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 OV(r,e){let t=Array.isArray(r)?String.fromCharCode.apply(null,r):kse(r);return e?t:t.toLowerCase()}function Ky(r,e,t,n=!1){let o=r[e];return o!=null?OV(o.s,n):t}function Xy(r,e,t){let n=r[e];return n?n.b:t}function Yy(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 QI(r){switch(typeof r=="string"&&(r=Eo[r]),r){case Eo.DT_FLOAT:return"float32";case Eo.DT_INT32:case Eo.DT_INT64:case Eo.DT_INT8:case Eo.DT_UINT8:return"int32";case Eo.DT_BOOL:return"bool";case Eo.DT_DOUBLE:return"float32";case Eo.DT_STRING:return"string";default:return null}}function PV(r,e,t){let n=r[e];return n&&n.func?n.func.name:t}function Zy(r,e,t){let n=r[e];return n&&n.type?QI(n.type):t}function Jy(r,e,t){let n=r[e];return n&&n.list&&n.list.type?n.list.type.map(o=>QI(o)):t}function MV(r){if(!r.unknownRank)return r.dim!=null?r.dim.map(e=>typeof e.size=="number"?e.size:parseInt(e.size,10)):[]}function Qy(r,e,t){let n=r[e];return n&&n.shape?MV(n.shape):t}function eb(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 tb(r,e,t,n=!1){let o=r[e];return o&&o.list&&o.list.s?o.list.s.map(s=>OV(s,n)):t}function rb(r,e,t){let n=r[e];return n&&n.list&&n.list.shape?n.list.shape.map(o=>MV(o)):t}function nb(r,e,t){let n=r[e];return n&&n.list&&n.list.b?n.list.b:t}var eS=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 yr(e,this.tensorMap,this.context)}getAttr(e,t){let n=this.node.rawAttrs[e];if(n.tensor!=null)return yr(e,this.tensorMap,this.context);if(n.i!=null||n.f!=null)return Yy(this.node.rawAttrs,e,t);if(n.s!=null)return Ky(this.node.rawAttrs,e,t);if(n.b!=null)return Xy(this.node.rawAttrs,e,t);if(n.shape!=null)return Qy(this.node.rawAttrs,e,t);if(n.type!=null)return Zy(this.node.rawAttrs,e,t);if(n.list!=null){if(n.list.i!=null||n.list.f!=null)return eb(this.node.rawAttrs,e,t);if(n.list.s!=null)return tb(this.node.rawAttrs,e,t);if(n.list.shape!=null)return rb(this.node.rawAttrs,e,t);if(n.list.b!=null)return nb(this.node.rawAttrs,e,t);if(n.list.type!=null)return Jy(this.node.rawAttrs,e,t)}return t}};var LV=(r,e,t)=>{switch(r.op){case"BiasAdd":case"AddV2":case"Add":return[J(v("a",r,e,t),v("b",r,e,t))];case"AddN":return[S_(v("tensors",r,e,t))];case"FloorMod":case"Mod":return[Lf(v("a",r,e,t),v("b",r,e,t))];case"Mul":return[P(v("a",r,e,t),v("b",r,e,t))];case"RealDiv":case"Div":return[ue(v("a",r,e,t),v("b",r,e,t))];case"DivNoNan":return[Ef(v("a",r,e,t),v("b",r,e,t))];case"FloorDiv":return[yu(v("a",r,e,t),v("b",r,e,t))];case"Sub":return[ce(v("a",r,e,t),v("b",r,e,t))];case"Minimum":return[Rs(v("a",r,e,t),v("b",r,e,t))];case"Maximum":return[an(v("a",r,e,t),v("b",r,e,t))];case"Pow":return[jr(v("a",r,e,t),v("b",r,e,t))];case"SquaredDifference":return[Bu(v("a",r,e,t),v("b",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var zV=(r,e,t)=>{switch(r.op){case"Abs":case"ComplexAbs":return[Tt(v("x",r,e,t))];case"Acos":return[hf(v("x",r,e,t))];case"Acosh":return[gf(v("x",r,e,t))];case"Asin":return[yf(v("x",r,e,t))];case"Asinh":return[bf(v("x",r,e,t))];case"Atan":return[wf(v("x",r,e,t))];case"Atan2":return[_f(v("x",r,e,t),v("y",r,e,t))];case"Atanh":return[kf(v("x",r,e,t))];case"Ceil":return[If(v("x",r,e,t))];case"Complex":return[Fn(v("real",r,e,t),v("imag",r,e,t))];case"Cos":return[Ea(v("x",r,e,t))];case"Cosh":return[Cu(v("x",r,e,t))];case"Elu":return[As(v("x",r,e,t))];case"Erf":return[Af(v("x",r,e,t))];case"Exp":return[nr(v("x",r,e,t))];case"Expm1":return[Df(v("x",r,e,t))];case"Floor":return[$s(v("x",r,e,t))];case"Log":return[hr(v("x",r,e,t))];case"Log1p":return[Tu(v("x",r,e,t))];case"Imag":return[Su(v("x",r,e,t))];case"Neg":return[Ke(v("x",r,e,t))];case"Reciprocal":return[zf(v("x",r,e,t))];case"Real":return[Al(v("x",r,e,t))];case"Relu":return[Mr(v("x",r,e,t))];case"Round":return[Fu(v("x",r,e,t))];case"Selu":return[Pu(v("x",r,e,t))];case"Sigmoid":return[Pr(v("x",r,e,t))];case"Sin":return[Mu(v("x",r,e,t))];case"Sign":return[Vf(v("x",r,e,t))];case"Sinh":return[Lu(v("x",r,e,t))];case"Softplus":return[po(v("x",r,e,t))];case"Sqrt":return[xt(v("x",r,e,t))];case"Square":return[Le(v("x",r,e,t))];case"Tanh":return[Ts(v("x",r,e,t))];case"Tan":return[Uf(v("x",r,e,t))];case"ClipByValue":return[fr(v("x",r,e,t),v("clipValueMin",r,e,t),v("clipValueMax",r,e,t))];case"Relu6":return[Ru(v("x",r,e,t))];case"Rsqrt":return[Ou(yr(r.inputNames[0],e,t))];case"Prod":return[Du(v("x",r,e,t),v("axes",r,e,t))];case"LeakyRelu":return[Aa(v("x",r,e,t),v("alpha",r,e,t))];case"Prelu":return[Fa(v("x",r,e,t),v("alpha",r,e,t))];case"IsNan":return[$f(yr(r.inputNames[0],e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};function Vn(r,e,t=""){if(!(typeof r=="number"||typeof e=="number")){y.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];y.assert(o<0||s<0||o===s,()=>t+` Shapes ${r} and ${e} must match`)}}}function BV(r){return!(typeof r=="number"||r.some(e=>e<0))}function $m(r,e,t){let n=ob(r,t),o=!BV(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=ob(s.shape,n)}),!BV(n))throw new Error(`Non-fully-defined elementShape: ${n}`);return n}function ob(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 tS=class{constructor(e,t,n,o,s,a,i){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=o,this.identicalElementShapes=s,this.dynamicSize=a,this.clearAfterRead=i,this.tensors=[],this.closed_=!1,this.idTensor=pe(0),Rt(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),Vn(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,Rt(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 Nr([],[0].concat(this.elementShape));let n=this.readMany(e);return Vn(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),Ht(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 Nr([],[0].concat(this.elementShape));let t=[];for(let o=0;o<this.size();o++)t.push(o);let n=this.readMany(t);return Vn(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),et(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,gr(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,a=[];B(()=>{t=L(t,[1,n,s]);for(let l=0;l<e.length;++l){let u=l===0?0:o[l-1],c=[0,u,0],p=[1,e[l],s];a[l]=L(Fe(t,c,p),this.elementShape)}return a});let i=[];for(let l=0;l<e.length;l++)i[l]=l;this.writeMany(i,a)}};var Sc=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}`);Vn(t,s.shape,"TensorList shape mismatch: "),Rt(s)}),this.idTensor=pe(0),this.maxNumElements=o,Rt(this.idTensor)}get id(){return this.idTensor.id}copy(){return new Sc([...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.`);Vn(e,this.elementShape,"TensorList shape mismatch: ");let o=$m(this.elementShape,this.tensors,e);return B(()=>{let s=this.tensors.map(a=>L(a,o));return Ht(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=$m(this.elementShape,this.tensors,e),o=this.tensors.pop();return Vn(o.shape,e,"TensorList shape mismatch: "),L(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(Vn(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Rt(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.`);Vn(this.tensors[e].shape,t,"TensorList shape mismatch: ");let o=$m(this.elementShape,this.tensors,t);return L(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.`);Vn(this.elementShape,t.shape,"TensorList shape mismatch: "),Rt(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}`);Vn(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());let o=$m(this.elementShape,this.tensors,n);return e.length===0?Nr([],[0].concat(o)):B(()=>{let s=e.map(a=>L(this.tensors[a],o));return Ht(s,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Vn(this.elementShape,t,"TensorList shape mismatch: ");let n=$m(this.elementShape,this.tensors,t);return this.size()===0?Nr([],[0].concat(n)):B(()=>{let o=this.tensors.map(s=>L(s,n));return et(o,0)})}};function VV(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);Vn(o,e,"TensorList shape mismatch: ");let s=gr(r);return new Sc(s,e,n)}function GV(r,e,t){return new Sc([],r,e,t)}function WV(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 Sc([],t,r.dtype,n),a=gr(r,0);return e.forEach((i,l)=>{s.setItem(i,a[l])}),s}function jV(r,e,t){let n=0,o=e.map(c=>(n+=c,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),a=ob(s,t),i=n===0?0:r.size/n,l=B(()=>{let c=[];r=L(r,[1,n,i]);for(let p=0;p<e.length;++p){let m=p===0?0:o[p-1],f=[0,m,0],d=[1,e[p],i];c[p]=L(Fe(r,f,d),a)}return r.dispose(),c}),u=new Sc([],t,r.dtype,e.length);for(let c=0;c<l.length;c++)u.setItem(c,l[c]);return u}var UV=async(r,e,t)=>{switch(r.op){case"If":case"StatelessIf":{let n=v("thenBranch",r,e,t),o=v("elseBranch",r,e,t),s=v("cond",r,e,t),a=v("args",r,e,t);return(await s.data())[0]?t.functionMap[n].executeFunctionAsync(a,t.tensorArrayMap,t.tensorListMap):t.functionMap[o].executeFunctionAsync(a,t.tensorArrayMap,t.tensorListMap)}case"While":case"StatelessWhile":{let n=v("body",r,e,t),o=v("cond",r,e,t),s=v("args",r,e,t),a=await t.functionMap[o].executeFunctionAsync(s,t.tensorArrayMap,t.tensorListMap),i=s.map(c=>c.id),l=await a[0].data();a.forEach(c=>{!c.kept&&i.indexOf(c.id)===-1&&c.dispose()});let u=s;for(;l[0];){let c=u;u=await t.functionMap[n].executeFunctionAsync(u,t.tensorArrayMap,t.tensorListMap);let p=u.map(f=>f.id);c.forEach(f=>{!f.kept&&i.indexOf(f.id)===-1&&p.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&&i.indexOf(f.id)===-1&&p.indexOf(f.id)===-1&&f.dispose()})}return u}case"LoopCond":{let n=v("pred",r,e,t);return[Hs(n)]}case"Switch":{let n=v("pred",r,e,t),o=v("data",r,e,t);return o.kept||(o=Hs(o)),(await n.data())[0]?[void 0,o]:[o,void 0]}case"Merge":{let n=r.inputNames.find(o=>yr(o,e,t)!==void 0);if(n){let o=yr(n,e,t);return[Hs(o)]}return}case"Enter":{let n=v("frameName",r,e,t),o=v("tensor",r,e,t);return t.enterFrame(n),[Hs(o)]}case"Exit":{let n=v("tensor",r,e,t);return t.exitFrame(),[Hs(n)]}case"NextIteration":{let n=v("tensor",r,e,t);return t.nextIteration(),[Hs(n)]}case"TensorArrayV3":{let n=v("size",r,e,t),o=v("dtype",r,e,t),s=v("elementShape",r,e,t),a=v("dynamicSize",r,e,t),i=v("clearAfterRead",r,e,t),l=v("identicalElementShapes",r,e,t),u=v("name",r,e,t),c=new tS(u,o,n,s,l,a,i);return t.addTensorArray(c),[c.idTensor,pe(1)]}case"TensorArrayWriteV3":{let n=v("tensorArrayId",r,e,t),o=v("index",r,e,t),s=v("tensor",r,e,t),a=t.getTensorArray(n.id);return a.write(o,s),[a.idTensor]}case"TensorArrayReadV3":{let n=v("tensorArrayId",r,e,t),o=v("index",r,e,t);return[t.getTensorArray(n.id).read(o)]}case"TensorArrayGatherV3":{let n=v("tensorArrayId",r,e,t),o=v("indices",r,e,t),s=v("dtype",r,e,t);return[t.getTensorArray(n.id).gather(o,s)]}case"TensorArrayScatterV3":{let n=v("tensorArrayId",r,e,t),o=v("indices",r,e,t),s=v("tensor",r,e,t),a=t.getTensorArray(n.id);return a.scatter(o,s),[a.idTensor]}case"TensorArrayConcatV3":{let n=v("tensorArrayId",r,e,t),o=t.getTensorArray(n.id),s=v("dtype",r,e,t);return[o.concat(s)]}case"TensorArraySplitV3":{let n=v("tensorArrayId",r,e,t),o=v("tensor",r,e,t),s=v("lengths",r,e,t),a=t.getTensorArray(n.id);return a.split(s,o),[a.idTensor]}case"TensorArraySizeV3":{let n=v("tensorArrayId",r,e,t),o=t.getTensorArray(n.id);return[pe(o.size(),"int32")]}case"TensorArrayCloseV3":{let n=v("tensorArrayId",r,e,t),o=t.getTensorArray(n.id);return o.clearAndClose(),[o.idTensor]}case"TensorListSetItem":{let n=v("tensorListId",r,e,t),o=v("index",r,e,t),s=v("tensor",r,e,t),a=t.getTensorList(n.id);return a.setItem(o,s),[a.idTensor]}case"TensorListGetItem":{let n=v("tensorListId",r,e,t),o=v("index",r,e,t),s=v("elementShape",r,e,t),a=v("elementDType",r,e,t);return[t.getTensorList(n.id).getItem(o,s,a)]}case"TensorListScatterV2":case"TensorListScatter":{let n=v("indices",r,e,t),o=v("tensor",r,e,t),s=v("elementShape",r,e,t),a=v("numElements",r,e,t),i=WV(o,n,s,a);return t.addTensorList(i),[i.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let n=v("elementShape",r,e,t),o=v("elementDType",r,e,t),s;r.op==="TensorListReserve"?s="numElements":s="maxNumElements";let a=v(s,r,e,t),i=GV(n,o,a);return t.addTensorList(i),[i.idTensor]}case"TensorListGather":{let n=v("tensorListId",r,e,t),o=v("indices",r,e,t),s=v("elementShape",r,e,t),a=v("elementDType",r,e,t);return[t.getTensorList(n.id).gather(o,a,s)]}case"TensorListStack":{let n=v("tensorListId",r,e,t),o=v("elementShape",r,e,t),s=v("elementDType",r,e,t),a=v("numElements",r,e,t);return[t.getTensorList(n.id).stack(o,s,a)]}case"TensorListFromTensor":{let n=v("tensor",r,e,t),o=v("elementShape",r,e,t),s=v("elementDType",r,e,t),a=VV(n,o,s);return t.addTensorList(a),[a.idTensor]}case"TensorListConcat":{let n=v("tensorListId",r,e,t),o=t.getTensorList(n.id),s=v("dtype",r,e,t),a=v("elementShape",r,e,t);return[o.concat(s,a)]}case"TensorListPushBack":{let n=v("tensorListId",r,e,t),o=v("tensor",r,e,t),s=t.getTensorList(n.id);return s.pushBack(o),[s.idTensor]}case"TensorListPopBack":{let n=v("tensorListId",r,e,t),o=v("elementShape",r,e,t),s=v("elementDType",r,e,t);return[t.getTensorList(n.id).popBack(o,s)]}case"TensorListSplit":{let n=v("tensor",r,e,t),o=v("elementShape",r,e,t),s=v("lengths",r,e,t),a=jV(n,s,o);return t.addTensorList(a),[a.idTensor]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};function qV(r,e,t){let[n,o]=v("fusedOps",r,e,t),s=n==="biasadd",a=!s,i=o==="prelu",l=n==="fusedbatchnorm",u=v("numArgs",r,e,t);if(s){if(i&&u!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&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 c=v("strides",r,e,t),p=qh(r,e,t),m=v("dataFormat",r,e,t).toUpperCase(),f=v("dilations",r,e,t),[d,h]=v("args",r,e,t);a&&(h=d,d=void 0);let g=v("leakyreluAlpha",r,e,t);return{stride:c,pad:p,dataFormat:m,dilations:f,biasArg:d,preluArg:h,activationFunc:o,leakyreluAlpha:g}}var HV=(r,e,t)=>{switch(r.op){case"Conv1D":{let n=v("stride",r,e,t),o=v("pad",r,e,t),s=v("dataFormat",r,e,t).toUpperCase(),a=v("dilation",r,e,t);return[ku(v("x",r,e,t),v("filter",r,e,t),n,o,s,a)]}case"Conv2D":{let n=v("strides",r,e,t),o=qh(r,e,t),s=v("dataFormat",r,e,t).toUpperCase(),a=v("dilations",r,e,t);return[on(v("x",r,e,t),v("filter",r,e,t),[n[1],n[2]],o,s,[a[1],a[2]])]}case"_FusedConv2D":{let{stride:n,pad:o,dataFormat:s,dilations:a,biasArg:i,preluArg:l,activationFunc:u,leakyreluAlpha:c}=qV(r,e,t);return[ho.conv2d({x:v("x",r,e,t),filter:v("filter",r,e,t),strides:[n[1],n[2]],pad:o,dataFormat:s,dilations:[a[1],a[2]],bias:i,activation:u,preluActivationWeights:l,leakyreluAlpha:c})]}case"FusedDepthwiseConv2dNative":{let{stride:n,pad:o,dataFormat:s,dilations:a,biasArg:i,preluArg:l,activationFunc:u,leakyreluAlpha:c}=qV(r,e,t);return[ho.depthwiseConv2d({x:v("x",r,e,t),filter:v("filter",r,e,t),strides:[n[1],n[2]],pad:o,dataFormat:s,dilations:[a[1],a[2]],bias:i,activation:u,preluActivationWeights:l,leakyreluAlpha:c})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{let n=v("outputShape",r,e,t),o=v("strides",r,e,t),s=qh(r,e,t);return[vu(v("x",r,e,t),v("filter",r,e,t),n,[o[1],o[2]],s)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{let n=v("strides",r,e,t),o=qh(r,e,t),s=v("dilations",r,e,t),a=v("dataFormat",r,e,t).toUpperCase();return[Es(v("input",r,e,t),v("filter",r,e,t),[n[1],n[2]],o,a,[s[1],s[2]])]}case"Conv3D":{let n=v("strides",r,e,t),o=v("pad",r,e,t),s=v("dataFormat",r,e,t).toUpperCase(),a=v("dilations",r,e,t);return[Sf(v("x",r,e,t),v("filter",r,e,t),[n[1],n[2],n[3]],o,s,[a[1],a[2],a[3]])]}case"AvgPool":{let n=v("strides",r,e,t),o=v("pad",r,e,t),s=v("kernelSize",r,e,t);return[Sa(v("x",r,e,t),[s[1],s[2]],[n[1],n[2]],o)]}case"MaxPool":{let n=v("strides",r,e,t),o=v("pad",r,e,t),s=v("kernelSize",r,e,t);return[$a(v("x",r,e,t),[s[1],s[2]],[n[1],n[2]],o)]}case"MaxPoolWithArgmax":{let n=v("strides",r,e,t),o=v("pad",r,e,t),s=v("kernelSize",r,e,t),a=v("includeBatchInIndex",r,e,t),{result:i,indexes:l}=X_(v("x",r,e,t),[s[1],s[2]],[n[1],n[2]],o,a);return[i,l]}case"AvgPool3D":{let n=v("strides",r,e,t),o=v("pad",r,e,t),s=v("kernelSize",r,e,t);return[vf(v("x",r,e,t),[s[1],s[2],s[3]],[n[1],n[2],n[3]],o)]}case"MaxPool3D":{let n=v("strides",r,e,t),o=v("pad",r,e,t),s=v("kernelSize",r,e,t);return[Pf(v("x",r,e,t),[s[1],s[2],s[3]],[n[1],n[2],n[3]],o)]}case"Dilation2D":{let n=v("strides",r,e,t),o=v("pad",r,e,t),s=v("dilations",r,e,t),a=n[1],i=n[2],l=s[1],u=s[2];return[Tf(v("x",r,e,t),v("filter",r,e,t),[a,i],o,[l,u],"NHWC")]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var KV=(r,e,t)=>{switch(r.op){case"Fill":{let n=v("shape",r,e,t),o=v("dtype",r,e,t),s=v("value",r,e,t);return[Ds(n,s,o)]}case"LinSpace":{let n=v("start",r,e,t),o=v("stop",r,e,t),s=v("num",r,e,t);return[W_(n,o,s)]}case"Multinomial":{let n=v("logits",r,e,t),o=v("numSamples",r,e,t),s=v("seed",r,e,t);return[Y_(n,o,s)]}case"OneHot":{let n=v("indices",r,e,t),o=v("depth",r,e,t),s=v("onValue",r,e,t),a=v("offValue",r,e,t);return[Ss(n,o,s,a)]}case"Ones":return[or(v("shape",r,e,t),v("dtype",r,e,t))];case"OnesLike":return[ur(v("x",r,e,t))];case"RandomUniform":return[Fs(v("shape",r,e,t),v("minval",r,e,t),v("maxval",r,e,t),v("dtype",r,e,t))];case"Range":{let n=v("start",r,e,t),o=v("stop",r,e,t),s=v("step",r,e,t);return[Oa(n,o,s,v("dtype",r,e,t))]}case"TruncatedNormal":{let n=v("shape",r,e,t),o=v("mean",r,e,t),s=v("stdDev",r,e,t),a=v("seed",r,e,t);return[Vu(n,o,s,v("dtype",r,e,t),a)]}case"Zeros":return[gt(v("shape",r,e,t),v("dtype",r,e,t))];case"ZerosLike":return[Se(v("x",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};function rS(r,e,t){let n=v("boxes",r,e,t),o=v("scores",r,e,t),s=v("maxOutputSize",r,e,t),a=v("iouThreshold",r,e,t),i=v("scoreThreshold",r,e,t),l=v("softNmsSigma",r,e,t);return{boxes:n,scores:o,maxOutputSize:s,iouThreshold:a,scoreThreshold:i,softNmsSigma:l}}var XV=async(r,e,t)=>{switch(r.op){case"NonMaxSuppressionV5":{let{boxes:n,scores:o,maxOutputSize:s,iouThreshold:a,scoreThreshold:i,softNmsSigma:l}=rS(r,e,t),u=await yi.nonMaxSuppressionWithScoreAsync(n,o,s,a,i,l);return[u.selectedIndices,u.selectedScores]}case"NonMaxSuppressionV4":{let{boxes:n,scores:o,maxOutputSize:s,iouThreshold:a,scoreThreshold:i}=rS(r,e,t),l=v("padToMaxOutputSize",r,e,t),u=await yi.nonMaxSuppressionPaddedAsync(n,o,s,a,i,l);return[u.selectedIndices,u.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{let{boxes:n,scores:o,maxOutputSize:s,iouThreshold:a,scoreThreshold:i}=rS(r,e,t);return[await yi.nonMaxSuppressionAsync(n,o,s,a,i)]}case"Where":{let n=oe(v("condition",r,e,t),"bool"),o=[await Kf(n)];return n.dispose(),o}case"ListDiff":return lk(v("x",r,e,t),v("y",r,e,t));default:throw TypeError(`Node type ${r.op} is not implemented`)}};var YV=(r,e,t)=>{switch(r.op){case"TopKV2":{let n=v("x",r,e,t),o=v("k",r,e,t),s=v("sorted",r,e,t),a=qf(n,o,s);return[a.values,a.indices]}case"Unique":{let n=v("x",r,e,t),o=Bp(n);return[o.values,o.indices]}case"UniqueV2":{let n=v("x",r,e,t),o=v("axis",r,e,t),s=Bp(n,o);return[s.values,s.indices]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var ZV=(r,e,t)=>{switch(r.op){case"Const":return e[r.name];case"PlaceholderWithDefault":let n=v("default",r,e,t);return[yr(r.name,e,t)||n];case"Placeholder":return[yr(r.name,e,t)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let u=v("x",r,e,t);return[Hs(u)]}case"IdentityN":return v("x",r,e,t).map(u=>Hs(u));case"Snapshot":let o=v("x",r,e,t);return[Hs(o)];case"Shape":return[Dt(v("x",r,e,t).shape,"int32")];case"ShapeN":return v("x",r,e,t).map(u=>Dt(u.shape));case"Size":return[pe(v("x",r,e,t).size,"int32")];case"Rank":return[pe(v("x",r,e,t).rank,"int32")];case"NoOp":return[pe(1)];case"Print":let s=v("x",r,e,t),a=v("data",r,e,t),i=v("message",r,e,t),l=v("summarize",r,e,t);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(i);for(let u=0;u<a.length;u++)console.log(Array.prototype.slice.call(a[u].dataSync()).slice(0,l));return[s];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var nS=class{constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=pe(0),this.tensorMap=new Map,Rt(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 pe(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(),B(()=>{let o=gr(t),s=n.length,a=o.length;y.assert(s===a,()=>`The number of elements doesn't match, keys has ${s} elements, the values has ${a} elements.`);for(let i=0;i<s;i++){let l=n[i],u=o[i];Rt(u),this.tensorMap.set(l,u)}return this.handle})}async find(e,t){this.checkKeyAndValueTensor(e,t);let n=await e.data();return B(()=>{let o=[];for(let s=0;s<n.length;s++){let a=n[s],i=this.findWithDefault(a,t);o.push(i)}return Ht(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 JV=async(r,e,t,n)=>{switch(r.op){case"HashTable":case"HashTableV2":{let o=v("keyDType",r,e,t),s=v("valueDType",r,e,t),a=new nS(o,s);return n.addHashTable(r.name,a),[a.handle]}case"LookupTableImport":case"LookupTableImportV2":{let o=v("tableHandle",r,e,t,n),s=v("keys",r,e,t),a=v("values",r,e,t);return[await n.getHashTableById(o.id).import(s,a)]}case"LookupTableFind":case"LookupTableFindV2":{let o=v("tableHandle",r,e,t,n),s=v("keys",r,e,t),a=v("defaultValue",r,e,t);return[await n.getHashTableById(o.id).find(s,a)]}case"LookupTableSize":case"LookupTableSizeV2":{let o=v("tableHandle",r,e,t,n);return[n.getHashTableById(o.id).tensorSize()]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var QV=(r,e,t)=>{switch(r.op){case"ResizeBilinear":{let n=v("images",r,e,t),o=v("size",r,e,t),s=v("alignCorners",r,e,t),a=v("halfPixelCenters",r,e,t);return[yi.resizeBilinear(n,[o[0],o[1]],s,a)]}case"ResizeNearestNeighbor":{let n=v("images",r,e,t),o=v("size",r,e,t),s=v("alignCorners",r,e,t),a=v("halfPixelCenters",r,e,t);return[yi.resizeNearestNeighbor(n,[o[0],o[1]],s,a)]}case"CropAndResize":{let n=v("image",r,e,t),o=v("boxes",r,e,t),s=v("boxInd",r,e,t),a=v("cropSize",r,e,t),i=v("method",r,e,t),l=v("extrapolationValue",r,e,t);return[yi.cropAndResize(n,o,s,a,i,l)]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var eG=(r,e,t)=>{switch(r.op){case"Equal":return[On(v("a",r,e,t),v("b",r,e,t))];case"NotEqual":return[fo(v("a",r,e,t),v("b",r,e,t))];case"Greater":return[qt(v("a",r,e,t),v("b",r,e,t))];case"GreaterEqual":return[_n(v("a",r,e,t),v("b",r,e,t))];case"Less":return[Nu(v("a",r,e,t),v("b",r,e,t))];case"LessEqual":return[kn(v("a",r,e,t),v("b",r,e,t))];case"LogicalAnd":return[_r(v("a",r,e,t),v("b",r,e,t))];case"LogicalNot":return[Da(v("a",r,e,t))];case"LogicalOr":return[Au(v("a",r,e,t),v("b",r,e,t))];case"Select":case"SelectV2":return[Ct(v("condition",r,e,t),v("a",r,e,t),v("b",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var tG=(r,e,t)=>{switch(r.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[Be(v("a",r,e,t),v("b",r,e,t),v("transposeA",r,e,t),v("transposeB",r,e,t))];case"Einsum":return[B_(v("equation",r,e,t),...v("tensors",r,e,t))];case"Transpose":return[qe(v("x",r,e,t),v("perm",r,e,t))];case"_FusedMatMul":let[n,o]=v("fusedOps",r,e,t),s=n==="biasadd",a=o==="prelu",i=v("numArgs",r,e,t),l=v("leakyreluAlpha",r,e,t);if(s){if(a&&i!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!a&&i!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}let[u,c]=v("args",r,e,t);return[ho.matMul({a:v("a",r,e,t),b:v("b",r,e,t),transposeA:v("transposeA",r,e,t),transposeB:v("transposeB",r,e,t),bias:u,activation:o,preluActivationWeights:c,leakyreluAlpha:l})];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var rG=(r,e,t)=>{switch(r.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[uo(v("x",r,e,t),v("mean",r,e,t),v("variance",r,e,t),v("offset",r,e,t),v("scale",r,e,t),v("epsilon",r,e,t))];case"FusedBatchNormV3":return[uo(v("x",r,e,t),v("mean",r,e,t),v("variance",r,e,t),v("offset",r,e,t),v("scale",r,e,t),v("epsilon",r,e,t))];case"LRN":return[Rf(v("x",r,e,t),v("radius",r,e,t),v("bias",r,e,t),v("alpha",r,e,t),v("beta",r,e,t))];case"Softmax":return[Pa(v("x",r,e,t))];case"LogSoftmax":return[Eu(v("x",r,e,t))];case"SparseToDense":return[tx(v("sparseIndices",r,e,t),v("outputShape",r,e,t),v("sparseValues",r,e,t),v("defaultValue",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var nG=(r,e,t)=>{switch(r.op){case"Max":{let a=v("axis",r,e,t),i=v("keepDims",r,e,t);return[Er(v("x",r,e,t),a,i)]}case"Mean":{let a=v("axis",r,e,t),i=v("keepDims",r,e,t);return[ht(v("x",r,e,t),a,i)]}case"Min":{let a=v("axis",r,e,t),i=v("keepDims",r,e,t);return[El(v("x",r,e,t),a,i)]}case"Sum":{let a=v("axis",r,e,t),i=v("keepDims",r,e,t);return[de(v("x",r,e,t),a,i)]}case"All":{let a=v("axis",r,e,t),i=v("keepDims",r,e,t);return[bu(v("x",r,e,t),a,i)]}case"Any":{let a=v("axis",r,e,t),i=v("keepDims",r,e,t);return[Nl(v("x",r,e,t),a,i)]}case"ArgMax":{let a=v("axis",r,e,t);return[Tl(v("x",r,e,t),a)]}case"ArgMin":{let a=v("axis",r,e,t);return[xf(v("x",r,e,t),a)]}case"Prod":{let a=v("axis",r,e,t),i=v("keepDims",r,e,t);return[Du(v("x",r,e,t),a,i)]}case"Cumsum":{let a=v("axis",r,e,t),i=v("exclusive",r,e,t),l=v("reverse",r,e,t);return[Iu(v("x",r,e,t),a,i,l)]}case"Bincount":let n=v("x",r,e,t),o=v("weights",r,e,t),s=v("size",r,e,t);return[Cf(n,o,s)];case"DenseBincount":{let a=v("x",r,e,t),i=v("weights",r,e,t),l=v("size",r,e,t),u=v("binaryOutput",r,e,t);return[L_(a,i,l,u)]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var oG=(r,e,t)=>{switch(r.op){case"ConcatV2":case"Concat":{let n=v("n",r,e,t),o=v("axis",r,e,t),s=v("tensors",r,e,t);return s=s.slice(0,n),[et(s,o)]}case"Gather":{let n=v("x",r,e,t),o=v("indices",r,e,t);return[co(n,oe(o,"int32"),0)]}case"GatherV2":{let n=v("axis",r,e,t),o=v("batchDims",r,e,t),s=v("x",r,e,t),a=v("indices",r,e,t);return[co(s,oe(a,"int32"),n,o)]}case"Reverse":{let n=v("dims",r,e,t),o=[];for(let a=0;a<n.length;a++)n[a]&&o.push(a);let s=v("x",r,e,t);return[Jt(s,o)]}case"ReverseV2":{let n=v("axis",r,e,t),o=v("x",r,e,t);return[Jt(o,n)]}case"Slice":{let n=v("begin",r,e,t),o=v("size",r,e,t);return[Fe(v("x",r,e,t),n,o)]}case"StridedSlice":{let n=v("begin",r,e,t),o=v("end",r,e,t),s=v("strides",r,e,t),a=v("beginMask",r,e,t),i=v("endMask",r,e,t),l=v("ellipsisMask",r,e,t),u=v("newAxisMask",r,e,t),c=v("shrinkAxisMask",r,e,t),p=v("x",r,e,t);return[jf(p,n,o,s,a,i,l,u,c)]}case"Pack":return B(()=>{let n=v("axis",r,e,t),o=v("tensors",r,e,t),s=o[0].shape,a=Pn(o[0]).shape,i=o.map(l=>{let u=y.arraysEqual(l.shape,s);if(!u&&!y.arraysEqual(Pn(l).shape,a))throw new Error("the input tensors shape does not match");return u?l:L(l,s)});return[Ht(i,n)]});case"Unpack":{let n=v("axis",r,e,t),o=v("tensor",r,e,t);return gr(o,n)}case"Tile":{let n=v("reps",r,e,t);return[Kn(v("x",r,e,t),n)]}case"Split":case"SplitV":{let n=v("axis",r,e,t),o=v("numOrSizeSplits",r,e,t),s=v("x",r,e,t);return sr(s,o,n)}case"ScatterNd":{let n=v("indices",r,e,t),o=v("values",r,e,t),s=v("shape",r,e,t);return[uE(n,o,s)]}case"GatherNd":{let n=v("x",r,e,t),o=v("indices",r,e,t);return[pE(n,o)]}case"SparseToDense":{let n=v("sparseIndices",r,e,t),o=v("outputShape",r,e,t),s=v("sparseValues",r,e,t),a=v("defaultValue",r,e,t);return[tx(n,s,o,s.dtype===a.dtype?a:oe(a,s.dtype))]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var sG=(r,e,t)=>{switch(r.op){case"SparseFillEmptyRows":{let{outputIndices:n,outputValues:o,emptyRowIndicator:s,reverseIndexMap:a}=Xf.sparseFillEmptyRows(v("indices",r,e,t),v("values",r,e,t),v("denseShape",r,e,t),v("defaultValue",r,e,t));return[n,o,s,a]}case"SparseReshape":{let{outputIndices:n,outputShape:o}=Xf.sparseReshape(v("inputIndices",r,e,t),v("inputShape",r,e,t),v("newShape",r,e,t));return[n,o]}case"SparseSegmentMean":return[Xf.sparseSegmentMean(v("data",r,e,t),v("indices",r,e,t),v("segmentIds",r,e,t))];case"SparseSegmentSum":return[Xf.sparseSegmentSum(v("data",r,e,t),v("indices",r,e,t),v("segmentIds",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var iG=(r,e,t)=>{switch(r.op){case"FFT":return[Ma(v("x",r,e,t))];case"IFFT":return[gi(v("x",r,e,t))];case"RFFT":return[La(v("x",r,e,t))];case"IRFFT":return[zu(v("x",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var aG=(r,e,t)=>{switch(r.op){case"StringNGrams":{let{nGrams:n,nGramsSplits:o}=mx.stringNGrams(v("data",r,e,t),v("dataSplits",r,e,t),v("separator",r,e,t),v("nGramWidths",r,e,t),v("leftPad",r,e,t),v("rightPad",r,e,t),v("padWidth",r,e,t),v("preserveShortSequences",r,e,t));return[n,o]}case"StringSplit":{let{indices:n,values:o,shape:s}=mx.stringSplit(v("input",r,e,t),v("delimiter",r,e,t),v("skipEmpty",r,e,t));return[n,o,s]}case"StringToHashBucketFast":return[mx.stringToHashBucketFast(v("input",r,e,t),v("numBuckets",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var lG=(r,e,t)=>{switch(r.op){case"Cast":return[oe(v("x",r,e,t),v("dtype",r,e,t))];case"ExpandDims":{let n=v("axis",r,e,t);return[dr(v("x",r,e,t),n)]}case"Squeeze":{let n=v("axis",r,e,t);return[Pn(v("x",r,e,t),n)]}case"Reshape":return[L(v("x",r,e,t),v("shape",r,e,t))];case"MirrorPad":return[Mf(v("x",r,e,t),v("padding",r,e,t),v("mode",r,e,t))];case"PadV2":case"Pad":return[Wr(v("x",r,e,t),v("padding",r,e,t),v("constantValue",r,e,t))];case"SpaceToBatchND":{let n=v("blockShape",r,e,t),o=v("paddings",r,e,t);return[Ra(v("x",r,e,t),n,o)]}case"BatchToSpaceND":{let n=v("blockShape",r,e,t),o=v("crops",r,e,t);return[Na(v("x",r,e,t),n,o)]}case"DepthToSpace":{let n=v("blockSize",r,e,t),o=v("dataFormat",r,e,t).toUpperCase();return[Nf(v("x",r,e,t),n,o)]}case"BroadcastTo":return[Ta(v("x",r,e,t),v("shape",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};function oS(r,e,t,n){let o=((s,a,i)=>{switch(s.category){case"arithmetic":return B(()=>LV(s,a,i));case"basic_math":return B(()=>zV(s,a,i));case"control":return UV(s,a,i);case"convolution":return B(()=>HV(s,a,i));case"creation":return B(()=>KV(s,a,i));case"dynamic":return XV(s,a,i);case"evaluation":return B(()=>YV(s,a,i));case"image":return B(()=>QV(s,a,i));case"graph":return B(()=>ZV(s,a,i));case"logical":return B(()=>eG(s,a,i));case"matrices":return B(()=>tG(s,a,i));case"normalization":return B(()=>rG(s,a,i));case"reduction":return B(()=>nG(s,a,i));case"slice_join":return B(()=>oG(s,a,i));case"sparse":return B(()=>sG(s,a,i));case"spectral":return B(()=>iG(s,a,i));case"string":return B(()=>aG(s,a,i));case"transformation":return B(()=>lG(s,a,i));case"hash_table":return JV(s,a,i,n);case"custom":let l=Uy(s.op);if(l&&l.customExecutor)return l.customExecutor(new eS(s,a,i));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 y.isPromise(o)?o.then(s=>[].concat(s)):[].concat(o)}var sb=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 sS(r,e,t,n){let o=new Set,s=[],a=null,i=null,l=new Set,u=Object.keys(r).map(m=>hn(m)[0]),c=[];n!=null&&(c=n.map(m=>hn(m.name)[0]));let p=[...e];for(;p.length>0;){let m=p.pop();if((iS(m)||Sse(m)||Nse(m))&&a==null&&(a=m,i=a.children.map(f=>f.name).filter(f=>o.has(f))),o.add(m.name),t[m.name]==null&&u.indexOf(m.name)===-1&&c.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),p.push(f))})}}return{inputs:r,outputs:e,usedNodes:o,missingInputs:s,dynamicNode:a,syncInputs:i}}function uG(r,e,t){let{usedNodes:n,inputs:o}=t,s=[],a=Object.keys(o).map(c=>hn(c)[0]).map(c=>r.nodes[c]),i=r.initNodes;a.forEach(c=>{n.has(c.name)&&s.push(c)}),r.weights.forEach(c=>{n.has(c.name)&&s.push(c)}),i!=null&&i.forEach(c=>{n.has(c.name)&&s.push(c)});let l=new Set,u=[];for(;s.length>0;){let c=s.pop();l.add(c.name),e[c.name]||u.push(c),c.children.forEach(p=>{!l.has(p.name)&&n.has(p.name)&&p.inputs.every(m=>l.has(m.name))&&s.push(p)})}return u}var vse=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],Cse=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],Ise=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"];function iS(r){return vse.indexOf(r.op)>=0}function Sse(r){return Cse.indexOf(r.op)>=0}function Nse(r){return Ise.indexOf(r.op)>=0}var Rm=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 Rm(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=sS(e,t,this.weightMap,this._initNodes),{missingInputs:o,dynamicNode:s,syncInputs:a}=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 [${a}]`);if(o.length>0){let i=t.map(u=>u.name),l=Object.keys(e);throw new Error(`Cannot compute the outputs [${i}] from the provided inputs [${l}]. Missing the following inputs: [${o}]`)}return uG(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(p=>this.graph.nodes[hn(p)[0]]),s=t.map(p=>hn(p)[0]),a=s.map(p=>this.graph.nodes[p]);a.length===0&&(a=this._outputs);let i=this.getCompilationKey(o,a),l=this.compiledMap.get(i);l==null&&(l=this.compile(e,a),this.compiledMap.set(i,l));let u={},c={};return B(()=>{let p=new sb(this.weightMap,u,c,this.functionExecutorMap),m=Object.assign({},this.weightMap);Object.keys(e).forEach(h=>{let[g,x]=hn(h),b=[];b[x]=e[h],m[g]=b});let f=this.getFrozenTensorIds(m),d={};for(let h=0;h<l.length;h++){let g=l[h];if(!m[g.name]){let x=oS(g,m,p,this._resourceManager);if(y.isPromise(x))throw new Error(`The execution of the op '${g.op}' returned a promise. Please use model.executeAsync() instead.`);m[g.name]=x,this.checkTensorForDisposal(g.name,g,m,p,f,s,d)}}return this.parent==null&&p.dispose(f),t.map(h=>yr(h,m,p))})}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,a,i){t.category==="control"||a.indexOf(e)!==-1||(n[e].forEach(l=>{l!=null&&(i[l.id]=(i[l.id]||0)+t.children.length)}),t.inputs.forEach(l=>{if(l.category!=="control"){let u=FV(l.name,n,o);u!=null&&u.forEach(c=>{if(c&&!c.kept&&!s.has(c.id)){let p=i[c.id];p===1?(c.dispose(),delete i[c.id]):p!=null&&i[c.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 a=new sb(this.weightMap,o,s,this.functionExecutorMap),i=await this.executeWithControlFlow(e,a,t,n),l=t.map(m=>yr(m,i,a)),u=l.map(m=>m.id),c=Object.keys(e).map(m=>e[m].id),p=new Set([...u,...c,...this.weightIds]);return Object.keys(i).forEach(m=>{i[m].forEach(d=>{d&&!d.kept&&!d.isDisposed&&!p.has(d.id)&&d.dispose()})}),this.parent==null&&a.dispose(p),l}async executeFunctionAsync(e,t,n){let o=e.reduce((s,a,i)=>(s[this.inputs[i].name]=a,s),{});return this._executeAsync(o,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,o){let s=Object.keys(e),a=s.map(w=>this.graph.nodes[hn(w)[0]]),i=n.map(w=>hn(w)[0]),l=i.map(w=>this.graph.nodes[w]);l.length===0&&(l=this._outputs);let{usedNodes:u,missingInputs:c,dynamicNode:p,syncInputs:m}=sS(e,l,this.weightMap,this._initNodes),f=[...a,...this.graph.weights,...this._initNodes||[]].map(w=>({node:w,contexts:t.currentContext})),d=Object.assign({},this.weightMap);Object.keys(e).forEach(w=>{let[_,C]=hn(w),A=[];A[C]=e[w],d[_]=A});let h={},g=this.getFrozenTensorIds(d),x={};for(;f.length>0;){let w=this.processStack(a,f,t,d,x,g,i,h,u);await Promise.all(w)}p==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 b=l.filter(w=>!iS(w)&&!yr(w.name,d,t)).map(w=>w.name);if(b.length>0){let w="";throw p!=null&&(w=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${m}]`),new Error(`Cannot compute the outputs [${b}] from the provided inputs [${s}]. Consider providing the following inputs: [${c}]. ${w}`)}return d}processStack(e,t,n,o,s,a,i,l,u){let c=[];for(;t.length>0;){let p=t.pop();n.currentContext=p.contexts;let m="";if(p.node.op==="Enter"&&v("isConstant",p.node,o,n)&&([m]=qs(p.node.name,n)),o[p.node.name]==null){let f=oS(p.node,o,n,this._resourceManager);m||([m]=qs(p.node.name,n));let d=n.currentContext;y.isPromise(f)?c.push(f.then(h=>(o[m]=h,n.currentContext=d,this.checkTensorForDisposal(m,p.node,o,n,a,i,l),this.processChildNodes(p.node,t,n,o,s,u),h))):(o[m]=f,this.checkTensorForDisposal(m,p.node,o,n,a,i,l),this.processChildNodes(p.node,t,n,o,s,u))}else this.processChildNodes(p.node,t,n,o,s,u)}return c}processChildNodes(e,t,n,o,s,a){e.children.forEach(i=>{let[l]=qs(i.name,n);s[l]||!a.has(i.name)||(i.op==="Merge"?i.inputNames.some(u=>!!yr(u,o,n))&&(s[l]=!0,t.push({contexts:n.currentContext,node:i})):i.inputNames.every(u=>!!yr(u,o,n))&&(s[l]=!0,t.push({contexts:n.currentContext,node:i})))})}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]=hn(t),s=this.graph.nodes[o];if(s.attrParams.shape&&s.attrParams.shape.value){let a=s.attrParams.shape.value,i=a.length===n.shape.length&&n.shape.every((l,u)=>a[u]===-1||a[u]===l);y.assert(i,()=>`The shape of dict['${s.name}'] provided in model.execute(dict) must be [${a}], but was [${n.shape}]`)}s.attrParams.dtype&&s.attrParams.dtype.value&&y.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]=hn(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]=hn(t);if(!this.graph.nodes[n])throw new Error(`The output '${t}' is not found in the graph`)})}};var aS=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 Tse="?tfjs-format=file",Ese="model.json",lS=class{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={}),this.resourceManager=new aS}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=Or.browserHTTPRequest(e,this.loadOptions);else{let t=Or.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(Or.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=Or.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new Rm(Hy.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=Hy.Instance.transformGraph(e.modelInitializer);this.initializer=new Rm(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=Or.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 Me)&&!Array.isArray(e))return e;if(e=Array.isArray(e)?e:[e],e.length!==this.inputNodes.length)throw new Error(`Input tensor count mismatch,the graph model has ${this.inputNodes.length} placeholders, while there are ${e.length} input tensors.`);return this.inputNodes.reduce((t,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 Ase(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}${Ese}${Tse}`);let t=new lS(r,e);return await t.load(),t}var Dse="3.7.0";var vS={};je(vS,{CSVDataset:()=>Zh,Dataset:()=>Ni,FileDataSource:()=>rg,TextLineDataset:()=>Xh,URLDataSource:()=>ng,array:()=>qG,csv:()=>rW,func:()=>nW,generator:()=>oW,microphone:()=>iW,version_data:()=>aW,webcam:()=>sW,zip:()=>HG});var UG=nu(hS());var AG=nu(hS());function IG(r,e){return ab(r,e)}function ab(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(Zl(r)){let s=Array.isArray(r)?[]:{};n.add(r);for(let a in r){let i=r[a],l=ab(i,e,t,n);s[a]=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 SG(r,e=gS){return NG(r,e)}function NG(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(Zl(n)){let s=Array.isArray(n)?[]:{};t.add(n);for(let a in n){let i=r.map(u=>u[a]),l=NG(i,e,t);s[a]=l}return t.delete(n),s}else throw new Error(`Can't recurse into non-iterable type: ${n}`);else return o.value}function gS(r){return r===null?null:Zl(r[0])?{value:null,recurse:!0}:{value:r,recurse:!1}}async function lb(r,e){let t=new Map;ab(r,e,t);for(let o of Array.from(t.keys())){let s=t.get(o);if(y.isPromise(s)){let a=await s;t.set(o,a)}}return ab(r,e,t)}function Zl(r){return r!=null&&!ArrayBuffer.isView(r)&&(Array.isArray(r)||typeof r=="object"&&!(r instanceof Me))}function TG(r){return r==null||Lse(r)||Array.isArray(r)||typeof r=="object"&&r instanceof Me||y.isTypedArray(r)}function Lse(r){return r===null||typeof r!="object"&&typeof r!="function"}function EG(r){return IG(r,zse)}function zse(r){return r instanceof Me?{value:r.clone(),recurse:!1}:Zl(r)?{value:null,recurse:!0}:{value:r,recurse:!1}}var Hh=class{constructor(e){if(this.capacity=e,this.begin=0,this.end=0,e==null)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(e<1)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=new Array(e),this.doubledCapacity=2*e}wrap(e){for(;e<0;)e+=this.doubledCapacity;return e%this.doubledCapacity}get(e){if(e<0)throw new RangeError("Can't get item at a negative index.");return this.data[e%this.capacity]}set(e,t){if(e<0)throw new RangeError("Can't set item at a negative index.");this.data[e%this.capacity]=t}length(){let e=this.end-this.begin;return e<0&&(e=this.doubledCapacity+e),e}isFull(){return this.length()===this.capacity}isEmpty(){return this.length()===0}push(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,e),this.end=this.wrap(this.end+1)}pushAll(e){for(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 Fm=class extends Hh{constructor(){super(Fm.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}};Fm.INITIAL_CAPACITY=32;function xS(r){return new RG(r)}function Kh(r){return new FG(r)}function DG(r,e){return new bS(r,e)}function $G(r,e=el.FAIL){return new WG(r,e)}var er=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 VG(this,e)}filter(e){return new zG(this,e)}map(e){return new BG(this,e)}mapAsync(e){return new yS(this,e)}serialMapAsync(e){return new yS(this,e).serial()}flatmap(e){return new GG(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 LG(this,e,t)}columnMajorBatch(e,t=!0,n=gS){return this.rowMajorBatch(e,t).map(s=>SG(s,n))}concatenate(e,t){return new bS(xS([this,e]),t)}take(e){return e<0||e==null?this:new MG(this,e)}skip(e){return e<0||e==null?this:new PG(this,e)}prefetch(e){return new wS(this,e)}shuffle(e,t){return new jG(this,e,t)}serial(){return new OG(this)}},RG=class extends er{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:EG(e),done:!1}}},FG=class extends er{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}}},OG=class extends er{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()}},PG=class extends er{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;De(e.value)}return this.upstream.next()}},MG=class extends er{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()}},LG=class extends er{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}}},zG=class extends er{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;De(e.value)}}},BG=class extends er{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=lo.getTensorsInContainer(e.value),n=this.transform(e.value),o=lo.getTensorsInContainer(n);for(let s of t)lo.isTensorInList(s,o)||s.dispose();return{value:n,done:!1}}},VG=class extends er{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}}}},yS=class extends er{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=lo.getTensorsInContainer(e.value),n=await this.transform(e.value),o=lo.getTensorsInContainer(n);for(let s of t)lo.isTensorInList(s,o)||s.dispose();return{value:n,done:!1}}},Om=class extends er{constructor(){super();this.outputQueue=new Fm,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}}},GG=class extends Om{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=lo.getTensorsInContainer(e.value),n=this.transform(e.value),o=lo.getTensorsInContainer(n);this.outputQueue.pushAll(n);for(let s of t)lo.isTensorInList(s,o)||s.dispose();return!0}},bS=class extends er{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}},el;(function(r){r[r.FAIL=0]="FAIL",r[r.SHORTEST=1]="SHORTEST",r[r.LONGEST=2]="LONGEST"})(el||(el={}));var WG=class extends er{constructor(e,t=el.FAIL){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(a){return a instanceof er?{value:a.next().then(l=>(t++,l.done&&n++,l.value)),recurse:!1}:{value:null,recurse:!0}}let s=await lb(this.iterators,o);if(t===n)return{value:null,done:!0};if(n>0)switch(this.mismatchMode){case el.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case el.SHORTEST:return{value:null,done:!0};case el.LONGEST:default:}return this.count++,{value:s,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}},wS=class extends er{constructor(e,t){super();this.upstream=e,this.bufferSize=t,this.buffer=new Hh(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()}},jG=class extends wS{constructor(e,t,n){super(e,t);this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=AG.alea(n||y.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 Ni=class{constructor(){this.size=null}batch(e,t=!0){let n=this;y.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),Tn(async()=>(await n.iterator()).columnMajorBatch(e,t,Bse),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,Tn(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){let t=this,n;return this.size===Infinity?n=Infinity:n=null,Tn(async()=>(await t.iterator()).filter(o=>B(()=>e(o))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){let t=this;return Tn(async()=>(await t.iterator()).map(n=>B(()=>e(n))),this.size)}mapAsync(e){let t=this;return Tn(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 Tn(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,Tn(async()=>{let o=Kh(async()=>({value:await t.iterator(),done:!1}));return DG(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,Tn(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=UG.alea(t||y.now().toString());return Tn(async()=>{let a=s.int32();return n&&(a+=s.int32()),(await o.iterator()).shuffle(e,a.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,Tn(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()}};Ni.MAX_BUFFER_SIZE=1e4;function Tn(r,e=null){return new class extends Ni{constructor(){super(...arguments);this.size=e}async iterator(){return r()}}}function qG(r){return Tn(async()=>xS(r),r.length)}function HG(r){if(!Zl(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 Tn(async()=>{let t=await lb(r,n=>{if(n instanceof Ni)return{value:n.iterator(),recurse:!1};if(Zl(n))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return $G(t,el.SHORTEST)},e)}function Bse(r){if(r===null)return null;let e=r[0];return TG(e)?{value:Vse(r),recurse:!1}:{value:null,recurse:!0}}function Vse(r){if(r.length===0)throw new Error("Can't make a batch of zero elements.");return r[0]instanceof Me?Ht(r):Nr(r)}var Xh=class extends Ni{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 ub='"',Yh=Symbol("out"),KG=Symbol("field"),cb=Symbol("quote"),_S=Symbol("quoteafterquote"),XG=Symbol("quoteinquote"),Zh=class extends Ni{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 Xh(e),t||(t={}),this.hasHeader=t.hasHeader!==!1,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(y.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&&y.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(y.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 a=this.fullColumnNames[s],i=this.columnConfigs?this.columnConfigs[a]:null;if(!(this.configuredColumnsOnly&&!i)){let l=t[s],u=null;if(l==="")if(i&&i.default!==void 0)u=i.default;else{if(i&&(i.required||i.isLabel))throw new Error(`Required column ${a} is empty in this line: ${e}`);u=void 0}else{let c=Number(l);if(isNaN(c))i&&i.dtype==="bool"?u=this.getBoolean(l):u=l;else if(!i||!i.dtype)u=c;else switch(i.dtype){case"float32":u=c;break;case"int32":u=Math.floor(c);break;case"bool":u=this.getBoolean(l);break;default:u=c}}i&&i.isLabel?o[a]=u:n[a]=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,a=Yh;for(let i=0;i<s;i++)switch(a){case Yh:switch(e.charAt(i)){case ub:o=i+1,a=cb;break;case this.delimiter:if(o=i+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),a=Yh;break;default:a=KG,o=i;break}break;case KG:switch(e.charAt(i)){case this.delimiter:n.push(e.substring(o,i)),a=Yh,o=i+1;break;default:}break;case cb:switch(e.charAt(i)){case ub:a=_S;break;default:}break;case _S:switch(e.charAt(i)){case this.delimiter:n.push(e.substring(o,i-1)),a=Yh,o=i+1;break;case ub:a=cb;break;default:a=XG;break}break;case XG:switch(e.charAt(i)){case ub:a=cb;break;default:}break;default:}if(a===_S?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 Jh=class extends er{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(W().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");let t=new Jh(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(y.sizeFromShape(t));return n.set(e,n.length-e.length),Nr(n,t)}};var Qh=class extends er{constructor(e,t){super();if(this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=Dt([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,a=(1-o)/2,i=s+n,l=o+a;this.cropBox=xi([a,s,l,i],[1,4])}else this.cropBox=xi([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(W().get("IS_NODE"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!t.resizeWidth||!t.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=t.resizeWidth,e.height=t.resizeHeight}let n=new Qh(e,t);return await n.start(),n}async start(){this.webcamConfig.facingMode&&y.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=zg.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 B(()=>{let t=dr(oe(e,"float32"),0),n;n=yi.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let o=n.shape;return L(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 eg=class{};var pb=class extends er{split(e){return new YG(this,e)}},YG=class extends pb{constructor(e,t){super();this.upstream=e,this.impl=new ZG(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},ZG=class extends Om{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 kS=class extends er{decodeUTF8(){return new QG(this)}},QG=class extends pb{constructor(e){super();this.upstream=e,this.impl=new eW(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},eW=class extends Om{constructor(e){super();if(this.upstream=e,W().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:t}=JG();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 W().get("IS_BROWSER")?n=this.decoder.decode(t,{stream:!0}):n=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0}};var tg=class extends kS{constructor(e,t={}){super();this.file=e,this.options=t,y.assert(e instanceof Uint8Array||(W().get("IS_BROWSER")?e instanceof File||e instanceof Blob:!1),()=>"FileChunkIterator only supports File, Blob and Uint8Array right now."),this.offset=t.offset||0,this.chunkSize=t.chunkSize||1024*1024}summary(){return`FileChunks ${this.file}`}async next(){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=i=>{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=i=>n(new Error("Aborted")),s.onerror=i=>n(new Error(i.type));let a=this.file.slice(this.offset,o);s.readAsArrayBuffer(a)}this.offset=o}),done:!1}}};async function tW(r,e={}){let t,n;typeof r=="string"?t=r:(t=r.url,n=Gse(r));let o=await y.fetch(t,n);if(o.ok){let s=new Uint8Array(await o.arrayBuffer());return new tg(s,e)}else throw new Error(o.statusText)}var Gse=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 mb(r){return typeof r=="string"&&r.substr(0,7)==="file://"}var rg=class extends eg{constructor(e,t={}){super();this.input=e,this.options=t}async iterator(){if(mb(this.input)&&W().get("IS_NODE")){let e=Lc("fs");this.input=e.readFileSync(this.input.substr(7))}return new tg(this.input,this.options)}};var ng=class extends eg{constructor(e,t={}){super();this.url=e,this.fileOptions=t}async iterator(){return mb(this.url)?new rg(this.url,this.fileOptions).iterator():tW(this.url,this.fileOptions)}};function rW(r,e={}){return new Zh(new ng(r),e)}function nW(r){let e=Kh(r);return Tn(async()=>e)}function oW(r){return Tn(async()=>{let e=await r();return Kh(()=>e.next())})}async function sW(r,e){return Qh.create(r,e)}async function iW(r){return Jh.create(r)}var aW="3.7.0";var OKt={tfjs:(Hm==null?void 0:Hm.version)||void 0,"tfjs-core":(Km==null?void 0:Km.version)||void 0,"tfjs-data":(Xm==null?void 0:Xm.version)||void 0,"tfjs-layers":(Ym==null?void 0:Ym.version)||void 0,"tfjs-converter":(Zm==null?void 0:Zm.version)||void 0,"tfjs-backend-cpu":Mk||void 0,"tfjs-backend-webgl":Hv||void 0,"tfjs-backend-wasm":EC||void 0};export{Js as Abs,Ri as Acos,Fi as Acosh,qu as AdadeltaOptimizer,Hu as AdagradOptimizer,Ku as AdamOptimizer,Xu as AdamaxOptimizer,jn as Add,$o as AddN,Oi as All,Pi as Any,Ro as ArgMax,ll as ArgMin,Mi as Asin,Li as Asinh,zi as Atan,Vi as Atan2,Bi as Atanh,Fo as AvgPool,ul as AvgPool3D,jc as AvgPool3DGrad,Wc as AvgPoolGrad,fy as BackendWasm,Oo as BatchMatMul,cl as BatchToSpaceND,Uc as Bincount,x1 as BroadcastTo,DI as Callback,WC as CallbackList,to as Cast,Po as Ceil,ro as ClipByValue,qc as Complex,pl as ComplexAbs,Qs as Concat,Mo as Conv2D,Hc as Conv2DBackpropFilter,Lo as Conv2DBackpropInput,ml as Conv3D,Kc as Conv3DBackpropFilterV2,Xc as Conv3DBackpropInputV2,zo as Cos,Gi as Cosh,Wi as CropAndResize,Bo as Cumsum,UC as CustomCallback,al as DataStorage,Yc as DenseBincount,ji as DepthToSpace,Vo as DepthwiseConv2dNative,Zc as DepthwiseConv2dNativeBackpropFilter,Jc as DepthwiseConv2dNativeBackpropInput,Qc as Diag,fl as Dilation2D,nf as Dilation2DBackpropFilter,rf as Dilation2DBackpropInput,Gw as ENV,$I as EarlyStopping,ep as Einsum,Ui as Elu,tp as EluGrad,Ng as Environment,Hi as Equal,qi as Erf,Wo as Exp,ei as ExpandDims,Ki as Expm1,rp as FFT,dl as Fill,Xi as FlipLeftRight,jo as Floor,Uo as FloorDiv,of as FromPixels,qo as FusedBatchNorm,mi as FusedConv2D,fi as FusedDepthwiseConv2D,qx as GPGPUContext,Yi as GatherNd,ti as GatherV2,lS as GraphModel,Zi as Greater,Ho as GreaterEqual,jC as History,np as IFFT,no as Identity,op as Imag,St as InputSpec,Ji as IsFinite,Qi as IsInf,ea as IsNan,Xs as KernelBackend,hl as LRN,ip as LRNGrad,Ny as LayerVariable,Jn as LayersModel,Ko as LeakyRelu,ta as Less,ra as LessEqual,sp as LinSpace,Xo as Log,na as Log1p,y1 as LogSoftmax,oa as LogicalAnd,iu as LogicalNot,au as LogicalOr,Qu as MathBackendCPU,lc as MathBackendWebGL,Yo as Max,Jo as MaxPool,gl as MaxPool3D,lp as MaxPool3DGrad,ap as MaxPoolGrad,up as MaxPoolWithArgmax,Zo as Maximum,Qo as Mean,es as Min,ts as Minimum,rs as MirrorPad,sa as Mod,Yu as MomentumOptimizer,cp as Multinomial,ns as Multiply,ri as Neg,aa as NonMaxSuppressionV3,la as NonMaxSuppressionV4,ua as NonMaxSuppressionV5,ia as NotEqual,H1 as OP_SCOPE_SUFFIX,os as OneHot,ni as OnesLike,Ur as Optimizer,oi as Pack,ss as PadV2,Xse as Pool,is as Pow,as as Prelu,ca as Prod,Zu as RMSPropOptimizer,Bn as RNN,xl as Range,Jw as Rank,pp as Real,Go as RealDiv,pa as Reciprocal,Kt as Reduction,ls as Relu,cs as Relu6,si as Reshape,us as ResizeBilinear,fp as ResizeBilinearGrad,yl as ResizeNearestNeighbor,mp as ResizeNearestNeighborGrad,ps as Reverse,wa as RotateWithOffset,ms as Round,fs as Rsqrt,za as SGDOptimizer,ma as ScatterNd,ii as Select,fa as Selu,Ja as Sequential,hs as Sigmoid,ha as Sign,ds as Sin,da as Sinh,ai as Slice,ys as Softmax,ga as Softplus,bl as SpaceToBatchND,dp as SparseFillEmptyRows,hp as SparseReshape,gp as SparseSegmentMean,xp as SparseSegmentSum,yp as SparseToDense,li as SplitV,gs as Sqrt,wl as Square,bs as SquaredDifference,oo as Step,xa as StridedSlice,bp as StringNGrams,wp as StringSplit,_p as StringToHashBucketFast,ws as Sub,xs as Sum,mn as SymbolicTensor,_s as Tan,ks as Tanh,Me as Tensor,ct as TensorBuffer,Un as Tile,ya as TopK,ba as Transform,vs as Transpose,kp as Unique,ui as Unpack,_l as UnsortedSegmentSum,Cl as Variable,ci as ZerosLike,pi as _FusedMatMul,Tt as abs,hf as acos,gf as acosh,J as add,S_ as addN,bu as all,Nl as any,Tl as argMax,xf as argMin,yf as asin,bf as asinh,wf as atan,_f as atan2,kf as atanh,Sa as avgPool,vf as avgPool3d,WT as backend,I as backend_util,_U as basicLSTMCell,uo as batchNorm,A_ as batchNorm2d,D_ as batchNorm3d,$_ as batchNorm4d,Na as batchToSpaceND,Cf as bincount,vNe as booleanMaskAsync,Ta as broadcastTo,zg as browser,Ie as buffer,ese as callbacks,oe as cast,If as ceil,fr as clipByValue,qn as clone,Fn as complex,et as concat,R_ as concat1d,F_ as concat2d,O_ as concat3d,P_ as concat4d,NB as constraints,ku as conv1d,on as conv2d,vu as conv2dTranspose,Sf as conv3d,M_ as conv3dTranspose,tie as copyRegisteredKernels,Ea as cos,Cu as cosh,rx as cosineWindow,Iu as cumsum,sn as customGrad,vS as data,L_ as denseBincount,I_ as deprecationWarn,Nf as depthToSpace,Es as depthwiseConv2d,rse as deregisterOp,gu as device_util,XU as diag,Tf as dilation2d,Oue as disableDeprecationWarnings,De as dispose,Pue as disposeVariables,ue as div,Ef as divNoNan,z_ as dot,fE as dropout,B_ as einsum,As as elu,Fue as enableDebugMode,Rue as enableProdMode,dE as enclosingPowerOfTwo,Ns as engine,W as env,On as equal,Af as erf,nr as exp,dr as expandDims,Df as expm1,Pp as eye,Ma as fft,Ds as fill,Gue as findBackend,Wue as findBackendFactory,$s as floor,yu as floorDiv,yR as forceHalfFloat,ho as fused,co as gather,pE as gatherND,Bg as gather_util,Bue as getBackend,Uw as getGradient,af as getKernel,Tg as getKernelsForBackend,f$ as gpgpu_util,Iq as grad,Sq as grads,qt as greater,_n as greaterEqual,gi as ifft,Su as imag,yi as image,R1e as inTopKAsync,HB as initializers,eI as input,Or as io,zu as irfft,V_ as isFinite,G_ as isInf,$f as isNaN,Rt as keep,zr as kernel_impls,TV as layers,Aa as leakyRelu,Nu as less,kn as lessEqual,JE as linalg,W_ as linspace,Ase as loadGraphModel,mne as loadLayersModel,Rf as localResponseNormalization,hr as log,Tu as log1p,j_ as logSigmoid,Eu as logSoftmax,Of as logSumExp,_r as logicalAnd,Da as logicalNot,Au as logicalOr,K_ as logicalXor,vFe as losses,Be as matMul,IT as math,Er as max,$a as maxPool,Pf as maxPool3d,X_ as maxPoolWithArgmax,an as maximum,ht as mean,df as memory,Kq as meshgrid,EV as metrics,El as min,Rs as minimum,Mf as mirrorPad,Lf as mod,cne as model,AV as models,Mp as moments,XNe as movingAverage,P as mul,rH as multiRNNCell,Y_ as multinomial,Ke as neg,Yf as nextFrame,Vp as norm,fo as notEqual,Ss as oneHot,or as ones,ur as onesLike,S as op,aH as outerProduct,Wr as pad,cH as pad1d,mH as pad2d,dH as pad3d,gH as pad4d,Z_ as pool,jr as pow,Fa as prelu,g_ as print,Du as prod,Mue as profile,IH as rand,RH as randomGamma,Jg as randomNormal,Fs as randomUniform,Oa as range,zue as ready,Al as real,zf as reciprocal,Rp as registerBackend,fne as registerCallbackConstructor,b1 as registerGradient,lu as registerKernel,tse as registerOp,DV as regularizers,Mr as relu,Ru as relu6,Vue as removeBackend,L as reshape,Jt as reverse,GH as reverse1d,jH as reverse2d,qH as reverse3d,KH as reverse4d,La as rfft,Fu as round,Ou as rsqrt,pe as scalar,uE as scatterND,Gg as scatter_util,Pu as selu,Bf as separableConv2d,pne as sequential,Q as serialization,W4 as setBackend,jue as setPlatform,Mte as setWasmPath,Lte as setWasmPaths,Jk as setWebGLContext,lk as setdiff1dAsync,Tx as shared,Pr as sigmoid,Vf as sign,ZRe as signal,Mu as sin,Lu as sinh,Fe as slice,Gf as slice1d,Qg as slice2d,Wf as slice3d,zp as slice4d,lr as slice_util,Pa as softmax,po as softplus,Ra as spaceToBatchND,Xf as sparse,tx as sparseToDense,qRe as spectral,sr as split,xt as sqrt,Le as square,Bu as squaredDifference,Pn as squeeze,Ht as stack,Os as step,jf as stridedSlice,mx as string,ce as sub,de as sum,du as sumOutType,Uf as tan,Ts as tanh,Nr as tensor,Dt as tensor1d,xi as tensor2d,w_ as tensor3d,wK as tensor4d,_K as tensor5d,kK as tensor6d,lo as tensor_util,GT as test_util,B as tidy,Kn as tile,Lue as time,qf as topk,Ju as train,qe as transpose,Vu as truncatedNormal,Bp as unique,eie as unregisterGradient,Qse as unregisterKernel,Hf as unsortedSegmentSum,gr as unstack,mr as upcastType,y as util,Nq as valueAndGrad,Tq as valueAndGrads,uk as variable,Kg as variableGrads,OKt as version,Dse as version_converter,G4 as version_core,Mk as version_cpu,Ud as version_layers,EC as version_wasm,Hv as version_webgl,bJe as webgl,m$ as webgl_util,Ct as where,Kf as whereAsync,gt as zeros,Se 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 See the LICENSE file. */
|
|
//# sourceMappingURL=tfjs.esm.js.map
|