/* Face-API homepage: author: ' */ var YB=Object.create,Lh=Object.defineProperty,ZB=Object.getPrototypeOf,JB=Object.prototype.hasOwnProperty,QB=Object.getOwnPropertyNames,e3=Object.getOwnPropertyDescriptor;var AI=r=>Lh(r,"__esModule",{value:!0});var Ur=(r,e)=>()=>(e||(e={exports:{}},r(e.exports,e)),e.exports),et=(r,e)=>{AI(r);for(var t in e)Lh(r,t,{get:e[t],enumerable:!0})},t3=(r,e,t)=>{if(AI(r),e&&typeof e=="object"||typeof e=="function")for(let o of QB(e))!JB.call(r,o)&&o!=="default"&&Lh(r,o,{get:()=>e[o],enumerable:!(t=e3(e,o))||t.enumerable});return r},Ec=r=>r&&r.__esModule?r:t3(Lh(r!=null?YB(ZB(r)):{},"default",{value:r,enumerable:!0}),r);var hN=Ur(()=>{});var KN=Ur((HN,I_)=>{(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>>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})(HN,typeof I_=="object"&&I_,typeof define=="function"&&define)});var YN=Ur((XN,N_)=>{(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>>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})(XN,typeof N_=="object"&&N_,typeof define=="function"&&define)});var JN=Ur((ZN,S_)=>{(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>>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})(ZN,typeof S_=="object"&&S_,typeof define=="function"&&define)});var eS=Ur((QN,T_)=>{(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;p0;--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})(QN,typeof T_=="object"&&T_,typeof define=="function"&&define)});var rS=Ur((tS,E_)=>{(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=[],y=128;for(c===(c|0)?(m=c,c=null):(c=c+"\0",m=0,y=Math.max(y,c.length)),f=0,d=-32;d>>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})(tS,typeof E_=="object"&&E_,typeof define=="function"&&define)});var nS=Ur((oS,A_)=>{(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>>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})(oS,typeof A_=="object"&&A_,typeof define=="function"&&define)});var sS=Ur(()=>{});var iS=Ur((sye,ig)=>{(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,k){var $=[];w=w==!0?{entropy:!0}:w||{};var T=g(h(w.entropy?[_,b(r)]:_==null?y():_,3),$),F=new f($),M=function(){for(var L=F.g(n),G=i,H=0;L=u;)L/=2,G/=2,H>>>=1;return(L+H)/G};return M.int32=function(){return F.g(4)|0},M.quick=function(){return F.g(4)/4294967296},M.double=M,g(b(F.S),r),(w.pass||k||function(L,G,H,U){return U&&(U.S&&d(U,F),L.state=function(){return d(F,{})}),H?(e[a]=L,G):L})(M,T,"global"in w?w.global:this==e,w.state)}e["seed"+a]=m;function f(_){var w,k=_.length,$=this,T=0,F=$.i=$.j=0,M=$.S=[];for(k||(_=[k++]);T{var k4=KN(),C4=YN(),I4=JN(),N4=eS(),S4=rS(),T4=nS(),Pu=iS();Pu.alea=k4;Pu.xor128=C4;Pu.xorwow=I4;Pu.xorshift7=N4;Pu.xor4096=S4;Pu.tychei=T4;aS.exports=Pu});var HE=Ur(()=>{});var Xp=Ur(()=>{});var Sz=Ur(()=>{});var Tz=Ur(()=>{});var Ez=Ur((Xx,dI)=>{var hI=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 Q.buffer!=nt&&vr(Q.buffer),ho}function o(){return Q.buffer!=nt&&vr(Q.buffer),Jt}function n(){return Q.buffer!=nt&&vr(Q.buffer),jo}function s(){return Q.buffer!=nt&&vr(Q.buffer),Gr}function a(){return Q.buffer!=nt&&vr(Q.buffer),Eo}var i=typeof e!="undefined"?e:{},l=void 0,u={},c;for(c in i)i.hasOwnProperty(c)&&(u[c]=i[c]);var p=[],m="./this.program",f=function(I,D){throw D},d=!1,h=!1,g=!1,y=!1;d=typeof window=="object",h=typeof importScripts=="function",g=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",y=!d&&!g&&!h;var b=i.ENVIRONMENT_IS_PTHREAD||!1;b&&(nt=i.buffer,Do=i.DYNAMIC_BASE,Fl=i.DYNAMICTOP_PTR);var _="";function w(I){return i.locateFile?i.locateFile(I,_):_+I}var k,$,T,F,M,L;if(g){h?_=Xp().dirname(_)+"/":_=__dirname+"/",k=function(D,P){return M||(M=require("fs")),L||(L=Xp()),D=L.normalize(D),M.readFileSync(D,P?null:"utf8")},T=function(D){var P=k(D,!0);return P.buffer||(P=new Uint8Array(P)),ye(P.buffer),P},process.argv.length>1&&(m=process.argv[1].replace(/\\/g,"/")),p=process.argv.slice(2),process.on("uncaughtException",function(I){if(!(I instanceof TI))throw I}),process.on("unhandledRejection",ea),f=function(I){process.exit(I)},i.inspect=function(){return"[Emscripten Module object]"};var G;try{G=Sz()}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=G.Worker}else y?(typeof read!="undefined"&&(k=function(D){return read(D)}),T=function(D){var P;return typeof readbuffer=="function"?new Uint8Array(readbuffer(D)):(P=read(D,"binary"),ye(typeof P=="object"),P)},typeof scriptArgs!="undefined"?p=scriptArgs:typeof arguments!="undefined"&&(p=arguments),typeof quit=="function"&&(f=function(I){quit(I)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(d||h)&&(h?_=self.location.href:document.currentScript&&(_=document.currentScript.src),l&&(_=l),_.indexOf("blob:")!==0?_=_.substr(0,_.lastIndexOf("/")+1):_="",g?(k=function(D,P){return M||(M=require("fs")),L||(L=Xp()),D=L.normalize(D),M.readFileSync(D,P?null:"utf8")},T=function(D){var P=k(D,!0);return P.buffer||(P=new Uint8Array(P)),ye(P.buffer),P}):(k=function(D){var P=new XMLHttpRequest;return P.open("GET",D,!1),P.send(null),P.responseText},h&&(T=function(D){var P=new XMLHttpRequest;return P.open("GET",D,!1),P.responseType="arraybuffer",P.send(null),new Uint8Array(P.response)}),$=function(D,P,j){var de=new XMLHttpRequest;de.open("GET",D,!0),de.responseType="arraybuffer",de.onload=function(){if(de.status==200||de.status==0&&de.response){P(de.response);return}j()},de.onerror=j,de.send(null)}),F=function(I){document.title=I});g&&typeof performance=="undefined"&&(performance=Tz().performance);var H=i.print||console.log.bind(console),U=i.printErr||console.warn.bind(console);for(c in u)u.hasOwnProperty(c)&&(i[c]=u[c]);u=null,i.arguments&&(p=i.arguments),i.thisProgram&&(m=i.thisProgram),i.quit&&(f=i.quit);var Z=Atomics.load,K=Atomics.store,X=Atomics.compareExchange,oe;i.wasmBinary&&(oe=i.wasmBinary);var J;i.noExitRuntime&&(J=i.noExitRuntime),typeof WebAssembly!="object"&&U("no native wasm support detected");var Q,ie=new WebAssembly.Table({initial:169,maximum:169+0,element:"anyfunc"}),ae,ue=0,le=0,ge=!1,we=0;function ye(I,D){I||ea("Assertion failed: "+D)}function ke(I){var D=i["_"+I];return ye(D,"Cannot call unknown function "+I+", make sure it is exported"),D}function Ee(I,D,P,j,de){var xe={string:function(yo){var Za=0;if(yo!=null&&yo!==0){var um=(yo.length<<2)+1;Za=Ic(um),gt(yo,Za,um)}return Za},array:function(yo){var Za=Ic(yo.length);return xt(yo,Za),Za}};function he(yo){return D==="string"?ze(yo):D==="boolean"?Boolean(yo):yo}var Te=ke(I),ft=[],mr=0;if(j)for(var Rr=0;Rr=j);){var xe=I[D++];if(!xe)return de;if(!(xe&128)){de+=String.fromCharCode(xe);continue}var he=I[D++]&63;if((xe&224)==192){de+=String.fromCharCode((xe&31)<<6|he);continue}var Te=I[D++]&63;if((xe&240)==224?xe=(xe&15)<<12|he<<6|Te:xe=(xe&7)<<18|he<<12|Te<<6|I[D++]&63,xe<65536)de+=String.fromCharCode(xe);else{var ft=xe-65536;de+=String.fromCharCode(55296|ft>>10,56320|ft&1023)}}return de}function ze(I,D){return I?Pe(o(),I,D):""}function mt(I,D,P,j){if(!(j>0))return 0;for(var de=P,xe=P+j-1,he=0;he=55296&&Te<=57343){var ft=I.charCodeAt(++he);Te=65536+((Te&1023)<<10)|ft&1023}if(Te<=127){if(P>=xe)break;D[P++]=Te}else if(Te<=2047){if(P+1>=xe)break;D[P++]=192|Te>>6,D[P++]=128|Te&63}else if(Te<=65535){if(P+2>=xe)break;D[P++]=224|Te>>12,D[P++]=128|Te>>6&63,D[P++]=128|Te&63}else{if(P+3>=xe)break;D[P++]=240|Te>>18,D[P++]=128|Te>>12&63,D[P++]=128|Te>>6&63,D[P++]=128|Te&63}}return D[P]=0,P-de}function gt(I,D,P){return mt(I,o(),D,P)}function Ct(I){for(var D=0,P=0;P=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 xt(I,D){t().set(I,D)}var yt=65536;function It(I,D){return I%D>0&&(I+=D-I%D),I}var nt,ho,Jt,go,$r,jo,Gr,To,Eo;function vr(I){nt=I,i.HEAP8=ho=new Int8Array(I),i.HEAP16=go=new Int16Array(I),i.HEAP32=jo=new Int32Array(I),i.HEAPU8=Jt=new Uint8Array(I),i.HEAPU16=$r=new Uint16Array(I),i.HEAPU32=Gr=new Uint32Array(I),i.HEAPF32=To=new Float32Array(I),i.HEAPF64=Eo=new Float64Array(I)}var Ao=5256464,ro=Ao,Zi=13584,Do=5256464,Fl=12656,Ji=i.INITIAL_MEMORY||16777216;if(b)Q=i.wasmMemory,nt=i.buffer;else if(i.wasmMemory)Q=i.wasmMemory;else if(Q=new WebAssembly.Memory({initial:Ji/yt,maximum:2147483648/yt,shared:!0}),!(Q.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"),g&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");Q&&(nt=Q.buffer),Ji=nt.byteLength,vr(nt),b||(n()[Fl>>2]=Do);function os(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 Ol=[],dh=[],hh=[],gh=[],Yp=[],$o=!1;b&&($o=!0);function xh(){if(!b){if(i.preRun)for(typeof i.preRun=="function"&&(i.preRun=[i.preRun]);i.preRun.length;)Pl(i.preRun.shift());os(Ol)}}function Qx(){$o=!0,os(dh)}function ey(){b||os(hh)}function ty(){if(!b){if(i.postRun)for(typeof i.postRun=="function"&&(i.postRun=[i.postRun]);i.postRun.length;)yc(i.postRun.shift());os(Yp)}}function Pl(I){Ol.unshift(I)}function yc(I){Yp.unshift(I)}var ry=Math.ceil,oy=Math.floor,Qi=0,Zp=null,Ml=null;function ny(I){ye(!b,"addRunDependency cannot be used in a pthread worker"),Qi++,i.monitorRunDependencies&&i.monitorRunDependencies(Qi)}function yh(I){if(Qi--,i.monitorRunDependencies&&i.monitorRunDependencies(Qi),Qi==0&&(Zp!==null&&(clearInterval(Zp),Zp=null),Ml)){var D=Ml;Ml=null,D()}}i.preloadedImages={},i.preloadedAudios={};function ea(I){throw i.onAbort&&i.onAbort(I),b&&console.error("Pthread aborting at "+new Error().stack),I+="",H(I),U(I),ge=!0,we=1,I="abort("+I+"). Build with -s ASSERTIONS=1 for more info.",new WebAssembly.RuntimeError(I)}function bh(I,D){return String.prototype.startsWith?I.startsWith(D):I.indexOf(D)===0}var sy="data:application/octet-stream;base64,";function _h(I){return bh(I,sy)}var iy="file://";function wh(I){return bh(I,iy)}var qo="tfjs-backend-wasm-threaded-simd.wasm";_h(qo)||(qo=w(qo));function vh(){try{if(oe)return new Uint8Array(oe);if(T)return T(qo);throw"both async and sync fetching of the wasm failed"}catch(I){ea(I)}}function ay(){return!oe&&(d||h)&&typeof fetch=="function"&&!wh(qo)?fetch(qo,{credentials:"same-origin"}).then(function(I){if(!I.ok)throw"failed to load wasm binary file at '"+qo+"'";return I.arrayBuffer()}).catch(function(){return vh()}):new Promise(function(I,D){I(vh())})}function ly(){var I={a:Rh};function D(he,Te){var ft=he.exports;if(i.asm=ft,ae=Te,!b){var mr=ve.unusedWorkers.length;ve.unusedWorkers.forEach(function(Rr){ve.loadWasmModuleToWorker(Rr,function(){--mr||yh("wasm-instantiate")})})}}b||ny("wasm-instantiate");function P(he){D(he.instance,he.module)}function j(he){return ay().then(function(Te){return WebAssembly.instantiate(Te,I)}).then(he,function(Te){U("failed to asynchronously prepare wasm: "+Te),ea(Te)})}function de(){if(!oe&&typeof WebAssembly.instantiateStreaming=="function"&&!_h(qo)&&!wh(qo)&&typeof fetch=="function")fetch(qo,{credentials:"same-origin"}).then(function(he){var Te=WebAssembly.instantiateStreaming(he,I);return Te.then(P,function(ft){U("wasm streaming compile failed: "+ft),U("falling back to ArrayBuffer instantiation"),j(P)})});else return j(P)}if(i.instantiateWasm)try{var xe=i.instantiateWasm(I,D);return xe}catch(he){return U("Module.instantiateWasm callback failed with error: "+he),!1}return de(),{}}var uy={};function cy(){ve.initRuntime()}b||dh.push({func:function(){em()}});var kh=0,Ch=0,Ih=0;function bc(I,D,P){I=I|0,D=D|0,P=P|0,kh=I,Ih=D,Ch=P}i.__register_pthread_ptr=bc;var Jp={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},_c=13568;function wc(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(),_c>>2),j=0;if(P==I){var de=Atomics.compareExchange(n(),_c>>2,P,0);if(de==P&&(--D,j=1,D<=0))return 1}var xe=Atomics.notify(n(),I>>2,D);if(xe>=0)return xe+j;throw"Atomics.notify returned an unexpected value "+xe}i._emscripten_futex_wake=wc;function py(I){if(b)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=ve.pthreads[I];D.worker.terminate(),ve.freeThreadData(D),ve.runningWorkers.splice(ve.runningWorkers.indexOf(D.worker),1),D.worker.pthread=void 0}function my(I){if(b)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=ve.pthreads[I];D.worker.postMessage({cmd:"cancel"})}function fy(I){if(b)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=ve.pthreads[I];if(D){var P=D.worker;ve.returnWorkerToPool(P)}}var ve={MAIN_THREAD_ID:1,mainThreadInfo:{schedPolicy:0,schedPrio:0},unusedWorkers:[],runningWorkers:[],initRuntime:function(){bc(ve.mainThreadBlock,!h,1),CI(ve.mainThreadBlock)},initMainThreadBlock:function(){for(var I=8,D=0;D>2]=ve.mainThreadBlock;var P=ve.mainThreadBlock+156;n()[P>>2]=P;for(var j=13056,D=0;D<128;++D)s()[j/4+D]=0;Atomics.store(s(),ve.mainThreadBlock+104>>2,j),Atomics.store(s(),ve.mainThreadBlock+40>>2,ve.mainThreadBlock),Atomics.store(s(),ve.mainThreadBlock+44>>2,42)},initWorker:function(){},pthreads:{},exitHandlers:null,setThreadStatus:function(){},runExitHandlers:function(){if(ve.exitHandlers!==null){for(;ve.exitHandlers.length>0;)ve.exitHandlers.pop()();ve.exitHandlers=null}b&&ue&&kI()},threadExit:function(I){var D=Vs();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),ve.runExitHandlers(),wc(D+0,2147483647),bc(0,0,0),ue=0,b&&postMessage({cmd:"exit"}))},threadCancel:function(){ve.runExitHandlers(),Atomics.store(s(),ue+4>>2,-1),Atomics.store(s(),ue+0>>2,1),wc(ue+0,2147483647),ue=le=0,bc(0,0,0),postMessage({cmd:"cancelDone"})},terminateAllThreads:function(){for(var I in ve.pthreads){var D=ve.pthreads[I];D&&D.worker&&ve.returnWorkerToPool(D.worker)}ve.pthreads={};for(var P=0;P>2];n()[I.threadInfoStruct+104>>2]=0,sm(D),sm(I.threadInfoStruct)}I.threadInfoStruct=0,I.allocatedOwnStack&&I.stackBase&&sm(I.stackBase),I.stackBase=0,I.worker&&(I.worker.pthread=null)}},returnWorkerToPool:function(I){delete ve.pthreads[I.pthread.thread],ve.unusedWorkers.push(I),ve.runningWorkers.splice(ve.runningWorkers.indexOf(I),1),ve.freeThreadData(I.pthread),I.pthread=void 0},receiveObjectTransfer:function(I){},loadWasmModuleToWorker:function(I,D){I.onmessage=function(P){var j=P.data,de=j.cmd;if(I.pthread&&(ve.currentProxiedOperationCallerThread=I.pthread.threadInfoStruct),j.targetThread&&j.targetThread!=Vs()){var xe=ve.pthreads[j.targetThread];xe?xe.worker.postMessage(P.data,j.transferList):console.error('Internal error! Worker sent a message "'+de+'" to target pthread '+j.targetThread+", but that thread no longer exists!"),ve.currentProxiedOperationCallerThread=void 0;return}if(de==="processQueuedMainThreadWork")tb();else if(de==="spawnThread")Dh(P.data);else if(de==="cleanupThread")fy(j.thread);else if(de==="killThread")py(j.thread);else if(de==="cancelThread")my(j.thread);else if(de==="loaded")I.loaded=!0,D&&D(I),I.runPthread&&(I.runPthread(),delete I.runPthread);else if(de==="print")H("Thread "+j.threadId+": "+j.text);else if(de==="printErr")U("Thread "+j.threadId+": "+j.text);else if(de==="alert")alert("Thread "+j.threadId+": "+j.text);else if(de==="exit"){var he=I.pthread&&Atomics.load(s(),I.pthread.thread+68>>2);he&&ve.returnWorkerToPool(I)}else de==="cancelDone"?ve.returnWorkerToPool(I):de==="objectTransfer"?ve.receiveObjectTransfer(P.data):P.data.target==="setimmediate"?I.postMessage(P.data):U("worker sent an unknown command "+de);ve.currentProxiedOperationCallerThread=void 0},I.onerror=function(P){U("pthread sent an error! "+P.filename+":"+P.lineno+": "+P.message)},g&&(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||l,wasmMemory:Q,wasmModule:ae,DYNAMIC_BASE:Do,DYNAMICTOP_PTR:Fl})},allocateUnusedWorker:function(){var I=w("tfjs-backend-wasm-threaded-simd.worker.js");ve.unusedWorkers.push(new Worker(I))},getNewWorker:function(){return ve.unusedWorkers.length==0&&(ve.allocateUnusedWorker(),ve.loadWasmModuleToWorker(ve.unusedWorkers[0])),ve.unusedWorkers.length>0?ve.unusedWorkers.pop():null},busySpinWait:function(I){for(var D=performance.now()+I;performance.now()>2]=I,I}function by(I,D){if(b)return Ka(1,1,I,D);gh.unshift({func:I,arg:D})}function _y(I,D){if(I==D)postMessage({cmd:"processQueuedMainThreadWork"});else if(b)postMessage({targetThread:I,cmd:"processThreadQueue"});else{var P=ve.pthreads[I],j=P&&P.worker;if(!j)return;j.postMessage({cmd:"processThreadQueue"})}return 1}function wy(){ea()}function vy(I,D){I=I|0,D=D|0}function ky(I,D,P){if(I<=0||I>t().length||I&!0)return-28;if(h){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 de=Atomics.load(n(),I>>2);if(D!=de)return-6;var xe=performance.now(),he=xe+P;Atomics.store(n(),_c>>2,I);for(var Te=I;I==Te;){if(xe=performance.now(),xe>he)return-73;tb(),I=Atomics.load(n(),_c>>2)}return 0}}function Cy(){return Ih|0}function Iy(){return Ch|0}function Ny(I,D,P){o().copyWithin(I,D,D+P)}function Sy(){return navigator.hardwareConcurrency}function Ka(I,D){for(var P=arguments.length-2,j=im(),de=Ic(P*8),xe=de>>3,he=0;he>3]),D+=8):(D=D+3&~3,P.push(n()[D>>2]),D+=4);return P}function Ty(I,D,P){zl.length=D;for(var j=P>>3,de=0;de>>16),vr(Q.buffer),1}catch(D){}}function Dy(I){I=I>>>0;var D=Ey();if(I<=D)return!1;var P=65536,j=2147483648;if(I>j)return!1;for(var de=16777216,xe=1;xe<=4;xe*=2){var he=D*(1+.2/xe);he=Math.min(he,I+100663296);var Te=Math.min(j,It(Math.max(de,I,he),P)),ft=Ay(Te);if(ft)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||(gh.push(Ze.removeAllEventListeners),Ze.removeEventListenersRegistered=!0)},deferredCalls:[],deferCall:function(I,D,P){function j(he,Te){if(he.length!=Te.length)return!1;for(var ft in he)if(he[ft]!=Te[ft])return!1;return!0}for(var de in Ze.deferredCalls){var xe=Ze.deferredCalls[de];if(xe.targetFunction==I&&j(xe.argsList,P))return}Ze.deferredCalls.push({targetFunction:I,precedence:D,argsList:P}),Ze.deferredCalls.sort(function(he,Te){return he.precedence>2]=P,n()[he+4>>2]=j,n()[he+8>>2]=de,rb(I,637534208,D,j,he),Nc(xe)},getTargetThreadForEventCallback:function(I){switch(I){case 1:return 0;case 2:return ve.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 $y(I){var D=Ct(I)+1,P=nm(D);return gt(I,P,D),P}function Ry(I,D,P,j){var de=im(),xe=Ic(12),he=0;D&&(he=$y(D)),n()[xe>>2]=he,n()[xe+4>>2]=P,n()[xe+8>>2]=j,rb(I,657457152,0,he,xe),Nc(de)}function Fy(I,D,P,j){D=D?ze(D):"",Ry(I,D,P,j)}function Oy(I){return I>2?ze(I):I}var Py=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];function My(I){I=Oy(I);var D=Py[I]||(typeof document!="undefined"?document.querySelector(I):void 0);return D}function Qp(I){return My(I)}function Nh(I,D,P){var j=Qp(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 de=!1;if(j.GLctxObject&&j.GLctxObject.GLctx){var xe=j.GLctxObject.GLctx.getParameter(2978);de=xe[0]===0&&xe[1]===0&&xe[2]===j.width&&xe[3]===j.height}j.width=D,j.height=P,de&&j.GLctxObject.GLctx.viewport(0,0,D,P)}else if(j.canvasSharedPtr){var he=n()[j.canvasSharedPtr+8>>2];return Fy(he,I,D,P),1}else return-4;return 0}function Sh(I,D,P){return b?Ka(2,1,I,D,P):Nh(I,D,P)}function Ly(I,D,P){var j=Qp(I);return j?Nh(I,D,P):Sh(I,D,P)}function zy(I){I=I|0}function By(I,D){I=I|0,D=D|0}function Vy(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,de,xe){D.drawArraysInstancedANGLE(P,j,de,xe)},I.drawElementsInstanced=function(P,j,de,xe,he){D.drawElementsInstancedANGLE(P,j,de,xe,he)},1}function Wy(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 Gy(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>2]:-1;de+=ze(n()[P+xe*4>>2],he<0?void 0:he)}return de},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=nm(8);n()[P+4>>2]=Vs();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=Xa=rt.currentContext&&rt.currentContext.GLctx,!(I&&!Xa)},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),sm(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;Vy(D),Wy(D),Gy(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(de){P.indexOf(de)!=-1&&D.getExtension(de)})}},populateUniformTable:function(I){for(var D=rt.programs[I],P=rt.programInfos[I]={uniforms:{},maxUniformLength:0,maxAttributeLength:-1,maxUniformBlockNameLength:-1},j=P.uniforms,de=Xa.getProgramParameter(D,35718),xe=0;xe>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 de=n()[j+(24>>2)];P.powerPreference=Uy[de],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 xe=Qp(I);if(!xe)return-4;if(P.explicitSwapControl)return-1;var he=rt.createContext(xe,P);return he}function qy(I,D){return jy(I,D)}var Bl={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 de=I[j];de==="."?I.splice(j,1):de===".."?(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=Bl.normalizeArray(I.split("/").filter(function(j){return!!j}),!D).join("/"),!I&&!D&&(I="."),I&&P&&(I+="/"),(D?"/":"")+I},dirname:function(I){var D=Bl.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 Bl.splitPath(I)[3]},join:function(){var I=Array.prototype.slice.call(arguments,0);return Bl.normalize(I.join("/"))},join2:function(I,D){return Bl.normalize(I+"/"+D)}},kc={mappings:{},buffers:[null,[],[]],printChar:function(I,D){var P=kc.buffers[I];D===0||D===10?((I===1?H:U)(Pe(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=ze(I);return D},get64:function(I,D){return I}};function Th(I){return b?Ka(3,1,I):0}function Eh(I,D,P,j,de){if(b)return Ka(4,1,I,D,P,j,de)}function Ah(I,D,P,j){if(b)return Ka(5,1,I,D,P,j);for(var de=0,xe=0;xe>2],Te=n()[D+(xe*8+4)>>2],ft=0;ft>2]=de,0}function Hy(I){var D=ve.exitHandlers.pop();I&&D()}function Ky(I,D){ve.exitHandlers===null&&(ve.exitHandlers=[]),ve.exitHandlers.push(function(){SI(I,D)})}function Dh(I){if(b)throw"Internal Error! _spawn_thread() can only ever be called from main application thread!";var D=ve.getNewWorker();if(D.pthread!==void 0)throw"Internal error!";if(!I.pthread_ptr)throw"Internal error, no pthread ptr!";ve.runningWorkers.push(D);for(var P=nm(128*4),j=0;j<128;++j)n()[P+j*4>>2]=0;var de=I.stackBase+I.stackSize,xe=ve.pthreads[I.pthread_ptr]={worker:D,stackBase:I.stackBase,stackSize:I.stackSize,allocatedOwnStack:I.allocatedOwnStack,thread:I.pthread_ptr,threadInfoStruct:I.pthread_ptr},he=xe.threadInfoStruct>>2;Atomics.store(s(),he+(0>>2),0),Atomics.store(s(),he+(4>>2),0),Atomics.store(s(),he+(8>>2),0),Atomics.store(s(),he+(68>>2),I.detached),Atomics.store(s(),he+(104>>2),P),Atomics.store(s(),he+(48>>2),0),Atomics.store(s(),he+(40>>2),xe.threadInfoStruct),Atomics.store(s(),he+(44>>2),42),Atomics.store(s(),he+(108>>2),I.stackSize),Atomics.store(s(),he+(84>>2),I.stackSize),Atomics.store(s(),he+(80>>2),de),Atomics.store(s(),he+(108+8>>2),de),Atomics.store(s(),he+(108+12>>2),I.detached),Atomics.store(s(),he+(108+20>>2),I.schedPolicy),Atomics.store(s(),he+(108+24>>2),I.schedPrio);var Te=_I(),ft=Te+40;Atomics.store(s(),he+(176>>2),ft),D.pthread=xe;var mr={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(){mr.time=performance.now(),D.postMessage(mr,I.transferList)},D.loaded&&(D.runPthread(),delete D.runPthread)}function Xy(I,D,P){if(!D&&!P)return Jp.EINVAL;if(!I)return U("pthread_getschedparam called with a null thread pointer!"),Jp.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!"),Jp.ESRCH;var de=Atomics.load(s(),I+108+20>>2),xe=Atomics.load(s(),I+108+24>>2);return D&&(n()[D>>2]=de),P&&(n()[P>>2]=xe),0}function Vs(){return kh|0}i._pthread_self=Vs;function Yy(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 de=[],xe=0;if(b&&(de.length===0||xe))return II(687865856,I,D,P,j);if(xe)return xe;var he=0,Te=0,ft=0,mr=0,Rr=0;if(D){he=n()[D>>2],he+=81920,Te=n()[D+8>>2],ft=n()[D+12>>2]!==0;var Sc=n()[D+16>>2]===0;if(Sc){var lm=n()[D+20>>2],yo=n()[D+24>>2],Za=ve.currentProxiedOperationCallerThread?ve.currentProxiedOperationCallerThread:Vs();Xy(Za,D+20,D+24),mr=n()[D+20>>2],Rr=n()[D+24>>2],n()[D+20>>2]=lm,n()[D+24>>2]=yo}else mr=n()[D+20>>2],Rr=n()[D+24>>2]}else he=2097152;var um=Te==0;um?Te=vI(16,he):(Te-=he,ye(Te>0));for(var Tc=nm(232),nb=0;nb<232>>2;++nb)s()[(Tc>>2)+nb]=0;n()[I>>2]=Tc,n()[Tc+12>>2]=Tc;var EI=Tc+156;n()[EI>>2]=EI;var sb={stackBase:Te,stackSize:he,allocatedOwnStack:um,schedPolicy:mr,schedPrio:Rr,detached:ft,startRoutine:P,pthread_ptr:Tc,parent_pthread_ptr:Vs(),arg:j,transferList:de};return b?(sb.cmd="spawnThread",postMessage(sb,de)):Dh(sb),0}function Zy(I){return I=+I,I>=0?+oy(I+.5):+ry(I-.5)}function $h(I){if(b)return Ka(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 yy(28),-1}b?ve.initWorker():ve.initMainThreadBlock();var Xa;rt.init();var Jy=[null,by,Sh,Th,Eh,Ah,$h],Rh={e:gy,r:xy,w:_y,a:wy,l:vy,d:ky,c:wc,h:Ll,g:Cy,x:Iy,q:Ny,B:Sy,t:Ty,A:Dy,u:Ly,k:zy,s:By,v:qy,m:Th,o:Eh,i:Ah,p:cy,memory:Q||i.wasmMemory,y:Hy,z:Ky,j:Yy,b:Vs,f:Zy,n:$h,table:ie},Cc=ly();i.asm=Cc;var em=i.___wasm_call_ctors=function(){return(em=i.___wasm_call_ctors=i.asm.C).apply(null,arguments)},Vl=i._init=function(){return(Vl=i._init=i.asm.D).apply(null,arguments)},tm=i._register_tensor=function(){return(tm=i._register_tensor=i.asm.E).apply(null,arguments)},Qy=i._dispose_data=function(){return(Qy=i._dispose_data=i.asm.F).apply(null,arguments)},eb=i._dispose=function(){return(eb=i._dispose=i.asm.G).apply(null,arguments)},rm=i._Abs=function(){return(rm=i._Abs=i.asm.H).apply(null,arguments)},Fh=i._Add=function(){return(Fh=i._Add=i.asm.I).apply(null,arguments)},Oh=i._AddN=function(){return(Oh=i._AddN=i.asm.J).apply(null,arguments)},q=i._ArgMax=function(){return(q=i._ArgMax=i.asm.K).apply(null,arguments)},se=i._AvgPool=function(){return(se=i._AvgPool=i.asm.L).apply(null,arguments)},_e=i._BatchMatMul=function(){return(_e=i._BatchMatMul=i.asm.M).apply(null,arguments)},Ke=i._ClipByValue=function(){return(Ke=i._ClipByValue=i.asm.N).apply(null,arguments)},Xe=i._Conv2D=function(){return(Xe=i._Conv2D=i.asm.O).apply(null,arguments)},Kt=i._Conv2DBackpropInput=function(){return(Kt=i._Conv2DBackpropInput=i.asm.P).apply(null,arguments)},lt=i._Cos=function(){return(lt=i._Cos=i.asm.Q).apply(null,arguments)},st=i._CropAndResize=function(){return(st=i._CropAndResize=i.asm.R).apply(null,arguments)},yr=i._Cumsum=function(){return(yr=i._Cumsum=i.asm.S).apply(null,arguments)},ta=i._DepthToSpace=function(){return(ta=i._DepthToSpace=i.asm.T).apply(null,arguments)},ra=i._DepthwiseConv2dNative=function(){return(ra=i._DepthwiseConv2dNative=i.asm.U).apply(null,arguments)},Ph=i._Equal=function(){return(Ph=i._Equal=i.asm.V).apply(null,arguments)},om=i._Exp=function(){return(om=i._Exp=i.asm.W).apply(null,arguments)},xo=i._FlipLeftRight=function(){return(xo=i._FlipLeftRight=i.asm.X).apply(null,arguments)},Ya=i._Floor=function(){return(Ya=i._Floor=i.asm.Y).apply(null,arguments)},Mh=i._FloorDiv=function(){return(Mh=i._FloorDiv=i.asm.Z).apply(null,arguments)},Oz=i._FusedBatchNorm=function(){return(Oz=i._FusedBatchNorm=i.asm._).apply(null,arguments)},Pz=i._FusedConv2D=function(){return(Pz=i._FusedConv2D=i.asm.$).apply(null,arguments)},Mz=i._FusedDepthwiseConv2D=function(){return(Mz=i._FusedDepthwiseConv2D=i.asm.aa).apply(null,arguments)},Lz=i._Gather=function(){return(Lz=i._Gather=i.asm.ba).apply(null,arguments)},zz=i._GatherNd=function(){return(zz=i._GatherNd=i.asm.ca).apply(null,arguments)},Bz=i._Greater=function(){return(Bz=i._Greater=i.asm.da).apply(null,arguments)},Vz=i._GreaterEqual=function(){return(Vz=i._GreaterEqual=i.asm.ea).apply(null,arguments)},Wz=i._LeakyRelu=function(){return(Wz=i._LeakyRelu=i.asm.fa).apply(null,arguments)},Gz=i._Less=function(){return(Gz=i._Less=i.asm.ga).apply(null,arguments)},Uz=i._LessEqual=function(){return(Uz=i._LessEqual=i.asm.ha).apply(null,arguments)},jz=i._Log=function(){return(jz=i._Log=i.asm.ia).apply(null,arguments)},qz=i._LogicalAnd=function(){return(qz=i._LogicalAnd=i.asm.ja).apply(null,arguments)},Hz=i._Max=function(){return(Hz=i._Max=i.asm.ka).apply(null,arguments)},Kz=i._MaxPool=function(){return(Kz=i._MaxPool=i.asm.la).apply(null,arguments)},Xz=i._Maximum=function(){return(Xz=i._Maximum=i.asm.ma).apply(null,arguments)},Yz=i._Mean=function(){return(Yz=i._Mean=i.asm.na).apply(null,arguments)},Zz=i._Min=function(){return(Zz=i._Min=i.asm.oa).apply(null,arguments)},Jz=i._Minimum=function(){return(Jz=i._Minimum=i.asm.pa).apply(null,arguments)},Qz=i._Multiply=function(){return(Qz=i._Multiply=i.asm.qa).apply(null,arguments)},eB=i._Neg=function(){return(eB=i._Neg=i.asm.ra).apply(null,arguments)},tB=i._NonMaxSuppressionV3=function(){return(tB=i._NonMaxSuppressionV3=i.asm.sa).apply(null,arguments)},rB=i._NonMaxSuppressionV4=function(){return(rB=i._NonMaxSuppressionV4=i.asm.ta).apply(null,arguments)},oB=i._NonMaxSuppressionV5=function(){return(oB=i._NonMaxSuppressionV5=i.asm.ua).apply(null,arguments)},nB=i._NotEqual=function(){return(nB=i._NotEqual=i.asm.va).apply(null,arguments)},sB=i._OneHot=function(){return(sB=i._OneHot=i.asm.wa).apply(null,arguments)},iB=i._PadV2=function(){return(iB=i._PadV2=i.asm.xa).apply(null,arguments)},aB=i._Pow=function(){return(aB=i._Pow=i.asm.ya).apply(null,arguments)},lB=i._Prelu=function(){return(lB=i._Prelu=i.asm.za).apply(null,arguments)},uB=i._Prod=function(){return(uB=i._Prod=i.asm.Aa).apply(null,arguments)},cB=i._RealDiv=function(){return(cB=i._RealDiv=i.asm.Ba).apply(null,arguments)},pB=i._Relu=function(){return(pB=i._Relu=i.asm.Ca).apply(null,arguments)},mB=i._Relu6=function(){return(mB=i._Relu6=i.asm.Da).apply(null,arguments)},fB=i._ResizeBilinear=function(){return(fB=i._ResizeBilinear=i.asm.Ea).apply(null,arguments)},dB=i._Reverse=function(){return(dB=i._Reverse=i.asm.Fa).apply(null,arguments)},hB=i._RotateWithOffset=function(){return(hB=i._RotateWithOffset=i.asm.Ga).apply(null,arguments)},gB=i._Round=function(){return(gB=i._Round=i.asm.Ha).apply(null,arguments)},xB=i._Rsqrt=function(){return(xB=i._Rsqrt=i.asm.Ia).apply(null,arguments)},yB=i._ScatterNd=function(){return(yB=i._ScatterNd=i.asm.Ja).apply(null,arguments)},bB=i._SelectV2=function(){return(bB=i._SelectV2=i.asm.Ka).apply(null,arguments)},_B=i._Sigmoid=function(){return(_B=i._Sigmoid=i.asm.La).apply(null,arguments)},wB=i._Sin=function(){return(wB=i._Sin=i.asm.Ma).apply(null,arguments)},vB=i._Softmax=function(){return(vB=i._Softmax=i.asm.Na).apply(null,arguments)},kB=i._Sqrt=function(){return(kB=i._Sqrt=i.asm.Oa).apply(null,arguments)},CB=i._Square=function(){return(CB=i._Square=i.asm.Pa).apply(null,arguments)},IB=i._SquaredDifference=function(){return(IB=i._SquaredDifference=i.asm.Qa).apply(null,arguments)},NB=i._StridedSlice=function(){return(NB=i._StridedSlice=i.asm.Ra).apply(null,arguments)},SB=i._Sub=function(){return(SB=i._Sub=i.asm.Sa).apply(null,arguments)},TB=i._Sum=function(){return(TB=i._Sum=i.asm.Ta).apply(null,arguments)},EB=i._Tanh=function(){return(EB=i._Tanh=i.asm.Ua).apply(null,arguments)},AB=i._Tile=function(){return(AB=i._Tile=i.asm.Va).apply(null,arguments)},DB=i._TopK=function(){return(DB=i._TopK=i.asm.Wa).apply(null,arguments)},$B=i._Transpose=function(){return($B=i._Transpose=i.asm.Xa).apply(null,arguments)},RB=i.__FusedMatMul=function(){return(RB=i.__FusedMatMul=i.asm.Ya).apply(null,arguments)},nm=i._malloc=function(){return(nm=i._malloc=i.asm.Za).apply(null,arguments)},sm=i._free=function(){return(sm=i._free=i.asm._a).apply(null,arguments)},_I=i._emscripten_get_global_libc=function(){return(_I=i._emscripten_get_global_libc=i.asm.$a).apply(null,arguments)},wI=i.___errno_location=function(){return(wI=i.___errno_location=i.asm.ab).apply(null,arguments)},FB=i.___em_js__initPthreadsJS=function(){return(FB=i.___em_js__initPthreadsJS=i.asm.bb).apply(null,arguments)},vI=i._memalign=function(){return(vI=i._memalign=i.asm.cb).apply(null,arguments)},kI=i.___pthread_tsd_run_dtors=function(){return(kI=i.___pthread_tsd_run_dtors=i.asm.db).apply(null,arguments)},tb=i._emscripten_main_thread_process_queued_calls=function(){return(tb=i._emscripten_main_thread_process_queued_calls=i.asm.eb).apply(null,arguments)},OB=i._emscripten_current_thread_process_queued_calls=function(){return(OB=i._emscripten_current_thread_process_queued_calls=i.asm.fb).apply(null,arguments)},CI=i._emscripten_register_main_browser_thread_id=function(){return(CI=i._emscripten_register_main_browser_thread_id=i.asm.gb).apply(null,arguments)},PB=i._emscripten_main_browser_thread_id=function(){return(PB=i._emscripten_main_browser_thread_id=i.asm.hb).apply(null,arguments)},MB=i._emscripten_async_run_in_main_thread=function(){return(MB=i._emscripten_async_run_in_main_thread=i.asm.ib).apply(null,arguments)},LB=i._emscripten_sync_run_in_main_thread=function(){return(LB=i._emscripten_sync_run_in_main_thread=i.asm.jb).apply(null,arguments)},zB=i._emscripten_sync_run_in_main_thread_0=function(){return(zB=i._emscripten_sync_run_in_main_thread_0=i.asm.kb).apply(null,arguments)},BB=i._emscripten_sync_run_in_main_thread_1=function(){return(BB=i._emscripten_sync_run_in_main_thread_1=i.asm.lb).apply(null,arguments)},VB=i._emscripten_sync_run_in_main_thread_2=function(){return(VB=i._emscripten_sync_run_in_main_thread_2=i.asm.mb).apply(null,arguments)},WB=i._emscripten_sync_run_in_main_thread_xprintf_varargs=function(){return(WB=i._emscripten_sync_run_in_main_thread_xprintf_varargs=i.asm.nb).apply(null,arguments)},GB=i._emscripten_sync_run_in_main_thread_3=function(){return(GB=i._emscripten_sync_run_in_main_thread_3=i.asm.ob).apply(null,arguments)},II=i._emscripten_sync_run_in_main_thread_4=function(){return(II=i._emscripten_sync_run_in_main_thread_4=i.asm.pb).apply(null,arguments)},UB=i._emscripten_sync_run_in_main_thread_5=function(){return(UB=i._emscripten_sync_run_in_main_thread_5=i.asm.qb).apply(null,arguments)},jB=i._emscripten_sync_run_in_main_thread_6=function(){return(jB=i._emscripten_sync_run_in_main_thread_6=i.asm.rb).apply(null,arguments)},qB=i._emscripten_sync_run_in_main_thread_7=function(){return(qB=i._emscripten_sync_run_in_main_thread_7=i.asm.sb).apply(null,arguments)},NI=i._emscripten_run_in_main_runtime_thread_js=function(){return(NI=i._emscripten_run_in_main_runtime_thread_js=i.asm.tb).apply(null,arguments)},rb=i._emscripten_async_queue_on_thread_=function(){return(rb=i._emscripten_async_queue_on_thread_=i.asm.ub).apply(null,arguments)},HB=i._emscripten_tls_init=function(){return(HB=i._emscripten_tls_init=i.asm.vb).apply(null,arguments)},im=i.stackSave=function(){return(im=i.stackSave=i.asm.wb).apply(null,arguments)},Ic=i.stackAlloc=function(){return(Ic=i.stackAlloc=i.asm.xb).apply(null,arguments)},Nc=i.stackRestore=function(){return(Nc=i.stackRestore=i.asm.yb).apply(null,arguments)},SI=i.dynCall_vi=function(){return(SI=i.dynCall_vi=i.asm.zb).apply(null,arguments)},KB=i.dynCall_v=function(){return(KB=i.dynCall_v=i.asm.Ab).apply(null,arguments)},XB=i.dynCall_ii=function(){return(XB=i.dynCall_ii=i.asm.Bb).apply(null,arguments)};i.asm=Cc,i.cwrap=Re,i.PThread=ve,i.PThread=ve,i._pthread_self=Vs,i.wasmMemory=Q,i.ExitStatus=TI;var am;i.then=function(I){if(am)I(i);else{var D=i.onRuntimeInitialized;i.onRuntimeInitialized=function(){D&&D(),I(i)}}return i};function TI(I){this.name="ExitStatus",this.message="Program terminated with exit("+I+")",this.status=I}Ml=function I(){am||ob(),am||(Ml=I)};function ob(I){if(I=I||p,Qi>0||(xh(),Qi>0))return;function D(){am||(am=!0,i.calledRun=!0,!ge&&(Qx(),ey(),i.onRuntimeInitialized&&i.onRuntimeInitialized(),ty()))}i.setStatus?(i.setStatus("Running..."),setTimeout(function(){setTimeout(function(){i.setStatus("")},1),D()},1)):D()}if(i.run=ob,i.preInit)for(typeof i.preInit=="function"&&(i.preInit=[i.preInit]);i.preInit.length>0;)i.preInit.pop()();return b||(J=!0),b||ob(),e}}();typeof Xx=="object"&&typeof dI=="object"?dI.exports=hI:typeof define=="function"&&define.amd?define([],function(){return hI}):typeof Xx=="object"&&(Xx.WasmBackendModuleThreadedSimd=hI)});var Dz=Ur((Yx,gI)=>{var xI=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(q,se){throw se},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(q){return t.locateFile?t.locateFile(q,m):m+q}var d,h,g,y,b,_;c?(u?m=Xp().dirname(m)+"/":m=__dirname+"/",d=function(se,_e){return b||(b=require("fs")),_||(_=Xp()),se=_.normalize(se),b.readFileSync(se,_e?null:"utf8")},g=function(se){var _e=d(se,!0);return _e.buffer||(_e=new Uint8Array(_e)),H(_e.buffer),_e},process.argv.length>1&&(a=process.argv[1].replace(/\\/g,"/")),s=process.argv.slice(2),process.on("uncaughtException",function(q){if(!(q instanceof tm))throw q}),process.on("unhandledRejection",os),i=function(q){process.exit(q)},t.inspect=function(){return"[Emscripten Module object]"}):p?(typeof read!="undefined"&&(d=function(se){return read(se)}),g=function(se){var _e;return typeof readbuffer=="function"?new Uint8Array(readbuffer(se)):(_e=read(se,"binary"),H(typeof _e=="object"),_e)},typeof scriptArgs!="undefined"?s=scriptArgs:typeof arguments!="undefined"&&(s=arguments),typeof quit=="function"&&(i=function(q){quit(q)}),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(se){var _e=new XMLHttpRequest;return _e.open("GET",se,!1),_e.send(null),_e.responseText},u&&(g=function(se){var _e=new XMLHttpRequest;return _e.open("GET",se,!1),_e.responseType="arraybuffer",_e.send(null),new Uint8Array(_e.response)}),h=function(se,_e,Ke){var Xe=new XMLHttpRequest;Xe.open("GET",se,!0),Xe.responseType="arraybuffer",Xe.onload=function(){if(Xe.status==200||Xe.status==0&&Xe.response){_e(Xe.response);return}Ke()},Xe.onerror=Ke,Xe.send(null)},y=function(q){document.title=q});var w=t.print||console.log.bind(console),k=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 T;t.noExitRuntime&&(T=t.noExitRuntime),typeof WebAssembly!="object"&&k("no native wasm support detected");var F,M=new WebAssembly.Table({initial:151,maximum:151+0,element:"anyfunc"}),L=!1,G=0;function H(q,se){q||os("Assertion failed: "+se)}function U(q){var se=t["_"+q];return H(se,"Cannot call unknown function "+q+", make sure it is exported"),se}function Z(q,se,_e,Ke,Xe){var Kt={string:function(xo){var Ya=0;if(xo!=null&&xo!==0){var Mh=(xo.length<<2)+1;Ya=Cc(Mh),ie(xo,Ya,Mh)}return Ya},array:function(xo){var Ya=Cc(xo.length);return ae(xo,Ya),Ya}};function lt(xo){return se==="string"?J(xo):se==="boolean"?Boolean(xo):xo}var st=U(q),yr=[],ta=0;if(Ke)for(var ra=0;ra=Ke);)++Xe;if(Xe-se>16&&q.subarray&&X)return X.decode(q.subarray(se,Xe));for(var Kt="";se>10,56320|ta&1023)}}return Kt}function J(q,se){return q?oe(ge,q,se):""}function Q(q,se,_e,Ke){if(!(Ke>0))return 0;for(var Xe=_e,Kt=_e+Ke-1,lt=0;lt=55296&&st<=57343){var yr=q.charCodeAt(++lt);st=65536+((st&1023)<<10)|yr&1023}if(st<=127){if(_e>=Kt)break;se[_e++]=st}else if(st<=2047){if(_e+1>=Kt)break;se[_e++]=192|st>>6,se[_e++]=128|st&63}else if(st<=65535){if(_e+2>=Kt)break;se[_e++]=224|st>>12,se[_e++]=128|st>>6&63,se[_e++]=128|st&63}else{if(_e+3>=Kt)break;se[_e++]=240|st>>18,se[_e++]=128|st>>12&63,se[_e++]=128|st>>6&63,se[_e++]=128|st&63}}return se[_e]=0,_e-Xe}function ie(q,se,_e){return Q(q,ge,se,_e)}function ae(q,se){le.set(q,se)}var ue,le,ge,we,ye,ke,Ee,Re,Pe;function ze(q){ue=q,t.HEAP8=le=new Int8Array(q),t.HEAP16=we=new Int16Array(q),t.HEAP32=ke=new Int32Array(q),t.HEAPU8=ge=new Uint8Array(q),t.HEAPU16=ye=new Uint16Array(q),t.HEAPU32=Ee=new Uint32Array(q),t.HEAPF32=Re=new Float32Array(q),t.HEAPF64=Pe=new Float64Array(q)}var mt=t.INITIAL_MEMORY||16777216;function gt(q){for(;q.length>0;){var se=q.shift();if(typeof se=="function"){se(t);continue}var _e=se.func;typeof _e=="number"?se.arg===void 0?t.dynCall_v(_e):t.dynCall_vi(_e,se.arg):_e(se.arg===void 0?null:se.arg)}}var Ct=[],xt=[],yt=[],It=[],nt=!1,ho=!1;function Jt(){if(t.preRun)for(typeof t.preRun=="function"&&(t.preRun=[t.preRun]);t.preRun.length;)To(t.preRun.shift());gt(Ct)}function go(){nt=!0,gt(xt)}function $r(){gt(yt)}function jo(){ho=!0}function Gr(){if(t.postRun)for(typeof t.postRun=="function"&&(t.postRun=[t.postRun]);t.postRun.length;)Eo(t.postRun.shift());gt(It)}function To(q){Ct.unshift(q)}function Eo(q){It.unshift(q)}var vr=Math.ceil,Ao=Math.floor,ro=0,Zi=null,Do=null;function Fl(q){ro++,t.monitorRunDependencies&&t.monitorRunDependencies(ro)}function Ji(q){if(ro--,t.monitorRunDependencies&&t.monitorRunDependencies(ro),ro==0&&(Zi!==null&&(clearInterval(Zi),Zi=null),Do)){var se=Do;Do=null,se()}}t.preloadedImages={},t.preloadedAudios={};function os(q){throw t.onAbort&&t.onAbort(q),q+="",w(q),k(q),L=!0,G=1,q="abort("+q+"). Build with -s ASSERTIONS=1 for more info.",new WebAssembly.RuntimeError(q)}function Ol(q,se){return String.prototype.startsWith?q.startsWith(se):q.indexOf(se)===0}var dh="data:application/octet-stream;base64,";function hh(q){return Ol(q,dh)}var gh="file://";function Yp(q){return Ol(q,gh)}var $o="tfjs-backend-wasm.wasm";hh($o)||($o=f($o));function xh(){try{if($)return new Uint8Array($);if(g)return g($o);throw"both async and sync fetching of the wasm failed"}catch(q){os(q)}}function Qx(){return!$&&(l||u)&&typeof fetch=="function"&&!Yp($o)?fetch($o,{credentials:"same-origin"}).then(function(q){if(!q.ok)throw"failed to load wasm binary file at '"+$o+"'";return q.arrayBuffer()}).catch(function(){return xh()}):new Promise(function(q,se){q(xh())})}function ey(){var q={env:yh,wasi_snapshot_preview1:yh};function se(lt,st){var yr=lt.exports;t.asm=yr,F=yr.memory,ze(F.buffer),Ji("wasm-instantiate")}Fl("wasm-instantiate");function _e(lt){se(lt.instance)}function Ke(lt){return Qx().then(function(st){return WebAssembly.instantiate(st,q)}).then(lt,function(st){k("failed to asynchronously prepare wasm: "+st),os(st)})}function Xe(){if(!$&&typeof WebAssembly.instantiateStreaming=="function"&&!hh($o)&&!Yp($o)&&typeof fetch=="function")fetch($o,{credentials:"same-origin"}).then(function(lt){var st=WebAssembly.instantiateStreaming(lt,q);return st.then(_e,function(yr){k("wasm streaming compile failed: "+yr),k("falling back to ArrayBuffer instantiation"),Ke(_e)})});else return Ke(_e)}if(t.instantiateWasm)try{var Kt=t.instantiateWasm(q,se);return Kt}catch(lt){return k("Module.instantiateWasm callback failed with error: "+lt),!1}return Xe(),{}}xt.push();function ty(q){ze(F.buffer)}var Pl={splitPath:function(q){var se=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;return se.exec(q).slice(1)},normalizeArray:function(q,se){for(var _e=0,Ke=q.length-1;Ke>=0;Ke--){var Xe=q[Ke];Xe==="."?q.splice(Ke,1):Xe===".."?(q.splice(Ke,1),_e++):_e&&(q.splice(Ke,1),_e--)}if(se)for(;_e;_e--)q.unshift("..");return q},normalize:function(q){var se=q.charAt(0)==="/",_e=q.substr(-1)==="/";return q=Pl.normalizeArray(q.split("/").filter(function(Ke){return!!Ke}),!se).join("/"),!q&&!se&&(q="."),q&&_e&&(q+="/"),(se?"/":"")+q},dirname:function(q){var se=Pl.splitPath(q),_e=se[0],Ke=se[1];return!_e&&!Ke?".":(Ke&&(Ke=Ke.substr(0,Ke.length-1)),_e+Ke)},basename:function(q){if(q==="/")return"/";var se=q.lastIndexOf("/");return se===-1?q:q.substr(se+1)},extname:function(q){return Pl.splitPath(q)[3]},join:function(){var q=Array.prototype.slice.call(arguments,0);return Pl.normalize(q.join("/"))},join2:function(q,se){return Pl.normalize(q+"/"+se)}},yc={mappings:{},buffers:[null,[],[]],printChar:function(q,se){var _e=yc.buffers[q];se===0||se===10?((q===1?w:k)(oe(_e,0)),_e.length=0):_e.push(se)},varargs:void 0,get:function(){yc.varargs+=4;var q=ke[yc.varargs-4>>2];return q},getStr:function(q){var se=J(q);return se},get64:function(q,se){return q}};function ry(q){return 0}function oy(q,se,_e,Ke,Xe){}function Qi(q,se,_e,Ke){for(var Xe=0,Kt=0;Kt<_e;Kt++){for(var lt=ke[se+Kt*8>>2],st=ke[se+(Kt*8+4)>>2],yr=0;yr>2]=Xe,0}function Zp(q){Fh(q)}function Ml(q){Zp(q)}function ny(q){return q=+q,q>=0?+Ao(q+.5):+vr(q-.5)}var yh={emscripten_notify_memory_growth:ty,fd_close:ry,fd_seek:oy,fd_write:Qi,proc_exit:Ml,roundf:ny},ea=ey();t.asm=ea;var bh=t._init=function(){return(bh=t._init=t.asm.init).apply(null,arguments)},sy=t._register_tensor=function(){return(sy=t._register_tensor=t.asm.register_tensor).apply(null,arguments)},_h=t._dispose_data=function(){return(_h=t._dispose_data=t.asm.dispose_data).apply(null,arguments)},iy=t._dispose=function(){return(iy=t._dispose=t.asm.dispose).apply(null,arguments)},wh=t._Abs=function(){return(wh=t._Abs=t.asm.Abs).apply(null,arguments)},qo=t._Add=function(){return(qo=t._Add=t.asm.Add).apply(null,arguments)},vh=t._AddN=function(){return(vh=t._AddN=t.asm.AddN).apply(null,arguments)},ay=t._ArgMax=function(){return(ay=t._ArgMax=t.asm.ArgMax).apply(null,arguments)},ly=t._AvgPool=function(){return(ly=t._AvgPool=t.asm.AvgPool).apply(null,arguments)},uy=t._BatchMatMul=function(){return(uy=t._BatchMatMul=t.asm.BatchMatMul).apply(null,arguments)},cy=t._ClipByValue=function(){return(cy=t._ClipByValue=t.asm.ClipByValue).apply(null,arguments)},kh=t._Conv2D=function(){return(kh=t._Conv2D=t.asm.Conv2D).apply(null,arguments)},Ch=t._Conv2DBackpropInput=function(){return(Ch=t._Conv2DBackpropInput=t.asm.Conv2DBackpropInput).apply(null,arguments)},Ih=t._Cos=function(){return(Ih=t._Cos=t.asm.Cos).apply(null,arguments)},bc=t._CropAndResize=function(){return(bc=t._CropAndResize=t.asm.CropAndResize).apply(null,arguments)},Jp=t._Cumsum=function(){return(Jp=t._Cumsum=t.asm.Cumsum).apply(null,arguments)},_c=t._DepthToSpace=function(){return(_c=t._DepthToSpace=t.asm.DepthToSpace).apply(null,arguments)},wc=t._DepthwiseConv2dNative=function(){return(wc=t._DepthwiseConv2dNative=t.asm.DepthwiseConv2dNative).apply(null,arguments)},py=t._Equal=function(){return(py=t._Equal=t.asm.Equal).apply(null,arguments)},my=t._Exp=function(){return(my=t._Exp=t.asm.Exp).apply(null,arguments)},fy=t._FlipLeftRight=function(){return(fy=t._FlipLeftRight=t.asm.FlipLeftRight).apply(null,arguments)},ve=t._Floor=function(){return(ve=t._Floor=t.asm.Floor).apply(null,arguments)},dy=t._FloorDiv=function(){return(dy=t._FloorDiv=t.asm.FloorDiv).apply(null,arguments)},hy=t._FusedBatchNorm=function(){return(hy=t._FusedBatchNorm=t.asm.FusedBatchNorm).apply(null,arguments)},gy=t._FusedConv2D=function(){return(gy=t._FusedConv2D=t.asm.FusedConv2D).apply(null,arguments)},xy=t._FusedDepthwiseConv2D=function(){return(xy=t._FusedDepthwiseConv2D=t.asm.FusedDepthwiseConv2D).apply(null,arguments)},Ll=t._Gather=function(){return(Ll=t._Gather=t.asm.Gather).apply(null,arguments)},yy=t._GatherNd=function(){return(yy=t._GatherNd=t.asm.GatherNd).apply(null,arguments)},by=t._Greater=function(){return(by=t._Greater=t.asm.Greater).apply(null,arguments)},_y=t._GreaterEqual=function(){return(_y=t._GreaterEqual=t.asm.GreaterEqual).apply(null,arguments)},wy=t._LeakyRelu=function(){return(wy=t._LeakyRelu=t.asm.LeakyRelu).apply(null,arguments)},vy=t._Less=function(){return(vy=t._Less=t.asm.Less).apply(null,arguments)},ky=t._LessEqual=function(){return(ky=t._LessEqual=t.asm.LessEqual).apply(null,arguments)},Cy=t._Log=function(){return(Cy=t._Log=t.asm.Log).apply(null,arguments)},Iy=t._LogicalAnd=function(){return(Iy=t._LogicalAnd=t.asm.LogicalAnd).apply(null,arguments)},Ny=t._Max=function(){return(Ny=t._Max=t.asm.Max).apply(null,arguments)},Sy=t._MaxPool=function(){return(Sy=t._MaxPool=t.asm.MaxPool).apply(null,arguments)},Ka=t._Maximum=function(){return(Ka=t._Maximum=t.asm.Maximum).apply(null,arguments)},zl=t._Mean=function(){return(zl=t._Mean=t.asm.Mean).apply(null,arguments)},vc=t._Min=function(){return(vc=t._Min=t.asm.Min).apply(null,arguments)},Ty=t._Minimum=function(){return(Ty=t._Minimum=t.asm.Minimum).apply(null,arguments)},Ey=t._Multiply=function(){return(Ey=t._Multiply=t.asm.Multiply).apply(null,arguments)},Ay=t._Neg=function(){return(Ay=t._Neg=t.asm.Neg).apply(null,arguments)},Dy=t._NonMaxSuppressionV3=function(){return(Dy=t._NonMaxSuppressionV3=t.asm.NonMaxSuppressionV3).apply(null,arguments)},Ze=t._NonMaxSuppressionV4=function(){return(Ze=t._NonMaxSuppressionV4=t.asm.NonMaxSuppressionV4).apply(null,arguments)},$y=t._NonMaxSuppressionV5=function(){return($y=t._NonMaxSuppressionV5=t.asm.NonMaxSuppressionV5).apply(null,arguments)},Ry=t._NotEqual=function(){return(Ry=t._NotEqual=t.asm.NotEqual).apply(null,arguments)},Fy=t._OneHot=function(){return(Fy=t._OneHot=t.asm.OneHot).apply(null,arguments)},Oy=t._PadV2=function(){return(Oy=t._PadV2=t.asm.PadV2).apply(null,arguments)},Py=t._Pow=function(){return(Py=t._Pow=t.asm.Pow).apply(null,arguments)},My=t._Prelu=function(){return(My=t._Prelu=t.asm.Prelu).apply(null,arguments)},Qp=t._Prod=function(){return(Qp=t._Prod=t.asm.Prod).apply(null,arguments)},Nh=t._RealDiv=function(){return(Nh=t._RealDiv=t.asm.RealDiv).apply(null,arguments)},Sh=t._Relu=function(){return(Sh=t._Relu=t.asm.Relu).apply(null,arguments)},Ly=t._Relu6=function(){return(Ly=t._Relu6=t.asm.Relu6).apply(null,arguments)},zy=t._ResizeBilinear=function(){return(zy=t._ResizeBilinear=t.asm.ResizeBilinear).apply(null,arguments)},By=t._Reverse=function(){return(By=t._Reverse=t.asm.Reverse).apply(null,arguments)},Vy=t._RotateWithOffset=function(){return(Vy=t._RotateWithOffset=t.asm.RotateWithOffset).apply(null,arguments)},Wy=t._Round=function(){return(Wy=t._Round=t.asm.Round).apply(null,arguments)},Gy=t._Rsqrt=function(){return(Gy=t._Rsqrt=t.asm.Rsqrt).apply(null,arguments)},rt=t._ScatterNd=function(){return(rt=t._ScatterNd=t.asm.ScatterNd).apply(null,arguments)},Uy=t._SelectV2=function(){return(Uy=t._SelectV2=t.asm.SelectV2).apply(null,arguments)},jy=t._Sigmoid=function(){return(jy=t._Sigmoid=t.asm.Sigmoid).apply(null,arguments)},qy=t._Sin=function(){return(qy=t._Sin=t.asm.Sin).apply(null,arguments)},Bl=t._Softmax=function(){return(Bl=t._Softmax=t.asm.Softmax).apply(null,arguments)},kc=t._Sqrt=function(){return(kc=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)},Ah=t._StridedSlice=function(){return(Ah=t._StridedSlice=t.asm.StridedSlice).apply(null,arguments)},Hy=t._Sub=function(){return(Hy=t._Sub=t.asm.Sub).apply(null,arguments)},Ky=t._Sum=function(){return(Ky=t._Sum=t.asm.Sum).apply(null,arguments)},Dh=t._Tanh=function(){return(Dh=t._Tanh=t.asm.Tanh).apply(null,arguments)},Xy=t._Tile=function(){return(Xy=t._Tile=t.asm.Tile).apply(null,arguments)},Vs=t._TopK=function(){return(Vs=t._TopK=t.asm.TopK).apply(null,arguments)},Yy=t._Transpose=function(){return(Yy=t._Transpose=t.asm.Transpose).apply(null,arguments)},Zy=t.__FusedMatMul=function(){return(Zy=t.__FusedMatMul=t.asm._FusedMatMul).apply(null,arguments)},$h=t._malloc=function(){return($h=t._malloc=t.asm.malloc).apply(null,arguments)},Xa=t._free=function(){return(Xa=t._free=t.asm.free).apply(null,arguments)},Jy=t.__start=function(){return(Jy=t.__start=t.asm._start).apply(null,arguments)},Rh=t.stackSave=function(){return(Rh=t.stackSave=t.asm.stackSave).apply(null,arguments)},Cc=t.stackAlloc=function(){return(Cc=t.stackAlloc=t.asm.stackAlloc).apply(null,arguments)},em=t.stackRestore=function(){return(em=t.stackRestore=t.asm.stackRestore).apply(null,arguments)};t.asm=ea,t.cwrap=K;var Vl;t.then=function(q){if(Vl)q(t);else{var se=t.onRuntimeInitialized;t.onRuntimeInitialized=function(){se&&se(),q(t)}}return t};function tm(q){this.name="ExitStatus",this.message="Program terminated with exit("+q+")",this.status=q}var Qy=!1;Do=function q(){Vl||rm(),Vl||(Do=q)};function eb(q){var se=t.__start;try{se();var _e=0;Fh(_e,!0)}catch(Xe){if(Xe instanceof tm)return;if(Xe=="unwind"){T=!0;return}else{var Ke=Xe;Xe&&typeof Xe=="object"&&Xe.stack&&(Ke=[Xe,Xe.stack]),k("exception thrown: "+Ke),i(1,Xe)}}finally{Qy=!0}}function rm(q){if(q=q||s,ro>0||(Jt(),ro>0))return;function se(){Vl||(Vl=!0,t.calledRun=!0,!L&&(go(),$r(),t.onRuntimeInitialized&&t.onRuntimeInitialized(),Oh&&eb(q),Gr()))}t.setStatus?(t.setStatus("Running..."),setTimeout(function(){setTimeout(function(){t.setStatus("")},1),se()},1)):se()}t.run=rm;function Fh(q,se){se&&T&&q===0||(T||(L=!0,G=q,jo(),t.onExit&&t.onExit(q)),i(q,new tm(q)))}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),T=!0,rm(),e}}();typeof Yx=="object"&&typeof gI=="object"?gI.exports=xI:typeof define=="function"&&define.amd?define([],function(){return xI}):typeof Yx=="object"&&(Yx.WasmBackendModule=xI)});var r3=1e-7,o3=1e-4,Ja=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{time(e){return Y("time")}read(e){return Y("read")}readSync(e){return Y("readSync")}numDataIds(){return Y("numDataIds")}disposeData(e){return Y("disposeData")}write(e,t,o){return Y("write")}move(e,t,o,n){return Y("move")}memory(){return Y("memory")}floatPrecision(){return Y("floatPrecision")}epsilon(){return this.floatPrecision()===32?r3:o3}batchMatMul(e,t,o,n){return Y("batchMatMul")}fusedBatchMatMul({a:e,b:t,transposeA:o,transposeB:n,bias:s,activation:a,preluActivationWeights:i}){return Y("fusedBatchMatMul")}slice(e,t,o){return Y("slice")}stridedSlice(e,t,o,n){return Y("stridedSlice")}unstack(e,t){return Y("unstack")}reverse(e,t){return Y("reverse")}concat(e,t){return Y("concat")}neg(e){return Y("neg")}add(e,t){return Y("add")}addN(e){return Y("addN")}subtract(e,t){return Y("subtract")}multiply(e,t){return Y("multiply")}realDivide(e,t){return Y("realDivide")}floorDiv(e,t){return Y("floorDiv")}sum(e,t){return Y("sum")}prod(e,t){return Y("prod")}unsortedSegmentSum(e,t,o){return Y("unsortedSegmentSum")}argMin(e,t){return Y("argMin")}argMax(e,t){return Y("argMax")}equal(e,t){return Y("equal")}notEqual(e,t){return Y("notEqual")}less(e,t){return Y("less")}lessEqual(e,t){return Y("lessEqual")}greater(e,t){return Y("greater")}greaterEqual(e,t){return Y("greaterEqual")}logicalNot(e){return Y("logicalNot")}logicalAnd(e,t){return Y("logicalAnd")}logicalOr(e,t){return Y("logicalOr")}where(e){return Y("where")}select(e,t,o){return Y("select")}topk(e,t,o){return Y("topk")}min(e,t){return Y("min")}minimum(e,t){return Y("minimum")}mod(e,t){return Y("mod")}max(e,t){return Y("max")}maximum(e,t){return Y("maximum")}all(e,t){return Y("all")}any(e,t){return Y("any")}squaredDifference(e,t){return Y("squaredDifference")}ceil(e){return Y("ceil")}floor(e){return Y("floor")}round(e){return Y("round")}sign(e){return Y("sign")}isNaN(e){return Y("isNaN")}isInf(e){return Y("isInf")}isFinite(e){return Y("isFinite")}pow(e,t){return Y("pow")}exp(e){return Y("exp")}expm1(e){return Y("expm1")}softmax(e,t){return Y("softmax")}log(e){return Y("log")}log1p(e){return Y("log1p")}sqrt(e){return Y("sqrt")}rsqrt(e){return Y("rsqrt")}square(e){return Y("square")}reciprocal(e){return Y("reciprocal")}relu(e){return Y("relu")}relu6(e){return Y("relu6")}prelu(e,t){return Y("prelu")}elu(e){return Y("elu")}eluDer(e,t){return Y("eluDer")}selu(e){return Y("selu")}int(e){return Y("int")}clip(e,t,o){return Y("clip")}abs(e){return Y("abs")}complexAbs(e){return Y("complexAbs")}sigmoid(e){return Y("sigmoid")}softplus(e){return Y("softplus")}sin(e){return Y("sin")}cos(e){return Y("cos")}tan(e){return Y("tan")}asin(e){return Y("asin")}acos(e){return Y("acos")}atan(e){return Y("atan")}atan2(e,t){return Y("atan2")}sinh(e){return Y("sinh")}cosh(e){return Y("cosh")}tanh(e){return Y("tanh")}asinh(e){return Y("asinh")}acosh(e){return Y("acosh")}atanh(e){return Y("atanh")}erf(e){return Y("erf")}step(e,t){return Y("step")}fusedConv2d({input:e,filter:t,convInfo:o,bias:n,activation:s,preluActivationWeights:a}){return Y("fusedConv2d")}conv2d(e,t,o){return Y("conv2d")}conv2dDerInput(e,t,o){return Y("conv2dDerInput")}conv2dDerFilter(e,t,o){return Y("conv2dDerFilter")}fusedDepthwiseConv2D({input:e,filter:t,convInfo:o,bias:n,activation:s,preluActivationWeights:a}){return Y("fusedDepthwiseConv2D")}depthwiseConv2D(e,t,o){return Y("depthwiseConv2D")}depthwiseConv2DDerInput(e,t,o){return Y("depthwiseConv2DDerInput")}depthwiseConv2DDerFilter(e,t,o){return Y("depthwiseConv2DDerFilter")}conv3d(e,t,o){return Y("conv3d")}conv3dDerInput(e,t,o){return Y("conv3dDerInput")}conv3dDerFilter(e,t,o){return Y("conv3dDerFilter")}maxPool(e,t){return Y("maxPool")}maxPoolBackprop(e,t,o,n){return Y("maxPoolBackprop")}avgPool(e,t){return Y("avgPool")}avgPoolBackprop(e,t,o){return Y("avgPoolBackprop")}avgPool3d(e,t){return Y("avgPool3d")}avgPool3dBackprop(e,t,o){return Y("avgPool3dBackprop")}maxPool3d(e,t){return Y("maxPool3d")}maxPool3dBackprop(e,t,o,n){return Y("maxPool3dBackprop")}reshape(e,t){return Y("reshape")}cast(e,t){return Y("cast")}tile(e,t){return Y("tile")}pad(e,t,o){return Y("pad")}transpose(e,t){return Y("transpose")}gather(e,t,o,n=0){return Y("gather")}gatherND(e,t){return Y("gatherND")}scatterND(e,t,o){return Y("scatterND")}batchToSpaceND(e,t,o){return Y("batchToSpaceND")}spaceToBatchND(e,t,o){return Y("spaceToBatchND")}resizeBilinear(e,t,o,n,s){return Y("resizeBilinear")}resizeBilinearBackprop(e,t,o){return Y("resizeBilinearBackprop")}resizeNearestNeighbor(e,t,o,n,s){return Y("resizeNearestNeighbor")}resizeNearestNeighborBackprop(e,t,o){return Y("resizeNearestNeighborBackprop")}batchNorm(e,t,o,n,s,a){return Y("batchNorm")}localResponseNormalization4D(e,t,o,n,s){return Y("localResponseNormalization4D")}LRNGrad(e,t,o,n,s,a,i){return Y("LRNGrad")}multinomial(e,t,o,n){return Y("multinomial")}oneHot(e,t,o,n){return Y("oneHot")}cumsum(e,t,o,n){return Y("cumsum")}nonMaxSuppression(e,t,o,n,s){return Y("nonMaxSuppression")}fft(e){return Y("fft")}ifft(e){return Y("ifft")}complex(e,t){return Y("complex")}real(e){return Y("real")}imag(e){return Y("imag")}cropAndResize(e,t,o,n,s,a){return Y("cropAndResize")}depthToSpace(e,t,o){return Y("depthToSpace")}split(e,t,o){return Y("split")}sparseToDense(e,t,o,n){return Y("sparseToDense")}diag(e){return Y("diag")}fill(e,t,o){return Y("fill")}onesLike(e){return Y("onesLike")}zerosLike(e){return Y("zerosLike")}linspace(e,t,o){return Y("linspace")}dispose(){return Y("dispose")}};function Y(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 DI(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 Ac(r,e,t){return Math.max(r,Math.min(e,t))}function n3(r){return r%2==0?r:r+1}function s3(r){let e=0;for(let t=0;tt+` Shapes ${r} and ${e} must match`)}function Ro(r){E(r!=null,()=>"The input to the tensor constructor must be a non-null value.")}function ns(r,e=[],t=!1){if(e==null&&(e=[]),Array.isArray(r)||nr(r)&&!t)for(let o=0;o0,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 f3(r,e){let t=1,o=-1;for(let s=0;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 tr(r,e){let t=e.length;return r=r==null?e.map((o,n)=>n):[].concat(r),E(r.every(o=>o>=-t&&o`All values in axis param must be in range [-${t}, ${t}) but got axis ${r}`),E(r.every(o=>it(o)),()=>`All values in axis param must be integers but got axis ${r}`),r.map(o=>o<0?t+o:o)}function ib(r,e){let t=[],o=[],n=e!=null&&Array.isArray(e)&&e.length===0,s=e==null||n?null:tr(e,r).sort(),a=0;for(let i=0;ii)&&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 ab(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 lb(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 ub(r,e){for(let t=0;te+=t.length),e}function ss(r){return typeof r=="string"||r instanceof String}function $I(r){return typeof r=="boolean"}function RI(r){return typeof r=="number"}function Dc(r){return Array.isArray(r)?Dc(r[0]):r instanceof Float32Array?"float32":r instanceof Int32Array||r instanceof Uint8Array?"int32":RI(r)?"float32":ss(r)?"string":$I(r)?"bool":"float32"}function Gs(r){return!!(r&&r.constructor&&r.call&&r.apply)}function $c(r,e){for(let t=e;t=0;--o)t[o]=t[o+1]*r[o+1];return t}function FI(r,e,t){let o=new Array;if(e.length===1){let n=e[0];for(let s=0;si*l);for(let i=0;io*n);if(t===0)return[];if(t!==e.length)throw new Error(`[${r}] does not match the input size ${e.length}.`);return FI(0,r,e)}function cm(r,e){let t=Rc(r,e);for(let o=0;oo*n,1);if(e==null||e==="float32")return Gl(r,new Float32Array(t));if(e==="int32")return Gl(r,new Int32Array(t));if(e==="bool")return Gl(r,new Uint8Array(t));throw new Error(`Unknown data type ${e}`)}function pm(r){r.forEach(e=>{E(Number.isInteger(e)&&e>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${r}].`)})}function h3(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{let[n,s]=o.split(":");this.urlFlags[n]=y3(n,s)})}};function x3(r){let e={};return r.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(t,...o)=>(b3(e,o[0],o[1]),o.join("="))),e}function b3(r,e,t){r[decodeURIComponent(e)]=decodeURIComponent(t||"")}function y3(r,e){if(e=e.toLowerCase(),e==="true"||e==="false")return e==="true";if(`${+e}`===e)return+e;throw new Error(`Could not parse value flag value ${e} for flag ${r}.`)}function W(){return db}var db=null;function PI(r){db=r}var hb;function gb(){if(hb==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");hb=r}return hb}function _3(){let r=gb();return r._tfGlobals==null&&(r._tfGlobals=new Map),r._tfGlobals}function xb(r,e){let t=_3();if(t.has(r))return t.get(r);{let o=e();return t.set(r,o),t.get(r)}}var is="Abs",js="Acos",qs="Acosh",bo="Add",Ho="AddN",Ul="All",jl="Any",Ko="ArgMax",oa="ArgMin",Hs="Asin",Ks="Asinh",Xs="Atan",Ys="Atanh",Zs="Atan2",Xo="AvgPool",ql="AvgPoolGrad",na="AvgPool3D",Hl="AvgPool3DGrad",Yo="BatchMatMul",sa="BatchToSpaceND",Kl="Bincount",yb="BroadcastTo",Fo="Cast",Js="Ceil",Oo="ClipByValue",Xl="Complex",ia="ComplexAbs",as="Concat",Zo="Conv2D",Yl="Conv2DBackpropFilter",Jo="Conv2DBackpropInput",aa="Conv3D",Zl="Conv3DBackpropFilterV2",Jl="Conv3DBackpropInputV2",Qo="Cos",Qs="Cosh",en="Cumsum",ei="CropAndResize",Ql="DenseBincount",ti="DepthToSpace",tn="DepthwiseConv2dNative",eu="DepthwiseConv2dNativeBackpropFilter",tu="DepthwiseConv2dNativeBackpropInput",ru="Diag",la="Dilation2D",Fc="Dilation2DBackpropInput",Oc="Dilation2DBackpropFilter",rn="RealDiv",ri="Elu",ou="EluGrad",oi="Erf",ni="Equal",on="Exp",ls="ExpandDims",si="Expm1",nu="FFT",ua="Fill",ii="FlipLeftRight",nn="Floor",sn="FloorDiv",an="FusedBatchNorm",us="GatherV2",ai="GatherNd",li="Greater",ln="GreaterEqual",cs="Identity",su="IFFT",iu="Imag",ui="IsFinite",ci="IsInf",pi="IsNan",un="LeakyRelu",mi="Less",fi="LessEqual",au="LinSpace",cn="Log",di="Log1p",hi="LogicalAnd",Qa="LogicalNot",el="LogicalOr",bb="LogSoftmax",ca="LRN",lu="LRNGrad",pn="Max",mn="Maximum",fn="MaxPool",uu="MaxPoolGrad",pa="MaxPool3D",cu="MaxPool3DGrad",pu="MaxPoolWithArgmax",dn="Mean",hn="Min",gn="Minimum",ma="MirrorPad",gi="Mod",mu="Multinomial",xn="Multiply",ps="Neg",xi="NotEqual",yi="NonMaxSuppressionV3",bi="NonMaxSuppressionV4",_i="NonMaxSuppressionV5",ms="OnesLike",yn="OneHot",fs="Pack",bn="PadV2",w3="Pool",_n="Pow",wn="Prelu",wi="Prod",fa="Range",fu="Real",vi="Reciprocal",vn="Relu",ds="Reshape",da="ResizeNearestNeighbor",du="ResizeNearestNeighborGrad",kn="ResizeBilinear",hu="ResizeBilinearGrad",Cn="Relu6",In="Reverse",Nn="Round",Sn="Rsqrt",ki="ScatterNd",hs="Select",Ci="Selu",gs="Slice",Tn="Sin",Ii="Sinh",Ni="Sign",En="Sigmoid",Si="Softplus",An="Sqrt",Dn="Sum",ha="SpaceToBatchND",xs="SplitV",$n="Softmax",Rn="SquaredDifference",ga="Square",Fn="Sub",gu="SparseToDense",Ti="StridedSlice",Ei="Tan",On="Tanh",_o="Tile",Ai="TopK",Pn="Transpose",xu="Unique",ys="Unpack",xa="UnsortedSegmentSum",bs="ZerosLike",Di="Step",Pc="FromPixels",$i="RotateWithOffset",_s="_FusedMatMul",ws="FusedConv2D",vs="FusedDepthwiseConv2D";var Mc=xb("kernelRegistry",()=>new Map),fm=xb("gradRegistry",()=>new Map);function dm(r,e){let t=_b(r,e);return Mc.get(t)}function Bh(r){return fm.get(r)}function hm(r){let e=Mc.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 tl(r){let{kernelName:e,backendName:t}=r,o=_b(e,t);Mc.has(o)&&console.warn(`The kernel '${e}' for backend '${t}' is already registered`),Mc.set(o,r)}function wb(r){let{kernelName:e}=r;fm.has(e)&&W().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${e}'`),fm.set(e,r)}function v3(r,e){let t=_b(r,e);if(!Mc.has(t))throw new Error(`The kernel '${r}' for backend '${e}' is not registered`);Mc.delete(t)}function k3(r){if(!fm.has(r))throw new Error(`The gradient '${r}' for backend is not registered`);fm.delete(r)}function C3(r,e){hm(r).forEach(o=>{let n=Object.assign({},o,{backendName:e});tl(n)})}function _b(r,e){return`${e}_${r}`}var x={};et(x,{arraysEqual:()=>jr,assert:()=>E,assertNonNegativeIntegerDimensions:()=>pm,assertNonNull:()=>Ro,assertShapesMatch:()=>Ge,bytesFromStringArray:()=>fb,bytesPerElement:()=>mb,checkConversionForErrors:()=>ub,clamp:()=>Ac,computeStrides:()=>Us,createScalarValue:()=>I3,createShuffledIndices:()=>p3,decodeString:()=>zc,distSquared:()=>a3,encodeString:()=>rl,fetch:()=>S3,flatten:()=>ns,getArrayFromDType:()=>lb,getTypedArrayFromDType:()=>ab,hasEncodingLoss:()=>pb,indexToLoc:()=>g3,inferDtype:()=>Dc,inferFromImplicitShape:()=>f3,isBoolean:()=>$I,isFunction:()=>Gs,isInt:()=>it,isNumber:()=>RI,isPromise:()=>mm,isScalarShape:()=>l3,isString:()=>ss,isTypedArray:()=>nr,isValidDtype:()=>cb,locToIndex:()=>h3,makeOnesTypedArray:()=>cm,makeZerosNestedTypedArray:()=>d3,makeZerosTypedArray:()=>Rc,nearestDivisor:()=>$c,nearestLargerEven:()=>n3,now:()=>Vh,parseAxisParam:()=>tr,randUniform:()=>i3,repeatedTry:()=>m3,rightPad:()=>Wl,shuffle:()=>DI,sizeFromShape:()=>dt,sizeToSquarishShape:()=>c3,squeezeShape:()=>ib,sum:()=>s3,tanh:()=>u3,toNestedArray:()=>Gl,toTypedArray:()=>Lc});function I3(r,e){return e==="string"?rl(r):Lc([r],e)}function N3(r,e){return r instanceof Float32Array&&e==="float32"||r instanceof Int32Array&&e==="int32"||r instanceof Uint8Array&&e==="bool"}function Lc(r,e){if(e==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(r)&&(r=ns(r)),W().getBool("DEBUG")&&ub(r,e),N3(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{n=o()},a=this.backendTimer.time(s);if(W().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let l=0;l{T3(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 T3(r,e,t){if(e!=="float32")return!1;for(let o=0;o0?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 LI(r,e,t){let o={},n={};for(let l=0;lo[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=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(!jr(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 BI=20,gm=3,kb=7;function VI(r,e,t,o){let n=Us(e),s=E3(r,e,t,n),a=e.length,i=Wh(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 E3(r,e,t,o){let n=dt(e),s=o[o.length-1],a=new Array(s).fill(0),i=e.length,l=t==="complex64"?ym(r):r;if(i>1)for(let u=0;uBI){let g=gm*a,y=Array.from(r.slice(0,g)),b=Array.from(r.slice((i-gm)*a,i*a));return t==="complex64"&&(y=ym(y),b=ym(b)),["["+y.map((_,w)=>xm(_,n[w],t)).join(", ")+", ..., "+b.map((_,w)=>xm(_,n[i-gm+w],t)).join(", ")+"]"]}let h=t==="complex64"?ym(r):Array.from(r);return["["+h.map((g,y)=>xm(g,n[y],t)).join(", ")+"]"]}let u=e.slice(1),c=o.slice(1),p=o[0]*a,m=[];if(i>BI){for(let h=0;h`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||lb(t,this.size),this.strides=Us(e)}set(e,...t){t.length===0&&(t=[0]),E(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let 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;nzc(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=Ri().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>zc(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 Ri().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Ri().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Bc.print(this,e)}clone(){return this.throwIfDisposed(),Bc.clone(this)}toString(e=!1){let t=this.dataSync();return VI(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Bc.cast(this,e)}variable(e=!0,t,o){return this.throwIfDisposed(),Ri().makeVariable(this,e,t,o)}};Object.defineProperty(R,Symbol.hasInstance,{value:r=>!!r&&r.data!=null&&r.dataSync!=null&&r.throwIfDisposed!=null});var ol=class extends R{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(!jr(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Ri().disposeTensor(this),this.dataId=e.dataId,Ri().incRef(this,null)}dispose(){Ri().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(ol,Symbol.hasInstance,{value:r=>r instanceof R&&r.assign!=null&&r.assign instanceof Function});var Mn={};et(Mn,{assertTypesMatch:()=>Eb,getTensorsInContainer:()=>bm,isTensorInList:()=>$3,makeTypesMatch:()=>Ue});var Cb;(function(r){r.R0="R0",r.R1="R1",r.R2="R2",r.R3="R3",r.R4="R4",r.R5="R5",r.R6="R6"})(Cb||(Cb={}));var Ib;(function(r){r.float32="float32",r.int32="int32",r.bool="int32",r.complex64="complex64"})(Ib||(Ib={}));var Nb;(function(r){r.float32="float32",r.int32="int32",r.bool="bool",r.complex64="complex64"})(Nb||(Nb={}));var Sb;(function(r){r.float32="float32",r.int32="float32",r.bool="float32",r.complex64="complex64"})(Sb||(Sb={}));var Tb;(function(r){r.float32="complex64",r.int32="complex64",r.bool="complex64",r.complex64="complex64"})(Tb||(Tb={}));var D3={float32:Sb,int32:Ib,bool:Nb,complex64:Tb};function fr(r,e){if(r==="string"||e==="string"){if(r==="string"&&e==="string")return"string";throw new Error(`Can not upcast ${r} with ${e}`)}return D3[r][e]}function yu(r){return fr(r,"int32")}function Ue(r,e){if(r.dtype===e.dtype)return[r,e];let t=fr(r.dtype,e.dtype);return[r.cast(t),e.cast(t)]}function Eb(r,e){E(r.dtype===e.dtype,()=>`The dtypes of the first(${r.dtype}) and second(${e.dtype}) input must match`)}function $3(r,e){return e.some(t=>t.id===r.id)}function bm(r){let e=[],t=new Set;return qI(r,e,t),e}function qI(r,e,t){if(r==null)return;if(r instanceof R){e.push(r);return}if(!R3(r))return;let o=r;for(let n in o){let s=o[n];t.has(s)||(t.add(s),qI(s,e,t))}}function R3(r){return Array.isArray(r)||typeof r=="object"}var Ab=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()}},bu=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Ab}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;let e=this.getSortedBackends();for(let t=0;t{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){hm(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(nthis.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){let e=this.getSortedBackends();for(let t=0;tthis.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 bu.nextTensorId++}nextVariableId(){return bu.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 A.runKernelFunc(c=>c.cast(a,i),l,null,Fo,u)}}),s=[];return this.addTapeNode(this.state.activeScope.name,o,[t],n,s,{}),t}runKernel(e,t,o,n,s){let a=null,i=null;return this.runKernelFunc(a,t,i,e,o,n,s)}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,t,o,n,s,a,i){let l,u=[],c=this.isTapeOn();n==null&&(n=this.state.activeScope!=null?this.state.activeScope.name:"");let p=this.state.numBytes,m=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let f;this.backendName==null&&this.backend;let d=dm(n,this.backendName),h;if(d!=null)f=()=>{let y=this.backend.numDataIds();h=d.kernelFunc({inputs:t,attrs:s,backend:this.backend});let b=Array.isArray(h)?h:[h];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(n,y,b);let _=b.map(w=>{if(w.rank!=null)return w;let{dataId:k,shape:$,dtype:T}=w;return this.makeTensorFromDataId(k,$,T)});if(c){let w=this.getTensorsForGradient(n,t,_);if(w==null){i==null&&(i=[]);let k=_.filter(($,T)=>i[T]);w=(a||[]).slice().concat(k)}u=this.saveTensorsForBackwardMode(w)}return _};else{if(e==null)throw new Error(`Error running ${n}: Neither modular kernel nor forward func passed`);let y=b=>{!c||(u=b.map(_=>this.keep(this.clone(_))))};f=()=>{let b=this.backend.numDataIds();h=this.tidy(()=>e(this.backend,y));let _=Array.isArray(h)?h:[h];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(n,b,_),_}}let g;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?l=f():(g=this.profiler.profileKernel(n,t,()=>f()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(g),l=g.outputs)}),c&&this.addTapeNode(n,t,l,o,u,s),this.state.profiling&&this.state.activeProfile.kernels.push({name:n,bytesAdded:this.state.numBytes-p,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-m,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(t).map(y=>t[y]!=null?t[y].shape:null),outputShapes:l.map(y=>y.shape),kernelTimeMs:g.timeMs,extraInfo:g.extraInfo}),Array.isArray(h)?l:l[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?(E(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),i=Object.keys(t).map(u=>t[u])):i=s.map(u=>t[u]);let l=o.filter((u,c)=>a[c]);return i.concat(l)}return null}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"&&ss(e[0])&&(s=e.map(l=>rl(l)));let a=n.write(s,t,o),i=new R(t,o,a,this.nextTensorId());if(this.incRef(i,n),o==="string"){let l=this.state.tensorInfo.get(a),u=fb(s);this.state.numBytes+=u-l.bytes,l.bytes=u}return i}makeTensorFromDataId(e,t,o,n){o=o||"float32";let s=new R(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 ol(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*mb(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 ol||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)):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=Rc(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=bm(e),o=new Set(t.map(s=>s.id));for(let s=0;s{!s.kept&&s.scopeId===n.id&&this.track(s)})}gradients(e,t,o,n=!1){if(E(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));E(s instanceof R,()=>"The result y returned by f() must be a tensor.");let a=LI(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?F3(s.shape):o,zI(i,a,u=>this.tidy(u),O3);let l=t.map(u=>i[u.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(u=>{for(let c of u.saved)c.dispose()}),this.state.activeTape=null),{value:s,grads:l}})}customGrad(e){return E(Gs(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{E(t.every(s=>s instanceof R),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let o,n={};return t.forEach((s,a)=>{n[a]=s}),this.runKernelFunc((s,a)=>(o=e(...t,a),E(o.value instanceof R,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),E(Gs(o.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),o.value),n,(s,a)=>{let i=o.gradFunc(s,a),l=Array.isArray(i)?i:[i];E(l.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),E(l.every(c=>c instanceof R),()=>"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 u={};return l.forEach((c,p)=>{u[p]=()=>c}),u})}}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 Ab;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}};bu.nextTensorId=0;bu.nextVariableId=0;function F3(r){let e=cm(dt(r),"float32");return A.makeTensor(e,r,"float32")}function Db(){let r=gb();if(r._tfengine==null){let e=new zh(r);r._tfengine=new bu(e)}return PI(r._tfengine.ENV),GI(()=>r._tfengine),r._tfengine}var A=Db();function O3(r,e){let t={a:r,b:e};return A.runKernel(bo,t)}var Vc={};et(Vc,{isBrowser:()=>$b,isMobile:()=>M3});function P3(){return typeof navigator!="undefined"&&navigator!=null}function M3(){if(P3()){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 $b(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var Fi=W();Fi.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.")});Fi.registerFlag("IS_BROWSER",()=>$b());Fi.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Fi.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Fi.registerFlag("PROD",()=>!1);Fi.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Fi.getBool("DEBUG"));Fi.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Fi.registerFlag("IS_TEST",()=>!1);Fi.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);function kr(r,e){let t=r;if(nr(r))return e==="string"?[]:[r.length];if(!Array.isArray(r))return[];let o=[];for(;Array.isArray(t)||nr(t)&&e!=="string";)o.push(t.length),t=t[0];return Array.isArray(r)&&W().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&HI(r,o,[]),o}function HI(r,e,t){if(t=t||[],!Array.isArray(r)&&!nr(r)){E(e.length===0,()=>`Element arr[${t.join("][")}] is a primitive, but should be an array/TypedArray of ${e[0]} elements`);return}E(e.length>0,()=>`Element arr[${t.join("][")}] should be a primitive, but is an array of ${r.length} elements`),E(r.length===e[0],()=>`Element arr[${t.join("][")}] should have ${e[0]} elements, but has ${r.length} elements`);let o=e.slice(1);for(let n=0;n=0&&(n=o),KI(o,n,e,t),r==null||!nr(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);!nr(r)&&!Array.isArray(r)&&(r=[r]);let i=n!=="string"?Lc(r,n):ns(r,[],!0);return A.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)=>v(s,`${e}[${a}]`,t,o))}var XI="__op";function N(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+XI;let n=(...s)=>{A.startScope(t);try{let a=o(...s);return mm(a)&&console.error("Cannot return a Promise inside of tidy."),A.endScope(a),a}catch(a){throw A.endScope(null),a}};return Object.defineProperty(n,"name",{value:t,configurable:!0}),n}function L3(r,e){let t=v(r,"real","complex"),o=v(e,"imag","complex");Ge(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 A.runKernel(Xl,n)}var wo=N({complex_:L3});function qr(r,e,t,o){if(o==null&&(o=Dc(r)),o==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!nr(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){pm(e);let n=dt(e),s=dt(t);E(n===s,()=>`Based on the provided shape, [${e}], the tensor should have ${n} values but has ${s}`);for(let a=0;a`Error creating a new Tensor. Inferred shape (${t}) does not match the provided shape (${e}). `)}}return!nr(r)&&!Array.isArray(r)&&(r=[r]),e=e||t,r=o!=="string"?Lc(r,o):ns(r,[],!0),A.makeTensor(r,e,o)}function Fr(r,e,t){let o=kr(r,t);return qr(r,e,o,t)}var _m={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};var Gh=4;async function YI(r,e){let t=[],o=[],n=Array.isArray(r)?r.map(a=>a.name):Object.keys(r);for(let a=0;a{let m=await l.bytes(),f=m.reduce((g,y)=>g+y.length,0)+Gh*m.length,d=new Uint8Array(f),h=0;for(let g=0;g{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 Rb=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function ZI(r){return Rb?Buffer.byteLength(r):new Blob([r]).size}function JI(r){if(Rb)return Buffer.from(r).toString("base64");let e=new Uint8Array(r),t="";for(let o=0,n=e.length;o{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 Fb(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 Oi(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:ZI(JSON.stringify(r.modelTopology)),weightSpecsBytes:r.weightSpecs==null?0:ZI(JSON.stringify(r.weightSpecs)),weightDataBytes:r.weightData==null?0:r.weightData.byteLength}}function V3(){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 W3(){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 G3(){let r=new Uint32Array(64);for(let e=0;e<64;e++)r[e]=1024;return r[0]=r[32]=0,r}function B3(){let r=V3(),e=W3(),t=G3();return o=>{let n=new ArrayBuffer(4*o.length),s=new Uint32Array(n);for(let a=0;a>10]+(i&1023)]+e[i>>10];s[a]=l}return new Float32Array(n)}}var Tt=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Tt.instance==null&&(Tt.instance=new Tt),Tt.instance}static registerSaveRouter(e){Tt.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Tt.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Tt.getHandlers(e,"save")}static getLoadHandlers(e,t){return Tt.getHandlers(e,"load",t)}static getHandlers(e,t,o){let n=[];return(t==="load"?Tt.getInstance().loadRouters:Tt.getInstance().saveRouters).forEach(a=>{let i=a(e,o);i!==null&&n.push(i)}),n}},eN=r=>Tt.registerSaveRouter(r),tN=r=>Tt.registerLoadRouter(r),rN=r=>Tt.getSaveHandlers(r),oN=(r,e)=>Tt.getLoadHandlers(r,e);var Ob="tensorflowjs",Pb=1,_u="models_store",nl="model_info_store";function nN(){if(!W().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");let r=typeof window=="undefined"?self:window,e=r.indexedDB||r.mozIndexedDB||r.webkitIndexedDB||r.msIndexedDB||r.shimIndexedDB;if(e==null)throw new Error("The current browser does not appear to support IndexedDB.");return e}function Mb(r){let e=r.result;e.createObjectStore(_u,{keyPath:"modelPath"}),e.createObjectStore(nl,{keyPath:"modelPath"})}var ba=class{constructor(e){if(this.indexedDB=nN(),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(Ob,Pb);s.onupgradeneeded=()=>Mb(s),s.onsuccess=()=>{let a=s.result;if(t==null){let i=a.transaction(_u,"readonly"),u=i.objectStore(_u).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=Oi(t),l=a.transaction(nl,"readwrite"),u=l.objectStore(nl),c=u.put({modelPath:this.modelPath,modelArtifactsInfo:i}),p;c.onsuccess=()=>{p=a.transaction(_u,"readwrite");let f=p.objectStore(_u).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:i});f.onsuccess=()=>o({modelArtifactsInfo:i}),f.onerror=d=>{u=l.objectStore(nl);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 sN=r=>W().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(ba.URL_SCHEME)?U3(r.slice(ba.URL_SCHEME.length)):null;Tt.registerSaveRouter(sN);Tt.registerLoadRouter(sN);function U3(r){return new ba(r)}function j3(r){return r.startsWith(ba.URL_SCHEME)?r.slice(ba.URL_SCHEME.length):r}var Lb=class{constructor(){this.indexedDB=nN()}async listModels(){return new Promise((e,t)=>{let o=this.indexedDB.open(Ob,Pb);o.onupgradeneeded=()=>Mb(o),o.onsuccess=()=>{let n=o.result,s=n.transaction(nl,"readonly"),i=s.objectStore(nl).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=j3(e),new Promise((t,o)=>{let n=this.indexedDB.open(Ob,Pb);n.onupgradeneeded=()=>Mb(n),n.onsuccess=()=>{let s=n.result,a=s.transaction(nl,"readwrite"),i=a.objectStore(nl),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(_u,"readwrite");let f=u.objectStore(_u).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",iN="info",q3="model_topology",H3="weight_specs",K3="weight_data",X3="model_metadata";function aN(r){return{info:[Gc,r,iN].join(_a),topology:[Gc,r,q3].join(_a),weightSpecs:[Gc,r,H3].join(_a),weightData:[Gc,r,K3].join(_a),modelMetadata:[Gc,r,X3].join(_a)}}function Y3(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 Z3(r){return r.startsWith(wa.URL_SCHEME)?r.slice(wa.URL_SCHEME.length):r}var wa=class{constructor(e){if(!W().getBool("IS_BROWSER")||typeof window=="undefined"||typeof window.localStorage=="undefined")throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,e==null||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=aN(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=Oi(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,JI(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=QI(a),t}};wa.URL_SCHEME="localstorage://";var lN=r=>W().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(wa.URL_SCHEME)?J3(r.slice(wa.URL_SCHEME.length)):null;Tt.registerSaveRouter(lN);Tt.registerLoadRouter(lN);function J3(r){return new wa(r)}var zb=class{constructor(){E(W().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),E(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=Gc+_a,o=_a+iN;for(let n=0;n"scheme must not be undefined or null."),e.endsWith(Uc)&&(e=e.slice(0,e.indexOf(Uc))),E(e.length>0,()=>"scheme must not be an empty string.");let o=Hr.getInstance();E(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(Uc)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Hr.getSchemes().join(",")}`);return{scheme:r.split(Uc)[0],path:r.split(Uc)[1]}}async function uN(r,e,t=!1){E(r!==e,()=>`Old path and new path are the same: '${r}'`);let o=Tt.getLoadHandlers(r);E(o.length>0,()=>`Copying failed because no load handler is found for source URL ${r}.`),E(o.length<2,()=>`Copying failed because more than one (${o.length}) load handlers for source URL ${r}.`);let n=o[0],s=Tt.getSaveHandlers(e);E(s.length>0,()=>`Copying failed because no save handler is found for destination URL ${e}.`),E(s.length<2,()=>`Copying failed because more than one (${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 Hr.getManager(i).removeModel(l);let p=await a.save(c);return t&&!u&&await Hr.getManager(i).removeModel(l),p.modelArtifactsInfo}async function cN(){let r=Hr.getSchemes(),e={};for(let t of r){let o=await Hr.getManager(t).listModels();for(let n in o){let s=t+Uc+n;e[s]=o[n]}}return e}async function pN(r){let e=jh(r);return Hr.getManager(e.scheme).removeModel(e.path)}async function mN(r,e){return uN(r,e,!1)}async function fN(r,e){return uN(r,e,!0)}var dN=class{fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return this.textEncoder==null&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}};if(W().get("IS_BROWSER")){W().setPlatform("browser",new dN);try{Hr.registerManager(wa.URL_SCHEME,new zb)}catch(r){}try{Hr.registerManager(ba.URL_SCHEME,new Lb)}catch(r){}}var Q3={importFetch:()=>hN()},Bb;var gN=class{constructor(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return W().global.fetch!=null?W().global.fetch(e,t):(Bb==null&&(Bb=Q3.importFetch()),Bb(e,t))}now(){let e=process.hrtime();return e[0]*1e3+e[1]/1e6}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return e.length===0?"":new this.util.TextDecoder(t).decode(e)}};W().get("IS_NODE")&&W().setPlatform("node",new gN);function Ie(r,e="float32",t){return e=e||"float32",pm(r),new ct(r,e,t)}function eV(r,e){let t=v(r,"x","cast");if(!cb(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 A.runKernel(Fo,o,n)}var ne=N({cast_:eV});function tV(r){let t={x:v(r,"x","clone","string_or_numeric")};return A.runKernel(cs,t)}var Po=N({clone_:tV});function Vb(r,e=!1){console.log(r.toString(e))}Db();var rV={buffer:Ie,cast:ne,clone:Po,print:Vb};UI(rV);var Cr={};et(Cr,{browserFiles:()=>bN,browserHTTPRequest:()=>vN,concatenateArrayBuffers:()=>Wc,copyModel:()=>mN,decodeWeights:()=>Uh,encodeWeights:()=>YI,fromMemory:()=>CN,getLoadHandlers:()=>oN,getModelArtifactsInfoForJSON:()=>Oi,getSaveHandlers:()=>rN,http:()=>Kh,isHTTPScheme:()=>Hh,listModels:()=>cN,loadWeights:()=>_N,moveModel:()=>fN,registerLoadRouter:()=>tN,registerSaveRouter:()=>eN,removeModel:()=>pN,weightsLoaderFactory:()=>Ub,withSaveHandler:()=>IN});var oV="model",nV=".json",sV=".weights.bin";function xN(r){return new Promise(e=>setTimeout(e)).then(r)}var sl=class{constructor(e){if(!W().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(sl.URL_SCHEME)&&(e=e.slice(sl.URL_SCHEME.length)),(e==null||e.length===0)&&(e=oV),this.modelTopologyFileName=e+nV,this.weightDataFileName=e+sV}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 xN(()=>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 xN(()=>i.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Oi(e)}}}};sl.URL_SCHEME="downloads://";var yN=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=y=>{let b=y.target.result,_=m.indexOf(h);if(f[_]=b,f.indexOf(null)===-1){let w={modelTopology:l,weightSpecs:p,weightData:Wc(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=y=>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=>Fb(a.name)),s={};for(let a of e)a.paths.forEach(i=>{let l=Fb(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}},aV=r=>W().getBool("IS_BROWSER")&&!Array.isArray(r)&&r.startsWith(sl.URL_SCHEME)?iV(r.slice(sl.URL_SCHEME.length)):null;Tt.registerSaveRouter(aV);function iV(r="model"){return new sl(r)}function bN(r){return new yN(r)}function Wb(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){E(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function i(l,u){E(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),E(u>=0&&u<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${u}`),E(u>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${u}`)}return Promise.all(r.map(s))}async function Gb(r,e){e==null&&(e={});let t=e.fetchFunc==null?W().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 Wb(o,e.onProgress,n,s)).map(p=>p.arrayBuffer()),l=.5,u=1;return e.onProgress==null?await Promise.all(i):await Wb(i,e.onProgress,l,u)}async function _N(r,e="",t,o){return Ub(a=>Gb(a,{requestInit:o}))(r,e,t)}function Ub(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 y="quantization"in g?g.quantization.dtype:g.dtype,b=_m[y]*dt(g.shape),_=()=>{n[d]=!0,s[d]==null&&(s[d]=[]),s[d].push({manifestEntry:g,groupOffset:h,sizeBytes:b})};o!=null?o.forEach((w,k)=>{w===g.name&&(_(),a[k]=!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{let k=g.slice(w.groupOffset,w.groupOffset+w.sizeBytes),$=Uh(k,[w.manifestEntry]);for(let T in $)p[T]=$[T]}),m+=d}),p}}var lV="application/octet-stream",uV="application/json",qh=class{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(E(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=W().platform.fetch,E(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&E(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let 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:uV}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:lV}),"model.weights.bin");let s=await this.fetch(this.path,t);if(s.ok)return{modelArtifactsInfo:Oi(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]=cV(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 Gb(i,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[a,Wc(u)]}};qh.URL_SCHEME_REGEX=/^https?:\/\//;function cV(r){let e=r.lastIndexOf("/"),t=r.lastIndexOf("?"),o=r.substring(0,e),n=t>e?r.substring(t):"";return[o+"/",n]}function Hh(r){return r.match(qh.URL_SCHEME_REGEX)!=null}var wN=(r,e)=>{if(typeof fetch=="undefined"&&(e==null||e.fetchFunc==null))return null;{let t=!0;if(Array.isArray(r)?t=r.every(o=>Hh(o)):t=Hh(r),t)return Kh(r,e)}return null};Tt.registerSaveRouter(wN);Tt.registerLoadRouter(wN);function Kh(r,e){return new qh(r,e)}function vN(r,e){return Kh(r,e)}var Xh=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},kN=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function CN(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 IN(r){return new kN(r)}var NN={};et(NN,{confusionMatrix:()=>hV});function pV(r,e,t=!1,o=!1){let n=v(r,"a","matMul"),s=v(e,"b","matMul");[n,s]=Ue(n,s);let a={a:n,b:s},i={transposeA:t,transposeB:o};return A.runKernel(Yo,a,i)}var je=N({matMul_:pV});function mV(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:v(r,"indices","oneHot","int32")},a={depth:e,onValue:t,offValue:o};return A.runKernel(yn,s,a)}var ks=N({oneHot_:mV});function fV(r,e){let t=v(r,"x","transpose");if(e==null&&(e=t.shape.map((s,a)=>a).reverse()),E(t.rank===e.length,()=>`Error in transpose: rank of input ${t.rank} must match length of perm ${e}.`),e.forEach(s=>{E(s>=0&&s`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 A.runKernel(Pn,o,n)}var qe=N({transpose_:fV});function dV(r,e,t){let o=v(r,"labels","confusionMatrix"),n=v(e,"predictions","confusionMatrix");E(t==null||t>0&&Number.isInteger(t),()=>`If provided, numClasses must be a positive integer, but got ${t}`),E(o.rank===1,()=>`Expected the rank of labels to be 1, but got ${o.rank}`),E(n.rank===1,()=>`Expected the rank of predictions to be 1, but got ${n.rank}`),E(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.`),E(t>0&&Number.isInteger(t),()=>`numClasses is required to be a positive integer, but got ${t}`);let s=ks(ne(o,"int32"),t),a=ks(ne(n,"int32"),t),i=qe(s),l=je(i,a);return ne(l,"int32")}var hV=N({confusionMatrix_:dV});var Yh={};et(Yh,{fromPixels:()=>yV,toPixels:()=>xV});function jb(r,e,t){if(Ro(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 qr(r,e,o,t)}var jc;function gV(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 element.")}if(dm(Pc,A.backendName)!=null){let d={pixels:r},h={numChannels:e};return A.runKernel(Pc,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)&&(jc==null&&(jc=document.createElement("canvas").getContext("2d")),jc.canvas.width=u,jc.canvas.height=c,jc.drawImage(r,0,0,u,c),p=jc.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;h4||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;u1)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 yV=N({fromPixels_:gV});var Zh={};et(Zh,{prepareAndValidate:()=>SN});function SN(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(dt(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;pp/u),1].slice(0,s);return[l,a,u,c]}var Jh={};et(Jh,{calculateShapes:()=>TN,validateInput:()=>Qh,validateUpdateShape:()=>qb});function qb(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.rank1?e.shape[o-1]:1,s=t.length,a=1;for(let p=n;pbV,computeFlatOffset:()=>wV,computeOutShape:()=>EN,getNormalizedAxes:()=>LN,isSliceContinous:()=>_V,maskToAxes:()=>eg,parseSliceParams:()=>Hb,sliceInfo:()=>vV,startForAxis:()=>PN,startIndicesWithElidedDims:()=>RN,stopForAxis:()=>MN,stopIndicesWithElidedDims:()=>FN,stridesForAxis:()=>ON,stridesWithElidedDims:()=>AN});function bV(r,e,t){let o=r.shape.length;E(o===e.length,()=>`Error in slice${o}D: Length of begin ${e} must match the rank of the array (${o}).`),E(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`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 EN(r,e,t){let o=[];for(let n=0;n0){let f=e[0],d=t+1;c=RN(a,f,d,o,r),p=FN(i,f,d,n,r),m=AN(s,f,d,r)}else for(let f=0;f-1)s[i]=0;else{let l=DN(e,t,i),u=o[l];r&1<-1)s[i]=Number.MAX_SAFE_INTEGER;else{let l=DN(e,t,i),u=o[l];r&1<0?a=Number.MIN_SAFE_INTEGER:a=Number.MAX_SAFE_INTEGER);let l=o[n];return a<0&&(a+=l),a=Ac(0,a,l-1),a}function MN(r,e,t,o,n,s){let a=e[n],i=t[n]||1;(r&1<0?a=Number.MAX_SAFE_INTEGER:a=Number.MIN_SAFE_INTEGER);let l=o[n];return a<0&&(a+=l),i>0?a=Ac(0,a,l):a=Ac(-1,a,l-1),a}function _V(r,e,t){let o=t.length;for(let n=0;n1){o=n;break}for(let n=o+1;n0||t[n]!==r[n])return!1;return!0}function wV(r,e){let t=r.length>0?r[r.length-1]:1;for(let o=0;o{E(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.lengtha>=0?a:(E(a===-1,()=>`Negative size values should be exactly -1 but got ${a} for the slice() size at index ${i}.`),r.shape[i]-o[i])),[o,s]}function vV(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(T=>{u[T]=0,c[T]=1,h.splice(T,0,1)});let{begin:g,end:y,strides:b}=LN(h,m,f,u,c,p,n,s,a);u=g,c=y,p=b;let _=eg(l);_.forEach(T=>{c[T]=u[T]+1,p[T]=1});let w=EN(u,c,p),k=w.filter((T,F)=>_.indexOf(F)===-1);return{nonStrided:p.every(T=>T===1),$begin:u,$end:c,$strides:p,size:w,newShape:h,outShape:k}}var te={};et(te,{Serializable:()=>tg,SerializationMap:()=>va,registerClass:()=>oo});var tg=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},va=class{constructor(){this.classNameMap={}}static getMap(){return va.instance==null&&(va.instance=new va),va.instance}static register(e){va.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function oo(r){E(r.className!=null,()=>"Class being registered does not have the static className property defined."),E(typeof r.className=="string",()=>"className is required to be a string, but got type "+typeof r.className),E(r.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),va.register(r)}var zN={};et(zN,{TEST_EPSILON_FLOAT16:()=>BN,encodeStrings:()=>VN,expectArrayBuffersEqual:()=>EV,expectArraysClose:()=>CV,expectArraysEqual:()=>NV,expectNumbersClose:()=>SV,expectPromiseToFail:()=>IV,expectValuesInRange:()=>TV,testEpsilon:()=>Kb});var kV=.001,BN=.1;function CV(r,e,t){return t==null&&(t=Kb()),Xb(r,e,(o,n)=>Yb(o,n,t))}function Kb(){return A.backend.floatPrecision()===32?kV:BN}function Xb(r,e,t){let o=!0;if((nr(r)||nr(e))&&(o=!1),nr(r)&&nr(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(!jr(a,i))throw new Error(`Arrays have different shapes. Actual: [${a}]. Expected: [${i}]`)}let n=nr(r)?r:ns(r),s=nr(e)?e:ns(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;ae.fail(),()=>e())}function NV(r,e){let t=typeof e=="string"||typeof e=="number"||typeof e=="boolean"?[e]:e;return ss(r)||ss(r[0])||ss(e)||ss(e[0])?Xb(r,t,(o,n)=>o==n):Xb(r,e,(o,n)=>Yb(o,n,0))}function SV(r,e,t){if(t==null&&(t=Kb()),!Yb(r,e,t))throw new Error(`Numbers differ: actual === ${r}, expected === ${e}`)}function Yb(r,e,t){return!isFinite(r)&&!isFinite(e)?!0:!(isNaN(r)||isNaN(e)||Math.abs(r-e)>t)}function TV(r,e,t){for(let o=0;ot)throw new Error(`Value out of range:${r[o]} low: ${e}, high: ${t}`)}function EV(r,e){expect(new Float32Array(r)).toEqual(new Float32Array(e))}function VN(r){for(let e=0;et.dispose())}function Dt(r){return A.keep(r)}function OV(r){return A.time(r)}function WN(r){return A.setBackend(r)}function PV(){return A.ready()}function MV(){return A.backendName}function LV(r){A.removeBackend(r)}function zV(r){return A.findBackend(r)}function BV(r){return A.findBackendFactory(r)}function wu(r,e,t=1){return A.registerBackend(r,e,t)}function Jb(){return A.backend}function VV(r,e){W().setPlatform(r,e)}function WV(r,e){let t=v(r,"a","add"),o=v(e,"b","add");[t,o]=Ue(t,o);let n={a:t,b:o};return A.runKernel(bo,n)}var ee=N({add_:WV});function GV(r,e){let t=v(r,"a","floorDiv"),o=v(e,"b","floorDiv");[t,o]=Ue(t,o);let n={a:t,b:o};return A.runKernel(sn,n)}var vu=N({floorDiv_:GV});function UV(r,e){let t=v(r,"a","div"),o=v(e,"b","div");if([t,o]=Ue(t,o),t.dtype==="int32"&&o.dtype==="int32")return vu(t,o);let n={a:t,b:o},s={};return A.runKernel(rn,n,s)}var fe=N({div_:UV});function jV(r,e){let t=v(r,"a","mul"),o=v(e,"b","mul");[t,o]=Ue(t,o);let n={a:t,b:o};return A.runKernel(xn,n)}var O=N({mul_:jV});function qV(r){let e=v(r,"x","abs");if(e.dtype==="complex64"){let t={x:e};return A.runKernel(ia,t)}else{let t={x:e};return A.runKernel(is,t)}}var Et=N({abs_:qV});function HV(r){let t={x:v(r,"x","acos")};return A.runKernel(js,t)}var wm=N({acos_:HV});function KV(r){let t={x:v(r,"x","acosh")};return A.runKernel(qs,t)}var vm=N({acosh_:KV});function XV(r){E(Array.isArray(r),()=>"The argument passed to tf.addN() must be a list of tensors"),E(r.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${r.length}`);let e=r.map((n,s)=>v(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(!jr(n.shape,t.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let o=e;return A.runKernel(Ho,o)}var Qb=N({addN_:XV});function YV(r,e=null,t=!1){let n={x:v(r,"x","all","bool")},s={axis:e,keepDims:t};return A.runKernel(Ul,n,s)}var ku=N({all_:YV});function ZV(r,e=null,t=!1){let n={x:v(r,"x","any","bool")},s={axis:e,keepDims:t};return A.runKernel(jl,n,s)}var il=N({any_:ZV});function JV(r,e=0){let o={x:v(r,"x","argMax")},n={axis:e};return A.runKernel(Ko,o,n)}var al=N({argMax_:JV});function QV(r,e=0){let o={x:v(r,"x","argMin")},n={axis:e};return A.runKernel(oa,o,n)}var km=N({argMin_:QV});function eW(r){let t={x:v(r,"x","asin")};return A.runKernel(Hs,t)}var Cm=N({asin_:eW});function tW(r){let t={x:v(r,"x","asinh")};return A.runKernel(Ks,t)}var Im=N({asinh_:tW});function rW(r){let t={x:v(r,"x","atan")};return A.runKernel(Xs,t)}var Nm=N({atan_:rW});function oW(r,e){let t=v(r,"a","atan2"),o=v(e,"b","atan2");[t,o]=Ue(t,o);let n={a:t,b:o};return A.runKernel(Zs,n)}var Sm=N({atan2_:oW});function nW(r){let t={x:v(r,"x","atanh")};return A.runKernel(Ys,t)}var Tm=N({atanh_:nW});function sW(r,e,t,o,n="NHWC",s){let a=r[3],i=[...e,a],l=GN(n);return Cu(r,i,t,s,o,null,null,l)}function e_(r,e,t,o,n,s,a="channelsLast"){let[i,l]=rg(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 Cu(r,u,t,o,n,s,!1,a)}function iW(r,e,t,o,n,s,a="NDHWC"){let[i,l,u]=t_(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 UN(r,c,t,o,n,!1,p,s)}function Cu(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]=rg(t),[y,b]=rg(o),_=Hc(m,y),w=Hc(f,b),{padInfo:k,outHeight:$,outWidth:T}=aW(n,u,c,h,g,_,w,s,i),F=a?d*p:d,M;return i==="channelsFirst"?M=[l,F,$,T]:i==="channelsLast"&&(M=[l,$,T,F]),{batchSize:l,dataFormat:i,inHeight:u,inWidth:c,inChannels:p,outHeight:$,outWidth:T,outChannels:F,padInfo:k,strideHeight:h,strideWidth:g,filterHeight:m,filterWidth:f,effectiveFilterHeight:_,effectiveFilterWidth:w,dilationHeight:y,dilationWidth:b,inShape:r,outShape:M,filterShape:e}}function UN(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,[y,b,_]=t_(t),[w,k,$]=t_(o),T=Hc(f,w),F=Hc(d,k),M=Hc(h,$),{padInfo:L,outDepth:G,outHeight:H,outWidth:U}=lW(n,u,c,p,y,b,_,T,F,M,i),Z=s?g*m:g,K;return a==="channelsFirst"?K=[l,Z,G,H,U]:a==="channelsLast"&&(K=[l,G,H,U,Z]),{batchSize:l,dataFormat:a,inDepth:u,inHeight:c,inWidth:p,inChannels:m,outDepth:G,outHeight:H,outWidth:U,outChannels:Z,padInfo:L,strideDepth:y,strideHeight:b,strideWidth:_,filterDepth:f,filterHeight:d,filterWidth:h,effectiveFilterDepth:T,effectiveFilterHeight:F,effectiveFilterWidth:M,dilationDepth:w,dilationHeight:k,dilationWidth:$,inShape:r,outShape:K,filterShape:e}}function uW(r,e,t,o,n){o==null&&(o=r_(r,e,t));let s=r[0],a=r[1],i=Iu((s-e+2*o)/t+1,n),l=Iu((a-e+2*o)/t+1,n);return[i,l]}function cW(r,e,t,o,n,s){n==null&&(n=r_(r,e,o));let a=r[0],i=r[1],l=r[2],u=Iu((a-e+2*n)/o+1,s),c=Iu((i-e+2*n)/o+1,s),p=Iu((l-e+2*n)/o+1,s);return[u,c,p,t]}function r_(r,e,t,o=1){let n=Hc(e,o);return Math.floor((r[0]*(t-1)-t+n)/2)}function rg(r){return typeof r=="number"?[r,r,r]:r.length===2?[r[0],r[1],1]:r}function t_(r){return typeof r=="number"?[r,r,r]:r}function Hc(r,e){return e<=1?r:r+(r-1)*(e-1)}function aW(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=uW([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),y=f-g;u={top:d,bottom:h,left:g,right:y,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=Iu((e-s+m+f)/o+1,i),p=Iu((t-a+d+h)/n+1,i)}else throw Error(`Unknown padding parameter: ${r}`);return{padInfo:u,outHeight:c,outWidth:p}}function lW(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=cW([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,y=(d-1)*a+u-o,b=Math.floor(h/2),_=h-b,w=Math.floor(g/2),k=g-w,$=Math.floor(y/2),T=y-$;p={top:w,bottom:k,left:$,right:T,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 Iu(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 Mo(r){let[e,t,o]=rg(r);return e===1&&t===1&&o===1}function Pt(r,e){return Mo(r)||Mo(e)}function GN(r){if(r==="NHWC")return"channelsLast";if(r==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${r}`)}function pW(r,e){let o={x:v(r,"x","reshape","string_or_numeric")},n={shape:e};return A.runKernel(ds,o,n)}var z=N({reshape_:pW});function mW(r,e,t,o,n){let s=v(r,"x","avgPool","float32"),a=1;E(Pt(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=z(s,[1,s.shape[0],s.shape[1],s.shape[2]])),E(i.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`),n!=null&&E(it(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=A.runKernel(Xo,u,c);return p=ne(p,s.dtype),l?z(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var ka=N({avgPool_:mW});function fW(r,e,t,o,n,s="NDHWC",a){a==null?a=[1,1,1]:Ot("dilations is deprecated, this field will be gone in v3.0.0.");let i=v(r,"x","avgPool3d","float32"),l=i,u=!1;i.rank===4&&(u=!0,l=z(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),E(l.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${l.rank}.`),E(s==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),E(Pt(t,a),()=>`Error in avgPool3d: Either strides or dilations must be 1. Got strides ${t} and dilations '${a}'`),n!=null&&E(it(o),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${n} but got pad ${o}.`);let c={x:l},p={filterSize:e,strides:t,pad:o,dimRoundingMode:n,dataFormat:s,dilations:a},m=A.runKernel(na,c,p);return m=ne(m,l.dtype),u?z(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}var Em=N({avgPool3d_:fW});function dW(r,e=0){E(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 Po(t[0]);let o=t,n={axis:e};return A.runKernel(as,o,n)}var Je=N({concat_:dW});function hW(r){let t={x:v(r,"x","sigmoid")};return A.runKernel(En,t)}var Kr=N({sigmoid_:hW});function gW(r,e,t){let o=v(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 A.runKernel(gs,n,s)}var Fe=N({slice_:gW});function xW(r){let t={x:v(r,"x","tanh")};return A.runKernel(On,t)}var Pi=N({tanh_:xW});function yW(r,e,t,o,n,s){let a=v(r,"forgetBias","basicLSTMCell"),i=v(e,"lstmKernel","basicLSTMCell"),l=v(t,"lstmBias","basicLSTMCell"),u=v(o,"data","basicLSTMCell"),c=v(n,"c","basicLSTMCell"),p=v(s,"h","basicLSTMCell"),m=Je([u,p],1),f=je(m,i),d=ee(f,l),h=d.shape[0],g=d.shape[1]/4,y=[h,g],b=Fe(d,[0,0],y),_=Fe(d,[0,g],y),w=Fe(d,[0,g*2],y),k=Fe(d,[0,g*3],y),$=ee(O(Kr(b),Pi(_)),O(c,Kr(ee(a,w)))),T=O(Pi($),Kr(k));return[$,T]}var bW=N({basicLSTMCell_:yW});function _W(r,e,t){let o=v(r,"x","batchToSpaceND"),n=e.reduce((i,l)=>i*l);E(o.rank>=1+e.length,()=>`input rank is ${o.rank} but should be > than blockShape.length ${e.length}`),E(t.length===e.length,()=>`crops.length is ${t.length} but should be equal to blockShape.length ${e.length}`),E(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 A.runKernel(sa,s,a)}var Ca=N({batchToSpaceND_:_W});function jN(r){let e;return r.rank===0||r.rank===1?e=z(r,[1,1,1,r.size]):r.rank===2?e=z(r,[1,1,r.shape[0],r.shape[1]]):r.rank===3?e=z(r,[1,r.shape[0],r.shape[1],r.shape[2]]):e=r,e}function wW(r,e,t,o,n,s){s==null&&(s=.001);let a=v(r,"x","batchNorm"),i=v(e,"mean","batchNorm"),l=v(t,"variance","batchNorm"),u;n!=null&&(u=v(n,"scale","batchNorm"));let c;o!=null&&(c=v(o,"offset","batchNorm")),E(i.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),E(c==null||i.rank===c.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),E(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let m={x:jN(a),scale:u,offset:c,mean:i,variance:l},f={varianceEpsilon:s},d=A.runKernel(an,m,f);return z(d,a.shape)}var Ln=N({batchNorm_:wW});function vW(r,e,t,o,n,s){let a=v(r,"x","batchNorm"),i=v(e,"mean","batchNorm"),l=v(t,"variance","batchNorm"),u;n!=null&&(u=v(n,"scale","batchNorm"));let c;return o!=null&&(c=v(o,"offset","batchNorm")),E(a.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${a.rank}.`),E(i.rank===2||i.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`),E(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&E(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),c!=null&&E(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${c.rank}.`),Ln(a,i,l,c,u,s)}var o_=N({batchNorm2d_:vW});function kW(r,e,t,o,n,s){let a=v(r,"x","batchNorm"),i=v(e,"mean","batchNorm"),l=v(t,"variance","batchNorm"),u;n!=null&&(u=v(n,"scale","batchNorm"));let c;return o!=null&&(c=v(o,"offset","batchNorm")),E(a.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${a.rank}.`),E(i.rank===3||i.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`),E(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&E(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),c!=null&&E(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${c.rank}.`),Ln(a,i,l,c,u,s)}var n_=N({batchNorm3d_:kW});function CW(r,e,t,o,n,s){let a=v(r,"x","batchNorm"),i=v(e,"mean","batchNorm"),l=v(t,"variance","batchNorm"),u;n!=null&&(u=v(n,"scale","batchNorm"));let c;return o!=null&&(c=v(o,"offset","batchNorm")),E(a.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${a.rank}.`),E(i.rank===4||i.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`),E(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),u!=null&&E(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`),c!=null&&E(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${c.rank}.`),Ln(a,i,l,c,u,s)}var s_=N({batchNorm4d_:CW});function IW(r,e,t){let o=v(r,"x","bincount"),n=v(e,"weights","bincount");E(o.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${o.dtype}`),E(t>=0,()=>`size must be non-negative, but got ${t}.`),E(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 A.runKernel(Kl,s,a)}var i_=N({bincount_:IW});function NW(r,e){let t=v(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.lengtht.rank){let u=t.shape.slice();for(;u.length=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 Po(t);let i={x:t},l={reps:s};return A.runKernel(_o,i,l)}var ll=N({broadcastTo_:NW});function SW(r){let t={x:v(r,"x","ceil")};return A.runKernel(Js,t)}var Am=N({ceil_:SW});function TW(r,e,t){let o=v(r,"x","clipByValue");E(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 A.runKernel(Oo,n,s)}var ir=N({clipByValue_:TW});function EW(r){return Je(r,0)}var a_=N({concat1d_:EW});function AW(r,e){return Je(r,e)}var l_=N({concat2d_:AW});function DW(r,e){return Je(r,e)}var u_=N({concat3d_:DW});function $W(r,e){return Je(r,e)}var c_=N({concat4d_:$W});function RW(r,e,t,o,n="NHWC",s=[1,1],a){let i=v(r,"x","conv2d"),l=v(e,"filter","conv2d"),u=i,c=!1;i.rank===3&&(c=!0,u=z(i,[1,i.shape[0],i.shape[1],i.shape[2]])),E(u.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`),E(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),a!=null&&E(it(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];E(p===l.shape[2],()=>`Error in conv2d: depth of input (${p}) must match input depth for filter ${l.shape[2]}.`),E(Pt(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=A.runKernel(Zo,m,f);return c?z(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Xr=N({conv2d_:RW});function FW(r,e,t,o,n="NWC",s=1,a){let i=v(r,"x","conv1d"),l=v(e,"filter","conv1d"),u=i,c=!1;i.rank===2&&(c=!0,u=z(i,[1,i.shape[0],i.shape[1]])),E(u.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`),E(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),a!=null&&E(it(o),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`),E(u.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`),E(Pt(t,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${t} and dilation '${s}'`),E(n==="NWC",()=>`Error in conv1d: got dataFormat of ${n} but only NWC is currently supported.`);let p=z(l,[1,l.shape[0],l.shape[1],l.shape[2]]),m=z(u,[u.shape[0],1,u.shape[1],u.shape[2]]),g=Xr(m,p,[1,t],o,"NHWC",[1,s],a);return c?z(g,[g.shape[2],g.shape[3]]):z(g,[g.shape[0],g.shape[2],g.shape[3]])}var Nu=N({conv1d_:FW});function OW(r,e,t,o,n,s="NHWC",a){E(r.length===e.rank,()=>`Length of inShape (${r.length}) and rank of dy (${e.rank}) must match`);let i=r,l=e,u=!1;e.rank===3&&(u=!0,l=z(e,[1,e.shape[0],e.shape[1],e.shape[2]]),i=[1,r[0],r[1],r[2]]),E(i.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`),E(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),E(t.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${t.rank}`);let c=s==="NHWC"?i[3]:i[1],p=s==="NHWC"?l.shape[3]:l.shape[1];E(c===t.shape[2],()=>`Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${t.shape[2]}.`),E(p===t.shape[3],()=>`Error in conv2dDerInput: depth of output (${p}) must match output depth for filter ${t.shape[3]}.`),a!=null&&E(it(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=A.runKernel(Jo,m,f);return u?z(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Kc=N({conv2DBackpropInput_:OW});function PW(r,e,t,o,n,s){let a=v(r,"x","conv2dTranspose"),i=v(e,"filter","conv2dTranspose");return Kc(t,a,i,o,n,"NHWC",s)}var Su=N({conv2dTranspose_:PW});function MW(r,e,t,o,n="NDHWC",s=[1,1,1]){let a=v(r,"x","conv3d"),i=v(e,"filter","conv3d"),l=a,u=!1;a.rank===4&&(u=!0,l=z(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]])),E(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),E(i.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`),E(l.shape[4]===i.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${i.shape[3]}.`),E(Pt(t,s),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`),E(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=A.runKernel(aa,c,p);return u?z(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}var Dm=N({conv3d_:MW});function LW(r,e,t,o,n){E(r.length===e.rank,()=>`Length of inShape (${r.length}) and rank of dy (${e.rank}) must match`);let s=r,a=e,i=!1;e.rank===4&&(i=!0,a=z(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]),s=[1,r[0],r[1],r[2],r[3]]);let l=s[4],u=a.shape[4];E(s.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`),E(a.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${a.rank}`),E(t.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${t.rank}`),E(l===t.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${t.shape[3]}.`),E(u===t.shape[4],()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${t.shape[4]}.`);let c={dy:a,filter:t},p={pad:n,strides:o,inputShape:s},m=A.runKernel(Jl,c,p);return i?z(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}var og=N({conv3DBackpropInput_:LW});function zW(r,e,t,o,n){let s=v(r,"x","conv3dTranspose"),a=v(e,"filter","conv3dTranspose");return og(t,s,a,o,n)}var BW=N({conv3dTranspose_:zW});function VW(r){let t={x:v(r,"x","cos")};return A.runKernel(Qo,t)}var Ia=N({cos_:VW});function WW(r){let t={x:v(r,"x","cosh")};return A.runKernel(Qs,t)}var Tu=N({cosh_:WW});function GW(r,e=0,t=!1,o=!1){let s={x:v(r,"x","cumsum")},a={axis:e,exclusive:t,reverse:o};return A.runKernel(en,s,a)}var Eu=N({cumsum_:GW});function UW(r,e,t,o=!1){let n=v(r,"x","denseBincount"),s=v(e,"weights","denseBincount");E(n.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${n.dtype}`),E(n.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${n.rank}.`),E(t>=0,()=>`size must be non-negative, but got ${t}.`),E(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 A.runKernel(Ql,a,i)}var p_=N({denseBincount_:UW});function jW(r,e,t="NHWC"){let o=v(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];E(n*e>=0,()=>`Negative dimension size caused by overflow when multiplying ${n} and ${e} for depthToSpace with input shape ${o.shape}`),E(s*e>=0,()=>`Negative dimension size caused by overflow when multiplying ${s} and ${e} for depthToSpace with input shape ${o.shape}`),E(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 A.runKernel(ti,i,l)}var $m=N({depthToSpace_:jW});function qW(r,e,t,o,n="NHWC",s=[1,1],a){let i=v(r,"x","depthwiseConv2d"),l=v(e,"filter","depthwiseConv2d"),u=i,c=!1;i.rank===3&&(c=!0,u=z(i,[1,i.shape[0],i.shape[1],i.shape[2]])),E(u.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),E(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),E(u.shape[3]===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${u.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),a!=null&&E(it(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=A.runKernel(tn,p,m);return c?z(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Lo=N({depthwiseConv2d_:qW});function HW(r){let t={x:v(r,"x","diag")};return A.runKernel(ru,t)}var KW=N({diag_:HW});function XW(r,e,t,o,n=[1,1],s="NHWC"){let a=v(r,"x","dilation2d"),i=v(e,"filter","dilation2d");E(a.rank===3||a.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${a.rank}.`),E(i.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`),E(s==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);let l=a,u=!1;a.rank===3&&(l=z(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=A.runKernel(la,c,p);return u?z(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Rm=N({dilation2d_:XW});function YW(r,e){let t=r.length,o=[];for(let n=0;n1&&a===1&&o.unshift(s)}return o}function Nt(r,e){let t=[];for(let o=0;o1)&&t.unshift(s)}return t}function Ve(r,e){let t=[],o=Math.max(r.length,e.length);for(let n=0;n"The first dimension of `a` must match the size of `condition`."),s.rank!==1&&Ge(s.shape,l.shape,"Error in where: ");let u={condition:s,t:i,e:l};return A.runKernel(hs,u)}var $t=N({where_:JW});function QW(r){let t={x:v(r,"x","zerosLike")};return A.runKernel(bs,t)}var Ne=N({zerosLike_:QW});function eG(r,e){let t=v(r,"a","div"),o=v(e,"b","div");[t,o]=Ue(t,o);let n=fe(t,o),s=Ne(n),a=Yr(o,s);return $t(a,s,n)}var Fm=N({divNoNan_:eG});function tG(r,e){let t=v(r,"t1","dot"),o=v(e,"t2","dot");E((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(E(n===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${n} and ${s}.`),t.rank===1&&o.rank===1){let a=z(t,[1,-1]),i=z(o,[-1,1]),l=je(a,i);return z(l,[])}else if(t.rank===1&&o.rank===2){let a=z(t,[1,-1]),i=z(o,[o.shape[0],o.shape[1]]),l=je(a,i);return z(l,[l.size])}else if(t.rank===2&&o.rank===1){let a=z(o,[-1,1]),i=je(t,a);return z(i,[i.size])}else{let a=z(o,[o.shape[0],o.shape[1]]);return je(t,a)}}var m_=N({dot_:tG});function rG(r){let t={x:v(r,"x","elu")};return A.runKernel(ri,t)}var Is=N({elu_:rG});function oG(r){let e=v(r,"x","erf");E(e.dtype==="int32"||e.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),e.dtype==="int32"&&(e=ne(e,"float32"));let t={x:e};return A.runKernel(oi,t)}var Om=N({erf_:oG});function nG(r){let t={x:v(r,"x","exp")};return A.runKernel(on,t)}var Qt=N({exp_:nG});function sG(r,e=0){let t=v(r,"x","expandDims","string_or_numeric");E(e<=t.rank,()=>"Axis must be <= rank of the tensor");let o={input:t},n={dim:e};return A.runKernel(ls,o,n)}var br=N({expandDims_:sG});function iG(r){let t={x:v(r,"x","expm1")};return A.runKernel(si,t)}var Pm=N({expm1_:iG});function aG(r,e){let t=v(r,"x","tile","string_or_numeric");E(t.rank===e.length,()=>`Error in transpose: rank of input ${t.rank} must match length of reps ${e}.`);let o={x:t},n={reps:e};return A.runKernel(_o,o,n)}var zo=N({tile_:aG});function lG(r,e,t,o="float32"){e==null&&(e=r);let n=Ie([r,e],o),s=r<=e?r:e;for(let i=0;i`Error in localResponseNormalization: x must be rank 3 or 4 but got rank ${s.rank}.`),E(it(e),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${e}.`);let a=s,i=!1;s.rank===3&&(i=!0,a=z(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=A.runKernel(ca,l,u);return i?z(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var Mm=N({localResponseNormalization_:_G});function wG(r){let t={x:v(r,"x","log")};return A.runKernel(cn,t)}var ar=N({log_:wG});function vG(r){let t={x:v(r,"x","log1p")};return A.runKernel(di,t)}var Du=N({log1p_:vG});function kG(r){return E(Gs(r),()=>"The f passed in grad(f) must be a function"),(e,t)=>{let o=v(e,"x","tf.grad","string_or_numeric"),n=t!=null?v(t,"dy","tf.grad"):null;return A.tidy(()=>{let{value:s,grads:a}=A.gradients(()=>r(o),[o],n);return n!=null&&Ge(s.shape,n.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),ng(a),a[0]})}}function CG(r){return E(Gs(r),()=>"The f passed in grads(f) must be a function"),(e,t)=>{E(Array.isArray(e),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let o=ya(e,"args","tf.grads","string_or_numeric"),n=t!=null?v(t,"dy","tf.grads"):null;return A.tidy(()=>{let{value:s,grads:a}=A.gradients(()=>r(...o),o,n);return n!=null&&Ge(s.shape,n.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),ng(a),a})}}function IG(r){return E(Gs(r),()=>"The f passed in valueAndGrad(f) must be a function"),(e,t)=>{E(e instanceof R,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),E(t==null||t instanceof R,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:o,value:n}=A.gradients(()=>r(e),[e],t);return ng(o),{grad:o[0],value:n}}}function NG(r){return E(Gs(r),()=>"The f passed in valueAndGrads(f) must be a function"),(e,t)=>{E(Array.isArray(e)&&e.every(n=>n instanceof R),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),E(t==null||t instanceof R,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let o=A.gradients(()=>r(...e),e,t);return t!=null&&Ge(o.value.shape,t.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),ng(o.grads),o}}function sg(r,e){E(Gs(r),()=>"The f passed in variableGrads(f) must be a function"),E(e==null||Array.isArray(e)&&e.every(u=>u instanceof ol),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let t=e!=null;if(!t){e=[];for(let u in A.registeredVariables)e.push(A.registeredVariables[u])}let o=t?e.filter(u=>!u.trainable):null,n=e.length;e=e.filter(u=>u.trainable),E(e.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${n} variables is trainable.`);let s=!0,{value:a,grads:i}=A.gradients(r,e,null,s);E(i.some(u=>u!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),E(a.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`);let l={};return e.forEach((u,c)=>{i[c]!=null&&(l[u.name]=i[c])}),o!=null&&o.forEach(u=>l[u.name]=null),{value:a,grads:l}}function Zr(r){return A.customGrad(r)}function ng(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 SG(r){let t={x:v(r,"x","neg")};return A.runKernel(ps,t)}var He=N({neg_:SG});function TG(r){let t={x:v(r,"x","softplus")};return A.runKernel(Si,t)}var Ss=N({softplus_:TG});function EG(r){let e=v(r,"x","logSigmoid");return Zr(o=>({value:He(Ss(He(o))),gradFunc:a=>O(a,Kr(He(o)))}))(e)}var x_=N({logSigmoid_:EG});function AG(r,e=null,t=!1){let n={x:v(r,"x","max")},s={reductionIndices:e,keepDims:t};return A.runKernel(pn,n,s)}var lr=N({max_:AG});function DG(r,e){let t=v(r,"a","sub"),o=v(e,"b","sub");[t,o]=Ue(t,o);let n={a:t,b:o};return A.runKernel(Fn,n)}var pe=N({sub_:DG});function $G(r,e=null,t=!1){let o=v(r,"x","sum");o.dtype==="bool"&&(o=ne(o,"int32"));let n={x:o},s={axis:e,keepDims:t};return A.runKernel(Dn,n,s)}var be=N({sum_:$G});function RG(r,e=-1){let t=v(r,"logits","logSoftmax");if(e===-1&&(e=t.rank-1),e!==t.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${t.rank} and axis was ${e}`);return Zr((n,s)=>{let a=!0,i=lr(n,e,!0),l=pe(n,i),u=pe(ne(l,"float32"),ar(be(Qt(l),e,a)));return s([u]),{value:u,gradFunc:(p,m)=>{let[f]=m,d=!0,h=Qt(f);return pe(p,O(be(p,e,d),h))}}})(t)}var $u=N({logSoftmax_:RG});function y_(r,e){for(let t=0;tr[s]);return[t,n]}function Bn(r,e){let t=e.map(o=>1);return qN(r,t,e)}function FG(r,e,t){E(y_(e,t),()=>`${r} supports only inner-most axes for now. Got axes ${e} and rank-${t} input.`)}function __(r,e){if(y_(r,e))return null;let t=[];for(let o=0;ot.push(o)),t}function Lm(r){return r.map((e,t)=>[t,e]).sort((e,t)=>e[1]-t[1]).map(e=>e[0])}function OG(r,e){let t=[];for(let o=e-r;o`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),E(Pt(t,a),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${t} and dilations '${a}'`),n!=null&&E(it(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=A.runKernel(fn,u,c);return l?z(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Aa=N({maxPool_:VG});function WG(r,e=[1,1,1],t,o,n,s="NDHWC",a){a==null?a=[1,1,1]:Ot("dilations is deprecated, this field will be gone in v3.0.0.");let i=v(r,"x","maxPool3d"),l=i,u=!1;i.rank===4&&(u=!0,l=z(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),E(l.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${l.rank}.`),E(s==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),E(Pt(t,a),()=>`Error in maxPool3d: Either strides or dilations must be 1. Got strides ${t} and dilations '${a}'`),n!=null&&E(it(o),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${n} but got pad ${o}.`);let c={x:l},p={filterSize:e,strides:t,pad:o,dimRoundingMode:n,dataFormat:s,dilations:a},m=A.runKernel(pa,c,p);return u?z(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}var Bm=N({maxPool3d_:WG});function GG(r,e,t,o,n=!1){let a={x:v(r,"x","maxPoolWithArgmax")},i={filterSize:e,strides:t,pad:o,includeBatchInIndex:n},l=A.runKernel(pu,a,i);return{result:l[0],indexes:l[1]}}var v_=N({maxPoolWithArgmax_:GG});function UG(r,e){let t=v(r,"a","maximum"),o=v(e,"b","maximum");[t,o]=Ue(t,o),t.dtype==="bool"&&(t=ne(t,"int32"),o=ne(o,"int32")),Ve(t.shape,o.shape);let n={a:t,b:o};return A.runKernel(mn,n)}var Ir=N({maximum_:UG});function jG(r,e=null,t=!1){let n={x:v(r,"x","mean")},s={axis:e,keepDims:t};return A.runKernel(dn,n,s)}var bt=N({mean_:jG});function qG(r,e=null,t=!1){let n={x:v(r,"x","min")},s={axis:e,keepDims:t};return A.runKernel(hn,n,s)}var Mi=N({min_:qG});function HG(r,e){let t=v(r,"a","minimum"),o=v(e,"b","minimum");[t,o]=Ue(t,o),t.dtype==="bool"&&(t=ne(t,"int32"),o=ne(o,"int32")),Ve(t.shape,o.shape);let n={a:t,b:o};return A.runKernel(gn,n)}var Bo=N({minimum_:HG});function KG(r,e,t){E(t==="reflect"||t==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${t}.`);let o=v(r,"x","mirrorPad");if(o.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");E(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"Invalid number of paddings. Must be length of 2 each."),E(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 A.runKernel(ma,a,s)}var Vm=N({mirrorPad_:KG});function XG(r,e){let t=v(r,"a","mod"),o=v(e,"b","mod");[t,o]=Ue(t,o);let n={a:t,b:o};return A.runKernel(gi,n)}var Fu=N({mod_:XG});function YG(r){let e=v(r,"x","square"),t={};return A.runKernel("Square",{x:e},t)}var Me=N({square_:YG});function ZG(r,e=null,t=!1){r=v(r,"x","moments");let o=tr(e,r.shape),n=bt(r,o,t),s=n.shape;t||(s=Bn(n.shape,o));let a=Me(pe(ne(r,"float32"),z(n,s))),i=bt(a,o,t);return{mean:n,variance:i}}var Yc=N({moments_:ZG});function JG(r,e,t,o){let n=v(e,"data","multiRNNCell"),s=ya(t,"c","multiRNNCell"),a=ya(o,"h","multiRNNCell"),i=n,l=[];for(let p=0;p2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${a}`);t=t||Math.random();let l={logits:a===1?z(n,[1,-1]):n},u={numSamples:e,seed:t,normalized:o},c=A.runKernel(mu,l,u);return a===1?z(c,[c.size]):c}var k_=N({multinomial_:e4});function t4(r,e){let t=v(r,"a","notEqual"),o=v(e,"b","notEqual");[t,o]=Ue(t,o),Ve(t.shape,o.shape);let n={a:t,b:o};return A.runKernel(xi,n)}var vo=N({notEqual_:t4});function pt(r,e="float32"){if(e==="complex64"){let o=pt(r,"float32"),n=pt(r,"float32");return wo(o,n)}let t=Rc(dt(r),e);return A.makeTensor(t,r,e)}function Nr(r,e="float32"){if(e==="complex64"){let o=Nr(r,"float32"),n=pt(r,"float32");return wo(o,n)}let t=cm(dt(r),e);return A.makeTensor(t,r,e)}function r4(r){let t={x:v(r,"x","onesLike")};return A.runKernel(ms,t)}var rr=N({onesLike_:r4});function o4(r,e){let t=v(r,"v1","outerProduct"),o=v(e,"v2","outerProduct");E(t.rank===1&&o.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${t.rank} and ${o.rank}.`);let n=z(t,[-1,1]),s=z(o,[1,-1]);return je(n,s)}var n4=N({outerProduct_:o4});function s4(r,e,t=0){let o=v(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 A.runKernel(bn,s,n)}var Pr=N({pad_:s4});function i4(r,e,t=0){return E(e.length===2,()=>"Invalid number of paddings. Must be length of 2."),Pr(r,[e],t)}var a4=N({pad1d_:i4});function l4(r,e,t=0){return E(e.length===2&&e[0].length===2&&e[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Pr(r,e,t)}var u4=N({pad2d_:l4});function c4(r,e,t=0){return E(e.length===3&&e[0].length===2&&e[1].length===2&&e[2].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Pr(r,e,t)}var p4=N({pad3d_:c4});function m4(r,e,t=0){return E(e.length===4&&e[0].length===2&&e[1].length===2&&e[2].length===2&&e[3].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Pr(r,e,t)}var f4=N({pad4d_:m4});function d4(r,e,t){let o=v(r,"x","spaceToBatchND");E(o.rank>=1+e.length,()=>`input rank ${o.rank} should be > than [blockShape] ${e.length}`),E(t.length===e.length,()=>`paddings.shape[0] ${t.length} must be equal to [blockShape] ${e.length}`),E(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 A.runKernel(ha,n,s)}var Da=N({spaceToBatchND_:d4});function x4(r,e,t,o,n,s){n==null&&(n=[1,1]),s==null&&(s=1),o===0&&(o="valid");let a=v(r,"x","maxPool"),i=a,l=!1;a.rank===3&&(l=!0,i=z(a,[1,a.shape[0],a.shape[1],a.shape[2]])),E(Pt(s,n),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${n}'`);let u=e_(i.shape,e,s,n,o),c=[u.dilationHeight,u.dilationWidth],p;o==="same"?p=g4([u.filterHeight,u.filterWidth],c):p=[[0,0],[0,0]];let m=c[0]===1&&c[1]===1,[f,d]=h4([u.inHeight,u.inWidth],c,p),h=m?o:"valid",g=m?i:Da(i,c,f),b=(t==="avg"?()=>ka(g,e,s,h):()=>Aa(g,e,s,h))(),_=m?b:Ca(b,c,d);return l?z(_,[_.shape[1],_.shape[2],_.shape[3]]):_}function h4(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 g4(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 C_=N({pool_:x4});function y4(r,e){let t=v(r,"base","pow"),o=v(e,"exp","pow");[t,o]=Ue(t,o);let n={a:t,b:o};return A.runKernel(_n,n)}var _r=N({pow_:y4});function b4(r,e){let t=v(r,"x","prelu"),o=v(e,"alpha","prelu"),n={x:t,alpha:o};return A.runKernel(wn,n)}var $a=N({prelu_:b4});function _4(r,e=null,t=!1){let o=v(r,"x","prod");o.dtype==="bool"&&(o=ne(o,"int32"));let n={x:o},s={axis:e,keepDims:t};return A.runKernel(wi,n,s)}var Ou=N({prod_:_4});function w4(r,e,t){let o=dt(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=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}},D_=class{constructor(e,t,o,n){this.alpha=e,this.beta=1/t,this.dtype=o;let s=n||Math.random();this.randu=ag.alea(s.toString()),this.randn=new Zc(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(),sthis.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=ag.alea(n)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function E4(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 D_(e,t,o,n),a=Ie(r,o);for(let i=0;i`Error in reverse1D: x must be rank 1 but got rank ${e.rank}.`),Yt(e,0)}var z4=N({reverse1d_:L4});function B4(r,e){let t=v(r,"x","reverse");return E(t.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${t.rank}.`),Yt(t,e)}var V4=N({reverse2d_:B4});function W4(r,e){let t=v(r,"x","reverse");return E(t.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${t.rank}.`),Yt(t,e)}var G4=N({reverse3d_:W4});function U4(r,e){let t=v(r,"x","reverse");return E(t.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${t.rank}.`),Yt(t,e)}var j4=N({reverse4d_:U4});function q4(r){let t={x:v(r,"x","round")};return A.runKernel(Nn,t)}var Um=N({round_:q4});function H4(r){let t={x:v(r,"x","rsqrt")};return A.runKernel(Sn,t)}var Lu=N({rsqrt_:H4});function ce(r,e){if((nr(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"&&nr(r)&&!(r instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return qr(r,[],[],e)}function K4(r){let t={x:v(r,"x","selu")};return A.runKernel(Ci,t)}var zu=N({selu_:K4});function X4(r,e,t,o,n,s=[1,1],a="NHWC"){let i=v(r,"x","separableConv2d"),l=v(e,"depthwiseFilter","separableConv2d"),u=v(t,"pointwiseFilter","separableConv2d"),c=i,p=!1;if(i.rank===3&&(p=!0,c=z(i,[1,i.shape[0],i.shape[1],i.shape[2]])),a==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");E(c.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`),E(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),E(u.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),E(u.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`),E(u.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${u.shape[1]}.`);let m=l.shape[2],f=l.shape[3];E(u.shape[2]===m*f,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${m*f}, but got ${u.shape[2]}.`);let d=Lo(c,l,o,n,a,s),g=Xr(d,u,1,"valid",a);return p?z(g,[g.shape[1],g.shape[2],g.shape[3]]):g}var jm=N({separableConv2d_:X4});async function Y4(r,e){let t=v(r,"x","setdiff1d"),o=v(e,"y","setdiff1d");E(t.dtype===o.dtype,()=>`x and y should have the same dtype, but got x (${t.dtype}) and y (${o.dtype}).`),E(t.rank===1,()=>`x should be 1D tensor, but got x (${t.shape}).`),E(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`slice1d expects a rank-1 tensor, but got a rank-${o.rank} tensor`),Fe(o,[e],[t])}var Hm=N({slice1d_:eU});function tU(r,e,t){let o=v(r,"x","slice2d");return E(o.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${o.rank} tensor`),Fe(o,e,t)}var ug=N({slice2d_:tU});function rU(r,e,t){let o=v(r,"x","slice3d");return E(o.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${o.rank} tensor`),Fe(o,e,t)}var Km=N({slice3d_:rU});function oU(r,e,t){let o=v(r,"x","slice4d");return E(o.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${o.rank} tensor`),Fe(o,e,t)}var Qc=N({slice4d_:oU});function nU(r,e=-1){let t=v(r,"logits","softmax","float32");if(e===-1&&(e=t.rank-1),e!==t.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${t.rank} and dim was ${e}`);let o={logits:t},n={dim:e};return A.runKernel($n,o,n)}var Ra=N({softmax_:nU});function sU(r){E(r.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${r.dtype}.`);let e={input:r};return A.runKernel(nu,e)}var Fa=N({fft_:sU});function iU(r){E(r.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${r.dtype}.`);let e={input:r};return A.runKernel(su,e)}var Li=N({ifft_:iU});function aU(r){let e=r.shape[r.shape.length-1],t=r.size/e,o;if(e<=2){let n=z(r,[t,e]);o=Li(n)}else{let n=[t,2*(e-1)],s=z(ul(r),[t,e]),a=z(Au(r),[t,e]),i=Yt(Fe(s,[0,1],[t,e-2]),1),l=O(Yt(Fe(a,[0,1],[t,e-2]),1),ce(-1)),u=Je([s,i],1),c=Je([a,l],1),p=z(wo(u,c),[n[0],n[1]]);o=Li(p)}if(o=ul(o),r.rank===3&&r.shape[0]!==0){let n=o,s=r.shape[0];o=z(o,[s,o.shape[0]/s,o.shape[1]]),n.dispose()}return o}var Wu=N({irfft_:aU});function lU(r,e,t=0){let n={x:v(r,"x","split")},s={numOrSizeSplits:e,axis:t};return A.runKernel(xs,n,s)}var ur=N({split_:lU});function uU(r,e){E(r.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${r.dtype}`);let t=r.shape[r.shape.length-1],o=r.size/t,n;if(e!=null&&e0),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,pt(d)],r.shape.length-1),t=e}else n=r;let s=Ne(n),a=z(wo(n,s),[o,t]),i=Fa(a),l=Math.floor(t/2)+1,u=ul(i),c=Au(i),p=ur(u,[l,t-l],u.shape.length-1),m=ur(c,[l,t-l],c.shape.length-1),f=n.shape.slice();return f[n.shape.length-1]=l,z(wo(p[0],m[0]),f)}var Oa=N({rfft_:uU});function cU(r){let t={x:v(r,"x","sqrt")};return A.runKernel(An,t)}var _t=N({sqrt_:cU});function pU(r,e){let t=v(r,"a","squaredDifference"),o=v(e,"b","squaredDifference");[t,o]=Ue(t,o),Ve(t.shape,o.shape);let n={a:t,b:o},s={};return A.runKernel(Rn,n,s)}var Pa=N({squaredDifference_:pU});function mU(r,e){let t=v(r,"x","squeeze");return z(t,ib(t.shape,e).newShape)}var ko=N({squeeze_:mU});function fU(r,e=0){let t=ya(r,"tensors","stack","string_or_numeric");E(t.length>=1,()=>"Pass at least one tensor to tf.stack"),t.length>0&&E(e<=t[0].rank,()=>"Axis must be <= rank of the tensor");let o=t,n={axis:e};return A.runKernel(fs,o,n)}var Wt=N({stack_:fU});function dU(r,e=0){let o={x:v(r,"x","step")},n={alpha:e};return A.runKernel(Di,o,n)}var Es=N({step_:dU});function hU(r,e,t,o,n=0,s=0,a=0,i=0,l=0){let c={x:v(r,"x","stridedSlice")},p={begin:e,end:t,strides:o,beginMask:n,endMask:s,ellipsisMask:a,newAxisMask:i,shrinkAxisMask:l};return A.runKernel(Ti,c,p)}var Xm=N({stridedSlice_:hU});function gU(r){let t={x:v(r,"x","tan")};return A.runKernel(Ei,t)}var Ym=N({tan_:gU});function Gt(r,e){Ro(r);let t=kr(r,e);if(t.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return qr(r,null,t,e)}function zi(r,e,t){if(Ro(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 qr(r,e,o,t)}function xU(r,e,t){if(Ro(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 qr(r,e,o,t)}function yU(r,e,t){if(Ro(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 qr(r,e,o,t)}function bU(r,e,t){if(Ro(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,qr(r,e,o,t)}function _U(r,e=1,t=!0){let o=v(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]=A.runKernel(Ai,s,a);return{values:i,indices:l}}var Zm=N({topk_:_U});function wU(r,e=0,t=1,o,n){if(o!=null&&o==="bool")throw new Error("Unsupported data type $ { dtype }");let s=new Zc(e,t,o,!0,n),a=Ie(r,o);for(let i=0;i0,()=>"The input tensor must be at least 1D");let o={x:t},n={axis:e},[s,a]=A.runKernel(xu,o,n);return{values:s,indices:a}}var ep=N({unique_:vU});function kU(r,e,t){let o=v(r,"x","unsortedSegmentSum"),n=v(e,"segmentIds","unsortedSegmentSum","int32");E(it(t),()=>"numSegments must be of dtype int");let s={x:o,segmentIds:n},a={numSegments:t};return A.runKernel(xa,s,a)}var Jm=N({unsortedSegmentSum_:kU});function CU(r,e=0){let t=v(r,"x","unstack","string_or_numeric");E(e>=-t.shape.length&&e`Axis = ${e} is not in [-${t.shape.length}, ${t.shape.length})`);let o={value:t},n={axis:e};return A.runKernel(ys,o,n)}var cr=N({unstack_:CU});function F_(r,e=!0,t,o){return A.makeVariable(r,e,t,o)}function O_(r,e){let t=[];for(let s=0;s0,()=>"mask cannot be scalar"),Ge(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"Shape mismatch in v and x");let l=ce(1),u=pe(l,i),c=O(pe(a,s),u);if(n){E(o!=null,()=>"When using zeroDebias: true, step is required.");let p=v(o,"step","movingAverage");c=fe(c,pe(l,_r(i,p)))}return ee(s,c)}var jU=N({movingAverage_:UU});function qU(r,e,t){let o=v(r,"indices","scatterND","int32"),n=v(e,"updates","scatterND");Qh(n,o,t);let s={indices:o,updates:n},a={shape:t};return A.runKernel(ki,s,a)}var Z_=N({scatterND_:qU});function uS(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 HU(r,e,t,o=0){let n=v(r,"sparseIndices","sparseToDense","int32"),s=v(e,"sparseValues","sparseToDense"),a=v(o,"defaultValue","sparseToDense",s.dtype);uS(n,s,t,a);let i={sparseIndices:n,sparseValues:s,defaultValue:a},l={outputShape:t};return A.runKernel(gu,i,l)}var ef=N({sparseToDense_:HU});function KU(r,e){let t=v(e,"indices","gatherND","int32"),n={params:v(r,"x","gatherND"),indices:t};return A.runKernel(ai,n)}var J_=N({gatherND_:KU});function cS(r,e){if(e==null)return r.shape.slice();if(jr(r.shape,e))return e;if(r.shape.length===e.length){let t=[];for(let o=0;o`x has to be a floating point tensor since it's going to be scaled, but got a ${n.dtype} tensor instead.`),E(e>=0&&e<1,()=>`rate must be a float in the range [0, 1), but got ${e}.`),e===0)return r instanceof R?n.clone():n;let s=cS(n,t),a=1-e,i=fe(Ns(ee(Ts(s,0,1,"float32",o),a)),a);return O(n,i)}var Q_=N({dropout_:XU});function ew(r){return Math.floor(Math.pow(2,Math.ceil(Math.log(r)/Math.log(2))))}function tf(r,e,t){let o=1-r%2,n=new Float32Array(r);for(let s=0;s1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${o.rank}`),E(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}`),Ge(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];E(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=ab("bool",l);for(let p=0;pg.value-h.value),c[p]=0;for(let h=0;hej,depthwiseConv2d:()=>nj,matMul:()=>ij});function JU(r,e,t,o,n,s="NHWC",a){let i=r;r.rank===3&&(i=z(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let l=e;l.rank===3&&(l=z(e,[1,e.shape[0],e.shape[1],e.shape[2]])),E(i.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`),E(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),E(t.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${t}.`);let u=s==="NHWC"?i.shape[3]:i.shape[1],c=s==="NHWC"?l.shape[3]:l.shape[1];E(u===t[2],()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${t[2]}.`),E(c===t[3],()=>`Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${t[3]}).`),a!=null&&E(it(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 A.runKernel(Yl,p,m)}var tp=N({conv2DBackpropFilter_:JU});function ju(r,e,t){if(t==null||t==="linear")return r;if(t==="relu")return O(r,Es(e));throw new Error(`Cannot compute gradient for fused activation ${t}.`)}function qu(r,e){let t=e,o=Nt(r.shape,e.shape);return o.length>0&&(t=be(t,o)),z(t,r.shape)}function Hu(r,e,t,o){if(e==="linear")return r;if(e==="relu")return Sr(r);if(e==="elu")return Is(r);if(e==="relu6")return Mu(r);if(e==="prelu")return $a(r,t);if(e==="leakyrelu")return Sa(r,o);throw new Error(`Unknown fused activation ${e}.`)}var Ku=(r,e)=>!(r>0)||e==="linear";function QU({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",Ku(A.state.gradientDepth,l)===!1){let k=Xr(r,e,t,o,n,s,a);return i!=null&&(k=ee(k,i)),Hu(k,l,u,c)}let p=v(r,"x","conv2d"),m=v(e,"filter","conv2d"),f=p,d=!1;p.rank===3&&(d=!0,f=z(p,[1,p.shape[0],p.shape[1],p.shape[2]])),E(f.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${f.rank}.`),E(m.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${m.rank}.`),a!=null&&E(it(o),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${o}.`),E(f.shape[3]===m.shape[2],()=>`Error in conv2d: depth of input (${f.shape[3]}) must match input depth for filter ${m.shape[2]}.`),E(Pt(t,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`),E(n==="NHWC",()=>`Error in conv2d: got dataFormat of ${n} but only NHWC is currently supported.`);let h=Cu(f.shape,m.shape,t,s,o,a),g;i!=null&&(g=v(i,"bias","fused conv2d"),[g]=Ue(g,p),Ve(h.outShape,g.shape));let y;u!=null&&(y=v(u,"prelu weights","fused conv2d"));let b=(k,$)=>{let[T,F,M,L]=$,G=ju(k,M,l);E(Mo(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let H=Kc(F.shape,G,T,t,o),U=tp(F,G,T.shape,t,o),Z=[H,U];if(L!=null){let K=qu(L,G);Z.push(K)}return Z},_={x:f,filter:m,bias:g,preluActivationWeights:y},w={strides:t,pad:o,dataFormat:n,dilations:s,dimRoundingMode:a,activation:l,leakyreluAlpha:c};return i==null?Zr(($,T,F)=>{let M=A.runKernel(ws,_,w);return F([T,$,M]),d&&(M=z(M,[M.shape[1],M.shape[2],M.shape[3]])),{value:M,gradFunc:b}})(f,m):Zr(($,T,F,M)=>{let L=A.runKernel(ws,_,w);return M([T,$,L,F]),d&&(L=z(L,[L.shape[1],L.shape[2],L.shape[3]])),{value:L,gradFunc:b}})(f,m,g)}var ej=N({fusedConv2d_:QU});function tj(r,e,t,o,n,s=[1,1],a){let i=r;r.rank===3&&(i=z(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let l=e;l.rank===3&&(l=z(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 A.runKernel(eu,u,c)}var cg=N({depthwiseConv2dNativeBackpropFilter_:tj});function rj(r,e,t,o,n,s=[1,1],a){let i=e,l=!1;e.rank===3&&(l=!0,i=z(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=A.runKernel(tu,u,c);return l?z(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var pg=N({depthwiseConv2dNativeBackpropInput_:rj});function oj({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(Ku(A.state.gradientDepth,l)===!1){let k=Lo(r,e,t,o,n,s,a);return i!=null&&(k=ee(k,i)),Hu(k,l,u,c)}let p=v(r,"x","depthwiseConv2d"),m=v(e,"filter","depthwiseConv2d"),f=p,d=!1;p.rank===3&&(d=!0,f=z(p,[1,p.shape[0],p.shape[1],p.shape[2]])),E(f.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${f.rank}.`),E(m.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${m.rank}.`),E(f.shape[3]===m.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${f.shape[3]}) must match the inChannels dimension in filter ${m.shape[2]}.`),s==null&&(s=[1,1]),E(Pt(t,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${t} and dilations '${s}'`),a!=null&&E(it(o),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${a} but got pad ${o}.`);let h=Cu(f.shape,m.shape,t,s,o,a,!0),g;i!=null&&(g=v(i,"bias","fused conv2d"),[g]=Ue(g,p),Ve(h.outShape,g.shape));let y;u!=null&&(y=v(u,"prelu weights","fused depthwiseConv2d"));let b=(k,$)=>{E(Mo(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);let[T,F,M,L]=$,G=ju(k,M,l),H=pg(F.shape,G,T,t,o,s,a),U=cg(F,G,T.shape,t,o,s,a);if(L!=null){let Z=qu(g,G);return[H,U,Z]}return[H,U]},_={x:f,filter:m,bias:g,preluActivationWeights:y},w={strides:t,pad:o,dataFormat:n,dilations:s,dimRoundingMode:a,activation:l,leakyreluAlpha:c};return i==null?Zr(($,T,F)=>{let M=A.runKernel(vs,_,w);return F([T,$,M]),d&&(M=z(M,[M.shape[1],M.shape[2],M.shape[3]])),{value:M,gradFunc:b}})(f,m):Zr(($,T,F,M)=>{let L=A.runKernel(vs,_,w);return M([T,$,L,F]),d&&(L=z(L,[L.shape[1],L.shape[2],L.shape[3]])),{value:L,gradFunc:b}})(f,m,g)}var nj=N({fusedDepthwiseConv2d_:oj});function sj({a:r,b:e,transposeA:t=!1,transposeB:o=!1,bias:n,activation:s="linear",preluActivationWeights:a,leakyreluAlpha:i}){if(Ku(A.state.gradientDepth,s)===!1){let L=je(r,e,t,o);return n!=null&&(L=ee(L,n)),Hu(L,s,a,i)}let l=v(r,"a","fused matMul"),u=v(e,"b","fused matMul");[l,u]=Ue(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=dt(d),y=dt(h);E(l.rank>=2&&u.rank>=2&&l.rank===u.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${l.rank} and ${u.rank}.`),E(jr(d,h),()=>`Error in fused matMul: outer dimensions (${d}) and (${h}) of Tensors with shapes ${l.shape} and ${u.shape} must match.`),E(c===p,()=>`Error in fused matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${t} and transposeB=${o} must match.`);let b=l.shape.slice(0,-2).concat([m,f]),_=t?z(l,[g,c,m]):z(l,[g,m,c]),w=o?z(u,[y,f,p]):z(u,[y,p,f]),k;n!=null&&(k=v(n,"bias","fused matMul"),[k]=Ue(k,l),Ve(b,k.shape));let $;a!=null&&($=v(a,"prelu weights","fused matMul"));let T=(L,G)=>{let[H,U,Z,K]=G,X=ju(z(L,Z.shape),Z,s),oe,J;if(!t&&!o?(oe=je(X,U,!1,!0),J=je(H,X,!0,!1)):!t&&o?(oe=je(X,U,!1,!1),J=je(X,H,!0,!1)):t&&!o?(oe=je(U,X,!1,!0),J=je(H,X,!1,!1)):(oe=je(U,X,!0,!0),J=je(X,H,!0,!0)),n!=null){let Q=qu(K,X);return[oe,J,Q]}else return[oe,J]},F={a:_,b:w,bias:k,preluActivationWeights:$},M={transposeA:t,transposeB:o,activation:s,leakyreluAlpha:i};return n==null?Zr((G,H,U)=>{let Z=A.runKernel(_s,F,M);return U([G,H,Z]),{value:z(Z,b),gradFunc:T}})(_,w):Zr((G,H,U,Z)=>{let K=A.runKernel(_s,F,M);return Z([G,H,K,U]),{value:z(K,b),gradFunc:T}})(_,w,k)}var ij=N({fusedMatMul_:sj});function aj(r){return tf(r,.54,.46)}var pS=N({hammingWindow_:aj});function lj(r){return tf(r,.5,.5)}var mg=N({hannWindow_:lj});function uj(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`Error in cropAndResize: image must be rank 4,but got rank ${a.rank}.`),E(i.rank===2&&i.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${i.shape}.`),E(l.rank===1&&l.shape[0]===u,()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${i.shape}.`),E(o.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${o.length}.`),E(o[0]>=1&&o[1]>=1,()=>`cropSize must be atleast [1,1], but was ${o}`),E(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 A.runKernel(ei,c,p)}var fS=N({cropAndResize_:pj});function mj(r){let e=v(r,"image","flipLeftRight","float32");E(e.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${e.rank}.`);let t={image:e};return A.runKernel(ii,t,{})}var dS=N({flipLeftRight_:mj});function fj(r,e,t=0,o=.5){let n=v(r,"image","rotateWithOffset","float32");E(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 A.runKernel($i,s,a)}var hS=N({rotateWithOffset_:fj});function Wn(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),E(0<=o&&o<=1,()=>`iouThreshold must be in [0, 1], but was '${o}'`),E(r.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${r.rank}'`),E(r.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${r.shape[1]}`),E(e.rank===1,()=>"scores must be a 1D tensor"),E(e.shape[0]===a,()=>`scores has incompatible shape with boxes. Expected ${a}, but was ${e.shape[0]}`),E(0<=s&&s<=1,()=>`softNmsSigma must be in [0, 1], but was '${s}'`),{maxOutputSize:t,iouThreshold:o,scoreThreshold:n,softNmsSigma:s}}function dj(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY){let s=v(r,"boxes","nonMaxSuppression"),a=v(e,"scores","nonMaxSuppression"),i=Wn(s,a,t,o,n);t=i.maxOutputSize,o=i.iouThreshold,n=i.scoreThreshold;let l={maxOutputSize:t,iouThreshold:o,scoreThreshold:n};return A.runKernel(yi,{boxes:s,scores:a},l)}var gS=N({nonMaxSuppression_:dj});function xS(r,e,t){let o=hj(r,e,t),n=o<0?-(o+1):o;r.splice(n,0,e)}function hj(r,e,t){return xj(r,e,t||gj)}function gj(r,e){return r>e?1:r>>1);let i=t(e,r[s]);i>0?o=s+1:(n=s,a=!i)}return a?o:-o-1}function rw(r,e,t,o,n){return tw(r,e,t,o,n,0)}function ow(r,e,t,o,n,s){return tw(r,e,t,o,n,0,!1,s,!0)}function nw(r,e,t,o,n,s){return tw(r,e,t,o,n,s,!0)}function tw(r,e,t,o,n,s,a=!1,i=!1,l=!1){let u=[];for(let g=0;gn&&u.push({score:e[g],boxIndex:g,suppressBeginIndex:0});u.sort(yS);let c=s>0?-.5/s:0,p=[],m=[];for(;p.length0;){let g=u.pop(),{score:y,boxIndex:b,suppressBeginIndex:_}=g;if(y=_;--k){let $=yj(r,b,p[k]);if($>=o){w=!0;break}if(g.score=g.score*bj(o,c,$),g.score<=n)break}g.suppressBeginIndex=p.length,w||(g.score===y?(p.push(b),m.push(g.score)):g.score>n&&xS(u,g,yS))}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 yj(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),y=Math.min(i,p),b=Math.min(l,m),_=Math.max(y-h,0)*Math.max(b-g,0);return _/(f+d-_)}function bj(r,e,t){let o=Math.exp(e*t*t);return t<=r?o:0}function yS(r,e){return r.score-e.score||r.score===e.score&&e.boxIndex-r.boxIndex}async function _j(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY){let s=v(r,"boxes","nonMaxSuppressionAsync"),a=v(e,"scores","nonMaxSuppressionAsync"),i=Wn(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}=rw(u,c,t,o,n);return s!==r&&s.dispose(),a!==e&&a.dispose(),Gt(p,"int32")}var bS=_j;function wj(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY,s=0){let a=v(r,"boxes","nonMaxSuppression"),i=v(e,"scores","nonMaxSuppression"),l=Wn(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=A.runKernel(_i,u,c);return{selectedIndices:p[0],selectedScores:p[1]}}var _S=N({nonMaxSuppressionWithScore_:wj});async function vj(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY,s=0){let a=v(r,"boxes","nonMaxSuppressionAsync"),i=v(e,"scores","nonMaxSuppressionAsync"),l=Wn(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}=nw(c,p,t,o,n,s);return a!==r&&a.dispose(),i!==e&&i.dispose(),{selectedIndices:Gt(m,"int32"),selectedScores:Gt(f)}}var wS=vj;function kj(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY,s=!1){let a=v(r,"boxes","nonMaxSuppression"),i=v(e,"scores","nonMaxSuppression"),l=Wn(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=A.runKernel(bi,m,f);return{selectedIndices:d[0],validOutputs:d[1]}}var vS=N({nonMaxSuppressionPadded_:kj});async function Cj(r,e,t,o=.5,n=Number.NEGATIVE_INFINITY,s=!1){let a=v(r,"boxes","nonMaxSuppressionAsync"),i=v(e,"scores","nonMaxSuppressionAsync"),l=Wn(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}=ow(m,f,u,c,p,s);return a!==r&&a.dispose(),i!==e&&i.dispose(),{selectedIndices:Gt(d,"int32"),validOutputs:ce(h,"int32")}}var kS=Cj;function Ij(r,e,t=!1,o=!1){let n=v(r,"images","resizeBilinear");E(n.rank===3||n.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${n.rank}.`),E(e.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${e}.`),E(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=z(n,[1,n.shape[0],n.shape[1],n.shape[2]]));let[]=e,i={images:s},l={alignCorners:t,halfPixelCenters:o,size:e},u=A.runKernel(kn,i,l);return a?z(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var dg=N({resizeBilinear_:Ij});function Nj(r,e,t=!1,o=!1){let n=v(r,"images","resizeNearestNeighbor");E(n.rank===3||n.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${n.rank}.`),E(e.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${e}.`),E(n.dtype==="float32"||n.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),E(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=z(n,[1,n.shape[0],n.shape[1],n.shape[2]]));let[]=e,i={images:s},l={alignCorners:t,halfPixelCenters:o,size:e},u=A.runKernel(da,i,l);return a?z(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var hg=N({resizeNearestNeighbor_:Nj});function Sj(r,e,t){E(e%1==0,()=>`bandPart(): numLower must be an integer, got ${e}.`),E(t%1==0,()=>`bandPart(): numUpper must be an integer, got ${t}.`);let o=v(r,"a","bandPart");E(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=z(Jc(0,s,1,"int32"),[-1,1]),l=Jc(0,a,1,"int32"),u=pe(i,l),c=dr(no(u,ce(+e,"int32")),Or(u,ce(-t,"int32"))),p=pt([s,a],o.dtype);return z(Wt(cr(z(o,[-1,s,a])).map(m=>$t(c,m,p))),n)}var CS=N({bandPart_:Sj});function Tj(r){let e;if(Array.isArray(r)){e=!1,E(r!=null&&r.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let n=r[0].shape[0];for(let s=1;s`Gram-Schmidt: Non-unique lengths found in the input vectors: (${r[s].shape[0]} vs. ${n})`)}else e=!0,r=ur(r,r.shape[0],0).map(n=>ko(n,[0]));E(r.length<=r[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${r.length}) exceeds number of dimensions (${r[0].shape[0]}).`);let t=[],o=r;for(let n=0;n{let s=o[n];if(n>0)for(let a=0;a=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${r.rank}`),r.rank===2)return NS(r,e);{let t=r.shape.slice(0,r.shape.length-2).reduce((l,u)=>l*u),o=cr(z(r,[t,r.shape[r.shape.length-2],r.shape[r.shape.length-1]]),0),n=[],s=[];o.forEach(l=>{let[u,c]=NS(l,e);n.push(u),s.push(c)});let a=z(Wt(n,0),r.shape),i=z(Wt(s,0),r.shape);return[a,i]}}function NS(r,e=!1){return A.tidy(()=>{E(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=Xc(t),s=Po(r),a=zi([[1]],[1,1]),i=Po(a),l=t>=o?o:t;for(let u=0;u{let f=Fe(s,[u,u],[t-u,1]),d=Uu(f),h=Fe(s,[u,u],[1,1]),g=$t(Xt(h,0),zi([[-1]]),zi([[1]])),y=pe(h,O(g,d)),b=fe(f,y);b.shape[0]===1?i=Po(a):i=Je([a,Fe(b,[1,0],[b.shape[0]-1,b.shape[1]])],0);let _=He(fe(je(g,y),d)),w=Fe(s,[u,0],[t-u,o]),k=O(_,i),$=qe(i);if(u===0)s=pe(w,je(k,je($,w)));else{let M=pe(w,je(k,je($,w)));s=Je([Fe(s,[0,0],[u,o]),M],0)}let T=qe(k),F=Fe(n,[0,u],[t,n.shape[1]-u]);if(u===0)n=pe(F,je(je(F,i),T));else{let M=pe(F,je(je(F,i),T));n=Je([Fe(n,[0,0],[t,u]),M],1)}return[i,s,n]}),Ae([c,p,m])}return!e&&t>o&&(n=Fe(n,[0,0],[t,o]),s=Fe(s,[0,0],[o,o])),[n,s]})}var SS=N({qr_:Ej});var Ut;(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"})(Ut||(Ut={}));function Aj(r,e,t=Ut.SUM_BY_NONZERO_WEIGHTS){let o=v(r,"losses","computeWeightedLoss"),n=null;e!=null&&(n=v(e,"weights","computeWeightedLoss"));let s=n==null?o:O(o,n);if(t===Ut.NONE)return s;if(t===Ut.SUM)return be(s);if(t===Ut.MEAN){if(n==null)return bt(s);{let a=o.size/n.size,i=fe(be(s),be(n));return a>1?fe(i,ce(a)):i}}if(t===Ut.SUM_BY_NONZERO_WEIGHTS){if(n==null)return fe(be(s),ce(o.size));{let a=O(n,Nr(o.shape)),i=ne(be(vo(a,ce(0))),"float32");return fe(be(s),i)}}throw Error(`Unknown reduction: ${t}`)}var Tr=N({computeWeightedLoss_:Aj});function Dj(r,e,t,o=Ut.SUM_BY_NONZERO_WEIGHTS){let n=v(r,"labels","absoluteDifference"),s=v(e,"predictions","absoluteDifference"),a=null;t!=null&&(a=v(t,"weights","absoluteDifference")),Ge(n.shape,s.shape,"Error in absoluteDifference: ");let i=Et(pe(n,s));return Tr(i,a,o)}var TS=N({absoluteDifference_:Dj});function $j(r,e,t,o,n=Ut.SUM_BY_NONZERO_WEIGHTS){let s=v(r,"labels","cosineDistance"),a=v(e,"predictions","cosineDistance"),i=null;o!=null&&(i=v(o,"weights","cosineDistance")),Ge(s.shape,a.shape,"Error in cosineDistance: ");let l=ce(1),u=pe(l,be(O(s,a),t,!0));return Tr(u,i,n)}var ES=N({cosineDistance_:$j});function Rj(r,e,t,o=Ut.SUM_BY_NONZERO_WEIGHTS){let n=v(r,"labels","hingeLoss"),s=v(e,"predictions","hingeLoss"),a=null;t!=null&&(a=v(t,"weights","hingeLoss")),Ge(n.shape,s.shape,"Error in hingeLoss: ");let i=ce(1);n=pe(O(ce(2),n),i);let l=Sr(pe(i,O(n,s)));return Tr(l,a,o)}var AS=N({hingeLoss_:Rj});function Fj(r,e,t,o=1,n=Ut.SUM_BY_NONZERO_WEIGHTS){let s=v(r,"labels","huberLoss"),a=v(e,"predictions","huberLoss"),i=null;t!=null&&(i=v(t,"weights","huberLoss")),Ge(s.shape,a.shape,"Error in huberLoss: ");let l=ce(o),u=Et(pe(a,s)),c=Bo(u,l),p=pe(u,c),m=ee(O(ce(.5),Me(c)),O(l,p));return Tr(m,i,n)}var DS=N({huberLoss_:Fj});function Oj(r,e,t,o=1e-7,n=Ut.SUM_BY_NONZERO_WEIGHTS){let s=v(r,"labels","logLoss"),a=v(e,"predictions","logLoss"),i=null;t!=null&&(i=v(t,"weights","logLoss")),Ge(s.shape,a.shape,"Error in logLoss: ");let l=ce(1),u=ce(o),c=He(O(s,ar(ee(a,u)))),p=O(pe(l,s),ar(ee(pe(l,a),u))),m=pe(c,p);return Tr(m,i,n)}var $S=N({logLoss_:Oj});function Pj(r,e,t,o=Ut.SUM_BY_NONZERO_WEIGHTS){let n=v(r,"labels","meanSquaredError"),s=v(e,"predictions","meanSquaredError"),a=null;t!=null&&(a=v(t,"weights","meanSquaredError")),Ge(n.shape,s.shape,"Error in meanSquaredError: ");let i=Pa(n,s);return Tr(i,a,o)}var RS=N({meanSquaredError_:Pj});function Mj(r,e){let t=v(r,"labels","sigmoidCrossEntropyWithLogits"),o=v(e,"logits","sigmoidCrossEntropyWithLogits");Ge(t.shape,o.shape,"Error in sigmoidCrossEntropyWithLogits: ");let n=Sr(o),s=O(o,t),a=Du(Qt(He(Et(o))));return ee(pe(n,s),a)}function Lj(r,e,t,o=0,n=Ut.SUM_BY_NONZERO_WEIGHTS){let s=v(r,"multiClassLabels","sigmoidCrossEntropy"),a=v(e,"logits","sigmoidCrossEntropy"),i=null;if(t!=null&&(i=v(t,"weights","sigmoidCrossEntropy")),Ge(s.shape,a.shape,"Error in sigmoidCrossEntropy: "),o>0){let u=ce(o),c=ce(1),p=ce(.5);s=ee(O(s,pe(c,u)),O(p,u))}let l=Mj(s,a);return Tr(l,i,n)}var FS=N({sigmoidCrossEntropy_:Lj});function zj(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 Zr((n,s,a)=>{let l=zm(s,[t],!0),u=pe(ne(s,"float32"),l);a([n,u]);let c=He(O(u,n));return{value:be(c,[t]),gradFunc:(f,d)=>{let[h,g]=d,y=Bn(f.shape,[t]);return[O(z(f,y),pe(ne(h,"float32"),Qt(g))),O(z(f,y),pe(Qt(g),ne(h,"float32")))]}}})(r,e)}function Bj(r,e,t,o=0,n=Ut.SUM_BY_NONZERO_WEIGHTS){let s=v(r,"onehotLabels","softmaxCrossEntropy"),a=v(e,"logits","softmaxCrossEntropy"),i=null;if(t!=null&&(i=v(t,"weights","softmaxCrossEntropy")),Ge(s.shape,a.shape,"Error in softmaxCrossEntropy: "),o>0){let u=ce(o),c=ce(1),p=ce(s.shape[1]);s=ee(O(s,pe(c,u)),fe(u,p))}let l=zj(s,a);return Tr(l,i,n)}var OS=N({softmaxCrossEntropy_:Bj});var Vj={fft:Fa,ifft:Li,rfft:Oa,irfft:Wu},Wj={hammingWindow:pS,hannWindow:mg,frame:fg,stft:mS},As={flipLeftRight:dS,resizeNearestNeighbor:hg,resizeBilinear:dg,rotateWithOffset:hS,cropAndResize:fS,nonMaxSuppression:gS,nonMaxSuppressionAsync:bS,nonMaxSuppressionWithScore:_S,nonMaxSuppressionWithScoreAsync:wS,nonMaxSuppressionPadded:vS,nonMaxSuppressionPaddedAsync:kS},sw={bandPart:CS,gramSchmidt:IS,qr:SS},Gj={absoluteDifference:TS,computeWeightedLoss:Tr,cosineDistance:ES,hingeLoss:AS,huberLoss:DS,logLoss:$S,meanSquaredError:RS,sigmoidCrossEntropy:FS,softmaxCrossEntropy:OS};var Mr=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 Ae(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 sg(e,t)}dispose(){this.iterations_!=null&&Ae(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:ce(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}};Object.defineProperty(Mr,Symbol.hasInstance,{value:r=>r.minimize!=null&&r.computeGradients!=null&&r.applyGradients!=null});var rp=class extends Mr{constructor(e,t,o=null){super();this.learningRate=e,this.rho=t,this.epsilon=o,this.accumulatedGrads=[],this.accumulatedUpdates=[],o==null&&(this.epsilon=A.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(o=>o.name):Object.keys(e)).forEach((o,n)=>{let s=A.registeredVariables[o],a=!1;this.accumulatedGrads[n]==null&&(this.accumulatedGrads[n]={originalName:`${o}/accum_grad`,variable:V(()=>Ne(s).variable(a))}),this.accumulatedUpdates[n]==null&&(this.accumulatedUpdates[n]={originalName:`${o}/accum_var`,variable:V(()=>Ne(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=ee(O(l,this.rho),O(Me(i),1-this.rho)),p=O(fe(_t(ee(u,this.epsilon)),_t(ee(l,this.epsilon))),i),m=ee(O(u,this.rho),O(Me(p),1-this.rho));l.assign(c),u.assign(m);let f=ee(O(p,-this.learningRate),s);s.assign(f)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(Ae(this.accumulatedGrads.map(e=>e.variable)),Ae(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)}};rp.className="Adadelta";oo(rp);var op=class extends Mr{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=A.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=ee(i,Me(a));i.assign(l);let u=ee(O(fe(a,_t(ee(l,A.backend.epsilon()))),-this.learningRate),s);s.assign(u)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&Ae(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)}};op.className="Adagrad";oo(op);var np=class extends Mr{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=ce(t).variable(),this.accBeta2=ce(o).variable()}),n==null&&(this.epsilon=A.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(o=>o.name):Object.keys(e);V(()=>{let o=pe(1,this.accBeta1),n=pe(1,this.accBeta2);t.forEach((s,a)=>{let i=A.registeredVariables[s],l=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${s}/m`,variable:V(()=>Ne(i).variable(l))}),this.accumulatedSecondMoment[a]==null&&(this.accumulatedSecondMoment[a]={originalName:`${s}/v`,variable:V(()=>Ne(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=ee(O(c,this.beta1),O(u,1-this.beta1)),f=ee(O(p,this.beta2),O(Me(u),1-this.beta2)),d=fe(m,o),h=fe(f,n);c.assign(m),p.assign(f);let g=ee(O(fe(d,ee(_t(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&&Ae(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&Ae(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(_r(this.beta1,this.iterations_+1)),this.accBeta2.assign(_r(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)}};np.className="Adam";oo(np);var sp=class extends Mr{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=ce(0).variable(),this.accBeta1=ce(t).variable()}),n==null&&(this.epsilon=A.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(o=>o.name):Object.keys(e);V(()=>{let o=pe(1,this.accBeta1),n=fe(-this.learningRate,ee(O(this.iteration,this.decay),1));t.forEach((s,a)=>{let i=A.registeredVariables[s],l=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${s}/m`,variable:Ne(i).variable(l)}),this.accumulatedWeightedInfNorm[a]==null&&(this.accumulatedWeightedInfNorm[a]={originalName:`${s}/v`,variable:Ne(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=ee(O(c,this.beta1),O(u,1-this.beta1)),f=O(p,this.beta2),d=Et(u),h=Ir(f,d);c.assign(m),p.assign(h);let g=ee(O(fe(n,o),fe(m,ee(h,this.epsilon))),i);i.assign(g)}),this.iteration.assign(ee(this.iteration,1)),this.accBeta1.assign(O(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Ae(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&Ae(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)}};sp.className="Adamax";oo(sp);var cl=class extends Mr{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=A.registeredVariables[o];V(()=>{let i=ee(O(this.c,s),a);a.assign(i)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=Dt(ce(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(e=await this.extractIterations(e),e.length!==0)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}};cl.className="SGD";oo(cl);var ip=class extends cl{constructor(e,t,o=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=o,this.accumulations=[],this.m=ce(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(o=>o.name):Object.keys(e)).forEach((o,n)=>{let s=A.registeredVariables[o];if(this.accumulations[n]==null){let l=!1;this.accumulations[n]={originalName:`${o}/momentum`,variable:V(()=>Ne(s).variable(l))}}let a=this.accumulations[n].variable,i=Array.isArray(e)?e[n].tensor:e[o];i!=null&&V(()=>{let l,u=ee(O(this.m,a),i);this.useNesterov?l=ee(O(this.c,ee(i,O(u,this.m))),s):l=ee(O(this.c,u),s),a.assign(u),s.assign(l)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&Ae(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)}};ip.className="Momentum";oo(ip);var ap=class extends Mr{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=A.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=A.registeredVariables[o],a=!1;this.accumulatedMeanSquares[n]==null&&(this.accumulatedMeanSquares[n]={originalName:`${o}/rms`,variable:V(()=>Ne(s).variable(a))}),this.accumulatedMoments[n]==null&&(this.accumulatedMoments[n]={originalName:`${o}/momentum`,variable:V(()=>Ne(s).variable(a))}),this.accumulatedMeanGrads[n]==null&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${o}/mg`,variable:V(()=>Ne(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=ee(O(l,this.decay),O(Me(i),1-this.decay));if(this.centered){let p=this.accumulatedMeanGrads[n].variable,m=ee(O(p,this.decay),O(i,1-this.decay)),f=fe(O(i,this.learningRate),_t(pe(c,ee(Me(m),this.epsilon)))),d=ee(O(u,this.momentum),f);l.assign(c),p.assign(m),u.assign(d);let h=pe(s,d);s.assign(h)}else{let p=ee(O(l,this.decay),O(Me(i),1-this.decay)),m=ee(O(u,this.momentum),fe(O(i,this.learningRate),_t(ee(p,this.epsilon))));l.assign(p),u.assign(m);let f=pe(s,m);s.assign(f)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&Ae(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&Ae(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&Ae(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)}};ap.className="RMSProp";oo(ap);var Ma=class{static sgd(e){return new cl(e)}static momentum(e,t,o=!1){return new ip(e,t,o)}static rmsprop(e,t=.9,o=0,n=null,s=!1){return new ap(e,t,o,n,s)}static adam(e=.001,t=.9,o=.999,n=null){return new np(e,t,o,n)}static adadelta(e=.001,t=.95,o=null){return new rp(e,t,o)}static adamax(e=.002,t=.9,o=.999,n=null,s=0){return new sp(e,t,o,n,s)}static adagrad(e,t=.1){return new op(e,t)}};var pl={sgd:Ma.sgd,momentum:Ma.momentum,adadelta:Ma.adadelta,adagrad:Ma.adagrad,rmsprop:Ma.rmsprop,adamax:Ma.adamax,adam:Ma.adam};var Uj=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:r=>r())();function rf(){return new Promise(r=>Uj(()=>r()))}var S={};et(S,{ERF_A1:()=>tq,ERF_A2:()=>rq,ERF_A3:()=>oq,ERF_A4:()=>nq,ERF_A5:()=>sq,ERF_P:()=>eq,PARALLELIZE_THRESHOLD:()=>gg,SELU_SCALE:()=>aw,SELU_SCALEALPHA:()=>iw,applyActivation:()=>Hu,assertAndGetBroadcastShape:()=>Ve,assertAxesAreInnerMostDims:()=>FG,assertParamsConsistent:()=>jj,assignToTypedArray:()=>fq,axesAreInnerMostDims:()=>y_,calculateShapes:()=>TN,castTensor:()=>_q,combineLocations:()=>qN,complexWithEvenIndex:()=>cq,complexWithOddIndex:()=>pq,computeConv2DInfo:()=>Cu,computeConv3DInfo:()=>UN,computeDefaultPad:()=>r_,computeDilation2DInfo:()=>sW,computeOptimalWindowSize:()=>Hj,computeOutAndReduceShapes:()=>b_,computeOutShape:()=>qj,computePool2DInfo:()=>e_,computePool3DInfo:()=>iW,convertConv2DDataFormat:()=>GN,eitherStridesOrDilationsAreOne:()=>Pt,expandShapeToKeepDim:()=>Bn,exponent:()=>hq,exponents:()=>dq,fromStringArrayToUint8:()=>kq,fromUint8ToStringArray:()=>vq,getAxesPermutation:()=>__,getBroadcastDims:()=>YW,getComplexWithIndex:()=>mq,getFusedBiasGradient:()=>qu,getFusedDyActivation:()=>ju,getImageCenter:()=>Kj,getInnerMostAxes:()=>OG,getPermuted:()=>Yj,getReductionAxes:()=>Nt,getReshaped:()=>Xj,getReshapedPermuted:()=>Zj,getSliceBeginCoords:()=>Jj,getSliceSize:()=>Qj,getUndoAxesPermutation:()=>Lm,log:()=>aq,mergeRealAndImagArrays:()=>lq,prepareAndValidate:()=>SN,prepareSplitSize:()=>gq,reshapeTensor:()=>wq,segment_util:()=>PS,shouldFuse:()=>Ku,slice_util:()=>sr,splitRealAndImagArrays:()=>uq,tupleValuesAreOne:()=>Mo,upcastType:()=>fr,validateInput:()=>Qh,validateUpdateShape:()=>qb,warn:()=>iq});function jj(r,e){let t=r[0].length;r.forEach((n,s)=>{E(n.length===t,()=>`Error in concat${t}D: rank of tensors[${s}] must be the same as the rank of the rest (${t})`)}),E(e>=0&&e`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`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 qj(r,e){let t=r[0].slice();for(let o=1;o=e*2+1||a%2==1?s.push(a):n.push(a);o.push(...n),o.push(0),o.push(...s)}return o}function Zj(r,e,t,o=!0){let n=[];o?n.push(r[0]/t):n.push(r[0]*t);for(let s=1;s"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);E(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}E(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 PS={};et(PS,{collectGatherOpShapeInfo:()=>bq,computeOutShape:()=>yq,segOpComputeOptimalWindowSize:()=>xq});function xq(r,e){let t=!1,o;for(r<=gg?(o=r,t=!0):o=$c(r,Math.floor(Math.sqrt(r)));!t;)o>e||o===r?t=!0:o=$c(r,o+1);return o}function yq(r,e,t){let o=[],n=r.length;for(let s=0;sn))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(tzc(e))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function kq(r){return r.map(e=>rl(e))}var Er={};et(Er,{nonMaxSuppressionV3Impl:()=>rw,nonMaxSuppressionV4Impl:()=>ow,nonMaxSuppressionV5Impl:()=>nw,whereImpl:()=>O_});var xg={kernelName:is,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(r,Es(ne(t,"float32"),-1))}}};var MS={kernelName:js,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let o=Me(ne(t,"float32")),n=_t(pe(ce(1),o));return He(fe(r,n))}}}};var LS={kernelName:qs,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let o=_t(pe(Me(ne(t,"float32")),1));return fe(r,o)}}}};var zS={kernelName:bo,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=Ve(t.shape,o.shape);return{a:()=>{let i=r,l=Nt(t.shape,n);return l.length>0&&(i=be(i,l)),z(i,t.shape)},b:()=>{let i=r,l=Nt(o.shape,n);return l.length>0&&(i=be(i,l)),z(i,o.shape)}}}};var BS={kernelName:Ho,saveAllInputs:!0,gradFunc:(r,e)=>{let t={};return e.forEach((o,n)=>{t[n]=()=>r.clone()}),t}};var VS={kernelName:Ko,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>Ne(t)}}};var WS={kernelName:oa,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>Ne(t)}}};var GS={kernelName:Hs,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>fe(r,_t(pe(ce(1),Me(ne(t,"float32")))))}}};var US={kernelName:Ks,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let o=_t(ee(ce(1),Me(ne(t,"float32"))));return fe(r,o)}}}};var jS={kernelName:Zs,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=Ve(t.shape,o.shape);return{a:()=>{let i=ee(Me(t),Me(o)),l=O(r,fe(o,i)),u=Nt(t.shape,n);return u.length>0&&(l=be(l,u)),z(l,t.shape)},b:()=>{let i=ee(Me(t),Me(o)),l=He(O(r,fe(t,i))),u=Nt(o.shape,n);return u.length>0&&(l=be(l,u)),z(l,o.shape)}}}};var qS={kernelName:Xs,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>fe(r,ee(Me(ne(t,"float32")),1))}}};var HS={kernelName:Ys,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>fe(r,pe(ce(1),Me(ne(t,"float32"))))}}};function Cq(r,e,t,o,n=[1,1,1],s,a){let i=v(r,"dy","avgPool3dGrad"),l=v(e,"input","avgPool3dGrad"),u=i,c=l,p=!1;l.rank===4&&(p=!0,u=z(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),c=z(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]])),E(u.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${u.rank}.`),E(c.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${c.rank}.`),E(Pt(o,n),()=>`Error in avgPool3dGrad: Either strides or dilations must be 1. Got strides ${o} and dilations '${n}'`),a!=null&&E(it(s),()=>`Error in avgPool3dGrad: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`);let m={dy:u,input:c},f={filterSize:t,strides:o,dilations:n,pad:s,dimRoundingMode:a},d=A.runKernel(Hl,m,f);return p?z(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var KS=N({avgPool3dGrad_:Cq});var XS={kernelName:na,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{filterSize:n,strides:s,dilations:a,pad:i,dimRoundingMode:l}=t,u=a==null?[1,1,1]:a;return{x:()=>KS(r,o,n,s,u,i,l)}}};function Iq(r,e,t,o,n){let s=v(r,"dy","avgPoolGrad"),a=v(e,"input","avgPoolGrad");E(a.rank===s.rank,()=>`Rank of input (${a.rank}) does not match rank of dy (${s.rank})`);let i=a,l=s,u=!1;a.rank===3&&(u=!0,i=z(a,[1,a.shape[0],a.shape[1],a.shape[2]]),l=z(s,[1,s.shape[0],s.shape[1],s.shape[2]])),E(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),E(i.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${i.rank}.`);let c={dy:l,input:i},p={filterSize:t,strides:o,pad:n},m=A.runKernel(ql,c,p);return u?z(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var YS=N({avgPoolGrad_:Iq});var ZS={kernelName:Xo,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{filterSize:n,strides:s,pad:a}=t;return{x:()=>YS(r,o,n,s,a)}}};var JS={kernelName:Yo,inputsToSave:["a","b"],gradFunc:(r,e,t)=>{let[o,n]=e,{transposeA:s,transposeB:a}=t;return!s&&!a?{a:()=>je(r,n,!1,!0),b:()=>je(o,r,!0,!1)}:!s&&a?{a:()=>je(r,n,!1,!1),b:()=>je(r,o,!0,!1)}:s&&!a?{a:()=>je(n,r,!1,!0),b:()=>je(o,r,!1,!1)}:{a:()=>je(n,r,!0,!0),b:()=>je(r,o,!0,!0)}}};var QS={kernelName:sa,gradFunc:(r,e,t)=>{let{blockShape:o,crops:n}=t;return{x:()=>Da(r,o,n)}}};var e0={kernelName:yb,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;l1&&i.push(l);return{x:()=>be(r,i,!0)}}};var t0={kernelName:Fo,gradFunc:r=>({x:()=>r.clone()})};var r0={kernelName:Js,gradFunc:r=>({x:()=>Ne(r)})};var o0={kernelName:Oo,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{clipValueMin:n,clipValueMax:s}=t;return{x:()=>$t(dr(Or(o,n),no(o,s)),r,Ne(r))}}};var n0={kernelName:ia,inputsToSave:["x"],gradFunc:xg.gradFunc};var s0={kernelName:as,saveAllInputs:!0,gradFunc:(r,e,t)=>{let o=e.map(l=>l.shape),{axis:n}=t,s=tr(n,e[0].shape)[0],a=o.map(l=>l[s]);return ur(r,a,s).map(l=>()=>l)}};var i0={kernelName:Zo,inputsToSave:["x","filter"],gradFunc:(r,e,t)=>{let[o,n]=e,{dilations:s,strides:a,pad:i,dataFormat:l}=t;return E(Mo(s),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`),{x:()=>Kc(o.shape,r,n,a,i,l),filter:()=>tp(o,r,n.shape,a,i,l)}}};var a0={kernelName:Jo,inputsToSave:["dy","filter"],gradFunc:(r,e,t)=>{let[o,n]=e,{strides:s,pad:a,dataFormat:i,dimRoundingMode:l}=t;return{dy:()=>Xr(r,n,s,a,i,1,l),filter:()=>tp(r,o,n.shape,s,a,i,l)}}};function Nq(r,e,t,o,n){let s=r;r.rank===4&&(s=z(r,[1,r.shape[0],r.shape[1],r.shape[2],r.shape[3]]));let a=e;a.rank===4&&(a=z(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]])),E(s.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${s.shape}.`),E(a.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${a.shape}.`),E(t.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${t}.`),E(s.shape[4]===t[3],()=>`Error in conv3dDerFilter: depth of input ${s.shape[4]}) must match input depth in filter (${t[3]}.`),E(a.shape[4]===t[4],()=>`Error in conv3dDerFilter: depth of dy (${a.shape[4]}) must match output depth for filter (${t[4]}).`);let i={x:s,dy:a},l={strides:o,pad:n,filterShape:t};return A.runKernel(Zl,i,l)}var l0=N({conv3DBackpropFilter_:Nq});var u0={kernelName:aa,inputsToSave:["x","filter"],gradFunc:(r,e,t)=>{let{dilations:o,strides:n,pad:s}=t;E(Mo(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:()=>og(a.shape,r,i,n,s),filter:()=>l0(a,r,i.shape,n,s)}}};var c0={kernelName:Qo,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(He(Bu(ne(t,"float32"))),r)}}};var p0={kernelName:Qs,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(Vu(ne(t,"float32")),r)}}};var m0={kernelName:en,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{axis:n,exclusive:s,reverse:a}=t;return{x:()=>{let i=__([n],o.rank),l=Eu(r,n,s,!a);return i!=null&&(l=qe(l,i)),l}}}};var f0={kernelName:tn,inputsToSave:["x","filter"],gradFunc:(r,e,t)=>{let{dilations:o,strides:n,pad:s,dimRoundingMode:a}=t,i=o==null?[1,1]:o;E(Mo(i),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${i}'`);let[l,u]=e;return E(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),E(u.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${u.rank}.`),E(l.shape[3]===u.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`),E(Pt(n,i),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'.`),a!=null&&E(it(s),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${a} but got pad ${s}.`),{x:()=>pg(l.shape,r,u,n,s,o,a),filter:()=>cg(l,r,u.shape,n,s,o,a)}}};var d0={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:()=>A.runKernel(Fc,s,t),filter:()=>A.runKernel(Oc,a,t)}}};var h0={kernelName:ri,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e,o={dy:r,y:t};return{x:()=>A.runKernel(ou,o)}}};var g0={kernelName:oi,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e,o=O(Qt(He(Me(t))),2/Math.sqrt(Math.PI));return{x:()=>O(r,o)}}};var x0={kernelName:on,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(r,t)}}};var y0={kernelName:ls,inputsToSave:["input"],gradFunc:(r,e)=>{let[t]=e;return{input:()=>z(r,t.shape)}}};var b0={kernelName:si,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(r,Qt(t))}}};var _0={kernelName:nn,gradFunc:r=>({x:()=>Ne(r)})};var w0={kernelName:sn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=Ve(t.shape,o.shape);return{a:()=>{let i=fe(r,ne(o,"float32")),l=Nt(t.shape,n);return l.length>0?z(be(i,l),t.shape):i},b:()=>{let i=O(r,ne(t,"float32")),l=Nt(o.shape,n);l.length>0&&(i=z(be(i,l),o.shape));let u=Me(o);return He(fe(i,ne(u,"float32")))}}}};var v0={kernelName:an,inputsToSave:["x","mean","variance","scale"],gradFunc:(r,e,t)=>{let{varianceEpsilon:o}=t,[n,s,a,i]=e,l=i==null?ce(1):i,u=Nt(s.shape,n.shape),c=[];if(s.rank===1){for(let w=0;ws.rank===1?z(O(O(r,zo(z(f,[1,1,1,s.shape[0]]),c)),l),n.shape):z(O(O(r,f),l),n.shape),mean:()=>{let w=O(O(f,ce(-1)),m);return s.rank===1&&(w=be(w,u)),z(w,s.shape)},variance:()=>{let w=O(O(d,p),m);return s.rank===1&&(w=be(w,u)),z(w,s.shape)},scale:()=>{let w=O(p,f),k=O(r,w);return s.rank===1&&(k=be(k,u)),z(k,s.shape)},offset:()=>{let w=r;return s.rank===1&&(w=be(w,u)),z(w,s.shape)}}}};var I0={kernelName:us,inputsToSave:["x","indices"],gradFunc:(r,e,t)=>{let[o,n]=e,{axis:s}=t,a=tr(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=k0(0,p),h=k0(p+1,p+1+f),g=C0([c,[u],m]),y=z(r,g),b=z(n,[u]),_=C0([[p],d,h]),w=qe(y,_),k=Jm(w,b,o.shape[a]),$=Lm(_);return k=qe(k,$),k},indices:()=>n}}};function k0(r,e){let t=[];for(let o=r;o{let[t,o]=e;return{a:()=>Ne(t),b:()=>Ne(o)}}};var S0={kernelName:cs,gradFunc:r=>({x:()=>ne(r,"float32")})};var T0={kernelName:ui,gradFunc:r=>({x:()=>Ne(r)})};var E0={kernelName:ci,gradFunc:r=>({x:()=>Ne(r)})};var A0={kernelName:pi,gradFunc:r=>({x:()=>Ne(r)})};var D0={kernelName:un,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{alpha:n}=t,s=Xt(o,0);return{x:()=>$t(s,r,O(r,n))}}};var $0={kernelName:di,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>fe(r,ee(t,1))}}};var R0={kernelName:cn,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>fe(r,ne(t,"float32"))}}};var F0={kernelName:bb,inputsToSave:[],outputsToSave:[!0],gradFunc:(r,e,t)=>{let[o]=e,{axis:n}=t;return{logits:()=>{let s=!0,a=Qt(o);return pe(r,O(be(r,n,s),a))}}}};function Sq(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 A.runKernel(lu,i,l)}var O0=N({localResponseNormalizationBackprop_:Sq});var P0={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:()=>O0(o,n,r,s,a,i,l)}}};function yg(r,e,t,o){return e.rankO(r,ne(Yr(t,e),r.dtype))}}var lw={kernelName:pn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let o=t,{reductionIndices:n}=o,s=e[0],a=e[1],i=tr(n,s.shape),l=yg(r,a,s,i);return{x:()=>l.x()}}};var M0={kernelName:mn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e;return{a:()=>O(r,ne(Or(t,o),"float32")),b:()=>O(r,ne(Ta(t,o),"float32"))}}};function Tq(r,e,t,o,n,s=[1,1,1],a,i){let l=v(r,"dy","maxPool3dGrad"),u=v(e,"input","maxPool3dGrad"),c=v(t,"output","maxPool3dGrad"),p=l,m=u,f=c,d=!1;u.rank===4&&(d=!0,p=z(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),m=z(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]]),f=z(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),E(p.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${p.rank}.`),E(m.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${m.rank}.`),E(f.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${f.rank}.`),E(Pt(n,s),()=>`Error in maxPool3dGrad: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),i!=null&&E(it(a),()=>`Error in maxPool3dGrad: pad must be an integer when using, dimRoundingMode ${i} but got pad ${a}.`);let h={dy:p,input:m,output:f},g={filterSize:o,strides:n,dilations:s,pad:a,dimRoundingMode:i},y=A.runKernel(cu,h,g);return d?z(y,[y.shape[1],y.shape[2],y.shape[3],y.shape[4]]):y}var L0=N({maxPool3dGrad_:Tq});var z0={kernelName:pa,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let[o,n]=e,{filterSize:s,strides:a,dilations:i,pad:l,dimRoundingMode:u}=t,c=i==null?[1,1,1]:i;return{x:()=>L0(r,o,n,s,a,c,l,u)}}};function Eq(r,e,t,o,n,s,a){let i=v(r,"dy","maxPoolGrad"),l=v(e,"input","maxPoolGrad"),u=v(t,"output","maxPoolGrad");E(l.rank===i.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${i.rank})`),E(i.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${i.rank}.`),E(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),a!=null&&E(it(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 A.runKernel(uu,c,p)}var B0=N({maxPoolGrad_:Eq});var V0={kernelName:fn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let[o,n]=e,{filterSize:s,strides:a,pad:i}=t;return{x:()=>B0(r,o,n,s,a,i)}}};var W0={kernelName:dn,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{axis:n}=t,s=tr(n,o.shape),i=b_(o.shape,s)[1],l=dt(i);return{x:()=>{let c=o.shape.slice();s.forEach(f=>{c[f]=1});let p=z(r,c);return fe(O(p,Nr(o.shape,"float32")),l)}}}};var G0={kernelName:hn,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(r,e,t)=>{let o=t,{axis:n}=o,[s,a]=e,i=tr(n,s.shape),l=yg(r,a,s,i);return{x:()=>l.x()}}};var U0={kernelName:gn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e;return{a:()=>O(r,ne(no(t,o),"float32")),b:()=>O(r,ne(Xt(t,o),"float32"))}}};var j0={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 q0={kernelName:gi,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=Ve(t.shape,o.shape);return{a:()=>{let i=Nt(t.shape,n);return i.length>0?z(be(r,i),t.shape):r},b:()=>{let i=O(r,He(Ns(fe(t,o)))),l=Nt(o.shape,n);return l.length>0?z(be(i,l),o.shape):i}}}};var H0={kernelName:xn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=Ve(t.shape,o.shape);return{a:()=>{let i=O(r,ne(o,"float32")),l=Nt(t.shape,n);return l.length>0?z(be(i,l),t.shape):i},b:()=>{let i=O(r,ne(t,"float32")),l=Nt(o.shape,n);return l.length>0?z(be(i,l),o.shape):i}}}};var K0={kernelName:ps,gradFunc:r=>({x:()=>He(r)})};var X0={kernelName:yn,inputsToSave:["indices"],gradFunc:(r,e)=>{let t=e[0];return{indices:()=>pt(t.shape,"float32")}}};var Y0={kernelName:ms,gradFunc:r=>({x:()=>Ne(r)})};var Z0={kernelName:fs,saveAllInputs:!0,gradFunc:(r,e,t)=>{let{axis:o}=t;return cr(r,o).map(s=>()=>s)}};var uw={kernelName:bn,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 J0={kernelName:_n,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(r,e)=>{let[t,o,n]=e,s=t,a=o,i=Ve(s.shape,a.shape);return{a:()=>{let c=ne(a,"float32"),p=O(r,O(c,_r(s,pe(c,ce(1))))),m=Nt(s.shape,i);return m.length>0&&(p=be(p,m)),z(p,s.shape)},b:()=>{let c=Xt(s,0),p=$t(c,ar(s),Ne(s)),m=O(r,O(n,p)),f=Nt(a.shape,i);return f.length>0&&(m=be(m,f)),z(m,a.shape)}}}};var Q0={kernelName:wn,inputsToSave:["x","alpha"],gradFunc:(r,e)=>{let[t,o]=e,n=Xt(t,0);return{x:()=>$t(n,r,O(r,o)),alpha:()=>{let s=$t(n,Ne(r),O(r,t)),a=Nt(o.shape,r.shape);return a.length>0&&(s=be(s,a)),z(s,o.shape)}}}};var eT={kernelName:rn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=Ve(t.shape,o.shape);return{a:()=>{let i=fe(r,ne(o,"float32")),l=Nt(t.shape,n);return l.length>0?z(be(i,l),t.shape):i},b:()=>{let i=O(r,ne(t,"float32")),l=Nt(o.shape,n);l.length>0&&(i=z(be(i,l),o.shape));let u=Me(o);return He(fe(i,ne(u,"float32")))}}}};var tT={kernelName:vi,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>fe(r,He(Me(t)))}}};var rT={kernelName:Cn,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e,o=O(no(t,6),Es(t));return{x:()=>O(r,ne(o,"float32"))}}};var oT={kernelName:vn,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(r,ne(Es(t),"float32"))}}};var nT={kernelName:ds,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>z(r,t.shape)}}};var sT={kernelName:kn,inputsToSave:["images"],gradFunc:(r,e,t)=>{let[o]=e,n={dy:r,images:o};return{images:()=>A.runKernel(hu,n,t)}}};var iT={kernelName:da,inputsToSave:["images"],gradFunc:(r,e,t)=>{let[o]=e,n={dy:r,images:o};return{images:()=>A.runKernel(du,n,t)}}};var aT={kernelName:In,gradFunc:(r,e,t)=>{let{dims:o}=t,n=tr(o,r.shape);return{x:()=>Yt(r,n)}}};var lT={kernelName:Nn,gradFunc:r=>({x:()=>Ne(r)})};var uT={kernelName:Sn,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>He(fe(r,O(_r(t,1.5),2)))}}};var cT={kernelName:hs,inputsToSave:["condition"],gradFunc:(r,e)=>{let[t]=e;return{condition:()=>ne(Ne(t),"float32"),t:()=>O(r,ne(t,r.dtype)),e:()=>O(r,ne(Ea(t),r.dtype))}}};var pT={kernelName:Ci,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>{let o=Xt(t,ce(0)),n=ce(iw),s=ce(aw),a=O(r,s),i=O(O(r,n),Qt(ne(t,"float32")));return $t(o,a,i)}}}};var mT={kernelName:En,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(r,O(t,pe(ce(1),t)))}}};var fT={kernelName:Ni,gradFunc:r=>({x:()=>Ne(r)})};var dT={kernelName:Tn,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(Ia(ne(t,"float32")),r)}}};var hT={kernelName:Ii,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(Tu(ne(t,"float32")),r)}}};var gT={kernelName:gs,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{begin:n,size:s}=t,a=o.shape,[i,l]=Hb(o,n,s),u=[];for(let c=0;cPr(r,u)}}};var xT={kernelName:$n,outputsToSave:[!0],gradFunc:(r,e,t)=>{let[o]=e,{dim:n}=t,s=!0,a=O(r,o);return{logits:()=>pe(a,O(be(a,[n],s),o))}}};var yT={kernelName:Si,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(r,Kr(t))}}};var cw={kernelName:ha,gradFunc:(r,e,t)=>{let{blockShape:o,paddings:n}=t;return{x:()=>Ca(r,o,n)}}};var pw={kernelName:xs,gradFunc:(r,e,t)=>{let{axis:o}=t;return{x:()=>Je(r,o)}}};var bT={kernelName:An,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>fe(r,O(_t(ne(t,"float32")),2))}}};var _T={kernelName:ga,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(r,O(ne(t,"float32"),2))}}};var wT={kernelName:Rn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=ce(2);return{a:()=>O(r,O(n,pe(t,o))),b:()=>O(r,O(n,pe(o,t)))}}};var vT={kernelName:Di,gradFunc:r=>({x:()=>Ne(r)})};var kT={kernelName:Fn,inputsToSave:["a","b"],gradFunc:(r,e)=>{let[t,o]=e,n=Ve(t.shape,o.shape);return{a:()=>{let i=r,l=Nt(t.shape,n);return l.length>0&&(i=be(i,l)),z(i,t.shape)},b:()=>{let i=r,l=Nt(o.shape,n);return l.length>0&&(i=be(i,l)),z(He(i),o.shape)}}}};var CT={kernelName:Dn,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,n=o.shape.slice(),{axis:s}=t;tr(s,o.shape).forEach(u=>{n[u]=1});let i=z(r,n),l=O(i,Nr(o.shape,"float32"));return{x:()=>l}}};var IT={kernelName:Ei,inputsToSave:["x"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>fe(r,Me(Ia(t)))}}};var NT={kernelName:On,outputsToSave:[!0],gradFunc:(r,e)=>{let[t]=e;return{x:()=>O(pe(ce(1),Me(t)),r)}}};var ST={kernelName:_o,inputsToSave:["x"],gradFunc:(r,e,t)=>{let[o]=e,{reps:n}=t;return{x:()=>{let a=Ne(o);if(o.rank===1)for(let i=0;i{let o=t,{perm:n}=o,s=Lm(n);return{x:()=>qe(r,s)}}};var ET={kernelName:ys,gradFunc:(r,e,t)=>{let o=t,{axis:n}=o;return{value:()=>Wt(r,n)}}};var AT={kernelName:xa,inputsToSave:["segmentIds"],gradFunc:(r,e)=>{let[t]=e;return{x:()=>Aq(r,t)}}};function Aq(r,e){let t=Ir(e,Ne(e)),o=zn(r,t),n=Or(e,ce(0,"int32")),s=o.rank-n.rank;for(let i=0;i({x:()=>Ne(r)})};var Dq=[xg,MS,LS,zS,BS,VS,WS,GS,US,jS,qS,HS,XS,ZS,JS,QS,e0,t0,r0,o0,n0,s0,a0,i0,u0,c0,p0,m0,f0,d0,eT,h0,g0,x0,y0,b0,w0,_0,v0,I0,N0,S0,T0,E0,A0,D0,$0,R0,F0,P0,lw,lw,M0,z0,V0,W0,G0,U0,j0,q0,H0,K0,X0,Y0,Z0,uw,uw,J0,Q0,tT,rT,oT,nT,sT,iT,aT,lT,uT,cT,pT,mT,fT,dT,hT,gT,xT,yT,cw,cw,pw,pw,bT,wT,_T,vT,kT,CT,IT,NT,ST,TT,ET,AT,DT];for(let r of Dq)wb(r);R.prototype.abs=function(){return this.throwIfDisposed(),Et(this)};R.prototype.acos=function(){return this.throwIfDisposed(),wm(this)};R.prototype.acosh=function(){return this.throwIfDisposed(),vm(this)};R.prototype.addStrict=function(r){return this.throwIfDisposed(),W_(this,r)};R.prototype.add=function(r){return this.throwIfDisposed(),ee(this,r)};R.prototype.all=function(r,e){return this.throwIfDisposed(),ku(this,r,e)};R.prototype.any=function(r,e){return this.throwIfDisposed(),il(this,r,e)};R.prototype.argMax=function(r){return this.throwIfDisposed(),al(this,r)};R.prototype.argMin=function(r){return this.throwIfDisposed(),km(this,r)};R.prototype.asScalar=function(){return this.throwIfDisposed(),E(this.size===1,()=>"The array must have only 1 element."),z(this,[])};R.prototype.asType=function(r){return this.throwIfDisposed(),ne(this,r)};R.prototype.as1D=function(){return this.throwIfDisposed(),z(this,[this.size])};R.prototype.as2D=function(r,e){return this.throwIfDisposed(),z(this,[r,e])};R.prototype.as3D=function(r,e,t){return this.throwIfDisposed(),z(this,[r,e,t])};R.prototype.as4D=function(r,e,t,o){return this.throwIfDisposed(),z(this,[r,e,t,o])};R.prototype.as5D=function(r,e,t,o,n){return this.throwIfDisposed(),z(this,[r,e,t,o,n])};R.prototype.asin=function(){return this.throwIfDisposed(),Cm(this)};R.prototype.asinh=function(){return this.throwIfDisposed(),Im(this)};R.prototype.atan=function(){return this.throwIfDisposed(),Nm(this)};R.prototype.atan2=function(r){return this.throwIfDisposed(),Sm(this,r)};R.prototype.atanh=function(){return this.throwIfDisposed(),Tm(this)};R.prototype.avgPool=function(r,e,t,o){return this.throwIfDisposed(),ka(this,r,e,t,o)};R.prototype.batchToSpaceND=function(r,e){return this.throwIfDisposed(),Ca(this,r,e)};R.prototype.batchNorm=function(r,e,t,o,n){return this.throwIfDisposed(),Ln(this,r,e,t,o,n)};R.prototype.broadcastTo=function(r){return this.throwIfDisposed(),ll(this,r)};R.prototype.cast=function(r){return this.throwIfDisposed(),ne(this,r)};R.prototype.ceil=function(){return this.throwIfDisposed(),Am(this)};R.prototype.clipByValue=function(r,e){return this.throwIfDisposed(),ir(this,r,e)};R.prototype.concat=function(r,e){return this.throwIfDisposed(),r instanceof R&&(r=[r]),Je([this,...r],e)};R.prototype.conv1d=function(r,e,t,o,n,s){return this.throwIfDisposed(),Nu(this,r,e,t,o,n,s)};R.prototype.conv2dTranspose=function(r,e,t,o,n){return this.throwIfDisposed(),Su(this,r,e,t,o,n)};R.prototype.conv2d=function(r,e,t,o,n,s){return this.throwIfDisposed(),Xr(this,r,e,t,o,n,s)};R.prototype.cos=function(){return this.throwIfDisposed(),Ia(this)};R.prototype.cosh=function(){return this.throwIfDisposed(),Tu(this)};R.prototype.cumsum=function(r,e,t){return this.throwIfDisposed(),Eu(this,r,e,t)};R.prototype.depthToSpace=function(r,e){return this.throwIfDisposed(),$m(this,r,e)};R.prototype.depthwiseConv2D=function(r,e,t,o,n,s){return Ot("depthwiseConv2D is deprecated, use depthwiseConv2d instead"),this.throwIfDisposed(),Lo(this,r,e,t,o,n,s)};R.prototype.depthwiseConv2d=function(r,e,t,o,n,s){return this.throwIfDisposed(),Lo(this,r,e,t,o,n,s)};R.prototype.dilation2d=function(r,e,t,o,n){return this.throwIfDisposed(),Rm(this,r,e,t,o,n)};R.prototype.divNoNan=function(r){return this.throwIfDisposed(),Fm(this,r)};R.prototype.divStrict=function(r){return this.throwIfDisposed(),G_(this,r)};R.prototype.div=function(r){return this.throwIfDisposed(),fe(this,r)};R.prototype.dot=function(r){return this.throwIfDisposed(),m_(this,r)};R.prototype.elu=function(){return this.throwIfDisposed(),Is(this)};R.prototype.equalStrict=function(r){return this.throwIfDisposed(),P_(this,r)};R.prototype.equal=function(r){return this.throwIfDisposed(),Yr(this,r)};R.prototype.erf=function(){return this.throwIfDisposed(),Om(this)};R.prototype.exp=function(){return this.throwIfDisposed(),Qt(this)};R.prototype.expandDims=function(r){return this.throwIfDisposed(),br(this,r)};R.prototype.expm1=function(){return this.throwIfDisposed(),Pm(this)};R.prototype.fft=function(){return this.throwIfDisposed(),Fa(this)};R.prototype.flatten=function(){return this.throwIfDisposed(),z(this,[this.size])};R.prototype.floor=function(){return this.throwIfDisposed(),Ns(this)};R.prototype.floorDiv=function(r){return this.throwIfDisposed(),vu(this,r)};R.prototype.gather=function(r,e){return this.throwIfDisposed(),zn(this,r,e)};R.prototype.greaterEqualStrict=function(r){return this.throwIfDisposed(),M_(this,r)};R.prototype.greaterEqual=function(r){return this.throwIfDisposed(),Or(this,r)};R.prototype.greaterStrict=function(r){return this.throwIfDisposed(),L_(this,r)};R.prototype.greater=function(r){return this.throwIfDisposed(),Xt(this,r)};R.prototype.ifft=function(){return this.throwIfDisposed(),Li(this)};R.prototype.irfft=function(){return this.throwIfDisposed(),Wu(this)};R.prototype.isFinite=function(){return this.throwIfDisposed(),f_(this)};R.prototype.isInf=function(){return this.throwIfDisposed(),d_(this)};R.prototype.isNaN=function(){return this.throwIfDisposed(),h_(this)};R.prototype.leakyRelu=function(r){return this.throwIfDisposed(),Sa(this,r)};R.prototype.lessEqualStrict=function(r){return this.throwIfDisposed(),z_(this,r)};R.prototype.lessEqual=function(r){return this.throwIfDisposed(),no(this,r)};R.prototype.lessStrict=function(r){return this.throwIfDisposed(),B_(this,r)};R.prototype.less=function(r){return this.throwIfDisposed(),Ta(this,r)};R.prototype.localResponseNormalization=function(r,e,t,o){return this.throwIfDisposed(),Mm(this,r,e,t,o)};R.prototype.logSigmoid=function(){return this.throwIfDisposed(),x_(this)};R.prototype.logSoftmax=function(r){return this.throwIfDisposed(),$u(this,r)};R.prototype.logSumExp=function(r,e){return this.throwIfDisposed(),zm(this,r,e)};R.prototype.log=function(){return this.throwIfDisposed(),ar(this)};R.prototype.log1p=function(){return this.throwIfDisposed(),Du(this)};R.prototype.logicalAnd=function(r){return this.throwIfDisposed(),dr(this,r)};R.prototype.logicalNot=function(){return this.throwIfDisposed(),Ea(this)};R.prototype.logicalOr=function(r){return this.throwIfDisposed(),Ru(this,r)};R.prototype.logicalXor=function(r){return this.throwIfDisposed(),w_(this,r)};R.prototype.matMul=function(r,e,t){return this.throwIfDisposed(),je(this,r,e,t)};R.prototype.maxPool=function(r,e,t,o){return this.throwIfDisposed(),Aa(this,r,e,t,o)};R.prototype.max=function(r,e){return this.throwIfDisposed(),lr(this,r,e)};R.prototype.maximumStrict=function(r){return this.throwIfDisposed(),U_(this,r)};R.prototype.maximum=function(r){return this.throwIfDisposed(),Ir(this,r)};R.prototype.mean=function(r,e){return this.throwIfDisposed(),bt(this,r,e)};R.prototype.min=function(r,e){return this.throwIfDisposed(),Mi(this,r,e)};R.prototype.minimumStrict=function(r){return this.throwIfDisposed(),j_(this,r)};R.prototype.minimum=function(r){return this.throwIfDisposed(),Bo(this,r)};R.prototype.mirrorPad=function(r,e){return this.throwIfDisposed(),Vm(this,r,e)};R.prototype.modStrict=function(r){return this.throwIfDisposed(),q_(this,r)};R.prototype.mod=function(r){return this.throwIfDisposed(),Fu(this,r)};R.prototype.mulStrict=function(r){return this.throwIfDisposed(),H_(this,r)};R.prototype.mul=function(r){return this.throwIfDisposed(),O(this,r)};R.prototype.neg=function(){return this.throwIfDisposed(),He(this)};R.prototype.norm=function(r,e,t){return this.throwIfDisposed(),Uu(this,r,e,t)};R.prototype.notEqualStrict=function(r){return this.throwIfDisposed(),V_(this,r)};R.prototype.notEqual=function(r){return this.throwIfDisposed(),vo(this,r)};R.prototype.oneHot=function(r,e=1,t=0){return this.throwIfDisposed(),ks(this,r,e,t)};R.prototype.onesLike=function(){return this.throwIfDisposed(),rr(this)};R.prototype.pad=function(r,e){return this.throwIfDisposed(),Pr(this,r,e)};R.prototype.pool=function(r,e,t,o,n){return this.throwIfDisposed(),C_(this,r,e,t,o,n)};R.prototype.powStrict=function(r){return this.throwIfDisposed(),K_(this,r)};R.prototype.pow=function(r){return this.throwIfDisposed(),_r(this,r)};R.prototype.prelu=function(r){return this.throwIfDisposed(),$a(this,r)};R.prototype.prod=function(r,e){return this.throwIfDisposed(),Ou(this,r,e)};R.prototype.reciprocal=function(){return this.throwIfDisposed(),Gm(this)};R.prototype.relu=function(){return this.throwIfDisposed(),Sr(this)};R.prototype.relu6=function(){return this.throwIfDisposed(),Mu(this)};R.prototype.reshapeAs=function(r){return this.throwIfDisposed(),z(this,r.shape)};R.prototype.reshape=function(r){return this.throwIfDisposed(),z(this,r)};R.prototype.resizeBilinear=function(r,e,t){return this.throwIfDisposed(),dg(this,r,e,t)};R.prototype.resizeNearestNeighbor=function(r,e,t){return this.throwIfDisposed(),hg(this,r,e,t)};R.prototype.reverse=function(r){return this.throwIfDisposed(),Yt(this,r)};R.prototype.rfft=function(){return this.throwIfDisposed(),Oa(this)};R.prototype.round=function(){return this.throwIfDisposed(),Um(this)};R.prototype.rsqrt=function(){return this.throwIfDisposed(),Lu(this)};R.prototype.selu=function(){return this.throwIfDisposed(),zu(this)};R.prototype.separableConv2d=function(r,e,t,o,n,s){return this.throwIfDisposed(),jm(this,r,e,t,o,n,s)};R.prototype.sigmoid=function(){return this.throwIfDisposed(),Kr(this)};R.prototype.sign=function(){return this.throwIfDisposed(),qm(this)};R.prototype.sin=function(){return this.throwIfDisposed(),Bu(this)};R.prototype.sinh=function(){return this.throwIfDisposed(),Vu(this)};R.prototype.slice=function(r,e){return this.throwIfDisposed(),Fe(this,r,e)};R.prototype.softmax=function(r){return this.throwIfDisposed(),Ra(this,r)};R.prototype.softplus=function(){return this.throwIfDisposed(),Ss(this)};R.prototype.spaceToBatchND=function(r,e){return this.throwIfDisposed(),Da(this,r,e)};R.prototype.split=function(r,e){return this.throwIfDisposed(),ur(this,r,e)};R.prototype.sqrt=function(){return this.throwIfDisposed(),_t(this)};R.prototype.square=function(){return this.throwIfDisposed(),Me(this)};R.prototype.squaredDifference=function(r){return this.throwIfDisposed(),Pa(this,r)};R.prototype.squaredDifferenceStrict=function(r){return this.throwIfDisposed(),X_(this,r)};R.prototype.squeeze=function(r){return this.throwIfDisposed(),ko(this,r)};R.prototype.stack=function(r,e){this.throwIfDisposed();let t=r instanceof R?[this,r]:[this,...r];return Wt(t,e)};R.prototype.step=function(r){return this.throwIfDisposed(),Es(this,r)};R.prototype.stridedSlice=function(r,e,t,o,n,s,a,i){return this.throwIfDisposed(),Xm(this,r,e,t,o,n,s,a,i)};R.prototype.subStrict=function(r){return this.throwIfDisposed(),Y_(this,r)};R.prototype.sub=function(r){return this.throwIfDisposed(),pe(this,r)};R.prototype.sum=function(r,e){return this.throwIfDisposed(),be(this,r,e)};R.prototype.tan=function(){return this.throwIfDisposed(),Ym(this)};R.prototype.tanh=function(){return this.throwIfDisposed(),Pi(this)};R.prototype.tile=function(r){return this.throwIfDisposed(),zo(this,r)};R.prototype.toBool=function(){return this.throwIfDisposed(),ne(this,"bool")};R.prototype.toFloat=function(){return this.throwIfDisposed(),ne(this,"float32")};R.prototype.toInt=function(){return this.throwIfDisposed(),ne(this,"int32")};R.prototype.topk=function(r,e){return this.throwIfDisposed(),Zm(this,r,e)};R.prototype.transpose=function(r){return this.throwIfDisposed(),qe(this,r)};R.prototype.unique=function(r){return this.throwIfDisposed(),ep(this,r)};R.prototype.unsortedSegmentSum=function(r,e){return this.throwIfDisposed(),Jm(this,r,e)};R.prototype.unstack=function(r){return this.throwIfDisposed(),cr(this,r)};R.prototype.where=function(r,e){return this.throwIfDisposed(),$t(r,this,e)};R.prototype.zerosLike=function(){return this.throwIfDisposed(),Ne(this)};var xw={};et(xw,{maxNorm:()=>Rq,minMaxNorm:()=>Pq,nonNeg:()=>Oq,unitNorm:()=>Fq});var mw;function er(){return mw==null&&(mw=Jb().epsilon()),mw}function Jr(){return"channelsLast"}var Co=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Co.prototype)}},Lr=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Lr.prototype)}},B=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,B.prototype)}},Se=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Se.prototype)}},of=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,of.prototype)}},fw=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,fw.prototype)}};function Gn(r,e){if(Array.isArray(r)){let t=[];for(let o=0;ot.toUpperCase())}var jn={};function lp(r){if(r==null)return null;let e={};return e.className=r.getClassName(),e.config=r.getConfig(),e}function hw(r){if(!(r==null||typeof r!="object"))if(Array.isArray(r))r.forEach(e=>hw(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:hw(o))}}}function Bi(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 jn)a=jn[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 jn?[i,l]=jn.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(jn))u[f]=jn[f];for(let f of Object.keys(t))u[f]=t[f];let c=s.config;c.customObjects=u;let p=Object.assign({},jn);for(let f of Object.keys(t))jn[f]=t[f];hw(s.config);let m=l(i,s.config,t,n);return jn=Object.assign({},p),m}else{let u=Object.assign({},jn);for(let p of Object.keys(t))jn[p]=t[p];let c=new i(s.config);return jn=Object.assign({},u),c}}}function $q(r,e){return re?1:0}function nf(r,e){return-1*$q(r,e)}function qn(r){if(r==null)return r;let e=[];for(let t of r)e.indexOf(t)===-1&&e.push(t);return e}function $T(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 Vi(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 bg(r,e,t=0,o=Infinity){return Vo(t>=0),Vo(o>=t),Array.isArray(r)&&r.length>=t&&r.length<=o&&r.every(n=>typeof n===e)}function jt(r,e){Array.isArray(r)?(x.assert(r.length>0,()=>`${e} is unexpectedly an empty array.`),r.forEach((t,o)=>jt(t,`element ${o+1} of ${e}`))):x.assert(Number.isInteger(r)&&r>0,()=>`Expected ${e} to be a positive integer, but got ${RT(r)}.`)}function RT(r){return r===null?"null":Array.isArray(r)?"["+r.map(e=>RT(e)).join(",")+"]":typeof r=="string"?`"${r}"`:`${r}`}function FT(r,e){let t=x.now(),o;return(...s)=>{let a=x.now();return a-t_t(be(O(r,r),e,!0)))}var up=class extends te.Serializable{getConfig(){return{}}},sf=class extends up{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=gw(e,this.axis),o=ir(t,0,this.maxValue);return O(e,fe(o,ee(er(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};sf.className="MaxNorm";te.registerClass(sf);var af=class extends up{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return V(()=>fe(e,ee(er(),gw(e,this.axis))))}getConfig(){return{axis:this.axis}}};af.className="UnitNorm";te.registerClass(af);var lf=class extends up{apply(e){return Sr(e)}};lf.className="NonNeg";te.registerClass(lf);var uf=class extends up{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=gw(e,this.axis),o=ee(O(this.rate,ir(t,this.minValue,this.maxValue)),O(1-this.rate,t));return O(e,fe(o,ee(er(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};uf.className="MinMaxNorm";te.registerClass(uf);var OT={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Mt(r){return lp(r)}function PT(r,e={}){return Bi(r,te.SerializationMap.getMap().classNameMap,e,"constraint")}function Lt(r){if(r==null)return null;if(typeof r=="string"){let t={className:r in OT?OT[r]:r,config:{}};return PT(t)}else return r instanceof up?r:PT(r)}function Rq(r){return new sf(r)}function Fq(r){return new af(r)}function Oq(){return new lf}function Pq(r){return new uf(r)}var vw={};et(vw,{constant:()=>Uq,glorotNormal:()=>Zq,glorotUniform:()=>Yq,heNormal:()=>Jq,heUniform:()=>Qq,identity:()=>Kq,leCunNormal:()=>eH,leCunUniform:()=>tH,ones:()=>Gq,orthogonal:()=>rH,randomNormal:()=>qq,randomUniform:()=>jq,truncatedNormal:()=>Hq,varianceScaling:()=>Xq,zeros:()=>Wq});var MT=["channelsFirst","channelsLast"],LT=["nearest","bilinear"],zT=["valid","same","causal"],BT=["max","avg"],VT=["sum","mul","concat","ave"];var cp=new Map;function Rt(r){Vi(MT,"DataFormat",r)}function WT(r){Vi(LT,"InterpolationFormat",r)}function Qr(r){Vi(zT,"PaddingMode",r)}function yw(r){Vi(BT,"PoolMode",r)}var cf=[],GT="/";function Ds(r,e){cf.push(r);try{let t=e();return cf.pop(),t}catch(t){throw cf.pop(),t}}function Mq(){return cf.length===0?"":cf.join(GT)+GT}function wg(r){if(!UT(r))throw new Error("Not a valid tensor name: '"+r+"'");return Mq()+r}function vg(r){if(!UT(r))throw new Error("Not a valid tensor name: '"+r+"'");cp.has(r)||cp.set(r,0);let e=cp.get(r);if(cp.set(r,cp.get(r)+1),e>0){let t=`${r}_${e}`;return cp.set(t,1),t}else return r}var Lq=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function UT(r){return!!r.match(Lq)}function jT(r){return r===parseInt(r.toString(),10)}function Hn(r,e,t){e==null&&(e=0),t==null&&(t=r.length);let o=1;for(let n=e;n{if(r.shape.length!==2)throw new B(`repeat() expects a rank-2 tensor, but received a rank-${r.shape.length} tensor.`);let t=Ba(r,1);return kg(t,[1,e,1])})}function KT(r){let e=[Hn(r.shape)];return r.reshape(e)}function XT(r){if(r.rank<=1)throw new B(`batchFlatten requires a minimum rank of 2. Got rank: ${r.rank}.`);let e=[r.shape[0],Hn(r.shape,1)];return r.reshape(e)}function Va(r,e,t){return V(()=>{switch(r.rank){case 1:return Hm(r,e,t);case 2:return ug(r,[e,0],[t,r.shape[1]]);case 3:return Km(r,[e,0,0],[t,r.shape[1],r.shape[2]]);case 4:return Qc(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 bw(r,e,t){return V(()=>{switch(r.rank){case 1:return Hm(r,e,t);case 2:return ug(r,[0,e],[r.shape[0],t]);case 3:return Km(r,[0,0,e],[r.shape[0],r.shape[1],t]);case 4:return Qc(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 pf(r,e,t,o){return V(()=>{switch(r.rank){case 1:return Hm(r,e,t);case 2:switch(o){case 1:return Va(r,e,t);case 2:return bw(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 Va(r,e,t);case 2:return Km(r,[0,e,0],[r.shape[0],t,r.shape[2]]);case 3:return bw(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 Va(r,e,t);case 2:return Qc(r,[0,e,0,0],[r.shape[0],t,r.shape[2],r.shape[3]]);case 3:return Qc(r,[0,0,e,0],[r.shape[0],r.shape[1],t,r.shape[3]]);case 4:return bw(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 pp(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 _w(r,e){switch(r.rank){case 1:return a_([r,e]);case 2:return l_([r,e],0);case 3:return u_([r,e],0);case 4:return c_([r,e],0);default:throw new B(`concatAlongFirstAxis() received an unsupported tensor rank: ${r.rank}`)}}function kg(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 zo(r,e)}function mp(r,e=0,t=1,o,n){return lg(r,e,t,o,n)}function Kn(r,e,t,o){if(r.rank<2||e.rank<2)throw new Se(`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 Se(`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 Vn.matMul({a:r,b:e,transposeA:n,transposeB:s,bias:o?ww(r.rank,o,Jr()):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 Vn.matMul({a:r,b:e,transposeA:m,transposeB:f,bias:o?ww(r.rank,o,Jr()):null,activation:t}).reshape(p)}}function Cg(r,e,t){return V(()=>(Array.isArray(e)?e=Gt(e,"int32"):e=e.toInt(),zn(r,e,t)))}function Yu(r){return O(r,r)}function ww(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 so(r,e,t){return V(()=>(t==null&&(t=Jr()),Rt(t),r.add(ww(r.rank,e,t))))}function YT(r,e=1){if(e!==1)throw new Se(`Support for alpha values other than 1 (${e}) is not implemented yet.`);return Is(r)}function ZT(r){return V(()=>fe(r,Et(r).add(1)))}function Ig(r,e,t,o){return V(()=>Q_(r,e,t,o))}function JT(r){return V(()=>{let e=ee(.5,O(.2,r));return ir(e,0,1)})}function ml(r,e,t=!1){return t?r():e()}var QT=["fanIn","fanOut","fanAvg"],e1=["normal","uniform","truncatedNormal"];function zq(r){Vi(QT,"FanMode",r)}function Bq(r){Vi(e1,"Distribution",r)}var io=class extends te.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},mf=class extends io{apply(e,t){return pt(e,t)}};mf.className="Zeros";te.registerClass(mf);var Zu=class extends io{apply(e,t){return Nr(e,t)}};Zu.className="Ones";te.registerClass(Zu);var ff=class extends io{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(ce(this.value),Nr(e,t)))}getConfig(){return{value:this.value}}};ff.className="Constant";te.registerClass(ff);var df=class extends io{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 Ts(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}};df.className="RandomUniform";te.registerClass(df);var hf=class extends io{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 Se(`randomNormal does not support dType ${t}.`);return mp(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};hf.className="RandomNormal";te.registerClass(hf);var gf=class extends io{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 Se(`truncatedNormal does not support dType ${t}.`);return Gu(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};gf.className="TruncatedNormal";te.registerClass(gf);var xf=class extends io{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,Xc(e[0]))})}getConfig(){return{gain:this.gain}}};xf.className="Identity";te.registerClass(xf);function Vq(r,e="channelsLast"){let t,o;if(Rt(e),r.length===2)t=r[0],o=r[1];else if([3,4,5].indexOf(r.length)!==-1){if(e==="channelsFirst"){let n=Hn(r,2);t=r[1]*n,o=r[0]*n}else if(e==="channelsLast"){let n=Hn(r,0,r.length-2);t=r[r.length-2]*n,o=r[r.length-1]*n}}else{let n=Hn(r);t=Math.sqrt(n),o=Math.sqrt(n)}return[t,o]}var Br=class extends io{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,zq(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,Bq(this.distribution),this.seed=e.seed}apply(e,t){let o=Vq(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 Se(`${this.getClassName()} does not support dType ${t}.`);return Gu(e,0,i,t,this.seed)}else{let i=Math.sqrt(3*a);return Ts(e,-i,i,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};Br.className="VarianceScaling";te.registerClass(Br);var fp=class extends Br{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Br.className}};fp.className="GlorotUniform";te.registerClass(fp);var dp=class extends Br{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Br.className}};dp.className="GlorotNormal";te.registerClass(dp);var hp=class extends Br{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Br.className}};hp.className="HeNormal";te.registerClass(hp);var gp=class extends Br{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Br.className}};gp.className="HeUniform";te.registerClass(gp);var xp=class extends Br{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return Br.className}};xp.className="LeCunNormal";te.registerClass(xp);var yp=class extends Br{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return Br.className}};yp.className="LeCunNormal";te.registerClass(yp);var yf=class extends io{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 Se("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return V(()=>{if(e.length<2)throw new Se("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=mp(o,0,1,"float32"),s=sw.gramSchmidt(n);return e[0]>e[1]&&(s=s.transpose()),O(this.gain,s)})}getConfig(){return{gain:this.gain,seed:this.seed}}};yf.className="Orthogonal";te.registerClass(yf);var t1={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 r1(r,e={}){return Bi(r,te.SerializationMap.getMap().classNameMap,e,"initializer")}function St(r){return lp(r)}function ht(r){if(typeof r=="string"){let e=r in t1?t1[r]:r;if(e==="GlorotNormal")return new dp;if(e==="GlorotUniform")return new fp;if(e==="HeNormal")return new hp;if(e==="HeUniform")return new gp;if(e==="LeCunNormal")return new xp;if(e==="LeCunUniform")return new yp;{let t={};return t.className=e,t.config={},r1(t)}}else return r instanceof io?r:r1(r)}function Wq(){return new mf}function Gq(){return new Zu}function Uq(r){return new ff(r)}function jq(r){return new df(r)}function qq(r){return new hf(r)}function Hq(r){return new gf(r)}function Kq(r){return new xf(r)}function Xq(r){return new Br(r)}function Yq(r){return new fp(r)}function Zq(r){return new dp(r)}function Jq(r){return new hp(r)}function Qq(r){return new gp(r)}function eH(r){return new xp(r)}function tH(r){return new yp(r)}function rH(r){return new yf(r)}var nv={};et(nv,{Layer:()=>Le,RNN:()=>co,RNNCell:()=>wl,activation:()=>_K,add:()=>EK,alphaDropout:()=>m6,average:()=>AK,averagePooling1d:()=>sv,averagePooling2d:()=>iv,averagePooling3d:()=>av,avgPool1d:()=>zK,avgPool2d:()=>VK,avgPool3d:()=>GK,avgPooling1d:()=>BK,avgPooling2d:()=>WK,avgPooling3d:()=>UK,batchNormalization:()=>PK,bidirectional:()=>n6,concatenate:()=>DK,conv1d:()=>mK,conv2d:()=>fK,conv2dTranspose:()=>dK,conv3d:()=>hK,convLstm2d:()=>e6,convLstm2dCell:()=>t6,cropping2D:()=>xK,dense:()=>wK,depthwiseConv2d:()=>bK,dot:()=>OK,dropout:()=>vK,elu:()=>iK,embedding:()=>TK,flatten:()=>CK,gaussianDropout:()=>p6,gaussianNoise:()=>c6,globalAveragePooling1d:()=>jK,globalAveragePooling2d:()=>qK,globalMaxPool1d:()=>i6,globalMaxPool2d:()=>a6,globalMaxPooling1d:()=>M1,globalMaxPooling2d:()=>L1,gru:()=>KK,gruCell:()=>XK,input:()=>Hg,inputLayer:()=>sK,layerNormalization:()=>MK,leakyReLU:()=>lK,lstm:()=>YK,lstmCell:()=>ZK,masking:()=>f6,maxPool1d:()=>l6,maxPool2d:()=>u6,maxPooling1d:()=>z1,maxPooling2d:()=>B1,maxPooling3d:()=>HK,maximum:()=>$K,minimum:()=>RK,multiply:()=>FK,permute:()=>SK,prelu:()=>uK,reLU:()=>aK,repeatVector:()=>IK,reshape:()=>NK,rnn:()=>r6,separableConv2d:()=>gK,simpleRNN:()=>JK,simpleRNNCell:()=>QK,softmax:()=>cK,spatialDropout1d:()=>kK,stackedRNNCells:()=>o6,thresholdedReLU:()=>pK,timeDistributed:()=>s6,upSampling2d:()=>yK,zeroPadding2d:()=>LK});var oH=0;function Ng(){return oH++}var Sg={};function fl(r=""){return r in Sg||(Sg[r]=0),Sg[r]+=1,r+Sg[r].toString()}function Tg(r){return Array.isArray(r)&&Array.isArray(r[0])}function bp(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 _p(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 o1="Variable",bf=class{constructor(e,t="float32",o=o1,n=!0,s=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=Ng(),o=o==null?o1:o,this.originalName=wg(o),this.name=vg(this.originalName),this.trainable_=n,this.constraint=s,this.val=F_(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),nH(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 nH(r,e){if(r.shape.toString()!==e.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(r.shape)+" vs. "+JSON.stringify(e.shape))}function _f(r){return r.map(e=>e.read())}function wp(r){r.forEach(e=>{e[0].write(e[1])})}var At=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||{}}},Vr=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=Ng(),a!=null&&(this.originalName=wg(a),this.name=vg(this.originalName)),this.rank=t.length}},sH=0,dl=class{constructor(e,t){this.callArgs=t,this.id=sH++,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}}},iH=0,Le=class extends te.Serializable{constructor(e={}){super();this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=iH++,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=Un(o)+"_"+fl(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 Lr(`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 hr(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return hr(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new Co(`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 Co(`Layer ${this.name} is not connected, no input to return.`);return hr(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new Co(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new Co(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return hr(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map(e=>e())}get updates(){return this._updates}get built(){return this._built}set built(e){this._built=e}get trainable(){return this.trainable_}set trainable(e){this._trainableWeights.forEach(t=>t.trainable=e),this.trainable_=e}get trainableWeights(){return this.trainable_?this._trainableWeights.filter(e=>e.trainable):[]}set trainableWeights(e){this._trainableWeights=e}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter(e=>!e.trainable).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(e){this._nonTrainableWeights=e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(e){if(e=wt(e),this.inputSpec==null||this.inputSpec.length===0)return;let t=wt(this.inputSpec);if(e.length!==t.length)throw new B(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let o=0;os.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=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{if(!this.built){this.assertInputCompatibility(e);let a=[];for(let i of wt(e))a.push(i.shape);this.build(hr(a)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&s&&(this._refCount=1)}if(this.assertInputCompatibility(e),s){let a=this.call(e,t),i=wt(a),l=[];for(let u of i)o.indexOf(u)!==-1&&(u=u.clone()),l.push(u);if(a=hr(l),this.activityRegularizer!=null)throw new Se("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return a}else{let a=aH(e),i=this.computeOutputShape(a),l,u=lH(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 Vr(u,c,this,wt(e),t,this.name,p)):l=new Vr(u,i,this,wt(e),t,this.name),this.addInboundNode(e,l,null,null,a,i,t),this._refCount++,this.activityRegularizer!=null)throw new Se("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 Co(`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 Co(`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 Lr(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return _p(this.weights)}build(e){this.built=!0}getWeights(e=!1){return _f(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=_f(t);for(let s=0;ss.apply(u.read())),a==null&&(a=!0),a?this._trainableWeights.push(u):this._nonTrainableWeights.push(u),u}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){e==null||Array.isArray(e)&&e.length===0||(e=wt(e),this._losses!==void 0&&this._losses!==null&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(t!=null)if(Array.isArray(t))t.forEach(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=wt(e);t=wt(t),o=wt(o),n=wt(n),s=bp(s),a=bp(a);let u=[],c=[],p=[];for(let m of l)u.push(m.sourceLayer),c.push(m.nodeIndex),p.push(m.tensorIndex);new dl({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;me.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 aH(r){r=wt(r);let e=[];for(let t of r)e.push(t.shape);return hr(e)}function lH(r){return"float32"}function kw(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;s0){let n=await Promise.all(e);for(let s=0;see(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(fe(1,this.seen),this.totals[o]);t[o]=n,this.totals[o].dispose(),Dt(t[o])}))}},$g=class extends hl{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;inew Rg(o,e))}var ao=class{constructor(){}static registerCallbackConstructor(e,t){x.assert(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),ao.checkForDuplicate(t),ao.constructors[e]==null&&(ao.constructors[e]=[]),ao.constructors[e].push(t)}static checkForDuplicate(e){for(let t in ao.constructors)ao.constructors[+t].forEach(n=>{if(n===e)throw new B("Duplicate callback constructor.")})}static clear(){ao.constructors={}}static createCallbacks(e){let t=[];for(let o in ao.constructors){let n=+o;e>=n&&t.push(...ao.constructors[n])}return t.map(o=>new o)}};ao.constructors={};function Og(r,e,t,o,n,s,a,i,l){let u=new $g,c=[new s1,...ao.createCallbacks(e)];r!=null&&c.push(...r),c.push(u);let p=new Dg(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 eo(r,e={},t=!1){return Bi(r,te.SerializationMap.getMap().classNameMap,e,"layer",t)}function wf(r,e){return V(()=>{r.dtype!=="float32"&&(r=r.asType("float32"));let t=be(Yu(r),e,!0),o=Na(t.shape,er()),n=_t(Ir(t,o));return fe(r,n)})}function Ui(r,e){return V(()=>bt(Yu(pe(e,r)),-1))}function vp(r,e){return V(()=>bt(Et(pe(e,r)),-1))}function gl(r,e){return V(()=>{let t=pe(r,e),o=ir(Et(r),er(),Number.MAX_VALUE),n=Et(fe(t,o));return O(100,bt(n,-1))})}function cH(r,e){return V(()=>{let t=ir(e,er(),Number.MAX_VALUE),o=ar(ee(1,t)),n=ir(r,er(),Number.MAX_VALUE),s=ar(ee(1,n));return bt(Yu(pe(o,s)),-1)})}function pH(r,e){return V(()=>{let t=Ir(0,pe(1,O(r,e)));return bt(Yu(t),-1)})}function mH(r,e){return V(()=>{let t=Ir(0,pe(1,O(r,e)));return bt(t,-1)})}function fH(r,e){return V(()=>{let t=be(O(r,e),-1),o=lr(O(pe(1,r),e),-1);return Ir(0,ee(1,pe(o,t)))})}function dH(r,e){return V(()=>{let t=Math.log(2),o=pe(e,r),n=pe(ee(o,Ss(O(-2,o))),t);return bt(n,-1)})}function Ju(r,e,t=!1){return V(()=>{if(t)e=Ra(e);else{let o=be(e,e.shape.length-1,!0);e=fe(e,o)}return e=ir(e,er(),1-er()),He(be(O(r.toFloat(),ar(e)),e.shape.length-1))})}function kp(r,e,t=!1){return V(()=>{let o=Ns(KT(r)).toInt();e=ir(e,er(),1-er());let n=e.shape,s=ks(o,n[n.length-1]).reshape(n);return Ju(s,e,t)})}function hH(r,e){if(!x.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 Cp(r,e){return V(()=>{let t;return t=ir(e,er(),1-er()),t=ar(fe(t,pe(1,t))),bt(hH(r,t),-1)})}function gH(r,e){return V(()=>{let t=ir(r,er(),1),o=ir(e,er(),1);return be(O(r,ar(fe(t,o))),-1)})}function xH(r,e){return V(()=>{let t=ar(ee(er(),e));return bt(pe(e,O(r,t)),-1)})}function vf(r,e){return V(()=>{let t=wf(r,-1),o=wf(e,-1),n=O(t,o);return He(be(n,-1))})}var kf={meanSquaredError:Ui,meanAbsoluteError:vp,meanAbsolutePercentageError:gl,meanSquaredLogarithmicError:cH,squaredHinge:pH,hinge:mH,categoricalHinge:fH,logcosh:dH,categoricalCrossentropy:Ju,sparseCategoricalCrossentropy:kp,binaryCrossentropy:Cp,kullbackLeiblerDivergence:gH,poisson:xH,cosineProximity:vf};function Pg(r){if(typeof r=="string"){if(r in kf)return kf[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 Cf(r,e){return V(()=>{let t=O(.5,rr(e)),o=za(Xt(e,t),r.dtype);return bt(Yr(r,o),-1)})}function If(r,e){return V(()=>za(Yr(al(r,-1),al(e,-1)),"float32"))}function i1(r,e){return V(()=>dr(r.equal(1),e.equal(1)).sum().cast("float32"))}function yH(r,e){return V(()=>dr(r.equal(1),e.equal(0)).sum().cast("float32"))}function bH(r,e){return V(()=>dr(r.equal(0),e.equal(1)).sum().cast("float32"))}function Cw(r,e){return V(()=>{let t=i1(r,e),o=bH(r,e),n=t.add(o);return $t(Xt(n,0),t.div(n),0).cast("float32")})}function a1(r,e){return V(()=>{let t=i1(r,e),o=yH(r,e),n=t.add(o);return $t(Xt(n,0),t.div(n),0).cast("float32")})}function Mg(r,e){return Cp(r,e)}function Lg(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)),Yr(r,e).asType("float32")}var _H=Ui,wH=Ui,vH=vp,kH=vp,CH=gl,IH=gl,Nf=Ju,NH=vf,Iw=kp,zg={binaryAccuracy:Cf,categoricalAccuracy:If,precision:Cw,categoricalCrossentropy:Nf,sparseCategoricalCrossentropy:Iw,mse:_H,MSE:wH,mae:vH,MAE:kH,mape:CH,MAPE:IH,cosine:NH};function l1(r){if(typeof r=="string"&&r in zg)return zg[r];if(typeof r!="string"&&r!=null)return r;throw new B(`Unknown metric ${r}`)}function Sf(r){if(Vo(r!==null,`Unknown LossOrMetricFn ${r}`),typeof r=="string")return r;{let e;for(let t of Object.keys(kf))if(kf[t]===r){e=t;break}if(e!==void 0)return e;for(let t of Object.keys(zg))if(zg[t]===r){e=t;break}return e!==void 0?e:r.name}}function u1(r){let e={Adagrad:()=>pl.adagrad(.01),Adadelta:()=>pl.adadelta(1,.95,er()),Adam:()=>pl.adam(.001,.9,.999,er()),Adamax:()=>pl.adamax(.002,.9,.999,er(),0),RMSProp:()=>pl.rmsprop(.001,.9,0,er()),SGD:()=>pl.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 c1=1*1024*1024;function Sw(r,e,t=!1){if(r==null||typeof r!="object"||Object.getPrototypeOf(r)!==Object.prototype||!Nw(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>c1&&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 <= ${c1}.`)}}function Nw(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"||!Nw(r[t]))return!1;return!0}else if(Array.isArray(r)){for(let e of r)if(!Nw(e))return!1;return!0}else return!1;else{let e=typeof r;return e==="string"||e==="number"||e==="boolean"}}function p1(r,e,t,o=console.log){let n=TH(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)),Bg(s,t,o),o("=".repeat(e));let i=r.layers;for(let c=0;c1||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 Bg(r,e,t=console.log){let o="";for(let n=0;n0&&(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 EH(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()];Bg(a,e,t)}function AH(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;pd.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(Tw[c]==null){let d=$H(a,e);p=d.sorted,m=d.recipientCounts,Tw[c]=p,f1[c]=m}p=Tw[c],m={},n||Object.assign(m,f1[c]);let f=new Rs(e);for(let d=0;do.maxNumTensors&&(o.maxNumTensors=M),M0,()=>"Expected at least one fetch, got none");let t=[],o={};if(r.length===1){let n=d1(r[0],e);t=n.sorted,o=n.recipientMap}else{let n=new Set;for(let s of r){let{sorted:a,recipientMap:i}=d1(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:FH(o)}}function FH(r){let e={};for(let t in r)e[t]=r[t].size;return e}function d1(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 RH(r){let e;if(r.sourceLayer.inboundNodes.length===1)e=r.sourceLayer.output;else{let t=null;for(let o=0;ob.name)}`);qn(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,k=b.tensorIndex;this.outputLayers.push(_),this.outputLayersNodeIndices.push(w),this.outputLayersTensorIndices.push(k)}for(let b of this.inputs){let _=b.sourceLayer,w=b.nodeIndex,k=b.tensorIndex;Vo(w===0,"input layer has >1 nodes"),Vo(k===0,"input layer has >1 tensors"),this.inputLayers.push(_),this.inputLayersNodeIndices.push(w),this.inputLayersTensorIndices.push(k)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let b=0;bb.shape),this.internalOutputShapes=this.outputs.map(b=>b.shape);let t={},o={},n={},s={},a={},i=[],l=(b,_,w,k,$,T)=>{(k==null||$==null||T==null)&&(k=b.sourceLayer,$=b.nodeIndex,T=b.tensorIndex);let F=k.inboundNodes[$];if(w.indexOf(F)!==-1)throw new Lr(`The tensor ${b.name} at layer "${k.name}" is part of a cycle.`);if(_.indexOf(F)!==-1)return;this.containerNodes.add(Wo.nodeKey(k,$)),k.id in a||(a[k.id]=Object.keys(a).length),w.indexOf(F)===-1&&w.push(F);let M=F.inboundLayers.length;for(let L=0;L=0;)w.splice(w.indexOf(F),1);i.push(F)},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 k=0;kparseInt(b,10)).sort(nf);this.layers=[];for(let b of d){let _=f[b];_.sort((w,k)=>{let $=a[w.id],T=a[k.id];return $T?1:0});for(let w of _)w instanceof Wo&&this.internalContainerRefs.push(w),this.layers.push(w)}this.layersByDepth=f,d=Object.keys(m).map(b=>parseInt(b,10)).sort(nf);let h=this.inputs.slice(),g=[];for(let b of d)for(let _ of m[b]){let w=_.outboundLayer;if(w!=null){for(let k of _.inputTensors)if(h.indexOf(k)===-1)throw new Lr(`Graph disconnected: cannot obtain value for tensor ${k} at layer "${w.name}". The following previous layers were accessed without issue: ${g}`);for(let k of _.outputTensors)h.push(k);g.push(w.name)}}this.nodesByDepth=m;let y=this.layers.map(b=>b.name);for(let b of y){let _=y.filter(w=>w===b).length;if(_!==1)throw new Lr(`The name "${b}" is used ${_} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(y))}this.outboundNodes=[],this.inboundNodes=[],new dl({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}`)}wp(s)}updatedConfig(){let e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${xl}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){let o=Vg(this.updatedConfig());return t?JSON.stringify(o):o}call(e,t){return V(()=>{e=wt(e);let o=new Rs;for(let n=0;n{e=wt(e);let o;return t==null?o=Gn(null,e.length):o=wt(t),this.runInternalGraph(e,o)[1]})}computeOutputShape(e){let t=bp(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;iparseInt(i,10)).sort(nf);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;hparseInt(l,10)).sort(nf);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,y,b,_;if(c.callArgs!=null&&(h=c.callArgs),d.length===1){let[w,k]=d[0];h.mask==null&&(h.mask=k),b=wt(p.call(w,h)),_=wt(p.computeMask(w,k)),g=[w],y=[k]}else g=d.map(w=>w[0]),y=d.map(w=>w[1]),h.mask==null&&(h.mask=y),b=wt(p.call(g,h)),_=wt(p.computeMask(g,y));if(p.activityRegularizer)throw new Se("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let w=0;w{let e=[];for(let t of this.layers)for(let o=0;o0){let h=[];for(let g=0;g0&&g.apply(hr(b),_)}function u(g){let y=g.name,b=eo(g,t.customObjects!=null?t.customObjects:{});b.setFastWeightInitDuringBuild(n),s[y]=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(;!$T(a);)for(let g of p){let y=s[g.name];if(y.name in a){let b=a[y.name];delete a[y.name];for(let _ of b)l(y,_)}}let m=[],f=[],d=t.inputLayers;for(let g of d){let y=g[0],b=g[1],_=g[2];Vo(y in s);let k=s[y].inboundNodes[b].outputTensors;m.push(k[_])}let h=t.outputLayers;for(let g of h){let y=g[0],b=g[1],_=g[2];Vo(y in s);let k=s[y].inboundNodes[b].outputTensors;f.push(k[_])}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 OH(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 OH(r,e,"classWeight")}async function Gg(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());Ae(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])}),Gt(a,"float32")}else return null}function h1(r,e){return O(r,e)}var PH=32;function x1(r,e){let t,o,n=e;t=n.xs,o=n.ys,x.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=g1("input",r.inputNames,t),a=g1("output",r.outputNames,o),i=s[0].shape[0];x.assert(s.length===r.inputs.length,()=>`LayersModel has ${r.inputs.length} inputs, but the dataset provides ${s.length} inputs. (Expected input keys: ${JSON.stringify(r.inputNames)})`),x.assert(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`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`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 g1(r,e,t){if(t instanceof R)return[t];if(Array.isArray(t))return x.assert(t.length===e.length,()=>`Received an array of ${t.length} Tensors, but expected ${e.length} to match the ${r} keys ${e}.`),t;{let 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 MH(r){if(r.length===3)throw new Se("Validation with sample weights is not implemented yet.");return{xs:r[0],ys:r[1]}}async function b1(r,e,t){let o=t.batchesPerEpoch!=null;if(x.assert(r.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),x.assert(t!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),x.assert(t.epochs!=null&&t.epochs>0&&Number.isInteger(t.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${t.epochs}`),x.assert(!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}`),x.assert(t.validationSplit==null,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),r.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");r.isTraining=!0;try{let n=t.validationData!=null,s,a;if(n)if(y1(t.validationData))x.assert(t.validationBatches==null||t.validationBatches>0&&Number.isInteger(t.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${t.validationBatches}`);else{let g=MH(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=Fg(t.callbacks,t.yieldEvery),p=t.verbose==null?1:t.verbose,{callbackList:m,history:f}=Og(c,p,t.epochs,null,null,LH(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.batchesPerEpoch:_.done){if(n){let w;y1(t.validationData)?w=wt(await r.evaluateDataset(t.validationData,{batches:t.validationBatches})):w=wt(r.evaluate(s,a,{batchSize:t.validationBatchSize==null?PH:t.validationBatchSize,verbose:0}));for(let k=0;k0)throw new Se("Verbose mode is not implemented yet.");x.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=zH(e)?e:await e.iterator(),i=0,l=0;for(;o?l{if(u.value){let{xs:c,ys:p}=x1(r,u.value),m=c.concat(p),f=V(()=>n(m));if(Ae(m),l===0)for(let h=0;hee(s[h],O(d,g))),l>0&&Ae(y)}Ae(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;u0&&Number.isInteger(r),()=>`batchSize is required to be a positive integer, but got ${r}`)}function Ip(r,e,t){return r==null?[null]:Array.isArray(r)?r.map(o=>Va(o,e,t-e)):Va(r,e,t-e)}function jg(r,e){return V(()=>r==null?null:Array.isArray(r)?r.map(t=>jg(t,e)):Cg(r,e.dtype==="int32"?e:e.toInt()))}function qg(r,e){let t=[],o=0,n=null;for(;o=r&&(n=r),t.push([o,n]),o=n;return t}async function BH(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"),y;g!=null&&(y=zr(0,g)),a==null&&(a=1);let{callbackList:b,history:_}=Og(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{let L=T[F][0],G=T[F][1],H=Va($,L,G-L);M.batch=F,M.size=G-L;let U=jg(t,H),Z=e(U);for(let K=0;K0){if(d=!0,o.validationData.length===2)a=o.validationData[0],i=o.validationData[1];else throw o.validationData.length===3?new Se("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 T=!0,F=await r.standardizeUserData(a,i,null,null,T,p);l=F[0],u=F[1],h=l.concat(u)}else if(o.validationSplit!=null&&o.validationSplit>0&&o.validationSplit<1){d=!0;let T=Math.floor(n[0].shape[0]*(1-o.validationSplit)),F=n[0].shape[0];l=Ip(n,T,F),n=Ip(n,0,T),u=Ip(s,T,F),s=Ip(s,0,T),h=l.concat(u)}else o.validationSteps!=null&&(d=!0);let g=n.concat(s).concat(c);r.checkTrainableWeightsConsistency();let y=r.makeTrainFunction(),b=r.getDedupedMetricsNames(),_,w;d?(r.makeTestFunction(),_=r.testFunction,w=b.slice().concat(b.map(T=>"val_"+T))):(_=null,h=[],w=b.slice());let k=Fg(o.callbacks,o.yieldEvery);return await BH(r,y,g,b,p,o.epochs,o.verbose,k,_,h,o.shuffle,w,o.initialEpoch,null,null)}finally{r.isTraining=!1,yl(n,e),yl(s,t),yl(l,a),yl(u,i),c!=null&&Ae(c)}}function Ew(r){let e=[];r instanceof R&&(r=[r]);for(let t=0;tt.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 R)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 VH(r){return r instanceof R}function Aw(r){return Array.isArray(r)}function v1(r){return!VH(r)&&!Aw(r)}function k1(r,e,t,o=!0,n=""){if(e==null||e.length===0){if(r!=null){let a=!1;if(Aw(r)&&r.length>0)a=!0;else if(v1(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(v1(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(Aw(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=Ew(s),t!=null)for(let a=0;a=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 WH(r,e,t){let o=qn(r.map(s=>s.shape[0]));o.sort();let n=qn(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&&!x.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 GH(r,e,t){let o=[Ui,Cp,Ju];for(let n=0;n1)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[]);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 jH="layers-model",Io=class extends Wo{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).");p1(this,e,t,o)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=u1(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Mr))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(Pg(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=>Pg(i))}else{let a=Pg(e.loss);this.outputs.forEach(i=>{t.push(a)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let a=0;a{for(let a=0;a1&&(this.metricsTensors.push([i,a]),this.metricsNames.push(this.outputNames[a]+"_loss"))}});let n=UH(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])};Ds("metric",()=>{for(let a=0;a{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]===Cp?["accuracy","acc"].indexOf(d)!==-1?m=Cf:["crossentropy","ce"].indexOf(d)!==-1&&(m=Mg):this.lossFunctions[a]===kp?["accuracy","acc"].indexOf(d)!==-1?m=Lg:["crossentropy","ce"].indexOf(d)!==-1&&(m=Iw):["accuracy","acc"].indexOf(d)!==-1?m=If:["crossentropy","ce"].indexOf(d)!==-1&&(m=Nf);let y;["accuracy","acc"].indexOf(d)!==-1?y="acc":["crossentropy","ce"].indexOf(d)!==-1&&(y="ce"),f=m,p=c+y}else f=l1(d),p=c+Sf(d);let h;Ds(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;Ug(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 hr(u)}finally{yl(a[0],e),yl(a[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),_1(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 Rs;if(e instanceof R&&(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;li.name);for(let i=0;i0){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 Se("Verbose predictLoop() is not implemented yet.");let s=qg(n,t),a=this.outputs.map(i=>[]);for(let i=0;i{let u=s[i][0],c=s[i][1],p=Ip(e,u,c),m=[];if(Array.isArray(p))for(let d=0;da[c].push(u));return hr(a.map(i=>Je(i,0)))})}predict(e,t={}){let o=Ew(e);C1(o,this.inputNames,this.feedInputShapes,!1);try{let n=t.batchSize==null?32:t.batchSize;return Ug(n),this.predictLoop(o,n)}finally{yl(o,e)}}predictOnBatch(e){C1(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 Lr("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");let s=[];for(let a=0;a0&&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{let a=this.checkNumSamples(t,o,s,"steps"),i=[];if(n>0)throw new Se("Verbose mode is not implemented yet.");if(s!=null)throw new Se("steps mode in testLoop() is not implemented yet");{let l=qg(a,o),u=Gt(zr(0,a));for(let c=0;c1&&(s+=`_${dw(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;h1&&h{d=ee(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;uUn(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]=Un(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[Un(Sf(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>Un(Sf(e)));{let e={};for(let t in this.metrics)e[t]=Un(Sf(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=Qu(e.optimizer_config),o=eo(t),n;if(typeof e.loss=="string")n=La(e.loss);else if(Array.isArray(e.loss))n=e.loss.map(a=>La(a));else if(e.loss!=null){n={};for(let a in e.loss)n[a]=La(e.loss[a])}let s;if(Array.isArray(e.metrics))s=e.metrics.map(a=>La(a));else if(e.metrics!=null){s={};for(let a in e.metrics)s[a]=La(e.metrics[a])}this.compile({loss:n,metrics:s,optimizer:o})}async save(e,t){if(typeof e=="string"){let u=Cr.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 Cr.encodeWeights(this.getNamedWeights(t)),n=!1,s=null,i={modelTopology:this.toJSON(s,n),format:jH,generatedBy:`TensorFlow.js tfjs-layers v${xl}`,convertedBy:null};if((t==null?!1:t.includeOptimizer)&&this.optimizer!=null){i.trainingConfig=this.getTrainingConfig();let u="optimizer",{data:c,specs:p}=await Cr.encodeWeights(await this.optimizer.getWeights(),u);o.specs.push(...p),o.data=Cr.concatenateArrayBuffers([o.data,c])}if(this.userDefinedMetadata!=null){let u=!0;Sw(this.userDefinedMetadata,this.name,u),i.userDefinedMetadata=this.userDefinedMetadata}return i.weightData=o.data,i.weightSpecs=o.specs,e.save(i)}setUserDefinedMetadata(e){Sw(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};Io.className="Model";te.registerClass(Io);var Dw=class extends Io{};Dw.className="Functional";te.registerClass(Dw);async function I1(r,e){"modelTopology"in r||(r={modelTopology:r}),r=r;let t=r.modelTopology;t.model_config!=null&&(t=t.model_config);let o=Qu(t),n=eo(o,e);if(r.weightsManifest!=null){let s=await Cr.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),Ae(s)}return n}async function N1(r,e){if(e==null&&(e={}),typeof r=="string"){let t=Cr.getLoadHandlers(r,e);if(t.length===0)t.push(Cr.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 qH(r,void 0,e)}async function qH(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=eo(Qu(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}=HH(o.weightData,o.weightSpecs);i.loadWeights(u,s),i.optimizer!=null&&c.length>0&&await i.optimizer.setWeights(c),Ae(u),Ae(c.map(p=>p.tensor))}return i}function HH(r,e){let t=Cr.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 ji=class extends Io{constructor(e){super({inputs:[],outputs:[]});if(e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:fl("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 ji||e instanceof Io,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=Eg({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=kw(this.outputs[0])}this.inboundNodes=[],new dl({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Gn(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 Io({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 Lr("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 Lr("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 Lr("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 Lr("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 x.assert(t.layers!=null,()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."),s=t.layers,delete t.layers,a=t;let i=new e(a);if(!(i instanceof ji))throw new Se(`Sequential.fromConfig called on non-Sequential input: ${i}`);for(let l of s){let c=eo(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}}};ji.className="Sequential";te.registerClass(ji);function S1(r){return new Io(r)}function T1(r){return new ji(r)}function E1(r,e){return e==null&&(e={}),N1(r,e)}function Hg(r){return Eg(r)}function A1(r,e){ao.registerCallbackConstructor(r,e)}var lo=class extends te.Serializable{getConfig(){return{}}},$w=class extends lo{apply(e,t=1){return YT(e,t)}};$w.className="elu";te.registerClass($w);var Rw=class extends lo{apply(e){return zu(e)}};Rw.className="selu";te.registerClass(Rw);var Fw=class extends lo{apply(e){return Sr(e)}};Fw.className="relu";te.registerClass(Fw);var Ow=class extends lo{apply(e){return V(()=>Bo(6,Sr(e)))}};Ow.className="relu6";te.registerClass(Ow);var Pw=class extends lo{apply(e){return e}};Pw.className="linear";te.registerClass(Pw);var Mw=class extends lo{apply(e){return Kr(e)}};Mw.className="sigmoid";te.registerClass(Mw);var Lw=class extends lo{apply(e){return JT(e)}};Lw.className="hardSigmoid";te.registerClass(Lw);var zw=class extends lo{apply(e){return Ss(e)}};zw.className="softplus";te.registerClass(zw);var Bw=class extends lo{apply(e){return ZT(e)}};Bw.className="softsign";te.registerClass(Bw);var Vw=class extends lo{apply(e){return Pi(e)}};Vw.className="tanh";te.registerClass(Vw);var Tf=class extends lo{apply(e,t=-1){return Ra(e,t)}};Tf.className="softmax";te.registerClass(Tf);var Ww=class extends lo{apply(e,t=-1){return $u(e,t)}};Ww.className="logSoftmax";te.registerClass(Ww);var Gw=class extends lo{apply(e,t=1){return V(()=>Kr(e.mul(t)).mul(e))}};Gw.className="swish";te.registerClass(Gw);function Fs(r){return r.getClassName()}function Uw(r,e={}){return Bi(r,te.SerializationMap.getMap().classNameMap,e,"activation")}function Os(r){if(r==null){let e={};return e.className="linear",e.config={},Uw(e)}if(typeof r=="string"){let e={};return e.className=r,e.config={},Uw(e)}else return r instanceof lo?r:Uw(r)}function jw(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 qw=class extends te.Serializable{},tc=class extends qw{constructor(e){super();jw(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=pt([1]);return this.hasL1&&(t=ee(t,be(O(this.l1,Et(e))))),this.hasL2&&(t=ee(t,be(O(this.l2,Yu(e))))),t.asScalar()})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}};tc.className="L1L2";te.registerClass(tc);function D1(r){return jw(r),new tc({l1:r!=null?r.l1:null,l2:0})}function $1(r){return jw(r),new tc({l2:r!=null?r.l2:null,l1:0})}var R1={l1l2:"L1L2"};function ut(r){return lp(r)}function F1(r,e={}){return Bi(r,te.SerializationMap.getMap().classNameMap,e,"regularizer")}function vt(r){if(r==null)return null;if(typeof r=="string"){let t={className:r in R1?R1[r]:r,config:{}};return F1(t)}else return r instanceof qw?r:F1(r)}var Ef=class extends Le{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=Oe(e);let o=Sr(e);return this.maxValue!=null&&(o=ir(o,0,this.maxValue)),o}computeOutputShape(e){return e}getConfig(){let e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}};Ef.className="ReLU";te.registerClass(Ef);var Af=class extends Le{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}};Af.className="LeakyReLU";te.registerClass(Af);var Df=class extends Le{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=ht(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=vt(e.alphaRegularizer),this.alphaConstraint=Lt(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(Rt(e),e==="channelsFirst"?qe(r,[0,2,3,1]):r))}function Hw(r,e){return V(()=>(Rt(e),e==="channelsFirst"?qe(r,[0,2,3,4,1]):r))}function KH(r,e,t,o=1,n="valid",s,a=1){return V(()=>{if(s==null&&(s=Jr()),Rt(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=qe(r,[0,2,1])),n==="causal")throw new Se("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let i=Nu(r,e,o,n==="same"?"same":"valid","NWC",a);return t!=null&&(i=so(i,t)),i})}function O1(r,e,t,o=[1,1],n="valid",s,a,i=null){return V(()=>{if(s==null&&(s=Jr()),Rt(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=Pf(r,s);if(n==="causal")throw new Se("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=Vn.conv2d({x:l,filter:e,strides:o,pad:n==="same"?"same":"valid",dilations:a,dataFormat:"NHWC",bias:t,activation:i}),s==="channelsFirst"&&(l=qe(l,[0,3,1,2])),l})}function XH(r,e,t,o=[1,1,1],n="valid",s,a){return V(()=>{if(s==null&&(s=Jr()),Rt(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=Hw(r,s);if(n==="causal")throw new Se("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return i=Dm(i,e,o,n==="same"?"same":"valid","NDHWC",a),t!=null&&(i=so(i,t)),s==="channelsFirst"&&(i=qe(i,[0,4,1,2,3])),i})}var Np=class extends Le{constructor(e,t){super(t);if(this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",Np.verifyArgs(t),this.rank=e,jt(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new Se(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=bl(t.kernelSize,e,"kernelSize"),this.strides=bl(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,Qr(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,Rt(this.dataFormat),this.activation=Os(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=ht(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Lt(t.biasConstraint),this.biasRegularizer=vt(t.biasRegularizer),this.activityRegularizer=vt(t.activityRegularizer),this.dilationRate=bl(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(Vo("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!bg(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:Fs(this.activation),useBias:this.useBias,biasInitializer:St(this.biasInitializer),biasRegularizer:ut(this.biasRegularizer),activityRegularizer:ut(this.activityRegularizer),biasConstraint:Mt(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}},rc=class extends Np{constructor(e,t){super(e,t);this.kernel=null,rc.verifyArgs(t),this.filters=t.filters,jt(this.filters,"filters"),this.kernelInitializer=ht(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Lt(t.kernelConstraint),this.kernelRegularizer=vt(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=_g(this.activation.getClassName());if(s!=null&&this.rank===2)o=O1(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate,s);else{if(this.rank===1)o=KH(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)o=O1(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)o=XH(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new Se("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 0 but got ${JSON.stringify(e.filters)}`)}},_l=class extends rc{constructor(e){super(2,e);_l.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!bg(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)}.`)}};_l.className="Conv2D";te.registerClass(_l);var oc=class extends rc{constructor(e){super(3,e);oc.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)}.`)}};oc.className="Conv3D";te.registerClass(oc);var Mf=class extends _l{constructor(e){super(e);if(this.inputSpec=[new At({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 At({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=Of(l,m,c,this.padding),h=Of(u,f,p,this.padding),g=[s,d,h,this.filters];this.dataFormat!=="channelsLast"&&(o=qe(o,[0,2,3,1]));let y=Su(o,this.kernel.read(),g,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(y=qe(y,[0,3,1,2])),this.bias!=null&&(y=so(y,this.bias.read(),this.dataFormat)),this.activation!=null&&(y=this.activation.apply(y)),y})}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]=Of(t[n],l,a,this.padding),t[s]=Of(t[s],u,i,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};Mf.className="Conv2DTranspose";te.registerClass(Mf);var Kw=class extends rc{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=ht(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=vt(t.depthwiseRegularizer),this.depthwiseConstraint=Lt(t.depthwiseConstraint),this.pointwiseInitializer=ht(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=vt(t.pointwiseRegularizer),this.pointwiseConstraint=Lt(t.pointwiseConstraint)}build(e){if(e=Qe(e),e.length{e=Oe(e);let o;if(this.rank===1)throw new Se("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=qe(e,[0,2,3,1])),o=jm(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(o=so(o,this.bias.read(),this.dataFormat)),this.activation!=null&&(o=this.activation.apply(o)),this.dataFormat==="channelsFirst"&&(o=qe(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=St(this.depthwiseInitializer),e.pointwiseInitializer=St(this.pointwiseInitializer),e.depthwiseRegularizer=ut(this.depthwiseRegularizer),e.pointwiseRegularizer=ut(this.pointwiseRegularizer),e.depthwiseConstraint=Mt(this.depthwiseConstraint),e.pointwiseConstraint=Mt(this.pointwiseConstraint),e}};Kw.className="SeparableConv";var Lf=class extends Kw{constructor(e){super(2,e)}};Lf.className="SeparableConv2D";te.registerClass(Lf);var nc=class extends rc{constructor(e){super(1,e);nc.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"&&!bg(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)}.`)}};nc.className="Conv1D";te.registerClass(nc);var zf=class extends Le{constructor(e){super(e);typeof e.cropping=="number"?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:typeof e.cropping[0]=="number"?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=e.dataFormat===void 0?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return this.dataFormat==="channelsFirst"?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return V(()=>{if(e=Oe(e),this.dataFormat==="channelsLast"){let o=pf(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return pf(o,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let o=pf(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return pf(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}};zf.className="Cropping2D";te.registerClass(zf);var Bf=class extends Le{constructor(e){super(e);this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=e.size==null?this.DEFAULT_SIZE:e.size,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Rt(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,WT(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=qe(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 qe(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}};Bf.className="UpSampling2D";te.registerClass(Bf);function YH(r,e,t=[1,1],o="valid",n,s){return V(()=>{n==null&&(n=Jr()),Rt(n);let a=Pf(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=Lo(a,e,t,o==="same"?"same":"valid","NHWC",s),n==="channelsFirst"&&(a=qe(a,[0,3,1,2])),a})}var Vf=class extends Np{constructor(e){super(2,e);this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=ht(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Lt(e.depthwiseConstraint),this.depthwiseRegularizer=vt(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=YH(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(o=so(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=uo(t,this.kernelSize[0],this.padding,this.strides[0]),a=uo(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=St(this.depthwiseInitializer),e.depthwiseRegularizer=ut(this.depthwiseRegularizer),e.depthwiseConstraint=Mt(this.depthwiseRegularizer),e}};Vf.className="DepthwiseConv2D";te.registerClass(Vf);function Xw(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 Yw(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(zr(2,l));if(e=qe(e,u),s!=null)throw new Se("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=br(n,-1)),n=qe(n,u)),o&&(e=Yt(e,0),n!=null&&(n=Yt(n,0)));let c=[],p,m=t,f=e.shape[0],d=cr(e),h;n!=null&&(h=cr(n));for(let y=0;yr(b,m));if(n==null)p=_[0],m=_[1];else{let w=V(()=>{let k=h[y],$=rr(k).sub(k),T=_[0].mul(k).add(m[0].mul($)),F=m.map((M,L)=>_[1][L].mul(k).add(M.mul($)));return{output:T,newStates:F}});p=w.output,m=w.newStates}i&&c.push(p)}let g;return i&&(g=Wt(c,1)),[p,g,m]})}var co=class extends Le{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 Sp({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 At({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 zr(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){Tg(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;oi.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 At({shape:[null,i]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){V(()=>{if(!this.stateful)throw new Co("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=>pt([o,n])):this.states_=[pt([o,this.cell.stateSize])];else if(e==null)Ae(this.states_),this.keptStates!=null&&(Ae(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(n=>pt([o,n])):this.states_[0]=pt([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()):Ae(this.states_);for(let n=0;nDt(n.clone()))})}apply(e,t){let o=t==null?null:t.initialState,n=t==null?null:t.constants;t==null&&(t={});let s=Xw(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 At({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 Vr){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=Yw((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=pt(e.shape);return t=be(t,[1,2]),t=Ba(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(o=>o>1?kg(t,[1,o]):t):this.cell.stateSize>1?[kg(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()===co.className&&(t.cell={className:this.cell.getClassName(),config:o}),Object.assign({},o,e,t)}static fromConfig(e,t,o={}){let n=t.cell,s=eo(n,o);return new e(Object.assign(t,{cell:s}))}};co.className="RNN";te.registerClass(co);var wl=class extends Le{},Tp=class extends wl{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,jt(this.units,"units"),this.activation=Os(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=ht(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=ht(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=ht(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=vt(e.kernelRegularizer),this.recurrentRegularizer=vt(e.recurrentRegularizer),this.biasRegularizer=vt(e.biasRegularizer),this.kernelConstraint=Lt(e.kernelConstraint),this.recurrentConstraint=Lt(e.recurrentConstraint),this.biasConstraint=Lt(e.biasConstraint),this.dropout=Xu([1,$s([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Xu([1,$s([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;0rr(e),rate:this.dropout,training:n})),0rr(o),rate:this.recurrentDropout,training:n}));let s,a=this.dropoutMask,i=this.recurrentDropoutMask;a!=null?s=Kn(O(e,a),this.kernel.read()):s=Kn(e,this.kernel.read()),this.bias!=null&&(s=so(s,this.bias.read())),i!=null&&(o=O(o,i));let l=ee(s,Kn(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:Fs(this.activation),useBias:this.useBias,kernelInitializer:St(this.kernelInitializer),recurrentInitializer:St(this.recurrentInitializer),biasInitializer:St(this.biasInitializer),kernelRegularizer:ut(this.kernelRegularizer),recurrentRegularizer:ut(this.recurrentRegularizer),biasRegularizer:ut(this.biasRegularizer),activityRegularizer:ut(this.activityRegularizer),kernelConstraint:Mt(this.kernelConstraint),recurrentConstraint:Mt(this.recurrentConstraint),biasConstraint:Mt(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign({},e,t)}};Tp.className="SimpleRNNCell";te.registerClass(Tp);var Wf=class extends co{constructor(e){e.cell=new Tp(e),super(e)}call(e,t){return V(()=>{this.cell.dropoutMask!=null&&(Ae(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Ae(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)}};Wf.className="SimpleRNN";te.registerClass(Wf);var Ep=class extends wl{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,jt(this.units,"units"),this.activation=Os(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Os(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=ht(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=ht(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=ht(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=vt(e.kernelRegularizer),this.recurrentRegularizer=vt(e.recurrentRegularizer),this.biasRegularizer=vt(e.biasRegularizer),this.kernelConstraint=Lt(e.kernelConstraint),this.recurrentConstraint=Lt(e.recurrentConstraint),this.biasConstraint=Lt(e.biasConstraint),this.dropout=Xu([1,$s([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Xu([1,$s([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],0rr(e),rate:this.dropout,training:o,count:3})),0rr(n),rate:this.recurrentDropout,training:o,count:3}));let s=this.dropoutMask,a=this.recurrentDropoutMask,i,l,u;0{this.cell.dropoutMask!=null&&(Ae(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Ae(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)}};Gf.className="GRU";te.registerClass(Gf);var vl=class extends wl{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,jt(this.units,"units"),this.activation=Os(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Os(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=ht(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=ht(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=ht(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=vt(e.kernelRegularizer),this.recurrentRegularizer=vt(e.recurrentRegularizer),this.biasRegularizer=vt(e.biasRegularizer),this.kernelConstraint=Lt(e.kernelConstraint),this.recurrentConstraint=Lt(e.recurrentConstraint),this.biasConstraint=Lt(e.biasConstraint),this.dropout=Xu([1,$s([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Xu([1,$s([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 io{apply(l,u){let c=s.apply([a]),p=new Zu().apply([a]),m=s.apply([a*2]);return _w(_w(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],0rr(e),rate:this.dropout,training:o,count:4})),0rr(n),rate:this.recurrentDropout,training:o,count:4}));let a=this.dropoutMask,i=this.recurrentDropoutMask,l,u,c,p;0{this.cell.dropoutMask!=null&&(Ae(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Ae(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)}};Uf.className="LSTM";te.registerClass(Uf);var Sp=class extends wl{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{Ds(`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(eo(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 _f(e)}setWeights(e){let t=[];for(let o of this.cells){let n=o.weights.length,s=e.splice(n);for(let a=0;aIg(e(),t),a=()=>ml(s,e,o);return!n||n<=1?Dt(a().clone()):Array(n).fill(void 0).map(a).map(l=>Dt(l.clone()))}var ZH=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{if(this.cell.dropoutMask!=null&&(Ae(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Ae(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=pt(s);return Array.isArray(t)?Array(t.length).fill(a):[a]})}resetStates(e,t=!1){V(()=>{if(!this.stateful)throw new Co("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(()=>pt(s)):this.states_=[pt(s)];else if(e==null)Ae(this.states_),this.keptStates!=null&&(Ae(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>pt(s)):this.states_[0]=pt(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()):Ae(this.states_);for(let i=0;iDt(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=uo(u,n[0],s,a[0],i[0]),m=uo(c,n[1],s,a[1],i[1]);return[...e.slice(0,2),...l?[o,p,m]:[p,m,o]]}};Zw.className="ConvRNN2D";var Ap=class extends vl{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,jt(this.filters,"filters"),this.kernelSize=bl(o,2,"kernelSize"),this.kernelSize.forEach(l=>jt(l,"kernelSize")),this.strides=bl(n||1,2,"strides"),this.strides.forEach(l=>jt(l,"strides")),this.padding=s||"valid",Qr(this.padding),this.dataFormat=a||"channelsLast",Rt(this.dataFormat),this.dilationRate=bl(i||1,2,"dilationRate"),this.dilationRate.forEach(l=>jt(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 io{apply(m,f){let d=u.apply([c]),h=Nr([c]),g=u.apply([c*2]);return pp([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;0rr(n),rate:this.dropout,training:o,count:i}));let l=this.dropoutMask,u=(ie,ae,ue)=>!ae||!ae[ue]?ie:O(ae[ue],ie),c=u(n,l,0),p=u(n,l,1),m=u(n,l,2),f=u(n,l,3);0rr(s),rate:this.recurrentDropout,training:o,count:i}));let d=this.recurrentDropoutMask,h=u(s,d,0),g=u(s,d,1),y=u(s,d,2),b=u(s,d,3),_=3,[w,k,$,T]=ur(this.kernel.read(),i,_),[F,M,L,G]=this.useBias?ur(this.bias.read(),i):[null,null,null,null];c=this.inputConv(c,w,F,this.padding),p=this.inputConv(p,k,M,this.padding),m=this.inputConv(m,$,L,this.padding),f=this.inputConv(f,T,G,this.padding);let[H,U,Z,K]=ur(this.recurrentKernel.read(),i,_);h=this.recurrentConv(h,H),g=this.recurrentConv(g,U),y=this.recurrentConv(y,Z),b=this.recurrentConv(b,K);let X=this.recurrentActivation.apply(ee(c,h)),oe=this.recurrentActivation.apply(ee(p,g)),J=ee(O(oe,a),O(X,this.activation.apply(ee(m,y)))),Q=O(this.recurrentActivation.apply(ee(f,b)),this.activation.apply(J));return[Q,Q,J]})}getConfig(){let e=super.getConfig(),{units:t}=e,o=ZH(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=Xr(e,t,this.strides,n||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return o?so(s,o,this.dataFormat):s}recurrentConv(e,t){return Xr(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};Ap.className="ConvLSTM2DCell";te.registerClass(Ap);var jf=class extends Zw{constructor(e){let t=new Ap(e);super(Object.assign({},e,{cell:t}))}static fromConfig(e,t){return new e(t)}};jf.className="ConvLSTM2D";te.registerClass(jf);var Dp=class extends Le{constructor(e){super(e);this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(this.noiseShape==null)return this.noiseShape;let t=e.shape,o=[];for(let n=0;n{this.invokeCallHook(e,t);let o=Oe(e);if(0Ig(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()}};Dp.className="Dropout";te.registerClass(Dp);var qf=class extends Dp{constructor(e){super(e);this.inputSpec=[{ndim:3}]}getNoiseShape(e){let t=e.shape;return[t[0],1,t[2]]}};qf.className="SpatialDropout1D";te.registerClass(qf);var Hf=class extends Le{constructor(e){super(e);if(this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.batchInputShape==null&&e.inputShape==null&&e.inputDim!=null){let t=null;e.batchSize!=null&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,jt(this.units,"units"),this.activation=Os(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=ht(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=ht(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Lt(e.kernelConstraint),this.biasConstraint=Lt(e.biasConstraint),this.kernelRegularizer=vt(e.kernelRegularizer),this.biasRegularizer=vt(e.biasRegularizer),this.activityRegularizer=vt(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=_g(this.activation.getClassName()),s;return n!=null?s=Kn(o,this.kernel.read(),n,this.bias?this.bias.read():null):(s=Kn(o,this.kernel.read()),this.bias!=null&&(s=so(s,this.bias.read())),this.activation!=null&&(s=this.activation.apply(s))),s})}getConfig(){let e={units:this.units,activation:Fs(this.activation),useBias:this.useBias,kernelInitializer:St(this.kernelInitializer),biasInitializer:St(this.biasInitializer),kernelRegularizer:ut(this.kernelRegularizer),biasRegularizer:ut(this.biasRegularizer),activityRegularizer:ut(this.activityRegularizer),kernelConstraint:Mt(this.kernelConstraint),biasConstraint:Mt(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}};Hf.className="Dense";te.registerClass(Hf);var Kf=class extends Le{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],Hn(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{this.invokeCallHook(e,t);let o=Oe(e);return this.activation.apply(o)})}getConfig(){let e={activation:Fs(this.activation)},t=super.getConfig();return Object.assign(e,t),e}};Xf.className="Activation";te.registerClass(Xf);var Yf=class extends Le{constructor(e){super(e);this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return V(()=>(e=Oe(e),HT(e,this.n)))}getConfig(){let e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}};Yf.className="RepeatVector";te.registerClass(Yf);var Zf=class extends Le{constructor(e){super(e);this.targetShape=e.targetShape;for(let t=0;t{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}};Zf.className="Reshape";te.registerClass(Zf);var Jf=class extends Le{constructor(e){super(e);if(e.dims==null)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);let t=zr(1,e.dims.length+1);if(!x.arraysEqual(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new At({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 qe(Oe(e),this.dimsIncludingBatch)}getConfig(){let e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}};Jf.className="Permute";te.registerClass(Jf);var Qf=class extends Le{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 il(vo(o,this.maskValue),n)}call(e,t){return V(()=>{this.invokeCallHook(e,t);let o=Oe(e),n=-1,s=!0,a=il(vo(o,this.maskValue),n,s);return o.mul(a.asType(o.dtype))})}};Qf.className="Masking";te.registerClass(Qf);var ed=class extends Le{constructor(e){super(e);if(this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",e.batchInputShape==null&&e.inputShape==null){let t=null;e.batchSize!=null&&(t=e.batchSize),e.inputLength==null?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(wt(e.inputLength))}this.inputDim=e.inputDim,jt(this.inputDim,"inputDim"),this.outputDim=e.outputDim,jt(this.outputDim,"outputDim"),this.embeddingsInitializer=ht(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=vt(e.embeddingsRegularizer),this.activityRegularizer=vt(e.activityRegularizer),this.embeddingsConstraint=Lt(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),vo(e,Ne(e))):null)}computeOutputShape(e){if(e=Qe(e),this.inputLength==null)return[...e,this.outputDim];let t=wt(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{this.invokeCallHook(e,t);let o=Oe(e);return o.dtype!=="int32"&&(o=za(o,"int32")),Cg(this.embeddings.read(),o.as1D()).reshape(Qe(this.computeOutputShape(o.shape)))})}getConfig(){let e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:St(this.embeddingsInitializer),embeddingsRegularizer:ut(this.embeddingsRegularizer),activityRegularizer:ut(this.activityRegularizer),embeddingsConstraint:Mt(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}};ed.className="Embedding";te.registerClass(ed);var kl=class extends Le{constructor(e){super(e||{});this.supportsMasking=!0}mergeFunction(e){throw new Se}computeElementwiseOpOutputShape(e,t){if(e==null||t==null)return null;if(e.length1)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;ss.length);e.indexOf(null)===-1&&qn(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=$s(n);for(let a of e){let i=a.rank;for(let l=0;l1){let c=zr(1,u).concat([0]);o.push(qe(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=qe(a.reshape([-1,c]),[1,0]).reshape(p)}else if(i>1){let l=[i-1].concat(zr(0,i-1));a=qe(a,l)}}return a}}else return this.mergeFunction(e)})}computeOutputShape(e){e=e;let t;e[0]==null?t=null:t=e[0].slice(1);for(let n=1;n{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:br(n,0));let o=t[0];for(let n=1;n{let t=e[0].clone();for(let o=1;o{let t=e[0].clone();for(let o=1;o{let t=e[0].clone();for(let o=1;o{let t=e[0];for(let o=1;o{let t=e[0];for(let o=1;o1)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(()=>pp(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;a3||e.shape.length>3)throw new Se("batchDot is not implemented for tensors of 4D or higher rank yet");if(x.assert(r.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${r.shape.length}`),x.assert(r.shape.length>=2,()=>`batchDot requires the rank of y to be >= 2, but got ${e.shape.length}`),typeof t=="number"&&(t=[t,t]),r.dtype==="complex64"||e.dtype==="complex64")throw new Se("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;uo){a=n-o;let l=[];for(let u=0;u0){let l;o>n?l=o+n-3:l=o-1;let u=[];for(let c=l;c"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 Se("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)=>ad(s,e[a].shape.length)):n=[ad(this.axes,t.shape.length),ad(this.axes,o.shape.length)],this.normalize&&(t=wf(t,n[0]),o=wf(o,n[1])),JH(t,o,n)}interpretAxes(e,t){let o;return Array.isArray(this.axes)?o=this.axes:o=[ad(this.axes,e.length),ad(this.axes,t.length)],o}computeOutputShape(e){x.assert(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");let t=e[0].slice(),o=e[1].slice();if(t.length>3||o.length>3)throw new Se("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}};ld.className="Dot";te.registerClass(ld);var ud=class extends Le{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 ml(()=>mp(o.shape,0,this.stddev).add(o),()=>o,t.training||!1)})}};ud.className="GaussianNoise";te.registerClass(ud);var cd=class extends Le{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?ml(()=>{let s=Math.sqrt(this.rate/(1-this.rate));return o.mul(mp(o.shape,1,s))},()=>o,t.training||!1):o})}};cd.className="GaussianDropout";te.registerClass(cd);var pd=class extends Le{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 ml(()=>{let s=Oe(e),a=1.6732632423543772,i=1.0507009873554805,l=-a*i,u=Or(Ts(o),this.rate);u=za(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})}};pd.className="AlphaDropout";te.registerClass(pd);function md(r,e,t,o,n,s=.001){let a;if(r.rank===2)a=o_(r,e,t,o,n,s);else if(r.rank===3)a=n_(r,e,t,o,n,s);else if(r.rank===4)a=s_(r,e,t,o,n,s);else throw new Se(`batchNormalization is not implemented for array of rank ${r.rank} yet`);return a}function QH(r,e,t,o,n=.001){return V(()=>{let s=Yc(r,o),a=s.mean,i=s.variance;return[md(r,a,i,t,e,n),a,i]})}function eK(r,e,t,o,n=.001){return V(()=>{let s=Yc(r,o),a=s.mean,i=s.variance,l=[];for(let d of zr(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[md(r,u,c,m,p,n),a,i]})}function tK(r,e,t,o,n=.001){return x.arraysEqual(o.slice().sort(),zr(0,r.rank-1))?QH(r,e,t,o,n):eK(r,e,t,o,n)}var fd=class extends Le{constructor(e){e==null&&(e={}),super(e),this.supportsMasking=!0,this.axis=e.axis==null?-1:e.axis,this.momentum=e.momentum==null?.99:e.momentum,this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=ht(e.betaInitializer||"zeros"),this.gammaInitializer=ht(e.gammaInitializer||"ones"),this.movingMeanInitializer=ht(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=ht(e.movingVarianceInitializer||"ones"),this.betaConstraint=Lt(e.betaConstraint),this.gammaConstraint=Lt(e.gammaConstraint),this.betaRegularizer=vt(e.betaRegularizer),this.gammaRegularizer=vt(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 At({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=zr(0,a),l=this.axis>=0?this.axis:this.axis+a;i.splice(l,1);let u=Gn(1,a);u[l]=s[l];let c=i.slice();c.sort();let p=!x.arraysEqual(c,zr(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,k=this.scale?this.gamma.read().reshape(u):null;return md(n,b,_,w,k,this.epsilon)}else return md(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]=tK(n,this.gamma.read(),this.beta.read(),i,this.epsilon),g=(b,_,w)=>{V(()=>{let k=1-w,$=b.read(),T=$.sub(_).mul(k);b.write($.sub(T))})};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:St(this.betaInitializer),gammaInitializer:St(this.gammaInitializer),movingMeanInitializer:St(this.movingMeanInitializer),movingVarianceInitializer:St(this.movingVarianceInitializer),betaRegularizer:ut(this.betaRegularizer),gammaRegularizer:ut(this.gammaRegularizer),betaConstraint:Mt(this.betaConstraint),gammaConstraint:Mt(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}};fd.className="BatchNormalization";te.registerClass(fd);var dd=class extends Le{constructor(e){if(e==null&&(e={}),super(e),this.axis=e.axis==null?-1:e.axis,typeof this.axis=="number"){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else if(Array.isArray(this.axis)){for(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=ht(e.betaInitializer||"zeros"),this.gammaInitializer=ht(e.gammaInitializer||"ones"),this.betaRegularizer=vt(e.betaRegularizer),this.gammaRegularizer=vt(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=t)throw new Error(`Invalid axis: ${s}`);if(this.axis.length!==qn(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}=Yc(o,this.axis,a),u=Gn(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{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=Jr()),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]],Pr(r,o)})}var hd=class extends Le{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?Jr():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 At({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(()=>rK(Oe(e),this.padding,this.dataFormat))}getConfig(){let e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};hd.className="ZeroPadding2D";te.registerClass(hd);function Kg(r,e,t,o,n,s){return V(()=>{Rt(n),yw(s),Qr(o),t==null&&(t=[1,1]),o==null&&(o="valid"),n==null&&(n=Jr()),s==null&&(s="max"),r=Pf(r,n);let a,i=o==="same"?"same":"valid";return s==="max"?a=Aa(r,e,t,i):a=ka(r,e,t,i),n==="channelsFirst"&&(a=qe(a,[0,3,1,2])),a})}function P1(r,e,t,o,n,s){return V(()=>{Rt(n),yw(s),Qr(o),t==null&&(t=[1,1,1]),o==null&&(o="valid"),n==null&&(n=Jr()),s==null&&(s="max"),r=Hw(r,n);let a,i=o==="same"?"same":"valid";return s==="max"?a=Bm(r,e,t,i):a=Em(r,e,t,i),n==="channelsFirst"&&(a=qe(a,[0,4,1,2,3])),a})}var Jw=class extends Le{constructor(e){if(e.poolSize==null&&(e.poolSize=2),super(e),typeof e.poolSize=="number")this.poolSize=[e.poolSize];else if(Array.isArray(e.poolSize)&&e.poolSize.length===1&&typeof e.poolSize[0]=="number")this.poolSize=e.poolSize;else throw new B(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(jt(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)}`);jt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,Qr(this.padding),this.inputSpec=[new At({ndim:3})]}computeOutputShape(e){e=Qe(e);let t=uo(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=Ba(Oe(e),2);let o=this.poolingFunction(Oe(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return ko(o,[2])})}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}},gd=class extends Jw{constructor(e){super(e)}poolingFunction(e,t,o,n,s){return Rt(s),Qr(n),Kg(e,t,o,n,s,"max")}};gd.className="MaxPooling1D";te.registerClass(gd);var xd=class extends Jw{constructor(e){super(e)}poolingFunction(e,t,o,n,s){return Rt(s),Qr(n),Kg(e,t,o,n,s,"avg")}};xd.className="AveragePooling1D";te.registerClass(xd);var Qw=class extends Le{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==2)throw new 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];jt(this.poolSize,"poolSize"),jt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Rt(this.dataFormat),Qr(this.padding),this.inputSpec=[new At({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=uo(t,this.poolSize[0],this.padding,this.strides[0]),o=uo(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}},yd=class extends Qw{constructor(e){super(e)}poolingFunction(e,t,o,n,s){return Rt(s),Qr(n),Kg(e,t,o,n,s,"max")}};yd.className="MaxPooling2D";te.registerClass(yd);var bd=class extends Qw{constructor(e){super(e)}poolingFunction(e,t,o,n,s){return Rt(s),Qr(n),Kg(e,t,o,n,s,"avg")}};bd.className="AveragePooling2D";te.registerClass(bd);var ev=class extends Le{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==3)throw new 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];jt(this.poolSize,"poolSize"),jt(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Rt(this.dataFormat),Qr(this.padding),this.inputSpec=[new At({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=uo(t,this.poolSize[0],this.padding,this.strides[0]),o=uo(o,this.poolSize[1],this.padding,this.strides[1]),n=uo(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}},_d=class extends ev{constructor(e){super(e)}poolingFunction(e,t,o,n,s){return Rt(s),Qr(n),P1(e,t,o,n,s,"max")}};_d.className="MaxPooling3D";te.registerClass(_d);var wd=class extends ev{constructor(e){super(e)}poolingFunction(e,t,o,n,s){return Rt(s),Qr(n),P1(e,t,o,n,s,"avg")}};wd.className="AveragePooling3D";te.registerClass(wd);var tv=class extends Le{constructor(e){super(e);this.inputSpec=[new At({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Se}},vd=class extends tv{constructor(e){super(e||{})}call(e,t){return V(()=>{let o=Oe(e);return bt(o,1)})}};vd.className="GlobalAveragePooling1D";te.registerClass(vd);var kd=class extends tv{constructor(e){super(e||{})}call(e,t){return V(()=>{let o=Oe(e);return lr(o,1)})}};kd.className="GlobalMaxPooling1D";te.registerClass(kd);var rv=class extends Le{constructor(e){super(e);this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Rt(this.dataFormat),this.inputSpec=[new At({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Se}getConfig(){let e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},Cd=class extends rv{call(e,t){return V(()=>{let o=Oe(e);return this.dataFormat==="channelsLast"?bt(o,[1,2]):bt(o,[2,3])})}};Cd.className="GlobalAveragePooling2D";te.registerClass(Cd);var Id=class extends rv{call(e,t){return V(()=>{let o=Oe(e);return this.dataFormat==="channelsLast"?lr(o,[1,2]):lr(o,[2,3])})}};Id.className="GlobalMaxPooling2D";te.registerClass(Id);var ov=class extends Le{constructor(e){super(e);this.layer=e.layer}build(e){this.built=!0}get trainable(){return this.layer!=null?this.layer.trainable:!1}set trainable(e){this.layer!=null&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){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=eo(n,o);delete t.layer;let a={layer:s};return Object.assign(a,t),new e(a)}},Nd=class extends ov{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),Yw((a,i)=>[Oe(this.layer.call(a,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};Nd.className="TimeDistributed";te.registerClass(Nd);function oK(r){Vi(VT,"BidirectionalMergeMode",r)}var nK="concat",Sd=class extends ov{constructor(e){super(e);let t=e.layer.getConfig(),o={};o.className=e.layer.getClassName(),o.config=t,this.forwardLayer=eo(o),t.goBackwards=t.goBackwards!==!0;let n={};if(n.className=e.layer.getClassName(),n.config=t,this.backwardLayer=eo(n),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?nK:e.mergeMode,oK(this.mergeMode),e.weights)throw new Se("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()):hr(n)}apply(e,t){let o=t==null?null:t.initialState,n=t==null?null:t.constants;t==null&&(t={});let s=Xw(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 At({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 Se("Support for constants in Bidirectional layers is not implemented yet.");let l=a[0]instanceof Vr;for(let u of a)if(u instanceof Vr!==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=Yt(s,1));let i;return this.mergeMode==="concat"?i=pp([n,s]):this.mergeMode==="sum"?i=ee(n,s):this.mergeMode==="ave"?i=O(.5,ee(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){Ds(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),Ds(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=eo(t.layer);if(delete t.layer,t.numConstants!=null)throw new Se("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");let n=t;return n.layer=o,new e(n)}};Sd.className="Bidirectional";te.registerClass(Sd);function sK(r){return new Wi(r)}function iK(r){return new $f(r)}function aK(r){return new Ef(r)}function lK(r){return new Af(r)}function uK(r){return new Df(r)}function cK(r){return new Ff(r)}function pK(r){return new Rf(r)}function mK(r){return new nc(r)}function fK(r){return new _l(r)}function dK(r){return new Mf(r)}function hK(r){return new oc(r)}function gK(r){return new Lf(r)}function xK(r){return new zf(r)}function yK(r){return new Bf(r)}function bK(r){return new Vf(r)}function _K(r){return new Xf(r)}function wK(r){return new Hf(r)}function vK(r){return new Dp(r)}function kK(r){return new qf(r)}function CK(r){return new Kf(r)}function IK(r){return new Yf(r)}function NK(r){return new Zf(r)}function SK(r){return new Jf(r)}function TK(r){return new ed(r)}function EK(r){return new td(r)}function AK(r){return new od(r)}function DK(r){return new id(r)}function $K(r){return new nd(r)}function RK(r){return new sd(r)}function FK(r){return new rd(r)}function OK(r){return new ld(r)}function PK(r){return new fd(r)}function MK(r){return new dd(r)}function LK(r){return new hd(r)}function sv(r){return new xd(r)}function zK(r){return sv(r)}function BK(r){return sv(r)}function iv(r){return new bd(r)}function VK(r){return iv(r)}function WK(r){return iv(r)}function av(r){return new wd(r)}function GK(r){return av(r)}function UK(r){return av(r)}function jK(r){return new vd(r)}function qK(r){return new Cd(r)}function M1(r){return new kd(r)}function L1(r){return new Id(r)}function z1(r){return new gd(r)}function B1(r){return new yd(r)}function HK(r){return new _d(r)}function KK(r){return new Gf(r)}function XK(r){return new Ep(r)}function YK(r){return new Uf(r)}function ZK(r){return new vl(r)}function JK(r){return new Wf(r)}function QK(r){return new Tp(r)}function e6(r){return new jf(r)}function t6(r){return new Ap(r)}function r6(r){return new co(r)}function o6(r){return new Sp(r)}function n6(r){return new Sd(r)}function s6(r){return new Nd(r)}var i6=M1,a6=L1,l6=z1,u6=B1;function c6(r){return new ud(r)}function p6(r){return new cd(r)}function m6(r){return new pd(r)}function f6(r){return new Qf(r)}var lv={};et(lv,{MAPE:()=>C6,MSE:()=>S6,binaryAccuracy:()=>d6,binaryCrossentropy:()=>h6,categoricalAccuracy:()=>x6,categoricalCrossentropy:()=>y6,cosineProximity:()=>w6,mape:()=>I6,meanAbsoluteError:()=>v6,meanAbsolutePercentageError:()=>k6,meanSquaredError:()=>N6,mse:()=>T6,precision:()=>b6,recall:()=>_6,sparseCategoricalAccuracy:()=>g6});function d6(r,e){return Cf(r,e)}function h6(r,e){return Mg(r,e)}function g6(r,e){return Lg(r,e)}function x6(r,e){return If(r,e)}function y6(r,e){return Nf(r,e)}function b6(r,e){return Cw(r,e)}function _6(r,e){return a1(r,e)}function w6(r,e){return vf(r,e)}function v6(r,e){return vp(r,e)}function k6(r,e){return gl(r,e)}function C6(r,e){return gl(r,e)}function I6(r,e){return gl(r,e)}function N6(r,e){return Ui(r,e)}function S6(r,e){return Ui(r,e)}function T6(r,e){return Ui(r,e)}var uv={};et(uv,{modelFromJSON:()=>I1});var cv={};et(cv,{l1:()=>A6,l1l2:()=>E6,l2:()=>D6});function E6(r){return new tc(r)}function A6(r){return D1(r)}function D6(r){return $1(r)}var Xg=class extends hl{constructor(){super(...arguments);this.model=null}setModel(e){if(!(e instanceof Io))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function Yg(r,e){return re}var Zg=class extends Xg{constructor(e){super();if(e==null&&(e={}),e.restoreBestWeights)throw new Se("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=Yg:this.mode==="max"?this.monitorFunc=V1:this.monitor.indexOf("acc")!==-1?this.monitorFunc=V1:this.monitorFunc=Yg,this.monitorFunc===Yg&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Yg?Infinity:-Infinity}async onEpochEnd(e,t){await Gi(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 $6(r){return new Zg(r)}var W1={earlyStopping:$6};var Xn;(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"})(Xn||(Xn={}));var G1;(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={}))})(G1||(G1={}));var pv={};function U1(r,e){let t={tfOpName:r,category:"custom",inputs:[],attrs:[],customExecutor:e};pv[r]=t}function Jg(r){return pv[r]}function j1(r){delete pv[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 gr(e.inputNames[s.inputIndexStart],t,o,n);if(s.type==="tensors")return e.inputNames.slice(i,l).map(m=>gr(m,t,o,n));let u=gr(e.inputNames.slice(i)[0],t,o,n),c=u.dataSync();return s.type==="number"?c[0]:x.toNestedArray(u.shape,c)}let a=e.attrParams[r];return a&&a.value}function gr(r,e,t,o){let[n,s]=to(r);if(o!=null){let i=o.getHashTableHandleByName(n);if(i!=null)return i}let a=t.currentContextIds.find(i=>!!e[Qg(n,i)]);return a!==void 0?e[Qg(n,a)][s]:void 0}function q1(r,e,t){return e[Qg(r,t.currentContextId)]}function Ps(r,e){let[t,o]=to(r);return[Qg(t,e&&e.currentContextId),o]}function Qg(r,e){return e?`${r}-${e}`:r}function to(r){let e=r.split(":");return e.length===1?[r,0]:[e[0],Number(e[e.length-1])]}function Td(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 Ms(r){return r.kept?r:Po(r)}var mv={};et(mv,{json:()=>R6});var R6=[{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 fv={};et(fv,{json:()=>F6});var F6=[{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 dv={};et(dv,{json:()=>O6});var O6=[{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 hv={};et(hv,{json:()=>P6});var P6=[{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 gv={};et(gv,{json:()=>M6});var M6=[{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 xv={};et(xv,{json:()=>L6});var L6=[{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 yv={};et(yv,{json:()=>z6});var z6=[{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 bv={};et(bv,{json:()=>B6});var B6=[{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 _v={};et(_v,{json:()=>V6});var V6=[{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 wv={};et(wv,{json:()=>W6});var W6=[{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 vv={};et(vv,{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 kv={};et(kv,{json:()=>U6});var U6=[{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 Cv={};et(Cv,{json:()=>j6});var j6=[{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 Iv={};et(Iv,{json:()=>q6});var q6=[{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 Nv={};et(Nv,{json:()=>H6});var H6=[{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 Sv={};et(Sv,{json:()=>K6});var K6=[{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 Tv={};et(Tv,{json:()=>X6});var X6=[{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 ex=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let e=[mv,fv,dv,hv,gv,xv,yv,vv,wv,bv,kv,Cv,Iv,Nv,Sv,Tv,_v],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(y=>{let[b]=Ps(y);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]=Ps(h),y=i[g];y!=null&&(y.signatureKey=p[h],u.push(y))}),Object.keys(c).length>0?Object.keys(c).forEach(h=>{let[g]=Ps(h),y=i[g];y&&(y.signatureKey=c[h],l.push(y))}):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=Jg(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=tx(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=tx(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"string[]":i=lx(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=lx(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"number":i=ox(e.attr,s.tfName,s.defaultValue||0),i===void 0&&!!s.tfDeprecatedName&&(i=ox(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"number[]":i=ax(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=ax(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"bool":i=rx(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=rx(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"bool[]":i=cx(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=cx(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"shape":i=ix(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=ix(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"shape[]":i=ux(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=ux(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"dtype":i=nx(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=nx(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"func":i=H1(e.attr,s.tfName,s.defaultValue),i===void 0&&!!s.tfDeprecatedName&&(i=H1(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]=Ps(p.name),f={name:m,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:Ev(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]=Ps(f);m.inputs.push(s[d]),s[d].children.push(m)})});let u=e.ret;e.signature.outputArg.forEach(p=>{let[m,f]=Ps(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 Y6(r){let e=W().global;if(typeof e.atob!="undefined")return e.atob(r);if(typeof Buffer!="undefined")return new Buffer(r,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}function K1(r,e){let t=Array.isArray(r)?String.fromCharCode.apply(null,r):Y6(r);return e?t:t.toLowerCase()}function tx(r,e,t,o=!1){let n=r[e];return n!=null?K1(n.s,o):t}function rx(r,e,t){let o=r[e];return o?o.b:t}function ox(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 Ev(r){switch(typeof r=="string"&&(r=Xn[r]),r){case Xn.DT_FLOAT:return"float32";case Xn.DT_INT32:case Xn.DT_INT64:case Xn.DT_INT8:case Xn.DT_UINT8:return"int32";case Xn.DT_BOOL:return"bool";case Xn.DT_DOUBLE:return"float32";case Xn.DT_STRING:return"string";default:return null}}function H1(r,e,t){let o=r[e];return o&&o.func?o.func.name:t}function nx(r,e,t){let o=r[e];return o&&o.type?Ev(o.type):t}function sx(r,e,t){let o=r[e];return o&&o.list&&o.list.type?o.list.type.map(n=>Ev(n)):t}function X1(r){if(!r.unknownRank)return r.dim!=null?r.dim.map(e=>typeof e.size=="number"?e.size:parseInt(e.size,10)):[]}function ix(r,e,t){let o=r[e];return o&&o.shape?X1(o.shape):t}function ax(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 lx(r,e,t,o=!1){let n=r[e];return n&&n.list&&n.list.s?n.list.s.map(s=>K1(s,o)):t}function ux(r,e,t){let o=r[e];return o&&o.list&&o.list.shape?o.list.shape.map(n=>X1(n)):t}function cx(r,e,t){let o=r[e];return o&&o.list&&o.list.b?o.list.b:t}var Av=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 gr(e,this.tensorMap,this.context)}getAttr(e,t){let o=this.node.rawAttrs[e];if(o.tensor!=null)return gr(e,this.tensorMap,this.context);if(o.i!=null||o.f!=null)return ox(this.node.rawAttrs,e,t);if(o.s!=null)return tx(this.node.rawAttrs,e,t);if(o.b!=null)return rx(this.node.rawAttrs,e,t);if(o.shape!=null)return ix(this.node.rawAttrs,e,t);if(o.type!=null)return nx(this.node.rawAttrs,e,t);if(o.list!=null){if(o.list.i!=null||o.list.f!=null)return ax(this.node.rawAttrs,e,t);if(o.list.s!=null)return lx(this.node.rawAttrs,e,t);if(o.list.shape!=null)return ux(this.node.rawAttrs,e,t);if(o.list.b!=null)return cx(this.node.rawAttrs,e,t);if(o.list.type!=null)return sx(this.node.rawAttrs,e,t)}return t}};var Y1=(r,e,t)=>{switch(r.op){case"BiasAdd":case"AddV2":case"Add":return[ee(C("a",r,e,t),C("b",r,e,t))];case"AddN":return[Qb(C("tensors",r,e,t))];case"FloorMod":case"Mod":return[Fu(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[fe(C("a",r,e,t),C("b",r,e,t))];case"DivNoNan":return[Fm(C("a",r,e,t),C("b",r,e,t))];case"FloorDiv":return[vu(C("a",r,e,t),C("b",r,e,t))];case"Sub":return[pe(C("a",r,e,t),C("b",r,e,t))];case"Minimum":return[Bo(C("a",r,e,t),C("b",r,e,t))];case"Maximum":return[Ir(C("a",r,e,t),C("b",r,e,t))];case"Pow":return[_r(C("a",r,e,t),C("b",r,e,t))];case"SquaredDifference":return[Pa(C("a",r,e,t),C("b",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var Z1=(r,e,t)=>{switch(r.op){case"Abs":case"ComplexAbs":return[Et(C("x",r,e,t))];case"Acos":return[wm(C("x",r,e,t))];case"Acosh":return[vm(C("x",r,e,t))];case"Asin":return[Cm(C("x",r,e,t))];case"Asinh":return[Im(C("x",r,e,t))];case"Atan":return[Nm(C("x",r,e,t))];case"Atan2":return[Sm(C("x",r,e,t),C("y",r,e,t))];case"Atanh":return[Tm(C("x",r,e,t))];case"Ceil":return[Am(C("x",r,e,t))];case"Complex":return[wo(C("real",r,e,t),C("imag",r,e,t))];case"Cos":return[Ia(C("x",r,e,t))];case"Cosh":return[Tu(C("x",r,e,t))];case"Elu":return[Is(C("x",r,e,t))];case"Erf":return[Om(C("x",r,e,t))];case"Exp":return[Qt(C("x",r,e,t))];case"Expm1":return[Pm(C("x",r,e,t))];case"Floor":return[Ns(C("x",r,e,t))];case"Log":return[ar(C("x",r,e,t))];case"Log1p":return[Du(C("x",r,e,t))];case"Imag":return[Au(C("x",r,e,t))];case"Neg":return[He(C("x",r,e,t))];case"Reciprocal":return[Gm(C("x",r,e,t))];case"Real":return[ul(C("x",r,e,t))];case"Relu":return[Sr(C("x",r,e,t))];case"Round":return[Um(C("x",r,e,t))];case"Selu":return[zu(C("x",r,e,t))];case"Sigmoid":return[Kr(C("x",r,e,t))];case"Sin":return[Bu(C("x",r,e,t))];case"Sign":return[qm(C("x",r,e,t))];case"Sinh":return[Vu(C("x",r,e,t))];case"Softplus":return[Ss(C("x",r,e,t))];case"Sqrt":return[_t(C("x",r,e,t))];case"Square":return[Me(C("x",r,e,t))];case"Tanh":return[Pi(C("x",r,e,t))];case"Tan":return[Ym(C("x",r,e,t))];case"ClipByValue":return[ir(C("x",r,e,t),C("clipValueMin",r,e,t),C("clipValueMax",r,e,t))];case"Relu6":return[Mu(C("x",r,e,t))];case"Rsqrt":return[Lu(gr(r.inputNames[0],e,t))];case"Prod":return[Ou(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[$a(C("x",r,e,t),C("alpha",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};function No(r,e,t=""){x.assert(Z6(r,e),()=>t+` Shapes ${r} and ${e} must match`)}function Z6(r,e){if(r.length!==e.length)return!1;for(let t=0;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),No(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,Dt(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.maxSize)throw new Error(`Max index must be < array size (${o} vs. ${this.maxSize})`);this.writeMany(e,cr(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=z(t,[1,o,s]);for(let l=0;l{if(o!==s.dtype)throw new Error(`Invalid data types; op elements ${o}, but list elements ${s.dtype}`);No(t,s.shape,"TensorList shape mismatch: "),Dt(s)}),this.idTensor=ce(0),this.maxNumElements=n,Dt(this.idTensor)}get id(){return this.idTensor.id}copy(){return new sc([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.id))&&t.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,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 No(e,this.elementShape,"TensorList shape mismatch: "),V(()=>{let n=this.tensors.map(s=>z(s,e));return Wt(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 No(o.shape,e,"TensorList shape mismatch: "),z(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(No(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Dt(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 No(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.`);No(this.elementShape,t.shape,"TensorList shape mismatch: "),Dt(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 No(this.elementShape,o,"TensorList shape mismatch: "),e=e.slice(0,this.size()),e.length===0?Fr([],[0].concat(this.elementShape)):V(()=>{let n=e.map(s=>z(this.tensors[s],o));return Wt(n,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);return No(this.elementShape,t,"TensorList shape mismatch: "),this.size()===0?Fr([],[0].concat(this.elementShape)):V(()=>{let o=this.tensors.map(n=>z(n,t));return Je(o,0)})}};function J1(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);No(n,e,"TensorList shape mismatch: ");let s=cr(r);return new sc(s,e,o)}function Q1(r,e,t){return new sc([],r,e,t)}function eE(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 sc([],t,r.dtype,o),a=cr(r,0);return e.forEach((i,l)=>{s.setItem(i,a[l])}),s}function tE(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=z(r,[1,o,s]);for(let u=0;u{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[Ms(o)]}case"Switch":{let o=C("pred",r,e,t),n=C("data",r,e,t);return n.kept||(n=Ms(n)),(await o.data())[0]?[void 0,n]:[n,void 0]}case"Merge":{let o=r.inputNames.find(n=>gr(n,e,t)!==void 0);if(o){let n=gr(o,e,t);return[Ms(n)]}return}case"Enter":{let o=C("frameName",r,e,t),n=C("tensor",r,e,t);return t.enterFrame(o),[Ms(n)]}case"Exit":{let o=C("tensor",r,e,t);return t.exitFrame(),[Ms(o)]}case"NextIteration":{let o=C("tensor",r,e,t);return t.nextIteration(),[Ms(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 Dv(u,n,o,s,l,a,i);return t.addTensorArray(c),[c.idTensor,ce(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[ce(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=eE(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=Q1(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=J1(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=tE(o,s,n);return t.addTensorList(a),[a.idTensor]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};function oE(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=Td(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 nE=(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[Nu(C("x",r,e,t),C("filter",r,e,t),o,n,s,a)]}case"Conv2D":{let o=C("strides",r,e,t),n=Td(r,e,t),s=C("dataFormat",r,e,t).toUpperCase(),a=C("dilations",r,e,t);return[Xr(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}=oE(r,e,t);return[Vn.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}=oE(r,e,t);return[Vn.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=Td(r,e,t);return[Su(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=Td(r,e,t),s=C("dilations",r,e,t),a=C("dataFormat",r,e,t).toUpperCase();return[Lo(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[Dm(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[ka(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[Aa(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}=v_(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[Em(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[Bm(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[Rm(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 sE=(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[g_(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[k_(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[Nr(C("shape",r,e,t),C("dtype",r,e,t))];case"OnesLike":return[rr(C("x",r,e,t))];case"RandomUniform":return[Ts(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[Jc(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[Gu(o,n,s,C("dtype",r,e,t),a)]}case"Zeros":return[pt(C("shape",r,e,t),C("dtype",r,e,t))];case"ZerosLike":return[Ne(C("x",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};function $v(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 iE=async(r,e,t)=>{switch(r.op){case"NonMaxSuppressionV5":{let{boxes:o,scores:n,maxOutputSize:s,iouThreshold:a,scoreThreshold:i,softNmsSigma:l}=$v(r,e,t),u=await As.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}=$v(r,e,t),l=C("padToMaxOutputSize",r,e,t),u=await As.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}=$v(r,e,t);return[await As.nonMaxSuppressionAsync(o,n,s,a,i)]}case"Where":{let o=ne(C("condition",r,e,t),"bool"),n=[await Qm(o)];return o.dispose(),n}case"ListDiff":return R_(C("x",r,e,t),C("y",r,e,t));default:throw TypeError(`Node type ${r.op} is not implemented`)}};var aE=(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=Zm(o,n,s);return[a.values,a.indices]}case"Unique":{let o=C("x",r,e,t),n=ep(o);return[n.values,n.indices]}case"UniqueV2":{let o=C("x",r,e,t),n=C("axis",r,e,t),s=ep(o,n);return[s.values,s.indices]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var lE=(r,e,t)=>{switch(r.op){case"Const":return e[r.name];case"PlaceholderWithDefault":let o=C("default",r,e,t);return[gr(r.name,e,t)||o];case"Placeholder":return[gr(r.name,e,t)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let u=C("x",r,e,t);return[Ms(u)]}case"IdentityN":return C("x",r,e,t).map(u=>Ms(u));case"Snapshot":let n=C("x",r,e,t);return[Ms(n)];case"Shape":return[Gt(C("x",r,e,t).shape,"int32")];case"ShapeN":return C("x",r,e,t).map(u=>Gt(u.shape));case"Size":return[ce(C("x",r,e,t).size,"int32")];case"Rank":return[ce(C("x",r,e,t).rank,"int32")];case"NoOp":return[ce(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;ue.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=cr(t),s=o.length,a=n.length;x.assert(s===a,()=>`The number of elements doesn't match, keys has ${s} elements, the values has ${a} elements.`);for(let i=0;i{let n=[];for(let s=0;s{switch(r.op){case"HashTable":case"HashTableV2":{let n=C("keyDType",r,e,t),s=C("valueDType",r,e,t),a=new Rv(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 cE=(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[As.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[As.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[As.cropAndResize(o,n,s,a,i,l)]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var pE=(r,e,t)=>{switch(r.op){case"Equal":return[Yr(C("a",r,e,t),C("b",r,e,t))];case"NotEqual":return[vo(C("a",r,e,t),C("b",r,e,t))];case"Greater":return[Xt(C("a",r,e,t),C("b",r,e,t))];case"GreaterEqual":return[Or(C("a",r,e,t),C("b",r,e,t))];case"Less":return[Ta(C("a",r,e,t),C("b",r,e,t))];case"LessEqual":return[no(C("a",r,e,t),C("b",r,e,t))];case"LogicalAnd":return[dr(C("a",r,e,t),C("b",r,e,t))];case"LogicalNot":return[Ea(C("a",r,e,t))];case"LogicalOr":return[Ru(C("a",r,e,t),C("b",r,e,t))];case"Select":case"SelectV2":return[$t(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 mE=(r,e,t)=>{switch(r.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[je(C("a",r,e,t),C("b",r,e,t),C("transposeA",r,e,t),C("transposeB",r,e,t))];case"Transpose":return[qe(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[Vn.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 fE=(r,e,t)=>{switch(r.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[Ln(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[Ln(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[Mm(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[Ra(C("x",r,e,t))];case"LogSoftmax":return[$u(C("x",r,e,t))];case"SparseToDense":return[ef(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 dE=(r,e,t)=>{switch(r.op){case"Max":{let a=C("axis",r,e,t),i=C("keepDims",r,e,t);return[lr(C("x",r,e,t),a,i)]}case"Mean":{let a=C("axis",r,e,t),i=C("keepDims",r,e,t);return[bt(C("x",r,e,t),a,i)]}case"Min":{let a=C("axis",r,e,t),i=C("keepDims",r,e,t);return[Mi(C("x",r,e,t),a,i)]}case"Sum":{let a=C("axis",r,e,t),i=C("keepDims",r,e,t);return[be(C("x",r,e,t),a,i)]}case"All":{let a=C("axis",r,e,t),i=C("keepDims",r,e,t);return[ku(C("x",r,e,t),a,i)]}case"Any":{let a=C("axis",r,e,t),i=C("keepDims",r,e,t);return[il(C("x",r,e,t),a,i)]}case"ArgMax":{let a=C("axis",r,e,t);return[al(C("x",r,e,t),a)]}case"ArgMin":{let a=C("axis",r,e,t);return[km(C("x",r,e,t),a)]}case"Prod":{let a=C("axis",r,e,t),i=C("keepDims",r,e,t);return[Ou(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[Eu(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[i_(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[p_(a,i,l,u)]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var hE=(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[zn(o,ne(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[zn(s,ne(a,"int32"),o,n)]}case"Reverse":{let o=C("dims",r,e,t),n=[];for(let a=0;a{let o=C("axis",r,e,t),n=C("tensors",r,e,t),s=n[0].shape,a=ko(n[0]).shape,i=n.map(l=>{let u=x.arraysEqual(l.shape,s);if(!u&&!x.arraysEqual(ko(l).shape,a))throw new Error("the input tensors shape does not match");return u?l:z(l,s)});return[Wt(i,o)]});case"Unpack":{let o=C("axis",r,e,t),n=C("tensor",r,e,t);return cr(n,o)}case"Tile":{let o=C("reps",r,e,t);return[zo(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 ur(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[Z_(o,n,s)]}case"GatherNd":{let o=C("x",r,e,t),n=C("indices",r,e,t);return[J_(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[ef(o,s,n,s.dtype===a.dtype?a:ne(a,s.dtype))]}default:throw TypeError(`Node type ${r.op} is not implemented`)}};var gE=(r,e,t)=>{switch(r.op){case"FFT":return[Fa(C("x",r,e,t))];case"IFFT":return[Li(C("x",r,e,t))];case"RFFT":return[Oa(C("x",r,e,t))];case"IRFFT":return[Wu(C("x",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};var xE=(r,e,t)=>{switch(r.op){case"Cast":return[ne(C("x",r,e,t),C("dtype",r,e,t))];case"ExpandDims":{let o=C("axis",r,e,t);return[br(C("x",r,e,t),o)]}case"Squeeze":{let o=C("axis",r,e,t);return[ko(C("x",r,e,t),o)]}case"Reshape":return[z(C("x",r,e,t),C("shape",r,e,t))];case"MirrorPad":return[Vm(C("x",r,e,t),C("padding",r,e,t),C("mode",r,e,t))];case"PadV2":case"Pad":return[Pr(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[Da(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[$m(C("x",r,e,t),o,n)]}case"BroadcastTo":return[ll(C("x",r,e,t),C("shape",r,e,t))];default:throw TypeError(`Node type ${r.op} is not implemented`)}};function Fv(r,e,t,o){let n=((s,a,i)=>{switch(s.category){case"arithmetic":return V(()=>Y1(s,a,i));case"basic_math":return V(()=>Z1(s,a,i));case"control":return rE(s,a,i);case"convolution":return V(()=>nE(s,a,i));case"creation":return V(()=>sE(s,a,i));case"dynamic":return iE(s,a,i);case"evaluation":return V(()=>aE(s,a,i));case"image":return V(()=>cE(s,a,i));case"graph":return V(()=>lE(s,a,i));case"logical":return V(()=>pE(s,a,i));case"matrices":return V(()=>mE(s,a,i));case"normalization":return V(()=>fE(s,a,i));case"reduction":return V(()=>dE(s,a,i));case"slice_join":return V(()=>hE(s,a,i));case"spectral":return V(()=>gE(s,a,i));case"transformation":return V(()=>xE(s,a,i));case"hash_table":return uE(s,a,i,o);case"custom":let l=Jg(s.op);if(l&&l.customExecutor)return l.customExecutor(new Av(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 x.isPromise(n)?n.then(s=>[].concat(s)):[].concat(n)}var px=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;tt.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 Pv(r,e,t,o){let n=new Set,s=[],a=null,i=null,l=new Set,u=Object.keys(r).map(m=>to(m)[0]),c=[];o!=null&&(c=o.map(m=>to(m.name)[0]));let p=[...e];for(;p.length>0;){let m=p.pop();if((Ov(m)||J6(m)||Q6(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 yE(r,e,t){let{usedNodes:o,inputs:n}=t,s=[],a=Object.keys(n).map(c=>to(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 e5=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],t5=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],r5=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2"];function Ov(r){return e5.indexOf(r.op)>=0}function J6(r){return t5.indexOf(r.op)>=0}function Q6(r){return r5.indexOf(r.op)>=0}var $p=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 $p(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=Pv(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 yE(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[to(p)[0]]),s=t.map(p=>to(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 px(this.weightMap,u,c,this.functionExecutorMap),m=Object.assign({},this.weightMap);Object.keys(e).forEach(h=>{let[g,y]=to(h),b=[];b[y]=e[h],m[g]=b});let f=this.getFrozenTensorIds(m),d={};for(let h=0;hgr(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=q1(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 px(this.weightMap,n,s,this.functionExecutorMap),i=await this.executeWithControlFlow(e,a,t,o),l=t.map(m=>gr(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[to(_)[0]]),i=o.map(_=>to(_)[0]),l=i.map(_=>this.graph.nodes[_]);l.length===0&&(l=this._outputs);let{usedNodes:u,missingInputs:c,dynamicNode:p,syncInputs:m}=Pv(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,k]=to(_),$=[];$[k]=e[_],d[w]=$});let h={},g=this.getFrozenTensorIds(d),y={};for(;f.length>0;){let _=this.processStack(a,f,t,d,y,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(_=>!Ov(_)&&!gr(_.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]=Ps(p.node.name,o)),n[p.node.name]==null){let f=Fv(p.node,n,o,this._resourceManager);m||([m]=Ps(p.node.name,o));let d=o.currentContext;x.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]=Ps(i.name,o);s[l]||!a.has(i.name)||(i.op==="Merge"?i.inputNames.some(u=>!!gr(u,n,o))&&(s[l]=!0,t.push({contexts:o.currentContext,node:i})):i.inputNames.every(u=>!!gr(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]=to(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);x.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&&x.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]=to(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]=to(t);if(!this.graph.nodes[o])throw new Error(`The output '${t}' is not found in the graph`)})}};var Mv=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 o5="?tfjs-format=file",n5="model.json",mx=class{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={}),this.resourceManager=new Mv}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=Cr.browserHTTPRequest(e,this.loadOptions);else{let t=Cr.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(Cr.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=Cr.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new $p(ex.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=ex.Instance.transformGraph(e.modelInitializer);this.initializer=new $p(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=Cr.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 R)&&!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 bE(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}${n5}${o5}`);let t=new mx(r,e);return await t.load(),t}var fx="2.8.3";var jv={};et(jv,{CSVDataset:()=>Rd,Dataset:()=>qi,FileDataSource:()=>Ld,TextLineDataset:()=>Dd,URLDataSource:()=>zd,array:()=>VE,csv:()=>ZE,func:()=>JE,generator:()=>QE,microphone:()=>tA,version_data:()=>_x,webcam:()=>eA,zip:()=>WE});var BE=Ec(Wm());var IE=Ec(Wm());function _E(r,e){return dx(r,e)}function dx(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(Cl(r)){let s=Array.isArray(r)?[]:{};o.add(r);for(let a in r){let i=r[a],l=dx(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 vE(r,e=Lv){return wE(r,e)}function wE(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(Cl(o)){let s=Array.isArray(o)?[]:{};t.add(o);for(let a in o){let i=r.map(u=>u[a]),l=wE(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 Lv(r){return r===null?null:Cl(r[0])?{value:null,recurse:!0}:{value:r,recurse:!1}}async function hx(r,e){let t=new Map;dx(r,e,t);for(let n of Array.from(t.keys())){let s=t.get(n);if(x.isPromise(s)){let a=await s;t.set(n,a)}}return dx(r,e,t)}function Cl(r){return r!=null&&!ArrayBuffer.isView(r)&&(Array.isArray(r)||typeof r=="object"&&!(r instanceof R))}function kE(r){return r==null||s5(r)||Array.isArray(r)||typeof r=="object"&&r instanceof R||x.isTypedArray(r)}function s5(r){return r===null||typeof r!="object"&&typeof r!="function"}function CE(r){return _E(r,i5)}function i5(r){return r instanceof R?{value:r.clone(),recurse:!1}:Cl(r)?{value:null,recurse:!0}:{value:r,recurse:!1}}var Ed=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 Rp=class extends Ed{constructor(){super(Rp.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;nt===!0)}rowMajorBatch(e,t=!0){return new FE(this,e,t)}columnMajorBatch(e,t=!0,o=Lv){return this.rowMajorBatch(e,t).map(s=>vE(s,o))}concatenate(e,t){return new Bv(zv([this,e]),t)}take(e){return e<0||e==null?this:new RE(this,e)}skip(e){return e<0||e==null?this:new $E(this,e)}prefetch(e){return new Wv(this,e)}shuffle(e,t){return new zE(this,e,t)}serial(){return new DE(this)}},NE=class extends Zt{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:CE(e),done:!1}}},SE=class extends Zt{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}}},DE=class extends Zt{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()}},$E=class extends Zt{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++ Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}},FE=class extends Zt{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.length0?{value:e,done:!1}:{value:null,done:!0};e.push(t.value)}return{value:e,done:!1}}},OE=class extends Zt{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;Ae(e.value)}}},PE=class extends Zt{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=Mn.getTensorsInContainer(e.value),o=this.transform(e.value),n=Mn.getTensorsInContainer(o);for(let s of t)Mn.isTensorInList(s,n)||s.dispose();return{value:o,done:!1}}},ME=class extends Zt{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}}}},Vv=class extends Zt{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=Mn.getTensorsInContainer(e.value),o=await this.transform(e.value),n=Mn.getTensorsInContainer(o);for(let s of t)Mn.isTensorInList(s,n)||s.dispose();return{value:o,done:!1}}},Fp=class extends Zt{constructor(){super();this.outputQueue=new Rp,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}}},LE=class extends Fp{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=Mn.getTensorsInContainer(e.value),o=this.transform(e.value),n=Mn.getTensorsInContainer(o);this.outputQueue.pushAll(o);for(let s of t)Mn.isTensorInList(s,n)||s.dispose();return!0}},Bv=class extends Zt{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}},Ga;(function(r){r[r.FAIL=0]="FAIL",r[r.SHORTEST=1]="SHORTEST",r[r.LONGEST=2]="LONGEST"})(Ga||(Ga={}));var EE=class extends Zt{constructor(e,t=Ga.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 Zt?{value:a.next().then(l=>(t++,l.done&&o++,l.value)),recurse:!1}:{value:null,recurse:!0}}let s=await hx(this.iterators,n);if(t===o)return{value:null,done:!0};if(o>0)switch(this.mismatchMode){case Ga.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case Ga.SHORTEST:return{value:null,done:!0};case Ga.LONGEST:default:}return this.count++,{value:s,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}},Wv=class extends Zt{constructor(e,t){super();this.upstream=e,this.bufferSize=t,this.buffer=new Ed(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()}},zE=class extends Wv{constructor(e,t,o){super(e,t);this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=IE.alea(o||x.now().toString()),this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}randomInt(e){return Math.floor(this.random()*e)}chooseIndex(){return this.randomInt(this.buffer.length())}async serialNext(){for(this.upstreamExhausted||this.refill();!this.buffer.isEmpty();){let e=this.chooseIndex(),t=await this.buffer.shuffleExcise(e);if(t.done)this.upstreamExhausted=!0;else return this.refill(),t}return{value:null,done:!0}}};var qi=class{constructor(){this.size=null}batch(e,t=!0){let o=this;x.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),po(async()=>(await o.iterator()).columnMajorBatch(e,t,a5),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,po(async()=>(await t.iterator()).concatenate(await e.iterator()),o)}filter(e){let t=this,o;return this.size===Infinity?o=Infinity:o=null,po(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 po(async()=>(await t.iterator()).map(o=>V(()=>e(o))),this.size)}mapAsync(e){let t=this;return po(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 po(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,po(async()=>{let n=Ad(async()=>({value:await t.iterator(),done:!1}));return TE(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(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=BE.alea(t||x.now().toString());return po(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,po(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 po(r,e=null){return new class extends qi{constructor(){super(...arguments);this.size=e}async iterator(){return r()}}}function VE(r){return po(async()=>zv(r),r.length)}function WE(r){if(!Cl(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{let t=await hx(r,o=>{if(o instanceof qi)return{value:o.iterator(),recurse:!1};if(Cl(o))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return AE(t,Ga.SHORTEST)},e)}function a5(r){if(r===null)return null;let e=r[0];return kE(e)?{value:l5(r),recurse:!1}:{value:null,recurse:!0}}function l5(r){if(r.length===0)throw new Error("Can't make a batch of zero elements.");return r[0]instanceof R?Wt(r):Fr(r)}var Dd=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 gx='"',$d=Symbol("out"),GE=Symbol("field"),xx=Symbol("quote"),Gv=Symbol("quoteafterquote"),UE=Symbol("quoteinquote"),Rd=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 Dd(e),t||(t={}),this.hasHeader=t.hasHeader!==!1,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(x.assert(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){let e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&x.assert(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);let t=this.fullColumnNames.reduce((n,s)=>(n[s]=n[s]+1||1,n),{}),o=Object.keys(t).filter(n=>t[n]>1);if(x.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;s14||!Number.isInteger(t))throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);if(this.numFrames=e.numFramesPerSpectrogram||43,this.sampleRateHz=e.sampleRateHz,this.columnTruncateLength=e.columnTruncateLength||this.fftSize,this.audioTrackConstraints=e.audioTrackConstraints,this.smoothingTimeConstant=e.smoothingTimeConstant||0,this.includeSpectrogram=e.includeSpectrogram!==!1,this.includeWaveform=e.includeWaveform===!0,!this.includeSpectrogram&&!this.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.")}summary(){return"microphone"}static async create(e={}){if(W().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");let t=new Fd(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(x.sizeFromShape(t));return o.set(e,o.length-e.length),Fr(o,t)}};var Od=class extends Zt{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=Gt([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=zi([a,s,l,i],[1,4])}else this.cropBox=zi([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(W().get("IS_NODE"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!t.resizeWidth||!t.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=t.resizeWidth,e.height=t.resizeHeight}let o=new Od(e,t);return await o.start(),o}async start(){this.webcamConfig.facingMode&&x.assert(this.webcamConfig.facingMode==="user"||this.webcamConfig.facingMode==="environment",()=>`Invalid webcam facing mode: ${this.webcamConfig.facingMode}. Please provide 'user' or 'environment'`);try{this.stream=await navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})}catch(e){throw e.message=`Error thrown while initializing video stream: ${e.message}`,e}if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(e){console.log(e),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,new Promise(e=>{this.webcamVideoElement.onloadedmetadata=()=>{e()}})}async next(){if(this.isClosed)return{value:null,done:!0};let e;try{e=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=e.toFloat().expandDims(0),o;o=As.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let n=o.shape;return o.reshape(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 Pd=class{};var yx=class extends Zt{split(e){return new jE(this,e)}},jE=class extends yx{constructor(e,t){super();this.upstream=e,this.impl=new qE(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},qE=class extends Fp{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 Uv=class extends Zt{decodeUTF8(){return new KE(this)}},KE=class extends yx{constructor(e){super();this.upstream=e,this.impl=new XE(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},XE=class extends Fp{constructor(e){super();if(this.upstream=e,W().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:t}=HE();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 W().get("IS_BROWSER")?o=this.decoder.decode(t,{stream:!0}):o=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(o),!0}};var Md=class extends Uv{constructor(e,t={}){super();this.file=e,this.options=t,x.assert(e instanceof Uint8Array||(W().get("IS_BROWSER")?e instanceof File||e instanceof Blob:!1),()=>"FileChunkIterator only supports File, Blob and Uint8Array right now."),this.offset=t.offset||0,this.chunkSize=t.chunkSize||1024*1024}summary(){return`FileChunks ${this.file}`}async next(){return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?{value:null,done:!0}:{value:await new Promise((t,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 YE(r,e={}){let t,o;typeof r=="string"?t=r:(t=r.url,o=u5(r));let n=await x.fetch(t,o);if(n.ok){let s=new Uint8Array(await n.arrayBuffer());return new Md(s,e)}else throw new Error(n.statusText)}var u5=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 bx(r){return typeof r=="string"&&r.substr(0,7)==="file://"}var Ld=class extends Pd{constructor(e,t={}){super();this.input=e,this.options=t}async iterator(){if(bx(this.input)&&W().get("IS_NODE")){let e=require("fs");this.input=e.readFileSync(this.input.substr(7))}return new Md(this.input,this.options)}};var zd=class extends Pd{constructor(e,t={}){super();this.url=e,this.fileOptions=t}async iterator(){return bx(this.url)?new Ld(this.url,this.fileOptions).iterator():YE(this.url,this.fileOptions)}};function ZE(r,e={}){return new Rd(new zd(r),e)}function JE(r){let e=Ad(r);return po(async()=>e)}function QE(r){return po(async()=>{let e=await r();return Ad(()=>e.next())})}async function eA(r,e){return Od.create(r,e)}async function tA(r){return Fd.create(r)}var _x="2.8.3";function re(r,e){Array.isArray(r)||(r=[r]),r.forEach(t=>{t!=null&&x.assert(t.dtype!=="complex64",()=>`${e} does not support complex64 tensors in the CPU backend.`)})}var c5=Er.whereImpl,qv=class extends Ws{constructor(){super();this.blockSize=48,this.firstUse=!0,this.data=new Ja(this,Cs())}write(e,t,o){this.firstUse&&(this.firstUse=!1,W().get("IS_NODE")&&S.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&&x.isString(o[0])){let s=o.map(a=>x.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 S.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=>x.decodeString(n))}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return Ie(e.shape,e.dtype,o)}makeOutput(e,t,o){let n=this.write(e,t,o);return Cs().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=x.now();return e(),{kernelMs:x.now()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){re([e],"where");let t=this.readSync(e.dataId);return c5(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}};var rk={};et(rk,{addImpl:()=>lA,bincountImpl:()=>Bd,bincountReduceImpl:()=>Hv,ceilImpl:()=>cA,concatImpl:()=>Vd,expImpl:()=>mA,expm1Impl:()=>dA,floorImpl:()=>gA,gatherV2Impl:()=>Xv,greaterImpl:()=>yA,lessImpl:()=>_A,linSpaceImpl:()=>Yv,logImpl:()=>vA,maxImpl:()=>Zv,maximumImpl:()=>CA,minimumImpl:()=>NA,multiplyImpl:()=>wx,negImpl:()=>EA,notEqualImpl:()=>DA,prodImpl:()=>FA,rangeImpl:()=>Ud,rsqrtImpl:()=>PA,simpleAbsImpl:()=>rA,sliceImpl:()=>jd,squaredDifferenceImpl:()=>zA,stridedSliceImpl:()=>Jv,subImpl:()=>VA,tileImpl:()=>Qv,topKImpl:()=>ek,transposeImpl:()=>Gd,uniqueImpl:()=>tk});function rA(r){let e=new Float32Array(r.length);for(let t=0;t{let{x:e}=r.inputs,t=r.backend;re(e,"abs");let o=new Float32Array(x.sizeFromShape(e.shape)),n=t.data.get(e.dataId).values;return o=rA(n),t.makeOutput(o,e.shape,"float32")},oA={kernelName:is,backendName:"cpu",kernelFunc:p5};function Ye(r){return(e,t,o,n,s)=>{let a=S.assertAndGetBroadcastShape(e,t),i=a.length,l=x.computeStrides(a),u=x.sizeFromShape(a),c=x.getTypedArrayFromDType(s,u),p=e.length,m=t.length,f=x.computeStrides(e),d=x.computeStrides(t),h=S.getBroadcastDims(e,a),g=S.getBroadcastDims(t,a);if(h.length+g.length===0)for(let y=0;y_[T]=0);let w=x.locToIndex(_,p,f),k=b.slice(-m);g.forEach(T=>k[T]=0);let $=x.locToIndex(k,m,d);c[y]=r(o[w],n[$])}return[c,a]}}function pr(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 nA={kernelName:Xl,backendName:"cpu",kernelFunc:pr};function Op(r,e,t="float32"){if(t==="complex64"){let n=Op(r,e,"float32"),s=Op(r,e,"float32");return pr({inputs:{real:n,imag:s},backend:r})}let o=x.makeZerosTypedArray(x.sizeFromShape(e),t);return r.makeTensorInfo(e,t,o)}function Ar(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 sA={kernelName:cs,backendName:"cpu",kernelFunc:Ar};function Yn(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 iA={kernelName:fu,backendName:"cpu",kernelFunc:Yn};function Zn(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{dtype:s}=o;if(s==="complex64"){if(n.dtype==="complex64")return Ar({inputs:{x:n},backend:t});let a=Op(t,n.shape,n.dtype),i=Zn({inputs:{x:n},backend:t,attrs:{dtype:"float32"}}),l=pr({inputs:{real:i,imag:a},backend:t});return t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),l}if(n.dtype==="complex64"){let a=Yn({inputs:{input:n},backend:t}),i=Zn({inputs:{x:a},backend:t,attrs:{dtype:s}});return t.disposeIntermediateTensorInfo(a),i}if(!x.hasEncodingLoss(n.dtype,s)){let a=Ar({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=x.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 aA={kernelName:Fo,backendName:"cpu",kernelFunc:Zn};function ot(r,e,t,o){return t==null?({inputs:n,backend:s})=>{let{a,b:i}=n,l=s;re([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=Zn({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=Zn({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(h.dataId),y=g.complexTensorInfos.real,b=g.complexTensorInfos.imag,_=l.data.get(y.dataId).values,w=l.data.get(b.dataId).values,[k,$,T]=t(a.shape,i.shape,f,d,_,w),F=l.makeTensorInfo(T,"float32",k),M=l.makeTensorInfo(T,"float32",$),L=pr({inputs:{real:F,imag:M},backend:l});return l.disposeIntermediateTensorInfo(u),l.disposeIntermediateTensorInfo(h),l.disposeIntermediateTensorInfo(F),l.disposeIntermediateTensorInfo(M),L}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 Pp(r){return(e,t,o,n,s,a)=>{let i=S.assertAndGetBroadcastShape(e,t),l=x.sizeFromShape(i),u=i.length,c=x.computeStrides(i),p=x.getTypedArrayFromDType("float32",l),m=x.getTypedArrayFromDType("float32",l),f=S.getBroadcastDims(e,i),d=S.getBroadcastDims(t,i),h=S.mergeRealAndImagArrays(o,n),g=S.mergeRealAndImagArrays(s,a),y=e.length,b=x.computeStrides(e),_=t.length,w=x.computeStrides(t);if(f.length+d.length===0)for(let k=0;kT[H]=0);let F=x.locToIndex(T,y,b),M=$.slice(-_);d.forEach(H=>M[H]=0);let L=x.locToIndex(M,_,w),G=r(h[F*2],h[F*2+1],g[L*2],g[L*2+1]);p[k]=G.real,m[k]=G.imag}return[p,m,i]}}var lA=Ye((r,e)=>r+e),m5=Pp((r,e,t,o)=>({real:r+t,imag:e+o})),Ua=ot(bo,lA,m5),uA={kernelName:bo,backendName:"cpu",kernelFunc:Ua};function Bd(r,e,t,o,n){let s=x.sizeFromShape(o),a=x.makeZerosTypedArray(n,t);for(let i=0;i=n||(s>0?a[l]+=e[i]:a[l]+=1)}return a}function Hv(r,e,t,o=!1){let n=r.shape[0],s=r.shape[1],a=Ie([n,t],e.dtype);for(let i=0;i=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 Jn(r){return(e,t,o)=>{let n=x.getTypedArrayFromDType(t,e.length);for(let s=0;s{let{x:a}=o;if(re(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=x.sizeFromShape(a.shape),c=t||a.dtype,p=x.getArrayFromDType(c,u);for(let m=0;m{let{x:a}=o;if(re(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 cA=Jn(r=>Math.ceil(r)),f5=Qn(Js,cA),pA={kernelName:Js,backendName:"cpu",kernelFunc:f5};function Vd(r,e,t,o){let n=x.getArrayFromDType(t,x.sizeFromShape(e));if(o&&t!=="string"){let s=0;r.forEach(a=>{let i=x.sizeFromShape(a.shape);n.set(a.vals,s),s+=i})}else{let s=0;r.forEach(a=>{let i=t==="string"?S.fromUint8ToStringArray(a.vals):a.vals,l=0;for(let u=0;uMath.exp(r)),Kv=Qn(on,mA),fA={kernelName:on,backendName:"cpu",kernelFunc:Kv};var dA=Jn(r=>Math.expm1(r)),d5=Qn(si,dA),hA={kernelName:si,backendName:"cpu",kernelFunc:d5};var gA=Jn(r=>Math.floor(r)),h5=Qn(nn,gA),xA={kernelName:nn,backendName:"cpu",kernelFunc:h5};function Xv(r,e,t){let o=Ie(t,r.dtype);for(let n=0;nr>e?1:0),g5=ot(li,yA,null,"bool"),bA={kernelName:li,backendName:"cpu",kernelFunc:g5};var _A=Ye((r,e)=>rMath.log(r)),y5=Qn(cn,vA),kA={kernelName:cn,backendName:"cpu",kernelFunc:y5};function Zv(r,e,t,o){let n=x.getTypedArrayFromDType(o,x.sizeFromShape(t));for(let s=0;si&&(i=u)}n[s]=i}return n}var CA=Ye((r,e)=>Math.max(r,e)),b5=ot(mn,CA),IA={kernelName:mn,backendName:"cpu",kernelFunc:b5};var NA=Ye((r,e)=>Math.min(r,e)),_5=ot(gn,NA),SA={kernelName:gn,backendName:"cpu",kernelFunc:_5};var wx=Ye((r,e)=>r*e),w5=Pp((r,e,t,o)=>({real:r*t-e*o,imag:r*o+e*t})),Wd=ot(xn,wx,w5),TA={kernelName:xn,backendName:"cpu",kernelFunc:Wd};function EA(r,e,t){let o=x.createScalarValue(-1,t);return wx([],e,o,r,t)}function v5(r){let{inputs:e,backend:t}=r,{x:o}=e;re(o,"neg");let n=t.data.get(o.dataId).values,[s,a]=EA(n,o.shape,o.dtype);return t.makeTensorInfo(a,o.dtype,s)}var AA={kernelName:ps,backendName:"cpu",kernelFunc:v5};var DA=Ye((r,e)=>r!==e?1:0),k5=ot(xi,DA,null,"bool"),$A={kernelName:xi,backendName:"cpu",kernelFunc:k5};function Gd(r,e,t,o,n){let s=e.length,a=x.sizeFromShape(e),i=x.computeStrides(e),l=x.computeStrides(n),u=x.getTypedArrayFromDType(t,x.sizeFromShape(n));for(let c=0;ct.disposeIntermediateTensorInfo(b)),t.makeTensorInfo(y,g,d)}var OA={kernelName:wi,backendName:"cpu",kernelFunc:C5};function Ud(r,e,t,o){let n=r===e,s=r1;if(n||s||a)return x.makeZerosTypedArray(0,o);let i=Math.abs(Math.ceil((e-r)/t)),l=x.makeZerosTypedArray(i,o);e1/Math.sqrt(r)),I5=Qn(Sn,PA),MA={kernelName:Sn,backendName:"cpu",kernelFunc:I5};function jd(r,e,t,o,n){let s=sr.isSliceContinous(o,e,t),a=x.sizeFromShape(t),i=x.computeStrides(o);if(s){let p=sr.computeFlatOffset(e,i);return n==="string"?r.slice(p,p+a):r.subarray(p,p+a)}let l=n==="string"?S.fromUint8ToStringArray(r):r,u=Ie(o,n,l),c=Ie(t,n);for(let p=0;pd+e[h]);c.set(u.get(...f),...m)}return n==="string"?S.fromStringArrayToUint8(c.values):c.values}function es(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{begin:s,size:a}=o;re(n,"slice");let[i,l]=sr.parseSliceParams(n,s,a);sr.assertParamsValid(n,i,l);let u=t.data.get(n.dataId).values,c=jd(u,i,l,n.shape,n.dtype);return t.makeTensorInfo(l,n.dtype,c)}var LA={kernelName:gs,backendName:"cpu",kernelFunc:es};var zA=Ye((r,e)=>{let t=r-e;return t*t}),N5=ot(Rn,zA),BA={kernelName:Rn,backendName:"cpu",kernelFunc:N5};function Jv(r,e,t,o){let n=Ie(r,e.dtype);for(let s=0;sr-e),S5=Pp((r,e,t,o)=>({real:r-t,imag:e-o})),qd=ot(Fn,VA,S5),WA={kernelName:Fn,backendName:"cpu",kernelFunc:qd};function Qv(r,e){let t=new Array(r.rank);for(let n=0;n_.value-b.value);let h=p*o,g=l.subarray(h,h+o),y=u.subarray(h,h+o);for(let b=0;b{for(let g=0;gnew qv,1);var ok=$e(ri,r=>r>=0?r:Math.exp(r)-1),UA={kernelName:ri,backendName:"cpu",kernelFunc:ok};function nk(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{alpha:s}=o;re([n],"leakyRelu");let a=x.sizeFromShape(n.shape),i=t.data.get(n.dataId).values,l=x.getTypedArrayFromDType("float32",a);for(let u=0;ur<0?e*r:r);function sk(r){let{inputs:e,backend:t}=r,{x:o,alpha:n}=e;re([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 qA={kernelName:wn,backendName:"cpu",kernelFunc:sk};var ik=$e(vn,r=>Math.max(0,r)),HA={kernelName:vn,backendName:"cpu",kernelFunc:ik};var ak=$e(Cn,r=>Math.min(Math.max(0,r),6)),KA={kernelName:Cn,backendName:"cpu",kernelFunc:ak};function Mp(r,e,t,o,n){if(t==="linear")return Ar({inputs:{x:e},backend:r});if(t==="relu")return ik({inputs:{x:e},backend:r});if(t==="elu")return ok({inputs:{x:e},backend:r});if(t==="relu6")return ak({inputs:{x:e},backend:r});if(t==="prelu")return sk({inputs:{x:e,alpha:o},backend:r});if(t==="leakyrelu")return nk({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=x.sizeFromShape(n.shape),i=x.inferFromImplicitShape(s,a),l=x.sizeFromShape(i);x.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 XA={kernelName:ds,backendName:"cpu",kernelFunc:tt};function lk(r){let{inputs:e,backend:t,attrs:o}=r,{a:n,b:s}=e,{transposeA:a,transposeB:i}=o;re([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=x.sizeFromShape(d),y=x.sizeFromShape(h),b=g===y||g===1||y===1;x.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>y?n.shape.slice(0,-2):s.shape.slice(0,-2)).concat([m,f]);x.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 k=a?[g,c,m]:[g,m,c],$=i?[y,f,p]:[y,p,f],T=tt({inputs:{x:n},backend:t,attrs:{shape:k}}),F=tt({inputs:{x:s},backend:t,attrs:{shape:$}}),M=a?T.shape[1]:T.shape[2],L=a?T.shape[2]:T.shape[1],G=i?F.shape[1]:F.shape[2],H=Math.max(g,y),U=t.data.get(T.dataId).values,Z=t.data.get(F.dataId).values,K=x.computeStrides(T.shape),X=x.computeStrides(F.shape),[oe,J,Q]=a?[K[0],1,K[1]]:[K[0],K[1],1],[ie,ae,ue]=i?[1,X[1],X[0]]:[X[1],1,X[0]],le=L*G,ge=Ie([H,L,G],T.dtype),we=ge.values,ye=t.blockSize;for(let ke=0;keMath.acos(r)),JA={kernelName:js,backendName:"cpu",kernelFunc:A5};var D5=$e(qs,r=>Math.acosh(r)),QA={kernelName:qs,backendName:"cpu",kernelFunc:D5};function $5(r){let{inputs:e,backend:t}=r,o=e;re(e,"addN");let n=o.map(i=>t.data.get(i.dataId).values),s=Ie(o[0].shape,o[0].dtype),a=s.values;for(let i=0;ib&&(b=k,_=w)}f[g]=_}return u.forEach(g=>t.disposeIntermediateTensorInfo(g)),t.makeTensorInfo(c,"int32",f)}var o2={kernelName:Ko,backendName:"cpu",kernelFunc:O5};function P5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s}=o;re(n,"argMin");let a=x.parseAxisParam(s,n.shape),i=S.getAxesPermutation(a,n.shape.length),l=n,u=[];i!=null&&(l=or({inputs:{x:n},backend:t,attrs:{perm:i}}),u.push(l),a=S.getInnerMostAxes(a.length,l.shape.length)),a=[a[0]],S.assertAxesAreInnerMostDims("argMin",a,l.shape.length);let[c,p]=S.computeOutAndReduceShapes(l.shape,a),m=x.sizeFromShape(c),f=x.makeZerosTypedArray(m,"int32"),d=x.sizeFromShape(p),h=t.data.get(l.dataId).values;for(let g=0;gt.disposeIntermediateTensorInfo(g)),t.makeTensorInfo(c,"int32",f)}var n2={kernelName:oa,backendName:"cpu",kernelFunc:P5};var M5=$e(Hs,r=>Math.asin(r)),s2={kernelName:Hs,backendName:"cpu",kernelFunc:M5};var L5=$e(Ks,r=>Math.asinh(r)),i2={kernelName:Ks,backendName:"cpu",kernelFunc:L5};var z5=$e(Xs,r=>Math.atan(r)),a2={kernelName:Xs,backendName:"cpu",kernelFunc:z5};var B5=Ye((r,e)=>Math.atan2(r,e)),V5=ot(Zs,B5),l2={kernelName:Zs,backendName:"cpu",kernelFunc:V5};var W5=$e(Ys,r=>Math.atanh(r)),u2={kernelName:Ys,backendName:"cpu",kernelFunc:W5};function Lp(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=Ie(n.outShape,t),g=h.values,y=n.outShape[1]*n.outShape[2]*n.outShape[3],b=n.outShape[2]*n.outShape[3],_=n.outShape[3];for(let w=0;woe?oe=we:s==="avg"&&(J+=we,Q++)}if(isNaN(oe))break}let ie=H+U*_+T;g[ie]=s==="avg"?J/Q:oe}}}return h}function vx(r,e,t,o,n=!1,s=!1){let a=Ie(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=Ie(e,t,r);for(let g=0;gL&&(L=X,n?G=s?((g*o.inHeight+H)*o.inWidth+Z)*o.inChannels+y:(H*o.inWidth+Z)*o.inChannels+y:G=U*m+K)}}a.set(G,g,b,$,y)}}return a}function kx(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,y=n.padInfo.left,b=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,_=Ie(n.outShape,t),w=_.values,k=n.outShape[1]*n.outShape[2]*n.outShape[3]*n.outShape[4],$=n.outShape[2]*n.outShape[3]*n.outShape[4],T=n.outShape[3]*n.outShape[4],F=n.outShape[4];for(let M=0;MEe?Ee=nt:s==="avg"&&(Re+=nt,Pe++),isNaN(Ee))break}if(isNaN(Ee))break}if(isNaN(Ee))break}let ze=ke+H;w[ze]=s==="avg"?Re/Pe:Ee}}}}return _}function c2(r,e){let t=Ie(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=U&&(U=ae,Z=X*c*p+J*c+ie)}}}t.set(Z,h,y,k,M,g)}}}return t}function G5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e;re(n,"avgPool");let{filterSize:s,strides:a,pad:i,dimRoundingMode:l}=o,u=1;x.assert(S.eitherStridesOrDilationsAreOne(a,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let c=S.computePool2DInfo(n.shape,s,a,u,i,l),p;if(c.filterWidth===1&&c.filterHeight===1&&x.arraysEqual(c.inShape,c.outShape))p=Ar({inputs:{x:n},backend:t});else{let m=t.data.get(n.dataId).values,f=x.computeStrides(n.shape),d=Lp(m,n.shape,n.dtype,f,c,"avg");p=t.makeTensorInfo(c.outShape,n.dtype,d.values)}return p}var p2={kernelName:Xo,backendName:"cpu",kernelFunc:G5};function U5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{filterSize:s,strides:a,pad:i,dimRoundingMode:l,dataFormat:u,dilations:c}=o;re(n,"avgPool3d");let p=c;p==null&&(p=[1,1,1]);let m=S.computePool3DInfo(n.shape,s,a,p,i,l,u),f=t.data.get(n.dataId).values,d=kx(f,n.shape,n.dtype,x.computeStrides(n.shape),m,"avg");return t.makeTensorInfo(d.shape,"float32",d.values)}var m2={kernelName:na,backendName:"cpu",kernelFunc:U5};function j5(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,{filterSize:a,strides:i,pad:l,dilations:u,dimRoundingMode:c}=o;re([n,s],"avgPool3DGrad");let p=S.computePool3DInfo(s.shape,a,i,u,l,c),m=p.strideDepth,f=p.strideHeight,d=p.strideWidth,h=p.filterDepth,g=p.filterHeight,y=p.filterWidth,b=p.dilationDepth,_=p.dilationHeight,w=p.dilationWidth,k=p.effectiveFilterDepth,$=p.effectiveFilterHeight,T=p.effectiveFilterWidth,F=k-1-p.padInfo.front,M=T-1-p.padInfo.left,L=$-1-p.padInfo.top,G=Ie(s.shape,"float32"),H=1/(h*g*y),U=t.bufferSync(n);for(let Z=0;Z=p.outDepth||Math.floor(ge)!==ge))for(let we=0;we<$;we+=_){let ye=(ie+we)/f;if(!(ye<0||ye>=p.outHeight||Math.floor(ye)!==ye))for(let ke=0;ke=p.outWidth||Math.floor(Ee)!==Ee)continue;ue+=U.get(Z,ge,ye,Ee,K)}}}G.set(ue*H,Z,X,oe,J,K)}return t.makeTensorInfo(G.shape,G.dtype,G.values)}var f2={kernelName:Hl,backendName:"cpu",kernelFunc:j5};function q5(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,a=s;re([n,s],"avgPoolGrad");let{filterSize:i,strides:l,pad:u}=o,c=S.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,y=c.effectiveFilterHeight,b=c.effectiveFilterWidth,_=b-1-c.padInfo.left,w=y-1-c.padInfo.top,k=Ie(a.shape,"float32"),$=1/(f*d),T=t.data.get(n.dataId).values,F=Ie(n.shape,"float32",T);for(let M=0;M=c.outHeight||Math.floor(oe)!==oe))for(let J=0;J=c.outWidth||Math.floor(Q)!==Q)continue;K+=F.get(M,oe,Q,L)}}k.set(K*$,M,G,H,L)}return t.makeTensorInfo(k.shape,k.dtype,k.values)}var d2={kernelName:ql,backendName:"cpu",kernelFunc:q5};function H5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,scale:s,offset:a,mean:i,variance:l}=e;x.assert(i.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),x.assert(a==null||i.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),x.assert(s==null||i.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),re([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,y=f.length,b=m.length,_=p.length,w=0,k=0,$=0,T=0;for(let F=0;F=g&&(w=0),k>=_&&(k=0),$>=y&&($=0),T>=b&&(T=0);return t.makeTensorInfo(n.shape,n.dtype,h)}var h2={kernelName:an,backendName:"cpu",kernelFunc:H5};function K5(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockShape:s,crops:a}=o;re([n],"batchToSpaceND");let i=s.reduce((y,b)=>y*b),l=S.getReshaped(n.shape,s,i),u=S.getPermuted(l.length,s.length),c=S.getReshapedPermuted(n.shape,s,i),p=S.getSliceBeginCoords(a,s.length),m=S.getSliceSize(c,a,s.length),f=tt({inputs:{x:n},backend:t,attrs:{shape:l}}),d=or({inputs:{x:f},backend:t,attrs:{perm:u}}),h=tt({inputs:{x:d},backend:t,attrs:{shape:c}}),g=es({inputs:{x:h},backend:t,attrs:{begin:p,size:m}});return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(h),g}var g2={kernelName:sa,backendName:"cpu",kernelFunc:K5};function X5(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=Bd(i,l,s.dtype,s.shape,a);return t.makeTensorInfo([a],s.dtype,u)}var x2={kernelName:Kl,backendName:"cpu",kernelFunc:X5};var Y5=$e(Oo,(r,e)=>{let t=e;return r>t.clipValueMax?t.clipValueMax:r{let{x:e}=r.inputs,t=r.backend,o=new Float32Array(x.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;uh.shape),s);if(x.sizeFromShape(a)===0)return t.makeTensorInfo(a,e[0].dtype,[]);let i=e.filter(h=>x.sizeFromShape(h.shape)>0);if(i.length===1)return Ar({inputs:{x:i[0]},backend:t});let l=i.map(h=>h.shape);if(S.assertParamsConsistent(l,s),i[0].dtype==="complex64"){let h=i.map(w=>Yn({inputs:{input:w},backend:t})),g=i.map(w=>Hi({inputs:{input:w},backend:t})),y=Il({inputs:h,backend:t,attrs:{axis:s}}),b=Il({inputs:g,backend:t,attrs:{axis:s}}),_=pr({inputs:{real:y,imag:b},backend:t});return h.forEach(w=>t.disposeIntermediateTensorInfo(w)),g.forEach(w=>t.disposeIntermediateTensorInfo(w)),t.disposeIntermediateTensorInfo(y),t.disposeIntermediateTensorInfo(b),_}let u=i.map(h=>{let g=x.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=S.computeOutShape(u.map(h=>h.shape),1);let p=u[0].shape[0]===1,m=Vd(c,a,e[0].dtype,p),f=S.computeOutShape(i.map(h=>h.shape),s),d=t.makeTensorInfo(f,e[0].dtype,m);return u.forEach(h=>t.disposeIntermediateTensorInfo(h)),d}var w2={kernelName:as,backendName:"cpu",kernelFunc:Il};function uk(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;re([n,s],"conv2d");let p=S.convertConv2DDataFormat(l),m=S.computeConv2DInfo(n.shape,s.shape,a,u,i,c,!1,p),f=m.filterHeight,d=m.filterWidth,h=m.dilationHeight,g=m.dilationWidth,y=m.padInfo.left,b=m.padInfo.top,_=m.dataFormat==="channelsLast",w=new ct(m.outShape,n.dtype),k=x.computeStrides(n.shape),$=x.computeStrides(s.shape),T=k[0],F=_?k[1]:k[2],M=_?k[2]:1,L=_?1:k[1],G=w.strides[0],H=_?w.strides[1]:w.strides[2],U=_?w.strides[2]:1,Z=_?1:w.strides[1],K=t.data.get(n.dataId).values,X=t.data.get(s.dataId).values,oe=w.values;for(let J=0;J=m.inHeight)continue;let ye=ge*$[0],ke=Q+we*F;for(let Ee=0;Ee=m.inWidth)continue;let gt=ye+ze*$[1],Ct=ke+mt*M,xt=gt;for(let yt=0;yt=u.inDepth)continue;let J=X*M[0],Q=G+oe*F[1];for(let ie=0;ie=u.inHeight)continue;let we=J+le*M[1],ye=Q+ge*F[2];for(let ke=0;ke=u.inWidth)continue;let mt=we+Pe*M[2],gt=ye+ze*u.inChannels,Ct=mt;for(let xt=0;xtMath.cos(r)),T2={kernelName:Qo,backendName:"cpu",kernelFunc:oX};var nX=$e(Qs,r=>Math.cosh(r)),E2={kernelName:Qs,backendName:"cpu",kernelFunc:nX};function sX(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,y=Ie([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,k=x.computeStrides(n.shape),$=x.computeStrides(y.shape);for(let T=0;T=c)continue;let Z=h>1?(G-M)*(p-1)/(h-1):0,K=g>1?(H-L)*(m-1)/(g-1):0;for(let X=0;X1?M*(p-1)+X*Z:.5*(M+G)*(p-1);if(oe<0||oe>p-1){for(let J=0;J1?L*(m-1)+ae*K:.5*(L+H)*(m-1);if(ue<0||ue>m-1){for(let ye=0;ye1?L*(m-1)+J*K:.5*(L+H)*(m-1);if(Q<0||Q>m-1){for(let ue=0;uey+d-b-1:(y,b)=>y+b;for(let y=0;y`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${a}`),x.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 y=0;y`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${m}'`);let f=S.computeConv2DInfo(n.shape,s.shape,a,m,i,u,!0),{filterHeight:d,filterWidth:h,dilationHeight:g,dilationWidth:y,padInfo:b}=f,_=b.left,w=b.top,k=f.outChannels/f.inChannels,$=new ct(f.outShape,n.dtype),T=t.data.get(n.dataId).values,F=t.data.get(s.dataId).values,M=$.values;for(let L=0;L=f.inHeight)continue;let J=X*p[0],Q=G+oe*c[1];for(let ie=0;ie=f.inWidth)continue;let we=J+le*p[1],ye=Q+ge*f.inChannels,ke=ae,Ee=we;for(let Re=0;Re{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:y,outWidth:b,padInfo:_,strideHeight:w,strideWidth:k,filterHeight:$,filterWidth:T,dilationHeight:F,dilationWidth:M,outShape:L}=S.computeDilation2DInfo(o.shape,n.shape,s,a,"NHWC",i),G=x.sizeFromShape(L),H=L.length,U=x.getArrayFromDType(o.dtype,G);for(let K=0;K=0&&ge=0&&yeae&&(ae=Re)}}}let ue=x.locToIndex([K,X,J,ie],H,x.computeStrides(L));U[ue]=ae}}}return{dataId:l.write(x.toTypedArray(U,o.dtype),L,o.dtype),shape:L,dtype:o.dtype}}};var z2={kernelName:Oc,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=x.toNestedArray(o.shape,u.data.get(o.dataId).values),p=x.toNestedArray(n.shape,u.data.get(n.dataId).values),{batchSize:m,inHeight:f,inWidth:d,inChannels:h,outHeight:g,outWidth:y,padInfo:b,strideHeight:_,strideWidth:w,filterHeight:k,filterWidth:$,dilationHeight:T,dilationWidth:F,outShape:M}=S.computeDilation2DInfo(o.shape,n.shape,a,i,"NHWC",l);x.assert(s.rank===M.length,()=>`Error in ${Oc}, dy must have the same rank as output ${M.length}, but got ${s.rank}`);let L=x.toNestedArray(M,u.data.get(s.dataId).values),G=x.makeZerosNestedTypedArray(n.shape,n.dtype);for(let U=0;U=0&&le=0&&weQ&&(Q=ye,ie=ue,ae=ge)}}}G[ie][ae][J]+=L[U][Z][X][J]}}}return{dataId:u.write(x.toTypedArray(G,o.dtype),n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}};var B2={kernelName:Fc,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=x.toNestedArray(o.shape,u.data.get(o.dataId).values),p=x.toNestedArray(n.shape,u.data.get(n.dataId).values),{batchSize:m,inHeight:f,inWidth:d,inChannels:h,outHeight:g,outWidth:y,padInfo:b,strideHeight:_,strideWidth:w,filterHeight:k,filterWidth:$,dilationHeight:T,dilationWidth:F,outShape:M}=S.computeDilation2DInfo(o.shape,n.shape,a,i,"NHWC",l);x.assert(s.rank===M.length,()=>`Error in ${Fc}, dy must have the same rank as output ${M.length}, but got ${s.rank}`);let L=x.toNestedArray(M,u.data.get(s.dataId).values),G=x.makeZerosNestedTypedArray(o.shape,o.dtype);for(let U=0;U=0&&le=0&&weQ&&(Q=ye,ie=le,ae=we)}}}G[U][ie][ae][J]+=L[U][Z][X][J]}}}return{dataId:u.write(x.toTypedArray(G,o.dtype),o.shape,o.dtype),shape:o.shape,dtype:o.dtype}}};function mX(r){let{inputs:e,backend:t}=r,{dy:o,y:n}=e;re([o,n],"eluGrad");let s=new Float32Array(x.sizeFromShape(n.shape)),a=t.data.get(n.dataId).values,i=t.data.get(o.dataId).values;for(let l=0;l=1?s[l]=i[l]:s[l]=i[l]*(u+1)}return t.makeTensorInfo(n.shape,"float32",s)}var V2={kernelName:ou,backendName:"cpu",kernelFunc:mX};var fX=Ye((r,e)=>r===e?1:0),pk=ot(ni,fX,null,"bool"),W2={kernelName:ni,backendName:"cpu",kernelFunc:pk};var dX=S.ERF_P,hX=S.ERF_A1,gX=S.ERF_A2,xX=S.ERF_A3,yX=S.ERF_A4,bX=S.ERF_A5,_X=$e(oi,r=>{let e=Math.sign(r),t=Math.abs(r),o=1/(1+dX*t);return e*(1-((((bX*o+yX)*o+xX)*o+gX)*o+hX)*o*Math.exp(-t*t))}),G2={kernelName:oi,backendName:"cpu",kernelFunc:_X};function zp(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&&(x.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 U2={kernelName:ls,backendName:"cpu",kernelFunc:zp};var wX=Ye((r,e)=>r/e),Hd=ot(rn,wX),Kd={kernelName:rn,backendName:"cpu",kernelFunc:Hd};function Cx(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=x.sizeFromShape(u),p=x.getTypedArrayFromDType("float32",c),m=x.getTypedArrayFromDType("float32",c);for(let g=0;g{let{image:o}=r,n=t,s=x.getTypedArrayFromDType(o.dtype,x.sizeFromShape(o.shape)),[a,i,l,u]=o.shape,c=n.data.get(o.dataId).values;for(let m=0;m=0&&kMath.floor(r/e)),TX=ot(sn,SX,null,"int32"),K2={kernelName:sn,backendName:"cpu",kernelFunc:TX};function EX(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=uk({inputs:{x:n,filter:s},backend:t,attrs:{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:m}});if(a){let g=h;h=Ua({inputs:{a:h,b:a},backend:t}),t.disposeIntermediateTensorInfo(g)}if(f){let g=h;h=Mp(t,h,f,i,d),t.disposeIntermediateTensorInfo(g)}return h}var X2={kernelName:ws,backendName:"cpu",kernelFunc:EX};function AX(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=ck({inputs:{x:n,filter:s},backend:t,attrs:{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:m}});if(a){let g=h;h=Ua({inputs:{a:h,b:a},backend:t}),t.disposeIntermediateTensorInfo(g)}if(f){let g=h;h=Mp(t,h,f,i,d),t.disposeIntermediateTensorInfo(g)}return h}var Y2={kernelName:vs,backendName:"cpu",kernelFunc:AX};function DX(r){let{inputs:e,backend:t}=r,{params:o,indices:n}=e,s=x.sizeFromShape(o.shape),a=n.shape,i=a[a.length-1],[l,u,c,p]=S.prepareAndValidate(o,n);if(u===0)return t.makeTensorInfo(l,o.dtype,[]);let m=Ie([u,c],o.dtype),f=t.data.get(n.dataId).values,d=t.data.get(o.dataId).values;for(let h=0;h=s/c)throw new Error(`Invalid indices: ${g} does not index into ${o.shape}`);for(let b=0;br>=e?1:0),FX=ot(ln,RX,null,"bool"),Q2={kernelName:ln,backendName:"cpu",kernelFunc:FX};function OX(r){let{inputs:e,backend:t}=r,{input:o}=e,n=x.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=Cx(i,!0,t),u=tt({inputs:{x:l},backend:t,attrs:{shape:o.shape}});return t.disposeIntermediateTensorInfo(i),t.disposeIntermediateTensorInfo(l),u}var eD={kernelName:su,backendName:"cpu",kernelFunc:OX};var PX=$e(ui,r=>Number.isFinite(r)?1:0,"bool"),tD={kernelName:ui,backendName:"cpu",kernelFunc:PX};var MX=$e(ci,r=>Math.abs(r)===Infinity?1:0,"bool"),rD={kernelName:ci,backendName:"cpu",kernelFunc:MX};var LX=$e(pi,r=>Number.isNaN(r)?1:0,"bool"),oD={kernelName:pi,backendName:"cpu",kernelFunc:LX};var zX=Ye((r,e)=>r<=e?1:0),BX=ot(fi,zX,null,"bool"),nD={kernelName:fi,backendName:"cpu",kernelFunc:BX};function VX(r){let{backend:e,attrs:t}=r,{start:o,stop:n,num:s}=t,a=Yv(o,n,s);return e.makeTensorInfo([a.length],"float32",a)}var sD={kernelName:au,backendName:"cpu",kernelFunc:VX};var WX=$e(di,r=>Math.log1p(r)),iD={kernelName:di,backendName:"cpu",kernelFunc:WX};var GX=Ye((r,e)=>r&&e),UX=ot(hi,GX,null,"bool"),aD={kernelName:hi,backendName:"cpu",kernelFunc:UX};var jX=$e(Qa,r=>r?0:1,"bool"),lD={kernelName:Qa,backendName:"cpu",kernelFunc:jX};var qX=Ye((r,e)=>r||e),HX=ot(el,qX,null,"bool"),uD={kernelName:el,backendName:"cpu",kernelFunc:HX};function KX(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{depthRadius:s,bias:a,alpha:i,beta:l}=o;re(n,"LRN");let u=n.shape[3],c=u-1,p=t.data.get(n.dataId).values,m=x.sizeFromShape(n.shape),f=new Float32Array(m);function d(h){let g=h%u,y=h-g+Math.max(0,g-s),b=h-g+Math.min(g+s,c),_=0;for(;y<=b;y++){let w=p[y];_+=w*w}return _}for(let h=0;h`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let c=S.computePool2DInfo(n.shape,s,a,u,i,l),p;if(c.filterWidth===1&&c.filterHeight===1&&x.arraysEqual(c.inShape,c.outShape))p=Ar({inputs:{x:n},backend:t});else{let m=t.data.get(n.dataId).values,f=x.computeStrides(n.shape),d=Lp(m,n.shape,n.dtype,f,c,"max");p=t.makeTensorInfo(c.outShape,n.dtype,d.values)}return p}var fD={kernelName:fn,backendName:"cpu",kernelFunc:YX};function ZX(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{filterSize:s,strides:a,pad:i,dimRoundingMode:l,dataFormat:u,dilations:c}=o;re(n,"maxPool3d");let p=c;p==null&&(p=[1,1,1]);let m=S.computePool3DInfo(n.shape,s,a,p,i,l,u),f=t.data.get(n.dataId).values,d=kx(f,n.shape,n.dtype,x.computeStrides(n.shape),m,"max");return t.makeTensorInfo(d.shape,"float32",d.values)}var dD={kernelName:pa,backendName:"cpu",kernelFunc:ZX};function JX(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,{filterSize:a,strides:i,pad:l,dilations:u,dimRoundingMode:c}=o;re([n,s],"maxPool3DGrad");let p=S.computePool3DInfo(s.shape,a,i,u,l,c),m=t.bufferSync(s),f=c2(m,p),d=p.strideDepth,h=p.strideHeight,g=p.strideWidth,y=p.dilationDepth,b=p.dilationHeight,_=p.dilationWidth,w=p.effectiveFilterDepth,k=p.effectiveFilterHeight,$=p.effectiveFilterWidth,T=w-1-p.padInfo.front,F=$-1-p.padInfo.left,M=k-1-p.padInfo.top,L=Ie(s.shape,"float32"),G=t.bufferSync(n);for(let H=0;H=p.outDepth||Math.floor(ue)!==ue))for(let le=0;le=p.outHeight||Math.floor(ge)!==ge))for(let we=0;we<$;we+=_){let ye=(Q+we)/g;if(ye<0||ye>=p.outWidth||Math.floor(ye)!==ye)continue;let ke=w*k*$-1-f.get(H,ue,ge,ye,U),Ee=ae*k*$+le*$+we,Re=ke===Ee?1:0;if(Re===0)continue;ie+=G.get(H,ue,ge,ye,U)*Re}}}L.set(ie,H,Z,K,X,U)}return t.makeTensorInfo(L.shape,L.dtype,L.values)}var hD={kernelName:cu,backendName:"cpu",kernelFunc:JX};function QX(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s,output:a}=e,i=s;re([s,a],"maxPoolGrad");let{filterSize:l,strides:u,pad:c,dimRoundingMode:p}=o,m=S.computePool2DInfo(i.shape,l,u,1,c,p),f=t.data.get(i.dataId).values,d=Ie(m.outShape,i.dtype,vx(f,i.shape,i.dtype,m).values),h=m.strideHeight,g=m.strideWidth,y=m.dilationHeight,b=m.dilationWidth,_=m.effectiveFilterHeight,w=m.effectiveFilterWidth,k=w-1-m.padInfo.left,$=_-1-m.padInfo.top,T=Ie(i.shape,"float32"),F=t.data.get(n.dataId).values,M=Ie(n.shape,"float32",F);for(let L=0;L=m.outHeight||Math.floor(J)!==J))for(let Q=0;Q=m.outWidth||Math.floor(ie)!==ie)continue;let ae=_*w-1-d.get(L,J,ie,G),ue=oe*w+Q,le=ae===ue?1:0;if(le===0)continue;X+=M.get(L,J,ie,G)*le}}T.set(X,L,H,U,G)}return t.makeTensorInfo(T.shape,T.dtype,T.values)}var gD={kernelName:uu,backendName:"cpu",kernelFunc:QX};function xD(r,e,t,o,n){let s=x.computeStrides(e),a=Lp(r,e,t,s,n,"max"),i=vx(r,e,t,n,!0,o);return[a.values,i.values]}var yD={kernelName:pu,backendName:"cpu",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{x:o}=r,{filterSize:n,strides:s,pad:a,includeBatchInIndex:i}=e,l=t;re(o,"MaxPoolWithArgmax");let u=l.data.get(o.dataId).values,c=S.computePool2DInfo(o.shape,n,s,[1,1],a),[p,m]=xD(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 ic(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o;re(n,"sum");let i;n.dtype==="bool"?i=Zn({inputs:{x:n},backend:t,attrs:{dtype:"int32"}}):i=Ar({inputs:{x:n},backend:t});let l=i.shape.length,u=x.parseAxisParam(s,i.shape),c=S.getAxesPermutation(u,l),p=u,m=i;c!=null&&(m=or({inputs:{x:i},backend:t,attrs:{perm:c}}),p=S.getInnerMostAxes(p.length,l)),S.assertAxesAreInnerMostDims("sum",p,m.shape.length);let[f,d]=S.computeOutAndReduceShapes(m.shape,p),h=S.upcastType(m.dtype,"int32"),g=Op(t,f,h),y=x.sizeFromShape(d),b=t.data.get(g.dataId).values,_=t.data.get(m.dataId).values;for(let w=0;wt.disposeIntermediateTensorInfo(g)),h}var _D={kernelName:dn,backendName:"cpu",kernelFunc:e8};function t8(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o;re(n,"min");let i=x.parseAxisParam(s,n.shape),l=i,u=S.getAxesPermutation(l,n.shape.length),c=n;u!=null&&(c=or({inputs:{x:n},backend:t,attrs:{perm:u}}),l=S.getInnerMostAxes(l.length,n.shape.length)),S.assertAxesAreInnerMostDims("min",l,c.shape.length);let[p,m]=S.computeOutAndReduceShapes(c.shape,l),f=x.sizeFromShape(m),d=x.makeZerosTypedArray(x.sizeFromShape(p),c.dtype),h=t.data.get(c.dataId).values;for(let y=0;y_[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=x.computeStrides(n.shape),d=x.sizeFromShape(i),h=i.length,g=x.computeStrides(i),y=x.getTypedArrayFromDType(n.dtype,d);for(let _=0;_=u[$]&&(w[$]=(u[$]-1)*2-w[$]+c);w=w.map(($,T)=>$-l[T]);let k=x.locToIndex(w,m,f);y[_]=p[k]}return{dataId:t.write(y,i,n.dtype),shape:i,dtype:n.dtype}}var vD={kernelName:ma,backendName:"cpu",kernelFunc:r8};var o8=Ye((r,e)=>{let t=r%e;return r<0&&e<0||r>=0&&e>=0?t:(t+e)%e}),n8=ot(gi,o8),kD={kernelName:gi,backendName:"cpu",kernelFunc:n8};var ID=Ec(Wm());function dk(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=x.parseAxisParam([i],n.shape),u=fk({inputs:{x:n},backend:t,attrs:{reductionIndices:l,keepDims:!1}}),c=S.expandShapeToKeepDim(u.shape,l),p=tt({inputs:{x:u},backend:t,attrs:{shape:c}}),m=qd({inputs:{a:n,b:p},backend:t}),f=Kv({inputs:{x:m},backend:t}),d=ic({inputs:{x:f},backend:t,attrs:{axis:l,keepDims:!1}}),h=tt({inputs:{x:d},backend:t,attrs:{shape:c}}),g=Hd({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 CD={kernelName:$n,backendName:"cpu",kernelFunc:dk};function s8(r){let{inputs:e,backend:t,attrs:o}=r,{logits:n}=e,{numSamples:s,seed:a,normalized:i}=o;re(n,"multinomial");let l=i?n:dk({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=x.makeZerosTypedArray(x.sizeFromShape(m),"int32");for(let d=0;d=0&&c[p]{x.assertShapesMatch(s,c.shape,"All tensors passed to stack must have matching shapes"),x.assert(a===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=e.map(c=>{let p=zp({inputs:{input:c},backend:t,attrs:{dim:n}});return i.push(p),p}),u=Il({inputs:l,backend:t,attrs:{axis:n}});return i.forEach(c=>t.disposeIntermediateTensorInfo(c)),u}var FD={kernelName:fs,backendName:"cpu",kernelFunc:hk};function f8(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{paddings:s,constantValue:a}=o;re(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=x.sizeFromShape(n.shape),p=n.shape.length,m=x.computeStrides(n.shape),f=x.sizeFromShape(i),d=i.length,h=x.computeStrides(i),g=x.getTypedArrayFromDType(n.dtype,f);a!==0&&g.fill(a);for(let b=0;b$+l[T]),k=x.locToIndex(w,d,h);g[k]=u[b]}return{dataId:t.write(g,i,n.dtype),shape:i,dtype:n.dtype}}var Ix={kernelName:bn,backendName:"cpu",kernelFunc:f8};var d8=Ye((r,e)=>Math.pow(r,e)),h8=ot(_n,d8),OD={kernelName:_n,backendName:"cpu",kernelFunc:h8};function g8(r){let{backend:e,attrs:t}=r,{start:o,stop:n,dtype:s,step:a}=t,i=Ud(o,n,a,s);return e.makeTensorInfo([i.length],s,i)}var PD={kernelName:fa,backendName:"cpu",kernelFunc:g8};var x8=$e(vi,r=>1/r),MD={kernelName:vi,backendName:"cpu",kernelFunc:x8};function y8(r){let{inputs:e,backend:t,attrs:o}=r,{images:n}=e,{alignCorners:s,halfPixelCenters:a,size:i}=o;re(n,"resizeBilinear");let l=x.computeStrides(n.shape),[u,c]=i,[p,m,f,d]=n.shape,h=t.data.get(n.dataId).values,g=new Float32Array(x.sizeFromShape([p,u,c,d])),y=[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=y[0]/b[0],k=y[1]/b[1];for(let $=0;$1?u-1:u,a&&f>1?c-1:c],g=[a&&m>1?m-1:m,a&&f>1?f-1:f],y=h[0]/g[0],b=h[1]/g[1],_=t.data.get(s.dataId).values,w=0;for(let k=0;k1?m-1:m,s&&c>1?f-1:f],b=[s&&u>1?u-1:u,s&&c>1?c-1:c],_=y[0]/b[0],w=y[1]/b[1],k=0;for(let $=0;$1?c-1:c,a&&d>1?p-1:p],b=[a&&f>1?f-1:f,a&&d>1?d-1:d],_=y[0]/b[0],w=y[1]/b[1],k=1/_,$=1/w,T=Math.ceil(k)*2+2,F=Math.ceil($)*2+2;for(let M=0;M=f)continue;let le=L+ue*l[1],ge=ue*_,we=Math.min(c-1,a?Math.round(ge):Math.floor(ge));if(G===we)for(let ye=0;ye=d)continue;let Ee=le+ke*l[2],Re=ke*w,Pe=Math.min(p-1,a?Math.round(Re):Math.floor(Re));K===Pe&&(ie+=g[Ee+Q])}}h[X+Q]=ie}}}}return t.makeTensorInfo(n.shape,n.dtype,h)}var VD={kernelName:du,backendName:"cpu",kernelFunc:w8};function v8(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{dims:s}=o;re(n,"reverse");let a=n.shape.length,i=x.parseAxisParam(s,n.shape);if(a===0)return Ar({inputs:{x:n},backend:t});let l=new ct(n.shape,n.dtype),u=t.bufferSync(n);for(let c=0;cm[f]=n.shape[f]-1-m[f]),l.set(u.get(...m),...p)}return t.makeTensorInfo(l.shape,l.dtype,l.values)}var WD={kernelName:In,backendName:"cpu",kernelFunc:v8};var GD={kernelName:$i,backendName:"cpu",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{image:o}=r,{radians:n,fillValue:s,center:a}=e,i=t,l=x.getTypedArrayFromDType(o.dtype,x.sizeFromShape(o.shape)),[u,c,p,m]=o.shape,[f,d]=S.getImageCenter(a,c,p),h=255,g=Math.sin(n),y=Math.cos(n),b=i.data.get(o.dataId).values;for(let w=0;w=0&&Z=0&&K{let e=Math.floor(r);return r-e<.5?Math.floor(r):r-e>.5?Math.ceil(r):e%2==0?e:e+1}),UD={kernelName:Nn,backendName:"cpu",kernelFunc:k8};function Nx(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 Ie(t,e.dtype);let f=Ie(c,e.dtype);f.values.fill(l);for(let d=0;d=o/n)throw new Error(`Invalid indices: ${h} does not index into ${t}`);for(let y=0;y1||n.shape.length===1?1:x.sizeFromShape(n.shape.slice(1));for(let d=0;dr>=0?S8*r:N8*(Math.exp(r)-1)),HD={kernelName:Ci,backendName:"cpu",kernelFunc:T8};var E8=$e(En,r=>1/(1+Math.exp(-r))),KD={kernelName:En,backendName:"cpu",kernelFunc:E8};var A8=$e(Ni,r=>r<0?-1:r>0?1:0),XD={kernelName:Ni,backendName:"cpu",kernelFunc:A8};var D8=$e(Tn,r=>Math.sin(r)),YD={kernelName:Tn,backendName:"cpu",kernelFunc:D8};var $8=$e(Ii,r=>Math.sinh(r)),ZD={kernelName:Ii,backendName:"cpu",kernelFunc:$8};var R8=11920928955078125e-23,JD=Math.log(R8)+2,F8=$e(Si,r=>{let e=r>-JD,t=r{let m=[...c];m[i]=p;let f=es({inputs:{x:n},backend:t,attrs:{begin:u,size:m}});return u[i]+=p,f})}var r$={kernelName:xs,backendName:"cpu",kernelFunc:M8};var L8=$e(An,r=>Math.sqrt(r)),o$={kernelName:An,backendName:"cpu",kernelFunc:L8};var n$={kernelName:ga,backendName:"cpu",kernelFunc:({inputs:r,backend:e})=>{let{x:t}=r,o=e;re(t,"square");let n=o.data.get(t.dataId).values,s=new Float32Array(n.length);for(let i=0;i{let t=e;return isNaN(r)?NaN:r>0?1:t.alpha}),s$={kernelName:Di,backendName:"cpu",kernelFunc:z8};function B8(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;re(n,"stridedSlice");let{nonStrided:f,$begin:d,$strides:h,size:g,newShape:y,outShape:b}=sr.sliceInfo(n.shape,s,a,i,l,u,c,p,m),_=tt({inputs:{x:n},backend:t,attrs:{shape:y}}),w;if(f){let $=es({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(_),T=Jv(b,$,h,d);w=t.makeTensorInfo(T.shape,T.dtype,T.values)}let k=tt({inputs:{x:w},backend:t,attrs:{shape:b}});return t.disposeIntermediateTensorInfo(_),t.disposeIntermediateTensorInfo(w),k}var i$={kernelName:Ti,backendName:"cpu",kernelFunc:B8};var V8=$e(Ei,r=>Math.tan(r)),a$={kernelName:Ei,backendName:"cpu",kernelFunc:V8};var W8=$e(On,r=>Math.tanh(r)),l$={kernelName:On,backendName:"cpu",kernelFunc:W8};function G8(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{reps:s}=o;re(n,"tile");let a=Qv(t.bufferSync(n),s);return t.makeTensorInfo(a.shape,a.dtype,a.values)}var u$={kernelName:_o,backendName:"cpu",kernelFunc:G8};function U8(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{k:s,sorted:a}=o;re(n,"topk");let i=t.data.get(n.dataId).values,[l,u]=ek(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 c$={kernelName:Ai,backendName:"cpu",kernelFunc:U8};function j8(r){let{inputs:e,attrs:t,backend:o}=r,{axis:n}=t,{x:s}=e;re(s,"unique");let a=o.data.get(s.dataId).values,{outputValues:i,outputShape:l,indices:u}=tk(a,n,s.shape,s.dtype);return[o.makeTensorInfo(l,s.dtype,i),o.makeTensorInfo([u.length],"int32",u)]}var p$={kernelName:xu,backendName:"cpu",kernelFunc:j8};function q8(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;ft.disposeIntermediateTensorInfo(d)),f}var f$={kernelName:xa,backendName:"cpu",kernelFunc:H8};var K8=[ZA,oA,JA,QA,uA,e2,t2,r2,o2,n2,s2,i2,a2,l2,u2,p2,m2,f2,d2,YA,h2,g2,x2,aA,pA,y2,nA,b2,w2,k2,C2,v2,N2,S2,I2,T2,E2,A2,D2,$2,R2,F2,O2,P2,M2,L2,B2,z2,Kd,UA,V2,W2,G2,fA,U2,hA,j2,q2,H2,xA,K2,X2,Y2,Z2,J2,bA,Q2,sA,eD,_2,tD,rD,oD,jA,wA,nD,sD,kA,iD,aD,lD,uD,cD,pD,IA,fD,dD,hD,gD,yD,mD,_D,wD,SA,vD,kD,ND,TA,AA,SD,TD,ED,$A,AD,RD,FD,Ix,OD,qA,OA,PD,iA,MD,HA,KA,XA,LD,zD,BD,VD,WD,GD,UD,MA,jD,qD,HD,KD,XD,YD,ZD,LA,CD,QD,e$,t$,r$,o$,n$,BA,s$,i$,WA,bD,a$,l$,u$,c$,RA,p$,m$,f$,DD];for(let r of K8)tl(r);var ac={},gk={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function d$(r,e){ac[r]=e}function Go(r){if(!(r in ac)){let t=X8(r);if(t!==null)ac[r]=t;else return console.log("Could not get context for WebGL version",r),null}let e=ac[r];return e.isContextLost()?(delete ac[r],Go(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),ac[r])}function Y8(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 X8(r){if(r!==1&&r!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let e=Y8(r);return e.addEventListener("webglcontextlost",t=>{t.preventDefault(),delete ac[r]},!1),r===1?e.getContext("webgl",gk)||e.getContext("experimental-webgl",gk):e.getContext("webgl2",gk)}var Nl;(function(r){r[r.DENSE=0]="DENSE",r[r.SHARED_BATCH=1]="SHARED_BATCH"})(Nl||(Nl={}));var Dr;(function(r){r[r.RENDER=0]="RENDER",r[r.UPLOAD=1]="UPLOAD",r[r.PIXELS=2]="PIXELS",r[r.DOWNLOAD=3]="DOWNLOAD"})(Dr||(Dr={}));var wr;(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"})(wr||(wr={}));function lc(r,e){return[e,r]}function h$(r,e){return r*e}function Sl(r){let e=x.sizeFromShape(r),t=Math.ceil(e/4);return x.sizeToSquarishShape(t)}function Ki(r,e){return[Math.max(1,Math.ceil(e/2)),Math.max(1,Math.ceil(r/2))]}function g$(r,e){let[t,o]=Ki(r,e);return t*o*4}function Zd(r,e){let t=r,o,n,s,a,i,l,u,c,p,m;return W().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 De(r,e){let t=e();return W().getBool("DEBUG")&&Z8(r),t}function Z8(r){let e=r.getError();if(e!==r.NO_ERROR)throw new Error("WebGL Error: "+J8(r,e))}var Q8=596e-10,eY=65504;function x$(r){return!!(W().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||r===0||Q8r.getExtension(e),'Extension "'+e+'" not supported on this browser.')}function y$(r,e){let t=ja(r,()=>r.createShader(r.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(De(r,()=>r.shaderSource(t,e)),De(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 b$(r,e){let t=ja(r,()=>r.createShader(r.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(De(r,()=>r.shaderSource(t,e)),De(r,()=>r.compileShader(t)),r.getShaderParameter(t,r.COMPILE_STATUS)===!1)throw tY(e,r.getShaderInfoLog(t)),new Error("Failed to compile fragment shader.");return t}var rY=/ERROR: [0-9]+:([0-9]+):/g;function tY(r,e){let t=rY.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)=>x.rightPad((m+1).toString(),s)+p),i=0;for(let p=0;pr.createProgram(),"Unable to create WebGLProgram.")}function w$(r,e){if(De(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 Sx(r,e){if(De(r,()=>r.validateProgram(e)),r.getProgramParameter(e,r.VALIDATE_STATUS)===!1)throw console.log(r.getProgramInfoLog(e)),new Error("Shader program validation failed.")}function v$(r,e){let t=ja(r,()=>r.createBuffer(),"Unable to create WebGLBuffer");return De(r,()=>r.bindBuffer(r.ARRAY_BUFFER,t)),De(r,()=>r.bufferData(r.ARRAY_BUFFER,e,r.STATIC_DRAW)),t}function k$(r,e){let t=ja(r,()=>r.createBuffer(),"Unable to create WebGLBuffer");return De(r,()=>r.bindBuffer(r.ELEMENT_ARRAY_BUFFER,t)),De(r,()=>r.bufferData(r.ELEMENT_ARRAY_BUFFER,e,r.STATIC_DRAW)),t}function C$(r){return ja(r,()=>r.createTexture(),"Unable to create WebGLTexture.")}function I$(r,e){let t=W().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 N$(r){return ja(r,()=>r.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function xk(r,e,t,o,n,s,a){let i=r.getAttribLocation(e,t);return i===-1?!1:(De(r,()=>r.bindBuffer(r.ARRAY_BUFFER,o)),De(r,()=>r.vertexAttribPointer(i,n,r.FLOAT,!1,s,a)),De(r,()=>r.enableVertexAttribArray(i)),!0)}function nY(r,e,t){oY(r,t),De(r,()=>r.activeTexture(r.TEXTURE0+t)),De(r,()=>r.bindTexture(r.TEXTURE_2D,e))}function S$(r,e,t){return ja(r,()=>r.getUniformLocation(e,t),'uniform "'+t+'" not present in program.')}function T$(r,e,t){return r.getUniformLocation(e,t)}function E$(r,e,t,o){De(r,()=>nY(r,e,o)),De(r,()=>r.uniform1i(t,o))}function Tx(r,e,t){De(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,t)),De(r,()=>r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,e,0))}function yk(r,e){De(r,()=>r.bindFramebuffer(r.FRAMEBUFFER,e)),De(r,()=>r.framebufferTexture2D(r.FRAMEBUFFER,r.COLOR_ATTACHMENT0,r.TEXTURE_2D,null,0))}function Qd(r){let e=r.checkFramebufferStatus(r.FRAMEBUFFER);if(e!==r.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+sY(r,e))}function sY(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 ja(r,e,t){let o=De(r,()=>e());if(o==null)throw new Error(t);return o}function oY(r,e){let t=r.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,o=e+r.TEXTURE0;if(ot){let n=`[gl.TEXTURE0, gl.TEXTURE${t}]`;throw new Error(`textureUnit must be in ${n}.`)}}function Tl(r,e=2){return x.sizeFromShape(r.slice(0,r.length-e))}function El(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 Ex(r){let e=[1,1,1];return r.length===0||r.length===1&&r[0]===1||(e=[Tl(r),...El(r)]),e}function A$(r,e=!1){let t=W().getNumber("WEBGL_MAX_TEXTURE_SIZE");e&&(t=t*2,r=r.map((n,s)=>s>=r.length-2?x.nearestLargerEven(r[s]):r[s]),r.length===1&&(r=[2,r[0]])),r.length!==2&&(r=x.squeezeShape(r).newShape);let o=x.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=Tl(r),s=2,a=2;return r.length&&([s,a]=El(r)),o=n*(s/2)*(a/2),x.sizeToSquarishShape(o).map(i=>i*2)}return x.sizeToSquarishShape(o)}function Ax(r){return r%2==0}function uc(r,e){if(r=r.slice(-2),e=e.slice(-2),x.arraysEqual(r,e)||!r.length||!e.length||r[0]===0||r[1]===0||e[0]===0||e[1]===0)return!0;if(r.length!==e.length){let t=r.slice(-1)[0],o=e.slice(-1)[0];if(t===o||Ax(t)&&Ax(o)&&(r[0]===1||e[0]===1))return!0}return r[1]===e[1]&&Ax(r[0])&&Ax(e[0])}var bk,_k;function D$(r){if(bk==null){let e=Go(r);bk=e.getParameter(e.MAX_TEXTURE_SIZE)}return bk}function $$(r){if(_k==null){let e=Go(r);_k=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,_k)}function R$(r){if(r===0)return 0;let e,t=Go(r);return Uo(t,"EXT_disjoint_timer_query_webgl2")&&r===2?e=2:Uo(t,"EXT_disjoint_timer_query")?e=1:e=0,e}function Uo(r,e){return r.getExtension(e)!=null}function wk(r){try{if(Go(r)!=null)return!0}catch(e){return console.log("Error when getting WebGL context: ",e),!1}return!1}function F$(r){if(r===0)return!1;let e=Go(r);if(r===1){if(!Uo(e,"OES_texture_float"))return!1}else if(!Uo(e,"EXT_color_buffer_float"))return!1;return vk(e)}function O$(r){if(r===0)return!1;let e=Go(r);if(r===1){if(!Uo(e,"OES_texture_float")||!Uo(e,"WEBGL_color_buffer_float"))return!1}else{if(Uo(e,"EXT_color_buffer_float"))return vk(e);let o="EXT_color_buffer_half_float";if(Uo(e,o)){let n=e.getExtension(o);return iY(e,n)}return!1}return vk(e)}function vk(r){let e=Zd(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 iY(r,e){let t=Zd(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 P$(r){return r!==2?!1:Go(r).fenceSync!=null}function Xi(r,e){Array.isArray(r)||(r=[r]),r.forEach(t=>{t!=null&&x.assert(t.dtype!=="complex64",()=>`${e} does not support complex64 tensors in the WebGL backend.`)})}var We=W();We.registerFlag("HAS_WEBGL",()=>We.getNumber("WEBGL_VERSION")>0);We.registerFlag("WEBGL_VERSION",()=>wk(2)?2:wk(1)?1:0);We.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);We.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>We.get("WEBGL_VERSION")===2);We.registerFlag("WEBGL_CPU_FORWARD",()=>!0);We.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);We.registerFlag("WEBGL_PACK",()=>We.getBool("HAS_WEBGL"));We.registerFlag("WEBGL_PACK_NORMALIZATION",()=>We.getBool("WEBGL_PACK"));We.registerFlag("WEBGL_PACK_CLIP",()=>We.getBool("WEBGL_PACK"));We.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>!1);We.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>We.getBool("WEBGL_PACK"));We.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>We.getBool("WEBGL_PACK"));We.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>We.getBool("WEBGL_PACK"));We.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>We.getBool("WEBGL_PACK"));We.registerFlag("WEBGL_PACK_REDUCE",()=>We.getBool("WEBGL_PACK"));We.registerFlag("WEBGL_LAZILY_UNPACK",()=>We.getBool("WEBGL_PACK"));We.registerFlag("WEBGL_CONV_IM2COL",()=>We.getBool("WEBGL_PACK"));We.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>D$(We.getNumber("WEBGL_VERSION")));We.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>$$(We.getNumber("WEBGL_VERSION")));We.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let r=We.getNumber("WEBGL_VERSION");return r===0?0:R$(r)});We.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>We.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!Vc.isMobile());We.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>F$(We.getNumber("WEBGL_VERSION")));We.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>We.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:We.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));We.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>O$(We.getNumber("WEBGL_VERSION")));We.registerFlag("WEBGL_FENCE_API_ENABLED",()=>P$(We.getNumber("WEBGL_VERSION")));We.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>We.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);We.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 zt(){let r,e,t,o,n,s,a,i,l,u;return W().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 Ls(r,e,t="index"){let o=x.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 Bp(r){let e=x.computeStrides(r).map(t=>t.toString());return` int getFlatIndex(ivec3 coords) { return coords.x * ${e[0]} + coords.y * ${e[1]} + coords.z; } `}var Dx=` 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 kk=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Nl.DENSE;let t=Sl(e),o=zt();this.outputShape=e,this.userCode=` ivec3 outCoordsFromFlatIndex(int index) { ${Ls(["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 Ck=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Nl.DENSE;let t=Sl(e),o=zt();this.outputShape=e,this.userCode=` ivec3 outCoordsFromFlatIndex(int index) { ${Ls(["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 Ik=class{constructor(e){this.variableNames=["A"],this.outTexUsage=Dr.DOWNLOAD;let t=zt();this.outputShape=e,this.userCode=` ${Dx} void main() { float x = getAAtOutCoords(); ${t.output} = encode_float(x); } `}};var Nk=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Dr.DOWNLOAD;let t=zt();this.outputShape=e,this.userCode=` ${Dx} void main() { ivec3 coords = getOutputCoords(); float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z)); ${t.output} = encode_float(x); } `}};var Sk=class{constructor(e,t,o=!1){this.variableNames=["A"];let n=zt(),[s,a]=t;this.outputShape=e;let i="result";o&&(i="floor(result * 255. + 0.5)"),this.userCode=` ${Bp(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 Tk=class{constructor(e,t,o=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let n=zt(),[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=` ${Bp(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 M$(r){let e=zt(),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 y$(r,t)}function L$(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 v$(r,e)}function z$(r){let e=new Uint16Array([0,1,2,2,1,3]);return k$(r,e)}function eh(r,e,t,o,n,s){I$(e,t);let a=C$(r),i=r.TEXTURE_2D;return De(r,()=>r.bindTexture(i,a)),De(r,()=>r.texParameteri(i,r.TEXTURE_WRAP_S,r.CLAMP_TO_EDGE)),De(r,()=>r.texParameteri(i,r.TEXTURE_WRAP_T,r.CLAMP_TO_EDGE)),De(r,()=>r.texParameteri(i,r.TEXTURE_MIN_FILTER,r.NEAREST)),De(r,()=>r.texParameteri(i,r.TEXTURE_MAG_FILTER,r.NEAREST)),De(r,()=>r.texImage2D(i,0,o,e,t,0,n,s,null)),De(r,()=>r.bindTexture(r.TEXTURE_2D,null)),a}function Ek(r){return r.internalFormatFloat}function B$(r,e,t,o){let[n,s]=lc(e,t);return eh(r,n,s,Ek(o),o.textureFormatFloat,r.FLOAT)}function Ak(r){return r.internalFormatHalfFloat}function V$(r,e,t,o){let[n,s]=lc(e,t);return eh(r,n,s,Ak(o),o.textureFormatFloat,o.textureTypeHalfFloat)}function Dk(r){return r.downloadTextureFormat}function W$(r,e,t,o){let[n,s]=lc(e,t);return eh(r,n,s,Dk(o),r.RGBA,r.UNSIGNED_BYTE)}function $k(r){return r.internalFormatPackedFloat}function G$(r,e,t,o){let[n,s]=Ki(e,t);return eh(r,n,s,$k(o),r.RGBA,r.FLOAT)}function Rk(r){return r.internalFormatPackedHalfFloat}function U$(r,e,t,o){let[n,s]=Ki(e,t);return eh(r,n,s,Rk(o),r.RGBA,o.textureTypeHalfFloat)}function j$(r,e,t){let o=0,n=3*4,s=3*4+2*4;return De(r,()=>r.bindBuffer(r.ARRAY_BUFFER,t)),xk(r,e,"clipSpacePos",t,3,s,o)&&xk(r,e,"uv",t,2,s,n)}function q$(r,e,t,o,n,s){De(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),De(r,()=>r.texImage2D(r.TEXTURE_2D,0,l,t,o,0,r.RGBA,i,a)),De(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function H$(r,e,t){De(r,()=>r.bindTexture(r.TEXTURE_2D,e)),t.data instanceof Uint8Array?De(r,()=>r.texImage2D(r.TEXTURE_2D,0,r.RGBA,t.width,t.height,0,r.RGBA,r.UNSIGNED_BYTE,t.data)):De(r,()=>r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,t)),De(r,()=>r.bindTexture(r.TEXTURE_2D,null))}function K$(r,e,t,o){let n=r.createBuffer();De(r,()=>r.bindBuffer(r.PIXEL_PACK_BUFFER,n));let i=4*4*e*t;return De(r,()=>r.bufferData(r.PIXEL_PACK_BUFFER,i,r.STREAM_READ)),De(r,()=>r.readPixels(0,0,t,e,r.RGBA,r.FLOAT,0)),De(r,()=>r.bindBuffer(r.PIXEL_PACK_BUFFER,null)),n}function X$(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 Y$(r,e,t,o){let[n,s]=lc(e,t),a=4,i=new Uint8Array(h$(e*t,a));return De(r,()=>r.readPixels(0,0,n,s,o.downloadTextureFormat,r.UNSIGNED_BYTE,i)),new Float32Array(i.buffer)}function Z$(r,e,t,o,n,s,a,i){let l=r,u=new Float32Array(g$(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 J$(r,e,t){let o=new Float32Array(e*t*4);return De(r,()=>r.readPixels(0,0,t,e,r.RGBA,r.FLOAT,o)),o}var Fk=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];let t=W().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,d$(t,e)):this.gl=Go(t);let o="WEBGL_color_buffer_float",n="EXT_color_buffer_half_float";if(W().getNumber("WEBGL_VERSION")===1){let s="OES_texture_float",a="OES_texture_half_float";if(this.textureFloatExtension=Jd(this.gl,s),Uo(this.gl,a))this.textureHalfFloatExtension=Jd(this.gl,a);else if(W().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(o),Uo(this.gl,n))this.colorBufferHalfFloatExtension=Jd(this.gl,n);else if(W().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(o="EXT_color_buffer_float",Uo(this.gl,o))this.colorBufferFloatExtension=this.gl.getExtension(o);else if(Uo(this.gl,n))this.colorBufferHalfFloatExtension=this.gl.getExtension(n);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=L$(this.gl),this.indexBuffer=z$(this.gl),this.framebuffer=N$(this.gl),this.textureConfig=Zd(this.gl,this.textureHalfFloatExtension)}get debug(){return W().getBool("DEBUG")}dispose(){if(this.disposed)return;this.program!=null&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),this.outputTexture!=null&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");let e=this.gl;De(e,()=>e.finish()),De(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),De(e,()=>e.deleteFramebuffer(this.framebuffer)),De(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),De(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),De(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),B$(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),V$(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),W$(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),H$(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,o,n){this.throwIfDisposed(),q$(this.gl,e,t,o,n,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),U$(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),G$(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(yk(this.gl,this.framebuffer),this.outputTexture=null),De(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,o){return this.downloadMatrixDriver(e,()=>Y$(this.gl,t,o,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,o,n,s,a){return Z$(this.gl,e,t,o,n,s,a,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return X$(this.gl,e,t)}createBufferFromTexture(e,t,o){this.bindTextureToFrameBuffer(e);let n=K$(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(W().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 W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),o=()=>this.isQueryAvailable(t,W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):o=()=>!0;return{query:t,isFencePassed:o}}downloadMatrixFromPackedTexture(e,t,o){return this.downloadMatrixDriver(e,()=>J$(this.gl,t,o))}createProgram(e){this.throwIfDisposed();let t=this.gl,o=b$(t,e),n=M$(t),s=_$(t);return De(t,()=>t.attachShader(s,n)),De(t,()=>t.attachShader(s,o)),w$(t,s),this.debug&&Sx(t,s),this.vertexAttrsAreBound||(this.setProgram(s),this.vertexAttrsAreBound=j$(t,this.program,this.vertexBuffer)),s}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&De(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&Sx(this.gl,this.program),De(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,o=!0){return this.throwIfDisposed(),o?S$(this.gl,e,t):T$(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),De(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(),E$(this.gl,e,t,o)}setOutputMatrixTexture(e,t,o){this.setOutputMatrixTextureDriver(e,o,t)}setOutputPackedMatrixTexture(e,t,o){this.throwIfDisposed();let[n,s]=Ki(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&&Sx(this.gl,this.program),Qd(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();let e=this.gl;this.debug&&this.debugValidate(),De(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),De(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=Jd(this.gl,W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let 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(W().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 x.repeatedTry(()=>this.disposed||this.isQueryAvailable(e,W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(t===0)return null;if(t===2){let 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=aY(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)&&x.repeatedTry(()=>(this.pollItems(),this.itemsToPoll.length===0))}bindTextureToFrameBuffer(e){this.throwIfDisposed(),Tx(this.gl,e,this.framebuffer),this.debug&&Qd(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(Tx(this.gl,this.outputTexture,this.framebuffer),this.debug&&Qd(this.gl)):yk(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;Tx(n,e,this.framebuffer),this.debug&&Qd(n),this.outputTexture=e,De(n,()=>n.viewport(0,0,t,o)),De(n,()=>n.scissor(0,0,t,o))}setOutputMatrixWriteRegionDriver(e,t,o,n){this.throwIfDisposed(),De(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 aY(r){let e=0;for(;e{let h=x.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=>lY(d,e,o)).join(` `),i=e.texShape,l=zt(),u=pY(l),c,p,m=dY(l);return e.isPacked?(c=uY(e.logicalShape,i),p=fY(l)):(c=cY(e.logicalShape,i),p=mY(l)),o&&(m+=hY),[m,u,p,s,c,a,t].join(` `)}function Vp(r){let e=r.shapeInfo.logicalShape;switch(e.length){case 0:return gY(r);case 1:return xY(r);case 2:return yY(r);case 3:return bY(r);case 4:return _Y(r);case 5:return wY(r);case 6:return vY(r);default:throw new Error(`${e.length}-D input sampling is not yet supported`)}}function tR(r){switch(r.shapeInfo.logicalShape.length){case 0:return kY(r);case 1:return CY(r);case 2:return IY(r);case 3:return NY(r);default:return SY(r)}}function lY(r,e,t=!1){let o="";t?o+=tR(r):o+=Vp(r);let n=r.shapeInfo.logicalShape,s=e.logicalShape;return n.length<=s.length&&(t?o+=TY(r,e):o+=EY(r,e)),o}function uY(r,e){switch(r.length){case 0:return rR();case 1:return AY(r,e);case 2:return RY(r,e);case 3:return DY(r,e);default:return $Y(r,e)}}function cY(r,e){switch(r.length){case 0:return rR();case 1:return FY(r,e);case 2:return zY(r,e);case 3:return OY(r,e);case 4:return PY(r,e);case 5:return MY(r,e);case 6:return LY(r,e);default:throw new Error(`${r.length}-D output sampling is not yet supported`)}}function pY(r){return` float sampleTexture(sampler2D textureSampler, vec2 uv) { return ${r.texture2D}(textureSampler, uv).r; } `}function mY(r){return` void setOutput(float val) { ${r.output} = vec4(val, 0, 0, 0); } `}function fY(r){return` void setOutput(vec4 val) { ${r.output} = val; } `}function dY(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); } ${BY} ${VY} ${WY} `}var BY=` 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); } `,VY=` 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); } `,WY=` 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); } `,hY=` 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 rR(){return` int getOutputCoords() { return 0; } `}function AY(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 FY(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 DY(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 OY(r,e){let t=Ls(["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 $Y(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=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=x.sizeFromShape(r.shapeInfo.logicalShape)===1,y=x.sizeFromShape(e.logicalShape)===1;if(s===1&&!h&&!y)f=` return vec4(outputValue.xy, outputValue.xy); `;else if(h&&!y)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 EY(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&&x.arraysEqual(a,s))return` float ${n}() { return sampleTexture(${t}, resultUV); } `;let u=Be(l),c=Q$(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 Be(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 Up(r,e){return e.map(t=>r[t]).join(", ")}function oR(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=eR(s,i,n,e.packedInputs),u=r.createProgram(l),c=null,p=r.getUniformLocation(u,"NAN",!1);W().getNumber("WEBGL_VERSION")===1&&(c=r.getUniformLocation(u,"INFINITY",!1));let m={};for(let f=0;f{let n=t.logicalShape,s=e[o],a=s.shape;if(!x.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(!x.arraysEqual(i,l))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${l} must match`)})}function sR(r,e,t,o,n){nR(e.inShapeInfos,t),nR([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),W().getNumber("WEBGL_VERSION")===1&&e.infLoc!==null&&r.gl.uniform1f(e.infLoc,Infinity),e.nanLoc!==null&&r.gl.uniform1f(e.nanLoc,NaN),t.forEach((i,l)=>{let u=e.program.variableNames[l],c=e.uniformLocations[u],p=e.uniformLocations[`offset${u}`];if(c!=null){if(i.isUniform){if(x.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 iR(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:aR,bincountImpl:$x,bincountReduceImpl:lR,ceilImpl:uR,concatImpl:cR,expImpl:pR,expm1Impl:mR,floorImpl:fR,gatherV2Impl:dR,greaterImpl:hR,lessImpl:gR,linSpaceImpl:xR,logImpl:yR,maxImpl:bR,maximumImpl:_R,minimumImpl:wR,multiplyImpl:vR,negImpl:kR,prodImpl:CR,rangeImpl:IR,rsqrtImpl:NR,simpleAbsImpl:Rx,sliceImpl:SR,stridedSliceImpl:TR,subImpl:ER,tileImpl:AR,topKImpl:DR,transposeImpl:jp,uniqueImpl:$R}=rk;function Ok(r,e){return["x","y","z","w","u","v"].slice(0,e).map(t=>`${r}.${t}`)}function qt(r,e){return e===1?[r]:Ok(r,e)}function RR(r,e){if(r===1)return"rc";let t="";for(let o=0;o ${e[0]}`;let o="";for(let n=r-2;n= ${e[n]}`,n= ${e}; bool rEdge = rp1 >= ${t}; `}function jY(r,e){let t=r.length,o=qY(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 th=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=` ${HY(t)} ${Bp(e)} void main() { ivec3 rc = getOutputCoords(); vec4 result = vec4(0.); ivec3 thisRC; int rows = ${e[1]}; int cols = ${e[2]}; ${o} setOutput(result); } `}};function HY(r){return` ivec3 inputCoordsFromReshapedOutCoords(int index) { ${Ls(["r","c","d"],r)} return ivec3(r, c, d); } `}var Mk=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=OR(t,o),s=PR(e,n,o);s in this.freeTextures||(this.freeTextures[s]=[]),s in this.usedTextures||(this.usedTextures[s]=[]);let a=FR(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===wr.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):n===wr.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):n===wr.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):n===wr.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):n===wr.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=OR(o,n),a=PR(t,s,n);a in this.freeTextures||(this.freeTextures[a]=[]);let i=FR(t,s,this.gpgpu.gl,this.gpgpu.textureConfig,n),l=W().get("WEBGL_DELETE_TEXTURE_THRESHOLD");l!==-1&&this._numBytesAllocated>l?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=i):(this.freeTextures[a].push(e),this.numFreeTextures++,this._numBytesFree+=i),this.numUsedTextures--;let u=this.usedTextures[a],c=u.indexOf(e);if(c<0)throw new Error("Cannot release a texture that was never provided by this texture manager");u.splice(c,1),this.log()}log(){if(!this.logEnabled)return;let e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);let t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures!=null){for(let e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});for(let e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function KY(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 FR(r,e,t,o,n){let s=XY(e,o),a;if(n){let[l,u]=Ki(r[0],r[1]);a=l*u}else{let[l,u]=lc(r[0],r[1]);a=l*u}let i=KY(t,s);return a*i}function XY(r,e){switch(r){case wr.PACKED_2X2_FLOAT32:return $k(e);case wr.PACKED_2X2_FLOAT16:return Rk(e);case wr.UNPACKED_FLOAT32:return Ek(e);case wr.UNPACKED_FLOAT16:return Ak(e);case wr.PACKED_4X1_UNSIGNED_BYTE:return Dk(e);default:throw new Error(`Unknown physical texture type ${r}`)}}function YY(r){return W().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?r?wr.PACKED_2X2_FLOAT32:wr.UNPACKED_FLOAT32:r?wr.PACKED_2X2_FLOAT16:wr.UNPACKED_FLOAT16}function OR(r,e){if(r===Dr.UPLOAD)return wr.PACKED_2X2_FLOAT32;if(r===Dr.RENDER||r==null)return YY(e);if(r===Dr.DOWNLOAD||r===Dr.PIXELS)return wr.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${r}`)}function PR(r,e,t){return`${r[0]}_${r[1]}_${e}_${t}`}var mo=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.userCode=` float unaryOperation(float x) { ${t} } void main() { float x = getAAtOutCoords(); float y = unaryOperation(x); setOutput(y); } `}},xr="if (isnan(x)) return x;",MR="return x;",Lk="return abs(x);";var LR="return (x >= 0.0) ? x : (exp(x) - 1.0);",zR=xr+` return (x < 0.0) ? 0.0 : x; `,BR=xr+` return (x < 0.0) ? 0.0 : min(6.0, x); `,rh="return x;";var VR="return x;",WR=` 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; `,GR=` 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; `,UR=` 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; `,zs=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 zk=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;let t=e.length,o=qt("rc",t),n=Be(t),s=RR(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 ZY=Er.whereImpl,JY=1e-7,QY=1e-4,Fx={};function e7(r){return r in Fx||(Fx[r]={}),Fx[r]}var t7=128,r7=600;function o7(){return W().global.screen==null?1024:W().global.screen.height*W().global.screen.width*window.devicePixelRatio*r7/1024/1024}var Bk=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,!W().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){let t=Go(W().getNumber("WEBGL_VERSION"));this.binaryCache=e7(W().getNumber("WEBGL_VERSION")),this.gpgpu=new Fk(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 Mk(this.gpgpu),this.numMBBeforeWarning=o7(),this.texData=new Ja(this,Cs())}numDataIds(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes}write(e,t,o){if((W().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||W().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:Dr.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--}}move(e,t,o,n){if(W().getBool("DEBUG")&&this.checkNumericalProblems(t),n==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:o,dtype:n,values:t,usage:Dr.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 zs(i,rh):m=new mo(i,rh);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=x.now());let p;if(n==="complex64"){let m=this.readSync(s.real.dataId),f=this.readSync(s.imag.dataId);p=S.mergeRealAndImagArrays(m,f)}else p=this.getValuesFromTexture(e);return u&&(this.downloadWaitMs+=x.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 zs(n,rh):d=new mo(n,rh);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(!W().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&W().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let u=null,c;if(a!=="complex64"&&W().get("WEBGL_BUFFER_SUPPORTED")){c=this.decode(e);let d=this.texData.get(c.dataId);u=this.gpgpu.createBufferFromTexture(d.texture,...Sl(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=S.mergeRealAndImagArrays(h,g)}else if(u==null)p=this.getValuesFromTexture(e);else{let d=x.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=>x.decodeString(n))}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return Ie(e.shape,e.dtype,o)}checkNumericalProblems(e){if(e!=null)for(let t=0;tl.query)).filter(l=>l!=null),a=x.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(W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){let l=await Promise.all(s);i.kernelMs=x.sum(l),i.getExtraProfileInfo=()=>l.map((u,c)=>({name:a[c],ms:u})).map(u=>`${u.name}: ${u.ms}`).join(", ")}else i.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,i}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:x.now(),endMs:null}}endTimer(e){return W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=x.now(),e)}async getQueryTime(e){if(W().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);let t=e;return t.endMs-t.startMs}disposeData(e){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 W().getBool("WEBGL_CPU_FORWARD")?(this.cpuBackend==null&&(this.cpuBackend=Cs().findBackend("cpu")),this.cpuBackend):null}shouldExecuteOnCPU(e,t=t7){let o=this.getCPUBackend();return!W().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&&x.sizeFromShape(n.shape)0&&x.isString(o[0])){let s=o.map(a=>x.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 Cs().makeTensorFromDataId(n,e,t,this)}unpackTensor(e){let t=new zk(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){let t=new Pk(e.shape),o=!0;return this.runWebGLProgram(t,[e],e.dtype,null,o)}packedReshape(e,t){let o=[Tl(e.shape),...El(e.shape)],n={dtype:e.dtype,shape:o,dataId:e.dataId},s=[Tl(t),...El(t)],a=new th(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=Ex(n),i;o?i=new Ck(a):i=new kk(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===Nl.DENSE){let h=Sl(e.outputShape);i.texShape=h.map(g=>g*2)}if(e.outTexUsage!=null&&(i.usage=e.outTexUsage),x.sizeFromShape(a.shape)===0)return i.values=x.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&&x.sizeFromShape(h.shape)<=W().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&&!uc(g.shape,h.shape)){let y=h,b=h.shape;h.shape=g.shape,h=this.packedReshape(h,b),l.push(h),g=this.texData.get(h.dataId),y.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=iR(e,u,c),m=this.getAndSaveBinary(p,()=>oR(this.gpgpu,e,u,c)),f=this.activeTimers!=null,d;if(f&&(d=this.startTimer()),sR(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)})),!W().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 Cs().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||(W().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach(t=>{this.gpgpu.deleteProgram(this.binaryCache[t].webGLProgram),delete this.binaryCache[t]}),this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement!="undefined"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return this.floatPrecisionValue==null&&(this.floatPrecisionValue=V(()=>{if(!W().get("WEBGL_RENDER_FLOAT32_ENABLED")){let e=W().getBool("DEBUG");W().set("DEBUG",!1);let t=this.abs(ce(1e-8)).dataSync()[0];if(W().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?JY:QY}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=x.now());let p=t.texShape;if(p==null&&(p=A$(o,l),t.texShape=p),s!=null){let m=Ex(o),f,d=p[1],h=p[0],g=s instanceof Uint8Array;l?([d,h]=Ki(p[0],p[1]),f=new Tk(m,[h,d],g)):f=new Sk(m,[h,d],g);let y=this.makeTensorInfo([h,d],n);g?this.texData.get(y.dataId).usage=Dr.PIXELS:this.texData.get(y.dataId).usage=Dr.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(y.dataId),d,h,s);let b=!0,_=this.runWebGLProgram(f,[y],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(y),this.texData.delete(_.dataId),t.values=null,u&&(this.uploadWaitMs+=x.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=n7(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]*x.bytesPerElement(t)}};function n7(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;onew Bk,2);var Ox=` if (isnan(a)) return a; if (isnan(b)) return b; `;var ts=class{constructor(e,t,o){this.variableNames=["A","B"],this.outputShape=S.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 Al=` 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 Bs=class{constructor(e,t,o,n=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=S.assertAndGetBroadcastShape(t,o);let s=this.outputShape.length,a="";if(n)if(s===0||x.sizeFromShape(this.outputShape)===1)a=` result.y = 0.; result.z = 0.; result.w = 0.; `;else if(a=` ${Be(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=qt("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 Ht(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 qR={kernelName:cs,backendName:"webgl",kernelFunc:Ht};function fo(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=Ht({inputs:{x:o},backend:t}),l=t.texData.get(i.dataId);l.complexParentRefCount++;let u=Ht({inputs:{x:n},backend:t}),c=t.texData.get(u.dataId);return c.complexParentRefCount++,a.complexTensorInfos={real:i,imag:u},s}var HR={kernelName:Xl,backendName:"webgl",kernelFunc:fo};var Vk="return (a < 0.) ? b * a : a;",Wk=` vec4 aLessThanZero = vec4(lessThan(a, vec4(0.))); return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); `;function s7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{alpha:s}=o,a=t.makeTensorInfo([],"float32",x.createScalarValue(s,"float32")),i=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bs(Wk,n.shape,a.shape):new ts(Vk,n.shape,a.shape),l=t.runWebGLProgram(i,[n,a],n.dtype);return t.disposeIntermediateTensorInfo(a),l}var KR={kernelName:un,backendName:"webgl",kernelFunc:s7};var Gk="return (a < 0.) ? b * a : a;",Uk=` vec4 aLessThanZero = vec4(lessThan(a, vec4(0.))); return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); `;function i7(r){let{inputs:e,backend:t}=r,{x:o,alpha:n}=e,s=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bs(Uk,o.shape,n.shape):new ts(Gk,o.shape,n.shape);return t.runWebGLProgram(s,[o,n],o.dtype)}var XR={kernelName:wn,backendName:"webgl",kernelFunc:i7};var Px="if (isnan(x)) return x;",YR=` if (isnan(a)) return a; if (isnan(b)) return b; `,ZR=` 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 Ce({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=W().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&e!=null,c;return u?c=new zs(a.shape,e):c=new mo(a.shape,r),i.runWebGLProgram(c,[a],l)}}function at({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,y]=[[d.complexTensorInfos.real,h.complexTensorInfos.real],[d.complexTensorInfos.imag,h.complexTensorInfos.imag]].map(_=>{let[w,k]=_,$={dataId:w.dataId,dtype:w.dtype,shape:l.shape},T={dataId:k.dataId,dtype:k.dtype,shape:u.shape},F=new ts(r,l.shape,u.shape);return c.runWebGLProgram(F,[$,T],fr(w.dtype,k.dtype))}),b=fo({inputs:{real:g,imag:y},backend:c});return c.disposeIntermediateTensorInfo(g),c.disposeIntermediateTensorInfo(y),b}let p=s||fr(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,y]=n(l.shape,u.shape,d.values,h.values,p),b=c.makeTensorInfo(y,p),_=c.texData.get(b.dataId);return _.values=g,b}let m=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&e!=null,f;return m?f=new Bs(e,l.shape,u.shape,t):f=new ts(r,l.shape,u.shape),c.runWebGLProgram(f,[l,u],p)}}function Dl(r,e=!1){if(r==="linear")return e?VR:MR;if(r==="relu")return e?GR:zR;if(r==="elu")return e?WR:LR;if(r==="relu6")return e?UR:BR;if(r==="prelu")return e?Uk:Gk;if(r==="leakyrelu")return e?Wk:Vk;throw new Error(`Activation ${r} has not been implemented for the WebGL backend.`)}var oh=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="",y="";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} }`,y="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]`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&&!uc(n.shape,l)&&!(c.texture!==null&&uc(c.shape,l))?eF(n,l,a):(a.incRef(n.dataId),{dataId:n.dataId,shape:l,dtype:n.dtype})}var tF={kernelName:ds,backendName:"webgl",kernelFunc:me};var Lx=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 * ${x.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 Hk=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 a7(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=S.computeOptimalWindowSize(t);e.push({inSize:t,windowSize:o,outSize:Math.ceil(t/o)})}return e}function So(r,e,t,o){let n=a7(r.shape),s=r;for(let a=0;a6)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;n6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let n=Be(this.rank),s=Ok("rc",this.rank),a=new Array(this.rank);for(let c=0;c=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 k=(y>b?r.shape.slice(0,-2):e.shape.slice(0,-2)).concat([f,d]);x.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?[y,p,f]:[y,f,p],T=o?[b,d,m]:[b,m,d],F=me({inputs:{x:r},backend:n,attrs:{shape:$}}),M=me({inputs:{x:e},backend:n,attrs:{shape:T}}),L=[F,M],G=Math.max(y,b),H=t?F.shape[1]:F.shape[2],U=s!=null,Z=a!=null,K=l==="leakyrelu",X=l!=null?Dl(l,!0):null,oe=U||Z||K||X!=null,J;if((f===1||d===1)&&H>Yk&&oe===!1){let ie=F,ae=M;t&&(ie=Bt({inputs:{x:F},backend:n,attrs:{perm:[0,2,1]}}),L.push(ie)),o&&(ae=Bt({inputs:{x:M},backend:n,attrs:{perm:[0,2,1]}}),L.push(ae));let ue=d!==1,le=d===1,ge=ie;ue&&(ge=me({inputs:{x:ie},backend:n,attrs:{shape:[G,H,1]}}),L.push(ge));let we=d===1?2:1,ye=ae;le&&(ye=me({inputs:{x:ae},backend:n,attrs:{shape:[G,1,H]}}),L.push(ye));let ke=qk({inputs:{a:ge,b:ye},backend:n});J=nh({inputs:{x:ke},backend:n,attrs:{axis:we,keepDims:!0}}),L.push(ke)}else{let ie=fr(r.dtype,e.dtype),ae=new oh($,T,[G,f,d],t,o,U,X,Z,K),ue=[F,M];if(s!=null&&ue.push(s),Z&&ue.push(a),K){let le=n.makeTensorInfo([],"float32",x.createScalarValue(i,"float32"));ue.push(le),L.push(le)}J=n.runWebGLProgram(ae,ue,ie)}let Q=me({inputs:{x:J},backend:n,attrs:{shape:k}});L.push(J);for(let ie of L)n.disposeIntermediateTensorInfo(ie);return Q}function u7(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 pc({a:n,b:s,transposeA:l,transposeB:u,backend:t,bias:a,preluActivationWeights:i,leakyreluAlpha:p,activation:c})}var sF={kernelName:_s,backendName:"webgl",kernelFunc:u7};var iF="return abs(x);";function c7(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=Rx(s.values);return t.makeTensorInfo(o.shape,o.dtype,a)}let n;return W().getBool("WEBGL_PACK_UNARY_OPERATIONS")?n=new zs(o.shape,iF):n=new mo(o.shape,iF),t.runWebGLProgram(n,[o],o.dtype)}var aF={kernelName:is,backendName:"webgl",kernelFunc:c7};var p7=xr+` if (abs(x) > 1.) { return NAN; } return acos(x); `,m7=Ce({opSnippet:p7}),lF={kernelName:js,backendName:"webgl",kernelFunc:m7};var f7=xr+` if (x < 1.0) return NAN; return log(x + sqrt(x * x - 1.0));`,d7=Ce({opSnippet:f7}),uF={kernelName:qs,backendName:"webgl",kernelFunc:d7};var cF="return a + b;",h7=at({opSnippet:cF,packedOpSnippet:cF,supportsComplex:!0,cpuKernelImpl:aR}),pF={kernelName:bo,backendName:"webgl",kernelFunc:h7};var Zk=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 Jk=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 zx(r){let{inputs:e,backend:t}=r,o=e;if(o.length===1)return Ht({inputs:{x:o[0]},backend:t});if(o.length>W().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let l=Math.floor(o.length/2),u=zx({inputs:o.slice(0,l),backend:t}),c=zx({inputs:o.slice(l),backend:t});return zx({inputs:[u,c],backend:t})}let n=o.map(l=>l.dtype).reduce((l,u)=>fr(l,u)),s=o.map(l=>l.shape),i=W().getBool("WEBGL_PACK")?new Jk(o[0].shape,s):new Zk(o[0].shape,s);return t.runWebGLProgram(i,o,n)}var mF={kernelName:Ho,backendName:"webgl",kernelFunc:zx};function g7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o,i=n.shape.length,l=x.parseAxisParam(s,n.shape),u=l,c=S.getAxesPermutation(u,i),p=n;c!=null&&(p=Bt({inputs:{x:n},backend:t,attrs:{perm:c}}),u=S.getInnerMostAxes(u.length,i)),S.assertAxesAreInnerMostDims("all",u,i);let[m,f]=S.computeOutAndReduceShapes(p.shape,u),d=x.sizeFromShape(f),h=me({inputs:{x:p},backend:t,attrs:{shape:[-1,d]}}),g=So(h,h.dtype,"all",t),y;if(a){let b=S.expandShapeToKeepDim(m,l);y=me({inputs:{x:g},backend:t,attrs:{shape:b}})}else y=me({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),c!=null&&t.disposeIntermediateTensorInfo(p),y}var fF={kernelName:Ul,backendName:"webgl",kernelFunc:g7};function x7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o,i=n.shape.length,l=x.parseAxisParam(s,n.shape),u=l,c=S.getAxesPermutation(u,i),p=n;c!=null&&(p=Bt({inputs:{x:n},backend:t,attrs:{perm:c}}),u=S.getInnerMostAxes(u.length,i)),S.assertAxesAreInnerMostDims("any",u,i);let[m,f]=S.computeOutAndReduceShapes(p.shape,u),d=x.sizeFromShape(f),h=me({inputs:{x:p},backend:t,attrs:{shape:[-1,d]}}),g=So(h,h.dtype,"any",t),y;if(a){let b=S.expandShapeToKeepDim(m,l);y=me({inputs:{x:g},backend:t,attrs:{shape:b}})}else y=me({inputs:{x:g},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(h),t.disposeIntermediateTensorInfo(g),c!=null&&t.disposeIntermediateTensorInfo(p),y}var dF={kernelName:jl,backendName:"webgl",kernelFunc:x7};var Qk=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 eC=class{constructor(e,t,o,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,x.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=Be(l),c=qt("coords",l),p,m;if(a===1){m=l+1;let F=Be(m);p=` ${F} sourceLocR = ${F}(${c.join()}, 0); ++${c[l-1]}; ${F} sourceLocG = ${F}(${c.join()}, 0); ++${c[l-2]}; ${F} sourceLocA = ${F}(${c.join()}, 0); --${c[l-1]}; ${F} sourceLocB = ${F}(${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(F=>"int "+F),g=qt("sourceLocR",m-1).concat("inIdx.r"),y=qt("sourceLocG",m-1).concat("inIdx.g"),b=qt("sourceLocB",m-1).concat("inIdx.b"),_=qt("sourceLocA",m-1).concat("inIdx.a"),w=o==="max"?"greaterThan":"lessThan",k=n?"":` inIdx = round(vec4(getBestIndicesAChannel(${g.join()}), getBestIndicesAChannel(${y.join()}), getBestIndicesAChannel(${b.join()}), getBestIndicesAChannel(${_.join()})));`,$=`vec4( getAChannel(${g.join()}), hasNextCol ? getAChannel(${y.join()}) : 0., hasNextRow ? getAChannel(${b.join()}) : 0., hasNextRow && hasNextCol ? getAChannel(${_.join()}) : 0.)`,T=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()})); } ${T} 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; ${k} 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 hF(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=S.computeOptimalWindowSize(s),i={windowSize:a,inSize:s,batchSize:n,outSize:Math.ceil(s/a)},l=new Qk(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=hF(r,e,t,c);return r.disposeIntermediateTensorInfo(c),p}function gF(r,e,t,o=null){let n=o!=null?o.shape:e.shape,s=n[n.length-1],a=S.computeOptimalWindowSize(s),i=new eC(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=gF(r,e,t,u);return r.disposeIntermediateTensorInfo(u),c}return u}function Bx(r,e,t,o){let n=[t];if(S.assertAxesAreInnerMostDims("arg"+o.charAt(0).toUpperCase()+o.slice(1),n,e.shape.length),!W().getBool("WEBGL_PACK_REDUCE")||e.shape.length<=2){let s=[],[a,i]=S.computeOutAndReduceShapes(e.shape,n),l=x.sizeFromShape(i),u=me({inputs:{x:e},backend:r,attrs:{shape:[-1,l]}});s.push(u);let c=hF(r,u,o);s.push(c);let p=me({inputs:{x:c},backend:r,attrs:{shape:a}});return s.forEach(m=>r.disposeIntermediateTensorInfo(m)),p}return gF(r,e,o)}function y7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s}=o,a=x.parseAxisParam(s,n.shape),i=S.getAxesPermutation(a,n.shape.length),l=n,u=[];i!=null&&(l=Bt({inputs:{x:n},backend:t,attrs:{perm:i}}),u.push(l),a=S.getInnerMostAxes(a.length,l.shape.length)),S.assertAxesAreInnerMostDims("argMax",[a[0]],l.shape.length);let c=Bx(t,l,a[0],"max");return u.forEach(p=>t.disposeIntermediateTensorInfo(p)),c}var xF={kernelName:Ko,backendName:"webgl",kernelFunc:y7};function b7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s}=o,a=x.parseAxisParam(s,n.shape),i=S.getAxesPermutation(a,n.shape.length),l=n,u=[];i!=null&&(l=Bt({inputs:{x:n},backend:t,attrs:{perm:i}}),u.push(l),a=S.getInnerMostAxes(a.length,l.shape.length)),S.assertAxesAreInnerMostDims("argMin",[a[0]],l.shape.length);let c=Bx(t,l,a[0],"min");return u.forEach(p=>t.disposeIntermediateTensorInfo(p)),c}var yF={kernelName:oa,backendName:"webgl",kernelFunc:b7};var _7=xr+` if (abs(x) > 1.) { return NAN; } return asin(x); `,w7=Ce({opSnippet:_7}),bF={kernelName:Hs,backendName:"webgl",kernelFunc:w7};var v7=xr+"return log(x + sqrt(x * x + 1.0));",k7=Ce({opSnippet:v7}),_F={kernelName:Ks,backendName:"webgl",kernelFunc:k7};var C7=xr+` return atan(x); `,I7=Ce({opSnippet:C7}),wF={kernelName:Xs,backendName:"webgl",kernelFunc:I7};var N7=YR+` return atan(a, b); `,S7=` vec4 result = atan(a, b); vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0)); `+ZR+` return result; `,T7=at({opSnippet:N7,packedOpSnippet:S7}),vF={kernelName:Zs,backendName:"webgl",kernelFunc:T7};var E7=xr+` if ((x < -1.0) || (x > 1.0)) return NAN; return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,A7=Ce({opSnippet:E7}),kF={kernelName:Ys,backendName:"webgl",kernelFunc:A7};var Yi=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`,y=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`,b="0.0";if(h||(b="-1.0 / 1e-20"),o){let F=">=";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 ${F} currMinMaxValue) { minMaxValue = value; minMaxValueFound = 1.0; minMaxPosition = ${n?s?g:y:`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 k=Math.floor(a/4)*4,$=a%4,T=` 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 < ${k}; 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) ); ${T} } int xC = xCCorner + ${k}; if (${$===1}) { vec4 values = vec4( getValue(batch, xR, xC, d), initializationValue, initializationValue, initializationValue ); ${T} } else if (${$===2}) { vec4 values = vec4( getValue(batch, xR, xC, d), getValue(batch, xR, xC + ${c}, d), initializationValue, initializationValue ); ${T} } 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 ); ${T} } } setOutput(${w}); } `}},mc=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,y=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 L=">=";this.userCode=` const ivec3 strides = ivec3(${i}, ${l}, ${u}); const ivec3 pads = ivec3(${g}, ${y}, ${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 ${L} 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 k="max",$=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&($="avgValue / count");let T=Math.floor(a/4)*4,F=a%4,M=` if (${_}) { avgValue += dot(values, ones); } else { minMaxValue = ${k}(values, minMaxValue); } `;this.userCode=` const ivec3 strides = ivec3(${i}, ${l}, ${u}); const ivec3 pads = ivec3(${g}, ${y}, ${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 < ${T}; 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 + ${T}; if (${F===1}) { vec4 values = vec4( getValue(batch, xD, xR, xC, ch), initializationValue, initializationValue, initializationValue ); ${M} } else if (${F===2}) { vec4 values = vec4( getValue(batch, xD, xR, xC, ch), getValue(batch, xD, xR, xC + ${m}, ch), initializationValue, initializationValue ); ${M} } else if (${F===3}) { vec4 values = vec4( getValue(batch, xD, xR, xC, ch), getValue(batch, xD, xR, xC + ${m}, ch), getValue(batch, xD, xR, xC + 2 * ${m}, ch), initializationValue ); ${M} } } setOutput(${$}); } } `}};function D7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e;Xi(n,"avgPool");let{filterSize:s,strides:a,pad:i,dimRoundingMode:l}=o,u=1;x.assert(S.eitherStridesOrDilationsAreOne(a,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let c=S.computePool2DInfo(n.shape,s,a,u,i,l);if(c.filterWidth===1&&c.filterHeight===1&&x.arraysEqual(c.inShape,c.outShape))return Ht({inputs:{x:n},backend:t});let p=new Yi(c,"avg",!1);return t.runWebGLProgram(p,[n],"float32")}var CF={kernelName:Xo,backendName:"webgl",kernelFunc:D7};function $7(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=S.computePool3DInfo(n.shape,s,a,c,i,l,u),m=new mc(p,"avg",!1);return t.runWebGLProgram(m,[n],"float32")}var IF={kernelName:na,backendName:"webgl",kernelFunc:$7};var tC=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); } `}},rC=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,y=1/(t*o*n);this.userCode=` const ivec3 pads = ivec3(${d}, ${h}, ${g}); const float avgMultiplier = float(${y}); 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 R7(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=S.computePool3DInfo(a.shape,i,l,p,u,c),f=new rC(m);return t.runWebGLProgram(f,[n],a.dtype)}var NF={kernelName:Hl,backendName:"webgl",kernelFunc:R7};function F7(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s}=e,a=s;Xi([n,s],"avgPoolGrad");let{filterSize:i,strides:l,pad:u}=o,c=S.computePool2DInfo(a.shape,i,l,1,u),p=new tC(c);return t.runWebGLProgram(p,[n],a.dtype)}var SF={kernelName:ql,backendName:"webgl",kernelFunc:F7};function O7(r){let{inputs:e,backend:t,attrs:o}=r,{a:n,b:s}=e,{transposeA:a,transposeB:i}=o;return pc({a:n,b:s,transposeA:a,transposeB:i,backend:t})}var TF={kernelName:Yo,backendName:"webgl",kernelFunc:O7};var oC=class{constructor(e,t,o,n,s,a){this.outputShape=[],this.variableNames=["x","mean","variance"],S.assertAndGetBroadcastShape(e,t),S.assertAndGetBroadcastShape(e,o);let i="0.0";n!=null&&(S.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let l="1.0";s!=null&&(S.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 nC=class{constructor(e,t,o,n,s,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],S.assertAndGetBroadcastShape(e,t),S.assertAndGetBroadcastShape(e,o);let i="vec4(0.0)";n!=null&&(S.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let l="vec4(1.0)";s!=null&&(S.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 P7=({inputs:r,backend:e,attrs:t})=>{let{x:o,mean:n,variance:s,offset:a,scale:i}=r;x.assert(n.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),x.assert(a==null||n.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),x.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=W().getBool("WEBGL_PACK_NORMALIZATION")?new nC(o.shape,n.shape,s.shape,c,p,l):new oC(o.shape,n.shape,s.shape,c,p,l);return e.runWebGLProgram(m,u,u[0].dtype)},EF={kernelName:an,backendName:"webgl",kernelFunc:P7};var sC=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=Be(this.rank),o=`uniform int start[${this.rank}];`,n=M7(this.rank),s,a=e.map((i,l)=>`sourceLoc.${iC[l]} = start[${l}] + coords.${iC[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)}}},iC=["x","y","z","w","u","v"];function M7(r){if(r===1)return"sourceLoc";if(r<=6)return iC.slice(0,r).map(e=>"sourceLoc."+e).join(",");throw Error(`Slicing for rank ${r} is not yet supported`)}var aC=class{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;let t=Be(this.rank),o=qt("coords",this.rank),n=qt("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 L7(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.shape=t,a.dtype=r.dtype;let i=sr.computeFlatOffset(e,x.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 qa(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{begin:s,size:a}=o,[i,l]=sr.parseSliceParams(n,s,a);if(sr.assertParamsValid(n,i,l),x.sizeFromShape(l)===0)return t.makeTensorInfo(l,n.dtype,[]);if(t.shouldExecuteOnCPU([n])||n.dtype==="string"){let p=t.texData.get(n.dataId),m=SR(p.values,i,l,n.shape,n.dtype);return t.makeTensorInfo(l,n.dtype,m)}let{isPacked:u}=t.texData.get(n.dataId),c=sr.isSliceContinous(n.shape,i,l);if(u||!c){let p=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new aC(l):new sC(l),m=p.getCustomSetupFunc(i);return t.runWebGLProgram(p,[n],n.dtype,m)}return t.uploadToGPU(n.dataId),L7(n,i,l,t)}var AF={kernelName:gs,backendName:"webgl",kernelFunc:qa};var z7=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockShape:s,crops:a}=o;x.assert(n.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let i=s.reduce((b,_)=>b*_),l=S.getReshaped(n.shape,s,i),u=S.getPermuted(l.length,s.length),c=S.getReshapedPermuted(n.shape,s,i),p=S.getSliceBeginCoords(a,s.length),m=S.getSliceSize(c,a,s.length),f=[],d=me({inputs:{x:n},backend:t,attrs:{shape:l}}),h=Bt({inputs:{x:d},backend:t,attrs:{perm:u}}),g=me({inputs:{x:h},backend:t,attrs:{shape:c}}),y=qa({inputs:{x:g},backend:t,attrs:{begin:p,size:m}});return f.push(d),f.push(h),f.push(g),f.forEach(b=>t.disposeIntermediateTensorInfo(b)),y},DF={kernelName:sa,backendName:"webgl",kernelFunc:z7};function B7(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=$x(i,l,s.dtype,s.shape,a);return t.makeTensorInfo([a],s.dtype,u)}var $F={kernelName:Kl,backendName:"webgl",kernelFunc:B7};var V7="return float(a != b);",lC=at({opSnippet:V7,dtype:"bool"}),RF={kernelName:xi,backendName:"webgl",kernelFunc:lC};function Ha(r){let{inputs:e,backend:t}=r,{input:o}=e,n=t.texData.get(o.dataId);return Ht({inputs:{x:n.complexTensorInfos.real},backend:t})}var FF={kernelName:fu,backendName:"webgl",kernelFunc:Ha};var W7="return float(int(x));";function OF(r,e){let t=new mo(r.shape,W7),o=e.runWebGLProgram(t,[r],"int32");return{dataId:o.dataId,shape:o.shape,dtype:o.dtype}}function uC(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{dtype:s}=o;if(s==="complex64"){if(n.dtype==="complex64")return Ht({inputs:{x:n},backend:t});let a=pt(n.shape),i=uC({inputs:{x:n},backend:t,attrs:{dtype:"float32"}}),l=fo({inputs:{real:i,imag:a},backend:t});return a.dispose(),t.disposeIntermediateTensorInfo(i),l}if(n.dtype==="complex64"){let a=Ha({inputs:{input:n},backend:t}),i=uC({inputs:{x:a},backend:t,attrs:{dtype:s}});return t.disposeIntermediateTensorInfo(a),i}if(!x.hasEncodingLoss(n.dtype,s)){let a=Ht({inputs:{x:n},backend:t});return{dataId:a.dataId,shape:a.shape,dtype:s}}if(s==="int32")return OF(n,t);if(s==="bool"){let a=t.makeTensorInfo([],"bool",x.getTypedArrayFromDType("bool",1)),l=lC({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 PF={kernelName:Fo,backendName:"webgl",kernelFunc:uC};var MF="return ceil(x);",G7=Ce({opSnippet:MF,packedOpSnippet:MF,cpuKernelImpl:uR}),LF={kernelName:Js,backendName:"webgl",kernelFunc:G7};var cC=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 pC=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 U7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{clipValueMin:s,clipValueMax:a}=o,i;W().getBool("WEBGL_PACK_CLIP")?i=new pC(n.shape):i=new cC(n.shape);let l=i.getCustomSetupFunc(s,a);return t.runWebGLProgram(i,[n],n.dtype,l)}var zF={kernelName:Oo,backendName:"webgl",kernelFunc:U7};var mC=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 BF(r,e){return{dataId:e.dataId,dtype:e.dtype,shape:r.shape}}function j7(r){let{inputs:e,backend:t}=r,{x:o}=e,n=t.texData.get(o.dataId),s=new mC(o.shape),a=[BF(o,n.complexTensorInfos.real),BF(o,n.complexTensorInfos.imag)];return t.runWebGLProgram(s,a,a[0].dtype)}var VF={kernelName:ia,backendName:"webgl",kernelFunc:j7};var fC=class{constructor(e){this.outputShape=[],this.outputShape=S.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${g}`);let l=new Array(e.length-1);l[0]=e[0][t];for(let h=1;h= ${l[h-1]}) { return getChannel( getT${h}(${Vx(i,u,g)}), vec2(${Vx(c,u,g)})); }`}let f=l.length,d=l[l.length-1];m+=` return getChannel( getT${f}(${Vx(i,u,d)}), vec2(${Vx(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 Vx(r,e,t){let o=r.indexOf(e);return r.map((s,a)=>a===o?`${s} - ${t}`:s).join()}function fc(r){let{inputs:e,backend:t}=r,{input:o}=e,n=t.texData.get(o.dataId);return Ht({inputs:{x:n.complexTensorInfos.imag},backend:t})}var WF={kernelName:iu,backendName:"webgl",kernelFunc:fc};function dc(r,e,t){let o=r[0].dtype;if(o==="complex64"){let u=r.map(d=>Ha({inputs:{input:d},backend:t})),c=r.map(d=>fc({inputs:{input:d},backend:t})),p=dc(u,e,t),m=dc(c,e,t),f=fo({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}=GF(r,e,t),p=u.map(g=>({vals:t.readSync(g.dataId),shape:g.shape})),m=u[0].shape[0]===1,f=cR(p,c,o,m),d=S.computeOutShape(r.map(g=>g.shape),e),h=t.makeTensorInfo(d,o,f);return u.forEach(g=>t.disposeIntermediateTensorInfo(g)),h}if(r.length>W().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let u=Math.floor(r.length/2),c=dc(r.slice(0,u),e,t),p=dc(r.slice(u),e,t),m=dc([c,p],e,t);return t.disposeIntermediateTensorInfo(c),t.disposeIntermediateTensorInfo(p),m}if(W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&r[0].shape.length>1){let u=new dC(r.map(c=>c.shape),e);return t.runWebGLProgram(u,r,o)}let{tensors2D:n,outShape:s}=GF(r,e,t),a=new fC(n.map(u=>u.shape)),i=t.runWebGLProgram(a,n,o);n.forEach(u=>t.disposeIntermediateTensorInfo(u));let l=me({inputs:{x:i},attrs:{shape:s},backend:t});return t.disposeIntermediateTensorInfo(i),l}function GF(r,e,t){let o=S.computeOutShape(r.map(s=>s.shape),e);return{tensors2D:r.map(s=>me({inputs:{x:s},attrs:{shape:[-1,x.sizeFromShape(s.shape.slice(e))]},backend:t})),outShape:o}}function hC(r){let{inputs:e,backend:t,attrs:o}=r,{axis:n}=o,s=x.parseAxisParam(n,e[0].shape)[0],a=S.computeOutShape(e.map(u=>u.shape),s);if(x.sizeFromShape(a)===0)return t.makeTensorInfo(a,e[0].dtype,[]);let i=e.filter(u=>x.sizeFromShape(u.shape)>0);if(i.length===1)return Ht({inputs:{x:i[0]},backend:t});let l=i.map(u=>u.shape);return S.assertParamsConsistent(l,s),dc(i,s,t)}var UF={kernelName:as,backendName:"webgl",kernelFunc:hC};var sh=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",y=g?1:2,b=g?2:3,_=g?3:1,w="",k="";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} } `,k="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[${y}], 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; ${$} ${k} setOutput(result); } `}},gC=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 xC=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=zt(),y=m==="channelsLast",b=y?0:1,_=y?1:2,w="";for(let k=0;k<=1;k++)for(let $=0;$<=1;$++)w+=` blockIndex = rc.y + ${$}; pos = rc.x + ${k}; 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 (${y}) { innerDims = vec2(d1, ch); result[${k*2+$}] = getChannel( getA(d0, int(innerDims.x), int(innerDims.y)), innerDims); } else { innerDims = vec2(d0, d1); result[${k*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,y=[],b=(p===1||m===1)&&c>Yk,_=l[2]%2!=0&&!!u.isPacked;if(b||!W().getBool("WEBGL_LAZILY_UNPACK")||!W().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!_){let w=f?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],k=me({inputs:{x:r},backend:o,attrs:{shape:[1,w,t.inChannels]}}),$=me({inputs:{x:e},backend:o,attrs:{shape:[1,t.inChannels,t.outChannels]}}),T=pc({a:k,b:$,transposeA:d,transposeB:h,backend:o,bias:n,activation:i,preluActivationWeights:s,leakyreluAlpha:a});g=me({inputs:{x:T},backend:o,attrs:{shape:t.outShape}}),y.push(k),y.push($),y.push(T)}else{let w=f?l[0]*l[1]*(l[2]+1):l[0]*l[2]*(l[3]+1),k={dataId:r.dataId,shape:[1,w,t.inChannels],dtype:r.dtype},$=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,x.assert(uc(u.shape,k.shape),()=>`packed reshape ${u.shape} to ${k.shape} isn't free`);let T=me({inputs:{x:e},backend:o,attrs:{shape:[1,t.inChannels,t.outChannels]}});y.push(T);let F=pc({a:k,b:T,backend:o,transposeA:d,transposeB:h,bias:n,activation:i,preluActivationWeights:s,leakyreluAlpha:a}),M=o.texData.get(F.dataId);x.assert(M.isPacked,()=>"batchMatMul result is expected to be packed"),u.shape=$,M.shape=t.outShape,g=Ht({inputs:{x:F},backend:o}),g.shape=t.outShape,y.push(F)}for(let w of y)o.disposeIntermediateTensorInfo(w);return g}function Gx({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,y=[h,g],b=!0,_=!1,w=[],k=me({inputs:{x:r},backend:o,attrs:{shape:r.shape.slice(1)}}),$=me({inputs:{x:e},backend:o,attrs:{shape:[1,h,x.sizeFromShape(e.shape)/h]}});w.push(k),w.push($);let T=new xC(y,k.shape,t),F=o.runWebGLProgram(T,[k],"float32"),M=me({inputs:{x:F},backend:o,attrs:{shape:[1,y[0],y[1]]}});w.push(F),w.push(M);let L=n!=null,G=s!=null,H=i==="leakyrelu",U=i?Dl(i,!0):null,Z=new oh(M.shape,$.shape,[1,g,t.outChannels],b,_,L,U,G,H),K=[M,$];if(n&&K.push(n),G&&K.push(s),H){let Q=o.makeTensorInfo([],"float32",x.createScalarValue(a,"float32"));K.push(Q),w.push(Q)}let X=o.runWebGLProgram(Z,K,"float32"),oe=d?[1,m,p,t.outChannels]:[1,t.outChannels,m,p],J=me({inputs:{x:X},backend:o,attrs:{shape:oe}});w.push(X);for(let Q of w)o.disposeIntermediateTensorInfo(Q);return J}function q7(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=S.convertConv2DDataFormat(l),m=S.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(W().getBool("WEBGL_CONV_IM2COL")&&n.shape[0]===1)f=Gx({x:n,filter:s,convInfo:m,backend:t});else{let h=new sh(m);f=t.runWebGLProgram(h,[n,s],"float32")}let d=me({inputs:{x:f},backend:t,attrs:{shape:m.outShape}});return t.disposeIntermediateTensorInfo(f),d}var jF={kernelName:Zo,backendName:"webgl",kernelFunc:q7};var yC=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); } `}},bC=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); } `}},_C=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); } `}},wC=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 H7(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=S.convertConv2DDataFormat(l),m=S.computeConv2DInfo(n.shape,c,a,1,i,u,!1,p),f=new yC(m);return t.runWebGLProgram(f,[n,s],"float32")}var qF={kernelName:Yl,backendName:"webgl",kernelFunc:H7};function K7(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=S.convertConv2DDataFormat(u),m=S.computeConv2DInfo(a,s.shape,i,1,l,c,!1,p),f=new bC(m);return t.runWebGLProgram(f,[n,s],"float32")}var HF={kernelName:Jo,backendName:"webgl",kernelFunc:K7};function X7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dilations:l}=o,u=S.computeConv3DInfo(n.shape,s.shape,a,l,i),c=new gC(u);return t.runWebGLProgram(c,[n,s],"float32")}var KF={kernelName:aa,backendName:"webgl",kernelFunc:X7};function Y7(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,dy:s}=e,{strides:a,pad:i,filterShape:l}=o,u=S.computeConv3DInfo(n.shape,l,a,1,i),c=new _C(u);return t.runWebGLProgram(c,[n,s],"float32")}var XF={kernelName:Zl,backendName:"webgl",kernelFunc:Y7};function Z7(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,filter:s}=e,{pad:a,strides:i,inputShape:l}=o,u=S.computeConv3DInfo(l,s.shape,i,1,a),c=new wC(u);return t.runWebGLProgram(c,[n,s],"float32")}var YF={kernelName:Jl,backendName:"webgl",kernelFunc:Z7};var J7=Px+` return cos(x); `,Q7=Ce({opSnippet:J7}),ZF={kernelName:Qo,backendName:"webgl",kernelFunc:Q7};var eZ=` float e2x = exp(-x); return (e2x + 1.0 / e2x) / 2.0; `,tZ=Ce({opSnippet:eZ}),JF={kernelName:Qs,backendName:"webgl",kernelFunc:tZ};var vC=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,y,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,k]=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 = ${y}; float width_scale = ${w}; float in_y = ${b}; if( in_y < 0.0 || in_y > ${d} ) { setOutput(float(${s})); return; } float in_x = ${k}; 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 rZ=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 vC(n.shape,s.shape,i,l,u);return t.runWebGLProgram(c,[n,s,a],"float32")},QF={kernelName:ei,backendName:"webgl",kernelFunc:rZ};var Ux=class{constructor(e,t,o){this.variableNames=["x"],this.outputShape=e;let n=e.length,s=t?"0.0":`getX(${eO(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() { ${Be(n)} coords = getOutputCoords(); int end = ${tO(n,"coords")}; float val = ${s}; int pow2 = int(pow(2.0, index)); if (${i}) { int idx = ${l}; ${tO(n,"coords")} = idx; val += getX(${eO(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 eO(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 tO(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 oZ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,exclusive:a,reverse:i}=o,l=n.shape.length,u=S.getAxesPermutation([s],l),c=n;u!=null&&(c=Bt({inputs:{x:n},backend:t,attrs:{perm:u}}));let p=S.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=Ht({inputs:{x:c},backend:t});for(let d=0;d<=Math.ceil(Math.log2(m))-1;d++){let h=new Ux(c.shape,!1,i),g=h.getCustomSetupFunc(d),y=f;f=t.runWebGLProgram(h,[f],f.dtype,g),t.disposeIntermediateTensorInfo(y)}if(a){let d=new Ux(c.shape,a,i),h=f;f=t.runWebGLProgram(d,[f],f.dtype),t.disposeIntermediateTensorInfo(h)}if(u!=null){let d=S.getUndoAxesPermutation(u),h=Bt({inputs:{x:f},backend:t,attrs:{perm:d}});return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(c),h}return f}var rO={kernelName:en,backendName:"webgl",kernelFunc:oZ};function nZ(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=$x(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=lR(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 oO={kernelName:Ql,backendName:"webgl",kernelFunc:nZ};var kC=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 sZ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockSize:s,dataFormat:a}=o;x.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 kC(d,s,a);return t.runWebGLProgram(h,[n],n.dtype)}var nO={kernelName:ti,backendName:"webgl",kernelFunc:sZ};var ih=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,y="",b="";o&&(n?y=`float activation(float a) { float b = getPreluActivationWeightsAtOutCoords(); ${o} }`:s?y=`float activation(float a) { float b = getLeakyreluAlphaAtOutCoords(); ${o} }`:y=` 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=` ${y} 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 ah=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,y="int xR; int xC; int xCOffset;";for(let k=0;k= 0 && xR < ${a} && xCOffset >= 0 && xCOffset < ${i}) { xTexelR${k}C${T} = getX(batch, xR, xCOffset, d1); // Need to manually clear unused channels in case // we're reading from recycled texture. if(xCOffset + 1 >= ${i}) { xTexelR${k}C${T}.zw = vec2(0.); } } else { xTexelR${k}C${T} = 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${k}C${T} = vec4(previous.zw, xTexelR${k}C${T}.xy); } else { xR${k}C${T} = vec4(0, 0, xTexelR${k}C${T}.xy); } `:y+=` if(xR >= 0 && xR < ${a} && xC >= 0 && xC < ${i}) { xTexelR${k}C${T} = getX(batch, xR, xC, d1); } else { xTexelR${k}C${T} = vec4(0.); } xR${k}C${T} = xTexelR${k}C${T}; `,T+1= 0 && xR < ${a} && xCOffset >= 0 && xCOffset < ${i}) { xTexelR${k}C${T+2} = getX(batch, xR, xCOffset, d1); } `,f>1&&(y+=` xCOffset -= 2; if(xR >= 0 && xR < ${a} && xCOffset >= 0 && xCOffset < ${i}) { xTexelR${k}C${T} = getX(batch, xR, xCOffset, d1); } else { xTexelR${k}C${T} = vec4(0.); } `),y+=` xR${k}C${T+1} = vec4( xTexelR${k}C${T}.zw, xTexelR${k}C${T+2}.xy); `):y+=` xCOffset = xC + ${F}; if(xR >= 0 && xR < ${a} && xCOffset >= 0 && xCOffset < ${i}) { xTexelR${k}C${T+2} = getX(batch, xR, xCOffset, d1); } xR${k}C${T+1} = xTexelR${k}C${T+2}; `}}else T= 0 && xR < ${a}) { `,u%2==1?(y+=` xCOffset = xC + 1 - ${p}; if(xCOffset >= 0 && xCOffset < ${i}) { xTexelR${k}C${T} = getX(batch, xR, xCOffset, d1); } else { xTexelR${k}C${T} = vec4(0.); } if(xC + 1 >= 0 && xC + 1 < ${i}) { xTexelR${k}C${T+2} = getX(batch, xR, xC + 1, d1); } else { xTexelR${k}C${T+2} = vec4(0.); } xR${k}C${T} = vec4( xTexelR${k}C${T}.zw, xTexelR${k}C${T+2}.zw); `,T+1= 0 && xCOffset < ${i}) { final = getX(batch, xR, xCOffset, d1); } xR${k}C${T+1} = vec4(xTexelR${k}C${T+2}.xy, final.xy); `)):(y+=` if(xC >= 0 && xC < ${i}) { xTexelR${k}C${T} = getX(batch, xR, xC, d1); } else { xTexelR${k}C${T} = vec4(0.); } xCOffset = xC + ${p}; if(xCOffset >= 0 && xCOffset < ${i}) { xTexelR${k}C${T+2} = getX(batch, xR, xCOffset, d1); } else { xTexelR${k}C${T+2} = vec4(0.); } xR${k}C${T} = vec4( xTexelR${k}C${T}.xy, xTexelR${k}C${T+2}.xy); `,T+1`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${c}'`);let p=S.computeConv2DInfo(n.shape,s.shape,a,c,i,u,!0),m;return W().getBool("WEBGL_PACK_DEPTHWISECONV")&&p.strideWidth<=2&&p.outChannels/p.inChannels==1?m=new ah(p):m=new ih(p),t.runWebGLProgram(m,[n,s],"float32")}var sO={kernelName:tn,backendName:"webgl",kernelFunc:iZ};var CC=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); } `}},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=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 aZ(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=S.computeConv2DInfo(n.shape,c,a,i,l,u,!0),m=new CC(p);return t.runWebGLProgram(m,[n,s],"float32")}var iO={kernelName:eu,backendName:"webgl",kernelFunc:aZ};function lZ(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=S.computeConv2DInfo(c,s.shape,a,i,l,u,!0),m=new IC(p);return t.runWebGLProgram(m,[n,s],"float32")}var aO={kernelName:tu,backendName:"webgl",kernelFunc:lZ};var NC=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 uZ(r){let{inputs:e,backend:t}=r,{x:o}=e,n=[...o.shape,...o.shape],s=x.sizeFromShape(o.shape),a=me({inputs:{x:o},backend:t,attrs:{shape:[s]}}),i=new NC(s),l=t.runWebGLProgram(i,[a],a.dtype),u=me({inputs:{x:l},backend:t,attrs:{shape:n}});return t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(l),u}var lO={kernelName:ru,backendName:"webgl",kernelFunc:uZ};var SC=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 cZ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n,filter:s}=e,{strides:a,pad:i,dilations:l}=o,u=S.computeDilation2DInfo(n.shape,s.shape,a,i,"NHWC",l),c,p=new SC(u);c=t.runWebGLProgram(p,[n,s],"float32");let m=me({inputs:{x:c},backend:t,attrs:{shape:u.outShape}});return t.disposeIntermediateTensorInfo(c),m}var uO={kernelName:la,backendName:"webgl",kernelFunc:cZ};var pZ="return (x >= 0.0) ? x : (exp(x) - 1.0);",mZ=` 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; `,fZ=Ce({opSnippet:pZ,packedOpSnippet:mZ}),cO={kernelName:ri,backendName:"webgl",kernelFunc:fZ};var dZ="return (b >= 1.0) ? a : a * (b + 1.0);",hZ=` vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.))); return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0)))); `,gZ=r=>{let{inputs:e,backend:t}=r,{dy:o,y:n}=e,s=W().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bs(hZ,o.shape,n.shape):new ts(dZ,o.shape,n.shape);return t.runWebGLProgram(s,[o,n],o.dtype)},pO={kernelName:ou,backendName:"webgl",kernelFunc:gZ};var xZ=` return vec4(equal(a, b)); `,yZ="return float(a == b);",bZ=at({opSnippet:yZ,packedOpSnippet:xZ,dtype:"bool"}),mO={kernelName:ni,backendName:"webgl",kernelFunc:bZ};var _Z=` // Error function is calculated approximately with elementary function. // See "Handbook of Mathematical Functions with Formulas, // Graphs, and Mathematical Tables", Abramowitz and Stegun. float p = ${S.ERF_P}; float a1 = ${S.ERF_A1}; float a2 = ${S.ERF_A2}; float a3 = ${S.ERF_A3}; float a4 = ${S.ERF_A4}; float a5 = ${S.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)); `,wZ=Ce({opSnippet:_Z}),fO={kernelName:oi,backendName:"webgl",kernelFunc:wZ};var dO="return exp(x);",TC=Ce({opSnippet:dO,packedOpSnippet:dO,cpuKernelImpl:pR}),hO={kernelName:on,backendName:"webgl",kernelFunc:TC};function jx(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&&(x.assert(-(a+1)<=n,()=>`Axis must be in the interval [${-(a+1)}, ${a}]`),l=a+n+1),i.splice(l,0,1),me({inputs:{x:s},backend:o,attrs:{shape:i}})}var gO={kernelName:ls,backendName:"webgl",kernelFunc:jx};var xO="return exp(x) - 1.0;",vZ=Ce({opSnippet:xO,packedOpSnippet:xO,cpuKernelImpl:mR}),yO={kernelName:si,backendName:"webgl",kernelFunc:vZ};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 Hx(r,e,t){let o=t.texData.get(r.dataId),n=x.sizeFromShape(r.shape),s=r.shape[r.shape.length-1],a=n/s,l=me({inputs:{x:r},backend:t,attrs:{shape:[a,s]}}).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=fo({inputs:{real:m,imag:f},backend:t});t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(f);let h=me({inputs:{x:d},backend:t,attrs:{shape:r.shape}});return t.disposeIntermediateTensorInfo(h),h}function kZ(r){let{inputs:e,backend:t}=r,{input:o}=e;return Hx(o,!1,t)}var bO={kernelName:nu,backendName:"webgl",kernelFunc:kZ};var EC=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 lh(r){let{backend:e,attrs:t}=r,{shape:o,value:n}=t,{dtype:s}=t;if(s=s||x.inferDtype(n),s==="string"){let a=x.getArrayFromDType(s,x.sizeFromShape(o));return a.fill(n),e.makeTensorInfo(o,s,a)}else{let a=new EC(o,n),i=a.getCustomSetupFunc(n);return e.runWebGLProgram(a,[],s,i)}}var _O={kernelName:ua,backendName:"webgl",kernelFunc:lh};var AC=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 wO={kernelName:ii,backendName:"webgl",kernelFunc:({inputs:r,backend:e})=>{let{image:t}=r,o=e,n=new AC(t.shape);return o.runWebGLProgram(n,[t],t.dtype)}};var vO="return floor(x);",CZ=Ce({opSnippet:vO,packedOpSnippet:vO,cpuKernelImpl:fR}),kO={kernelName:nn,backendName:"webgl",kernelFunc:CZ};var IZ=` 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; } `,NZ=` 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); `,SZ=at({opSnippet:IZ,packedOpSnippet:NZ,dtype:"int32"}),CO={kernelName:sn,backendName:"webgl",kernelFunc:SZ};var DC=class{constructor(e){this.variableNames=["A"];let t=zt(),[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 $C=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=zt(),[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 IO={kernelName:Pc,backendName:"webgl",kernelFunc:TZ},qp;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)&&(qp==null&&(qp=document.createElement("canvas").getContext("2d")),qp.canvas.width=u,qp.canvas.height=c,qp.drawImage(n,0,0,u,c),n=qp.canvas);let f=t.makeTensorInfo(p,"int32");t.texData.get(f.dataId).usage=Dr.PIXELS,t.gpgpu.uploadPixelDataToTexture(t.getTexture(f.dataId),n);let d=W().getBool("WEBGL_PACK")?new $C(m):new DC(m),h=t.runWebGLProgram(d,[f],"int32");return t.disposeData(f.dataId),h}function EZ(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=S.convertConv2DDataFormat(c),g=S.computeConv2DInfo(n.shape,s.shape,l,p,u,m,!1,h),y,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"))y=Wx({x:n,filter:s,convInfo:g,backend:t,bias:a,activation:f,preluActivationWeights:i,leakyreluAlpha:d});else if(W().getBool("WEBGL_CONV_IM2COL")&&n.shape[0]===1)y=Gx({x:n,filter:s,convInfo:g,backend:t,bias:a,activation:f,preluActivationWeights:i,leakyreluAlpha:d});else{let w=a!=null,k=i!=null,$=f==="leakyrelu",T=f?Dl(f,!1):null,F=new sh(g,w,T,k,$),M=[n,s];if(a&&M.push(a),i&&M.push(i),$){let L=t.makeTensorInfo([],"float32",x.createScalarValue(d,"float32"));M.push(L),b.push(L)}y=t.runWebGLProgram(F,M,"float32")}let _=me({inputs:{x:y},backend:t,attrs:{shape:g.outShape}});return b.push(y),b.forEach(w=>t.disposeIntermediateTensorInfo(w)),_}var NO={kernelName:ws,backendName:"webgl",kernelFunc:EZ};function AZ(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]),x.assert(S.eitherStridesOrDilationsAreOne(l,h),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${h}'`);let g=S.computeConv2DInfo(n.shape,s.shape,l,h,u,p,!0),y=W().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,b=m?Dl(m,y):null,_=[n,s],w=a!=null,k=i!=null,$=m==="leakyrelu";if(w&&_.push(a),k&&_.push(i),$){let M=t.makeTensorInfo([],"float32",x.createScalarValue(f,"float32"));_.push(M),d.push(M)}let T;y?T=new ah(g,w,b,k,$):T=new ih(g,w,b,k,$);let F=t.runWebGLProgram(T,_,"float32");return d.forEach(M=>t.disposeIntermediateTensorInfo(M)),F}var SO={kernelName:vs,backendName:"webgl",kernelFunc:AZ};var RC=class{constructor(e,t,o){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=o;let n=Be(t.length),s=Be(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 DZ(r){let{inputs:e,backend:t}=r,{params:o,indices:n}=e,s=n.shape,a=s[s.length-1],[i,l,u,c]=S.prepareAndValidate(o,n),p=me({inputs:{x:n},backend:t,attrs:{shape:[l,a]}}),m=me({inputs:{x:o},backend:t,attrs:{shape:[x.sizeFromShape(o.shape)/u,u]}}),f=new RC(a,c,[l,u]),d=t.runWebGLProgram(f,[m,p],m.dtype),h=me({inputs:{x:d},backend:t,attrs:{shape:i}});return t.disposeIntermediateTensorInfo(p),t.disposeIntermediateTensorInfo(m),t.disposeIntermediateTensorInfo(d),h}var TO={kernelName:ai,backendName:"webgl",kernelFunc:DZ};var FC=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let o=Be(this.rank),n=$Z(e,2);this.userCode=` void main() { ${o} resRC = getOutputCoords(); setOutput(getA(${n})); } `}};function $Z(r,e){let t=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[];for(let n=0;nt.disposeIntermediateTensorInfo(k)),t.makeTensorInfo(u.outputShape,w.dtype,w.values)}let h=new FC(m.shape,d),g=t.runWebGLProgram(h,[m,f],m.dtype);p.push(g);let y=me({inputs:{x:g},backend:t,attrs:{shape:u.outputShape}});return p.forEach(b=>t.disposeIntermediateTensorInfo(b)),y}var EO={kernelName:us,backendName:"webgl",kernelFunc:RZ};var FZ="return float(a > b);",OZ=` return vec4(greaterThan(a, b)); `,PZ=at({opSnippet:FZ,packedOpSnippet:OZ,cpuKernelImpl:hR,dtype:"bool"}),AO={kernelName:li,backendName:"webgl",kernelFunc:PZ};var MZ="return float(a >= b);",LZ=` return vec4(greaterThanEqual(a, b)); `,zZ=at({opSnippet:MZ,packedOpSnippet:LZ,dtype:"bool"}),DO={kernelName:ln,backendName:"webgl",kernelFunc:zZ};function BZ(r){let{inputs:e,backend:t}=r,{input:o}=e;return Hx(o,!0,t)}var $O={kernelName:su,backendName:"webgl",kernelFunc:BZ};var VZ="return float(!isnan(x) && !isinf(x));",WZ=Ce({opSnippet:VZ,dtype:"bool"}),RO={kernelName:ui,backendName:"webgl",kernelFunc:WZ};var GZ="return float(isinf(x));",UZ=Ce({opSnippet:GZ,dtype:"bool"}),FO={kernelName:ci,backendName:"webgl",kernelFunc:UZ};var jZ="return float(isnan(x));",qZ=Ce({opSnippet:jZ,dtype:"bool"}),OO={kernelName:pi,backendName:"webgl",kernelFunc:qZ};var HZ="return float(a < b);",KZ=` return vec4(lessThan(a, b)); `,XZ=at({opSnippet:HZ,packedOpSnippet:KZ,cpuKernelImpl:gR,dtype:"bool"}),PO={kernelName:mi,backendName:"webgl",kernelFunc:XZ};var YZ="return float(a <= b);",ZZ=` return vec4(lessThanEqual(a, b)); `,JZ=at({opSnippet:YZ,packedOpSnippet:ZZ,dtype:"bool"}),MO={kernelName:fi,backendName:"webgl",kernelFunc:JZ};function QZ(r){let{backend:e,attrs:t}=r,{start:o,stop:n,num:s}=t,a=xR(o,n,s);return e.makeTensorInfo([a.length],"float32",a)}var LO={kernelName:au,backendName:"webgl",kernelFunc:QZ};var e9=`if (x < 0.0) return NAN; return log(x);`,t9=` 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; `,r9=Ce({opSnippet:e9,packedOpSnippet:t9,cpuKernelImpl:yR}),zO={kernelName:cn,backendName:"webgl",kernelFunc:r9};var o9="return log(1.0 + x);",n9=Ce({opSnippet:o9}),BO={kernelName:di,backendName:"webgl",kernelFunc:n9};var s9="return float(a >= 1.0 && b >= 1.0);",i9=` return vec4( vec4(greaterThanEqual(a, vec4(1.0))) * vec4(greaterThanEqual(b, vec4(1.0)))); `,a9=at({opSnippet:s9,packedOpSnippet:i9,dtype:"bool"}),VO={kernelName:hi,backendName:"webgl",kernelFunc:a9};var l9="return float(!(x >= 1.0));",u9=Ce({opSnippet:l9}),WO={kernelName:Qa,backendName:"webgl",kernelFunc:u9};var c9="return float(a >= 1.0 || b >= 1.0);",p9=` return min( vec4(greaterThanEqual(a, vec4(1.0))) + vec4(greaterThanEqual(b, vec4(1.0))), vec4(1.0)); `,m9=at({opSnippet:c9,packedOpSnippet:p9,dtype:"bool"}),GO={kernelName:el,backendName:"webgl",kernelFunc:m9};var OC=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 PC=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 f9=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{depthRadius:s,bias:a,alpha:i,beta:l}=o,u=W().getBool("WEBGL_PACK_NORMALIZATION")?new PC(n.shape,s,a,i,l):new OC(n.shape,s,a,i,l);return t.runWebGLProgram(u,[n],n.dtype)},UO={kernelName:ca,backendName:"webgl",kernelFunc:f9};var MC=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 d9=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 MC(n.shape,i,l,u,c);return t.runWebGLProgram(p,[n,s,a],n.dtype)},jO={kernelName:lu,backendName:"webgl",kernelFunc:d9};function qO(r,e,t,o){let n=x.sizeFromShape(e),a=x.sizeFromShape(r.shape)/n,i=me({inputs:{x:r},attrs:{shape:[a,n]},backend:o}),l=So(i,r.dtype,"max",o),u=me({inputs:{x:l},attrs:{shape:t},backend:o});return o.disposeIntermediateTensorInfo(i),o.disposeIntermediateTensorInfo(l),u}function LC(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{reductionIndices:s,keepDims:a}=o,i=n.shape.length,l=x.parseAxisParam(s,n.shape),u=l,c=S.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 T=0;T`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let c=S.computePool2DInfo(n.shape,s,a,u,i,l);if(c.filterWidth===1&&c.filterHeight===1&&x.arraysEqual(c.inShape,c.outShape))return Ht({inputs:{x:n},backend:t});let p=new Yi(c,"max",!1);return t.runWebGLProgram(p,[n],n.dtype)}var XO={kernelName:fn,backendName:"webgl",kernelFunc:y9};function b9(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=S.computePool3DInfo(n.shape,s,a,c,i,u,l),m=new mc(p,"max",!1);return t.runWebGLProgram(m,[n],n.dtype)}var YO={kernelName:pa,backendName:"webgl",kernelFunc:b9};var zC=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); } `}},BC=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 _9(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=S.computePool3DInfo(a.shape,i,l,p,u,c),f=new mc(m,"max",!0),d=t.runWebGLProgram(f,[a],a.dtype),h=new BC(m),g=t.runWebGLProgram(h,[n,d],a.dtype);return t.disposeIntermediateTensorInfo(d),g}var ZO={kernelName:cu,backendName:"webgl",kernelFunc:_9};function w9(r){let{inputs:e,backend:t,attrs:o}=r,{dy:n,input:s,output:a}=e,i=s;Xi([s,a],"maxPoolGrad");let{filterSize:l,strides:u,pad:c,dimRoundingMode:p}=o,m=S.computePool2DInfo(i.shape,l,u,1,c,p),f=!0,d=new Yi(m,"max",f),h=t.runWebGLProgram(d,[i],i.dtype),g=new zC(m),y=t.runWebGLProgram(g,[n,h],i.dtype);return t.disposeIntermediateTensorInfo(h),y}var JO={kernelName:uu,backendName:"webgl",kernelFunc:w9};function QO(r,e,t,o){let n=new Yi(t,"max",!1),s=o.runWebGLProgram(n,[r],"float32");n=new Yi(t,"max",!0,!0,e);let a=o.runWebGLProgram(n,[r],"float32");return[s,a]}var eP={kernelName:pu,backendName:"webgl",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{x:o}=r,{filterSize:n,strides:s,pad:a,includeBatchInIndex:i}=e,l=t;x.assert(o.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${o.shape.length}.`);let u=[1,1];x.assert(S.eitherStridesOrDilationsAreOne(s,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${u}'`);let c=S.computePool2DInfo(o.shape,n,s,u,a),[p,m]=QO(o,i,c,l);return[p,m]}};function tP(r,e,t,o){let n=x.sizeFromShape(e),a=x.sizeFromShape(r.shape)/n,i=me({inputs:{x:r},attrs:{shape:[a,n]},backend:o}),l=So(i,"float32","mean",o),u=me({inputs:{x:l},attrs:{shape:t},backend:o});return o.disposeIntermediateTensorInfo(i),o.disposeIntermediateTensorInfo(l),u}var rP={kernelName:dn,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=x.parseAxisParam(s,o.shape),u=l,c=S.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,k=new Array(i);for(let F=0;Fc[0]+e[p]+c[1]);let n=e.length,s=Be(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 WC=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=Be(n),a=t.map(d=>d[0]).join(","),i=t.map((d,h)=>d[0]+e[h]).join(","),l=qt("rc",n),u=qt("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 N9=({inputs:r,backend:e,attrs:t})=>{let{x:o}=r,{paddings:n,mode:s}=t,a=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new WC(o.shape,n,s):new VC(o.shape,n,s);return e.runWebGLProgram(a,[o],o.dtype)},sP={kernelName:ma,backendName:"webgl",kernelFunc:N9};var S9=`if (b == 0.0) return NAN; return mod(a, b);`,T9=` vec4 result = mod(a, b); vec4 isNaN = vec4(equal(b, vec4(0.0))); `+Al+` return result; `,E9=at({opSnippet:S9,packedOpSnippet:T9}),iP={kernelName:gi,backendName:"webgl",kernelFunc:E9};var GC=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 A9=` if (a == b) { return 1.0; }; return a / b;`,D9=` // 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; `,UC=at({opSnippet:A9,packedOpSnippet:D9,checkOutOfBounds:!0}),aP={kernelName:rn,backendName:"webgl",kernelFunc:UC};var lP="return a - b;",jC=at({opSnippet:lP,packedOpSnippet:lP,supportsComplex:!0,cpuKernelImpl:ER}),uP={kernelName:Fn,backendName:"webgl",kernelFunc:jC};function qC(r){let{inputs:e,backend:t,attrs:o}=r,{logits:n}=e,{dim:s}=o,a=x.parseAxisParam([s],n.shape),i=LC({inputs:{x:n},backend:t,attrs:{reductionIndices:a,keepDims:!1}}),l=S.expandShapeToKeepDim(i.shape,a),u=me({inputs:{x:i},backend:t,attrs:{shape:l}}),c=jC({inputs:{a:n,b:u},backend:t}),p=TC({inputs:{x:c},backend:t}),m=nh({inputs:{x:p},backend:t,attrs:{axis:a,keepDims:!1}}),f=me({inputs:{x:m},backend:t,attrs:{shape:l}}),d=UC({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 cP={kernelName:$n,backendName:"webgl",kernelFunc:qC};function $9(r){let{inputs:e,backend:t,attrs:o}=r,{logits:n}=e,{numSamples:s,seed:a,normalized:i}=o,l=i?n:qC({inputs:{logits:n},backend:t,attrs:{dim:n.shape.length-1}}),u=l.shape[0],c=l.shape[1],p=new GC(u,c,s),m=p.getCustomSetupFunc(a),f=t.runWebGLProgram(p,[l],"int32",m);return i||t.disposeIntermediateTensorInfo(l),f}var pP={kernelName:mu,backendName:"webgl",kernelFunc:$9};var mP="return -x;";function R9(r){let{inputs:e,backend:t}=r,{x:o}=e;if(t.shouldExecuteOnCPU([o])){let s=t.texData.get(o.dataId),[a,i]=kR(s.values,o.shape,o.dtype);return t.makeTensorInfo(i,o.dtype,a)}let n;return W().getBool("WEBGL_PACK_UNARY_OPERATIONS")?n=new zs(o.shape,mP):n=new mo(o.shape,mP),t.runWebGLProgram(n,[o],o.dtype)}var fP={kernelName:ps,backendName:"webgl",kernelFunc:R9};var F9=Er.nonMaxSuppressionV3Impl;function O9(r){S.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}=F9(u,c,a,i,l);return t.makeTensorInfo([p.length],"int32",new Int32Array(p))}var dP={kernelName:yi,backendName:"webgl",kernelFunc:O9};var P9=Er.nonMaxSuppressionV4Impl;function M9(r){S.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}=P9(c,p,a,i,l,u);return[t.makeTensorInfo([m.length],"int32",new Int32Array(m)),t.makeTensorInfo([],"int32",new Int32Array([f]))]}var hP={kernelName:bi,backendName:"webgl",kernelFunc:M9};var L9=Er.nonMaxSuppressionV5Impl;function z9(r){S.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:y}=L9(c,p,m,f,d,h);return[t.makeTensorInfo([g.length],"int32",new Int32Array(g)),t.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var gP={kernelName:_i,backendName:"webgl",kernelFunc:z9};var HC=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 B9=r=>{let{inputs:e,backend:t,attrs:o}=r,{indices:n}=e,{depth:s,onValue:a,offValue:i}=o,l=x.sizeFromShape(n.shape),u=new HC(l,s,a,i),c=me({inputs:{x:n},backend:t,attrs:{shape:[l]}}),p=t.runWebGLProgram(u,[c],n.dtype);t.disposeIntermediateTensorInfo(c);let m=[...n.shape,s],f=me({inputs:{x:p},backend:t,attrs:{shape:m}});return t.disposeIntermediateTensorInfo(p),f},xP={kernelName:yn,backendName:"webgl",kernelFunc:B9};function uh(r){let{inputs:e,backend:t}=r,{x:o}=e;if(o.dtype==="complex64"){let n=Ha({inputs:{input:o},backend:t}),s=uh({inputs:{x:n},backend:t}),a=fc({inputs:{input:o},backend:t}),i=uh({inputs:{x:a},backend:t}),l=fo({inputs:{real:s,imag:i},backend:t});return t.disposeIntermediateTensorInfo(n),t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),l}else return lh({attrs:{shape:o.shape,dtype:o.dtype,value:o.dtype==="string"?"":0},backend:t})}var yP={kernelName:bs,backendName:"webgl",kernelFunc:uh};function bP(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=Ha({inputs:{input:o},backend:t}),s=bP({inputs:{x:n},backend:t}),a=fc({inputs:{input:o},backend:t}),i=uh({inputs:{x:a},backend:t}),l=fo({inputs:{real:s,imag:i},backend:t});return t.disposeIntermediateTensorInfo(n),t.disposeIntermediateTensorInfo(s),t.disposeIntermediateTensorInfo(a),t.disposeIntermediateTensorInfo(i),l}else return lh({attrs:{shape:o.shape,dtype:o.dtype,value:1},backend:t})}var _P={kernelName:ms,backendName:"webgl",kernelFunc:bP};function V9(r){let{inputs:e,backend:t,attrs:o}=r,{axis:n}=o;if(e.length===1)return jx({inputs:{input:e[0]},backend:t,attrs:{dim:n}});let s=e[0].shape,a=e[0].dtype;e.forEach(c=>{x.assertShapesMatch(s,c.shape,"All tensors passed to stack must have matching shapes"),x.assert(a===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=e.map(c=>{let p=jx({inputs:{input:c},backend:t,attrs:{dim:n}});return i.push(p),p}),u=hC({inputs:l,backend:t,attrs:{axis:n}});return i.forEach(c=>t.disposeIntermediateTensorInfo(c)),u}var wP={kernelName:fs,backendName:"webgl",kernelFunc:V9};var KC=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=Be(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 XC=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=Be(n),a=t.map(h=>h[0]).join(","),i=t.map((h,g)=>h[0]+e[g]).join(","),l=qt("rc",n),u=qt("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{let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{paddings:s,constantValue:a}=o,i=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new XC(n.shape,s,a):new KC(n.shape,s,a);return t.runWebGLProgram(i,[n],n.dtype)},vP={kernelName:bn,backendName:"webgl",kernelFunc:YC};var W9=` 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)); `+Al+` return result; `,U9=at({opSnippet:W9,packedOpSnippet:G9}),kP={kernelName:_n,backendName:"webgl",kernelFunc:U9};function j9(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{axis:s,keepDims:a}=o,i=n.shape.length,l=[],u=x.parseAxisParam(s,n.shape),c=u,p=S.getAxesPermutation(c,i),m=n;p!=null&&(m=Bt({inputs:{x:n},backend:t,attrs:{perm:p}}),c=S.getInnerMostAxes(c.length,i),l.push(m)),S.assertAxesAreInnerMostDims("prod",c,i);let f;if(t.shouldExecuteOnCPU([m])){let d=t.texData.get(m.dataId).values,{outVals:h,outShape:g,outDtype:y}=CR(m.shape,m.dtype,d,c);f=t.makeTensorInfo(g,y,h)}else{let[d,h]=S.computeOutAndReduceShapes(m.shape,c),g=x.sizeFromShape(h),y=me({inputs:{x:m},backend:t,attrs:{shape:[-1,g]}}),b=yu(n.dtype),_=So(y,b,"prod",t);f=me({inputs:{x:_},backend:t,attrs:{shape:d}}),l.push(y),l.push(_)}if(a){l.push(f);let d=S.expandShapeToKeepDim(f.shape,u);f=me({inputs:{x:f},backend:t,attrs:{shape:d}})}return l.forEach(d=>t.disposeIntermediateTensorInfo(d)),f}var CP={kernelName:wi,backendName:"webgl",kernelFunc:j9};var ZC=r=>{let{backend:e,attrs:t}=r,{start:o,stop:n,step:s,dtype:a}=t,i=IR(o,n,s,a);return e.makeTensorInfo([i.length],a,i)},IP={kernelName:fa,backendName:"webgl",kernelFunc:ZC};var q9="return 1.0 / x;",H9=Ce({opSnippet:q9}),NP={kernelName:vi,backendName:"webgl",kernelFunc:H9};var K9=xr+` return (x < 0.0) ? 0.0 : x; `,X9=` 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; `,Y9=Ce({opSnippet:K9,packedOpSnippet:X9}),SP={kernelName:vn,backendName:"webgl",kernelFunc:Y9};var Z9=xr+` return (x < 0.0) ? 0.0 : min(6.0, x); `,J9=` 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; `,Q9=Ce({opSnippet:Z9,packedOpSnippet:J9}),TP={kernelName:Cn,backendName:"webgl",kernelFunc:Q9};var JC=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 QC=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 eJ(r){let{inputs:e,backend:t,attrs:o}=r,{images:n}=e,{alignCorners:s,halfPixelCenters:a,size:i}=o,[l,u]=i,c=W().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new QC(n.shape,l,u,s,a):new JC(n.shape,l,u,s,a);return t.runWebGLProgram(c,[n],"float32")}var EP={kernelName:kn,backendName:"webgl",kernelFunc:eJ};var eI=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 tJ(r){let{inputs:e,backend:t,attrs:o}=r,{images:n,dy:s}=e,{alignCorners:a}=o,i=new eI(s.shape,n.shape,a);return t.runWebGLProgram(i,[s],s.dtype)}var AP={kernelName:hu,backendName:"webgl",kernelFunc:tJ};var tI=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 rJ(r){let{inputs:e,backend:t,attrs:o}=r,{images:n}=e,{alignCorners:s,halfPixelCenters:a,size:i}=o,[l,u]=i,c=new tI(n.shape,l,u,s,a);return t.runWebGLProgram(c,[n],n.dtype)}var DP={kernelName:da,backendName:"webgl",kernelFunc:rJ};var rI=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 oJ(r){let{inputs:e,backend:t,attrs:o}=r,{images:n,dy:s}=e,{alignCorners:a}=o,i=new rI(s.shape,n.shape,a);return t.runWebGLProgram(i,[s],s.dtype)}var $P={kernelName:du,backendName:"webgl",kernelFunc:oJ};var oI=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=Be(o);this.userCode=` void main() { ${a} coords = getOutputCoords(); setOutput(getX(${s})); } `}};var nI=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=qt("rc",o),s=`${n[o-1]} + 1 < ${this.outputShape[o-1]}`,a=`${n[o-2]} + 1 < ${this.outputShape[o-2]}`,i=Be(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(","),y=h.slice(-2).join(",");return`getChannel(getX(${g}), vec2(${y}))`}function f(d,h){return t.indexOf(d)!==-1&&e[d]!==1?`${e[d]} - ${h[d]} - 1`:`${h[d]}`}}};function nJ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{dims:s}=o,a=n.shape.length,i=x.parseAxisParam(s,n.shape);if(a===0)return Ht({inputs:{x:n},backend:t});let l=W().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new nI(n.shape,i):new oI(n.shape,i);return t.runWebGLProgram(l,[n],n.dtype)}var RP={kernelName:In,backendName:"webgl",kernelFunc:nJ};var sI=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]=S.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 FP={kernelName:$i,backendName:"webgl",kernelFunc:({inputs:r,attrs:e,backend:t})=>{let{image:o}=r,{radians:n,fillValue:s,center:a}=e,i=t,l=new sI(o.shape,n,s,a);return i.runWebGLProgram(l,[o],o.dtype)}};var sJ=` // 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; } } `,iJ=Ce({opSnippet:sJ}),OP={kernelName:Nn,backendName:"webgl",kernelFunc:iJ};var aJ="return inversesqrt(x);",lJ=Ce({opSnippet:aJ,cpuKernelImpl:NR}),PP={kernelName:Sn,backendName:"webgl",kernelFunc:lJ};var ch=class{constructor(e,t,o,n,s,a,i=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;let l=Be(s.length),u=Be(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 uJ(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}=S.calculateShapes(s,n,a),m=[p/u,u];if(p===0)return t.makeTensorInfo(a,n.dtype);let f=me({inputs:{x:n},backend:t,attrs:{shape:[l,i]}}),d=me({inputs:{x:s},backend:t,attrs:{shape:[l,u]}}),h=t.makeTensorInfo([],"float32",new Float32Array([0])),g=new ch(l,i,f.shape.length,d.shape.length,c,m),y=t.runWebGLProgram(g,[d,f,h],d.dtype),b=me({inputs:{x:y},backend:t,attrs:{shape:a}});return t.disposeIntermediateTensorInfo(f),t.disposeIntermediateTensorInfo(d),t.disposeIntermediateTensorInfo(y),t.disposeIntermediateTensorInfo(h),b}var MP={kernelName:ki,backendName:"webgl",kernelFunc:uJ};var iI=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= 1.0) { setOutput(getA(${s})); } else { setOutput(getB(${s})); } } `}};function cJ(r){let{inputs:e,backend:t}=r,{condition:o,t:n,e:s}=e,a=new iI(o.shape.length,n.shape,n.shape.length);return t.runWebGLProgram(a,[o,n,s],fr(n.dtype,s.dtype))}var LP={kernelName:hs,backendName:"webgl",kernelFunc:cJ};var pJ=` // Stable and Attracting Fixed Point (0, 1) for Normalized Weights. // see: https://arxiv.org/abs/1706.02515 float scaleAlpha = ${S.SELU_SCALEALPHA}; float scale = ${S.SELU_SCALE}; return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0); `,mJ=Ce({opSnippet:pJ}),zP={kernelName:Ci,backendName:"webgl",kernelFunc:mJ};var fJ="return 1.0 / (1.0 + exp(-1.0 * x));",dJ=Ce({opSnippet:fJ}),BP={kernelName:En,backendName:"webgl",kernelFunc:dJ};var hJ=` if (isnan(x)) { return 0.0; } return sign(x); `,gJ=Ce({opSnippet:hJ}),VP={kernelName:Ni,backendName:"webgl",kernelFunc:gJ};var xJ=Px+` return sin(x); `,yJ=Ce({opSnippet:xJ}),WP={kernelName:Tn,backendName:"webgl",kernelFunc:yJ};var bJ=` float e2x = exp(x); return (e2x - 1.0 / e2x) / 2.0; `,_J=Ce({opSnippet:bJ}),GP={kernelName:Ii,backendName:"webgl",kernelFunc:_J};var wJ=` 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; `,vJ=Ce({opSnippet:wJ}),UP={kernelName:Si,backendName:"webgl",kernelFunc:vJ};var kJ=r=>{let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{blockShape:s,paddings:a}=o;x.assert(n.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let i=s.reduce((y,b)=>y*b),l=[[0,0]];l.push(...a);for(let y=1+s.length;yt.disposeIntermediateTensorInfo(y)),g},jP={kernelName:ha,backendName:"webgl",kernelFunc:kJ};function CJ(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}=S.calculateShapes(s,n,i),m=!1,f=new ch(u,l,n.shape.length,s.shape.length,c,[p,1],m),d=t.runWebGLProgram(f,[s,n,a],s.dtype),h=me({inputs:{x:d},backend:t,attrs:{shape:i}});return t.disposeIntermediateTensorInfo(d),h}var qP={kernelName:gu,backendName:"webgl",kernelFunc:CJ};function IJ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{numOrSizeSplits:s,axis:a}=o,i=x.parseAxisParam(a,n.shape)[0],l=S.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=qa({inputs:{x:n},backend:t,attrs:{begin:c,size:f}});return c[i]+=m,d})}var HP={kernelName:xs,backendName:"webgl",kernelFunc:IJ};var NJ="return sqrt(x);",SJ=Ce({opSnippet:NJ}),KP={kernelName:An,backendName:"webgl",kernelFunc:SJ};var TJ="return x * x;",EJ=Ce({opSnippet:TJ}),XP={kernelName:ga,backendName:"webgl",kernelFunc:EJ};var YP="return (a - b) * (a - b);",AJ=at({opSnippet:YP,packedOpSnippet:YP}),ZP={kernelName:Rn,backendName:"webgl",kernelFunc:AJ};function DJ({inputs:r,attrs:e,backend:t}){let{x:o}=r,n=xr+` return x > 0.0 ? 1.0 : float(${e.alpha}); `,s=new mo(o.shape,n);return t.runWebGLProgram(s,[o],o.dtype)}var JP={kernelName:Di,backendName:"webgl",kernelFunc:DJ};var aI=class{constructor(e,t,o){this.variableNames=["x"],this.outputShape=o;let n=o.length,s=Be(o.length),a=Be(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 $J(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:y,outShape:b}=sr.sliceInfo(n.shape,s,a,i,l,u,c,p,m),_=me({inputs:{x:n},backend:t,attrs:{shape:y}}),w;if(f){let $=qa({inputs:{x:_},backend:t,attrs:{begin:d,size:g}});w=me({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 F=t.texData.get(_.dataId).values,M=Ie(_.shape,_.dtype,F),L=TR(b,M,h,d);w=t.makeTensorInfo(b,_.dtype,L.values)}else{let T=new aI(d,h,b);w=t.runWebGLProgram(T,[_],_.dtype)}let k=me({inputs:{x:w},backend:t,attrs:{shape:b}});return t.disposeIntermediateTensorInfo(_),t.disposeIntermediateTensorInfo(w),k}var QP={kernelName:Ti,backendName:"webgl",kernelFunc:$J};var RJ="return tan(x);",FJ=Ce({opSnippet:RJ}),eM={kernelName:Ei,backendName:"webgl",kernelFunc:FJ};var OJ=` float e2x = exp(-2.0 * abs(x)); return sign(x) * (1.0 - e2x) / (1.0 + e2x); `,PJ=Ce({opSnippet:OJ}),tM={kernelName:On,backendName:"webgl",kernelFunc:PJ};var lI=class{constructor(e,t){this.variableNames=["A"];let o=new Array(e.length);for(let a=0;a5)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;nx.decodeString(m)),c=Ie(n.shape,n.dtype,u),p=AR(c,s);return t.makeTensorInfo(p.shape,p.dtype,p.values)}let a=new lI(n.shape,s);return t.runWebGLProgram(a,[n],n.dtype)}var rM={kernelName:_o,backendName:"webgl",kernelFunc:uI};function LJ(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{k:s,sorted:a}=o,i=t.readSync(n.dataId),[l,u]=DR(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 oM={kernelName:Ai,backendName:"webgl",kernelFunc:LJ};function zJ(r){let{inputs:e,attrs:t,backend:o}=r,{axis:n}=t,{x:s}=e;Xi(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}=$R(a,n,s.shape,s.dtype);return[o.makeTensorInfo(l,s.dtype,i),o.makeTensorInfo([u.length],"int32",u)]}var nM={kernelName:xu,backendName:"webgl",kernelFunc:zJ};function BJ(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;ht.disposeIntermediateTensorInfo(h)),d}var sM={kernelName:ys,backendName:"webgl",kernelFunc:BJ};var cI=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 VJ(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=S.getAxesPermutation([u],i),p=n;c!=null&&(p=Bt({inputs:{x:n},backend:t,attrs:{perm:c}}),l.push(p),u=S.getInnerMostAxes(1,i)[0]);let m=S.segment_util.computeOutShape(p.shape,u,a),f=x.sizeFromShape([p.shape[u]]),d=me({inputs:{x:p},backend:t,attrs:{shape:[-1,f]}});l.push(d);let h=yu(n.dtype),g=(w,k,$,T,F)=>{let M=w.shape[0],L=w.shape[1],G=S.segment_util.segOpComputeOptimalWindowSize(L,F),H={windowSize:G,inSize:L,batchSize:M,numSegments:F},U=new cI(H,k),Z=t.compileAndRun(U,[w,$],T);if(l.push(Z),Z.shape[1]===F)return Z;let K=ZC({backend:t,attrs:{start:0,stop:F,step:1,dtype:"float32"}}),X=uI({inputs:{x:K},backend:t,attrs:{reps:[L/G]}});return l.push(K),l.push(X),g(Z,k,X,T,F)},y=g(d,"unsortedSegmentSum",s,h,a),b=me({inputs:{x:y},backend:t,attrs:{shape:m}}),_=b;if(c!=null){l.push(b);let w=S.getUndoAxesPermutation(c);_=Bt({inputs:{x:_},backend:t,attrs:{perm:w}})}return l.forEach(w=>t.disposeIntermediateTensorInfo(w)),_}var iM={kernelName:xa,backendName:"webgl",kernelFunc:VJ};var WJ=[UO,jO,sF,aF,lF,uF,pF,mF,fF,dF,xF,yF,bF,_F,vF,wF,kF,IF,CF,NF,SF,TF,EF,DF,$F,PF,LF,zF,VF,HR,UF,qF,HF,jF,XF,YF,KF,ZF,JF,QF,rO,oO,nO,iO,aO,sO,lO,uO,cO,pO,mO,fO,hO,gO,yO,bO,_O,wO,kO,CO,IO,NO,SO,TO,EO,AO,DO,qR,$O,WF,RO,FO,OO,KR,PO,MO,LO,BO,zO,VO,WO,GO,HO,YO,XO,ZO,JO,eP,KO,rP,oP,nP,sP,iP,pP,QR,fP,dP,hP,gP,RF,xP,_P,wP,vP,kP,XR,CP,IP,FF,aP,NP,TP,SP,tF,EP,AP,DP,$P,RP,FP,OP,PP,MP,LP,zP,BP,VP,WP,GP,AF,cP,UP,jP,qP,HP,KP,XP,ZP,JP,QP,uP,oF,eM,tM,rM,oM,nF,nM,sM,iM,yP];for(let r of WJ)tl(r);var aM="2.8.3";var GJ={"tfjs-core":Zb,"tfjs-backend-cpu":GA,"tfjs-backend-webgl":jR,"tfjs-data":_x,"tfjs-layers":xl,"tfjs-converter":fx,tfjs:aM};var Vt;(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"})(Vt||(Vt={}));var Rl;(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"})(Rl||(Rl={}));var lM;function UJ(r){lM=r.wasm.cwrap(_s,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function jJ(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 F=t.dataIdMap.get(a.dataId);if(F.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${F.shape.length}.`);d=F.id}let h=i==null?0:t.dataIdMap.get(i.dataId).id,g=Rl[c];if(g==null)throw new Error(`${c} activation not yet supported for FusedConv2D in the wasm backend.`);let y=l?n.shape[2]:n.shape[1],b=u?s.shape[1]:s.shape[2],_=n.shape[0],w=t.makeOutput([_,y,b],n.dtype),k=t.dataIdMap.get(w.dataId).id,$=new Uint8Array(new Int32Array(n.shape).buffer),T=new Uint8Array(new Int32Array(s.shape).buffer);return lM(m,$,n.shape.length,f,T,s.shape.length,l,u,g,d,h,p||0,k),w}var uM={kernelName:_s,backendName:"wasm",setupFunc:UJ,kernelFunc:jJ};function Ft(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 x.sizeFromShape(l.shape)===0||e(i,u),l}return{kernelName:r,backendName:"wasm",setupFunc:t,kernelFunc:o}}var cM=Ft(is);function kt(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=S.assertAndGetBroadcastShape(u.shape,c.shape),h=i.makeOutput(d,f);if(x.sizeFromShape(d)===0)return h;let g=new Uint8Array(new Int32Array(u.shape).buffer),y=new Uint8Array(new Int32Array(c.shape).buffer),b=i.dataIdMap.get(h.dataId).id,_=()=>o(p,g,u.shape.length,m,y,c.shape.length,Vt[u.dtype],b);if(e&&u.dtype==="float32")return _(),h;let w=S.getBroadcastDims(u.shape,d),k=S.getBroadcastDims(c.shape,d),$=w.every((F,M)=>F===M),T=k.every((F,M)=>F===M);if($&&T)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 qJ=!0,pM=kt(bo,qJ);var mM;function HJ(r){mM=r.wasm.cwrap(Ho,null,["array","number","number","number"])}function KJ(r){let{inputs:e,backend:t}=r,o=t.makeOutput(e[0].shape,e[0].dtype);if(x.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 mM(s,n.length,Vt[o.dtype],a),o}var fM={kernelName:Ho,backendName:"wasm",setupFunc:HJ,kernelFunc:KJ};function hc(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 dM={kernelName:cs,backendName:"wasm",kernelFunc:hc};var hM;function XJ(r){hM=r.wasm.cwrap(Pn,null,["number","array","number","number","number","array","number"])}function Hp(r){let{inputs:e,backend:t,attrs:o}=r,[n,s]=ZJ(e.x.shape,o.perm),a=!0;for(let d=0;d=n&&(s===-1||o[s]>o[a])&&(s=a);o[s]=n}return[t,o]}var gM={kernelName:Pn,backendName:"wasm",kernelFunc:Hp,setupFunc:XJ};function rs(r,e,t){let o=r.shape,n=r.shape.length,s=x.parseAxisParam(e,o),a=s,i=S.getAxesPermutation(a,n),l=null,u=!1;if(i!=null){let c=new Array(n);for(let f=0;f`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 wM={kernelName:ds,backendName:"wasm",kernelFunc:Wr};var vM;function rQ(r){vM=r.wasm.cwrap(Yo,null,["number","array","number","number","array","number","number","number","number"])}function oQ(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=x.sizeFromShape(d),y=x.sizeFromShape(h),b=g===y||g===1||y===1;x.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>y?n.shape.slice(0,-2):s.shape.slice(0,-2)).concat([m,f]);x.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 k=a?[g,c,m]:[g,m,c],$=i?[y,f,p]:[y,p,f],T=Wr({inputs:{x:n},backend:t,attrs:{shape:k}}),F=Wr({inputs:{x:s},backend:t,attrs:{shape:$}}),M=t.dataIdMap.get(T.dataId).id,L=t.dataIdMap.get(F.dataId).id,G=a?T.shape[2]:T.shape[1],H=i?F.shape[1]:F.shape[2],U=Math.max(g,y),Z=t.makeOutput([U,G,H],T.dtype),K=t.dataIdMap.get(Z.dataId).id,X=new Uint8Array(new Int32Array(T.shape).buffer),oe=new Uint8Array(new Int32Array(F.shape).buffer);return vM(M,X,T.shape.length,L,oe,F.shape.length,a,i,K),Z.shape=w,Z}var kM={kernelName:Yo,backendName:"wasm",setupFunc:rQ,kernelFunc:oQ};function gc(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 CM={kernelName:Fo,backendName:"wasm",kernelFunc:gc};var IM;function nQ(r){IM=r.wasm.cwrap(Oo,null,["number","number","number","number"])}function sQ(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 IM(i,s,a,u),l}var NM={kernelName:Oo,backendName:"wasm",setupFunc:nQ,kernelFunc:sQ};function pI(r){let{inputs:e,backend:t}=r,o=x.parseAxisParam(r.attrs.axis,e[0].shape)[0],n=S.computeOutShape(e.map(f=>f.shape),o),s=e.filter(f=>x.sizeFromShape(f.shape)>0);if(s.length===1)return hc({inputs:{x:s[0]},backend:t});let a=t.makeOutput(n,e[0].dtype);if(x.sizeFromShape(n)===0)return a;let i=s.map(f=>f.shape);if(S.assertParamsConsistent(i,o),s[0].dtype==="string"){let f=s.map(_=>{let w=x.sizeFromShape(_.shape.slice(o));return Wr({inputs:{x:_},backend:t,attrs:{shape:[-1,w]}})}),d=f.map(_=>({vals:t.readSync(_.dataId),shape:_.shape}));n=S.computeOutShape(f.map(_=>_.shape),1);let h=f[0].shape[0]===1,g=Vd(d,n,e[0].dtype,h),y=S.computeOutShape(s.map(_=>_.shape),o);a.shape=y;let b=t.dataIdMap.get(a.dataId);return b.stringBytes=S.fromStringArrayToUint8(g),a}let l=x.sizeFromShape(s[0].shape.slice(0,o)),u=0,c=s.map(f=>{let d=x.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`cumsum does not support ${n.dtype} tensors in the WASM backend`);let u=S.getAxesPermutation([s],l),c=n;u!==null&&(c=Hp({inputs:{x:n},attrs:{perm:u},backend:t}));let p=S.getInnerMostAxes(1,l)[0];S.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;OM(d,a?1:0,i?1:0,f,h,Vt[n.dtype]);let g=m;if(u!==null){let y=S.getUndoAxesPermutation(u);g=Hp({inputs:{x:m},attrs:{perm:y},backend:t}),t.disposeData(c.dataId),t.disposeData(m.dataId)}return g}var PM={kernelName:en,backendName:"wasm",setupFunc:mQ,kernelFunc:fQ};var MM;function dQ(r){MM=r.wasm.cwrap(ti,null,["number","number","number","array","number","array","array","number","number"])}function hQ(r){let{backend:e,inputs:t,attrs:o}=r,{x:n}=t,{blockSize:s,dataFormat:a}=o;x.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"),y=e.dataIdMap.get(n.dataId).id,b=new Uint8Array(new Int32Array(x.computeStrides(n.shape)).buffer),_=new Uint8Array(new Int32Array(d).buffer),w=new Uint8Array(new Int32Array(x.computeStrides(d)).buffer),k=e.dataIdMap.get(h.dataId).id;return MM(y,s,a==="NHWC"?1:0,b,n.shape.length-1,_,w,d.length,k),h}var LM={kernelName:ti,backendName:"wasm",setupFunc:dQ,kernelFunc:hQ};var zM;function gQ(r){zM=r.wasm.cwrap(tn,null,["number","number","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,{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=S.computeConv2DInfo(n.shape,s.shape,l,m,c,p,!0),d=f.filterHeight,h=f.filterWidth,g=f.padInfo.top,y=f.padInfo.right,b=f.padInfo.bottom,_=f.padInfo.left,w=f.dilationHeight,k=f.dilationWidth,$=f.strideHeight,T=f.strideWidth,F=f.inChannels,M=f.outChannels,L=f.padInfo.type==="SAME"?1:0;if(f.dataFormat!=="channelsLast")throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${f.dataFormat}'. Please use 'channelsLast'.`);let G=o.makeOutput(f.outShape,"float32"),H=o.dataIdMap.get(G.dataId).id;return zM(a,n.shape[0],n.shape[1],n.shape[2],i,d,h,g,y,b,_,L,w,k,$,T,F,M,H),G}var BM={kernelName:tn,backendName:"wasm",setupFunc:gQ,kernelFunc:xQ};var yQ=!1,VM=kt(ni,yQ,"bool");var WM=Ft(on);function Kx(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&&(x.assert(-(a+1)<=s,()=>`Axis must be in the interval [${-(a+1)}, ${a}]`),l=a+s+1),i.splice(l,0,1),Wr({inputs:{x:n},backend:o,attrs:{shape:i}})}var GM={kernelName:ls,backendName:"wasm",kernelFunc:Kx};function bQ(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 UM={kernelName:ua,backendName:"wasm",kernelFunc:bQ};var jM;function _Q(r){jM=r.wasm.cwrap(ii,null,["number","number","number","number","number","number"])}function wQ(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 jM(s,i,l,u,c,a),n}var qM={kernelName:ii,backendName:"wasm",kernelFunc:wQ,setupFunc:_Q};var HM=Ft(nn);var vQ=!1,KM=kt(sn,vQ);var XM;function kQ(r){XM=r.wasm.cwrap(an,null,["number","number","number","number","number","number","number"])}function CQ(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(x.sizeFromShape(s.shape)===0)return h;let g=e.dataIdMap.get(h.dataId).id;return XM(c,p,m,f,d,n,g),h}var YM={kernelName:an,backendName:"wasm",setupFunc:kQ,kernelFunc:CQ};var ZM;function IQ(r){ZM=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 NQ(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=S.computeConv2DInfo(n.shape,s.shape,l,c,u,m),g=Rl[f];if(g==null)throw new Error(`${f} activation not yet supported for FusedConv2D in the wasm backend.`);let y=o.dataIdMap.get(n.dataId).id,b=o.dataIdMap.get(s.dataId).id,_=h.outChannels,w=0;if(a!=null){let le=o.dataIdMap.get(a.dataId);if(le.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${le.shape.length}.`);if(le.shape[0]!==_)throw new Error(`FusedConv2D bias shape (${le.shape}) does not match the number of output channels (${_})`);w=le.id}let k=h.filterHeight,$=h.filterWidth,T=h.padInfo.top,F=h.padInfo.right,M=h.padInfo.bottom,L=h.padInfo.left,G=h.dilationHeight,H=h.dilationWidth,U=h.strideHeight,Z=h.strideWidth,K=h.inChannels,X=h.padInfo.type==="SAME"?1:0,oe=h.batchSize,J=h.inHeight,Q=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"),ae=o.dataIdMap.get(ie.dataId).id,ue=i==null?0:o.dataIdMap.get(i.dataId).id;return ZM(y,oe,J,Q,b,k,$,w,T,F,M,L,X,G,H,U,Z,K,_,g,ue,d||0,ae),ie}var JM={kernelName:ws,backendName:"wasm",setupFunc:IQ,kernelFunc:NQ};var QM;function SQ(r){QM=r.wasm.cwrap(vs,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=S.computeConv2DInfo(n.shape,s.shape,l,c,u,m,!0),g=Rl[f];if(g==null)throw new Error(`${f} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);let y=o.dataIdMap.get(n.dataId).id,b=o.dataIdMap.get(s.dataId).id,_=h.outChannels,w=0;if(a!=null){let le=o.dataIdMap.get(a.dataId);if(le.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${le.shape.length}.`);if(le.shape[0]!==_)throw new Error(`FusedDepthwiseConv2D bias shape (${le.shape}) does not match the number of output channels (${_})`);w=le.id}let k=h.filterHeight,$=h.filterWidth,T=h.padInfo.top,F=h.padInfo.right,M=h.padInfo.bottom,L=h.padInfo.left,G=h.dilationHeight,H=h.dilationWidth,U=h.strideHeight,Z=h.strideWidth,K=h.inChannels,X=h.padInfo.type==="SAME"?1:0,oe=h.batchSize,J=h.inHeight,Q=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"),ae=o.dataIdMap.get(ie.dataId).id,ue=i==null?0:o.dataIdMap.get(i.dataId).id;return QM(y,oe,J,Q,b,k,$,w,T,F,M,L,X,G,H,U,Z,K,_,g,ue,d||0,ae),ie}var eL={kernelName:vs,backendName:"wasm",setupFunc:SQ,kernelFunc:TQ};var tL;function EQ(r){tL=r.wasm.cwrap(ai,null,["number","number","number","number","number","number","array","number"])}function AQ(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),y=e.dataIdMap.get(u.dataId).id;return tL(f,Vt[o.dtype],h,a,p,i,g,y),u}var rL={kernelName:ai,backendName:"wasm",setupFunc:EQ,kernelFunc:AQ};var oL;function DQ(r){oL=r.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function $Q(r){let{backend:e,inputs:t,attrs:o}=r,{x:n,indices:s}=t,{axis:a,batchDims:i}=o,l=x.parseAxisParam(a,n.shape)[0],u=S.segment_util.collectGatherOpShapeInfo(n,s,l,i),c=Wr({inputs:{x:n},attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]},backend:e}),p=x.sizeFromShape(s.shape),m=Wr({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(x.sizeFromShape(n.shape)===0)return d;let h=c.shape.length-1,y=e.dataIdMap.get(c.dataId).id,_=e.dataIdMap.get(m.dataId).id,w=e.dataIdMap.get(d.dataId).id,k=new Uint8Array(new Int32Array(x.computeStrides(c.shape)).buffer),$=new Uint8Array(new Int32Array(x.computeStrides(f)).buffer);return oL(y,Vt[n.dtype],k,h,_,u.batchSize,$,w),d.shape=u.outputShape,d}var nL={kernelName:us,backendName:"wasm",setupFunc:DQ,kernelFunc:$Q};var RQ=!1,sL=kt(li,RQ,"bool");var FQ=!1,iL=kt(ln,FQ,"bool");var aL;function OQ(r){aL=r.wasm.cwrap(un,null,["number","number","number"])}function PQ(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(x.sizeFromShape(e.shape)!==0){let a=o.dataIdMap.get(s.dataId).id;aL(n,t,a)}return s}var lL={kernelName:un,backendName:"wasm",setupFunc:OQ,kernelFunc:PQ};var MQ=!1,uL=kt(mi,MQ,"bool");var LQ=!1,cL=kt(fi,LQ,"bool");var pL=Ft(cn);var zQ=!1,mL=kt(hi,zQ,"bool");var fL;function BQ(r){fL=r.wasm.cwrap(pn,null,["number, number, number"])}function VQ(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}=rs(a,n,e);if(f){let _=e.dataIdMap.get(c.dataId).id;u=c,l=_}let d=u.shape.length;S.assertAxesAreInnerMostDims("max",p,d);let[h,g]=S.computeOutAndReduceShapes(u.shape,p),y=x.sizeFromShape(g),b=e.makeOutput(h,a.dtype);if(x.sizeFromShape(u.shape)!==0){let _=e.dataIdMap.get(b.dataId).id;fL(l,y,_)}if(f&&e.disposeData(c.dataId),s){let _=S.expandShapeToKeepDim(b.shape,m);b.shape=_}return b}var dL={kernelName:pn,backendName:"wasm",setupFunc:BQ,kernelFunc:VQ};var WQ=!1,hL=kt(mn,WQ);var gL;function GQ(r){gL=r.wasm.cwrap(fn,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function UQ(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=S.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,y=c.dilationHeight,b=c.dilationWidth,_=c.strideHeight,w=c.strideWidth,k=c.inChannels,$=c.outChannels;if(c.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);let T=o.makeOutput(c.outShape,"float32"),F=o.dataIdMap.get(T.dataId).id;return gL(s,n.shape[0],n.shape[1],n.shape[2],p,m,f,d,h,g,y,b,_,w,k,$,F),T}var xL={kernelName:fn,backendName:"wasm",setupFunc:GQ,kernelFunc:UQ};var yL;function jQ(r){yL=r.wasm.cwrap(dn,null,["number, number, number"])}function qQ(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}=rs(a,n,e),d=p;if(f){let w=e.dataIdMap.get(c.dataId).id;w!==i&&(u=c,l=w,d=S.getInnerMostAxes(d.length,u.shape.length))}S.assertAxesAreInnerMostDims("mean",d,u.shape.length);let[h,g]=S.computeOutAndReduceShapes(u.shape,d),y=x.sizeFromShape(g),b=u;u.dtype!=="float32"&&(b=gc({backend:e,inputs:{x:u},attrs:{dtype:"float32"}}),l=e.dataIdMap.get(b.dataId).id);let _=e.makeOutput(h,"float32");if(x.sizeFromShape(u.shape)!==0){let w=e.dataIdMap.get(_.dataId).id;yL(l,y,w)}if(f&&e.disposeData(c.dataId),s){let w=S.expandShapeToKeepDim(_.shape,m);_.shape=w}return u.dtype!=="float32"&&e.disposeData(b.dataId),_}var bL={kernelName:dn,backendName:"wasm",setupFunc:jQ,kernelFunc:qQ};var _L;function HQ(r){_L=r.wasm.cwrap(hn,null,["number, number, number"])}function KQ(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}=rs(a,n,e);if(f){let _=e.dataIdMap.get(c.dataId).id;_!==i&&(u=c,l=_)}let d=u.shape.length;S.assertAxesAreInnerMostDims("min",p,d);let[h,g]=S.computeOutAndReduceShapes(u.shape,p),y=x.sizeFromShape(g),b=e.makeOutput(h,u.dtype);if(x.sizeFromShape(u.shape)!==0){let _=e.dataIdMap.get(b.dataId).id;_L(l,y,_)}if(f&&e.disposeData(c.dataId),s){let _=S.expandShapeToKeepDim(b.shape,m);b.shape=_}return b}var wL={kernelName:hn,backendName:"wasm",setupFunc:HQ,kernelFunc:KQ};var XQ=!1,vL=kt(gn,XQ);var YQ=!0,kL=kt(xn,YQ);var CL=Ft(ps);function Kp(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 IL;function ZQ(r){IL=r.wasm.cwrap(yi,"number",["number","number","number","number","number"])}function JQ(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=IL(u,c,s,n,a),{pSelectedIndices:m,selectedSize:f,pSelectedScores:d,pValidOutputs:h}=Kp(e,p);return e.wasm._free(d),e.wasm._free(h),e.makeOutput([f],"int32",m)}var NL={kernelName:yi,backendName:"wasm",setupFunc:ZQ,kernelFunc:JQ};var SL;function QQ(r){SL=r.wasm.cwrap(bi,"number",["number","number","number","number","number","bool"])}function eee(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=SL(c,p,s,n,a,i),{pSelectedIndices:f,selectedSize:d,pSelectedScores:h,pValidOutputs:g}=Kp(e,m);e.wasm._free(h);let y=e.makeOutput([d],"int32",f),b=e.makeOutput([],"int32",g);return[y,b]}var TL={kernelName:bi,backendName:"wasm",setupFunc:QQ,kernelFunc:eee};var EL;function tee(r){EL=r.wasm.cwrap(_i,"number",["number","number","number","number","number","number"])}function ree(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=EL(c,p,s,n,a,i),{pSelectedIndices:f,selectedSize:d,pSelectedScores:h,pValidOutputs:g}=Kp(e,m);e.wasm._free(g);let y=e.makeOutput([d],"int32",f),b=e.makeOutput([d],"float32",h);return[y,b]}var AL={kernelName:_i,backendName:"wasm",setupFunc:tee,kernelFunc:ree};var oee=!1,DL=kt(xi,oee,"bool");var $L;function nee(r){$L=r.wasm.cwrap(yn,null,["number","number","number","number","number"])}function see(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 $L(p,s,a,i,u),l}var RL={kernelName:yn,backendName:"wasm",setupFunc:nee,kernelFunc:see};function iee(r){let{inputs:{x:e},backend:t}=r,o=t.makeOutput(e.shape,e.dtype);return t.typedArrayFromHeap(o).fill(1),o}var FL={kernelName:ms,backendName:"wasm",kernelFunc:iee};function aee(r){let{inputs:e,backend:t,attrs:o}=r,{axis:n}=o;if(e.length===1)return Kx({inputs:{input:e[0]},backend:t,attrs:{dim:n}});let s=e[0].shape,a=e[0].dtype;e.forEach(l=>{x.assertShapesMatch(s,l.shape,"All tensors passed to stack must have matching shapes"),x.assert(a===l.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=e.map(l=>Kx({inputs:{input:l},backend:t,attrs:{dim:n}}));return pI({inputs:i,backend:t,attrs:{axis:n}})}var OL={kernelName:fs,backendName:"wasm",kernelFunc:aee};var PL;function lee(r){PL=r.wasm.cwrap(bn,null,["number","array","number","number","array","array","number","number"])}function uee(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 PL(a,u,e.shape.length,Vt[e.dtype],m,f,n,l),i}var ML={kernelName:bn,backendName:"wasm",kernelFunc:uee,setupFunc:lee};var cee=!1,LL=kt(_n,cee);var zL;function pee(r){zL=r.wasm.cwrap(wn,null,["number","number","number"])}function mee(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 zL(s,a,l),i}var BL={kernelName:wn,backendName:"wasm",setupFunc:pee,kernelFunc:mee};var VL;function fee(r){VL=r.wasm.cwrap(wi,null,["number","number","number","number"])}function dee(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}=rs(a,n,e),d=p;if(f){let _=e.dataIdMap.get(c.dataId).id;_!==i&&(u=c,l=_,d=S.getInnerMostAxes(d.length,u.shape.length))}S.assertAxesAreInnerMostDims("prod",d,u.shape.length);let[h,g]=S.computeOutAndReduceShapes(u.shape,d),y=x.sizeFromShape(g),b=e.makeOutput(h,u.dtype);if(x.sizeFromShape(u.shape)!==0){let _=e.dataIdMap.get(b.dataId).id;VL(l,y,Vt[b.dtype],_)}if(f&&e.disposeData(c.dataId),s){let _=S.expandShapeToKeepDim(b.shape,m);b.shape=_}return b}var WL={kernelName:wi,backendName:"wasm",setupFunc:fee,kernelFunc:dee};var hee=r=>{let{backend:e,attrs:t}=r,{start:o,stop:n,step:s,dtype:a}=t,i=Ud(o,n,s,a),l=e.makeOutput([i.length],a);return e.typedArrayFromHeap(l).set(i),l},GL={kernelName:fa,backendName:"wasm",kernelFunc:hee};var gee=!0,UL=kt(rn,gee);var jL=Ft(vn);var qL=Ft(Cn);var HL;function xee(r){HL=r.wasm.cwrap(kn,null,["number","number","number","number","number","number","number","number","number","number"])}function yee(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=gc({backend:e,inputs:{x:n},attrs:{dtype:"float32"}}),h=e.dataIdMap.get(g.dataId));let y=h.id,b=e.makeOutput(d,"float32");if(x.sizeFromShape(n.shape)===0)return b;let _=e.dataIdMap.get(b.dataId).id;return HL(y,c,p,m,f,l,u,s?1:0,a?1:0,_),g!=null&&e.disposeData(g.dataId),b}var KL={kernelName:kn,backendName:"wasm",setupFunc:xee,kernelFunc:yee};var XL;function bee(r){XL=r.wasm.cwrap(In,null,["number","array","number","array","number","number"])}function _ee(r){let{inputs:e,backend:t,attrs:o}=r,{x:n}=e,{dims:s}=o,a=x.parseAxisParam(s,n.shape);if(n.shape.length===0)return hc({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 XL(l,c,a.length,p,n.shape.length,u),Wr({inputs:{x:i},attrs:{shape:n.shape},backend:t})}var YL={kernelName:In,backendName:"wasm",kernelFunc:_ee,setupFunc:bee};var ZL;function wee(r){ZL=r.wasm.cwrap($i,null,["number","number","number","number","number","number","number","number","array","number","number"])}function vee(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]=S.getImageCenter(i,m,f),y=a===0,b=255,_=typeof a=="number"?[a,a,a,y?0:b]:[...a,b],w=new Uint8Array(new Int32Array(_).buffer);return ZL(u,p,m,f,d,s,h,g,w,_.length,c),l}var JL={kernelName:$i,backendName:"wasm",kernelFunc:vee,setupFunc:wee};var QL=Ft(Nn);var ez=Ft(Sn);var tz;function kee(r){tz=r.wasm.cwrap(ki,null,["number","number","number","number","number","number","array","number","number"])}function Cee(r){let{backend:e,inputs:t,attrs:o}=r,{indices:n,updates:s}=t,{shape:a}=o,i=e.makeOutput(a,s.dtype);if(x.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,y=new Uint8Array(new Int32Array(p).buffer),b=e.dataIdMap.get(i.dataId).id;return tz(d,g,Vt[s.dtype],l,u,c,y,m,b),i}var rz={kernelName:ki,backendName:"wasm",setupFunc:kee,kernelFunc:Cee};var oz;function Iee(r){oz=r.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function Nee(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:x.sizeFromShape(n.shape.slice(1));return oz(a,i,l,f,c),u}var nz={kernelName:hs,backendName:"wasm",kernelFunc:Nee,setupFunc:Iee};var sz;function See(r){sz=r.wasm.cwrap(En,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 x.sizeFromShape(n.shape)===0||sz(o,s),n}var iz={kernelName:"Sigmoid",backendName:"wasm",setupFunc:See,kernelFunc:Tee};var az=Ft(Tn);function xc(r){let{inputs:{x:e},attrs:{begin:t,size:o},backend:n}=r,[s,a]=sr.parseSliceParams(e,t,o),i=sr.isSliceContinous(e.shape,s,a),l=n.readSync(e.dataId),u=n.makeOutput(a,e.dtype),c=x.computeStrides(e.shape),p=n.dataIdMap.get(u.dataId);if(i){let d=sr.computeFlatOffset(s,c);return e.dtype==="string"?p.stringBytes=l.slice(d,d+x.sizeFromShape(a)):n.typedArrayFromHeap(u).set(l.subarray(d,d+x.sizeFromShape(a))),u}if(e.dtype==="string"){let d=jd(l,s,a,e.shape,e.dtype);return p.stringBytes=d,u}let m=n.typedArrayFromHeap(u),f=e.shape.length;if(f===2)Eee(l,c[0],m,s,a);else if(f===3)Aee(l,c[0],c[1],m,s,a);else if(f===4)Dee(l,c[0],c[1],c[2],m,s,a);else{let d=jd(l,s,a,e.shape,e.dtype);m.set(d)}return u}function Eee(r,e,t,o,n){let s=0,a=o[0],i=o[1],l=a+n[0];for(let u=a;u{let m=[...c];m[i]=p;let f=xc({inputs:{x:n},attrs:{begin:u,size:m},backend:o});return u[i]+=p,f})}var pz={kernelName:xs,backendName:"wasm",kernelFunc:Fee};var mz=Ft(An);var fz=Ft(ga);var Oee=!0,dz=kt(Rn,Oee);var hz;function Pee(r){hz=r.wasm.cwrap(Ti,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=S.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=S.slice_util.maskToAxes(p),g=n.shape.slice();h.forEach(L=>{s[L]=0,a[L]=1,g.splice(L,0,1)});let y=Wr({inputs:{x:n},attrs:{shape:g},backend:e}),{begin:b,end:_,strides:w}=S.slice_util.getNormalizedAxes(y.shape,f,d,s,a,i,l,u,c);s=b,a=_,i=w;let k=S.slice_util.maskToAxes(m);k.forEach(L=>{a[L]=s[L]+1,i[L]=1});let $=S.slice_util.computeOutShape(s,a,i),T=$.filter((L,G)=>k.indexOf(G)===-1);if(i.every(L=>L===1)){let L=xc({inputs:{x:n},attrs:{begin:s,size:$},backend:e});return Wr({inputs:{x:L},attrs:{shape:T},backend:e})}let M=e.makeOutput(T,"float32");if(!T.some(L=>L===0)){let L=e.dataIdMap.get(y.dataId).id,G=new Uint8Array(new Int32Array(x.computeStrides(y.shape)).buffer),H=new Uint8Array(new Int32Array(s).buffer),U=new Uint8Array(new Int32Array(a).buffer),Z=new Uint8Array(new Int32Array(i).buffer),K=new Uint8Array(new Int32Array(T).buffer),X=new Uint8Array(new Int32Array(x.computeStrides(T)).buffer),oe=e.dataIdMap.get(M.dataId).id;hz(L,G,y.shape.length,H,U,Z,K,X,T.length,oe)}return Wr({inputs:{x:M},attrs:{shape:T},backend:e})}var gz={kernelName:Ti,backendName:"wasm",setupFunc:Pee,kernelFunc:Mee};var Lee=!0,xz=kt(Fn,Lee);var yz;function zee(r){yz=r.wasm.cwrap(Dn,null,["number, number, number"])}function Bee(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}=rs(a,n,e),d=p;if(f){let _=e.dataIdMap.get(c.dataId).id;_!==i&&(u=c,l=_,d=S.getInnerMostAxes(d.length,u.shape.length))}S.assertAxesAreInnerMostDims("sum",d,u.shape.length);let[h,g]=S.computeOutAndReduceShapes(u.shape,d),y=x.sizeFromShape(g),b=e.makeOutput(h,u.dtype);if(x.sizeFromShape(u.shape)!==0){let _=e.dataIdMap.get(b.dataId).id;yz(l,y,_)}if(f&&e.disposeData(c.dataId),s){let _=S.expandShapeToKeepDim(b.shape,m);b.shape=_}return b}var bz={kernelName:Dn,backendName:"wasm",setupFunc:zee,kernelFunc:Bee};var _z=Ft(On);var wz;function Vee(r){wz=r.wasm.cwrap(_o,null,["number","array","number","array","number","number"])}function Wee(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{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 kz(a,i,o.shape.length,Vt[o.dtype],n,s,c,m),[u,p]},Cz={kernelName:Ai,backendName:"wasm",setupFunc:Gee,kernelFunc:Uee};function jee(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({dataId:f,dtype:d,shape:l}))}var Iz={kernelName:ys,backendName:"wasm",kernelFunc:jee};function qee(r){let{inputs:{x:e},backend:t}=r,o=t.makeOutput(e.shape,e.dtype);return t.typedArrayFromHeap(o).fill(0),o}var Nz={kernelName:bs,backendName:"wasm",kernelFunc:qee};var Hee=[cM,pM,fM,yM,_M,kM,CM,NM,SM,EM,DM,$M,FM,PM,LM,BM,VM,WM,GM,UM,qM,HM,KM,uM,YM,JM,eL,rL,nL,sL,iL,dM,lL,uL,cL,pL,mL,dL,hL,xL,bL,wL,vL,kL,CL,NL,TL,AL,DL,RL,FL,OL,ML,LL,BL,WL,GL,UL,jL,qL,wM,KL,YL,JL,ez,QL,rz,nz,iz,az,lz,cz,pz,mz,fz,dz,gz,xz,bz,_z,vz,Cz,gM,Iz,Nz];for(let r of Hee)tl(r);var fI=W();fI.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])));fI.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(fI.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 yI=Ec(Ez());var Az='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 $z=Ec(Dz());var Zx=class extends Ws{constructor(e){super();this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.init(),this.dataIdMap=new Ja(this,Cs())}write(e,t,o){let n={};return this.move(n,e,t,o),n}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){let t=x.now();return e(),{kernelMs:x.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=x.sizeFromShape(o),i=a*x.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+x.sizeFromShape(n)*x.bytesPerElement(o));return Kee(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=x.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=x.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 Xee(r){return(e,t)=>(x.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 Rz(r,e,t){if(Jx!=null)return Jx;let o="tfjs-backend-wasm.wasm";return r&&e?o="tfjs-backend-wasm-threaded-simd.wasm":r&&(o="tfjs-backend-wasm-simd.wasm"),ph!=null&&ph[o]!=null?ph[o]:t+o}async function Fz(){let[r,e]=await Promise.all([W().getAsync("WASM_HAS_SIMD_SUPPORT"),W().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((t,o)=>{let n={};n.locateFile=(l,u)=>{if(l.endsWith(".worker.js")){let c=Az,p=new Blob([c],{type:"application/javascript"});return URL.createObjectURL(p)}return l.endsWith(".wasm")?Rz(r,e,mh!=null?mh:u):u+l},bI&&(n.instantiateWasm=Xee(Rz(r,e,mh!=null?mh:"")));let s;e&&r&&Jx==null?(s=yI.default(n),s.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+yI.default.toString()],{type:"text/javascript"})):s=$z.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,fh=!1,t({wasm:s})},s.onAbort=()=>{if(i||fh)return;fh=!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 Kee(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 Yee=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],Jx=null,mh=null,ph={},fh=!1,bI=!1;function Zee(r,e=!1){if(Ot("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),fh)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");Jx=r,bI=e}function Jee(r,e=!1){if(fh)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")mh=r;else{ph=r;let t=Yee.filter(o=>ph[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.`)}bI=e}var Qee="2.8.3";var ete=2;wu("wasm",async()=>{let{wasm:r}=await Fz();return new Zx(r)},ete);export{is as Abs,js as Acos,qs as Acosh,rp as AdadeltaOptimizer,op as AdagradOptimizer,np as AdamOptimizer,sp as AdamaxOptimizer,bo as Add,Ho as AddN,Ul as All,jl as Any,Ko as ArgMax,oa as ArgMin,Hs as Asin,Ks as Asinh,Xs as Atan,Zs as Atan2,Ys as Atanh,Xo as AvgPool,na as AvgPool3D,Hl as AvgPool3DGrad,ql as AvgPoolGrad,Zx as BackendWasm,Yo as BatchMatMul,sa as BatchToSpaceND,Kl as Bincount,yb as BroadcastTo,Xg as Callback,Dg as CallbackList,Fo as Cast,Js as Ceil,Oo as ClipByValue,Xl as Complex,ia as ComplexAbs,as as Concat,Zo as Conv2D,Yl as Conv2DBackpropFilter,Jo as Conv2DBackpropInput,aa as Conv3D,Zl as Conv3DBackpropFilterV2,Jl as Conv3DBackpropInputV2,Qo as Cos,Qs as Cosh,ei as CropAndResize,en as Cumsum,Rg as CustomCallback,Ja as DataStorage,Ql as DenseBincount,ti as DepthToSpace,tn as DepthwiseConv2dNative,eu as DepthwiseConv2dNativeBackpropFilter,tu as DepthwiseConv2dNativeBackpropInput,ru as Diag,la as Dilation2D,Oc as Dilation2DBackpropFilter,Fc as Dilation2DBackpropInput,db as ENV,Zg as EarlyStopping,ri as Elu,ou as EluGrad,zh as Environment,ni as Equal,oi as Erf,on as Exp,ls as ExpandDims,si as Expm1,nu as FFT,ua as Fill,ii as FlipLeftRight,nn as Floor,sn as FloorDiv,Pc as FromPixels,an as FusedBatchNorm,ws as FusedConv2D,vs as FusedDepthwiseConv2D,ai as GatherNd,us as GatherV2,mx as GraphModel,li as Greater,ln as GreaterEqual,$g as History,su as IFFT,cs as Identity,iu as Imag,At as InputSpec,ui as IsFinite,ci as IsInf,pi as IsNan,Ws as KernelBackend,ca as LRN,lu as LRNGrad,bf as LayerVariable,Io as LayersModel,un as LeakyRelu,mi as Less,fi as LessEqual,au as LinSpace,cn as Log,di as Log1p,bb as LogSoftmax,hi as LogicalAnd,Qa as LogicalNot,el as LogicalOr,pn as Max,fn as MaxPool,pa as MaxPool3D,cu as MaxPool3DGrad,uu as MaxPoolGrad,pu as MaxPoolWithArgmax,mn as Maximum,dn as Mean,hn as Min,gn as Minimum,ma as MirrorPad,gi as Mod,ip as MomentumOptimizer,mu as Multinomial,xn as Multiply,ps as Neg,yi as NonMaxSuppressionV3,bi as NonMaxSuppressionV4,_i as NonMaxSuppressionV5,xi as NotEqual,XI as OP_SCOPE_SUFFIX,yn as OneHot,ms as OnesLike,Mr as Optimizer,fs as Pack,bn as PadV2,w3 as Pool,_n as Pow,wn as Prelu,wi as Prod,ap as RMSPropOptimizer,co as RNN,fa as Range,Cb as Rank,fu as Real,rn as RealDiv,vi as Reciprocal,Ut as Reduction,vn as Relu,Cn as Relu6,ds as Reshape,kn as ResizeBilinear,hu as ResizeBilinearGrad,da as ResizeNearestNeighbor,du as ResizeNearestNeighborGrad,In as Reverse,$i as RotateWithOffset,Nn as Round,Sn as Rsqrt,cl as SGDOptimizer,ki as ScatterNd,hs as Select,Ci as Selu,ji as Sequential,En as Sigmoid,Ni as Sign,Tn as Sin,Ii as Sinh,gs as Slice,$n as Softmax,Si as Softplus,ha as SpaceToBatchND,gu as SparseToDense,xs as SplitV,An as Sqrt,ga as Square,Rn as SquaredDifference,Di as Step,Ti as StridedSlice,Fn as Sub,Dn as Sum,Vr as SymbolicTensor,Ei as Tan,On as Tanh,R as Tensor,ct as TensorBuffer,_o as Tile,Ai as TopK,Pn as Transpose,xu as Unique,ys as Unpack,xa as UnsortedSegmentSum,ol as Variable,bs as ZerosLike,_s as _FusedMatMul,Et as abs,wm as acos,vm as acosh,ee as add,Qb as addN,W_ as addStrict,ku as all,il as any,al as argMax,km as argMin,Cm as asin,Im as asinh,Nm as atan,Sm as atan2,Tm as atanh,ka as avgPool,Em as avgPool3d,Jb as backend,S as backend_util,bW as basicLSTMCell,Ln as batchNorm,o_ as batchNorm2d,n_ as batchNorm3d,s_ as batchNorm4d,Ca as batchToSpaceND,i_ as bincount,SU as booleanMaskAsync,ll as broadcastTo,Yh as browser,Ie as buffer,W1 as callbacks,ne as cast,Am as ceil,ir as clipByValue,Po as clone,wo as complex,Je as concat,a_ as concat1d,l_ as concat2d,u_ as concat3d,c_ as concat4d,xw as constraints,Nu as conv1d,Xr as conv2d,Su as conv2dTranspose,Dm as conv3d,BW as conv3dTranspose,C3 as copyRegisteredKernels,Ia as cos,Tu as cosh,tf as cosineWindow,Eu as cumsum,Zr as customGrad,jv as data,p_ as denseBincount,Ot as deprecationWarn,$m as depthToSpace,Lo as depthwiseConv2d,j1 as deregisterOp,Vc as device_util,KW as diag,Rm as dilation2d,$V as disableDeprecationWarnings,Ae as dispose,RV as disposeVariables,fe as div,Fm as divNoNan,G_ as divStrict,m_ as dot,Q_ as dropout,Is as elu,DV as enableDebugMode,AV as enableProdMode,ew as enclosingPowerOfTwo,Cs as engine,W as env,Yr as equal,P_ as equalStrict,Om as erf,Qt as exp,br as expandDims,Pm as expm1,Xc as eye,Fa as fft,Na as fill,zV as findBackend,BV as findBackendFactory,Ns as floor,vu as floorDiv,Vn as fused,zn as gather,J_ as gatherND,Zh as gather_util,MV as getBackend,Bh as getGradient,dm as getKernel,hm as getKernelsForBackend,kG as grad,CG as grads,Xt as greater,Or as greaterEqual,M_ as greaterEqualStrict,L_ as greaterStrict,Li as ifft,Au as imag,As as image,ZU as inTopKAsync,vw as initializers,Hg as input,Cr as io,Wu as irfft,f_ as isFinite,d_ as isInf,h_ as isNaN,Dt as keep,Er as kernel_impls,nv as layers,Sa as leakyRelu,Ta as less,no as lessEqual,z_ as lessEqualStrict,B_ as lessStrict,sw as linalg,g_ as linspace,bE as loadGraphModel,E1 as loadLayersModel,Mm as localResponseNormalization,ar as log,Du as log1p,x_ as logSigmoid,$u as logSoftmax,zm as logSumExp,dr as logicalAnd,Ea as logicalNot,Ru as logicalOr,w_ as logicalXor,Gj as losses,je as matMul,NN as math,lr as max,Aa as maxPool,Bm as maxPool3d,v_ as maxPoolWithArgmax,Ir as maximum,U_ as maximumStrict,bt as mean,qc as memory,lv as metrics,Mi as min,Bo as minimum,j_ as minimumStrict,Vm as mirrorPad,Fu as mod,q_ as modStrict,S1 as model,uv as models,Yc as moments,jU as movingAverage,O as mul,H_ as mulStrict,QG as multiRNNCell,k_ as multinomial,He as neg,rf as nextFrame,Uu as norm,vo as notEqual,V_ as notEqualStrict,ks as oneHot,Nr as ones,rr as onesLike,N as op,n4 as outerProduct,Pr as pad,a4 as pad1d,u4 as pad2d,p4 as pad3d,f4 as pad4d,C_ as pool,_r as pow,K_ as powStrict,$a as prelu,Vb as print,Ou as prod,FV as profile,v4 as rand,A4 as randomGamma,lg as randomNormal,Ts as randomUniform,Jc as range,PV as ready,ul as real,Gm as reciprocal,wu as registerBackend,A1 as registerCallbackConstructor,wb as registerGradient,tl as registerKernel,U1 as registerOp,cv as regularizers,Sr as relu,Mu as relu6,LV as removeBackend,z as reshape,Yt as reverse,z4 as reverse1d,V4 as reverse2d,G4 as reverse3d,j4 as reverse4d,Oa as rfft,Um as round,Lu as rsqrt,ce as scalar,Z_ as scatterND,Jh as scatter_util,zu as selu,jm as separableConv2d,T1 as sequential,te as serialization,WN as setBackend,VV as setPlatform,Zee as setWasmPath,Jee as setWasmPaths,R_ as setdiff1dAsync,Kr as sigmoid,qm as sign,Wj as signal,Bu as sin,Vu as sinh,Fe as slice,Hm as slice1d,ug as slice2d,Km as slice3d,Qc as slice4d,sr as slice_util,Ra as softmax,Ss as softplus,Da as spaceToBatchND,ef as sparseToDense,Vj as spectral,ur as split,_t as sqrt,Me as square,Pa as squaredDifference,X_ as squaredDifferenceStrict,ko as squeeze,Wt as stack,Es as step,Xm as stridedSlice,pe as sub,Y_ as subStrict,be as sum,yu as sumOutType,Ym as tan,Pi as tanh,Fr as tensor,Gt as tensor1d,zi as tensor2d,jb as tensor3d,xU as tensor4d,yU as tensor5d,bU as tensor6d,Mn as tensor_util,zN as test_util,V as tidy,zo as tile,OV as time,Zm as topk,pl as train,qe as transpose,Gu as truncatedNormal,ep as unique,k3 as unregisterGradient,v3 as unregisterKernel,Jm as unsortedSegmentSum,cr as unstack,fr as upcastType,x as util,IG as valueAndGrad,NG as valueAndGrads,F_ as variable,sg as variableGrads,GJ as version,fx as version_converter,Zb as version_core,xl as version_layers,Qee as version_wasm,$t as where,Qm as whereAsync,pt as zeros,Ne 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