4224 lines
1.0 MiB
4224 lines
1.0 MiB
|
|
/*
|
|
Face-API
|
|
homepage: <https://github.com/vladmandic/face-api>
|
|
author: <https://github.com/vladmandic>'
|
|
*/
|
|
|
|
var LB=Object.create,Lh=Object.defineProperty,zB=Object.getPrototypeOf,BB=Object.prototype.hasOwnProperty,VB=Object.getOwnPropertyNames,GB=Object.getOwnPropertyDescriptor;var xI=r=>Lh(r,"__esModule",{value:!0});var Br=(r,e)=>()=>(e||(e={exports:{}},r(e.exports,e)),e.exports),et=(r,e)=>{xI(r);for(var t in e)Lh(r,t,{get:e[t],enumerable:!0})},WB=(r,e,t)=>{if(xI(r),e&&typeof e=="object"||typeof e=="function")for(let o of VB(e))!BB.call(r,o)&&o!=="default"&&Lh(r,o,{get:()=>e[o],enumerable:!(t=GB(e,o))||t.enumerable});return r},Sc=r=>r&&r.__esModule?r:WB(Lh(r!=null?LB(zB(r)):{},"default",{value:r,enumerable:!0}),r);var rN=Br(()=>{});var ON=Br((FN,S_)=>{(function(r,e,t){function o(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 n(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 o(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"&&n(c,u),p.state=function(){return n(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})(FN,typeof S_=="object"&&S_,typeof define=="function"&&define)});var MN=Br((PN,T_)=>{(function(r,e,t){function o(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 n(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 o(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"&&n(u,l),c.state=function(){return n(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xor128=s})(PN,typeof T_=="object"&&T_,typeof define=="function"&&define)});var zN=Br((LN,E_)=>{(function(r,e,t){function o(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 n(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 o(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"&&n(u,l),c.state=function(){return n(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xorwow=s})(LN,typeof E_=="object"&&E_,typeof define=="function"&&define)});var VN=Br((BN,A_)=>{(function(r,e,t){function o(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 n(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 o(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&&n(u,l),c.state=function(){return n(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xorshift7=s})(BN,typeof A_=="object"&&A_,typeof define=="function"&&define)});var WN=Br((GN,D_)=>{(function(r,e,t){function o(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 n(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 o(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&&n(u,l),c.state=function(){return n(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.xor4096=s})(GN,typeof D_=="object"&&D_,typeof define=="function"&&define)});var jN=Br((UN,$_)=>{(function(r,e,t){function o(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 n(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 o(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"&&n(u,l),c.state=function(){return n(l,{})}),c}e&&e.exports?e.exports=s:t&&t.amd?t(function(){return s}):this.tychei=s})(UN,typeof $_=="object"&&$_,typeof define=="function"&&define)});var HN=Br(()=>{});var qN=Br((Dxe,ag)=>{(function(r,e){var t=this,o=256,n=6,s=52,a="random",i=e.pow(o,n),l=e.pow(2,s),u=l*2,c=o-1,p;function m(_,w,v){var $=[];w=w==!0?{entropy:!0}:w||{};var A=g(h(w.entropy?[_,b(r)]:_==null?x():_,3),$),R=new f($),M=function(){for(var z=R.g(n),W=i,U=0;z<l;)z=(z+U)*o,W*=o,U=R.g(1);for(;z>=u;)z/=2,W/=2,U>>>=1;return(z+U)/W};return M.int32=function(){return R.g(4)|0},M.quick=function(){return R.g(4)/4294967296},M.double=M,g(b(R.S),r),(w.pass||v||function(z,W,U,q){return q&&(q.S&&d(q,R),z.state=function(){return d(R,{})}),U?(e[a]=z,W):z})(M,A,"global"in w?w.global:this==e,w.state)}e["seed"+a]=m;function f(_){var w,v=_.length,$=this,A=0,R=$.i=$.j=0,M=$.S=[];for(v||(_=[v++]);A<o;)M[A]=A++;for(A=0;A<o;A++)M[A]=M[R=c&R+_[A%v]+(w=M[A])],M[R]=w;($.g=function(z){for(var W,U=0,q=$.i,Z=$.j,X=$.S;z--;)W=X[q=c&q+1],U=U*o+X[c&(X[q]=X[Z=c&Z+W])+(X[Z]=W)];return $.i=q,$.j=Z,U})(o)}function d(_,w){return w.i=_.i,w.j=_.j,w.S=_.S.slice(),w}function h(_,w){var v=[],$=typeof _,A;if(w&&$=="object")for(A in _)try{v.push(h(_[A],w-1))}catch(R){}return v.length?v:$=="string"?_:_+"\0"}function g(_,w){for(var v=_+"",$,A=0;A<v.length;)w[c&A]=c&($^=w[c&A]*19)+v.charCodeAt(A++);return b(w)}function x(){try{var _;return p&&(_=p.randomBytes)?_=_(o):(_=new Uint8Array(o),(t.crypto||t.msCrypto).getRandomValues(_)),b(_)}catch($){var w=t.navigator,v=w&&w.plugins;return[+new Date,t,v,t.screen,b(r)]}}function b(_){return String.fromCharCode.apply(0,_)}if(g(e.random(),r),typeof ag=="object"&&ag.exports){ag.exports=m;try{p=HN()}catch(_){}}else typeof define=="function"&&define.amd&&define(function(){return m})})([],Math)});var jm=Br(($xe,KN)=>{var f4=ON(),d4=MN(),h4=zN(),g4=VN(),x4=WN(),y4=jN(),Ru=qN();Ru.alea=f4;Ru.xor128=d4;Ru.xorwow=h4;Ru.xorshift7=g4;Ru.xor4096=x4;Ru.tychei=y4;KN.exports=Ru});var FE=Br(()=>{});var Kp=Br(()=>{});var gz=Br(()=>{});var xz=Br(()=>{});var yz=Br((Yx,tI)=>{var rI=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 K.buffer!=qe&&wr(K.buffer),Ft}function o(){return K.buffer!=qe&&wr(K.buffer),po}function n(){return K.buffer!=qe&&wr(K.buffer),_r}function s(){return K.buffer!=qe&&wr(K.buffer),Bo}function a(){return K.buffer!=qe&&wr(K.buffer),fo}var i=typeof e!="undefined"?e:{},l={},u;for(u in i)i.hasOwnProperty(u)&&(l[u]=i[u]);var c=[],p="./this.program",m=function(I,D){throw D},f=!1,d=!1,h=!1,g=!1;f=typeof window=="object",d=typeof importScripts=="function",h=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g=!f&&!h&&!d;var x=i.ENVIRONMENT_IS_PTHREAD||!1;x&&(qe=i.buffer,ts=i.DYNAMIC_BASE,So=i.DYNAMICTOP_PTR);var b="";function _(I){return i.locateFile?i.locateFile(I,b):b+I}var w,v,$,A,R,M;if(h){d?b=Kp().dirname(b)+"/":b=__dirname+"/",w=function(D,P){return R||(R=require("fs")),M||(M=Kp()),D=M.normalize(D),R.readFileSync(D,P?null:"utf8")},$=function(D){var P=w(D,!0);return P.buffer||(P=new Uint8Array(P)),ge(P.buffer),P},process.argv.length>1&&(p=process.argv[1].replace(/\\/g,"/")),c=process.argv.slice(2),process.on("uncaughtException",function(I){if(!(I instanceof hI))throw I}),process.on("unhandledRejection",ea),m=function(I){process.exit(I)},i.inspect=function(){return"[Emscripten Module object]"};var z;try{z=gz()}catch(I){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),I}Worker=z.Worker}else g?(typeof read!="undefined"&&(w=function(D){return read(D)}),$=function(D){var P;return typeof readbuffer=="function"?new Uint8Array(readbuffer(D)):(P=read(D,"binary"),ge(typeof P=="object"),P)},typeof scriptArgs!="undefined"?c=scriptArgs:typeof arguments!="undefined"&&(c=arguments),typeof quit=="function"&&(m=function(I){quit(I)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(f||d)&&(d?b=self.location.href:document.currentScript&&(b=document.currentScript.src),typeof r!="undefined"&&r&&(b=r),b.indexOf("blob:")!==0?b=b.substr(0,b.lastIndexOf("/")+1):b="",h?(w=function(D,P){return R||(R=require("fs")),M||(M=Kp()),D=M.normalize(D),R.readFileSync(D,P?null:"utf8")},$=function(D){var P=w(D,!0);return P.buffer||(P=new Uint8Array(P)),ge(P.buffer),P}):(w=function(D){var P=new XMLHttpRequest;return P.open("GET",D,!1),P.send(null),P.responseText},d&&($=function(D){var P=new XMLHttpRequest;return P.open("GET",D,!1),P.responseType="arraybuffer",P.send(null),new Uint8Array(P.response)}),v=function(D,P,j){var me=new XMLHttpRequest;me.open("GET",D,!0),me.responseType="arraybuffer",me.onload=function(){if(me.status==200||me.status==0&&me.response){P(me.response);return}j()},me.onerror=j,me.send(null)}),A=function(I){document.title=I});h&&typeof performance=="undefined"&&(performance=xz().performance);var W=i.print||console.log.bind(console),U=i.printErr||console.warn.bind(console);for(u in l)l.hasOwnProperty(u)&&(i[u]=l[u]);l=null,i.arguments&&(c=i.arguments),i.thisProgram&&(p=i.thisProgram),i.quit&&(m=i.quit);var q=Atomics.load,Z=Atomics.store,X=Atomics.compareExchange,Y;i.wasmBinary&&(Y=i.wasmBinary);var te;i.noExitRuntime&&(te=i.noExitRuntime),typeof WebAssembly!="object"&&U("no native wasm support detected");var K,re=new WebAssembly.Table({initial:169,maximum:169+0,element:"anyfunc"}),ie,se=0,pe=0,ae=!1,xe=0;function ge(I,D){I||ea("Assertion failed: "+D)}function _e(I){var D=i["_"+I];return ge(D,"Cannot call unknown function "+I+", make sure it is exported"),D}function ke(I,D,P,j,me){var he={string:function(go){var Xa=0;if(go!=null&&go!==0){var pm=(go.length<<2)+1;Xa=vc(pm),ut(go,Xa,pm)}return Xa},array:function(go){var Xa=vc(go.length);return kt(go,Xa),Xa}};function fe(go){return D==="string"?Re(go):D==="boolean"?Boolean(go):go}var Se=_e(I),mt=[],pr=0;if(j)for(var Ar=0;Ar<j.length;Ar++){var Ic=he[P[Ar]];Ic?(pr===0&&(pr=lm()),mt[Ar]=Ic(j[Ar])):mt[Ar]=j[Ar]}var cm=Se.apply(null,mt);return cm=fe(cm),pr!==0&&Cc(pr),cm}function De(I,D,P,j){P=P||[];var me=P.every(function(fe){return fe==="number"}),he=D!=="string";return he&&me&&!j?_e(I):function(){return ke(I,D,P,arguments,j)}}function $e(I,D,P){for(var j=D+P,me="";!(D>=j);){var he=I[D++];if(!he)return me;if(!(he&128)){me+=String.fromCharCode(he);continue}var fe=I[D++]&63;if((he&224)==192){me+=String.fromCharCode((he&31)<<6|fe);continue}var Se=I[D++]&63;if((he&240)==224?he=(he&15)<<12|fe<<6|Se:he=(he&7)<<18|fe<<12|Se<<6|I[D++]&63,he<65536)me+=String.fromCharCode(he);else{var mt=he-65536;me+=String.fromCharCode(55296|mt>>10,56320|mt&1023)}}return me}function Re(I,D){return I?$e(o(),I,D):""}function He(I,D,P,j){if(!(j>0))return 0;for(var me=P,he=P+j-1,fe=0;fe<I.length;++fe){var Se=I.charCodeAt(fe);if(Se>=55296&&Se<=57343){var mt=I.charCodeAt(++fe);Se=65536+((Se&1023)<<10)|mt&1023}if(Se<=127){if(P>=he)break;D[P++]=Se}else if(Se<=2047){if(P+1>=he)break;D[P++]=192|Se>>6,D[P++]=128|Se&63}else if(Se<=65535){if(P+2>=he)break;D[P++]=224|Se>>12,D[P++]=128|Se>>6&63,D[P++]=128|Se&63}else{if(P+3>=he)break;D[P++]=240|Se>>18,D[P++]=128|Se>>12&63,D[P++]=128|Se>>6&63,D[P++]=128|Se&63}}return D[P]=0,P-me}function ut(I,D,P){return He(I,o(),D,P)}function wt(I){for(var D=0,P=0;P<I.length;++P){var j=I.charCodeAt(P);j>=55296&&j<=57343&&(j=65536+((j&1023)<<10)|I.charCodeAt(++P)&1023),j<=127?++D:j<=2047?D+=2:j<=65535?D+=3:D+=4}return D}function kt(I,D){t().set(I,D)}var pt=65536;function vt(I,D){return I%D>0&&(I+=D-I%D),I}var qe,Ft,po,Zt,mo,_r,Bo,Jr,fo;function wr(I){qe=I,i.HEAP8=Ft=new Int8Array(I),i.HEAP16=Zt=new Int16Array(I),i.HEAP32=_r=new Int32Array(I),i.HEAPU8=po=new Uint8Array(I),i.HEAPU16=mo=new Uint16Array(I),i.HEAPU32=Bo=new Uint32Array(I),i.HEAPF32=Jr=new Float32Array(I),i.HEAPF64=fo=new Float64Array(I)}var No=5256480,Vo=No,Qr=13600,ts=5256480,So=12672,gc=i.INITIAL_MEMORY||16777216;if(x)K=i.wasmMemory,qe=i.buffer;else if(i.wasmMemory)K=i.wasmMemory;else if(K=new WebAssembly.Memory({initial:gc/pt,maximum:2147483648/pt,shared:!0}),!(K.buffer instanceof SharedArrayBuffer))throw U("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"),h&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");K&&(qe=K.buffer),gc=qe.byteLength,wr(qe),x||(n()[So>>2]=ts);function rs(I){for(;I.length>0;){var D=I.shift();if(typeof D=="function"){D(i);continue}var P=D.func;typeof P=="number"?D.arg===void 0?i.dynCall_v(P):i.dynCall_vi(P,D.arg):P(D.arg===void 0?null:D.arg)}}var Ji=[],$l=[],ey=[],Xp=[],xh=[],Yp=!1;x&&(Yp=!0);function Go(){if(!x){if(i.preRun)for(typeof i.preRun=="function"&&(i.preRun=[i.preRun]);i.preRun.length;)oy(i.preRun.shift());rs(Ji)}}function yh(){Yp=!0,rs($l)}function ty(){x||rs(ey)}function ry(){if(!x){if(i.postRun)for(typeof i.postRun=="function"&&(i.postRun=[i.postRun]);i.postRun.length;)Rl(i.postRun.shift());rs(xh)}}function oy(I){Ji.unshift(I)}function Rl(I){xh.unshift(I)}var xc=Math.ceil,ny=Math.floor,Qi=0,Zp=null,Fl=null;function sy(I){ge(!x,"addRunDependency cannot be used in a pthread worker"),Qi++,i.monitorRunDependencies&&i.monitorRunDependencies(Qi)}function iy(I){if(Qi--,i.monitorRunDependencies&&i.monitorRunDependencies(Qi),Qi==0&&(Zp!==null&&(clearInterval(Zp),Zp=null),Fl)){var D=Fl;Fl=null,D()}}i.preloadedImages={},i.preloadedAudios={};function ea(I){throw i.onAbort&&i.onAbort(I),x&&console.error("Pthread aborting at "+new Error().stack),I+="",W(I),U(I),ae=!0,xe=1,I="abort("+I+"). Build with -s ASSERTIONS=1 for more info.",new WebAssembly.RuntimeError(I)}function Jp(I,D){return String.prototype.startsWith?I.startsWith(D):I.indexOf(D)===0}var ay="data:application/octet-stream;base64,";function bh(I){return Jp(I,ay)}var ly="file://";function _h(I){return Jp(I,ly)}var Wo="tfjs-backend-wasm-threaded-simd.wasm";bh(Wo)||(Wo=_(Wo));function wh(){try{if(Y)return new Uint8Array(Y);if($)return $(Wo);throw"both async and sync fetching of the wasm failed"}catch(I){ea(I)}}function uy(){return!Y&&(f||d)&&typeof fetch=="function"&&!_h(Wo)?fetch(Wo,{credentials:"same-origin"}).then(function(I){if(!I.ok)throw"failed to load wasm binary file at '"+Wo+"'";return I.arrayBuffer()}).catch(function(){return wh()}):new Promise(function(I,D){I(wh())})}function cy(){var I={a:tb};function D(fe,Se){var mt=fe.exports;if(i.asm=mt,ie=Se,!x){var pr=we.unusedWorkers.length;we.unusedWorkers.forEach(function(Ar){we.loadWasmModuleToWorker(Ar,function(){--pr||iy("wasm-instantiate")})})}}x||sy("wasm-instantiate");function P(fe){D(fe.instance,fe.module)}function j(fe){return uy().then(function(Se){return WebAssembly.instantiate(Se,I)}).then(fe,function(Se){U("failed to asynchronously prepare wasm: "+Se),ea(Se)})}function me(){if(!Y&&typeof WebAssembly.instantiateStreaming=="function"&&!bh(Wo)&&!_h(Wo)&&typeof fetch=="function")fetch(Wo,{credentials:"same-origin"}).then(function(fe){var Se=WebAssembly.instantiateStreaming(fe,I);return Se.then(P,function(mt){U("wasm streaming compile failed: "+mt),U("falling back to ArrayBuffer instantiation"),j(P)})});else return j(P)}if(i.instantiateWasm)try{var he=i.instantiateWasm(I,D);return he}catch(fe){return U("Module.instantiateWasm callback failed with error: "+fe),!1}return me(),{}}var py={};function my(){we.initRuntime()}x||$l.push({func:function(){tm()}});var kh=0,vh=0,Ch=0;function yc(I,D,P){I=I|0,D=D|0,P=P|0,kh=I,Ch=D,vh=P}i.__register_pthread_ptr=yc;var Qp={EPERM:63,ENOENT:44,ESRCH:71,EINTR:27,EIO:29,ENXIO:60,E2BIG:1,ENOEXEC:45,EBADF:8,ECHILD:12,EAGAIN:6,EWOULDBLOCK:6,ENOMEM:48,EACCES:2,EFAULT:21,ENOTBLK:105,EBUSY:10,EEXIST:20,EXDEV:75,ENODEV:43,ENOTDIR:54,EISDIR:31,EINVAL:28,ENFILE:41,EMFILE:33,ENOTTY:59,ETXTBSY:74,EFBIG:22,ENOSPC:51,ESPIPE:70,EROFS:69,EMLINK:34,EPIPE:64,EDOM:18,ERANGE:68,ENOMSG:49,EIDRM:24,ECHRNG:106,EL2NSYNC:156,EL3HLT:107,EL3RST:108,ELNRNG:109,EUNATCH:110,ENOCSI:111,EL2HLT:112,EDEADLK:16,ENOLCK:46,EBADE:113,EBADR:114,EXFULL:115,ENOANO:104,EBADRQC:103,EBADSLT:102,EDEADLOCK:16,EBFONT:101,ENOSTR:100,ENODATA:116,ETIME:117,ENOSR:118,ENONET:119,ENOPKG:120,EREMOTE:121,ENOLINK:47,EADV:122,ESRMNT:123,ECOMM:124,EPROTO:65,EMULTIHOP:36,EDOTDOT:125,EBADMSG:9,ENOTUNIQ:126,EBADFD:127,EREMCHG:128,ELIBACC:129,ELIBBAD:130,ELIBSCN:131,ELIBMAX:132,ELIBEXEC:133,ENOSYS:52,ENOTEMPTY:55,ENAMETOOLONG:37,ELOOP:32,EOPNOTSUPP:138,EPFNOSUPPORT:139,ECONNRESET:15,ENOBUFS:42,EAFNOSUPPORT:5,EPROTOTYPE:67,ENOTSOCK:57,ENOPROTOOPT:50,ESHUTDOWN:140,ECONNREFUSED:14,EADDRINUSE:3,ECONNABORTED:13,ENETUNREACH:40,ENETDOWN:38,ETIMEDOUT:73,EHOSTDOWN:142,EHOSTUNREACH:23,EINPROGRESS:26,EALREADY:7,EDESTADDRREQ:17,EMSGSIZE:35,EPROTONOSUPPORT:66,ESOCKTNOSUPPORT:137,EADDRNOTAVAIL:4,ENETRESET:39,EISCONN:30,ENOTCONN:53,ETOOMANYREFS:141,EUSERS:136,EDQUOT:19,ESTALE:72,ENOTSUP:138,ENOMEDIUM:148,EILSEQ:25,EOVERFLOW:61,ECANCELED:11,ENOTRECOVERABLE:56,EOWNERDEAD:62,ESTRPIPE:135},bc=13584;function _c(I,D){if(I<=0||I>t().length||I&!0||D<0)return-28;if(D==0)return 0;D>=2147483647&&(D=Infinity);var P=Atomics.load(n(),bc>>2),j=0;if(P==I){var me=Atomics.compareExchange(n(),bc>>2,P,0);if(me==P&&(--D,j=1,D<=0))return 1}var he=Atomics.notify(n(),I>>2,D);if(he>=0)return he+j;throw"Atomics.notify returned an unexpected value "+he}i._emscripten_futex_wake=_c;function fy(I){if(x)throw"Internal Error! _kill_thread() can only ever be called from main application thread!";if(!I)throw"Internal Error! Null pthread_ptr in _kill_thread!";n()[I+12>>2]=0;var D=we.pthreads[I];D.worker.terminate(),we.freeThreadData(D),we.runningWorkers.splice(we.runningWorkers.indexOf(D.worker),1),D.worker.pthread=void 0}function dy(I){if(x)throw"Internal Error! _cancel_thread() can only ever be called from main application thread!";if(!I)throw"Internal Error! Null pthread_ptr in _cancel_thread!";var D=we.pthreads[I];D.worker.postMessage({cmd:"cancel"})}function hy(I){if(x)throw"Internal Error! _cleanup_thread() can only ever be called from main application thread!";if(!I)throw"Internal Error! Null pthread_ptr in _cleanup_thread!";n()[I+12>>2]=0;var D=we.pthreads[I];if(D){var P=D.worker;we.returnWorkerToPool(P)}}var we={MAIN_THREAD_ID:1,mainThreadInfo:{schedPolicy:0,schedPrio:0},unusedWorkers:[],runningWorkers:[],initRuntime:function(){yc(we.mainThreadBlock,!d,1),pI(we.mainThreadBlock)},initMainThreadBlock:function(){for(var I=8,D=0;D<I;++D)we.allocateUnusedWorker();we.mainThreadBlock=12832;for(var D=0;D<232/4;++D)s()[we.mainThreadBlock/4+D]=0;n()[we.mainThreadBlock+12>>2]=we.mainThreadBlock;var P=we.mainThreadBlock+156;n()[P>>2]=P;for(var j=13072,D=0;D<128;++D)s()[j/4+D]=0;Atomics.store(s(),we.mainThreadBlock+104>>2,j),Atomics.store(s(),we.mainThreadBlock+40>>2,we.mainThreadBlock),Atomics.store(s(),we.mainThreadBlock+44>>2,42)},initWorker:function(){},pthreads:{},exitHandlers:null,setThreadStatus:function(){},runExitHandlers:function(){if(we.exitHandlers!==null){for(;we.exitHandlers.length>0;)we.exitHandlers.pop()();we.exitHandlers=null}x&&se&&cI()},threadExit:function(I){var D=Gs();D&&(Atomics.store(s(),D+4>>2,I),Atomics.store(s(),D+0>>2,1),Atomics.store(s(),D+60>>2,1),Atomics.store(s(),D+64>>2,0),we.runExitHandlers(),_c(D+0,2147483647),yc(0,0,0),se=0,x&&postMessage({cmd:"exit"}))},threadCancel:function(){we.runExitHandlers(),Atomics.store(s(),se+4>>2,-1),Atomics.store(s(),se+0>>2,1),_c(se+0,2147483647),se=pe=0,yc(0,0,0),postMessage({cmd:"cancelDone"})},terminateAllThreads:function(){for(var I in we.pthreads){var D=we.pthreads[I];D&&D.worker&&we.returnWorkerToPool(D.worker)}we.pthreads={};for(var P=0;P<we.unusedWorkers.length;++P){var j=we.unusedWorkers[P];j.terminate()}we.unusedWorkers=[];for(var P=0;P<we.runningWorkers.length;++P){var j=we.runningWorkers[P],D=j.pthread;we.freeThreadData(D),j.terminate()}we.runningWorkers=[]},freeThreadData:function(I){if(!!I){if(I.threadInfoStruct){var D=n()[I.threadInfoStruct+104>>2];n()[I.threadInfoStruct+104>>2]=0,am(D),am(I.threadInfoStruct)}I.threadInfoStruct=0,I.allocatedOwnStack&&I.stackBase&&am(I.stackBase),I.stackBase=0,I.worker&&(I.worker.pthread=null)}},returnWorkerToPool:function(I){delete we.pthreads[I.pthread.thread],we.unusedWorkers.push(I),we.runningWorkers.splice(we.runningWorkers.indexOf(I),1),we.freeThreadData(I.pthread),I.pthread=void 0},receiveObjectTransfer:function(I){},loadWasmModuleToWorker:function(I,D){I.onmessage=function(P){var j=P.data,me=j.cmd;if(I.pthread&&(we.currentProxiedOperationCallerThread=I.pthread.threadInfoStruct),j.targetThread&&j.targetThread!=Gs()){var he=we.pthreads[j.targetThread];he?he.worker.postMessage(P.data,j.transferList):console.error('Internal error! Worker sent a message "'+me+'" to target pthread '+j.targetThread+", but that thread no longer exists!"),we.currentProxiedOperationCallerThread=void 0;return}if(me==="processQueuedMainThreadWork")nb();else if(me==="spawnThread")Ah(P.data);else if(me==="cleanupThread")hy(j.thread);else if(me==="killThread")fy(j.thread);else if(me==="cancelThread")dy(j.thread);else if(me==="loaded")I.loaded=!0,D&&D(I),I.runPthread&&(I.runPthread(),delete I.runPthread);else if(me==="print")W("Thread "+j.threadId+": "+j.text);else if(me==="printErr")U("Thread "+j.threadId+": "+j.text);else if(me==="alert")alert("Thread "+j.threadId+": "+j.text);else if(me==="exit"){var fe=I.pthread&&Atomics.load(s(),I.pthread.thread+68>>2);fe&&we.returnWorkerToPool(I)}else me==="cancelDone"?we.returnWorkerToPool(I):me==="objectTransfer"?we.receiveObjectTransfer(P.data):P.data.target==="setimmediate"?I.postMessage(P.data):U("worker sent an unknown command "+me);we.currentProxiedOperationCallerThread=void 0},I.onerror=function(P){U("pthread sent an error! "+P.filename+":"+P.lineno+": "+P.message)},h&&(I.on("message",function(P){I.onmessage({data:P})}),I.on("error",function(P){I.onerror(P)}),I.on("exit",function(P){console.log("worker exited - TODO: update the worker queue?")})),I.postMessage({cmd:"load",urlOrBlob:i.mainScriptUrlOrBlob||r,wasmMemory:K,wasmModule:ie,DYNAMIC_BASE:ts,DYNAMICTOP_PTR:So})},allocateUnusedWorker:function(){var I=_("tfjs-backend-wasm-threaded-simd.worker.js");we.unusedWorkers.push(new Worker(I))},getNewWorker:function(){return we.unusedWorkers.length==0&&(we.allocateUnusedWorker(),we.loadWasmModuleToWorker(we.unusedWorkers[0])),we.unusedWorkers.length>0?we.unusedWorkers.pop():null},busySpinWait:function(I){for(var D=performance.now()+I;performance.now()<D;);}};function gy(I,D){No=Vo=I,Qr=D,Cc(I)}i.establishStackSpace=gy;function xy(){return te}i.getNoExitRuntime=xy;function yy(I,D,P,j){ea("Assertion failed: "+Re(I)+", at: "+[D?Re(D):"unknown filename",P,j?Re(j):"unknown function"])}function by(I,D){var P=_main(I,D)}var Ol;h?Ol=function(){var I=process.hrtime();return I[0]*1e3+I[1]/1e6}:x?Ol=function(){return performance.now()-i.__performance_now_clock_drift}:typeof dateNow!="undefined"?Ol=dateNow:Ol=function(){return performance.now()};function _y(I){return n()[aI()>>2]=I,I}function wy(I,D){if(x)return Ha(1,1,I,D);Xp.unshift({func:I,arg:D})}function ky(I,D){if(I==D)postMessage({cmd:"processQueuedMainThreadWork"});else if(x)postMessage({targetThread:I,cmd:"processThreadQueue"});else{var P=we.pthreads[I],j=P&&P.worker;if(!j)return;j.postMessage({cmd:"processThreadQueue"})}return 1}function vy(){ea()}function Cy(I,D){I=I|0,D=D|0}function Iy(I,D,P){if(I<=0||I>t().length||I&!0)return-28;if(d){var j=Atomics.wait(n(),I>>2,D,P);if(j==="timed-out")return-73;if(j==="not-equal")return-6;if(j==="ok")return 0;throw"Atomics.wait returned an unexpected value "+j}else{var me=Atomics.load(n(),I>>2);if(D!=me)return-6;var he=performance.now(),fe=he+P;Atomics.store(n(),bc>>2,I);for(var Se=I;I==Se;){if(he=performance.now(),he>fe)return-73;nb(),I=Atomics.load(n(),bc>>2)}return 0}}function Ny(){return Ch|0}function Sy(){return vh|0}function Ty(I,D,P){o().copyWithin(I,D,D+P)}function Ey(){return navigator.hardwareConcurrency}function Ha(I,D){for(var P=arguments.length-2,j=lm(),me=vc(P*8),he=me>>3,fe=0;fe<P;fe++)a()[he+fe]=arguments[2+fe];var Se=fI(I,P,me,D);return Cc(j),Se}var Pl=[];function wc(I,D){wc.array||(wc.array=[]);var P=wc.array;P.length=0;for(var j;j=o()[I++];)j===100||j===102?(D=D+7&~7,P.push(a()[D>>3]),D+=8):(D=D+3&~3,P.push(n()[D>>2]),D+=4);return P}function Ay(I,D,P){Pl.length=D;for(var j=P>>3,me=0;me<D;me++)Pl[me]=a()[j+me];var he=I<0,fe=he?py[-I-1]:eb[I];if(he){var Se=Pl[1],mt=Pl[2],pr=wc(Se,mt);return fe.apply(null,pr)}return fe.apply(null,Pl)}function Dy(){return o().length}function $y(I){try{return K.grow(I-qe.byteLength+65535>>>16),wr(K.buffer),1}catch(D){}}function Ry(I){I=I>>>0;var D=Dy();if(I<=D)return!1;var P=65536,j=2147483648;if(I>j)return!1;for(var me=16777216,he=1;he<=4;he*=2){var fe=D*(1+.2/he);fe=Math.min(fe,I+100663296);var Se=Math.min(j,vt(Math.max(me,I,fe),P)),mt=$y(Se);if(mt)return!0}return!1}var Ze={keyEvent:0,mouseEvent:0,wheelEvent:0,uiEvent:0,focusEvent:0,deviceOrientationEvent:0,deviceMotionEvent:0,fullscreenChangeEvent:0,pointerlockChangeEvent:0,visibilityChangeEvent:0,touchEvent:0,previousFullscreenElement:null,previousScreenX:null,previousScreenY:null,removeEventListenersRegistered:!1,removeAllEventListeners:function(){for(var I=Ze.eventHandlers.length-1;I>=0;--I)Ze._removeHandler(I);Ze.eventHandlers=[],Ze.deferredCalls=[]},registerRemoveEventListeners:function(){Ze.removeEventListenersRegistered||(Xp.push(Ze.removeAllEventListeners),Ze.removeEventListenersRegistered=!0)},deferredCalls:[],deferCall:function(I,D,P){function j(fe,Se){if(fe.length!=Se.length)return!1;for(var mt in fe)if(fe[mt]!=Se[mt])return!1;return!0}for(var me in Ze.deferredCalls){var he=Ze.deferredCalls[me];if(he.targetFunction==I&&j(he.argsList,P))return}Ze.deferredCalls.push({targetFunction:I,precedence:D,argsList:P}),Ze.deferredCalls.sort(function(fe,Se){return fe.precedence<Se.precedence})},removeDeferredCalls:function(I){for(var D=0;D<Ze.deferredCalls.length;++D)Ze.deferredCalls[D].targetFunction==I&&(Ze.deferredCalls.splice(D,1),--D)},canPerformEventHandlerRequests:function(){return Ze.inEventHandler&&Ze.currentEventHandler.allowsDeferredCalls},runDeferredCalls:function(){if(!!Ze.canPerformEventHandlerRequests())for(var I=0;I<Ze.deferredCalls.length;++I){var D=Ze.deferredCalls[I];Ze.deferredCalls.splice(I,1),--I,D.targetFunction.apply(null,D.argsList)}},inEventHandler:0,currentEventHandler:null,eventHandlers:[],removeAllHandlersOnTarget:function(I,D){for(var P=0;P<Ze.eventHandlers.length;++P)Ze.eventHandlers[P].target==I&&(!D||D==Ze.eventHandlers[P].eventTypeString)&&Ze._removeHandler(P--)},_removeHandler:function(I){var D=Ze.eventHandlers[I];D.target.removeEventListener(D.eventTypeString,D.eventListenerFunc,D.useCapture),Ze.eventHandlers.splice(I,1)},registerOrRemoveHandler:function(I){var D=function(me){++Ze.inEventHandler,Ze.currentEventHandler=I,Ze.runDeferredCalls(),I.handlerFunc(me),Ze.runDeferredCalls(),--Ze.inEventHandler};if(I.callbackfunc)I.eventListenerFunc=D,I.target.addEventListener(I.eventTypeString,D,I.useCapture),Ze.eventHandlers.push(I),Ze.registerRemoveEventListeners();else for(var P=0;P<Ze.eventHandlers.length;++P)Ze.eventHandlers[P].target==I.target&&Ze.eventHandlers[P].eventTypeString==I.eventTypeString&&Ze._removeHandler(P--)},queueEventHandlerOnThread_iiii:function(I,D,P,j,me){var he=lm(),fe=vc(12);n()[fe>>2]=P,n()[fe+4>>2]=j,n()[fe+8>>2]=me,sb(I,637534208,D,j,fe),Cc(he)},getTargetThreadForEventCallback:function(I){switch(I){case 1:return 0;case 2:return we.currentProxiedOperationCallerThread;default:return I}},getNodeNameForTarget:function(I){return I?I==window?"#window":I==screen?"#screen":I&&I.nodeName?I.nodeName:"":""},fullscreenEnabled:function(){return document.fullscreenEnabled||document.webkitFullscreenEnabled}};function Fy(I){var D=wt(I)+1,P=im(D);return ut(I,P,D),P}function Oy(I,D,P,j){var me=lm(),he=vc(12),fe=0;D&&(fe=Fy(D)),n()[he>>2]=fe,n()[he+4>>2]=P,n()[he+8>>2]=j,sb(I,657457152,0,fe,he),Cc(me)}function Py(I,D,P,j){D=D?Re(D):"",Oy(I,D,P,j)}function My(I){return I>2?Re(I):I}var Ly=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];function zy(I){I=My(I);var D=Ly[I]||(typeof document!="undefined"?document.querySelector(I):void 0);return D}function em(I){return zy(I)}function Ih(I,D,P){var j=em(I);if(!j)return-4;if(j.canvasSharedPtr&&(n()[j.canvasSharedPtr>>2]=D,n()[j.canvasSharedPtr+4>>2]=P),j.offscreenCanvas||!j.controlTransferredOffscreen){j.offscreenCanvas&&(j=j.offscreenCanvas);var me=!1;if(j.GLctxObject&&j.GLctxObject.GLctx){var he=j.GLctxObject.GLctx.getParameter(2978);me=he[0]===0&&he[1]===0&&he[2]===j.width&&he[3]===j.height}j.width=D,j.height=P,me&&j.GLctxObject.GLctx.viewport(0,0,D,P)}else if(j.canvasSharedPtr){var fe=n()[j.canvasSharedPtr+8>>2];return Py(fe,I,D,P),1}else return-4;return 0}function Nh(I,D,P){return x?Ha(2,1,I,D,P):Ih(I,D,P)}function By(I,D,P){var j=em(I);return j?Ih(I,D,P):Nh(I,D,P)}function Vy(I){I=I|0}function Gy(I,D){I=I|0,D=D|0}function Wy(I){var D=I.getExtension("ANGLE_instanced_arrays");if(D)return I.vertexAttribDivisor=function(P,j){D.vertexAttribDivisorANGLE(P,j)},I.drawArraysInstanced=function(P,j,me,he){D.drawArraysInstancedANGLE(P,j,me,he)},I.drawElementsInstanced=function(P,j,me,he,fe){D.drawElementsInstancedANGLE(P,j,me,he,fe)},1}function Uy(I){var D=I.getExtension("OES_vertex_array_object");if(D)return I.createVertexArray=function(){return D.createVertexArrayOES()},I.deleteVertexArray=function(P){D.deleteVertexArrayOES(P)},I.bindVertexArray=function(P){D.bindVertexArrayOES(P)},I.isVertexArray=function(P){return D.isVertexArrayOES(P)},1}function jy(I){var D=I.getExtension("WEBGL_draw_buffers");if(D)return I.drawBuffers=function(P,j){D.drawBuffersWEBGL(P,j)},1}var rt={counter:1,lastError:0,buffers:[],mappedBuffers:{},programs:[],framebuffers:[],renderbuffers:[],textures:[],uniforms:[],shaders:[],vaos:[],contexts:{},currentContext:null,offscreenCanvases:{},timerQueriesEXT:[],programInfos:{},stringCache:{},unpackAlignment:4,init:function(){for(var I=new Float32Array(rt.MINI_TEMP_BUFFER_SIZE),D=0;D<rt.MINI_TEMP_BUFFER_SIZE;D++)rt.miniTempBufferFloatViews[D]=I.subarray(0,D+1);for(var P=new Int32Array(rt.MINI_TEMP_BUFFER_SIZE),D=0;D<rt.MINI_TEMP_BUFFER_SIZE;D++)rt.miniTempBufferIntViews[D]=P.subarray(0,D+1)},recordError:function(D){rt.lastError||(rt.lastError=D)},getNewId:function(I){for(var D=rt.counter++,P=I.length;P<D;P++)I[P]=null;return D},MINI_TEMP_BUFFER_SIZE:256,miniTempBufferFloatViews:[0],miniTempBufferIntViews:[0],getSource:function(I,D,P,j){for(var me="",he=0;he<D;++he){var fe=j?n()[j+he*4>>2]:-1;me+=Re(n()[P+he*4>>2],fe<0?void 0:fe)}return me},createContext:function(I,D){var P=I.getContext("webgl",D);if(!P)return 0;var j=rt.registerContext(P,D);return j},registerContext:function(I,D){var P=im(8);n()[P+4>>2]=Gs();var j={handle:P,attributes:D,version:D.majorVersion,GLctx:I};return I.canvas&&(I.canvas.GLctxObject=j),rt.contexts[P]=j,(typeof D.enableExtensionsByDefault=="undefined"||D.enableExtensionsByDefault)&&rt.initExtensions(j),P},makeContextCurrent:function(I){return rt.currentContext=rt.contexts[I],i.ctx=qa=rt.currentContext&&rt.currentContext.GLctx,!(I&&!qa)},getContext:function(I){return rt.contexts[I]},deleteContext:function(I){rt.currentContext===rt.contexts[I]&&(rt.currentContext=null),typeof Ze=="object"&&Ze.removeAllHandlersOnTarget(rt.contexts[I].GLctx.canvas),rt.contexts[I]&&rt.contexts[I].GLctx.canvas&&(rt.contexts[I].GLctx.canvas.GLctxObject=void 0),am(rt.contexts[I].handle),rt.contexts[I]=null},initExtensions:function(I){if(I||(I=rt.currentContext),!I.initExtensionsDone){I.initExtensionsDone=!0;var D=I.GLctx;Wy(D),Uy(D),jy(D),D.disjointTimerQueryExt=D.getExtension("EXT_disjoint_timer_query");var P=["OES_texture_float","OES_texture_half_float","OES_standard_derivatives","OES_vertex_array_object","WEBGL_compressed_texture_s3tc","WEBGL_depth_texture","OES_element_index_uint","EXT_texture_filter_anisotropic","EXT_frag_depth","WEBGL_draw_buffers","ANGLE_instanced_arrays","OES_texture_float_linear","OES_texture_half_float_linear","EXT_blend_minmax","EXT_shader_texture_lod","EXT_texture_norm16","WEBGL_compressed_texture_pvrtc","EXT_color_buffer_half_float","WEBGL_color_buffer_float","EXT_sRGB","WEBGL_compressed_texture_etc1","EXT_disjoint_timer_query","WEBGL_compressed_texture_etc","WEBGL_compressed_texture_astc","EXT_color_buffer_float","WEBGL_compressed_texture_s3tc_srgb","EXT_disjoint_timer_query_webgl2","WEBKIT_WEBGL_compressed_texture_pvrtc"],j=D.getSupportedExtensions()||[];j.forEach(function(me){P.indexOf(me)!=-1&&D.getExtension(me)})}},populateUniformTable:function(I){for(var D=rt.programs[I],P=rt.programInfos[I]={uniforms:{},maxUniformLength:0,maxAttributeLength:-1,maxUniformBlockNameLength:-1},j=P.uniforms,me=qa.getProgramParameter(D,35718),he=0;he<me;++he){var fe=qa.getActiveUniform(D,he),Se=fe.name;P.maxUniformLength=Math.max(P.maxUniformLength,Se.length+1),Se.slice(-1)=="]"&&(Se=Se.slice(0,Se.lastIndexOf("[")));var mt=qa.getUniformLocation(D,Se);if(mt){var pr=rt.getNewId(rt.uniforms);j[Se]=[fe.size,pr],rt.uniforms[pr]=mt;for(var Ar=1;Ar<fe.size;++Ar){var Ic=Se+"["+Ar+"]";mt=qa.getUniformLocation(D,Ic),pr=rt.getNewId(rt.uniforms),rt.uniforms[pr]=mt}}}}},Hy=["default","low-power","high-performance"];function qy(I,D){var P={},j=D>>2;P.alpha=!!n()[j+(0>>2)],P.depth=!!n()[j+(4>>2)],P.stencil=!!n()[j+(8>>2)],P.antialias=!!n()[j+(12>>2)],P.premultipliedAlpha=!!n()[j+(16>>2)],P.preserveDrawingBuffer=!!n()[j+(20>>2)];var me=n()[j+(24>>2)];P.powerPreference=Hy[me],P.failIfMajorPerformanceCaveat=!!n()[j+(28>>2)],P.majorVersion=n()[j+(32>>2)],P.minorVersion=n()[j+(36>>2)],P.enableExtensionsByDefault=n()[j+(40>>2)],P.explicitSwapControl=n()[j+(44>>2)],P.proxyContextToMainThread=n()[j+(48>>2)],P.renderViaOffscreenBackBuffer=n()[j+(52>>2)];var he=em(I);if(!he)return-4;if(P.explicitSwapControl)return-1;var fe=rt.createContext(he,P);return fe}function Ky(I,D){return qy(I,D)}var Ml={splitPath:function(I){var D=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return D.exec(I).slice(1)},normalizeArray:function(I,D){for(var P=0,j=I.length-1;j>=0;j--){var me=I[j];me==="."?I.splice(j,1):me===".."?(I.splice(j,1),P++):P&&(I.splice(j,1),P--)}if(D)for(;P;P--)I.unshift("..");return I},normalize:function(I){var D=I.charAt(0)==="/",P=I.substr(-1)==="/";return I=Ml.normalizeArray(I.split("/").filter(function(j){return!!j}),!D).join("/"),!I&&!D&&(I="."),I&&P&&(I+="/"),(D?"/":"")+I},dirname:function(I){var D=Ml.splitPath(I),P=D[0],j=D[1];return!P&&!j?".":(j&&(j=j.substr(0,j.length-1)),P+j)},basename:function(I){if(I==="/")return"/";var D=I.lastIndexOf("/");return D===-1?I:I.substr(D+1)},extname:function(I){return Ml.splitPath(I)[3]},join:function(){var I=Array.prototype.slice.call(arguments,0);return Ml.normalize(I.join("/"))},join2:function(I,D){return Ml.normalize(I+"/"+D)}},kc={mappings:{},buffers:[null,[],[]],printChar:function(I,D){var P=kc.buffers[I];D===0||D===10?((I===1?W:U)($e(P,0)),P.length=0):P.push(D)},varargs:void 0,get:function(){kc.varargs+=4;var I=n()[kc.varargs-4>>2];return I},getStr:function(I){var D=Re(I);return D},get64:function(I,D){return I}};function Sh(I){return x?Ha(3,1,I):0}function Th(I,D,P,j,me){if(x)return Ha(4,1,I,D,P,j,me)}function Eh(I,D,P,j){if(x)return Ha(5,1,I,D,P,j);for(var me=0,he=0;he<P;he++){for(var fe=n()[D+he*8>>2],Se=n()[D+(he*8+4)>>2],mt=0;mt<Se;mt++)kc.printChar(I,o()[fe+mt]);me+=Se}return n()[j>>2]=me,0}function Xy(I){var D=we.exitHandlers.pop();I&&D()}function Yy(I,D){we.exitHandlers===null&&(we.exitHandlers=[]),we.exitHandlers.push(function(){dI(I,D)})}function Ah(I){if(x)throw"Internal Error! _spawn_thread() can only ever be called from main application thread!";var D=we.getNewWorker();if(D.pthread!==void 0)throw"Internal error!";if(!I.pthread_ptr)throw"Internal error, no pthread ptr!";we.runningWorkers.push(D);for(var P=im(128*4),j=0;j<128;++j)n()[P+j*4>>2]=0;var me=I.stackBase+I.stackSize,he=we.pthreads[I.pthread_ptr]={worker:D,stackBase:I.stackBase,stackSize:I.stackSize,allocatedOwnStack:I.allocatedOwnStack,thread:I.pthread_ptr,threadInfoStruct:I.pthread_ptr},fe=he.threadInfoStruct>>2;Atomics.store(s(),fe+(0>>2),0),Atomics.store(s(),fe+(4>>2),0),Atomics.store(s(),fe+(8>>2),0),Atomics.store(s(),fe+(68>>2),I.detached),Atomics.store(s(),fe+(104>>2),P),Atomics.store(s(),fe+(48>>2),0),Atomics.store(s(),fe+(40>>2),he.threadInfoStruct),Atomics.store(s(),fe+(44>>2),42),Atomics.store(s(),fe+(108>>2),I.stackSize),Atomics.store(s(),fe+(84>>2),I.stackSize),Atomics.store(s(),fe+(80>>2),me),Atomics.store(s(),fe+(108+8>>2),me),Atomics.store(s(),fe+(108+12>>2),I.detached),Atomics.store(s(),fe+(108+20>>2),I.schedPolicy),Atomics.store(s(),fe+(108+24>>2),I.schedPrio);var Se=lI(),mt=Se+40;Atomics.store(s(),fe+(176>>2),mt),D.pthread=he;var pr={cmd:"run",start_routine:I.startRoutine,arg:I.arg,threadInfoStruct:I.pthread_ptr,selfThreadId:I.pthread_ptr,parentThreadId:I.parent_pthread_ptr,stackBase:I.stackBase,stackSize:I.stackSize};D.runPthread=function(){pr.time=performance.now(),D.postMessage(pr,I.transferList)},D.loaded&&(D.runPthread(),delete D.runPthread)}function Zy(I,D,P){if(!D&&!P)return Qp.EINVAL;if(!I)return U("pthread_getschedparam called with a null thread pointer!"),Qp.ESRCH;var j=n()[I+12>>2];if(j!==I)return U("pthread_getschedparam attempted on thread "+I+", which does not point to a valid thread, or does not exist anymore!"),Qp.ESRCH;var me=Atomics.load(s(),I+108+20>>2),he=Atomics.load(s(),I+108+24>>2);return D&&(n()[D>>2]=me),P&&(n()[P>>2]=he),0}function Gs(){return kh|0}i._pthread_self=Gs;function Jy(I,D,P,j){if(typeof SharedArrayBuffer=="undefined")return U("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;if(!I)return U("pthread_create called with a null thread pointer!"),28;var me=[],he=0;if(x&&(me.length===0||he))return mI(687865856,I,D,P,j);if(he)return he;var fe=0,Se=0,mt=0,pr=0,Ar=0;if(D){fe=n()[D>>2],fe+=81920,Se=n()[D+8>>2],mt=n()[D+12>>2]!==0;var Ic=n()[D+16>>2]===0;if(Ic){var cm=n()[D+20>>2],go=n()[D+24>>2],Xa=we.currentProxiedOperationCallerThread?we.currentProxiedOperationCallerThread:Gs();Zy(Xa,D+20,D+24),pr=n()[D+20>>2],Ar=n()[D+24>>2],n()[D+20>>2]=cm,n()[D+24>>2]=go}else pr=n()[D+20>>2],Ar=n()[D+24>>2]}else fe=2097152;var pm=Se==0;pm?Se=uI(16,fe):(Se-=fe,ge(Se>0));for(var Nc=im(232),ab=0;ab<232>>2;++ab)s()[(Nc>>2)+ab]=0;n()[I>>2]=Nc,n()[Nc+12>>2]=Nc;var gI=Nc+156;n()[gI>>2]=gI;var lb={stackBase:Se,stackSize:fe,allocatedOwnStack:pm,schedPolicy:pr,schedPrio:Ar,detached:mt,startRoutine:P,pthread_ptr:Nc,parent_pthread_ptr:Gs(),arg:j,transferList:me};return x?(lb.cmd="spawnThread",postMessage(lb,me)):Ah(lb),0}function Qy(I){return I=+I,I>=0?+ny(I+.5):+xc(I-.5)}function Dh(I){if(x)return Ha(6,1,I);switch(I){case 30:return 16384;case 85:var D=2147483648;return D/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 80:case 81:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:case 79: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: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 _y(28),-1}x?we.initWorker():we.initMainThreadBlock();var qa;rt.init();var eb=[null,wy,Nh,Sh,Th,Eh,Dh],tb={e:yy,r:by,w:ky,a:vy,l:Cy,d:Iy,c:_c,h:Ol,g:Ny,x:Sy,q:Ty,B:Ey,t:Ay,A:Ry,u:By,k:Vy,s:Gy,v:Ky,m:Sh,o:Th,i:Eh,p:my,memory:K||i.wasmMemory,y:Xy,z:Yy,j:Jy,b:Gs,f:Qy,n:Dh,table:re},$h=cy();i.asm=$h;var tm=i.___wasm_call_ctors=function(){return(tm=i.___wasm_call_ctors=i.asm.C).apply(null,arguments)},rm=i._init=function(){return(rm=i._init=i.asm.D).apply(null,arguments)},Rh=i._register_tensor=function(){return(Rh=i._register_tensor=i.asm.E).apply(null,arguments)},Ll=i._dispose_data=function(){return(Ll=i._dispose_data=i.asm.F).apply(null,arguments)},om=i._dispose=function(){return(om=i._dispose=i.asm.G).apply(null,arguments)},rb=i._Abs=function(){return(rb=i._Abs=i.asm.H).apply(null,arguments)},ob=i._Add=function(){return(ob=i._Add=i.asm.I).apply(null,arguments)},nm=i._AddN=function(){return(nm=i._AddN=i.asm.J).apply(null,arguments)},Fh=i._ArgMax=function(){return(Fh=i._ArgMax=i.asm.K).apply(null,arguments)},Oh=i._AvgPool=function(){return(Oh=i._AvgPool=i.asm.L).apply(null,arguments)},H=i._BatchMatMul=function(){return(H=i._BatchMatMul=i.asm.M).apply(null,arguments)},ne=i._ClipByValue=function(){return(ne=i._ClipByValue=i.asm.N).apply(null,arguments)},be=i._Conv2D=function(){return(be=i._Conv2D=i.asm.O).apply(null,arguments)},Ke=i._Conv2DBackpropInput=function(){return(Ke=i._Conv2DBackpropInput=i.asm.P).apply(null,arguments)},Xe=i._Cos=function(){return(Xe=i._Cos=i.asm.Q).apply(null,arguments)},Ht=i._CropAndResize=function(){return(Ht=i._CropAndResize=i.asm.R).apply(null,arguments)},at=i._Cumsum=function(){return(at=i._Cumsum=i.asm.S).apply(null,arguments)},nt=i._DepthToSpace=function(){return(nt=i._DepthToSpace=i.asm.T).apply(null,arguments)},xr=i._DepthwiseConv2dNative=function(){return(xr=i._DepthwiseConv2dNative=i.asm.U).apply(null,arguments)},ta=i._Equal=function(){return(ta=i._Equal=i.asm.V).apply(null,arguments)},ra=i._Exp=function(){return(ra=i._Exp=i.asm.W).apply(null,arguments)},Ph=i._FlipLeftRight=function(){return(Ph=i._FlipLeftRight=i.asm.X).apply(null,arguments)},sm=i._Floor=function(){return(sm=i._Floor=i.asm.Y).apply(null,arguments)},ho=i._FloorDiv=function(){return(ho=i._FloorDiv=i.asm.Z).apply(null,arguments)},Ka=i._FusedBatchNorm=function(){return(Ka=i._FusedBatchNorm=i.asm._).apply(null,arguments)},Mh=i._FusedConv2D=function(){return(Mh=i._FusedConv2D=i.asm.$).apply(null,arguments)},Cz=i._FusedDepthwiseConv2D=function(){return(Cz=i._FusedDepthwiseConv2D=i.asm.aa).apply(null,arguments)},Iz=i._Gather=function(){return(Iz=i._Gather=i.asm.ba).apply(null,arguments)},Nz=i._GatherNd=function(){return(Nz=i._GatherNd=i.asm.ca).apply(null,arguments)},Sz=i._Greater=function(){return(Sz=i._Greater=i.asm.da).apply(null,arguments)},Tz=i._GreaterEqual=function(){return(Tz=i._GreaterEqual=i.asm.ea).apply(null,arguments)},Ez=i._LeakyRelu=function(){return(Ez=i._LeakyRelu=i.asm.fa).apply(null,arguments)},Az=i._Less=function(){return(Az=i._Less=i.asm.ga).apply(null,arguments)},Dz=i._LessEqual=function(){return(Dz=i._LessEqual=i.asm.ha).apply(null,arguments)},$z=i._Log=function(){return($z=i._Log=i.asm.ia).apply(null,arguments)},Rz=i._LogicalAnd=function(){return(Rz=i._LogicalAnd=i.asm.ja).apply(null,arguments)},Fz=i._Max=function(){return(Fz=i._Max=i.asm.ka).apply(null,arguments)},Oz=i._MaxPool=function(){return(Oz=i._MaxPool=i.asm.la).apply(null,arguments)},Pz=i._Maximum=function(){return(Pz=i._Maximum=i.asm.ma).apply(null,arguments)},Mz=i._Mean=function(){return(Mz=i._Mean=i.asm.na).apply(null,arguments)},Lz=i._Min=function(){return(Lz=i._Min=i.asm.oa).apply(null,arguments)},zz=i._Minimum=function(){return(zz=i._Minimum=i.asm.pa).apply(null,arguments)},Bz=i._Multiply=function(){return(Bz=i._Multiply=i.asm.qa).apply(null,arguments)},Vz=i._Neg=function(){return(Vz=i._Neg=i.asm.ra).apply(null,arguments)},Gz=i._NonMaxSuppressionV3=function(){return(Gz=i._NonMaxSuppressionV3=i.asm.sa).apply(null,arguments)},Wz=i._NonMaxSuppressionV4=function(){return(Wz=i._NonMaxSuppressionV4=i.asm.ta).apply(null,arguments)},Uz=i._NonMaxSuppressionV5=function(){return(Uz=i._NonMaxSuppressionV5=i.asm.ua).apply(null,arguments)},jz=i._NotEqual=function(){return(jz=i._NotEqual=i.asm.va).apply(null,arguments)},Hz=i._OneHot=function(){return(Hz=i._OneHot=i.asm.wa).apply(null,arguments)},qz=i._PadV2=function(){return(qz=i._PadV2=i.asm.xa).apply(null,arguments)},Kz=i._Pow=function(){return(Kz=i._Pow=i.asm.ya).apply(null,arguments)},Xz=i._Prelu=function(){return(Xz=i._Prelu=i.asm.za).apply(null,arguments)},Yz=i._Prod=function(){return(Yz=i._Prod=i.asm.Aa).apply(null,arguments)},Zz=i._RealDiv=function(){return(Zz=i._RealDiv=i.asm.Ba).apply(null,arguments)},Jz=i._Relu=function(){return(Jz=i._Relu=i.asm.Ca).apply(null,arguments)},Qz=i._Relu6=function(){return(Qz=i._Relu6=i.asm.Da).apply(null,arguments)},eB=i._ResizeBilinear=function(){return(eB=i._ResizeBilinear=i.asm.Ea).apply(null,arguments)},tB=i._Reverse=function(){return(tB=i._Reverse=i.asm.Fa).apply(null,arguments)},rB=i._RotateWithOffset=function(){return(rB=i._RotateWithOffset=i.asm.Ga).apply(null,arguments)},oB=i._Round=function(){return(oB=i._Round=i.asm.Ha).apply(null,arguments)},nB=i._Rsqrt=function(){return(nB=i._Rsqrt=i.asm.Ia).apply(null,arguments)},sB=i._ScatterNd=function(){return(sB=i._ScatterNd=i.asm.Ja).apply(null,arguments)},iB=i._SelectV2=function(){return(iB=i._SelectV2=i.asm.Ka).apply(null,arguments)},aB=i._Sigmoid=function(){return(aB=i._Sigmoid=i.asm.La).apply(null,arguments)},lB=i._Sin=function(){return(lB=i._Sin=i.asm.Ma).apply(null,arguments)},uB=i._Softmax=function(){return(uB=i._Softmax=i.asm.Na).apply(null,arguments)},cB=i._Sqrt=function(){return(cB=i._Sqrt=i.asm.Oa).apply(null,arguments)},pB=i._Square=function(){return(pB=i._Square=i.asm.Pa).apply(null,arguments)},mB=i._SquaredDifference=function(){return(mB=i._SquaredDifference=i.asm.Qa).apply(null,arguments)},fB=i._Step=function(){return(fB=i._Step=i.asm.Ra).apply(null,arguments)},dB=i._StridedSlice=function(){return(dB=i._StridedSlice=i.asm.Sa).apply(null,arguments)},hB=i._Sub=function(){return(hB=i._Sub=i.asm.Ta).apply(null,arguments)},gB=i._Sum=function(){return(gB=i._Sum=i.asm.Ua).apply(null,arguments)},xB=i._Tanh=function(){return(xB=i._Tanh=i.asm.Va).apply(null,arguments)},yB=i._Tile=function(){return(yB=i._Tile=i.asm.Wa).apply(null,arguments)},bB=i._TopK=function(){return(bB=i._TopK=i.asm.Xa).apply(null,arguments)},_B=i._Transpose=function(){return(_B=i._Transpose=i.asm.Ya).apply(null,arguments)},wB=i.__FusedMatMul=function(){return(wB=i.__FusedMatMul=i.asm.Za).apply(null,arguments)},im=i._malloc=function(){return(im=i._malloc=i.asm._a).apply(null,arguments)},am=i._free=function(){return(am=i._free=i.asm.$a).apply(null,arguments)},kB=i.___em_js__initPthreadsJS=function(){return(kB=i.___em_js__initPthreadsJS=i.asm.ab).apply(null,arguments)},aI=i.___errno_location=function(){return(aI=i.___errno_location=i.asm.bb).apply(null,arguments)},lI=i._emscripten_get_global_libc=function(){return(lI=i._emscripten_get_global_libc=i.asm.cb).apply(null,arguments)},uI=i._memalign=function(){return(uI=i._memalign=i.asm.db).apply(null,arguments)},cI=i.___pthread_tsd_run_dtors=function(){return(cI=i.___pthread_tsd_run_dtors=i.asm.eb).apply(null,arguments)},nb=i._emscripten_main_thread_process_queued_calls=function(){return(nb=i._emscripten_main_thread_process_queued_calls=i.asm.fb).apply(null,arguments)},vB=i._emscripten_current_thread_process_queued_calls=function(){return(vB=i._emscripten_current_thread_process_queued_calls=i.asm.gb).apply(null,arguments)},pI=i._emscripten_register_main_browser_thread_id=function(){return(pI=i._emscripten_register_main_browser_thread_id=i.asm.hb).apply(null,arguments)},CB=i._emscripten_main_browser_thread_id=function(){return(CB=i._emscripten_main_browser_thread_id=i.asm.ib).apply(null,arguments)},IB=i._emscripten_async_run_in_main_thread=function(){return(IB=i._emscripten_async_run_in_main_thread=i.asm.jb).apply(null,arguments)},NB=i._emscripten_sync_run_in_main_thread=function(){return(NB=i._emscripten_sync_run_in_main_thread=i.asm.kb).apply(null,arguments)},SB=i._emscripten_sync_run_in_main_thread_0=function(){return(SB=i._emscripten_sync_run_in_main_thread_0=i.asm.lb).apply(null,arguments)},TB=i._emscripten_sync_run_in_main_thread_1=function(){return(TB=i._emscripten_sync_run_in_main_thread_1=i.asm.mb).apply(null,arguments)},EB=i._emscripten_sync_run_in_main_thread_2=function(){return(EB=i._emscripten_sync_run_in_main_thread_2=i.asm.nb).apply(null,arguments)},AB=i._emscripten_sync_run_in_main_thread_xprintf_varargs=function(){return(AB=i._emscripten_sync_run_in_main_thread_xprintf_varargs=i.asm.ob).apply(null,arguments)},DB=i._emscripten_sync_run_in_main_thread_3=function(){return(DB=i._emscripten_sync_run_in_main_thread_3=i.asm.pb).apply(null,arguments)},mI=i._emscripten_sync_run_in_main_thread_4=function(){return(mI=i._emscripten_sync_run_in_main_thread_4=i.asm.qb).apply(null,arguments)},$B=i._emscripten_sync_run_in_main_thread_5=function(){return($B=i._emscripten_sync_run_in_main_thread_5=i.asm.rb).apply(null,arguments)},RB=i._emscripten_sync_run_in_main_thread_6=function(){return(RB=i._emscripten_sync_run_in_main_thread_6=i.asm.sb).apply(null,arguments)},FB=i._emscripten_sync_run_in_main_thread_7=function(){return(FB=i._emscripten_sync_run_in_main_thread_7=i.asm.tb).apply(null,arguments)},fI=i._emscripten_run_in_main_runtime_thread_js=function(){return(fI=i._emscripten_run_in_main_runtime_thread_js=i.asm.ub).apply(null,arguments)},sb=i._emscripten_async_queue_on_thread_=function(){return(sb=i._emscripten_async_queue_on_thread_=i.asm.vb).apply(null,arguments)},OB=i._emscripten_tls_init=function(){return(OB=i._emscripten_tls_init=i.asm.wb).apply(null,arguments)},lm=i.stackSave=function(){return(lm=i.stackSave=i.asm.xb).apply(null,arguments)},vc=i.stackAlloc=function(){return(vc=i.stackAlloc=i.asm.yb).apply(null,arguments)},Cc=i.stackRestore=function(){return(Cc=i.stackRestore=i.asm.zb).apply(null,arguments)},dI=i.dynCall_vi=function(){return(dI=i.dynCall_vi=i.asm.Ab).apply(null,arguments)},PB=i.dynCall_v=function(){return(PB=i.dynCall_v=i.asm.Bb).apply(null,arguments)},MB=i.dynCall_ii=function(){return(MB=i.dynCall_ii=i.asm.Cb).apply(null,arguments)};i.asm=$h,i.cwrap=De,i.PThread=we,i.PThread=we,i._pthread_self=Gs,i.wasmMemory=K,i.ExitStatus=hI;var um;i.then=function(I){if(um)I(i);else{var D=i.onRuntimeInitialized;i.onRuntimeInitialized=function(){D&&D(),I(i)}}return i};function hI(I){this.name="ExitStatus",this.message="Program terminated with exit("+I+")",this.status=I}Fl=function I(){um||ib(),um||(Fl=I)};function ib(I){if(I=I||c,Qi>0||(Go(),Qi>0))return;function D(){um||(um=!0,i.calledRun=!0,!ae&&(yh(),ty(),i.onRuntimeInitialized&&i.onRuntimeInitialized(),ry()))}i.setStatus?(i.setStatus("Running..."),setTimeout(function(){setTimeout(function(){i.setStatus("")},1),D()},1)):D()}if(i.run=ib,i.preInit)for(typeof i.preInit=="function"&&(i.preInit=[i.preInit]);i.preInit.length>0;)i.preInit.pop()();return x||(te=!0),x||ib(),e}}();typeof Yx=="object"&&typeof tI=="object"?tI.exports=rI:typeof define=="function"&&define.amd?define([],function(){return rI}):typeof Yx=="object"&&(Yx.WasmBackendModuleThreadedSimd=rI)});var _z=Br((Zx,oI)=>{var nI=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:{},o={},n;for(n in t)t.hasOwnProperty(n)&&(o[n]=t[n]);var s=[],a="./this.program",i=function(H,ne){throw ne},l=!1,u=!1,c=!1,p=!1;l=typeof window=="object",u=typeof importScripts=="function",c=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",p=!l&&!c&&!u;var m="";function f(H){return t.locateFile?t.locateFile(H,m):m+H}var d,h,g,x,b,_;c?(u?m=Kp().dirname(m)+"/":m=__dirname+"/",d=function(ne,be){return b||(b=require("fs")),_||(_=Kp()),ne=_.normalize(ne),b.readFileSync(ne,be?null:"utf8")},g=function(ne){var be=d(ne,!0);return be.buffer||(be=new Uint8Array(be)),U(be.buffer),be},process.argv.length>1&&(a=process.argv[1].replace(/\\/g,"/")),s=process.argv.slice(2),process.on("uncaughtException",function(H){if(!(H instanceof om))throw H}),process.on("unhandledRejection",Ji),i=function(H){process.exit(H)},t.inspect=function(){return"[Emscripten Module object]"}):p?(typeof read!="undefined"&&(d=function(ne){return read(ne)}),g=function(ne){var be;return typeof readbuffer=="function"?new Uint8Array(readbuffer(ne)):(be=read(ne,"binary"),U(typeof be=="object"),be)},typeof scriptArgs!="undefined"?s=scriptArgs:typeof arguments!="undefined"&&(s=arguments),typeof quit=="function"&&(i=function(H){quit(H)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(l||u)&&(u?m=self.location.href:document.currentScript&&(m=document.currentScript.src),r&&(m=r),m.indexOf("blob:")!==0?m=m.substr(0,m.lastIndexOf("/")+1):m="",d=function(ne){var be=new XMLHttpRequest;return be.open("GET",ne,!1),be.send(null),be.responseText},u&&(g=function(ne){var be=new XMLHttpRequest;return be.open("GET",ne,!1),be.responseType="arraybuffer",be.send(null),new Uint8Array(be.response)}),h=function(ne,be,Ke){var Xe=new XMLHttpRequest;Xe.open("GET",ne,!0),Xe.responseType="arraybuffer",Xe.onload=function(){if(Xe.status==200||Xe.status==0&&Xe.response){be(Xe.response);return}Ke()},Xe.onerror=Ke,Xe.send(null)},x=function(H){document.title=H});var w=t.print||console.log.bind(console),v=t.printErr||console.warn.bind(console);for(n in o)o.hasOwnProperty(n)&&(t[n]=o[n]);o=null,t.arguments&&(s=t.arguments),t.thisProgram&&(a=t.thisProgram),t.quit&&(i=t.quit);var $;t.wasmBinary&&($=t.wasmBinary);var A;t.noExitRuntime&&(A=t.noExitRuntime),typeof WebAssembly!="object"&&v("no native wasm support detected");var R,M=new WebAssembly.Table({initial:151,maximum:151+0,element:"anyfunc"}),z=!1,W=0;function U(H,ne){H||Ji("Assertion failed: "+ne)}function q(H){var ne=t["_"+H];return U(ne,"Cannot call unknown function "+H+", make sure it is exported"),ne}function Z(H,ne,be,Ke,Xe){var Ht={string:function(ho){var Ka=0;if(ho!=null&&ho!==0){var Mh=(ho.length<<2)+1;Ka=rm(Mh),ie(ho,Ka,Mh)}return Ka},array:function(ho){var Ka=rm(ho.length);return se(ho,Ka),Ka}};function at(ho){return ne==="string"?K(ho):ne==="boolean"?Boolean(ho):ho}var nt=q(H),xr=[],ta=0;if(Ke)for(var ra=0;ra<Ke.length;ra++){var Ph=Ht[be[ra]];Ph?(ta===0&&(ta=tm()),xr[ra]=Ph(Ke[ra])):xr[ra]=Ke[ra]}var sm=nt.apply(null,xr);return sm=at(sm),ta!==0&&Rh(ta),sm}function X(H,ne,be,Ke){be=be||[];var Xe=be.every(function(at){return at==="number"}),Ht=ne!=="string";return Ht&&Xe&&!Ke?q(H):function(){return Z(H,ne,be,arguments,Ke)}}var Y=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function te(H,ne,be){for(var Ke=ne+be,Xe=ne;H[Xe]&&!(Xe>=Ke);)++Xe;if(Xe-ne>16&&H.subarray&&Y)return Y.decode(H.subarray(ne,Xe));for(var Ht="";ne<Xe;){var at=H[ne++];if(!(at&128)){Ht+=String.fromCharCode(at);continue}var nt=H[ne++]&63;if((at&224)==192){Ht+=String.fromCharCode((at&31)<<6|nt);continue}var xr=H[ne++]&63;if((at&240)==224?at=(at&15)<<12|nt<<6|xr:at=(at&7)<<18|nt<<12|xr<<6|H[ne++]&63,at<65536)Ht+=String.fromCharCode(at);else{var ta=at-65536;Ht+=String.fromCharCode(55296|ta>>10,56320|ta&1023)}}return Ht}function K(H,ne){return H?te(xe,H,ne):""}function re(H,ne,be,Ke){if(!(Ke>0))return 0;for(var Xe=be,Ht=be+Ke-1,at=0;at<H.length;++at){var nt=H.charCodeAt(at);if(nt>=55296&&nt<=57343){var xr=H.charCodeAt(++at);nt=65536+((nt&1023)<<10)|xr&1023}if(nt<=127){if(be>=Ht)break;ne[be++]=nt}else if(nt<=2047){if(be+1>=Ht)break;ne[be++]=192|nt>>6,ne[be++]=128|nt&63}else if(nt<=65535){if(be+2>=Ht)break;ne[be++]=224|nt>>12,ne[be++]=128|nt>>6&63,ne[be++]=128|nt&63}else{if(be+3>=Ht)break;ne[be++]=240|nt>>18,ne[be++]=128|nt>>12&63,ne[be++]=128|nt>>6&63,ne[be++]=128|nt&63}}return ne[be]=0,be-Xe}function ie(H,ne,be){return re(H,xe,ne,be)}function se(H,ne){ae.set(H,ne)}var pe,ae,xe,ge,_e,ke,De,$e,Re;function He(H){pe=H,t.HEAP8=ae=new Int8Array(H),t.HEAP16=ge=new Int16Array(H),t.HEAP32=ke=new Int32Array(H),t.HEAPU8=xe=new Uint8Array(H),t.HEAPU16=_e=new Uint16Array(H),t.HEAPU32=De=new Uint32Array(H),t.HEAPF32=$e=new Float32Array(H),t.HEAPF64=Re=new Float64Array(H)}var ut=t.INITIAL_MEMORY||16777216;function wt(H){for(;H.length>0;){var ne=H.shift();if(typeof ne=="function"){ne(t);continue}var be=ne.func;typeof be=="number"?ne.arg===void 0?t.dynCall_v(be):t.dynCall_vi(be,ne.arg):be(ne.arg===void 0?null:ne.arg)}}var kt=[],pt=[],vt=[],qe=[],Ft=!1,po=!1;function Zt(){if(t.preRun)for(typeof t.preRun=="function"&&(t.preRun=[t.preRun]);t.preRun.length;)fo(t.preRun.shift());wt(kt)}function mo(){Ft=!0,wt(pt)}function _r(){wt(vt)}function Bo(){po=!0}function Jr(){if(t.postRun)for(typeof t.postRun=="function"&&(t.postRun=[t.postRun]);t.postRun.length;)wr(t.postRun.shift());wt(qe)}function fo(H){kt.unshift(H)}function wr(H){qe.unshift(H)}var No=Math.ceil,Vo=Math.floor,Qr=0,ts=null,So=null;function gc(H){Qr++,t.monitorRunDependencies&&t.monitorRunDependencies(Qr)}function rs(H){if(Qr--,t.monitorRunDependencies&&t.monitorRunDependencies(Qr),Qr==0&&(ts!==null&&(clearInterval(ts),ts=null),So)){var ne=So;So=null,ne()}}t.preloadedImages={},t.preloadedAudios={};function Ji(H){throw t.onAbort&&t.onAbort(H),H+="",w(H),v(H),z=!0,W=1,H="abort("+H+"). Build with -s ASSERTIONS=1 for more info.",new WebAssembly.RuntimeError(H)}function $l(H,ne){return String.prototype.startsWith?H.startsWith(ne):H.indexOf(ne)===0}var ey="data:application/octet-stream;base64,";function Xp(H){return $l(H,ey)}var xh="file://";function Yp(H){return $l(H,xh)}var Go="tfjs-backend-wasm.wasm";Xp(Go)||(Go=f(Go));function yh(){try{if($)return new Uint8Array($);if(g)return g(Go);throw"both async and sync fetching of the wasm failed"}catch(H){Ji(H)}}function ty(){return!$&&(l||u)&&typeof fetch=="function"&&!Yp(Go)?fetch(Go,{credentials:"same-origin"}).then(function(H){if(!H.ok)throw"failed to load wasm binary file at '"+Go+"'";return H.arrayBuffer()}).catch(function(){return yh()}):new Promise(function(H,ne){H(yh())})}function ry(){var H={env:ea,wasi_snapshot_preview1:ea};function ne(at,nt){var xr=at.exports;t.asm=xr,R=xr.memory,He(R.buffer),rs("wasm-instantiate")}gc("wasm-instantiate");function be(at){ne(at.instance)}function Ke(at){return ty().then(function(nt){return WebAssembly.instantiate(nt,H)}).then(at,function(nt){v("failed to asynchronously prepare wasm: "+nt),Ji(nt)})}function Xe(){if(!$&&typeof WebAssembly.instantiateStreaming=="function"&&!Xp(Go)&&!Yp(Go)&&typeof fetch=="function")fetch(Go,{credentials:"same-origin"}).then(function(at){var nt=WebAssembly.instantiateStreaming(at,H);return nt.then(be,function(xr){v("wasm streaming compile failed: "+xr),v("falling back to ArrayBuffer instantiation"),Ke(be)})});else return Ke(be)}if(t.instantiateWasm)try{var Ht=t.instantiateWasm(H,ne);return Ht}catch(at){return v("Module.instantiateWasm callback failed with error: "+at),!1}return Xe(),{}}pt.push();function oy(H){He(R.buffer)}var Rl={splitPath:function(H){var ne=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return ne.exec(H).slice(1)},normalizeArray:function(H,ne){for(var be=0,Ke=H.length-1;Ke>=0;Ke--){var Xe=H[Ke];Xe==="."?H.splice(Ke,1):Xe===".."?(H.splice(Ke,1),be++):be&&(H.splice(Ke,1),be--)}if(ne)for(;be;be--)H.unshift("..");return H},normalize:function(H){var ne=H.charAt(0)==="/",be=H.substr(-1)==="/";return H=Rl.normalizeArray(H.split("/").filter(function(Ke){return!!Ke}),!ne).join("/"),!H&&!ne&&(H="."),H&&be&&(H+="/"),(ne?"/":"")+H},dirname:function(H){var ne=Rl.splitPath(H),be=ne[0],Ke=ne[1];return!be&&!Ke?".":(Ke&&(Ke=Ke.substr(0,Ke.length-1)),be+Ke)},basename:function(H){if(H==="/")return"/";var ne=H.lastIndexOf("/");return ne===-1?H:H.substr(ne+1)},extname:function(H){return Rl.splitPath(H)[3]},join:function(){var H=Array.prototype.slice.call(arguments,0);return Rl.normalize(H.join("/"))},join2:function(H,ne){return Rl.normalize(H+"/"+ne)}},xc={mappings:{},buffers:[null,[],[]],printChar:function(H,ne){var be=xc.buffers[H];ne===0||ne===10?((H===1?w:v)(te(be,0)),be.length=0):be.push(ne)},varargs:void 0,get:function(){xc.varargs+=4;var H=ke[xc.varargs-4>>2];return H},getStr:function(H){var ne=K(H);return ne},get64:function(H,ne){return H}};function ny(H){return 0}function Qi(H,ne,be,Ke,Xe){}function Zp(H,ne,be,Ke){for(var Xe=0,Ht=0;Ht<be;Ht++){for(var at=ke[ne+Ht*8>>2],nt=ke[ne+(Ht*8+4)>>2],xr=0;xr<nt;xr++)xc.printChar(H,xe[at+xr]);Xe+=nt}return ke[Ke>>2]=Xe,0}function Fl(H){Fh(H)}function sy(H){Fl(H)}function iy(H){return H=+H,H>=0?+Vo(H+.5):+No(H-.5)}var ea={emscripten_notify_memory_growth:oy,fd_close:ny,fd_seek:Qi,fd_write:Zp,proc_exit:sy,roundf:iy},Jp=ry();t.asm=Jp;var ay=t._init=function(){return(ay=t._init=t.asm.init).apply(null,arguments)},bh=t._register_tensor=function(){return(bh=t._register_tensor=t.asm.register_tensor).apply(null,arguments)},ly=t._dispose_data=function(){return(ly=t._dispose_data=t.asm.dispose_data).apply(null,arguments)},_h=t._dispose=function(){return(_h=t._dispose=t.asm.dispose).apply(null,arguments)},Wo=t._Abs=function(){return(Wo=t._Abs=t.asm.Abs).apply(null,arguments)},wh=t._Add=function(){return(wh=t._Add=t.asm.Add).apply(null,arguments)},uy=t._AddN=function(){return(uy=t._AddN=t.asm.AddN).apply(null,arguments)},cy=t._ArgMax=function(){return(cy=t._ArgMax=t.asm.ArgMax).apply(null,arguments)},py=t._AvgPool=function(){return(py=t._AvgPool=t.asm.AvgPool).apply(null,arguments)},my=t._BatchMatMul=function(){return(my=t._BatchMatMul=t.asm.BatchMatMul).apply(null,arguments)},kh=t._ClipByValue=function(){return(kh=t._ClipByValue=t.asm.ClipByValue).apply(null,arguments)},vh=t._Conv2D=function(){return(vh=t._Conv2D=t.asm.Conv2D).apply(null,arguments)},Ch=t._Conv2DBackpropInput=function(){return(Ch=t._Conv2DBackpropInput=t.asm.Conv2DBackpropInput).apply(null,arguments)},yc=t._Cos=function(){return(yc=t._Cos=t.asm.Cos).apply(null,arguments)},Qp=t._CropAndResize=function(){return(Qp=t._CropAndResize=t.asm.CropAndResize).apply(null,arguments)},bc=t._Cumsum=function(){return(bc=t._Cumsum=t.asm.Cumsum).apply(null,arguments)},_c=t._DepthToSpace=function(){return(_c=t._DepthToSpace=t.asm.DepthToSpace).apply(null,arguments)},fy=t._DepthwiseConv2dNative=function(){return(fy=t._DepthwiseConv2dNative=t.asm.DepthwiseConv2dNative).apply(null,arguments)},dy=t._Equal=function(){return(dy=t._Equal=t.asm.Equal).apply(null,arguments)},hy=t._Exp=function(){return(hy=t._Exp=t.asm.Exp).apply(null,arguments)},we=t._FlipLeftRight=function(){return(we=t._FlipLeftRight=t.asm.FlipLeftRight).apply(null,arguments)},gy=t._Floor=function(){return(gy=t._Floor=t.asm.Floor).apply(null,arguments)},xy=t._FloorDiv=function(){return(xy=t._FloorDiv=t.asm.FloorDiv).apply(null,arguments)},yy=t._FusedBatchNorm=function(){return(yy=t._FusedBatchNorm=t.asm.FusedBatchNorm).apply(null,arguments)},by=t._FusedConv2D=function(){return(by=t._FusedConv2D=t.asm.FusedConv2D).apply(null,arguments)},Ol=t._FusedDepthwiseConv2D=function(){return(Ol=t._FusedDepthwiseConv2D=t.asm.FusedDepthwiseConv2D).apply(null,arguments)},_y=t._Gather=function(){return(_y=t._Gather=t.asm.Gather).apply(null,arguments)},wy=t._GatherNd=function(){return(wy=t._GatherNd=t.asm.GatherNd).apply(null,arguments)},ky=t._Greater=function(){return(ky=t._Greater=t.asm.Greater).apply(null,arguments)},vy=t._GreaterEqual=function(){return(vy=t._GreaterEqual=t.asm.GreaterEqual).apply(null,arguments)},Cy=t._LeakyRelu=function(){return(Cy=t._LeakyRelu=t.asm.LeakyRelu).apply(null,arguments)},Iy=t._Less=function(){return(Iy=t._Less=t.asm.Less).apply(null,arguments)},Ny=t._LessEqual=function(){return(Ny=t._LessEqual=t.asm.LessEqual).apply(null,arguments)},Sy=t._Log=function(){return(Sy=t._Log=t.asm.Log).apply(null,arguments)},Ty=t._LogicalAnd=function(){return(Ty=t._LogicalAnd=t.asm.LogicalAnd).apply(null,arguments)},Ey=t._Max=function(){return(Ey=t._Max=t.asm.Max).apply(null,arguments)},Ha=t._MaxPool=function(){return(Ha=t._MaxPool=t.asm.MaxPool).apply(null,arguments)},Pl=t._Maximum=function(){return(Pl=t._Maximum=t.asm.Maximum).apply(null,arguments)},wc=t._Mean=function(){return(wc=t._Mean=t.asm.Mean).apply(null,arguments)},Ay=t._Min=function(){return(Ay=t._Min=t.asm.Min).apply(null,arguments)},Dy=t._Minimum=function(){return(Dy=t._Minimum=t.asm.Minimum).apply(null,arguments)},$y=t._Multiply=function(){return($y=t._Multiply=t.asm.Multiply).apply(null,arguments)},Ry=t._Neg=function(){return(Ry=t._Neg=t.asm.Neg).apply(null,arguments)},Ze=t._NonMaxSuppressionV3=function(){return(Ze=t._NonMaxSuppressionV3=t.asm.NonMaxSuppressionV3).apply(null,arguments)},Fy=t._NonMaxSuppressionV4=function(){return(Fy=t._NonMaxSuppressionV4=t.asm.NonMaxSuppressionV4).apply(null,arguments)},Oy=t._NonMaxSuppressionV5=function(){return(Oy=t._NonMaxSuppressionV5=t.asm.NonMaxSuppressionV5).apply(null,arguments)},Py=t._NotEqual=function(){return(Py=t._NotEqual=t.asm.NotEqual).apply(null,arguments)},My=t._OneHot=function(){return(My=t._OneHot=t.asm.OneHot).apply(null,arguments)},Ly=t._PadV2=function(){return(Ly=t._PadV2=t.asm.PadV2).apply(null,arguments)},zy=t._Pow=function(){return(zy=t._Pow=t.asm.Pow).apply(null,arguments)},em=t._Prelu=function(){return(em=t._Prelu=t.asm.Prelu).apply(null,arguments)},Ih=t._Prod=function(){return(Ih=t._Prod=t.asm.Prod).apply(null,arguments)},Nh=t._RealDiv=function(){return(Nh=t._RealDiv=t.asm.RealDiv).apply(null,arguments)},By=t._Relu=function(){return(By=t._Relu=t.asm.Relu).apply(null,arguments)},Vy=t._Relu6=function(){return(Vy=t._Relu6=t.asm.Relu6).apply(null,arguments)},Gy=t._ResizeBilinear=function(){return(Gy=t._ResizeBilinear=t.asm.ResizeBilinear).apply(null,arguments)},Wy=t._Reverse=function(){return(Wy=t._Reverse=t.asm.Reverse).apply(null,arguments)},Uy=t._RotateWithOffset=function(){return(Uy=t._RotateWithOffset=t.asm.RotateWithOffset).apply(null,arguments)},jy=t._Round=function(){return(jy=t._Round=t.asm.Round).apply(null,arguments)},rt=t._Rsqrt=function(){return(rt=t._Rsqrt=t.asm.Rsqrt).apply(null,arguments)},Hy=t._ScatterNd=function(){return(Hy=t._ScatterNd=t.asm.ScatterNd).apply(null,arguments)},qy=t._SelectV2=function(){return(qy=t._SelectV2=t.asm.SelectV2).apply(null,arguments)},Ky=t._Sigmoid=function(){return(Ky=t._Sigmoid=t.asm.Sigmoid).apply(null,arguments)},Ml=t._Sin=function(){return(Ml=t._Sin=t.asm.Sin).apply(null,arguments)},kc=t._Softmax=function(){return(kc=t._Softmax=t.asm.Softmax).apply(null,arguments)},Sh=t._Sqrt=function(){return(Sh=t._Sqrt=t.asm.Sqrt).apply(null,arguments)},Th=t._Square=function(){return(Th=t._Square=t.asm.Square).apply(null,arguments)},Eh=t._SquaredDifference=function(){return(Eh=t._SquaredDifference=t.asm.SquaredDifference).apply(null,arguments)},Xy=t._Step=function(){return(Xy=t._Step=t.asm.Step).apply(null,arguments)},Yy=t._StridedSlice=function(){return(Yy=t._StridedSlice=t.asm.StridedSlice).apply(null,arguments)},Ah=t._Sub=function(){return(Ah=t._Sub=t.asm.Sub).apply(null,arguments)},Zy=t._Sum=function(){return(Zy=t._Sum=t.asm.Sum).apply(null,arguments)},Gs=t._Tanh=function(){return(Gs=t._Tanh=t.asm.Tanh).apply(null,arguments)},Jy=t._Tile=function(){return(Jy=t._Tile=t.asm.Tile).apply(null,arguments)},Qy=t._TopK=function(){return(Qy=t._TopK=t.asm.TopK).apply(null,arguments)},Dh=t._Transpose=function(){return(Dh=t._Transpose=t.asm.Transpose).apply(null,arguments)},qa=t.__FusedMatMul=function(){return(qa=t.__FusedMatMul=t.asm._FusedMatMul).apply(null,arguments)},eb=t._malloc=function(){return(eb=t._malloc=t.asm.malloc).apply(null,arguments)},tb=t._free=function(){return(tb=t._free=t.asm.free).apply(null,arguments)},$h=t.__start=function(){return($h=t.__start=t.asm._start).apply(null,arguments)},tm=t.stackSave=function(){return(tm=t.stackSave=t.asm.stackSave).apply(null,arguments)},rm=t.stackAlloc=function(){return(rm=t.stackAlloc=t.asm.stackAlloc).apply(null,arguments)},Rh=t.stackRestore=function(){return(Rh=t.stackRestore=t.asm.stackRestore).apply(null,arguments)};t.asm=Jp,t.cwrap=X;var Ll;t.then=function(H){if(Ll)H(t);else{var ne=t.onRuntimeInitialized;t.onRuntimeInitialized=function(){ne&&ne(),H(t)}}return t};function om(H){this.name="ExitStatus",this.message="Program terminated with exit("+H+")",this.status=H}var rb=!1;So=function H(){Ll||nm(),Ll||(So=H)};function ob(H){var ne=t.__start;try{ne();var be=0;Fh(be,!0)}catch(Xe){if(Xe instanceof om)return;if(Xe=="unwind"){A=!0;return}else{var Ke=Xe;Xe&&typeof Xe=="object"&&Xe.stack&&(Ke=[Xe,Xe.stack]),v("exception thrown: "+Ke),i(1,Xe)}}finally{rb=!0}}function nm(H){if(H=H||s,Qr>0||(Zt(),Qr>0))return;function ne(){Ll||(Ll=!0,t.calledRun=!0,!z&&(mo(),_r(),t.onRuntimeInitialized&&t.onRuntimeInitialized(),Oh&&ob(H),Jr()))}t.setStatus?(t.setStatus("Running..."),setTimeout(function(){setTimeout(function(){t.setStatus("")},1),ne()},1)):ne()}t.run=nm;function Fh(H,ne){ne&&A&&H===0||(A||(z=!0,W=H,Bo(),t.onExit&&t.onExit(H)),i(H,new om(H)))}if(t.preInit)for(typeof t.preInit=="function"&&(t.preInit=[t.preInit]);t.preInit.length>0;)t.preInit.pop()();var Oh=!0;return t.noInitialRun&&(Oh=!1),A=!0,nm(),e}}();typeof Zx=="object"&&typeof oI=="object"?oI.exports=nI:typeof define=="function"&&define.amd?define([],function(){return nI}):typeof Zx=="object"&&(Zx.WasmBackendModule=nI)});var UB=1e-7,jB=1e-4,Ya=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}},Ws=class{decComplexRef(e){}time(e){return Us("time")}read(e){return Us("read")}readSync(e){return Us("readSync")}numDataIds(){return Us("numDataIds")}disposeData(e){return Us("disposeData")}write(e,t,o){return Us("write")}move(e,t,o,n){return Us("move")}memory(){return Us("memory")}floatPrecision(){return Us("floatPrecision")}epsilon(){return this.floatPrecision()===32?UB:jB}dispose(){return Us("dispose")}};function Us(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 yI(r){let e=r.length,t=0,o=0;for(;e>0;)o=Math.random()*e|0,e--,t=r[e],r[e]=r[o],r[o]=t}function HB(r,e){if(r.length!==e.length)throw 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,o,n,s=0;for(;t>0;)s=Math.random()*t|0,t--,o=r[t],n=e[t],r[t]=r[s],e[t]=e[s],r[s]=o,e[s]=n}function Tc(r,e,t){return Math.max(r,Math.min(e,t))}function qB(r){return r%2==0?r:r+1}function KB(r){let e=0;for(let t=0;t<r.length;t++)e+=r[t];return e}function XB(r,e){let t=Math.random();return e*t+(1-t)*r}function YB(r,e){let t=0;for(let o=0;o<r.length;o++){let n=Number(r[o])-Number(e[o]);t+=n*n}return t}function T(r,e){if(!r)throw new Error(typeof e=="string"?e:e())}function Nt(r,e,t=""){T(Vr(r,e),()=>t+` Shapes ${r} and ${e} must match`)}function To(r){T(r!=null,()=>"The input to the tensor constructor must be a non-null value.")}function os(r,e=[],t=!1){if(e==null&&(e=[]),Array.isArray(r)||rr(r)&&!t)for(let o=0;o<r.length;++o)os(r[o],e,t);else e.push(r);return e}function ft(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 ZB(r){return r.length===0}function Vr(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 JB(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 QB(r){let e=Math.ceil(Math.sqrt(r));return[e,Math.ceil(r/e)]}function e3(r){let e=new Uint32Array(r);for(let t=0;t<r;++t)e[t]=t;return yI(e),e}function zl(r,e){return e<=r.length?r:r+" ".repeat(e-r.length)}function t3(r,e=o=>0,t){return new Promise((o,n)=>{let s=0,a=()=>{if(r()){o();return}s++;let i=e(s);if(t!=null&&s>=t){n();return}setTimeout(a,i)};a()})}function r3(r,e){let t=1,o=-1;for(let s=0;s<r.length;++s)if(r[s]>=0)t*=r[s];else if(r[s]===-1){if(o!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${o} and dim ${s}`);o=s}else if(r[s]<0)throw Error(`Shapes can not be < 0. Found ${r[s]} at dim ${s}`);if(o===-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 n=r.slice();return n[o]=e/t,n}function Jt(r,e){let t=e.length;return r=r==null?e.map((o,n)=>n):[].concat(r),T(r.every(o=>o>=-t&&o<t),()=>`All values in axis param must be in range [-${t}, ${t}) but got axis ${r}`),T(r.every(o=>st(o)),()=>`All values in axis param must be integers but got axis ${r}`),r.map(o=>o<0?t+o:o)}function ub(r,e){let t=[],o=[],n=e!=null&&Array.isArray(e)&&e.length===0,s=e==null||n?null:Jt(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]),o.push(i)),s[a]<=i&&a++}r[i]!==1&&(t.push(r[i]),o.push(i))}return{newShape:t,keptDims:o}}function cb(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 pb(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 mb(r,e){for(let t=0;t<r.length;t++){let o=r[t];if(isNaN(o)||!isFinite(o))throw Error(`A tensor of type ${e} being uploaded contains ${o}.`)}}function fb(r){return r==="bool"||r==="complex64"||r==="float32"||r==="int32"||r==="string"}function o3(r,e){return!(e==="complex64"||e==="float32"&&r!=="complex64"||e==="int32"&&r!=="float32"&&r!=="complex64"||e==="bool"&&r==="bool")}function rr(r){return r instanceof Float32Array||r instanceof Int32Array||r instanceof Uint8Array}function db(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 hb(r){if(r==null)return 0;let e=0;return r.forEach(t=>e+=t.length),e}function ns(r){return typeof r=="string"||r instanceof String}function bI(r){return typeof r=="boolean"}function _I(r){return typeof r=="number"}function Ec(r){return Array.isArray(r)?Ec(r[0]):r instanceof Float32Array?"float32":r instanceof Int32Array||r instanceof Uint8Array?"int32":_I(r)?"float32":ns(r)?"string":bI(r)?"bool":"float32"}function js(r){return!!(r&&r.constructor&&r.call&&r.apply)}function Ac(r,e){for(let t=e;t<r;++t)if(r%t==0)return t;return r}function Hs(r){let e=r.length;if(e<2)return[];let t=new Array(e-1);t[e-2]=r[e-1];for(let o=e-3;o>=0;--o)t[o]=t[o+1]*r[o+1];return t}function wI(r,e,t){let o=new Array;if(e.length===1){let n=e[0];for(let s=0;s<n;s++)o[s]=t[r+s]}else{let n=e[0],s=e.slice(1),a=s.reduce((i,l)=>i*l);for(let i=0;i<n;i++)o[i]=wI(r+i*a,s,t)}return o}function Bl(r,e){if(r.length===0)return e[0];let t=r.reduce((o,n)=>o*n);if(t===0)return[];if(t!==e.length)throw new Error(`[${r}] does not match the input size ${e.length}.`);return wI(0,r,e)}function mm(r,e){let t=Dc(r,e);for(let o=0;o<t.length;o++)t[o]=1;return t}function Dc(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 n3(r,e){let t=r.reduce((o,n)=>o*n,1);if(e==null||e==="float32")return Bl(r,new Float32Array(t));if(e==="int32")return Bl(r,new Int32Array(t));if(e==="bool")return Bl(r,new Uint8Array(t));throw new Error(`Unknown data type ${e}`)}function fm(r){r.forEach(e=>{T(Number.isInteger(e)&&e>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${r}].`)})}function s3(r,e,t){if(e===0)return 0;if(e===1)return r[0];let o=r[r.length-1];for(let n=0;n<r.length-1;++n)o+=t[n]*r[n];return o}function i3(r,e,t){if(e===0)return[];if(e===1)return[r];let o=new Array(e);for(let n=0;n<o.length-1;++n)o[n]=Math.floor(r/t[n]),r-=o[n]*t[n];return o[o.length-1]=r,o}function dm(r){return r&&r.then&&typeof r.then=="function"}var kI="tfjsflags",zh=class{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}setPlatform(e,t){this.platform!=null&&console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${t}.`),this.platformName=e,this.platform=t}registerFlag(e,t,o){if(this.flagRegistry[e]={evaluationFn:t,setHook:o},this.urlFlags[e]!=null){let n=this.urlFlags[e];console.warn(`Setting feature override from URL ${e}: ${n}.`),this.set(e,n)}}async getAsync(e){return e in this.flags?this.flags[e]:(this.flags[e]=await this.evaluateFlag(e),this.flags[e])}get(e){if(e in this.flags)return this.flags[e];let t=this.evaluateFlag(e);if(dm(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=a3(this.global.location.search);kI in e&&e[kI].split(",").forEach(o=>{let[n,s]=o.split(":");this.urlFlags[n]=l3(n,s)})}};function a3(r){let e={};return r.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(t,...o)=>(u3(e,o[0],o[1]),o.join("="))),e}function u3(r,e,t){r[decodeURIComponent(e)]=decodeURIComponent(t||"")}function l3(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 G(){return gb}var gb=null;function vI(r){gb=r}var xb;function yb(){if(xb==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");xb=r}return xb}function c3(){let r=yb();return r._tfGlobals==null&&(r._tfGlobals=new Map),r._tfGlobals}function hm(r,e){let t=c3();if(t.has(r))return t.get(r);{let o=e();return t.set(r,o),t.get(r)}}var ss="Abs",qs="Acos",Ks="Acosh",xo="Add",Uo="AddN",Vl="All",Gl="Any",jo="ArgMax",oa="ArgMin",Xs="Asin",Ys="Asinh",Zs="Atan",Js="Atanh",Qs="Atan2",Ho="AvgPool",Wl="AvgPoolGrad",na="AvgPool3D",Ul="AvgPool3DGrad",qo="BatchMatMul",sa="BatchToSpaceND",jl="Bincount",bb="BroadcastTo",Eo="Cast",ei="Ceil",Ao="ClipByValue",Hl="Complex",ia="ComplexAbs",is="Concat",Ko="Conv2D",ql="Conv2DBackpropFilter",Xo="Conv2DBackpropInput",aa="Conv3D",Kl="Conv3DBackpropFilterV2",Xl="Conv3DBackpropInputV2",Yo="Cos",ti="Cosh",Zo="Cumsum",ri="CropAndResize",Yl="DenseBincount",oi="DepthToSpace",Jo="DepthwiseConv2dNative",Zl="DepthwiseConv2dNativeBackpropFilter",Jl="DepthwiseConv2dNativeBackpropInput",Ql="Diag",la="Dilation2D",$c="Dilation2DBackpropInput",Rc="Dilation2DBackpropFilter",Qo="RealDiv",ni="Elu",eu="EluGrad",si="Erf",ii="Equal",en="Exp",as="ExpandDims",ai="Expm1",tu="FFT",ua="Fill",li="FlipLeftRight",tn="Floor",rn="FloorDiv",on="FusedBatchNorm",ls="GatherV2",ui="GatherNd",ci="Greater",nn="GreaterEqual",us="Identity",ru="IFFT",ou="Imag",pi="IsFinite",mi="IsInf",fi="IsNan",sn="LeakyRelu",di="Less",hi="LessEqual",nu="LinSpace",an="Log",gi="Log1p",xi="LogicalAnd",Za="LogicalNot",Ja="LogicalOr",_b="LogSoftmax",ca="LRN",su="LRNGrad",ln="Max",un="Maximum",cn="MaxPool",iu="MaxPoolGrad",pa="MaxPool3D",au="MaxPool3DGrad",lu="MaxPoolWithArgmax",pn="Mean",mn="Min",fn="Minimum",ma="MirrorPad",yi="Mod",uu="Multinomial",dn="Multiply",cs="Neg",bi="NotEqual",_i="NonMaxSuppressionV3",wi="NonMaxSuppressionV4",ki="NonMaxSuppressionV5",ps="OnesLike",hn="OneHot",ms="Pack",gn="PadV2",p3="Pool",xn="Pow",yn="Prelu",vi="Prod",fa="Range",cu="Real",Ci="Reciprocal",bn="Relu",fs="Reshape",da="ResizeNearestNeighbor",pu="ResizeNearestNeighborGrad",_n="ResizeBilinear",mu="ResizeBilinearGrad",wn="Relu6",kn="Reverse",vn="Round",Cn="Rsqrt",Ii="ScatterNd",ds="Select",Ni="Selu",hs="Slice",In="Sin",Si="Sinh",Ti="Sign",Nn="Sigmoid",Ei="Softplus",Sn="Sqrt",Tn="Sum",ha="SpaceToBatchND",gs="SplitV",En="Softmax",An="SquaredDifference",ga="Square",Dn="Sub",fu="SparseToDense",Ai="StridedSlice",Di="Tan",$n="Tanh",yo="Tile",$i="TopK",Rn="Transpose",du="Unique",xs="Unpack",xa="UnsortedSegmentSum",ys="ZerosLike",Do="Step",Fc="FromPixels",Ri="RotateWithOffset",bs="_FusedMatMul",_s="FusedConv2D",ws="FusedDepthwiseConv2D";var Oc=hm("kernelRegistry",()=>new Map),gm=hm("gradRegistry",()=>new Map);function Pc(r,e){let t=wb(r,e);return Oc.get(t)}function Bh(r){return gm.get(r)}function xm(r){let e=Oc.entries(),t=[];for(;;){let{done:o,value:n}=e.next();if(o)break;let[s,a]=n,[i]=s.split("_");i===r&&t.push(a)}return t}function Qa(r){let{kernelName:e,backendName:t}=r,o=wb(e,t);Oc.has(o)&&console.warn(`The kernel '${e}' for backend '${t}' is already registered`),Oc.set(o,r)}function kb(r){let{kernelName:e}=r;gm.has(e)&&G().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${e}'`),gm.set(e,r)}function m3(r,e){let t=wb(r,e);if(!Oc.has(t))throw new Error(`The kernel '${r}' for backend '${e}' is not registered`);Oc.delete(t)}function f3(r){if(!gm.has(r))throw new Error(`The gradient '${r}' for backend is not registered`);gm.delete(r)}function d3(r,e){xm(r).forEach(o=>{let n=Object.assign({},o,{backendName:e});Qa(n)})}function wb(r,e){return`${e}_${r}`}var y={};et(y,{arraysEqual:()=>Vr,assert:()=>T,assertNonNegativeIntegerDimensions:()=>fm,assertNonNull:()=>To,assertShapesMatch:()=>Nt,bytesFromStringArray:()=>hb,bytesPerElement:()=>db,checkConversionForErrors:()=>mb,clamp:()=>Tc,computeStrides:()=>Hs,createScalarValue:()=>h3,createShuffledIndices:()=>e3,decodeString:()=>Lc,distSquared:()=>YB,encodeString:()=>el,fetch:()=>x3,flatten:()=>os,getArrayFromDType:()=>pb,getTypedArrayFromDType:()=>cb,hasEncodingLoss:()=>o3,indexToLoc:()=>i3,inferDtype:()=>Ec,inferFromImplicitShape:()=>r3,isBoolean:()=>bI,isFunction:()=>js,isInt:()=>st,isNumber:()=>_I,isPromise:()=>dm,isScalarShape:()=>ZB,isString:()=>ns,isTypedArray:()=>rr,isValidDtype:()=>fb,locToIndex:()=>s3,makeOnesTypedArray:()=>mm,makeZerosNestedTypedArray:()=>n3,makeZerosTypedArray:()=>Dc,nearestDivisor:()=>Ac,nearestLargerEven:()=>qB,now:()=>Vh,parseAxisParam:()=>Jt,randUniform:()=>XB,repeatedTry:()=>t3,rightPad:()=>zl,shuffle:()=>yI,shuffleCombo:()=>HB,sizeFromShape:()=>ft,sizeToSquarishShape:()=>QB,squeezeShape:()=>ub,sum:()=>KB,tanh:()=>JB,toNestedArray:()=>Bl,toTypedArray:()=>Mc});function h3(r,e){return e==="string"?el(r):Mc([r],e)}function g3(r,e){return r instanceof Float32Array&&e==="float32"||r instanceof Int32Array&&e==="int32"||r instanceof Uint8Array&&e==="bool"}function Mc(r,e){if(e==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(r)&&(r=os(r)),G().getBool("DEBUG")&&mb(r,e),g3(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 o=0;o<t.length;++o)Math.round(r[o])!==0&&(t[o]=1);return t}else throw new Error(`Unknown data type ${e}`)}function Vh(){return G().platform.now()}function x3(r,e){return G().platform.fetch(r,e)}function el(r,e="utf-8"){return e=e||"utf-8",G().platform.encode(r,e)}function Lc(r,e="utf-8"){return e=e||"utf-8",G().platform.decode(r,e)}var vb=class{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new CI)}profileKernel(e,t,o){let n,s=()=>{n=o()},a=this.backendTimer.time(s);if(G().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let l=0;l<n.length;l++){let u=n[l];u.data().then(c=>{y3(c,u.dtype,e)})}return{kernelName:e,outputs:n,inputs:t,timeMs:a.then(l=>l.kernelMs),extraInfo:a.then(l=>l.getExtraProfileInfo!=null?l.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:o,timeMs:n,inputs:s,extraInfo:a}=e;o.forEach(i=>{Promise.all([i.data(),n,a]).then(l=>{this.logger.logKernelProfile(t,i,l[0],l[1],s,l[2])})})}};function y3(r,e,t){if(e!=="float32")return!1;for(let o=0;o<r.length;o++){let n=r[o];if(isNaN(n)||!isFinite(n))return console.warn(`Found ${n} in the result of '${t}'`),!0}return!1}var CI=class{logKernelProfile(e,t,o,n,s,a){let i=typeof n=="number"?zl(`${n}ms`,9):n.error,l=zl(e,25),u=t.rank,c=t.size,p=zl(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 II(r,e,t){let o={},n={};for(let l=0;l<e.length;l++)o[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(o[m.id]){u.outputs.forEach(h=>o[h.id]=!0),f=!0,n[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(n[u.id]&&a[u.id]){let c={};for(let m in u.inputs){let f=u.inputs[m];o[f.id]&&(c[m]=f)}let p=Object.assign({},u);p.inputs=c,p.outputs=u.outputs,i.push(p)}}return i}function NI(r,e,t,o){for(let n=e.length-1;n>=0;n--){let s=e[n],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(!Vr(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]=o(p,u),p.dispose()}}}}var SI=20,ym=3,Cb=7;function TI(r,e,t,o){let n=Hs(e),s=b3(r,e,t,n),a=e.length,i=Gh(r,e,t,n,s),l=["Tensor"];return o&&(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 b3(r,e,t,o){let n=ft(e),s=o[o.length-1],a=new Array(s).fill(0),i=e.length,l=t==="complex64"?_m(r):r;if(i>1)for(let u=0;u<n/s;u++){let c=u*s;for(let p=0;p<s;p++)a[p]=Math.max(a[p],bm(l[c+p],0,t).length)}return a}function bm(r,e,t){let o;return Array.isArray(r)?o=`${parseFloat(r[0].toFixed(Cb))} + ${parseFloat(r[1].toFixed(Cb))}j`:ns(r)?o=`'${r}'`:t==="bool"?o=EI(r):o=parseFloat(r.toFixed(Cb)).toString(),zl(o,e)}function EI(r){return r===0?"false":"true"}function Gh(r,e,t,o,n,s=!0){let a=t==="complex64"?2:1,i=e[0],l=e.length;if(l===0){if(t==="complex64"){let h=_m(r);return[bm(h[0],0,t)]}return t==="bool"?[EI(r[0])]:[r[0].toString()]}if(l===1){if(i>SI){let g=ym*a,x=Array.from(r.slice(0,g)),b=Array.from(r.slice((i-ym)*a,i*a));return t==="complex64"&&(x=_m(x),b=_m(b)),["["+x.map((_,w)=>bm(_,n[w],t)).join(", ")+", ..., "+b.map((_,w)=>bm(_,n[i-ym+w],t)).join(", ")+"]"]}let h=t==="complex64"?_m(r):Array.from(r);return["["+h.map((g,x)=>bm(g,n[x],t)).join(", ")+"]"]}let u=e.slice(1),c=o.slice(1),p=o[0]*a,m=[];if(i>SI){for(let h=0;h<ym;h++){let g=h*p,x=g+p;m.push(...Gh(r.slice(g,x),u,t,c,n,!1))}m.push("...");for(let h=i-ym;h<i;h++){let g=h*p,x=g+p;m.push(...Gh(r.slice(g,x),u,t,c,n,h===i-1))}}else for(let h=0;h<i;h++){let g=h*p,x=g+p;m.push(...Gh(r.slice(g,x),u,t,c,n,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 _m(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,o){if(this.dtype=t,this.shape=e.slice(),this.size=ft(e),o!=null){let n=o.length;T(n===this.size,()=>`Length of values '${n}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=o||pb(t,this.size),this.strides=Hs(e)}set(e,...t){t.length===0&&(t=[0]),T(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let o=this.locToIndex(t);this.values[o]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let n of e){if(n<0||n>=this.shape[t]){let s=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(s)}t++}let o=e[e.length-1];for(let n=0;n<e.length-1;++n)o+=this.strides[n]*e[n];return this.values[o]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let o=0;o<e.length-1;++o)t+=this.strides[o]*e[o];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];let t=new Array(this.shape.length);for(let o=0;o<t.length-1;++o)t[o]=Math.floor(e/this.strides[o]),e-=t[o]*this.strides[o];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Fi().makeTensor(this.values,this.shape,this.dtype)}},Fi=null,zc=null,_3=null;function AI(r){Fi=r}function DI(r){zc=r}function $I(r){_3=r}var Ve=class{constructor(e,t,o,n){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=ft(e),this.strides=Hs(e),this.dataId=o,this.id=n,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let e=await this.data();return zc.buffer(this.shape,this.dtype,e)}bufferSync(){return zc.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return Bl(this.shape,e)}arraySync(){return Bl(this.shape,this.dataSync())}async data(){this.throwIfDisposed();let e=Fi().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(o=>Lc(o))}catch(o){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=Fi().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Lc(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 Fi().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Fi().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return zc.print(this,e)}clone(){return this.throwIfDisposed(),zc.clone(this)}toString(e=!1){let t=this.dataSync();return TI(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),zc.cast(this,e)}variable(e=!0,t,o){return this.throwIfDisposed(),Fi().makeVariable(this,e,t,o)}};Object.defineProperty(Ve,Symbol.hasInstance,{value:r=>!!r&&r.data!=null&&r.dataSync!=null&&r.throwIfDisposed!=null});function F(){return hm("Tensor",()=>Ve)}F();var tl=class extends Ve{constructor(e,t,o,n){super(e.shape,e.dtype,e.dataId,n);this.trainable=t,this.name=o}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(!Vr(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Fi().disposeTensor(this),this.dataId=e.dataId,Fi().incRef(this,null)}dispose(){Fi().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(tl,Symbol.hasInstance,{value:r=>r instanceof Ve&&r.assign!=null&&r.assign instanceof Function});var Fn={};et(Fn,{assertTypesMatch:()=>Ab,getTensorsInContainer:()=>wm,isTensorInList:()=>k3,makeTypesMatch:()=>Ge});var Ib;(function(r){r.R0="R0",r.R1="R1",r.R2="R2",r.R3="R3",r.R4="R4",r.R5="R5",r.R6="R6"})(Ib||(Ib={}));var Nb;(function(r){r.float32="float32",r.int32="int32",r.bool="int32",r.complex64="complex64"})(Nb||(Nb={}));var Sb;(function(r){r.float32="float32",r.int32="int32",r.bool="bool",r.complex64="complex64"})(Sb||(Sb={}));var Tb;(function(r){r.float32="float32",r.int32="float32",r.bool="float32",r.complex64="complex64"})(Tb||(Tb={}));var Eb;(function(r){r.float32="complex64",r.int32="complex64",r.bool="complex64",r.complex64="complex64"})(Eb||(Eb={}));var w3={float32:Tb,int32:Nb,bool:Sb,complex64:Eb};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 w3[r][e]}function hu(r){return mr(r,"int32")}function Ge(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 Ab(r,e){T(r.dtype===e.dtype,()=>`The dtypes of the first(${r.dtype}) and second(${e.dtype}) input must match`)}function k3(r,e){return e.some(t=>t.id===r.id)}function wm(r){let e=[],t=new Set;return RI(r,e,t),e}function RI(r,e,t){if(r==null)return;if(r instanceof Ve){e.push(r);return}if(!v3(r))return;let o=r;for(let n in o){let s=o[n];t.has(s)||(t.add(s),RI(s,e,t))}}function v3(r){return Array.isArray(r)||typeof r=="object"}function Db(r){return r.kernelName!=null}var $b=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()}},gu=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new $b}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 o=e[t];if(await this.initializeBackend(o).success){await this.setBackend(o);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,o=1){return e in this.registryFactory?(console.warn(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:o},!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:o}=this.initializeBackend(e);if(!(o?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new vb(this.backendInstance),!0}setupRegisteredKernels(){xm(this.backendName).forEach(t=>{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){xm(e).forEach(o=>{o.disposeFunc!=null&&o.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 o=t.factory();if(o&&!(o instanceof Ws)&&typeof o.then=="function"){let n=++this.pendingBackendInitId,s=o.then(a=>n<this.pendingBackendInitId?!1:(this.registry[e]=a,this.pendingBackendInit=null,!0)).catch(a=>(n<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]=o,{success:!0,asyncInit:!1}}catch(o){return console.warn(`Initialization of backend ${e} failed`),console.warn(o.stack||o.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 o=e[t],{success:n,asyncInit:s}=this.initializeBackend(o);if(s||n)return{name:o,asyncInit:s}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){let o=this.state.tensorInfo.get(t),n=o.backend,s=this.readSync(t);n.disposeData(t),o.backend=e,e.move(t,s,o.shape,o.dtype),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let o=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");o=e}let n;return this.scopedRun(()=>this.startScope(o),()=>this.endScope(n),()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n))}scopedRun(e,t,o){e();try{let n=o();return t(),n}catch(n){throw t(),n}}nextTensorId(){return gu.nextTensorId++}nextVariableId(){return gu.nextVariableId++}clone(e){let t=this.makeTensorFromDataId(e.dataId,e.shape,e.dtype),o={x:e},n=a=>({x:()=>{let i="float32",l={x:a},u={dtype:i};return E.runKernel(Eo,l,u)}}),s=[];return this.addTapeNode(this.state.activeScope.name,o,[t],n,s,{}),t}runKernel(e,t,o){if(!(Pc(e,this.backendName)!=null))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:o})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,o){let n=this.backend.numDataIds(),s=0;o.forEach(l=>{s+=l.dtype==="complex64"?3:1});let a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=n-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,o=[],n=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=Db(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(Db(e)){let{kernelName:d,inputs:h,attrs:g}=e;this.backendName==null&&this.backend;let x=Pc(d,this.backendName);T(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 _=Array.isArray(l)?l:[l];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(d,b,_);let w=_.map(v=>{if(v.rank!=null)return v;let{dataId:$,shape:A,dtype:R}=v;return this.makeTensorFromDataId($,A,R)});if(n){let v=this.getTensorsForGradient(d,h,w);o=this.saveTensorsForBackwardMode(v)}return w}}else{let{forwardFunc:d}=e,h=g=>{!n||(o=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=Db(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)}),n&&this.addTapeNode(u,c,t,m,o,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(o=>this.keep(this.clone(o)))}getTensorsForGradient(e,t,o){let n=Bh(e);if(n!=null){let s=n.inputsToSave||[],a=n.outputsToSave||[],i;n.saveAllInputs?(T(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=o.filter((u,c)=>a[c]);return i.concat(l)}return[]}makeTensor(e,t,o,n){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");o=o||"float32",n=n||this.backend;let s=e;o==="string"&&ns(e[0])&&(s=e.map(l=>el(l)));let a=n.write(s,t,o),i=new Ve(t,o,a,this.nextTensorId());if(this.incRef(i,n),o==="string"){let l=this.state.tensorInfo.get(a),u=hb(s);this.state.numBytes+=u-l.bytes,l.bytes=u}return i}makeTensorFromDataId(e,t,o,n){o=o||"float32";let s=new Ve(t,o,e,this.nextTensorId());return this.incRef(s,n),s}makeVariable(e,t=!0,o,n){o=o||this.nextVariableId().toString(),n!=null&&n!==e.dtype&&(e=e.cast(n));let s=new tl(e,t,o,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}incRef(e,t){let o=this.state.tensorInfo.has(e.dataId)?this.state.tensorInfo.get(e.dataId).refCount:0;if(this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++,o===0){this.state.numDataBuffers++;let n=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(n=e.size*db(e.dtype)),this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n,refCount:0}),this.state.numBytes+=n}this.state.tensorInfo.get(e.dataId).refCount++,e instanceof tl||this.track(e)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;this.state.numTensors--,e.dtype==="string"&&this.state.numStringTensors--;let t=this.state.tensorInfo.get(e.dataId);t.refCount<=1?(e.dtype!=="complex64"&&(this.state.numBytes-=t.bytes),this.state.numDataBuffers--,t.backend.disposeData(e.dataId),this.state.tensorInfo.delete(e.dataId)):(t.backend.decComplexRef(e.dataId),this.state.tensorInfo.get(e.dataId).refCount--)}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,o=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(n=>n.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-o;for(let n of this.state.activeProfile.kernels)n.kernelTimeMs=await n.kernelTimeMs,n.extraInfo=await n.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,o,n,s,a){let i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:o,saved:s},l=Bh(e);l!=null&&(n=l.gradFunc),n!=null&&(i.gradient=u=>(u=u.map((c,p)=>{if(c==null){let m=o[p],f=Dc(m.size,m.dtype);return this.makeTensor(f,m.shape,m.dtype)}return c}),n(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=wm(e),o=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&&!o.has(a.id)&&a.dispose()}let n=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===n.id&&this.track(s)})}gradients(e,t,o,n=!1){if(T(t.length>0,()=>"gradients() received an empty list of xs."),o!=null&&o.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${o.dtype}'`);let s=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));T(s instanceof Ve,()=>"The result y returned by f() must be a tensor.");let a=II(this.state.activeTape,t,s);if(!n&&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]=o==null?C3(s.shape):o,NI(i,a,u=>this.tidy(u),I3);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 T(js(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{T(t.every(i=>i instanceof Ve),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let o,n={};t.forEach((i,l)=>{n[l]=i});let s=(i,l)=>(o=e(...t,l),T(o.value instanceof Ve,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),T(js(o.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),o.value),a=(i,l)=>{let u=o.gradFunc(i,l),c=Array.isArray(u)?u:[u];T(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(...)."),T(c.every(m=>m instanceof Ve),()=>"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:n})}}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=Vh(),o=await this.backend.time(e);return o.wallMs=Vh()-t,o}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 $b;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}};gu.nextTensorId=0;gu.nextVariableId=0;function C3(r){let e=mm(ft(r),"float32");return E.makeTensor(e,r,"float32")}function Rb(){let r=yb();if(r._tfengine==null){let e=new zh(r);r._tfengine=new gu(e)}return vI(r._tfengine.ENV),AI(()=>r._tfengine),r._tfengine}var E=Rb();function I3(r,e){let t={a:r,b:e};return E.runKernel(xo,t)}var Bc={};et(Bc,{isBrowser:()=>Fb,isMobile:()=>S3});function N3(){return typeof navigator!="undefined"&&navigator!=null}function S3(){if(N3()){let r=navigator.userAgent||navigator.vendor||window.opera;return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(r)||/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(r.substr(0,4))}return!1}function Fb(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var Oi=G();Oi.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.")});Oi.registerFlag("IS_BROWSER",()=>Fb());Oi.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Oi.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Oi.registerFlag("PROD",()=>!1);Oi.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Oi.getBool("DEBUG"));Oi.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Oi.registerFlag("IS_TEST",()=>!1);Oi.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);function kr(r,e){let t=r;if(rr(r))return e==="string"?[]:[r.length];if(!Array.isArray(r))return[];let o=[];for(;Array.isArray(t)||rr(t)&&e!=="string";)o.push(t.length),t=t[0];return Array.isArray(r)&&G().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&FI(r,o,[]),o}function FI(r,e,t){if(t=t||[],!Array.isArray(r)&&!rr(r)){T(e.length===0,()=>`Element arr[${t.join("][")}] is a primitive, but should be an array/TypedArray of ${e[0]} elements`);return}T(e.length>0,()=>`Element arr[${t.join("][")}] should be a primitive, but is an array of ${r.length} elements`),T(r.length===e[0],()=>`Element arr[${t.join("][")}] should have ${e[0]} elements, but has ${r.length} elements`);let o=e.slice(1);for(let n=0;n<r.length;++n)FI(r[n],o,t.concat(n))}function OI(r,e,t,o){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 '${o}' must be ${r} tensor, but got ${e} tensor`)}}function k(r,e,t,o="numeric"){if(r instanceof Ve)return OI(o,r.dtype,e,t),r;let n=Ec(r);if(n!=="string"&&["bool","int32","float32"].indexOf(o)>=0&&(n=o),OI(o,n,e,t),r==null||!rr(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=kr(r,n);!rr(r)&&!Array.isArray(r)&&(r=[r]);let i=n!=="string"?Mc(r,n):os(r,[],!0);return E.makeTensor(i,s,n)}function ya(r,e,t,o="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,o))}var PI="__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],o=r[t];t.endsWith("_")&&(t=t.substring(0,t.length-1)),t=t+PI;let n=(...s)=>{E.startScope(t);try{let a=o(...s);return dm(a)&&console.error("Cannot return a Promise inside of tidy."),E.endScope(a),a}catch(a){throw E.endScope(null),a}};return Object.defineProperty(n,"name",{value:t,configurable:!0}),n}function T3(r,e){let t=k(r,"real","complex"),o=k(e,"imag","complex");Nt(t.shape,o.shape,`real and imag shapes, ${t.shape} and ${o.shape}, must match in call to tf.complex().`);let n={real:t,imag:o};return E.runKernel(Hl,n)}var bo=S({complex_:T3});function Gr(r,e,t,o){if(o==null&&(o=Ec(r)),o==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!rr(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){fm(e);let n=ft(e),s=ft(t);T(n===s,()=>`Based on the provided shape, [${e}], the tensor should have ${n} values but has ${s}`);for(let a=0;a<t.length;++a){let i=t[a],l=a===t.length-1?i!==ft(e.slice(a)):!0;T(t[a]===e[a]||!l,()=>`Error creating a new Tensor. Inferred shape (${t}) does not match the provided shape (${e}). `)}}return!rr(r)&&!Array.isArray(r)&&(r=[r]),e=e||t,r=o!=="string"?Mc(r,o):os(r,[],!0),E.makeTensor(r,e,o)}function Dr(r,e,t){let o=kr(r,t);return Gr(r,e,o,t)}var km={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};var Wh=4;async function MI(r,e){let t=[],o=[],n=Array.isArray(r)?r.map(a=>a.name):Object.keys(r);for(let a=0;a<n.length;++a){let i=n[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)+Wh*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+=Wh,d.set(x,h),h+=x.length}p(d)});o.push(c)}else o.push(l.data());e!=null&&(u.group=e),t.push(u)}let s=await Promise.all(o);return{data:E3(s),specs:t}}function Uh(r,e){let t={},o,n=0;for(let s of e){let a=s.name,i=s.dtype,l=s.shape,u=ft(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=km[p.dtype],f=r.slice(n,n+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")o===void 0&&(o=A3()),c=o(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}`);n+=u*m}else if(i==="string"){let p=ft(s.shape);c=[];for(let m=0;m<p;m++){let f=new Uint32Array(r.slice(n,n+Wh))[0];n+=Wh;let d=new Uint8Array(r.slice(n,n+f));c.push(d),n+=f}}else{let p=km[i],m=r.slice(n,n+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=Dr(f,l,"float32"),g=Dr(d,l,"float32");t[a]=bo(h,g),h.dispose(),g.dispose()}else throw new Error(`Unsupported dtype in weight '${a}': ${i}`);n+=u*p}i!=="complex64"&&(t[a]=Dr(c,l,i))}return t}function E3(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 o=new Uint8Array(e),n=0;return t.forEach(s=>{o.set(new Uint8Array(s.buffer),n),n+=s.byteLength}),o.buffer}var Ob=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function LI(r){return Ob?Buffer.byteLength(r):new Blob([r]).size}function zI(r){if(Ob)return Buffer.from(r).toString("base64");let e=new Uint8Array(r),t="";for(let o=0,n=e.length;o<n;o++)t+=String.fromCharCode(e[o]);return btoa(t)}function BI(r){if(Ob){let o=Buffer.from(r,"base64");return o.buffer.slice(o.byteOffset,o.byteOffset+o.byteLength)}let e=atob(r),t=new Uint8Array(e.length);for(let o=0;o<e.length;++o)t.set([e.charCodeAt(o)],o);return t.buffer}function Vc(r){if(r.length===1)return r[0];let e=0;r.forEach(n=>{e+=n.byteLength});let t=new Uint8Array(e),o=0;return r.forEach(n=>{t.set(new Uint8Array(n),o),o+=n.byteLength}),t.buffer}function Pb(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 Pi(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:LI(JSON.stringify(r.modelTopology)),weightSpecsBytes:r.weightSpecs==null?0:LI(JSON.stringify(r.weightSpecs)),weightDataBytes:r.weightData==null?0:r.weightData.byteLength}}function D3(){let r=t=>{let o=t<<13,n=0;for(;(o&8388608)==0;)n-=8388608,o<<=1;return o&=~8388608,n+=947912704,o|n},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 $3(){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 R3(){let r=new Uint32Array(64);for(let e=0;e<64;e++)r[e]=1024;return r[0]=r[32]=0,r}function A3(){let r=D3(),e=$3(),t=R3();return o=>{let n=new ArrayBuffer(4*o.length),s=new Uint32Array(n);for(let a=0;a<o.length;a++){let i=o[a],l=r[t[i>>10]+(i&1023)]+e[i>>10];s[a]=l}return new Float32Array(n)}}var St=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return St.instance==null&&(St.instance=new St),St.instance}static registerSaveRouter(e){St.getInstance().saveRouters.push(e)}static registerLoadRouter(e){St.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return St.getHandlers(e,"save")}static getLoadHandlers(e,t){return St.getHandlers(e,"load",t)}static getHandlers(e,t,o){let n=[];return(t==="load"?St.getInstance().loadRouters:St.getInstance().saveRouters).forEach(a=>{let i=a(e,o);i!==null&&n.push(i)}),n}},VI=r=>St.registerSaveRouter(r),GI=r=>St.registerLoadRouter(r),WI=r=>St.getSaveHandlers(r),UI=(r,e)=>St.getLoadHandlers(r,e);var Mb="tensorflowjs",Lb=1,xu="models_store",rl="model_info_store";function jI(){if(!G().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 zb(r){let e=r.result;e.createObjectStore(xu,{keyPath:"modelPath"}),e.createObjectStore(rl,{keyPath:"modelPath"})}var ba=class{constructor(e){if(this.indexedDB=jI(),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((o,n)=>{let s=this.indexedDB.open(Mb,Lb);s.onupgradeneeded=()=>zb(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(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));o(u.result.modelArtifacts)},u.onerror=c=>(a.close(),n(u.error)),i.oncomplete=()=>a.close()}else{let i=Pi(t),l=a.transaction(rl,"readwrite"),u=l.objectStore(rl),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=()=>o({modelArtifactsInfo:i}),f.onerror=d=>{u=l.objectStore(rl);let h=u.delete(this.modelPath);h.onsuccess=()=>(a.close(),n(f.error)),h.onerror=g=>(a.close(),n(f.error))}},c.onerror=m=>(a.close(),n(c.error)),l.oncomplete=()=>{p==null?a.close():p.oncomplete=()=>a.close()}}},s.onerror=a=>n(s.error)})}};ba.URL_SCHEME="indexeddb://";var HI=r=>G().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(ba.URL_SCHEME)?F3(r.slice(ba.URL_SCHEME.length)):null;St.registerSaveRouter(HI);St.registerLoadRouter(HI);function F3(r){return new ba(r)}function O3(r){return r.startsWith(ba.URL_SCHEME)?r.slice(ba.URL_SCHEME.length):r}var Bb=class{constructor(){this.indexedDB=jI()}async listModels(){return new Promise((e,t)=>{let o=this.indexedDB.open(Mb,Lb);o.onupgradeneeded=()=>zb(o),o.onsuccess=()=>{let n=o.result,s=n.transaction(rl,"readonly"),i=s.objectStore(rl).getAll();i.onsuccess=()=>{let l={};for(let u of i.result)l[u.modelPath]=u.modelArtifactsInfo;e(l)},i.onerror=l=>(n.close(),t(i.error)),s.oncomplete=()=>n.close()},o.onerror=n=>t(o.error)})}async removeModel(e){return e=O3(e),new Promise((t,o)=>{let n=this.indexedDB.open(Mb,Lb);n.onupgradeneeded=()=>zb(n),n.onsuccess=()=>{let s=n.result,a=s.transaction(rl,"readwrite"),i=a.objectStore(rl),l=i.get(e),u;l.onsuccess=()=>{if(l.result==null)return s.close(),o(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=>o(l.error)};c.onsuccess=p,c.onerror=m=>(p(),s.close(),o(l.error))}},l.onerror=c=>(s.close(),o(l.error)),a.oncomplete=()=>{u==null?s.close():u.oncomplete=()=>s.close()}},n.onerror=s=>o(n.error)})}};var _a="/",Gc="tensorflowjs_models",qI="info",P3="model_topology",M3="weight_specs",L3="weight_data",z3="model_metadata";function KI(r){return{info:[Gc,r,qI].join(_a),topology:[Gc,r,P3].join(_a),weightSpecs:[Gc,r,M3].join(_a),weightData:[Gc,r,L3].join(_a),modelMetadata:[Gc,r,z3].join(_a)}}function B3(r){let e=r.split(_a);if(e.length<3)throw new Error(`Invalid key format: ${r}`);return e.slice(1,e.length-1).join(_a)}function V3(r){return r.startsWith(wa.URL_SCHEME)?r.slice(wa.URL_SCHEME.length):r}var wa=class{constructor(e){if(!G().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=KI(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),o=JSON.stringify(e.weightSpecs),n=Pi(e);try{this.LS.setItem(this.keys.info,JSON.stringify(n)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,o),this.LS.setItem(this.keys.weightData,zI(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:n}}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=${n.modelTopologyBytes}, weightSpecsBytes=${n.weightSpecsBytes}, weightDataBytes=${n.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={},o=JSON.parse(this.LS.getItem(this.keys.topology));if(o==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=o;let n=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(n==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=n;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=BI(a),t}};wa.URL_SCHEME="localstorage://";var XI=r=>G().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(wa.URL_SCHEME)?G3(r.slice(wa.URL_SCHEME.length)):null;St.registerSaveRouter(XI);St.registerLoadRouter(XI);function G3(r){return new wa(r)}var Vb=class{constructor(){T(G().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),T(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=Gc+_a,o=_a+qI;for(let n=0;n<this.LS.length;++n){let s=this.LS.key(n);if(s.startsWith(t)&&s.endsWith(o)){let a=B3(s);e[a]=JSON.parse(this.LS.getItem(s))}}return e}async removeModel(e){e=V3(e);let t=KI(e);if(this.LS.getItem(t.info)==null)throw new Error(`Cannot find model at path '${e}'`);let o=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),o}};var Wc="://",Wr=class{constructor(){this.managers={}}static getInstance(){return Wr.instance==null&&(Wr.instance=new Wr),Wr.instance}static registerManager(e,t){T(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(Wc)&&(e=e.slice(0,e.indexOf(Wc))),T(e.length>0,()=>"scheme must not be an empty string.");let o=Wr.getInstance();T(o.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),o.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 jh(r){if(r.indexOf(Wc)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Wr.getSchemes().join(",")}`);return{scheme:r.split(Wc)[0],path:r.split(Wc)[1]}}async function YI(r,e,t=!1){T(r!==e,()=>`Old path and new path are the same: '${r}'`);let o=St.getLoadHandlers(r);T(o.length>0,()=>`Copying failed because no load handler is found for source URL ${r}.`),T(o.length<2,()=>`Copying failed because more than one (${o.length}) load handlers for source URL ${r}.`);let n=o[0],s=St.getSaveHandlers(e);T(s.length>0,()=>`Copying failed because no save handler is found for destination URL ${e}.`),T(s.length<2,()=>`Copying failed because more than one (${o.length}) save handlers for destination URL ${e}.`);let a=s[0],i=jh(r).scheme,l=jh(r).path,u=i===jh(r).scheme,c=await n.load();t&&u&&await Wr.getManager(i).removeModel(l);let p=await a.save(c);return t&&!u&&await Wr.getManager(i).removeModel(l),p.modelArtifactsInfo}async function ZI(){let r=Wr.getSchemes(),e={};for(let t of r){let o=await Wr.getManager(t).listModels();for(let n in o){let s=t+Wc+n;e[s]=o[n]}}return e}async function JI(r){let e=jh(r);return Wr.getManager(e.scheme).removeModel(e.path)}async function QI(r,e){return YI(r,e,!1)}async function eN(r,e){return YI(r,e,!0)}var tN=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(G().get("IS_BROWSER")){G().setPlatform("browser",new tN);try{Wr.registerManager(wa.URL_SCHEME,new Vb)}catch(r){}try{Wr.registerManager(ba.URL_SCHEME,new Bb)}catch(r){}}var W3={importFetch:()=>rN()},Gb;var oN=class{constructor(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return G().global.fetch!=null?G().global.fetch(e,t):(Gb==null&&(Gb=W3.importFetch()),Gb(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)}};G().get("IS_NODE")&&G().setPlatform("node",new oN);function Ce(r,e="float32",t){return e=e||"float32",fm(r),new ct(r,e,t)}function U3(r,e){let t=k(r,"x","cast");if(!fb(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 o={x:t},n={dtype:e};return E.runKernel(Eo,o,n)}var oe=S({cast_:U3});function j3(r){let t={x:k(r,"x","clone","string_or_numeric")};return E.runKernel(us,t)}var $o=S({clone_:j3});function Wb(r,e=!1){console.log(r.toString(e))}Rb();var H3={buffer:Ce,cast:oe,clone:$o,print:Wb};DI(H3);var vr={};et(vr,{browserFiles:()=>iN,browserHTTPRequest:()=>uN,concatenateArrayBuffers:()=>Vc,copyModel:()=>QI,decodeWeights:()=>Uh,encodeWeights:()=>MI,fromMemory:()=>pN,getLoadHandlers:()=>UI,getModelArtifactsInfoForJSON:()=>Pi,getSaveHandlers:()=>WI,http:()=>Kh,isHTTPScheme:()=>qh,listModels:()=>ZI,loadWeights:()=>aN,moveModel:()=>eN,registerLoadRouter:()=>GI,registerSaveRouter:()=>VI,removeModel:()=>JI,weightsLoaderFactory:()=>Hb,withSaveHandler:()=>mN});var q3="model",K3=".json",X3=".weights.bin";function nN(r){return new Promise(e=>setTimeout(e)).then(r)}var ol=class{constructor(e){if(!G().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(ol.URL_SCHEME)&&(e=e.slice(ol.URL_SCHEME.length)),(e==null||e.length===0)&&(e=q3),this.modelTopologyFileName=e+K3,this.weightDataFileName=e+X3}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 o=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:o};e.signature!=null&&(n.signature=e.signature),e.userDefinedMetadata!=null&&(n.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(n.modelInitializer=e.modelInitializer);let s=window.URL.createObjectURL(new Blob([JSON.stringify(n)],{type:"application/json"})),a=this.jsonAnchor==null?document.createElement("a"):this.jsonAnchor;if(a.download=this.modelTopologyFileName,a.href=s,await nN(()=>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 nN(()=>i.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Pi(e)}}}};ol.URL_SCHEME="downloads://";var sN=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((o,n)=>{let s=new FileReader;s.onload=a=>{let i=JSON.parse(a.target.result),l=i.modelTopology;if(l==null){n(new Error(`modelTopology field is missing from file ${e.name}`));return}t.length===0&&o({modelTopology:l});let u=i.weightsManifest;if(u==null){n(new Error(`weightManifest field is missing from file ${e.name}`));return}let c;try{c=this.checkManifestAndWeightFiles(u,t)}catch(d){n(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,_=m.indexOf(h);if(f[_]=b,f.indexOf(null)===-1){let w={modelTopology:l,weightSpecs:p,weightData:Vc(f),format:i.format,generatedBy:i.generatedBy,convertedBy:i.convertedBy};i.signature!=null&&(w.signature=i.signature),i.userDefinedMetadata!=null&&(w.userDefinedMetadata=i.userDefinedMetadata),i.modelInitializer!=null&&(w.modelInitializer=i.modelInitializer),o(w)}},g.onerror=x=>n(`Failed to weights data from file of path '${h}'.`),g.readAsArrayBuffer(c[h])})})},s.onerror=a=>n(`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 o=[],n=t.map(a=>Pb(a.name)),s={};for(let a of e)a.paths.forEach(i=>{let l=Pb(i);if(o.indexOf(l)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${l}'`);if(o.push(l),n.indexOf(l)===-1)throw new Error(`Weight file with basename '${l}' is not provided.`);s[i]=t[n.indexOf(l)]});if(o.length!==t.length)throw new Error(`Mismatch in the number of files in weights manifest (${o.length}) and the number of weight files provided (${t.length}).`);return s}},Z3=r=>G().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(ol.URL_SCHEME)?Y3(r.slice(ol.URL_SCHEME.length)):null;St.registerSaveRouter(Z3);function Y3(r="model"){return new ol(r)}function iN(r){return new sN(r)}function Ub(r,e,t,o){a(r),t=t==null?0:t,o=o==null?1:o,i(t,o);let n=0,s=l=>(l.then(u=>{let c=t+ ++n/r.length*(o-t);return e(c),u}),l);function a(l){T(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function i(l,u){T(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),T(u>=0&&u<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${u}`),T(u>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${u}`)}return Promise.all(r.map(s))}async function jb(r,e){e==null&&(e={});let t=e.fetchFunc==null?G().platform.fetch:e.fetchFunc,o=r.map(p=>t(p,e.requestInit,{isBinary:!0})),n=0,s=.5,i=(e.onProgress==null?await Promise.all(o):await Ub(o,e.onProgress,n,s)).map(p=>p.arrayBuffer()),l=.5,u=1;return e.onProgress==null?await Promise.all(i):await Ub(i,e.onProgress,l,u)}async function aN(r,e="",t,o){return Hb(a=>jb(a,{requestInit:o}))(r,e,t)}function Hb(r){return async(e,t="",o)=>{let n=e.map(()=>!1),s={},a=o!=null?o.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=km[x]*ft(g.shape),_=()=>{n[d]=!0,s[d]==null&&(s[d]=[]),s[d].push({manifestEntry:g,groupOffset:h,sizeBytes:b})};o!=null?o.forEach((w,v)=>{w===g.name&&(_(),a[v]=!0)}):_(),i.push(g.name),h+=b})}),!a.every(f=>f)){let f=o.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=n.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 w=0;w<d;w++)h+=c[m+w].byteLength;let g=new ArrayBuffer(h),x=new Uint8Array(g),b=0;for(let w=0;w<d;w++){let v=new Uint8Array(c[m+w]);x.set(v,b),b+=v.byteLength}s[f].forEach(w=>{let v=g.slice(w.groupOffset,w.groupOffset+w.sizeBytes),$=Uh(v,[w.manifestEntry]);for(let A in $)p[A]=$[A]}),m+=d}),p}}var J3="application/octet-stream",Q3="application/json",Hh=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?(T(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=G().platform.fetch,T(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&T(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 o=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:o};e.signature!=null&&(n.signature=e.signature),e.userDefinedMetadata!=null&&(n.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(n.modelInitializer=e.modelInitializer),t.body.append("model.json",new Blob([JSON.stringify(n)],{type:Q3}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:J3}),"model.weights.bin");let s=await this.fetch(this.path,t);if(s.ok)return{modelArtifactsInfo:Pi(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 o=t.modelTopology,n=t.weightsManifest,s=t.generatedBy,a=t.convertedBy,i=t.format,l=t.signature,u=t.userDefinedMetadata;if(o==null&&n==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);let c,p;n!=null&&([c,p]=await this.loadWeights(n));let m={modelTopology:o,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,[o,n]=eV(t),s=this.weightPathPrefix||o,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+n);this.weightUrlConverter&&i.push(...await Promise.all(l));let u=await jb(i,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[a,Vc(u)]}};Hh.URL_SCHEME_REGEX=/^https?:\/\//;function eV(r){let e=r.lastIndexOf("/"),t=r.lastIndexOf("?"),o=r.substring(0,e),n=t>e?r.substring(t):"";return[o+"/",n]}function qh(r){return r.match(Hh.URL_SCHEME_REGEX)!=null}var lN=(r,e)=>{if(typeof fetch=="undefined"&&(e==null||e.fetchFunc==null))return null;{let t=!0;if(Array.isArray(r)?t=r.every(o=>qh(o)):t=qh(r),t)return Kh(r,e)}return null};St.registerSaveRouter(lN);St.registerLoadRouter(lN);function Kh(r,e){return new Hh(r,e)}function uN(r,e){return Kh(r,e)}var Xh=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},cN=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function pN(r,e,t,o){return arguments.length===1?r.modelTopology!=null||r.weightSpecs!=null?new Xh(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 Xh({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 Xh({modelTopology:r,weightSpecs:e,weightData:t,trainingConfig:o}))}function mN(r){return new cN(r)}var fN={};et(fN,{confusionMatrix:()=>sV});function tV(r,e,t=!1,o=!1){let n=k(r,"a","matMul"),s=k(e,"b","matMul");[n,s]=Ge(n,s);let a={a:n,b:s},i={transposeA:t,transposeB:o};return E.runKernel(qo,a,i)}var We=S({matMul_:tV});function rV(r,e,t=1,o=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:o};return E.runKernel(hn,s,a)}var ks=S({oneHot_:rV});function oV(r,e){let t=k(r,"x","transpose");if(e==null&&(e=t.shape.map((s,a)=>a).reverse()),T(t.rank===e.length,()=>`Error in transpose: rank of input ${t.rank} must match length of perm ${e}.`),e.forEach(s=>{T(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 o={x:t},n={perm:e};return E.runKernel(Rn,o,n)}var Ue=S({transpose_:oV});function nV(r,e,t){let o=k(r,"labels","confusionMatrix"),n=k(e,"predictions","confusionMatrix");T(t==null||t>0&&Number.isInteger(t),()=>`If provided, numClasses must be a positive integer, but got ${t}`),T(o.rank===1,()=>`Expected the rank of labels to be 1, but got ${o.rank}`),T(n.rank===1,()=>`Expected the rank of predictions to be 1, but got ${n.rank}`),T(o.shape[0]===n.shape[0],()=>`Mismatch in the number of examples: ${o.shape[0]} vs. ${n.shape[0]}. Labels and predictions should have the same number of elements.`),T(t>0&&Number.isInteger(t),()=>`numClasses is required to be a positive integer, but got ${t}`);let s=ks(oe(o,"int32"),t),a=ks(oe(n,"int32"),t),i=Ue(s),l=We(i,a);return oe(l,"int32")}var sV=S({confusionMatrix_:nV});var Yh={};et(Yh,{fromPixels:()=>lV,toPixels:()=>aV});function qb(r,e,t){if(To(r),e!=null&&e.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let o=kr(r,t);if(o.length!==3&&o.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(o.length===1&&e==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Gr(r,e,o,t)}var Uc;function iV(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,o=!1,n=!1,s=!1,a=!1,i=!1;if(r.data instanceof Uint8Array)t=!0;else if(typeof ImageData!="undefined"&&r instanceof ImageData)o=!0;else if(typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement)n=!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(n){let d=2;if(n&&r.readyState<d)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.")}if(Pc(Fc,E.backendName)!=null){let d={pixels:r},h={numChannels:e};return E.runKernel(Fc,d,h)}let[u,c]=n?[r.videoWidth,r.videoHeight]:[r.width,r.height],p;a?p=r.getContext("2d").getImageData(0,0,u,c).data:o||t?p=r.data:(s||n||i)&&(Uc==null&&(Uc=document.createElement("canvas").getContext("2d")),Uc.canvas.width=u,Uc.canvas.height=c,Uc.drawImage(r,0,0,u,c),p=Uc.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 qb(m,[c,u,e],"int32")}async function aV(r,e){let t=k(r,"img","toPixels");if(!(r instanceof Ve)){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[o,n]=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(n*o*4);for(let u=0;u<o*n;++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=n,e.height=o;let u=e.getContext("2d"),c=new ImageData(l,n,o);u.putImageData(c,0,0)}return t!==r&&t.dispose(),l}var lV=S({fromPixels_:iV});var Zh={};et(Zh,{prepareAndValidate:()=>dN});function dN(r,e){let t=r.shape.length,o=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(o<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${o}.`);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[o-1]>t)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${e.shape[o-1]} vs. ${t}`);if(ft(r.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${r.shape}.`);let n=e.shape,s=n[n.length-1],a=1;for(let p=0;p<n.length-1;++p)a*=n[p];let i=r.shape,l=n.slice();l.pop();let u=1;for(let p=s;p<t;++p)u*=i[p],l.push(i[p]);let c=[...Hs(r.shape).map(p=>p/u),1].slice(0,s);return[l,a,u,c]}var Jh={};et(Jh,{calculateShapes:()=>hN,validateInput:()=>Qh,validateUpdateShape:()=>Kb});function Kb(r,e,t){let o=e.rank>1?e.shape[e.rank-1]:1,n=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: ${o}, and batchDim: ${n}.`;if(t.rank<n)throw new Error(s+` update.rank < ${n}. `);if(r.length<o+(t.rank-n))throw new Error(s+` Output shape length < ${o+(t.rank-n)}`);if(t.rank!==n+r.length-o)throw new Error(s+` update.rank != ${n+r.length-o}`);for(let a=0;a<n;++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-n;++a)if(t.shape[a+n]!==r[a+o])throw new Error(s+` updates.shape[${a+n}] (${t.shape[a+n]}) != shape[${a+n}] (${r[a+n]})`)}function Qh(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}`)}Kb(t,e,r)}function hN(r,e,t){let o=e.shape.length,n=o>1?e.shape[o-1]:1,s=t.length,a=1;for(let p=n;p<s;++p)a*=t[p];let i=n<1?1:n,l=ft(e.shape)/i,u=[...Hs(t.slice(0,n)),1],c=ft(t);return{sliceRank:n,numUpdates:l,sliceSize:a,strides:u,outputSize:c}}var or={};et(or,{assertParamsValid:()=>uV,computeFlatOffset:()=>pV,computeOutShape:()=>gN,getNormalizedAxes:()=>IN,isSliceContinous:()=>cV,maskToAxes:()=>eg,parseSliceParams:()=>Xb,sliceInfo:()=>mV,startForAxis:()=>vN,startIndicesWithElidedDims:()=>_N,stopForAxis:()=>CN,stopIndicesWithElidedDims:()=>wN,stridesForAxis:()=>kN,stridesWithElidedDims:()=>xN});function uV(r,e,t){let o=r.shape.length;T(o===e.length,()=>`Error in slice${o}D: Length of begin ${e} must match the rank of the array (${o}).`),T(o===t.length,()=>`Error in slice${o}D: Length of size ${t} must match the rank of the array (${o}).`);for(let n=0;n<o;++n)T(e[n]+t[n]<=r.shape[n],()=>`Error in slice${o}D: begin[${n}] + size[${n}] (${e[n]+t[n]}) would overflow input.shape[${n}] (${r.shape[n]})`)}function eg(r){let e=[],t=0;for(;r>0;)r&1&&e.push(t),r/=2,t++;return e}function gN(r,e,t){let o=[];for(let n=0;n<r.length;n++)o[n]=Math.ceil((e[n]-r[n])/t[n]);return o}function xN(r,e,t,o){let n=[...r];for(let s=n.length;s<o.length;s++)n.push(1);for(let s=0;s<t;s++)s===0?n[e]=1:(n.splice(e,0,1),n.pop());return n}function yN(r,e,t){return t<=r?t:t-(e-1)}function bN(r,e){let t=[];for(let o=0;o<r;o++)t.push(e+o);return t}function IN(r,e,t,o,n,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=_N(a,f,d,o,r),p=wN(i,f,d,n,r),m=xN(s,f,d,r)}else for(let f=0;f<u;f++)c[f]=vN(a,o,s,r,f,l),p[f]=CN(i,n,s,r,f,l),m[f]=kN(s,f,l);return{begin:c,end:p,strides:m}}function _N(r,e,t,o,n){let s=[...n],a=bN(t,e);for(let i=0;i<s.length;i++)if(a.indexOf(i)>-1)s[i]=0;else{let l=yN(e,t,i),u=o[l];r&1<<l&&(u=0),s[i]=u}return s}function wN(r,e,t,o,n){let s=[...n],a=bN(t,e);for(let i=0;i<s.length;i++)if(a.indexOf(i)>-1)s[i]=Number.MAX_SAFE_INTEGER;else{let l=yN(e,t,i),u=o[l];r&1<<l&&(u=Number.MAX_SAFE_INTEGER),s[i]=u}for(let i=0;i<s.length;i++){let l=n[i];s[i]<0&&(s[i]+=l),s[i]=Tc(0,s[i],n[i])}return s}function kN(r,e,t){let o=r[e];return(t&1<<e||o==null)&&(o=1),o}function vN(r,e,t,o,n,s){let a=e[n],i=t[n]||1;(r&1<<n||s&1<<n||a==null)&&(i>0?a=Number.MIN_SAFE_INTEGER:a=Number.MAX_SAFE_INTEGER);let l=o[n];return a<0&&(a+=l),a=Tc(0,a,l-1),a}function CN(r,e,t,o,n,s){let a=e[n],i=t[n]||1;(r&1<<n||s&1<<n||a==null)&&(i>0?a=Number.MAX_SAFE_INTEGER:a=Number.MIN_SAFE_INTEGER);let l=o[n];return a<0&&(a+=l),i>0?a=Tc(0,a,l):a=Tc(-1,a,l-1),a}function cV(r,e,t){let o=t.length;for(let n=0;n<t.length;n++)if(t[n]>1){o=n;break}for(let n=o+1;n<t.length;n++)if(e[n]>0||t[n]!==r[n])return!1;return!0}function pV(r,e){let t=r.length>0?r[r.length-1]:1;for(let o=0;o<r.length-1;o++)t+=r[o]*e[o];return t}function Xb(r,e,t){let o,n=r.shape.length;typeof e=="number"?o=[e,...new Array(n-1).fill(0)]:e.length<n?o=e.concat(new Array(n-e.length).fill(0)):o=e.slice(),o.forEach(a=>{T(a!==-1,()=>"slice() does not support negative begin indexing.")});let s;return t==null?s=new Array(n).fill(-1):typeof t=="number"?s=[t,...new Array(n-1).fill(-1)]:t.length<n?s=t.concat(new Array(n-t.length).fill(-1)):s=t,s=s.map((a,i)=>a>=0?a:(T(a===-1,()=>`Negative size values should be exactly -1 but got ${a} for the slice() size at index ${i}.`),r.shape[i]-o[i])),[o,s]}function mV(r,e,t,o,n,s,a,i,l){let u=e.slice(),c=t.slice(),p=o;o==null&&(p=new Array(u.length));let m=eg(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=eg(i),h=r.slice();d.forEach(A=>{u[A]=0,c[A]=1,h.splice(A,0,1)});let{begin:g,end:x,strides:b}=IN(h,m,f,u,c,p,n,s,a);u=g,c=x,p=b;let _=eg(l);_.forEach(A=>{c[A]=u[A]+1,p[A]=1});let w=gN(u,c,p),v=w.filter((A,R)=>_.indexOf(R)===-1);return{nonStrided:p.every(A=>A===1),$begin:u,$end:c,$strides:p,size:w,newShape:h,outShape:v}}var J={};et(J,{Serializable:()=>tg,SerializationMap:()=>ka,registerClass:()=>eo});var tg=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},ka=class{constructor(){this.classNameMap={}}static getMap(){return ka.instance==null&&(ka.instance=new ka),ka.instance}static register(e){ka.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function eo(r){T(r.className!=null,()=>"Class being registered does not have the static className property defined."),T(typeof r.className=="string",()=>"className is required to be a string, but got type "+typeof r.className),T(r.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),ka.register(r)}var NN={};et(NN,{TEST_EPSILON_FLOAT16:()=>SN,encodeStrings:()=>TN,expectArrayBuffersEqual:()=>bV,expectArraysClose:()=>dV,expectArraysEqual:()=>gV,expectNumbersClose:()=>xV,expectPromiseToFail:()=>hV,expectValuesInRange:()=>yV,testEpsilon:()=>Yb});var fV=.001,SN=.1;function dV(r,e,t){return t==null&&(t=Yb()),Zb(r,e,(o,n)=>Jb(o,n,t))}function Yb(){return E.backend.floatPrecision()===32?fV:SN}function Zb(r,e,t){let o=!0;if((rr(r)||rr(e))&&(o=!1),rr(r)&&rr(e)&&(o=!0),o){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=kr(r),i=kr(e);if(!Vr(a,i))throw new Error(`Arrays have different shapes. Actual: [${a}]. Expected: [${i}]`)}let n=rr(r)?r:os(r),s=rr(e)?e:os(e);if(n.length!==s.length)throw new Error(`Arrays have different lengths actual: ${n.length} vs expected: ${s.length}.
|
|
Actual: ${n}.
|
|
Expected: ${s}.`);for(let a=0;a<s.length;++a){let i=n[a],l=s[a];if(!t(i,l))throw new Error(`Arrays differ: actual[${a}] = ${i}, expected[${a}] = ${l}.
|
|
Actual: ${n}.
|
|
Expected: ${s}.`)}}function hV(r,e){r().then(()=>e.fail(),()=>e())}function gV(r,e){let t=typeof e=="string"||typeof e=="number"||typeof e=="boolean"?[e]:e;return ns(r)||ns(r[0])||ns(e)||ns(e[0])?Zb(r,t,(o,n)=>o==n):Zb(r,e,(o,n)=>Jb(o,n,0))}function xV(r,e,t){if(t==null&&(t=Yb()),!Jb(r,e,t))throw new Error(`Numbers differ: actual === ${r}, expected === ${e}`)}function Jb(r,e,t){return!isFinite(r)&&!isFinite(e)?!0:!(isNaN(r)||isNaN(e)||Math.abs(r-e)>t)}function yV(r,e,t){for(let o=0;o<r.length;o++)if(r[o]<e||r[o]>t)throw new Error(`Value out of range:${r[o]} low: ${e}, high: ${t}`)}function bV(r,e){expect(new Float32Array(r)).toEqual(new Float32Array(e))}function TN(r){for(let e=0;e<r.length;e++){let t=r[e];Array.isArray(t)?TN(t):r[e]=el(t)}return r}var Qb="3.0.0";function _V(){G().set("PROD",!0)}function wV(){G().set("DEBUG",!0)}function kV(){G().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function rg(r){G().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(r+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}$I(rg);function vV(){E.disposeVariables()}function vs(){return E}function jc(){return E.memory()}function CV(r){return E.profile(r)}function V(r,e){return E.tidy(r,e)}function Te(r){wm(r).forEach(t=>t.dispose())}function At(r){return E.keep(r)}function IV(r){return E.time(r)}function EN(r){return E.setBackend(r)}function NV(){return E.ready()}function SV(){return E.backendName}function TV(r){E.removeBackend(r)}function EV(r){return E.findBackend(r)}function AV(r){return E.findBackendFactory(r)}function yu(r,e,t=1){return E.registerBackend(r,e,t)}function e_(){return E.backend}function DV(r,e){G().setPlatform(r,e)}function $V(r,e){let t=k(r,"a","add"),o=k(e,"b","add");[t,o]=Ge(t,o);let n={a:t,b:o};return E.runKernel(xo,n)}var Q=S({add_:$V});function RV(r,e){let t=k(r,"a","floorDiv"),o=k(e,"b","floorDiv");[t,o]=Ge(t,o);let n={a:t,b:o};return E.runKernel(rn,n)}var bu=S({floorDiv_:RV});function FV(r,e){let t=k(r,"a","div"),o=k(e,"b","div");if([t,o]=Ge(t,o),t.dtype==="int32"&&o.dtype==="int32")return bu(t,o);let n={a:t,b:o},s={};return E.runKernel(Qo,n,s)}var de=S({div_:FV});function OV(r,e){let t=k(r,"a","mul"),o=k(e,"b","mul");[t,o]=Ge(t,o);let n={a:t,b:o};return E.runKernel(dn,n)}var O=S({mul_:OV});function PV(r){let e=k(r,"x","abs");if(e.dtype==="complex64"){let t={x:e};return E.runKernel(ia,t)}else{let t={x:e};return E.runKernel(ss,t)}}var Tt=S({abs_:PV});function MV(r){let t={x:k(r,"x","acos")};return E.runKernel(qs,t)}var vm=S({acos_:MV});function LV(r){let t={x:k(r,"x","acosh")};return E.runKernel(Ks,t)}var Cm=S({acosh_:LV});function zV(r){T(Array.isArray(r),()=>"The argument passed to tf.addN() must be a list of tensors"),T(r.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${r.length}`);let e=r.map((n,s)=>k(n,`tensors${s}`,"addN")),t=e[0];e.forEach(n=>{if(n.dtype!==t.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),e.forEach(n=>{if(!Vr(n.shape,t.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let o=e;return E.runKernel(Uo,o)}var t_=S({addN_:zV});function BV(r,e=null,t=!1){let n={x:k(r,"x","all","bool")},s={axis:e,keepDims:t};return E.runKernel(Vl,n,s)}var _u=S({all_:BV});function VV(r,e=null,t=!1){let n={x:k(r,"x","any","bool")},s={axis:e,keepDims:t};return E.runKernel(Gl,n,s)}var nl=S({any_:VV});function GV(r,e=0){let o={x:k(r,"x","argMax")},n={axis:e};return E.runKernel(jo,o,n)}var sl=S({argMax_:GV});function WV(r,e=0){let o={x:k(r,"x","argMin")},n={axis:e};return E.runKernel(oa,o,n)}var Im=S({argMin_:WV});function UV(r){let t={x:k(r,"x","asin")};return E.runKernel(Xs,t)}var Nm=S({asin_:UV});function jV(r){let t={x:k(r,"x","asinh")};return E.runKernel(Ys,t)}var Sm=S({asinh_:jV});function HV(r){let t={x:k(r,"x","atan")};return E.runKernel(Zs,t)}var Tm=S({atan_:HV});function qV(r,e){let t=k(r,"a","atan2"),o=k(e,"b","atan2");[t,o]=Ge(t,o);let n={a:t,b:o};return E.runKernel(Qs,n)}var Em=S({atan2_:qV});function KV(r){let t={x:k(r,"x","atanh")};return E.runKernel(Js,t)}var Am=S({atanh_:KV});function XV(r,e,t,o,n="NHWC",s){let a=r[3],i=[...e,a],l=AN(n);return wu(r,i,t,s,o,null,null,l)}function r_(r,e,t,o,n,s,a="channelsLast"){let[i,l]=og(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,o,n,s,!1,a)}function YV(r,e,t,o,n,s,a="NDHWC"){let[i,l,u]=o_(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 DN(r,c,t,o,n,!1,p,s)}function wu(r,e,t,o,n,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]=og(t),[x,b]=og(o),_=Hc(m,x),w=Hc(f,b),{padInfo:v,outHeight:$,outWidth:A}=ZV(n,u,c,h,g,_,w,s,i),R=a?d*p:d,M;return i==="channelsFirst"?M=[l,R,$,A]:i==="channelsLast"&&(M=[l,$,A,R]),{batchSize:l,dataFormat:i,inHeight:u,inWidth:c,inChannels:p,outHeight:$,outWidth:A,outChannels:R,padInfo:v,strideHeight:h,strideWidth:g,filterHeight:m,filterWidth:f,effectiveFilterHeight:_,effectiveFilterWidth:w,dilationHeight:x,dilationWidth:b,inShape:r,outShape:M,filterShape:e}}function DN(r,e,t,o,n,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,_]=o_(t),[w,v,$]=o_(o),A=Hc(f,w),R=Hc(d,v),M=Hc(h,$),{padInfo:z,outDepth:W,outHeight:U,outWidth:q}=JV(n,u,c,p,x,b,_,A,R,M,i),Z=s?g*m:g,X;return a==="channelsFirst"?X=[l,Z,W,U,q]:a==="channelsLast"&&(X=[l,W,U,q,Z]),{batchSize:l,dataFormat:a,inDepth:u,inHeight:c,inWidth:p,inChannels:m,outDepth:W,outHeight:U,outWidth:q,outChannels:Z,padInfo:z,strideDepth:x,strideHeight:b,strideWidth:_,filterDepth:f,filterHeight:d,filterWidth:h,effectiveFilterDepth:A,effectiveFilterHeight:R,effectiveFilterWidth:M,dilationDepth:w,dilationHeight:v,dilationWidth:$,inShape:r,outShape:X,filterShape:e}}function QV(r,e,t,o,n){o==null&&(o=n_(r,e,t));let s=r[0],a=r[1],i=ku((s-e+2*o)/t+1,n),l=ku((a-e+2*o)/t+1,n);return[i,l]}function eG(r,e,t,o,n,s){n==null&&(n=n_(r,e,o));let a=r[0],i=r[1],l=r[2],u=ku((a-e+2*n)/o+1,s),c=ku((i-e+2*n)/o+1,s),p=ku((l-e+2*n)/o+1,s);return[u,c,p,t]}function n_(r,e,t,o=1){let n=Hc(e,o);return Math.floor((r[0]*(t-1)-t+n)/2)}function og(r){return typeof r=="number"?[r,r,r]:r.length===2?[r[0],r[1],1]:r}function o_(r){return typeof r=="number"?[r,r,r]:r}function Hc(r,e){return e<=1?r:r+(r-1)*(e-1)}function ZV(r,e,t,o,n,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=QV([e,t],s,o,r,i);c=f[0],p=f[1]}else if(r==="same"){c=Math.ceil(e/o),p=Math.ceil(t/n);let m=Math.max(0,(c-1)*o+s-e),f=Math.max(0,(p-1)*n+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)/o),p=Math.ceil((t-a+1)/n);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=ku((e-s+m+f)/o+1,i),p=ku((t-a+d+h)/n+1,i)}else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:u,outHeight:c,outWidth:p}}function JV(r,e,t,o,n,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=eG([e,t,o,1],i,1,n,r,c);m=g[0],f=g[1],d=g[2]}else if(r==="same"){m=Math.ceil(e/n),f=Math.ceil(t/s),d=Math.ceil(o/a);let h=(m-1)*n+i-e,g=(f-1)*s+l-t,x=(d-1)*a+u-o,b=Math.floor(h/2),_=h-b,w=Math.floor(g/2),v=g-w,$=Math.floor(x/2),A=x-$;p={top:w,bottom:v,left:$,right:A,front:b,back:_,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)/n),f=Math.ceil((t-l+1)/s),d=Math.ceil((o-u+1)/a);else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:p,outDepth:m,outHeight:f,outWidth:d}}function ku(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 Ro(r){let[e,t,o]=og(r);return e===1&&t===1&&o===1}function yr(r,e){return Ro(r)||Ro(e)}function AN(r){if(r==="NHWC")return"channelsLast";if(r==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${r}`)}function tG(r,e){let o={x:k(r,"x","reshape","string_or_numeric")},n={shape:e};return E.runKernel(fs,o,n)}var L=S({reshape_:tG});function rG(r,e,t,o,n){let s=k(r,"x","avgPool","float32"),a=1;T(yr(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]])),T(i.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`),n!=null&&T(st(o),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${n} but got pad ${o}.`);let u={x:i},c={filterSize:e,strides:t,pad:o,dimRoundingMode:n},p=E.runKernel(Ho,u,c);return p=oe(p,s.dtype),l?L(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var va=S({avgPool_:rG});function oG(r,e,t,o,n,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]])),T(i.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${i.rank}.`),T(s==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),n!=null&&T(st(o),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${n} but got pad ${o}.`);let u={x:i},c={filterSize:e,strides:t,pad:o,dimRoundingMode:n,dataFormat:s},p=E.runKernel(na,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 Dm=S({avgPool3d_:oG});function nG(r,e=0){T(r.length>=1,()=>"Pass at least one tensor to concat");let t=ya(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 $o(t[0]);let o=t,n={axis:e};return E.runKernel(is,o,n)}var Je=S({concat_:nG});function sG(r){let t={x:k(r,"x","sigmoid")};return E.runKernel(Nn,t)}var Ur=S({sigmoid_:sG});function iG(r,e,t){let o=k(r,"x","slice","string_or_numeric");if(o.rank===0)throw new Error("Slicing scalar is not possible");let n={x:o},s={begin:e,size:t};return E.runKernel(hs,n,s)}var Fe=S({slice_:iG});function aG(r){let t={x:k(r,"x","tanh")};return E.runKernel($n,t)}var Mi=S({tanh_:aG});function lG(r,e,t,o,n,s){let a=k(r,"forgetBias","basicLSTMCell"),i=k(e,"lstmKernel","basicLSTMCell"),l=k(t,"lstmBias","basicLSTMCell"),u=k(o,"data","basicLSTMCell"),c=k(n,"c","basicLSTMCell"),p=k(s,"h","basicLSTMCell"),m=Je([u,p],1),f=We(m,i),d=Q(f,l),h=d.shape[0],g=d.shape[1]/4,x=[h,g],b=Fe(d,[0,0],x),_=Fe(d,[0,g],x),w=Fe(d,[0,g*2],x),v=Fe(d,[0,g*3],x),$=Q(O(Ur(b),Mi(_)),O(c,Ur(Q(a,w)))),A=O(Mi($),Ur(v));return[$,A]}var uG=S({basicLSTMCell_:lG});function cG(r,e,t){let o=k(r,"x","batchToSpaceND"),n=e.reduce((i,l)=>i*l);T(o.rank>=1+e.length,()=>`input rank is ${o.rank} but should be > than blockShape.length ${e.length}`),T(t.length===e.length,()=>`crops.length is ${t.length} but should be equal to blockShape.length ${e.length}`),T(o.shape[0]%n==0,()=>`input tensor batch is ${o.shape[0]} but is not divisible by the product of the elements of blockShape ${e.join(" * ")} === ${n}`);let s={x:o},a={blockShape:e,crops:t};return E.runKernel(sa,s,a)}var Ca=S({batchToSpaceND_:cG});function $N(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 pG(r,e,t,o,n,s){s==null&&(s=.001);let a=k(r,"x","batchNorm"),i=k(e,"mean","batchNorm"),l=k(t,"variance","batchNorm"),u;n!=null&&(u=k(n,"scale","batchNorm"));let c;o!=null&&(c=k(o,"offset","batchNorm")),T(i.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),T(c==null||i.rank===c.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),T(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let m={x:$N(a),scale:u,offset:c,mean:i,variance:l},f={varianceEpsilon:s},d=E.runKernel(on,m,f);return L(d,a.shape)}var On=S({batchNorm_:pG});function mG(r,e,t,o,n,s){let a=k(r,"x","batchNorm"),i=k(e,"mean","batchNorm"),l=k(t,"variance","batchNorm"),u;n!=null&&(u=k(n,"scale","batchNorm"));let c;return o!=null&&(c=k(o,"offset","batchNorm")),T(a.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${a.rank}.`),T(i.rank===2||i.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`),T(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&T(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),c!=null&&T(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${c.rank}.`),On(a,i,l,c,u,s)}var s_=S({batchNorm2d_:mG});function fG(r,e,t,o,n,s){let a=k(r,"x","batchNorm"),i=k(e,"mean","batchNorm"),l=k(t,"variance","batchNorm"),u;n!=null&&(u=k(n,"scale","batchNorm"));let c;return o!=null&&(c=k(o,"offset","batchNorm")),T(a.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${a.rank}.`),T(i.rank===3||i.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`),T(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&T(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),c!=null&&T(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${c.rank}.`),On(a,i,l,c,u,s)}var i_=S({batchNorm3d_:fG});function dG(r,e,t,o,n,s){let a=k(r,"x","batchNorm"),i=k(e,"mean","batchNorm"),l=k(t,"variance","batchNorm"),u;n!=null&&(u=k(n,"scale","batchNorm"));let c;return o!=null&&(c=k(o,"offset","batchNorm")),T(a.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${a.rank}.`),T(i.rank===4||i.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`),T(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),u!=null&&T(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`),c!=null&&T(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${c.rank}.`),On(a,i,l,c,u,s)}var a_=S({batchNorm4d_:dG});function hG(r,e,t){let o=k(r,"x","bincount"),n=k(e,"weights","bincount");T(o.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${o.dtype}`),T(t>=0,()=>`size must be non-negative, but got ${t}.`),T(n.size===o.size||n.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${o.shape}, weights shape: ${n.shape}.`);let s={x:o,weights:n},a={size:t};return E.runKernel(jl,s,a)}var l_=S({bincount_:hG});function gG(r,e){let t=k(r,"broadcastTo","x"),o=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 n=t.shape,s=Array.from(e);for(let u=e.length-1;u>=0;u--)if(n[u]===e[u])s[u]=1;else if(t.shape[u]!==1)throw new Error(`broadcastTo(): [${o}] cannot be broadcast to [${e}].`);if(s.map((u,c)=>u>1?c:-1).filter(u=>u>=0).length===0)return $o(t);let i={x:t},l={reps:s};return E.runKernel(yo,i,l)}var il=S({broadcastTo_:gG});function xG(r){let t={x:k(r,"x","ceil")};return E.runKernel(ei,t)}var $m=S({ceil_:xG});function yG(r,e,t){let o=k(r,"x","clipByValue");T(e<=t,()=>`Error in clip: min (${e}) must be less than or equal to max (${t}).`);let n={x:o},s={clipValueMin:e,clipValueMax:t};return E.runKernel(Ao,n,s)}var nr=S({clipByValue_:yG});function bG(r){return Je(r,0)}var u_=S({concat1d_:bG});function _G(r,e){return Je(r,e)}var c_=S({concat2d_:_G});function wG(r,e){return Je(r,e)}var p_=S({concat3d_:wG});function kG(r,e){return Je(r,e)}var m_=S({concat4d_:kG});function vG(r,e,t,o,n="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]])),T(u.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`),T(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),a!=null&&T(st(o),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);let p=n==="NHWC"?u.shape[3]:u.shape[1];T(p===l.shape[2],()=>`Error in conv2d: depth of input (${p}) must match input depth for filter ${l.shape[2]}.`),T(yr(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:o,dataFormat:n,dilations:s,dimRoundingMode:a},d=E.runKernel(Ko,m,f);return c?L(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var jr=S({conv2d_:vG});function CG(r,e,t,o,n="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]])),T(u.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`),T(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),a!=null&&T(st(o),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`),T(u.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`),T(yr(t,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${t} and dilation '${s}'`),T(n==="NWC",()=>`Error in conv1d: got dataFormat of ${n} 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=jr(m,p,[1,t],o,"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 vu=S({conv1d_:CG});function IG(r,e,t,o,n,s="NHWC",a){T(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]]),T(i.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`),T(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),T(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];T(c===t.shape[2],()=>`Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${t.shape[2]}.`),T(p===t.shape[3],()=>`Error in conv2dDerInput: depth of output (${p}) must match output depth for filter ${t.shape[3]}.`),a!=null&&T(st(n),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${a} but got pad ${n}.`);let m={dy:l,filter:t},f={strides:o,pad:n,dataFormat:s,dimRoundingMode:a,inputShape:i},d=E.runKernel(Xo,m,f);return u?L(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var qc=S({conv2DBackpropInput_:IG});function NG(r,e,t,o,n,s){let a=k(r,"x","conv2dTranspose"),i=k(e,"filter","conv2dTranspose");return qc(t,a,i,o,n,"NHWC",s)}var Cu=S({conv2dTranspose_:NG});function SG(r,e,t,o,n="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]])),T(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),T(i.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`),T(l.shape[4]===i.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${i.shape[3]}.`),T(yr(t,s),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`),T(n==="NDHWC",()=>`Error in conv3d: got dataFormat of ${n} but only NDHWC is currently supported.`);let c={x:l,filter:i},p={strides:t,pad:o,dataFormat:n,dilations:s},m=E.runKernel(aa,c,p);return u?L(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}var Rm=S({conv3d_:SG});function TG(r,e,t,o,n){T(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];T(s.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`),T(a.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${a.rank}`),T(t.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${t.rank}`),T(l===t.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${t.shape[3]}.`),T(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:n,strides:o,inputShape:s},m=E.runKernel(Xl,c,p);return i?L(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}var ng=S({conv3DBackpropInput_:TG});function EG(r,e,t,o,n){let s=k(r,"x","conv3dTranspose"),a=k(e,"filter","conv3dTranspose");return ng(t,s,a,o,n)}var AG=S({conv3dTranspose_:EG});function DG(r){let t={x:k(r,"x","cos")};return E.runKernel(Yo,t)}var Ia=S({cos_:DG});function $G(r){let t={x:k(r,"x","cosh")};return E.runKernel(ti,t)}var Iu=S({cosh_:$G});function RG(r,e=0,t=!1,o=!1){let s={x:k(r,"x","cumsum")},a={axis:e,exclusive:t,reverse:o};return E.runKernel(Zo,s,a)}var Nu=S({cumsum_:RG});function FG(r,e,t,o=!1){let n=k(r,"x","denseBincount"),s=k(e,"weights","denseBincount");T(n.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${n.dtype}`),T(n.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${n.rank}.`),T(t>=0,()=>`size must be non-negative, but got ${t}.`),T(s.size===n.size||s.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${n.shape}, weights shape: ${s.shape}.`);let a={x:n,weights:s},i={size:t,binaryOutput:o};return E.runKernel(Yl,a,i)}var f_=S({denseBincount_:FG});function OG(r,e,t="NHWC"){let o=k(r,"x","depthToSpace"),n=t==="NHWC"?o.shape[1]:o.shape[2],s=t==="NHWC"?o.shape[2]:o.shape[3],a=t==="NHWC"?o.shape[3]:o.shape[1];T(n*e>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${n} and ${e} for depthToSpace with input shape
|
|
${o.shape}`),T(s*e>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${s} and ${e} for depthToSpace with input shape
|
|
${o.shape}`),T(a%(e*e)==0,()=>`Dimension size must be evenly divisible by ${e*e} but is ${a} for depthToSpace with input shape ${o.shape}`);let i={x:o},l={blockSize:e,dataFormat:t};return E.runKernel(oi,i,l)}var Fm=S({depthToSpace_:OG});function PG(r,e,t,o,n="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]])),T(u.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),T(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),T(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&&T(st(o),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`);let p={x:u,filter:l},m={strides:t,pad:o,dataFormat:n,dilations:s,dimRoundingMode:a},f=E.runKernel(Jo,p,m);return c?L(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Cs=S({depthwiseConv2d_:PG});function MG(r){let t={x:k(r,"x","diag")};return E.runKernel(Ql,t)}var LG=S({diag_:MG});function zG(r,e,t,o,n=[1,1],s="NHWC"){let a=k(r,"x","dilation2d"),i=k(e,"filter","dilation2d");T(a.rank===3||a.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${a.rank}.`),T(i.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`),T(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:o,dilations:n},m=E.runKernel(la,c,p);return u?L(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Om=S({dilation2d_:zG});function BG(r,e){let t=r.length,o=[];for(let n=0;n<t;n++){let s=t-1-n,a=r[s]||1;(e[e.length-1-n]||1)>1&&a===1&&o.unshift(s)}return o}function Ct(r,e){let t=[];for(let o=0;o<e.length;o++){let n=r[r.length-o-1],s=e.length-o-1,a=e[s];(n==null||n===1&&a>1)&&t.unshift(s)}return t}function ze(r,e){let t=[],o=Math.max(r.length,e.length);for(let n=0;n<o;n++){let s=r[r.length-n-1];s==null&&(s=1);let a=e[e.length-n-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 VG(r,e){let t=k(r,"a","equal"),o=k(e,"b","equal");[t,o]=Ge(t,o),ze(t.shape,o.shape);let n={a:t,b:o};return E.runKernel(ii,n)}var _o=S({equal_:VG});function GG(r,e,t){let o=k(e,"a","where"),n=k(t,"b","where"),s=k(r,"condition","where","bool"),a=ze(o.shape,n.shape),i=il(o,a),l=il(n,a);s.rank===1&&T(s.shape[0]===o.shape[0],()=>"The first dimension of `a` must match the size of `condition`."),s.rank!==1&&Nt(s.shape,l.shape,"Error in where: ");let u={condition:s,t:i,e:l};return E.runKernel(ds,u)}var Dt=S({where_:GG});function WG(r){let t={x:k(r,"x","zerosLike")};return E.runKernel(ys,t)}var Ie=S({zerosLike_:WG});function UG(r,e){let t=k(r,"a","div"),o=k(e,"b","div");[t,o]=Ge(t,o);let n=de(t,o),s=Ie(n),a=_o(o,s);return Dt(a,s,n)}var Pm=S({divNoNan_:UG});function jG(r,e){let t=k(r,"t1","dot"),o=k(e,"t2","dot");T((t.rank===1||t.rank===2)&&(o.rank===1||o.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${t.rank} and ${o.rank}.`);let n=t.rank===1?t.size:t.shape[1],s=o.rank===1?o.size:o.shape[0];if(T(n===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${n} and ${s}.`),t.rank===1&&o.rank===1){let a=L(t,[1,-1]),i=L(o,[-1,1]),l=We(a,i);return L(l,[])}else if(t.rank===1&&o.rank===2){let a=L(t,[1,-1]),i=L(o,[o.shape[0],o.shape[1]]),l=We(a,i);return L(l,[l.size])}else if(t.rank===2&&o.rank===1){let a=L(o,[-1,1]),i=We(t,a);return L(i,[i.size])}else{let a=L(o,[o.shape[0],o.shape[1]]);return We(t,a)}}var d_=S({dot_:jG});function HG(r){let t={x:k(r,"x","elu")};return E.runKernel(ni,t)}var Is=S({elu_:HG});function qG(r){let e=k(r,"x","erf");T(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 E.runKernel(si,t)}var Mm=S({erf_:qG});function KG(r){let t={x:k(r,"x","exp")};return E.runKernel(en,t)}var Xt=S({exp_:KG});function XG(r,e=0){let t=k(r,"x","expandDims","string_or_numeric");T(e<=t.rank,()=>"Axis must be <= rank of the tensor");let o={input:t},n={dim:e};return E.runKernel(as,o,n)}var sr=S({expandDims_:XG});function YG(r){let t={x:k(r,"x","expm1")};return E.runKernel(ai,t)}var Lm=S({expm1_:YG});function ZG(r,e){let t=k(r,"x","tile","string_or_numeric");T(t.rank===e.length,()=>`Error in transpose: rank of input ${t.rank} must match length of reps ${e}.`);let o={x:t},n={reps:e};return E.runKernel(yo,o,n)}var Fo=S({tile_:ZG});function JG(r,e,t,o="float32"){e==null&&(e=r);let n=Ce([r,e],o),s=r<=e?r:e;for(let i=0;i<s;++i)n.set(1,i,i);let a=L(n.toTensor(),[r,e]);if(t==null)return a;if(t.length===1)return Fo(sr(a,0),[t[0],1,1]);if(t.length===2)return Fo(sr(sr(a,0),0),[t[0],t[1],1,1]);if(t.length===3)return Fo(sr(sr(sr(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 Kc=S({eye_:JG});function Na(r,e,t){let o={shape:r,value:e,dtype:t};return E.runKernel(ua,{},o)}function QG(r){let t={x:k(r,"x","floor")};return E.runKernel(tn,t)}var Ns=S({floor_:QG});function eW(r,e,t=0,o=0){let n=k(r,"x","gather"),s=k(e,"indices","gather","int32"),a={x:n,indices:s},i={axis:t,batchDims:o};return E.runKernel(ls,a,i)}var Pn=S({gather_:eW});function tW(r,e){let t=k(r,"a","greater"),o=k(e,"b","greater");[t,o]=Ge(t,o),ze(t.shape,o.shape);let n={a:t,b:o};return E.runKernel(ci,n)}var Qt=S({greater_:tW});function rW(r,e){let t=k(r,"a","greaterEqual"),o=k(e,"b","greaterEqual");[t,o]=Ge(t,o),ze(t.shape,o.shape);let n={a:t,b:o};return E.runKernel(nn,n)}var to=S({greaterEqual_:rW});function oW(r){let t={input:k(r,"input","imag")};return E.runKernel(ou,t)}var Su=S({imag_:oW});function nW(r){let t={x:k(r,"x","isFinite")};return E.runKernel(pi,t)}var h_=S({isFinite_:nW});function sW(r){let t={x:k(r,"x","isInf")};return E.runKernel(mi,t)}var g_=S({isInf_:sW});function iW(r){let t={x:k(r,"x","isNaN")};return E.runKernel(fi,t)}var x_=S({isNaN_:iW});function aW(r,e=.2){let o={x:k(r,"x","leakyRelu")},n={alpha:e};return E.runKernel(sn,o,n)}var Sa=S({leakyRelu_:aW});function lW(r,e){let t=k(r,"a","less"),o=k(e,"b","less");[t,o]=Ge(t,o),ze(t.shape,o.shape);let n={a:t,b:o};return E.runKernel(di,n)}var Tu=S({less_:lW});function uW(r,e){let t=k(r,"a","lessEqual"),o=k(e,"b","lessEqual");[t,o]=Ge(t,o),ze(t.shape,o.shape);let n={a:t,b:o};return E.runKernel(hi,n)}var Oo=S({lessEqual_:uW});function y_(r,e,t){if(t<=0)throw new Error("The number of values should be positive.");let o={start:r,stop:e,num:t};return E.runKernel(nu,{},o)}function cW(r,e=5,t=1,o=1,n=.5){let s=k(r,"x","localResponseNormalization");T(s.rank===4||s.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
|
|
rank ${s.rank}.`),T(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:o,beta:n},c=E.runKernel(ca,l,u);return i?L(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var zm=S({localResponseNormalization_:cW});function pW(r){let t={x:k(r,"x","log")};return E.runKernel(an,t)}var ir=S({log_:pW});function mW(r){let t={x:k(r,"x","log1p")};return E.runKernel(gi,t)}var Eu=S({log1p_:mW});function fW(r){return T(js(r),()=>"The f passed in grad(f) must be a function"),(e,t)=>{let o=k(e,"x","tf.grad","string_or_numeric"),n=t!=null?k(t,"dy","tf.grad"):null;return E.tidy(()=>{let{value:s,grads:a}=E.gradients(()=>r(o),[o],n);return n!=null&&Nt(s.shape,n.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),sg(a),a[0]})}}function dW(r){return T(js(r),()=>"The f passed in grads(f) must be a function"),(e,t)=>{T(Array.isArray(e),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let o=ya(e,"args","tf.grads","string_or_numeric"),n=t!=null?k(t,"dy","tf.grads"):null;return E.tidy(()=>{let{value:s,grads:a}=E.gradients(()=>r(...o),o,n);return n!=null&&Nt(s.shape,n.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),sg(a),a})}}function hW(r){return T(js(r),()=>"The f passed in valueAndGrad(f) must be a function"),(e,t)=>{T(e instanceof Ve,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),T(t==null||t instanceof Ve,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:o,value:n}=E.gradients(()=>r(e),[e],t);return sg(o),{grad:o[0],value:n}}}function gW(r){return T(js(r),()=>"The f passed in valueAndGrads(f) must be a function"),(e,t)=>{T(Array.isArray(e)&&e.every(n=>n instanceof Ve),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),T(t==null||t instanceof Ve,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let o=E.gradients(()=>r(...e),e,t);return t!=null&&Nt(o.value.shape,t.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),sg(o.grads),o}}function ig(r,e){T(js(r),()=>"The f passed in variableGrads(f) must be a function"),T(e==null||Array.isArray(e)&&e.every(u=>u instanceof tl),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let t=e!=null;if(!t){e=[];for(let u in E.registeredVariables)e.push(E.registeredVariables[u])}let o=t?e.filter(u=>!u.trainable):null,n=e.length;e=e.filter(u=>u.trainable),T(e.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${n} variables is trainable.`);let s=!0,{value:a,grads:i}=E.gradients(r,e,null,s);T(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()."),T(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])}),o!=null&&o.forEach(u=>l[u.name]=null),{value:a,grads:l}}function Hr(r){return E.customGrad(r)}function sg(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 xW(r){let t={x:k(r,"x","neg")};return E.runKernel(cs,t)}var je=S({neg_:xW});function yW(r){let t={x:k(r,"x","softplus")};return E.runKernel(Ei,t)}var Ss=S({softplus_:yW});function bW(r){let e=k(r,"x","logSigmoid");return Hr(o=>({value:je(Ss(je(o))),gradFunc:a=>O(a,Ur(je(o)))}))(e)}var b_=S({logSigmoid_:bW});function _W(r,e=null,t=!1){let n={x:k(r,"x","max")},s={reductionIndices:e,keepDims:t};return E.runKernel(ln,n,s)}var ar=S({max_:_W});function wW(r,e){let t=k(r,"a","sub"),o=k(e,"b","sub");[t,o]=Ge(t,o);let n={a:t,b:o};return E.runKernel(Dn,n)}var ue=S({sub_:wW});function kW(r,e=null,t=!1){let o=k(r,"x","sum");o.dtype==="bool"&&(o=oe(o,"int32"));let n={x:o},s={axis:e,keepDims:t};return E.runKernel(Tn,n,s)}var ye=S({sum_:kW});function vW(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 Hr((n,s)=>{let a=!0,i=ar(n,e,!0),l=ue(n,i),u=ue(oe(l,"float32"),ir(ye(Xt(l),e,a)));return s([u]),{value:u,gradFunc:(p,m)=>{let[f]=m,d=!0,h=Xt(f);return ue(p,O(ye(p,e,d),h))}}})(t)}var Au=S({logSoftmax_:vW});function __(r,e){for(let t=0;t<r.length;++t)if(r[r.length-t-1]!==e-1-t)return!1;return!0}function RN(r,e,t){let o=r.length+e.length,n=[],s=0,a=0;for(let i=0;i<o;i++)t.indexOf(i)===-1?n.push(r[s++]):n.push(e[a++]);return n}function w_(r,e){let t=[],o=r.length;for(let s=0;s<o;s++)e.indexOf(s)===-1&&t.push(r[s]);let n=e.map(s=>r[s]);return[t,n]}function Mn(r,e){let t=e.map(o=>1);return RN(r,t,e)}function CW(r,e,t){T(__(e,t),()=>`${r} supports only inner-most axes for now. Got axes ${e} and rank-${t} input.`)}function k_(r,e){if(__(r,e))return null;let t=[];for(let o=0;o<e;++o)r.indexOf(o)===-1&&t.push(o);return r.forEach(o=>t.push(o)),t}function Bm(r){return r.map((e,t)=>[t,e]).sort((e,t)=>e[1]-t[1]).map(e=>e[0])}function IW(r,e){let t=[];for(let o=e-r;o<e;++o)t.push(o);return t}function NW(r,e=null,t=!1){let o=k(r,"x","logSumExp"),n=Jt(e,o.shape),s=ar(o,n,!0),a=ue(o,s),i=Xt(a),l=ye(i,n),u=ir(l),c=Q(L(s,u.shape),u);if(t){let p=Mn(c.shape,n);return L(c,p)}return c}var Vm=S({logSumExp_:NW});function SW(r,e){let t=k(r,"a","logicalAnd","bool"),o=k(e,"b","logicalAnd","bool");ze(t.shape,o.shape);let n={a:t,b:o};return E.runKernel(xi,n)}var fr=S({logicalAnd_:SW});function TW(r){let t={x:k(r,"x","logicalNot","bool")};return E.runKernel(Za,t)}var Ta=S({logicalNot_:TW});function EW(r,e){let t=k(r,"a","logicalOr","bool"),o=k(e,"b","logicalOr","bool");ze(t.shape,o.shape);let n={a:t,b:o};return E.runKernel(Ja,n)}var Du=S({logicalOr_:EW});function AW(r,e){let t=k(r,"a","logicalXor","bool"),o=k(e,"b","logicalXor","bool");return ze(t.shape,o.shape),fr(Du(r,e),Ta(fr(r,e)))}var v_=S({logicalXor_:AW});function DW(r,e,t,o,n){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]])),T(i.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),T(yr(t,a),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${t} and dilations '${a}'`),n!=null&&T(st(o),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${n} but got pad ${o}.`);let u={x:i},c={filterSize:e,strides:t,pad:o,dimRoundingMode:n},p=E.runKernel(cn,u,c);return l?L(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Ea=S({maxPool_:DW});function $W(r,e=[1,1,1],t,o,n,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]])),T(i.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`),T(s==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),n!=null&&T(st(o),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${n} but got pad ${o}.`);let u={x:i},c={filterSize:e,strides:t,pad:o,dimRoundingMode:n,dataFormat:s},p=E.runKernel(pa,u,c);return l?L(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var Gm=S({maxPool3d_:$W});function RW(r,e,t,o,n=!1){let a={x:k(r,"x","maxPoolWithArgmax")},i={filterSize:e,strides:t,pad:o,includeBatchInIndex:n},l=E.runKernel(lu,a,i);return{result:l[0],indexes:l[1]}}var C_=S({maxPoolWithArgmax_:RW});function FW(r,e){let t=k(r,"a","maximum"),o=k(e,"b","maximum");[t,o]=Ge(t,o),t.dtype==="bool"&&(t=oe(t,"int32"),o=oe(o,"int32")),ze(t.shape,o.shape);let n={a:t,b:o};return E.runKernel(un,n)}var qr=S({maximum_:FW});function OW(r,e=null,t=!1){let n={x:k(r,"x","mean")},s={axis:e,keepDims:t};return E.runKernel(pn,n,s)}var ht=S({mean_:OW});function PW(r,e=null,t=!1){let n={x:k(r,"x","min")},s={axis:e,keepDims:t};return E.runKernel(mn,n,s)}var Li=S({min_:PW});function MW(r,e){let t=k(r,"a","minimum"),o=k(e,"b","minimum");[t,o]=Ge(t,o),t.dtype==="bool"&&(t=oe(t,"int32"),o=oe(o,"int32")),ze(t.shape,o.shape);let n={a:t,b:o};return E.runKernel(fn,n)}var Ts=S({minimum_:MW});function LW(r,e,t){T(t==="reflect"||t==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${t}.`);let o=k(r,"x","mirrorPad");if(o.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");T(e.length===o.rank,()=>`Padding doesn't match input. Must be ${o.rank}. Got ${e.length}.`);let n=t==="reflect"?1:0;for(let i=0;i<o.rank;i++)T(e[i].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),T(e[i][0]>=0&&e[i][0]<=o.shape[i]-n&&e[i][1]>=0&&e[i][1]<=o.shape[i]-n,()=>`Padding in dimension ${i} cannot be greater than or equal to ${o.shape[i]-n} or less than 0 for input of shape ${o.shape}`);let s={paddings:e,mode:t},a={x:o};return E.runKernel(ma,a,s)}var Wm=S({mirrorPad_:LW});function zW(r,e){let t=k(r,"a","mod"),o=k(e,"b","mod");[t,o]=Ge(t,o);let n={a:t,b:o};return E.runKernel(yi,n)}var Um=S({mod_:zW});function BW(r){let e=k(r,"x","square"),t={};return E.runKernel("Square",{x:e},t)}var Pe=S({square_:BW});function VW(r,e=null,t=!1){r=k(r,"x","moments");let o=Jt(e,r.shape),n=ht(r,o,t),s=n.shape;t||(s=Mn(n.shape,o));let a=Pe(ue(oe(r,"float32"),L(n,s))),i=ht(a,o,t);return{mean:n,variance:i}}var Xc=S({moments_:VW});function GW(r,e,t,o){let n=k(e,"data","multiRNNCell"),s=ya(t,"c","multiRNNCell"),a=ya(o,"h","multiRNNCell"),i=n,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 WW=S({multiRNNCell_:GW});function UW(r,e,t,o=!1){let n=k(r,"logits","multinomial"),s=n.size,a=n.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(n,[1,-1]):n},u={numSamples:e,seed:t,normalized:o},c=E.runKernel(uu,l,u);return a===1?L(c,[c.size]):c}var I_=S({multinomial_:UW});function jW(r,e){let t=k(r,"a","notEqual"),o=k(e,"b","notEqual");[t,o]=Ge(t,o),ze(t.shape,o.shape);let n={a:t,b:o};return E.runKernel(bi,n)}var Ln=S({notEqual_:jW});function gt(r,e="float32"){if(e==="complex64"){let o=gt(r,"float32"),n=gt(r,"float32");return bo(o,n)}let t=Dc(ft(r),e);return E.makeTensor(t,r,e)}function Cr(r,e="float32"){if(e==="complex64"){let o=Cr(r,"float32"),n=gt(r,"float32");return bo(o,n)}let t=mm(ft(r),e);return E.makeTensor(t,r,e)}function HW(r){let t={x:k(r,"x","onesLike")};return E.runKernel(ps,t)}var er=S({onesLike_:HW});function qW(r,e){let t=k(r,"v1","outerProduct"),o=k(e,"v2","outerProduct");T(t.rank===1&&o.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${t.rank} and ${o.rank}.`);let n=L(t,[-1,1]),s=L(o,[1,-1]);return We(n,s)}var KW=S({outerProduct_:qW});function XW(r,e,t=0){let o=k(r,"x","pad");if(o.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let n={paddings:e,constantValue:t},s={x:o};return E.runKernel(gn,s,n)}var $r=S({pad_:XW});function YW(r,e,t=0){return T(e.length===2,()=>"Invalid number of paddings. Must be length of 2."),$r(r,[e],t)}var ZW=S({pad1d_:YW});function JW(r,e,t=0){return T(e.length===2&&e[0].length===2&&e[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),$r(r,e,t)}var QW=S({pad2d_:JW});function e4(r,e,t=0){return T(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."),$r(r,e,t)}var t4=S({pad3d_:e4});function r4(r,e,t=0){return T(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."),$r(r,e,t)}var o4=S({pad4d_:r4});function n4(r,e,t){let o=k(r,"x","spaceToBatchND");T(o.rank>=1+e.length,()=>`input rank ${o.rank} should be > than [blockShape] ${e.length}`),T(t.length===e.length,()=>`paddings.shape[0] ${t.length} must be equal to [blockShape] ${e.length}`),T(o.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 ${o.shape.slice(1)} with paddings ${t.toString()} must be divisible by blockShapes ${e.toString()}`);let n={x:o},s={blockShape:e,paddings:t};return E.runKernel(ha,n,s)}var Aa=S({spaceToBatchND_:n4});function a4(r,e,t,o,n,s){n==null&&(n=[1,1]),s==null&&(s=1),o===0&&(o="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]])),T(yr(s,n),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${n}'`);let u=r_(i.shape,e,s,n,o),c=[u.dilationHeight,u.dilationWidth],p;o==="same"?p=i4([u.filterHeight,u.filterWidth],c):p=[[0,0],[0,0]];let m=c[0]===1&&c[1]===1,[f,d]=s4([u.inHeight,u.inWidth],c,p),h=m?o:"valid",g=m?i:Aa(i,c,f),b=(t==="avg"?()=>va(g,e,s,h):()=>Ea(g,e,s,h))(),_=m?b:Ca(b,c,d);return l?L(_,[_.shape[1],_.shape[2],_.shape[3]]):_}function s4(r,e,t){let o=t.map(c=>c[0]),n=t.map(c=>c[1]),s=r.concat(o,n),a=e.map((c,p)=>(c-s[p]%c)%c),i=n.map((c,p)=>c+a[p]),l=e.map((c,p)=>[o[p],i[p]]),u=e.map((c,p)=>[0,a[p]]);return[l,u]}function i4(r,e){let o=r.map((a,i)=>a+(a-1)*(e[i]-1)).map(a=>a-1),n=o.map(a=>Math.floor(a/2)),s=o.map((a,i)=>a-n[i]);return o.map((a,i)=>[n[i],s[i]])}var N_=S({pool_:a4});function l4(r,e){let t=k(r,"base","pow"),o=k(e,"exp","pow");[t,o]=Ge(t,o);let n={a:t,b:o};return E.runKernel(xn,n)}var Rr=S({pow_:l4});function u4(r,e){let t=k(r,"x","prelu"),o=k(e,"alpha","prelu"),n={x:t,alpha:o};return E.runKernel(yn,n)}var Da=S({prelu_:u4});function c4(r,e=null,t=!1){let o=k(r,"x","prod");o.dtype==="bool"&&(o=oe(o,"int32"));let n={x:o},s={axis:e,keepDims:t};return E.runKernel(vi,n,s)}var $u=S({prod_:c4});function p4(r,e,t){let o=ft(r),n=null;if(t==null||t==="float32")n=new Float32Array(o);else if(t==="int32")n=new Int32Array(o);else if(t==="bool")n=new Uint8Array(o);else throw new Error(`Unknown data type ${t}`);for(let s=0;s<o;s++)n[s]=e();return E.makeTensor(n,r,t)}var m4=S({rand_:p4});var lg=Sc(jm());var Yc=class{constructor(e,t,o,n,s){this.mean=e,this.stdDev=t,this.dtype=o,this.nextVal=NaN,this.truncated=n,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);let a=s||Math.random();this.random=lg.alea(a.toString())}nextValue(){if(!isNaN(this.nextVal)){let n=this.nextVal;return this.nextVal=NaN,n}let e,t,o=!1;for(;!o;){let n,s,a;do n=2*this.random()-1,s=2*this.random()-1,a=n*n+s*s;while(a>=1||a===0);let i=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*n*i,t=this.mean+this.stdDev*s*i,(!this.truncated||this.isValidTruncated(e))&&(o=!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}},R_=class{constructor(e,t,o,n){this.alpha=e,this.beta=1/t,this.dtype=o;let s=n||Math.random();this.randu=lg.alea(s.toString()),this.randn=new Yc(0,1,o,!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,o,n,s,a;for(;;){do n=this.randn.nextValue(),a=1+this.c*n;while(a<=0);if(a*=a*a,e=n*n,t=1-.331*e*e,o=.5*e+this.d*(1-a+Math.log(a)),s=this.randu(),s<t||Math.log(s)<o)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)}},F_=class{constructor(e=0,t=1,o,n){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=o,n==null&&(n=Math.random()),typeof n=="number"&&(n=n.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=lg.alea(n)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function b4(r,e,t=1,o="float32",n){if(t==null&&(t=1),o==null&&(o="float32"),o!=="float32"&&o!=="int32")throw new Error(`Unsupported data type ${o}`);let s=new R_(e,t,o,n),a=Ce(r,o);for(let i=0;i<a.values.length;i++)a.values[i]=s.nextValue();return a.toTensor()}var _4=S({randomGamma_:b4});function w4(r,e=0,t=1,o,n){if(o!=null&&o==="bool")throw new Error(`Unsupported data type ${o}`);let s=new Yc(e,t,o,!1,n),a=Ce(r,o);for(let i=0;i<a.values.length;i++)a.values[i]=s.nextValue();return a.toTensor()}var ug=S({randomNormal_:w4});function k4(r,e=0,t=1,o="float32",n){let s=Ce(r,o),a=new F_(e,t,null,n);for(let i=0;i<s.values.length;i++)s.values[i]=a.nextValue();return s.toTensor()}var Es=S({randomUniform_:k4});function Zc(r,e,t=1,o="float32"){if(t===0)throw new Error("Cannot have a step of zero");let n={start:r,stop:e,step:t,dtype:o};return E.runKernel(fa,{},n)}function v4(r){let t={input:k(r,"input","real")};return E.runKernel(cu,t)}var al=S({real_:v4});function C4(r){let t={x:k(r,"x","reciprocal")};return E.runKernel(Ci,t)}var Hm=S({reciprocal_:C4});function I4(r){let t={x:k(r,"x","relu")};return E.runKernel(bn,t)}var Ir=S({relu_:I4});function N4(r){let t={x:k(r,"x","relu6")};return E.runKernel(wn,t)}var Fu=S({relu6_:N4});function S4(r,e){let o={x:k(r,"x","reverse")},n={dims:e};return E.runKernel(kn,o,n)}var qt=S({reverse_:S4});function T4(r){let e=k(r,"x","reverse");return T(e.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${e.rank}.`),qt(e,0)}var E4=S({reverse1d_:T4});function A4(r,e){let t=k(r,"x","reverse");return T(t.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${t.rank}.`),qt(t,e)}var D4=S({reverse2d_:A4});function $4(r,e){let t=k(r,"x","reverse");return T(t.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${t.rank}.`),qt(t,e)}var R4=S({reverse3d_:$4});function F4(r,e){let t=k(r,"x","reverse");return T(t.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${t.rank}.`),qt(t,e)}var O4=S({reverse4d_:F4});function P4(r){let t={x:k(r,"x","round")};return E.runKernel(vn,t)}var qm=S({round_:P4});function M4(r){let t={x:k(r,"x","rsqrt")};return E.runKernel(Cn,t)}var Ou=S({rsqrt_:M4});function le(r,e){if((rr(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"&&rr(r)&&!(r instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Gr(r,[],[],e)}function L4(r){let t={x:k(r,"x","selu")};return E.runKernel(Ni,t)}var Pu=S({selu_:L4});function z4(r,e,t,o,n,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");T(c.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`),T(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),T(u.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),T(u.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`),T(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];T(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=Cs(c,l,o,n,a,s),g=jr(d,u,1,"valid",a);return p?L(g,[g.shape[1],g.shape[2],g.shape[3]]):g}var Km=S({separableConv2d_:z4});async function B4(r,e){let t=k(r,"x","setdiff1d"),o=k(e,"y","setdiff1d");T(t.dtype===o.dtype,()=>`x and y should have the same dtype, but got x (${t.dtype}) and y (${o.dtype}).`),T(t.rank===1,()=>`x should be 1D tensor, but got x (${t.shape}).`),T(o.rank===1,()=>`y should be 1D tensor, but got y (${o.shape}).`);let n=await t.data(),s=await o.data(),a=new Set(s),i=0;for(let c=0;c<n.length;c++)a.has(n[c])||i++;let l=new ct([i],t.dtype),u=new ct([i],"int32");for(let c=0,p=0;c<n.length;c++)a.has(n[c])||(l.values[p]=n[c],u.values[p]=c,p++);return[l.toTensor(),u.toTensor()]}var O_=B4;function V4(r){let t={x:k(r,"x","sign")};return E.runKernel(Ti,t)}var Xm=S({sign_:V4});function G4(r){let t={x:k(r,"x","sin")};return E.runKernel(In,t)}var Mu=S({sin_:G4});function W4(r){let t={x:k(r,"x","sinh")};return E.runKernel(Si,t)}var Lu=S({sinh_:W4});function U4(r,e,t){let o=k(r,"x","slice1d");return T(o.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${o.rank} tensor`),Fe(o,[e],[t])}var Ym=S({slice1d_:U4});function j4(r,e,t){let o=k(r,"x","slice2d");return T(o.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${o.rank} tensor`),Fe(o,e,t)}var cg=S({slice2d_:j4});function H4(r,e,t){let o=k(r,"x","slice3d");return T(o.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${o.rank} tensor`),Fe(o,e,t)}var Zm=S({slice3d_:H4});function q4(r,e,t){let o=k(r,"x","slice4d");return T(o.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${o.rank} tensor`),Fe(o,e,t)}var Jc=S({slice4d_:q4});function K4(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 o={logits:t},n={dim:e};return E.runKernel(En,o,n)}var $a=S({softmax_:K4});function X4(r){T(r.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${r.dtype}.`);let e={input:r};return E.runKernel(tu,e)}var Ra=S({fft_:X4});function Y4(r){T(r.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${r.dtype}.`);let e={input:r};return E.runKernel(ru,e)}var zi=S({ifft_:Y4});function Z4(r){let e=r.shape[r.shape.length-1],t=r.size/e,o;if(e<=2){let n=L(r,[t,e]);o=zi(n)}else{let n=[t,2*(e-1)],s=L(al(r),[t,e]),a=L(Su(r),[t,e]),i=qt(Fe(s,[0,1],[t,e-2]),1),l=O(qt(Fe(a,[0,1],[t,e-2]),1),le(-1)),u=Je([s,i],1),c=Je([a,l],1),p=L(bo(u,c),[n[0],n[1]]);o=zi(p)}if(o=al(o),r.rank===3&&r.shape[0]!==0){let n=o,s=r.shape[0];o=L(o,[s,o.shape[0]/s,o.shape[1]]),n.dispose()}return o}var zu=S({irfft_:Z4});function J4(r,e,t=0){let n={x:k(r,"x","split")},s={numOrSizeSplits:e,axis:t};return E.runKernel(gs,n,s)}var lr=S({split_:J4});function Q4(r,e){T(r.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${r.dtype}`);let t=r.shape[r.shape.length-1],o=r.size/t,n;if(e!=null&&e<t){let d=r.shape.map(g=>0),h=r.shape.map(g=>g);h[r.shape.length-1]=e,n=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,n=Je([r,gt(d)],r.shape.length-1),t=e}else n=r;let s=Ie(n),a=L(bo(n,s),[o,t]),i=Ra(a),l=Math.floor(t/2)+1,u=al(i),c=Su(i),p=lr(u,[l,t-l],u.shape.length-1),m=lr(c,[l,t-l],c.shape.length-1),f=n.shape.slice();return f[n.shape.length-1]=l,L(bo(p[0],m[0]),f)}var Fa=S({rfft_:Q4});function eU(r){let t={x:k(r,"x","sqrt")};return E.runKernel(Sn,t)}var xt=S({sqrt_:eU});function tU(r,e){let t=k(r,"a","squaredDifference"),o=k(e,"b","squaredDifference");[t,o]=Ge(t,o),ze(t.shape,o.shape);let n={a:t,b:o},s={};return E.runKernel(An,n,s)}var Bu=S({squaredDifference_:tU});function rU(r,e){let t=k(r,"x","squeeze");return L(t,ub(t.shape,e).newShape)}var wo=S({squeeze_:rU});function oU(r,e=0){let t=ya(r,"tensors","stack","string_or_numeric");T(t.length>=1,()=>"Pass at least one tensor to tf.stack"),t.length>0&&T(e<=t[0].rank,()=>"Axis must be <= rank of the tensor");let o=t,n={axis:e};return E.runKernel(ms,o,n)}var Bt=S({stack_:oU});function nU(r,e=0){let o={x:k(r,"x","step")},n={alpha:e};return E.runKernel(Do,o,n)}var As=S({step_:nU});function sU(r,e,t,o,n=0,s=0,a=0,i=0,l=0){let c={x:k(r,"x","stridedSlice")},p={begin:e,end:t,strides:o,beginMask:n,endMask:s,ellipsisMask:a,newAxisMask:i,shrinkAxisMask:l};return E.runKernel(Ai,c,p)}var Jm=S({stridedSlice_:sU});function iU(r){let t={x:k(r,"x","tan")};return E.runKernel(Di,t)}var Qm=S({tan_:iU});function Vt(r,e){To(r);let t=kr(r,e);if(t.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Gr(r,null,t,e)}function Bi(r,e,t){if(To(r),e!=null&&e.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let o=kr(r,t);if(o.length!==2&&o.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(o.length===1&&e==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Gr(r,e,o,t)}function aU(r,e,t){if(To(r),e!=null&&e.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let o=kr(r,t);if(o.length!==4&&o.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(o.length===1&&e==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Gr(r,e,o,t)}function lU(r,e,t){if(To(r),e!=null&&e.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let o=kr(r,t);if(o.length!==5&&o.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(o.length===1&&e==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Gr(r,e,o,t)}function uU(r,e,t){if(To(r),e!=null&&e.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let o=kr(r,t);if(o.length!==6&&o.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(o.length===1&&e==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return e=e||o,Gr(r,e,o,t)}function cU(r,e=1,t=!0){let o=k(r,"x","topk");if(o.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let n=o.shape[o.shape.length-1];if(e>n)throw new Error(`'k' passed to topk() must be <= the last dimension (${n}) but got ${e}`);let s={x:o},a={k:e,sorted:t},[i,l]=E.runKernel($i,s,a);return{values:i,indices:l}}var ef=S({topk_:cU});function pU(r,e=0,t=1,o,n){if(o!=null&&o==="bool")throw new Error("Unsupported data type $ { dtype }");let s=new Yc(e,t,o,!0,n),a=Ce(r,o);for(let i=0;i<a.values.length;i++)a.values[i]=s.nextValue();return a.toTensor()}var Vu=S({truncatedNormal_:pU});function mU(r,e=0){let t=k(r,"x","unique","string_or_numeric");T(t.rank>0,()=>"The input tensor must be at least 1D");let o={x:t},n={axis:e},[s,a]=E.runKernel(du,o,n);return{values:s,indices:a}}var Qc=S({unique_:mU});function fU(r,e,t){let o=k(r,"x","unsortedSegmentSum"),n=k(e,"segmentIds","unsortedSegmentSum","int32");T(st(t),()=>"numSegments must be of dtype int");let s={x:o,segmentIds:n},a={numSegments:t};return E.runKernel(xa,s,a)}var tf=S({unsortedSegmentSum_:fU});function dU(r,e=0){let t=k(r,"x","unstack","string_or_numeric");T(e>=-t.shape.length&&e<t.shape.length,()=>`Axis = ${e} is not in [-${t.shape.length}, ${t.shape.length})`);let o={value:t},n={axis:e};return E.runKernel(xs,o,n)}var ur=S({unstack_:dU});function P_(r,e=!0,t,o){return E.makeVariable(r,e,t,o)}function M_(r,e){let t=[];for(let s=0;s<e.length;s++)e[s]&&t.push(s);let o=Ce(r,"int32"),n=Ce([t.length,r.length],"int32");for(let s=0;s<t.length;s++){let a=o.indexToLoc(t[s]),i=s*r.length;n.values.set(a,i)}return n.toTensor()}async function hU(r){let e=k(r,"condition","whereAsync","bool"),t=await e.data(),o=M_(e.shape,t);return r!==e&&e.dispose(),o}var rf=hU;async function gU(r,e,t){let o=k(r,"tensor","boolMask"),n=k(e,"mask","boolMask","bool"),s=t==null?0:t,a=n.rank,i=o.shape;T(a>0,()=>"mask cannot be scalar"),Nt(i.slice(s,s+a),n.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(o,u),p=L(n,[-1]),m=await rf(p),f=wo(m,[1]),d=Pn(c,f,s);return r!==o&&o.dispose(),e!==n&&n.dispose(),f.dispose(),c.dispose(),p.dispose(),m.dispose(),d}var xU=gU;function yU(r,e="euclidean",t=null,o=!1){r=k(r,"x","norm");let n=XN(r,e,t),s=n.shape;if(o){let a=Jt(t,r.shape);s=Mn(n.shape,a)}return L(n,s)}function XN(r,e,t=null){if(r.rank===0)return Tt(r);if(r.rank!==1&&t===null)return XN(L(r,[-1]),e,t);if(r.rank===1||typeof t=="number"||Array.isArray(t)&&t.length===1){if(e===1)return ye(Tt(r),t);if(e===Infinity)return ar(Tt(r),t);if(e===-Infinity)return Li(Tt(r),t);if(e==="euclidean"||e===2)return xt(ye(Rr(Tt(r),le(2,"int32")),t));throw new Error(`Error in norm: invalid ord value: ${e}`)}if(Array.isArray(t)&&t.length===2){if(e===1)return ar(ye(Tt(r),t[0]),t[1]-1);if(e===Infinity)return ar(ye(Tt(r),t[1]),t[0]);if(e===-Infinity)return Li(ye(Tt(r),t[1]),t[0]);if(e==="fro"||e==="euclidean")return xt(ye(Pe(r),t));throw new Error(`Error in norm: invalid ord value: ${e}`)}throw new Error(`Error in norm: invalid axis: ${t}`)}var Gu=S({norm_:yU});function bU(r,e,t,o,n=!0){let s=k(r,"v","movingAverage"),a=k(e,"x","movingAverage"),i=k(t,"decay","movingAverage");Ab(s,a),T(Vr(s.shape,a.shape),()=>"Shape mismatch in v and x");let l=le(1),u=ue(l,i),c=O(ue(a,s),u);if(n){T(o!=null,()=>"When using zeroDebias: true, step is required.");let p=k(o,"step","movingAverage");c=de(c,ue(l,Rr(i,p)))}return Q(s,c)}var _U=S({movingAverage_:bU});function wU(r,e,t){let o=k(r,"indices","scatterND","int32"),n=k(e,"updates","scatterND");Qh(n,o,t);let s={indices:o,updates:n},a={shape:t};return E.runKernel(Ii,s,a)}var L_=S({scatterND_:wU});function YN(r,e,t,o){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 n=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===n))throw new Error(`sparseValues has incorrect shape ${e.shape}, should be [] or [${n}]`);if(e.dtype!==o.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function kU(r,e,t,o=0){let n=k(r,"sparseIndices","sparseToDense","int32"),s=k(e,"sparseValues","sparseToDense"),a=k(o,"defaultValue","sparseToDense",s.dtype);YN(n,s,t,a);let i={sparseIndices:n,sparseValues:s,defaultValue:a},l={outputShape:t};return E.runKernel(fu,i,l)}var of=S({sparseToDense_:kU});function vU(r,e){let t=k(e,"indices","gatherND","int32"),n={params:k(r,"x","gatherND"),indices:t};return E.runKernel(ui,n)}var z_=S({gatherND_:vU});function ZN(r,e){if(e==null)return r.shape.slice();if(Vr(r.shape,e))return e;if(r.shape.length===e.length){let t=[];for(let o=0;o<r.shape.length;o++)e[o]==null&&r.shape[o]!=null?t.push(r.shape[o]):t.push(e[o]);return t}return e}function CU(r,e,t,o){let n=k(r,"x","dropout");if(T(n.dtype==="float32",()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${n.dtype} tensor instead.`),T(e>=0&&e<1,()=>`rate must be a float in the range [0, 1), but got ${e}.`),e===0)return r instanceof Ve?n.clone():n;let s=ZN(n,t),a=1-e,i=de(Ns(Q(Es(s,0,1,"float32",o),a)),a);return O(n,i)}var B_=S({dropout_:CU});function V_(r){return Math.floor(Math.pow(2,Math.ceil(Math.log(r)/Math.log(2))))}function nf(r,e,t){let o=1-r%2,n=new Float32Array(r);for(let s=0;s<r;++s){let a=2*Math.PI*s/(r+o-1);n[s]=e-t*Math.cos(a)}return Vt(n,"float32")}async function IU(r,e,t=1){let o=k(r,"predictions","inTopK"),n=k(e,"targets","inTopK");T(o.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${o.rank}`),T(o.rank-1===n.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${o.rank} and targets rank ${n.rank}`),Nt(o.shape.slice(0,o.shape.length-1),n.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let s=o.shape[o.shape.length-1];T(t>0&&t<=s,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${s}), but got ${t}`);let a=await o.data(),i=await n.data(),[l,u]=[a.length/s,s],c=cb("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!==o&&o.dispose(),e!==n&&n.dispose(),Dr(c,n.shape,"bool")}var NU=IU;var zn={};et(zn,{conv2d:()=>EU,depthwiseConv2d:()=>RU,matMul:()=>OU});function SU(r,e,t,o,n,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]])),T(i.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`),T(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),T(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];T(u===t[2],()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${t[2]}.`),T(c===t[3],()=>`Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${t[3]}).`),a!=null&&T(st(n),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${a} but got pad ${n}.`);let p={x:i,dy:l},m={strides:o,pad:n,dataFormat:s,dimRoundingMode:a,filterShape:t};return E.runKernel(ql,p,m)}var ep=S({conv2DBackpropFilter_:SU});function Wu(r,e,t){if(t==null||t==="linear")return r;if(t==="relu")return O(r,As(e));throw new Error(`Cannot compute gradient for fused activation ${t}.`)}function Uu(r,e){let t=e,o=Ct(r.shape,e.shape);return o.length>0&&(t=ye(t,o)),L(t,r.shape)}function ju(r,e,t,o){if(e==="linear")return r;if(e==="relu")return Ir(r);if(e==="elu")return Is(r);if(e==="relu6")return Fu(r);if(e==="prelu")return Da(r,t);if(e==="leakyrelu")return Sa(r,o);throw new Error(`Unknown fused activation ${e}.`)}var Hu=(r,e)=>!(r>0)||e==="linear";function TU({x:r,filter:e,strides:t,pad:o,dataFormat:n="NHWC",dilations:s=[1,1],dimRoundingMode:a,bias:i,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:c}){if(l=l||"linear",Hu(E.state.gradientDepth,l)===!1){let v=jr(r,e,t,o,n,s,a);return i!=null&&(v=Q(v,i)),ju(v,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]])),T(f.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${f.rank}.`),T(m.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${m.rank}.`),a!=null&&T(st(o),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`),T(f.shape[3]===m.shape[2],()=>`Error in conv2d: depth of input (${f.shape[3]}) must match input depth for filter ${m.shape[2]}.`),T(yr(t,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`),T(n==="NHWC",()=>`Error in conv2d: got dataFormat of ${n} but only NHWC is currently supported.`);let h=wu(f.shape,m.shape,t,s,o,a),g;i!=null&&(g=k(i,"bias","fused conv2d"),[g]=Ge(g,p),ze(h.outShape,g.shape));let x;u!=null&&(x=k(u,"prelu weights","fused conv2d"));let b=(v,$)=>{let[A,R,M,z]=$,W=Wu(v,M,l);T(Ro(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let U=qc(R.shape,W,A,t,o),q=ep(R,W,A.shape,t,o),Z=[U,q];if(z!=null){let X=Uu(z,W);Z.push(X)}return Z},_={x:f,filter:m,bias:g,preluActivationWeights:x},w={strides:t,pad:o,dataFormat:n,dilations:s,dimRoundingMode:a,activation:l,leakyreluAlpha:c};return i==null?Hr(($,A,R)=>{let M=E.runKernel(_s,_,w);return R([A,$,M]),d&&(M=L(M,[M.shape[1],M.shape[2],M.shape[3]])),{value:M,gradFunc:b}})(f,m):Hr(($,A,R,M)=>{let z=E.runKernel(_s,_,w);return M([A,$,z,R]),d&&(z=L(z,[z.shape[1],z.shape[2],z.shape[3]])),{value:z,gradFunc:b}})(f,m,g)}var EU=S({fusedConv2d_:TU});function AU(r,e,t,o,n,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:o,pad:n,dimRoundingMode:a,dilations:s,filterShape:t};return E.runKernel(Zl,u,c)}var pg=S({depthwiseConv2dNativeBackpropFilter_:AU});function DU(r,e,t,o,n,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:o,pad:n,dimRoundingMode:a,dilations:s,inputShape:r},p=E.runKernel(Jl,u,c);return l?L(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var mg=S({depthwiseConv2dNativeBackpropInput_:DU});function $U({x:r,filter:e,strides:t,pad:o,dataFormat:n="NHWC",dilations:s=[1,1],dimRoundingMode:a,bias:i,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:c}){if(Hu(E.state.gradientDepth,l)===!1){let v=Cs(r,e,t,o,n,s,a);return i!=null&&(v=Q(v,i)),ju(v,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]])),T(f.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${f.rank}.`),T(m.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${m.rank}.`),T(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]),T(yr(t,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`),a!=null&&T(st(o),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${a} but got pad ${o}.`);let h=wu(f.shape,m.shape,t,s,o,a,!0),g;i!=null&&(g=k(i,"bias","fused conv2d"),[g]=Ge(g,p),ze(h.outShape,g.shape));let x;u!=null&&(x=k(u,"prelu weights","fused depthwiseConv2d"));let b=(v,$)=>{T(Ro(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);let[A,R,M,z]=$,W=Wu(v,M,l),U=mg(R.shape,W,A,t,o,s,a),q=pg(R,W,A.shape,t,o,s,a);if(z!=null){let Z=Uu(g,W);return[U,q,Z]}return[U,q]},_={x:f,filter:m,bias:g,preluActivationWeights:x},w={strides:t,pad:o,dataFormat:n,dilations:s,dimRoundingMode:a,activation:l,leakyreluAlpha:c};return i==null?Hr(($,A,R)=>{let M=E.runKernel(ws,_,w);return R([A,$,M]),d&&(M=L(M,[M.shape[1],M.shape[2],M.shape[3]])),{value:M,gradFunc:b}})(f,m):Hr(($,A,R,M)=>{let z=E.runKernel(ws,_,w);return M([A,$,z,R]),d&&(z=L(z,[z.shape[1],z.shape[2],z.shape[3]])),{value:z,gradFunc:b}})(f,m,g)}var RU=S({fusedDepthwiseConv2d_:$U});function FU({a:r,b:e,transposeA:t=!1,transposeB:o=!1,bias:n,activation:s="linear",preluActivationWeights:a,leakyreluAlpha:i}){if(Hu(E.state.gradientDepth,s)===!1){let z=We(r,e,t,o);return n!=null&&(z=Q(z,n)),ju(z,s,a,i)}let l=k(r,"a","fused matMul"),u=k(e,"b","fused matMul");[l,u]=Ge(l,u);let c=t?l.shape[l.rank-2]:l.shape[l.rank-1],p=o?u.shape[u.rank-1]:u.shape[u.rank-2],m=t?l.shape[l.rank-1]:l.shape[l.rank-2],f=o?u.shape[u.rank-2]:u.shape[u.rank-1],d=l.shape.slice(0,-2),h=u.shape.slice(0,-2),g=ft(d),x=ft(h);T(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}.`),T(Vr(d,h),()=>`Error in fused matMul: outer dimensions (${d}) and (${h}) of Tensors with shapes ${l.shape} and ${u.shape} must match.`),T(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=${o} must match.`);let b=l.shape.slice(0,-2).concat([m,f]),_=t?L(l,[g,c,m]):L(l,[g,m,c]),w=o?L(u,[x,f,p]):L(u,[x,p,f]),v;n!=null&&(v=k(n,"bias","fused matMul"),[v]=Ge(v,l),ze(b,v.shape));let $;a!=null&&($=k(a,"prelu weights","fused matMul"));let A=(z,W)=>{let[U,q,Z,X]=W,Y=Wu(L(z,Z.shape),Z,s),te,K;if(!t&&!o?(te=We(Y,q,!1,!0),K=We(U,Y,!0,!1)):!t&&o?(te=We(Y,q,!1,!1),K=We(Y,U,!0,!1)):t&&!o?(te=We(q,Y,!1,!0),K=We(U,Y,!1,!1)):(te=We(q,Y,!0,!0),K=We(Y,U,!0,!0)),n!=null){let re=Uu(X,Y);return[te,K,re]}else return[te,K]},R={a:_,b:w,bias:v,preluActivationWeights:$},M={transposeA:t,transposeB:o,activation:s,leakyreluAlpha:i};return n==null?Hr((W,U,q)=>{let Z=E.runKernel(bs,R,M);return q([W,U,Z]),{value:L(Z,b),gradFunc:A}})(_,w):Hr((W,U,q,Z)=>{let X=E.runKernel(bs,R,M);return Z([W,U,X,q]),{value:L(X,b),gradFunc:A}})(_,w,v)}var OU=S({fusedMatMul_:FU});function PU(r){return nf(r,.54,.46)}var JN=S({hammingWindow_:PU});function MU(r){return nf(r,.5,.5)}var fg=S({hannWindow_:MU});function LU(r,e,t,o=!1,n=0){let s=0,a=[];for(;s+e<=r.size;)a.push(Fe(r,s,e)),s+=t;if(o)for(;s<r.size;){let i=s+e-r.size,l=Je([Fe(r,s,e-i),Na([i],n)]);a.push(l),s+=t}return a.length===0?Bi([],[0,e]):L(Je(a),[a.length,e])}var dg=S({frame_:LU});function zU(r,e,t,o,n=fg){o==null&&(o=V_(e));let s=dg(r,e,t),a=O(s,n(e)),i=[];for(let l=0;l<s.shape[0];l++)i.push(Fa(Fe(a,[l,0],[1,e]),o));return Je(i)}var QN=S({stft_:zU});function BU(r,e,t,o,n="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];T(a.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${a.rank}.`),T(i.rank===2&&i.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${i.shape}.`),T(l.rank===1&&l.shape[0]===u,()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${i.shape}.`),T(o.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${o.length}.`),T(o[0]>=1&&o[1]>=1,()=>`cropSize must be atleast [1,1], but was ${o}`),T(n==="bilinear"||n==="nearest",()=>`method must be bilinear or nearest, but was ${n}`);let c={image:a,boxes:i,boxInd:l},p={method:n,extrapolationValue:s,cropSize:o};return E.runKernel(ri,c,p)}var e0=S({cropAndResize_:BU});function VU(r){let e=k(r,"image","flipLeftRight","float32");T(e.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${e.rank}.`);let t={image:e};return E.runKernel(li,t,{})}var t0=S({flipLeftRight_:VU});function GU(r,e,t=0,o=.5){let n=k(r,"image","rotateWithOffset","float32");T(n.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${n.rank}.`);let s={image:n},a={radians:e,fillValue:t,center:o};return E.runKernel(Ri,s,a)}var r0=S({rotateWithOffset_:GU});function Bn(r,e,t,o,n,s){o==null&&(o=.5),n==null&&(n=Number.NEGATIVE_INFINITY),s==null&&(s=0);let a=r.shape[0];return t=Math.min(t,a),T(0<=o&&o<=1,()=>`iouThreshold must be in [0, 1], but was '${o}'`),T(r.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${r.rank}'`),T(r.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${r.shape[1]}`),T(e.rank===1,()=>"scores must be a 1D tensor"),T(e.shape[0]===a,()=>`scores has incompatible shape with boxes. Expected ${a}, but was ${e.shape[0]}`),T(0<=s&&s<=1,()=>`softNmsSigma must be in [0, 1], but was '${s}'`),{maxOutputSize:t,iouThreshold:o,scoreThreshold:n,softNmsSigma:s}}function WU(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY){let s=k(r,"boxes","nonMaxSuppression"),a=k(e,"scores","nonMaxSuppression"),i=Bn(s,a,t,o,n);t=i.maxOutputSize,o=i.iouThreshold,n=i.scoreThreshold;let l={maxOutputSize:t,iouThreshold:o,scoreThreshold:n};return E.runKernel(_i,{boxes:s,scores:a},l)}var o0=S({nonMaxSuppression_:WU});function n0(r,e,t){let o=UU(r,e,t),n=o<0?-(o+1):o;r.splice(n,0,e)}function UU(r,e,t){return HU(r,e,t||jU)}function jU(r,e){return r>e?1:r<e?-1:0}function HU(r,e,t){let o=0,n=r.length,s=0,a=!1;for(;o<n;){s=o+(n-o>>>1);let i=t(e,r[s]);i>0?o=s+1:(n=s,a=!i)}return a?o:-o-1}function W_(r,e,t,o,n){return G_(r,e,t,o,n,0)}function U_(r,e,t,o,n,s){return G_(r,e,t,o,n,0,!1,s,!0)}function j_(r,e,t,o,n,s){return G_(r,e,t,o,n,s,!0)}function G_(r,e,t,o,n,s,a=!1,i=!1,l=!1){let u=[];for(let g=0;g<e.length;g++)e[g]>n&&u.push({score:e[g],boxIndex:g,suppressBeginIndex:0});u.sort(s0);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:_}=g;if(x<n)break;let w=!1;for(let v=p.length-1;v>=_;--v){let $=qU(r,b,p[v]);if($>=o){w=!0;break}if(g.score=g.score*KU(o,c,$),g.score<=n)break}g.suppressBeginIndex=p.length,w||(g.score===x?(p.push(b),m.push(g.score)):g.score>n&&n0(u,g,s0))}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 qU(r,e,t){let o=r.subarray(e*4,e*4+4),n=r.subarray(t*4,t*4+4),s=Math.min(o[0],o[2]),a=Math.min(o[1],o[3]),i=Math.max(o[0],o[2]),l=Math.max(o[1],o[3]),u=Math.min(n[0],n[2]),c=Math.min(n[1],n[3]),p=Math.max(n[0],n[2]),m=Math.max(n[1],n[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),_=Math.max(x-h,0)*Math.max(b-g,0);return _/(f+d-_)}function KU(r,e,t){let o=Math.exp(e*t*t);return t<=r?o:0}function s0(r,e){return r.score-e.score||r.score===e.score&&e.boxIndex-r.boxIndex}async function XU(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY){let s=k(r,"boxes","nonMaxSuppressionAsync"),a=k(e,"scores","nonMaxSuppressionAsync"),i=Bn(s,a,t,o,n);t=i.maxOutputSize,o=i.iouThreshold,n=i.scoreThreshold;let l=await Promise.all([s.data(),a.data()]),u=l[0],c=l[1],{selectedIndices:p}=W_(u,c,t,o,n);return s!==r&&s.dispose(),a!==e&&a.dispose(),Vt(p,"int32")}var i0=XU;function YU(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY,s=0){let a=k(r,"boxes","nonMaxSuppression"),i=k(e,"scores","nonMaxSuppression"),l=Bn(a,i,t,o,n,s);t=l.maxOutputSize,o=l.iouThreshold,n=l.scoreThreshold,s=l.softNmsSigma;let u={boxes:a,scores:i},c={maxOutputSize:t,iouThreshold:o,scoreThreshold:n,softNmsSigma:s},p=E.runKernel(ki,u,c);return{selectedIndices:p[0],selectedScores:p[1]}}var a0=S({nonMaxSuppressionWithScore_:YU});async function ZU(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY,s=0){let a=k(r,"boxes","nonMaxSuppressionAsync"),i=k(e,"scores","nonMaxSuppressionAsync"),l=Bn(a,i,t,o,n,s);t=l.maxOutputSize,o=l.iouThreshold,n=l.scoreThreshold,s=l.softNmsSigma;let u=await Promise.all([a.data(),i.data()]),c=u[0],p=u[1],{selectedIndices:m,selectedScores:f}=j_(c,p,t,o,n,s);return a!==r&&a.dispose(),i!==e&&i.dispose(),{selectedIndices:Vt(m,"int32"),selectedScores:Vt(f)}}var l0=ZU;function JU(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY,s=!1){let a=k(r,"boxes","nonMaxSuppression"),i=k(e,"scores","nonMaxSuppression"),l=Bn(a,i,t,o,n,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=E.runKernel(wi,m,f);return{selectedIndices:d[0],validOutputs:d[1]}}var u0=S({nonMaxSuppressionPadded_:JU});async function QU(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY,s=!1){let a=k(r,"boxes","nonMaxSuppressionAsync"),i=k(e,"scores","nonMaxSuppressionAsync"),l=Bn(a,i,t,o,n,null),u=l.maxOutputSize,c=l.iouThreshold,p=l.scoreThreshold,[m,f]=await Promise.all([a.data(),i.data()]),{selectedIndices:d,validOutputs:h}=U_(m,f,u,c,p,s);return a!==r&&a.dispose(),i!==e&&i.dispose(),{selectedIndices:Vt(d,"int32"),validOutputs:le(h,"int32")}}var c0=QU;function ej(r,e,t=!1,o=!1){let n=k(r,"images","resizeBilinear");T(n.rank===3||n.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${n.rank}.`),T(e.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${e}.`),T(o===!1||t===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let s=n,a=!1;n.rank===3&&(a=!0,s=L(n,[1,n.shape[0],n.shape[1],n.shape[2]]));let[]=e,i={images:s},l={alignCorners:t,halfPixelCenters:o,size:e},u=E.runKernel(_n,i,l);return a?L(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var hg=S({resizeBilinear_:ej});function tj(r,e,t=!1,o=!1){let n=k(r,"images","resizeNearestNeighbor");T(n.rank===3||n.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${n.rank}.`),T(e.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${e}.`),T(n.dtype==="float32"||n.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),T(o===!1||t===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let s=n,a=!1;n.rank===3&&(a=!0,s=L(n,[1,n.shape[0],n.shape[1],n.shape[2]]));let[]=e,i={images:s},l={alignCorners:t,halfPixelCenters:o,size:e},u=E.runKernel(da,i,l);return a?L(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var gg=S({resizeNearestNeighbor_:tj});function rj(r,e,t){T(e%1==0,()=>`bandPart(): numLower must be an integer, got ${e}.`),T(t%1==0,()=>`bandPart(): numUpper must be an integer, got ${t}.`);let o=k(r,"a","bandPart");T(o.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${o.rank}.`);let n=o.shape,[s,a]=o.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(Zc(0,s,1,"int32"),[-1,1]),l=Zc(0,a,1,"int32"),u=ue(i,l),c=fr(Oo(u,le(+e,"int32")),to(u,le(-t,"int32"))),p=gt([s,a],o.dtype);return L(Bt(ur(L(o,[-1,s,a])).map(m=>Dt(c,m,p))),n)}var p0=S({bandPart_:rj});function oj(r){let e;if(Array.isArray(r)){e=!1,T(r!=null&&r.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let n=r[0].shape[0];for(let s=1;s<r.length;++s)T(r[s].shape[0]===n,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${r[s].shape[0]} vs. ${n})`)}else e=!0,r=lr(r,r.shape[0],0).map(n=>wo(n,[0]));T(r.length<=r[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${r.length}) exceeds number of dimensions (${r[0].shape[0]}).`);let t=[],o=r;for(let n=0;n<r.length;++n)t.push(E.tidy(()=>{let s=o[n];if(n>0)for(let a=0;a<n;++a){let i=O(ye(O(t[a],s)),t[a]);s=ue(s,i)}return de(s,Gu(s,"euclidean"))}));return e?Bt(t,0):t}var m0=S({gramSchmidt_:oj});function nj(r,e=!1){if(T(r.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${r.rank}`),r.rank===2)return f0(r,e);{let t=r.shape.slice(0,r.shape.length-2).reduce((l,u)=>l*u),o=ur(L(r,[t,r.shape[r.shape.length-2],r.shape[r.shape.length-1]]),0),n=[],s=[];o.forEach(l=>{let[u,c]=f0(l,e);n.push(u),s.push(c)});let a=L(Bt(n,0),r.shape),i=L(Bt(s,0),r.shape);return[a,i]}}function f0(r,e=!1){return E.tidy(()=>{T(r.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${r.shape.length}D Tensor.`);let t=r.shape[0],o=r.shape[1],n=Kc(t),s=$o(r),a=Bi([[1]],[1,1]),i=$o(a),l=t>=o?o:t;for(let u=0;u<l;++u){let c=s,p=i,m=n;[i,s,n]=E.tidy(()=>{let f=Fe(s,[u,u],[t-u,1]),d=Gu(f),h=Fe(s,[u,u],[1,1]),g=Dt(Qt(h,0),Bi([[-1]]),Bi([[1]])),x=ue(h,O(g,d)),b=de(f,x);b.shape[0]===1?i=$o(a):i=Je([a,Fe(b,[1,0],[b.shape[0]-1,b.shape[1]])],0);let _=je(de(We(g,x),d)),w=Fe(s,[u,0],[t-u,o]),v=O(_,i),$=Ue(i);if(u===0)s=ue(w,We(v,We($,w)));else{let M=ue(w,We(v,We($,w)));s=Je([Fe(s,[0,0],[u,o]),M],0)}let A=Ue(v),R=Fe(n,[0,u],[t,n.shape[1]-u]);if(u===0)n=ue(R,We(We(R,i),A));else{let M=ue(R,We(We(R,i),A));n=Je([Fe(n,[0,0],[t,u]),M],1)}return[i,s,n]}),Te([c,p,m])}return!e&&t>o&&(n=Fe(n,[0,0],[t,o]),s=Fe(s,[0,0],[o,o])),[n,s]})}var d0=S({qr_:nj});var Gt;(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"})(Gt||(Gt={}));function sj(r,e,t=Gt.SUM_BY_NONZERO_WEIGHTS){let o=k(r,"losses","computeWeightedLoss"),n=null;e!=null&&(n=k(e,"weights","computeWeightedLoss"));let s=n==null?o:O(o,n);if(t===Gt.NONE)return s;if(t===Gt.SUM)return ye(s);if(t===Gt.MEAN){if(n==null)return ht(s);{let a=o.size/n.size,i=de(ye(s),ye(n));return a>1?de(i,le(a)):i}}if(t===Gt.SUM_BY_NONZERO_WEIGHTS){if(n==null)return de(ye(s),le(o.size));{let a=O(n,Cr(o.shape)),i=oe(ye(Ln(a,le(0))),"float32");return de(ye(s),i)}}throw Error(`Unknown reduction: ${t}`)}var Nr=S({computeWeightedLoss_:sj});function ij(r,e,t,o=Gt.SUM_BY_NONZERO_WEIGHTS){let n=k(r,"labels","absoluteDifference"),s=k(e,"predictions","absoluteDifference"),a=null;t!=null&&(a=k(t,"weights","absoluteDifference")),Nt(n.shape,s.shape,"Error in absoluteDifference: ");let i=Tt(ue(n,s));return Nr(i,a,o)}var h0=S({absoluteDifference_:ij});function aj(r,e,t,o,n=Gt.SUM_BY_NONZERO_WEIGHTS){let s=k(r,"labels","cosineDistance"),a=k(e,"predictions","cosineDistance"),i=null;o!=null&&(i=k(o,"weights","cosineDistance")),Nt(s.shape,a.shape,"Error in cosineDistance: ");let l=le(1),u=ue(l,ye(O(s,a),t,!0));return Nr(u,i,n)}var g0=S({cosineDistance_:aj});function lj(r,e,t,o=Gt.SUM_BY_NONZERO_WEIGHTS){let n=k(r,"labels","hingeLoss"),s=k(e,"predictions","hingeLoss"),a=null;t!=null&&(a=k(t,"weights","hingeLoss")),Nt(n.shape,s.shape,"Error in hingeLoss: ");let i=le(1);n=ue(O(le(2),n),i);let l=Ir(ue(i,O(n,s)));return Nr(l,a,o)}var x0=S({hingeLoss_:lj});function uj(r,e,t,o=1,n=Gt.SUM_BY_NONZERO_WEIGHTS){let s=k(r,"labels","huberLoss"),a=k(e,"predictions","huberLoss"),i=null;t!=null&&(i=k(t,"weights","huberLoss")),Nt(s.shape,a.shape,"Error in huberLoss: ");let l=le(o),u=Tt(ue(a,s)),c=Ts(u,l),p=ue(u,c),m=Q(O(le(.5),Pe(c)),O(l,p));return Nr(m,i,n)}var y0=S({huberLoss_:uj});function cj(r,e,t,o=1e-7,n=Gt.SUM_BY_NONZERO_WEIGHTS){let s=k(r,"labels","logLoss"),a=k(e,"predictions","logLoss"),i=null;t!=null&&(i=k(t,"weights","logLoss")),Nt(s.shape,a.shape,"Error in logLoss: ");let l=le(1),u=le(o),c=je(O(s,ir(Q(a,u)))),p=O(ue(l,s),ir(Q(ue(l,a),u))),m=ue(c,p);return Nr(m,i,n)}var b0=S({logLoss_:cj});function pj(r,e,t,o=Gt.SUM_BY_NONZERO_WEIGHTS){let n=k(r,"labels","meanSquaredError"),s=k(e,"predictions","meanSquaredError"),a=null;t!=null&&(a=k(t,"weights","meanSquaredError")),Nt(n.shape,s.shape,"Error in meanSquaredError: ");let i=Bu(n,s);return Nr(i,a,o)}var _0=S({meanSquaredError_:pj});function mj(r,e){let t=k(r,"labels","sigmoidCrossEntropyWithLogits"),o=k(e,"logits","sigmoidCrossEntropyWithLogits");Nt(t.shape,o.shape,"Error in sigmoidCrossEntropyWithLogits: ");let n=Ir(o),s=O(o,t),a=Eu(Xt(je(Tt(o))));return Q(ue(n,s),a)}function fj(r,e,t,o=0,n=Gt.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")),Nt(s.shape,a.shape,"Error in sigmoidCrossEntropy: "),o>0){let u=le(o),c=le(1),p=le(.5);s=Q(O(s,ue(c,u)),O(p,u))}let l=mj(s,a);return Nr(l,i,n)}var w0=S({sigmoidCrossEntropy_:fj});function dj(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 Hr((n,s,a)=>{let l=Vm(s,[t],!0),u=ue(oe(s,"float32"),l);a([n,u]);let c=je(O(u,n));return{value:ye(c,[t]),gradFunc:(f,d)=>{let[h,g]=d,x=Mn(f.shape,[t]);return[O(L(f,x),ue(oe(h,"float32"),Xt(g))),O(L(f,x),ue(Xt(g),oe(h,"float32")))]}}})(r,e)}function hj(r,e,t,o=0,n=Gt.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")),Nt(s.shape,a.shape,"Error in softmaxCrossEntropy: "),o>0){let u=le(o),c=le(1),p=le(s.shape[1]);s=Q(O(s,ue(c,u)),de(u,p))}let l=dj(s,a);return Nr(l,i,n)}var k0=S({softmaxCrossEntropy_:hj});var gj={fft:Ra,ifft:zi,rfft:Fa,irfft:zu},xj={hammingWindow:JN,hannWindow:fg,frame:dg,stft:QN},Ds={flipLeftRight:t0,resizeNearestNeighbor:gg,resizeBilinear:hg,rotateWithOffset:r0,cropAndResize:e0,nonMaxSuppression:o0,nonMaxSuppressionAsync:i0,nonMaxSuppressionWithScore:a0,nonMaxSuppressionWithScoreAsync:l0,nonMaxSuppressionPadded:u0,nonMaxSuppressionPaddedAsync:c0},H_={bandPart:p0,gramSchmidt:m0,qr:d0},yj={absoluteDifference:h0,computeWeightedLoss:Nr,cosineDistance:g0,hingeLoss:x0,huberLoss:y0,logLoss:b0,meanSquaredError:_0,sigmoidCrossEntropy:w0,softmaxCrossEntropy:k0};var Fr=class extends tg{minimize(e,t=!1,o){let{value:n,grads:s}=this.computeGradients(e,o);if(o!=null){let a=o.map(i=>({name:i.name,tensor:s[i.name]}));this.applyGradients(a)}else this.applyGradients(s);return Te(s),t?n:(n.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return ig(e,t)}dispose(){this.iterations_!=null&&Te(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:le(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(Fr,Symbol.hasInstance,{value:r=>r.minimize!=null&&r.computeGradients!=null&&r.applyGradients!=null});var tp=class extends Fr{constructor(e,t,o=null){super();this.learningRate=e,this.rho=t,this.epsilon=o,this.accumulatedGrads=[],this.accumulatedUpdates=[],o==null&&(this.epsilon=E.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(o=>o.name):Object.keys(e)).forEach((o,n)=>{let s=E.registeredVariables[o],a=!1;this.accumulatedGrads[n]==null&&(this.accumulatedGrads[n]={originalName:`${o}/accum_grad`,variable:V(()=>Ie(s).variable(a))}),this.accumulatedUpdates[n]==null&&(this.accumulatedUpdates[n]={originalName:`${o}/accum_var`,variable:V(()=>Ie(s).variable(a))});let i=Array.isArray(e)?e[n].tensor:e[o];if(i==null)return;let l=this.accumulatedGrads[n].variable,u=this.accumulatedUpdates[n].variable;V(()=>{let c=Q(O(l,this.rho),O(Pe(i),1-this.rho)),p=O(de(xt(Q(u,this.epsilon)),xt(Q(l,this.epsilon))),i),m=Q(O(u,this.rho),O(Pe(p),1-this.rho));l.assign(c),u.assign(m);let f=Q(O(p,-this.learningRate),s);s.assign(f)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(Te(this.accumulatedGrads.map(e=>e.variable)),Te(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,o=!1;this.accumulatedGrads=e.slice(0,t).map(n=>({originalName:n.name,variable:n.tensor.variable(o)})),this.accumulatedUpdates=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.tensor.variable(o)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}};tp.className="Adadelta";eo(tp);var rp=class extends Fr{constructor(e,t=.1){super();this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(o=>o.name):Object.keys(e)).forEach((o,n)=>{let s=E.registeredVariables[o];if(this.accumulatedGrads[n]==null){let l=!1;this.accumulatedGrads[n]={originalName:`${o}/accumulator`,variable:V(()=>Na(s.shape,this.initialAccumulatorValue).variable(l))}}let a=Array.isArray(e)?e[n].tensor:e[o];if(a==null)return;let i=this.accumulatedGrads[n].variable;V(()=>{let l=Q(i,Pe(a));i.assign(l);let u=Q(O(de(a,xt(Q(l,E.backend.epsilon()))),-this.learningRate),s);s.assign(u)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&Te(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(o=>({originalName:o.name,variable:o.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}};rp.className="Adagrad";eo(rp);var op=class extends Fr{constructor(e,t,o,n=null){super();this.learningRate=e,this.beta1=t,this.beta2=o,this.epsilon=n,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],V(()=>{this.accBeta1=le(t).variable(),this.accBeta2=le(o).variable()}),n==null&&(this.epsilon=E.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(o=>o.name):Object.keys(e);V(()=>{let o=ue(1,this.accBeta1),n=ue(1,this.accBeta2);t.forEach((s,a)=>{let i=E.registeredVariables[s],l=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${s}/m`,variable:V(()=>Ie(i).variable(l))}),this.accumulatedSecondMoment[a]==null&&(this.accumulatedSecondMoment[a]={originalName:`${s}/v`,variable:V(()=>Ie(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=Q(O(c,this.beta1),O(u,1-this.beta1)),f=Q(O(p,this.beta2),O(Pe(u),1-this.beta2)),d=de(m,o),h=de(f,n);c.assign(m),p.assign(f);let g=Q(O(de(d,Q(xt(h),this.epsilon)),-this.learningRate),i);i.assign(g)}),this.accBeta1.assign(O(this.accBeta1,this.beta1)),this.accBeta2.assign(O(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&Te(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&Te(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),V(()=>{this.accBeta1.assign(Rr(this.beta1,this.iterations_+1)),this.accBeta2.assign(Rr(this.beta2,this.iterations_+1))});let t=e.length/2,o=!1;this.accumulatedFirstMoment=e.slice(0,t).map(n=>({originalName:n.name,variable:n.tensor.variable(o)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.tensor.variable(o)}))}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)}};op.className="Adam";eo(op);var np=class extends Fr{constructor(e,t,o,n=null,s=0){super();this.learningRate=e,this.beta1=t,this.beta2=o,this.epsilon=n,this.decay=s,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],V(()=>{this.iteration=le(0).variable(),this.accBeta1=le(t).variable()}),n==null&&(this.epsilon=E.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(o=>o.name):Object.keys(e);V(()=>{let o=ue(1,this.accBeta1),n=de(-this.learningRate,Q(O(this.iteration,this.decay),1));t.forEach((s,a)=>{let i=E.registeredVariables[s],l=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${s}/m`,variable:Ie(i).variable(l)}),this.accumulatedWeightedInfNorm[a]==null&&(this.accumulatedWeightedInfNorm[a]={originalName:`${s}/v`,variable:Ie(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=Q(O(c,this.beta1),O(u,1-this.beta1)),f=O(p,this.beta2),d=Tt(u),h=qr(f,d);c.assign(m),p.assign(h);let g=Q(O(de(n,o),de(m,Q(h,this.epsilon))),i);i.assign(g)}),this.iteration.assign(Q(this.iteration,1)),this.accBeta1.assign(O(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Te(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&Te(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)}};np.className="Adamax";eo(np);var ll=class extends Fr{constructor(e){super();this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(o=>o.name):Object.keys(e)).forEach((o,n)=>{let s=Array.isArray(e)?e[n].tensor:e[o];if(s==null)return;let a=E.registeredVariables[o];V(()=>{let i=Q(O(this.c,s),a);a.assign(i)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=At(le(-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)}};ll.className="SGD";eo(ll);var sp=class extends ll{constructor(e,t,o=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=o,this.accumulations=[],this.m=le(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(o=>o.name):Object.keys(e)).forEach((o,n)=>{let s=E.registeredVariables[o];if(this.accumulations[n]==null){let l=!1;this.accumulations[n]={originalName:`${o}/momentum`,variable:V(()=>Ie(s).variable(l))}}let a=this.accumulations[n].variable,i=Array.isArray(e)?e[n].tensor:e[o];i!=null&&V(()=>{let l,u=Q(O(this.m,a),i);this.useNesterov?l=Q(O(this.c,Q(i,O(u,this.m))),s):l=Q(O(this.c,u),s),a.assign(u),s.assign(l)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&Te(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(o=>({originalName:o.name,variable:o.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)}};sp.className="Momentum";eo(sp);var ip=class extends Fr{constructor(e,t=.9,o=0,n=null,s=!1){super();if(this.learningRate=e,this.decay=t,this.momentum=o,this.epsilon=n,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=s,n==null&&(this.epsilon=E.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(o=>o.name):Object.keys(e)).forEach((o,n)=>{let s=E.registeredVariables[o],a=!1;this.accumulatedMeanSquares[n]==null&&(this.accumulatedMeanSquares[n]={originalName:`${o}/rms`,variable:V(()=>Ie(s).variable(a))}),this.accumulatedMoments[n]==null&&(this.accumulatedMoments[n]={originalName:`${o}/momentum`,variable:V(()=>Ie(s).variable(a))}),this.accumulatedMeanGrads[n]==null&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${o}/mg`,variable:V(()=>Ie(s).variable(a))});let i=Array.isArray(e)?e[n].tensor:e[o];if(i==null)return;let l=this.accumulatedMeanSquares[n].variable,u=this.accumulatedMoments[n].variable;V(()=>{let c=Q(O(l,this.decay),O(Pe(i),1-this.decay));if(this.centered){let p=this.accumulatedMeanGrads[n].variable,m=Q(O(p,this.decay),O(i,1-this.decay)),f=de(O(i,this.learningRate),xt(ue(c,Q(Pe(m),this.epsilon)))),d=Q(O(u,this.momentum),f);l.assign(c),p.assign(m),u.assign(d);let h=ue(s,d);s.assign(h)}else{let p=Q(O(l,this.decay),O(Pe(i),1-this.decay)),m=Q(O(u,this.momentum),de(O(i,this.learningRate),xt(Q(p,this.epsilon))));l.assign(p),u.assign(m);let f=ue(s,m);s.assign(f)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&Te(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&Te(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&Te(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,o=!1;this.accumulatedMeanSquares=e.slice(0,t).map(n=>({originalName:n.name,variable:n.tensor.variable(o)})),this.accumulatedMoments=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.tensor.variable(o)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(n=>({originalName:n.name,variable:n.tensor.variable(o)})))}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)}};ip.className="RMSProp";eo(ip);var Oa=class{static sgd(e){return new ll(e)}static momentum(e,t,o=!1){return new sp(e,t,o)}static rmsprop(e,t=.9,o=0,n=null,s=!1){return new ip(e,t,o,n,s)}static adam(e=.001,t=.9,o=.999,n=null){return new op(e,t,o,n)}static adadelta(e=.001,t=.95,o=null){return new tp(e,t,o)}static adamax(e=.002,t=.9,o=.999,n=null,s=0){return new np(e,t,o,n,s)}static adagrad(e,t=.1){return new rp(e,t)}};var ul={sgd:Oa.sgd,momentum:Oa.momentum,adadelta:Oa.adadelta,adagrad:Oa.adagrad,rmsprop:Oa.rmsprop,adamax:Oa.adamax,adam:Oa.adam};var bj=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:r=>r())();function sf(){return new Promise(r=>bj(()=>r()))}var N={};et(N,{ERF_A1:()=>Aj,ERF_A2:()=>Dj,ERF_A3:()=>$j,ERF_A4:()=>Rj,ERF_A5:()=>Fj,ERF_P:()=>Ej,PARALLELIZE_THRESHOLD:()=>xg,SELU_SCALE:()=>K_,SELU_SCALEALPHA:()=>q_,applyActivation:()=>ju,assertAndGetBroadcastShape:()=>ze,assertAxesAreInnerMostDims:()=>CW,assertParamsConsistent:()=>_j,assignToTypedArray:()=>Gj,axesAreInnerMostDims:()=>__,calculateShapes:()=>hN,combineLocations:()=>RN,complexWithEvenIndex:()=>zj,complexWithOddIndex:()=>Bj,computeConv2DInfo:()=>wu,computeConv3DInfo:()=>DN,computeDefaultPad:()=>n_,computeDilation2DInfo:()=>XV,computeOptimalWindowSize:()=>kj,computeOutAndReduceShapes:()=>w_,computeOutShape:()=>wj,computePool2DInfo:()=>r_,computePool3DInfo:()=>YV,convertConv2DDataFormat:()=>AN,eitherStridesOrDilationsAreOne:()=>yr,expandShapeToKeepDim:()=>Mn,exponent:()=>Uj,exponents:()=>Wj,fromStringArrayToUint8:()=>Yj,fromUint8ToStringArray:()=>Xj,getAxesPermutation:()=>k_,getBroadcastDims:()=>BG,getComplexWithIndex:()=>Vj,getFusedBiasGradient:()=>Uu,getFusedDyActivation:()=>Wu,getImageCenter:()=>vj,getInnerMostAxes:()=>IW,getPermuted:()=>Ij,getReductionAxes:()=>Ct,getReshaped:()=>Cj,getReshapedPermuted:()=>Nj,getSliceBeginCoords:()=>Sj,getSliceSize:()=>Tj,getUndoAxesPermutation:()=>Bm,log:()=>Pj,mergeRealAndImagArrays:()=>Mj,prepareAndValidate:()=>dN,prepareSplitSize:()=>jj,segment_util:()=>v0,shouldFuse:()=>Hu,slice_util:()=>or,splitRealAndImagArrays:()=>Lj,tupleValuesAreOne:()=>Ro,upcastType:()=>mr,validateInput:()=>Qh,validateUpdateShape:()=>Kb,warn:()=>Oj});function _j(r,e){let t=r[0].length;r.forEach((n,s)=>{T(n.length===t,()=>`Error in concat${t}D: rank of tensors[${s}] must be the same as the rank of the rest (${t})`)}),T(e>=0&&e<t,()=>`Error in concat${t}D: axis must be between 0 and ${t-1}.`);let o=r[0];r.forEach((n,s)=>{for(let a=0;a<t;a++)T(a===e||n[a]===o[a],()=>`Error in concat${t}D: Shape of tensors[${s}] (${n}) does not match the shape of the rest (${o}) along the non-concatenated axis ${s}.`)})}function wj(r,e){let t=r[0].slice();for(let o=1;o<r.length;o++)t[e]+=r[o][e];return t}var xg=30;function kj(r){return r<=xg?r:Ac(r,Math.floor(Math.sqrt(r)))}function vj(r,e,t){let o=t*(typeof r=="number"?r:r[0]),n=e*(typeof r=="number"?r:r[1]);return[o,n]}function Cj(r,e,t,o=!0){let n=[];if(o)n=n.concat(e.slice(0)),n.push(r[0]/t),n=n.concat(r.slice(1));else{n=n.concat(r[0]);let s=e.length;for(let a=0;a<s;++a)n=n.concat([r[a+1]/e[a],e[a]]);n=n.concat(r.slice(s+1))}return n}function Ij(r,e,t=!0){let o=[];if(t){o.push(e);for(let n=e+1;n<r;++n)n<=2*e?(o.push(n),o.push(n-(e+1))):o.push(n)}else{let n=[],s=[];for(let a=1;a<r;++a)a>=e*2+1||a%2==1?s.push(a):n.push(a);o.push(...n),o.push(0),o.push(...s)}return o}function Nj(r,e,t,o=!0){let n=[];o?n.push(r[0]/t):n.push(r[0]*t);for(let s=1;s<r.length;++s)s<=e.length?o?n.push(e[s-1]*r[s]):n.push(r[s]/e[s-1]):n.push(r[s]);return n}function Sj(r,e){let t=[0];for(let o=0;o<e;++o)t.push(r[o][0]);return t}function Tj(r,e,t){let o=r.slice(0,1);for(let n=0;n<t;++n)o.push(r[n+1]-e[n][0]-e[n][1]);return o}var q_=1.7580993408473768,K_=1.0507009873554805;var Ej=.3275911,Aj=.254829592,Dj=-.284496736,$j=1.421413741,Rj=-1.453152027,Fj=1.061405429;function Oj(...r){G().getBool("IS_TEST")||console.warn(...r)}function Pj(...r){G().getBool("IS_TEST")||console.log(...r)}function Mj(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 o=0;o<t.length;o+=2)t[o]=r[o/2],t[o+1]=e[o/2];return t}function Lj(r){let e=new Float32Array(r.length/2),t=new Float32Array(r.length/2);for(let o=0;o<r.length;o+=2)e[o/2]=r[o],t[o/2]=r[o+1];return{real:e,imag:t}}function zj(r){let e=Math.ceil(r.length/4),t=new Float32Array(e),o=new Float32Array(e);for(let n=0;n<r.length;n+=4)t[Math.floor(n/4)]=r[n],o[Math.floor(n/4)]=r[n+1];return{real:t,imag:o}}function Bj(r){let e=Math.floor(r.length/4),t=new Float32Array(e),o=new Float32Array(e);for(let n=2;n<r.length;n+=4)t[Math.floor(n/4)]=r[n],o[Math.floor(n/4)]=r[n+1];return{real:t,imag:o}}function Vj(r,e){let t=r[e*2],o=r[e*2+1];return{real:t,imag:o}}function Gj(r,e,t,o){r[o*2]=e,r[o*2+1]=t}function Wj(r,e){let t=new Float32Array(r/2),o=new Float32Array(r/2);for(let n=0;n<Math.ceil(r/2);n++){let s=(e?2:-2)*Math.PI*(n/r);t[n]=Math.cos(s),o[n]=Math.sin(s)}return{real:t,imag:o}}function Uj(r,e,t){let o=(t?2:-2)*Math.PI*(r/e),n=Math.cos(o),s=Math.sin(o);return{real:n,imag:s}}function jj(r,e,t=0){let o=[];if(typeof e=="number")T(r.shape[t]%e==0,()=>"Number of splits must evenly divide the axis."),o=new Array(e).fill(r.shape[t]/e);else{let n=e.reduce((a,i)=>(i===-1&&(a+=1),a),0);T(n<=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}T(r.shape[t]===e.reduce((a,i)=>a+i),()=>"The sum of sizes must match the size of the axis dimension."),o=e}return o}var v0={};et(v0,{collectGatherOpShapeInfo:()=>Kj,computeOutShape:()=>qj,segOpComputeOptimalWindowSize:()=>Hj});function Hj(r,e){let t=!1,o;for(r<=xg?(o=r,t=!0):o=Ac(r,Math.floor(Math.sqrt(r)));!t;)o>e||o===r?t=!0:o=Ac(r,o+1);return o}function qj(r,e,t){let o=[],n=r.length;for(let s=0;s<n;s++)s!==e?o.push(r[s]):o.push(t);return o}function Kj(r,e,t,o){let n=e.shape.length,s=r.shape.length;if(o!==0&&(o<-n||o>n))throw new Error(`Expect batchDims in the range of [-${n}, ${n}], but got ${o}`);if(o<0&&(o+=n),o>s)throw new Error(`batchDims (${o}) must be less than rank(x) (
|
|
${s}).`);if(t<o)throw new Error(`batchDims (${o}) must be less than or equal to axis (${t}).`);for(let p=0;p<o;++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<o;++p)i.push(r.shape[p]),l*=r.shape[p];for(let p=o;p<t;p++)i.push(r.shape[p]),u*=r.shape[p];for(let p=o;p<n;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 Xj(r){try{return r.map(e=>Lc(e))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function Yj(r){return r.map(e=>el(e))}var Sr={};et(Sr,{nonMaxSuppressionV3Impl:()=>W_,nonMaxSuppressionV4Impl:()=>U_,nonMaxSuppressionV5Impl:()=>j_,whereImpl:()=>M_});var yg={kernelName:ss,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(r,As(oe(t,"float32"),-1))}}};var C0={kernelName:qs,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let o=Pe(oe(t,"float32")),n=xt(ue(le(1),o));return je(de(r,n))}}}};var I0={kernelName:Ks,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let o=xt(ue(Pe(oe(t,"float32")),1));return de(r,o)}}}};var N0={kernelName:xo,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=ze(t.shape,o.shape);return{a:()=>{let i=r,l=Ct(t.shape,n);return l.length>0&&(i=ye(i,l)),L(i,t.shape)},b:()=>{let i=r,l=Ct(o.shape,n);return l.length>0&&(i=ye(i,l)),L(i,o.shape)}}}};var S0={kernelName:Uo,saveAllInputs:!0,gradFunc:(r,e)=>{let t={};return e.forEach((o,n)=>{t[n]=()=>r.clone()}),t}};var T0={kernelName:jo,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>Ie(t)}}};var E0={kernelName:oa,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>Ie(t)}}};var A0={kernelName:Xs,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>de(r,xt(ue(le(1),Pe(oe(t,"float32")))))}}};var D0={kernelName:Ys,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let o=xt(Q(le(1),Pe(oe(t,"float32"))));return de(r,o)}}}};var $0={kernelName:Qs,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=ze(t.shape,o.shape);return{a:()=>{let i=Q(Pe(t),Pe(o)),l=O(r,de(o,i)),u=Ct(t.shape,n);return u.length>0&&(l=ye(l,u)),L(l,t.shape)},b:()=>{let i=Q(Pe(t),Pe(o)),l=je(O(r,de(t,i))),u=Ct(o.shape,n);return u.length>0&&(l=ye(l,u)),L(l,o.shape)}}}};var R0={kernelName:Zs,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>de(r,Q(Pe(oe(t,"float32")),1))}}};var F0={kernelName:Js,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>de(r,ue(le(1),Pe(oe(t,"float32"))))}}};function Zj(r,e,t,o,n,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]])),T(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),T(u.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`),s!=null&&T(st(n),()=>`Error in avgPool3dGrad: pad must be an integer when using, dimRoundingMode ${s} but got pad ${n}.`);let p={dy:l,input:u},m={filterSize:t,strides:o,pad:n,dimRoundingMode:s},f=E.runKernel(Ul,p,m);return c?L(f,[f.shape[1],f.shape[2],f.shape[3],f.shape[4]]):f}var O0=S({avgPool3dGrad_:Zj});var P0={kernelName:na,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{filterSize:n,strides:s,pad:a,dimRoundingMode:i}=t;return{x:()=>O0(r,o,n,s,a,i)}}};function Jj(r,e,t,o,n){let s=k(r,"dy","avgPoolGrad"),a=k(e,"input","avgPoolGrad");T(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]])),T(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),T(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:o,pad:n},m=E.runKernel(Wl,c,p);return u?L(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var M0=S({avgPoolGrad_:Jj});var L0={kernelName:Ho,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{filterSize:n,strides:s,pad:a}=t;return{x:()=>M0(r,o,n,s,a)}}};var z0={kernelName:qo,inputsToSave:["a","b"],gradFunc:(r,e,t)=>{let[o,n]=e,{transposeA:s,transposeB:a}=t;return!s&&!a?{a:()=>We(r,n,!1,!0),b:()=>We(o,r,!0,!1)}:!s&&a?{a:()=>We(r,n,!1,!1),b:()=>We(r,o,!0,!1)}:s&&!a?{a:()=>We(n,r,!1,!0),b:()=>We(o,r,!1,!1)}:{a:()=>We(n,r,!0,!0),b:()=>We(r,o,!0,!0)}}};var B0={kernelName:sa,gradFunc:(r,e,t)=>{let{blockShape:o,crops:n}=t;return{x:()=>Aa(r,o,n)}}};var V0={kernelName:bb,gradFunc:(r,e,t)=>{let o=t,n=o.inputShape,s=o.shape,a=Array.from(s);for(let l=n.length-1;l>=0;l--)if(n[l]===s[l])a[l]=1;else if(n[l]!==1)throw new Error(`broadcastTo(): [${n}] cannot be broadcast to [${s}].`);let i=[];for(let l=0;l<a.length;l++)a[l]>1&&i.push(l);return{x:()=>ye(r,i,!0)}}};var G0={kernelName:Eo,gradFunc:r=>({x:()=>r.clone()})};var W0={kernelName:ei,gradFunc:r=>({x:()=>Ie(r)})};var U0={kernelName:Ao,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{clipValueMin:n,clipValueMax:s}=t;return{x:()=>Dt(fr(to(o,n),Oo(o,s)),r,Ie(r))}}};var j0={kernelName:ia,inputsToSave:["x"],gradFunc:yg.gradFunc};var H0={kernelName:is,saveAllInputs:!0,gradFunc:(r,e,t)=>{let o=e.map(l=>l.shape),{axis:n}=t,s=Jt(n,e[0].shape)[0],a=o.map(l=>l[s]);return lr(r,a,s).map(l=>()=>l)}};var q0={kernelName:Ko,inputsToSave:["x","filter"],gradFunc:(r,e,t)=>{let[o,n]=e,{dilations:s,strides:a,pad:i,dataFormat:l}=t;return T(Ro(s),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`),{x:()=>qc(o.shape,r,n,a,i,l),filter:()=>ep(o,r,n.shape,a,i,l)}}};var K0={kernelName:Xo,inputsToSave:["dy","filter"],gradFunc:(r,e,t)=>{let[o,n]=e,{strides:s,pad:a,dataFormat:i,dimRoundingMode:l}=t;return{dy:()=>jr(r,n,s,a,i,1,l),filter:()=>ep(r,o,n.shape,s,a,i,l)}}};function Qj(r,e,t,o,n){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]])),T(s.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${s.shape}.`),T(a.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${a.shape}.`),T(t.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${t}.`),T(s.shape[4]===t[3],()=>`Error in conv3dDerFilter: depth of input ${s.shape[4]}) must match input depth in filter (${t[3]}.`),T(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:o,pad:n,filterShape:t};return E.runKernel(Kl,i,l)}var X0=S({conv3DBackpropFilter_:Qj});var Y0={kernelName:aa,inputsToSave:["x","filter"],gradFunc:(r,e,t)=>{let{dilations:o,strides:n,pad:s}=t;T(Ro(o),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${o}'`);let[a,i]=e;return{x:()=>ng(a.shape,r,i,n,s),filter:()=>X0(a,r,i.shape,n,s)}}};var Z0={kernelName:Yo,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(je(Mu(oe(t,"float32"))),r)}}};var J0={kernelName:ti,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(Lu(oe(t,"float32")),r)}}};var Q0={kernelName:Zo,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{axis:n,exclusive:s,reverse:a}=t;return{x:()=>{let i=k_([n],o.rank),l=Nu(r,n,s,!a);return i!=null&&(l=Ue(l,i)),l}}}};var eS={kernelName:Jo,inputsToSave:["x","filter"],gradFunc:(r,e,t)=>{let{dilations:o,strides:n,pad:s,dimRoundingMode:a}=t,i=o==null?[1,1]:o;T(Ro(i),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${i}'`);let[l,u]=e;return T(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),T(u.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${u.rank}.`),T(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]}.`),T(yr(n,i),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'.`),a!=null&&T(st(s),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`),{x:()=>mg(l.shape,r,u,n,s,o,a),filter:()=>pg(l,r,u.shape,n,s,o,a)}}};var tS={kernelName:la,inputsToSave:["x","filter"],gradFunc:(r,e,t)=>{let[o,n]=e,s={x:o,filter:n,dy:r},a={x:o,filter:n,dy:r};return{x:()=>E.runKernel($c,s,t),filter:()=>E.runKernel(Rc,a,t)}}};var rS={kernelName:ni,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e,o={dy:r,y:t};return{x:()=>E.runKernel(eu,o)}}};var oS={kernelName:si,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e,o=O(Xt(je(Pe(t))),2/Math.sqrt(Math.PI));return{x:()=>O(r,o)}}};var nS={kernelName:en,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(r,t)}}};var sS={kernelName:as,inputsToSave:["input"],gradFunc:(r,e)=>{let[t]=e;return{input:()=>L(r,t.shape)}}};var iS={kernelName:ai,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(r,Xt(t))}}};var aS={kernelName:tn,gradFunc:r=>({x:()=>Ie(r)})};var lS={kernelName:rn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=ze(t.shape,o.shape);return{a:()=>{let i=de(r,oe(o,"float32")),l=Ct(t.shape,n);return l.length>0?L(ye(i,l),t.shape):i},b:()=>{let i=O(r,oe(t,"float32")),l=Ct(o.shape,n);l.length>0&&(i=L(ye(i,l),o.shape));let u=Pe(o);return je(de(i,oe(u,"float32")))}}}};var uS={kernelName:on,inputsToSave:["x","mean","variance","scale"],gradFunc:(r,e,t)=>{let{varianceEpsilon:o}=t,[n,s,a,i]=e,l=i==null?le(1):i,u=Ct(s.shape,n.shape),c=[];if(s.rank===1){for(let w=0;w<n.shape.length-1;++w)c.push(n.shape[w]);c.push(1)}let p=ue(n,s),m=O(r,l),f=Ou(Q(a,le(o))),d=O(O(O(f,f),f),le(-.5));return{x:()=>s.rank===1?L(O(O(r,Fo(L(f,[1,1,1,s.shape[0]]),c)),l),n.shape):L(O(O(r,f),l),n.shape),mean:()=>{let w=O(O(f,le(-1)),m);return s.rank===1&&(w=ye(w,u)),L(w,s.shape)},variance:()=>{let w=O(O(d,p),m);return s.rank===1&&(w=ye(w,u)),L(w,s.shape)},scale:()=>{let w=O(p,f),v=O(r,w);return s.rank===1&&(v=ye(v,u)),L(v,s.shape)},offset:()=>{let w=r;return s.rank===1&&(w=ye(w,u)),L(w,s.shape)}}}};var mS={kernelName:ls,inputsToSave:["x","indices"],gradFunc:(r,e,t)=>{let[o,n]=e,{axis:s}=t,a=Jt(s,o.shape)[0];return{x:()=>{let l=o.shape,u=n.size,c=l.slice(0,a),p=c.length,m=l.slice(s,l.length).slice(1),f=m.length,d=cS(0,p),h=cS(p+1,p+1+f),g=pS([c,[u],m]),x=L(r,g),b=L(n,[u]),_=pS([[p],d,h]),w=Ue(x,_),v=tf(w,b,o.shape[a]),$=Bm(_);return v=Ue(v,$),v},indices:()=>n}}};function cS(r,e){let t=[];for(let o=r;o<e;++o)t.push(o);return t}function pS(r){let e=[];for(let t=0;t<r.length;++t)for(let o=0;o<r[t].length;++o)e.push(r[t][o]);return e}var fS={kernelName:nn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e;return{a:()=>Ie(t),b:()=>Ie(o)}}};var dS={kernelName:us,gradFunc:r=>({x:()=>oe(r,"float32")})};var hS={kernelName:pi,gradFunc:r=>({x:()=>Ie(r)})};var gS={kernelName:mi,gradFunc:r=>({x:()=>Ie(r)})};var xS={kernelName:fi,gradFunc:r=>({x:()=>Ie(r)})};var yS={kernelName:sn,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{alpha:n}=t,s=Qt(o,0);return{x:()=>Dt(s,r,O(r,n))}}};var bS={kernelName:gi,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>de(r,Q(t,1))}}};var _S={kernelName:an,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>de(r,oe(t,"float32"))}}};var wS={kernelName:_b,inputsToSave:[],outputsToSave:[!0],gradFunc:(r,e,t)=>{let[o]=e,{axis:n}=t;return{logits:()=>{let s=!0,a=Xt(o);return ue(r,O(ye(r,n,s),a))}}}};function eH(r,e,t,o=5,n=1,s=1,a=.5){let i={x:r,y:e,dy:t},l={depthRadius:o,bias:n,alpha:s,beta:a};return E.runKernel(su,i,l)}var kS=S({localResponseNormalizationBackprop_:eH});var vS={kernelName:ca,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let[o,n]=e,{depthRadius:s,bias:a,alpha:i,beta:l}=t;return{x:()=>kS(o,n,r,s,a,i,l)}}};function bg(r,e,t,o){return e.rank<t.rank&&(e=L(e,Mn(e.shape,o))),r.rank<t.rank&&(r=L(r,Mn(r.shape,o))),{x:()=>O(r,oe(_o(t,e),r.dtype))}}var X_={kernelName:ln,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let o=t,{reductionIndices:n}=o,s=e[0],a=e[1],i=Jt(n,s.shape),l=bg(r,a,s,i);return{x:()=>l.x()}}};var CS={kernelName:un,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e;return{a:()=>O(r,oe(to(t,o),"float32")),b:()=>O(r,oe(Tu(t,o),"float32"))}}};function tH(r,e,t,o,n,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]])),T(c.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`),T(p.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${p.rank}.`),T(m.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${m.rank}.`),a!=null&&T(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:o,strides:n,pad:s,dimRoundingMode:a},g=E.runKernel(au,d,h);return f?L(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var IS=S({maxPool3dGrad_:tH});var NS={kernelName:pa,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let[o,n]=e,{filterSize:s,strides:a,pad:i,dimRoundingMode:l}=t;return{x:()=>IS(r,o,n,s,a,i,l)}}};function rH(r,e,t,o,n,s,a){let i=k(r,"dy","maxPoolGrad"),l=k(e,"input","maxPoolGrad"),u=k(t,"output","maxPoolGrad");T(l.rank===i.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${i.rank})`),T(i.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${i.rank}.`),T(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),a!=null&&T(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:o,strides:n,pad:s,dimRoundingMode:a};return E.runKernel(iu,c,p)}var SS=S({maxPoolGrad_:rH});var TS={kernelName:cn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let[o,n]=e,{filterSize:s,strides:a,pad:i}=t;return{x:()=>SS(r,o,n,s,a,i)}}};var ES={kernelName:pn,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{axis:n}=t,s=Jt(n,o.shape),i=w_(o.shape,s)[1],l=ft(i);return{x:()=>{let c=o.shape.slice();s.forEach(f=>{c[f]=1});let p=L(r,c);return de(O(p,Cr(o.shape,"float32")),l)}}}};var AS={kernelName:mn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let o=t,{axis:n}=o,[s,a]=e,i=Jt(n,s.shape),l=bg(r,a,s,i);return{x:()=>l.x()}}};var DS={kernelName:fn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e;return{a:()=>O(r,oe(Oo(t,o),"float32")),b:()=>O(r,oe(Qt(t,o),"float32"))}}};var $S={kernelName:ma,inputsToSave:["x"],gradFunc:(r,e,t)=>{let o=e[0],{paddings:n}=t,s=n.map(a=>a[0]);return{x:()=>Fe(r,s,o.shape)}}};var RS={kernelName:yi,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=ze(t.shape,o.shape);return{a:()=>{let i=Ct(t.shape,n);return i.length>0?L(ye(r,i),t.shape):r},b:()=>{let i=O(r,je(Ns(de(t,o)))),l=Ct(o.shape,n);return l.length>0?L(ye(i,l),o.shape):i}}}};var FS={kernelName:dn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=ze(t.shape,o.shape);return{a:()=>{let i=O(r,oe(o,"float32")),l=Ct(t.shape,n);return l.length>0?L(ye(i,l),t.shape):i},b:()=>{let i=O(r,oe(t,"float32")),l=Ct(o.shape,n);return l.length>0?L(ye(i,l),o.shape):i}}}};var OS={kernelName:cs,gradFunc:r=>({x:()=>je(r)})};var PS={kernelName:hn,inputsToSave:["indices"],gradFunc:(r,e)=>{let t=e[0];return{indices:()=>gt(t.shape,"float32")}}};var MS={kernelName:ps,gradFunc:r=>({x:()=>Ie(r)})};var LS={kernelName:ms,saveAllInputs:!0,gradFunc:(r,e,t)=>{let{axis:o}=t;return ur(r,o).map(s=>()=>s)}};var Y_={kernelName:gn,inputsToSave:["x"],gradFunc:(r,e,t)=>{let o=e[0],{paddings:n}=t,s=n.map(a=>a[0]);return{x:()=>Fe(r,s,o.shape)}}};var zS={kernelName:xn,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(r,e)=>{let[t,o,n]=e,s=t,a=o,i=ze(s.shape,a.shape);return{a:()=>{let c=oe(a,"float32"),p=O(r,O(c,Rr(s,ue(c,le(1))))),m=Ct(s.shape,i);return m.length>0&&(p=ye(p,m)),L(p,s.shape)},b:()=>{let c=Qt(s,0),p=Dt(c,ir(s),Ie(s)),m=O(r,O(n,p)),f=Ct(a.shape,i);return f.length>0&&(m=ye(m,f)),L(m,a.shape)}}}};var BS={kernelName:yn,inputsToSave:["x","alpha"],gradFunc:(r,e)=>{let[t,o]=e,n=Qt(t,0);return{x:()=>Dt(n,r,O(r,o)),alpha:()=>{let s=Dt(n,Ie(r),O(r,t)),a=Ct(o.shape,r.shape);return a.length>0&&(s=ye(s,a)),L(s,o.shape)}}}};var VS={kernelName:Qo,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=ze(t.shape,o.shape);return{a:()=>{let i=de(r,oe(o,"float32")),l=Ct(t.shape,n);return l.length>0?L(ye(i,l),t.shape):i},b:()=>{let i=O(r,oe(t,"float32")),l=Ct(o.shape,n);l.length>0&&(i=L(ye(i,l),o.shape));let u=Pe(o);return je(de(i,oe(u,"float32")))}}}};var GS={kernelName:Ci,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>de(r,je(Pe(t)))}}};var WS={kernelName:wn,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e,o=O(Oo(t,6),As(t));return{x:()=>O(r,oe(o,"float32"))}}};var US={kernelName:bn,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(r,oe(As(t),"float32"))}}};var jS={kernelName:fs,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>L(r,t.shape)}}};var HS={kernelName:_n,inputsToSave:["images"],gradFunc:(r,e,t)=>{let[o]=e,n={dy:r,images:o};return{images:()=>E.runKernel(mu,n,t)}}};var qS={kernelName:da,inputsToSave:["images"],gradFunc:(r,e,t)=>{let[o]=e,n={dy:r,images:o};return{images:()=>E.runKernel(pu,n,t)}}};var KS={kernelName:kn,gradFunc:(r,e,t)=>{let{dims:o}=t,n=Jt(o,r.shape);return{x:()=>qt(r,n)}}};var XS={kernelName:vn,gradFunc:r=>({x:()=>Ie(r)})};var YS={kernelName:Cn,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>je(de(r,O(Rr(t,1.5),2)))}}};var ZS={kernelName:ds,inputsToSave:["condition"],gradFunc:(r,e)=>{let[t]=e;return{condition:()=>oe(Ie(t),"float32"),t:()=>O(r,oe(t,r.dtype)),e:()=>O(r,oe(Ta(t),r.dtype))}}};var JS={kernelName:Ni,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let o=Qt(t,le(0)),n=le(q_),s=le(K_),a=O(r,s),i=O(O(r,n),Xt(oe(t,"float32")));return Dt(o,a,i)}}}};var QS={kernelName:Nn,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(r,O(t,ue(le(1),t)))}}};var eT={kernelName:Ti,gradFunc:r=>({x:()=>Ie(r)})};var tT={kernelName:In,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(Ia(oe(t,"float32")),r)}}};var rT={kernelName:Si,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(Iu(oe(t,"float32")),r)}}};var oT={kernelName:hs,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{begin:n,size:s}=t,a=o.shape,[i,l]=Xb(o,n,s),u=[];for(let c=0;c<r.rank;c++)u.push([i[c],a[c]-i[c]-l[c]]);return{x:()=>$r(r,u)}}};var nT={kernelName:En,outputsToSave:[!0],gradFunc:(r,e,t)=>{let[o]=e,{dim:n}=t,s=!0,a=O(r,o);return{logits:()=>ue(a,O(ye(a,[n],s),o))}}};var sT={kernelName:Ei,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(r,Ur(t))}}};var Z_={kernelName:ha,gradFunc:(r,e,t)=>{let{blockShape:o,paddings:n}=t;return{x:()=>Ca(r,o,n)}}};var J_={kernelName:gs,gradFunc:(r,e,t)=>{let{axis:o}=t;return{x:()=>Je(r,o)}}};var iT={kernelName:Sn,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>de(r,O(xt(oe(t,"float32")),2))}}};var aT={kernelName:ga,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(r,O(oe(t,"float32"),2))}}};var lT={kernelName:An,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=le(2);return{a:()=>O(r,O(n,ue(t,o))),b:()=>O(r,O(n,ue(o,t)))}}};var uT={kernelName:Do,gradFunc:r=>({x:()=>Ie(r)})};var cT={kernelName:Dn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=ze(t.shape,o.shape);return{a:()=>{let i=r,l=Ct(t.shape,n);return l.length>0&&(i=ye(i,l)),L(i,t.shape)},b:()=>{let i=r,l=Ct(o.shape,n);return l.length>0&&(i=ye(i,l)),L(je(i),o.shape)}}}};var pT={kernelName:Tn,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,n=o.shape.slice(),{axis:s}=t;Jt(s,o.shape).forEach(u=>{n[u]=1});let i=L(r,n),l=O(i,Cr(o.shape,"float32"));return{x:()=>l}}};var mT={kernelName:Di,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>de(r,Pe(Ia(t)))}}};var fT={kernelName:$n,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(ue(le(1),Pe(t)),r)}}};var dT={kernelName:yo,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{reps:n}=t;return{x:()=>{let a=Ie(o);if(o.rank===1)for(let i=0;i<n[0];++i)a=Q(a,Fe(r,[i*o.shape[0]],[o.shape[0]]));else if(o.rank===2)for(let i=0;i<n[0];++i)for(let l=0;l<n[1];++l)a=Q(a,Fe(r,[i*o.shape[0],l*o.shape[1]],[o.shape[0],o.shape[1]]));else if(o.rank===3)for(let i=0;i<n[0];++i)for(let l=0;l<n[1];++l)for(let u=0;u<n[2];++u)a=Q(a,Fe(r,[i*o.shape[0],l*o.shape[1],u*o.shape[2]],[o.shape[0],o.shape[1],o.shape[2]]));else if(o.rank===4)for(let i=0;i<n[0];++i)for(let l=0;l<n[1];++l)for(let u=0;u<n[2];++u)for(let c=0;c<n[3];++c)a=Q(a,Fe(r,[i*o.shape[0],l*o.shape[1],u*o.shape[2],c*o.shape[3]],[o.shape[0],o.shape[1],o.shape[2],o.shape[3]]));else throw new Error(`Gradient for tile operation is not implemented for rank-${o.rank} tensors yet.`);return a}}}};var hT={kernelName:Rn,gradFunc:(r,e,t)=>{let o=t,{perm:n}=o,s=Bm(n);return{x:()=>Ue(r,s)}}};var gT={kernelName:xs,gradFunc:(r,e,t)=>{let o=t,{axis:n}=o;return{value:()=>Bt(r,n)}}};var xT={kernelName:xa,inputsToSave:["segmentIds"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>oH(r,t)}}};function oH(r,e){let t=qr(e,Ie(e)),o=Pn(r,t),n=to(e,le(0,"int32")),s=o.rank-n.rank;for(let i=0;i<s;++i)n=sr(n,i+1);n=fr(n,Cr(o.shape,"bool"));let a=Ie(o);return Dt(n,o,a)}var yT={kernelName:ys,gradFunc:r=>({x:()=>Ie(r)})};var nH=[yg,C0,I0,N0,S0,T0,E0,A0,D0,$0,R0,F0,P0,L0,z0,B0,V0,G0,W0,U0,j0,H0,K0,q0,Y0,Z0,J0,Q0,eS,tS,VS,rS,oS,nS,sS,iS,lS,aS,uS,mS,fS,dS,hS,gS,xS,yS,bS,_S,wS,vS,X_,X_,CS,NS,TS,ES,AS,DS,$S,RS,FS,OS,PS,MS,LS,Y_,Y_,zS,BS,GS,WS,US,jS,HS,qS,KS,XS,YS,ZS,JS,QS,eT,tT,rT,oT,nT,sT,Z_,Z_,J_,J_,iT,lT,aT,uT,cT,pT,mT,fT,dT,hT,gT,xT,yT];for(let r of nH)kb(r);F().prototype.abs=function(){return this.throwIfDisposed(),Tt(this)};F().prototype.acos=function(){return this.throwIfDisposed(),vm(this)};F().prototype.acosh=function(){return this.throwIfDisposed(),Cm(this)};F().prototype.add=function(r){return this.throwIfDisposed(),Q(this,r)};F().prototype.all=function(r,e){return this.throwIfDisposed(),_u(this,r,e)};F().prototype.any=function(r,e){return this.throwIfDisposed(),nl(this,r,e)};F().prototype.argMax=function(r){return this.throwIfDisposed(),sl(this,r)};F().prototype.argMin=function(r){return this.throwIfDisposed(),Im(this,r)};F().prototype.asScalar=function(){return this.throwIfDisposed(),T(this.size===1,()=>"The array must have only 1 element."),L(this,[])};F().prototype.asType=function(r){return this.throwIfDisposed(),oe(this,r)};F().prototype.as1D=function(){return this.throwIfDisposed(),L(this,[this.size])};F().prototype.as2D=function(r,e){return this.throwIfDisposed(),L(this,[r,e])};F().prototype.as3D=function(r,e,t){return this.throwIfDisposed(),L(this,[r,e,t])};F().prototype.as4D=function(r,e,t,o){return this.throwIfDisposed(),L(this,[r,e,t,o])};F().prototype.as5D=function(r,e,t,o,n){return this.throwIfDisposed(),L(this,[r,e,t,o,n])};F().prototype.asin=function(){return this.throwIfDisposed(),Nm(this)};F().prototype.asinh=function(){return this.throwIfDisposed(),Sm(this)};F().prototype.atan=function(){return this.throwIfDisposed(),Tm(this)};F().prototype.atan2=function(r){return this.throwIfDisposed(),Em(this,r)};F().prototype.atanh=function(){return this.throwIfDisposed(),Am(this)};F().prototype.avgPool=function(r,e,t,o){return this.throwIfDisposed(),va(this,r,e,t,o)};F().prototype.batchToSpaceND=function(r,e){return this.throwIfDisposed(),Ca(this,r,e)};F().prototype.batchNorm=function(r,e,t,o,n){return this.throwIfDisposed(),On(this,r,e,t,o,n)};F().prototype.broadcastTo=function(r){return this.throwIfDisposed(),il(this,r)};F().prototype.cast=function(r){return this.throwIfDisposed(),oe(this,r)};F().prototype.ceil=function(){return this.throwIfDisposed(),$m(this)};F().prototype.clipByValue=function(r,e){return this.throwIfDisposed(),nr(this,r,e)};F().prototype.concat=function(r,e){return this.throwIfDisposed(),r instanceof Ve&&(r=[r]),Je([this,...r],e)};F().prototype.conv1d=function(r,e,t,o,n,s){return this.throwIfDisposed(),vu(this,r,e,t,o,n,s)};F().prototype.conv2dTranspose=function(r,e,t,o,n){return this.throwIfDisposed(),Cu(this,r,e,t,o,n)};F().prototype.conv2d=function(r,e,t,o,n,s){return this.throwIfDisposed(),jr(this,r,e,t,o,n,s)};F().prototype.cos=function(){return this.throwIfDisposed(),Ia(this)};F().prototype.cosh=function(){return this.throwIfDisposed(),Iu(this)};F().prototype.cumsum=function(r,e,t){return this.throwIfDisposed(),Nu(this,r,e,t)};F().prototype.depthToSpace=function(r,e){return this.throwIfDisposed(),Fm(this,r,e)};F().prototype.depthwiseConv2d=function(r,e,t,o,n,s){return this.throwIfDisposed(),Cs(this,r,e,t,o,n,s)};F().prototype.dilation2d=function(r,e,t,o,n){return this.throwIfDisposed(),Om(this,r,e,t,o,n)};F().prototype.divNoNan=function(r){return this.throwIfDisposed(),Pm(this,r)};F().prototype.div=function(r){return this.throwIfDisposed(),de(this,r)};F().prototype.dot=function(r){return this.throwIfDisposed(),d_(this,r)};F().prototype.elu=function(){return this.throwIfDisposed(),Is(this)};F().prototype.equal=function(r){return this.throwIfDisposed(),_o(this,r)};F().prototype.erf=function(){return this.throwIfDisposed(),Mm(this)};F().prototype.exp=function(){return this.throwIfDisposed(),Xt(this)};F().prototype.expandDims=function(r){return this.throwIfDisposed(),sr(this,r)};F().prototype.expm1=function(){return this.throwIfDisposed(),Lm(this)};F().prototype.fft=function(){return this.throwIfDisposed(),Ra(this)};F().prototype.flatten=function(){return this.throwIfDisposed(),L(this,[this.size])};F().prototype.floor=function(){return this.throwIfDisposed(),Ns(this)};F().prototype.floorDiv=function(r){return this.throwIfDisposed(),bu(this,r)};F().prototype.gather=function(r,e){return this.throwIfDisposed(),Pn(this,r,e)};F().prototype.greaterEqual=function(r){return this.throwIfDisposed(),to(this,r)};F().prototype.greater=function(r){return this.throwIfDisposed(),Qt(this,r)};F().prototype.ifft=function(){return this.throwIfDisposed(),zi(this)};F().prototype.irfft=function(){return this.throwIfDisposed(),zu(this)};F().prototype.isFinite=function(){return this.throwIfDisposed(),h_(this)};F().prototype.isInf=function(){return this.throwIfDisposed(),g_(this)};F().prototype.isNaN=function(){return this.throwIfDisposed(),x_(this)};F().prototype.leakyRelu=function(r){return this.throwIfDisposed(),Sa(this,r)};F().prototype.lessEqual=function(r){return this.throwIfDisposed(),Oo(this,r)};F().prototype.less=function(r){return this.throwIfDisposed(),Tu(this,r)};F().prototype.localResponseNormalization=function(r,e,t,o){return this.throwIfDisposed(),zm(this,r,e,t,o)};F().prototype.logSigmoid=function(){return this.throwIfDisposed(),b_(this)};F().prototype.logSoftmax=function(r){return this.throwIfDisposed(),Au(this,r)};F().prototype.logSumExp=function(r,e){return this.throwIfDisposed(),Vm(this,r,e)};F().prototype.log=function(){return this.throwIfDisposed(),ir(this)};F().prototype.log1p=function(){return this.throwIfDisposed(),Eu(this)};F().prototype.logicalAnd=function(r){return this.throwIfDisposed(),fr(this,r)};F().prototype.logicalNot=function(){return this.throwIfDisposed(),Ta(this)};F().prototype.logicalOr=function(r){return this.throwIfDisposed(),Du(this,r)};F().prototype.logicalXor=function(r){return this.throwIfDisposed(),v_(this,r)};F().prototype.matMul=function(r,e,t){return this.throwIfDisposed(),We(this,r,e,t)};F().prototype.maxPool=function(r,e,t,o){return this.throwIfDisposed(),Ea(this,r,e,t,o)};F().prototype.max=function(r,e){return this.throwIfDisposed(),ar(this,r,e)};F().prototype.maximum=function(r){return this.throwIfDisposed(),qr(this,r)};F().prototype.mean=function(r,e){return this.throwIfDisposed(),ht(this,r,e)};F().prototype.min=function(r,e){return this.throwIfDisposed(),Li(this,r,e)};F().prototype.minimum=function(r){return this.throwIfDisposed(),Ts(this,r)};F().prototype.mirrorPad=function(r,e){return this.throwIfDisposed(),Wm(this,r,e)};F().prototype.mod=function(r){return this.throwIfDisposed(),Um(this,r)};F().prototype.mul=function(r){return this.throwIfDisposed(),O(this,r)};F().prototype.neg=function(){return this.throwIfDisposed(),je(this)};F().prototype.norm=function(r,e,t){return this.throwIfDisposed(),Gu(this,r,e,t)};F().prototype.notEqual=function(r){return this.throwIfDisposed(),Ln(this,r)};F().prototype.oneHot=function(r,e=1,t=0){return this.throwIfDisposed(),ks(this,r,e,t)};F().prototype.onesLike=function(){return this.throwIfDisposed(),er(this)};F().prototype.pad=function(r,e){return this.throwIfDisposed(),$r(this,r,e)};F().prototype.pool=function(r,e,t,o,n){return this.throwIfDisposed(),N_(this,r,e,t,o,n)};F().prototype.pow=function(r){return this.throwIfDisposed(),Rr(this,r)};F().prototype.prelu=function(r){return this.throwIfDisposed(),Da(this,r)};F().prototype.prod=function(r,e){return this.throwIfDisposed(),$u(this,r,e)};F().prototype.reciprocal=function(){return this.throwIfDisposed(),Hm(this)};F().prototype.relu=function(){return this.throwIfDisposed(),Ir(this)};F().prototype.relu6=function(){return this.throwIfDisposed(),Fu(this)};F().prototype.reshapeAs=function(r){return this.throwIfDisposed(),L(this,r.shape)};F().prototype.reshape=function(r){return this.throwIfDisposed(),L(this,r)};F().prototype.resizeBilinear=function(r,e,t){return this.throwIfDisposed(),hg(this,r,e,t)};F().prototype.resizeNearestNeighbor=function(r,e,t){return this.throwIfDisposed(),gg(this,r,e,t)};F().prototype.reverse=function(r){return this.throwIfDisposed(),qt(this,r)};F().prototype.rfft=function(){return this.throwIfDisposed(),Fa(this)};F().prototype.round=function(){return this.throwIfDisposed(),qm(this)};F().prototype.rsqrt=function(){return this.throwIfDisposed(),Ou(this)};F().prototype.selu=function(){return this.throwIfDisposed(),Pu(this)};F().prototype.separableConv2d=function(r,e,t,o,n,s){return this.throwIfDisposed(),Km(this,r,e,t,o,n,s)};F().prototype.sigmoid=function(){return this.throwIfDisposed(),Ur(this)};F().prototype.sign=function(){return this.throwIfDisposed(),Xm(this)};F().prototype.sin=function(){return this.throwIfDisposed(),Mu(this)};F().prototype.sinh=function(){return this.throwIfDisposed(),Lu(this)};F().prototype.slice=function(r,e){return this.throwIfDisposed(),Fe(this,r,e)};F().prototype.softmax=function(r){return this.throwIfDisposed(),$a(this,r)};F().prototype.softplus=function(){return this.throwIfDisposed(),Ss(this)};F().prototype.spaceToBatchND=function(r,e){return this.throwIfDisposed(),Aa(this,r,e)};F().prototype.split=function(r,e){return this.throwIfDisposed(),lr(this,r,e)};F().prototype.sqrt=function(){return this.throwIfDisposed(),xt(this)};F().prototype.square=function(){return this.throwIfDisposed(),Pe(this)};F().prototype.squaredDifference=function(r){return this.throwIfDisposed(),Bu(this,r)};F().prototype.squeeze=function(r){return this.throwIfDisposed(),wo(this,r)};F().prototype.stack=function(r,e){this.throwIfDisposed();let t=r instanceof Ve?[this,r]:[this,...r];return Bt(t,e)};F().prototype.step=function(r){return this.throwIfDisposed(),As(this,r)};F().prototype.stridedSlice=function(r,e,t,o,n,s,a,i){return this.throwIfDisposed(),Jm(this,r,e,t,o,n,s,a,i)};F().prototype.sub=function(r){return this.throwIfDisposed(),ue(this,r)};F().prototype.sum=function(r,e){return this.throwIfDisposed(),ye(this,r,e)};F().prototype.tan=function(){return this.throwIfDisposed(),Qm(this)};F().prototype.tanh=function(){return this.throwIfDisposed(),Mi(this)};F().prototype.tile=function(r){return this.throwIfDisposed(),Fo(this,r)};F().prototype.toBool=function(){return this.throwIfDisposed(),oe(this,"bool")};F().prototype.toFloat=function(){return this.throwIfDisposed(),oe(this,"float32")};F().prototype.toInt=function(){return this.throwIfDisposed(),oe(this,"int32")};F().prototype.topk=function(r,e){return this.throwIfDisposed(),ef(this,r,e)};F().prototype.transpose=function(r){return this.throwIfDisposed(),Ue(this,r)};F().prototype.unique=function(r){return this.throwIfDisposed(),Qc(this,r)};F().prototype.unsortedSegmentSum=function(r,e){return this.throwIfDisposed(),tf(this,r,e)};F().prototype.unstack=function(r){return this.throwIfDisposed(),ur(this,r)};F().prototype.where=function(r,e){return this.throwIfDisposed(),Dt(r,this,e)};F().prototype.zerosLike=function(){return this.throwIfDisposed(),Ie(this)};var nw={};et(nw,{maxNorm:()=>iH,minMaxNorm:()=>uH,nonNeg:()=>lH,unitNorm:()=>aH});var Q_;function Yt(){return Q_==null&&(Q_=e_().epsilon()),Q_}function Kr(){return"channelsLast"}var ko=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,ko.prototype)}},Or=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Or.prototype)}},B=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,B.prototype)}},Ne=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Ne.prototype)}},af=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,af.prototype)}},ew=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,ew.prototype)}};function Vn(r,e){if(Array.isArray(r)){let t=[];for(let o=0;o<e;o++)t=t.concat(r);return t}else{let t=new Array(e);return t.fill(r),t}}function Po(r,e){if(!r)throw new af(e)}function tw(r,e){let t=0;for(let o of r)o===e&&t++;return t}function dr(r){return r.length===1?r[0]:r}function yt(r){return Array.isArray(r)?r:[r]}function Gn(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 Pa(r){return r.length<=1||r.indexOf("_")===-1?r:r.replace(/[_]+(\w|$)/g,(e,t)=>t.toUpperCase())}var Wn={};function ap(r){if(r==null)return null;let e={};return e.className=r.getClassName(),e.config=r.getConfig(),e}function rw(r){if(!(r==null||typeof r!="object"))if(Array.isArray(r))r.forEach(e=>rw(e));else{let e=Object.keys(r);for(let t of e){let o=r[t];o!=null&&typeof o=="object"&&(!Array.isArray(o)&&o.type==="ndarray"&&typeof o.value=="number"?r[t]=o.value:rw(o))}}}function Vi(r,e={},t={},o="object",n=!1){if(typeof r=="string"){let s=r,a;if(s in t)a=t[s];else if(s in Wn)a=Wn[s];else if(a=e[s],a==null)throw new B(`Unknown ${o}: ${r}. This may be due to one of the following reasons:
|
|
1. The ${o} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
|
|
2. The custom ${o} 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 B(`${o}: 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 Wn?[i,l]=Wn.className:a in e&&([i,l]=e[a]),i==null)throw new B(`Unknown ${o}: ${a}. This may be due to one of the following reasons:
|
|
1. The ${o} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
|
|
2. The custom ${o} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(l!=null){let u={};for(let f of Object.keys(Wn))u[f]=Wn[f];for(let f of Object.keys(t))u[f]=t[f];let c=s.config;c.customObjects=u;let p=Object.assign({},Wn);for(let f of Object.keys(t))Wn[f]=t[f];rw(s.config);let m=l(i,s.config,t,n);return Wn=Object.assign({},p),m}else{let u=Object.assign({},Wn);for(let p of Object.keys(t))Wn[p]=t[p];let c=new i(s.config);return Wn=Object.assign({},u),c}}}function sH(r,e){return r<e?-1:r>e?1:0}function lf(r,e){return-1*sH(r,e)}function Un(r){if(r==null)return r;let e=[];for(let t of r)e.indexOf(t)===-1&&e.push(t);return e}function bT(r){if(r==null)throw new B(`Invalid value in obj: ${JSON.stringify(r)}`);for(let e in r)if(r.hasOwnProperty(e))return!1;return!0}function Gi(r,e,t){if(t!=null&&r.indexOf(t)<0)throw new B(`${t} is not a valid ${e}. Valid values are ${r} or null/undefined.`)}function _g(r,e,t=0,o=Infinity){return Po(t>=0),Po(o>=t),Array.isArray(r)&&r.length>=t&&r.length<=o&&r.every(n=>typeof n===e)}function Wt(r,e){Array.isArray(r)?(y.assert(r.length>0,()=>`${e} is unexpectedly an empty array.`),r.forEach((t,o)=>Wt(t,`element ${o+1} of ${e}`))):y.assert(Number.isInteger(r)&&r>0,()=>`Expected ${e} to be a positive integer, but got ${_T(r)}.`)}function _T(r){return r===null?"null":Array.isArray(r)?"["+r.map(e=>_T(e)).join(",")+"]":typeof r=="string"?`"${r}"`:`${r}`}function wT(r,e){let t=y.now(),o;return(...s)=>{let a=y.now();return a-t<e||(t=a,o=r(...s)),o}}function wg(r){return r==="relu"?"relu":r==="linear"?"linear":r==="elu"?"elu":null}function ow(r,e){return V(()=>xt(ye(O(r,r),e,!0)))}var lp=class extends J.Serializable{getConfig(){return{}}},uf=class extends lp{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 V(()=>{let t=ow(e,this.axis),o=nr(t,0,this.maxValue);return O(e,de(o,Q(Yt(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};uf.className="MaxNorm";J.registerClass(uf);var cf=class extends lp{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return V(()=>de(e,Q(Yt(),ow(e,this.axis))))}getConfig(){return{axis:this.axis}}};cf.className="UnitNorm";J.registerClass(cf);var pf=class extends lp{apply(e){return Ir(e)}};pf.className="NonNeg";J.registerClass(pf);var mf=class extends lp{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 V(()=>{let t=ow(e,this.axis),o=Q(O(this.rate,nr(t,this.minValue,this.maxValue)),O(1-this.rate,t));return O(e,de(o,Q(Yt(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};mf.className="MinMaxNorm";J.registerClass(mf);var kT={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Ot(r){return ap(r)}function vT(r,e={}){return Vi(r,J.SerializationMap.getMap().classNameMap,e,"constraint")}function Pt(r){if(r==null)return null;if(typeof r=="string"){let t={className:r in kT?kT[r]:r,config:{}};return vT(t)}else return r instanceof lp?r:vT(r)}function iH(r){return new uf(r)}function aH(r){return new cf(r)}function lH(){return new pf}function uH(r){return new mf(r)}var uw={};et(uw,{constant:()=>xH,glorotNormal:()=>CH,glorotUniform:()=>vH,heNormal:()=>IH,heUniform:()=>NH,identity:()=>wH,leCunNormal:()=>SH,leCunUniform:()=>TH,ones:()=>gH,orthogonal:()=>EH,randomNormal:()=>bH,randomUniform:()=>yH,truncatedNormal:()=>_H,varianceScaling:()=>kH,zeros:()=>hH});var CT=["channelsFirst","channelsLast"],IT=["nearest","bilinear"],NT=["valid","same","causal"],ST=["max","avg"],TT=["sum","mul","concat","ave"];var up=new Map;function $t(r){Gi(CT,"DataFormat",r)}function ET(r){Gi(IT,"InterpolationFormat",r)}function Xr(r){Gi(NT,"PaddingMode",r)}function sw(r){Gi(ST,"PoolMode",r)}var ff=[],AT="/";function $s(r,e){ff.push(r);try{let t=e();return ff.pop(),t}catch(t){throw ff.pop(),t}}function cH(){return ff.length===0?"":ff.join(AT)+AT}function kg(r){if(!DT(r))throw new Error("Not a valid tensor name: '"+r+"'");return cH()+r}function vg(r){if(!DT(r))throw new Error("Not a valid tensor name: '"+r+"'");up.has(r)||up.set(r,0);let e=up.get(r);if(up.set(r,up.get(r)+1),e>0){let t=`${r}_${e}`;return up.set(t,1),t}else return r}var pH=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function DT(r){return!!r.match(pH)}function $T(r){return r===parseInt(r.toString(),10)}function jn(r,e,t){e==null&&(e=0),t==null&&(t=r.length);let o=1;for(let n=e;n<t;++n)o*=r[n];return o}function RT(r){return r=Array.isArray(r)?new Float32Array(r):r,Vt(r)}function qu(r){return Li(RT(r)).dataSync()[0]}function Rs(r){return ar(RT(r)).dataSync()[0]}function Pr(r,e){if(e<r)throw new B(`end (${e}) < begin (${r}) is forbidden.`);let t=[];for(let o=r;o<e;++o)t.push(o);return t}function Ma(r,e){return r.asType(e)}function La(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 FT(r,e){return V(()=>{if(r.shape.length!==2)throw new B(`repeat() expects a rank-2 tensor, but received a rank-${r.shape.length} tensor.`);let t=La(r,1);return Cg(t,[1,e,1])})}function OT(r){let e=[jn(r.shape)];return r.reshape(e)}function PT(r){if(r.rank<=1)throw new B(`batchFlatten requires a minimum rank of 2. Got rank: ${r.rank}.`);let e=[r.shape[0],jn(r.shape,1)];return r.reshape(e)}function za(r,e,t){return V(()=>{switch(r.rank){case 1:return Ym(r,e,t);case 2:return cg(r,[e,0],[t,r.shape[1]]);case 3:return Zm(r,[e,0,0],[t,r.shape[1],r.shape[2]]);case 4:return Jc(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 B(`sliceAlongFirstAxis() received an unsupported tensor rank: ${r.rank}`)}})}function iw(r,e,t){return V(()=>{switch(r.rank){case 1:return Ym(r,e,t);case 2:return cg(r,[0,e],[r.shape[0],t]);case 3:return Zm(r,[0,0,e],[r.shape[0],r.shape[1],t]);case 4:return Jc(r,[0,0,0,e],[r.shape[0],r.shape[1],r.shape[2],t]);default:throw new B(`sliceAlongLastAxis() received an unsupported tensor rank: ${r.rank}`)}})}function df(r,e,t,o){return V(()=>{switch(r.rank){case 1:return Ym(r,e,t);case 2:switch(o){case 1:return za(r,e,t);case 2:return iw(r,e,t);default:throw new B(`The axis is not within the rank of the tensor ${o}`)}case 3:switch(o){case 1:return za(r,e,t);case 2:return Zm(r,[0,e,0],[r.shape[0],t,r.shape[2]]);case 3:return iw(r,e,t);default:throw new B(`The axis is not within the rank of the tensor ${o}`)}case 4:switch(o){case 1:return za(r,e,t);case 2:return Jc(r,[0,e,0,0],[r.shape[0],t,r.shape[2],r.shape[3]]);case 3:return Jc(r,[0,0,e,0],[r.shape[0],r.shape[1],t,r.shape[3]]);case 4:return iw(r,e,t);default:throw new B(`The axis is not within the rank of the tensor ${o}`)}default:throw new B(`sliceAlongLastAxis() received an unsupported tensor rank: ${r.rank}`)}})}function cp(r,e=-1){let t;return e<0&&(t=r[0].rank,t!==0?e=t:e=0),e===r[0].rank&&(e=-1),Je(r,e)}function aw(r,e){switch(r.rank){case 1:return u_([r,e]);case 2:return c_([r,e],0);case 3:return p_([r,e],0);case 4:return m_([r,e],0);default:throw new B(`concatAlongFirstAxis() received an unsupported tensor rank: ${r.rank}`)}}function Cg(r,e){if(Array.isArray(e)||(e=[e]),r.rank!==e.length)throw new B(`The length of input n (${e.length}) does not match the number of dimensions in input x (${r.rank})`);return Fo(r,e)}function pp(r,e=0,t=1,o,n){return ug(r,e,t,o,n)}function Hn(r,e,t,o){if(r.rank<2||e.rank<2)throw new Ne(`dot requires both inputs to be rank >= 2 but got x shape = ${r.shape} and y shape = ${e.shape}`);if(e.rank>=3){let n=r.shape.slice(-1)[0],s=e.shape.slice(-2)[0];if(n!==s)throw new Ne(`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 n=!1,s=!1;return zn.matMul({a:r,b:e,transposeA:n,transposeB:s,bias:o?lw(r.rank,o,Kr()):null,activation:t})}else{let n=r.shape.slice(),s=n.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=[...n,...u],m=!1,f=!1;return zn.matMul({a:r,b:e,transposeA:m,transposeB:f,bias:o?lw(r.rank,o,Kr()):null,activation:t}).reshape(p)}}function Ig(r,e,t){return V(()=>(Array.isArray(e)?e=Vt(e,"int32"):e=e.toInt(),Pn(r,e,t)))}function Ku(r){return O(r,r)}function lw(r,e,t){let o=e.shape;if(e.rank!==1&&e.rank!==r)throw new B(`Unexpected bias dimensions: ${e.rank}; expected it to be 1 or ${r}`);if(r===5){if(t==="channelsFirst")return o.length===1?e.reshape([1,o[0],1,1,1]):e.reshape([1,o[3],o[0],o[1],o[2]]);if(t==="channelsLast")return o.length===1?e.reshape([1,1,1,1,o[0]]):e.reshape([1].concat(o))}else if(r===4){if(t==="channelsFirst")return o.length===1?e.reshape([1,o[0],1,1]):e.reshape([1,o[2],o[0],o[1]]);if(t==="channelsLast")return o.length===1?e.reshape([1,1,1,o[0]]):e.reshape([1].concat(o))}else if(r===3){if(t==="channelsFirst")return o.length===1?e.reshape([1,o[0],1]):e.reshape([1,o[1],o[0]]);if(t==="channelsLast")return o.length===1?e.reshape([1,1,o[0]]):e.reshape([1].concat(o))}else if(r<3)return e;throw new B(`Unsupported input rank by biasAdd: ${e.rank}`)}function ro(r,e,t){return V(()=>(t==null&&(t=Kr()),$t(t),r.add(lw(r.rank,e,t))))}function MT(r,e=1){if(e!==1)throw new Ne(`Support for alpha values other than 1 (${e}) is not implemented yet.`);return Is(r)}function LT(r){return V(()=>de(r,Tt(r).add(1)))}function Ng(r,e,t,o){return V(()=>B_(r,e,t,o))}function zT(r){return V(()=>{let e=Q(.5,O(.2,r));return nr(e,0,1)})}function cl(r,e,t=!1){return t?r():e()}var BT=["fanIn","fanOut","fanAvg"],VT=["normal","uniform","truncatedNormal"];function mH(r){Gi(BT,"FanMode",r)}function fH(r){Gi(VT,"Distribution",r)}var oo=class extends J.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},hf=class extends oo{apply(e,t){return gt(e,t)}};hf.className="Zeros";J.registerClass(hf);var Xu=class extends oo{apply(e,t){return Cr(e,t)}};Xu.className="Ones";J.registerClass(Xu);var gf=class extends oo{constructor(e){super();if(typeof e!="object")throw new B(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new B(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return V(()=>O(le(this.value),Cr(e,t)))}getConfig(){return{value:this.value}}};gf.className="Constant";J.registerClass(gf);var xf=class extends oo{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 Es(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}};xf.className="RandomUniform";J.registerClass(xf);var yf=class extends oo{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 Ne(`randomNormal does not support dType ${t}.`);return pp(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};yf.className="RandomNormal";J.registerClass(yf);var bf=class extends oo{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 Ne(`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}}};bf.className="TruncatedNormal";J.registerClass(bf);var _f=class extends oo{constructor(e){super();this.gain=e.gain!=null?e.gain:1}apply(e,t){return V(()=>{if(e.length!==2||e[0]!==e[1])throw new B("Identity matrix initializer can only be used for 2D square matrices.");return O(this.gain,Kc(e[0]))})}getConfig(){return{gain:this.gain}}};_f.className="Identity";J.registerClass(_f);function dH(r,e="channelsLast"){let t,o;if($t(e),r.length===2)t=r[0],o=r[1];else if([3,4,5].indexOf(r.length)!==-1){if(e==="channelsFirst"){let n=jn(r,2);t=r[1]*n,o=r[0]*n}else if(e==="channelsLast"){let n=jn(r,0,r.length-2);t=r[r.length-2]*n,o=r[r.length-1]*n}}else{let n=jn(r);t=Math.sqrt(n),o=Math.sqrt(n)}return[t,o]}var Mr=class extends oo{constructor(e){super();if(e.scale<0)throw new B(`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,mH(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,fH(this.distribution),this.seed=e.seed}apply(e,t){let o=dH(e),n=o[0],s=o[1],a=this.scale;if(this.mode==="fanIn"?a/=Math.max(1,n):this.mode==="fanOut"?a/=Math.max(1,s):a/=Math.max(1,(n+s)/2),this.distribution==="normal"){let i=Math.sqrt(a);if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Ne(`${this.getClassName()} does not support dType ${t}.`);return Vu(e,0,i,t,this.seed)}else{let i=Math.sqrt(3*a);return Es(e,-i,i,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};Mr.className="VarianceScaling";J.registerClass(Mr);var mp=class extends Mr{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Mr.className}};mp.className="GlorotUniform";J.registerClass(mp);var fp=class extends Mr{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Mr.className}};fp.className="GlorotNormal";J.registerClass(fp);var dp=class extends Mr{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Mr.className}};dp.className="HeNormal";J.registerClass(dp);var hp=class extends Mr{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Mr.className}};hp.className="HeUniform";J.registerClass(hp);var gp=class extends Mr{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Mr.className}};gp.className="LeCunNormal";J.registerClass(gp);var xp=class extends Mr{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Mr.className}};xp.className="LeCunNormal";J.registerClass(xp);var wf=class extends oo{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 Ne("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return V(()=>{if(e.length<2)throw new Ne("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 o=e[0]>e[1]?[e[1],e[0]]:e,n=pp(o,0,1,"float32"),s=H_.gramSchmidt(n);return e[0]>e[1]&&(s=s.transpose()),O(this.gain,s)})}getConfig(){return{gain:this.gain,seed:this.seed}}};wf.className="Orthogonal";J.registerClass(wf);var GT={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 WT(r,e={}){return Vi(r,J.SerializationMap.getMap().classNameMap,e,"initializer")}function It(r){return ap(r)}function dt(r){if(typeof r=="string"){let e=r in GT?GT[r]:r;if(e==="GlorotNormal")return new fp;if(e==="GlorotUniform")return new mp;if(e==="HeNormal")return new dp;if(e==="HeUniform")return new hp;if(e==="LeCunNormal")return new gp;if(e==="LeCunUniform")return new xp;{let t={};return t.className=e,t.config={},WT(t)}}else return r instanceof oo?r:WT(r)}function hH(){return new hf}function gH(){return new Xu}function xH(r){return new gf(r)}function yH(r){return new xf(r)}function bH(r){return new yf(r)}function _H(r){return new bf(r)}function wH(r){return new _f(r)}function kH(r){return new Mr(r)}function vH(r){return new mp(r)}function CH(r){return new fp(r)}function IH(r){return new dp(r)}function NH(r){return new hp(r)}function SH(r){return new gp(r)}function TH(r){return new xp(r)}function EH(r){return new wf(r)}var jw={};et(jw,{Layer:()=>Me,RNN:()=>ao,RNNCell:()=>bl,activation:()=>qq,add:()=>rK,alphaDropout:()=>zK,average:()=>oK,averagePooling1d:()=>Hw,averagePooling2d:()=>qw,averagePooling3d:()=>Kw,avgPool1d:()=>mK,avgPool2d:()=>dK,avgPool3d:()=>gK,avgPooling1d:()=>fK,avgPooling2d:()=>hK,avgPooling3d:()=>xK,batchNormalization:()=>uK,bidirectional:()=>DK,concatenate:()=>nK,conv1d:()=>zq,conv2d:()=>Bq,conv2dTranspose:()=>Vq,conv3d:()=>Gq,convLstm2d:()=>SK,convLstm2dCell:()=>TK,cropping2D:()=>Uq,dense:()=>Kq,depthwiseConv2d:()=>Hq,dot:()=>lK,dropout:()=>Xq,elu:()=>Rq,embedding:()=>tK,flatten:()=>Zq,gaussianDropout:()=>LK,gaussianNoise:()=>MK,globalAveragePooling1d:()=>yK,globalAveragePooling2d:()=>bK,globalMaxPool1d:()=>RK,globalMaxPool2d:()=>FK,globalMaxPooling1d:()=>C1,globalMaxPooling2d:()=>I1,gru:()=>wK,gruCell:()=>kK,input:()=>Kg,inputLayer:()=>$q,layerNormalization:()=>cK,leakyReLU:()=>Oq,lstm:()=>vK,lstmCell:()=>CK,masking:()=>BK,maxPool1d:()=>OK,maxPool2d:()=>PK,maxPooling1d:()=>N1,maxPooling2d:()=>S1,maxPooling3d:()=>_K,maximum:()=>sK,minimum:()=>iK,multiply:()=>aK,permute:()=>eK,prelu:()=>Pq,reLU:()=>Fq,repeatVector:()=>Jq,reshape:()=>Qq,rnn:()=>EK,separableConv2d:()=>Wq,simpleRNN:()=>IK,simpleRNNCell:()=>NK,softmax:()=>Mq,spatialDropout1d:()=>Yq,stackedRNNCells:()=>AK,thresholdedReLU:()=>Lq,timeDistributed:()=>$K,upSampling2d:()=>jq,zeroPadding2d:()=>pK});var AH=0;function Sg(){return AH++}var Tg={};function pl(r=""){return r in Tg||(Tg[r]=0),Tg[r]+=1,r+Tg[r].toString()}function Eg(r){return Array.isArray(r)&&Array.isArray(r[0])}function yp(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 B(`Expected Tensor length to be 1; got ${r.length}`);e=r[0]}else e=r;return e}function Qe(r){if(Array.isArray(r)&&Array.isArray(r[0])){if(r.length===1)return r=r,r[0];throw new B(`Expected exactly 1 Shape; got ${r.length}`)}else return r}function bp(r){let e=0;for(let t of r)t.shape.length===0?e+=1:e+=t.shape.reduce((o,n)=>o*n);return e}var UT="Variable",kf=class{constructor(e,t="float32",o=UT,n=!0,s=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=Sg(),o=o==null?UT:o,this.originalName=kg(o),this.name=vg(this.originalName),this.trainable_=n,this.constraint=s,this.val=P_(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),DH(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 DH(r,e){if(r.shape.toString()!==e.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(r.shape)+" vs. "+JSON.stringify(e.shape))}function vf(r){return r.map(e=>e.read())}function _p(r){r.forEach(e=>{e[0].write(e[1])})}var Et=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||{}}},Lr=class{constructor(e,t,o,n,s,a,i){this.dtype=e,this.shape=t,this.sourceLayer=o,this.inputs=n,this.callArgs=s,this.outputTensorIndex=i,this.id=Sg(),a!=null&&(this.originalName=kg(a),this.name=vg(this.originalName)),this.rank=t.length}},$H=0,ml=class{constructor(e,t){this.callArgs=t,this.id=$H++,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 o of e.inboundLayers)o!=null&&o.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}}},RH=0,Me=class extends J.Serializable{constructor(e={}){super();this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=RH++,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 o=this.getClassName();t=Gn(o)+"_"+pl(o)}if(this.name=t,this.trainable_=e.trainable==null?!0:e.trainable,e.inputShape!=null||e.batchInputShape!=null){let o;if(e.batchInputShape!=null)o=e.batchInputShape;else if(e.inputShape!=null){let s=null;e.batchSize!=null&&(s=e.batchSize),o=[s].concat(e.inputShape)}this.batchInputShape=o;let n=e.dtype;n==null&&(n=e.inputDType),n==null&&(n="float32"),this.dtype=n}e.weights!=null?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(this.inboundNodes.length===0)throw new Or(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new B(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return dr(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return dr(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new ko(`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 ko(`Layer ${this.name} is not connected, no input to return.`);return dr(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new ko(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new ko(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return dr(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=yt(e),this.inputSpec==null||this.inputSpec.length===0)return;let t=yt(this.inputSpec);if(e.length!==t.length)throw new B(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let o=0;o<e.length;o++){let n=e[o],s=t[o];if(s==null)continue;let a=n.rank;if(s.ndim!=null&&a!==s.ndim)throw new B(`Input ${o} is incompatible with layer ${this.name}: expected ndim=${s.ndim}, found ndim=${a}`);if(s.maxNDim!=null&&a>s.maxNDim)throw new B(`Input ${o} is incompatible with layer ${this.name}: expected max_ndim=${s.maxNDim}, found ndim=${a}`);if(s.minNDim!=null&&a<s.minNDim)throw new B(`Input ${o} is incompatible with layer ${this.name}: expected min_ndim=${s.minNDim}, found ndim=${a}.`);if(s.dtype!=null&&n.dtype!==s.dtype)throw new B(`Input ${o} is incompatible with layer ${this.name} : expected dtype=${s.dtype}, found dtype=${n.dtype}.`);if(s.axes){let i=n.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 B(`Input ${o} 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=n.shape[i];if(l!=null&&u!=null&&l!==u)throw new B(`Input ${o} is incompatible with layer ${this.name}: expected shape=${s.shape}, found shape=${n.shape}.`)}}}call(e,t){return e}invokeCallHook(e,t){this._callHook!=null&&this._callHook(e,t)}setCallHook(e){this._callHook=e}clearCallHook(){this._callHook=null}apply(e,t){t=t||{},this.assertNotDisposed();let o=yt(e),n=!0;for(let a of o)if(!(a instanceof Lr)){n=!1;break}let s=!0;for(let a of o)if(a instanceof Lr){s=!1;break}if(n===s)throw new B("Arguments to apply() must be all SymbolicTensors or all Tensors");return $s(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);let a=[];for(let i of yt(e))a.push(i.shape);this.build(dr(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=yt(a),l=[];for(let u of i)o.indexOf(u)!==-1&&(u=u.clone()),l.push(u);if(a=dr(l),this.activityRegularizer!=null)throw new Ne("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return a}else{let a=FH(e),i=this.computeOutputShape(a),l,u=OH(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 Lr(u,c,this,yt(e),t,this.name,p)):l=new Lr(u,i,this,yt(e),t,this.name),this.addInboundNode(e,l,null,null,a,i,t),this._refCount++,this.activityRegularizer!=null)throw new Ne("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((o,n)=>{o!=null&&e[n]!=null&&e[n]!==o&&(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 ko(`The layer ${this.name} has never been called and thus has no defined output shape.`);let e=[];for(let t of this.inboundNodes){let o=JSON.stringify(t.outputShapes);e.indexOf(o)===-1&&e.push(o)}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 ko(`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 Or(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return bp(this.weights)}build(e){this.built=!0}getWeights(e=!1){return vf(e?this.trainableWeights:this.weights)}setWeights(e){V(()=>{let t=this.weights;if(t.length!==e.length)throw new B(`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 o=[],n=vf(t);for(let s=0;s<n.length;++s){let a=n[s],i=t[s],l=e[s];if(!y.arraysEqual(a.shape,l.shape))throw new B(`Layer weight shape ${a.shape} not compatible with provided weight shape ${l.shape}`);o.push([i,l])}_p(o)})}addWeight(e,t,o,n,s,a,i){if(this._addedWeightNames.indexOf(e)!==-1)throw new B(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),o==null&&(o="float32"),this.fastWeightInitDuringBuild&&(n=dt("zeros"));let l=n.apply(t,o),u=new kf(l,o,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=yt(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(o=>{if(o!=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,o,n,s,a,i=null){let l=yt(e);t=yt(t),o=yt(o),n=yt(n),s=yp(s),a=yp(a);let u=[],c=[],p=[];for(let m of l)u.push(m.sourceLayer),c.push(m.nodeIndex),p.push(m.tensorIndex);new ml({outboundLayer:this,inboundLayers:u,nodeIndices:c,tensorIndices:p,inputTensors:l,outputTensors:t,inputMasks:o,outputMasks:n,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 FH(r){r=yt(r);let e=[];for(let t of r)e.push(t.shape);return dr(e)}function OH(r){return"float32"}function cw(r,e,t){if((e==null||t!=null&&t>0)&&(e=r.sourceLayer,t=r.nodeIndex),e.inboundNodes.length===0)return[r];{let o=e.inboundNodes[t];if(o.inboundLayers.length===0)return o.inputTensors;{let n=[];for(let s=0;s<o.inboundLayers.length;s++){let a=o.inputTensors[s],i=o.inboundLayers[s],l=o.nodeIndices[s],u=cw(a,i,l);for(let c of u)n.indexOf(c)===-1&&n.push(c)}return n}}}var Wi=class extends Me{constructor(e){super({dtype:e.dtype,name:e.name!=null?e.name:pl("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 B("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 B("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(e.batchSize!=null)throw new B("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");let o=e.dtype||"float32";this.batchInputShape=t,this.dtype=o,this.inputSpec=[{shape:t}];let n=new Lr(this.dtype,this.batchInputShape,this,[],{},this.name);n.nodeIndex=0,n.tensorIndex=0,new ml({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[n],outputTensors:[n],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new B(`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}}};Wi.className="InputLayer";J.registerClass(Wi);function Ag(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 B("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 Wi({batchInputShape:e,name:r.name,dtype:t,sparse:r.sparse}).inboundNodes[0].outputTensors[0]}async function Ui(r){if(r==null)return;let e=[],t=[],o=[];for(let n in r){let s=r[n];if(typeof s!="number"){let a=s;e.push(a.data()),t.push(n),o.push(a)}}if(e.length>0){let n=await Promise.all(e);for(let s=0;s<n.length;++s)r[t[s]]=n[s][0];Te(o)}}function Dg(r){if(r!=null)for(let e in r){let t=r[e];typeof t!="number"&&t.dispose()}}var jT;(function(r){r[r.SILENT=0]="SILENT",r[r.VERBOSE=1]="VERBOSE"})(jT||(jT={}));var PH=125,fl=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){}},$g=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 o of this.callbacks)await o.onEpochBegin(e,t)}async onEpochEnd(e,t){t==null&&(t={});for(let o of this.callbacks)await o.onEpochEnd(e,t)}async onBatchBegin(e,t){t==null&&(t={});for(let o of this.callbacks)await o.onBatchBegin(e,t)}async onBatchEnd(e,t){t==null&&(t={});for(let o of this.callbacks)await o.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)}},HT=class extends fl{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){t==null&&(t={});let o=t.size==null?0:t.size;this.seen+=o;for(let n in t){let s=t[n];if(typeof s=="number")this.totals.hasOwnProperty(n)||(this.totals[n]=0),this.totals[n]=this.totals[n]+s*o;else{let a;n in this.totals?a=this.totals[n]:this.totals[n]=0;let i=V(()=>Q(this.totals[n],O(s,o)));this.totals[n]=i,a!=null&&a.dispose()}}}async onEpochEnd(e,t){if(t!=null)for(let o of this.params.metrics)this.totals[o]!=null&&(typeof this.totals[o]=="number"?t[o]=this.totals[o]/this.seen:V(()=>{let n=O(de(1,this.seen),this.totals[o]);t[o]=n,this.totals[o].dispose(),At(t[o])}))}},Rg=class extends fl{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){t==null&&(t={}),this.epoch.push(e);for(let o in t)this.history[o]==null&&(this.history[o]=[]),this.history[o].push(t[o])}async syncData(){let e=[],t=[],o=[];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),o.push(i)}}let n=await Promise.all(e);for(let s=0;s<n.length;++s)this.history[t[s]][o[s]].dispose(),this.history[t[s]][o[s]]=n[s][0]}},Fg=class extends fl{constructor(e,t){super();if(this.currentEpoch=0,this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=PH),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=wT(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,o){let n=[];this.yield!=null&&(await Ui(o),n.push(this.yield(e,t,o))),n.push(sf()),await Promise.all(n)}async onEpochBegin(e,t){this.currentEpoch=e,this.epochBegin!=null&&(await Ui(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){let o=[];this.epochEnd!=null&&(await Ui(t),o.push(this.epochEnd(e,t))),this.yieldEvery==="epoch"&&o.push(sf()),await Promise.all(o)}async onBatchBegin(e,t){this.batchBegin!=null&&(await Ui(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){let o=[];this.batchEnd!=null&&(await Ui(t),o.push(this.batchEnd(e,t))),this.yieldEvery==="batch"?o.push(sf()):y.isNumber(this.yieldEvery)&&o.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(o)}async onTrainBegin(e){this.trainBegin!=null&&(await Ui(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await Ui(e),await this.trainEnd(e))}};function Og(r,e){return r==null&&(r={}),r instanceof fl?[r]:Array.isArray(r)&&r[0]instanceof fl?r:yt(r).map(o=>new Fg(o,e))}var no=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}`),no.checkForDuplicate(t),no.constructors[e]==null&&(no.constructors[e]=[]),no.constructors[e].push(t)}static checkForDuplicate(e){for(let t in no.constructors)no.constructors[+t].forEach(n=>{if(n===e)throw new B("Duplicate callback constructor.")})}static clear(){no.constructors={}}static createCallbacks(e){let t=[];for(let o in no.constructors){let n=+o;e>=n&&t.push(...no.constructors[n])}return t.map(o=>new o)}};no.constructors={};function Pg(r,e,t,o,n,s,a,i,l){let u=new Rg,c=[new HT,...no.createCallbacks(e)];r!=null&&c.push(...r),c.push(u);let p=new $g(c);return p.setParams({epochs:t,initialEpoch:o,samples:n,steps:s,batchSize:a,verbose:e,doValidation:i,metrics:l}),{callbackList:p,history:u}}function Yr(r,e={},t=!1){return Vi(r,J.SerializationMap.getMap().classNameMap,e,"layer",t)}function Cf(r,e){return V(()=>{r.dtype!=="float32"&&(r=r.asType("float32"));let t=ye(Ku(r),e,!0),o=Na(t.shape,Yt()),n=xt(qr(t,o));return de(r,n)})}function ji(r,e){return V(()=>ht(Ku(ue(e,r)),-1))}function wp(r,e){return V(()=>ht(Tt(ue(e,r)),-1))}function dl(r,e){return V(()=>{let t=ue(r,e),o=nr(Tt(r),Yt(),Number.MAX_VALUE),n=Tt(de(t,o));return O(100,ht(n,-1))})}function MH(r,e){return V(()=>{let t=nr(e,Yt(),Number.MAX_VALUE),o=ir(Q(1,t)),n=nr(r,Yt(),Number.MAX_VALUE),s=ir(Q(1,n));return ht(Ku(ue(o,s)),-1)})}function LH(r,e){return V(()=>{let t=qr(0,ue(1,O(r,e)));return ht(Ku(t),-1)})}function zH(r,e){return V(()=>{let t=qr(0,ue(1,O(r,e)));return ht(t,-1)})}function BH(r,e){return V(()=>{let t=ye(O(r,e),-1),o=ar(O(ue(1,r),e),-1);return qr(0,Q(1,ue(o,t)))})}function VH(r,e){return V(()=>{let t=Math.log(2),o=ue(e,r),n=ue(Q(o,Ss(O(-2,o))),t);return ht(n,-1)})}function Yu(r,e,t=!1){return V(()=>{if(t)e=$a(e);else{let o=ye(e,e.shape.length-1,!0);e=de(e,o)}return e=nr(e,Yt(),1-Yt()),je(ye(O(r.toFloat(),ir(e)),e.shape.length-1))})}function kp(r,e,t=!1){return V(()=>{let o=Ns(OT(r)).toInt();e=nr(e,Yt(),1-Yt());let n=e.shape,s=ks(o,n[n.length-1]).reshape(n);return Yu(s,e,t)})}function GH(r,e){if(!y.arraysEqual(r.shape,e.shape))throw new B(`logits and labels must have the same shape, but got shapes ${JSON.stringify(r.shape)} and ${JSON.stringify(e.shape)}`);return V(()=>{let t=e.relu(),o=e.abs().neg();return t.sub(e.mul(r)).add(o.exp().log1p())})}function vp(r,e){return V(()=>{let t;return t=nr(e,Yt(),1-Yt()),t=ir(de(t,ue(1,t))),ht(GH(r,t),-1)})}function WH(r,e){return V(()=>{let t=nr(r,Yt(),1),o=nr(e,Yt(),1);return ye(O(r,ir(de(t,o))),-1)})}function UH(r,e){return V(()=>{let t=ir(Q(Yt(),e));return ht(ue(e,O(r,t)),-1)})}function If(r,e){return V(()=>{let t=Cf(r,-1),o=Cf(e,-1),n=O(t,o);return je(ye(n,-1))})}var Nf={meanSquaredError:ji,meanAbsoluteError:wp,meanAbsolutePercentageError:dl,meanSquaredLogarithmicError:MH,squaredHinge:LH,hinge:zH,categoricalHinge:BH,logcosh:VH,categoricalCrossentropy:Yu,sparseCategoricalCrossentropy:kp,binaryCrossentropy:vp,kullbackLeiblerDivergence:WH,poisson:UH,cosineProximity:If};function Mg(r){if(typeof r=="string"){if(r in Nf)return Nf[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 B(e)}else return r}function Sf(r,e){return V(()=>{let t=O(.5,er(e)),o=Ma(Qt(e,t),r.dtype);return ht(_o(r,o),-1)})}function Tf(r,e){return V(()=>Ma(_o(sl(r,-1),sl(e,-1)),"float32"))}function qT(r,e){return V(()=>fr(r.equal(1),e.equal(1)).sum().cast("float32"))}function jH(r,e){return V(()=>fr(r.equal(1),e.equal(0)).sum().cast("float32"))}function HH(r,e){return V(()=>fr(r.equal(0),e.equal(1)).sum().cast("float32"))}function pw(r,e){return V(()=>{let t=qT(r,e),o=HH(r,e),n=t.add(o);return Dt(Qt(n,0),t.div(n),0).cast("float32")})}function KT(r,e){return V(()=>{let t=qT(r,e),o=jH(r,e),n=t.add(o);return Dt(Qt(n,0),t.div(n),0).cast("float32")})}function Lg(r,e){return vp(r,e)}function zg(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)),_o(r,e).asType("float32")}var qH=ji,KH=ji,XH=wp,YH=wp,ZH=dl,JH=dl,Ef=Yu,QH=If,mw=kp,Bg={binaryAccuracy:Sf,categoricalAccuracy:Tf,precision:pw,categoricalCrossentropy:Ef,sparseCategoricalCrossentropy:mw,mse:qH,MSE:KH,mae:XH,MAE:YH,mape:ZH,MAPE:JH,cosine:QH};function XT(r){if(typeof r=="string"&&r in Bg)return Bg[r];if(typeof r!="string"&&r!=null)return r;throw new B(`Unknown metric ${r}`)}function Af(r){if(Po(r!==null,`Unknown LossOrMetricFn ${r}`),typeof r=="string")return r;{let e;for(let t of Object.keys(Nf))if(Nf[t]===r){e=t;break}if(e!==void 0)return e;for(let t of Object.keys(Bg))if(Bg[t]===r){e=t;break}return e!==void 0?e:r.name}}function YT(r){let e={Adagrad:()=>ul.adagrad(.01),Adadelta:()=>ul.adadelta(1,.95,Yt()),Adam:()=>ul.adam(.001,.9,.999,Yt()),Adamax:()=>ul.adamax(.002,.9,.999,Yt(),0),RMSProp:()=>ul.rmsprop(.001,.9,0,Yt()),SGD:()=>ul.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 B(`Unknown Optimizer ${r}`)}var ZT=1*1024*1024;function dw(r,e,t=!1){if(r==null||typeof r!="object"||Object.getPrototypeOf(r)!==Object.prototype||!fw(r))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(t){let o=JSON.stringify(r);o.length>ZT&&console.warn(`User-defined metadata of model "${e}" is too large in size (length=${o.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= ${ZT}.`)}}function fw(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"||!fw(r[t]))return!1;return!0}else if(Array.isArray(r)){for(let e of r)if(!fw(e))return!1;return!0}else return!1;else{let e=typeof r;return e==="string"||e==="number"||e==="boolean"}}function JT(r,e,t,o=console.log){let n=tq(r),s=["Layer (type)","Output shape","Param #"];n?(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(!n){s.push("Receives inputs"),a=[];for(let c in r.nodesByDepth)a.push(...r.nodesByDepth[c])}o("_".repeat(e)),Vg(s,t,o),o("=".repeat(e));let i=r.layers;for(let c=0;c<i.length;++c)n?rq(i[c],t,o):oq(i[c],t,a,o),o((c===i.length-1?"=":"_").repeat(e));r.checkTrainableWeightsConsistency();let l=eq(r),u=bp(r.nonTrainableWeights);o(`Total params: ${l+u}`),o(`Trainable params: ${l}`),o(`Non-trainable params: ${u}`),o("_".repeat(e))}function eq(r){let e;return r.collectedTrainableWeights!=null?e=bp(r.collectedTrainableWeights):e=bp(r.trainableWeights),e}function tq(r){let e=!0,t=[],o=[];for(let n in r.nodesByDepth)t.push(r.nodesByDepth[n]);for(let n of t){if(n.length>1||n.length===1&&n[0].inboundLayers.length>1){e=!1;break}o.push(...n)}if(e)for(let n of r.layers){let s=!1;for(let a of n.inboundNodes)if(o.indexOf(a)!==-1)if(s){e=!1;break}else s=!0;if(!e)break}return e}function Vg(r,e,t=console.log){let o="";for(let n=0;n<r.length;++n)n>0&&(o=o.slice(0,o.length-1)+" "),o+=r[n],o=o.slice(0,e[n]),o+=" ".repeat(e[n]-o.length);t(o)}function rq(r,e,t){let o;try{o=JSON.stringify(r.outputShape)}catch(i){o="multiple"}let n=r.name,s=r.getClassName(),a=[`${n} (${s})`,o,r.countParams().toString()];Vg(a,e,t)}function oq(r,e,t,o){let n;try{n=JSON.stringify(r.outputShape)}catch(c){n="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})`,n,r.countParams().toString(),l];Vg(u,e,o);for(let c=1;c<s.length;++c)Vg(["","","",s[c]],e,o)}function QT(r,e,t){return(r==="inboundNodes"||r==="outputLayers"||r==="inputLayers")&&e===0&&typeof t=="string"}function Zu(r,e){if(r===null)return null;if(typeof r=="string")return Pa(r);if(typeof r=="number"||typeof r=="boolean")return r;if(r instanceof Array){let t=[],o=r.length;for(let n=0;n<o;++n){let s=r[n];QT(e,n,s)?t.push(s):t.push(Zu(s,e))}return t}else{let t={};for(let o of Object.keys(r)){let n=r[o];if(o==="name"&&typeof n=="string")t[o]=n;else{let s=Pa(o);t[s]=Zu(n,s)}}return t}}function Gg(r,e){if(r==null)return null;if(typeof r=="string")return Gn(r);if(typeof r=="number"||typeof r=="boolean")return r;if(r instanceof Array){let t=[],o=r.length;for(let n=0;n<o;++n){let s=r[n];QT(e,n,s)?t.push(s):t.push(Gg(s,e))}return t}else{let t={};for(let o of Object.keys(r)){let n=r[o],s=Gn(o);(o==="name"||o==="className")&&typeof n=="string"?t[s]=n:t[s]=Gg(n,o)}return t}}var hl="3.0.0";function nq(r,e){if(r.dtype==null||r.dtype===e.dtype)return e;try{return oe(e,r.dtype)}catch(t){throw new B(`The dtype of the feed (${e.dtype}) can not be cast to the dtype of the key '${r.name}' (${r.dtype}).`)}}var Fs=class{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof Fs)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,o){if(this.id2Value[e.id]==null)this.id2Value[e.id]=nq(e,t),this.name2Id[e.name]=e.id,o!=null&&(this.id2Mask[e.id]=o);else throw new B(`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 Lr){if(this.id2Value[e.id]==null)throw new B(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}else{let t=this.name2Id[e];if(t==null)throw new B(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof Lr){if(this.id2Value[e.id]==null)throw new B(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}else{let t=this.name2Id[e];if(t==null)throw new B(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){this.id2Mask!=null&&Te(this.id2Mask)}},hw={},e1={};function Ju(r,e,t,o){let n=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);o!=null&&(o.maxNumTensors=-Infinity,o.minNumTensors=Infinity);let c=i.join(",")+"|"+e.names().join(","),p,m;if(hw[c]==null){let d=sq(a,e);p=d.sorted,m=d.recipientCounts,hw[c]=p,e1[c]=m}p=hw[c],m={},n||Object.assign(m,e1[c]);let f=new Fs(e);for(let d=0;d<p.length;++d){if(o!=null){let M=jc().numTensors;M>o.maxNumTensors&&(o.maxNumTensors=M),M<o.minNumTensors&&(o.minNumTensors=M)}let h=p[d],g=h.sourceLayer;if(g instanceof Wi)continue;let x=[],b=[],_=[],w=!1;for(let M of h.inputs){let z=f.getValue(M),W=f.getMask(M);x.push(z),b.push(W),W!=null&&(w=!0),n||(m[M.name]--,m[M.name]===0&&!e.hasKey(M)&&i.indexOf(M.name)===-1&&!z.isDisposed&&M.sourceLayer.stateful!==!0&&_.push(z))}w&&(t=t||{},t.mask=b[0]);let v=yt(g.apply(x,t)),$=null;g.supportsMasking&&($=g.computeMask(x,b));let A=iq(h),R=Array.isArray(A)?A:[A];for(let M=0;M<R.length;++M){f.hasKey(R[M])||f.add(R[M],v[M],Array.isArray($)?$[0]:$);let z=i.indexOf(R[M].name);z!==-1&&(l[z]=v[M])}n||Te(_)}return f.disposeMasks(),s?l:l[0]}function sq(r,e){y.assert(r!=null&&r.length>0,()=>"Expected at least one fetch, got none");let t=[],o={};if(r.length===1){let n=t1(r[0],e);t=n.sorted,o=n.recipientMap}else{let n=new Set;for(let s of r){let{sorted:a,recipientMap:i}=t1(s,e);for(let l of a)n.has(l.name)||(t.push(l),n.add(l.name));for(let l in i)o[l]==null&&(o[l]=new Set),i[l].forEach(u=>o[l].add(u))}}return{sorted:t,recipientCounts:aq(o)}}function aq(r){let e={};for(let t in r)e[t]=r[t].size;return e}function t1(r,e){let t=new Set,o=[],n={};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(),o.push(i),t.add(i.name),l&&a.pop();else{a.push(s.length-1);for(let u of i.inputs)n[u.name]==null&&(n[u.name]=new Set),n[u.name].add(i.name),!t.has(u.name)&&s.push(u)}}return{sorted:o,recipientMap:n}}function iq(r){let e;if(r.sourceLayer.inboundNodes.length===1)e=r.sourceLayer.output;else{let t=null;for(let o=0;o<r.sourceLayer.inboundNodes.length;++o)for(let n of r.sourceLayer.inboundNodes[o].outputTensors)if(n.id===r.id){t=o;break}e=r.sourceLayer.getOutputAt(t)}return e}var Mo=class extends Me{constructor(e){super({});if(this.containerNodes=new Set,this.name=e.name,this.name==null){let b=this.getClassName().toLowerCase();this.name=pl(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],Un(this.inputs).length!==this.inputs.length)throw new B(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(b=>b.name)}`);Un(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 _=b.sourceLayer,w=b.nodeIndex,v=b.tensorIndex;this.outputLayers.push(_),this.outputLayersNodeIndices.push(w),this.outputLayersTensorIndices.push(v)}for(let b of this.inputs){let _=b.sourceLayer,w=b.nodeIndex,v=b.tensorIndex;Po(w===0,"input layer has >1 nodes"),Po(v===0,"input layer has >1 tensors"),this.inputLayers.push(_),this.inputLayersNodeIndices.push(w),this.inputLayersTensorIndices.push(v)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let b=0;b<this.inputLayers.length;b++){let _=this.inputLayers[b];if(!(_ instanceof Wi))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${b} (0-based) originates from layer type ${_.getClassName()}.`);this.inputNames.push(_.name),this.feedInputShapes.push(_.batchInputShape),this.feedInputNames.push(_.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={},o={},n={},s={},a={},i=[],l=(b,_,w,v,$,A)=>{(v==null||$==null||A==null)&&(v=b.sourceLayer,$=b.nodeIndex,A=b.tensorIndex);let R=v.inboundNodes[$];if(w.indexOf(R)!==-1)throw new Or(`The tensor ${b.name} at layer "${v.name}" is part of a cycle.`);if(_.indexOf(R)!==-1)return;this.containerNodes.add(Mo.nodeKey(v,$)),v.id in a||(a[v.id]=Object.keys(a).length),w.indexOf(R)===-1&&w.push(R);let M=R.inboundLayers.length;for(let z=0;z<M;z++){let W=R.inputTensors[z],U=R.inboundLayers[z],q=R.nodeIndices[z],Z=R.tensorIndices[z];l(W,_,w,U,q,Z)}for(_.push(R);w.indexOf(R)>=0;)w.splice(w.indexOf(R),1);i.push(R)},u=[],c=[];for(let b of this.outputs)l(b,u,c);let p=i.slice().reverse();for(let b of p){o[b.id]=b,b.id in t||(t[b.id]=0);let _=t[b.id],w=n[b.outboundLayer.id]==null?0:n[b.outboundLayer.id];_=Math.max(_,w),n[b.outboundLayer.id]=_,s[b.outboundLayer.id]=b.outboundLayer,t[b.id]=_;for(let v=0;v<b.inboundLayers.length;v++){let $=b.inboundLayers[v],A=b.nodeIndices[v],R=$.inboundNodes[A],M=t[R.id]==null?0:t[R.id];t[R.id]=Math.max(_+1,M),o[R.id]=R}}let m={};for(let b in t){let _=t[b];_ in m||(m[_]=[]),m[_].push(o[b])}let f={};for(let b in n){let _=n[b];_ in f||(f[_]=[]),f[_].push(s[b])}let d=Object.keys(f).map(b=>parseInt(b,10)).sort(lf);this.layers=[];for(let b of d){let _=f[b];_.sort((w,v)=>{let $=a[w.id],A=a[v.id];return $<A?-1:$>A?1:0});for(let w of _)w instanceof Mo&&this.internalContainerRefs.push(w),this.layers.push(w)}this.layersByDepth=f,d=Object.keys(m).map(b=>parseInt(b,10)).sort(lf);let h=this.inputs.slice(),g=[];for(let b of d)for(let _ of m[b]){let w=_.outboundLayer;if(w!=null){for(let v of _.inputTensors)if(h.indexOf(v)===-1)throw new Or(`Graph disconnected: cannot obtain value for tensor ${v} at layer "${w.name}". The following previous layers were accessed without issue: ${g}`);for(let v of _.outputTensors)h.push(v);g.push(w.name)}}this.nodesByDepth=m;let x=this.layers.map(b=>b.name);for(let b of x){let _=x.filter(w=>w===b).length;if(_!==1)throw new Or(`The name "${b}" is used ${_} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(x))}this.outboundNodes=[],this.inboundNodes=[],new ml({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(o=>o.trainable=e)}),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new B("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 o of this.layers)t.push(...o.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){let o={},n=0;for(let a of this.layers)for(let i of a.weights){if(o[i.originalName]!=null)throw new B(`Duplicate weight name: ${i.originalName}`);o[i.originalName]=i,n++}let s=[];for(let a in e){let i=a;if(o[a]==null){let l=a.split("/");i=l.slice(0,-2).concat([l[l.length-1]]).join("/")}if(o[i]!=null)s.push([o[i],e[a]]);else if(t)throw new B(`Provided weight data has no target variable: ${a}`);delete o[i]}if(t){let a=[];for(let i in o)a.push(i);if(a.length>0)throw new B(`${a.length} of ${n} weights are not set: ${a}`)}_p(s)}updatedConfig(){let e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${hl}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){let o=Gg(this.updatedConfig());return t?JSON.stringify(o):o}call(e,t){return V(()=>{e=yt(e);let o=new Fs;for(let n=0;n<this.inputs.length;++n)o.add(this.inputs[n],e[n]);return Ju(this.outputs,o,t)})}computeMask(e,t){return V(()=>{e=yt(e);let o;return t==null?o=Vn(null,e.length):o=yt(t),this.runInternalGraph(e,o)[1]})}computeOutputShape(e){let t=yp(e);if(t.length!==this.inputLayers.length)throw new B(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);let o={};for(let i=0;i<t.length;i++){let l=this.inputLayers[i],u=t[i],c=l.name+"_0_0";o[c]=u}let n=Object.keys(this.nodesByDepth).map(i=>parseInt(i,10)).sort(lf);if(n.length>1)for(let i of n){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],_=`${g.name}_${x}_${b}`,w=o[_];p.push(w)}let m=c.computeOutputShape(dr(p)),f=yp(m),d=c.inboundNodes.indexOf(u);for(let h=0;h<f.length;h++){let g=`${c.name}_${d}_${h}`;o[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];Po(l in o),s.push(o[l])}return dr(s)}runInternalGraph(e,t){t==null&&(t=Vn(null,e.length));let o={};for(let l=0;l<this.inputs.length;++l){let u=this.inputs[l],c=e[l],p=t[l];o[u.id]=[c,p]}let n=Object.keys(this.nodesByDepth).map(l=>parseInt(l,10)).sort(lf);for(let l of n){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 o&&d.push(o[h.id]);if(d.length===m.length){let h={},g,x,b,_;if(c.callArgs!=null&&(h=c.callArgs),d.length===1){let[w,v]=d[0];h.mask==null&&(h.mask=v),b=yt(p.call(w,h)),_=yt(p.computeMask(w,v)),g=[w],x=[v]}else g=d.map(w=>w[0]),x=d.map(w=>w[1]),h.mask==null&&(h.mask=x),b=yt(p.call(g,h)),_=yt(p.computeMask(g,x));if(p.activityRegularizer)throw new Ne("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let w=0;w<f.length;++w){let v=f[w],$=b[w],A=_[w];o[v.id]=[$,A]}}}}let s=[],a=[],i=[];for(let l of this.outputs){Po(l.id in o,`Could not compute output ${l.name} : ${l.id}`);let[u,c]=o[l.id];i.push(u.shape),s.push(u),a.push(c)}return[s,a,i]}buildNodeConversionMap(e){let t={},o;for(let n of this.layers){o=n instanceof Mo?1:0;for(let s=0;s<n.inboundNodes.length;s++){let a=Mo.nodeKey(n,s);this.containerNodes.has(a)&&(t[a]=o,o+=1)}}return t}getLayer(e,t){if(t!=null){if(this.layers.length<=t)throw new B(`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 B("Provide either a layer name or layer index");for(let o of this.layers)if(o.name===e)return o;throw new B(`No such layer: ${e}`)}calculateLosses(){return V(()=>{let e=[];for(let t of this.layers)for(let o=0;o<t.inboundNodes.length;++o){let n=Mo.nodeKey(t,o);this.containerNodes.has(n)&&e.push(...t.calculateLosses())}return e})}getConfig(){let e={name:this.name},t=this.buildNodeConversionMap(this.layers),o=[];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=Mo.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],_=m.tensorIndices[g],w=Mo.nodeKey(x,b),v=t[w];v==null&&(v=0),h.push([x.name,v,_,d])}u.push(h)}}}let c={};c.name=a.name,c.className=i,c.config=l,c.inboundNodes=u,o.push(c)}e.layers=o;let n=[];for(let a=0;a<this.inputLayers.length;a++){let i=this.inputLayers[a],l=this.inputLayersNodeIndices[a],u=Mo.nodeKey(i,l);if(!this.containerNodes.has(u))continue;let c=t[u];c==null&&(c=0);let p=this.inputLayersTensorIndices[a];n.push([i.name,c,p])}e.inputLayers=n;let s=[];for(let a=0;a<this.outputLayers.length;a++){let i=this.outputLayers[a],l=this.outputLayersNodeIndices[a],u=Mo.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,o={},n=!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=[],_;for(let w of x){let v=w[0],$=w[1],A=w[2];if(_=w[3]==null?{}:w[3],!(v in s)){i(g,x);return}let R=s[v];if(R.inboundNodes.length<=$){i(g,x);return}let M=R.inboundNodes[$];b.push(M.outputTensors[A])}b.length>0&&g.apply(dr(b),_)}function u(g){let x=g.name,b=Yr(g,t.customObjects!=null?t.customObjects:{});b.setFastWeightInitDuringBuild(n),s[x]=b,g.inboundNodes.forEach(w=>{if(!(w instanceof Array))throw new B(`Corrupted configuration, expected array for nodeData: ${w}`);i(b,w)})}let c=t.name,p=t.layers;for(let g of p)u(g);for(;!bT(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 _ of b)l(x,_)}}let m=[],f=[],d=t.inputLayers;for(let g of d){let x=g[0],b=g[1],_=g[2];Po(x in s);let v=s[x].inboundNodes[b].outputTensors;m.push(v[_])}let h=t.outputLayers;for(let g of h){let x=g[0],b=g[1],_=g[2];Po(x in s);let v=s[x].inboundNodes[b].outputTensors;f.push(v[_])}return new e({inputs:m,outputs:f,name:c})}get stateful(){if(this._stateful)throw new B("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(){V(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}};function lq(r,e,t){let o=e.length;if(r==null||Array.isArray(r)&&r.length===0)return e.map(n=>null);if(o===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!==o)throw new Error(`Provided ${t} is an array of ${r.length} element(s), but the model has ${o} 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 n=[];return e.forEach(s=>{s in r?n.push(r[s]):n.push(null)}),n}else throw new Error(`The model has multiple (${o}) outputs, so ${t} must be either an array with ${o} elements or an object with ${e} keys. Provided ${t} not understood: ${JSON.stringify(r)}`)}function Wg(r,e){return lq(r,e,"classWeight")}async function Ug(r,e,t,o){if(e!=null||o!=null)throw new Error("Support sampleWeight is not implemented yet");if(t!=null){let n=V(()=>{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 n.data());Te(n);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])}),Vt(a,"float32")}else return null}function r1(r,e){return O(r,e)}var uq=32;function n1(r,e){let t,o,n=e;t=n.xs,o=n.ys,y.assert(t!=null&&o!=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=o1("input",r.inputNames,t),a=o1("output",r.outputNames,o),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 o1(r,e,t){if(t instanceof Ve)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 o=[];for(let n of e){if(t[n]==null)throw new B(`The feature data generated by the dataset lacks the required ${r} key '${n}'.`);o.push(t[n])}return o}}function cq(r){if(r.length===3)throw new Ne("Validation with sample weights is not implemented yet.");return{xs:r[0],ys:r[1]}}async function i1(r,e,t){let o=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(!o||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 n=t.validationData!=null,s,a;if(n)if(s1(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=cq(t.validationData);s=g.xs,a=g.ys}let i=r.makeTrainFunction(),l=r.getDedupedMetricsNames(),u;n?u=l.slice().concat(l.map(g=>"val_"+g)):u=l.slice();let c=Og(t.callbacks,t.yieldEvery),p=t.verbose==null?1:t.verbose,{callbackList:m,history:f}=Pg(c,p,t.epochs,null,null,pq(e,t),null,n,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(o||(h=await e.iterator());o?x<t.batchesPerEpoch:!0;){let _=await h.next();if(o&&_.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(_.value!=null){let{xs:w,ys:v}=n1(r,_.value),$={};$.batch=b,$.size=w[0].shape[0],await m.onBatchBegin(b,$);let A=[];if(t.classWeight!=null){let z=Wg(t.classWeight,r.outputNames);for(let W=0;W<z.length;++W)A.push(await Ug(v[W],null,z[W]))}let R=w.concat(v).concat(A),M=i(R);Te(R);for(let z=0;z<l.length;++z){let W=l[z],U=M[z];$[W]=U,At(U)}await m.onBatchEnd(b,$),Dg($),b++,x++}if(o?x>=t.batchesPerEpoch:_.done){if(n){let w;s1(t.validationData)?w=yt(await r.evaluateDataset(t.validationData,{batches:t.validationBatches})):w=yt(r.evaluate(s,a,{batchSize:t.validationBatchSize==null?uq:t.validationBatchSize,verbose:0}));for(let v=0;v<r.metricsNames.length;++v)g[`val_${r.metricsNames[v]}`]=w[v]}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 pq(r,e){let t=null;return e.batchesPerEpoch!=null?t=e.batchesPerEpoch:Number.isFinite(r.size)&&(t=r.size),t}function s1(r){return typeof r.iterator=="function"}function mq(r){return typeof r.next=="function"}async function a1(r,e,t){t=t||{};let o=t.batches!=null,n=r.testFunction,s=[];if(t.verbose>0)throw new Ne("Verbose mode is not implemented yet.");y.assert(!o||t.batches>0&&Number.isInteger(t.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(t.batches)}`);let a=mq(e)?e:await e.iterator(),i=0,l=0;for(;o?l<t.batches:!0;){let u=await a.next();if(s=V(()=>{if(u.value){let{xs:c,ys:p}=n1(r,u.value),m=c.concat(p),f=V(()=>n(m));if(Te(m),l===0)for(let h=0;h<f.length;++h)s.push(le(0));let d=m[0].shape[0];for(let h=0;h<f.length;++h){let g=f[h],x=s[h];s[h]=V(()=>Q(s[h],O(d,g))),l>0&&Te(x)}Te(f),i+=d,++l}return s}),u.done){o&&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]=de(s[u],i),Te(c)}return dr(s)}function jg(r){y.assert(r>0&&Number.isInteger(r),()=>`batchSize is required to be a positive integer, but got ${r}`)}function Cp(r,e,t){return r==null?[null]:Array.isArray(r)?r.map(o=>za(o,e,t-e)):za(r,e,t-e)}function Hg(r,e){return V(()=>r==null?null:Array.isArray(r)?r.map(t=>Hg(t,e)):Ig(r,e.dtype==="int32"?e:e.toInt()))}function qg(r,e){let t=[],o=0,n=null;for(;o<r;)n=o+e,n>=r&&(n=r),t.push([o,n]),o=n;return t}async function fq(r,e,t,o,n,s,a,i,l,u,c,p,m,f,d){n==null&&(n=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 B("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");let g=r.checkNumSamples(t,n,f,"steps_per_epoch"),x;g!=null&&(x=Pr(0,g)),a==null&&(a=1);let{callbackList:b,history:_}=Pg(i,a,s,m,g,f,n,h,p);b.setModel(r),r.history=_,await b.onTrainBegin(),r.stopTraining_=!1;for(let w=m;w<s;++w){await b.onEpochBegin(w);let v={};if(f!=null)throw new Ne("stepsPerEpoch mode is not implemented yet.");{if(c==="batch")throw new Ne("batch shuffling is not implemneted yet");c&&y.shuffle(x);let $=Vt(x),A=qg(g,n);for(let R=0;R<A.length;++R){let M={};if(await b.onBatchBegin(R,M),V(()=>{let z=A[R][0],W=A[R][1],U=za($,z,W-z);M.batch=R,M.size=W-z;let q=Hg(t,U),Z=e(q);for(let X=0;X<o.length;++X){let Y=o[X],te=Z[X];M[Y]=te,At(te)}if(R===A.length-1&&h){let X=r.testLoop(l,u,n);for(let Y=0;Y<o.length;++Y){let te=o[Y],K=X[Y];At(K),v["val_"+te]=K}}}),await b.onBatchEnd(R,M),Dg(M),r.stopTraining_)break}$.dispose()}if(await b.onEpochEnd(w,v),r.stopTraining_)break}return await b.onTrainEnd(),await r.history.syncData(),r.history}async function l1(r,e,t,o={}){if(r.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");r.isTraining=!0;let n,s,a,i,l,u,c;try{let p=o.batchSize==null?32:o.batchSize;jg(p);let m=!1,f=await r.standardizeUserData(e,t,o.sampleWeight,o.classWeight,m,p);n=f[0],s=f[1],c=f[2];let d=!1,h;if(o.validationData!=null&&o.validationData.length>0){if(d=!0,o.validationData.length===2)a=o.validationData[0],i=o.validationData[1];else throw o.validationData.length===3?new Ne("validationData including sample weights is not supported yet."):new B(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${o.validationData} is invalid.`);let A=!0,R=await r.standardizeUserData(a,i,null,null,A,p);l=R[0],u=R[1],h=l.concat(u)}else if(o.validationSplit!=null&&o.validationSplit>0&&o.validationSplit<1){d=!0;let A=Math.floor(n[0].shape[0]*(1-o.validationSplit)),R=n[0].shape[0];l=Cp(n,A,R),n=Cp(n,0,A),u=Cp(s,A,R),s=Cp(s,0,A),h=l.concat(u)}else o.validationSteps!=null&&(d=!0);let g=n.concat(s).concat(c);r.checkTrainableWeightsConsistency();let x=r.makeTrainFunction(),b=r.getDedupedMetricsNames(),_,w;d?(r.makeTestFunction(),_=r.testFunction,w=b.slice().concat(b.map(A=>"val_"+A))):(_=null,h=[],w=b.slice());let v=Og(o.callbacks,o.yieldEvery);return await fq(r,x,g,b,p,o.epochs,o.verbose,v,_,h,o.shuffle,w,o.initialEpoch,null,null)}finally{r.isTraining=!1,gl(n,e),gl(s,t),gl(l,a),gl(u,i),c!=null&&Te(c)}}function gw(r){let e=[];r instanceof Ve&&(r=[r]);for(let t=0;t<r.length;++t){let o=r[t];if(o.rank===1)e.push(La(o,1));else{if(o.rank===0)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");e.push(o)}}return e}function gl(r,e){if(r==null)return;let t=[];if(e instanceof Ve)t.push(e.id);else if(Array.isArray(e))e.forEach(n=>t.push(n.id));else if(e!=null)for(let n in e){let s=e[n];t.push(s.id)}let o=[];if(r instanceof Ve)t.indexOf(r.id)===-1&&o.push(r);else if(Array.isArray(r))r.forEach(n=>{t.indexOf(n.id)===-1&&o.push(n)});else if(r!=null)for(let n in r){let s=r[n];t.indexOf(s.id)===-1&&o.push(s)}o.forEach(n=>{n.isDisposed||n.dispose()})}function dq(r){return r instanceof Ve}function xw(r){return Array.isArray(r)}function u1(r){return!dq(r)&&!xw(r)}function c1(r,e,t,o=!0,n=""){if(e==null||e.length===0){if(r!=null){let a=!1;if(xw(r)&&r.length>0)a=!0;else if(u1(r)){for(let i in r)if(r.hasOwnProperty(i)){a=!0;break}}else a=!0;if(a)throw new B(`Error when checking model ${n} expected no data, but got ${r}`)}return[]}if(r==null)return e.map(a=>null);let s;if(u1(r)){r=r,s=[];for(let a of e){if(r[a]==null)throw new B(`No data provided for "${a}". Need data for each key in: ${e}`);s.push(r[a])}}else if(xw(r)){if(r=r,r.length!==e.length)throw new B(`Error when checking model ${n}: 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 B(`The model ${n} expects ${e.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${r.shape}`);s=[r]}if(s=gw(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 B(`Error when checking ${n}: 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&&!o)continue;let u=i.shape[l],c=t[a][l];if(c!=null&&c>=0&&u!==c)throw new B(`Error when checking ${n}: expected ${e[a]} to have shape [${t[a]}], but got array with shape [${i.shape}].`)}}return s}function hq(r,e,t){let o=Un(r.map(s=>s.shape[0]));o.sort();let n=Un(e.map(s=>s.shape[0]));if(n.sort(),o.length>1)throw new B(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(r.map(s=>s.shape))}`);if(n.length>1)throw new B(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(s=>s.shape))}`);if(o.length>0&&n.length>0&&!y.arraysEqual(o,n))throw new B(`Input Tensors should have the same number of samples as target Tensors. Found ${o[0]} input sample(s) and ${n[0]} target sample(s).`)}function gq(r,e,t){let o=[ji,vp,Yu];for(let n=0;n<r.length;++n){let s=r[n],a=e[n],i=t[n];if(a!=null){if(a===Yu&&s.shape[s.shape.length-1]===1)throw new B(`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(o.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 B(`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 p1(r,e,t,o=!0,n=""){let s;if(Array.isArray(r)){if(r.length!==e.length)throw new B(`Error when checking model ${n}: 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 B(`The model expects ${e.length} ${n} 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 B(`Error when checking ${n}: 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&&!o)continue;let u=i.shape[l],c=t[a][l];if(c!=null&&c!==u)throw new B(`Error when checking ${n}: expected ${e[a]} to have shape ${JSON.stringify(t[a])} but got array with shape ${JSON.stringify(i.shape)}.`)}}}function xq(r,e){if(r==null||Array.isArray(r)&&r.length===0)return e.map(o=>[]);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(o=>t);{let o=[];for(let n of e){let s=t.hasOwnProperty(n)?t[n]:[];Array.isArray(s)||(s=[s]),o.push(s)}return o}}var yq="layers-model",vo=class extends Mo{constructor(e){super(e);this.isTraining=!1}summary(e,t,o=console.log){if(!this.built)throw new B("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).");JT(this,e,t,o)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=YT(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Fr))throw new B("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 B(`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(Mg(e.loss[a]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new B(`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=>Mg(i))}else{let a=Mg(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 o=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],$s("loss",()=>{for(let a=0;a<this.outputs.length;++a){if(o.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 n=xq(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])};$s("metric",()=>{for(let a=0;a<this.outputs.length;++a){if(o.indexOf(a)!==-1)continue;let i=n[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]===vp?["accuracy","acc"].indexOf(d)!==-1?m=Sf:["crossentropy","ce"].indexOf(d)!==-1&&(m=Lg):this.lossFunctions[a]===kp?["accuracy","acc"].indexOf(d)!==-1?m=zg:["crossentropy","ce"].indexOf(d)!==-1&&(m=mw):["accuracy","acc"].indexOf(d)!==-1?m=Tf:["crossentropy","ce"].indexOf(d)!==-1&&(m=Ef);let x;["accuracy","acc"].indexOf(d)!==-1?x="acc":["crossentropy","ce"].indexOf(d)!==-1&&(x="ce"),f=m,p=c+x}else f=XT(d),p=c+Af(d);let h;$s(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,o={}){let n=o.batchSize==null?32:o.batchSize;jg(n);let s=!0,a=this.standardizeUserDataXY(e,t,s,n);try{let i=a[0].concat(a[1]);this.makeTestFunction();let l=this.testFunction,u=this.testLoop(l,i,n,o.verbose,o.steps);return dr(u)}finally{gl(a[0],e),gl(a[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),a1(this,e,t)}checkNumSamples(e,t,o,n="steps"){let s;if(o!=null){if(s=null,t!=null)throw new B(`If ${n} 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 B(`Either the input data should have a defined shape, or ${n} shoud be specified.`);return s}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new B("`outputs` is an empty Array, which is not allowed.");let o=Array.isArray(t),n=o?t:[t],s=this.retrieveSymbolicTensors(n),a=new Fs;if(e instanceof Ve&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new B(`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 B(`No value is provided for the model's input ${l.name}`);a.add(l,u)}let i=Ju(s,a);return o?i:i[0]}retrieveSymbolicTensors(e){let t=Vn(null,e.length),o=e.length;for(let n of this.layers){let s=Array.isArray(n.output)?n.output:[n.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],o--),o===0)break}if(o===0)break}if(o>0){let n=[];throw t.forEach((s,a)=>{s==null&&n.push(e[a])}),new B(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(n)}`)}return t}predictLoop(e,t=32,o=!1){return V(()=>{let n=this.checkNumSamples(e);if(o)throw new Ne("Verbose predictLoop() is not implemented yet.");let s=qg(n,t),a=this.outputs.map(i=>[]);for(let i=0;i<s.length;++i)V(()=>{let u=s[i][0],c=s[i][1],p=Cp(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 Fs(m);return Ju(this.outputs,f)}).forEach((u,c)=>a[c].push(u));return dr(a.map(i=>Je(i,0)))})}predict(e,t={}){let o=gw(e);p1(o,this.inputNames,this.feedInputShapes,!1);try{let n=t.batchSize==null?32:t.batchSize;return jg(n),this.predictLoop(o,n)}finally{gl(o,e)}}predictOnBatch(e){p1(e,this.inputNames,this.feedInputShapes,!0);let t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,o=!0,n){if(this.optimizer_==null)throw new Or("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]===kp?s.push(i.slice(0,i.length-1).concat([1])):s.push(i)}if(e=c1(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=c1(t,this.feedOutputNames,s,!1,"target"),hq(e,t,null),gq(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&n!=null&&n>0&&e[0].shape[0]%n!=0)throw new B(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${n}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,o,n,s=!0,a){let[i,l]=this.standardizeUserDataXY(e,t,s,a);if(o!=null)throw new Error("sample weight is not supported yet.");let u=null;if(n!=null){let c=Wg(n,this.outputNames);u=[];for(let p=0;p<c.length;++p)u.push(await Ug(l[p],null,c[p]))}return[i,l,u]}testLoop(e,t,o,n=0,s){return V(()=>{let a=this.checkNumSamples(t,o,s,"steps"),i=[];if(n>0)throw new Ne("Verbose mode is not implemented yet.");if(s!=null)throw new Ne("steps mode in testLoop() is not implemented yet");{let l=qg(a,o),u=Vt(Pr(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=Hg(t,f),h=e(d);if(c===0)for(let g=0;g<h.length;++g)i.push(le(0));for(let g=0;g<h.length;++g){let x=h[g];i[g]=Q(i[g],O(m-p,x))}}for(let c=0;c<i.length;++c)i[c]=de(i[c],a)}return i})}getDedupedMetricsNames(){let e=this.metricsNames,t=[];for(let o=0;o<e.length;++o){let n=e[o],s=n;tw(e,n)>1&&(s+=`_${tw(e.slice(0,o),n)}`),t.push(s)}return t}makeTrainFunction(){return e=>{let t=[],o=e.slice(0,this.inputs.length),n=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:o[h]});let m=new Fs(p),f=Ju(this.outputs,m,{training:!0}),d;for(let h=0;h<this.lossFunctions.length;++h){let x=this.lossFunctions[h](n[h],f[h]);s[h]!=null&&(x=r1(x,s[h]));let b=ht(x);t.push(b),h===0?d=x:d=Q(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(n[b],f[b]))}At(g),a.push(g)}return d=ht(d),this.calculateLosses().forEach(h=>{d=Q(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=>V(()=>{let t=[],o,n=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:n[u]});let i=new Fs(a),l=Ju(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?o=p:o=Q(o,p),t.push(o)}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,o={}){return l1(this,e,t,o)}async fitDataset(e,t){return i1(this,e,t)}async trainOnBatch(e,t){let o=await this.standardizeUserData(e,t),n=o[0],s=o[1],i=this.makeTrainFunction()(n.concat(s)),l=[];for(let u of i){let c=await u.data();l.push(c[0])}return Te(i),dr(l)}getNamedWeights(e){let t=[],o=e!=null&&e.trainableOnly,n=o?this.trainableWeights:this.weights,s=this.getWeights(o);for(let a=0;a<n.length;++a)o&&!n[a].trainable||t.push({name:n[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=jc().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-jc().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=Gn(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=>Gn(t))}else{let t=Object.keys(this.loss);e={};let o=this.loss;for(let n of t)if(typeof o[n]=="string")e[n]=Gn(o[n]);else throw new Error("Serialization of non-string loss is not supported.")}return e}getMetricIdentifiers(){if(typeof this.metrics=="string"||typeof this.metrics=="function")return[Gn(Af(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>Gn(Af(e)));{let e={};for(let t in this.metrics)e[t]=Gn(Af(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=Zu(e.optimizer_config),o=Yr(t),n;if(typeof e.loss=="string")n=Pa(e.loss);else if(Array.isArray(e.loss))n=e.loss.map(a=>Pa(a));else if(e.loss!=null){n={};for(let a in e.loss)n[a]=Pa(e.loss[a])}let s;if(Array.isArray(e.metrics))s=e.metrics.map(a=>Pa(a));else if(e.metrics!=null){s={};for(let a in e.metrics)s[a]=Pa(e.metrics[a])}this.compile({loss:n,metrics:s,optimizer:o})}async save(e,t){if(typeof e=="string"){let u=vr.getSaveHandlers(e);if(u.length===0)throw new B(`Cannot find any save handlers for URL '${e}'`);if(u.length>1)throw new B(`Found more than one (${u.length}) save handlers for URL '${e}'`);e=u[0]}if(e.save==null)throw new B("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");let o=await vr.encodeWeights(this.getNamedWeights(t)),n=!1,s=null,i={modelTopology:this.toJSON(s,n),format:yq,generatedBy:`TensorFlow.js tfjs-layers v${hl}`,convertedBy:null};if((t==null?!1:t.includeOptimizer)&&this.optimizer!=null){i.trainingConfig=this.getTrainingConfig();let u="optimizer",{data:c,specs:p}=await vr.encodeWeights(await this.optimizer.getWeights(),u);o.specs.push(...p),o.data=vr.concatenateArrayBuffers([o.data,c])}if(this.userDefinedMetadata!=null){let u=!0;dw(this.userDefinedMetadata,this.name,u),i.userDefinedMetadata=this.userDefinedMetadata}return i.weightData=o.data,i.weightSpecs=o.specs,e.save(i)}setUserDefinedMetadata(e){dw(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};vo.className="Model";J.registerClass(vo);var yw=class extends vo{};yw.className="Functional";J.registerClass(yw);async function m1(r,e){"modelTopology"in r||(r={modelTopology:r}),r=r;let t=r.modelTopology;t.model_config!=null&&(t=t.model_config);let o=Zu(t),n=Yr(o,e);if(r.weightsManifest!=null){let s=await vr.loadWeights(r.weightsManifest,r.pathPrefix,n.weights.map(i=>i.originalName)),a={};for(let i of n.weights)a[i.originalName]=s[i.originalName];n.loadWeights(a),Te(s)}return n}async function f1(r,e){if(e==null&&(e={}),typeof r=="string"){let t=vr.getLoadHandlers(r,e);if(t.length===0)t.push(vr.browserHTTPRequest(r,e));else if(t.length>1)throw new B(`Found more than one (${t.length}) load handlers for URL '${r}'`);r=t[0]}return bq(r,void 0,e)}async function bq(r,e,t){if(t==null&&(t={}),r.load==null)throw new B("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let o=await r.load(),n=o.modelTopology;n.model_config!=null&&(n=n.model_config);let s=t.strict==null?!0:t.strict,a=o.weightData!=null&&o.weightSpecs!=null&&s,i=Yr(Zu(n),e,a),l=o.trainingConfig;if(l!=null&&i.loadTrainingConfig(l),o.userDefinedMetadata!=null&&i.setUserDefinedMetadata(o.userDefinedMetadata),o.weightData!=null){if(o.weightSpecs==null)throw new B("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");let{modelWeights:u,optimizerWeights:c}=_q(o.weightData,o.weightSpecs);i.loadWeights(u,s),i.optimizer!=null&&c.length>0&&await i.optimizer.setWeights(c),Te(u),Te(c.map(p=>p.tensor))}return i}function _q(r,e){let t=vr.decodeWeights(r,e),o={},n=[];return e.forEach(s=>{s.group==="optimizer"?n.push({name:s.name,tensor:t[s.name]}):o[s.name]=t[s.name]}),{modelWeights:o,optimizerWeights:n}}var Hi=class extends vo{constructor(e){super({inputs:[],outputs:[]});if(e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:pl("sequential_"),e.layers!=null)for(let t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some(o=>o<0))throw new B(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){let t=e instanceof Hi||e instanceof vo,o;if(t){if(o=e,o.outputs.length!==1)throw new B("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(o.inputs.length!==1)throw new B("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 B("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");let n=Ag({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(n)}if(t)this.outputs=o.outputs,this.inputs=o.inputs;else{if(e.inboundNodes.length!==1)throw new B(`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 B("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=cw(this.outputs[0])}this.inboundNodes=[],new ml({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Vn(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(n=>n.shape),outputShapes:this.outputs[0].shape})}else{let n=e.apply(this.outputs[0]);if(Array.isArray(n))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[n],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(this.layers.length===0)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),this.layers.length===0)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{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(Qe(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 vo({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,o=console.log){this.built||this.build(),super.summary(e,t,o)}setWeights(e){this.model==null&&this.build(),this.model.setWeights(e)}evaluate(e,t,o={}){if(!this.built)throw new Or("The model needs to be compiled before being used.");return this.model.evaluate(e,t,o)}async evaluateDataset(e,t){if(!this.built)throw new Or("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,o={}){if(!this.built)throw new Or("The model needs to be compiled before being used.");return this.model.fit(e,t,o)}async fitDataset(e,t){if(!this.built)throw new Or("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,o={},n=!1){let s,a={};if(t instanceof Array){if(t[0].className==null||t[0].className==="Merge")throw new B("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 Hi))throw new Ne(`Sequential.fromConfig called on non-Sequential input: ${i}`);for(let l of s){let c=Yr(l,void 0,n);n&&c.setFastWeightInitDuringBuild(!0),i.add(c)}return i}set stopTraining(e){if(this.model==null)throw new B("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 B("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 o={};o.className=t.getClassName(),o.config=t.getConfig(),e.push(o)}return{name:this.name,layers:e}}};Hi.className="Sequential";J.registerClass(Hi);function d1(r){return new vo(r)}function h1(r){return new Hi(r)}function g1(r,e){return e==null&&(e={}),f1(r,e)}function Kg(r){return Ag(r)}function x1(r,e){no.registerCallbackConstructor(r,e)}var so=class extends J.Serializable{getConfig(){return{}}},bw=class extends so{apply(e,t=1){return MT(e,t)}};bw.className="elu";J.registerClass(bw);var _w=class extends so{apply(e){return Pu(e)}};_w.className="selu";J.registerClass(_w);var ww=class extends so{apply(e){return Ir(e)}};ww.className="relu";J.registerClass(ww);var kw=class extends so{apply(e){return V(()=>Ts(6,Ir(e)))}};kw.className="relu6";J.registerClass(kw);var vw=class extends so{apply(e){return e}};vw.className="linear";J.registerClass(vw);var Cw=class extends so{apply(e){return Ur(e)}};Cw.className="sigmoid";J.registerClass(Cw);var Iw=class extends so{apply(e){return zT(e)}};Iw.className="hardSigmoid";J.registerClass(Iw);var Nw=class extends so{apply(e){return Ss(e)}};Nw.className="softplus";J.registerClass(Nw);var Sw=class extends so{apply(e){return LT(e)}};Sw.className="softsign";J.registerClass(Sw);var Tw=class extends so{apply(e){return Mi(e)}};Tw.className="tanh";J.registerClass(Tw);var Df=class extends so{apply(e,t=-1){return $a(e,t)}};Df.className="softmax";J.registerClass(Df);var Ew=class extends so{apply(e,t=-1){return Au(e,t)}};Ew.className="logSoftmax";J.registerClass(Ew);var Aw=class extends so{apply(e,t=1){return V(()=>Ur(e.mul(t)).mul(e))}};Aw.className="swish";J.registerClass(Aw);function Os(r){return r.getClassName()}function Dw(r,e={}){return Vi(r,J.SerializationMap.getMap().classNameMap,e,"activation")}function Ps(r){if(r==null){let e={};return e.className="linear",e.config={},Dw(e)}if(typeof r=="string"){let e={};return e.className=r,e.config={},Dw(e)}else return r instanceof so?r:Dw(r)}function $w(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 Rw=class extends J.Serializable{},Qu=class extends Rw{constructor(e){super();$w(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 V(()=>{let t=gt([1]);return this.hasL1&&(t=Q(t,ye(O(this.l1,Tt(e))))),this.hasL2&&(t=Q(t,ye(O(this.l2,Ku(e))))),t.asScalar()})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}};Qu.className="L1L2";J.registerClass(Qu);function y1(r){return $w(r),new Qu({l1:r!=null?r.l1:null,l2:0})}function b1(r){return $w(r),new Qu({l2:r!=null?r.l2:null,l1:0})}var _1={l1l2:"L1L2"};function lt(r){return ap(r)}function w1(r,e={}){return Vi(r,J.SerializationMap.getMap().classNameMap,e,"regularizer")}function bt(r){if(r==null)return null;if(typeof r=="string"){let t={className:r in _1?_1[r]:r,config:{}};return w1(t)}else return r instanceof Rw?r:w1(r)}var $f=class extends Me{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=Oe(e);let o=Ir(e);return this.maxValue!=null&&(o=nr(o,0,this.maxValue)),o}computeOutputShape(e){return e}getConfig(){let e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}};$f.className="ReLU";J.registerClass($f);var Rf=class extends Me{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 o=Oe(e);return Sa(o,this.alpha)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};Rf.className="LeakyReLU";J.registerClass(Rf);var Ff=class extends Me{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=dt(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=bt(e.alphaRegularizer),this.alphaConstraint=Pt(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 B(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=Qe(e);let t=e.slice(1);if(this.sharedAxes!=null)for(let n of this.sharedAxes)t[n-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);let o={};if(this.sharedAxes!=null)for(let n=1;n<e.length;++n)o[n]=e[n];this.inputSpec=[new Et({ndim:e.length,axes:o})],this.built=!0}call(e,t){return e=Oe(e),Da(e,this.alpha.read())}getConfig(){let e={alphaInitializer:It(this.alphaInitializer),alphaRegularizer:lt(this.alphaRegularizer),alphaConstraint:Ot(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}};Ff.className="PReLU";J.registerClass(Ff);var Of=class extends Me{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA=1,e==null&&(e={}),e.alpha!=null&&e.alpha!==this.DEFAULT_ALPHA)throw new Ne(`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 o=Oe(e);return Is(o)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};Of.className="ELU";J.registerClass(Of);var Pf=class extends Me{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 o=Oe(e);return o.mul(Ma(o.greater(this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){let e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}};Pf.className="ThresholdedReLU";J.registerClass(Pf);var Mf=class extends Me{constructor(e){super(e==null?{}:e);this.DEFAULT_AXIS=1,e==null&&(e={}),this.softmax=new Df().apply,this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis}call(e,t){let o=Oe(e);return this.softmax(o,this.axis)}computeOutputShape(e){return e}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};Mf.className="Softmax";J.registerClass(Mf);function xl(r,e,t){if(typeof r=="number")return Vn(r,e);if(r.length!==e)throw new B(`The ${t} argument must be an integer or tuple of ${e} integers. Received: ${r.length} elements.`);for(let o=0;o<e;++o){let n=r[o];if(!$T(n))throw new B(`The ${t} argument must be an integer or tuple of ${e} integers. Received: ${JSON.stringify(r)} including a non-integer number ${n}`)}return r}function io(r,e,t,o,n=1){if(r==null)return r;let s=e+(e-1)*(n-1),a;return t==="same"?a=r:a=r-s+1,Math.floor((a+o-1)/o)}function Lf(r,e,t,o){if(r==null)return null;if(o==="valid")r=r*e+Rs([t-e,0]);else if(o==="same")r=r*e;else throw new B(`Unsupport padding mode: ${o}.`);return r}function zf(r,e){return V(()=>($t(e),e==="channelsFirst"?Ue(r,[0,2,3,1]):r))}function Fw(r,e){return V(()=>($t(e),e==="channelsFirst"?Ue(r,[0,2,3,4,1]):r))}function wq(r,e,t,o=1,n="valid",s,a=1){return V(()=>{if(s==null&&(s=Kr()),$t(s),r.shape.length!==3)throw new B(`The input of a conv1dWithBias operation should be 3, but is ${r.shape.length} instead.`);if(e.shape.length!==3)throw new B(`The kernel for a conv1dWithBias operation should be 3, but is ${e.shape.length} instead`);if(t!=null&&t.shape.length!==1)throw new B(`The bias for a conv1dWithBias operation should be 1, but is ${e.shape.length} instead`);if(s==="channelsFirst"&&(r=Ue(r,[0,2,1])),n==="causal")throw new Ne("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let i=vu(r,e,o,n==="same"?"same":"valid","NWC",a);return t!=null&&(i=ro(i,t)),i})}function k1(r,e,t,o=[1,1],n="valid",s,a,i=null){return V(()=>{if(s==null&&(s=Kr()),$t(s),r.rank!==3&&r.rank!==4)throw new B(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${r.rank}.`);if(e.rank!==3&&e.rank!==4)throw new B(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${r.rank}.`);let l=zf(r,s);if(n==="causal")throw new Ne("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=zn.conv2d({x:l,filter:e,strides:o,pad:n==="same"?"same":"valid",dilations:a,dataFormat:"NHWC",bias:t,activation:i}),s==="channelsFirst"&&(l=Ue(l,[0,3,1,2])),l})}function kq(r,e,t,o=[1,1,1],n="valid",s,a){return V(()=>{if(s==null&&(s=Kr()),$t(s),r.rank!==4&&r.rank!==5)throw new B(`conv3dWithBias expects input to be of rank 4 or 5, but received ${r.rank}.`);if(e.rank!==4&&e.rank!==5)throw new B(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${r.rank}.`);let i=Fw(r,s);if(n==="causal")throw new Ne("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return i=Rm(i,e,o,n==="same"?"same":"valid","NDHWC",a),t!=null&&(i=ro(i,t)),s==="channelsFirst"&&(i=Ue(i,[0,4,1,2,3])),i})}var Ip=class extends Me{constructor(e,t){super(t);if(this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",Ip.verifyArgs(t),this.rank=e,Wt(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new Ne(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=xl(t.kernelSize,e,"kernelSize"),this.strides=xl(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,Xr(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,$t(this.dataFormat),this.activation=Ps(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=dt(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Pt(t.biasConstraint),this.biasRegularizer=bt(t.biasRegularizer),this.activityRegularizer=bt(t.activityRegularizer),this.dilationRate=xl(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new B(`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 B(`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 B(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(Po("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!_g(e.kernelSize,"number",1,3))throw new B(`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:Os(this.activation),useBias:this.useBias,biasInitializer:It(this.biasInitializer),biasRegularizer:lt(this.biasRegularizer),activityRegularizer:lt(this.activityRegularizer),biasConstraint:Ot(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}},ec=class extends Ip{constructor(e,t){super(e,t);this.kernel=null,ec.verifyArgs(t),this.filters=t.filters,Wt(this.filters,"filters"),this.kernelInitializer=dt(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Pt(t.kernelConstraint),this.kernelRegularizer=bt(t.kernelRegularizer)}build(e){e=Qe(e);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new B(`The channel dimension of the input should be defined. Found ${e[t]}`);let o=e[t],n=this.kernelSize.concat([o,this.filters]);this.kernel=this.addWeight("kernel",n,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:o}}],this.built=!0}call(e,t){return V(()=>{e=Oe(e);let o,n=this.bias==null?null:this.bias.read(),s=wg(this.activation.getClassName());if(s!=null&&this.rank===2)o=k1(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate,s);else{if(this.rank===1)o=wq(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)o=k1(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)o=kq(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new Ne("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(o=this.activation.apply(o))}return o})}computeOutputShape(e){e=Qe(e);let t=[],o=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let s=0;s<o.length;++s){let a=io(o[s],this.kernelSize[s],this.padding,this.strides[s],typeof this.dilationRate=="number"?this.dilationRate:this.dilationRate[s]);t.push(a)}let n=[e[0]];return this.dataFormat==="channelsLast"?(n=n.concat(t),n.push(this.filters)):(n.push(this.filters),n=n.concat(t)),n}getConfig(){let e={filters:this.filters,kernelInitializer:It(this.kernelInitializer),kernelRegularizer:lt(this.kernelRegularizer),kernelConstraint:Ot(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 B(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}},yl=class extends ec{constructor(e){super(2,e);yl.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!_g(e.kernelSize,"number",1,2))throw new B(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}};yl.className="Conv2D";J.registerClass(yl);var tc=class extends ec{constructor(e){super(3,e);tc.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 B(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}};tc.className="Conv3D";J.registerClass(tc);var Bf=class extends yl{constructor(e){super(e);if(this.inputSpec=[new Et({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new B(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=Qe(e),e.length!==4)throw new B("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 B("The channel dimension of the inputs should be defined. Found `None`.");let o=e[t],n=this.kernelSize.concat([this.filters,o]);this.kernel=this.addWeight("kernel",n,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Et({ndim:4,axes:{[t]:o}})],this.built=!0}call(e,t){return V(()=>{let o=Oe(e);if(o.shape.length!==4)throw new B(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${o.shape.length}`);let n=o.shape,s=n[0],a,i;this.dataFormat==="channelsFirst"?(a=2,i=3):(a=1,i=2);let l=n[a],u=n[i],c=this.kernelSize[0],p=this.kernelSize[1],m=this.strides[0],f=this.strides[1],d=Lf(l,m,c,this.padding),h=Lf(u,f,p,this.padding),g=[s,d,h,this.filters];this.dataFormat!=="channelsLast"&&(o=Ue(o,[0,2,3,1]));let x=Cu(o,this.kernel.read(),g,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(x=Ue(x,[0,3,1,2])),this.bias!=null&&(x=ro(x,this.bias.read(),this.dataFormat)),this.activation!=null&&(x=this.activation.apply(x)),x})}computeOutputShape(e){e=Qe(e);let t=e.slice(),o,n,s;this.dataFormat==="channelsFirst"?(o=1,n=2,s=3):(o=3,n=1,s=2);let a=this.kernelSize[0],i=this.kernelSize[1],l=this.strides[0],u=this.strides[1];return t[o]=this.filters,t[n]=Lf(t[n],l,a,this.padding),t[s]=Lf(t[s],u,i,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};Bf.className="Conv2DTranspose";J.registerClass(Bf);var Ow=class extends ec{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 B("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new B("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 B(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=t.depthMultiplier==null?1:t.depthMultiplier,this.depthwiseInitializer=dt(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=bt(t.depthwiseRegularizer),this.depthwiseConstraint=Pt(t.depthwiseConstraint),this.pointwiseInitializer=dt(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=bt(t.pointwiseRegularizer),this.pointwiseConstraint=Pt(t.pointwiseConstraint)}build(e){if(e=Qe(e),e.length<this.rank+2)throw new B(`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 B(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);let o=e[t],n=this.kernelSize.concat([o,this.depthMultiplier]),s=[];for(let i=0;i<this.rank;++i)s.push(1);s.push(o*this.depthMultiplier,this.filters);let a=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",n,"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 Et({ndim:this.rank+2,axes:{[t]:o}})],this.built=!0}call(e,t){return V(()=>{e=Oe(e);let o;if(this.rank===1)throw new Ne("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=Ue(e,[0,2,3,1])),o=Km(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(o=ro(o,this.bias.read(),this.dataFormat)),this.activation!=null&&(o=this.activation.apply(o)),this.dataFormat==="channelsFirst"&&(o=Ue(o,[0,3,1,2])),o})}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=lt(this.depthwiseRegularizer),e.pointwiseRegularizer=lt(this.pointwiseRegularizer),e.depthwiseConstraint=Ot(this.depthwiseConstraint),e.pointwiseConstraint=Ot(this.pointwiseConstraint),e}};Ow.className="SeparableConv";var Vf=class extends Ow{constructor(e){super(2,e)}};Vf.className="SeparableConv2D";J.registerClass(Vf);var rc=class extends ec{constructor(e){super(1,e);rc.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"&&!_g(e.kernelSize,"number",1,1))throw new B(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}};rc.className="Conv1D";J.registerClass(rc);var Gf=class extends Me{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 V(()=>{if(e=Oe(e),this.dataFormat==="channelsLast"){let o=df(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return df(o,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let o=df(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return df(o,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}};Gf.className="Cropping2D";J.registerClass(Gf);var Wf=class extends Me{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,$t(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,ET(this.interpolation)}computeOutputShape(e){if(this.dataFormat==="channelsFirst"){let t=e[2]==null?null:this.size[0]*e[2],o=e[3]==null?null:this.size[1]*e[3];return[e[0],e[1],t,o]}else{let t=e[1]==null?null:this.size[0]*e[1],o=e[2]==null?null:this.size[1]*e[2];return[e[0],t,o,e[3]]}}call(e,t){return V(()=>{let o=Oe(e),n=o.shape;if(this.dataFormat==="channelsFirst"){o=Ue(o,[0,2,3,1]);let s=this.size[0]*n[2],a=this.size[1]*n[3],i=this.interpolation==="nearest"?o.resizeNearestNeighbor([s,a]):o.resizeBilinear([s,a]);return Ue(i,[0,3,1,2])}else{let s=this.size[0]*n[1],a=this.size[1]*n[2];return this.interpolation==="nearest"?o.resizeNearestNeighbor([s,a]):o.resizeBilinear([s,a])}})}getConfig(){let e={size:this.size,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};Wf.className="UpSampling2D";J.registerClass(Wf);function vq(r,e,t=[1,1],o="valid",n,s){return V(()=>{n==null&&(n=Kr()),$t(n);let a=zf(r,n);if(r.rank!==4)throw new B(`Input for depthwiseConv2d is required to be 4-D, but is instead ${r.rank}-D`);if(e.rank!==4)throw new B(`depthwiseKernel is required to be 4-D, but is instead ${e.rank}-D`);return a=Cs(a,e,t,o==="same"?"same":"valid","NHWC",s),n==="channelsFirst"&&(a=Ue(a,[0,3,1,2])),a})}var Uf=class extends Ip{constructor(e){super(2,e);this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=dt(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Pt(e.depthwiseConstraint),this.depthwiseRegularizer=bt(e.depthwiseRegularizer)}build(e){if(e=Qe(e),e.length<4)throw new B(`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 B(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);let o=e[t],n=[this.kernelSize[0],this.kernelSize[1],o,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",n,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[o*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return V(()=>{e=Oe(e);let o=vq(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(o=ro(o,this.bias.read(),this.dataFormat)),this.activation!=null&&(o=this.activation.apply(o)),o})}computeOutputShape(e){e=Qe(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],o=this.dataFormat==="channelsFirst"?e[3]:e[2],n=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,s=io(t,this.kernelSize[0],this.padding,this.strides[0]),a=io(o,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],n,s,a]:[e[0],s,a,n]}getConfig(){let e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=It(this.depthwiseInitializer),e.depthwiseRegularizer=lt(this.depthwiseRegularizer),e.depthwiseConstraint=Ot(this.depthwiseRegularizer),e}};Uf.className="DepthwiseConv2D";J.registerClass(Uf);function Pw(r,e,t,o){if(Array.isArray(r)){if(e!=null||t!=null)throw new B("When inputs is an array, neither initialState or constants should be provided");o!=null&&(t=r.slice(r.length-o,r.length),r=r.slice(0,r.length-o)),r.length>1&&(e=r.slice(1,r.length)),r=r[0]}function n(s){return s==null||Array.isArray(s)?s:[s]}return e=n(e),t=n(t),{inputs:r,initialState:e,constants:t}}function Mw(r,e,t,o=!1,n,s,a=!1,i=!1){return V(()=>{let l=e.shape.length;if(l<3)throw new B(`Input should be at least 3D, but is ${l}D.`);let u=[1,0].concat(Pr(2,l));if(e=Ue(e,u),s!=null)throw new Ne("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."),n!=null&&(n=n.asType("bool").asType("float32"),n.rank===l-1&&(n=sr(n,-1)),n=Ue(n,u)),o&&(e=qt(e,0),n!=null&&(n=qt(n,0)));let c=[],p,m=t,f=e.shape[0],d=ur(e),h;n!=null&&(h=ur(n));for(let x=0;x<f;++x){let b=d[x],_=V(()=>r(b,m));if(n==null)p=_[0],m=_[1];else{let w=V(()=>{let v=h[x],$=er(v).sub(v),A=_[0].mul(v).add(m[0].mul($)),R=m.map((M,z)=>_[1][z].mul(v).add(M.mul($)));return{output:A,newStates:R}});p=w.output,m=w.newStates}i&&c.push(p)}let g;return i&&(g=Bt(c,1)),[p,g,m]})}var ao=class extends Me{constructor(e){super(e);let t;if(e.cell==null)throw new B("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new Np({cells:e.cell}):t=e.cell,t.stateSize==null)throw new B("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 Et({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 Pr(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){Eg(e)&&(e=e[0]),e=e;let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);let o=t[0],n;if(this.returnSequences?n=[e[0],e[1],o]:n=[e[0],o],this.returnState){let s=[];for(let a of t)s.push([e[0],a]);return[n].concat(s)}else return n}computeMask(e,t){return V(()=>{Array.isArray(t)&&(t=t[0]);let o=this.returnSequences?t:null;if(this.returnState){let n=this.states.map(s=>null);return[o].concat(n)}else return o})}get states(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let o=0;o<e;++o)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 Ne("Constants support is not implemented in RNN yet.");Eg(e)&&(e=e[0]),e=e;let o=this.stateful?e[0]:null,n=e.slice(2);this.inputSpec[0]=new Et({shape:[o,null,...n]});let s=[e[0]].concat(e.slice(2));if(t!=null)throw new Ne("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 B(`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 Et({shape:[null,i]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){V(()=>{if(!this.stateful)throw new ko("Cannot call resetStates() on an RNN Layer that is not stateful.");let o=this.inputSpec[0].shape[0];if(o==null)throw new B("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.states_==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(n=>gt([o,n])):this.states_=[gt([o,this.cell.stateSize])];else if(e==null)Te(this.states_),this.keptStates!=null&&(Te(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(n=>gt([o,n])):this.states_[0]=gt([o,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new B(`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()):Te(this.states_);for(let n=0;n<this.states_.length;++n){let s=e[n],a=Array.isArray(this.cell.stateSize)?this.cell.stateSize[n]:this.cell.stateSize,i=[o,a];if(!y.arraysEqual(s.shape,i))throw new B(`State ${n} is incompatible with layer ${this.name}: expected shape=${i}, received shape=${s.shape}`);this.states_[n]=s}}this.states_=this.states_.map(n=>At(n.clone()))})}apply(e,t){let o=t==null?null:t.initialState,n=t==null?null:t.constants;t==null&&(t={});let s=Pw(e,o,n,this.numConstants);e=s.inputs,o=s.initialState,n=s.constants;let a=[],i=[];if(o!=null){t.initialState=o,a=a.concat(o),this.stateSpec=[];for(let u of o)this.stateSpec.push(new Et({shape:u.shape}));i=i.concat(this.stateSpec)}if(n!=null&&(t.constants=n,a=a.concat(n),this.numConstants=n.length),a[0]instanceof Lr){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 V(()=>{let o=t==null?null:t.mask,n=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 B(`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:n},u=Mw((d,h)=>{let g=this.cell.call([d].concat(h),i);return[g[0],g.slice(1)]},e,s,this.goBackwards,o,null,this.unroll,this.returnSequences),c=u[0],p=u[1],m=u[2];this.stateful&&this.resetStates(m,n);let f=this.returnSequences?p:c;return this.returnState?[f].concat(m):f})}getInitialState(e){return V(()=>{let t=gt(e.shape);return t=ye(t,[1,2]),t=La(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(o=>o>1?Cg(t,[1,o]):t):this.cell.stateSize>1?[Cg(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 o=this.cell.getConfig();return this.getClassName()===ao.className&&(t.cell={className:this.cell.getClassName(),config:o}),Object.assign({},o,e,t)}static fromConfig(e,t,o={}){let n=t.cell,s=Yr(n,o);return new e(Object.assign(t,{cell:s}))}};ao.className="RNN";J.registerClass(ao);var bl=class extends Me{},Sp=class extends bl{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,Wt(this.units,"units"),this.activation=Ps(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=dt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=dt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=dt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=bt(e.kernelRegularizer),this.recurrentRegularizer=bt(e.recurrentRegularizer),this.biasRegularizer=bt(e.biasRegularizer),this.kernelConstraint=Pt(e.kernelConstraint),this.recurrentConstraint=Pt(e.recurrentConstraint),this.biasConstraint=Pt(e.biasConstraint),this.dropout=qu([1,Rs([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=qu([1,Rs([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Qe(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 V(()=>{if(e=e,e.length!==2)throw new B(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let o=e[1];e=e[0];let n=t.training==null?!1:t.training;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Ba({ones:()=>er(e),rate:this.dropout,training:n})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Ba({ones:()=>er(o),rate:this.recurrentDropout,training:n}));let s,a=this.dropoutMask,i=this.recurrentDropoutMask;a!=null?s=Hn(O(e,a),this.kernel.read()):s=Hn(e,this.kernel.read()),this.bias!=null&&(s=ro(s,this.bias.read())),i!=null&&(o=O(o,i));let l=Q(s,Hn(o,this.recurrentKernel.read()));return this.activation!=null&&(l=this.activation.apply(l)),[l,l]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Os(this.activation),useBias:this.useBias,kernelInitializer:It(this.kernelInitializer),recurrentInitializer:It(this.recurrentInitializer),biasInitializer:It(this.biasInitializer),kernelRegularizer:lt(this.kernelRegularizer),recurrentRegularizer:lt(this.recurrentRegularizer),biasRegularizer:lt(this.biasRegularizer),activityRegularizer:lt(this.activityRegularizer),kernelConstraint:Ot(this.kernelConstraint),recurrentConstraint:Ot(this.recurrentConstraint),biasConstraint:Ot(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign({},e,t)}};Sp.className="SimpleRNNCell";J.registerClass(Sp);var jf=class extends ao{constructor(e){e.cell=new Sp(e),super(e)}call(e,t){return V(()=>{this.cell.dropoutMask!=null&&(Te(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Te(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let o=t==null?null:t.mask,n=t==null?null:t.training,s=t==null?null:t.initialState;return super.call(e,{mask:o,training:n,initialState:s})})}static fromConfig(e,t){return new e(t)}};jf.className="SimpleRNN";J.registerClass(jf);var Tp=class extends bl{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 B("GRUCell does not support reset_after parameter set to true.");this.units=e.units,Wt(this.units,"units"),this.activation=Ps(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Ps(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=dt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=dt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=dt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=bt(e.kernelRegularizer),this.recurrentRegularizer=bt(e.recurrentRegularizer),this.biasRegularizer=bt(e.biasRegularizer),this.kernelConstraint=Pt(e.kernelConstraint),this.recurrentConstraint=Pt(e.recurrentConstraint),this.biasConstraint=Pt(e.biasConstraint),this.dropout=qu([1,Rs([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=qu([1,Rs([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=Qe(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 V(()=>{if(e=e,e.length!==2)throw new B(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);let o=t.training==null?!1:t.training,n=e[1];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Ba({ones:()=>er(e),rate:this.dropout,training:o,count:3})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Ba({ones:()=>er(n),rate:this.recurrentDropout,training:o,count:3}));let s=this.dropoutMask,a=this.recurrentDropoutMask,i,l,u;0<this.dropout&&this.dropout<1&&(e=O(e,s[0]));let c=Hn(e,this.kernel.read());this.useBias&&(c=ro(c,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(n=O(n,a[0]));let p=this.recurrentKernel.read(),[m,f]=lr(p,[2*this.units,this.units],p.rank-1),d=Hn(n,m),[h,g,x]=lr(c,3,c.rank-1),[b,_]=lr(d,2,d.rank-1);i=this.recurrentActivation.apply(Q(h,b)),l=this.recurrentActivation.apply(Q(g,_));let w=Hn(O(l,n),f);u=this.activation.apply(Q(x,w));let v=Q(O(i,n),O(Q(1,je(i)),u));return[v,v]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Os(this.activation),recurrentActivation:Os(this.recurrentActivation),useBias:this.useBias,kernelInitializer:It(this.kernelInitializer),recurrentInitializer:It(this.recurrentInitializer),biasInitializer:It(this.biasInitializer),kernelRegularizer:lt(this.kernelRegularizer),recurrentRegularizer:lt(this.recurrentRegularizer),biasRegularizer:lt(this.biasRegularizer),activityRegularizer:lt(this.activityRegularizer),kernelConstraint:Ot(this.kernelConstraint),recurrentConstraint:Ot(this.recurrentConstraint),biasConstraint:Ot(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign({},e,t)}};Tp.className="GRUCell";J.registerClass(Tp);var Hf=class extends ao{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 Tp(e),super(e)}call(e,t){return V(()=>{this.cell.dropoutMask!=null&&(Te(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Te(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let o=t==null?null:t.mask,n=t==null?null:t.training,s=t==null?null:t.initialState;return super.call(e,{mask:o,training:n,initialState:s})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};Hf.className="GRU";J.registerClass(Hf);var _l=class extends bl{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,Wt(this.units,"units"),this.activation=Ps(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Ps(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=dt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=dt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=dt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=bt(e.kernelRegularizer),this.recurrentRegularizer=bt(e.recurrentRegularizer),this.biasRegularizer=bt(e.biasRegularizer),this.kernelConstraint=Pt(e.kernelConstraint),this.recurrentConstraint=Pt(e.recurrentConstraint),this.biasConstraint=Pt(e.biasConstraint),this.dropout=qu([1,Rs([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=qu([1,Rs([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=Qe(e);let o=e[e.length-1];this.kernel=this.addWeight("kernel",[o,this.units*4],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*4],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint);let n;if(this.useBias){if(this.unitForgetBias){let s=this.biasInitializer,a=this.units;n=new(t=class extends oo{apply(l,u){let c=s.apply([a]),p=new Xu().apply([a]),m=s.apply([a*2]);return aw(aw(c,p),m)}},t.className="CustomInit",t)}else n=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,n,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return V(()=>{let o=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new B(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let n=e[1],s=e[2];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Ba({ones:()=>er(e),rate:this.dropout,training:o,count:4})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Ba({ones:()=>er(n),rate:this.recurrentDropout,training:o,count:4}));let a=this.dropoutMask,i=this.recurrentDropoutMask,l,u,c,p;0<this.dropout&&this.dropout<1&&(e=O(e,a[0]));let m=Hn(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(n=O(n,i[0])),m=Q(m,Hn(n,this.recurrentKernel.read())),this.useBias&&(m=ro(m,this.bias.read()));let[f,d,h,g]=lr(m,4,m.rank-1);l=this.recurrentActivation.apply(f),u=this.recurrentActivation.apply(d),c=Q(O(u,s),O(l,this.activation.apply(h))),p=this.recurrentActivation.apply(g);let x=O(p,this.activation.apply(c));return[x,x,c]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Os(this.activation),recurrentActivation:Os(this.recurrentActivation),useBias:this.useBias,kernelInitializer:It(this.kernelInitializer),recurrentInitializer:It(this.recurrentInitializer),biasInitializer:It(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:lt(this.kernelRegularizer),recurrentRegularizer:lt(this.recurrentRegularizer),biasRegularizer:lt(this.biasRegularizer),activityRegularizer:lt(this.activityRegularizer),kernelConstraint:Ot(this.kernelConstraint),recurrentConstraint:Ot(this.recurrentConstraint),biasConstraint:Ot(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign({},e,t)}};_l.className="LSTMCell";J.registerClass(_l);var qf=class extends ao{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 _l(e),super(e)}call(e,t){return V(()=>{this.cell.dropoutMask!=null&&(Te(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Te(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let o=t==null?null:t.mask,n=t==null?null:t.training,s=t==null?null:t.initialState;return super.call(e,{mask:o,training:n,initialState:s})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};qf.className="LSTM";J.registerClass(qf);var Np=class extends bl{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 V(()=>{e=e;let o=e.slice(1),n=[];for(let i of this.cells.slice().reverse())Array.isArray(i.stateSize)?n.push(o.splice(0,i.stateSize.length)):n.push(o.splice(0,1));n.reverse();let s=[],a;for(let i=0;i<this.cells.length;++i){let l=this.cells[i];o=n[i],i===0?a=[e[0]].concat(o):a=[a[0]].concat(o),a=l.call(a,t),s.push(a.slice(1))}o=[];for(let i of s.slice().reverse())o.push(...i);return[a[0]].concat(o)})}build(e){Eg(e)&&(e=e[0]),e=e;let t;this.cells.forEach((o,n)=>{$s(`RNNCell_${n}`,()=>{o.build(e),Array.isArray(o.stateSize)?t=o.stateSize[0]:t=o.stateSize,e=[e[0],t]})}),this.built=!0}getConfig(){let e=super.getConfig(),t=s=>({className:s.getClassName(),config:s.getConfig()}),n={cells:this.cells.map(t)};return Object.assign({},e,n)}static fromConfig(e,t,o={}){let n=[];for(let s of t.cells)n.push(Yr(s,o));return new e({cells:n})}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 o of this.cells)t.push(...o.trainableWeights);return t.concat(e)}return e}getWeights(){let e=[];for(let t of this.cells)e.push(...t.weights);return vf(e)}setWeights(e){let t=[];for(let o of this.cells){let n=o.weights.length,s=e.splice(n);for(let a=0;a<o.weights.length;++a)t.push([o.weights[a],s[a]])}_p(t)}};Np.className="StackedRNNCells";J.registerClass(Np);function Ba(r){let{ones:e,rate:t,training:o=!1,count:n=1}=r,s=()=>Ng(e(),t),a=()=>cl(s,e,o);return!n||n<=1?At(a().clone()):Array(n).fill(void 0).map(a).map(l=>At(l.clone()))}var Cq=function(r,e){var t={};for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&e.indexOf(o)<0&&(t[o]=r[o]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,o=Object.getOwnPropertySymbols(r);n<o.length;n++)e.indexOf(o[n])<0&&Object.prototype.propertyIsEnumerable.call(r,o[n])&&(t[o[n]]=r[o[n]]);return t};var Lw=class extends ao{constructor(e){if(e.unroll)throw new Ne("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Ne("It is not possible at the moment to stack convolutional cells.");super(e);this.inputSpec=[new Et({ndim:5})]}call(e,t){return V(()=>{if(this.cell.dropoutMask!=null&&(Te(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Te(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new B("ConvRNN2D cell does not support constants");let o=t==null?null:t.mask,n=t==null?null:t.training,s=t==null?null:t.initialState;return super.call(e,{mask:o,training:n,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 V(()=>{let{stateSize:t}=this.cell,o=e.shape,n=this.computeSingleOutputShape(o),s=[n[0],...n.slice(2)],a=gt(s);return Array.isArray(t)?Array(t.length).fill(a):[a]})}resetStates(e,t=!1){V(()=>{if(!this.stateful)throw new ko("Cannot call resetStates() on an RNN Layer that is not stateful.");let o=this.inputSpec[0].shape,n=this.computeSingleOutputShape(o),s=[n[0],...n.slice(2)];if(o[0]==null)throw new B("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)Te(this.states_),this.keptStates!=null&&(Te(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 B(`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()):Te(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 B(`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=>At(i.clone()))})}computeSingleOutputShape(e){let{dataFormat:t,filters:o,kernelSize:n,padding:s,strides:a,dilationRate:i}=this.cell,l=t==="channelsFirst",u=e[l?3:2],c=e[l?4:3],p=io(u,n[0],s,a[0],i[0]),m=io(c,n[1],s,a[1],i[1]);return[...e.slice(0,2),...l?[o,p,m]:[p,m,o]]}};Lw.className="ConvRNN2D";var Ep=class extends _l{constructor(e){let{filters:t,kernelSize:o,strides:n,padding:s,dataFormat:a,dilationRate:i}=e;super(Object.assign({},e,{units:t}));this.filters=t,Wt(this.filters,"filters"),this.kernelSize=xl(o,2,"kernelSize"),this.kernelSize.forEach(l=>Wt(l,"kernelSize")),this.strides=xl(n||1,2,"strides"),this.strides.forEach(l=>Wt(l,"strides")),this.padding=s||"valid",Xr(this.padding),this.dataFormat=a||"channelsLast",$t(this.dataFormat),this.dilationRate=xl(i||1,2,"dilationRate"),this.dilationRate.forEach(l=>Wt(l,"dilationRate"))}build(e){var t;e=Qe(e);let o=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[o]==null)throw new B(`The channel dimension of the input should be defined. Found ${e[o]}`);let n=e[o],s=4,a=this.kernelSize.concat([n,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 oo{apply(m,f){let d=u.apply([c]),h=Cr([c]),g=u.apply([c*2]);return cp([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 V(()=>{if(e.length!==3)throw new B(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let o=t.training||!1,n=e[0],s=e[1],a=e[2],i=4;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Ba({ones:()=>er(n),rate:this.dropout,training:o,count:i}));let l=this.dropoutMask,u=(ie,se,pe)=>!se||!se[pe]?ie:O(se[pe],ie),c=u(n,l,0),p=u(n,l,1),m=u(n,l,2),f=u(n,l,3);0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Ba({ones:()=>er(s),rate:this.recurrentDropout,training:o,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),_=3,[w,v,$,A]=lr(this.kernel.read(),i,_),[R,M,z,W]=this.useBias?lr(this.bias.read(),i):[null,null,null,null];c=this.inputConv(c,w,R,this.padding),p=this.inputConv(p,v,M,this.padding),m=this.inputConv(m,$,z,this.padding),f=this.inputConv(f,A,W,this.padding);let[U,q,Z,X]=lr(this.recurrentKernel.read(),i,_);h=this.recurrentConv(h,U),g=this.recurrentConv(g,q),x=this.recurrentConv(x,Z),b=this.recurrentConv(b,X);let Y=this.recurrentActivation.apply(Q(c,h)),te=this.recurrentActivation.apply(Q(p,g)),K=Q(O(te,a),O(Y,this.activation.apply(Q(m,x)))),re=O(this.recurrentActivation.apply(Q(f,b)),this.activation.apply(K));return[re,re,K]})}getConfig(){let e=super.getConfig(),{units:t}=e,o=Cq(e,["units"]),n={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign({},o,n)}inputConv(e,t,o,n){let s=jr(e,t,this.strides,n||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return o?ro(s,o,this.dataFormat):s}recurrentConv(e,t){return jr(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};Ep.className="ConvLSTM2DCell";J.registerClass(Ep);var Kf=class extends Lw{constructor(e){let t=new Ep(e);super(Object.assign({},e,{cell:t}))}static fromConfig(e,t){return new e(t)}};Kf.className="ConvLSTM2D";J.registerClass(Kf);var Ap=class extends Me{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,o=[];for(let n=0;n<this.noiseShape.length;++n)o.push(this.noiseShape[n]==null?t[n]:this.noiseShape[n]);return o}call(e,t){return V(()=>{this.invokeCallHook(e,t);let o=Oe(e);if(0<this.rate&&this.rate<1){let n=t.training==null?!1:t.training,s=this.getNoiseShape(o);return cl(()=>Ng(o,this.rate,s,this.seed),()=>o,n)}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()}};Ap.className="Dropout";J.registerClass(Ap);var Xf=class extends Ap{constructor(e){super(e);this.inputSpec=[{ndim:3}]}getNoiseShape(e){let t=e.shape;return[t[0],1,t[2]]}};Xf.className="SpatialDropout1D";J.registerClass(Xf);var Yf=class extends Me{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,Wt(this.units,"units"),this.activation=Ps(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=dt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=dt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Pt(e.kernelConstraint),this.biasConstraint=Pt(e.biasConstraint),this.kernelRegularizer=bt(e.kernelRegularizer),this.biasRegularizer=bt(e.biasRegularizer),this.activityRegularizer=bt(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=Qe(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=Qe(e);let t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return V(()=>{this.invokeCallHook(e,t);let o=Oe(e),n=wg(this.activation.getClassName()),s;return n!=null?s=Hn(o,this.kernel.read(),n,this.bias?this.bias.read():null):(s=Hn(o,this.kernel.read()),this.bias!=null&&(s=ro(s,this.bias.read())),this.activation!=null&&(s=this.activation.apply(s))),s})}getConfig(){let e={units:this.units,activation:Os(this.activation),useBias:this.useBias,kernelInitializer:It(this.kernelInitializer),biasInitializer:It(this.biasInitializer),kernelRegularizer:lt(this.kernelRegularizer),biasRegularizer:lt(this.biasRegularizer),activityRegularizer:lt(this.activityRegularizer),kernelConstraint:Ot(this.kernelConstraint),biasConstraint:Ot(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}};Yf.className="Dense";J.registerClass(Yf);var Zf=class extends Me{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=Qe(e);for(let t of e.slice(1))if(t==null)throw new B(`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],jn(e,1)]}call(e,t){return V(()=>{this.invokeCallHook(e,t);let o=Oe(e);if(this.dataFormat==="channelsFirst"&&o.rank>1){let n=[0];for(let s=2;s<o.rank;++s)n.push(s);n.push(1),o=o.transpose(n)}return PT(o)})}getConfig(){let e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);let t=super.getConfig();return Object.assign(e,t),e}};Zf.className="Flatten";J.registerClass(Zf);var Jf=class extends Me{constructor(e){super(e);this.supportsMasking=!0,this.activation=Ps(e.activation)}call(e,t){return V(()=>{this.invokeCallHook(e,t);let o=Oe(e);return this.activation.apply(o)})}getConfig(){let e={activation:Os(this.activation)},t=super.getConfig();return Object.assign(e,t),e}};Jf.className="Activation";J.registerClass(Jf);var Qf=class extends Me{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 V(()=>(e=Oe(e),FT(e,this.n)))}getConfig(){let e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}};Qf.className="RepeatVector";J.registerClass(Qf);var ed=class extends Me{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 o="Total size of new array must be unchanged.",n=t.slice(),s=1,a=null;for(let l=0;l<n.length;++l){let u=n[l];if(this.isUnknown(u))if(a===null)a=l;else throw new B("Can only specifiy one unknown dimension.");else s*=u}let i=jn(e);if(a!==null){if(s===0||i%s!=0)throw new B(o);n[a]=i/s}else if(i!==s)throw new B(o);return n}computeOutputShape(e){let t=!1;for(let o=0;o<e.length;++o)if(this.isUnknown(e[o])){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 V(()=>{this.invokeCallHook(e,t);let o=Oe(e),n=o.shape,s=n.slice(0,1).concat(this.fixUnknownDimension(n.slice(1),this.targetShape));return o.reshape(s)})}getConfig(){let e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}};ed.className="Reshape";J.registerClass(ed);var td=class extends Me{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=Pr(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 Et({ndim:this.dims.length+1})]}computeOutputShape(e){e=Qe(e);let t=e.slice();return this.dims.forEach((o,n)=>{t[n+1]=e[o]}),t}call(e,t){return Ue(Oe(e),this.dimsIncludingBatch)}getConfig(){let e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}};td.className="Permute";J.registerClass(td);var rd=class extends Me{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 o=Oe(e),n=-1;return nl(Ln(o,this.maskValue),n)}call(e,t){return V(()=>{this.invokeCallHook(e,t);let o=Oe(e),n=-1,s=!0,a=nl(Ln(o,this.maskValue),n,s);return o.mul(a.asType(o.dtype))})}};rd.className="Masking";J.registerClass(rd);var od=class extends Me{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(yt(e.inputLength))}this.inputDim=e.inputDim,Wt(this.inputDim,"inputDim"),this.outputDim=e.outputDim,Wt(this.outputDim,"outputDim"),this.embeddingsInitializer=dt(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=bt(e.embeddingsRegularizer),this.activityRegularizer=bt(e.activityRegularizer),this.embeddingsConstraint=Pt(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 V(()=>this.maskZero?(e=Oe(e),Ln(e,Ie(e))):null)}computeOutputShape(e){if(e=Qe(e),this.inputLength==null)return[...e,this.outputDim];let t=yt(this.inputLength);if(t.length!==e.length-1)throw new B(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let o=0;for(let n=0;n<t.length;++n){let s=t[n],a=e[n+1];if(s!=null&&a!=null&&s!==a)throw new B(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);s==null&&(t[o]=a),o++}}return[e[0],...t,this.outputDim]}call(e,t){return V(()=>{this.invokeCallHook(e,t);let o=Oe(e);return o.dtype!=="int32"&&(o=Ma(o,"int32")),Ig(this.embeddings.read(),o.as1D()).reshape(Qe(this.computeOutputShape(o.shape)))})}getConfig(){let e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:It(this.embeddingsInitializer),embeddingsRegularizer:lt(this.embeddingsRegularizer),activityRegularizer:lt(this.activityRegularizer),embeddingsConstraint:Ot(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}};od.className="Embedding";J.registerClass(od);var wl=class extends Me{constructor(e){super(e||{});this.supportsMasking=!0}mergeFunction(e){throw new Ne}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 o=e.slice(0,e.length-t.length);for(let n=0;n<t.length;++n){let s=e[e.length-t.length+n],a=t[n];if(s==null||a==null||s<0||a<0)o.push(null);else if(s===1)o.push(a);else if(a===1)o.push(s);else{if(s!==a)throw new B("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));o.push(s)}}return o}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[Qe(e)]),e=e,e.length<2)throw new B(`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=Un(t),t.length>1)throw new B(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let o=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);o=this.computeElementwiseOpOutputShape(o,a)}let n=e.map(s=>s.length);e.indexOf(null)===-1&&Un(n).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return V(()=>{if(e=e,this.reshapeRequired){let o=[],n=e.map(s=>s.rank);if(n.indexOf(null)===-1){let s=Rs(n);for(let a of e){let i=a.rank;for(let l=0;l<s-i;++l)a=La(a,1);o.push(a)}return this.mergeFunction(o)}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(jn(c.slice(1))));f=Ue(f,[1,0]),f=f.reshape(m),o.push(f),s=!0}else if(u>1){let c=Pr(1,u).concat([0]);o.push(Ue(l,c)),s=!0}else o.push(l)}let a=this.mergeFunction(o),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=Ue(a.reshape([-1,c]),[1,0]).reshape(p)}else if(i>1){let l=[i-1].concat(Pr(0,i-1));a=Ue(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 n=1;n<e.length;++n){let s=e[n]==null?null:e[n].slice(1);t=this.computeElementwiseOpOutputShape(t,s)}let o=[];for(let n of e)n!=null&&n[0]!==null&&o.push(n[0]);return o=Un(o),o.length===1?t=o.concat(t):t=[null].concat(t),t}computeMask(e,t){return V(()=>{if(t==null)return null;if(!Array.isArray(t))throw new B("`mask` should be an Array");if(!Array.isArray(e))throw new B("`inputs` should be an Array");if(t.length!==e.length)throw new B(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(n=>n==null))return null;t=t.map(n=>n==null?n:sr(n,0));let o=t[0];for(let n=1;n<t.length-1;++n)o=fr(o,t[n]);return o})}},nd=class extends wl{constructor(e){super(e)}mergeFunction(e){return V(()=>{let t=e[0].clone();for(let o=1;o<e.length;++o)t=Q(t,e[o]);return t})}};nd.className="Add";J.registerClass(nd);var sd=class extends wl{constructor(e){super(e)}mergeFunction(e){return V(()=>{let t=e[0].clone();for(let o=1;o<e.length;++o)t=O(t,e[o]);return t})}};sd.className="Multiply";J.registerClass(sd);var id=class extends wl{constructor(e){super(e)}mergeFunction(e){return V(()=>{let t=e[0].clone();for(let o=1;o<e.length;++o)t=Q(t,e[o]);return O(1/e.length,t)})}};id.className="Average";J.registerClass(id);var ad=class extends wl{constructor(e){super(e)}mergeFunction(e){return V(()=>{let t=e[0];for(let o=1;o<e.length;++o)t=qr(t,e[o]);return t})}};ad.className="Maximum";J.registerClass(ad);var ld=class extends wl{constructor(e){super(e)}mergeFunction(e){return V(()=>{let t=e[0];for(let o=1;o<e.length;++o)t=Ts(t,e[o]);return t})}};ld.className="Minimum";J.registerClass(ld);var ud=class extends wl{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 B("A `Concatenate` layer should be called on a list of at least 2 inputs");e=e;let t=!0;for(let n of e)if(n!=null){t=!1;break}if(t)return;let o=[];for(let n=0;n<e.length;++n){let s=e[n].slice();s.splice(this.axis,1);let a=!1;for(let i of o)if(y.arraysEqual(i,s)){a=!0;break}a||o.push(s)}if(o.length>1)throw new B("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return V(()=>cp(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new B("A `Concatenate` layer should be called on a list of inputs.");let t=e,o=t[0].slice(),n=this.axis<0?o.length+this.axis:this.axis;for(let s of t.slice(1)){if(o[n]==null||s[n]==null){o[n]=null;break}o[n]+=s[n]}return o}computeMask(e,t){if(t==null)return null;if(!Array.isArray(t))throw new B("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new B("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new B(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return V(()=>{let o=!0;if(t.forEach(a=>{if(a!=null){o=!1;return}}),o)return null;let n=[];for(let a=0;a<e.length;++a)t[a]==null?n.push(er(e[a]).asType("bool")):t[a].rank<e[a].rank?n.push(sr(t[a],-1)):n.push(t[a]);let s=Je(n,this.axis);return _u(s,-1,!1)})}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};ud.className="Concatenate";J.registerClass(ud);function cd(r,e){for(;r<0;)r+=e;return r}function Iq(r,e,t){if(r.shape.length>3||e.shape.length>3)throw new Ne("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 Ne("batchDot is not implemented for complex64-type Tensors yet.");let o=r.shape.length,n=e.shape.length;t==null&&(t=[o-1,n-2]);let s=t;return V(()=>{let a;if(o>n){a=o-n;let l=[];for(let u=0;u<a;++u)l.push(1);e=e.reshape(e.shape.concat(l))}else if(n>o){a=n-o;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;o>n?l=o+n-3:l=o-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 pd=class extends wl{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],o=e[1];if(t.length>3||o.length>3)throw new Ne("Dot layer does not support tensors of 4D or higher rank yet.");let n=this.interpretAxes(t,o);if(t[n[0]]!==o[n[1]])throw new B(`Dimension incompatibility: ${t[n[0]]} !== ${o[n[1]]}`)}mergeFunction(e){if(e.length!==2)throw new B(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t=e[0],o=e[1],n;return Array.isArray(this.axes)?n=this.axes.map((s,a)=>cd(s,e[a].shape.length)):n=[cd(this.axes,t.shape.length),cd(this.axes,o.shape.length)],this.normalize&&(t=Cf(t,n[0]),o=Cf(o,n[1])),Iq(t,o,n)}interpretAxes(e,t){let o;return Array.isArray(this.axes)?o=this.axes:o=[cd(this.axes,e.length),cd(this.axes,t.length)],o}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(),o=e[1].slice();if(t.length>3||o.length>3)throw new Ne("Dot layer does not support tensors of 4D or higher rank yet.");let n=this.interpretAxes(t,o);t.splice(n[0],1),o.splice(n[1],1),o.splice(0,1);let s=t.concat(o);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}};pd.className="Dot";J.registerClass(pd);var md=class extends Me{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 V(()=>{this.invokeCallHook(e,t);let o=Oe(e);return cl(()=>pp(o.shape,0,this.stddev).add(o),()=>o,t.training||!1)})}};md.className="GaussianNoise";J.registerClass(md);var fd=class extends Me{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 V(()=>{this.invokeCallHook(e,t);let o=Oe(e);return this.rate>0&&this.rate<1?cl(()=>{let s=Math.sqrt(this.rate/(1-this.rate));return o.mul(pp(o.shape,1,s))},()=>o,t.training||!1):o})}};fd.className="GaussianDropout";J.registerClass(fd);var dd=class extends Me{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 V(()=>{if(this.rate<1&&this.rate>0){let o=this._getNoiseShape(e);return cl(()=>{let s=Oe(e),a=1.6732632423543772,i=1.0507009873554805,l=-a*i,u=to(Es(o),this.rate);u=Ma(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})}};dd.className="AlphaDropout";J.registerClass(dd);function hd(r,e,t,o,n,s=.001){let a;if(r.rank===2)a=s_(r,e,t,o,n,s);else if(r.rank===3)a=i_(r,e,t,o,n,s);else if(r.rank===4)a=a_(r,e,t,o,n,s);else throw new Ne(`batchNormalization is not implemented for array of rank ${r.rank} yet`);return a}function Nq(r,e,t,o,n=.001){return V(()=>{let s=Xc(r,o),a=s.mean,i=s.variance;return[hd(r,a,i,t,e,n),a,i]})}function Sq(r,e,t,o,n=.001){return V(()=>{let s=Xc(r,o),a=s.mean,i=s.variance,l=[];for(let d of Pr(0,r.rank))o.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[hd(r,u,c,m,p,n),a,i]})}function Tq(r,e,t,o,n=.001){return y.arraysEqual(o.slice().sort(),Pr(0,r.rank-1))?Nq(r,e,t,o,n):Sq(r,e,t,o,n)}var gd=class extends Me{constructor(e){e==null&&(e={}),super(e),this.supportsMasking=!0,this.axis=e.axis==null?-1:e.axis,this.momentum=e.momentum==null?.99:e.momentum,this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=dt(e.betaInitializer||"zeros"),this.gammaInitializer=dt(e.gammaInitializer||"ones"),this.movingMeanInitializer=dt(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=dt(e.movingVarianceInitializer||"ones"),this.betaConstraint=Pt(e.betaConstraint),this.gammaConstraint=Pt(e.gammaConstraint),this.betaRegularizer=bt(e.betaRegularizer),this.gammaRegularizer=bt(e.gammaRegularizer)}build(e){e=Qe(e);let t=this.axis>=0?this.axis:this.axis+e.length,o=e[t];if(o==null)throw new B(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Et({ndim:e.length,axes:{[t]:o}})];let n=[o];this.scale&&(this.gamma=this.addWeight("gamma",n,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",n,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",n,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",n,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return V(()=>{let o=t.training==null?!1:t.training,n=Oe(e),s=n.shape,a=s.length,i=Pr(0,a),l=this.axis>=0?this.axis:this.axis+a;i.splice(l,1);let u=Vn(1,a);u[l]=s[l];let c=i.slice();c.sort();let p=!y.arraysEqual(c,Pr(0,a).slice(0,a-1)),m=()=>{if(p){let b=this.movingMean.read().reshape(u),_=this.movingVariance.read().reshape(u),w=this.center?this.beta.read().reshape(u):null,v=this.scale?this.gamma.read().reshape(u):null;return hd(n,b,_,w,v,this.epsilon)}else return hd(n,this.movingMean.read(),this.movingVariance.read(),this.beta==null?null:this.beta.read(),this.gamma==null?null:this.gamma.read(),this.epsilon)};if(!o)return m();let[f,d,h]=Tq(n,this.gamma.read(),this.beta.read(),i,this.epsilon),g=(b,_,w)=>{V(()=>{let v=1-w,$=b.read(),A=$.sub(_).mul(v);b.write($.sub(A))})};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:lt(this.betaRegularizer),gammaRegularizer:lt(this.gammaRegularizer),betaConstraint:Ot(this.betaConstraint),gammaConstraint:Ot(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}};gd.className="BatchNormalization";J.registerClass(gd);var xd=class extends Me{constructor(e){if(e==null&&(e={}),super(e),this.axis=e.axis==null?-1:e.axis,typeof this.axis=="number"){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else if(Array.isArray(this.axis)){for(let t of this.axis)if(!Number.isInteger(t))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}else throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=dt(e.betaInitializer||"zeros"),this.gammaInitializer=dt(e.gammaInitializer||"ones"),this.betaRegularizer=bt(e.betaRegularizer),this.gammaRegularizer=bt(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=Qe(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!==Un(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);let o=this.axis.map(s=>e[s]),n=!0;this.scale?this.gamma=this.addWeight("gamma",o,"float32",this.gammaInitializer,this.gammaRegularizer,n):this.gamma=null,this.center?this.beta=this.addWeight("beta",o,"float32",this.betaInitializer,this.betaRegularizer,n):this.beta=null,this.built=!0}call(e,t){let o=Oe(e),n=o.shape,s=n.length;return V(()=>{let a=!0,{mean:i,variance:l}=Xc(o,this.axis,a),u=Vn(1,s);for(let h of this.axis)u[h]=n[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(n[h]),d.push(1)):(f.push(1),d.push(n[h]));return i=i.tile(f),l=l.tile(f),p=p.tile(d),m=m.tile(d),hd(o,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:lt(this.betaRegularizer),gammaRegularizer:lt(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}};xd.className="LayerNormalization";J.registerClass(xd);function Eq(r,e,t){return V(()=>{if(r.rank!==4)throw new B(`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 B("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(t==null&&(t=Kr()),t!=="channelsLast"&&t!=="channelsFirst")throw new B(`Unknown data format: ${t}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let o;return t==="channelsFirst"?o=[[0,0],[0,0],e[0],e[1]]:o=[[0,0],e[0],e[1],[0,0]],$r(r,o)})}var yd=class extends Me{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?Kr():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 B(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,o;if(typeof e.padding[0]=="number")t=[e.padding[0],e.padding[0]],o=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,e.padding[0].length!==2)throw new B(`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 B(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);o=e.padding[1]}this.padding=[t,o]}this.inputSpec=[new Et({ndim:4})]}computeOutputShape(e){e=Qe(e);let t,o;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?o=e[3]+this.padding[1][0]+this.padding[1][1]:o=null,[e[0],e[1],t,o]):(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?o=e[2]+this.padding[1][0]+this.padding[1][1]:o=null,[e[0],t,o,e[3]])}call(e,t){return V(()=>Eq(Oe(e),this.padding,this.dataFormat))}getConfig(){let e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};yd.className="ZeroPadding2D";J.registerClass(yd);function Xg(r,e,t,o,n,s){return V(()=>{$t(n),sw(s),Xr(o),t==null&&(t=[1,1]),o==null&&(o="valid"),n==null&&(n=Kr()),s==null&&(s="max"),r=zf(r,n);let a,i=o==="same"?"same":"valid";return s==="max"?a=Ea(r,e,t,i):a=va(r,e,t,i),n==="channelsFirst"&&(a=Ue(a,[0,3,1,2])),a})}function v1(r,e,t,o,n,s){return V(()=>{$t(n),sw(s),Xr(o),t==null&&(t=[1,1,1]),o==null&&(o="valid"),n==null&&(n=Kr()),s==null&&(s="max"),r=Fw(r,n);let a,i=o==="same"?"same":"valid";return s==="max"?a=Gm(r,e,t,i):a=Dm(r,e,t,i),n==="channelsFirst"&&(a=Ue(a,[0,4,1,2,3])),a})}var zw=class extends Me{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 B(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(Wt(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 B(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);Wt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,Xr(this.padding),this.inputSpec=[new Et({ndim:3})]}computeOutputShape(e){e=Qe(e);let t=io(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return V(()=>{this.invokeCallHook(e,t),e=La(Oe(e),2);let o=this.poolingFunction(Oe(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return wo(o,[2])})}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}},bd=class extends zw{constructor(e){super(e)}poolingFunction(e,t,o,n,s){return $t(s),Xr(n),Xg(e,t,o,n,s,"max")}};bd.className="MaxPooling1D";J.registerClass(bd);var _d=class extends zw{constructor(e){super(e)}poolingFunction(e,t,o,n,s){return $t(s),Xr(n),Xg(e,t,o,n,s,"avg")}};_d.className="AveragePooling1D";J.registerClass(_d);var Bw=class extends Me{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 B(`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];Wt(this.poolSize,"poolSize"),Wt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,$t(this.dataFormat),Xr(this.padding),this.inputSpec=[new Et({ndim:4})]}computeOutputShape(e){e=Qe(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],o=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=io(t,this.poolSize[0],this.padding,this.strides[0]),o=io(o,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,o]:[e[0],t,o,e[3]]}call(e,t){return V(()=>(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}},wd=class extends Bw{constructor(e){super(e)}poolingFunction(e,t,o,n,s){return $t(s),Xr(n),Xg(e,t,o,n,s,"max")}};wd.className="MaxPooling2D";J.registerClass(wd);var kd=class extends Bw{constructor(e){super(e)}poolingFunction(e,t,o,n,s){return $t(s),Xr(n),Xg(e,t,o,n,s,"avg")}};kd.className="AveragePooling2D";J.registerClass(kd);var Vw=class extends Me{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 B(`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];Wt(this.poolSize,"poolSize"),Wt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,$t(this.dataFormat),Xr(this.padding),this.inputSpec=[new Et({ndim:5})]}computeOutputShape(e){e=Qe(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],o=this.dataFormat==="channelsFirst"?e[3]:e[2],n=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=io(t,this.poolSize[0],this.padding,this.strides[0]),o=io(o,this.poolSize[1],this.padding,this.strides[1]),n=io(n,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,o,n]:[e[0],t,o,n,e[4]]}call(e,t){return V(()=>(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}},vd=class extends Vw{constructor(e){super(e)}poolingFunction(e,t,o,n,s){return $t(s),Xr(n),v1(e,t,o,n,s,"max")}};vd.className="MaxPooling3D";J.registerClass(vd);var Cd=class extends Vw{constructor(e){super(e)}poolingFunction(e,t,o,n,s){return $t(s),Xr(n),v1(e,t,o,n,s,"avg")}};Cd.className="AveragePooling3D";J.registerClass(Cd);var Gw=class extends Me{constructor(e){super(e);this.inputSpec=[new Et({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Ne}},Id=class extends Gw{constructor(e){super(e||{})}call(e,t){return V(()=>{let o=Oe(e);return ht(o,1)})}};Id.className="GlobalAveragePooling1D";J.registerClass(Id);var Nd=class extends Gw{constructor(e){super(e||{})}call(e,t){return V(()=>{let o=Oe(e);return ar(o,1)})}};Nd.className="GlobalMaxPooling1D";J.registerClass(Nd);var Ww=class extends Me{constructor(e){super(e);this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,$t(this.dataFormat),this.inputSpec=[new Et({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Ne}getConfig(){let e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},Sd=class extends Ww{call(e,t){return V(()=>{let o=Oe(e);return this.dataFormat==="channelsLast"?ht(o,[1,2]):ht(o,[2,3])})}};Sd.className="GlobalAveragePooling2D";J.registerClass(Sd);var Td=class extends Ww{call(e,t){return V(()=>{let o=Oe(e);return this.dataFormat==="channelsLast"?ar(o,[1,2]):ar(o,[2,3])})}};Td.className="GlobalMaxPooling2D";J.registerClass(Td);var Uw=class extends Me{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,o={}){let n=t.layer,s=Yr(n,o);delete t.layer;let a={layer:s};return Object.assign(a,t),new e(a)}},Ed=class extends Uw{constructor(e){super(e);this.supportsMasking=!0}build(e){if(e=Qe(e),e.length<3)throw new B(`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=Qe(e);let t=[e[0]].concat(e.slice(2)),o=this.layer.computeOutputShape(t),n=e[1];return[o[0],n].concat(o.slice(1))}call(e,t){return V(()=>(e=Oe(e),Mw((a,i)=>[Oe(this.layer.call(a,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};Ed.className="TimeDistributed";J.registerClass(Ed);function Aq(r){Gi(TT,"BidirectionalMergeMode",r)}var Dq="concat",Ad=class extends Uw{constructor(e){super(e);let t=e.layer.getConfig(),o={};o.className=e.layer.getClassName(),o.config=t,this.forwardLayer=Yr(o),t.goBackwards=t.goBackwards!==!0;let n={};if(n.className=e.layer.getClassName(),n.config=t,this.backwardLayer=Yr(n),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?Dq:e.mergeMode,Aq(this.mergeMode),e.weights)throw new Ne("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,o=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,o)),this.backwardLayer.setWeights(e.slice(o))}computeOutputShape(e){let t=this.forwardLayer.computeOutputShape(e);Array.isArray(t)&&Array.isArray(t[0])||(t=[t]),t=t;let o,n,s;return this.returnState&&(s=t.slice(1)),o=t[0],o=o,this.mergeMode==="concat"?(o[o.length-1]*=2,n=[o]):this.mergeMode==null?n=[o,o.slice()]:n=[o],this.returnState?this.mergeMode==null?n.concat(s).concat(s.slice()):[o].concat(s).concat(s.slice()):dr(n)}apply(e,t){let o=t==null?null:t.initialState,n=t==null?null:t.constants;t==null&&(t={});let s=Pw(e,o,n,this.numConstants);if(e=s.inputs,o=s.initialState,n=s.constants,Array.isArray(e)&&(o=e.slice(1),e=e[0]),(o==null||o.length===0)&&n==null)return super.apply(e,t);let a=[],i=[];if(o!=null){let u=o.length;if(u%2>0)throw new B("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=o,a.push(...o);let c=o.map(p=>new Et({shape:p.shape}));this.forwardLayer.stateSpec=c.slice(0,u/2),this.backwardLayer.stateSpec=c.slice(u/2),i.push(...c)}if(n!=null)throw new Ne("Support for constants in Bidirectional layers is not implemented yet.");let l=a[0]instanceof Lr;for(let u of a)if(u instanceof Lr!==l)throw new B("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 V(()=>{let o=t.initialState,n,s;if(o==null)n=this.forwardLayer.call(e,t),s=this.backwardLayer.call(e,t);else{let l=o.slice(0,o.length/2),u=o.slice(o.length/2);n=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(n)&&(a=n.slice(1).concat(s.slice(1))),n=n[0],s=s[0]),this.returnSequences&&(s=qt(s,1));let i;return this.mergeMode==="concat"?i=cp([n,s]):this.mergeMode==="sum"?i=Q(n,s):this.mergeMode==="ave"?i=O(.5,Q(n,s)):this.mergeMode==="mul"?i=O(n,s):this.mergeMode==null&&(i=[n,s]),this.returnState?this.mergeMode==null?i.concat(a):[i].concat(a):i})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){$s(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),$s(this.backwardLayer.name,()=>{this.backwardLayer.build(e)}),this.built=!0}computeMask(e,t){Array.isArray(t)&&(t=t[0]);let o;if(this.returnSequences?this.mergeMode==null?o=[t,t]:o=t:this.mergeMode==null?o=[null,null]:o=null,this.returnState){let s=this.forwardLayer.states.map(a=>null);return Array.isArray(o)?o.concat(s).concat(s):[o].concat(s).concat(s)}else return o}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 o=Yr(t.layer);if(delete t.layer,t.numConstants!=null)throw new Ne("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");let n=t;return n.layer=o,new e(n)}};Ad.className="Bidirectional";J.registerClass(Ad);function $q(r){return new Wi(r)}function Rq(r){return new Of(r)}function Fq(r){return new $f(r)}function Oq(r){return new Rf(r)}function Pq(r){return new Ff(r)}function Mq(r){return new Mf(r)}function Lq(r){return new Pf(r)}function zq(r){return new rc(r)}function Bq(r){return new yl(r)}function Vq(r){return new Bf(r)}function Gq(r){return new tc(r)}function Wq(r){return new Vf(r)}function Uq(r){return new Gf(r)}function jq(r){return new Wf(r)}function Hq(r){return new Uf(r)}function qq(r){return new Jf(r)}function Kq(r){return new Yf(r)}function Xq(r){return new Ap(r)}function Yq(r){return new Xf(r)}function Zq(r){return new Zf(r)}function Jq(r){return new Qf(r)}function Qq(r){return new ed(r)}function eK(r){return new td(r)}function tK(r){return new od(r)}function rK(r){return new nd(r)}function oK(r){return new id(r)}function nK(r){return new ud(r)}function sK(r){return new ad(r)}function iK(r){return new ld(r)}function aK(r){return new sd(r)}function lK(r){return new pd(r)}function uK(r){return new gd(r)}function cK(r){return new xd(r)}function pK(r){return new yd(r)}function Hw(r){return new _d(r)}function mK(r){return Hw(r)}function fK(r){return Hw(r)}function qw(r){return new kd(r)}function dK(r){return qw(r)}function hK(r){return qw(r)}function Kw(r){return new Cd(r)}function gK(r){return Kw(r)}function xK(r){return Kw(r)}function yK(r){return new Id(r)}function bK(r){return new Sd(r)}function C1(r){return new Nd(r)}function I1(r){return new Td(r)}function N1(r){return new bd(r)}function S1(r){return new wd(r)}function _K(r){return new vd(r)}function wK(r){return new Hf(r)}function kK(r){return new Tp(r)}function vK(r){return new qf(r)}function CK(r){return new _l(r)}function IK(r){return new jf(r)}function NK(r){return new Sp(r)}function SK(r){return new Kf(r)}function TK(r){return new Ep(r)}function EK(r){return new ao(r)}function AK(r){return new Np(r)}function DK(r){return new Ad(r)}function $K(r){return new Ed(r)}var RK=C1,FK=I1,OK=N1,PK=S1;function MK(r){return new md(r)}function LK(r){return new fd(r)}function zK(r){return new dd(r)}function BK(r){return new rd(r)}var Xw={};et(Xw,{MAPE:()=>ZK,MSE:()=>e6,binaryAccuracy:()=>VK,binaryCrossentropy:()=>GK,categoricalAccuracy:()=>UK,categoricalCrossentropy:()=>jK,cosineProximity:()=>KK,mape:()=>JK,meanAbsoluteError:()=>XK,meanAbsolutePercentageError:()=>YK,meanSquaredError:()=>QK,mse:()=>t6,precision:()=>HK,recall:()=>qK,sparseCategoricalAccuracy:()=>WK});function VK(r,e){return Sf(r,e)}function GK(r,e){return Lg(r,e)}function WK(r,e){return zg(r,e)}function UK(r,e){return Tf(r,e)}function jK(r,e){return Ef(r,e)}function HK(r,e){return pw(r,e)}function qK(r,e){return KT(r,e)}function KK(r,e){return If(r,e)}function XK(r,e){return wp(r,e)}function YK(r,e){return dl(r,e)}function ZK(r,e){return dl(r,e)}function JK(r,e){return dl(r,e)}function QK(r,e){return ji(r,e)}function e6(r,e){return ji(r,e)}function t6(r,e){return ji(r,e)}var Yw={};et(Yw,{modelFromJSON:()=>m1});var Zw={};et(Zw,{l1:()=>o6,l1l2:()=>r6,l2:()=>n6});function r6(r){return new Qu(r)}function o6(r){return y1(r)}function n6(r){return b1(r)}var Yg=class extends fl{constructor(){super(...arguments);this.model=null}setModel(e){if(!(e instanceof vo))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function Zg(r,e){return r<e}function T1(r,e){return r>e}var Jg=class extends Yg{constructor(e){super();if(e==null&&(e={}),e.restoreBestWeights)throw new Ne("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=Zg:this.mode==="max"?this.monitorFunc=T1:this.monitor.indexOf("acc")!==-1?this.monitorFunc=T1:this.monitorFunc=Zg,this.monitorFunc===Zg&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Zg?Infinity:-Infinity}async onEpochEnd(e,t){await Ui(t);let o=this.getMonitorValue(t);o!=null&&(this.monitorFunc(o-this.minDelta,this.best)?(this.best=o,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 s6(r){return new Jg(r)}var E1={earlyStopping:s6};var qn;(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"})(qn||(qn={}));var A1;(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={}))})(A1||(A1={}));var Jw={};function D1(r,e){let t={tfOpName:r,category:"custom",inputs:[],attrs:[],customExecutor:e};Jw[r]=t}function Qg(r){return Jw[r]}function $1(r){delete Jw[r]}function C(r,e,t,o,n){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 hr(e.inputNames[s.inputIndexStart],t,o,n);if(s.type==="tensors")return e.inputNames.slice(i,l).map(m=>hr(m,t,o,n));let u=hr(e.inputNames.slice(i)[0],t,o,n),c=u.dataSync();return s.type==="number"?c[0]:y.toNestedArray(u.shape,c)}let a=e.attrParams[r];return a&&a.value}function hr(r,e,t,o){let[n,s]=Zr(r);if(o!=null){let i=o.getHashTableHandleByName(n);if(i!=null)return i}let a=t.currentContextIds.find(i=>!!e[ex(n,i)]);return a!==void 0?e[ex(n,a)][s]:void 0}function R1(r,e,t){return e[ex(r,t.currentContextId)]}function Ms(r,e){let[t,o]=Zr(r);return[ex(t,e&&e.currentContextId),o]}function ex(r,e){return e?`${r}-${e}`:r}function Zr(r){let e=r.split(":");return e.length===1?[r,0]:[e[0],Number(e[e.length-1])]}function Dd(r,e,t){let o=C("pad",r,e,t);if(o==="explicit"){o=C("explicitPaddings",r,e,t);let n=[[0,0],[0,0],[0,0],[0,0]];for(let s=0;s<4;s++)n[s][0]=o[s*2],n[s][1]=o[s*2+1];return n}return o}function Ls(r){return r.kept?r:$o(r)}var Qw={};et(Qw,{json:()=>i6});var i6=[{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 ek={};et(ek,{json:()=>a6});var a6=[{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}]}];var tk={};et(tk,{json:()=>l6});var l6=[{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 rk={};et(rk,{json:()=>u6});var u6=[{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 ok={};et(ok,{json:()=>c6});var c6=[{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 nk={};et(nk,{json:()=>p6});var p6=[{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 sk={};et(sk,{json:()=>m6});var m6=[{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 ik={};et(ik,{json:()=>f6});var f6=[{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 ak={};et(ak,{json:()=>d6});var d6=[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]}];var lk={};et(lk,{json:()=>h6});var h6=[{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 uk={};et(uk,{json:()=>g6});var g6=[{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 ck={};et(ck,{json:()=>x6});var x6=[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}];var pk={};et(pk,{json:()=>y6});var y6=[{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 mk={};et(mk,{json:()=>b6});var b6=[{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 fk={};et(fk,{json:()=>_6});var _6=[{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 dk={};et(dk,{json:()=>w6});var w6=[{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 hk={};et(hk,{json:()=>k6});var k6=[{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 tx=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let e=[Qw,ek,tk,rk,ok,nk,sk,uk,lk,ik,ck,pk,mk,fk,dk,hk,ak],t=[].concat(...e.map(o=>o.json));this.opMappers=t.reduce((o,n)=>(o[n.tfOpName]=n,o),{})}transformGraph(e,t={}){let o=e.node,n=[],s=[],a=[],i=o.reduce((h,g)=>(h[g.name]=this.mapNode(g),g.op.startsWith("Placeholder")?n.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=>{let[b]=Ms(x);g.inputs.push(i[b]),i[b].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]=Ms(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]=Ms(h),x=i[g];x&&(x.signatureKey=c[h],l.push(x))}):l=n;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:n,signature:t,functions:f};return a.length>0&&(d.initNodes=a),d}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,o)=>(t[e[o].name]=o,t),{})}mapNode(e){let t=Qg(e.op)||this.opMappers[e.op]||{};e.attr==null&&(e.attr={});let o={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(n=>n.startsWith("^")?n.substr(1):n),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr};return t.inputs!=null&&(o.inputParams=t.inputs.reduce((n,s)=>(n[s.name]={type:s.type,inputIndexStart:s.start,inputIndexEnd:s.end},n),{})),t.attrs!=null&&(o.attrParams=t.attrs.reduce((n,s)=>{let a=s.type,i;switch(s.type){case"string":i=rx(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=rx(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"string[]":i=ux(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=ux(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"number":i=nx(e.attr,s.tfName,s.defaultValue||0),i===void 0&&!!s.tfDeprecatedName&&(i=nx(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"number[]":i=lx(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=lx(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"bool":i=ox(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=ox(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"bool[]":i=px(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=px(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"shape":i=ax(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=ax(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"shape[]":i=cx(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=cx(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"dtype":i=sx(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=sx(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"dtype[]":i=ix(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=ix(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"func":i=F1(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=F1(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 n[s.name]={value:i,type:a},n},{})),o}mapFunction(e){let t=e.nodeDef,o=[],n=[],s={};t!=null&&(s=t.reduce((p,m)=>(p[m.name]=this.mapNode(m),m.op==="Const"&&n.push(p[m.name]),p),{}));let a=[],i=[];e.signature.inputArg.forEach(p=>{let[m]=Ms(p.name),f={name:m,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:gk(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=>{let[d]=Ms(f);m.inputs.push(s[d]),s[d].children.push(m)})});let u=e.ret;e.signature.outputArg.forEach(p=>{let[m,f]=Ms(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:n,placeholders:o,signature:c}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce((t,o)=>(t[o.name]=this.mapArgToTensorInfo(o),t),{}),outputs:e.signature.outputArg.reduce((t,o)=>(t[o.name]=this.mapArgToTensorInfo(o,e.ret),t),{})}}mapArgToTensorInfo(e,t){let o=e.name;return t!=null&&(o=t[o]),{name:o,dtype:e.type}}};function v6(r){let e=G().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 O1(r,e){let t=Array.isArray(r)?String.fromCharCode.apply(null,r):v6(r);return e?t:t.toLowerCase()}function rx(r,e,t,o=!1){let n=r[e];return n!=null?O1(n.s,o):t}function ox(r,e,t){let o=r[e];return o?o.b:t}function nx(r,e,t){let o=r[e]||{},n=o.i!=null?o.i:o.f!=null?o.f:t;return typeof n=="number"?n:parseInt(n,10)}function gk(r){switch(typeof r=="string"&&(r=qn[r]),r){case qn.DT_FLOAT:return"float32";case qn.DT_INT32:case qn.DT_INT64:case qn.DT_INT8:case qn.DT_UINT8:return"int32";case qn.DT_BOOL:return"bool";case qn.DT_DOUBLE:return"float32";case qn.DT_STRING:return"string";default:return null}}function F1(r,e,t){let o=r[e];return o&&o.func?o.func.name:t}function sx(r,e,t){let o=r[e];return o&&o.type?gk(o.type):t}function ix(r,e,t){let o=r[e];return o&&o.list&&o.list.type?o.list.type.map(n=>gk(n)):t}function P1(r){if(!r.unknownRank)return r.dim!=null?r.dim.map(e=>typeof e.size=="number"?e.size:parseInt(e.size,10)):[]}function ax(r,e,t){let o=r[e];return o&&o.shape?P1(o.shape):t}function lx(r,e,t){let o=r[e];return o?((o.list.f&&o.list.f.length?o.list.f:o.list.i)||[]).map(n=>typeof n=="number"?n:parseInt(n,10)):t}function ux(r,e,t,o=!1){let n=r[e];return n&&n.list&&n.list.s?n.list.s.map(s=>O1(s,o)):t}function cx(r,e,t){let o=r[e];return o&&o.list&&o.list.shape?o.list.shape.map(n=>P1(n)):t}function px(r,e,t){let o=r[e];return o&&o.list&&o.list.b?o.list.b:t}var xk=class{constructor(e,t,o){this.node=e,this.tensorMap=t,this.context=o,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(n=>this.getInput(n)),e.rawAttrs!=null&&(this.attrs=Object.keys(e.rawAttrs).reduce((n,s)=>(n[s]=this.getAttr(s),n),{}))}getInput(e){return hr(e,this.tensorMap,this.context)}getAttr(e,t){let o=this.node.rawAttrs[e];if(o.tensor!=null)return hr(e,this.tensorMap,this.context);if(o.i!=null||o.f!=null)return nx(this.node.rawAttrs,e,t);if(o.s!=null)return rx(this.node.rawAttrs,e,t);if(o.b!=null)return ox(this.node.rawAttrs,e,t);if(o.shape!=null)return ax(this.node.rawAttrs,e,t);if(o.type!=null)return sx(this.node.rawAttrs,e,t);if(o.list!=null){if(o.list.i!=null||o.list.f!=null)return lx(this.node.rawAttrs,e,t);if(o.list.s!=null)return ux(this.node.rawAttrs,e,t);if(o.list.shape!=null)return cx(this.node.rawAttrs,e,t);if(o.list.b!=null)return px(this.node.rawAttrs,e,t);if(o.list.type!=null)return ix(this.node.rawAttrs,e,t)}return t}};var M1=(r,e,t)=>{switch(r.op){case"BiasAdd":case"AddV2":case"Add":return[Q(C("a",r,e,t),C("b",r,e,t))];case"AddN":return[t_(C("tensors",r,e,t))];case"FloorMod":case"Mod":return[Um(C("a",r,e,t),C("b",r,e,t))];case"Mul":return[O(C("a",r,e,t),C("b",r,e,t))];case"RealDiv":case"Div":return[de(C("a",r,e,t),C("b",r,e,t))];case"DivNoNan":return[Pm(C("a",r,e,t),C("b",r,e,t))];case"FloorDiv":return[bu(C("a",r,e,t),C("b",r,e,t))];case"Sub":return[ue(C("a",r,e,t),C("b",r,e,t))];case"Minimum":return[Ts(C("a",r,e,t),C("b",r,e,t))];case"Maximum":return[qr(C("a",r,e,t),C("b",r,e,t))];case"Pow":return[Rr(C("a",r,e,t),C("b",r,e,t))];case"SquaredDifference":return[Bu(C("a",r,e,t),C("b",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var L1=(r,e,t)=>{switch(r.op){case"Abs":case"ComplexAbs":return[Tt(C("x",r,e,t))];case"Acos":return[vm(C("x",r,e,t))];case"Acosh":return[Cm(C("x",r,e,t))];case"Asin":return[Nm(C("x",r,e,t))];case"Asinh":return[Sm(C("x",r,e,t))];case"Atan":return[Tm(C("x",r,e,t))];case"Atan2":return[Em(C("x",r,e,t),C("y",r,e,t))];case"Atanh":return[Am(C("x",r,e,t))];case"Ceil":return[$m(C("x",r,e,t))];case"Complex":return[bo(C("real",r,e,t),C("imag",r,e,t))];case"Cos":return[Ia(C("x",r,e,t))];case"Cosh":return[Iu(C("x",r,e,t))];case"Elu":return[Is(C("x",r,e,t))];case"Erf":return[Mm(C("x",r,e,t))];case"Exp":return[Xt(C("x",r,e,t))];case"Expm1":return[Lm(C("x",r,e,t))];case"Floor":return[Ns(C("x",r,e,t))];case"Log":return[ir(C("x",r,e,t))];case"Log1p":return[Eu(C("x",r,e,t))];case"Imag":return[Su(C("x",r,e,t))];case"Neg":return[je(C("x",r,e,t))];case"Reciprocal":return[Hm(C("x",r,e,t))];case"Real":return[al(C("x",r,e,t))];case"Relu":return[Ir(C("x",r,e,t))];case"Round":return[qm(C("x",r,e,t))];case"Selu":return[Pu(C("x",r,e,t))];case"Sigmoid":return[Ur(C("x",r,e,t))];case"Sin":return[Mu(C("x",r,e,t))];case"Sign":return[Xm(C("x",r,e,t))];case"Sinh":return[Lu(C("x",r,e,t))];case"Softplus":return[Ss(C("x",r,e,t))];case"Sqrt":return[xt(C("x",r,e,t))];case"Square":return[Pe(C("x",r,e,t))];case"Tanh":return[Mi(C("x",r,e,t))];case"Tan":return[Qm(C("x",r,e,t))];case"ClipByValue":return[nr(C("x",r,e,t),C("clipValueMin",r,e,t),C("clipValueMax",r,e,t))];case"Relu6":return[Fu(C("x",r,e,t))];case"Rsqrt":return[Ou(hr(r.inputNames[0],e,t))];case"Prod":return[$u(C("x",r,e,t),C("axes",r,e,t))];case"LeakyRelu":return[Sa(C("x",r,e,t),C("alpha",r,e,t))];case"Prelu":return[Da(C("x",r,e,t),C("alpha",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};function Co(r,e,t=""){y.assert(C6(r,e),()=>t+` Shapes ${r} and ${e} must match`)}function C6(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==-1&&e[t]!==-1&&r[t]!==e[t])return!1;return!0}var yk=class{constructor(e,t,o,n,s,a,i){this.name=e,this.dtype=t,this.maxSize=o,this.elementShape=n,this.identicalElementShapes=s,this.dynamicSize=a,this.clearAfterRead=i,this.tensors=[],this.closed_=!1,this.idTensor=le(0),At(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 o=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),Co(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),o.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(o.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);o.tensor=t,At(t),o.written=!0,this.tensors[e]=o}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((o,n)=>this.write(o,t[n]))}gather(e,t){if(!!t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let n=0;n<this.size();n++)e.push(n)}if(e.length===0)return Dr([],[0].concat(this.elementShape));let o=this.readMany(e);return Co(this.elementShape,o[0].shape,"TensorArray shape mismatch: "),Bt(o,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 Dr([],[0].concat(this.elementShape));let t=[];for(let n=0;n<this.size();n++)t.push(n);let o=this.readMany(t);return Co(this.elementShape,o[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${o[0].shape})`),Je(o,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 o=Math.max(...e);if(!this.dynamicSize&&o>=this.maxSize)throw new Error(`Max index must be < array size (${o} vs. ${this.maxSize})`);this.writeMany(e,ur(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 o=0,n=e.map(l=>(o+=l,o));if(o!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to
|
|
tensor.shape[0], but sum of lengths is
|
|
${o}, 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=o===0?0:t.size/o,a=[];V(()=>{t=L(t,[1,o,s]);for(let l=0;l<e.length;++l){let u=l===0?0:n[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 oc=class{constructor(e,t,o,n=-1){this.tensors=e,this.elementShape=t,this.elementDtype=o,e!=null&&e.forEach(s=>{if(o!==s.dtype)throw new Error(`Invalid data types; op elements ${o}, but list elements ${s.dtype}`);Co(t,s.shape,"TensorList shape mismatch: "),At(s)}),this.idTensor=le(0),this.maxNumElements=n,At(this.idTensor)}get id(){return this.idTensor.id}copy(){return new oc([...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,o=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(o!==-1&&this.tensors.length!==o)throw new Error(`Operation expected a list with ${o} elements but got a list with ${this.tensors.length} elements.`);return Co(e,this.elementShape,"TensorList shape mismatch: "),V(()=>{let n=this.tensors.map(s=>L(s,e));return Bt(n,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");let o=this.tensors.pop();return Co(o.shape,e,"TensorList shape mismatch: "),L(o,e)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Co(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");At(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,o){if(o!==this.elementDtype)throw new Error(`Invalid data types; op elements ${o}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(this.tensors[e]==null)throw new Error(`element at index ${e} is null.`);return Co(this.tensors[e].shape,t,"TensorList shape mismatch: "),this.tensors[e]}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);Co(this.elementShape,t.shape,"TensorList shape mismatch: "),At(t),this.tensors[e]=t}gather(e,t,o){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);return Co(this.elementShape,o,"TensorList shape mismatch: "),e=e.slice(0,this.size()),e.length===0?Dr([],[0].concat(this.elementShape)):V(()=>{let n=e.map(s=>L(this.tensors[s],o));return Bt(n,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);return Co(this.elementShape,t,"TensorList shape mismatch: "),this.size()===0?Dr([],[0].concat(this.elementShape)):V(()=>{let o=this.tensors.map(n=>L(n,t));return Je(o,0)})}};function z1(r,e,t){let o=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 n=r.shape.slice(1);Co(n,e,"TensorList shape mismatch: ");let s=ur(r);return new oc(s,e,o)}function B1(r,e,t){return new oc([],r,e,t)}function V1(r,e,t,o){if(e.length!==r.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${r.shape[0]}`);let n=Math.max(...e);if(o!=null&&o!==-1&&n>=o)throw new Error(`Max index must be < array size (${n} vs. ${o})`);let s=new oc([],t,r.dtype,o),a=ur(r,0);return e.forEach((i,l)=>{s.setItem(i,a[l])}),s}function G1(r,e,t){let o=0,n=e.map(l=>(o+=l,o));if(o!==r.shape[0])throw new Error(`Expected sum of lengths to be equal to
|
|
tensor.shape[0], but sum of lengths is
|
|
${o}, and tensor's shape is: ${r.shape}`);let s=o===0?0:r.size/o,a=V(()=>{let l=[];r=L(r,[1,o,s]);for(let u=0;u<e.length;++u){let c=u===0?0:n[u-1],p=[0,c,0],m=[1,e[u],s];l[u]=L(Fe(r,p,m),t)}return r.dispose(),l}),i=new oc([],t,r.dtype,e.length);for(let l=0;l<a.length;l++)i.setItem(l,a[l]);return i}var W1=async(r,e,t)=>{switch(r.op){case"If":case"StatelessIf":{let o=C("thenBranch",r,e,t),n=C("elseBranch",r,e,t),s=C("cond",r,e,t),a=C("args",r,e,t);return(await s.data())[0]?t.functionMap[o].executeFunctionAsync(a,t.tensorArrayMap,t.tensorListMap):t.functionMap[n].executeFunctionAsync(a,t.tensorArrayMap,t.tensorListMap)}case"While":case"StatelessWhile":{let o=C("body",r,e,t),n=C("cond",r,e,t),s=C("args",r,e,t),a=await t.functionMap[n].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[o].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[n].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 o=C("pred",r,e,t);return[Ls(o)]}case"Switch":{let o=C("pred",r,e,t),n=C("data",r,e,t);return n.kept||(n=Ls(n)),(await o.data())[0]?[void 0,n]:[n,void 0]}case"Merge":{let o=r.inputNames.find(n=>hr(n,e,t)!==void 0);if(o){let n=hr(o,e,t);return[Ls(n)]}return}case"Enter":{let o=C("frameName",r,e,t),n=C("tensor",r,e,t);return t.enterFrame(o),[Ls(n)]}case"Exit":{let o=C("tensor",r,e,t);return t.exitFrame(),[Ls(o)]}case"NextIteration":{let o=C("tensor",r,e,t);return t.nextIteration(),[Ls(o)]}case"TensorArrayV3":{let o=C("size",r,e,t),n=C("dtype",r,e,t),s=C("elementShape",r,e,t),a=C("dynamicSize",r,e,t),i=C("clearAfterRead",r,e,t),l=C("identicalElementShapes",r,e,t),u=C("name",r,e,t),c=new yk(u,n,o,s,l,a,i);return t.addTensorArray(c),[c.idTensor,le(1)]}case"TensorArrayWriteV3":{let o=C("tensorArrayId",r,e,t),n=C("index",r,e,t),s=C("tensor",r,e,t),a=t.getTensorArray(o.id);return a.write(n,s),[a.idTensor]}case"TensorArrayReadV3":{let o=C("tensorArrayId",r,e,t),n=C("index",r,e,t);return[t.getTensorArray(o.id).read(n)]}case"TensorArrayGatherV3":{let o=C("tensorArrayId",r,e,t),n=C("indices",r,e,t),s=C("dtype",r,e,t);return[t.getTensorArray(o.id).gather(n,s)]}case"TensorArrayScatterV3":{let o=C("tensorArrayId",r,e,t),n=C("indices",r,e,t),s=C("tensor",r,e,t),a=t.getTensorArray(o.id);return a.scatter(n,s),[a.idTensor]}case"TensorArrayConcatV3":{let o=C("tensorArrayId",r,e,t),n=t.getTensorArray(o.id),s=C("dtype",r,e,t);return[n.concat(s)]}case"TensorArraySplitV3":{let o=C("tensorArrayId",r,e,t),n=C("tensor",r,e,t),s=C("lengths",r,e,t),a=t.getTensorArray(o.id);return a.split(s,n),[a.idTensor]}case"TensorArraySizeV3":{let o=C("tensorArrayId",r,e,t),n=t.getTensorArray(o.id);return[le(n.size(),"int32")]}case"TensorArrayCloseV3":{let o=C("tensorArrayId",r,e,t),n=t.getTensorArray(o.id);return n.clearAndClose(),[n.idTensor]}case"TensorListSetItem":{let o=C("tensorListId",r,e,t),n=C("index",r,e,t),s=C("tensor",r,e,t),a=t.getTensorList(o.id);return a.setItem(n,s),[a.idTensor]}case"TensorListGetItem":{let o=C("tensorListId",r,e,t),n=C("index",r,e,t),s=C("elementShape",r,e,t),a=C("elementDType",r,e,t);return[t.getTensorList(o.id).getItem(n,s,a)]}case"TensorListScatterV2":case"TensorListScatter":{let o=C("indices",r,e,t),n=C("tensor",r,e,t),s=C("elementShape",r,e,t),a=C("numElements",r,e,t),i=V1(n,o,s,a);return t.addTensorList(i),[i.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let o=C("elementShape",r,e,t),n=C("elementDType",r,e,t),s;r.op==="TensorListReserve"?s="numElements":s="maxNumElements";let a=C(s,r,e,t),i=B1(o,n,a);return t.addTensorList(i),[i.idTensor]}case"TensorListGather":{let o=C("tensorListId",r,e,t),n=C("indices",r,e,t),s=C("elementShape",r,e,t),a=C("elementDType",r,e,t);return[t.getTensorList(o.id).gather(n,a,s)]}case"TensorListStack":{let o=C("tensorListId",r,e,t),n=C("elementShape",r,e,t),s=C("elementDType",r,e,t),a=C("numElements",r,e,t);return[t.getTensorList(o.id).stack(n,s,a)]}case"TensorListFromTensor":{let o=C("tensor",r,e,t),n=C("elementShape",r,e,t),s=C("elementDType",r,e,t),a=z1(o,n,s);return t.addTensorList(a),[a.idTensor]}case"TensorListConcat":{let o=C("tensorListId",r,e,t),n=t.getTensorList(o.id),s=C("dtype",r,e,t),a=C("elementShape",r,e,t);return[n.concat(s,a)]}case"TensorListPushBack":{let o=C("tensorListId",r,e,t),n=C("tensor",r,e,t),s=t.getTensorList(o.id);return s.pushBack(n),[s.idTensor]}case"TensorListPopBack":{let o=C("tensorListId",r,e,t),n=C("elementShape",r,e,t),s=C("elementDType",r,e,t);return[t.getTensorList(o.id).popBack(n,s)]}case"TensorListSplit":{let o=C("tensor",r,e,t),n=C("elementShape",r,e,t),s=C("lengths",r,e,t),a=G1(o,s,n);return t.addTensorList(a),[a.idTensor]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};function U1(r,e,t){let[o,n]=C("fusedOps",r,e,t),s=o==="biasadd",a=n==="prelu",i=o==="fusedbatchnorm",l=C("numArgs",r,e,t);if(s){if(a&&l!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!a&&l!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(i)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported.");let u=C("strides",r,e,t),c=Dd(r,e,t),p=C("dataFormat",r,e,t).toUpperCase(),m=C("dilations",r,e,t),[f,d]=C("args",r,e,t),h=C("leakyreluAlpha",r,e,t);return{stride:u,pad:c,dataFormat:p,dilations:m,biasArg:f,preluArg:d,activationFunc:n,leakyreluAlpha:h}}var j1=(r,e,t)=>{switch(r.op){case"Conv1D":{let o=C("stride",r,e,t),n=C("pad",r,e,t),s=C("dataFormat",r,e,t).toUpperCase(),a=C("dilation",r,e,t);return[vu(C("x",r,e,t),C("filter",r,e,t),o,n,s,a)]}case"Conv2D":{let o=C("strides",r,e,t),n=Dd(r,e,t),s=C("dataFormat",r,e,t).toUpperCase(),a=C("dilations",r,e,t);return[jr(C("x",r,e,t),C("filter",r,e,t),[o[1],o[2]],n,s,[a[1],a[2]])]}case"_FusedConv2D":{let{stride:o,pad:n,dataFormat:s,dilations:a,biasArg:i,preluArg:l,activationFunc:u,leakyreluAlpha:c}=U1(r,e,t);return[zn.conv2d({x:C("x",r,e,t),filter:C("filter",r,e,t),strides:[o[1],o[2]],pad:n,dataFormat:s,dilations:[a[1],a[2]],bias:i,activation:u,preluActivationWeights:l,leakyreluAlpha:c})]}case"FusedDepthwiseConv2dNative":{let{stride:o,pad:n,dataFormat:s,dilations:a,biasArg:i,preluArg:l,activationFunc:u,leakyreluAlpha:c}=U1(r,e,t);return[zn.depthwiseConv2d({x:C("x",r,e,t),filter:C("filter",r,e,t),strides:[o[1],o[2]],pad:n,dataFormat:s,dilations:[a[1],a[2]],bias:i,activation:u,preluActivationWeights:l,leakyreluAlpha:c})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{let o=C("outputShape",r,e,t),n=C("strides",r,e,t),s=Dd(r,e,t);return[Cu(C("x",r,e,t),C("filter",r,e,t),o,[n[1],n[2]],s)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{let o=C("strides",r,e,t),n=Dd(r,e,t),s=C("dilations",r,e,t),a=C("dataFormat",r,e,t).toUpperCase();return[Cs(C("input",r,e,t),C("filter",r,e,t),[o[1],o[2]],n,a,[s[1],s[2]])]}case"Conv3D":{let o=C("strides",r,e,t),n=C("pad",r,e,t),s=C("dataFormat",r,e,t).toUpperCase(),a=C("dilations",r,e,t);return[Rm(C("x",r,e,t),C("filter",r,e,t),[o[1],o[2],o[3]],n,s,[a[1],a[2],a[3]])]}case"AvgPool":{let o=C("strides",r,e,t),n=C("pad",r,e,t),s=C("kernelSize",r,e,t);return[va(C("x",r,e,t),[s[1],s[2]],[o[1],o[2]],n)]}case"MaxPool":{let o=C("strides",r,e,t),n=C("pad",r,e,t),s=C("kernelSize",r,e,t);return[Ea(C("x",r,e,t),[s[1],s[2]],[o[1],o[2]],n)]}case"MaxPoolWithArgmax":{let o=C("strides",r,e,t),n=C("pad",r,e,t),s=C("kernelSize",r,e,t),a=C("includeBatchInIndex",r,e,t),{result:i,indexes:l}=C_(C("x",r,e,t),[s[1],s[2]],[o[1],o[2]],n,a);return[i,l]}case"AvgPool3D":{let o=C("strides",r,e,t),n=C("pad",r,e,t),s=C("kernelSize",r,e,t);return[Dm(C("x",r,e,t),[s[1],s[2],s[3]],[o[1],o[2],o[3]],n)]}case"MaxPool3D":{let o=C("strides",r,e,t),n=C("pad",r,e,t),s=C("kernelSize",r,e,t);return[Gm(C("x",r,e,t),[s[1],s[2],s[3]],[o[1],o[2],o[3]],n)]}case"Dilation2D":{let o=C("strides",r,e,t),n=C("pad",r,e,t),s=C("dilations",r,e,t),a=o[1],i=o[2],l=s[1],u=s[2];return[Om(C("x",r,e,t),C("filter",r,e,t),[a,i],n,[l,u],"NHWC")]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var H1=(r,e,t)=>{switch(r.op){case"Fill":{let o=C("shape",r,e,t),n=C("dtype",r,e,t),s=C("value",r,e,t);return[Na(o,s,n)]}case"LinSpace":{let o=C("start",r,e,t),n=C("stop",r,e,t),s=C("num",r,e,t);return[y_(o,n,s)]}case"Multinomial":{let o=C("logits",r,e,t),n=C("numSamples",r,e,t),s=C("seed",r,e,t);return[I_(o,n,s)]}case"OneHot":{let o=C("indices",r,e,t),n=C("depth",r,e,t),s=C("onValue",r,e,t),a=C("offValue",r,e,t);return[ks(o,n,s,a)]}case"Ones":return[Cr(C("shape",r,e,t),C("dtype",r,e,t))];case"OnesLike":return[er(C("x",r,e,t))];case"RandomUniform":return[Es(C("shape",r,e,t),C("minval",r,e,t),C("maxval",r,e,t),C("dtype",r,e,t))];case"Range":{let o=C("start",r,e,t),n=C("stop",r,e,t),s=C("step",r,e,t);return[Zc(o,n,s,C("dtype",r,e,t))]}case"TruncatedNormal":{let o=C("shape",r,e,t),n=C("mean",r,e,t),s=C("stdDev",r,e,t),a=C("seed",r,e,t);return[Vu(o,n,s,C("dtype",r,e,t),a)]}case"Zeros":return[gt(C("shape",r,e,t),C("dtype",r,e,t))];case"ZerosLike":return[Ie(C("x",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};function bk(r,e,t){let o=C("boxes",r,e,t),n=C("scores",r,e,t),s=C("maxOutputSize",r,e,t),a=C("iouThreshold",r,e,t),i=C("scoreThreshold",r,e,t),l=C("softNmsSigma",r,e,t);return{boxes:o,scores:n,maxOutputSize:s,iouThreshold:a,scoreThreshold:i,softNmsSigma:l}}var q1=async(r,e,t)=>{switch(r.op){case"NonMaxSuppressionV5":{let{boxes:o,scores:n,maxOutputSize:s,iouThreshold:a,scoreThreshold:i,softNmsSigma:l}=bk(r,e,t),u=await Ds.nonMaxSuppressionWithScoreAsync(o,n,s,a,i,l);return[u.selectedIndices,u.selectedScores]}case"NonMaxSuppressionV4":{let{boxes:o,scores:n,maxOutputSize:s,iouThreshold:a,scoreThreshold:i}=bk(r,e,t),l=C("padToMaxOutputSize",r,e,t),u=await Ds.nonMaxSuppressionPaddedAsync(o,n,s,a,i,l);return[u.selectedIndices,u.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{let{boxes:o,scores:n,maxOutputSize:s,iouThreshold:a,scoreThreshold:i}=bk(r,e,t);return[await Ds.nonMaxSuppressionAsync(o,n,s,a,i)]}case"Where":{let o=oe(C("condition",r,e,t),"bool"),n=[await rf(o)];return o.dispose(),n}case"ListDiff":return O_(C("x",r,e,t),C("y",r,e,t));default:throw TypeError(`Node type ${r.op} is not implemented`)}};var K1=(r,e,t)=>{switch(r.op){case"TopKV2":{let o=C("x",r,e,t),n=C("k",r,e,t),s=C("sorted",r,e,t),a=ef(o,n,s);return[a.values,a.indices]}case"Unique":{let o=C("x",r,e,t),n=Qc(o);return[n.values,n.indices]}case"UniqueV2":{let o=C("x",r,e,t),n=C("axis",r,e,t),s=Qc(o,n);return[s.values,s.indices]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var X1=(r,e,t)=>{switch(r.op){case"Const":return e[r.name];case"PlaceholderWithDefault":let o=C("default",r,e,t);return[hr(r.name,e,t)||o];case"Placeholder":return[hr(r.name,e,t)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let u=C("x",r,e,t);return[Ls(u)]}case"IdentityN":return C("x",r,e,t).map(u=>Ls(u));case"Snapshot":let n=C("x",r,e,t);return[Ls(n)];case"Shape":return[Vt(C("x",r,e,t).shape,"int32")];case"ShapeN":return C("x",r,e,t).map(u=>Vt(u.shape));case"Size":return[le(C("x",r,e,t).size,"int32")];case"Rank":return[le(C("x",r,e,t).rank,"int32")];case"NoOp":return[le(1)];case"Print":let s=C("x",r,e,t),a=C("data",r,e,t),i=C("message",r,e,t),l=C("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 _k=class{constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=le(0),this.tensorMap=new Map,At(this.handle)}get id(){return this.handle.id}clearAndClose(){this.tensorMap.forEach(e=>e.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}async import(e,t){this.checkKeyAndValueTensor(e,t);let o=await e.data();return this.tensorMap.forEach(n=>n.dispose()),this.tensorMap.clear(),V(()=>{let n=ur(t),s=o.length,a=n.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=o[i],u=n[i];At(u),this.tensorMap.set(l,u)}return this.handle})}async find(e,t){this.checkKeyAndValueTensor(e,t);let o=await e.data();return V(()=>{let n=[];for(let s=0;s<o.length;s++){let a=o[s],i=this.findWithDefault(a,t);n.push(i)}return Bt(n)})}findWithDefault(e,t){let o=this.tensorMap.get(e);return o!=null?o: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 Y1=async(r,e,t,o)=>{switch(r.op){case"HashTable":case"HashTableV2":{let n=C("keyDType",r,e,t),s=C("valueDType",r,e,t),a=new _k(n,s);return o.addHashTable(r.name,a),[a.handle]}case"LookupTableImport":case"LookupTableImportV2":{let n=C("tableHandle",r,e,t,o),s=C("keys",r,e,t),a=C("values",r,e,t);return[await o.getHashTableById(n.id).import(s,a)]}case"LookupTableFind":case"LookupTableFindV2":{let n=C("tableHandle",r,e,t,o),s=C("keys",r,e,t),a=C("defaultValue",r,e,t);return[await o.getHashTableById(n.id).find(s,a)]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var Z1=(r,e,t)=>{switch(r.op){case"ResizeBilinear":{let o=C("images",r,e,t),n=C("size",r,e,t),s=C("alignCorners",r,e,t),a=C("halfPixelCenters",r,e,t);return[Ds.resizeBilinear(o,[n[0],n[1]],s,a)]}case"ResizeNearestNeighbor":{let o=C("images",r,e,t),n=C("size",r,e,t),s=C("alignCorners",r,e,t),a=C("halfPixelCenters",r,e,t);return[Ds.resizeNearestNeighbor(o,[n[0],n[1]],s,a)]}case"CropAndResize":{let o=C("image",r,e,t),n=C("boxes",r,e,t),s=C("boxInd",r,e,t),a=C("cropSize",r,e,t),i=C("method",r,e,t),l=C("extrapolationValue",r,e,t);return[Ds.cropAndResize(o,n,s,a,i,l)]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var J1=(r,e,t)=>{switch(r.op){case"Equal":return[_o(C("a",r,e,t),C("b",r,e,t))];case"NotEqual":return[Ln(C("a",r,e,t),C("b",r,e,t))];case"Greater":return[Qt(C("a",r,e,t),C("b",r,e,t))];case"GreaterEqual":return[to(C("a",r,e,t),C("b",r,e,t))];case"Less":return[Tu(C("a",r,e,t),C("b",r,e,t))];case"LessEqual":return[Oo(C("a",r,e,t),C("b",r,e,t))];case"LogicalAnd":return[fr(C("a",r,e,t),C("b",r,e,t))];case"LogicalNot":return[Ta(C("a",r,e,t))];case"LogicalOr":return[Du(C("a",r,e,t),C("b",r,e,t))];case"Select":case"SelectV2":return[Dt(C("condition",r,e,t),C("a",r,e,t),C("b",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var Q1=(r,e,t)=>{switch(r.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[We(C("a",r,e,t),C("b",r,e,t),C("transposeA",r,e,t),C("transposeB",r,e,t))];case"Transpose":return[Ue(C("x",r,e,t),C("perm",r,e,t))];case"_FusedMatMul":let[o,n]=C("fusedOps",r,e,t),s=o==="biasadd",a=n==="prelu",i=C("numArgs",r,e,t),l=C("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]=C("args",r,e,t);return[zn.matMul({a:C("a",r,e,t),b:C("b",r,e,t),transposeA:C("transposeA",r,e,t),transposeB:C("transposeB",r,e,t),bias:u,activation:n,preluActivationWeights:c,leakyreluAlpha:l})];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var eE=(r,e,t)=>{switch(r.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[On(C("x",r,e,t),C("mean",r,e,t),C("variance",r,e,t),C("offset",r,e,t),C("scale",r,e,t),C("epsilon",r,e,t))];case"FusedBatchNormV3":return[On(C("x",r,e,t),C("mean",r,e,t),C("variance",r,e,t),C("offset",r,e,t),C("scale",r,e,t),C("epsilon",r,e,t))];case"LRN":return[zm(C("x",r,e,t),C("radius",r,e,t),C("bias",r,e,t),C("alpha",r,e,t),C("beta",r,e,t))];case"Softmax":return[$a(C("x",r,e,t))];case"LogSoftmax":return[Au(C("x",r,e,t))];case"SparseToDense":return[of(C("sparseIndices",r,e,t),C("outputShape",r,e,t),C("sparseValues",r,e,t),C("defaultValue",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var tE=(r,e,t)=>{switch(r.op){case"Max":{let a=C("axis",r,e,t),i=C("keepDims",r,e,t);return[ar(C("x",r,e,t),a,i)]}case"Mean":{let a=C("axis",r,e,t),i=C("keepDims",r,e,t);return[ht(C("x",r,e,t),a,i)]}case"Min":{let a=C("axis",r,e,t),i=C("keepDims",r,e,t);return[Li(C("x",r,e,t),a,i)]}case"Sum":{let a=C("axis",r,e,t),i=C("keepDims",r,e,t);return[ye(C("x",r,e,t),a,i)]}case"All":{let a=C("axis",r,e,t),i=C("keepDims",r,e,t);return[_u(C("x",r,e,t),a,i)]}case"Any":{let a=C("axis",r,e,t),i=C("keepDims",r,e,t);return[nl(C("x",r,e,t),a,i)]}case"ArgMax":{let a=C("axis",r,e,t);return[sl(C("x",r,e,t),a)]}case"ArgMin":{let a=C("axis",r,e,t);return[Im(C("x",r,e,t),a)]}case"Prod":{let a=C("axis",r,e,t),i=C("keepDims",r,e,t);return[$u(C("x",r,e,t),a,i)]}case"Cumsum":{let a=C("axis",r,e,t),i=C("exclusive",r,e,t),l=C("reverse",r,e,t);return[Nu(C("x",r,e,t),a,i,l)]}case"Bincount":let o=C("x",r,e,t),n=C("weights",r,e,t),s=C("size",r,e,t);return[l_(o,n,s)];case"DenseBincount":{let a=C("x",r,e,t),i=C("weights",r,e,t),l=C("size",r,e,t),u=C("binaryOutput",r,e,t);return[f_(a,i,l,u)]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var rE=(r,e,t)=>{switch(r.op){case"ConcatV2":case"Concat":{let o=C("n",r,e,t),n=C("axis",r,e,t),s=C("tensors",r,e,t);return s=s.slice(0,o),[Je(s,n)]}case"Gather":{let o=C("x",r,e,t),n=C("indices",r,e,t);return[Pn(o,oe(n,"int32"),0)]}case"GatherV2":{let o=C("axis",r,e,t),n=C("batchDims",r,e,t),s=C("x",r,e,t),a=C("indices",r,e,t);return[Pn(s,oe(a,"int32"),o,n)]}case"Reverse":{let o=C("dims",r,e,t),n=[];for(let a=0;a<o.length;a++)o[a]&&n.push(a);let s=C("x",r,e,t);return[qt(s,n)]}case"ReverseV2":{let o=C("axis",r,e,t),n=C("x",r,e,t);return[qt(n,o)]}case"Slice":{let o=C("begin",r,e,t),n=C("size",r,e,t);return[Fe(C("x",r,e,t),o,n)]}case"StridedSlice":{let o=C("begin",r,e,t),n=C("end",r,e,t),s=C("strides",r,e,t),a=C("beginMask",r,e,t),i=C("endMask",r,e,t),l=C("ellipsisMask",r,e,t),u=C("newAxisMask",r,e,t),c=C("shrinkAxisMask",r,e,t),p=C("x",r,e,t);return[Jm(p,o,n,s,a,i,l,u,c)]}case"Pack":return V(()=>{let o=C("axis",r,e,t),n=C("tensors",r,e,t),s=n[0].shape,a=wo(n[0]).shape,i=n.map(l=>{let u=y.arraysEqual(l.shape,s);if(!u&&!y.arraysEqual(wo(l).shape,a))throw new Error("the input tensors shape does not match");return u?l:L(l,s)});return[Bt(i,o)]});case"Unpack":{let o=C("axis",r,e,t),n=C("tensor",r,e,t);return ur(n,o)}case"Tile":{let o=C("reps",r,e,t);return[Fo(C("x",r,e,t),o)]}case"Split":case"SplitV":{let o=C("axis",r,e,t),n=C("numOrSizeSplits",r,e,t),s=C("x",r,e,t);return lr(s,n,o)}case"ScatterNd":{let o=C("indices",r,e,t),n=C("values",r,e,t),s=C("shape",r,e,t);return[L_(o,n,s)]}case"GatherNd":{let o=C("x",r,e,t),n=C("indices",r,e,t);return[z_(o,n)]}case"SparseToDense":{let o=C("sparseIndices",r,e,t),n=C("outputShape",r,e,t),s=C("sparseValues",r,e,t),a=C("defaultValue",r,e,t);return[of(o,s,n,s.dtype===a.dtype?a:oe(a,s.dtype))]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var oE=(r,e,t)=>{switch(r.op){case"FFT":return[Ra(C("x",r,e,t))];case"IFFT":return[zi(C("x",r,e,t))];case"RFFT":return[Fa(C("x",r,e,t))];case"IRFFT":return[zu(C("x",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var nE=(r,e,t)=>{switch(r.op){case"Cast":return[oe(C("x",r,e,t),C("dtype",r,e,t))];case"ExpandDims":{let o=C("axis",r,e,t);return[sr(C("x",r,e,t),o)]}case"Squeeze":{let o=C("axis",r,e,t);return[wo(C("x",r,e,t),o)]}case"Reshape":return[L(C("x",r,e,t),C("shape",r,e,t))];case"MirrorPad":return[Wm(C("x",r,e,t),C("padding",r,e,t),C("mode",r,e,t))];case"PadV2":case"Pad":return[$r(C("x",r,e,t),C("padding",r,e,t),C("constantValue",r,e,t))];case"SpaceToBatchND":{let o=C("blockShape",r,e,t),n=C("paddings",r,e,t);return[Aa(C("x",r,e,t),o,n)]}case"BatchToSpaceND":{let o=C("blockShape",r,e,t),n=C("crops",r,e,t);return[Ca(C("x",r,e,t),o,n)]}case"DepthToSpace":{let o=C("blockSize",r,e,t),n=C("dataFormat",r,e,t).toUpperCase();return[Fm(C("x",r,e,t),o,n)]}case"BroadcastTo":return[il(C("x",r,e,t),C("shape",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};function wk(r,e,t,o){let n=((s,a,i)=>{switch(s.category){case"arithmetic":return V(()=>M1(s,a,i));case"basic_math":return V(()=>L1(s,a,i));case"control":return W1(s,a,i);case"convolution":return V(()=>j1(s,a,i));case"creation":return V(()=>H1(s,a,i));case"dynamic":return q1(s,a,i);case"evaluation":return V(()=>K1(s,a,i));case"image":return V(()=>Z1(s,a,i));case"graph":return V(()=>X1(s,a,i));case"logical":return V(()=>J1(s,a,i));case"matrices":return V(()=>Q1(s,a,i));case"normalization":return V(()=>eE(s,a,i));case"reduction":return V(()=>tE(s,a,i));case"slice_join":return V(()=>rE(s,a,i));case"spectral":return V(()=>oE(s,a,i));case"transformation":return V(()=>nE(s,a,i));case"hash_table":return Y1(s,a,i,o);case"custom":let l=Qg(s.op);if(l&&l.customExecutor)return l.customExecutor(new xk(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(n)?n.then(s=>[].concat(s)):[].concat(n)}var mx=class{constructor(e={},t={},o={},n={}){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=o,this.functionMap=n,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){let e=[];for(let t=0;t<this.contexts.length-1;t++){let o=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(o))}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 vk(r,e,t,o){let n=new Set,s=[],a=null,i=null,l=new Set,u=Object.keys(r).map(m=>Zr(m)[0]),c=[];o!=null&&(c=o.map(m=>Zr(m.name)[0]));let p=[...e];for(;p.length>0;){let m=p.pop();if((kk(m)||I6(m)||N6(m))&&a==null&&(a=m,i=a.children.map(f=>f.name).filter(f=>n.has(f))),n.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:n,missingInputs:s,dynamicNode:a,syncInputs:i}}function sE(r,e,t){let{usedNodes:o,inputs:n}=t,s=[],a=Object.keys(n).map(c=>Zr(c)[0]).map(c=>r.nodes[c]),i=r.initNodes;a.forEach(c=>{o.has(c.name)&&s.push(c)}),r.weights.forEach(c=>{o.has(c.name)&&s.push(c)}),i!=null&&i.forEach(c=>{o.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)&&o.has(p.name)&&p.inputs.every(m=>l.has(m.name))&&s.push(p)})}return u}var S6=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],T6=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],E6=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2"];function kk(r){return S6.indexOf(r.op)>=0}function I6(r){return T6.indexOf(r.op)>=0}function N6(r){return E6.indexOf(r.op)>=0}var Dp=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(o=>{this._functionExecutorMap[o]=new Dp(e.functions[o],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(o=>e[o].map(n=>n.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 o=e.map(s=>s.name).sort(),n=t.map(s=>s.name).sort();return o.join(this.SEPERATOR)+"--"+n.join(this.SEPERATOR)}compile(e,t){let o=vk(e,t,this.weightMap,this._initNodes),{missingInputs:n,dynamicNode:s,syncInputs:a}=o;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(n.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: [${n}]`)}return sE(this.graph,this.weightMap,o)}execute(e,t){e=this.mapInputs(e);let o=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);let n=o.map(p=>this.graph.nodes[Zr(p)[0]]),s=t.map(p=>Zr(p)[0]),a=s.map(p=>this.graph.nodes[p]);a.length===0&&(a=this._outputs);let i=this.getCompilationKey(n,a),l=this.compiledMap.get(i);l==null&&(l=this.compile(e,a),this.compiledMap.set(i,l));let u={},c={};return V(()=>{let p=new mx(this.weightMap,u,c,this.functionExecutorMap),m=Object.assign({},this.weightMap);Object.keys(e).forEach(h=>{let[g,x]=Zr(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=wk(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=>hr(h,m,p))})}getFrozenTensorIds(e){let t=[].concat.apply([],Object.keys(e).map(o=>e[o]).map(o=>o.map(n=>n.id)));return new Set(t)}checkTensorForDisposal(e,t,o,n,s,a,i){t.category==="control"||a.indexOf(e)!==-1||(o[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=R1(l.name,o,n);u!=null&&u.forEach(c=>{if(c&&!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,o=!1,n={},s={}){o||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));let a=new mx(this.weightMap,n,s,this.functionExecutorMap),i=await this.executeWithControlFlow(e,a,t,o),l=t.map(m=>hr(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.isDisposed&&!p.has(d.id)&&d.dispose()})}),this.parent==null&&a.dispose(p),l}async executeFunctionAsync(e,t,o){let n=e.reduce((s,a,i)=>(s[this.inputs[i].name]=a,s),{});return this._executeAsync(n,this.outputNodes,!0,t,o)}async executeWithControlFlow(e,t,o,n){let s=Object.keys(e),a=s.map(_=>this.graph.nodes[Zr(_)[0]]),i=o.map(_=>Zr(_)[0]),l=i.map(_=>this.graph.nodes[_]);l.length===0&&(l=this._outputs);let{usedNodes:u,missingInputs:c,dynamicNode:p,syncInputs:m}=vk(e,l,this.weightMap,this._initNodes),f=[...a,...this.graph.weights,...this._initNodes||[]].map(_=>({node:_,contexts:t.currentContext})),d=Object.assign({},this.weightMap);Object.keys(e).forEach(_=>{let[w,v]=Zr(_),$=[];$[v]=e[_],d[w]=$});let h={},g=this.getFrozenTensorIds(d),x={};for(;f.length>0;){let _=this.processStack(a,f,t,d,x,g,i,h,u);await Promise.all(_)}p==null&&!n&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");let b=l.filter(_=>!kk(_)&&!hr(_.name,d,t)).map(_=>_.name);if(b.length>0){let _="";throw p!=null&&(_=`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}]. ${_}`)}return d}processStack(e,t,o,n,s,a,i,l,u){let c=[];for(;t.length>0;){let p=t.pop();o.currentContext=p.contexts;let m="";if(p.node.op==="Enter"&&C("isConstant",p.node,n,o)&&([m]=Ms(p.node.name,o)),n[p.node.name]==null){let f=wk(p.node,n,o,this._resourceManager);m||([m]=Ms(p.node.name,o));let d=o.currentContext;y.isPromise(f)?c.push(f.then(h=>(n[m]=h,o.currentContext=d,this.checkTensorForDisposal(m,p.node,n,o,a,i,l),this.processChildNodes(p.node,t,o,n,s,u),h))):(n[m]=f,this.checkTensorForDisposal(m,p.node,n,o,a,i,l),this.processChildNodes(p.node,t,o,n,s,u))}else this.processChildNodes(p.node,t,o,n,s,u)}return c}processChildNodes(e,t,o,n,s,a){e.children.forEach(i=>{let[l]=Ms(i.name,o);s[l]||!a.has(i.name)||(i.op==="Merge"?i.inputNames.some(u=>!!hr(u,n,o))&&(s[l]=!0,t.push({contexts:o.currentContext,node:i})):i.inputNames.every(u=>!!hr(u,n,o))&&(s[l]=!0,t.push({contexts:o.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 o=e[t],[n]=Zr(t),s=this.graph.nodes[n];if(s.attrParams.shape&&s.attrParams.shape.value){let a=s.attrParams.shape.value,i=a.length===o.shape.length&&o.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 [${o.shape}]`)}s.attrParams.dtype&&s.attrParams.dtype.value&&y.assert(o.dtype===s.attrParams.dtype.value,()=>`The dtype of dict['${s.name}'] provided in model.execute(dict) must be ${s.attrParams.dtype.value}, but was ${o.dtype}`)})}mapInputs(e){let t={};for(let o in e)if(this._signature!=null&&this._signature.inputs!=null&&this._signature.inputs[o]!=null){let n=this._signature.inputs[o];t[n.name]=e[o]}else t[o]=e[o];return t}checkInputs(e){let t=Object.keys(e).filter(o=>{let[n]=Zr(o);return this.graph.nodes[n]==null});if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map(t=>this._signature!=null&&this._signature.outputs!=null&&this._signature.outputs[t]!=null?this._signature.outputs[t].name:t,{})}checkOutputs(e){e.forEach(t=>{let[o]=Zr(t);if(!this.graph.nodes[o])throw new Error(`The output '${t}' is not found in the graph`)})}};var Ck=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 A6="?tfjs-format=file",D6="model.json",fx=class{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={}),this.resourceManager=new Ck}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=vr.browserHTTPRequest(e,this.loadOptions);else{let t=vr.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(vr.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,o;this.artifacts.userDefinedMetadata!=null&&this.artifacts.userDefinedMetadata.signature!=null?o=this.artifacts.userDefinedMetadata.signature:o=this.artifacts.signature,this.signature=o,this.version=`${t.versions.producer}.${t.versions.minConsumer}`;let n=vr.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new Dp(tx.Instance.transformGraph(t,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(n),this.executor.resourceManager=this.resourceManager,e.modelInitializer!=null&&e.modelInitializer.node!=null){let s=tx.Instance.transformGraph(e.modelInitializer);this.initializer=new Dp(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 o=vr.getSaveHandlers(e);if(o.length===0)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(o.length>1)throw new Error(`Found more than one (${o.length}) save handlers for URL '${e}'`);e=o[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 Ve)&&!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,o,n)=>(t[o]=e[n],t),{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}execute(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let o=this.executor.execute(e,t);return o.length>1?o:o[0]}async executeAsync(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let o=await this.executor.executeAsync(e,t);return o.length>1?o:o[0]}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,o)=>(t[o]=[e[o]],t),{})}dispose(){this.executor.dispose(),this.initializer&&this.initializer.dispose(),this.resourceManager.dispose()}};async function iE(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}${D6}${A6}`);let t=new fx(r,e);return await t.load(),t}var dx="3.0.0";var $k={};et($k,{CSVDataset:()=>Pd,Dataset:()=>qi,FileDataSource:()=>Vd,TextLineDataset:()=>Fd,URLDataSource:()=>Gd,array:()=>TE,csv:()=>LE,func:()=>zE,generator:()=>BE,microphone:()=>GE,version_data:()=>wx,webcam:()=>VE,zip:()=>EE});var SE=Sc(jm());var mE=Sc(jm());function aE(r,e){return hx(r,e)}function hx(r,e,t=new Map,o=new Set){if(r==null)return null;if(o.has(r))throw new Error("Circular references are not supported.");if(t.has(r))return t.get(r);let n=e(r);if(n.recurse&&n.value!==null)throw new Error("A deep map function may not return both a value and recurse=true.");if(n.recurse)if(kl(r)){let s=Array.isArray(r)?[]:{};o.add(r);for(let a in r){let i=r[a],l=hx(i,e,t,o);s[a]=l}return o.delete(r),s}else throw new Error(`Can't recurse into non-iterable type: ${r}`);else return t.set(r,n.value),n.value}function uE(r,e=Ik){return lE(r,e)}function lE(r,e,t=new Set){let o=r[0];if(t.has(o))throw new Error("Circular references are not supported.");let n=e(r);if(n.recurse&&n.value!==null)throw new Error("A deep zip function may not return both a value and recurse=true.");if(n.recurse)if(kl(o)){let s=Array.isArray(o)?[]:{};t.add(o);for(let a in o){let i=r.map(u=>u[a]),l=lE(i,e,t);s[a]=l}return t.delete(o),s}else throw new Error(`Can't recurse into non-iterable type: ${o}`);else return n.value}function Ik(r){return r===null?null:kl(r[0])?{value:null,recurse:!0}:{value:r,recurse:!1}}async function gx(r,e){let t=new Map;hx(r,e,t);for(let n of Array.from(t.keys())){let s=t.get(n);if(y.isPromise(s)){let a=await s;t.set(n,a)}}return hx(r,e,t)}function kl(r){return r!=null&&!ArrayBuffer.isView(r)&&(Array.isArray(r)||typeof r=="object"&&!(r instanceof Ve))}function cE(r){return r==null||$6(r)||Array.isArray(r)||typeof r=="object"&&r instanceof Ve||y.isTypedArray(r)}function $6(r){return r===null||typeof r!="object"&&typeof r!="function"}function pE(r){return aE(r,R6)}function R6(r){return r instanceof Ve?{value:r.clone(),recurse:!1}:kl(r)?{value:null,recurse:!0}:{value:r,recurse:!1}}var $d=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),o=this.get(t);return this.set(t,this.pop()),o}};var $p=class extends $d{constructor(){super($p.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),o=this.length();for(let n=0;n<o;n++)t[n]=this.get(this.wrap(this.begin+n));this.data=t,this.capacity=e,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=o}};$p.INITIAL_CAPACITY=32;function Nk(r){return new fE(r)}function Rd(r){return new dE(r)}function hE(r,e){return new Sk(r,e)}function xE(r,e=Va.FAIL){return new gE(r,e)}var Kt=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=[],o=await e.next();for(;!o.done;)t.push(o.value),o=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(),o=e(t.value);for(;!t.done&&o;)t=await this.next(),o=e(t.value)}handleErrors(e){return new CE(this,e)}filter(e){return new kE(this,e)}map(e){return new vE(this,e)}mapAsync(e){return new Tk(this,e)}serialMapAsync(e){return new Tk(this,e).serial()}flatmap(e){return new IE(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 wE(this,e,t)}columnMajorBatch(e,t=!0,o=Ik){return this.rowMajorBatch(e,t).map(s=>uE(s,o))}concatenate(e,t){return new Sk(Nk([this,e]),t)}take(e){return e<0||e==null?this:new _E(this,e)}skip(e){return e<0||e==null?this:new bE(this,e)}prefetch(e){return new Ek(this,e)}shuffle(e,t){return new NE(this,e,t)}serial(){return new yE(this)}},fE=class extends Kt{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:pE(e),done:!1}}},dE=class extends Kt{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}}},yE=class extends Kt{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()}},bE=class extends Kt{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;Te(e.value)}return this.upstream.next()}},_E=class extends Kt{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()}},wE=class extends Kt{constructor(e,t,o=!0){super();this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=o,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}}},kE=class extends Kt{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;Te(e.value)}}},vE=class extends Kt{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=Fn.getTensorsInContainer(e.value),o=this.transform(e.value),n=Fn.getTensorsInContainer(o);for(let s of t)Fn.isTensorInList(s,n)||s.dispose();return{value:o,done:!1}}},CE=class extends Kt{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}}}},Tk=class extends Kt{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=Fn.getTensorsInContainer(e.value),o=await this.transform(e.value),n=Fn.getTensorsInContainer(o);for(let s of t)Fn.isTensorInList(s,n)||s.dispose();return{value:o,done:!1}}},Rp=class extends Kt{constructor(){super();this.outputQueue=new $p,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}}},IE=class extends Rp{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=Fn.getTensorsInContainer(e.value),o=this.transform(e.value),n=Fn.getTensorsInContainer(o);this.outputQueue.pushAll(o);for(let s of t)Fn.isTensorInList(s,n)||s.dispose();return!0}},Sk=class extends Kt{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 o=await this.moreIterators.next();if(o.done)return{value:null,done:!0};this.iterator=o.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}},Va;(function(r){r[r.FAIL=0]="FAIL",r[r.SHORTEST=1]="SHORTEST",r[r.LONGEST=2]="LONGEST"})(Va||(Va={}));var gE=class extends Kt{constructor(e,t=Va.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,o=0;function n(a){return a instanceof Kt?{value:a.next().then(l=>(t++,l.done&&o++,l.value)),recurse:!1}:{value:null,recurse:!0}}let s=await gx(this.iterators,n);if(t===o)return{value:null,done:!0};if(o>0)switch(this.mismatchMode){case Va.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case Va.SHORTEST:return{value:null,done:!0};case Va.LONGEST:default:}return this.count++,{value:s,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}},Ek=class extends Kt{constructor(e,t){super();this.upstream=e,this.bufferSize=t,this.buffer=new $d(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()}},NE=class extends Ek{constructor(e,t,o){super(e,t);this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=mE.alea(o||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 qi=class{constructor(){this.size=null}batch(e,t=!0){let o=this;y.assert(e>0,()=>`batchSize needs to be positive, but it is
|
|
${e}`);let n;return this.size===Infinity||this.size==null?n=this.size:t?n=Math.ceil(this.size/e):n=Math.floor(this.size/e),lo(async()=>(await o.iterator()).columnMajorBatch(e,t,F6),n)}concatenate(e){let t=this,o;return this.size===Infinity||e.size===Infinity?o=Infinity:this.size!=null&&e.size!=null?o=this.size+e.size:o=null,lo(async()=>(await t.iterator()).concatenate(await e.iterator()),o)}filter(e){let t=this,o;return this.size===Infinity?o=Infinity:o=null,lo(async()=>(await t.iterator()).filter(n=>V(()=>e(n))),o)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){let t=this;return lo(async()=>(await t.iterator()).map(o=>V(()=>e(o))),this.size)}mapAsync(e){let t=this;return lo(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 lo(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){let t=this,o;return this.size!=null&&e>0?o=this.size*e:e===0?o=0:this.size!=null&&(e===void 0||e<0)?o=Infinity:o=null,lo(async()=>{let n=Rd(async()=>({value:await t.iterator(),done:!1}));return hE(n.take(e))},o)}skip(e){let t=this,o;return this.size!=null&&e>=0&&this.size>=e?o=this.size-e:this.size!=null&&(this.size<e||e===void 0||e<0)?o=0:o=null,lo(async()=>(await t.iterator()).skip(e),o)}shuffle(e,t,o=!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 n=this,s=SE.alea(t||y.now().toString());return lo(async()=>{let a=s.int32();return o&&(a+=s.int32()),(await n.iterator()).shuffle(e,a.toString())},this.size)}take(e){let t=this,o;return this.size!=null&&this.size>e?o=e:this.size!=null&&this.size<=e?o=this.size:o=null,lo(async()=>(await t.iterator()).take(e),o)}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()}};qi.MAX_BUFFER_SIZE=1e4;function lo(r,e=null){return new class extends qi{constructor(){super(...arguments);this.size=e}async iterator(){return r()}}}function TE(r){return lo(async()=>Nk(r),r.length)}function EE(r){if(!kl(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 lo(async()=>{let t=await gx(r,o=>{if(o instanceof qi)return{value:o.iterator(),recurse:!1};if(kl(o))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return xE(t,Va.SHORTEST)},e)}function F6(r){if(r===null)return null;let e=r[0];return cE(e)?{value:O6(r),recurse:!1}:{value:null,recurse:!0}}function O6(r){if(r.length===0)throw new Error("Can't make a batch of zero elements.");return r[0]instanceof Ve?Bt(r):Dr(r)}var Fd=class extends qi{constructor(e){super();this.input=e}async iterator(){return(await this.input.iterator()).decodeUTF8().split(`
|
|
`).map(n=>(n.endsWith("\r")&&(n=n.slice(0,-1)),n))}};var xx='"',Od=Symbol("out"),AE=Symbol("field"),yx=Symbol("quote"),Ak=Symbol("quoteafterquote"),DE=Symbol("quoteinquote"),Pd=class extends qi{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 Fd(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((n,s)=>(n[s]=n[s]+1||1,n),{}),o=Object.keys(t).filter(n=>t[n]>1);if(y.assert(o.length===0,()=>"Duplicate column names found: "+o.toString()),this.columnConfigs){for(let n of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(n)===-1)throw new Error('The key "'+n+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){let t=await(await this.base.iterator()).next();if(t.done)throw new Error("No data was found for CSV parsing.");let o=t.value;return this.parseRow(o,!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),o={},n={};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?n[a]=u:o[a]=u}}return Object.keys(n).length===0?o:{xs:o,ys:n}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){let o=[],n=0,s=e.length,a=Od;for(let i=0;i<s;i++)switch(a){case Od:switch(e.charAt(i)){case xx:n=i+1,a=yx;break;case this.delimiter:if(n=i+1,this.delimiter===" "&&this.delimWhitespace)break;o.push(""),a=Od;break;default:a=AE,n=i;break}break;case AE:switch(e.charAt(i)){case this.delimiter:o.push(e.substring(n,i)),a=Od,n=i+1;break;default:}break;case yx:switch(e.charAt(i)){case xx:a=Ak;break;default:}break;case Ak:switch(e.charAt(i)){case this.delimiter:o.push(e.substring(n,i-1)),a=Od,n=i+1;break;case xx:a=yx;break;default:a=DE;break}break;case DE:switch(e.charAt(i)){case xx:a=yx;break;default:}break;default:}if(a===Ak?o.push(e.substring(n,s-1)):o.push(e.substring(n)),t&&o.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${o}`);return o}};var Md=class extends Kt{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(G().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");let t=new Md(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(o){throw new Error(`Error thrown while initializing video stream: ${o.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,o=await this.getAudioData();if(this.includeSpectrogram){let n=this.flattenQueue(o.freqDataQueue);e=this.getTensorFromAudioDataArray(n,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){let n=this.flattenQueue(o.timeDataQueue);t=this.getTensorFromAudioDataArray(n,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:e,waveform:t},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){let e=[],t=[],o=0;return new Promise(n=>{let s=setInterval(()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-Infinity&&n({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++o===this.numFrames&&(clearInterval(s),n({freqDataQueue:e,timeDataQueue:t}))},this.fftSize/this.sampleRateHz*1e3)})}stop(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),this.stream!=null&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())}toArray(){throw new Error("Can not convert infinite audio stream to array.")}getSampleRate(){return this.sampleRateHz}flattenQueue(e){let t=e[0].length,o=new Float32Array(e.length*t);return e.forEach((n,s)=>o.set(n,s*t)),o}getTensorFromAudioDataArray(e,t){let o=new Float32Array(y.sizeFromShape(t));return o.set(e,o.length-e.length),Dr(o,t)}};var Ld=class extends Kt{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=Vt([0],"int32"),this.webcamConfig.centerCrop){let o=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,n=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,s=(1-o)/2,a=(1-n)/2,i=s+o,l=n+a;this.cropBox=Bi([a,s,l,i],[1,4])}else this.cropBox=Bi([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(G().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 o=new Ld(e,t);return await o.start(),o}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=Yh.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 V(()=>{let t=sr(oe(e,"float32"),0),o;o=Ds.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let n=o.shape;return L(o,n.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 zd=class{};var bx=class extends Kt{split(e){return new $E(this,e)}},$E=class extends bx{constructor(e,t){super();this.upstream=e,this.impl=new RE(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},RE=class extends Rp{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 o of t.slice(0,-1))this.outputQueue.push(o);return this.carryover=t[t.length-1],!0}};var Dk=class extends Kt{decodeUTF8(){return new OE(this)}},OE=class extends bx{constructor(e){super();this.upstream=e,this.impl=new PE(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},PE=class extends Rp{constructor(e){super();if(this.upstream=e,G().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:t}=FE();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 o;return G().get("IS_BROWSER")?o=this.decoder.decode(t,{stream:!0}):o=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(o),!0}};var Bd=class extends Dk{constructor(e,t={}){super();this.file=e,this.options=t,y.assert(e instanceof Uint8Array||(G().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,o)=>{let n=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)t(new Uint8Array(this.file.slice(this.offset,n)));else{let s=new FileReader;s.onload=i=>{let l=s.result;if(l instanceof ArrayBuffer&&(l=new Uint8Array(l)),!(l instanceof Uint8Array))return o(new TypeError("FileReader returned unknown type."));t(l)},s.onabort=i=>o(new Error("Aborted")),s.onerror=i=>o(new Error(i.type));let a=this.file.slice(this.offset,n);s.readAsArrayBuffer(a)}this.offset=n}),done:!1}}};async function ME(r,e={}){let t,o;typeof r=="string"?t=r:(t=r.url,o=P6(r));let n=await y.fetch(t,o);if(n.ok){let s=new Uint8Array(await n.arrayBuffer());return new Bd(s,e)}else throw new Error(n.statusText)}var P6=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 _x(r){return typeof r=="string"&&r.substr(0,7)==="file://"}var Vd=class extends zd{constructor(e,t={}){super();this.input=e,this.options=t}async iterator(){if(_x(this.input)&&G().get("IS_NODE")){let e=require("fs");this.input=e.readFileSync(this.input.substr(7))}return new Bd(this.input,this.options)}};var Gd=class extends zd{constructor(e,t={}){super();this.url=e,this.fileOptions=t}async iterator(){return _x(this.url)?new Vd(this.url,this.fileOptions).iterator():ME(this.url,this.fileOptions)}};function LE(r,e={}){return new Pd(new Gd(r),e)}function zE(r){let e=Rd(r);return lo(async()=>e)}function BE(r){return lo(async()=>{let e=await r();return Rd(()=>e.next())})}async function VE(r,e){return Ld.create(r,e)}async function GE(r){return Md.create(r)}var wx="3.0.0";function ee(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 M6=Sr.whereImpl,Rk=class extends Ws{constructor(){super();this.blockSize=48,this.firstUse=!0,this.data=new Ya(this,vs())}write(e,t,o){this.firstUse&&(this.firstUse=!1,G().get("IS_NODE")&&N.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 n={};return this.data.set(n,{values:e,dtype:o,refCount:1}),n}makeTensorInfo(e,t,o){let n;if(t==="string"&&o!=null&&o.length>0&&y.isString(o[0])){let s=o.map(a=>y.encodeString(a));n=this.write(s,e,t)}else n=this.write(o,e,t);return{dataId:n,shape:e,dtype:t}}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,o,n){this.data.set(e,{values:t,dtype:n,refCount:1})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){let{dtype:t,complexTensorInfos:o}=this.data.get(e);if(t==="complex64"){let n=this.readSync(o.real.dataId),s=this.readSync(o.imag.dataId);return N.mergeRealAndImagArrays(n,s)}return this.data.get(e).values}bufferSync(e){let t=this.readSync(e.dataId),o=t;if(e.dtype==="string")try{o=t.map(n=>y.decodeString(n))}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return Ce(e.shape,e.dtype,o)}makeOutput(e,t,o){let n=this.write(e,t,o);return vs().makeTensorFromDataId(n,t,o,this)}disposeData(e){if(this.data.has(e)){let{complexTensorInfos:t}=this.data.get(e);t!=null&&(this.disposeData(t.real.dataId),this.disposeData(t.imag.dataId)),this.data.delete(e)}}disposeIntermediateTensorInfo(e){let t=e.dataId;if(this.data.has(t)){let o=this.data.get(t);o.refCount--,o.refCount<1&&this.disposeData(t)}}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){ee([e],"where");let t=this.readSync(e.dataId);return M6(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};var Wk={};et(Wk,{addImpl:()=>XE,bincountImpl:()=>Wd,bincountReduceImpl:()=>Fk,ceilImpl:()=>ZE,concatImpl:()=>Ud,expImpl:()=>QE,expm1Impl:()=>tA,floorImpl:()=>oA,gatherV2Impl:()=>Pk,greaterImpl:()=>sA,lessImpl:()=>aA,linSpaceImpl:()=>Mk,logImpl:()=>uA,maxImpl:()=>Lk,maximumImpl:()=>pA,minimumImpl:()=>fA,multiplyImpl:()=>kx,negImpl:()=>gA,notEqualImpl:()=>yA,prodImpl:()=>wA,rangeImpl:()=>qd,rsqrtImpl:()=>vA,simpleAbsImpl:()=>WE,sliceImpl:()=>Kd,squaredDifferenceImpl:()=>NA,stridedSliceImpl:()=>zk,subImpl:()=>TA,tileImpl:()=>Bk,topKImpl:()=>Vk,transposeImpl:()=>Hd,uniqueImpl:()=>Gk});function WE(r){let e=new Float32Array(r.length);for(let t=0;t<r.length;++t)e[t]=Math.abs(r[t]);return e}var L6=r=>{let{x:e}=r.inputs,t=r.backend;ee(e,"abs");let o=new Float32Array(y.sizeFromShape(e.shape)),n=t.data.get(e.dataId).values;return o=WE(n),t.makeOutput(o,e.shape,"float32")},UE={kernelName:ss,backendName:"cpu",kernelFunc:L6};function Ye(r){return(e,t,o,n,s)=>{let a=N.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=N.getBroadcastDims(e,a),g=N.getBroadcastDims(t,a);if(h.length+g.length===0)for(let x=0;x<c.length;++x)c[x]=r(o[x%o.length],n[x%n.length]);else for(let x=0;x<c.length;++x){let b=y.indexToLoc(x,i,l),_=b.slice(-p);h.forEach(A=>_[A]=0);let w=y.locToIndex(_,p,f),v=b.slice(-m);g.forEach(A=>v[A]=0);let $=y.locToIndex(v,m,d);c[x]=r(o[w],n[$])}return[c,a]}}function cr(r){let{inputs:e,backend:t}=r,{real:o,imag:n}=e,s=t.data.get(o.dataId).values,a=t.data.get(n.dataId).values,i=t.makeTensorInfo(o.shape,"complex64"),l=t.data.get(i.dataId);return l.complexTensorInfos={real:t.makeTensorInfo(o.shape,"float32",s),imag:t.makeTensorInfo(n.shape,"float32",a)},i}var jE={kernelName:Hl,backendName:"cpu",kernelFunc:cr};function Fp(r,e,t="float32"){if(t==="complex64"){let n=Fp(r,e,"float32"),s=Fp(r,e,"float32");return cr({inputs:{real:n,imag:s},backend:r})}let o=y.makeZerosTypedArray(y.sizeFromShape(e),t);return r.makeTensorInfo(e,t,o)}function Tr(r){let{inputs:e,backend:t}=r,{x:o}=e;return t.incRef(o.dataId),{dataId:o.dataId,shape:o.shape,dtype:o.dtype}}var HE={kernelName:us,backendName:"cpu",kernelFunc:Tr};function Kn(r){let{inputs:e,backend:t}=r,{input:o}=e,n=t.data.get(o.dataId).complexTensorInfos.real,s=t.data.get(n.dataId).values;return t.makeTensorInfo(n.shape,n.dtype,s)}var qE={kernelName:cu,backendName:"cpu",kernelFunc:Kn};function Xn(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{dtype:s}=o;if(s==="complex64"){if(n.dtype==="complex64")return Tr({inputs:{x:n},backend:t});let a=Fp(t,n.shape,n.dtype),i=Xn({inputs:{x:n},backend:t,attrs:{dtype:"float32"}}),l=cr({inputs:{real:i,imag:a},backend:t});return t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),l}if(n.dtype==="complex64"){let a=Kn({inputs:{input:n},backend:t}),i=Xn({inputs:{x:a},backend:t,attrs:{dtype:s}});return t.disposeIntermediateTensorInfo(a),i}if(!y.hasEncodingLoss(n.dtype,s)){let a=Tr({inputs:{x:n},backend:t});return{dataId:a.dataId,shape:a.shape,dtype:s}}if(s==="int32"){let a=t.data.get(n.dataId).values,i=Int32Array.from(a);return t.makeTensorInfo(n.shape,"int32",i)}if(s==="bool"){let a=t.data.get(n.dataId).values,i=y.toTypedArray([0],n.dtype),[l,u]=Ye((c,p)=>c!==p?1:0)(n.shape,[],a,i,"bool");return t.makeTensorInfo(u,"bool",l)}throw new Error(`Error in Cast: failed to cast ${n.dtype} to ${s}`)}var KE={kernelName:Eo,backendName:"cpu",kernelFunc:Xn};function ot(r,e,t,o){return t==null?({inputs:n,backend:s})=>{let{a,b:i}=n,l=s;ee([a,i],r);let u=l.data.get(a.dataId).values,c=l.data.get(i.dataId).values,p=o||a.dtype,[m,f]=e(a.shape,i.shape,u,c,p);return l.makeTensorInfo(f,p,m)}:({inputs:n,backend:s})=>{let{a,b:i}=n,l=s;if(a.dtype==="complex64"||i.dtype==="complex64"){let u=Xn({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=Xn({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(h.dataId),x=g.complexTensorInfos.real,b=g.complexTensorInfos.imag,_=l.data.get(x.dataId).values,w=l.data.get(b.dataId).values,[v,$,A]=t(a.shape,i.shape,f,d,_,w),R=l.makeTensorInfo(A,"float32",v),M=l.makeTensorInfo(A,"float32",$),z=cr({inputs:{real:R,imag:M},backend:l});return l.disposeIntermediateTensorInfo(u),l.disposeIntermediateTensorInfo(h),l.disposeIntermediateTensorInfo(R),l.disposeIntermediateTensorInfo(M),z}else{let u=l.data.get(a.dataId).values,c=l.data.get(i.dataId).values,p=o||a.dtype,[m,f]=e(a.shape,i.shape,u,c,p);return l.makeTensorInfo(f,p,m)}}}function Op(r){return(e,t,o,n,s,a)=>{let i=N.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=N.getBroadcastDims(e,i),d=N.getBroadcastDims(t,i),h=N.mergeRealAndImagArrays(o,n),g=N.mergeRealAndImagArrays(s,a),x=e.length,b=y.computeStrides(e),_=t.length,w=y.computeStrides(t);if(f.length+d.length===0)for(let v=0;v<p.length;v++){let $=v%h.length,A=v%g.length,R=r(h[$*2],h[$*2+1],g[A*2],g[A*2+1]);p[v]=R.real,m[v]=R.imag}else for(let v=0;v<p.length;v++){let $=y.indexToLoc(v,u,c),A=$.slice(-x);f.forEach(U=>A[U]=0);let R=y.locToIndex(A,x,b),M=$.slice(-_);d.forEach(U=>M[U]=0);let z=y.locToIndex(M,_,w),W=r(h[R*2],h[R*2+1],g[z*2],g[z*2+1]);p[v]=W.real,m[v]=W.imag}return[p,m,i]}}var XE=Ye((r,e)=>r+e),z6=Op((r,e,t,o)=>({real:r+t,imag:e+o})),Ga=ot(xo,XE,z6),YE={kernelName:xo,backendName:"cpu",kernelFunc:Ga};function Wd(r,e,t,o,n){let s=y.sizeFromShape(o),a=y.makeZerosTypedArray(n,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>=n||(s>0?a[l]+=e[i]:a[l]+=1)}return a}function Fk(r,e,t,o=!1){let n=r.shape[0],s=r.shape[1],a=Ce([n,t],e.dtype);for(let i=0;i<n;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||(o?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 Yn(r){return(e,t,o)=>{let n=y.getTypedArrayFromDType(t,e.length);for(let s=0;s<e.length;++s)n[s]=r(e[s],o);return n}}function Ae(r,e,t){return({inputs:o,attrs:n,backend:s})=>{let{x:a}=o;if(ee(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],n);return i.makeTensorInfo(a.shape,c,p)}}function Zn(r,e,t){return({inputs:o,attrs:n,backend:s})=>{let{x:a}=o;if(ee(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,n);return i.makeTensorInfo(a.shape,u,c)}}var ZE=Yn(r=>Math.ceil(r)),B6=Zn(ei,ZE),JE={kernelName:ei,backendName:"cpu",kernelFunc:B6};function Ud(r,e,t,o){let n=y.getArrayFromDType(t,y.sizeFromShape(e));if(o&&t!=="string"){let s=0;r.forEach(a=>{let i=y.sizeFromShape(a.shape);n.set(a.vals,s),s+=i})}else{let s=0;r.forEach(a=>{let i=t==="string"?N.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)n[c+p]=i[l++]}s+=a.shape[1]})}return n}var QE=Yn(r=>Math.exp(r)),Ok=Zn(en,QE),eA={kernelName:en,backendName:"cpu",kernelFunc:Ok};var tA=Yn(r=>Math.expm1(r)),V6=Zn(ai,tA),rA={kernelName:ai,backendName:"cpu",kernelFunc:V6};var oA=Yn(r=>Math.floor(r)),G6=Zn(tn,oA),nA={kernelName:tn,backendName:"cpu",kernelFunc:G6};function Pk(r,e,t){let o=Ce(t,r.dtype);for(let n=0;n<o.size;++n){let a=o.indexToLoc(n).slice(),i=a[0],l=a[2],u=e.locToIndex([i,l]);a[2]=e.values[u];let c=r.locToIndex(a);o.values[n]=r.values[c]}return o}var sA=Ye((r,e)=>r>e?1:0),W6=ot(ci,sA,null,"bool"),iA={kernelName:ci,backendName:"cpu",kernelFunc:W6};var aA=Ye((r,e)=>r<e?1:0),U6=ot(di,aA,null,"bool"),lA={kernelName:di,backendName:"cpu",kernelFunc:U6};function Mk(r,e,t){let o=(e-r)/(t-1),n=y.makeZerosTypedArray(t,"float32");n[0]=r;for(let s=1;s<n.length;s++)n[s]=n[s-1]+o;return n}var uA=Yn(r=>Math.log(r)),j6=Zn(an,uA),cA={kernelName:an,backendName:"cpu",kernelFunc:j6};function Lk(r,e,t,o){let n=y.getTypedArrayFromDType(o,y.sizeFromShape(t));for(let s=0;s<n.length;++s){let a=s*e,i=r[a];for(let l=0;l<e;++l){let u=r[a+l];u>i&&(i=u)}n[s]=i}return n}var pA=Ye((r,e)=>Math.max(r,e)),H6=ot(un,pA),mA={kernelName:un,backendName:"cpu",kernelFunc:H6};var fA=Ye((r,e)=>Math.min(r,e)),q6=ot(fn,fA),dA={kernelName:fn,backendName:"cpu",kernelFunc:q6};var kx=Ye((r,e)=>r*e),K6=Op((r,e,t,o)=>({real:r*t-e*o,imag:r*o+e*t})),jd=ot(dn,kx,K6),hA={kernelName:dn,backendName:"cpu",kernelFunc:jd};function gA(r,e,t){let o=y.createScalarValue(-1,t);return kx([],e,o,r,t)}function X6(r){let{inputs:e,backend:t}=r,{x:o}=e;ee(o,"neg");let n=t.data.get(o.dataId).values,[s,a]=gA(n,o.shape,o.dtype);return t.makeTensorInfo(a,o.dtype,s)}var xA={kernelName:cs,backendName:"cpu",kernelFunc:X6};var yA=Ye((r,e)=>r!==e?1:0),Y6=ot(bi,yA,null,"bool"),bA={kernelName:bi,backendName:"cpu",kernelFunc:Y6};function Hd(r,e,t,o,n){let s=e.length,a=y.sizeFromShape(e),i=y.computeStrides(e),l=y.computeStrides(n),u=y.getTypedArrayFromDType(t,y.sizeFromShape(n));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[o[d]];let f=y.locToIndex(m,s,l);u[f]=r[c]}return u}function tr(r){let{inputs:e,attrs:t,backend:o}=r,{x:n}=e,{perm:s}=t;ee(n,"transpose");let a=n.shape.length,i=new Array(a);for(let p=0;p<i.length;p++)i[p]=n.shape[s[p]];let l=o.data.get(n.dataId).values,u=Hd(l,n.shape,n.dtype,s,i);return{dataId:o.write(u,i,n.dtype),shape:i,dtype:n.dtype}}var _A={kernelName:Rn,backendName:"cpu",kernelFunc:tr};function wA(r,e,t,o){let[n,s]=N.computeOutAndReduceShapes(r,o),a=mr(e,"int32"),i=y.makeZerosTypedArray(y.sizeFromShape(n),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:n,outDtype:a}}function Z6(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o;ee(n,"prod");let i=n.shape.length,l=y.parseAxisParam(s,n.shape),u=N.getAxesPermutation(l,i),c=l,p=n,m=[];u!=null&&(p=tr({inputs:{x:n},backend:t,attrs:{perm:u}}),m.push(p),c=N.getInnerMostAxes(c.length,i));let f=t.data.get(p.dataId).values,{outVals:d,outShape:h,outDtype:g}=wA(p.shape,p.dtype,f,c),x=h;return a&&(x=N.expandShapeToKeepDim(h,l)),m.forEach(b=>t.disposeIntermediateTensorInfo(b)),t.makeTensorInfo(x,g,d)}var kA={kernelName:vi,backendName:"cpu",kernelFunc:Z6};function qd(r,e,t,o){let n=r===e,s=r<e&&t<0,a=e<r&&t>1;if(n||s||a)return y.makeZerosTypedArray(0,o);let i=Math.abs(Math.ceil((e-r)/t)),l=y.makeZerosTypedArray(i,o);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 vA=Yn(r=>1/Math.sqrt(r)),J6=Zn(Cn,vA),CA={kernelName:Cn,backendName:"cpu",kernelFunc:J6};function Kd(r,e,t,o,n){let s=or.isSliceContinous(o,e,t),a=y.sizeFromShape(t),i=y.computeStrides(o);if(s){let p=or.computeFlatOffset(e,i);return n==="string"?r.slice(p,p+a):r.subarray(p,p+a)}let l=n==="string"?N.fromUint8ToStringArray(r):r,u=Ce(o,n,l),c=Ce(t,n);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 n==="string"?N.fromStringArrayToUint8(c.values):c.values}function Jn(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{begin:s,size:a}=o;ee(n,"slice");let[i,l]=or.parseSliceParams(n,s,a);or.assertParamsValid(n,i,l);let u=t.data.get(n.dataId).values,c=Kd(u,i,l,n.shape,n.dtype);return t.makeTensorInfo(l,n.dtype,c)}var IA={kernelName:hs,backendName:"cpu",kernelFunc:Jn};var NA=Ye((r,e)=>{let t=r-e;return t*t}),Q6=ot(An,NA),SA={kernelName:An,backendName:"cpu",kernelFunc:Q6};function zk(r,e,t,o){let n=Ce(r,e.dtype);for(let s=0;s<n.size;s++){let a=n.indexToLoc(s),i=new Array(a.length);for(let l=0;l<i.length;l++)i[l]=a[l]*t[l]+o[l];n.set(e.get(...i),...a)}return n}var TA=Ye((r,e)=>r-e),e5=Op((r,e,t,o)=>({real:r-t,imag:e-o})),Xd=ot(Dn,TA,e5),EA={kernelName:Dn,backendName:"cpu",kernelFunc:Xd};function Bk(r,e){let t=new Array(r.rank);for(let n=0;n<t.length;n++)t[n]=r.shape[n]*e[n];let o=Ce(t,r.dtype);for(let n=0;n<o.values.length;++n){let s=o.indexToLoc(n),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);o.values[n]=r.values[i]}return o}function Vk(r,e,t,o,n){let s=e[e.length-1],[a,i]=[r.length/s,s],l=y.getTypedArrayFromDType(t,a*o),u=y.getTypedArrayFromDType("int32",a*o);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,_)=>_.value-b.value);let h=p*o,g=l.subarray(h,h+o),x=u.subarray(h,h+o);for(let b=0;b<o;b++)g[b]=d[b].value,x[b]=d[b].index}let c=e.slice();return c[c.length-1]=o,[Ce(c,t,l),Ce(c,"int32",u)]}function Gk(r,e,t,o){let n=y.parseAxisParam(e,t)[0],s=[1,t[0],1];for(let d=0;d<n;d++)s[0]*=t[d];s[1]=t[n];for(let d=n+1;d<t.length;d++)s[2]*=t[d];let a={},i=new Int32Array(t[n]),l=new ct(s,o,r),u=[],c=s[0]===1&&s[2]===1;for(let d=0;d<t[n];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,o);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[n]=p[1],{outputValues:m.values,outputShape:f,indices:i}}var AA="3.0.0";yu("cpu",()=>new Rk,1);var Uk=Ae(ni,r=>r>=0?r:Math.exp(r)-1),DA={kernelName:ni,backendName:"cpu",kernelFunc:Uk};function jk(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{alpha:s}=o;ee([n],"leakyRelu");let a=y.sizeFromShape(n.shape),i=t.data.get(n.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(n.shape,"float32",l)}var $A={kernelName:sn,backendName:"cpu",kernelFunc:jk};var t5=Ye((r,e)=>r<0?e*r:r);function Hk(r){let{inputs:e,backend:t}=r,{x:o,alpha:n}=e;ee([o,n],"prelu");let s=t.data.get(o.dataId).values,a=t.data.get(n.dataId).values,[i,l]=t5(o.shape,n.shape,s,a,o.dtype);return t.makeTensorInfo(l,o.dtype,i)}var RA={kernelName:yn,backendName:"cpu",kernelFunc:Hk};var qk=Ae(bn,r=>Math.max(0,r)),FA={kernelName:bn,backendName:"cpu",kernelFunc:qk};var Kk=Ae(wn,r=>Math.min(Math.max(0,r),6)),OA={kernelName:wn,backendName:"cpu",kernelFunc:Kk};function Pp(r,e,t,o,n){if(t==="linear")return Tr({inputs:{x:e},backend:r});if(t==="relu")return qk({inputs:{x:e},backend:r});if(t==="elu")return Uk({inputs:{x:e},backend:r});if(t==="relu6")return Kk({inputs:{x:e},backend:r});if(t==="prelu")return Hk({inputs:{x:e,alpha:o},backend:r});if(t==="leakyrelu")return jk({inputs:{x:e},backend:r,attrs:{alpha:n}});throw new Error(`Activation ${t} has not been implemented for the CPU backend.`)}function tt(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{shape:s}=o,a=y.sizeFromShape(n.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 (${n.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`),t.incRef(n.dataId);let u=t.data.get(n.dataId);if(u.complexTensorInfos!=null){let c=u.complexTensorInfos.real,p=u.complexTensorInfos.imag;c.shape=i,p.shape=i}return{dataId:n.dataId,shape:i,dtype:n.dtype}}var PA={kernelName:fs,backendName:"cpu",kernelFunc:tt};function Xk(r){let{inputs:e,backend:t,attrs:o}=r,{a:n,b:s}=e,{transposeA:a,transposeB:i}=o;ee([n,s],"matMul");let l=n.shape.length,u=s.shape.length,c=a?n.shape[l-2]:n.shape[l-1],p=i?s.shape[u-1]:s.shape[u-2],m=a?n.shape[l-1]:n.shape[l-2],f=i?s.shape[u-2]:s.shape[u-1],d=n.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 w=(g>x?n.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 ${n.shape} and ${s.shape} and transposeA=${a} and transposeB=${i} must match.`);let v=a?[g,c,m]:[g,m,c],$=i?[x,f,p]:[x,p,f],A=tt({inputs:{x:n},backend:t,attrs:{shape:v}}),R=tt({inputs:{x:s},backend:t,attrs:{shape:$}}),M=a?A.shape[1]:A.shape[2],z=a?A.shape[2]:A.shape[1],W=i?R.shape[1]:R.shape[2],U=Math.max(g,x),q=t.data.get(A.dataId).values,Z=t.data.get(R.dataId).values,X=y.computeStrides(A.shape),Y=y.computeStrides(R.shape),[te,K,re]=a?[X[0],1,X[1]]:[X[0],X[1],1],[ie,se,pe]=i?[1,Y[1],Y[0]]:[Y[1],1,Y[0]],ae=z*W,xe=Ce([U,z,W],A.dtype),ge=xe.values,_e=t.blockSize;for(let ke=0;ke<U;ke++)for(let De=0;De<z;De+=_e)for(let $e=0;$e<W;$e+=_e)for(let Re=0;Re<M;Re+=_e){let He=Math.min(De+_e,z),ut=Math.min($e+_e,W),wt=Math.min(Re+_e,M);for(let kt=De;kt<He;kt++)for(let pt=$e;pt<ut;pt++){let vt=0;for(let qe=Re;qe<wt;qe++){let Ft=Math.min(ke,g-1)*te,po=Math.min(ke,x-1)*pe,Zt=q[Ft+kt*K+qe*re],mo=Z[qe*ie+pt*se+po];vt+=Zt*mo}ge[ke*ae+(kt*W+pt)]+=vt}}return t.disposeIntermediateTensorInfo(A),t.disposeIntermediateTensorInfo(R),t.makeTensorInfo(w,xe.dtype,xe.values)}var MA={kernelName:qo,backendName:"cpu",kernelFunc:Xk};function r5(r){let{inputs:e,backend:t,attrs:o}=r,{a:n,b:s,bias:a,preluActivationWeights:i}=e,{transposeA:l,transposeB:u,activation:c,leakyreluAlpha:p}=o,m,f,d,h=[];m=Xk({inputs:{a:n,b:s},attrs:{transposeA:l,transposeB:u},backend:t}),a&&(f=Ga({inputs:{a:m,b:a},backend:t}),h.push(m),m=f),c&&(d=Pp(t,m,c,i,p),h.push(m),m=d);for(let x of h)t.disposeIntermediateTensorInfo(x);return m}var LA={kernelName:bs,backendName:"cpu",kernelFunc:r5};var o5=Ae(qs,r=>Math.acos(r)),zA={kernelName:qs,backendName:"cpu",kernelFunc:o5};var n5=Ae(Ks,r=>Math.acosh(r)),BA={kernelName:Ks,backendName:"cpu",kernelFunc:n5};function s5(r){let{inputs:e,backend:t}=r,o=e;ee(e,"addN");let n=o.map(i=>t.data.get(i.dataId).values),s=Ce(o[0].shape,o[0].dtype),a=s.values;for(let i=0;i<o.length;i++){let l=n[i];for(let u=0;u<a.length;u++)a[u]+=l[u]}return t.makeTensorInfo(s.shape,s.dtype,s.values)}var VA={kernelName:Uo,backendName:"cpu",kernelFunc:s5};function i5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o;ee(n,"all");let i=y.parseAxisParam(s,n.shape),l=i,u=N.getAxesPermutation(l,n.shape.length),c=n;u!=null&&(c=tr({inputs:{x:n},backend:t,attrs:{perm:u}}),l=N.getInnerMostAxes(l.length,n.shape.length)),N.assertAxesAreInnerMostDims("all",l,c.shape.length);let[p,m]=N.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,_=h[b];for(let w=0;w<f;++w){let v=h[b+w];_=_&&v}d[x]=_}u!=null&&t.disposeIntermediateTensorInfo(c);let g=t.makeTensorInfo(p,c.dtype,d);if(a){let x=N.expandShapeToKeepDim(p,i),b=tt({inputs:{x:g},backend:t,attrs:{shape:x}});return t.disposeIntermediateTensorInfo(g),b}return g}var GA={kernelName:Vl,backendName:"cpu",kernelFunc:i5};function a5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o;ee(n,"any");let i=y.parseAxisParam(s,n.shape),l=i,u=N.getAxesPermutation(l,n.shape.length),c=n;u!=null&&(c=tr({inputs:{x:n},backend:t,attrs:{perm:u}}),l=N.getInnerMostAxes(l.length,n.shape.length)),N.assertAxesAreInnerMostDims("any",l,c.shape.length);let[p,m]=N.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,_=h[b];for(let w=0;w<f;++w){let v=h[b+w];_=_||v}d[x]=_}u!=null&&t.disposeIntermediateTensorInfo(c);let g=t.makeTensorInfo(p,c.dtype,d);if(a){let x=N.expandShapeToKeepDim(p,i),b=tt({inputs:{x:g},backend:t,attrs:{shape:x}});return t.disposeIntermediateTensorInfo(g),b}return g}var WA={kernelName:Gl,backendName:"cpu",kernelFunc:a5};function l5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s}=o;ee(n,"argMax");let a=y.parseAxisParam(s,n.shape),i=N.getAxesPermutation(a,n.shape.length),l=n,u=[];i!=null&&(l=tr({inputs:{x:n},backend:t,attrs:{perm:i}}),u.push(l),a=N.getInnerMostAxes(a.length,l.shape.length)),a=[a[0]],N.assertAxesAreInnerMostDims("argMax",a,l.shape.length);let[c,p]=N.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],_=0;for(let w=0;w<d;++w){let v=h[x+w];v>b&&(b=v,_=w)}f[g]=_}return u.forEach(g=>t.disposeIntermediateTensorInfo(g)),t.makeTensorInfo(c,"int32",f)}var UA={kernelName:jo,backendName:"cpu",kernelFunc:l5};function u5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s}=o;ee(n,"argMin");let a=y.parseAxisParam(s,n.shape),i=N.getAxesPermutation(a,n.shape.length),l=n,u=[];i!=null&&(l=tr({inputs:{x:n},backend:t,attrs:{perm:i}}),u.push(l),a=N.getInnerMostAxes(a.length,l.shape.length)),a=[a[0]],N.assertAxesAreInnerMostDims("argMin",a,l.shape.length);let[c,p]=N.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],_=0;for(let w=0;w<d;++w){let v=h[x+w];v<b&&(b=v,_=w)}f[g]=_}return u.forEach(g=>t.disposeIntermediateTensorInfo(g)),t.makeTensorInfo(c,"int32",f)}var jA={kernelName:oa,backendName:"cpu",kernelFunc:u5};var c5=Ae(Xs,r=>Math.asin(r)),HA={kernelName:Xs,backendName:"cpu",kernelFunc:c5};var p5=Ae(Ys,r=>Math.asinh(r)),qA={kernelName:Ys,backendName:"cpu",kernelFunc:p5};var m5=Ae(Zs,r=>Math.atan(r)),KA={kernelName:Zs,backendName:"cpu",kernelFunc:m5};var f5=Ye((r,e)=>Math.atan2(r,e)),d5=ot(Qs,f5),XA={kernelName:Qs,backendName:"cpu",kernelFunc:d5};var h5=Ae(Js,r=>Math.atanh(r)),YA={kernelName:Js,backendName:"cpu",kernelFunc:h5};function Mp(r,e,t,o,n,s){let a=n.strideHeight,i=n.strideWidth,l=n.dilationHeight,u=n.dilationWidth,c=n.effectiveFilterHeight,p=n.effectiveFilterWidth,m=n.padInfo.top,f=n.padInfo.left,d=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,h=Ce(n.outShape,t),g=h.values,x=n.outShape[1]*n.outShape[2]*n.outShape[3],b=n.outShape[2]*n.outShape[3],_=n.outShape[3];for(let w=0;w<n.batchSize;++w){let v=w*x,$=w*o[0];for(let A=0;A<n.inChannels;++A)for(let R=0;R<n.outHeight;++R){let M=R*a-m,z=Math.max(0,M),W=Math.min(n.inHeight,c+M),U=v+R*b;for(let q=0;q<n.outWidth;++q){let Z=q*i-f,X=Math.max(0,Z),Y=Math.min(n.inWidth,p+Z),te=d,K=0,re=0;for(let se=z;se<W;se+=l){let pe=$+se*o[1];for(let ae=X;ae<Y;ae+=u){let xe=pe+ae*o[2],ge=r[xe+A];s==="max"&&ge>te?te=ge:s==="avg"&&(K+=ge,re++)}if(isNaN(te))break}let ie=U+q*_+A;g[ie]=s==="avg"?K/re:te}}}return h}function vx(r,e,t,o,n=!1,s=!1){let a=Ce(o.outShape,"int32"),i=o.strideHeight,l=o.strideWidth,u=o.dilationHeight,c=o.dilationWidth,p=o.effectiveFilterHeight,m=o.effectiveFilterWidth,f=o.padInfo.top,d=o.padInfo.left,h=Ce(e,t,r);for(let g=0;g<o.batchSize;++g)for(let x=0;x<o.inChannels;++x)for(let b=0;b<o.outHeight;++b){let _=b*i-f,w=_;for(;w<0;)w+=u;let v=Math.min(o.inHeight,p+_);for(let $=0;$<o.outWidth;++$){let A=$*l-d,R=A;for(;R<0;)R+=c;let M=Math.min(o.inWidth,m+A),z=Number.NEGATIVE_INFINITY,W=-1;for(let U=w;U<v;U+=u){let q=U-_;for(let Z=R;Z<M;Z+=c){let X=Z-A,Y=h.get(g,U,Z,x);Y>z&&(z=Y,n?W=s?((g*o.inHeight+U)*o.inWidth+Z)*o.inChannels+x:(U*o.inWidth+Z)*o.inChannels+x:W=q*m+X)}}a.set(W,g,b,$,x)}}return a}function Cx(r,e,t,o,n,s){let a=n.strideDepth,i=n.strideHeight,l=n.strideWidth,u=n.dilationDepth,c=n.dilationHeight,p=n.dilationWidth,m=n.effectiveFilterDepth,f=n.effectiveFilterHeight,d=n.effectiveFilterWidth,h=n.padInfo.front,g=n.padInfo.top,x=n.padInfo.left,b=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,_=Ce(n.outShape,t),w=_.values,v=n.outShape[1]*n.outShape[2]*n.outShape[3]*n.outShape[4],$=n.outShape[2]*n.outShape[3]*n.outShape[4],A=n.outShape[3]*n.outShape[4],R=n.outShape[4];for(let M=0;M<n.batchSize;++M){let z=M*v,W=M*o[0];for(let U=0;U<n.inChannels;++U)for(let q=0;q<n.outDepth;++q){let Z=q*a-h,X=Z;for(;X<0;)X+=u;let Y=Math.min(n.inDepth,m+Z),te=z+q*$;for(let K=0;K<n.outHeight;++K){let re=K*i-g,ie=re;for(;ie<0;)ie+=c;let se=Math.min(n.inHeight,f+re),pe=te+K*A;for(let ae=0;ae<n.outWidth;++ae){let xe=ae*l-x,ge=xe;for(;ge<0;)ge+=p;let _e=Math.min(n.inWidth,d+xe),ke=pe+ae*R,De=b,$e=0,Re=0;for(let ut=X;ut<Y;ut+=u){let wt=W+ut*o[1];for(let kt=ie;kt<se;kt+=c){let pt=wt+kt*o[2];for(let vt=ge;vt<_e;vt+=p){let qe=pt+vt*o[3],Ft=r[qe+U];if(s==="max"&&Ft>De?De=Ft:s==="avg"&&($e+=Ft,Re++),isNaN(De))break}if(isNaN(De))break}if(isNaN(De))break}let He=ke+U;w[He]=s==="avg"?$e/Re:De}}}}return _}function ZA(r,e){let t=Ce(e.outShape,"int32"),o=e.strideDepth,n=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*o-m,_=b;for(;_<0;)_+=a;let w=Math.min(e.inDepth,u+b);for(let v=0;v<e.outHeight;++v){let $=v*n-f,A=$;for(;A<0;)A+=i;let R=Math.min(e.inHeight,c+$);for(let M=0;M<e.outWidth;++M){let z=M*s-d,W=z;for(;W<0;)W+=l;let U=Math.min(e.inWidth,p+z),q=Number.NEGATIVE_INFINITY,Z=-1;for(let X=_;X<w;X+=a){let Y=X-b;for(let te=A;te<R;te+=i){let K=te-$;for(let re=W;re<U;re+=l){let ie=re-z,se=r.get(h,X,te,re,g);se>=q&&(q=se,Z=Y*c*p+K*c+ie)}}}t.set(Z,h,x,v,M,g)}}}return t}function g5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e;ee(n,"avgPool");let{filterSize:s,strides:a,pad:i,dimRoundingMode:l}=o,u=1;y.assert(N.eitherStridesOrDilationsAreOne(a,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let c=N.computePool2DInfo(n.shape,s,a,u,i,l),p;if(c.filterWidth===1&&c.filterHeight===1&&y.arraysEqual(c.inShape,c.outShape))p=Tr({inputs:{x:n},backend:t});else{let m=t.data.get(n.dataId).values,f=y.computeStrides(n.shape),d=Mp(m,n.shape,n.dtype,f,c,"avg");p=t.makeTensorInfo(c.outShape,n.dtype,d.values)}return p}var JA={kernelName:Ho,backendName:"cpu",kernelFunc:g5};function x5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{filterSize:s,strides:a,pad:i,dimRoundingMode:l,dataFormat:u}=o;ee(n,"avgPool3d");let c=N.computePool3DInfo(n.shape,s,a,1,i,l,u),p=t.data.get(n.dataId).values,m=Cx(p,n.shape,n.dtype,y.computeStrides(n.shape),c,"avg");return t.makeTensorInfo(m.shape,"float32",m.values)}var QA={kernelName:na,backendName:"cpu",kernelFunc:x5};function y5(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,{filterSize:a,strides:i,pad:l,dimRoundingMode:u}=o;ee([n,s],"avgPool3DGrad");let c=N.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,_=c.dilationWidth,w=c.effectiveFilterDepth,v=c.effectiveFilterHeight,$=c.effectiveFilterWidth,A=w-1-c.padInfo.front,R=$-1-c.padInfo.left,M=v-1-c.padInfo.top,z=Ce(s.shape,"float32"),W=1/(d*h*g),U=t.bufferSync(n);for(let q=0;q<c.batchSize;++q)for(let Z=0;Z<c.inChannels;++Z)for(let X=0;X<c.inDepth;++X)for(let Y=0;Y<c.inHeight;++Y)for(let te=0;te<c.inWidth;++te){let K=X-A,re=Y-M,ie=te-R,se=0;for(let pe=0;pe<w;pe+=x){let ae=(K+pe)/p;if(!(ae<0||ae>=c.outDepth||Math.floor(ae)!==ae))for(let xe=0;xe<v;xe+=b){let ge=(re+xe)/m;if(!(ge<0||ge>=c.outHeight||Math.floor(ge)!==ge))for(let _e=0;_e<$;_e+=_){let ke=(ie+_e)/f;if(ke<0||ke>=c.outWidth||Math.floor(ke)!==ke)continue;se+=U.get(q,ae,ge,ke,Z)}}}z.set(se*W,q,X,Y,te,Z)}return t.makeTensorInfo(z.shape,z.dtype,z.values)}var e2={kernelName:Ul,backendName:"cpu",kernelFunc:y5};function b5(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,a=s;ee([n,s],"avgPoolGrad");let{filterSize:i,strides:l,pad:u}=o,c=N.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,_=b-1-c.padInfo.left,w=x-1-c.padInfo.top,v=Ce(a.shape,"float32"),$=1/(f*d),A=t.data.get(n.dataId).values,R=Ce(n.shape,"float32",A);for(let M=0;M<c.batchSize;++M)for(let z=0;z<c.inChannels;++z)for(let W=0;W<c.inHeight;++W)for(let U=0;U<c.inWidth;++U){let q=W-w,Z=U-_,X=0;for(let Y=0;Y<x;Y+=h){let te=(q+Y)/p;if(!(te<0||te>=c.outHeight||Math.floor(te)!==te))for(let K=0;K<b;K+=g){let re=(Z+K)/m;if(re<0||re>=c.outWidth||Math.floor(re)!==re)continue;X+=R.get(M,te,re,z)}}v.set(X*$,M,W,U,z)}return t.makeTensorInfo(v.shape,v.dtype,v.values)}var t2={kernelName:Wl,backendName:"cpu",kernelFunc:b5};function _5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,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."),ee([n,i,l,s,a],"batchNorm");let{varianceEpsilon:u}=o;u==null&&(u=.001);let c=t.data.get(n.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,_=p.length,w=0,v=0,$=0,A=0;for(let R=0;R<c.length;++R)h[R]=d[w++]+(c[R]-p[v++])*f[$++]/Math.sqrt(m[A++]+u),w>=g&&(w=0),v>=_&&(v=0),$>=x&&($=0),A>=b&&(A=0);return t.makeTensorInfo(n.shape,n.dtype,h)}var r2={kernelName:on,backendName:"cpu",kernelFunc:_5};function w5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockShape:s,crops:a}=o;ee([n],"batchToSpaceND");let i=s.reduce((x,b)=>x*b),l=N.getReshaped(n.shape,s,i),u=N.getPermuted(l.length,s.length),c=N.getReshapedPermuted(n.shape,s,i),p=N.getSliceBeginCoords(a,s.length),m=N.getSliceSize(c,a,s.length),f=tt({inputs:{x:n},backend:t,attrs:{shape:l}}),d=tr({inputs:{x:f},backend:t,attrs:{perm:u}}),h=tt({inputs:{x:d},backend:t,attrs:{shape:c}}),g=Jn({inputs:{x:h},backend:t,attrs:{begin:p,size:m}});return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(h),g}var o2={kernelName:sa,backendName:"cpu",kernelFunc:w5};function k5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,weights:s}=e,{size:a}=o,i=t.data.get(n.dataId).values,l=t.data.get(s.dataId).values,u=Wd(i,l,s.dtype,s.shape,a);return t.makeTensorInfo([a],s.dtype,u)}var n2={kernelName:jl,backendName:"cpu",kernelFunc:k5};var v5=Ae(Ao,(r,e)=>{let t=e;return r>t.clipValueMax?t.clipValueMax:r<t.clipValueMin?t.clipValueMin:r}),s2={kernelName:Ao,backendName:"cpu",kernelFunc:v5};var C5=r=>{let{x:e}=r.inputs,t=r.backend,o=new Float32Array(y.sizeFromShape(e.shape)),n=t.data.get(e.dataId),s=n.complexTensorInfos.real,a=n.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];o[u]=Math.hypot(c,p)}return t.makeOutput(o,e.shape,"float32")},i2={kernelName:ia,backendName:"cpu",kernelFunc:C5};function Ki(r){let{inputs:e,backend:t}=r,{input:o}=e,n=t.data.get(o.dataId).complexTensorInfos.imag,s=t.data.get(n.dataId).values;return t.makeTensorInfo(n.shape,n.dtype,s)}var a2={kernelName:ou,backendName:"cpu",kernelFunc:Ki};function vl(r){let{inputs:e,backend:t,attrs:o}=r,{axis:n}=o,s=y.parseAxisParam(n,e[0].shape)[0],a=N.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 Tr({inputs:{x:i[0]},backend:t});let l=i.map(h=>h.shape);if(N.assertParamsConsistent(l,s),i[0].dtype==="complex64"){let h=i.map(w=>Kn({inputs:{input:w},backend:t})),g=i.map(w=>Ki({inputs:{input:w},backend:t})),x=vl({inputs:h,backend:t,attrs:{axis:s}}),b=vl({inputs:g,backend:t,attrs:{axis:s}}),_=cr({inputs:{real:x,imag:b},backend:t});return h.forEach(w=>t.disposeIntermediateTensorInfo(w)),g.forEach(w=>t.disposeIntermediateTensorInfo(w)),t.disposeIntermediateTensorInfo(x),t.disposeIntermediateTensorInfo(b),_}let u=i.map(h=>{let g=y.sizeFromShape(h.shape.slice(s));return tt({inputs:{x:h},backend:t,attrs:{shape:[-1,g]}})}),c=u.map(h=>({vals:t.data.get(h.dataId).values,shape:h.shape}));a=N.computeOutShape(u.map(h=>h.shape),1);let p=u[0].shape[0]===1,m=Ud(c,a,e[0].dtype,p),f=N.computeOutShape(i.map(h=>h.shape),s),d=t.makeTensorInfo(f,e[0].dtype,m);return u.forEach(h=>t.disposeIntermediateTensorInfo(h)),d}var l2={kernelName:is,backendName:"cpu",kernelFunc:vl};function Yk(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dataFormat:l,dilations:u,dimRoundingMode:c}=o;ee([n,s],"conv2d");let p=N.convertConv2DDataFormat(l),m=N.computeConv2DInfo(n.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,_=m.dataFormat==="channelsLast",w=new ct(m.outShape,n.dtype),v=y.computeStrides(n.shape),$=y.computeStrides(s.shape),A=v[0],R=_?v[1]:v[2],M=_?v[2]:1,z=_?1:v[1],W=w.strides[0],U=_?w.strides[1]:w.strides[2],q=_?w.strides[2]:1,Z=_?1:w.strides[1],X=t.data.get(n.dataId).values,Y=t.data.get(s.dataId).values,te=w.values;for(let K=0;K<m.batchSize;++K){let re=K*A,ie=K*W;for(let se=0;se<m.outHeight;++se){let pe=ie+se*U,ae=se*m.strideHeight-b;for(let xe=0;xe<f;++xe){let ge=ae+xe*h;if(ge<0||ge>=m.inHeight)continue;let _e=xe*$[0],ke=re+ge*R;for(let De=0;De<m.outWidth;++De){let $e=pe+De*q,Re=De*m.strideWidth-x;for(let He=0;He<d;++He){let ut=Re+He*g;if(ut<0||ut>=m.inWidth)continue;let wt=_e+He*$[1],kt=ke+ut*M,pt=wt;for(let vt=0;vt<m.inChannels;++vt){let qe=X[kt+vt*z];for(let Ft=0;Ft<m.outChannels;++Ft)te[$e+Ft*Z]+=qe*Y[pt+Ft];pt+=m.outChannels}}}}}}return t.makeTensorInfo(w.shape,w.dtype,te)}var u2={kernelName:Ko,backendName:"cpu",kernelFunc:Yk};function I5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,dy:s}=e,{strides:a,pad:i,dataFormat:l,dimRoundingMode:u,filterShape:c}=o;ee([n,s],"conv2dBackpropFilter");let p=N.convertConv2DDataFormat(l),m=N.computeConv2DInfo(n.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"),_=m.padInfo.left,w=m.padInfo.top,v=t.data.get(n.dataId).values,$=t.data.get(s.dataId).values,A=new ct(n.shape,n.dtype,v),R=new ct(s.shape,s.dtype,$);for(let M=0;M<h;++M){let z=Math.max(0,Math.ceil((w-M)/f)),W=Math.min(m.outHeight,(m.inHeight+w-M)/f);for(let U=0;U<g;++U){let q=Math.max(0,Math.ceil((_-U)/d)),Z=Math.min(m.outWidth,(m.inWidth+_-U)/d);for(let X=0;X<m.inChannels;++X)for(let Y=0;Y<m.outChannels;++Y){let te=0;for(let K=0;K<m.batchSize;++K)for(let re=z;re<W;++re){let ie=M+re*f-w;for(let se=q;se<Z;++se){let pe=U+se*d-_;x?te+=A.get(K,ie,pe,X)*R.get(K,re,se,Y):te+=A.get(K,X,ie,pe)*R.get(K,Y,re,se)}}b.set(te,M,U,X,Y)}}}return t.makeTensorInfo(b.shape,b.dtype,b.values)}var c2={kernelName:ql,backendName:"cpu",kernelFunc:I5};function N5(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,filter:s}=e,{inputShape:a,strides:i,pad:l,dataFormat:u,dimRoundingMode:c}=o;ee([n,s],"conv2dBackpropInput");let p=y.computeStrides(s.shape),m=y.computeStrides(n.shape),f=N.convertConv2DDataFormat(u),d=N.computeConv2DInfo(a,s.shape,i,1,l,c,!1,f),h=new ct(d.inShape,"float32"),g=h.values,x=t.data.get(n.dataId).values,b=t.data.get(s.dataId).values,[_,w,v]=p,{batchSize:$,filterHeight:A,filterWidth:R,inChannels:M,inHeight:z,inWidth:W,outChannels:U,outHeight:q,outWidth:Z,strideHeight:X,strideWidth:Y}=d;f=d.dataFormat;let te=A-1-d.padInfo.top,K=R-1-d.padInfo.left,re=f==="channelsLast",ie=h.strides[0],se=re?h.strides[1]:h.strides[2],pe=re?h.strides[2]:1,ae=re?1:h.strides[1],xe=m[0],ge=re?m[1]:m[2],_e=re?m[2]:1,ke=re?1:m[1];for(let De=0;De<$;++De)for(let $e=0;$e<M;++$e)for(let Re=0;Re<z;++Re){let He=Re-te,ut=Math.max(0,Math.ceil(He/X)),wt=Math.min(q,(A+He)/X);for(let kt=0;kt<W;++kt){let pt=kt-K,vt=Math.max(0,Math.ceil(pt/Y)),qe=Math.min(Z,(R+pt)/Y),Ft=0;for(let Zt=ut;Zt<wt;++Zt){let mo=Zt*X-He;for(let _r=vt;_r<qe;++_r){let Bo=_r*Y-pt,Jr=xe*De+ge*Zt+_e*_r,fo=_*(A-1-mo)+w*(R-1-Bo)+v*$e;for(let wr=0;wr<U;++wr){let No=x[Jr+ke*wr],Vo=b[fo+wr];Ft+=No*Vo}}}let po=ie*De+se*Re+pe*kt+ae*$e;g[po]=Ft}}return t.makeTensorInfo(h.shape,h.dtype,h.values)}var p2={kernelName:Xo,backendName:"cpu",kernelFunc:N5};function S5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dilations:l}=o;ee([n,s],"conv3d");let u=N.computeConv3DInfo(n.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,_=g.top,w=new ct(u.outShape,n.dtype),v=t.data.get(n.dataId).values,$=t.data.get(s.dataId).values,A=w.values,R=y.computeStrides(n.shape),M=y.computeStrides(s.shape);for(let z=0;z<u.batchSize;++z){let W=z*R[0],U=z*w.strides[0];for(let q=0;q<u.outDepth;++q){let Z=U+q*w.strides[1],X=q*u.strideDepth-x;for(let Y=0;Y<c;++Y){let te=X+Y*f;if(te<0||te>=u.inDepth)continue;let K=Y*M[0],re=W+te*R[1];for(let ie=0;ie<u.outHeight;++ie){let se=Z+ie*w.strides[2],pe=ie*u.strideHeight-_;for(let ae=0;ae<p;++ae){let xe=pe+ae*d;if(xe<0||xe>=u.inHeight)continue;let ge=K+ae*M[1],_e=re+xe*R[2];for(let ke=0;ke<u.outWidth;++ke){let De=se+ke*u.outChannels,$e=ke*u.strideWidth-b;for(let Re=0;Re<m;++Re){let He=$e+Re*h;if(He<0||He>=u.inWidth)continue;let ut=ge+Re*M[2],wt=_e+He*u.inChannels,kt=ut;for(let pt=0;pt<u.inChannels;++pt){let vt=v[wt+pt];for(let qe=0;qe<u.outChannels;++qe)A[De+qe]+=vt*$[kt+qe];kt+=u.outChannels}}}}}}}}return t.makeTensorInfo(w.shape,w.dtype,w.values)}var m2={kernelName:aa,backendName:"cpu",kernelFunc:S5};function T5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,dy:s}=e,{strides:a,pad:i,filterShape:l}=o;ee([n,s],"conv3dBackpropFilterV2");let u=y.computeStrides(n.shape),c=y.computeStrides(s.shape),p=N.computeConv3DInfo(n.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"),_=b.values,[w,v,$,A]=b.strides,R=t.data.get(s.dataId).values,[M,z,W,U]=c,q=t.data.get(n.dataId).values,[Z,X,Y,te]=u,K=p.padInfo.front,re=p.padInfo.left,ie=p.padInfo.top;for(let se=0;se<h;++se){let pe=Math.max(0,Math.ceil((K-se)/m)),ae=Math.min(p.outDepth,(p.inDepth+K-se)/m),xe=se*w;for(let ge=0;ge<g;++ge){let _e=Math.max(0,Math.ceil((ie-ge)/f)),ke=Math.min(p.outHeight,(p.inHeight+ie-ge)/f),De=ge*v+xe;for(let $e=0;$e<x;++$e){let Re=Math.max(0,Math.ceil((re-$e)/d)),He=Math.min(p.outWidth,(p.inWidth+re-$e)/d),ut=$e*$+De;for(let wt=0;wt<p.inChannels;++wt){let kt=wt*A+ut;for(let pt=0;pt<p.outChannels;++pt){let vt=0;for(let qe=0;qe<p.batchSize;++qe){let Ft=qe*Z,po=qe*M;for(let Zt=pe;Zt<ae;++Zt){let _r=(se+Zt*m-K)*X+Ft,Bo=Zt*z+po;for(let Jr=_e;Jr<ke;++Jr){let wr=(ge+Jr*f-ie)*Y+_r,No=Jr*W+Bo;for(let Vo=Re;Vo<He;++Vo){let ts=($e+Vo*d-re)*te+wr,So=Vo*U+No;vt+=q[ts+wt]*R[So+pt]}}}}_[kt+pt]=vt}}}}}return t.makeTensorInfo(b.shape,b.dtype,b.values)}var f2={kernelName:Kl,backendName:"cpu",kernelFunc:T5};function E5(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,filter:s}=e,{pad:a,strides:i,inputShape:l}=o;ee([n],"conv3dBackpropInputV2");let u=y.computeStrides(n.shape),c=y.computeStrides(s.shape),p=N.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(n.dataId).values,[_,w,v,$]=u,A=t.data.get(s.dataId).values,[R,M,z,W]=c,{batchSize:U,filterDepth:q,filterHeight:Z,filterWidth:X,inChannels:Y,inDepth:te,inHeight:K,inWidth:re,outChannels:ie,outDepth:se,outHeight:pe,outWidth:ae,strideDepth:xe,strideHeight:ge,strideWidth:_e}=p,ke=q-1-p.padInfo.front,De=Z-1-p.padInfo.top,$e=X-1-p.padInfo.left;for(let Re=0;Re<U;++Re)for(let He=0;He<Y;++He)for(let ut=0;ut<te;++ut){let wt=ut-ke,kt=Math.max(0,Math.ceil(wt/xe)),pt=Math.min(se,(q+wt)/xe);for(let vt=0;vt<K;++vt){let qe=vt-De,Ft=Math.max(0,Math.ceil(qe/ge)),po=Math.min(pe,(Z+qe)/ge);for(let Zt=0;Zt<re;++Zt){let mo=Zt-$e,_r=Math.max(0,Math.ceil(mo/_e)),Bo=Math.min(ae,(X+mo)/_e),Jr=0;for(let fo=kt;fo<pt;++fo){let wr=fo*xe-wt;for(let No=Ft;No<po;++No){let Vo=No*ge-qe;for(let Qr=_r;Qr<Bo;++Qr){let ts=Qr*_e-mo,So=_*Re+w*fo+v*No+$*Qr,gc=R*(q-1-wr)+M*(Z-1-Vo)+z*(X-1-ts)+W*He;for(let rs=0;rs<ie;++rs){let Ji=b[So+rs],$l=A[gc+rs];Jr+=Ji*$l}}}}f[d*Re+h*ut+g*vt+x*Zt+He]=Jr}}}return t.makeTensorInfo(m.shape,m.dtype,m.values)}var d2={kernelName:Xl,backendName:"cpu",kernelFunc:E5};var A5=Ae(Yo,r=>Math.cos(r)),h2={kernelName:Yo,backendName:"cpu",kernelFunc:A5};var D5=Ae(ti,r=>Math.cosh(r)),g2={kernelName:ti,backendName:"cpu",kernelFunc:D5};function $5(r){let{inputs:e,backend:t,attrs:o}=r,{image:n,boxes:s,boxInd:a}=e,{cropSize:i,method:l,extrapolationValue:u}=o,[c,p,m,f]=n.shape,d=s.shape[0],[h,g]=i,x=Ce([d,h,g,f],"float32"),b=t.data.get(s.dataId).values,_=t.data.get(a.dataId).values,w=t.data.get(n.dataId).values,v=y.computeStrides(n.shape),$=y.computeStrides(x.shape);for(let A=0;A<d;A++){let R=A*4,M=b[R],z=b[R+1],W=b[R+2],U=b[R+3],q=_[A];if(q>=c)continue;let Z=h>1?(W-M)*(p-1)/(h-1):0,X=g>1?(U-z)*(m-1)/(g-1):0;for(let Y=0;Y<h;Y++){let te=h>1?M*(p-1)+Y*Z:.5*(M+W)*(p-1);if(te<0||te>p-1){for(let K=0;K<g;K++)for(let re=0;re<f;re++){let ie=re+K*$[2]+Y*$[1]+A*$[0];x.values[ie]=u}continue}if(l==="bilinear"){let K=Math.floor(te),re=Math.ceil(te),ie=te-K;for(let se=0;se<g;se++){let pe=g>1?z*(m-1)+se*X:.5*(z+U)*(m-1);if(pe<0||pe>m-1){for(let _e=0;_e<f;_e++){let ke=_e+se*$[2]+Y*$[1]+A*$[0];x.values[ke]=u}continue}let ae=Math.floor(pe),xe=Math.ceil(pe),ge=pe-ae;for(let _e=0;_e<f;_e++){let ke=_e+ae*v[2]+K*v[1]+q*v[0],De=w[ke];ke=_e+xe*v[2]+K*v[1]+q*v[0];let $e=w[ke];ke=_e+ae*v[2]+re*v[1]+q*v[0];let Re=w[ke];ke=_e+xe*v[2]+re*v[1]+q*v[0];let He=w[ke],ut=De+($e-De)*ge,wt=Re+(He-Re)*ge;ke=_e+se*$[2]+Y*$[1]+A*$[0],x.values[ke]=ut+(wt-ut)*ie}}}else for(let K=0;K<g;++K){let re=g>1?z*(m-1)+K*X:.5*(z+U)*(m-1);if(re<0||re>m-1){for(let pe=0;pe<f;pe++){let ae=pe+K*$[2]+Y*$[1]+A*$[0];x.values[ae]=u}continue}let ie=Math.round(re),se=Math.round(te);for(let pe=0;pe<f;pe++){let ae=pe+ie*v[2]+se*v[1]+q*v[0],xe=pe+K*$[2]+Y*$[1]+A*$[0];x.values[xe]=w[ae]}}}}return t.makeTensorInfo(x.shape,x.dtype,x.values)}var x2={kernelName:ri,backendName:"cpu",kernelFunc:$5};function R5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,exclusive:a,reverse:i}=o;ee(n,"cumsum");let l=N.getAxesPermutation([s],n.shape.length),u=n;l!=null&&(u=tr({inputs:{x:n},backend:t,attrs:{perm:l}}));let c=N.getInnerMostAxes(1,n.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 _=h(x,b);if(b===0)m[_]=a?0:f[_];else{let w=h(x,b-1);m[_]=a?f[w]+m[w]:f[_]+m[w]}}let g=t.makeTensorInfo(u.shape,p,m);if(l!=null){let x=N.getUndoAxesPermutation(l),b=tr({inputs:{x:g},backend:t,attrs:{perm:x}});return t.disposeIntermediateTensorInfo(g),t.disposeIntermediateTensorInfo(u),b}return g}var y2={kernelName:Zo,backendName:"cpu",kernelFunc:R5};function F5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,weights:s}=e,{size:a,binaryOutput:i}=o;if(n.shape.length===1){let l=t.data.get(n.dataId).values,u=t.data.get(s.dataId).values,c=Wd(l,u,s.dtype,s.shape,a);return t.makeTensorInfo([a],s.dtype,c)}else if(n.shape.length===2){let l=t.bufferSync(n),u=t.bufferSync(s),c=Fk(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${n.shape.length}.`)}var b2={kernelName:Yl,backendName:"cpu",kernelFunc:F5};function O5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockSize:s,dataFormat:a}=o;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=n.shape[0],l=n.shape[1],u=n.shape[2],c=n.shape[3],p=l*s,m=u*s,f=c/(s*s),d=t.data.get(n.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 _=Math.floor(b/s),w=b%s;for(let v=0;v<m;++v){let $=Math.floor(v/s),A=v%s,R=(w*s+A)*f;for(let M=0;M<f;++M){let W=M+R+c*($+u*(_+l*x));h[g++]=d[W]}}}return t.makeTensorInfo([i,p,m,f],n.dtype,h)}var _2={kernelName:oi,backendName:"cpu",kernelFunc:O5};function Zk(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dilations:l,dimRoundingMode:u}=o;ee([n,s],"depthwiseConv2DNative");let c=y.computeStrides(n.shape),p=y.computeStrides(s.shape),m=l;m==null&&(m=[1,1]),y.assert(N.eitherStridesOrDilationsAreOne(a,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${m}'`);let f=N.computeConv2DInfo(n.shape,s.shape,a,m,i,u,!0),{filterHeight:d,filterWidth:h,dilationHeight:g,dilationWidth:x,padInfo:b}=f,_=b.left,w=b.top,v=f.outChannels/f.inChannels,$=new ct(f.outShape,n.dtype),A=t.data.get(n.dataId).values,R=t.data.get(s.dataId).values,M=$.values;for(let z=0;z<f.batchSize;++z){let W=z*c[0],U=z*$.strides[0];for(let q=0;q<f.outHeight;++q){let Z=U+q*$.strides[1],X=q*f.strideHeight-_;for(let Y=0;Y<d;++Y){let te=X+Y*g;if(te<0||te>=f.inHeight)continue;let K=Y*p[0],re=W+te*c[1];for(let ie=0;ie<f.outWidth;++ie){let se=Z+ie*$.strides[2],pe=ie*f.strideWidth-w;for(let ae=0;ae<h;++ae){let xe=pe+ae*x;if(xe<0||xe>=f.inWidth)continue;let ge=K+ae*p[1],_e=re+xe*f.inChannels,ke=se,De=ge;for(let $e=0;$e<f.inChannels;++$e){let Re=A[_e+$e];for(let He=0;He<v;++He)M[ke+He]+=Re*R[De+He];ke+=v,De+=v}}}}}}return t.makeTensorInfo($.shape,$.dtype,$.values)}var w2={kernelName:Jo,backendName:"cpu",kernelFunc:Zk};function P5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,dy:s}=e,{strides:a,dilations:i,pad:l,dimRoundingMode:u,filterShape:c}=o;ee([n,s],"depthwiseConv2dNativeBackpropFilter");let p=N.computeConv2DInfo(n.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,_=p.outChannels/p.inChannels,w=t.data.get(n.dataId).values,v=new ct(n.shape,n.dtype,w),$=t.data.get(s.dataId).values,A=new ct(s.shape,s.dtype,$);for(let R=0;R<d;++R){let M=Math.max(0,Math.ceil((b-R)/m)),z=Math.min(p.outHeight,(p.inHeight+b-R)/m);for(let W=0;W<h;++W){let U=Math.max(0,Math.ceil((x-W)/f)),q=Math.min(p.outWidth,(p.inWidth+x-W)/f);for(let Z=0;Z<p.outChannels;++Z){let X=Math.trunc(Z/_),Y=Z%_,te=0;for(let K=0;K<p.batchSize;++K)for(let re=M;re<z;++re){let ie=R+re*m-b;for(let se=U;se<q;++se){let pe=W+se*f-x;te+=v.get(K,ie,pe,X)*A.get(K,re,se,Z)}}g.set(te,R,W,X,Y)}}}return t.makeTensorInfo(g.shape,g.dtype,g.values)}var k2={kernelName:Zl,backendName:"cpu",kernelFunc:P5};function M5(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,filter:s}=e,{strides:a,dilations:i,pad:l,dimRoundingMode:u,inputShape:c}=o;ee([n,s],"depthwiseConv2DNativeBackpropInput");let p=y.computeStrides(n.shape),m=y.computeStrides(s.shape),f=N.computeConv2DInfo(c,s.shape,a,i,l,u,!0),d=new ct(f.inShape,"float32"),h=d.values,[g,x,b]=d.strides,_=t.data.get(n.dataId).values,[w,v,$]=p,A=t.data.get(s.dataId).values,[R,M,z]=m,{batchSize:W,filterHeight:U,filterWidth:q,inChannels:Z,inHeight:X,inWidth:Y,outChannels:te,outHeight:K,outWidth:re,strideHeight:ie,strideWidth:se}=f,pe=U-1-f.padInfo.top,ae=q-1-f.padInfo.left,xe=te/Z;for(let ge=0;ge<W;++ge)for(let _e=0;_e<Z;++_e)for(let ke=0;ke<X;++ke){let De=ke-pe,$e=Math.max(0,Math.ceil(De/ie)),Re=Math.min(K,(U+De)/ie);for(let He=0;He<Y;++He){let ut=He-ae,wt=Math.max(0,Math.ceil(ut/se)),kt=Math.min(re,(q+ut)/se),pt=0;for(let vt=$e;vt<Re;++vt){let qe=vt*ie-De;for(let Ft=wt;Ft<kt;++Ft){let po=Ft*se-ut,Zt=w*ge+v*vt+$*Ft,mo=R*(U-1-qe)+M*(q-1-po)+z*_e;for(let _r=0;_r<xe;++_r){let Bo=_e*xe+_r,Jr=_[Zt+Bo],fo=A[mo+_r];pt+=Jr*fo}}}h[g*ge+x*ke+b*He+_e]=pt}}return t.makeTensorInfo(d.shape,d.dtype,d.values)}var v2={kernelName:Jl,backendName:"cpu",kernelFunc:M5};function L5(r){let{inputs:e,backend:t}=r,{x:o}=e,n=y.sizeFromShape(o.shape),s=t.data.get(o.dataId).values,a=Ce([n,n],o.dtype),i=a.values;for(let u=0;u<s.length;u++)i[u*n+u]=s[u];let l=[...o.shape,...o.shape];return t.makeTensorInfo(l,a.dtype,a.values)}var C2={kernelName:Ql,backendName:"cpu",kernelFunc:L5};var I2={kernelName:la,backendName:"cpu",kernelFunc:({inputs:r,backend:e,attrs:t})=>{let{x:o,filter:n}=r,{strides:s,pad:a,dilations:i}=t,l=e,u=l.data.get(o.dataId).values,c=o.shape.length,p=l.data.get(n.dataId).values,m=n.shape.length,{batchSize:f,inHeight:d,inWidth:h,inChannels:g,outHeight:x,outWidth:b,padInfo:_,strideHeight:w,strideWidth:v,filterHeight:$,filterWidth:A,dilationHeight:R,dilationWidth:M,outShape:z}=N.computeDilation2DInfo(o.shape,n.shape,s,a,"NHWC",i),W=y.sizeFromShape(z),U=z.length,q=y.getArrayFromDType(o.dtype,W);for(let X=0;X<f;++X)for(let Y=0;Y<x;++Y){let te=Y*w-_.top;for(let K=0;K<b;++K){let re=K*v-_.left;for(let ie=0;ie<g;++ie){let se=Number.MIN_SAFE_INTEGER;for(let ae=0;ae<$;++ae){let xe=te+ae*R;if(xe>=0&&xe<d)for(let ge=0;ge<A;++ge){let _e=re+ge*M;if(_e>=0&&_e<h){let ke=y.locToIndex([X,xe,_e,ie],c,y.computeStrides(o.shape)),De=y.locToIndex([ae,ge,ie],m,y.computeStrides(n.shape)),$e=u[ke]+p[De];$e>se&&(se=$e)}}}let pe=y.locToIndex([X,Y,K,ie],U,y.computeStrides(z));q[pe]=se}}}return{dataId:l.write(y.toTypedArray(q,o.dtype),z,o.dtype),shape:z,dtype:o.dtype}}};var N2={kernelName:Rc,backendName:"cpu",kernelFunc:({inputs:r,backend:e,attrs:t})=>{let{x:o,filter:n,dy:s}=r,{strides:a,pad:i,dilations:l}=t,u=e,c=y.toNestedArray(o.shape,u.data.get(o.dataId).values),p=y.toNestedArray(n.shape,u.data.get(n.dataId).values),{batchSize:m,inHeight:f,inWidth:d,inChannels:h,outHeight:g,outWidth:x,padInfo:b,strideHeight:_,strideWidth:w,filterHeight:v,filterWidth:$,dilationHeight:A,dilationWidth:R,outShape:M}=N.computeDilation2DInfo(o.shape,n.shape,a,i,"NHWC",l);y.assert(s.rank===M.length,()=>`Error in ${Rc}, dy must have the same rank as output ${M.length}, but got ${s.rank}`);let z=y.toNestedArray(M,u.data.get(s.dataId).values),W=y.makeZerosNestedTypedArray(n.shape,n.dtype);for(let q=0;q<m;++q)for(let Z=0;Z<g;++Z){let X=Z*_-b.top;for(let Y=0;Y<x;++Y){let te=Y*w-b.left;for(let K=0;K<h;++K){let re=Number.MIN_SAFE_INTEGER,ie=0,se=0;for(let pe=0;pe<v;++pe){let ae=X+pe*A;if(ae>=0&&ae<f)for(let xe=0;xe<$;++xe){let ge=te+xe*R;if(ge>=0&&ge<d){let _e=c[q][ae][ge][K]+p[pe][xe][K];_e>re&&(re=_e,ie=pe,se=xe)}}}W[ie][se][K]+=z[q][Z][Y][K]}}}return{dataId:u.write(y.toTypedArray(W,o.dtype),n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}};var S2={kernelName:$c,backendName:"cpu",kernelFunc:({inputs:r,backend:e,attrs:t})=>{let{x:o,filter:n,dy:s}=r,{strides:a,pad:i,dilations:l}=t,u=e,c=y.toNestedArray(o.shape,u.data.get(o.dataId).values),p=y.toNestedArray(n.shape,u.data.get(n.dataId).values),{batchSize:m,inHeight:f,inWidth:d,inChannels:h,outHeight:g,outWidth:x,padInfo:b,strideHeight:_,strideWidth:w,filterHeight:v,filterWidth:$,dilationHeight:A,dilationWidth:R,outShape:M}=N.computeDilation2DInfo(o.shape,n.shape,a,i,"NHWC",l);y.assert(s.rank===M.length,()=>`Error in ${$c}, dy must have the same rank as output ${M.length}, but got ${s.rank}`);let z=y.toNestedArray(M,u.data.get(s.dataId).values),W=y.makeZerosNestedTypedArray(o.shape,o.dtype);for(let q=0;q<m;++q)for(let Z=0;Z<g;++Z){let X=Z*_-b.top;for(let Y=0;Y<x;++Y){let te=Y*w-b.left;for(let K=0;K<h;++K){let re=Number.MIN_SAFE_INTEGER,ie=X<0?0:X,se=te<0?0:te;for(let pe=0;pe<v;++pe){let ae=X+pe*A;if(ae>=0&&ae<f)for(let xe=0;xe<$;++xe){let ge=te+xe*R;if(ge>=0&&ge<d){let _e=c[q][ae][ge][K]+p[pe][xe][K];_e>re&&(re=_e,ie=ae,se=ge)}}}W[q][ie][se][K]+=z[q][Z][Y][K]}}}return{dataId:u.write(y.toTypedArray(W,o.dtype),o.shape,o.dtype),shape:o.shape,dtype:o.dtype}}};function z5(r){let{inputs:e,backend:t}=r,{dy:o,y:n}=e;ee([o,n],"eluGrad");let s=new Float32Array(y.sizeFromShape(n.shape)),a=t.data.get(n.dataId).values,i=t.data.get(o.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(n.shape,"float32",s)}var T2={kernelName:eu,backendName:"cpu",kernelFunc:z5};var B5=Ye((r,e)=>r===e?1:0),Jk=ot(ii,B5,null,"bool"),E2={kernelName:ii,backendName:"cpu",kernelFunc:Jk};var V5=N.ERF_P,G5=N.ERF_A1,W5=N.ERF_A2,U5=N.ERF_A3,j5=N.ERF_A4,H5=N.ERF_A5,q5=Ae(si,r=>{let e=Math.sign(r),t=Math.abs(r),o=1/(1+V5*t);return e*(1-((((H5*o+j5)*o+U5)*o+W5)*o+G5)*o*Math.exp(-t*t))}),A2={kernelName:si,backendName:"cpu",kernelFunc:q5};function Lp(r){let{inputs:e,backend:t,attrs:o}=r,{input:n}=e,{dim:s}=o,a=n.shape.length,i=n.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),tt({inputs:{x:n},backend:t,attrs:{shape:i}})}var D2={kernelName:as,backendName:"cpu",kernelFunc:Lp};var K5=Ye((r,e)=>r/e),Yd=ot(Qo,K5),Zd={kernelName:Qo,backendName:"cpu",kernelFunc:Yd};function Ix(r,e,t){let o=r.shape,n=o[0],s=o[1],a=t.data.get(r.dataId),i=a.complexTensorInfos.real,l=a.complexTensorInfos.imag,u=[n,s],c=y.sizeFromShape(u),p=y.getTypedArrayFromDType("float32",c),m=y.getTypedArrayFromDType("float32",c);for(let g=0;g<n;g++){let x=Jn({inputs:{x:i},backend:t,attrs:{begin:[g,0],size:[1,s]}}),b=Jn({inputs:{x:l},backend:t,attrs:{begin:[g,0],size:[1,s]}}),_=cr({inputs:{real:x,imag:b},backend:t}),{real:w,imag:v}=X5(_,e,t),$=N.mergeRealAndImagArrays(w,v);for(let A=0;A<s;A++){let R=N.getComplexWithIndex($,A);p[g*s+A]=R.real,m[g*s+A]=R.imag}t.disposeIntermediateTensorInfo(x),t.disposeIntermediateTensorInfo(b),t.disposeIntermediateTensorInfo(_)}let f=t.makeTensorInfo(u,"float32",p),d=t.makeTensorInfo(u,"float32",m),h=cr({inputs:{real:f,imag:d},backend:t});return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(d),h}function X5(r,e,t){let o=y.sizeFromShape(r.shape),n=t.data.get(r.dataId),s=t.data.get(n.complexTensorInfos.real.dataId).values,a=t.data.get(n.complexTensorInfos.imag.dataId).values;if(Y5(o)){let i=Qk(s,a,o,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(o,"float32")),m=Tr({inputs:{x:p},backend:t}),f=Zd.kernelFunc({inputs:{a:u,b:p},backend:t}),d=Zd.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=N.mergeRealAndImagArrays(s,a),l=Z5(i,o,e);return N.splitRealAndImagArrays(l)}}function Y5(r){return(r&r-1)==0}function Qk(r,e,t,o,n){if(t===1)return{real:r,imag:e};let s=N.mergeRealAndImagArrays(r,e),a=t/2,i=N.complexWithEvenIndex(s),l=i.real,u=i.imag,c=[l.length],p=n.makeTensorInfo(c,"float32",l),m=n.makeTensorInfo(c,"float32",u),f=cr({inputs:{real:p,imag:m},backend:n}),d=N.complexWithOddIndex(s),h=d.real,g=d.imag,x=[h.length],b=n.makeTensorInfo(x,"float32",h),_=n.makeTensorInfo(x,"float32",g),w=cr({inputs:{real:b,imag:_},backend:n}),v=Qk(l,u,a,o,n),$=v.real,A=v.imag,R=[$.length],M=n.makeTensorInfo(R,"float32",$),z=n.makeTensorInfo(R,"float32",A),W=cr({inputs:{real:M,imag:z},backend:n}),U=Qk(h,g,a,o,n),q=U.real,Z=U.imag,X=[q.length],Y=n.makeTensorInfo(X,"float32",q),te=n.makeTensorInfo(X,"float32",Z),K=cr({inputs:{real:Y,imag:te},backend:n}),re=N.exponents(t,o),ie=[re.real.length],se=n.makeTensorInfo(ie,"float32",re.real),pe=n.makeTensorInfo(ie,"float32",re.imag),ae=cr({inputs:{real:se,imag:pe},backend:n}),xe=jd({inputs:{a:ae,b:K},backend:n}),ge=Ga({inputs:{a:W,b:xe},backend:n}),_e=Xd({inputs:{a:W,b:xe},backend:n}),ke=Kn({inputs:{input:ge},backend:n}),De=Kn({inputs:{input:_e},backend:n}),$e=Ki({inputs:{input:ge},backend:n}),Re=Ki({inputs:{input:_e},backend:n}),He=vl({inputs:[ke,De],backend:n,attrs:{axis:0}}),ut=vl({inputs:[$e,Re],backend:n,attrs:{axis:0}}),wt=n.data.get(He.dataId).values,kt=n.data.get(ut.dataId).values;return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(_),n.disposeIntermediateTensorInfo(w),n.disposeIntermediateTensorInfo(M),n.disposeIntermediateTensorInfo(z),n.disposeIntermediateTensorInfo(W),n.disposeIntermediateTensorInfo(Y),n.disposeIntermediateTensorInfo(te),n.disposeIntermediateTensorInfo(K),n.disposeIntermediateTensorInfo(se),n.disposeIntermediateTensorInfo(pe),n.disposeIntermediateTensorInfo(ae),n.disposeIntermediateTensorInfo(xe),n.disposeIntermediateTensorInfo(ge),n.disposeIntermediateTensorInfo(_e),n.disposeIntermediateTensorInfo(ke),n.disposeIntermediateTensorInfo($e),n.disposeIntermediateTensorInfo(De),n.disposeIntermediateTensorInfo(Re),n.disposeIntermediateTensorInfo(He),n.disposeIntermediateTensorInfo(ut),{real:wt,imag:kt}}function Z5(r,e,t){let o=new Float32Array(e*2);for(let n=0;n<e;n++){let s=0,a=0;for(let i=0;i<e;i++){let l=N.exponent(n*i,e,t),u=N.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),N.assignToTypedArray(o,s,a,n)}return o}function J5(r){let{inputs:e,backend:t}=r,{input:o}=e,n=y.sizeFromShape(o.shape),s=o.shape[o.shape.length-1],a=n/s,i=tt({inputs:{x:o},backend:t,attrs:{shape:[a,s]}}),l=Ix(i,!1,t),u=tt({inputs:{x:l},backend:t,attrs:{shape:o.shape}});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(l),u}var $2={kernelName:tu,backendName:"cpu",kernelFunc:J5};function Jd(r){let{backend:e,attrs:t}=r,{shape:o,value:n,dtype:s}=t,a=s||y.inferDtype(n),i=y.getArrayFromDType(a,y.sizeFromShape(o));return Q5(i,n,a),e.makeTensorInfo(o,a,i)}var R2={kernelName:ua,backendName:"cpu",kernelFunc:Jd};function Q5(r,e,t){r.fill(e)}var F2={kernelName:li,backendName:"cpu",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{image:o}=r,n=t,s=y.getTypedArrayFromDType(o.dtype,y.sizeFromShape(o.shape)),[a,i,l,u]=o.shape,c=n.data.get(o.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 w=[a,d,g,b][2],v=Math.round(l-w),$=f+h+x+b,A=c[$];if(v>=0&&v<l){let R=v*u,M=f+h+R+b;A=c[M]}s[$]=A}}}}return{dataId:n.write(s,o.shape,o.dtype),shape:o.shape,dtype:o.dtype}}};var eX=Ye((r,e)=>Math.floor(r/e)),tX=ot(rn,eX,null,"int32"),O2={kernelName:rn,backendName:"cpu",kernelFunc:tX};function rX(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s,bias:a,preluActivationWeights:i}=e,{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=o,h=Yk({inputs:{x:n,filter:s},backend:t,attrs:{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:m}});if(a){let g=h;h=Ga({inputs:{a:h,b:a},backend:t}),t.disposeIntermediateTensorInfo(g)}if(f){let g=h;h=Pp(t,h,f,i,d),t.disposeIntermediateTensorInfo(g)}return h}var P2={kernelName:_s,backendName:"cpu",kernelFunc:rX};function oX(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s,bias:a,preluActivationWeights:i}=e,{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=o,h=Zk({inputs:{x:n,filter:s},backend:t,attrs:{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:m}});if(a){let g=h;h=Ga({inputs:{a:h,b:a},backend:t}),t.disposeIntermediateTensorInfo(g)}if(f){let g=h;h=Pp(t,h,f,i,d),t.disposeIntermediateTensorInfo(g)}return h}var M2={kernelName:ws,backendName:"cpu",kernelFunc:oX};function nX(r){let{inputs:e,backend:t}=r,{params:o,indices:n}=e,s=y.sizeFromShape(o.shape),a=n.shape,i=a[a.length-1],[l,u,c,p]=N.prepareAndValidate(o,n);if(u===0)return t.makeTensorInfo(l,o.dtype,[]);let m=Ce([u,c],o.dtype),f=t.data.get(n.dataId).values,d=t.data.get(o.dataId).values;for(let h=0;h<u;h++){let g=[],x=0;for(let b=0;b<i;b++){let _=f[h*i+b];x+=_*p[b],g.push(_)}if(x<0||x>=s/c)throw new Error(`Invalid indices: ${g} does not index into ${o.shape}`);for(let b=0;b<c;b++)m.values[h*c+b]=d[x*c+b]}return t.makeTensorInfo(l,m.dtype,m.values)}var L2={kernelName:ui,backendName:"cpu",kernelFunc:nX};function sX(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,indices:s}=e,{axis:a,batchDims:i}=o;ee([n,s],"gatherV2");let l=i;i==null&&(l=0);let u=y.sizeFromShape(s.shape),c=y.parseAxisParam(a,n.shape)[0],p=N.segment_util.collectGatherOpShapeInfo(n,s,c,l),m=tt({inputs:{x:n},backend:t,attrs:{shape:[p.batchSize,p.outerSize,p.dimSize,p.sliceSize]}}),f=tt({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=Pk(g,h,d);return t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f),t.makeTensorInfo(p.outputShape,x.dtype,x.values)}var z2={kernelName:ls,backendName:"cpu",kernelFunc:sX};var iX=Ye((r,e)=>r>=e?1:0),aX=ot(nn,iX,null,"bool"),B2={kernelName:nn,backendName:"cpu",kernelFunc:aX};function lX(r){let{inputs:e,backend:t}=r,{input:o}=e,n=y.sizeFromShape(o.shape),s=o.shape[o.shape.length-1],a=n/s,i=tt({inputs:{x:o},backend:t,attrs:{shape:[a,s]}}),l=Ix(i,!0,t),u=tt({inputs:{x:l},backend:t,attrs:{shape:o.shape}});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(l),u}var V2={kernelName:ru,backendName:"cpu",kernelFunc:lX};var uX=Ae(pi,r=>Number.isFinite(r)?1:0,"bool"),G2={kernelName:pi,backendName:"cpu",kernelFunc:uX};var cX=Ae(mi,r=>Math.abs(r)===Infinity?1:0,"bool"),W2={kernelName:mi,backendName:"cpu",kernelFunc:cX};var pX=Ae(fi,r=>Number.isNaN(r)?1:0,"bool"),U2={kernelName:fi,backendName:"cpu",kernelFunc:pX};var mX=Ye((r,e)=>r<=e?1:0),fX=ot(hi,mX,null,"bool"),j2={kernelName:hi,backendName:"cpu",kernelFunc:fX};function dX(r){let{backend:e,attrs:t}=r,{start:o,stop:n,num:s}=t,a=Mk(o,n,s);return e.makeTensorInfo([a.length],"float32",a)}var H2={kernelName:nu,backendName:"cpu",kernelFunc:dX};var hX=Ae(gi,r=>Math.log1p(r)),q2={kernelName:gi,backendName:"cpu",kernelFunc:hX};var gX=Ye((r,e)=>r&&e),xX=ot(xi,gX,null,"bool"),K2={kernelName:xi,backendName:"cpu",kernelFunc:xX};var yX=Ae(Za,r=>r?0:1,"bool"),X2={kernelName:Za,backendName:"cpu",kernelFunc:yX};var bX=Ye((r,e)=>r||e),_X=ot(Ja,bX,null,"bool"),Y2={kernelName:Ja,backendName:"cpu",kernelFunc:_X};function wX(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{depthRadius:s,bias:a,alpha:i,beta:l}=o;ee(n,"LRN");let u=n.shape[3],c=u-1,p=t.data.get(n.dataId).values,m=y.sizeFromShape(n.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),_=0;for(;x<=b;x++){let w=p[x];_+=w*w}return _}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(n.shape,n.dtype,f)}var Z2={kernelName:ca,backendName:"cpu",kernelFunc:wX};function kX(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,y:s,dy:a}=e,{depthRadius:i,bias:l,alpha:u,beta:c}=o;ee(a,"LRNGrad");let p=y.sizeFromShape(a.shape),m=a.shape[3],f=t.data.get(a.dataId).values,d=t.data.get(n.dataId).values,h=t.data.get(s.dataId).values,g=new Float32Array(p),x=p;for(let b=0;b<x;b++){let _=b%m,w=b-_+Math.max(0,_-i),v=b-_+Math.min(m,_+i+1),$=0;for(let A=w;A<v;A++)$+=Math.pow(d[A],2);$=u*$+l;for(let A=w;A<v;A++){let R=-2*u*c*d[A]*h[b]/$;b===A&&(R+=Math.pow($,-c)),R*=f[b],g[A]+=R}}return t.makeTensorInfo(a.shape,n.dtype,g)}var J2={kernelName:su,backendName:"cpu",kernelFunc:kX};function ev(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{reductionIndices:s,keepDims:a}=o,i=t,l=n.shape,u=l.length,c=y.parseAxisParam(s,l),p=c,m=N.getAxesPermutation(p,u),f=i.data.get(n.dataId).values;if(m!=null){let w=new Array(u);for(let v=0;v<w.length;v++)w[v]=l[m[v]];f=Hd(f,l,n.dtype,m,w),p=N.getInnerMostAxes(p.length,u),l=w}ee(n,"max"),N.assertAxesAreInnerMostDims("max",p,u);let[d,h]=N.computeOutAndReduceShapes(l,p),g=y.sizeFromShape(h),x=Lk(f,g,d,n.dtype),b=i.write(x,d,n.dtype),_=d;return a&&(_=N.expandShapeToKeepDim(d,c)),{dataId:b,shape:_,dtype:n.dtype}}var Q2={kernelName:ln,backendName:"cpu",kernelFunc:ev};function vX(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e;ee(n,"maxPool");let{filterSize:s,strides:a,pad:i,dimRoundingMode:l}=o,u=1;y.assert(N.eitherStridesOrDilationsAreOne(a,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let c=N.computePool2DInfo(n.shape,s,a,u,i,l),p;if(c.filterWidth===1&&c.filterHeight===1&&y.arraysEqual(c.inShape,c.outShape))p=Tr({inputs:{x:n},backend:t});else{let m=t.data.get(n.dataId).values,f=y.computeStrides(n.shape),d=Mp(m,n.shape,n.dtype,f,c,"max");p=t.makeTensorInfo(c.outShape,n.dtype,d.values)}return p}var eD={kernelName:cn,backendName:"cpu",kernelFunc:vX};function CX(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{filterSize:s,strides:a,pad:i,dimRoundingMode:l,dataFormat:u}=o;ee(n,"maxPool3d");let c=N.computePool3DInfo(n.shape,s,a,1,i,l,u),p=t.data.get(n.dataId).values,m=Cx(p,n.shape,n.dtype,y.computeStrides(n.shape),c,"max");return t.makeTensorInfo(m.shape,"float32",m.values)}var tD={kernelName:pa,backendName:"cpu",kernelFunc:CX};function IX(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,{filterSize:a,strides:i,pad:l,dimRoundingMode:u}=o;ee([n,s],"maxPool3DGrad");let c=N.computePool3DInfo(s.shape,a,i,1,l,u),p=t.bufferSync(s),m=ZA(p,c),f=c.strideDepth,d=c.strideHeight,h=c.strideWidth,g=c.dilationDepth,x=c.dilationHeight,b=c.dilationWidth,_=c.effectiveFilterDepth,w=c.effectiveFilterHeight,v=c.effectiveFilterWidth,$=_-1-c.padInfo.front,A=v-1-c.padInfo.left,R=w-1-c.padInfo.top,M=Ce(s.shape,"float32"),z=t.bufferSync(n);for(let W=0;W<c.batchSize;++W)for(let U=0;U<c.inChannels;++U)for(let q=0;q<c.inDepth;++q)for(let Z=0;Z<c.inHeight;++Z)for(let X=0;X<c.inWidth;++X){let Y=q-$,te=Z-R,K=X-A,re=0;for(let ie=0;ie<_;ie+=g){let se=(Y+ie)/f;if(!(se<0||se>=c.outDepth||Math.floor(se)!==se))for(let pe=0;pe<w;pe+=x){let ae=(te+pe)/d;if(!(ae<0||ae>=c.outHeight||Math.floor(ae)!==ae))for(let xe=0;xe<v;xe+=b){let ge=(K+xe)/h;if(ge<0||ge>=c.outWidth||Math.floor(ge)!==ge)continue;let _e=_*w*v-1-m.get(W,se,ae,ge,U),ke=ie*w*v+pe*v+xe,De=_e===ke?1:0;if(De===0)continue;re+=z.get(W,se,ae,ge,U)*De}}}M.set(re,W,q,Z,X,U)}return t.makeTensorInfo(M.shape,M.dtype,M.values)}var rD={kernelName:au,backendName:"cpu",kernelFunc:IX};function NX(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s,output:a}=e,i=s;ee([s,a],"maxPoolGrad");let{filterSize:l,strides:u,pad:c,dimRoundingMode:p}=o,m=N.computePool2DInfo(i.shape,l,u,1,c,p),f=t.data.get(i.dataId).values,d=Ce(m.outShape,i.dtype,vx(f,i.shape,i.dtype,m).values),h=m.strideHeight,g=m.strideWidth,x=m.dilationHeight,b=m.dilationWidth,_=m.effectiveFilterHeight,w=m.effectiveFilterWidth,v=w-1-m.padInfo.left,$=_-1-m.padInfo.top,A=Ce(i.shape,"float32"),R=t.data.get(n.dataId).values,M=Ce(n.shape,"float32",R);for(let z=0;z<m.batchSize;++z)for(let W=0;W<m.inChannels;++W)for(let U=0;U<m.inHeight;++U)for(let q=0;q<m.inWidth;++q){let Z=U-$,X=q-v,Y=0;for(let te=0;te<_;te+=x){let K=(Z+te)/h;if(!(K<0||K>=m.outHeight||Math.floor(K)!==K))for(let re=0;re<w;re+=b){let ie=(X+re)/g;if(ie<0||ie>=m.outWidth||Math.floor(ie)!==ie)continue;let se=_*w-1-d.get(z,K,ie,W),pe=te*w+re,ae=se===pe?1:0;if(ae===0)continue;Y+=M.get(z,K,ie,W)*ae}}A.set(Y,z,U,q,W)}return t.makeTensorInfo(A.shape,A.dtype,A.values)}var oD={kernelName:iu,backendName:"cpu",kernelFunc:NX};function nD(r,e,t,o,n){let s=y.computeStrides(e),a=Mp(r,e,t,s,n,"max"),i=vx(r,e,t,n,!0,o);return[a.values,i.values]}var sD={kernelName:lu,backendName:"cpu",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{x:o}=r,{filterSize:n,strides:s,pad:a,includeBatchInIndex:i}=e,l=t;ee(o,"MaxPoolWithArgmax");let u=l.data.get(o.dataId).values,c=N.computePool2DInfo(o.shape,n,s,[1,1],a),[p,m]=nD(u,o.shape,o.dtype,i,c),f=l.write(p,c.outShape,o.dtype),d=l.write(m,c.outShape,o.dtype);return[{dataId:f,shape:c.outShape,dtype:o.dtype},{dataId:d,shape:c.outShape,dtype:"int32"}]}};function nc(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o;ee(n,"sum");let i;n.dtype==="bool"?i=Xn({inputs:{x:n},backend:t,attrs:{dtype:"int32"}}):i=Tr({inputs:{x:n},backend:t});let l=i.shape.length,u=y.parseAxisParam(s,i.shape),c=N.getAxesPermutation(u,l),p=u,m=i;c!=null&&(m=tr({inputs:{x:i},backend:t,attrs:{perm:c}}),p=N.getInnerMostAxes(p.length,l)),N.assertAxesAreInnerMostDims("sum",p,m.shape.length);let[f,d]=N.computeOutAndReduceShapes(m.shape,p),h=N.upcastType(m.dtype,"int32"),g=Fp(t,f,h),x=y.sizeFromShape(d),b=t.data.get(g.dataId).values,_=t.data.get(m.dataId).values;for(let w=0;w<b.length;++w){let v=w*x,$=0;for(let A=0;A<x;++A)$+=_[v+A];b[w]=$}if(a){let w=N.expandShapeToKeepDim(g.shape,u),v=g;g=tt({inputs:{x:g},backend:t,attrs:{shape:w}}),t.disposeIntermediateTensorInfo(v)}return t.disposeIntermediateTensorInfo(i),c!=null&&t.disposeIntermediateTensorInfo(m),g}var iD={kernelName:Tn,backendName:"cpu",kernelFunc:nc};function SX(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o,i=y.parseAxisParam(s,n.shape),u=N.computeOutAndReduceShapes(n.shape,i)[1],c=y.sizeFromShape(u),p=[],m=t.makeTensorInfo([],"float32",new Float32Array([c]));p.push(m);let f=Xn({inputs:{x:n},backend:t,attrs:{dtype:"float32"}});p.push(f);let d=Yd({inputs:{a:f,b:m},backend:t});p.push(d);let h=nc({inputs:{x:d},backend:t,attrs:{axis:s,keepDims:a}});return p.forEach(g=>t.disposeIntermediateTensorInfo(g)),h}var aD={kernelName:pn,backendName:"cpu",kernelFunc:SX};function TX(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o;ee(n,"min");let i=y.parseAxisParam(s,n.shape),l=i,u=N.getAxesPermutation(l,n.shape.length),c=n;u!=null&&(c=tr({inputs:{x:n},backend:t,attrs:{perm:u}}),l=N.getInnerMostAxes(l.length,n.shape.length)),N.assertAxesAreInnerMostDims("min",l,c.shape.length);let[p,m]=N.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,_=h[b];for(let w=0;w<f;++w){let v=h[b+w];v<_&&(_=v)}d[x]=_}u!=null&&t.disposeIntermediateTensorInfo(c);let g=t.makeTensorInfo(p,c.dtype,d);if(a){let x=N.expandShapeToKeepDim(p,i),b=tt({inputs:{x:g},backend:t,attrs:{shape:x}});return t.disposeIntermediateTensorInfo(g),b}return g}var lD={kernelName:mn,backendName:"cpu",kernelFunc:TX};function EX(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{paddings:s,mode:a}=o;ee(n,"mirrorPad");let i=s.map((_,w)=>_[0]+n.shape[w]+_[1]),l=s.map(_=>_[0]),u=s.map((_,w)=>_[0]+n.shape[w]),c=a==="reflect"?0:1,p=t.data.get(n.dataId).values,m=n.shape.length,f=y.computeStrides(n.shape),d=y.sizeFromShape(i),h=i.length,g=y.computeStrides(i),x=y.getTypedArrayFromDType(n.dtype,d);for(let _=0;_<d;_++){let w=y.indexToLoc(_,h,g);for(let $=0;$<h;$++)w[$]<l[$]?w[$]=l[$]*2-w[$]-c:w[$]>=u[$]&&(w[$]=(u[$]-1)*2-w[$]+c);w=w.map(($,A)=>$-l[A]);let v=y.locToIndex(w,m,f);x[_]=p[v]}return{dataId:t.write(x,i,n.dtype),shape:i,dtype:n.dtype}}var uD={kernelName:ma,backendName:"cpu",kernelFunc:EX};var AX=Ye((r,e)=>{let t=r%e;return r<0&&e<0||r>=0&&e>=0?t:(t+e)%e}),DX=ot(yi,AX),cD={kernelName:yi,backendName:"cpu",kernelFunc:DX};var mD=Sc(jm());function tv(r){let{inputs:e,backend:t,attrs:o}=r,{logits:n}=e,{dim:s}=o,a=n.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],n.shape),u=ev({inputs:{x:n},backend:t,attrs:{reductionIndices:l,keepDims:!1}}),c=N.expandShapeToKeepDim(u.shape,l),p=tt({inputs:{x:u},backend:t,attrs:{shape:c}}),m=Xd({inputs:{a:n,b:p},backend:t}),f=Ok({inputs:{x:m},backend:t}),d=nc({inputs:{x:f},backend:t,attrs:{axis:l,keepDims:!1}}),h=tt({inputs:{x:d},backend:t,attrs:{shape:c}}),g=Yd({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 pD={kernelName:En,backendName:"cpu",kernelFunc:tv};function $X(r){let{inputs:e,backend:t,attrs:o}=r,{logits:n}=e,{numSamples:s,seed:a,normalized:i}=o;ee(n,"multinomial");let l=i?n:tv({inputs:{logits:n},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 _=1;_<g.length;++_)g[_]=g[_-1]+p[h+_];let x=mD.alea(a.toString()),b=d*s;for(let _=0;_<s;++_){let w=x();f[b+_]=g.length;for(let v=0;v<g.length;v++)if(w<g[v]){f[b+_]=v;break}}}return i||t.disposeIntermediateTensorInfo(l),t.makeTensorInfo(m,"int32",f)}var fD={kernelName:uu,backendName:"cpu",kernelFunc:$X};var RX=Sr.nonMaxSuppressionV3Impl;function FX(r){let{inputs:e,backend:t,attrs:o}=r,{boxes:n,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:l}=o;ee(n,"NonMaxSuppression");let u=t.data.get(n.dataId).values,c=t.data.get(s.dataId).values,{selectedIndices:p}=RX(u,c,a,i,l);return t.makeTensorInfo([p.length],"int32",new Int32Array(p))}var dD={kernelName:_i,backendName:"cpu",kernelFunc:FX};var OX=Sr.nonMaxSuppressionV4Impl;function PX(r){let{inputs:e,backend:t,attrs:o}=r,{boxes:n,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:l,padToMaxOutputSize:u}=o;ee(n,"NonMaxSuppressionPadded");let c=t.data.get(n.dataId).values,p=t.data.get(s.dataId).values,{selectedIndices:m,validOutputs:f}=OX(c,p,a,i,l,u);return[t.makeTensorInfo([m.length],"int32",new Int32Array(m)),t.makeTensorInfo([],"int32",new Int32Array([f]))]}var hD={kernelName:wi,backendName:"cpu",kernelFunc:PX};var MX=Sr.nonMaxSuppressionV5Impl;function LX(r){let{inputs:e,backend:t,attrs:o}=r,{boxes:n,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:l,softNmsSigma:u}=o;ee(n,"NonMaxSuppressionWithScore");let c=t.data.get(n.dataId).values,p=t.data.get(s.dataId).values,m=a,f=i,d=l,h=u,{selectedIndices:g,selectedScores:x}=MX(c,p,m,f,d,h);return[t.makeTensorInfo([g.length],"int32",new Int32Array(g)),t.makeTensorInfo([x.length],"float32",new Float32Array(x))]}var gD={kernelName:ki,backendName:"cpu",kernelFunc:LX};function zX(r){let{inputs:e,backend:t,attrs:o}=r,{indices:n}=e,{depth:s,onValue:a,offValue:i}=o;ee(n,"oneHot");let l=y.sizeFromShape(n.shape),u=new Float32Array(l*s);u.fill(i);let c=t.data.get(n.dataId).values;for(let p=0;p<l;++p)c[p]>=0&&c[p]<s&&(u[p*s+c[p]]=a);return t.makeTensorInfo([...n.shape,s],"int32",u)}var xD={kernelName:hn,backendName:"cpu",kernelFunc:zX};function Qd(r){let{inputs:e,backend:t}=r,{x:o}=e;if(o.dtype==="string")throw new Error("zerosLike is not supported for string tensors");if(o.dtype==="complex64"){let n=Kn({inputs:{input:o},backend:t}),s=Qd({inputs:{x:n},backend:t}),a=Ki({inputs:{input:o},backend:t}),i=Qd({inputs:{x:a},backend:t}),l=cr({inputs:{real:s,imag:i},backend:t});return t.disposeIntermediateTensorInfo(n),t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),l}else return Jd({backend:t,attrs:{shape:o.shape,value:0,dtype:o.dtype}})}var yD={kernelName:ys,backendName:"cpu",kernelFunc:Qd};function bD(r){let{inputs:e,backend:t}=r,{x:o}=e;if(o.dtype==="string")throw new Error("onesLike is not supported for string tensors");if(o.dtype==="complex64"){let n=Kn({inputs:{input:o},backend:t}),s=bD({inputs:{x:n},backend:t}),a=Ki({inputs:{input:o},backend:t}),i=Qd({inputs:{x:a},backend:t}),l=cr({inputs:{real:s,imag:i},backend:t});return t.disposeIntermediateTensorInfo(n),t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),l}else return Jd({backend:t,attrs:{shape:o.shape,value:1,dtype:o.dtype}})}var _D={kernelName:ps,backendName:"cpu",kernelFunc:bD};function rv(r){let{inputs:e,backend:t,attrs:o}=r,{axis:n}=o;if(e.length===1)return Lp({inputs:{input:e[0]},backend:t,attrs:{dim:n}});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=Lp({inputs:{input:c},backend:t,attrs:{dim:n}});return i.push(p),p}),u=vl({inputs:l,backend:t,attrs:{axis:n}});return i.forEach(c=>t.disposeIntermediateTensorInfo(c)),u}var wD={kernelName:ms,backendName:"cpu",kernelFunc:rv};function BX(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{paddings:s,constantValue:a}=o;ee(n,"pad");let i=s.map((b,_)=>b[0]+n.shape[_]+b[1]),l=s.map(b=>b[0]),u=t.data.get(n.dataId).values,c=y.sizeFromShape(n.shape),p=n.shape.length,m=y.computeStrides(n.shape),f=y.sizeFromShape(i),d=i.length,h=y.computeStrides(i),g=y.getTypedArrayFromDType(n.dtype,f);a!==0&&g.fill(a);for(let b=0;b<c;b++){let w=y.indexToLoc(b,p,m).map(($,A)=>$+l[A]),v=y.locToIndex(w,d,h);g[v]=u[b]}return{dataId:t.write(g,i,n.dtype),shape:i,dtype:n.dtype}}var Nx={kernelName:gn,backendName:"cpu",kernelFunc:BX};var VX=Ye((r,e)=>Math.pow(r,e)),GX=ot(xn,VX),kD={kernelName:xn,backendName:"cpu",kernelFunc:GX};function WX(r){let{backend:e,attrs:t}=r,{start:o,stop:n,dtype:s,step:a}=t,i=qd(o,n,a,s);return e.makeTensorInfo([i.length],s,i)}var vD={kernelName:fa,backendName:"cpu",kernelFunc:WX};var UX=Ae(Ci,r=>1/r),CD={kernelName:Ci,backendName:"cpu",kernelFunc:UX};function jX(r){let{inputs:e,backend:t,attrs:o}=r,{images:n}=e,{alignCorners:s,halfPixelCenters:a,size:i}=o;ee(n,"resizeBilinear");let l=y.computeStrides(n.shape),[u,c]=i,[p,m,f,d]=n.shape,h=t.data.get(n.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],_=0,w=x[0]/b[0],v=x[1]/b[1];for(let $=0;$<p;$++)for(let A=0;A<u;A++){let R;a?R=w*(A+.5)-.5:R=w*A;let M=Math.max(0,Math.floor(R)),z=R-M,W=Math.min(m-1,Math.ceil(R)),U=$*l[0]+M*l[1],q=$*l[0]+W*l[1];for(let Z=0;Z<c;Z++){let X;a?X=v*(Z+.5)-.5:X=v*Z;let Y=Math.max(0,Math.floor(X)),te=X-Y,K=Math.min(f-1,Math.ceil(X)),re=U+Y*l[2],ie=q+Y*l[2],se=U+K*l[2],pe=q+K*l[2];for(let ae=0;ae<d;ae++){let xe=h[re+ae],ge=h[ie+ae],_e=h[se+ae],ke=h[pe+ae],De=xe+(_e-xe)*te,$e=ge+(ke-ge)*te,Re=De+($e-De)*z;g[_++]=Re}}}return t.makeTensorInfo([p,u,c,d],"float32",g)}var ID={kernelName:_n,backendName:"cpu",kernelFunc:jX};function HX(r){let{inputs:e,backend:t,attrs:o}=r,{images:n,dy:s}=e,{alignCorners:a}=o;ee([s,n],"resizeBilinearGrad");let i=y.computeStrides(n.shape),[l,u,c,p]=n.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],_=t.data.get(s.dataId).values,w=0;for(let v=0;v<l;v++){let $=v*i[0];for(let A=0;A<m;A++){let R=A*x,M=Math.floor(R),z=Math.min(Math.ceil(R),u-1),W=$+M*i[1],U=$+z*i[1],q=R-M,Z=1-q;for(let X=0;X<f;X++){let Y=X*b,te=Math.floor(Y),K=Math.min(Math.ceil(Y),c-1),re=Y-te,ie=1-re,se=W+te*i[2],pe=W+K*i[2],ae=U+te*i[2],xe=U+K*i[2],ge=Z*ie,_e=Z*re,ke=q*ie,De=q*re;for(let $e=0;$e<p;$e++){let Re=_[w++];d[se+$e]+=Re*ge,d[pe+$e]+=Re*_e,d[ae+$e]+=Re*ke,d[xe+$e]+=Re*De}}}}return t.makeTensorInfo([l,c,u,p],"float32",d)}var ND={kernelName:mu,backendName:"cpu",kernelFunc:HX};function qX(r){let{inputs:e,backend:t,attrs:o}=r,{images:n}=e,{alignCorners:s,halfPixelCenters:a,size:i}=o;ee(n,"resizeNearestNeighbor");let l=y.computeStrides(n.shape),[u,c]=i,[p,m,f,d]=n.shape,h=t.data.get(n.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],_=x[0]/b[0],w=x[1]/b[1],v=0;for(let $=0;$<p;$++){let A=$*l[0];for(let R=0;R<u;R++){let M=a?_*(R+.5):_*R,z=Math.min(m-1,s?Math.round(M):Math.floor(M));a&&(z=Math.max(0,z));let W=A+z*l[1];for(let U=0;U<c;U++){let q=a?w*(U+.5):w*U,Z=Math.min(f-1,s?Math.round(q):Math.floor(q));a&&(Z=Math.max(0,Z));let X=W+Z*l[2];for(let Y=0;Y<d;Y++){let te=h[X+Y];g[v++]=te}}}}return t.makeTensorInfo([p,u,c,d],n.dtype,g)}var SD={kernelName:da,backendName:"cpu",kernelFunc:qX};function KX(r){let{inputs:e,backend:t,attrs:o}=r,{images:n,dy:s}=e,{alignCorners:a}=o;ee([s,n],"resizeNearestNeighborGrad");let i=y.computeStrides(n.shape),l=y.computeStrides(s.shape),[u,c,p,m]=n.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],_=x[0]/b[0],w=x[1]/b[1],v=1/_,$=1/w,A=Math.ceil(v)*2+2,R=Math.ceil($)*2+2;for(let M=0;M<u;M++){let z=M*i[0];for(let W=0;W<c;W++){let U=z+W*i[1],q=Math.floor(W*v),Z=Math.floor(q-A/2);for(let X=0;X<p;X++){let Y=U+X*i[2],te=Math.floor(X*$),K=Math.floor(te-R/2);for(let re=0;re<m;re++){let ie=0;for(let se=0;se<A;se++){let pe=se+Z;if(pe<0||pe>=f)continue;let ae=z+pe*l[1],xe=pe*_,ge=Math.min(c-1,a?Math.round(xe):Math.floor(xe));if(W===ge)for(let _e=0;_e<R;_e++){let ke=_e+K;if(ke<0||ke>=d)continue;let De=ae+ke*l[2],$e=ke*w,Re=Math.min(p-1,a?Math.round($e):Math.floor($e));X===Re&&(ie+=g[De+re])}}h[Y+re]=ie}}}}return t.makeTensorInfo(n.shape,n.dtype,h)}var TD={kernelName:pu,backendName:"cpu",kernelFunc:KX};function XX(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{dims:s}=o;ee(n,"reverse");let a=n.shape.length,i=y.parseAxisParam(s,n.shape);if(a===0)return Tr({inputs:{x:n},backend:t});let l=new ct(n.shape,n.dtype),u=t.bufferSync(n);for(let c=0;c<l.size;c++){let p=l.indexToLoc(c),m=p.slice();i.forEach(f=>m[f]=n.shape[f]-1-m[f]),l.set(u.get(...m),...p)}return t.makeTensorInfo(l.shape,l.dtype,l.values)}var ED={kernelName:kn,backendName:"cpu",kernelFunc:XX};var AD={kernelName:Ri,backendName:"cpu",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{image:o}=r,{radians:n,fillValue:s,center:a}=e,i=t,l=y.getTypedArrayFromDType(o.dtype,y.sizeFromShape(o.shape)),[u,c,p,m]=o.shape,[f,d]=N.getImageCenter(a,c,p),h=255,g=Math.sin(n),x=Math.cos(n),b=i.data.get(o.dataId).values;for(let w=0;w<u;w++){let v=w*p*c*m;for(let $=0;$<c;$++){let A=$*(p*m);for(let R=0;R<p;R++){let M=R*m;for(let z=0;z<m;z++){let W=[u,$,R,z],U=W[2],q=W[1],Z=(U-f)*x-(q-d)*g,X=(U-f)*g+(q-d)*x;Z=Math.round(Z+f),X=Math.round(X+d);let Y=s;if(typeof s!="number"&&(z===3?Y=h:Y=s[z]),Z>=0&&Z<p&&X>=0&&X<c){let K=X*(p*m),re=Z*m,ie=v+K+re+z;Y=b[ie]}let te=v+A+M+z;l[te]=Y}}}}return{dataId:i.write(l,o.shape,o.dtype),shape:o.shape,dtype:o.dtype}}};var YX=Ae(vn,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}),DD={kernelName:vn,backendName:"cpu",kernelFunc:YX};function Sx(r,e,t,o,n,s,a,i,l,u){let c=[o/n,n],p=r.values,m=e.values;if(o===0)return Ce(t,e.dtype);let f=Ce(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>=o/n)throw new Error(`Invalid indices: ${h} does not index into ${t}`);for(let x=0;x<n;x++)u?f.values[g*n+x]+=m[d*n+x]:f.values[g*n+x]=e.rank===0?m[0]:m[d*n+x]}return f}function ZX(r){let{inputs:e,backend:t,attrs:o}=r,{indices:n,updates:s}=e,{shape:a}=o,{sliceRank:i,numUpdates:l,sliceSize:u,strides:c,outputSize:p}=N.calculateShapes(s,n,a),m=!0,f=t.bufferSync(n),d=t.bufferSync(s),h=Sx(f,d,a,p,u,l,i,c,0,m);return t.makeTensorInfo(a,h.dtype,h.values)}var $D={kernelName:Ii,backendName:"cpu",kernelFunc:ZX};function JX(r){let{inputs:e,backend:t}=r,{condition:o,t:n,e:s}=e;ee([o,n,s],"select");let a=o.shape.length,i=t.data.get(o.dataId).values,l=t.data.get(n.dataId).values,u=t.data.get(s.dataId).values,c=mr(n.dtype,s.dtype),p=y.makeZerosTypedArray(y.sizeFromShape(n.shape),c),m=0,f=a===0||a>1||n.shape.length===1?1:y.sizeFromShape(n.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(n.shape,c,p)}var RD={kernelName:ds,backendName:"cpu",kernelFunc:JX};var QX=N.SELU_SCALEALPHA,e8=N.SELU_SCALE,t8=Ae(Ni,r=>r>=0?e8*r:QX*(Math.exp(r)-1)),FD={kernelName:Ni,backendName:"cpu",kernelFunc:t8};var r8=Ae(Nn,r=>1/(1+Math.exp(-r))),OD={kernelName:Nn,backendName:"cpu",kernelFunc:r8};var o8=Ae(Ti,r=>r<0?-1:r>0?1:0),PD={kernelName:Ti,backendName:"cpu",kernelFunc:o8};var n8=Ae(In,r=>Math.sin(r)),MD={kernelName:In,backendName:"cpu",kernelFunc:n8};var s8=Ae(Si,r=>Math.sinh(r)),LD={kernelName:Si,backendName:"cpu",kernelFunc:s8};var i8=11920928955078125e-23,zD=Math.log(i8)+2,a8=Ae(Ei,r=>{let e=r>-zD,t=r<zD,o=Math.exp(r),n;return t?n=o:e?n=r:n=Math.log(1+o),n}),BD={kernelName:Ei,backendName:"cpu",kernelFunc:a8};function l8(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockShape:s,paddings:a}=o;ee([n],"spaceToBatchND");let i=y.sizeFromShape(s),l=[[0,0]];l.push(...a);for(let $=1+s.length;$<n.shape.length;++$)l.push([0,0]);let u=Nx.kernelFunc({inputs:{x:n},backend:t,attrs:{paddings:l,constantValue:0}}),c=N.getReshaped(u.shape,s,i,!1),p=N.getPermuted(c.length,s.length,!1),m=N.getReshapedPermuted(u.shape,s,i,!1),h=tt({inputs:{x:u},backend:t,attrs:{shape:c}}),b=tr({inputs:{x:h},backend:t,attrs:{perm:p}}),v=tt({inputs:{x:b},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(u),t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(b),v}var VD={kernelName:ha,backendName:"cpu",kernelFunc:l8};function u8(r){let{inputs:e,backend:t,attrs:o}=r,{sparseIndices:n,sparseValues:s,defaultValue:a}=e,{outputShape:i}=o,{sliceRank:l,numUpdates:u,sliceSize:c,strides:p,outputSize:m}=N.calculateShapes(s,n,i),f=!1,d=t.bufferSync(n),h=t.bufferSync(s),g=t.data.get(a.dataId).values[0],x=Sx(d,h,i,m,c,u,l,p,g,f);return t.makeTensorInfo(i,x.dtype,x.values)}var GD={kernelName:fu,backendName:"cpu",kernelFunc:u8};function c8(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{numOrSizeSplits:s,axis:a}=o,i=y.parseAxisParam(a,n.shape)[0],l=N.prepareSplitSize(n,s,i),u=new Array(n.shape.length).fill(0),c=n.shape.slice();return l.map(p=>{let m=[...c];m[i]=p;let f=Jn({inputs:{x:n},backend:t,attrs:{begin:u,size:m}});return u[i]+=p,f})}var WD={kernelName:gs,backendName:"cpu",kernelFunc:c8};var p8=Ae(Sn,r=>Math.sqrt(r)),UD={kernelName:Sn,backendName:"cpu",kernelFunc:p8};var jD={kernelName:ga,backendName:"cpu",kernelFunc:({inputs:r,backend:e})=>{let{x:t}=r,o=e;ee(t,"square");let n=o.data.get(t.dataId).values,s=new Float32Array(n.length);for(let i=0;i<n.length;++i){let l=n[i];s[i]=l*l}return{dataId:o.write(s,t.shape,t.dtype),shape:t.shape,dtype:t.dtype}}};var m8=Ae(Do,(r,e)=>{let t=e;return isNaN(r)?NaN:r>0?1:t.alpha}),HD={kernelName:Do,backendName:"cpu",kernelFunc:m8};function f8(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{begin:s,end:a,strides:i,beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:m}=o;ee(n,"stridedSlice");let{nonStrided:f,$begin:d,$strides:h,size:g,newShape:x,outShape:b}=or.sliceInfo(n.shape,s,a,i,l,u,c,p,m),_=tt({inputs:{x:n},backend:t,attrs:{shape:x}}),w;if(f){let $=Jn({inputs:{x:_},backend:t,attrs:{begin:d,size:g}});w=tt({inputs:{x:$},backend:t,attrs:{shape:b}}),t.disposeIntermediateTensorInfo($)}else if(b.some($=>$===0))w=t.makeTensorInfo(b,n.dtype,[]);else{let $=t.bufferSync(_),A=zk(b,$,h,d);w=t.makeTensorInfo(A.shape,A.dtype,A.values)}let v=tt({inputs:{x:w},backend:t,attrs:{shape:b}});return t.disposeIntermediateTensorInfo(_),t.disposeIntermediateTensorInfo(w),v}var qD={kernelName:Ai,backendName:"cpu",kernelFunc:f8};var d8=Ae(Di,r=>Math.tan(r)),KD={kernelName:Di,backendName:"cpu",kernelFunc:d8};var h8=Ae($n,r=>Math.tanh(r)),XD={kernelName:$n,backendName:"cpu",kernelFunc:h8};function g8(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{reps:s}=o;ee(n,"tile");let a=Bk(t.bufferSync(n),s);return t.makeTensorInfo(a.shape,a.dtype,a.values)}var YD={kernelName:yo,backendName:"cpu",kernelFunc:g8};function x8(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{k:s,sorted:a}=o;ee(n,"topk");let i=t.data.get(n.dataId).values,[l,u]=Vk(i,n.shape,n.dtype,s,a);return[t.makeTensorInfo(l.shape,l.dtype,l.values),t.makeTensorInfo(u.shape,u.dtype,u.values)]}var ZD={kernelName:$i,backendName:"cpu",kernelFunc:x8};function y8(r){let{inputs:e,attrs:t,backend:o}=r,{axis:n}=t,{x:s}=e;ee(s,"unique");let a=o.data.get(s.dataId).values,{outputValues:i,outputShape:l,indices:u}=Gk(a,n,s.shape,s.dtype);return[o.makeTensorInfo(l,s.dtype,i),o.makeTensorInfo([u.length],"int32",u)]}var JD={kernelName:du,backendName:"cpu",kernelFunc:y8};function b8(r){let{inputs:e,backend:t,attrs:o}=r,{value:n}=e,{axis:s}=o;s<0&&(s+=n.shape.length);let a=n.shape.length,i=n.shape[s],l=new Array(a-1),u=0;for(let f=0;f<a;f++)f!==s&&(l[u++]=n.shape[f]);let c=new Array(a).fill(0),p=n.shape.slice();p[s]=1;let m=new Array(i);for(let f=0;f<m.length;f++){c[s]=f;let d=Jn({inputs:{x:n},backend:t,attrs:{begin:c,size:p}});m[f]=tt({inputs:{x:d},backend:t,attrs:{shape:l}}),t.disposeIntermediateTensorInfo(d)}return m}var QD={kernelName:xs,backendName:"cpu",kernelFunc:b8};function _8(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,segmentIds:s}=e,{numSegments:a}=o;ee(n,"unsortedSegmentSum");let i=n.shape.length,l=s.shape.length,u=[],c=[],p=i-l,m=s;for(let d=0;d<p;++d){let h=Lp({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=Jk({inputs:{a:g,b:m},backend:t}),b=Xn({inputs:{x},backend:t,attrs:{dtype:"float32"}}),_=jd({inputs:{a:b,b:n},backend:t}),w=nc({inputs:{x:_},backend:t,attrs:{axis:0,keepDims:!1}});u.push(w),c.push(g),c.push(x),c.push(b),c.push(_),c.push(w)}let f=rv({inputs:u,backend:t,attrs:{axis:0}});return c.forEach(d=>t.disposeIntermediateTensorInfo(d)),f}var e$={kernelName:xa,backendName:"cpu",kernelFunc:_8};var w8=[LA,UE,zA,BA,YE,VA,GA,WA,UA,jA,HA,qA,KA,XA,YA,JA,QA,e2,t2,MA,r2,o2,n2,KE,JE,s2,jE,i2,l2,c2,p2,u2,f2,d2,m2,h2,g2,x2,y2,b2,_2,w2,k2,v2,C2,I2,S2,N2,Zd,DA,T2,E2,A2,eA,D2,rA,$2,R2,F2,nA,O2,P2,M2,L2,z2,iA,B2,HE,V2,a2,G2,W2,U2,$A,lA,j2,H2,cA,q2,K2,X2,Y2,Z2,J2,mA,eD,tD,rD,oD,sD,Q2,aD,lD,dA,uD,cD,fD,hA,xA,dD,hD,gD,bA,xD,_D,wD,Nx,kD,RA,kA,vD,qE,CD,FA,OA,PA,ID,ND,SD,TD,ED,AD,DD,CA,$D,RD,FD,OD,PD,MD,LD,IA,pD,BD,VD,GD,WD,UD,jD,SA,HD,qD,EA,iD,KD,XD,YD,ZD,_A,JD,QD,e$,yD];for(let r of w8)Qa(r);var sc={},ov={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function t$(r,e){sc[r]=e}function Lo(r){if(!(r in sc)){let t=k8(r);if(t!==null)sc[r]=t;else return console.log("Could not get context for WebGL version",r),null}let e=sc[r];return e.isContextLost()?(delete sc[r],Lo(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),sc[r])}function v8(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 k8(r){if(r!==1&&r!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let e=v8(r);return e.addEventListener("webglcontextlost",t=>{t.preventDefault(),delete sc[r]},!1),r===1?e.getContext("webgl",ov)||e.getContext("experimental-webgl",ov):e.getContext("webgl2",ov)}var Cl;(function(r){r[r.DENSE=0]="DENSE",r[r.SHARED_BATCH=1]="SHARED_BATCH"})(Cl||(Cl={}));var Er;(function(r){r[r.RENDER=0]="RENDER",r[r.UPLOAD=1]="UPLOAD",r[r.PIXELS=2]="PIXELS",r[r.DOWNLOAD=3]="DOWNLOAD"})(Er||(Er={}));var br;(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"})(br||(br={}));function ic(r,e){return[e,r]}function r$(r,e){return r*e}function Il(r){let e=y.sizeFromShape(r),t=Math.ceil(e/4);return y.sizeToSquarishShape(t)}function Xi(r,e){return[Math.max(1,Math.ceil(e/2)),Math.max(1,Math.ceil(r/2))]}function o$(r,e){let[t,o]=Xi(r,e);return t*o*4}function eh(r,e){let t=r,o,n,s,a,i,l,u,c,p,m;return G().getNumber("WEBGL_VERSION")===2?(o=t.R32F,n=t.R16F,s=t.RGBA16F,a=t.RGBA32F,i=t.RED,u=4,c=1,p=t.HALF_FLOAT,m=t.FLOAT):(o=r.RGBA,n=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:o,internalFormatHalfFloat:n,internalFormatPackedHalfFloat:s,internalFormatPackedFloat:a,textureFormatFloat:i,downloadTextureFormat:l,downloadUnpackNumChannels:u,defaultNumChannels:c,textureTypeHalfFloat:p,textureTypeFloat:m}}function Ee(r,e){let t=e();return G().getBool("DEBUG")&&C8(r),t}function C8(r){let e=r.getError();if(e!==r.NO_ERROR)throw new Error("WebGL Error: "+I8(r,e))}var N8=596e-10,S8=65504;function n$(r){return!!(G().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||r===0||N8<Math.abs(r)&&Math.abs(r)<S8)}function I8(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 th(r,e){return Wa(r,()=>r.getExtension(e),'Extension "'+e+'" not supported on this browser.')}function s$(r,e){let t=Wa(r,()=>r.createShader(r.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(Ee(r,()=>r.shaderSource(t,e)),Ee(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 i$(r,e){let t=Wa(r,()=>r.createShader(r.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(Ee(r,()=>r.shaderSource(t,e)),Ee(r,()=>r.compileShader(t)),r.getShaderParameter(t,r.COMPILE_STATUS)===!1)throw T8(e,r.getShaderInfoLog(t)),new Error("Failed to compile fragment shader.");return t}var E8=/ERROR: [0-9]+:([0-9]+):/g;function T8(r,e){let t=E8.exec(e);if(t==null){console.log(`Couldn't parse line number in error: ${e}`),console.log(r);return}let o=+t[1],n=r.split(`
|
|
`),s=n.length.toString().length+2,a=n.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,o-1),u=a.slice(o-1,o),c=a.slice(o);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 a$(r){return Wa(r,()=>r.createProgram(),"Unable to create WebGLProgram.")}function l$(r,e){if(Ee(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 Tx(r,e){if(Ee(r,()=>r.validateProgram(e)),r.getProgramParameter(e,r.VALIDATE_STATUS)===!1)throw console.log(r.getProgramInfoLog(e)),new Error("Shader program validation failed.")}function u$(r,e){let t=Wa(r,()=>r.createBuffer(),"Unable to create WebGLBuffer");return Ee(r,()=>r.bindBuffer(r.ARRAY_BUFFER,t)),Ee(r,()=>r.bufferData(r.ARRAY_BUFFER,e,r.STATIC_DRAW)),t}function c$(r,e){let t=Wa(r,()=>r.createBuffer(),"Unable to create WebGLBuffer");return Ee(r,()=>r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,t)),Ee(r,()=>r.bufferData(r.ELEMENT_ARRAY_BUFFER,e,r.STATIC_DRAW)),t}function p$(r){return Wa(r,()=>r.createTexture(),"Unable to create WebGLTexture.")}function m$(r,e){let t=G().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(r<=0||e<=0){let o=`[${r}x${e}]`;throw new Error("Requested texture size "+o+" is invalid.")}if(r>t||e>t){let o=`[${r}x${e}]`,n=`[${t}x${t}]`;throw new Error("Requested texture size "+o+" greater than WebGL maximum on this browser / GPU "+n+".")}}function f$(r){return Wa(r,()=>r.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function nv(r,e,t,o,n,s,a){let i=r.getAttribLocation(e,t);return i===-1?!1:(Ee(r,()=>r.bindBuffer(r.ARRAY_BUFFER,o)),Ee(r,()=>r.vertexAttribPointer(i,n,r.FLOAT,!1,s,a)),Ee(r,()=>r.enableVertexAttribArray(i)),!0)}function D8(r,e,t){A8(r,t),Ee(r,()=>r.activeTexture(r.TEXTURE0+t)),Ee(r,()=>r.bindTexture(r.TEXTURE_2D,e))}function d$(r,e,t){return Wa(r,()=>r.getUniformLocation(e,t),'uniform "'+t+'" not present in program.')}function h$(r,e,t){return r.getUniformLocation(e,t)}function g$(r,e,t,o){Ee(r,()=>D8(r,e,o)),Ee(r,()=>r.uniform1i(t,o))}function Ex(r,e,t){Ee(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,t)),Ee(r,()=>r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0))}function sv(r,e){Ee(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,e)),Ee(r,()=>r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,null,0))}function rh(r){let e=r.checkFramebufferStatus(r.FRAMEBUFFER);if(e!==r.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+$8(r,e))}function $8(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 o=Ee(r,()=>e());if(o==null)throw new Error(t);return o}function A8(r,e){let t=r.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,o=e+r.TEXTURE0;if(o<r.TEXTURE0||o>t){let n=`[gl.TEXTURE0, gl.TEXTURE${t}]`;throw new Error(`textureUnit must be in ${n}.`)}}function Nl(r,e=2){return y.sizeFromShape(r.slice(0,r.length-e))}function Sl(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 Ax(r){let e=[1,1,1];return r.length===0||r.length===1&&r[0]===1||(e=[Nl(r),...Sl(r)]),e}function x$(r,e=!1){let t=G().getNumber("WEBGL_MAX_TEXTURE_SIZE");e&&(t=t*2,r=r.map((n,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 o=y.sizeFromShape(r);if(r.length<=1&&o<=t)return[1,o];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 n=Nl(r),s=2,a=2;return r.length&&([s,a]=Sl(r)),o=n*(s/2)*(a/2),y.sizeToSquarishShape(o).map(i=>i*2)}return y.sizeToSquarishShape(o)}function Dx(r){return r%2==0}function ac(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],o=e.slice(-1)[0];if(t===o||Dx(t)&&Dx(o)&&(r[0]===1||e[0]===1))return!0}return r[1]===e[1]&&Dx(r[0])&&Dx(e[0])}var iv,av;function y$(r){if(iv==null){let e=Lo(r);iv=e.getParameter(e.MAX_TEXTURE_SIZE)}return iv}function b$(r){if(av==null){let e=Lo(r);av=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,av)}function _$(r){if(r===0)return 0;let e,t=Lo(r);return zo(t,"EXT_disjoint_timer_query_webgl2")&&r===2?e=2:zo(t,"EXT_disjoint_timer_query")?e=1:e=0,e}function zo(r,e){return r.getExtension(e)!=null}function lv(r){try{if(Lo(r)!=null)return!0}catch(e){return console.log("Error when getting WebGL context: ",e),!1}return!1}function w$(r){if(r===0)return!1;let e=Lo(r);if(r===1){if(!zo(e,"OES_texture_float"))return!1}else if(!zo(e,"EXT_color_buffer_float"))return!1;return uv(e)}function k$(r){if(r===0)return!1;let e=Lo(r);if(r===1){if(!zo(e,"OES_texture_float")||!zo(e,"WEBGL_color_buffer_float"))return!1}else{if(zo(e,"EXT_color_buffer_float"))return uv(e);let o="EXT_color_buffer_half_float";if(zo(e,o)){let n=e.getExtension(o);return R8(e,n)}return!1}return uv(e)}function uv(r){let e=eh(r),t=r.createTexture();r.bindTexture(r.TEXTURE_2D,t);let o=1,n=1;r.texImage2D(r.TEXTURE_2D,0,e.internalFormatFloat,o,n,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 R8(r,e){let t=eh(r,e),o=r.createTexture();r.bindTexture(r.TEXTURE_2D,o);let n=1,s=1;r.texImage2D(r.TEXTURE_2D,0,t.internalFormatHalfFloat,n,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,o,0);let i=r.checkFramebufferStatus(r.FRAMEBUFFER)===r.FRAMEBUFFER_COMPLETE;return r.bindTexture(r.TEXTURE_2D,null),r.bindFramebuffer(r.FRAMEBUFFER,null),r.deleteTexture(o),r.deleteFramebuffer(a),i}function v$(r){return r!==2?!1:Lo(r).fenceSync!=null}function Yi(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 Be=G();Be.registerFlag("HAS_WEBGL",()=>Be.getNumber("WEBGL_VERSION")>0);Be.registerFlag("WEBGL_VERSION",()=>lv(2)?2:lv(1)?1:0);Be.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);Be.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>Be.get("WEBGL_VERSION")===2);Be.registerFlag("WEBGL_CPU_FORWARD",()=>!0);Be.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);Be.registerFlag("WEBGL_PACK",()=>Be.getBool("HAS_WEBGL"));Be.registerFlag("WEBGL_PACK_NORMALIZATION",()=>Be.getBool("WEBGL_PACK"));Be.registerFlag("WEBGL_PACK_CLIP",()=>Be.getBool("WEBGL_PACK"));Be.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>!1);Be.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>Be.getBool("WEBGL_PACK"));Be.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>Be.getBool("WEBGL_PACK"));Be.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>Be.getBool("WEBGL_PACK"));Be.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>Be.getBool("WEBGL_PACK"));Be.registerFlag("WEBGL_PACK_REDUCE",()=>Be.getBool("WEBGL_PACK"));Be.registerFlag("WEBGL_LAZILY_UNPACK",()=>Be.getBool("WEBGL_PACK"));Be.registerFlag("WEBGL_CONV_IM2COL",()=>Be.getBool("WEBGL_PACK"));Be.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>y$(Be.getNumber("WEBGL_VERSION")));Be.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>b$(Be.getNumber("WEBGL_VERSION")));Be.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let r=Be.getNumber("WEBGL_VERSION");return r===0?0:_$(r)});Be.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>Be.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!Bc.isMobile());Be.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>w$(Be.getNumber("WEBGL_VERSION")));Be.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>Be.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:Be.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));Be.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>k$(Be.getNumber("WEBGL_VERSION")));Be.registerFlag("WEBGL_FENCE_API_ENABLED",()=>v$(Be.getNumber("WEBGL_VERSION")));Be.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>Be.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);Be.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}.`)});function Mt(){let r,e,t,o,n,s,a,i,l,u;return G().getNumber("WEBGL_VERSION")===2?(r="#version 300 es",e="in",t="out",o="in",n="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",o="varying",n="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:o,texture2D:n,output:s,defineOutput:a,defineSpecialNaN:i,defineSpecialInf:l,defineRound:u}}function zs(r,e,t="index"){let o=y.computeStrides(e);return o.map((n,s)=>{let a=`int ${r[s]} = ${t} / ${n}`,i=s===o.length-1?`int ${r[s+1]} = ${t} - ${r[s]} * ${n}`:`index -= ${r[s]} * ${n}`;return`${a}; ${i};`}).join("")}function zp(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 $x=`
|
|
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 cv=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Cl.DENSE;let t=Il(e),o=Mt();this.outputShape=e,this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${zs(["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);
|
|
}
|
|
|
|
${o.output} = result;
|
|
}
|
|
`}};var pv=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Cl.DENSE;let t=Il(e),o=Mt();this.outputShape=e,this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${zs(["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));
|
|
}
|
|
|
|
${o.output} = result;
|
|
}
|
|
`}};var mv=class{constructor(e){this.variableNames=["A"],this.outTexUsage=Er.DOWNLOAD;let t=Mt();this.outputShape=e,this.userCode=`
|
|
${$x}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}};var fv=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Er.DOWNLOAD;let t=Mt();this.outputShape=e,this.userCode=`
|
|
${$x}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}};var dv=class{constructor(e,t,o=!1){this.variableNames=["A"];let n=Mt(),[s,a]=t;this.outputShape=e;let i="result";o&&(i="floor(result * 255. + 0.5)"),this.userCode=`
|
|
${zp(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 = ${n.texture2D}(A, uv);
|
|
|
|
float result;
|
|
|
|
if(offset == 0) {
|
|
result = values[0];
|
|
} else if(offset == 1) {
|
|
result = values[1];
|
|
} else if(offset == 2) {
|
|
result = values[2];
|
|
} else {
|
|
result = values[3];
|
|
}
|
|
|
|
${n.output} = vec4(${i}, 0., 0., 0.);
|
|
}
|
|
`}};var hv=class{constructor(e,t,o=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let n=Mt(),[s,a]=t;this.outputShape=e;let i="",l="result";o&&(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 = ${n.texture2D}(A, uv);
|
|
|
|
if(offset == 0) {
|
|
result[${p}] = values[0];
|
|
} else if(offset == 1) {
|
|
result[${p}] = values[1];
|
|
} else if(offset == 2) {
|
|
result[${p}] = values[2];
|
|
} else {
|
|
result[${p}] = values[3];
|
|
}
|
|
}
|
|
}
|
|
`}this.userCode=`
|
|
${zp(e)}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
int flatIndex, r, c, offset;
|
|
ivec3 localCoords;
|
|
vec2 uv;
|
|
vec4 values;
|
|
|
|
${i}
|
|
|
|
${n.output} = ${l};
|
|
}
|
|
`}};function C$(r){let e=Mt(),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 s$(r,t)}function I$(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 u$(r,e)}function N$(r){let e=new Uint16Array([0,1,2,2,1,3]);return c$(r,e)}function oh(r,e,t,o,n,s){m$(e,t);let a=p$(r),i=r.TEXTURE_2D;return Ee(r,()=>r.bindTexture(i,a)),Ee(r,()=>r.texParameteri(i,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE)),Ee(r,()=>r.texParameteri(i,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE)),Ee(r,()=>r.texParameteri(i,r.TEXTURE_MIN_FILTER,r.NEAREST)),Ee(r,()=>r.texParameteri(i,r.TEXTURE_MAG_FILTER,r.NEAREST)),Ee(r,()=>r.texImage2D(i,0,o,e,t,0,n,s,null)),Ee(r,()=>r.bindTexture(r.TEXTURE_2D,null)),a}function gv(r){return r.internalFormatFloat}function S$(r,e,t,o){let[n,s]=ic(e,t);return oh(r,n,s,gv(o),o.textureFormatFloat,r.FLOAT)}function xv(r){return r.internalFormatHalfFloat}function T$(r,e,t,o){let[n,s]=ic(e,t);return oh(r,n,s,xv(o),o.textureFormatFloat,o.textureTypeHalfFloat)}function yv(r){return r.downloadTextureFormat}function E$(r,e,t,o){let[n,s]=ic(e,t);return oh(r,n,s,yv(o),r.RGBA,r.UNSIGNED_BYTE)}function bv(r){return r.internalFormatPackedFloat}function A$(r,e,t,o){let[n,s]=Xi(e,t);return oh(r,n,s,bv(o),r.RGBA,r.FLOAT)}function _v(r){return r.internalFormatPackedHalfFloat}function D$(r,e,t,o){let[n,s]=Xi(e,t);return oh(r,n,s,_v(o),r.RGBA,o.textureTypeHalfFloat)}function $$(r,e,t){let o=0,n=3*4,s=3*4+2*4;return Ee(r,()=>r.bindBuffer(r.ARRAY_BUFFER,t)),nv(r,e,"clipSpacePos",t,3,s,o)&&nv(r,e,"uv",t,2,s,n)}function R$(r,e,t,o,n,s){Ee(r,()=>r.bindTexture(r.TEXTURE_2D,e));let a,i,l;n instanceof Uint8Array?(a=new Uint8Array(t*o*4),i=r.UNSIGNED_BYTE,l=r.RGBA):(a=new Float32Array(t*o*4),i=r.FLOAT,l=s.internalFormatPackedFloat),a.set(n),Ee(r,()=>r.texImage2D(r.TEXTURE_2D,0,l,t,o,0,r.RGBA,i,a)),Ee(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function F$(r,e,t){Ee(r,()=>r.bindTexture(r.TEXTURE_2D,e)),t.data instanceof Uint8Array?Ee(r,()=>r.texImage2D(r.TEXTURE_2D,0,r.RGBA,t.width,t.height,0,r.RGBA,r.UNSIGNED_BYTE,t.data)):Ee(r,()=>r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,t)),Ee(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function O$(r,e,t,o){let n=r.createBuffer();Ee(r,()=>r.bindBuffer(r.PIXEL_PACK_BUFFER,n));let i=4*4*e*t;return Ee(r,()=>r.bufferData(r.PIXEL_PACK_BUFFER,i,r.STREAM_READ)),Ee(r,()=>r.readPixels(0,0,t,e,r.RGBA,r.FLOAT,0)),Ee(r,()=>r.bindBuffer(r.PIXEL_PACK_BUFFER,null)),n}function P$(r,e,t){let o=r,n=new Float32Array(t);return o.bindBuffer(o.PIXEL_PACK_BUFFER,e),o.getBufferSubData(o.PIXEL_PACK_BUFFER,0,n),o.bindBuffer(o.PIXEL_PACK_BUFFER,null),n}function M$(r,e,t,o){let[n,s]=ic(e,t),a=4,i=new Uint8Array(r$(e*t,a));return Ee(r,()=>r.readPixels(0,0,n,s,o.downloadTextureFormat,r.UNSIGNED_BYTE,i)),new Float32Array(i.buffer)}function L$(r,e,t,o,n,s,a,i){let l=r,u=new Float32Array(o$(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 z$(r,e,t){let o=new Float32Array(e*t*4);return Ee(r,()=>r.readPixels(0,0,t,e,r.RGBA,r.FLOAT,o)),o}var wv=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];let t=G().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,t$(t,e)):this.gl=Lo(t);let o="WEBGL_color_buffer_float",n="EXT_color_buffer_half_float";if(G().getNumber("WEBGL_VERSION")===1){let s="OES_texture_float",a="OES_texture_half_float";if(this.textureFloatExtension=th(this.gl,s),zo(this.gl,a))this.textureHalfFloatExtension=th(this.gl,a);else if(G().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(o),zo(this.gl,n))this.colorBufferHalfFloatExtension=th(this.gl,n);else if(G().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(o="EXT_color_buffer_float",zo(this.gl,o))this.colorBufferFloatExtension=this.gl.getExtension(o);else if(zo(this.gl,n))this.colorBufferHalfFloatExtension=this.gl.getExtension(n);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=I$(this.gl),this.indexBuffer=N$(this.gl),this.framebuffer=f$(this.gl),this.textureConfig=eh(this.gl,this.textureHalfFloatExtension)}get debug(){return G().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;Ee(e,()=>e.finish()),Ee(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),Ee(e,()=>e.deleteFramebuffer(this.framebuffer)),Ee(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),Ee(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),Ee(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),S$(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),T$(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),E$(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),F$(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,o,n){this.throwIfDisposed(),R$(this.gl,e,t,o,n,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),D$(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),A$(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(sv(this.gl,this.framebuffer),this.outputTexture=null),Ee(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,o){return this.downloadMatrixDriver(e,()=>M$(this.gl,t,o,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,o,n,s,a){return L$(this.gl,e,t,o,n,s,a,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return P$(this.gl,e,t)}createBufferFromTexture(e,t,o){this.bindTextureToFrameBuffer(e);let n=O$(this.gl,t,o,this.textureConfig);return this.unbindTextureToFrameBuffer(),n}createAndWaitForFence(){let e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,o;if(G().getBool("WEBGL_FENCE_API_ENABLED")){let n=e,s=n.fenceSync(n.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),o=()=>{let a=n.clientWaitSync(s,0,0);return a===n.ALREADY_SIGNALED||a===n.CONDITION_SATISFIED},t=s}else G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),o=()=>this.isQueryAvailable(t,G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):o=()=>!0;return{query:t,isFencePassed:o}}downloadMatrixFromPackedTexture(e,t,o){return this.downloadMatrixDriver(e,()=>z$(this.gl,t,o))}createProgram(e){this.throwIfDisposed();let t=this.gl,o=i$(t,e),n=C$(t),s=a$(t);return Ee(t,()=>t.attachShader(s,n)),Ee(t,()=>t.attachShader(s,o)),l$(t,s),this.debug&&Tx(t,s),this.vertexAttrsAreBound||(this.setProgram(s),this.vertexAttrsAreBound=$$(t,this.program,this.vertexBuffer)),s}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&Ee(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&Tx(this.gl,this.program),Ee(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,o=!0){return this.throwIfDisposed(),o?d$(this.gl,e,t):h$(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),Ee(this.gl,()=>this.gl.getAttribLocation(e,t))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,o){this.throwIfDisposed(),this.throwIfNoProgram(),g$(this.gl,e,t,o)}setOutputMatrixTexture(e,t,o){this.setOutputMatrixTextureDriver(e,o,t)}setOutputPackedMatrixTexture(e,t,o){this.throwIfDisposed();let[n,s]=Xi(t,o);this.setOutputMatrixTextureDriver(e,n,s)}setOutputMatrixWriteRegion(e,t,o,n){this.setOutputMatrixWriteRegionDriver(o,e,n,t)}setOutputPackedMatrixWriteRegion(e,t,o,n){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&Tx(this.gl,this.program),rh(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();let e=this.gl;this.debug&&this.debugValidate(),Ee(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),Ee(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=th(this.gl,G().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(G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let o=this.gl,n=this.getQueryTimerExtensionWebGL2(),s=o.createQuery();return o.beginQuery(n.TIME_ELAPSED_EXT,s),s}let e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let t=this.gl,o=this.getQueryTimerExtensionWebGL2();t.endQuery(o.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,G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(t===0)return null;if(t===2){let o=this.gl;return o.getQueryParameter(e,o.QUERY_RESULT)/1e6}else{let o=this.getQueryTimerExtensionWebGL1();return o.getQueryObjectEXT(e,o.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(t===0)return!0;if(t===2){let o=this.gl,n=this.getQueryTimerExtensionWebGL2(),s=o.getQueryParameter(e,o.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),s&&!this.disjoint}else{let o=this.getQueryTimerExtensionWebGL1(),n=o.getQueryObjectEXT(e,o.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(o.GPU_DISJOINT_EXT)),n&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){let e=F8(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=e;++t){let{resolveFn:o}=this.itemsToPoll[t];o()}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(),Ex(this.gl,e,this.framebuffer),this.debug&&rh(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(Ex(this.gl,this.outputTexture,this.framebuffer),this.debug&&rh(this.gl)):sv(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);let o=t();return this.unbindTextureToFrameBuffer(),o}setOutputMatrixTextureDriver(e,t,o){this.throwIfDisposed();let n=this.gl;Ex(n,e,this.framebuffer),this.debug&&rh(n),this.outputTexture=e,Ee(n,()=>n.viewport(0,0,t,o)),Ee(n,()=>n.scissor(0,0,t,o))}setOutputMatrixWriteRegionDriver(e,t,o,n){this.throwIfDisposed(),Ee(this.gl,()=>this.gl.scissor(e,t,o,n))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(this.program==null)throw new Error("No GPU program is currently set.")}};function F8(r){let e=0;for(;e<r.length&&r[e]();++e);return e-1}var{getBroadcastDims:B$}=N;function V$(r,e,t,o){let n=[];r.forEach(d=>{let h=y.sizeFromShape(d.shapeInfo.logicalShape);d.shapeInfo.isUniform?n.push(`uniform float ${d.name}${h>1?`[${h}]`:""};`):(n.push(`uniform sampler2D ${d.name};`),n.push(`uniform int offset${d.name};`))});let s=n.join(`
|
|
`),a=r.map(d=>O8(d,e,o)).join(`
|
|
`),i=e.texShape,l=Mt(),u=L8(l),c,p,m=V8(l);return e.isPacked?(c=P8(e.logicalShape,i),p=B8(l)):(c=M8(e.logicalShape,i),p=z8(l)),o&&(m+=G8),[m,u,p,s,c,a,t].join(`
|
|
`)}function Bp(r){let e=r.shapeInfo.logicalShape;switch(e.length){case 0:return W8(r);case 1:return U8(r);case 2:return j8(r);case 3:return H8(r);case 4:return q8(r);case 5:return K8(r);case 6:return X8(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 Y8(r);case 1:return Z8(r);case 2:return J8(r);case 3:return Q8(r);default:return eY(r)}}function O8(r,e,t=!1){let o="";t?o+=G$(r):o+=Bp(r);let n=r.shapeInfo.logicalShape,s=e.logicalShape;return n.length<=s.length&&(t?o+=tY(r,e):o+=rY(r,e)),o}function P8(r,e){switch(r.length){case 0:return W$();case 1:return oY(r,e);case 2:return iY(r,e);case 3:return nY(r,e);default:return sY(r,e)}}function M8(r,e){switch(r.length){case 0:return W$();case 1:return aY(r,e);case 2:return mY(r,e);case 3:return lY(r,e);case 4:return uY(r,e);case 5:return cY(r,e);case 6:return pY(r,e);default:throw new Error(`${r.length}-D output sampling is not yet supported`)}}function L8(r){return`
|
|
float sampleTexture(sampler2D textureSampler, vec2 uv) {
|
|
return ${r.texture2D}(textureSampler, uv).r;
|
|
}
|
|
`}function z8(r){return`
|
|
void setOutput(float val) {
|
|
${r.output} = vec4(val, 0, 0, 0);
|
|
}
|
|
`}function B8(r){return`
|
|
void setOutput(vec4 val) {
|
|
${r.output} = val;
|
|
}
|
|
`}function V8(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);
|
|
}
|
|
|
|
${fY}
|
|
${dY}
|
|
${hY}
|
|
`}var fY=`
|
|
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);
|
|
}
|
|
`,dY=`
|
|
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);
|
|
}
|
|
`,hY=`
|
|
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);
|
|
}
|
|
`,G8=`
|
|
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 W$(){return`
|
|
int getOutputCoords() {
|
|
return 0;
|
|
}
|
|
`}function oY(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 aY(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 nY(r,e){let t=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],o=Math.ceil(r[2]/2),n=o*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 / ${n};
|
|
index -= b * ${n};
|
|
|
|
int r = 2 * (index / ${o});
|
|
int c = imod(index, ${o}) * 2;
|
|
|
|
return ivec3(b, r, c);
|
|
}
|
|
`}function lY(r,e){let t=zs(["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 sY(r,e){let t=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],o=Math.ceil(r[r.length-1]/2),n=o*Math.ceil(r[r.length-2]/2),s=n,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 / ${n};
|
|
index -= b * ${n};
|
|
|
|
int r = 2 * (index / ${o});
|
|
int c = imod(index, ${o}) * 2;
|
|
|
|
return ivec${r.length}(${i});
|
|
}
|
|
`}function uY(r,e){let t=zs(["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 cY(r,e){let t=zs(["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 pY(r,e){let t=zs(["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 iY(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 o=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 / ${o});
|
|
int c = imod(index, ${o}) * 2;
|
|
|
|
return ivec2(r, c);
|
|
}
|
|
`}function mY(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 lc(r){return`offset${r}`}function Y8(r){let e=r.name,t="get"+e.charAt(0).toUpperCase()+e.slice(1),o=Mt();return`
|
|
vec4 ${t}() {
|
|
return ${o.texture2D}(${e}, halfCR);
|
|
}
|
|
`}function W8(r){let e=r.name,t="get"+e.charAt(0).toUpperCase()+e.slice(1);if(r.shapeInfo.isUniform)return`float ${t}() {return ${e};}`;let[o,n]=r.shapeInfo.texShape;if(o===1&&n===1)return`
|
|
float ${t}() {
|
|
return sampleTexture(${e}, halfCR);
|
|
}
|
|
`;let[s,a]=r.shapeInfo.texShape,i=lc(e);return`
|
|
float ${t}() {
|
|
vec2 uv = uvFromFlat(${s}, ${a}, ${i});
|
|
return sampleTexture(${e}, uv);
|
|
}
|
|
`}function Z8(r){let e=r.name,t="get"+e.charAt(0).toUpperCase()+e.slice(1),o=r.shapeInfo.texShape,n=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],s=Mt();return`
|
|
vec4 ${t}(int index) {
|
|
vec2 uv = packedUVfrom1D(
|
|
${n[0]}, ${n[1]}, index);
|
|
return ${s.texture2D}(${e}, uv);
|
|
}
|
|
`}function U8(r){let e=r.name,t="get"+e.charAt(0).toUpperCase()+e.slice(1);if(r.shapeInfo.isUniform)return`
|
|
float ${t}(int index) {
|
|
${Vp(r)}
|
|
}
|
|
`;let o=r.shapeInfo.texShape,n=o[0],s=o[1];if(s===1&&n===1)return`
|
|
float ${t}(int index) {
|
|
return sampleTexture(${e}, halfCR);
|
|
}
|
|
`;let a=lc(e);return s===1?`
|
|
float ${t}(int index) {
|
|
vec2 uv = vec2(0.5, (float(index + ${a}) + 0.5) / ${n}.0);
|
|
return sampleTexture(${e}, uv);
|
|
}
|
|
`:n===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(${n}, ${s}, index + ${a});
|
|
return sampleTexture(${e}, uv);
|
|
}
|
|
`}function J8(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=r.shapeInfo.texShape,s=n[0],a=n[1],i=Mt();if(n!=null&&y.arraysEqual(e,n))return`
|
|
vec4 ${o}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${a}.0, ${s}.0);
|
|
|
|
return ${i.texture2D}(${t}, uv);
|
|
}
|
|
`;let l=[Math.ceil(n[0]/2),Math.ceil(n[1]/2)],u=Math.ceil(e[1]/2);return`
|
|
vec4 ${o}(int row, int col) {
|
|
vec2 uv = packedUVfrom2D(${u}, ${l[0]}, ${l[1]}, row, col);
|
|
return ${i.texture2D}(${t}, uv);
|
|
}
|
|
`}function j8(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=r.shapeInfo.texShape;if(n!=null&&y.arraysEqual(e,n)){let p=n[0],m=n[1];return`
|
|
float ${o}(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=Gp(r,i),m=["row","col"];return`
|
|
${Bp(p)}
|
|
float ${o}(int row, int col) {
|
|
return ${o}(${Wp(m,a)});
|
|
}
|
|
`}if(r.shapeInfo.isUniform)return`
|
|
float ${o}(int row, int col) {
|
|
int index = round(dot(vec2(row, col), vec2(${e[1]}, 1)));
|
|
${Vp(r)}
|
|
}
|
|
`;let l=n[0],u=n[1],c=lc(t);return u===1?`
|
|
float ${o}(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 ${o}(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 ${o}(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 Q8(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=r.shapeInfo.texShape,s=[Math.ceil(n[0]/2),Math.ceil(n[1]/2)];if(e[0]===1){let p=e.slice(1),m=[1,2],f=Gp(r,p),d=["b","row","col"];return`
|
|
${G$(f)}
|
|
vec4 ${o}(int b, int row, int col) {
|
|
return ${o}(${Wp(d,m)});
|
|
}
|
|
`}let a=s[0],i=s[1],l=Math.ceil(e[2]/2),u=l*Math.ceil(e[1]/2),c=Mt();return`
|
|
vec4 ${o}(int b, int row, int col) {
|
|
vec2 uv = packedUVfrom3D(
|
|
${a}, ${i}, ${u}, ${l}, b, row, col);
|
|
return ${c.texture2D}(${t}, uv);
|
|
}
|
|
`}function H8(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=e[1]*e[2],s=e[2],{newShape:a,keptDims:i}=y.squeezeShape(e),l=a;if(l.length<e.length){let d=Gp(r,l),h=["row","col","depth"];return`
|
|
${Bp(d)}
|
|
float ${o}(int row, int col, int depth) {
|
|
return ${o}(${Wp(h,i)});
|
|
}
|
|
`}if(r.shapeInfo.isUniform)return`
|
|
float ${o}(int row, int col, int depth) {
|
|
int index = round(dot(vec3(row, col, depth),
|
|
vec3(${n}, ${s}, 1)));
|
|
${Vp(r)}
|
|
}
|
|
`;let u=r.shapeInfo.texShape,c=u[0],p=u[1],m=r.shapeInfo.flatOffset;if(p===n&&m==null)return`
|
|
float ${o}(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 ${o}(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=lc(t);return`
|
|
float ${o}(int row, int col, int depth) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${n} + col * ${s} + depth + ${f};
|
|
vec2 uv = uvFromFlat(${c}, ${p}, index);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function eY(r){let e=r.shapeInfo.logicalShape,t=e.length,o=r.name,n="get"+o.charAt(0).toUpperCase()+o.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=Mt();return`
|
|
vec4 ${n}(${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}(${o}, uv);
|
|
}
|
|
`}function q8(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=e[3],s=e[2]*n,a=e[1]*s,{newShape:i,keptDims:l}=y.squeezeShape(e);if(i.length<e.length){let d=Gp(r,i),h=["row","col","depth","depth2"];return`
|
|
${Bp(d)}
|
|
float ${o}(int row, int col, int depth, int depth2) {
|
|
return ${o}(${Wp(h,l)});
|
|
}
|
|
`}if(r.shapeInfo.isUniform)return`
|
|
float ${o}(int row, int col, int depth, int depth2) {
|
|
int index = round(dot(vec4(row, col, depth, depth2),
|
|
vec4(${a}, ${s}, ${n}, 1)));
|
|
${Vp(r)}
|
|
}
|
|
`;let u=r.shapeInfo.flatOffset,c=r.shapeInfo.texShape,p=c[0],m=c[1];if(m===a&&u==null)return`
|
|
float ${o}(int row, int col, int depth, int depth2) {
|
|
float texR = float(row);
|
|
float texC =
|
|
dot(vec3(col, depth, depth2),
|
|
vec3(${s}, ${n}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${m}.0, ${p}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`;if(m===n&&u==null)return`
|
|
float ${o}(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=lc(t);return`
|
|
float ${o}(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 * ${n} + depth2;
|
|
vec2 uv = uvFromFlat(${p}, ${m}, index + ${f});
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function K8(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),n=e[4],s=e[3]*n,a=e[2]*s,i=e[1]*a,{newShape:l,keptDims:u}=y.squeezeShape(e);if(l.length<e.length){let h=Gp(r,l),g=["row","col","depth","depth2","depth3"];return`
|
|
${Bp(h)}
|
|
float ${o}(int row, int col, int depth, int depth2, int depth3) {
|
|
return ${o}(${Wp(g,u)});
|
|
}
|
|
`}if(r.shapeInfo.isUniform)return`
|
|
float ${o}(int row, int col, int depth, int depth2, int depth3) {
|
|
float index = dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${i}, ${a}, ${s}, ${n})) +
|
|
depth3;
|
|
${Vp(r)}
|
|
}
|
|
`;let c=r.shapeInfo.flatOffset,p=r.shapeInfo.texShape,m=p[0],f=p[1];if(f===i&&c==null)return`
|
|
float ${o}(int row, int col, int depth, int depth2, int depth3) {
|
|
int texR = row;
|
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
|
vec4(${a}, ${s}, ${n}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${f}.0, ${m}.0);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`;if(f===n&&c==null)return`
|
|
float ${o}(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=lc(t);return`
|
|
float ${o}(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 * ${n} + depth3 + ${d};
|
|
vec2 uv = uvFromFlat(${m}, ${f}, index);
|
|
return sampleTexture(${t}, uv);
|
|
}
|
|
`}function X8(r){let e=r.shapeInfo.logicalShape,t=r.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),{newShape:n,keptDims:s}=y.squeezeShape(e);if(n.length<e.length){let g=Gp(r,n),x=["row","col","depth","depth2","depth3","depth4"];return`
|
|
${Bp(g)}
|
|
float ${o}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
return ${o}(${Wp(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 ${o}(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)));
|
|
${Vp(r)}
|
|
}
|
|
`;let p=r.shapeInfo.flatOffset,m=r.shapeInfo.texShape,f=m[0],d=m[1];if(d===c&&p==null)return`
|
|
float ${o}(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 ${o}(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=lc(t);return`
|
|
float ${o}(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 Vp(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 tY(r,e){let t=r.name,o=t.charAt(0).toUpperCase()+t.slice(1),n="get"+o+"AtOutCoords",s=r.shapeInfo.logicalShape.length,a=e.logicalShape.length,i=B$(r.shapeInfo.logicalShape,e.logicalShape),l=Le(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,_)=>`coords.${p[_+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,_=s-1;i.indexOf(b)>-1&&i.indexOf(_)>-1?f="return vec4(outputValue.x);":i.indexOf(b)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":i.indexOf(_)>-1&&(f="return vec4(outputValue.xx, outputValue.zz);")}return`
|
|
vec4 ${n}() {
|
|
${l} coords = getOutputCoords();
|
|
${c}
|
|
vec4 outputValue = get${o}(${m});
|
|
${f}
|
|
}
|
|
`}function rY(r,e){let t=r.name,o=t.charAt(0).toUpperCase()+t.slice(1),n="get"+o+"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 ${n}() {
|
|
return sampleTexture(${t}, resultUV);
|
|
}
|
|
`;let u=Le(l),c=B$(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 ${n}() {
|
|
${u} coords = getOutputCoords();
|
|
${m}
|
|
return get${o}(${d});
|
|
}
|
|
`}function Le(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 Gp(r,e){let t=JSON.parse(JSON.stringify(r));return t.shapeInfo.logicalShape=e,t}function Wp(r,e){return e.map(t=>r[t]).join(", ")}function U$(r,e,t,o){let n=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:o.shape,texShape:o.texData.texShape,isUniform:!1,isPacked:o.texData.isPacked,flatOffset:null},l=V$(s,i,n,e.packedInputs),u=r.createProgram(l),c=null,p=r.getUniformLocation(u,"NAN",!1);G().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 j$(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,o)=>{let n=t.logicalShape,s=e[o],a=s.shape;if(!y.arraysEqual(n,a))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${n} 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 H$(r,e,t,o,n){j$(e.inShapeInfos,t),j$([e.outShapeInfo],[o]);let s=o.texData.texture,a=o.texData.texShape;o.texData.isPacked?r.setOutputPackedMatrixTexture(s,a[0],a[1]):r.setOutputMatrixTexture(s,a[0],a[1]),r.setProgram(e.webGLProgram),G().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)}}),n!=null&&n(r,e.webGLProgram),r.executeProgram()}function q$(r,e,t){let o="";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;o+=`${a.shape}_${l}_${i}`});let n=r.userCode,s=r.constructor.name;return s+="_"+o+"_"+n,s}var{addImpl:K$,bincountImpl:Rx,bincountReduceImpl:X$,ceilImpl:Y$,concatImpl:Z$,expImpl:J$,expm1Impl:Q$,floorImpl:eR,gatherV2Impl:tR,greaterImpl:rR,lessImpl:oR,linSpaceImpl:nR,logImpl:sR,maxImpl:iR,maximumImpl:aR,minimumImpl:lR,multiplyImpl:uR,negImpl:cR,prodImpl:pR,rangeImpl:mR,rsqrtImpl:fR,simpleAbsImpl:Fx,sliceImpl:dR,stridedSliceImpl:hR,subImpl:gR,tileImpl:xR,topKImpl:yR,transposeImpl:Up,uniqueImpl:bR}=Wk;function kv(r,e){return["x","y","z","w","u","v"].slice(0,e).map(t=>`${r}.${t}`)}function Ut(r,e){return e===1?[r]:kv(r,e)}function _R(r,e){if(r===1)return"rc";let t="";for(let o=0;o<r;o++)t+=e[o],o<r-1&&(t+=",");return t}var vv=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 o=Ut("rc",t),n=Le(t),s=gY(t,e,o),a=xY(t,e[e.length-1],e[e.length-2],o),i=yY(e,o);this.userCode=`
|
|
void main() {
|
|
${n} rc = getOutputCoords();
|
|
|
|
if(${s}) {
|
|
setOutput(vec4(0));
|
|
} else {
|
|
${a}
|
|
|
|
setOutput(vec4(${i}));
|
|
}
|
|
}
|
|
`}}};function bY(r,e){let t=[];for(let o=0;o<=1;o++)for(let n=0;n<=1;n++){let s=`${o===0?"r":"rp1"}, ${n===0?"c":"cp1"}`;for(let a=2;a<r;a++)s=`${e[e.length-1-a]},`+s;t.push(s)}return t}function gY(r,e,t){if(r===1)return`rc > ${e[0]}`;let o="";for(let n=r-2;n<r;n++)o+=`${t[n]} >= ${e[n]}`,n<r-1&&(o+="||");return o}function xY(r,e,t,o){if(r===1)return"";let n=o.slice(-2);return`
|
|
int r = ${n[0]};
|
|
int c = ${n[1]};
|
|
int rp1 = r + 1;
|
|
int cp1 = c + 1;
|
|
|
|
bool cEdge = cp1 >= ${e};
|
|
bool rEdge = rp1 >= ${t};
|
|
`}function yY(r,e){let t=r.length,o=bY(t,e);return t===1?`getA(rc),
|
|
rc + 1 >= ${r[0]} ? 0. : getA(rc + 1),
|
|
0, 0`:`getA(${o[0]}),
|
|
cEdge ? 0. : getA(${o[1]}),
|
|
rEdge ? 0. : getA(${o[2]}),
|
|
rEdge || cEdge ? 0. : getA(${o[3]})`}var nh=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;let o="";for(let n=0;n<4;n++){let s="thisRC = rc;";n%2==1&&(s+="thisRC.z += 1;"),n>1&&(s+="thisRC.y += 1;"),o+=`
|
|
${s}
|
|
${n>0?"if(thisRC.y < rows && thisRC.z < cols){":""}
|
|
int flatIndex = getFlatIndex(thisRC);
|
|
|
|
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
|
|
vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
|
|
|
|
result[${n}] =
|
|
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
|
|
${n>0?"}":""}
|
|
`}this.userCode=`
|
|
${_Y(t)}
|
|
${zp(e)}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
ivec3 thisRC;
|
|
int rows = ${e[1]};
|
|
int cols = ${e[2]};
|
|
|
|
${o}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};function _Y(r){return`
|
|
ivec3 inputCoordsFromReshapedOutCoords(int index) {
|
|
${zs(["r","c","d"],r)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}var Cv=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,o){let n=kR(t,o),s=vR(e,n,o);s in this.freeTextures||(this.freeTextures[s]=[]),s in this.usedTextures||(this.usedTextures[s]=[]);let a=wR(e,n,this.gpgpu.gl,this.gpgpu.textureConfig,o);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 n===br.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):n===br.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):n===br.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):n===br.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):n===br.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,o,n){if(this.freeTextures==null)return;let s=kR(o,n),a=vR(t,s,n);a in this.freeTextures||(this.freeTextures[a]=[]);let i=wR(t,s,this.gpgpu.gl,this.gpgpu.textureConfig,n),l=G().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 wY(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 wR(r,e,t,o,n){let s=kY(e,o),a;if(n){let[l,u]=Xi(r[0],r[1]);a=l*u}else{let[l,u]=ic(r[0],r[1]);a=l*u}let i=wY(t,s);return a*i}function kY(r,e){switch(r){case br.PACKED_2X2_FLOAT32:return bv(e);case br.PACKED_2X2_FLOAT16:return _v(e);case br.UNPACKED_FLOAT32:return gv(e);case br.UNPACKED_FLOAT16:return xv(e);case br.PACKED_4X1_UNSIGNED_BYTE:return yv(e);default:throw new Error(`Unknown physical texture type ${r}`)}}function vY(r){return G().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?r?br.PACKED_2X2_FLOAT32:br.UNPACKED_FLOAT32:r?br.PACKED_2X2_FLOAT16:br.UNPACKED_FLOAT16}function kR(r,e){if(r===Er.UPLOAD)return br.PACKED_2X2_FLOAT32;if(r===Er.RENDER||r==null)return vY(e);if(r===Er.DOWNLOAD||r===Er.PIXELS)return br.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${r}`)}function vR(r,e,t){return`${r[0]}_${r[1]}_${e}_${t}`}var uo=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);
|
|
}
|
|
`}},gr="if (isnan(x)) return x;",CR="return x;",Iv="return abs(x);";var IR="return (x >= 0.0) ? x : (exp(x) - 1.0);",NR=gr+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,SR=gr+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,sh="return x;";var TR="return x;",ER=`
|
|
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;
|
|
`,AR=`
|
|
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;
|
|
`,DR=`
|
|
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;
|
|
`,Bs=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 Nv=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;let t=e.length,o=Ut("rc",t),n=Le(t),s=_R(t,o),a=o.slice(-2),i=t<=1?"rc":`vec2(${a.join(",")})`;this.userCode=`
|
|
void main() {
|
|
${n} rc = getOutputCoords();
|
|
vec4 packedInput = getA(${s});
|
|
|
|
setOutput(getChannel(packedInput, ${i}));
|
|
}
|
|
`}};var CY=Sr.whereImpl,IY=1e-7,NY=1e-4,Ox={};function SY(r){return r in Ox||(Ox[r]={}),Ox[r]}var TY=128,EY=600;function AY(){return G().global.screen==null?1024:G().global.screen.height*G().global.screen.width*window.devicePixelRatio*EY/1024/1024}var Sv=class extends Ws{constructor(e){super();if(this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.warnedAboutMemory=!1,this.warnedAboutCPUBackend=!1,this.pendingDeletes=0,this.disposed=!1,!G().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){let t=Lo(G().getNumber("WEBGL_VERSION"));this.binaryCache=SY(G().getNumber("WEBGL_VERSION")),this.gpgpu=new wv(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 Cv(this.gpgpu),this.numMBBeforeWarning=AY(),this.texData=new Ya(this,vs())}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(e,t,o){if((G().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||G().getBool("DEBUG"))&&this.checkNumericalProblems(e),o==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let n={};return this.texData.set(n,{shape:t,dtype:o,values:e,usage:Er.UPLOAD,refCount:1,complexParentRefCount:0}),n}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--}}decComplexRef(e){if(this.texData.has(e)){let t=this.texData.get(e);t.complexParentRefCount>0&&t.refCount--}}move(e,t,o,n){if(G().getBool("DEBUG")&&this.checkNumericalProblems(t),n==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:o,dtype:n,values:t,usage:Er.UPLOAD,refCount:1,complexParentRefCount:0})}disposeIntermediateTensorInfo(e){let t=e.dataId;if(this.texData.has(t)){let o=this.texData.get(t);o.refCount--,o.refCount<1&&this.disposeData(t)}}readSync(e){let t=this.texData.get(e),{values:o,dtype:n,complexTensorInfos:s,slice:a,shape:i,isPacked:l}=t;if(a!=null){let m;l?m=new Bs(i,sh):m=new uo(i,sh);let f=this.runWebGLProgram(m,[{dataId:e,shape:i,dtype:n}],n),d=this.readSync(f.dataId);return this.disposeIntermediateTensorInfo(f),d}if(o!=null)return this.convertAndCacheOnCPU(e);if(n==="string")return o;let u=this.activeTimers!=null,c;u&&(c=y.now());let p;if(n==="complex64"){let m=this.readSync(s.real.dataId),f=this.readSync(s.imag.dataId);p=N.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:o,shape:n,slice:s,dtype:a,complexTensorInfos:i,isPacked:l}=t;if(s!=null){let d;l?d=new Bs(n,sh):d=new uo(n,sh);let h=this.runWebGLProgram(d,[{dataId:e,shape:n,dtype:a}],a),g=this.read(h.dataId);return this.disposeIntermediateTensorInfo(h),g}if(o!=null)return this.convertAndCacheOnCPU(e);if(!G().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&G().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"&&G().get("WEBGL_BUFFER_SUPPORTED")){c=this.decode(e);let d=this.texData.get(c.dataId);u=this.gpgpu.createBufferFromTexture(d.texture,...Il(n))}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=N.mergeRealAndImagArrays(h,g)}else if(u==null)p=this.getValuesFromTexture(e);else{let d=y.sizeFromShape(n);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),this.pendingDeletes--),m}bufferSync(e){let t=this.readSync(e.dataId),o=t;if(e.dtype==="string")try{o=t.map(n=>y.decodeString(n))}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return Ce(e.shape,e.dtype,o)}checkNumericalProblems(e){if(e!=null)for(let t=0;t<e.length;t++){let o=e[t];if(!n$(o))throw G().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")?Error(`The value ${o} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`):Error(`The value ${o} cannot be represented on this device.`)}}getValuesFromTexture(e){let{shape:t,dtype:o,isPacked:n}=this.texData.get(e),s=y.sizeFromShape(t);if(G().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){let m=this.decode(e),f=this.texData.get(m.dataId),d=this.gpgpu.downloadMatrixFromPackedTexture(f.texture,...Il(t)).subarray(0,s);return this.disposeIntermediateTensorInfo(m),d}let a=G().getBool("WEBGL_PACK")&&n===!0,i=a?Ax(t):t,l=a?new fv(i):new mv(i),u=this.runWebGLProgram(l,[{shape:i,dtype:o,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}async time(e){let t=this.activeTimers,o=[],n=!1;this.programTimersStack==null?(this.programTimersStack=o,n=!0):this.activeTimers.push(o),this.activeTimers=o,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,n&&(this.programTimersStack=null);let i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};if(G().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 G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:y.now(),endMs:null}}endTimer(e){return G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=y.now(),e)}async getQueryTime(e){if(G().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);let t=e;return t.endMs-t.startMs}disposeData(e){if(this.pendingDisposal.has(e))return;if(this.pendingRead.has(e)){this.pendingDisposal.add(e),this.pendingDeletes++;return}if(!this.texData.has(e))return;if(this.texData.get(e).complexParentRefCount>0){this.texData.get(e).refCount--;return}this.releaseGPUData(e);let{complexTensorInfos:t}=this.texData.get(e);t!=null&&(this.texData.get(t.real.dataId).complexParentRefCount--,this.disposeIntermediateTensorInfo(t.real),this.texData.get(t.imag.dataId).complexParentRefCount--,this.disposeIntermediateTensorInfo(t.imag)),this.texData.delete(e)}releaseGPUData(e){let{texture:t,dtype:o,texShape:n,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(n,o),this.textureManager.releaseTexture(t,n,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)}getCPUBackend(){return G().getBool("WEBGL_CPU_FORWARD")?(this.cpuBackend==null&&(this.cpuBackend=vs().findBackend("cpu")),this.cpuBackend):null}shouldExecuteOnCPU(e,t=TY){let o=this.getCPUBackend();return!G().getBool("IS_TEST")&&!this.warnedAboutCPUBackend&&o==null&&(console.warn("Your application contains ops that are small enough to be executed on the CPU backend, however the CPU backend cannot be found. Consider importing the CPU backend (@tensorflow/tfjs-backend-cpu) for better performance."),this.warnedAboutCPUBackend=!0),o!=null&&e.every(n=>this.texData.get(n.dataId).texture==null&&y.sizeFromShape(n.shape)<t)}getGPGPUContext(){return this.gpgpu}where(e){N.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");let t=e.dataSync();return CY(e.shape,t)}packedUnaryOp(e,t,o){let n=new Bs(e.shape,t);return this.compileAndRun(n,[e],o)}abs(e){if(this.shouldExecuteOnCPU([e])&&e.dtype!=="complex64"){let o=Fx(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,o)}if(G().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Iv,e.dtype);let t=new uo(e.shape,Iv);return this.compileAndRun(t,[e])}makeTensorInfo(e,t,o){let n;if(t==="string"&&o!=null&&o.length>0&&y.isString(o[0])){let s=o.map(a=>y.encodeString(a));n=this.write(s,e,t)}else n=this.write(o,e,t);return this.texData.get(n).usage=null,{dataId:n,shape:e,dtype:t}}makeOutput(e,t,o){let{dataId:n}=this.makeTensorInfo(e,t,o);return vs().makeTensorFromDataId(n,e,t,this)}unpackTensor(e){let t=new Nv(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){let t=new vv(e.shape),o=!0;return this.runWebGLProgram(t,[e],e.dtype,null,o)}packedReshape(e,t){let o=[Nl(e.shape),...Sl(e.shape)],n={dtype:e.dtype,shape:o,dataId:e.dataId},s=[Nl(t),...Sl(t)],a=new nh(s,o),i=!0,l=this.runWebGLProgram(a,[n],e.dtype,null,i);return{dataId:l.dataId,shape:t,dtype:l.dtype}}decode(e){let t=this.texData.get(e),{isPacked:o,shape:n,dtype:s}=t,a=Ax(n),i;o?i=new pv(a):i=new cv(a);let l=!0,u=this.runWebGLProgram(i,[{shape:a,dtype:s,dataId:e}],s,null,l);return{dtype:s,shape:n,dataId:u.dataId}}runWebGLProgram(e,t,o,n,s=!1){let a=this.makeTensorInfo(e.outputShape,o),i=this.texData.get(a.dataId);if(e.packedOutput&&(i.isPacked=!0),e.outPackingScheme===Cl.DENSE){let h=Il(e.outputShape);i.texShape=h.map(g=>g*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(h=>{if(h.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let g=this.texData.get(h.dataId);if(g.texture==null){if(!e.packedInputs&&y.sizeFromShape(h.shape)<=G().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:h.shape,texData:null,isUniform:!0,uniformValues:g.values};e.packedInputs&&(g.isPacked=!0,g.shape=h.shape)}else if(!!g.isPacked!=!!e.packedInputs)h=g.isPacked?this.unpackTensor(h):this.packTensor(h),l.push(h),g=this.texData.get(h.dataId);else if(g.isPacked&&!ac(g.shape,h.shape)){let x=h,b=h.shape;h.shape=g.shape,h=this.packedReshape(h,b),l.push(h),g=this.texData.get(h.dataId),x.shape=b}return this.uploadToGPU(h.dataId),{shape:h.shape,texData:g,isUniform:!1}});this.uploadToGPU(a.dataId);let c={shape:a.shape,texData:i,isUniform:!1},p=q$(e,u,c),m=this.getAndSaveBinary(p,()=>U$(this.gpgpu,e,u,c)),f=this.activeTimers!=null,d;if(f&&(d=this.startTimer()),H$(this.gpgpu,m,u,c,n),l.forEach(h=>this.disposeIntermediateTensorInfo(h)),f&&(d=this.endTimer(d),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(d)})),!G().getBool("WEBGL_LAZILY_UNPACK")&&i.isPacked&&s===!1){let h=this.unpackTensor(a);return this.disposeIntermediateTensorInfo(a),h}return a}compileAndRun(e,t,o,n,s=!1){o=o||t[0].dtype;let a=this.runWebGLProgram(e,t,o,n,s);return vs().makeTensorFromDataId(a.dataId,a.shape,a.dtype)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(G().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=V(()=>{if(!G().get("WEBGL_RENDER_FLOAT32_ENABLED")){let e=G().getBool("DEBUG");G().set("DEBUG",!1);let t=this.abs(le(1e-8)).dataSync()[0];if(G().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?IY:NY}uploadToGPU(e){let t=this.texData.get(e),{shape:o,dtype:n,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=x$(o,l),t.texShape=p),s!=null){let m=Ax(o),f,d=p[1],h=p[0],g=s instanceof Uint8Array;l?([d,h]=Xi(p[0],p[1]),f=new hv(m,[h,d],g)):f=new dv(m,[h,d],g);let x=this.makeTensorInfo([h,d],n);g?this.texData.get(x.dataId).usage=Er.PIXELS:this.texData.get(x.dataId).usage=Er.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(x.dataId),d,h,s);let b=!0,_=this.runWebGLProgram(f,[x],n,null,b),w=this.texData.get(_.dataId);t.texture=w.texture,t.texShape=w.texShape,t.isPacked=w.isPacked,t.usage=w.usage,this.disposeIntermediateTensorInfo(x),this.texData.delete(_.dataId),t.values=null,u&&(this.uploadWaitMs+=y.now()-c)}else{let m=this.acquireTexture(p,i,n,l);t.texture=m}}convertAndCacheOnCPU(e,t){let o=this.texData.get(e),{dtype:n}=o;return this.releaseGPUData(e),t!=null&&(o.values=DY(t,n)),o.values}acquireTexture(e,t,o,n){if(this.numBytesInGPU+=this.computeBytes(e,o),!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,n)}computeBytes(e,t){return e[0]*e[1]*y.bytesPerElement(t)}};function DY(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 o=0;o<t.length;++o)t[o]=Math.round(r[o]);return t}else throw new Error(`Unknown dtype ${e}`)}var $R="3.0.0";Bc.isBrowser()&&yu("webgl",()=>new Sv,2);var Px=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`;var Qn=class{constructor(e,t,o){this.variableNames=["A","B"],this.outputShape=N.assertAndGetBroadcastShape(t,o),this.userCode=`
|
|
float binaryOperation(float a, float b) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
float a = getAAtOutCoords();
|
|
float b = getBAtOutCoords();
|
|
setOutput(binaryOperation(a, b));
|
|
}
|
|
`}};var Tl=`
|
|
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 Vs=class{constructor(e,t,o,n=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=N.assertAndGetBroadcastShape(t,o);let s=this.outputShape.length,a="";if(n)if(s===0||y.sizeFromShape(this.outputShape)===1)a=`
|
|
result.y = 0.;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else if(a=`
|
|
${Le(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=Ut("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 jt(r){let{inputs:e,backend:t}=r,{x:o}=e;return t.incRef(o.dataId),{dataId:o.dataId,shape:o.shape,dtype:o.dtype}}var RR={kernelName:us,backendName:"webgl",kernelFunc:jt};function co(r){let{inputs:e,backend:t}=r,{real:o,imag:n}=e,s=t.makeTensorInfo(o.shape,"complex64"),a=t.texData.get(s.dataId),i=jt({inputs:{x:o},backend:t}),l=t.texData.get(i.dataId);l.complexParentRefCount++;let u=jt({inputs:{x:n},backend:t}),c=t.texData.get(u.dataId);return c.complexParentRefCount++,a.complexTensorInfos={real:i,imag:u},s}var FR={kernelName:Hl,backendName:"webgl",kernelFunc:co};var Tv="return (a < 0.) ? b * a : a;",Ev=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function $Y(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{alpha:s}=o,a=t.makeTensorInfo([],"float32",y.createScalarValue(s,"float32")),i=G().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Vs(Ev,n.shape,a.shape):new Qn(Tv,n.shape,a.shape),l=t.runWebGLProgram(i,[n,a],n.dtype);return t.disposeIntermediateTensorInfo(a),l}var OR={kernelName:sn,backendName:"webgl",kernelFunc:$Y};var Av="return (a < 0.) ? b * a : a;",Dv=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function RY(r){let{inputs:e,backend:t}=r,{x:o,alpha:n}=e,s=G().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Vs(Dv,o.shape,n.shape):new Qn(Av,o.shape,n.shape);return t.runWebGLProgram(s,[o,n],o.dtype)}var PR={kernelName:yn,backendName:"webgl",kernelFunc:RY};var Mx="if (isnan(x)) return x;",MR=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,LR=`
|
|
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 ve({opSnippet:r,packedOpSnippet:e,cpuKernelImpl:t,dtype:o}){return({inputs:n,backend:s})=>{let{x:a}=n,i=s,l=o||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=G().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&e!=null,c;return u?c=new Bs(a.shape,e):c=new uo(a.shape,r),i.runWebGLProgram(c,[a],l)}}function it({opSnippet:r,packedOpSnippet:e,checkOutOfBounds:t=!1,supportsComplex:o=!1,cpuKernelImpl:n,dtype:s}){return({inputs:a,backend:i})=>{let{a:l,b:u}=a,c=i;if(o&&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(_=>{let[w,v]=_,$={dataId:w.dataId,dtype:w.dtype,shape:l.shape},A={dataId:v.dataId,dtype:v.dtype,shape:u.shape},R=new Qn(r,l.shape,u.shape);return c.runWebGLProgram(R,[$,A],mr(w.dtype,v.dtype))}),b=co({inputs:{real:g,imag:x},backend:c});return c.disposeIntermediateTensorInfo(g),c.disposeIntermediateTensorInfo(x),b}let p=s||mr(l.dtype,u.dtype);if(c.shouldExecuteOnCPU([l,u])&&n!=null){let d=c.texData.get(l.dataId),h=c.texData.get(u.dataId),[g,x]=n(l.shape,u.shape,d.values,h.values,p),b=c.makeTensorInfo(x,p),_=c.texData.get(b.dataId);return _.values=g,b}let m=G().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&e!=null,f;return m?f=new Vs(e,l.shape,u.shape,t):f=new Qn(r,l.shape,u.shape),c.runWebGLProgram(f,[l,u],p)}}function El(r,e=!1){if(r==="linear")return e?TR:CR;if(r==="relu")return e?AR:NR;if(r==="elu")return e?ER:IR;if(r==="relu6")return e?DR:SR;if(r==="prelu")return e?Dv:Av;if(r==="leakyrelu")return e?Ev:Tv;throw new Error(`Activation ${r} has not been implemented for the WebGL backend.`)}var ih=class{constructor(e,t,o,n=!1,s=!1,a=!1,i=null,l=!1,u=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=o;let c=n?e[1]:e[2],p=Math.ceil(c/2),m=n?"i * 2, rc.y":"rc.y, i * 2",f=s?"rc.z, i * 2":"i * 2, rc.z",d=n?["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 _="rc.x",w="rc.x";e[0]<t[0]?_=`int(min(float(rc.x), ${e[0]-1}.))`:t[0]<e[0]&&(w=`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 = ${_};
|
|
int batchB = ${w};
|
|
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 $v={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},Lx=class{constructor(e,t,o){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=N.assertAndGetBroadcastShape(t,o),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 zR="return a * b;";function Rv(r){let{inputs:e,backend:t}=r,{a:o,b:n}=e,s=N.upcastType(o.dtype,n.dtype);if(o.dtype==="complex64"){let i=t.texData.get(o.dataId),l=t.texData.get(n.dataId),u=new Lx($v.REAL,o.shape,n.shape),c=new Lx($v.IMAG,o.shape,n.shape),p=[{dataId:i.complexTensorInfos.real.dataId,dtype:i.complexTensorInfos.real.dtype,shape:o.shape},{dataId:i.complexTensorInfos.imag.dataId,dtype:i.complexTensorInfos.imag.dtype,shape:o.shape},{dataId:l.complexTensorInfos.real.dataId,dtype:l.complexTensorInfos.real.dtype,shape:n.shape},{dataId:l.complexTensorInfos.imag.dataId,dtype:l.complexTensorInfos.imag.dtype,shape:n.shape}],m=t.runWebGLProgram(u,p,"float32"),f=t.runWebGLProgram(c,p,"float32"),d=co({inputs:{real:m,imag:f},backend:t});return t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f),d}if(t.shouldExecuteOnCPU([o,n])){let i=t.texData.get(o.dataId),l=t.texData.get(n.dataId),[u,c]=uR(o.shape,n.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 G().getBool("WEBGL_PACK_BINARY_OPERATIONS")?a=new Vs(zR,o.shape,n.shape):a=new Qn(zR,o.shape,n.shape),t.runWebGLProgram(a,[o,n],s)}var BR={kernelName:dn,backendName:"webgl",kernelFunc:Rv};function VR(r,e,t){let o=[Nl(r.shape),...Sl(r.shape)],n={dtype:r.dtype,shape:o,dataId:r.dataId},s=[Nl(e),...Sl(e)],a=new nh(s,o),i=!0,l=t.runWebGLProgram(a,[n],r.dtype,null,i);return{dataId:l.dataId,shape:e,dtype:l.dtype}}function ce(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{shape:s}=o,a=t,i=y.sizeFromShape(n.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 (${n.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`);let c=a.texData.get(n.dataId);return c.isPacked&&!ac(n.shape,l)&&!(c.texture!==null&&ac(c.shape,l))?VR(n,l,a):(a.incRef(n.dataId),{dataId:n.dataId,shape:l,dtype:n.dtype})}var GR={kernelName:fs,backendName:"webgl",kernelFunc:ce};var zx=class{constructor(e,t){this.variableNames=["x"];let{windowSize:o,batchSize:n,inSize:s,outSize:a}=e;this.outputShape=[n,a];let i=Math.floor(o/4)*4,l=o%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%o>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 * ${o};
|
|
|
|
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 Fv=class{constructor(e,t){this.variableNames=["x"];let{windowSize:o,batchSize:n,inSize:s,outSize:a}=e;this.outputShape=[n,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(o/4)*4,p=o%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);
|
|
}
|
|
`,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%o>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 * ${o};
|
|
|
|
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 FY(r){let e=[];for(;e.length===0||e[e.length-1].outSize!==1;){let t=e.length?e[e.length-1].outSize:r[1],o=N.computeOptimalWindowSize(t);e.push({inSize:t,windowSize:o,outSize:Math.ceil(t/o)})}return e}function Io(r,e,t,o){let n=FY(r.shape),s=r;for(let a=0;a<n.length;a++){let{inSize:i,windowSize:l,outSize:u}=n[a],c,p;t==="mean"?c=a===0?new zx({windowSize:l,inSize:i,batchSize:r.shape[0],outSize:u},i):new zx({windowSize:l,inSize:i,batchSize:r.shape[0],outSize:u}):c=new Fv({windowSize:l,inSize:i,batchSize:r.shape[0],outSize:u},t),p=s,s=o.runWebGLProgram(c,[s],e),p.dataId!==r.dataId&&o.disposeIntermediateTensorInfo(p)}return s}var Ov=class{constructor(e,t){this.variableNames=["A"];let o=new Array(e.length);for(let a=0;a<o.length;a++)o[a]=e[t[a]];this.outputShape=o,this.rank=o.length;let n=Le(this.rank),s=OY(t);this.userCode=`
|
|
void main() {
|
|
${n} resRC = getOutputCoords();
|
|
setOutput(getA(${s}));
|
|
}
|
|
`}};function OY(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"],o=new Array(e);for(let n=0;n<r.length;n++)o[r[n]]=t[n];return o.join()}var Pv=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let o=new Array(e.length);for(let c=0;c<o.length;c++)o[c]=e[t[c]];if(this.outputShape=o,this.rank=o.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let n=Le(this.rank),s=kv("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]} < ${o[this.rank-1]}`,u=`getChannel(getA(${a.join()}), ${i})`;this.userCode=`
|
|
void main() {
|
|
${n} rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result[0] = ${u};
|
|
if(${l}) {
|
|
result[1] = ${u};
|
|
}
|
|
--${s[this.rank-1]};
|
|
if(++${s[this.rank-2]} < ${o[this.rank-2]}) {
|
|
result[2] = ${u};
|
|
if(${l}) {
|
|
result[3] = ${u};
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};function Al(r,e,t){let o=G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Pv(r.shape,e):new Ov(r.shape,e);return t.runWebGLProgram(o,[r],r.dtype)}function WR(r,e,t,o){let n=e,s=r.shape.length,a=y.parseAxisParam(n,r.shape),i=a,l=N.getAxesPermutation(i,s),u=l!=null,c=r;u&&(c=Al(r,l,o),i=N.getInnerMostAxes(i.length,s)),N.assertAxesAreInnerMostDims("sum",i,s);let[p,m]=N.computeOutAndReduceShapes(c.shape,i),f=p;t&&(f=N.expandShapeToKeepDim(p,a));let d=y.sizeFromShape(m),g=y.sizeFromShape(r.shape)/d,x=ce({inputs:{x:c},attrs:{shape:[g,d]},backend:o}),b=hu(r.dtype),_=Io(x,b,"sum",o),w=ce({inputs:{x:_},attrs:{shape:f},backend:o});return o.disposeIntermediateTensorInfo(x),o.disposeIntermediateTensorInfo(_),u&&o.disposeIntermediateTensorInfo(c),w}function ah(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o;return WR(n,s,a,t)}var UR={kernelName:Tn,backendName:"webgl",kernelFunc:ah};function Lt(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{perm:s}=o,a=t,i=n.shape.length,l=new Array(i);for(let c=0;c<l.length;c++)l[c]=n.shape[s[c]];let u;if(a.shouldExecuteOnCPU([n])){let p=a.texData.get(n.dataId).values,m=Up(p,n.shape,n.dtype,s,l);u=a.makeTensorInfo(l,n.dtype);let f=a.texData.get(u.dataId);f.values=m}else u=Al(n,s,a);return u}var jR={kernelName:Rn,backendName:"webgl",kernelFunc:Lt};var Mv=1e3;function uc({a:r,b:e,transposeA:t,transposeB:o,backend:n,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=o?e.shape[c-1]:e.shape[c-2],f=t?r.shape[u-1]:r.shape[u-2],d=o?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),_=x===b||x===1||b===1;y.assert(u>=2&&c>=2&&_,()=>`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 v=(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=${o} must match.`);let $=t?[x,p,f]:[x,f,p],A=o?[b,d,m]:[b,m,d],R=ce({inputs:{x:r},backend:n,attrs:{shape:$}}),M=ce({inputs:{x:e},backend:n,attrs:{shape:A}}),z=[R,M],W=Math.max(x,b),U=t?R.shape[1]:R.shape[2],q=s!=null,Z=a!=null,X=l==="leakyrelu",Y=l!=null?El(l,!0):null,te=q||Z||X||Y!=null,K;if((f===1||d===1)&&U>Mv&&te===!1){let ie=R,se=M;t&&(ie=Lt({inputs:{x:R},backend:n,attrs:{perm:[0,2,1]}}),z.push(ie)),o&&(se=Lt({inputs:{x:M},backend:n,attrs:{perm:[0,2,1]}}),z.push(se));let pe=d!==1,ae=d===1,xe=ie;pe&&(xe=ce({inputs:{x:ie},backend:n,attrs:{shape:[W,U,1]}}),z.push(xe));let ge=d===1?2:1,_e=se;ae&&(_e=ce({inputs:{x:se},backend:n,attrs:{shape:[W,1,U]}}),z.push(_e));let ke=Rv({inputs:{a:xe,b:_e},backend:n});K=ah({inputs:{x:ke},backend:n,attrs:{axis:ge,keepDims:!0}}),z.push(ke)}else{let ie=mr(r.dtype,e.dtype),se=new ih($,A,[W,f,d],t,o,q,Y,Z,X),pe=[R,M];if(s!=null&&pe.push(s),Z&&pe.push(a),X){let ae=n.makeTensorInfo([],"float32",y.createScalarValue(i,"float32"));pe.push(ae),z.push(ae)}K=n.runWebGLProgram(se,pe,ie)}let re=ce({inputs:{x:K},backend:n,attrs:{shape:v}});z.push(K);for(let ie of z)n.disposeIntermediateTensorInfo(ie);return re}function PY(r){let{inputs:e,backend:t,attrs:o}=r,{a:n,b:s,bias:a,preluActivationWeights:i}=e,{transposeA:l,transposeB:u,activation:c,leakyreluAlpha:p}=o;return uc({a:n,b:s,transposeA:l,transposeB:u,backend:t,bias:a,preluActivationWeights:i,leakyreluAlpha:p,activation:c})}var HR={kernelName:bs,backendName:"webgl",kernelFunc:PY};var qR="return abs(x);";function MY(r){let{inputs:e,backend:t}=r,{x:o}=e;if(t.shouldExecuteOnCPU([o])&&o.dtype!=="complex64"){let s=t.texData.get(o.dataId),a=Fx(s.values);return t.makeTensorInfo(o.shape,o.dtype,a)}let n;return G().getBool("WEBGL_PACK_UNARY_OPERATIONS")?n=new Bs(o.shape,qR):n=new uo(o.shape,qR),t.runWebGLProgram(n,[o],o.dtype)}var KR={kernelName:ss,backendName:"webgl",kernelFunc:MY};var LY=gr+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return acos(x);
|
|
`,zY=ve({opSnippet:LY}),XR={kernelName:qs,backendName:"webgl",kernelFunc:zY};var BY=gr+`
|
|
if (x < 1.0) return NAN;
|
|
return log(x + sqrt(x * x - 1.0));`,VY=ve({opSnippet:BY}),YR={kernelName:Ks,backendName:"webgl",kernelFunc:VY};var ZR="return a + b;",GY=it({opSnippet:ZR,packedOpSnippet:ZR,supportsComplex:!0,cpuKernelImpl:K$}),JR={kernelName:xo,backendName:"webgl",kernelFunc:GY};var Lv=class{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((s,a)=>`T${a}`);let o=[];this.variableNames.forEach(s=>{o.push(`float v${s} = get${s}AtOutCoords();`)});let n=this.variableNames.map(s=>`v${s}`).join(" + ");this.userCode=`
|
|
void main() {
|
|
${o.join(`
|
|
`)}
|
|
|
|
float result = ${n};
|
|
setOutput(result);
|
|
}
|
|
`}};var zv=class{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((s,a)=>`T${a}`);let o=[];this.variableNames.forEach(s=>{o.push(`vec4 v${s} = get${s}AtOutCoords();`)});let n=this.variableNames.map(s=>`v${s}`).join(" + ");this.userCode=`
|
|
void main() {
|
|
${o.join(`
|
|
`)}
|
|
|
|
vec4 result = ${n};
|
|
setOutput(result);
|
|
}
|
|
`}};function Bx(r){let{inputs:e,backend:t}=r,o=e;if(o.length===1)return jt({inputs:{x:o[0]},backend:t});if(o.length>G().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let l=Math.floor(o.length/2),u=Bx({inputs:o.slice(0,l),backend:t}),c=Bx({inputs:o.slice(l),backend:t});return Bx({inputs:[u,c],backend:t})}let n=o.map(l=>l.dtype).reduce((l,u)=>mr(l,u)),s=o.map(l=>l.shape),i=G().getBool("WEBGL_PACK")?new zv(o[0].shape,s):new Lv(o[0].shape,s);return t.runWebGLProgram(i,o,n)}var QR={kernelName:Uo,backendName:"webgl",kernelFunc:Bx};function WY(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o,i=n.shape.length,l=y.parseAxisParam(s,n.shape),u=l,c=N.getAxesPermutation(u,i),p=n;c!=null&&(p=Lt({inputs:{x:n},backend:t,attrs:{perm:c}}),u=N.getInnerMostAxes(u.length,i)),N.assertAxesAreInnerMostDims("all",u,i);let[m,f]=N.computeOutAndReduceShapes(p.shape,u),d=y.sizeFromShape(f),h=ce({inputs:{x:p},backend:t,attrs:{shape:[-1,d]}}),g=Io(h,h.dtype,"all",t),x;if(a){let b=N.expandShapeToKeepDim(m,l);x=ce({inputs:{x:g},backend:t,attrs:{shape:b}})}else x=ce({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),c!=null&&t.disposeIntermediateTensorInfo(p),x}var eF={kernelName:Vl,backendName:"webgl",kernelFunc:WY};function UY(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o,i=n.shape.length,l=y.parseAxisParam(s,n.shape),u=l,c=N.getAxesPermutation(u,i),p=n;c!=null&&(p=Lt({inputs:{x:n},backend:t,attrs:{perm:c}}),u=N.getInnerMostAxes(u.length,i)),N.assertAxesAreInnerMostDims("any",u,i);let[m,f]=N.computeOutAndReduceShapes(p.shape,u),d=y.sizeFromShape(f),h=ce({inputs:{x:p},backend:t,attrs:{shape:[-1,d]}}),g=Io(h,h.dtype,"any",t),x;if(a){let b=N.expandShapeToKeepDim(m,l);x=ce({inputs:{x:g},backend:t,attrs:{shape:b}})}else x=ce({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),c!=null&&t.disposeIntermediateTensorInfo(p),x}var tF={kernelName:Gl,backendName:"webgl",kernelFunc:UY};var Bv=class{constructor(e,t,o){this.variableNames=["A"];let{windowSize:n,batchSize:s,outSize:a}=e;o||this.variableNames.push("bestIndicesA"),this.outputShape=[s,a];let i=t==="max"?">":"<",l=o?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * ${n};
|
|
|
|
int bestIndex = inOffset;
|
|
float bestValue = getA(batch, bestIndex);
|
|
|
|
for (int i = 0; i < ${n}; i++) {
|
|
int inIdx = ${l};
|
|
float candidate = getA(batch, inIdx);
|
|
if (candidate ${i} bestValue) {
|
|
bestValue = candidate;
|
|
bestIndex = inIdx;
|
|
}
|
|
}
|
|
setOutput(float(bestIndex));
|
|
}
|
|
`}};var Vv=class{constructor(e,t,o,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,y.assert(e.length>2,()=>`Packed arg${o.charAt(0).toUpperCase()+o.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),n||this.variableNames.push("bestIndicesA");let i=this.outputShape,l=i.length,u=Le(l),c=Ut("coords",l),p,m;if(a===1){m=l+1;let R=Le(m);p=`
|
|
${R} sourceLocR = ${R}(${c.join()}, 0);
|
|
++${c[l-1]};
|
|
${R} sourceLocG = ${R}(${c.join()}, 0);
|
|
++${c[l-2]};
|
|
${R} sourceLocA = ${R}(${c.join()}, 0);
|
|
--${c[l-1]};
|
|
${R} sourceLocB = ${R}(${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(R=>"int "+R),g=Ut("sourceLocR",m-1).concat("inIdx.r"),x=Ut("sourceLocG",m-1).concat("inIdx.g"),b=Ut("sourceLocB",m-1).concat("inIdx.b"),_=Ut("sourceLocA",m-1).concat("inIdx.a"),w=o==="max"?"greaterThan":"lessThan",v=n?"":`
|
|
inIdx = round(vec4(getBestIndicesAChannel(${g.join()}),
|
|
getBestIndicesAChannel(${x.join()}),
|
|
getBestIndicesAChannel(${b.join()}),
|
|
getBestIndicesAChannel(${_.join()})));`,$=`vec4(
|
|
getAChannel(${g.join()}),
|
|
hasNextCol ? getAChannel(${x.join()}) : 0.,
|
|
hasNextRow ? getAChannel(${b.join()}) : 0.,
|
|
hasNextRow && hasNextCol ? getAChannel(${_.join()}) : 0.)`,A=n?"":`
|
|
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()}));
|
|
}
|
|
${A}
|
|
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 = ${$};
|
|
|
|
for (int i = 0; i < ${t}; i++) {
|
|
inIdx = srcIdx;
|
|
${v}
|
|
vec4 candidate = ${$};
|
|
bvec4 nan = isnan(candidate);
|
|
bvec4 replace = bvec4(
|
|
vec4(${w}(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 rF(r,e,t,o=null){let n=e.shape[0],s=e.shape[1];o!=null&&(n=o.shape[0],s=o.shape[1]);let a=N.computeOptimalWindowSize(s),i={windowSize:a,inSize:s,batchSize:n,outSize:Math.ceil(s/a)},l=new Bv(i,t,o==null),u=[e];o!=null&&u.push(o);let c=r.runWebGLProgram(l,u,"int32");if(c.shape[1]===1)return c;let p=rF(r,e,t,c);return r.disposeIntermediateTensorInfo(c),p}function oF(r,e,t,o=null){let n=o!=null?o.shape:e.shape,s=n[n.length-1],a=N.computeOptimalWindowSize(s),i=new Vv(n,a,t,o==null),l=o==null?[e]:[e,o],u=r.runWebGLProgram(i,l,"int32");if(u.shape.length===e.shape.length){let c=oF(r,e,t,u);return r.disposeIntermediateTensorInfo(u),c}return u}function Vx(r,e,t,o){let n=[t];if(N.assertAxesAreInnerMostDims("arg"+o.charAt(0).toUpperCase()+o.slice(1),n,e.shape.length),!G().getBool("WEBGL_PACK_REDUCE")||e.shape.length<=2){let s=[],[a,i]=N.computeOutAndReduceShapes(e.shape,n),l=y.sizeFromShape(i),u=ce({inputs:{x:e},backend:r,attrs:{shape:[-1,l]}});s.push(u);let c=rF(r,u,o);s.push(c);let p=ce({inputs:{x:c},backend:r,attrs:{shape:a}});return s.forEach(m=>r.disposeIntermediateTensorInfo(m)),p}return oF(r,e,o)}function jY(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s}=o,a=y.parseAxisParam(s,n.shape),i=N.getAxesPermutation(a,n.shape.length),l=n,u=[];i!=null&&(l=Lt({inputs:{x:n},backend:t,attrs:{perm:i}}),u.push(l),a=N.getInnerMostAxes(a.length,l.shape.length)),N.assertAxesAreInnerMostDims("argMax",[a[0]],l.shape.length);let c=Vx(t,l,a[0],"max");return u.forEach(p=>t.disposeIntermediateTensorInfo(p)),c}var nF={kernelName:jo,backendName:"webgl",kernelFunc:jY};function HY(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s}=o,a=y.parseAxisParam(s,n.shape),i=N.getAxesPermutation(a,n.shape.length),l=n,u=[];i!=null&&(l=Lt({inputs:{x:n},backend:t,attrs:{perm:i}}),u.push(l),a=N.getInnerMostAxes(a.length,l.shape.length)),N.assertAxesAreInnerMostDims("argMin",[a[0]],l.shape.length);let c=Vx(t,l,a[0],"min");return u.forEach(p=>t.disposeIntermediateTensorInfo(p)),c}var sF={kernelName:oa,backendName:"webgl",kernelFunc:HY};var qY=gr+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return asin(x);
|
|
`,KY=ve({opSnippet:qY}),iF={kernelName:Xs,backendName:"webgl",kernelFunc:KY};var XY=gr+"return log(x + sqrt(x * x + 1.0));",YY=ve({opSnippet:XY}),aF={kernelName:Ys,backendName:"webgl",kernelFunc:YY};var ZY=gr+`
|
|
return atan(x);
|
|
`,JY=ve({opSnippet:ZY}),lF={kernelName:Zs,backendName:"webgl",kernelFunc:JY};var QY=MR+`
|
|
return atan(a, b);
|
|
`,e7=`
|
|
vec4 result = atan(a, b);
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+LR+`
|
|
return result;
|
|
`,t7=it({opSnippet:QY,packedOpSnippet:e7}),uF={kernelName:Qs,backendName:"webgl",kernelFunc:t7};var r7=gr+`
|
|
if ((x < -1.0) || (x > 1.0)) return NAN;
|
|
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,o7=ve({opSnippet:r7}),cF={kernelName:Js,backendName:"webgl",kernelFunc:o7};var Zi=class{constructor(e,t,o,n=!1,s=!1){if(this.variableNames=["x"],t==="avg"&&o)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"),o){let R=">=";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 ${R} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${n?s?g:x:`wR * ${m} + wC`};
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;return}let _="max",w=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(w="avgValue / count");let v=Math.floor(a/4)*4,$=a%4,A=`
|
|
if (${h}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${_}(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 < ${v}; 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)
|
|
);
|
|
|
|
${A}
|
|
}
|
|
|
|
int xC = xCCorner + ${v};
|
|
if (${$===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${A}
|
|
} else if (${$===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${c}, d),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${A}
|
|
} else if (${$===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${c}, d),
|
|
getValue(batch, xR, xC + 2 * ${c}, d),
|
|
initializationValue
|
|
);
|
|
|
|
${A}
|
|
}
|
|
}
|
|
setOutput(${w});
|
|
}
|
|
`}},cc=class{constructor(e,t,o,n=!1,s=!1){if(this.variableNames=["x"],t==="avg"&&o)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 _=t==="avg",w="0.0";if(_||(w="-1.0 / 1e-20"),o){let z=">=";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 ${z} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${n?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 v="max",$=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&($="avgValue / count");let A=Math.floor(a/4)*4,R=a%4,M=`
|
|
if (${_}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${v}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${i}, ${l}, ${u});
|
|
const ivec3 pads = ivec3(${g}, ${x}, ${b});
|
|
const float initializationValue = ${w};
|
|
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(${w});
|
|
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 < ${A}; 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)
|
|
);
|
|
|
|
${M}
|
|
}
|
|
|
|
int xC = xCCorner + ${A};
|
|
if (${R===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${M}
|
|
} else if (${R===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${m}, ch),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${M}
|
|
} else if (${R===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
|
|
);
|
|
|
|
${M}
|
|
}
|
|
}
|
|
setOutput(${$});
|
|
}
|
|
}
|
|
`}};function n7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e;Yi(n,"avgPool");let{filterSize:s,strides:a,pad:i,dimRoundingMode:l}=o,u=1;y.assert(N.eitherStridesOrDilationsAreOne(a,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let c=N.computePool2DInfo(n.shape,s,a,u,i,l);if(c.filterWidth===1&&c.filterHeight===1&&y.arraysEqual(c.inShape,c.outShape))return jt({inputs:{x:n},backend:t});let p=new Zi(c,"avg",!1);return t.runWebGLProgram(p,[n],"float32")}var pF={kernelName:Ho,backendName:"webgl",kernelFunc:n7};function s7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{filterSize:s,strides:a,pad:i,dimRoundingMode:l,dataFormat:u}=o,c=[1,1,1],p=N.computePool3DInfo(n.shape,s,a,c,i,l,u),m=new cc(p,"avg",!1);return t.runWebGLProgram(m,[n],"float32")}var mF={kernelName:na,backendName:"webgl",kernelFunc:s7};var Gv=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,o=e.filterWidth,n=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*o);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) / ${n}.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);
|
|
}
|
|
`}},Wv=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,o=e.filterHeight,n=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*o*n);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 i7(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,a=s,{filterSize:i,strides:l,pad:u,dimRoundingMode:c}=o,p=[1,1,1],m=N.computePool3DInfo(a.shape,i,l,p,u,c),f=new Wv(m);return t.runWebGLProgram(f,[n],a.dtype)}var fF={kernelName:Ul,backendName:"webgl",kernelFunc:i7};function a7(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,a=s;Yi([n,s],"avgPoolGrad");let{filterSize:i,strides:l,pad:u}=o,c=N.computePool2DInfo(a.shape,i,l,1,u),p=new Gv(c);return t.runWebGLProgram(p,[n],a.dtype)}var dF={kernelName:Wl,backendName:"webgl",kernelFunc:a7};function l7(r){let{inputs:e,backend:t,attrs:o}=r,{a:n,b:s}=e,{transposeA:a,transposeB:i}=o;return uc({a:n,b:s,transposeA:a,transposeB:i,backend:t})}var hF={kernelName:qo,backendName:"webgl",kernelFunc:l7};var Uv=class{constructor(e,t,o,n,s,a){this.outputShape=[],this.variableNames=["x","mean","variance"],N.assertAndGetBroadcastShape(e,t),N.assertAndGetBroadcastShape(e,o);let i="0.0";n!=null&&(N.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let l="1.0";s!=null&&(N.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 jv=class{constructor(e,t,o,n,s,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],N.assertAndGetBroadcastShape(e,t),N.assertAndGetBroadcastShape(e,o);let i="vec4(0.0)";n!=null&&(N.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let l="vec4(1.0)";s!=null&&(N.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 u7=({inputs:r,backend:e,attrs:t})=>{let{x:o,mean:n,variance:s,offset:a,scale:i}=r;y.assert(n.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),y.assert(a==null||n.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),y.assert(i==null||n.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=[o,n,s],c=null;a!=null&&(c=a.shape,u.push(a));let p=null;i!=null&&(p=i.shape,u.push(i));let m=G().getBool("WEBGL_PACK_NORMALIZATION")?new jv(o.shape,n.shape,s.shape,c,p,l):new Uv(o.shape,n.shape,s.shape,c,p,l);return e.runWebGLProgram(m,u,u[0].dtype)},gF={kernelName:on,backendName:"webgl",kernelFunc:u7};var Hv=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=Le(this.rank),o=`uniform int start[${this.rank}];`,n=c7(this.rank),s,a=e.map((i,l)=>`sourceLoc.${qv[l]} = start[${l}] + coords.${qv[l]};`);s=`
|
|
${t} sourceLoc;
|
|
${t} coords = getOutputCoords();
|
|
${a.join(`
|
|
`)}
|
|
`,this.userCode=`
|
|
${o}
|
|
void main() {
|
|
${s}
|
|
setOutput(getSource(${n}));
|
|
}
|
|
`}getCustomSetupFunc(e){if(e.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${e.length})`);return(t,o)=>{this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(o,"start"),this.startLoc==null)||t.gl.uniform1iv(this.startLoc,e)}}},qv=["x","y","z","w","u","v"];function c7(r){if(r===1)return"sourceLoc";if(r<=6)return qv.slice(0,r).map(e=>"sourceLoc."+e).join(",");throw Error(`Slicing for rank ${r} is not yet supported`)}var Kv=class{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;let t=Le(this.rank),o=Ut("coords",this.rank),n=Ut("sourceLoc",this.rank),s=this.rank===1?"sourceLoc":`vec2(${n.slice(-2).join()})`,a=`getChannel(getSource(${n.join()}), ${s})`,i=`
|
|
result.x = ${a};
|
|
if (++${o[this.rank-1]} < ${e[this.rank-1]}) {
|
|
++${n[this.rank-1]};
|
|
result.y = ${a};
|
|
--${n[this.rank-1]};
|
|
}
|
|
`,l=this.rank===1?"":`
|
|
--${o[this.rank-1]};
|
|
if (++${o[this.rank-2]} < ${e[this.rank-2]}) {
|
|
++${n[this.rank-2]};
|
|
result.z = ${a};
|
|
if (++${o[this.rank-1]} < ${e[this.rank-1]}) {
|
|
++${n[this.rank-1]};
|
|
result.w = ${a};
|
|
}
|
|
}
|
|
`,u=this.rank<=4?`sourceLoc = coords +
|
|
${t}(${e.map((c,p)=>`start[${p}]`).join()});`:e.map((c,p)=>`${n[p]} = ${o[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,o)=>{this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(o,"start"),this.startLoc==null)||t.gl.uniform1iv(this.startLoc,e)}}};function p7(r,e,t,o){let n=o.texData.get(r.dataId),s=o.makeTensorInfo(t,r.dtype),a=o.texData.get(s.dataId);Object.assign(a,n),a.complexParentRefCount=0,a.refCount=1,a.shape=t,a.dtype=r.dtype;let i=or.computeFlatOffset(e,y.computeStrides(r.shape));n.slice&&(i+=n.slice.flatOffset),a.slice={flatOffset:i,origDataId:n.slice&&n.slice.origDataId||r.dataId};let l=o.dataRefCount.get(a.slice.origDataId)||1;return o.dataRefCount.set(a.slice.origDataId,l+1),s}function Ua(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{begin:s,size:a}=o,[i,l]=or.parseSliceParams(n,s,a);if(or.assertParamsValid(n,i,l),y.sizeFromShape(l)===0)return t.makeTensorInfo(l,n.dtype,[]);if(t.shouldExecuteOnCPU([n])||n.dtype==="string"){let p=t.texData.get(n.dataId),m=dR(p.values,i,l,n.shape,n.dtype);return t.makeTensorInfo(l,n.dtype,m)}let{isPacked:u}=t.texData.get(n.dataId),c=or.isSliceContinous(n.shape,i,l);if(u||!c){let p=G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Kv(l):new Hv(l),m=p.getCustomSetupFunc(i);return t.runWebGLProgram(p,[n],n.dtype,m)}return t.uploadToGPU(n.dataId),p7(n,i,l,t)}var xF={kernelName:hs,backendName:"webgl",kernelFunc:Ua};var m7=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockShape:s,crops:a}=o;y.assert(n.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let i=s.reduce((b,_)=>b*_),l=N.getReshaped(n.shape,s,i),u=N.getPermuted(l.length,s.length),c=N.getReshapedPermuted(n.shape,s,i),p=N.getSliceBeginCoords(a,s.length),m=N.getSliceSize(c,a,s.length),f=[],d=ce({inputs:{x:n},backend:t,attrs:{shape:l}}),h=Lt({inputs:{x:d},backend:t,attrs:{perm:u}}),g=ce({inputs:{x:h},backend:t,attrs:{shape:c}}),x=Ua({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},yF={kernelName:sa,backendName:"webgl",kernelFunc:m7};function f7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,weights:s}=e,{size:a}=o,i=t.readSync(n.dataId),l=t.readSync(s.dataId),u=Rx(i,l,s.dtype,s.shape,a);return t.makeTensorInfo([a],s.dtype,u)}var bF={kernelName:jl,backendName:"webgl",kernelFunc:f7};var d7="return float(a != b);",Xv=it({opSnippet:d7,dtype:"bool"}),_F={kernelName:bi,backendName:"webgl",kernelFunc:Xv};function ja(r){let{inputs:e,backend:t}=r,{input:o}=e,n=t.texData.get(o.dataId);return jt({inputs:{x:n.complexTensorInfos.real},backend:t})}var wF={kernelName:cu,backendName:"webgl",kernelFunc:ja};var h7="return float(int(x));";function kF(r,e){let t=new uo(r.shape,h7),o=e.runWebGLProgram(t,[r],"int32");return{dataId:o.dataId,shape:o.shape,dtype:o.dtype}}function Yv(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{dtype:s}=o;if(s==="complex64"){if(n.dtype==="complex64")return jt({inputs:{x:n},backend:t});let a=gt(n.shape),i=Yv({inputs:{x:n},backend:t,attrs:{dtype:"float32"}}),l=co({inputs:{real:i,imag:a},backend:t});return a.dispose(),t.disposeIntermediateTensorInfo(i),l}if(n.dtype==="complex64"){let a=ja({inputs:{input:n},backend:t}),i=Yv({inputs:{x:a},backend:t,attrs:{dtype:s}});return t.disposeIntermediateTensorInfo(a),i}if(!y.hasEncodingLoss(n.dtype,s)){let a=jt({inputs:{x:n},backend:t});return{dataId:a.dataId,shape:a.shape,dtype:s}}if(s==="int32")return kF(n,t);if(s==="bool"){let a=t.makeTensorInfo([],"bool",y.getTypedArrayFromDType("bool",1)),l=Xv({inputs:{a:n,b:a},backend:t});return t.disposeIntermediateTensorInfo(a),l}throw new Error(`Error in Cast: failed to cast ${n.dtype} to ${s}`)}var vF={kernelName:Eo,backendName:"webgl",kernelFunc:Yv};var CF="return ceil(x);",g7=ve({opSnippet:CF,packedOpSnippet:CF,cpuKernelImpl:Y$}),IF={kernelName:ei,backendName:"webgl",kernelFunc:g7};var Zv=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(o,n)=>{this.minLoc==null&&(this.minLoc=o.getUniformLocationNoThrow(n,"minVal"),this.maxLoc=o.getUniformLocationNoThrow(n,"maxVal")),o.gl.uniform1f(this.minLoc,e),o.gl.uniform1f(this.maxLoc,t)}}};var Jv=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(o,n)=>{this.minLoc==null&&(this.minLoc=o.getUniformLocationNoThrow(n,"minVal"),this.maxLoc=o.getUniformLocationNoThrow(n,"maxVal")),o.gl.uniform1f(this.minLoc,e),o.gl.uniform1f(this.maxLoc,t)}}};function x7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{clipValueMin:s,clipValueMax:a}=o,i;G().getBool("WEBGL_PACK_CLIP")?i=new Jv(n.shape):i=new Zv(n.shape);let l=i.getCustomSetupFunc(s,a);return t.runWebGLProgram(i,[n],n.dtype,l)}var NF={kernelName:Ao,backendName:"webgl",kernelFunc:x7};var Qv=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 SF(r,e){return{dataId:e.dataId,dtype:e.dtype,shape:r.shape}}function y7(r){let{inputs:e,backend:t}=r,{x:o}=e,n=t.texData.get(o.dataId),s=new Qv(o.shape),a=[SF(o,n.complexTensorInfos.real),SF(o,n.complexTensorInfos.imag)];return t.runWebGLProgram(s,a,a[0].dtype)}var TF={kernelName:ia,backendName:"webgl",kernelFunc:y7};var eC=class{constructor(e){this.outputShape=[],this.outputShape=N.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 o=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let a=1;a<t.length;a++){let i=t[a-1];o.push(`else if (yC < ${t[a]}) setOutput(getT${a}(yR, yC-${i}));`)}let n=t.length,s=t[t.length-1];o.push(`else setOutput(getT${n}(yR, yC-${s}));`),this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int yR = coords.x;
|
|
int yC = coords.y;
|
|
|
|
${o.join(`
|
|
`)}
|
|
}
|
|
`}};var tC=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=N.computeOutShape(e,t);let o=this.outputShape,n=o.length,s=Le(n),a=Ut("coords",n),i=["x","y","z","w","u","v"].slice(0,n);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}(${Gx(i,u,g)}),
|
|
vec2(${Gx(c,u,g)}));
|
|
}`}let f=l.length,d=l[l.length-1];m+=`
|
|
return getChannel(
|
|
getT${f}(${Gx(i,u,d)}),
|
|
vec2(${Gx(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[n-1]} = ${a[n-1]} + 1;
|
|
if (${a[n-1]} < ${o[n-1]}) {
|
|
result.g = getValue(${a});
|
|
}
|
|
|
|
${a[n-2]} = ${a[n-2]} + 1;
|
|
if (${a[n-2]} < ${o[n-2]}) {
|
|
result.a = getValue(${a});
|
|
}
|
|
|
|
${a[n-1]} = ${a[n-1]} - 1;
|
|
if (${a[n-2]} < ${o[n-2]} &&
|
|
${a[n-1]} < ${o[n-1]}) {
|
|
result.b = getValue(${a});
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};function Gx(r,e,t){let o=r.indexOf(e);return r.map((s,a)=>a===o?`${s} - ${t}`:s).join()}function pc(r){let{inputs:e,backend:t}=r,{input:o}=e,n=t.texData.get(o.dataId);return jt({inputs:{x:n.complexTensorInfos.imag},backend:t})}var EF={kernelName:ou,backendName:"webgl",kernelFunc:pc};function mc(r,e,t){let o=r[0].dtype;if(o==="complex64"){let u=r.map(d=>ja({inputs:{input:d},backend:t})),c=r.map(d=>pc({inputs:{input:d},backend:t})),p=mc(u,e,t),m=mc(c,e,t),f=co({inputs:{real:p,imag:m},backend:t});return u.forEach(d=>t.disposeIntermediateTensorInfo(d)),c.forEach(d=>t.disposeIntermediateTensorInfo(d)),t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(m),f}if(o==="string"){let{tensors2D:u,outShape:c}=AF(r,e,t),p=u.map(g=>({vals:t.readSync(g.dataId),shape:g.shape})),m=u[0].shape[0]===1,f=Z$(p,c,o,m),d=N.computeOutShape(r.map(g=>g.shape),e),h=t.makeTensorInfo(d,o,f);return u.forEach(g=>t.disposeIntermediateTensorInfo(g)),h}if(r.length>G().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let u=Math.floor(r.length/2),c=mc(r.slice(0,u),e,t),p=mc(r.slice(u),e,t),m=mc([c,p],e,t);return t.disposeIntermediateTensorInfo(c),t.disposeIntermediateTensorInfo(p),m}if(G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&r[0].shape.length>1){let u=new tC(r.map(c=>c.shape),e);return t.runWebGLProgram(u,r,o)}let{tensors2D:n,outShape:s}=AF(r,e,t),a=new eC(n.map(u=>u.shape)),i=t.runWebGLProgram(a,n,o);n.forEach(u=>t.disposeIntermediateTensorInfo(u));let l=ce({inputs:{x:i},attrs:{shape:s},backend:t});return t.disposeIntermediateTensorInfo(i),l}function AF(r,e,t){let o=N.computeOutShape(r.map(s=>s.shape),e);return{tensors2D:r.map(s=>ce({inputs:{x:s},attrs:{shape:[-1,y.sizeFromShape(s.shape.slice(e))]},backend:t})),outShape:o}}function rC(r){let{inputs:e,backend:t,attrs:o}=r,{axis:n}=o,s=y.parseAxisParam(n,e[0].shape)[0],a=N.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 jt({inputs:{x:i[0]},backend:t});let l=i.map(u=>u.shape);return N.assertParamsConsistent(l,s),mc(i,s,t)}var DF={kernelName:is,backendName:"webgl",kernelFunc:rC};var lh=class{constructor(e,t=!1,o=null,n=!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,_=g?3:1,w="",v="";o&&(n?w=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${o}
|
|
}`:s?w=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${o}
|
|
}`:w=`
|
|
float activation(float x) {
|
|
${o}
|
|
}
|
|
`,v="result = activation(result);");let $=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${w}
|
|
|
|
const ivec2 strides = ivec2(${l}, ${u});
|
|
const ivec2 pads = ivec2(${a}, ${i});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d2 = coords[${_}];
|
|
|
|
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;
|
|
${$}
|
|
${v}
|
|
setOutput(result);
|
|
}
|
|
`}},oC=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let t=e.padInfo.front,o=e.padInfo.top,n=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}, ${o}, ${n});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int d2 = coords.u;
|
|
|
|
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xFCorner = xFRCCorner.x;
|
|
int xRCorner = xFRCCorner.y;
|
|
int xCCorner = xFRCCorner.z;
|
|
|
|
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
|
|
// y(yF, yR, yC, d2). ? = to be determined. : = across all
|
|
// values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wF = 0; wF < ${p}; wF++) {
|
|
int xF = xFCorner + wF * ${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 nC=class{constructor(e,t,o){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;let{filterWidth:n,inChannels:s,strideWidth:a,strideHeight:i,padInfo:l,outWidth:u,dilationWidth:c,dilationHeight:p,dataFormat:m}=o,{left:f,top:d}=l,h=s*n,g=Mt(),x=m==="channelsLast",b=x?0:1,_=x?1:2,w="";for(let v=0;v<=1;v++)for(let $=0;$<=1;$++)w+=`
|
|
blockIndex = rc.y + ${$};
|
|
pos = rc.x + ${v};
|
|
|
|
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[_]} && d1 >= 0) {
|
|
|
|
ch = int(mod(float(pos), ${s}.));
|
|
|
|
if (${x}) {
|
|
innerDims = vec2(d1, ch);
|
|
result[${v*2+$}] = getChannel(
|
|
getA(d0, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
} else {
|
|
innerDims = vec2(d0, d1);
|
|
result[${v*2+$}] = getChannel(
|
|
getA(ch, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
`;this.userCode=`
|
|
void main() {
|
|
ivec2 rc = getOutputCoords();
|
|
|
|
vec4 result = vec4(0);
|
|
|
|
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
|
|
vec2 innerDims;
|
|
|
|
${w}
|
|
|
|
${g.output} = result;
|
|
}
|
|
`}};function Wx({x:r,filter:e,convInfo:t,backend:o,bias:n=null,preluActivationWeights:s=null,leakyreluAlpha:a=0,activation:i=null}){let l=r.shape,u=o.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>Mv,_=l[2]%2!=0&&!!u.isPacked;if(b||!G().getBool("WEBGL_LAZILY_UNPACK")||!G().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!_){let w=f?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],v=ce({inputs:{x:r},backend:o,attrs:{shape:[1,w,t.inChannels]}}),$=ce({inputs:{x:e},backend:o,attrs:{shape:[1,t.inChannels,t.outChannels]}}),A=uc({a:v,b:$,transposeA:d,transposeB:h,backend:o,bias:n,activation:i,preluActivationWeights:s,leakyreluAlpha:a});g=ce({inputs:{x:A},backend:o,attrs:{shape:t.outShape}}),x.push(v),x.push($),x.push(A)}else{let w=f?l[0]*l[1]*(l[2]+1):l[0]*l[2]*(l[3]+1),v={dataId:r.dataId,shape:[1,w,t.inChannels],dtype:r.dtype},$=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,y.assert(ac(u.shape,v.shape),()=>`packed reshape ${u.shape} to ${v.shape} isn't free`);let A=ce({inputs:{x:e},backend:o,attrs:{shape:[1,t.inChannels,t.outChannels]}});x.push(A);let R=uc({a:v,b:A,backend:o,transposeA:d,transposeB:h,bias:n,activation:i,preluActivationWeights:s,leakyreluAlpha:a}),M=o.texData.get(R.dataId);y.assert(M.isPacked,()=>"batchMatMul result is expected to be packed"),u.shape=$,M.shape=t.outShape,g=jt({inputs:{x:R},backend:o}),g.shape=t.outShape,x.push(R)}for(let w of x)o.disposeIntermediateTensorInfo(w);return g}function Ux({x:r,filter:e,convInfo:t,backend:o,bias:n=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,_=!1,w=[],v=ce({inputs:{x:r},backend:o,attrs:{shape:r.shape.slice(1)}}),$=ce({inputs:{x:e},backend:o,attrs:{shape:[1,h,y.sizeFromShape(e.shape)/h]}});w.push(v),w.push($);let A=new nC(x,v.shape,t),R=o.runWebGLProgram(A,[v],"float32"),M=ce({inputs:{x:R},backend:o,attrs:{shape:[1,x[0],x[1]]}});w.push(R),w.push(M);let z=n!=null,W=s!=null,U=i==="leakyrelu",q=i?El(i,!0):null,Z=new ih(M.shape,$.shape,[1,g,t.outChannels],b,_,z,q,W,U),X=[M,$];if(n&&X.push(n),W&&X.push(s),U){let re=o.makeTensorInfo([],"float32",y.createScalarValue(a,"float32"));X.push(re),w.push(re)}let Y=o.runWebGLProgram(Z,X,"float32"),te=d?[1,m,p,t.outChannels]:[1,t.outChannels,m,p],K=ce({inputs:{x:Y},backend:o,attrs:{shape:te}});w.push(Y);for(let re of w)o.disposeIntermediateTensorInfo(re);return K}function b7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dataFormat:l,dilations:u,dimRoundingMode:c}=o,p=N.convertConv2DDataFormat(l),m=N.computeConv2DInfo(n.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=Wx({x:n,filter:s,convInfo:m,backend:t});else if(G().getBool("WEBGL_CONV_IM2COL")&&n.shape[0]===1)f=Ux({x:n,filter:s,convInfo:m,backend:t});else{let h=new lh(m);f=t.runWebGLProgram(h,[n,s],"float32")}let d=ce({inputs:{x:f},backend:t,attrs:{shape:m.outShape}});return t.disposeIntermediateTensorInfo(f),d}var $F={kernelName:Ko,backendName:"webgl",kernelFunc:b7};var sC=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,o=e.strideWidth,n=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} - ${n};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${o} - ${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);
|
|
}
|
|
`}},iC=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,o=e.filterWidth,n=e.strideHeight,s=e.strideWidth,a=e.dataFormat==="channelsLast",i=t-1-e.padInfo.top,l=o-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) / ${n}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
int wRPerm = ${t} - 1 - wR;
|
|
|
|
for (int wC = 0; wC < ${o}; 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 = ${o} - 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);
|
|
}
|
|
`}},aC=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideDepth,o=e.strideHeight,n=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 * ${o} - ${a};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${n} - ${i};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float dyValue = getDy(b, yF, yR, yC, d2);
|
|
float xValue = getX(b, xF, xR, xC, d1);
|
|
dotProd += (xValue * dyValue);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},lC=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,o=e.filterHeight,n=e.filterWidth,s=e.strideDepth,a=e.strideHeight,i=e.strideWidth,l=t-1-e.padInfo.front,u=o-1-e.padInfo.top,c=n-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 < ${o}; 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 = ${o} - 1 - wR;
|
|
|
|
for (int wC = 0; wC < ${n}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${i}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = ${n} - 1 - wC;
|
|
|
|
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
|
|
float xValue = getDy(batch, idyF, idyR, idyC, d2);
|
|
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
|
|
dotProd += xValue * wValue;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function _7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,dy:s}=e,{strides:a,pad:i,dataFormat:l,dimRoundingMode:u,filterShape:c}=o,p=N.convertConv2DDataFormat(l),m=N.computeConv2DInfo(n.shape,c,a,1,i,u,!1,p),f=new sC(m);return t.runWebGLProgram(f,[n,s],"float32")}var RF={kernelName:ql,backendName:"webgl",kernelFunc:_7};function w7(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,filter:s}=e,{inputShape:a,strides:i,pad:l,dataFormat:u,dimRoundingMode:c}=o,p=N.convertConv2DDataFormat(u),m=N.computeConv2DInfo(a,s.shape,i,1,l,c,!1,p),f=new iC(m);return t.runWebGLProgram(f,[n,s],"float32")}var FF={kernelName:Xo,backendName:"webgl",kernelFunc:w7};function k7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dilations:l}=o,u=N.computeConv3DInfo(n.shape,s.shape,a,l,i),c=new oC(u);return t.runWebGLProgram(c,[n,s],"float32")}var OF={kernelName:aa,backendName:"webgl",kernelFunc:k7};function v7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,dy:s}=e,{strides:a,pad:i,filterShape:l}=o,u=N.computeConv3DInfo(n.shape,l,a,1,i),c=new aC(u);return t.runWebGLProgram(c,[n,s],"float32")}var PF={kernelName:Kl,backendName:"webgl",kernelFunc:v7};function C7(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,filter:s}=e,{pad:a,strides:i,inputShape:l}=o,u=N.computeConv3DInfo(l,s.shape,i,1,a),c=new lC(u);return t.runWebGLProgram(c,[n,s],"float32")}var MF={kernelName:Xl,backendName:"webgl",kernelFunc:C7};var I7=Mx+`
|
|
return cos(x);
|
|
`,N7=ve({opSnippet:I7}),LF={kernelName:Yo,backendName:"webgl",kernelFunc:N7};var S7=`
|
|
float e2x = exp(-x);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`,T7=ve({opSnippet:S7}),zF={kernelName:ti,backendName:"webgl",kernelFunc:T7};var uC=class{constructor(e,t,o,n,s){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[a,i,l,u]=e,[c]=t,[p,m]=o;this.outputShape=[c,p,m,u];let f=n==="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,v]=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(${_});
|
|
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 = ${w};
|
|
|
|
float in_y = ${b};
|
|
if( in_y < 0.0 || in_y > ${d} ) {
|
|
setOutput(float(${s}));
|
|
return;
|
|
}
|
|
float in_x = ${v};
|
|
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 E7=r=>{let{inputs:e,backend:t,attrs:o}=r,{image:n,boxes:s,boxInd:a}=e,{cropSize:i,method:l,extrapolationValue:u}=o,c=new uC(n.shape,s.shape,i,l,u);return t.runWebGLProgram(c,[n,s,a],"float32")},BF={kernelName:ri,backendName:"webgl",kernelFunc:E7};var jx=class{constructor(e,t,o){this.variableNames=["x"],this.outputShape=e;let n=e.length,s=t?"0.0":`getX(${VF(n,"coords")})`,a=e[e.length-1],i="",l="";t?(i=o?`end != ${a-1}`:"end != 0",l=o?"end + 1":"end - 1"):(i=o?`end + pow2 < ${a}`:"end >= pow2",l=o?"end + pow2":"end - pow2"),this.userCode=`
|
|
uniform float index;
|
|
void main() {
|
|
${Le(n)} coords = getOutputCoords();
|
|
int end = ${GF(n,"coords")};
|
|
float val = ${s};
|
|
int pow2 = int(pow(2.0, index));
|
|
if (${i}) {
|
|
int idx = ${l};
|
|
${GF(n,"coords")} = idx;
|
|
val += getX(${VF(n,"coords")});
|
|
}
|
|
setOutput(val);
|
|
}
|
|
`}getCustomSetupFunc(e){return(t,o)=>{this.index==null&&(this.index=t.getUniformLocation(o,"index")),t.gl.uniform1f(this.index,e)}}};function VF(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 GF(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 A7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,exclusive:a,reverse:i}=o,l=n.shape.length,u=N.getAxesPermutation([s],l),c=n;u!=null&&(c=Lt({inputs:{x:n},backend:t,attrs:{perm:u}}));let p=N.getInnerMostAxes(1,l)[0];if(p!==l-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${n.shape.length-1} but got axis=${s}`);let m=n.shape[p],f=jt({inputs:{x:c},backend:t});for(let d=0;d<=Math.ceil(Math.log2(m))-1;d++){let h=new jx(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 jx(c.shape,a,i),h=f;f=t.runWebGLProgram(d,[f],f.dtype),t.disposeIntermediateTensorInfo(h)}if(u!=null){let d=N.getUndoAxesPermutation(u),h=Lt({inputs:{x:f},backend:t,attrs:{perm:d}});return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(c),h}return f}var WF={kernelName:Zo,backendName:"webgl",kernelFunc:A7};function D7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,weights:s}=e,{size:a,binaryOutput:i}=o;if(n.shape.length===1){let l=t.readSync(n.dataId),u=t.readSync(s.dataId),c=Rx(l,u,s.dtype,s.shape,a);return t.makeTensorInfo([a],s.dtype,c)}else if(n.shape.length===2){let l=t.bufferSync(n),u=t.bufferSync(s),c=X$(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${n.shape.length}.`)}var UF={kernelName:Yl,backendName:"webgl",kernelFunc:D7};var cC=class{constructor(e,t,o){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=o,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 $7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockSize:s,dataFormat:a}=o;y.assert(s>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${s}`);let i=n.shape[0],l=a==="NHWC"?n.shape[1]:n.shape[2],u=a==="NHWC"?n.shape[2]:n.shape[3],c=a==="NHWC"?n.shape[3]:n.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 cC(d,s,a);return t.runWebGLProgram(h,[n],n.dtype)}var jF={kernelName:oi,backendName:"webgl",kernelFunc:$7};var uh=class{constructor(e,t=!1,o=null,n=!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="";o&&(n?x=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${o}
|
|
}`:s?x=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${o}
|
|
}`:x=`
|
|
float activation(float x) {
|
|
${o}
|
|
}
|
|
`,b="result = activation(result);");let _=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&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;
|
|
${_}
|
|
${b}
|
|
setOutput(result);
|
|
}
|
|
`}};var ch=class{constructor(e,t=!1,o=null,n=!1,s=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,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=h,x="int xR; int xC; int xCOffset;";for(let v=0;v<d;v++)for(let $=0;$<h;$++)x+=`
|
|
vec4 xTexelR${v}C${$*2} = vec4(0.);
|
|
vec4 wR${v}C${$} = vec4(0.);
|
|
vec4 xR${v}C${$} = vec4(0.);`;for(let v=0;v<d;v++)for(let $=0;$<g;$++){let A=$*2;if(x+=`
|
|
xR = xRCorner + ${v*m};
|
|
xC = xCCorner + ${A*f};
|
|
`,p===1){if(A<h&&(u%2==1?x+=`
|
|
xCOffset = xC + 1;
|
|
if(xR >= 0 && xR < ${a} && xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${v}C${A} = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if(xCOffset + 1 >= ${i}) {
|
|
xTexelR${v}C${A}.zw = vec2(0.);
|
|
}
|
|
} else {
|
|
xTexelR${v}C${A} = vec4(0.);
|
|
}
|
|
|
|
xCOffset = xC + 1 - 2;
|
|
if(xR >= 0 && xR < ${a} && xCOffset >= 0 && xCOffset < ${i}) {
|
|
vec4 previous = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if(xCOffset + 1 >= ${i}) {
|
|
previous.zw = vec2(0.);
|
|
}
|
|
|
|
xR${v}C${A} = vec4(previous.zw, xTexelR${v}C${A}.xy);
|
|
} else {
|
|
xR${v}C${A} = vec4(0, 0, xTexelR${v}C${A}.xy);
|
|
}
|
|
`:x+=`
|
|
if(xR >= 0 && xR < ${a} && xC >= 0 && xC < ${i}) {
|
|
xTexelR${v}C${A} = getX(batch, xR, xC, d1);
|
|
} else {
|
|
xTexelR${v}C${A} = vec4(0.);
|
|
}
|
|
|
|
xR${v}C${A} = xTexelR${v}C${A};
|
|
`,A+1<h)){let R=u%2==0?y.nearestLargerEven(f):f;f%2==0&&u%2==1||f%2!=0&&u%2!=1?(x+=`
|
|
xCOffset = xC + ${u%2} + ${R};
|
|
|
|
if(xR >= 0 && xR < ${a} &&
|
|
xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${v}C${A+2} = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
`,f>1&&(x+=`
|
|
xCOffset -= 2;
|
|
if(xR >= 0 && xR < ${a} &&
|
|
xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${v}C${A} = getX(batch, xR, xCOffset, d1);
|
|
} else {
|
|
xTexelR${v}C${A} = vec4(0.);
|
|
}
|
|
`),x+=`
|
|
xR${v}C${A+1} = vec4(
|
|
xTexelR${v}C${A}.zw, xTexelR${v}C${A+2}.xy);
|
|
`):x+=`
|
|
xCOffset = xC + ${R};
|
|
|
|
if(xR >= 0 && xR < ${a} &&
|
|
xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${v}C${A+2} = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
|
|
xR${v}C${A+1} = xTexelR${v}C${A+2};
|
|
`}}else A<h&&(x+=`
|
|
if(xR >= 0 && xR < ${a}) {
|
|
`,u%2==1?(x+=`
|
|
xCOffset = xC + 1 - ${p};
|
|
if(xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${v}C${A} = getX(batch, xR, xCOffset, d1);
|
|
} else {
|
|
xTexelR${v}C${A} = vec4(0.);
|
|
}
|
|
|
|
if(xC + 1 >= 0 && xC + 1 < ${i}) {
|
|
xTexelR${v}C${A+2} = getX(batch, xR, xC + 1, d1);
|
|
} else {
|
|
xTexelR${v}C${A+2} = vec4(0.);
|
|
}
|
|
|
|
xR${v}C${A} = vec4(
|
|
xTexelR${v}C${A}.zw, xTexelR${v}C${A+2}.zw);
|
|
`,A+1<h&&(x+=`
|
|
vec4 final = vec4(0.);
|
|
xCOffset = xC + 1 + ${p};
|
|
if(xCOffset >= 0 && xCOffset < ${i}) {
|
|
final = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
xR${v}C${A+1} = vec4(xTexelR${v}C${A+2}.xy, final.xy);
|
|
`)):(x+=`
|
|
if(xC >= 0 && xC < ${i}) {
|
|
xTexelR${v}C${A} = getX(batch, xR, xC, d1);
|
|
} else {
|
|
xTexelR${v}C${A} = vec4(0.);
|
|
}
|
|
|
|
xCOffset = xC + ${p};
|
|
if(xCOffset >= 0 && xCOffset < ${i}) {
|
|
xTexelR${v}C${A+2} = getX(batch, xR, xCOffset, d1);
|
|
} else {
|
|
xTexelR${v}C${A+2} = vec4(0.);
|
|
}
|
|
|
|
xR${v}C${A} = vec4(
|
|
xTexelR${v}C${A}.xy, xTexelR${v}C${A+2}.xy);
|
|
`,A+1<h&&(x+=`
|
|
xR${v}C${A+1} = vec4(
|
|
xTexelR${v}C${A}.zw, xTexelR${v}C${A+2}.zw);
|
|
`)),x+="}");A<h&&(x+=`
|
|
vec4 wTexelR${v}C${A} = getW(${v}, ${A}, d1, q);
|
|
wR${v}C${A} = vec4(wTexelR${v}C${A}.xz, wTexelR${v}C${A}.xz);
|
|
`,A+1<h&&(x+=`
|
|
vec4 wTexelR${v}C${A+1} = getW(${v}, ${A+1}, d1, q);
|
|
wR${v}C${A+1} =
|
|
vec4(wTexelR${v}C${A+1}.xz, wTexelR${v}C${A+1}.xz);`))}for(let v=0;v<d;v++)for(let $=0;$<h;$++)x+=`dotProd += xR${v}C${$} * wR${v}C${$};`;let b="",_="";o&&(n?b=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${o}
|
|
}`:s?b=`vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${o}
|
|
}`:b=`vec4 activation(vec4 x) {
|
|
${o}
|
|
}`,_="result = activation(result);");let w=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${b}
|
|
|
|
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;
|
|
int q = 0;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
vec4 dotProd = vec4(0.);
|
|
|
|
${x}
|
|
|
|
vec4 result = dotProd;
|
|
${w}
|
|
${_}
|
|
setOutput(result);
|
|
}
|
|
`}};function R7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dilations:l,dimRoundingMode:u}=o,c=l;c==null&&(c=[1,1]),y.assert(N.eitherStridesOrDilationsAreOne(a,c),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${c}'`);let p=N.computeConv2DInfo(n.shape,s.shape,a,c,i,u,!0),m;return G().getBool("WEBGL_PACK_DEPTHWISECONV")&&p.strideWidth<=2&&p.outChannels/p.inChannels==1?m=new ch(p):m=new uh(p),t.runWebGLProgram(m,[n,s],"float32")}var HF={kernelName:Jo,backendName:"webgl",kernelFunc:R7};var pC=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,o=e.strideWidth,n=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} - ${n};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${o} - ${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);
|
|
}
|
|
`}},mC=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,o=e.filterWidth,n=e.strideHeight,s=e.strideWidth,a=t-1-e.padInfo.top,i=o-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) / ${n}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
int wRPerm = ${t} - 1 - wR;
|
|
|
|
for (int wC = 0; wC < ${o}; 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 = ${o} - 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 F7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,dy:s}=e,{strides:a,dilations:i,pad:l,dimRoundingMode:u,filterShape:c}=o,p=N.computeConv2DInfo(n.shape,c,a,i,l,u,!0),m=new pC(p);return t.runWebGLProgram(m,[n,s],"float32")}var qF={kernelName:Zl,backendName:"webgl",kernelFunc:F7};function O7(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,filter:s}=e,{strides:a,dilations:i,pad:l,dimRoundingMode:u,inputShape:c}=o,p=N.computeConv2DInfo(c,s.shape,a,i,l,u,!0),m=new mC(p);return t.runWebGLProgram(m,[n,s],"float32")}var KF={kernelName:Jl,backendName:"webgl",kernelFunc:O7};var fC=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 P7(r){let{inputs:e,backend:t}=r,{x:o}=e,n=[...o.shape,...o.shape],s=y.sizeFromShape(o.shape),a=ce({inputs:{x:o},backend:t,attrs:{shape:[s]}}),i=new fC(s),l=t.runWebGLProgram(i,[a],a.dtype),u=ce({inputs:{x:l},backend:t,attrs:{shape:n}});return t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(l),u}var XF={kernelName:Ql,backendName:"webgl",kernelFunc:P7};var dC=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:o,padInfo:n,strideHeight:s,strideWidth:a,filterHeight:i,filterWidth:l,dilationHeight:u,dilationWidth:c}=e,{top:p,left:m}=n;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 < ${o}) {
|
|
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 M7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dilations:l}=o,u=N.computeDilation2DInfo(n.shape,s.shape,a,i,"NHWC",l),c,p=new dC(u);c=t.runWebGLProgram(p,[n,s],"float32");let m=ce({inputs:{x:c},backend:t,attrs:{shape:u.outShape}});return t.disposeIntermediateTensorInfo(c),m}var YF={kernelName:la,backendName:"webgl",kernelFunc:M7};var L7="return (x >= 0.0) ? x : (exp(x) - 1.0);",z7=`
|
|
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;
|
|
`,B7=ve({opSnippet:L7,packedOpSnippet:z7}),ZF={kernelName:ni,backendName:"webgl",kernelFunc:B7};var V7="return (b >= 1.0) ? a : a * (b + 1.0);",G7=`
|
|
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
|
|
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
|
|
`,W7=r=>{let{inputs:e,backend:t}=r,{dy:o,y:n}=e,s=G().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Vs(G7,o.shape,n.shape):new Qn(V7,o.shape,n.shape);return t.runWebGLProgram(s,[o,n],o.dtype)},JF={kernelName:eu,backendName:"webgl",kernelFunc:W7};var U7=`
|
|
return vec4(equal(a, b));
|
|
`,j7="return float(a == b);",H7=it({opSnippet:j7,packedOpSnippet:U7,dtype:"bool"}),QF={kernelName:ii,backendName:"webgl",kernelFunc:H7};var q7=`
|
|
// Error function is calculated approximately with elementary function.
|
|
// See "Handbook of Mathematical Functions with Formulas,
|
|
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
|
|
float p = ${N.ERF_P};
|
|
float a1 = ${N.ERF_A1};
|
|
float a2 = ${N.ERF_A2};
|
|
float a3 = ${N.ERF_A3};
|
|
float a4 = ${N.ERF_A4};
|
|
float a5 = ${N.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));
|
|
`,K7=ve({opSnippet:q7}),eO={kernelName:si,backendName:"webgl",kernelFunc:K7};var tO="return exp(x);",hC=ve({opSnippet:tO,packedOpSnippet:tO,cpuKernelImpl:J$}),rO={kernelName:en,backendName:"webgl",kernelFunc:hC};function Hx(r){let{inputs:e,attrs:t,backend:o}=r,{dim:n}=t,{input:s}=e,a=s.shape.length,i=s.shape.slice(),l=n;return n<0&&(y.assert(-(a+1)<=n,()=>`Axis must be in the interval [${-(a+1)}, ${a}]`),l=a+n+1),i.splice(l,0,1),ce({inputs:{x:s},backend:o,attrs:{shape:i}})}var oO={kernelName:as,backendName:"webgl",kernelFunc:Hx};var nO="return exp(x) - 1.0;",X7=ve({opSnippet:nO,packedOpSnippet:nO,cpuKernelImpl:Q$}),sO={kernelName:ai,backendName:"webgl",kernelFunc:X7};var qx=class{constructor(e,t,o){this.variableNames=["real","imag"];let n=t[1];this.outputShape=t;let s=o?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,a=o?`${n}.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(${n});
|
|
float exponentMultiplierTimesIndexRatio =
|
|
exponentMultiplier * indexRatio;
|
|
|
|
float result = 0.0;
|
|
|
|
for (int i = 0; i < ${n}; i++) {
|
|
// x = (-2|2 * PI / N) * index * i;
|
|
float x = exponentMultiplierTimesIndexRatio * float(i);
|
|
float expR = cos(x);
|
|
float expI = sin(x);
|
|
float real = getReal(batch, i);
|
|
float imag = getImag(batch, i);
|
|
|
|
result +=
|
|
unaryOpComplex(real, expR, imag, expI) / ${a};
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
setOutput(mulMatDFT(coords[0], coords[1]));
|
|
}
|
|
`}};function Kx(r,e,t){let o=t.texData.get(r.dataId),n=y.sizeFromShape(r.shape),s=r.shape[r.shape.length-1],a=n/s,i=ce({inputs:{x:r},backend:t,attrs:{shape:[a,s]}}),l=i.shape,u=new qx("real",l,e),c=new qx("imag",l,e),p=[{dataId:o.complexTensorInfos.real.dataId,dtype:o.complexTensorInfos.real.dtype,shape:l},{dataId:o.complexTensorInfos.imag.dataId,dtype:o.complexTensorInfos.imag.dtype,shape:l}],m=t.runWebGLProgram(u,p,"float32"),f=t.runWebGLProgram(c,p,"float32"),d=co({inputs:{real:m,imag:f},backend:t});t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f);let h=ce({inputs:{x:d},backend:t,attrs:{shape:r.shape}});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(d),h}function Y7(r){let{inputs:e,backend:t}=r,{input:o}=e;return Kx(o,!1,t)}var iO={kernelName:tu,backendName:"webgl",kernelFunc:Y7};var gC=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,o)=>{this.valueLoc==null&&(this.valueLoc=t.getUniformLocationNoThrow(o,"value")),t.gl.uniform1f(this.valueLoc,e)}}};function ph(r){let{backend:e,attrs:t}=r,{shape:o,value:n}=t,{dtype:s}=t;if(s=s||y.inferDtype(n),s==="string"){let a=y.getArrayFromDType(s,y.sizeFromShape(o));return a.fill(n),e.makeTensorInfo(o,s,a)}else{let a=new gC(o,n),i=a.getCustomSetupFunc(n);return e.runWebGLProgram(a,[],s,i)}}var aO={kernelName:ua,backendName:"webgl",kernelFunc:ph};var xC=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 lO={kernelName:li,backendName:"webgl",kernelFunc:({inputs:r,backend:e})=>{let{image:t}=r,o=e,n=new xC(t.shape);return o.runWebGLProgram(n,[t],t.dtype)}};var uO="return floor(x);",Z7=ve({opSnippet:uO,packedOpSnippet:uO,cpuKernelImpl:eR}),cO={kernelName:tn,backendName:"webgl",kernelFunc:Z7};var J7=`
|
|
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;
|
|
}
|
|
`,Q7=`
|
|
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);
|
|
`,eZ=it({opSnippet:J7,packedOpSnippet:Q7,dtype:"int32"}),pO={kernelName:rn,backendName:"webgl",kernelFunc:eZ};var yC=class{constructor(e){this.variableNames=["A"];let t=Mt(),[o,n]=e;this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
int texR = coords[0];
|
|
int texC = coords[1];
|
|
int depth = coords[2];
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${n}.0, ${o}.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 bC=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=Mt(),[o,n]=e;this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
int texR = coords[0];
|
|
int texC = coords[1];
|
|
int depth = coords[2];
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
for(int row=0; row<=1; row++) {
|
|
for(int col=0; col<=1; col++) {
|
|
texC = coords[1] + row;
|
|
depth = coords[2] + col;
|
|
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${n}.0, ${o}.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 mO={kernelName:Fc,backendName:"webgl",kernelFunc:tZ},jp;function tZ(r){let{inputs:e,backend:t,attrs:o}=r,{pixels:n}=e,{numChannels:s}=o,a=typeof HTMLVideoElement!="undefined"&&n instanceof HTMLVideoElement,i=typeof HTMLImageElement!="undefined"&&n instanceof HTMLImageElement,l=typeof ImageBitmap!="undefined"&&n instanceof ImageBitmap,[u,c]=a?[n.videoWidth,n.videoHeight]:[n.width,n.height],p=[c,u],m=[c,u,s];(i||a||l)&&(jp==null&&(jp=document.createElement("canvas").getContext("2d")),jp.canvas.width=u,jp.canvas.height=c,jp.drawImage(n,0,0,u,c),n=jp.canvas);let f=t.makeTensorInfo(p,"int32");t.texData.get(f.dataId).usage=Er.PIXELS,t.gpgpu.uploadPixelDataToTexture(t.getTexture(f.dataId),n);let d=G().getBool("WEBGL_PACK")?new bC(m):new yC(m),h=t.runWebGLProgram(d,[f],"int32");return t.disposeData(f.dataId),h}function rZ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s,bias:a,preluActivationWeights:i}=e,{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=o,h=N.convertConv2DDataFormat(c),g=N.computeConv2DInfo(n.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=Wx({x:n,filter:s,convInfo:g,backend:t,bias:a,activation:f,preluActivationWeights:i,leakyreluAlpha:d});else if(G().getBool("WEBGL_CONV_IM2COL")&&n.shape[0]===1)x=Ux({x:n,filter:s,convInfo:g,backend:t,bias:a,activation:f,preluActivationWeights:i,leakyreluAlpha:d});else{let w=a!=null,v=i!=null,$=f==="leakyrelu",A=f?El(f,!1):null,R=new lh(g,w,A,v,$),M=[n,s];if(a&&M.push(a),i&&M.push(i),$){let z=t.makeTensorInfo([],"float32",y.createScalarValue(d,"float32"));M.push(z),b.push(z)}x=t.runWebGLProgram(R,M,"float32")}let _=ce({inputs:{x},backend:t,attrs:{shape:g.outShape}});return b.push(x),b.forEach(w=>t.disposeIntermediateTensorInfo(w)),_}var fO={kernelName:_s,backendName:"webgl",kernelFunc:rZ};function oZ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s,bias:a,preluActivationWeights:i}=e,{strides:l,pad:u,dilations:c,dimRoundingMode:p,activation:m,leakyreluAlpha:f}=o,d=[],h=c;h==null&&(h=[1,1]),y.assert(N.eitherStridesOrDilationsAreOne(l,h),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${h}'`);let g=N.computeConv2DInfo(n.shape,s.shape,l,h,u,p,!0),x=G().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,b=m?El(m,x):null,_=[n,s],w=a!=null,v=i!=null,$=m==="leakyrelu";if(w&&_.push(a),v&&_.push(i),$){let M=t.makeTensorInfo([],"float32",y.createScalarValue(f,"float32"));_.push(M),d.push(M)}let A;x?A=new ch(g,w,b,v,$):A=new uh(g,w,b,v,$);let R=t.runWebGLProgram(A,_,"float32");return d.forEach(M=>t.disposeIntermediateTensorInfo(M)),R}var dO={kernelName:ws,backendName:"webgl",kernelFunc:oZ};var _C=class{constructor(e,t,o){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=o;let n=Le(t.length),s=Le(o.length),a=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
|
|
${n} strides = ${n}(${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 nZ(r){let{inputs:e,backend:t}=r,{params:o,indices:n}=e,s=n.shape,a=s[s.length-1],[i,l,u,c]=N.prepareAndValidate(o,n),p=ce({inputs:{x:n},backend:t,attrs:{shape:[l,a]}}),m=ce({inputs:{x:o},backend:t,attrs:{shape:[y.sizeFromShape(o.shape)/u,u]}}),f=new _C(a,c,[l,u]),d=t.runWebGLProgram(f,[m,p],m.dtype),h=ce({inputs:{x:d},backend:t,attrs:{shape:i}});return t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(d),h}var hO={kernelName:ui,backendName:"webgl",kernelFunc:nZ};var wC=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let o=Le(this.rank),n=sZ(e,2);this.userCode=`
|
|
void main() {
|
|
${o} resRC = getOutputCoords();
|
|
setOutput(getA(${n}));
|
|
}
|
|
`}};function sZ(r,e){let t=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[];for(let n=0;n<r.length;n++)n===2?o.push("int(getIndices(resRC.x, resRC.z))"):o.push(`${t[n]}`);return o.join()}function iZ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,indices:s}=e,{axis:a,batchDims:i}=o,l=y.parseAxisParam(a,n.shape)[0],u=N.segment_util.collectGatherOpShapeInfo(n,s,l,i),c=y.sizeFromShape(s.shape),p=[],m=ce({inputs:{x:n},backend:t,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),f=ce({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([n,s])||n.dtype==="string"){let b=t.bufferSync(f),_=t.bufferSync(m),w=tR(_,b,d);return p.forEach(v=>t.disposeIntermediateTensorInfo(v)),t.makeTensorInfo(u.outputShape,w.dtype,w.values)}let h=new wC(m.shape,d),g=t.runWebGLProgram(h,[m,f],m.dtype);p.push(g);let x=ce({inputs:{x:g},backend:t,attrs:{shape:u.outputShape}});return p.forEach(b=>t.disposeIntermediateTensorInfo(b)),x}var gO={kernelName:ls,backendName:"webgl",kernelFunc:iZ};var aZ="return float(a > b);",lZ=`
|
|
return vec4(greaterThan(a, b));
|
|
`,uZ=it({opSnippet:aZ,packedOpSnippet:lZ,cpuKernelImpl:rR,dtype:"bool"}),xO={kernelName:ci,backendName:"webgl",kernelFunc:uZ};var cZ="return float(a >= b);",pZ=`
|
|
return vec4(greaterThanEqual(a, b));
|
|
`,mZ=it({opSnippet:cZ,packedOpSnippet:pZ,dtype:"bool"}),yO={kernelName:nn,backendName:"webgl",kernelFunc:mZ};function fZ(r){let{inputs:e,backend:t}=r,{input:o}=e;return Kx(o,!0,t)}var bO={kernelName:ru,backendName:"webgl",kernelFunc:fZ};var dZ="return float(!isnan(x) && !isinf(x));",hZ=ve({opSnippet:dZ,dtype:"bool"}),_O={kernelName:pi,backendName:"webgl",kernelFunc:hZ};var gZ="return float(isinf(x));",xZ=ve({opSnippet:gZ,dtype:"bool"}),wO={kernelName:mi,backendName:"webgl",kernelFunc:xZ};var yZ="return float(isnan(x));",bZ=ve({opSnippet:yZ,dtype:"bool"}),kO={kernelName:fi,backendName:"webgl",kernelFunc:bZ};var _Z="return float(a < b);",wZ=`
|
|
return vec4(lessThan(a, b));
|
|
`,kZ=it({opSnippet:_Z,packedOpSnippet:wZ,cpuKernelImpl:oR,dtype:"bool"}),vO={kernelName:di,backendName:"webgl",kernelFunc:kZ};var vZ="return float(a <= b);",CZ=`
|
|
return vec4(lessThanEqual(a, b));
|
|
`,IZ=it({opSnippet:vZ,packedOpSnippet:CZ,dtype:"bool"}),CO={kernelName:hi,backendName:"webgl",kernelFunc:IZ};function NZ(r){let{backend:e,attrs:t}=r,{start:o,stop:n,num:s}=t,a=nR(o,n,s);return e.makeTensorInfo([a.length],"float32",a)}var IO={kernelName:nu,backendName:"webgl",kernelFunc:NZ};var SZ=`if (x < 0.0) return NAN;
|
|
return log(x);`,TZ=`
|
|
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;
|
|
`,EZ=ve({opSnippet:SZ,packedOpSnippet:TZ,cpuKernelImpl:sR}),NO={kernelName:an,backendName:"webgl",kernelFunc:EZ};var AZ="return log(1.0 + x);",DZ=ve({opSnippet:AZ}),SO={kernelName:gi,backendName:"webgl",kernelFunc:DZ};var $Z="return float(a >= 1.0 && b >= 1.0);",RZ=`
|
|
return vec4(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) *
|
|
vec4(greaterThanEqual(b, vec4(1.0))));
|
|
`,FZ=it({opSnippet:$Z,packedOpSnippet:RZ,dtype:"bool"}),TO={kernelName:xi,backendName:"webgl",kernelFunc:FZ};var OZ="return float(!(x >= 1.0));",PZ=ve({opSnippet:OZ}),EO={kernelName:Za,backendName:"webgl",kernelFunc:PZ};var MZ="return float(a >= 1.0 || b >= 1.0);",LZ=`
|
|
return min(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) +
|
|
vec4(greaterThanEqual(b, vec4(1.0))),
|
|
vec4(1.0));
|
|
`,zZ=it({opSnippet:MZ,packedOpSnippet:LZ,dtype:"bool"}),AO={kernelName:Ja,backendName:"webgl",kernelFunc:zZ};var kC=class{constructor(e,t,o,n,s){this.variableNames=["x"],this.outputShape=[];let a=t,i=e[3]-1;this.outputShape=e;let l,u=`float(${o}) + float(${n}) * 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 vC=class{constructor(e,t,o,n,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(${o}) + float(${n}) * 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 BZ=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{depthRadius:s,bias:a,alpha:i,beta:l}=o,u=G().getBool("WEBGL_PACK_NORMALIZATION")?new vC(n.shape,s,a,i,l):new kC(n.shape,s,a,i,l);return t.runWebGLProgram(u,[n],n.dtype)},DO={kernelName:ca,backendName:"webgl",kernelFunc:BZ};var CC=class{constructor(e,t,o,n,s){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=o,this.alpha=n,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(${n}) * norm + float(${o});
|
|
|
|
for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
|
|
if (k < depthBegin){
|
|
continue;
|
|
}
|
|
else if (k >= depthBegin && k < depthEnd){
|
|
float dyi = -2.0 * float(${n})
|
|
* float(${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 VZ=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n,y:s,dy:a}=e,{depthRadius:i,bias:l,alpha:u,beta:c}=o,p=new CC(n.shape,i,l,u,c);return t.runWebGLProgram(p,[n,s,a],n.dtype)},$O={kernelName:su,backendName:"webgl",kernelFunc:VZ};function RO(r,e,t,o){let n=y.sizeFromShape(e),a=y.sizeFromShape(r.shape)/n,i=ce({inputs:{x:r},attrs:{shape:[a,n]},backend:o}),l=Io(i,r.dtype,"max",o),u=ce({inputs:{x:l},attrs:{shape:t},backend:o});return o.disposeIntermediateTensorInfo(i),o.disposeIntermediateTensorInfo(l),u}function IC(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{reductionIndices:s,keepDims:a}=o,i=n.shape.length,l=y.parseAxisParam(s,n.shape),u=l,c=N.getAxesPermutation(u,i),p=c!=null,m=t.shouldExecuteOnCPU([n]),f=n;if(p){if(m){let _=t.texData.get(f.dataId).values,w=new Array(i);for(let A=0;A<w.length;A++)w[A]=n.shape[c[A]];let v=Up(_,n.shape,n.dtype,c,w);f=t.makeTensorInfo(w,n.dtype);let $=t.texData.get(f.dataId);$.values=v}else f=Al(n,c,t);u=N.getInnerMostAxes(u.length,i)}N.assertAxesAreInnerMostDims("max",u,i);let[d,h]=N.computeOutAndReduceShapes(f.shape,u),g=d;a&&(g=N.expandShapeToKeepDim(d,l));let x;if(m){let _=t.texData.get(f.dataId).values,w=iR(_,y.sizeFromShape(h),g,n.dtype);x=t.makeTensorInfo(g,n.dtype);let v=t.texData.get(x.dataId);v.values=w}else x=RO(f,h,g,t);return p&&t.disposeIntermediateTensorInfo(f),x}var FO={kernelName:ln,backendName:"webgl",kernelFunc:IC};var GZ=Px+`
|
|
return max(a, b);
|
|
`,WZ=`
|
|
vec4 result = vec4(max(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+Tl+`
|
|
return result;
|
|
`,UZ=it({opSnippet:GZ,packedOpSnippet:WZ,cpuKernelImpl:aR}),OO={kernelName:un,backendName:"webgl",kernelFunc:UZ};function jZ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e;Yi(n,"maxPool");let{filterSize:s,strides:a,pad:i,dimRoundingMode:l}=o,u=1;y.assert(N.eitherStridesOrDilationsAreOne(a,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let c=N.computePool2DInfo(n.shape,s,a,u,i,l);if(c.filterWidth===1&&c.filterHeight===1&&y.arraysEqual(c.inShape,c.outShape))return jt({inputs:{x:n},backend:t});let p=new Zi(c,"max",!1);return t.runWebGLProgram(p,[n],n.dtype)}var PO={kernelName:cn,backendName:"webgl",kernelFunc:jZ};function HZ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{filterSize:s,strides:a,pad:i,dataFormat:l,dimRoundingMode:u}=o,c=[1,1,1],p=N.computePool3DInfo(n.shape,s,a,c,i,u,l),m=new cc(p,"max",!1);return t.runWebGLProgram(m,[n],n.dtype)}var MO={kernelName:pa,backendName:"webgl",kernelFunc:HZ};var NC=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,o=e.strideWidth,n=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 += ${n}) {
|
|
float dyR = float(dyRCorner + wR) / ${t}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${a}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${o}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
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);
|
|
}
|
|
`}},SC=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,o=e.strideHeight,n=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) / ${o}.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) / ${n}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
|
|
int maxPosValue = ${d} -
|
|
int(getMaxPos(batch, idyD, idyR, idyC, ch));
|
|
|
|
// Get the current value, check it against the value from the
|
|
// position matrix.
|
|
int curPosValue =
|
|
wD * ${u} * ${c} +
|
|
wR * ${c} + wC;
|
|
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
|
|
|
dotProd += dyValue * mask;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function qZ(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,a=s,{filterSize:i,strides:l,pad:u,dimRoundingMode:c}=o,p=[1,1,1],m=N.computePool3DInfo(a.shape,i,l,p,u,c),f=new cc(m,"max",!0),d=t.runWebGLProgram(f,[a],a.dtype),h=new SC(m),g=t.runWebGLProgram(h,[n,d],a.dtype);return t.disposeIntermediateTensorInfo(d),g}var LO={kernelName:au,backendName:"webgl",kernelFunc:qZ};function KZ(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s,output:a}=e,i=s;Yi([s,a],"maxPoolGrad");let{filterSize:l,strides:u,pad:c,dimRoundingMode:p}=o,m=N.computePool2DInfo(i.shape,l,u,1,c,p),f=!0,d=new Zi(m,"max",f),h=t.runWebGLProgram(d,[i],i.dtype),g=new NC(m),x=t.runWebGLProgram(g,[n,h],i.dtype);return t.disposeIntermediateTensorInfo(h),x}var zO={kernelName:iu,backendName:"webgl",kernelFunc:KZ};function BO(r,e,t,o){let n=new Zi(t,"max",!1),s=o.runWebGLProgram(n,[r],"float32");n=new Zi(t,"max",!0,!0,e);let a=o.runWebGLProgram(n,[r],"float32");return[s,a]}var VO={kernelName:lu,backendName:"webgl",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{x:o}=r,{filterSize:n,strides:s,pad:a,includeBatchInIndex:i}=e,l=t;y.assert(o.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${o.shape.length}.`);let u=[1,1];y.assert(N.eitherStridesOrDilationsAreOne(s,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${u}'`);let c=N.computePool2DInfo(o.shape,n,s,u,a),[p,m]=BO(o,i,c,l);return[p,m]}};function GO(r,e,t,o){let n=y.sizeFromShape(e),a=y.sizeFromShape(r.shape)/n,i=ce({inputs:{x:r},attrs:{shape:[a,n]},backend:o}),l=Io(i,"float32","mean",o),u=ce({inputs:{x:l},attrs:{shape:t},backend:o});return o.disposeIntermediateTensorInfo(i),o.disposeIntermediateTensorInfo(l),u}var WO={kernelName:pn,backendName:"webgl",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{x:o}=r,{keepDims:n,axis:s}=e,a=t,i=o.shape.length,l=y.parseAxisParam(s,o.shape),u=l,c=N.getAxesPermutation(u,i),p=c!=null,m=a.shouldExecuteOnCPU([o]),f=[],d=o;if(p){if(m){let w=a.texData.get(d.dataId).values,v=new Array(i);for(let R=0;R<v.length;R++)v[R]=o.shape[c[R]];let $=Up(w,o.shape,o.dtype,c,v);d=a.makeTensorInfo(v,o.dtype);let A=a.texData.get(d.dataId);A.values=$}else d=Al(o,c,a);f.push(d),u=N.getInnerMostAxes(u.length,i)}N.assertAxesAreInnerMostDims("sum",u,i);let[h,g]=N.computeOutAndReduceShapes(d.shape,u),x=h;n&&(x=N.expandShapeToKeepDim(h,l));let b=GO(d,g,x,a);for(let _ of f)a.disposeIntermediateTensorInfo(_);return b}};function XZ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o,i=n.shape.length,l=y.parseAxisParam(s,n.shape),u=l,c=N.getAxesPermutation(u,i),p=n;c!=null&&(p=Lt({inputs:{x:n},backend:t,attrs:{perm:c}}),u=N.getInnerMostAxes(u.length,n.shape.length)),N.assertAxesAreInnerMostDims("min",u,i);let[m,f]=N.computeOutAndReduceShapes(p.shape,u),d=y.sizeFromShape(f),h=ce({inputs:{x:p},backend:t,attrs:{shape:[-1,d]}}),g=Io(h,h.dtype,"min",t),x;if(a){let b=N.expandShapeToKeepDim(m,l);x=ce({inputs:{x:g},backend:t,attrs:{shape:b}})}else x=ce({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),c!=null&&t.disposeIntermediateTensorInfo(p),x}var UO={kernelName:mn,backendName:"webgl",kernelFunc:XZ};var YZ=Px+`
|
|
return min(a, b);
|
|
`,ZZ=`
|
|
vec4 result = vec4(min(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+Tl+`
|
|
return result;
|
|
`,JZ=it({opSnippet:YZ,packedOpSnippet:ZZ,cpuKernelImpl:lR}),jO={kernelName:fn,backendName:"webgl",kernelFunc:JZ};var TC=class{constructor(e,t,o){this.variableNames=["x"],this.outputShape=t.map((c,p)=>c[0]+e[p]+c[1]);let n=e.length,s=Le(n),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,n),u=o==="reflect"?0:1;if(n===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 < ${n}; 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 EC=class{constructor(e,t,o){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((d,h)=>d[0]+e[h]+d[1]);let n=e.length,s=Le(n),a=t.map(d=>d[0]).join(","),i=t.map((d,h)=>d[0]+e[h]).join(","),l=Ut("rc",n),u=Ut("source",n),c=`${l[n-1]} < ${this.outputShape[n-1]}`,p=n===1?"source":`vec2(${u.slice(-2).join()})`,m=o==="reflect"?0:1,f="";if(n===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[n-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[n-1]} += 1;
|
|
if(${c}) {
|
|
${d}
|
|
result[1] = getChannel(getX(${u.join()}), ${p});
|
|
}
|
|
rc = outputLoc;
|
|
${l[n-2]} += 1;
|
|
if(${l[n-2]} < ${this.outputShape[n-2]}) {
|
|
${d}
|
|
result[2] = getChannel(getX(${u.join()}), ${p});
|
|
${l[n-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 QZ=({inputs:r,backend:e,attrs:t})=>{let{x:o}=r,{paddings:n,mode:s}=t,a=G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new EC(o.shape,n,s):new TC(o.shape,n,s);return e.runWebGLProgram(a,[o],o.dtype)},HO={kernelName:ma,backendName:"webgl",kernelFunc:QZ};var e9=`if (b == 0.0) return NAN;
|
|
return mod(a, b);`,t9=`
|
|
vec4 result = mod(a, b);
|
|
vec4 isNaN = vec4(equal(b, vec4(0.0)));
|
|
`+Tl+`
|
|
return result;
|
|
`,r9=it({opSnippet:e9,packedOpSnippet:t9}),qO={kernelName:yi,backendName:"webgl",kernelFunc:r9};var AC=class{constructor(e,t,o){this.variableNames=["probs"],this.outputShape=[e,o],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,o)=>{this.seedLoc==null&&(this.seedLoc=t.getUniformLocation(o,"seed")),t.gl.uniform1f(this.seedLoc,e)}}};var o9=`
|
|
if (a == b) {
|
|
return 1.0;
|
|
};
|
|
return a / b;`,n9=`
|
|
// 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;
|
|
`,DC=it({opSnippet:o9,packedOpSnippet:n9,checkOutOfBounds:!0}),KO={kernelName:Qo,backendName:"webgl",kernelFunc:DC};var XO="return a - b;",$C=it({opSnippet:XO,packedOpSnippet:XO,supportsComplex:!0,cpuKernelImpl:gR}),YO={kernelName:Dn,backendName:"webgl",kernelFunc:$C};function RC(r){let{inputs:e,backend:t,attrs:o}=r,{logits:n}=e,{dim:s}=o,a=y.parseAxisParam([s],n.shape),i=IC({inputs:{x:n},backend:t,attrs:{reductionIndices:a,keepDims:!1}}),l=N.expandShapeToKeepDim(i.shape,a),u=ce({inputs:{x:i},backend:t,attrs:{shape:l}}),c=$C({inputs:{a:n,b:u},backend:t}),p=hC({inputs:{x:c},backend:t}),m=ah({inputs:{x:p},backend:t,attrs:{axis:a,keepDims:!1}}),f=ce({inputs:{x:m},backend:t,attrs:{shape:l}}),d=DC({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 ZO={kernelName:En,backendName:"webgl",kernelFunc:RC};function s9(r){let{inputs:e,backend:t,attrs:o}=r,{logits:n}=e,{numSamples:s,seed:a,normalized:i}=o,l=i?n:RC({inputs:{logits:n},backend:t,attrs:{dim:n.shape.length-1}}),u=l.shape[0],c=l.shape[1],p=new AC(u,c,s),m=p.getCustomSetupFunc(a),f=t.runWebGLProgram(p,[l],"int32",m);return i||t.disposeIntermediateTensorInfo(l),f}var JO={kernelName:uu,backendName:"webgl",kernelFunc:s9};var QO="return -x;";function i9(r){let{inputs:e,backend:t}=r,{x:o}=e;if(t.shouldExecuteOnCPU([o])){let s=t.texData.get(o.dataId),[a,i]=cR(s.values,o.shape,o.dtype);return t.makeTensorInfo(i,o.dtype,a)}let n;return G().getBool("WEBGL_PACK_UNARY_OPERATIONS")?n=new Bs(o.shape,QO):n=new uo(o.shape,QO),t.runWebGLProgram(n,[o],o.dtype)}var eP={kernelName:cs,backendName:"webgl",kernelFunc:i9};var a9=Sr.nonMaxSuppressionV3Impl;function l9(r){N.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:e,backend:t,attrs:o}=r,{boxes:n,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:l}=o,u=t.readSync(n.dataId),c=t.readSync(s.dataId),{selectedIndices:p}=a9(u,c,a,i,l);return t.makeTensorInfo([p.length],"int32",new Int32Array(p))}var tP={kernelName:_i,backendName:"webgl",kernelFunc:l9};var u9=Sr.nonMaxSuppressionV4Impl;function c9(r){N.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:e,backend:t,attrs:o}=r,{boxes:n,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:l,padToMaxOutputSize:u}=o,c=t.readSync(n.dataId),p=t.readSync(s.dataId),{selectedIndices:m,validOutputs:f}=u9(c,p,a,i,l,u);return[t.makeTensorInfo([m.length],"int32",new Int32Array(m)),t.makeTensorInfo([],"int32",new Int32Array([f]))]}var rP={kernelName:wi,backendName:"webgl",kernelFunc:c9};var p9=Sr.nonMaxSuppressionV5Impl;function m9(r){N.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:e,backend:t,attrs:o}=r,{boxes:n,scores:s}=e,{maxOutputSize:a,iouThreshold:i,scoreThreshold:l,softNmsSigma:u}=o,c=t.readSync(n.dataId),p=t.readSync(s.dataId),m=a,f=i,d=l,h=u,{selectedIndices:g,selectedScores:x}=p9(c,p,m,f,d,h);return[t.makeTensorInfo([g.length],"int32",new Int32Array(g)),t.makeTensorInfo([x.length],"float32",new Float32Array(x))]}var oP={kernelName:ki,backendName:"webgl",kernelFunc:m9};var FC=class{constructor(e,t,o,n){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int index = round(getIndices(coords.x));
|
|
setOutput(mix(float(${n}), float(${o}),
|
|
float(index == coords.y)));
|
|
}
|
|
`}};var f9=r=>{let{inputs:e,backend:t,attrs:o}=r,{indices:n}=e,{depth:s,onValue:a,offValue:i}=o,l=y.sizeFromShape(n.shape),u=new FC(l,s,a,i),c=ce({inputs:{x:n},backend:t,attrs:{shape:[l]}}),p=t.runWebGLProgram(u,[c],n.dtype);t.disposeIntermediateTensorInfo(c);let m=[...n.shape,s],f=ce({inputs:{x:p},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(p),f},nP={kernelName:hn,backendName:"webgl",kernelFunc:f9};function mh(r){let{inputs:e,backend:t}=r,{x:o}=e;if(o.dtype==="complex64"){let n=ja({inputs:{input:o},backend:t}),s=mh({inputs:{x:n},backend:t}),a=pc({inputs:{input:o},backend:t}),i=mh({inputs:{x:a},backend:t}),l=co({inputs:{real:s,imag:i},backend:t});return t.disposeIntermediateTensorInfo(n),t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),l}else return ph({attrs:{shape:o.shape,dtype:o.dtype,value:o.dtype==="string"?"":0},backend:t})}var sP={kernelName:ys,backendName:"webgl",kernelFunc:mh};function iP(r){let{inputs:e,backend:t}=r,{x:o}=e;if(o.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(o.dtype==="complex64"){let n=ja({inputs:{input:o},backend:t}),s=iP({inputs:{x:n},backend:t}),a=pc({inputs:{input:o},backend:t}),i=mh({inputs:{x:a},backend:t}),l=co({inputs:{real:s,imag:i},backend:t});return t.disposeIntermediateTensorInfo(n),t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),l}else return ph({attrs:{shape:o.shape,dtype:o.dtype,value:1},backend:t})}var aP={kernelName:ps,backendName:"webgl",kernelFunc:iP};function d9(r){let{inputs:e,backend:t,attrs:o}=r,{axis:n}=o;if(e.length===1)return Hx({inputs:{input:e[0]},backend:t,attrs:{dim:n}});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=Hx({inputs:{input:c},backend:t,attrs:{dim:n}});return i.push(p),p}),u=rC({inputs:l,backend:t,attrs:{axis:n}});return i.forEach(c=>t.disposeIntermediateTensorInfo(c)),u}var lP={kernelName:ms,backendName:"webgl",kernelFunc:d9};var OC=class{constructor(e,t,o){this.variableNames=["x"],this.outputShape=t.map((u,c)=>u[0]+e[c]+u[1]);let n=e.length,s=Le(n),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,n);if(n===1){this.userCode=`
|
|
int start = ${a};
|
|
int end = ${i};
|
|
|
|
void main() {
|
|
int outC = getOutputCoords();
|
|
if (outC < start || outC >= end) {
|
|
setOutput(float(${o}));
|
|
} else {
|
|
setOutput(getX(outC - start));
|
|
}
|
|
}
|
|
`;return}this.userCode=`
|
|
${s} start = ${s}(${a});
|
|
${s} end = ${s}(${i});
|
|
|
|
void main() {
|
|
${s} outC = getOutputCoords();
|
|
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
|
|
setOutput(float(${o}));
|
|
} else {
|
|
${s} coords = outC - start;
|
|
setOutput(getX(${l}));
|
|
}
|
|
}
|
|
`}};var PC=class{constructor(e,t,o){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((h,g)=>h[0]+e[g]+h[1]);let n=e.length,s=Le(n),a=t.map(h=>h[0]).join(","),i=t.map((h,g)=>h[0]+e[g]).join(","),l=Ut("rc",n),u=Ut("source",n),c=`${l[n-1]} < ${this.outputShape[n-1]}`,p=n===1?"source":`vec2(${u.slice(-2).join()})`,m=[`${s} rc = outputLoc;`,`${l[n-1]} += 1;
|
|
if(${c}) {
|
|
`,n===1?"":`}
|
|
rc = outputLoc;
|
|
${l[n-2]} += 1;
|
|
if(${l[n-2]} < ${this.outputShape[n-2]}) {`,n===1?"":` ${l[n-1]} += 1;
|
|
if(${c}) {`],f=n===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",d="";for(let h=0,g=n===1?2:4;h<g;h++)d+=`
|
|
${m[h]}
|
|
if (${f}) {
|
|
result[${h}] = float(${o});
|
|
} else {
|
|
${s} source = rc - start;
|
|
result[${h}] = getChannel(getX(${u.join()}), ${p});
|
|
}
|
|
`;d+=n===1?"} ":"}}",this.userCode=`
|
|
const ${s} start = ${s}(${a});
|
|
const ${s} end = ${s}(${i});
|
|
|
|
void main() {
|
|
${s} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${d}
|
|
setOutput(result);
|
|
}
|
|
`}};var MC=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{paddings:s,constantValue:a}=o,i=G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new PC(n.shape,s,a):new OC(n.shape,s,a);return t.runWebGLProgram(i,[n],n.dtype)},uP={kernelName:gn,backendName:"webgl",kernelFunc:MC};var h9=`
|
|
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);
|
|
`,g9=`
|
|
// 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));
|
|
`+Tl+`
|
|
return result;
|
|
`,x9=it({opSnippet:h9,packedOpSnippet:g9}),cP={kernelName:xn,backendName:"webgl",kernelFunc:x9};function y9(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o,i=n.shape.length,l=[],u=y.parseAxisParam(s,n.shape),c=u,p=N.getAxesPermutation(c,i),m=n;p!=null&&(m=Lt({inputs:{x:n},backend:t,attrs:{perm:p}}),c=N.getInnerMostAxes(c.length,i),l.push(m)),N.assertAxesAreInnerMostDims("prod",c,i);let f;if(t.shouldExecuteOnCPU([m])){let d=t.texData.get(m.dataId).values,{outVals:h,outShape:g,outDtype:x}=pR(m.shape,m.dtype,d,c);f=t.makeTensorInfo(g,x,h)}else{let[d,h]=N.computeOutAndReduceShapes(m.shape,c),g=y.sizeFromShape(h),x=ce({inputs:{x:m},backend:t,attrs:{shape:[-1,g]}}),b=hu(n.dtype),_=Io(x,b,"prod",t);f=ce({inputs:{x:_},backend:t,attrs:{shape:d}}),l.push(x),l.push(_)}if(a){l.push(f);let d=N.expandShapeToKeepDim(f.shape,u);f=ce({inputs:{x:f},backend:t,attrs:{shape:d}})}return l.forEach(d=>t.disposeIntermediateTensorInfo(d)),f}var pP={kernelName:vi,backendName:"webgl",kernelFunc:y9};var LC=r=>{let{backend:e,attrs:t}=r,{start:o,stop:n,step:s,dtype:a}=t,i=mR(o,n,s,a);return e.makeTensorInfo([i.length],a,i)},mP={kernelName:fa,backendName:"webgl",kernelFunc:LC};var b9="return 1.0 / x;",_9=ve({opSnippet:b9}),fP={kernelName:Ci,backendName:"webgl",kernelFunc:_9};var w9=gr+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,k9=`
|
|
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;
|
|
`,v9=ve({opSnippet:w9,packedOpSnippet:k9}),dP={kernelName:bn,backendName:"webgl",kernelFunc:v9};var C9=gr+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,I9=`
|
|
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;
|
|
`,N9=ve({opSnippet:C9,packedOpSnippet:I9}),hP={kernelName:wn,backendName:"webgl",kernelFunc:N9};var zC=class{constructor(e,t,o,n,s){this.variableNames=["A"],this.outputShape=[];let[a,i,l,u]=e;this.outputShape=[a,t,o,u];let c=[n&&t>1?i-1:i,n&&o>1?l-1:l],p=[n&&t>1?t-1:t,n&&o>1?o-1:o],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 BC=class{constructor(e,t,o,n,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,i,l,u]=e;this.outputShape=[a,t,o,u];let c=[n&&t>1?i-1:i,n&&o>1?l-1:l],p=[n&&t>1?t-1:t,n&&o>1?o-1:o],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 < ${o-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 S9(r){let{inputs:e,backend:t,attrs:o}=r,{images:n}=e,{alignCorners:s,halfPixelCenters:a,size:i}=o,[l,u]=i,c=G().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new BC(n.shape,l,u,s,a):new zC(n.shape,l,u,s,a);return t.runWebGLProgram(c,[n],"float32")}var gP={kernelName:_n,backendName:"webgl",kernelFunc:S9};var VC=class{constructor(e,t,o){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,n,s]=t,[,a,i]=e,l=[o&&a>1?n-1:n,o&&i>1?s-1:s],u=[o&&a>1?a-1:a,o&&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), ${n-1}.0));
|
|
float dxRLerp = dxR - float(topDxRIndex);
|
|
float inverseDxRLerp = 1.0 - dxRLerp;
|
|
|
|
float dxC = float(dyC) * widthScale;
|
|
int leftDxCIndex = int(floor(dxC));
|
|
int rightDxCIndex = int(min(ceil(dxC), ${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 T9(r){let{inputs:e,backend:t,attrs:o}=r,{images:n,dy:s}=e,{alignCorners:a}=o,i=new VC(s.shape,n.shape,a);return t.runWebGLProgram(i,[s],s.dtype)}var xP={kernelName:mu,backendName:"webgl",kernelFunc:T9};var GC=class{constructor(e,t,o,n,s){this.variableNames=["A"],this.outputShape=[];let[a,i,l,u]=e;this.outputShape=[a,t,o,u];let c=[n&&t>1?i-1:i,n&&o>1?l-1:l],p=[n&&t>1?t-1:t,n&&o>1?o-1:o],m=n?"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);
|
|
}
|
|
`}};function E9(r){let{inputs:e,backend:t,attrs:o}=r,{images:n}=e,{alignCorners:s,halfPixelCenters:a,size:i}=o,[l,u]=i,c=new GC(n.shape,l,u,s,a);return t.runWebGLProgram(c,[n],n.dtype)}var yP={kernelName:da,backendName:"webgl",kernelFunc:E9};var WC=class{constructor(e,t,o){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,n,s]=t,[,a,i]=e,l=[o&&a>1?n-1:n,o&&i>1?s-1:s],u=[o&&a>1?a-1:a,o&&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(${n}) - 1),
|
|
${o} ? float(round(sourceFracRow)) :
|
|
float(floor(sourceFracRow))));
|
|
|
|
int sourceNearestCol = int(min(
|
|
float(int(${s}) - 1),
|
|
${o} ? float(round(sourceFracCol)) :
|
|
float(floor(sourceFracCol))));
|
|
|
|
if (r == sourceNearestRow && c == sourceNearestCol) {
|
|
accumulator += getDy(b, dyR, dyC, d);
|
|
}
|
|
}
|
|
}
|
|
// End loop over dy
|
|
|
|
setOutput(accumulator);
|
|
}
|
|
`}};function A9(r){let{inputs:e,backend:t,attrs:o}=r,{images:n,dy:s}=e,{alignCorners:a}=o,i=new WC(s.shape,n.shape,a);return t.runWebGLProgram(i,[s],s.dtype)}var bP={kernelName:pu,backendName:"webgl",kernelFunc:A9};var UC=class{constructor(e,t){this.variableNames=["x"];let o=e.length;if(o>4)throw new Error(`WebGL backend: Reverse of rank-${o} tensor is not yet supported`);if(this.outputShape=e,o===1){this.userCode=`
|
|
void main() {
|
|
int coord = getOutputCoords();
|
|
setOutput(getX(${e[0]} - coord - 1));
|
|
}
|
|
`;return}let n=i=>t.indexOf(i)!==-1&&e[i]!==1?`${e[i]} - coords[${i}] - 1`:`coords[${i}]`,s=e.map((i,l)=>n(l)).join(","),a=Le(o);this.userCode=`
|
|
void main() {
|
|
${a} coords = getOutputCoords();
|
|
setOutput(getX(${s}));
|
|
}
|
|
`}};var jC=class{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;let o=e.length;if(o>4)throw new Error(`WebGL backend: Reverse of rank-${o} tensor is not yet supported`);this.outputShape=e;let n=Ut("rc",o),s=`${n[o-1]} + 1 < ${this.outputShape[o-1]}`,a=`${n[o-2]} + 1 < ${this.outputShape[o-2]}`,i=Le(o);o===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(n.slice())};
|
|
if(${s}){
|
|
result.g = ${u(n.slice())};
|
|
}
|
|
if(${a}) {
|
|
result.b = ${c(n.slice())};
|
|
if(${s}) {
|
|
result.a = ${p(n.slice())};
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`;function l(d){return m(d)}function u(d){return d[o-1]="("+d[o-1]+" + 1)",m(d)}function c(d){return d[o-2]="("+d[o-2]+" + 1)",m(d)}function p(d){return d[o-1]="("+d[o-1]+" + 1)",d[o-2]="("+d[o-2]+" + 1)",m(d)}function m(d){let h=e.map((b,_)=>f(_,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 D9(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{dims:s}=o,a=n.shape.length,i=y.parseAxisParam(s,n.shape);if(a===0)return jt({inputs:{x:n},backend:t});let l=G().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new jC(n.shape,i):new UC(n.shape,i);return t.runWebGLProgram(l,[n],n.dtype)}var _P={kernelName:kn,backendName:"webgl",kernelFunc:D9};var HC=class{constructor(e,t,o,n){this.variableNames=["Image"],this.outputShape=[];let s=e[1],a=e[2],i=Math.sin(t).toFixed(3),l=Math.cos(t).toFixed(3);this.outputShape=e;let[u,c]=N.getImageCenter(n,s,a),p=u.toFixed(3),m=c.toFixed(3),f="";typeof o=="number"?f=`float outputValue = ${o.toFixed(2)};`:f=`
|
|
vec3 fill = vec3(${o.join(",")});
|
|
float outputValue = fill[coords[3]];`,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int x = coords[2];
|
|
int y = coords[1];
|
|
float coordXFloat = (float(x) - ${p}) * ${l} - (float(y) - ${m}) * ${i};
|
|
float coordYFloat = (float(x) - ${p}) * ${i} + (float(y) - ${m}) * ${l};
|
|
int coordX = int(round(coordXFloat + ${p}));
|
|
int coordY = int(round(coordYFloat + ${m}));
|
|
${f}
|
|
if(coordX >= 0 && coordX < ${a} && coordY >= 0 && coordY < ${s}) {
|
|
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
|
|
}
|
|
setOutput(outputValue);
|
|
}
|
|
`}};var wP={kernelName:Ri,backendName:"webgl",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{image:o}=r,{radians:n,fillValue:s,center:a}=e,i=t,l=new HC(o.shape,n,s,a);return i.runWebGLProgram(l,[o],o.dtype)}};var $9=`
|
|
// 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;
|
|
}
|
|
}
|
|
`,R9=ve({opSnippet:$9}),kP={kernelName:vn,backendName:"webgl",kernelFunc:R9};var F9="return inversesqrt(x);",O9=ve({opSnippet:F9,cpuKernelImpl:fR}),vP={kernelName:Cn,backendName:"webgl",kernelFunc:O9};var fh=class{constructor(e,t,o,n,s,a,i=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;let l=Le(s.length),u=Le(a.length),c="";o===1?c="i":o===2&&(c="i, j");let p=`getIndices(${c})`,m="";n===1?m="i":n===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 P9(r){let{inputs:e,backend:t,attrs:o}=r,{indices:n,updates:s}=e,{shape:a}=o,{sliceRank:i,numUpdates:l,sliceSize:u,strides:c,outputSize:p}=N.calculateShapes(s,n,a),m=[p/u,u];if(p===0)return t.makeTensorInfo(a,n.dtype);let f=ce({inputs:{x:n},backend:t,attrs:{shape:[l,i]}}),d=ce({inputs:{x:s},backend:t,attrs:{shape:[l,u]}}),h=t.makeTensorInfo([],"float32",new Float32Array([0])),g=new fh(l,i,f.shape.length,d.shape.length,c,m),x=t.runWebGLProgram(g,[d,f,h],d.dtype),b=ce({inputs:{x},backend:t,attrs:{shape:a}});return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(x),t.disposeIntermediateTensorInfo(h),b}var CP={kernelName:Ii,backendName:"webgl",kernelFunc:P9};var qC=class{constructor(e,t,o){this.variableNames=["c","a","b"],this.outputShape=t;let n,s;if(o>4)throw Error(`Where for rank ${o} is not yet supported`);if(o===1)s="resRC",n="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]}`);n=l.join(),s=u.join()}let a=Le(o);this.userCode=`
|
|
void main() {
|
|
${a} resRC = getOutputCoords();
|
|
float cVal = getC(${n});
|
|
if (cVal >= 1.0) {
|
|
setOutput(getA(${s}));
|
|
} else {
|
|
setOutput(getB(${s}));
|
|
}
|
|
}
|
|
`}};function M9(r){let{inputs:e,backend:t}=r,{condition:o,t:n,e:s}=e,a=new qC(o.shape.length,n.shape,n.shape.length);return t.runWebGLProgram(a,[o,n,s],mr(n.dtype,s.dtype))}var IP={kernelName:ds,backendName:"webgl",kernelFunc:M9};var L9=`
|
|
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
|
|
// see: https://arxiv.org/abs/1706.02515
|
|
float scaleAlpha = ${N.SELU_SCALEALPHA};
|
|
float scale = ${N.SELU_SCALE};
|
|
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
|
|
`,z9=ve({opSnippet:L9}),NP={kernelName:Ni,backendName:"webgl",kernelFunc:z9};var B9="return 1.0 / (1.0 + exp(-1.0 * x));",V9=ve({opSnippet:B9}),SP={kernelName:Nn,backendName:"webgl",kernelFunc:V9};var G9=`
|
|
if (isnan(x)) { return 0.0; }
|
|
return sign(x);
|
|
`,W9=ve({opSnippet:G9}),TP={kernelName:Ti,backendName:"webgl",kernelFunc:W9};var U9=Mx+`
|
|
return sin(x);
|
|
`,j9=ve({opSnippet:U9}),EP={kernelName:In,backendName:"webgl",kernelFunc:j9};var H9=`
|
|
float e2x = exp(x);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`,q9=ve({opSnippet:H9}),AP={kernelName:Si,backendName:"webgl",kernelFunc:q9};var K9=`
|
|
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;
|
|
`,X9=ve({opSnippet:K9}),DP={kernelName:Ei,backendName:"webgl",kernelFunc:X9};var Y9=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockShape:s,paddings:a}=o;y.assert(n.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<n.shape.length;++x)l.push([0,0]);let u=[],c=MC({inputs:{x:n},backend:t,attrs:{paddings:l,constantValue:0}}),p=N.getReshaped(c.shape,s,i,!1),m=N.getPermuted(p.length,s.length,!1),f=N.getReshapedPermuted(c.shape,s,i,!1),d=ce({inputs:{x:c},backend:t,attrs:{shape:p}}),h=Lt({inputs:{x:d},backend:t,attrs:{perm:m}}),g=ce({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},$P={kernelName:ha,backendName:"webgl",kernelFunc:Y9};function Z9(r){let{inputs:e,backend:t,attrs:o}=r,{sparseIndices:n,sparseValues:s,defaultValue:a}=e,{outputShape:i}=o,{sliceRank:l,numUpdates:u,strides:c,outputSize:p}=N.calculateShapes(s,n,i),m=!1,f=new fh(u,l,n.shape.length,s.shape.length,c,[p,1],m),d=t.runWebGLProgram(f,[s,n,a],s.dtype),h=ce({inputs:{x:d},backend:t,attrs:{shape:i}});return t.disposeIntermediateTensorInfo(d),h}var RP={kernelName:fu,backendName:"webgl",kernelFunc:Z9};function J9(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{numOrSizeSplits:s,axis:a}=o,i=y.parseAxisParam(a,n.shape)[0],l=N.prepareSplitSize(n,s,i),u=n.shape.length,c=new Array(u).fill(0),p=n.shape.slice();return l.map(m=>{let f=[...p];f[i]=m;let d=Ua({inputs:{x:n},backend:t,attrs:{begin:c,size:f}});return c[i]+=m,d})}var FP={kernelName:gs,backendName:"webgl",kernelFunc:J9};var Q9="return sqrt(x);",eJ=ve({opSnippet:Q9}),OP={kernelName:Sn,backendName:"webgl",kernelFunc:eJ};var tJ="return x * x;",rJ=ve({opSnippet:tJ}),PP={kernelName:ga,backendName:"webgl",kernelFunc:rJ};var MP="return (a - b) * (a - b);",oJ=it({opSnippet:MP,packedOpSnippet:MP}),LP={kernelName:An,backendName:"webgl",kernelFunc:oJ};function nJ({inputs:r,attrs:e,backend:t}){let{x:o}=r,n=gr+`
|
|
return x > 0.0 ? 1.0 : float(${e.alpha});
|
|
`,s=new uo(o.shape,n);return t.runWebGLProgram(s,[o],o.dtype)}var zP={kernelName:Do,backendName:"webgl",kernelFunc:nJ};var KC=class{constructor(e,t,o){this.variableNames=["x"],this.outputShape=o;let n=o.length,s=Le(o.length),a=Le(o.length),i="";if(n===1)i="coords * strides + begin";else{let l=0;i=o.map((u,c)=>(l++,o.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 sJ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{begin:s,end:a,strides:i,beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:m}=o,{nonStrided:f,$begin:d,$strides:h,size:g,newShape:x,outShape:b}=or.sliceInfo(n.shape,s,a,i,l,u,c,p,m),_=ce({inputs:{x:n},backend:t,attrs:{shape:x}}),w;if(f){let $=Ua({inputs:{x:_},backend:t,attrs:{begin:d,size:g}});w=ce({inputs:{x:$},backend:t,attrs:{shape:b}}),t.disposeIntermediateTensorInfo($)}else if(b.some($=>$===0))w=t.makeTensorInfo(b,n.dtype,[]);else if(t.shouldExecuteOnCPU([_])){let R=t.texData.get(_.dataId).values,M=Ce(_.shape,_.dtype,R),z=hR(b,M,h,d);w=t.makeTensorInfo(b,_.dtype,z.values)}else{let A=new KC(d,h,b);w=t.runWebGLProgram(A,[_],_.dtype)}let v=ce({inputs:{x:w},backend:t,attrs:{shape:b}});return t.disposeIntermediateTensorInfo(_),t.disposeIntermediateTensorInfo(w),v}var BP={kernelName:Ai,backendName:"webgl",kernelFunc:sJ};var iJ="return tan(x);",aJ=ve({opSnippet:iJ}),VP={kernelName:Di,backendName:"webgl",kernelFunc:aJ};var lJ=`
|
|
float e2x = exp(-2.0 * abs(x));
|
|
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
|
|
`,uJ=ve({opSnippet:lJ}),GP={kernelName:$n,backendName:"webgl",kernelFunc:uJ};var XC=class{constructor(e,t){this.variableNames=["A"];let o=new Array(e.length);for(let a=0;a<o.length;a++)o[a]=e[a]*t[a];this.outputShape=o,this.rank=o.length;let n=Le(this.rank),s=cJ(e);this.userCode=`
|
|
void main() {
|
|
${n} resRC = getOutputCoords();
|
|
setOutput(getA(${s}));
|
|
}
|
|
`}};function cJ(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"],o=[];for(let n=0;n<r.length;n++)o.push(`imod(${t[n]}, ${r[n]})`);return o.join()}function YC(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{reps:s}=o;if(n.dtype==="string"){let u=t.readSync(n.dataId).map(m=>y.decodeString(m)),c=Ce(n.shape,n.dtype,u),p=xR(c,s);return t.makeTensorInfo(p.shape,p.dtype,p.values)}let a=new XC(n.shape,s);return t.runWebGLProgram(a,[n],n.dtype)}var WP={kernelName:yo,backendName:"webgl",kernelFunc:YC};function pJ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{k:s,sorted:a}=o,i=t.readSync(n.dataId),[l,u]=yR(i,n.shape,n.dtype,s,a);return[t.makeTensorInfo(l.shape,l.dtype,l.values),t.makeTensorInfo(u.shape,u.dtype,u.values)]}var UP={kernelName:$i,backendName:"webgl",kernelFunc:pJ};function mJ(r){let{inputs:e,attrs:t,backend:o}=r,{axis:n}=t,{x:s}=e;Yi(s,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let a=o.readSync(s.dataId),{outputValues:i,outputShape:l,indices:u}=bR(a,n,s.shape,s.dtype);return[o.makeTensorInfo(l,s.dtype,i),o.makeTensorInfo([u.length],"int32",u)]}var jP={kernelName:du,backendName:"webgl",kernelFunc:mJ};function fJ(r){let{inputs:e,backend:t,attrs:o}=r,{value:n}=e,{axis:s}=o;s<0&&(s+=n.shape.length);let a=n,i=a.shape.length,l=n.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=Ua({inputs:{x:a},backend:t,attrs:{begin:m,size:f}}),x=ce({inputs:{x:g},backend:t,attrs:{shape:u}});d[h]=x,p.push(g)}return p.forEach(h=>t.disposeIntermediateTensorInfo(h)),d}var HP={kernelName:xs,backendName:"webgl",kernelFunc:fJ};var ZC=class{constructor(e,t){this.variableNames=["x","segmentIds"];let o=e.windowSize,n=e.batchSize,s=e.inSize,a=e.numSegments,i=a*Math.ceil(s/o);this.outputShape=[n,i];let l="0.0",u="sumValue",c=Math.floor(o/4)*4,p=o%4,m=`
|
|
sumValue += dot(values, segFilter);
|
|
`,f="";s%o>0&&(f=`
|
|
if (inIdx < 0 || inIdx >= ${s}) {
|
|
return initializationValue;
|
|
}
|
|
`);let d="";s%o>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(${o}));
|
|
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 dJ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,segmentIds:s}=e,{numSegments:a}=o,i=n.shape.length,l=[],u=0,c=N.getAxesPermutation([u],i),p=n;c!=null&&(p=Lt({inputs:{x:n},backend:t,attrs:{perm:c}}),l.push(p),u=N.getInnerMostAxes(1,i)[0]);let m=N.segment_util.computeOutShape(p.shape,u,a),f=y.sizeFromShape([p.shape[u]]),d=ce({inputs:{x:p},backend:t,attrs:{shape:[-1,f]}});l.push(d);let h=hu(n.dtype),g=(w,v,$,A,R)=>{let M=w.shape[0],z=w.shape[1],W=N.segment_util.segOpComputeOptimalWindowSize(z,R),U={windowSize:W,inSize:z,batchSize:M,numSegments:R},q=new ZC(U,v),Z=t.compileAndRun(q,[w,$],A);if(l.push(Z),Z.shape[1]===R)return Z;let X=LC({backend:t,attrs:{start:0,stop:R,step:1,dtype:"float32"}}),Y=YC({inputs:{x:X},backend:t,attrs:{reps:[z/W]}});return l.push(X),l.push(Y),g(Z,v,Y,A,R)},x=g(d,"unsortedSegmentSum",s,h,a),b=ce({inputs:{x},backend:t,attrs:{shape:m}}),_=b;if(c!=null){l.push(b);let w=N.getUndoAxesPermutation(c);_=Lt({inputs:{x:_},backend:t,attrs:{perm:w}})}return l.forEach(w=>t.disposeIntermediateTensorInfo(w)),_}var qP={kernelName:xa,backendName:"webgl",kernelFunc:dJ};var hJ=[DO,$O,HR,KR,XR,YR,JR,QR,eF,tF,nF,sF,iF,aF,uF,lF,cF,mF,pF,fF,dF,hF,gF,yF,bF,vF,IF,NF,TF,FR,DF,RF,FF,$F,PF,MF,OF,LF,zF,BF,WF,UF,jF,qF,KF,HF,XF,YF,ZF,JF,QF,eO,rO,oO,sO,iO,aO,lO,cO,pO,mO,fO,dO,hO,gO,xO,yO,RR,bO,EF,_O,wO,kO,OR,vO,CO,IO,SO,NO,TO,EO,AO,FO,MO,PO,LO,zO,VO,OO,WO,UO,jO,HO,qO,JO,BR,eP,tP,rP,oP,_F,nP,aP,lP,uP,cP,PR,pP,mP,wF,KO,fP,hP,dP,GR,gP,xP,yP,bP,_P,wP,kP,vP,CP,IP,NP,SP,TP,EP,AP,xF,ZO,DP,$P,RP,FP,OP,PP,LP,zP,BP,YO,UR,VP,GP,WP,UP,jR,jP,HP,qP,sP];for(let r of hJ)Qa(r);var KP="3.0.0";var gJ={"tfjs-core":Qb,"tfjs-backend-cpu":AA,"tfjs-backend-webgl":$R,"tfjs-data":wx,"tfjs-layers":hl,"tfjs-converter":dx,tfjs:KP};var zt;(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"})(zt||(zt={}));var Dl;(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"})(Dl||(Dl={}));var XP;function xJ(r){XP=r.wasm.cwrap(bs,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function yJ(r){let{inputs:e,backend:t,attrs:o}=r,{a:n,b:s,bias:a,preluActivationWeights:i}=e;if(n.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}=o,m=t.dataIdMap.get(n.dataId).id,f=t.dataIdMap.get(s.dataId).id,d=0;if(a!=null){let R=t.dataIdMap.get(a.dataId);if(R.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${R.shape.length}.`);d=R.id}let h=i==null?0:t.dataIdMap.get(i.dataId).id,g=Dl[c];if(g==null)throw new Error(`${c} activation not yet supported for FusedConv2D in the wasm backend.`);let x=l?n.shape[2]:n.shape[1],b=u?s.shape[1]:s.shape[2],_=n.shape[0],w=t.makeOutput([_,x,b],n.dtype),v=t.dataIdMap.get(w.dataId).id,$=new Uint8Array(new Int32Array(n.shape).buffer),A=new Uint8Array(new Int32Array(s.shape).buffer);return XP(m,$,n.shape.length,f,A,s.shape.length,l,u,g,d,h,p||0,v),w}var YP={kernelName:bs,backendName:"wasm",setupFunc:xJ,kernelFunc:yJ};function Rt(r){let e;function t(n){e=n.wasm.cwrap(r,null,["number","number"])}function o(n){let{backend:s,inputs:{x:a}}=n,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:o}}var ZP=Rt(ss);function _t(r,e,t){let o;function n(a){o=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=N.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,_=()=>o(p,g,u.shape.length,m,x,c.shape.length,zt[u.dtype],b);if(e&&u.dtype==="float32")return _(),h;let w=N.getBroadcastDims(u.shape,d),v=N.getBroadcastDims(c.shape,d),$=w.every((R,M)=>R===M),A=v.every((R,M)=>R===M);if($&&A)return _(),h;throw new Error(`Broadcasting along outer dims is not yet supported for ${u.dtype} ${r}.`)}return{kernelName:r,backendName:"wasm",setupFunc:n,kernelFunc:s}}var bJ=!0,JP=_t(xo,bJ);var QP;function _J(r){QP=r.wasm.cwrap(Uo,null,["array","number","number","number"])}function wJ(r){let{inputs:e,backend:t}=r,o=t.makeOutput(e[0].shape,e[0].dtype);if(y.sizeFromShape(o.shape)===0)return o;let n=e.map(i=>t.dataIdMap.get(i.dataId).id),s=new Uint8Array(new Int32Array(n).buffer),a=t.dataIdMap.get(o.dataId).id;return QP(s,n.length,zt[o.dtype],a),o}var eM={kernelName:Uo,backendName:"wasm",setupFunc:_J,kernelFunc:wJ};function fc(r){let{inputs:{x:e},backend:t}=r,o=t.makeOutput(e.shape,e.dtype),n=t.typedArrayFromHeap(e);return t.typedArrayFromHeap(o).set(n),o}var tM={kernelName:us,backendName:"wasm",kernelFunc:fc};var rM;function kJ(r){rM=r.wasm.cwrap(Rn,null,["number","array","number","number","number","array","number"])}function Hp(r){let{inputs:e,backend:t,attrs:o}=r,[n,s]=CJ(e.x.shape,o.perm),a=!0;for(let d=0;d<s.length;d++)s[d]!==d&&(a=!1);let i=vJ(e.x.shape,o.perm),l={dataId:e.x.dataId,shape:n,dtype:e.x.dtype};if(a){let d=fc({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 rM(c,f,l.shape.length,zt[l.dtype],p,m,s.length),u}function vJ(r,e){let t=new Array(r.length);for(let o=0;o<t.length;o++)t[o]=r[e[o]];return t}function CJ(r,e){let t=[],o=[];for(let n=0;n<r.length;++n)r[n]!==1&&t.push(r[n]),r[e[n]]!==1&&o.push(e[n]);for(let n=0;n<o.length;++n){let s=-1;for(let a=0;a<o.length;++a)o[a]>=n&&(s===-1||o[s]>o[a])&&(s=a);o[s]=n}return[t,o]}var oM={kernelName:Rn,backendName:"wasm",kernelFunc:Hp,setupFunc:kJ};function es(r,e,t){let o=r.shape,n=r.shape.length,s=y.parseAxisParam(e,o),a=s,i=N.getAxesPermutation(a,n),l=null,u=!1;if(i!=null){let c=new Array(n);for(let f=0;f<c.length;f++)c[f]=o[i[f]];a=N.getInnerMostAxes(a.length,n),l=Hp({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 nM;function IJ(r){nM=r.wasm.cwrap(jo,null,["number","number","number","number","number"])}function NJ(r){let{backend:e,inputs:t,attrs:o}=r,{axis:n}=o,{x:s}=t,a=e.dataIdMap.get(s.dataId).id,i=a,l=s,{transposed:u,axes:c,inputWasTransposed:p}=es(s,n,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 nM(i,zt[l.dtype],h,g,d),p&&e.disposeData(u.dataId),f}var sM={kernelName:jo,backendName:"wasm",kernelFunc:NJ,setupFunc:IJ};var iM;function SJ(r){iM=r.wasm.cwrap(Ho,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function TJ(r){let{inputs:e,attrs:t,backend:o}=r,n=e.x,s=o.dataIdMap.get(n.dataId).id,{filterSize:a,strides:i,pad:l,dimRoundingMode:u}=t,c=N.computePool2DInfo(n.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,_=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 w=o.makeOutput(c.outShape,"float32"),v=o.dataIdMap.get(w.dataId).id;return iM(s,n.shape[0],n.shape[1],n.shape[2],p,m,f,d,h,g,x,b,_,v),w}var aM={kernelName:Ho,backendName:"wasm",setupFunc:SJ,kernelFunc:TJ};function zr(r){let{inputs:e,attrs:t}=r,{x:o}=e,{shape:n}=t,s=y.sizeFromShape(o.shape),a=y.inferFromImplicitShape(n,s);return y.assert(s===y.sizeFromShape(a),()=>`new shape: ${a}, old shape: ${o.shape}. New shape and old shape must have the same number of elements.`),{dataId:o.dataId,shape:a,dtype:o.dtype}}var lM={kernelName:fs,backendName:"wasm",kernelFunc:zr};var uM;function EJ(r){uM=r.wasm.cwrap(qo,null,["number","array","number","number","array","number","number","number","number"])}function AJ(r){let{inputs:e,backend:t,attrs:o}=r,{a:n,b:s}=e,{transposeA:a,transposeB:i}=o;if(n.dtype!=="float32"||s.dtype!=="float32")throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");let l=n.shape.length,u=s.shape.length,c=a?n.shape[l-2]:n.shape[l-1],p=i?s.shape[u-1]:s.shape[u-2],m=a?n.shape[l-1]:n.shape[l-2],f=i?s.shape[u-2]:s.shape[u-1],d=n.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 w=(g>x?n.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 ${n.shape} and ${s.shape} and transposeA=${a} and transposeB=${i} must match.`);let v=a?[g,c,m]:[g,m,c],$=i?[x,f,p]:[x,p,f],A=zr({inputs:{x:n},backend:t,attrs:{shape:v}}),R=zr({inputs:{x:s},backend:t,attrs:{shape:$}}),M=t.dataIdMap.get(A.dataId).id,z=t.dataIdMap.get(R.dataId).id,W=a?A.shape[2]:A.shape[1],U=i?R.shape[1]:R.shape[2],q=Math.max(g,x),Z=t.makeOutput([q,W,U],A.dtype),X=t.dataIdMap.get(Z.dataId).id,Y=new Uint8Array(new Int32Array(A.shape).buffer),te=new Uint8Array(new Int32Array(R.shape).buffer);return uM(M,Y,A.shape.length,z,te,R.shape.length,a,i,X),Z.shape=w,Z}var cM={kernelName:qo,backendName:"wasm",setupFunc:EJ,kernelFunc:AJ};function dc(r){let{inputs:{x:e},attrs:{dtype:t},backend:o}=r,n=o.makeOutput(e.shape,t),s=o.typedArrayFromHeap(e);return o.typedArrayFromHeap(n).set(s),n}var pM={kernelName:Eo,backendName:"wasm",kernelFunc:dc};var mM;function DJ(r){mM=r.wasm.cwrap(Ao,null,["number","number","number","number"])}function $J(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{clipValueMin:s,clipValueMax:a}=o,i=t.dataIdMap.get(n.dataId).id,l=t.makeOutput(n.shape,n.dtype),u=t.dataIdMap.get(l.dataId).id;return mM(i,s,a,u),l}var fM={kernelName:Ao,backendName:"wasm",setupFunc:DJ,kernelFunc:$J};function JC(r){let{inputs:e,backend:t}=r,o=y.parseAxisParam(r.attrs.axis,e[0].shape)[0],n=N.computeOutShape(e.map(f=>f.shape),o),s=e.filter(f=>y.sizeFromShape(f.shape)>0);if(s.length===1)return fc({inputs:{x:s[0]},backend:t});let a=t.makeOutput(n,e[0].dtype);if(y.sizeFromShape(n)===0)return a;let i=s.map(f=>f.shape);if(N.assertParamsConsistent(i,o),s[0].dtype==="string"){let f=s.map(_=>{let w=y.sizeFromShape(_.shape.slice(o));return zr({inputs:{x:_},backend:t,attrs:{shape:[-1,w]}})}),d=f.map(_=>({vals:t.readSync(_.dataId),shape:_.shape}));n=N.computeOutShape(f.map(_=>_.shape),1);let h=f[0].shape[0]===1,g=Ud(d,n,e[0].dtype,h),x=N.computeOutShape(s.map(_=>_.shape),o);a.shape=x;let b=t.dataIdMap.get(a.dataId);return b.stringBytes=N.fromStringArrayToUint8(g),a}let l=y.sizeFromShape(s[0].shape.slice(0,o)),u=0,c=s.map(f=>{let d=y.sizeFromShape(f.shape.slice(o));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 dM={kernelName:is,backendName:"wasm",kernelFunc:JC};var hM;function RJ(r){hM=r.wasm.cwrap(Ko,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function FJ(r){let{inputs:e,attrs:t,backend:o}=r,{x:n,filter:s}=e,a=o.dataIdMap.get(n.dataId).id,i=o.dataIdMap.get(s.dataId).id,{strides:l,dilations:u,pad:c,dimRoundingMode:p,dataFormat:m}=t,f=N.convertConv2DDataFormat(m),d=N.computeConv2DInfo(n.shape,s.shape,l,u,c,p,!1,f),h=d.filterHeight,g=d.filterWidth,x=d.padInfo.top,b=d.padInfo.right,_=d.padInfo.bottom,w=d.padInfo.left,v=d.dilationHeight,$=d.dilationWidth,A=d.strideHeight,R=d.strideWidth,M=d.inChannels,z=d.outChannels,W=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 U=o.makeOutput(d.outShape,"float32"),q=o.dataIdMap.get(U.dataId).id;return hM(a,n.shape[0],n.shape[1],n.shape[2],i,h,g,x,b,_,w,W,v,$,A,R,M,z,q),U}var gM={kernelName:Ko,backendName:"wasm",setupFunc:RJ,kernelFunc:FJ};var xM;function OJ(r){xM=r.wasm.cwrap(Xo,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 PJ(r){let{backend:e,inputs:t,attrs:o}=r,{dy:n,filter:s}=t,{strides:a,pad:i,dataFormat:l,dimRoundingMode:u,inputShape:c}=o,p=1,m=N.convertConv2DDataFormat(l),f=N.computeConv2DInfo(c,s.shape,a,p,i,u,!1,m),{batchSize:d,filterHeight:h,filterWidth:g,inChannels:x,inHeight:b,inWidth:_,outChannels:w,outHeight:v,outWidth:$,strideHeight:A,strideWidth:R}=f,M=h-1-f.padInfo.top,z=g-1-f.padInfo.left,W=f.dataFormat==="channelsLast",U=y.computeStrides(f.inShape),q=y.computeStrides(n.shape),[Z,X,Y]=y.computeStrides(s.shape),te=U[0],K=W?U[1]:U[2],re=W?U[2]:1,ie=W?1:U[1],se=q[0],pe=W?q[1]:q[2],ae=W?q[2]:1,xe=W?1:q[1],ge=e.makeOutput(f.inShape,"float32"),_e=e.dataIdMap.get(ge.dataId).id,ke=e.dataIdMap.get(n.dataId).id,De=e.dataIdMap.get(s.dataId).id;return xM(ke,De,d,h,g,b,_,x,v,$,w,A,R,M,z,Z,X,Y,te,K,re,ie,se,pe,ae,xe,_e),ge}var yM={kernelName:Xo,backendName:"wasm",setupFunc:OJ,kernelFunc:PJ};var bM=Rt(Yo);var QC;(function(r){r[r.bilinear=0]="bilinear",r[r.nearest=1]="nearest"})(QC||(QC={}));var _M;function MJ(r){_M=r.wasm.cwrap(ri,null,["number","number","number","number","array","number","number","number","number","number"])}function LJ(r){let{backend:e,inputs:t,attrs:o}=r,{method:n,extrapolationValue:s,cropSize:a}=o,{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=dc({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,_=e.makeOutput(f,"float32"),w=e.dataIdMap.get(_.dataId).id,v=new Uint8Array(new Int32Array(i.shape).buffer);return _M(g,x,b,c,v,p,m,QC[n],s,w),h!=null&&e.disposeData(h.dataId),_}var wM={kernelName:ri,backendName:"wasm",setupFunc:MJ,kernelFunc:LJ};var kM;function zJ(r){kM=r.wasm.cwrap(Zo,null,["number","number","number","number","number","number"])}function BJ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,exclusive:a,reverse:i}=o,l=n.shape.length;y.assert(n.dtype==="float32"||n.dtype==="int32",()=>`cumsum does not support ${n.dtype} tensors in the WASM backend`);let u=N.getAxesPermutation([s],l),c=n;u!==null&&(c=Hp({inputs:{x:n},attrs:{perm:u},backend:t}));let p=N.getInnerMostAxes(1,l)[0];N.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;kM(d,a?1:0,i?1:0,f,h,zt[n.dtype]);let g=m;if(u!==null){let x=N.getUndoAxesPermutation(u);g=Hp({inputs:{x:m},attrs:{perm:x},backend:t}),t.disposeData(c.dataId),t.disposeData(m.dataId)}return g}var vM={kernelName:Zo,backendName:"wasm",setupFunc:zJ,kernelFunc:BJ};var CM;function VJ(r){CM=r.wasm.cwrap(oi,null,["number","number","number","array","number","array","array","number","number"])}function GJ(r){let{backend:e,inputs:t,attrs:o}=r,{x:n}=t,{blockSize:s,dataFormat:a}=o;y.assert(s>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${s}`);let i=n.shape[0],l=a==="NHWC"?n.shape[1]:n.shape[2],u=a==="NHWC"?n.shape[2]:n.shape[3],c=a==="NHWC"?n.shape[3]:n.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(n.dataId).id,b=new Uint8Array(new Int32Array(y.computeStrides(n.shape)).buffer),_=new Uint8Array(new Int32Array(d).buffer),w=new Uint8Array(new Int32Array(y.computeStrides(d)).buffer),v=e.dataIdMap.get(h.dataId).id;return CM(x,s,a==="NHWC"?1:0,b,n.shape.length-1,_,w,d.length,v),h}var IM={kernelName:oi,backendName:"wasm",setupFunc:VJ,kernelFunc:GJ};var NM;function WJ(r){NM=r.wasm.cwrap(Jo,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function UJ(r){let{inputs:e,attrs:t,backend:o}=r,{x:n,filter:s}=e,a=o.dataIdMap.get(n.dataId).id,i=o.dataIdMap.get(s.dataId).id,{strides:l,dilations:u,pad:c,dimRoundingMode:p}=t,m=u==null?[1,1]:u,f=N.computeConv2DInfo(n.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,_=f.padInfo.left,w=f.dilationHeight,v=f.dilationWidth,$=f.strideHeight,A=f.strideWidth,R=f.inChannels,M=f.outChannels,z=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 W=o.makeOutput(f.outShape,"float32"),U=o.dataIdMap.get(W.dataId).id;return NM(a,n.shape[0],n.shape[1],n.shape[2],i,d,h,g,x,b,_,z,w,v,$,A,R,M,U),W}var SM={kernelName:Jo,backendName:"wasm",setupFunc:WJ,kernelFunc:UJ};var jJ=!1,TM=_t(ii,jJ,"bool");var EM=Rt(en);function Xx(r){let{inputs:e,attrs:t,backend:o}=r,{input:n}=e,{dim:s}=t,a=n.shape.length,i=n.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),zr({inputs:{x:n},backend:o,attrs:{shape:i}})}var AM={kernelName:as,backendName:"wasm",kernelFunc:Xx};function HJ(r){let{attrs:{shape:e,value:t,dtype:o},backend:n}=r,s=n.makeOutput(e,o);return n.typedArrayFromHeap(s).fill(t),s}var DM={kernelName:ua,backendName:"wasm",kernelFunc:HJ};var $M;function qJ(r){$M=r.wasm.cwrap(li,null,["number","number","number","number","number","number"])}function KJ(r){let{inputs:e,backend:t}=r,{image:o}=e,n=t.makeOutput(o.shape,o.dtype),s=t.dataIdMap.get(o.dataId).id,a=t.dataIdMap.get(n.dataId).id,[i,l,u,c]=o.shape;return $M(s,i,l,u,c,a),n}var RM={kernelName:li,backendName:"wasm",kernelFunc:KJ,setupFunc:qJ};var FM=Rt(tn);var XJ=!1,OM=_t(rn,XJ);var PM;function YJ(r){PM=r.wasm.cwrap(on,null,["number","number","number","number","number","number","number"])}function ZJ(r){let{backend:e,inputs:t,attrs:o}=r,{varianceEpsilon:n}=o,{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 PM(c,p,m,f,d,n,g),h}var MM={kernelName:on,backendName:"wasm",setupFunc:YJ,kernelFunc:ZJ};var LM;function JJ(r){LM=r.wasm.cwrap(_s,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 QJ(r){let{inputs:e,attrs:t,backend:o}=r,{x:n,filter:s,bias:a,preluActivationWeights:i}=e,{strides:l,pad:u,dilations:c,dataFormat:p,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=t,h=N.computeConv2DInfo(n.shape,s.shape,l,c,u,m),g=Dl[f];if(g==null)throw new Error(`${f} activation not yet supported for FusedConv2D in the wasm backend.`);let x=o.dataIdMap.get(n.dataId).id,b=o.dataIdMap.get(s.dataId).id,_=h.outChannels,w=0;if(a!=null){let ae=o.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]!==_)throw new Error(`FusedConv2D bias shape (${ae.shape}) does not match the number of output channels (${_})`);w=ae.id}let v=h.filterHeight,$=h.filterWidth,A=h.padInfo.top,R=h.padInfo.right,M=h.padInfo.bottom,z=h.padInfo.left,W=h.dilationHeight,U=h.dilationWidth,q=h.strideHeight,Z=h.strideWidth,X=h.inChannels,Y=h.padInfo.type==="SAME"?1:0,te=h.batchSize,K=h.inHeight,re=h.inWidth;if(p!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);let ie=o.makeOutput(h.outShape,"float32"),se=o.dataIdMap.get(ie.dataId).id,pe=i==null?0:o.dataIdMap.get(i.dataId).id;return LM(x,te,K,re,b,v,$,w,A,R,M,z,Y,W,U,q,Z,X,_,g,pe,d||0,se),ie}var zM={kernelName:_s,backendName:"wasm",setupFunc:JJ,kernelFunc:QJ};var BM;function eQ(r){BM=r.wasm.cwrap(ws,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 tQ(r){let{inputs:e,attrs:t,backend:o}=r,{x:n,filter:s,bias:a,preluActivationWeights:i}=e,{strides:l,pad:u,dilations:c,dataFormat:p,dimRoundingMode:m,activation:f,leakyreluAlpha:d}=t,h=N.computeConv2DInfo(n.shape,s.shape,l,c,u,m,!0),g=Dl[f];if(g==null)throw new Error(`${f} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);let x=o.dataIdMap.get(n.dataId).id,b=o.dataIdMap.get(s.dataId).id,_=h.outChannels,w=0;if(a!=null){let ae=o.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]!==_)throw new Error(`FusedDepthwiseConv2D bias shape (${ae.shape}) does not match the number of output channels (${_})`);w=ae.id}let v=h.filterHeight,$=h.filterWidth,A=h.padInfo.top,R=h.padInfo.right,M=h.padInfo.bottom,z=h.padInfo.left,W=h.dilationHeight,U=h.dilationWidth,q=h.strideHeight,Z=h.strideWidth,X=h.inChannels,Y=h.padInfo.type==="SAME"?1:0,te=h.batchSize,K=h.inHeight,re=h.inWidth;if(p!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);let ie=o.makeOutput(h.outShape,"float32"),se=o.dataIdMap.get(ie.dataId).id,pe=i==null?0:o.dataIdMap.get(i.dataId).id;return BM(x,te,K,re,b,v,$,w,A,R,M,z,Y,W,U,q,Z,X,_,g,pe,d||0,se),ie}var VM={kernelName:ws,backendName:"wasm",setupFunc:eQ,kernelFunc:tQ};var GM;function rQ(r){GM=r.wasm.cwrap(ui,null,["number","number","number","number","number","number","array","number"])}function oQ(r){let{backend:e,inputs:t}=r,{params:o,indices:n}=t,[s,a,i,l]=Zh.prepareAndValidate(o,n),u=e.makeOutput(s,o.dtype);if(a===0)return u;let c=n.shape,p=c[c.length-1],f=e.dataIdMap.get(o.dataId).id,h=e.dataIdMap.get(n.dataId).id,g=new Uint8Array(new Int32Array(l).buffer),x=e.dataIdMap.get(u.dataId).id;return GM(f,zt[o.dtype],h,a,p,i,g,x),u}var WM={kernelName:ui,backendName:"wasm",setupFunc:rQ,kernelFunc:oQ};var UM;function nQ(r){UM=r.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function sQ(r){let{backend:e,inputs:t,attrs:o}=r,{x:n,indices:s}=t,{axis:a,batchDims:i}=o,l=y.parseAxisParam(a,n.shape)[0],u=N.segment_util.collectGatherOpShapeInfo(n,s,l,i),c=zr({inputs:{x:n},attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]},backend:e}),p=y.sizeFromShape(s.shape),m=zr({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,n.dtype);if(y.sizeFromShape(n.shape)===0)return d;let h=c.shape.length-1,x=e.dataIdMap.get(c.dataId).id,_=e.dataIdMap.get(m.dataId).id,w=e.dataIdMap.get(d.dataId).id,v=new Uint8Array(new Int32Array(y.computeStrides(c.shape)).buffer),$=new Uint8Array(new Int32Array(y.computeStrides(f)).buffer);return UM(x,zt[n.dtype],v,h,_,u.batchSize,$,w),d.shape=u.outputShape,d}var jM={kernelName:ls,backendName:"wasm",setupFunc:nQ,kernelFunc:sQ};var iQ=!1,HM=_t(ci,iQ,"bool");var aQ=!1,qM=_t(nn,aQ,"bool");var KM;function lQ(r){KM=r.wasm.cwrap(sn,null,["number","number","number"])}function uQ(r){let{inputs:{x:e},attrs:{alpha:t},backend:o}=r,n=o.dataIdMap.get(e.dataId).id,s=o.makeOutput(e.shape,e.dtype);if(y.sizeFromShape(e.shape)!==0){let a=o.dataIdMap.get(s.dataId).id;KM(n,t,a)}return s}var XM={kernelName:sn,backendName:"wasm",setupFunc:lQ,kernelFunc:uQ};var cQ=!1,YM=_t(di,cQ,"bool");var pQ=!1,ZM=_t(hi,pQ,"bool");var JM=Rt(an);var mQ=!1,QM=_t(xi,mQ,"bool");var eL;function fQ(r){eL=r.wasm.cwrap(ln,null,["number, number, number"])}function dQ(r){let{backend:e,inputs:t,attrs:o}=r,{reductionIndices:n,keepDims:s}=o,{x:a}=t,l=e.dataIdMap.get(a.dataId).id,u=a,{transposed:c,axes:p,originalAxes:m,inputWasTransposed:f}=es(a,n,e);if(f){let _=e.dataIdMap.get(c.dataId).id;u=c,l=_}let d=u.shape.length;N.assertAxesAreInnerMostDims("max",p,d);let[h,g]=N.computeOutAndReduceShapes(u.shape,p),x=y.sizeFromShape(g),b=e.makeOutput(h,a.dtype);if(y.sizeFromShape(u.shape)!==0){let _=e.dataIdMap.get(b.dataId).id;eL(l,x,_)}if(f&&e.disposeData(c.dataId),s){let _=N.expandShapeToKeepDim(b.shape,m);b.shape=_}return b}var tL={kernelName:ln,backendName:"wasm",setupFunc:fQ,kernelFunc:dQ};var hQ=!1,rL=_t(un,hQ);var oL;function gQ(r){oL=r.wasm.cwrap(cn,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function xQ(r){let{inputs:e,attrs:t,backend:o}=r,n=e.x,s=o.dataIdMap.get(n.dataId).id,{filterSize:a,strides:i,pad:l,dimRoundingMode:u}=t,c=N.computePool2DInfo(n.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,_=c.strideHeight,w=c.strideWidth,v=c.inChannels,$=c.outChannels;if(c.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);let A=o.makeOutput(c.outShape,"float32"),R=o.dataIdMap.get(A.dataId).id;return oL(s,n.shape[0],n.shape[1],n.shape[2],p,m,f,d,h,g,x,b,_,w,v,$,R),A}var nL={kernelName:cn,backendName:"wasm",setupFunc:gQ,kernelFunc:xQ};var sL;function yQ(r){sL=r.wasm.cwrap(pn,null,["number, number, number"])}function bQ(r){let{backend:e,inputs:t,attrs:o}=r,{axis:n,keepDims:s}=o,{x:a}=t,i=e.dataIdMap.get(a.dataId).id,l=i,u=a,{transposed:c,axes:p,originalAxes:m,inputWasTransposed:f}=es(a,n,e),d=p;if(f){let w=e.dataIdMap.get(c.dataId).id;w!==i&&(u=c,l=w,d=N.getInnerMostAxes(d.length,u.shape.length))}N.assertAxesAreInnerMostDims("mean",d,u.shape.length);let[h,g]=N.computeOutAndReduceShapes(u.shape,d),x=y.sizeFromShape(g),b=u;u.dtype!=="float32"&&(b=dc({backend:e,inputs:{x:u},attrs:{dtype:"float32"}}),l=e.dataIdMap.get(b.dataId).id);let _=e.makeOutput(h,"float32");if(y.sizeFromShape(u.shape)!==0){let w=e.dataIdMap.get(_.dataId).id;sL(l,x,w)}if(f&&e.disposeData(c.dataId),s){let w=N.expandShapeToKeepDim(_.shape,m);_.shape=w}return u.dtype!=="float32"&&e.disposeData(b.dataId),_}var iL={kernelName:pn,backendName:"wasm",setupFunc:yQ,kernelFunc:bQ};var aL;function _Q(r){aL=r.wasm.cwrap(mn,null,["number, number, number"])}function wQ(r){let{backend:e,inputs:t,attrs:o}=r,{axis:n,keepDims:s}=o,{x:a}=t,i=e.dataIdMap.get(a.dataId).id,l=i,u=a,{transposed:c,axes:p,originalAxes:m,inputWasTransposed:f}=es(a,n,e);if(f){let _=e.dataIdMap.get(c.dataId).id;_!==i&&(u=c,l=_)}let d=u.shape.length;N.assertAxesAreInnerMostDims("min",p,d);let[h,g]=N.computeOutAndReduceShapes(u.shape,p),x=y.sizeFromShape(g),b=e.makeOutput(h,u.dtype);if(y.sizeFromShape(u.shape)!==0){let _=e.dataIdMap.get(b.dataId).id;aL(l,x,_)}if(f&&e.disposeData(c.dataId),s){let _=N.expandShapeToKeepDim(b.shape,m);b.shape=_}return b}var lL={kernelName:mn,backendName:"wasm",setupFunc:_Q,kernelFunc:wQ};var kQ=!1,uL=_t(fn,kQ);var vQ=!0,cL=_t(dn,vQ);var pL=Rt(cs);function qp(r,e){let t=new Int32Array(r.wasm.HEAPU8.buffer,e,4),o=t[0],n=t[1],s=t[2],a=t[3];return r.wasm._free(e),{pSelectedIndices:o,selectedSize:n,pSelectedScores:s,pValidOutputs:a}}var mL;function CQ(r){mL=r.wasm.cwrap(_i,"number",["number","number","number","number","number"])}function IQ(r){let{backend:e,inputs:t,attrs:o}=r,{iouThreshold:n,maxOutputSize:s,scoreThreshold:a}=o,{boxes:i,scores:l}=t,u=e.dataIdMap.get(i.dataId).id,c=e.dataIdMap.get(l.dataId).id,p=mL(u,c,s,n,a),{pSelectedIndices:m,selectedSize:f,pSelectedScores:d,pValidOutputs:h}=qp(e,p);return e.wasm._free(d),e.wasm._free(h),e.makeOutput([f],"int32",m)}var fL={kernelName:_i,backendName:"wasm",setupFunc:CQ,kernelFunc:IQ};var dL;function NQ(r){dL=r.wasm.cwrap(wi,"number",["number","number","number","number","number","bool"])}function SQ(r){let{backend:e,inputs:t,attrs:o}=r,{iouThreshold:n,maxOutputSize:s,scoreThreshold:a,padToMaxOutputSize:i}=o,{boxes:l,scores:u}=t,c=e.dataIdMap.get(l.dataId).id,p=e.dataIdMap.get(u.dataId).id,m=dL(c,p,s,n,a,i),{pSelectedIndices:f,selectedSize:d,pSelectedScores:h,pValidOutputs:g}=qp(e,m);e.wasm._free(h);let x=e.makeOutput([d],"int32",f),b=e.makeOutput([],"int32",g);return[x,b]}var hL={kernelName:wi,backendName:"wasm",setupFunc:NQ,kernelFunc:SQ};var gL;function TQ(r){gL=r.wasm.cwrap(ki,"number",["number","number","number","number","number","number"])}function EQ(r){let{backend:e,inputs:t,attrs:o}=r,{iouThreshold:n,maxOutputSize:s,scoreThreshold:a,softNmsSigma:i}=o,{boxes:l,scores:u}=t,c=e.dataIdMap.get(l.dataId).id,p=e.dataIdMap.get(u.dataId).id,m=gL(c,p,s,n,a,i),{pSelectedIndices:f,selectedSize:d,pSelectedScores:h,pValidOutputs:g}=qp(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:ki,backendName:"wasm",setupFunc:TQ,kernelFunc:EQ};var AQ=!1,yL=_t(bi,AQ,"bool");var bL;function DQ(r){bL=r.wasm.cwrap(hn,null,["number","number","number","number","number"])}function $Q(r){let{inputs:e,backend:t,attrs:o}=r,{indices:n}=e,{depth:s,onValue:a,offValue:i}=o,l=t.makeOutput([...n.shape,s],"int32"),u=t.dataIdMap.get(l.dataId).id,p=t.dataIdMap.get(n.dataId).id;return bL(p,s,a,i,u),l}var _L={kernelName:hn,backendName:"wasm",setupFunc:DQ,kernelFunc:$Q};function RQ(r){let{inputs:{x:e},backend:t}=r,o=t.makeOutput(e.shape,e.dtype);return t.typedArrayFromHeap(o).fill(1),o}var wL={kernelName:ps,backendName:"wasm",kernelFunc:RQ};function FQ(r){let{inputs:e,backend:t,attrs:o}=r,{axis:n}=o;if(e.length===1)return Xx({inputs:{input:e[0]},backend:t,attrs:{dim:n}});let s=e[0].shape,a=e[0].dtype;e.forEach(l=>{y.assertShapesMatch(s,l.shape,"All tensors passed to stack must have matching shapes"),y.assert(a===l.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=e.map(l=>Xx({inputs:{input:l},backend:t,attrs:{dim:n}}));return JC({inputs:i,backend:t,attrs:{axis:n}})}var kL={kernelName:ms,backendName:"wasm",kernelFunc:FQ};var vL;function OQ(r){vL=r.wasm.cwrap(gn,null,["number","array","number","number","array","array","number","number"])}function PQ(r){let{inputs:{x:e},backend:t,attrs:{paddings:o,constantValue:n}}=r,s=o.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=o.map(d=>d[0]),p=o.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,zt[e.dtype],m,f,n,l),i}var CL={kernelName:gn,backendName:"wasm",kernelFunc:PQ,setupFunc:OQ};var MQ=!1,IL=_t(xn,MQ);var NL;function LQ(r){NL=r.wasm.cwrap(yn,null,["number","number","number"])}function zQ(r){let{inputs:e,backend:t}=r,{x:o,alpha:n}=e,s=t.dataIdMap.get(o.dataId).id,a=t.dataIdMap.get(n.dataId).id,i=t.makeOutput(o.shape,"float32"),l=t.dataIdMap.get(i.dataId).id;return NL(s,a,l),i}var SL={kernelName:yn,backendName:"wasm",setupFunc:LQ,kernelFunc:zQ};var TL;function BQ(r){TL=r.wasm.cwrap(vi,null,["number","number","number","number"])}function VQ(r){let{backend:e,inputs:t,attrs:o}=r,{axis:n,keepDims:s}=o,{x:a}=t,i=e.dataIdMap.get(a.dataId).id,l=i,u=a,{transposed:c,axes:p,originalAxes:m,inputWasTransposed:f}=es(a,n,e),d=p;if(f){let _=e.dataIdMap.get(c.dataId).id;_!==i&&(u=c,l=_,d=N.getInnerMostAxes(d.length,u.shape.length))}N.assertAxesAreInnerMostDims("prod",d,u.shape.length);let[h,g]=N.computeOutAndReduceShapes(u.shape,d),x=y.sizeFromShape(g),b=e.makeOutput(h,u.dtype);if(y.sizeFromShape(u.shape)!==0){let _=e.dataIdMap.get(b.dataId).id;TL(l,x,zt[b.dtype],_)}if(f&&e.disposeData(c.dataId),s){let _=N.expandShapeToKeepDim(b.shape,m);b.shape=_}return b}var EL={kernelName:vi,backendName:"wasm",setupFunc:BQ,kernelFunc:VQ};var GQ=r=>{let{backend:e,attrs:t}=r,{start:o,stop:n,step:s,dtype:a}=t,i=qd(o,n,s,a),l=e.makeOutput([i.length],a);return e.typedArrayFromHeap(l).set(i),l},AL={kernelName:fa,backendName:"wasm",kernelFunc:GQ};var WQ=!0,DL=_t(Qo,WQ);var $L=Rt(bn);var RL=Rt(wn);var FL;function UQ(r){FL=r.wasm.cwrap(_n,null,["number","number","number","number","number","number","number","number","number","number"])}function jQ(r){let{backend:e,inputs:t,attrs:o}=r,{images:n}=t,{alignCorners:s,halfPixelCenters:a,size:i}=o,[l,u]=i,[c,p,m,f]=n.shape,d=[c,l,u,f],h=e.dataIdMap.get(n.dataId),g;h.dtype!=="float32"&&(g=dc({backend:e,inputs:{x:n},attrs:{dtype:"float32"}}),h=e.dataIdMap.get(g.dataId));let x=h.id,b=e.makeOutput(d,"float32");if(y.sizeFromShape(n.shape)===0)return b;let _=e.dataIdMap.get(b.dataId).id;return FL(x,c,p,m,f,l,u,s?1:0,a?1:0,_),g!=null&&e.disposeData(g.dataId),b}var OL={kernelName:_n,backendName:"wasm",setupFunc:UQ,kernelFunc:jQ};var PL;function HQ(r){PL=r.wasm.cwrap(kn,null,["number","array","number","array","number","number"])}function qQ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{dims:s}=o,a=y.parseAxisParam(s,n.shape);if(n.shape.length===0)return fc({inputs:{x:n},backend:t});let i=t.makeOutput(n.shape,n.dtype),l=t.dataIdMap.get(n.dataId).id,u=t.dataIdMap.get(i.dataId).id,c=new Uint8Array(new Int32Array(a).buffer),p=new Uint8Array(new Int32Array(n.shape).buffer);return PL(l,c,a.length,p,n.shape.length,u),zr({inputs:{x:i},attrs:{shape:n.shape},backend:t})}var ML={kernelName:kn,backendName:"wasm",kernelFunc:qQ,setupFunc:HQ};var LL;function KQ(r){LL=r.wasm.cwrap(Ri,null,["number","number","number","number","number","number","number","number","array","number","number"])}function XQ(r){let{inputs:e,backend:t,attrs:o}=r,{image:n}=e,{radians:s,fillValue:a,center:i}=o,l=t.makeOutput(n.shape,n.dtype),u=t.dataIdMap.get(n.dataId).id,c=t.dataIdMap.get(l.dataId).id,[p,m,f,d]=n.shape,[h,g]=N.getImageCenter(i,m,f),x=a===0,b=255,_=typeof a=="number"?[a,a,a,x?0:b]:[...a,b],w=new Uint8Array(new Int32Array(_).buffer);return LL(u,p,m,f,d,s,h,g,w,_.length,c),l}var zL={kernelName:Ri,backendName:"wasm",kernelFunc:XQ,setupFunc:KQ};var BL=Rt(vn);var VL=Rt(Cn);var GL;function YQ(r){GL=r.wasm.cwrap(Ii,null,["number","number","number","number","number","number","array","number","number"])}function ZQ(r){let{backend:e,inputs:t,attrs:o}=r,{indices:n,updates:s}=t,{shape:a}=o,i=e.makeOutput(a,s.dtype);if(y.sizeFromShape(a)===0)return i;let{sliceRank:l,numUpdates:u,sliceSize:c,strides:p,outputSize:m}=Jh.calculateShapes(s,n,a),d=e.dataIdMap.get(n.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,zt[s.dtype],l,u,c,x,m,b),i}var WL={kernelName:Ii,backendName:"wasm",setupFunc:YQ,kernelFunc:ZQ};var UL;function JQ(r){UL=r.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function QQ(r){let{inputs:e,backend:t}=r,{condition:o,t:n,e:s}=e,a=t.dataIdMap.get(o.dataId).id,i=t.dataIdMap.get(n.dataId).id,l=t.dataIdMap.get(s.dataId).id,u=t.makeOutput(n.shape,n.dtype),c=t.dataIdMap.get(u.dataId).id,p=o.shape.length,m=n.shape.length,f=p===0||p>1||m===1?1:y.sizeFromShape(n.shape.slice(1));return UL(a,i,l,f,c),u}var jL={kernelName:ds,backendName:"wasm",kernelFunc:QQ,setupFunc:JQ};var HL;function eee(r){HL=r.wasm.cwrap(Nn,null,["number","number"])}function tee(r){let{backend:e,inputs:{x:t}}=r,o=e.dataIdMap.get(t.dataId).id,n=e.makeOutput(t.shape,t.dtype),s=e.dataIdMap.get(n.dataId).id;return y.sizeFromShape(n.shape)===0||HL(o,s),n}var qL={kernelName:"Sigmoid",backendName:"wasm",setupFunc:eee,kernelFunc:tee};var KL=Rt(In);function hc(r){let{inputs:{x:e},attrs:{begin:t,size:o},backend:n}=r,[s,a]=or.parseSliceParams(e,t,o),i=or.isSliceContinous(e.shape,s,a),l=n.readSync(e.dataId),u=n.makeOutput(a,e.dtype),c=y.computeStrides(e.shape),p=n.dataIdMap.get(u.dataId);if(i){let d=or.computeFlatOffset(s,c);return e.dtype==="string"?p.stringBytes=l.slice(d,d+y.sizeFromShape(a)):n.typedArrayFromHeap(u).set(l.subarray(d,d+y.sizeFromShape(a))),u}if(e.dtype==="string"){let d=Kd(l,s,a,e.shape,e.dtype);return p.stringBytes=d,u}let m=n.typedArrayFromHeap(u),f=e.shape.length;if(f===2)ree(l,c[0],m,s,a);else if(f===3)oee(l,c[0],c[1],m,s,a);else if(f===4)nee(l,c[0],c[1],c[2],m,s,a);else{let d=Kd(l,s,a,e.shape,e.dtype);m.set(d)}return u}function ree(r,e,t,o,n){let s=0,a=o[0],i=o[1],l=a+n[0];for(let u=a;u<l;u++){let c=u*e+i;t.set(r.subarray(c,c+n[1]),s),s+=n[1]}}function oee(r,e,t,o,n,s){let a=0,i=n[0],l=n[1],u=n[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;o.set(r.subarray(d,d+s[2]),a),a+=s[2]}}function nee(r,e,t,o,n,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*o+d;n.set(r.subarray(b,b+a[3]),i),i+=a[3]}}var XL={kernelName:hs,backendName:"wasm",kernelFunc:hc};var YL;function see(r){YL=r.wasm.cwrap(En,null,["number","number","number","number"])}function iee(r){let{backend:e,inputs:{logits:t},attrs:{dim:o}}=r,n=e.dataIdMap.get(t.dataId).id,s=e.makeOutput(t.shape,t.dtype),a=e.dataIdMap.get(s.dataId).id,i=t.shape[o],l=y.sizeFromShape(t.shape)/i;return y.sizeFromShape(s.shape)===0||YL(n,a,i,l),s}var ZL={kernelName:En,backendName:"wasm",setupFunc:see,kernelFunc:iee};function aee(r){let{inputs:e,attrs:t,backend:o}=r,{x:n}=e,{numOrSizeSplits:s,axis:a}=t,i=y.parseAxisParam(a,n.shape)[0],l=N.prepareSplitSize(n,s,i),u=new Array(n.shape.length).fill(0),c=n.shape.slice();return l.map(p=>{let m=[...c];m[i]=p;let f=hc({inputs:{x:n},attrs:{begin:u,size:m},backend:o});return u[i]+=p,f})}var JL={kernelName:gs,backendName:"wasm",kernelFunc:aee};var QL=Rt(Sn);var ez=Rt(ga);var lee=!0,tz=_t(An,lee);var rz;function uee(r){rz=r.wasm.cwrap(Do,null,["number","number","number"])}function cee(r){let{backend:e,inputs:t,attrs:o}=r,{alpha:n}=o,{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,n,l),i}var oz={kernelName:Do,backendName:"wasm",setupFunc:uee,kernelFunc:cee};var nz;function pee(r){nz=r.wasm.cwrap(Ai,null,["number","array","number","array","array","array","array","array","number","number"])}function mee(r){let{backend:e,inputs:t,attrs:o}=r,{x:n}=t,{begin:s,end:a,strides:i}=o;i==null&&(i=new Array(s.length));let{beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:m}=o,f=N.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=n.shape.length-s.length,h=N.slice_util.maskToAxes(p),g=n.shape.slice();h.forEach(z=>{s[z]=0,a[z]=1,g.splice(z,0,1)});let x=zr({inputs:{x:n},attrs:{shape:g},backend:e}),{begin:b,end:_,strides:w}=N.slice_util.getNormalizedAxes(x.shape,f,d,s,a,i,l,u,c);s=b,a=_,i=w;let v=N.slice_util.maskToAxes(m);v.forEach(z=>{a[z]=s[z]+1,i[z]=1});let $=N.slice_util.computeOutShape(s,a,i),A=$.filter((z,W)=>v.indexOf(W)===-1);if(i.every(z=>z===1)){let z=hc({inputs:{x:n},attrs:{begin:s,size:$},backend:e});return zr({inputs:{x:z},attrs:{shape:A},backend:e})}let M=e.makeOutput(A,"float32");if(!A.some(z=>z===0)){let z=e.dataIdMap.get(x.dataId).id,W=new Uint8Array(new Int32Array(y.computeStrides(x.shape)).buffer),U=new Uint8Array(new Int32Array(s).buffer),q=new Uint8Array(new Int32Array(a).buffer),Z=new Uint8Array(new Int32Array(i).buffer),X=new Uint8Array(new Int32Array(A).buffer),Y=new Uint8Array(new Int32Array(y.computeStrides(A)).buffer),te=e.dataIdMap.get(M.dataId).id;nz(z,W,x.shape.length,U,q,Z,X,Y,A.length,te)}return zr({inputs:{x:M},attrs:{shape:A},backend:e})}var sz={kernelName:Ai,backendName:"wasm",setupFunc:pee,kernelFunc:mee};var fee=!0,iz=_t(Dn,fee);var az;function dee(r){az=r.wasm.cwrap(Tn,null,["number, number, number"])}function hee(r){let{backend:e,inputs:t,attrs:o}=r,{axis:n,keepDims:s}=o,{x:a}=t,i=e.dataIdMap.get(a.dataId).id,l=i,u=a,{transposed:c,axes:p,originalAxes:m,inputWasTransposed:f}=es(a,n,e),d=p;if(f){let _=e.dataIdMap.get(c.dataId).id;_!==i&&(u=c,l=_,d=N.getInnerMostAxes(d.length,u.shape.length))}N.assertAxesAreInnerMostDims("sum",d,u.shape.length);let[h,g]=N.computeOutAndReduceShapes(u.shape,d),x=y.sizeFromShape(g),b=e.makeOutput(h,u.dtype);if(y.sizeFromShape(u.shape)!==0){let _=e.dataIdMap.get(b.dataId).id;az(l,x,_)}if(f&&e.disposeData(c.dataId),s){let _=N.expandShapeToKeepDim(b.shape,m);b.shape=_}return b}var lz={kernelName:Tn,backendName:"wasm",setupFunc:dee,kernelFunc:hee};var uz=Rt($n);var cz;function gee(r){cz=r.wasm.cwrap(yo,null,["number","array","number","array","number","number"])}function xee(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,s=t.dataIdMap.get(n.dataId).id,{reps:a}=o,i=new Array(n.shape.length);for(let m=0;m<i.length;m++)i[m]=n.shape[m]*a[m];let l=new Uint8Array(new Int32Array(n.shape).buffer),u=new Uint8Array(new Int32Array(i).buffer),c=t.makeOutput(i,n.dtype),p=t.dataIdMap.get(c.dataId).id;return cz(s,l,n.shape.length,u,i.length,zt[c.dtype],p),c}var pz={kernelName:yo,backendName:"wasm",setupFunc:gee,kernelFunc:xee};var mz;function yee(r){mz=r.wasm.cwrap($i,null,["number","array","number","number","number","bool","number","number"])}var bee=({inputs:r,backend:e,attrs:t})=>{let{x:o}=r,{k:n,sorted:s}=t,a=e.dataIdMap.get(o.dataId).id,i=new Uint8Array(new Int32Array(o.shape).buffer),l=o.shape.slice();l[l.length-1]=n;let u=e.makeOutput(l,o.dtype),c=e.dataIdMap.get(u.dataId).id,p=e.makeOutput(l,"int32"),m=e.dataIdMap.get(p.dataId).id;return mz(a,i,o.shape.length,zt[o.dtype],n,s,c,m),[u,p]},fz={kernelName:$i,backendName:"wasm",setupFunc:yee,kernelFunc:bee};function _ee(r){let{inputs:e,backend:t,attrs:o}=r,{value:n}=e,{axis:s}=o;s<0&&(s+=n.shape.length);let a=n.shape[s],i=n.shape.length,l=new Array(i-1),u=0;for(let f=0;f<i;f++)f!==s&&(l[u++]=n.shape[f]);let c=new Array(a),p=new Array(i).fill(0),m=n.shape.slice();m[s]=1;for(let f=0;f<c.length;f++)p[s]=f,c[f]=hc({inputs:{x:n},attrs:{begin:p,size:m},backend:t});return c.map(({dataId:f,dtype:d})=>({dataId:f,dtype:d,shape:l}))}var dz={kernelName:xs,backendName:"wasm",kernelFunc:_ee};function wee(r){let{inputs:{x:e},backend:t}=r,o=t.makeOutput(e.shape,e.dtype);return t.typedArrayFromHeap(o).fill(0),o}var hz={kernelName:ys,backendName:"wasm",kernelFunc:wee};var kee=[ZP,JP,eM,sM,aM,cM,pM,fM,dM,gM,yM,bM,wM,vM,IM,SM,TM,EM,AM,DM,RM,FM,OM,YP,MM,zM,VM,WM,jM,HM,qM,tM,XM,YM,ZM,JM,QM,tL,rL,nL,iL,lL,uL,cL,pL,fL,hL,xL,yL,_L,wL,kL,CL,IL,SL,EL,AL,DL,$L,RL,lM,OL,ML,zL,VL,BL,WL,jL,qL,KL,XL,ZL,JL,QL,ez,tz,oz,sz,iz,lz,uz,pz,fz,oM,dz,hz];for(let r of kee)Qa(r);var eI=G();eI.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])));eI.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(eI.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 sI=Sc(yz());var bz='var threadInfoStruct=0;var selfThreadId=0;var parentThreadId=0;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:selfThreadId})}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};this.onmessage=function(e){try{if(e.data.cmd==="load"){Module["DYNAMIC_BASE"]=e.data.DYNAMIC_BASE;Module["DYNAMICTOP_PTR"]=e.data.DYNAMICTOP_PTR;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)}Module=WasmBackendModuleThreadedSimd(Module);postMessage({"cmd":"loaded"})}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;threadInfoStruct=e.data.threadInfoStruct;Module["__register_pthread_ptr"](threadInfoStruct,0,0);selfThreadId=e.data.selfThreadId;parentThreadId=e.data.parentThreadId;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["dynCall_ii"](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"){Atomics.store(Module["HEAPU32"],threadInfoStruct+4>>2,ex instanceof Module["ExitStatus"]?ex.status:-2);Atomics.store(Module["HEAPU32"],threadInfoStruct+0>>2,1);Module["_emscripten_futex_wake"](threadInfoStruct+0,2147483647);if(!(ex instanceof Module["ExitStatus"]))throw ex}}}else if(e.data.cmd==="cancel"){if(threadInfoStruct){Module["PThread"].threadCancel()}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(threadInfoStruct){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.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");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 wz=Sc(_z());var Jx=class extends Ws{constructor(e){super();this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.init(),this.dataIdMap=new Ya(this,vs())}write(e,t,o){let n={};return this.move(n,e,t,o),n}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){let t=y.now();return e(),{kernelMs:y.now()-t}}move(e,t,o,n){let s=this.dataIdNextNumber++;if(n==="string"){let u=t;this.dataIdMap.set(e,{id:s,stringBytes:u,shape:o,dtype:n,memoryOffset:null});return}let a=y.sizeFromShape(o),i=a*y.bytesPerElement(n),l=this.wasm._malloc(i);this.dataIdMap.set(e,{id:s,memoryOffset:l,shape:o,dtype:n}),this.wasm.tfjs.registerTensor(s,a,l),t!=null&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,i),l)}async read(e){return this.readSync(e)}readSync(e){let{memoryOffset:t,dtype:o,shape:n,stringBytes:s}=this.dataIdMap.get(e);if(o==="string")return s;let a=this.wasm.HEAPU8.slice(t,t+y.sizeFromShape(n)*y.bytesPerElement(o));return vee(a.buffer,o)}disposeData(e){let t=this.dataIdMap.get(e);this.wasm._free(t.memoryOffset),this.wasm.tfjs.disposeData(t.id),this.dataIdMap.delete(e)}floatPrecision(){return 32}getMemoryOffset(e){return this.dataIdMap.get(e).memoryOffset}dispose(){this.wasm.tfjs.dispose(),this.wasm=null}memory(){return{unreliable:!1}}makeOutput(e,t,o){let n;if(o==null)n=this.write(null,e,t);else{n={};let s=this.dataIdNextNumber++;this.dataIdMap.set(n,{id:s,memoryOffset:o,shape:e,dtype:t});let a=y.sizeFromShape(e);this.wasm.tfjs.registerTensor(s,a,o)}return{dataId:n,shape:e,dtype:t}}typedArrayFromHeap({shape:e,dtype:t,dataId:o}){let n=this.wasm.HEAPU8.buffer,{memoryOffset:s}=this.dataIdMap.get(o),a=y.sizeFromShape(e);switch(t){case"float32":return new Float32Array(n,s,a);case"int32":return new Int32Array(n,s,a);case"bool":return new Uint8Array(n,s,a);default:throw new Error(`Unknown dtype ${t}`)}}};function Cee(r){return(e,t)=>(y.fetch(r,{credentials:"same-origin"}).then(o=>{o.ok||e.env.a(`failed to load wasm binary file at '${r}'`),o.arrayBuffer().then(n=>{WebAssembly.instantiate(n,e).then(s=>{t(s.instance)})})}),{})}function kz(r,e,t){if(Qx!=null)return Qx;let o="tfjs-backend-wasm.wasm";return r&&e?o="tfjs-backend-wasm-threaded-simd.wasm":r&&(o="tfjs-backend-wasm-simd.wasm"),dh!=null&&dh[o]!=null?dh[o]:t+o}async function vz(){let[r,e]=await Promise.all([G().getAsync("WASM_HAS_SIMD_SUPPORT"),G().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((t,o)=>{let n={};n.locateFile=(l,u)=>{if(l.endsWith(".worker.js")){let c=bz,p=new Blob([c],{type:"application/javascript"});return URL.createObjectURL(p)}return l.endsWith(".wasm")?kz(r,e,hh!=null?hh:u):u+l},iI&&(n.instantiateWasm=Cee(kz(r,e,hh!=null?hh:"")));let s;e&&r&&Qx==null?(s=sI.default(n),s.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+sI.default.toString()],{type:"text/javascript"})):s=wz.default(n);let a=null;s.tfjs={init:s.cwrap("init",null,[]),registerTensor:s.cwrap("register_tensor",null,["number","number","number"]),disposeData:s.cwrap("dispose_data",a,["number"]),dispose:s.cwrap("dispose",a,[])};let i=!1;s.onRuntimeInitialized=()=>{i=!0,gh=!1,t({wasm:s})},s.onAbort=()=>{if(i||gh)return;gh=!0,o({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"})}})}function vee(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 Iee=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],Qx=null,hh=null,dh={},gh=!1,iI=!1;function Nee(r,e=!1){if(rg("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),gh)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");Qx=r,iI=e}function See(r,e=!1){if(gh)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")hh=r;else{dh=r;let t=Iee.filter(o=>dh[o]==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.`)}iI=e}var Tee="3.0.0";var Eee=2;yu("wasm",async()=>{let{wasm:r}=await vz();return new Jx(r)},Eee);export{ss as Abs,qs as Acos,Ks as Acosh,tp as AdadeltaOptimizer,rp as AdagradOptimizer,op as AdamOptimizer,np as AdamaxOptimizer,xo as Add,Uo as AddN,Vl as All,Gl as Any,jo as ArgMax,oa as ArgMin,Xs as Asin,Ys as Asinh,Zs as Atan,Qs as Atan2,Js as Atanh,Ho as AvgPool,na as AvgPool3D,Ul as AvgPool3DGrad,Wl as AvgPoolGrad,Jx as BackendWasm,qo as BatchMatMul,sa as BatchToSpaceND,jl as Bincount,bb as BroadcastTo,Yg as Callback,$g as CallbackList,Eo as Cast,ei as Ceil,Ao as ClipByValue,Hl as Complex,ia as ComplexAbs,is as Concat,Ko as Conv2D,ql as Conv2DBackpropFilter,Xo as Conv2DBackpropInput,aa as Conv3D,Kl as Conv3DBackpropFilterV2,Xl as Conv3DBackpropInputV2,Yo as Cos,ti as Cosh,ri as CropAndResize,Zo as Cumsum,Fg as CustomCallback,Ya as DataStorage,Yl as DenseBincount,oi as DepthToSpace,Jo as DepthwiseConv2dNative,Zl as DepthwiseConv2dNativeBackpropFilter,Jl as DepthwiseConv2dNativeBackpropInput,Ql as Diag,la as Dilation2D,Rc as Dilation2DBackpropFilter,$c as Dilation2DBackpropInput,gb as ENV,Jg as EarlyStopping,ni as Elu,eu as EluGrad,zh as Environment,ii as Equal,si as Erf,en as Exp,as as ExpandDims,ai as Expm1,tu as FFT,ua as Fill,li as FlipLeftRight,tn as Floor,rn as FloorDiv,Fc as FromPixels,on as FusedBatchNorm,_s as FusedConv2D,ws as FusedDepthwiseConv2D,ui as GatherNd,ls as GatherV2,fx as GraphModel,ci as Greater,nn as GreaterEqual,Rg as History,ru as IFFT,us as Identity,ou as Imag,Et as InputSpec,pi as IsFinite,mi as IsInf,fi as IsNan,Ws as KernelBackend,ca as LRN,su as LRNGrad,kf as LayerVariable,vo as LayersModel,sn as LeakyRelu,di as Less,hi as LessEqual,nu as LinSpace,an as Log,gi as Log1p,_b as LogSoftmax,xi as LogicalAnd,Za as LogicalNot,Ja as LogicalOr,ln as Max,cn as MaxPool,pa as MaxPool3D,au as MaxPool3DGrad,iu as MaxPoolGrad,lu as MaxPoolWithArgmax,un as Maximum,pn as Mean,mn as Min,fn as Minimum,ma as MirrorPad,yi as Mod,sp as MomentumOptimizer,uu as Multinomial,dn as Multiply,cs as Neg,_i as NonMaxSuppressionV3,wi as NonMaxSuppressionV4,ki as NonMaxSuppressionV5,bi as NotEqual,PI as OP_SCOPE_SUFFIX,hn as OneHot,ps as OnesLike,Fr as Optimizer,ms as Pack,gn as PadV2,p3 as Pool,xn as Pow,yn as Prelu,vi as Prod,ip as RMSPropOptimizer,ao as RNN,fa as Range,Ib as Rank,cu as Real,Qo as RealDiv,Ci as Reciprocal,Gt as Reduction,bn as Relu,wn as Relu6,fs as Reshape,_n as ResizeBilinear,mu as ResizeBilinearGrad,da as ResizeNearestNeighbor,pu as ResizeNearestNeighborGrad,kn as Reverse,Ri as RotateWithOffset,vn as Round,Cn as Rsqrt,ll as SGDOptimizer,Ii as ScatterNd,ds as Select,Ni as Selu,Hi as Sequential,Nn as Sigmoid,Ti as Sign,In as Sin,Si as Sinh,hs as Slice,En as Softmax,Ei as Softplus,ha as SpaceToBatchND,fu as SparseToDense,gs as SplitV,Sn as Sqrt,ga as Square,An as SquaredDifference,Do as Step,Ai as StridedSlice,Dn as Sub,Tn as Sum,Lr as SymbolicTensor,Di as Tan,$n as Tanh,Ve as Tensor,ct as TensorBuffer,yo as Tile,$i as TopK,Rn as Transpose,du as Unique,xs as Unpack,xa as UnsortedSegmentSum,tl as Variable,ys as ZerosLike,bs as _FusedMatMul,Tt as abs,vm as acos,Cm as acosh,Q as add,t_ as addN,_u as all,nl as any,sl as argMax,Im as argMin,Nm as asin,Sm as asinh,Tm as atan,Em as atan2,Am as atanh,va as avgPool,Dm as avgPool3d,e_ as backend,N as backend_util,uG as basicLSTMCell,On as batchNorm,s_ as batchNorm2d,i_ as batchNorm3d,a_ as batchNorm4d,Ca as batchToSpaceND,l_ as bincount,xU as booleanMaskAsync,il as broadcastTo,Yh as browser,Ce as buffer,E1 as callbacks,oe as cast,$m as ceil,nr as clipByValue,$o as clone,bo as complex,Je as concat,u_ as concat1d,c_ as concat2d,p_ as concat3d,m_ as concat4d,nw as constraints,vu as conv1d,jr as conv2d,Cu as conv2dTranspose,Rm as conv3d,AG as conv3dTranspose,d3 as copyRegisteredKernels,Ia as cos,Iu as cosh,nf as cosineWindow,Nu as cumsum,Hr as customGrad,$k as data,f_ as denseBincount,rg as deprecationWarn,Fm as depthToSpace,Cs as depthwiseConv2d,$1 as deregisterOp,Bc as device_util,LG as diag,Om as dilation2d,kV as disableDeprecationWarnings,Te as dispose,vV as disposeVariables,de as div,Pm as divNoNan,d_ as dot,B_ as dropout,Is as elu,wV as enableDebugMode,_V as enableProdMode,V_ as enclosingPowerOfTwo,vs as engine,G as env,_o as equal,Mm as erf,Xt as exp,sr as expandDims,Lm as expm1,Kc as eye,Ra as fft,Na as fill,EV as findBackend,AV as findBackendFactory,Ns as floor,bu as floorDiv,zn as fused,Pn as gather,z_ as gatherND,Zh as gather_util,SV as getBackend,Bh as getGradient,Pc as getKernel,xm as getKernelsForBackend,fW as grad,dW as grads,Qt as greater,to as greaterEqual,zi as ifft,Su as imag,Ds as image,NU as inTopKAsync,uw as initializers,Kg as input,vr as io,zu as irfft,h_ as isFinite,g_ as isInf,x_ as isNaN,At as keep,Sr as kernel_impls,jw as layers,Sa as leakyRelu,Tu as less,Oo as lessEqual,H_ as linalg,y_ as linspace,iE as loadGraphModel,g1 as loadLayersModel,zm as localResponseNormalization,ir as log,Eu as log1p,b_ as logSigmoid,Au as logSoftmax,Vm as logSumExp,fr as logicalAnd,Ta as logicalNot,Du as logicalOr,v_ as logicalXor,yj as losses,We as matMul,fN as math,ar as max,Ea as maxPool,Gm as maxPool3d,C_ as maxPoolWithArgmax,qr as maximum,ht as mean,jc as memory,Xw as metrics,Li as min,Ts as minimum,Wm as mirrorPad,Um as mod,d1 as model,Yw as models,Xc as moments,_U as movingAverage,O as mul,WW as multiRNNCell,I_ as multinomial,je as neg,sf as nextFrame,Gu as norm,Ln as notEqual,ks as oneHot,Cr as ones,er as onesLike,S as op,KW as outerProduct,$r as pad,ZW as pad1d,QW as pad2d,t4 as pad3d,o4 as pad4d,N_ as pool,Rr as pow,Da as prelu,Wb as print,$u as prod,CV as profile,m4 as rand,_4 as randomGamma,ug as randomNormal,Es as randomUniform,Zc as range,NV as ready,al as real,Hm as reciprocal,yu as registerBackend,x1 as registerCallbackConstructor,kb as registerGradient,Qa as registerKernel,D1 as registerOp,Zw as regularizers,Ir as relu,Fu as relu6,TV as removeBackend,L as reshape,qt as reverse,E4 as reverse1d,D4 as reverse2d,R4 as reverse3d,O4 as reverse4d,Fa as rfft,qm as round,Ou as rsqrt,le as scalar,L_ as scatterND,Jh as scatter_util,Pu as selu,Km as separableConv2d,h1 as sequential,J as serialization,EN as setBackend,DV as setPlatform,Nee as setWasmPath,See as setWasmPaths,O_ as setdiff1dAsync,Ur as sigmoid,Xm as sign,xj as signal,Mu as sin,Lu as sinh,Fe as slice,Ym as slice1d,cg as slice2d,Zm as slice3d,Jc as slice4d,or as slice_util,$a as softmax,Ss as softplus,Aa as spaceToBatchND,of as sparseToDense,gj as spectral,lr as split,xt as sqrt,Pe as square,Bu as squaredDifference,wo as squeeze,Bt as stack,As as step,Jm as stridedSlice,ue as sub,ye as sum,hu as sumOutType,Qm as tan,Mi as tanh,Dr as tensor,Vt as tensor1d,Bi as tensor2d,qb as tensor3d,aU as tensor4d,lU as tensor5d,uU as tensor6d,Fn as tensor_util,NN as test_util,V as tidy,Fo as tile,IV as time,ef as topk,ul as train,Ue as transpose,Vu as truncatedNormal,Qc as unique,f3 as unregisterGradient,m3 as unregisterKernel,tf as unsortedSegmentSum,ur as unstack,mr as upcastType,y as util,hW as valueAndGrad,gW as valueAndGrads,P_ as variable,ig as variableGrads,gJ as version,dx as version_converter,Qb as version_core,hl as version_layers,Tee as version_wasm,Dt as where,rf as whereAsync,gt as zeros,Ie 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 See the LICENSE file. */
|
|
//# sourceMappingURL=tfjs.esm.js.map
|